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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
60831b9513a2d3dcc94bf9957d9bb7aaa3073306 | 55,341 | cc | C++ | chrome/browser/extensions/api/downloads/downloads_api.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | chrome/browser/extensions/api/downloads/downloads_api.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/api/downloads/downloads_api.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:31.000Z | 2020-11-04T07:19:31.000Z | // Copyright (c) 2012 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 "chrome/browser/extensions/api/downloads/downloads_api.h"
#include <algorithm>
#include <cctype>
#include <iterator>
#include <set>
#include <string>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/strings/string_split.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_danger_prompt.h"
#include "chrome/browser/download/download_file_icon_extractor.h"
#include "chrome/browser/download/download_query.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/extensions/event_names.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/extensions/extension_info_map.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/icon_loader.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/renderer_host/chrome_render_message_filter.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/cancelable_task_tracker.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/api/downloads.h"
#include "content/public/browser/download_interrupt_reasons.h"
#include "content/public/browser/download_item.h"
#include "content/public/browser/download_save_info.h"
#include "content/public/browser/download_url_parameters.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "net/base/load_flags.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/webui/web_ui_util.h"
using content::BrowserContext;
using content::BrowserThread;
using content::DownloadId;
using content::DownloadItem;
using content::DownloadManager;
namespace download_extension_errors {
// Error messages
const char kGenericError[] = "I'm afraid I can't do that";
const char kIconNotFoundError[] = "Icon not found";
const char kInvalidDangerTypeError[] = "Invalid danger type";
const char kInvalidFilenameError[] = "Invalid filename";
const char kInvalidFilterError[] = "Invalid query filter";
const char kInvalidOperationError[] = "Invalid operation";
const char kInvalidOrderByError[] = "Invalid orderBy field";
const char kInvalidQueryLimit[] = "Invalid query limit";
const char kInvalidStateError[] = "Invalid state";
const char kInvalidURLError[] = "Invalid URL";
const char kNotImplementedError[] = "NotImplemented.";
const char kTooManyListenersError[] = "Each extension may have at most one "
"onDeterminingFilename listener between all of its renderer execution "
"contexts.";
} // namespace download_extension_errors
namespace {
// Default icon size for getFileIcon() in pixels.
const int kDefaultIconSize = 32;
// Parameter keys
const char kBytesReceivedKey[] = "bytesReceived";
const char kDangerAcceptedKey[] = "dangerAccepted";
const char kDangerContent[] = "content";
const char kDangerFile[] = "file";
const char kDangerKey[] = "danger";
const char kDangerSafe[] = "safe";
const char kDangerUncommon[] = "uncommon";
const char kDangerAccepted[] = "accepted";
const char kDangerHost[] = "host";
const char kDangerUrl[] = "url";
const char kEndTimeKey[] = "endTime";
const char kEndedAfterKey[] = "endedAfter";
const char kEndedBeforeKey[] = "endedBefore";
const char kErrorKey[] = "error";
const char kExistsKey[] = "exists";
const char kFileSizeKey[] = "fileSize";
const char kFilenameKey[] = "filename";
const char kFilenameRegexKey[] = "filenameRegex";
const char kIdKey[] = "id";
const char kIncognito[] = "incognito";
const char kMimeKey[] = "mime";
const char kPausedKey[] = "paused";
const char kQueryKey[] = "query";
const char kStartTimeKey[] = "startTime";
const char kStartedAfterKey[] = "startedAfter";
const char kStartedBeforeKey[] = "startedBefore";
const char kStateComplete[] = "complete";
const char kStateInProgress[] = "in_progress";
const char kStateInterrupted[] = "interrupted";
const char kStateKey[] = "state";
const char kTotalBytesGreaterKey[] = "totalBytesGreater";
const char kTotalBytesKey[] = "totalBytes";
const char kTotalBytesLessKey[] = "totalBytesLess";
const char kUrlKey[] = "url";
const char kUrlRegexKey[] = "urlRegex";
// Note: Any change to the danger type strings, should be accompanied by a
// corresponding change to downloads.json.
const char* kDangerStrings[] = {
kDangerSafe,
kDangerFile,
kDangerUrl,
kDangerContent,
kDangerSafe,
kDangerUncommon,
kDangerAccepted,
kDangerHost,
};
COMPILE_ASSERT(arraysize(kDangerStrings) == content::DOWNLOAD_DANGER_TYPE_MAX,
download_danger_type_enum_changed);
// Note: Any change to the state strings, should be accompanied by a
// corresponding change to downloads.json.
const char* kStateStrings[] = {
kStateInProgress,
kStateComplete,
kStateInterrupted,
kStateInterrupted,
};
COMPILE_ASSERT(arraysize(kStateStrings) == DownloadItem::MAX_DOWNLOAD_STATE,
download_item_state_enum_changed);
const char* DangerString(content::DownloadDangerType danger) {
DCHECK(danger >= 0);
DCHECK(danger < static_cast<content::DownloadDangerType>(
arraysize(kDangerStrings)));
if (danger < 0 || danger >= static_cast<content::DownloadDangerType>(
arraysize(kDangerStrings)))
return "";
return kDangerStrings[danger];
}
content::DownloadDangerType DangerEnumFromString(const std::string& danger) {
for (size_t i = 0; i < arraysize(kDangerStrings); ++i) {
if (danger == kDangerStrings[i])
return static_cast<content::DownloadDangerType>(i);
}
return content::DOWNLOAD_DANGER_TYPE_MAX;
}
const char* StateString(DownloadItem::DownloadState state) {
DCHECK(state >= 0);
DCHECK(state < static_cast<DownloadItem::DownloadState>(
arraysize(kStateStrings)));
if (state < 0 || state >= static_cast<DownloadItem::DownloadState>(
arraysize(kStateStrings)))
return "";
return kStateStrings[state];
}
DownloadItem::DownloadState StateEnumFromString(const std::string& state) {
for (size_t i = 0; i < arraysize(kStateStrings); ++i) {
if ((kStateStrings[i] != NULL) && (state == kStateStrings[i]))
return static_cast<DownloadItem::DownloadState>(i);
}
return DownloadItem::MAX_DOWNLOAD_STATE;
}
bool ValidateFilename(const base::FilePath& filename) {
return !filename.empty() &&
(filename == filename.StripTrailingSeparators()) &&
(filename.BaseName().value() != base::FilePath::kCurrentDirectory) &&
!filename.ReferencesParent() &&
!filename.IsAbsolute();
}
std::string TimeToISO8601(const base::Time& t) {
base::Time::Exploded exploded;
t.UTCExplode(&exploded);
return base::StringPrintf(
"%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", exploded.year, exploded.month,
exploded.day_of_month, exploded.hour, exploded.minute, exploded.second,
exploded.millisecond);
}
scoped_ptr<base::DictionaryValue> DownloadItemToJSON(
DownloadItem* download_item,
bool incognito) {
base::DictionaryValue* json = new base::DictionaryValue();
json->SetBoolean(kExistsKey, !download_item->GetFileExternallyRemoved());
json->SetInteger(kIdKey, download_item->GetId());
json->SetString(kUrlKey, download_item->GetOriginalUrl().spec());
json->SetString(
kFilenameKey, download_item->GetFullPath().LossyDisplayName());
json->SetString(kDangerKey, DangerString(download_item->GetDangerType()));
if (download_item->GetDangerType() !=
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS)
json->SetBoolean(kDangerAcceptedKey,
download_item->GetDangerType() ==
content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED);
json->SetString(kStateKey, StateString(download_item->GetState()));
json->SetBoolean(kPausedKey, download_item->IsPaused());
json->SetString(kMimeKey, download_item->GetMimeType());
json->SetString(kStartTimeKey, TimeToISO8601(download_item->GetStartTime()));
json->SetInteger(kBytesReceivedKey, download_item->GetReceivedBytes());
json->SetInteger(kTotalBytesKey, download_item->GetTotalBytes());
json->SetBoolean(kIncognito, incognito);
if (download_item->GetState() == DownloadItem::INTERRUPTED) {
json->SetInteger(kErrorKey, static_cast<int>(
download_item->GetLastReason()));
} else if (download_item->GetState() == DownloadItem::CANCELLED) {
json->SetInteger(kErrorKey, static_cast<int>(
content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED));
}
if (!download_item->GetEndTime().is_null())
json->SetString(kEndTimeKey, TimeToISO8601(download_item->GetEndTime()));
// TODO(benjhayden): Implement fileSize.
json->SetInteger(kFileSizeKey, download_item->GetTotalBytes());
return scoped_ptr<base::DictionaryValue>(json);
}
class DownloadFileIconExtractorImpl : public DownloadFileIconExtractor {
public:
DownloadFileIconExtractorImpl() {}
virtual ~DownloadFileIconExtractorImpl() {}
virtual bool ExtractIconURLForPath(const base::FilePath& path,
IconLoader::IconSize icon_size,
IconURLCallback callback) OVERRIDE;
private:
void OnIconLoadComplete(gfx::Image* icon);
CancelableTaskTracker cancelable_task_tracker_;
IconURLCallback callback_;
};
bool DownloadFileIconExtractorImpl::ExtractIconURLForPath(
const base::FilePath& path,
IconLoader::IconSize icon_size,
IconURLCallback callback) {
callback_ = callback;
IconManager* im = g_browser_process->icon_manager();
// The contents of the file at |path| may have changed since a previous
// request, in which case the associated icon may also have changed.
// Therefore, always call LoadIcon instead of attempting a LookupIcon.
im->LoadIcon(path,
icon_size,
base::Bind(&DownloadFileIconExtractorImpl::OnIconLoadComplete,
base::Unretained(this)),
&cancelable_task_tracker_);
return true;
}
void DownloadFileIconExtractorImpl::OnIconLoadComplete(gfx::Image* icon) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::string url;
if (icon)
url = webui::GetBitmapDataUrl(icon->AsBitmap());
callback_.Run(url);
}
IconLoader::IconSize IconLoaderSizeFromPixelSize(int pixel_size) {
switch (pixel_size) {
case 16: return IconLoader::SMALL;
case 32: return IconLoader::NORMAL;
default:
NOTREACHED();
return IconLoader::NORMAL;
}
}
typedef base::hash_map<std::string, DownloadQuery::FilterType> FilterTypeMap;
void InitFilterTypeMap(FilterTypeMap& filter_types) {
filter_types[kBytesReceivedKey] = DownloadQuery::FILTER_BYTES_RECEIVED;
filter_types[kDangerAcceptedKey] = DownloadQuery::FILTER_DANGER_ACCEPTED;
filter_types[kExistsKey] = DownloadQuery::FILTER_EXISTS;
filter_types[kFilenameKey] = DownloadQuery::FILTER_FILENAME;
filter_types[kFilenameRegexKey] = DownloadQuery::FILTER_FILENAME_REGEX;
filter_types[kMimeKey] = DownloadQuery::FILTER_MIME;
filter_types[kPausedKey] = DownloadQuery::FILTER_PAUSED;
filter_types[kQueryKey] = DownloadQuery::FILTER_QUERY;
filter_types[kEndedAfterKey] = DownloadQuery::FILTER_ENDED_AFTER;
filter_types[kEndedBeforeKey] = DownloadQuery::FILTER_ENDED_BEFORE;
filter_types[kEndTimeKey] = DownloadQuery::FILTER_END_TIME;
filter_types[kStartedAfterKey] = DownloadQuery::FILTER_STARTED_AFTER;
filter_types[kStartedBeforeKey] = DownloadQuery::FILTER_STARTED_BEFORE;
filter_types[kStartTimeKey] = DownloadQuery::FILTER_START_TIME;
filter_types[kTotalBytesKey] = DownloadQuery::FILTER_TOTAL_BYTES;
filter_types[kTotalBytesGreaterKey] =
DownloadQuery::FILTER_TOTAL_BYTES_GREATER;
filter_types[kTotalBytesLessKey] = DownloadQuery::FILTER_TOTAL_BYTES_LESS;
filter_types[kUrlKey] = DownloadQuery::FILTER_URL;
filter_types[kUrlRegexKey] = DownloadQuery::FILTER_URL_REGEX;
}
typedef base::hash_map<std::string, DownloadQuery::SortType> SortTypeMap;
void InitSortTypeMap(SortTypeMap& sorter_types) {
sorter_types[kBytesReceivedKey] = DownloadQuery::SORT_BYTES_RECEIVED;
sorter_types[kDangerKey] = DownloadQuery::SORT_DANGER;
sorter_types[kDangerAcceptedKey] = DownloadQuery::SORT_DANGER_ACCEPTED;
sorter_types[kEndTimeKey] = DownloadQuery::SORT_END_TIME;
sorter_types[kExistsKey] = DownloadQuery::SORT_EXISTS;
sorter_types[kFilenameKey] = DownloadQuery::SORT_FILENAME;
sorter_types[kMimeKey] = DownloadQuery::SORT_MIME;
sorter_types[kPausedKey] = DownloadQuery::SORT_PAUSED;
sorter_types[kStartTimeKey] = DownloadQuery::SORT_START_TIME;
sorter_types[kStateKey] = DownloadQuery::SORT_STATE;
sorter_types[kTotalBytesKey] = DownloadQuery::SORT_TOTAL_BYTES;
sorter_types[kUrlKey] = DownloadQuery::SORT_URL;
}
bool IsNotTemporaryDownloadFilter(const DownloadItem& download_item) {
return !download_item.IsTemporary();
}
// Set |manager| to the on-record DownloadManager, and |incognito_manager| to
// the off-record DownloadManager if one exists and is requested via
// |include_incognito|. This should work regardless of whether |profile| is
// original or incognito.
void GetManagers(
Profile* profile,
bool include_incognito,
DownloadManager** manager,
DownloadManager** incognito_manager) {
*manager = BrowserContext::GetDownloadManager(profile->GetOriginalProfile());
if (profile->HasOffTheRecordProfile() &&
(include_incognito ||
profile->IsOffTheRecord())) {
*incognito_manager = BrowserContext::GetDownloadManager(
profile->GetOffTheRecordProfile());
} else {
*incognito_manager = NULL;
}
}
DownloadItem* GetDownload(Profile* profile, bool include_incognito, int id) {
DownloadManager* manager = NULL;
DownloadManager* incognito_manager = NULL;
GetManagers(profile, include_incognito, &manager, &incognito_manager);
DownloadItem* download_item = manager->GetDownload(id);
if (!download_item && incognito_manager)
download_item = incognito_manager->GetDownload(id);
return download_item;
}
DownloadItem* GetDownloadIfInProgress(
Profile* profile,
bool include_incognito,
int id) {
DownloadItem* download_item = GetDownload(profile, include_incognito, id);
return download_item && download_item->IsInProgress() ? download_item : NULL;
}
enum DownloadsFunctionName {
DOWNLOADS_FUNCTION_DOWNLOAD = 0,
DOWNLOADS_FUNCTION_SEARCH = 1,
DOWNLOADS_FUNCTION_PAUSE = 2,
DOWNLOADS_FUNCTION_RESUME = 3,
DOWNLOADS_FUNCTION_CANCEL = 4,
DOWNLOADS_FUNCTION_ERASE = 5,
DOWNLOADS_FUNCTION_SET_DESTINATION = 6,
DOWNLOADS_FUNCTION_ACCEPT_DANGER = 7,
DOWNLOADS_FUNCTION_SHOW = 8,
DOWNLOADS_FUNCTION_DRAG = 9,
DOWNLOADS_FUNCTION_GET_FILE_ICON = 10,
DOWNLOADS_FUNCTION_OPEN = 11,
// Insert new values here, not at the beginning.
DOWNLOADS_FUNCTION_LAST
};
void RecordApiFunctions(DownloadsFunctionName function) {
UMA_HISTOGRAM_ENUMERATION("Download.ApiFunctions",
function,
DOWNLOADS_FUNCTION_LAST);
}
void CompileDownloadQueryOrderBy(
const std::string& order_by_str, std::string* error, DownloadQuery* query) {
// TODO(benjhayden): Consider switching from LazyInstance to explicit string
// comparisons.
static base::LazyInstance<SortTypeMap> sorter_types =
LAZY_INSTANCE_INITIALIZER;
if (sorter_types.Get().size() == 0)
InitSortTypeMap(sorter_types.Get());
std::vector<std::string> order_by_strs;
base::SplitString(order_by_str, ' ', &order_by_strs);
for (std::vector<std::string>::const_iterator iter = order_by_strs.begin();
iter != order_by_strs.end(); ++iter) {
std::string term_str = *iter;
if (term_str.empty())
continue;
DownloadQuery::SortDirection direction = DownloadQuery::ASCENDING;
if (term_str[0] == '-') {
direction = DownloadQuery::DESCENDING;
term_str = term_str.substr(1);
}
SortTypeMap::const_iterator sorter_type =
sorter_types.Get().find(term_str);
if (sorter_type == sorter_types.Get().end()) {
*error = download_extension_errors::kInvalidOrderByError;
return;
}
query->AddSorter(sorter_type->second, direction);
}
}
void RunDownloadQuery(
const extensions::api::downloads::DownloadQuery& query_in,
DownloadManager* manager,
DownloadManager* incognito_manager,
std::string* error,
DownloadQuery::DownloadVector* results) {
// TODO(benjhayden): Consider switching from LazyInstance to explicit string
// comparisons.
static base::LazyInstance<FilterTypeMap> filter_types =
LAZY_INSTANCE_INITIALIZER;
if (filter_types.Get().size() == 0)
InitFilterTypeMap(filter_types.Get());
DownloadQuery query_out;
if (query_in.limit.get()) {
if (*query_in.limit.get() < 0) {
*error = download_extension_errors::kInvalidQueryLimit;
return;
}
query_out.Limit(*query_in.limit.get());
}
std::string state_string =
extensions::api::downloads::ToString(query_in.state);
if (!state_string.empty()) {
DownloadItem::DownloadState state = StateEnumFromString(state_string);
if (state == DownloadItem::MAX_DOWNLOAD_STATE) {
*error = download_extension_errors::kInvalidStateError;
return;
}
query_out.AddFilter(state);
}
std::string danger_string =
extensions::api::downloads::ToString(query_in.danger);
if (!danger_string.empty()) {
content::DownloadDangerType danger_type = DangerEnumFromString(
danger_string);
if (danger_type == content::DOWNLOAD_DANGER_TYPE_MAX) {
*error = download_extension_errors::kInvalidDangerTypeError;
return;
}
query_out.AddFilter(danger_type);
}
if (query_in.order_by.get()) {
CompileDownloadQueryOrderBy(*query_in.order_by.get(), error, &query_out);
if (!error->empty())
return;
}
scoped_ptr<base::DictionaryValue> query_in_value(query_in.ToValue().Pass());
for (base::DictionaryValue::Iterator query_json_field(*query_in_value.get());
query_json_field.HasNext(); query_json_field.Advance()) {
FilterTypeMap::const_iterator filter_type =
filter_types.Get().find(query_json_field.key());
if (filter_type != filter_types.Get().end()) {
if (!query_out.AddFilter(filter_type->second, query_json_field.value())) {
*error = download_extension_errors::kInvalidFilterError;
return;
}
}
}
DownloadQuery::DownloadVector all_items;
if (query_in.id.get()) {
DownloadItem* download_item = manager->GetDownload(*query_in.id.get());
if (!download_item && incognito_manager)
download_item = incognito_manager->GetDownload(*query_in.id.get());
if (download_item)
all_items.push_back(download_item);
} else {
manager->GetAllDownloads(&all_items);
if (incognito_manager)
incognito_manager->GetAllDownloads(&all_items);
}
query_out.AddFilter(base::Bind(&IsNotTemporaryDownloadFilter));
query_out.Search(all_items.begin(), all_items.end(), results);
}
class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data {
public:
static ExtensionDownloadsEventRouterData* Get(DownloadItem* download_item) {
base::SupportsUserData::Data* data = download_item->GetUserData(kKey);
return (data == NULL) ? NULL :
static_cast<ExtensionDownloadsEventRouterData*>(data);
}
explicit ExtensionDownloadsEventRouterData(
DownloadItem* download_item,
scoped_ptr<base::DictionaryValue> json_item)
: updated_(0),
changed_fired_(0),
json_(json_item.Pass()),
determined_overwrite_(false) {
download_item->SetUserData(kKey, this);
}
virtual ~ExtensionDownloadsEventRouterData() {
if (updated_ > 0) {
UMA_HISTOGRAM_PERCENTAGE("Download.OnChanged",
(changed_fired_ * 100 / updated_));
}
}
const base::DictionaryValue& json() const { return *json_.get(); }
void set_json(scoped_ptr<base::DictionaryValue> json_item) {
json_ = json_item.Pass();
}
void OnItemUpdated() { ++updated_; }
void OnChangedFired() { ++changed_fired_; }
void set_filename_change_callbacks(
const base::Closure& no_change,
const ExtensionDownloadsEventRouter::FilenameChangedCallback& change) {
filename_no_change_ = no_change;
filename_change_ = change;
}
void ClearPendingDeterminers() {
determined_filename_.clear();
determined_overwrite_ = false;
determiner_ = DeterminerInfo();
filename_no_change_ = base::Closure();
filename_change_ = ExtensionDownloadsEventRouter::FilenameChangedCallback();
weak_ptr_factory_.reset();
determiners_.clear();
}
void DeterminerRemoved(const std::string& extension_id) {
for (DeterminerInfoVector::iterator iter = determiners_.begin();
iter != determiners_.end();) {
if (iter->extension_id == extension_id) {
iter = determiners_.erase(iter);
} else {
++iter;
}
}
// If we just removed the last unreported determiner, then we need to call a
// callback.
CheckAllDeterminersCalled();
}
void AddPendingDeterminer(const std::string& extension_id,
const base::Time& installed) {
for (size_t index = 0; index < determiners_.size(); ++index) {
if (determiners_[index].extension_id == extension_id) {
DCHECK(false) << extension_id;
return;
}
}
determiners_.push_back(DeterminerInfo(extension_id, installed));
}
bool DeterminerAlreadyReported(const std::string& extension_id) {
for (size_t index = 0; index < determiners_.size(); ++index) {
if (determiners_[index].extension_id == extension_id) {
return determiners_[index].reported;
}
}
return false;
}
// Returns false if this extension_id was not expected or if this extension_id
// has already reported, regardless of whether the filename is valid.
bool DeterminerCallback(
const std::string& extension_id,
const base::FilePath& filename,
bool overwrite) {
bool found_info = false;
for (size_t index = 0; index < determiners_.size(); ++index) {
if (determiners_[index].extension_id == extension_id) {
found_info = true;
if (determiners_[index].reported)
return false;
determiners_[index].reported = true;
// Do not use filename if another determiner has already overridden the
// filename and they take precedence. Extensions that were installed
// later take precedence over previous extensions.
if (ValidateFilename(filename) &&
(determiner_.extension_id.empty() ||
(determiners_[index].install_time > determiner_.install_time))) {
determined_filename_ = filename;
determined_overwrite_ = overwrite;
determiner_ = determiners_[index];
}
break;
}
}
if (!found_info)
return false;
CheckAllDeterminersCalled();
return true;
}
private:
struct DeterminerInfo {
DeterminerInfo();
DeterminerInfo(const std::string& e_id,
const base::Time& installed);
~DeterminerInfo();
std::string extension_id;
base::Time install_time;
bool reported;
};
typedef std::vector<DeterminerInfo> DeterminerInfoVector;
static const char kKey[];
// This is safe to call even while not waiting for determiners to call back;
// in that case, the callbacks will be null so they won't be Run.
void CheckAllDeterminersCalled() {
for (DeterminerInfoVector::iterator iter = determiners_.begin();
iter != determiners_.end(); ++iter) {
if (!iter->reported)
return;
}
if (determined_filename_.empty()) {
if (!filename_no_change_.is_null())
filename_no_change_.Run();
} else {
if (!filename_change_.is_null())
filename_change_.Run(determined_filename_, determined_overwrite_);
}
// Don't clear determiners_ immediately in case there's a second listener
// for one of the extensions, so that DetermineFilename can return
// kTooManyListenersError. After a few seconds, DetermineFilename will
// return kInvalidOperationError instead of kTooManyListenersError so that
// determiners_ doesn't keep hogging memory.
weak_ptr_factory_.reset(
new base::WeakPtrFactory<ExtensionDownloadsEventRouterData>(this));
MessageLoopForUI::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ExtensionDownloadsEventRouterData::ClearPendingDeterminers,
weak_ptr_factory_->GetWeakPtr()),
base::TimeDelta::FromSeconds(30));
}
int updated_;
int changed_fired_;
scoped_ptr<base::DictionaryValue> json_;
base::Closure filename_no_change_;
ExtensionDownloadsEventRouter::FilenameChangedCallback filename_change_;
DeterminerInfoVector determiners_;
base::FilePath determined_filename_;
bool determined_overwrite_;
DeterminerInfo determiner_;
scoped_ptr<base::WeakPtrFactory<ExtensionDownloadsEventRouterData> >
weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ExtensionDownloadsEventRouterData);
};
ExtensionDownloadsEventRouterData::DeterminerInfo::DeterminerInfo(
const std::string& e_id,
const base::Time& installed)
: extension_id(e_id),
install_time(installed),
reported(false) {
}
ExtensionDownloadsEventRouterData::DeterminerInfo::DeterminerInfo()
: reported(false) {
}
ExtensionDownloadsEventRouterData::DeterminerInfo::~DeterminerInfo() {}
const char ExtensionDownloadsEventRouterData::kKey[] =
"DownloadItem ExtensionDownloadsEventRouterData";
class ManagerDestructionObserver : public DownloadManager::Observer {
public:
static void CheckForHistoryFilesRemoval(DownloadManager* manager) {
if (!manager)
return;
if (!manager_file_existence_last_checked_)
manager_file_existence_last_checked_ =
new std::map<DownloadManager*, ManagerDestructionObserver*>();
if (!(*manager_file_existence_last_checked_)[manager])
(*manager_file_existence_last_checked_)[manager] =
new ManagerDestructionObserver(manager);
(*manager_file_existence_last_checked_)[manager]->
CheckForHistoryFilesRemovalInternal();
}
private:
static const int kFileExistenceRateLimitSeconds = 10;
explicit ManagerDestructionObserver(DownloadManager* manager)
: manager_(manager) {
manager_->AddObserver(this);
}
virtual ~ManagerDestructionObserver() {
manager_->RemoveObserver(this);
}
virtual void ManagerGoingDown(DownloadManager* manager) OVERRIDE {
manager_file_existence_last_checked_->erase(manager);
if (manager_file_existence_last_checked_->size() == 0) {
delete manager_file_existence_last_checked_;
manager_file_existence_last_checked_ = NULL;
}
}
void CheckForHistoryFilesRemovalInternal() {
base::Time now(base::Time::Now());
int delta = now.ToTimeT() - last_checked_.ToTimeT();
if (delta > kFileExistenceRateLimitSeconds) {
last_checked_ = now;
manager_->CheckForHistoryFilesRemoval();
}
}
static std::map<DownloadManager*, ManagerDestructionObserver*>*
manager_file_existence_last_checked_;
DownloadManager* manager_;
base::Time last_checked_;
DISALLOW_COPY_AND_ASSIGN(ManagerDestructionObserver);
};
std::map<DownloadManager*, ManagerDestructionObserver*>*
ManagerDestructionObserver::manager_file_existence_last_checked_ = NULL;
void OnDeterminingFilenameWillDispatchCallback(
bool* any_determiners,
ExtensionDownloadsEventRouterData* data,
Profile* profile,
const extensions::Extension* extension,
ListValue* event_args) {
*any_determiners = true;
base::Time installed = extensions::ExtensionSystem::Get(
profile)->extension_service()->extension_prefs()->
GetInstallTime(extension->id());
data->AddPendingDeterminer(extension->id(), installed);
}
} // namespace
DownloadsDownloadFunction::DownloadsDownloadFunction() {}
DownloadsDownloadFunction::~DownloadsDownloadFunction() {}
bool DownloadsDownloadFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Download::Params> params(
extensions::api::downloads::Download::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
const extensions::api::downloads::DownloadOptions& options = params->options;
GURL download_url(options.url);
if (!download_url.is_valid() ||
(!download_url.SchemeIs("data") &&
download_url.GetOrigin() != GetExtension()->url().GetOrigin() &&
!GetExtension()->HasHostPermission(download_url))) {
error_ = download_extension_errors::kInvalidURLError;
return false;
}
Profile* current_profile = profile();
if (include_incognito() && profile()->HasOffTheRecordProfile())
current_profile = profile()->GetOffTheRecordProfile();
scoped_ptr<content::DownloadUrlParameters> download_params(
new content::DownloadUrlParameters(
download_url,
render_view_host()->GetProcess()->GetID(),
render_view_host()->GetRoutingID(),
current_profile->GetResourceContext()));
if (options.filename.get()) {
// TODO(benjhayden): Make json_schema_compiler generate string16s instead of
// std::strings. Can't get filename16 from options.ToValue() because that
// converts it from std::string.
base::DictionaryValue* options_value = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &options_value));
string16 filename16;
EXTENSION_FUNCTION_VALIDATE(options_value->GetString(
kFilenameKey, &filename16));
#if defined(OS_WIN)
base::FilePath file_path(filename16);
#elif defined(OS_POSIX)
base::FilePath file_path(*options.filename.get());
#endif
if (!ValidateFilename(file_path) ||
(file_path.DirName().value() != base::FilePath::kCurrentDirectory)) {
error_ = download_extension_errors::kInvalidFilenameError;
return false;
}
// TODO(benjhayden) Ensure that this filename is interpreted as a path
// relative to the default downloads directory without allowing '..'.
download_params->set_suggested_name(filename16);
}
if (options.save_as.get())
download_params->set_prompt(*options.save_as.get());
if (options.headers.get()) {
typedef extensions::api::downloads::HeaderNameValuePair HeaderNameValuePair;
for (std::vector<linked_ptr<HeaderNameValuePair> >::const_iterator iter =
options.headers->begin();
iter != options.headers->end();
++iter) {
const HeaderNameValuePair& name_value = **iter;
if (!net::HttpUtil::IsSafeHeader(name_value.name)) {
error_ = download_extension_errors::kGenericError;
return false;
}
download_params->add_request_header(name_value.name, name_value.value);
}
}
std::string method_string =
extensions::api::downloads::ToString(options.method);
if (!method_string.empty())
download_params->set_method(method_string);
if (options.body.get())
download_params->set_post_body(*options.body.get());
download_params->set_callback(base::Bind(
&DownloadsDownloadFunction::OnStarted, this));
// Prevent login prompts for 401/407 responses.
download_params->set_load_flags(net::LOAD_DO_NOT_PROMPT_FOR_LOGIN);
DownloadManager* manager = BrowserContext::GetDownloadManager(
current_profile);
manager->DownloadUrl(download_params.Pass());
RecordApiFunctions(DOWNLOADS_FUNCTION_DOWNLOAD);
return true;
}
void DownloadsDownloadFunction::OnStarted(
DownloadItem* item, net::Error error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(1) << __FUNCTION__ << " " << item << " " << error;
if (item) {
DCHECK_EQ(net::OK, error);
SetResult(base::Value::CreateIntegerValue(item->GetId()));
} else {
DCHECK_NE(net::OK, error);
error_ = net::ErrorToString(error);
}
SendResponse(error_.empty());
}
DownloadsSearchFunction::DownloadsSearchFunction() {}
DownloadsSearchFunction::~DownloadsSearchFunction() {}
bool DownloadsSearchFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Search::Params> params(
extensions::api::downloads::Search::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadManager* manager = NULL;
DownloadManager* incognito_manager = NULL;
GetManagers(profile(), include_incognito(), &manager, &incognito_manager);
ManagerDestructionObserver::CheckForHistoryFilesRemoval(manager);
ManagerDestructionObserver::CheckForHistoryFilesRemoval(incognito_manager);
DownloadQuery::DownloadVector results;
RunDownloadQuery(params->query,
manager,
incognito_manager,
&error_,
&results);
if (!error_.empty())
return false;
base::ListValue* json_results = new base::ListValue();
for (DownloadManager::DownloadVector::const_iterator it = results.begin();
it != results.end(); ++it) {
DownloadItem* download_item = *it;
int32 download_id = download_item->GetId();
bool off_record = ((incognito_manager != NULL) &&
(incognito_manager->GetDownload(download_id) != NULL));
scoped_ptr<base::DictionaryValue> json_item(DownloadItemToJSON(
*it, off_record));
json_results->Append(json_item.release());
}
SetResult(json_results);
RecordApiFunctions(DOWNLOADS_FUNCTION_SEARCH);
return true;
}
DownloadsPauseFunction::DownloadsPauseFunction() {}
DownloadsPauseFunction::~DownloadsPauseFunction() {}
bool DownloadsPauseFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Pause::Params> params(
extensions::api::downloads::Pause::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownloadIfInProgress(
profile(), include_incognito(), params->download_id);
if (download_item == NULL) {
// This could be due to an invalid download ID, or it could be due to the
// download not being currently active.
error_ = download_extension_errors::kInvalidOperationError;
} else {
// If the item is already paused, this is a no-op and the
// operation will silently succeed.
download_item->Pause();
}
if (error_.empty())
RecordApiFunctions(DOWNLOADS_FUNCTION_PAUSE);
return error_.empty();
}
DownloadsResumeFunction::DownloadsResumeFunction() {}
DownloadsResumeFunction::~DownloadsResumeFunction() {}
bool DownloadsResumeFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Resume::Params> params(
extensions::api::downloads::Resume::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownloadIfInProgress(
profile(), include_incognito(), params->download_id);
if (download_item == NULL) {
// This could be due to an invalid download ID, or it could be due to the
// download not being currently active.
error_ = download_extension_errors::kInvalidOperationError;
} else {
// Note that if the item isn't paused, this will be a no-op, and
// the extension call will seem successful.
download_item->Resume();
}
if (error_.empty())
RecordApiFunctions(DOWNLOADS_FUNCTION_RESUME);
return error_.empty();
}
DownloadsCancelFunction::DownloadsCancelFunction() {}
DownloadsCancelFunction::~DownloadsCancelFunction() {}
bool DownloadsCancelFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Resume::Params> params(
extensions::api::downloads::Resume::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownloadIfInProgress(
profile(), include_incognito(), params->download_id);
if (download_item != NULL)
download_item->Cancel(true);
// |download_item| can be NULL if the download ID was invalid or if the
// download is not currently active. Either way, it's not a failure.
RecordApiFunctions(DOWNLOADS_FUNCTION_CANCEL);
return true;
}
DownloadsEraseFunction::DownloadsEraseFunction() {}
DownloadsEraseFunction::~DownloadsEraseFunction() {}
bool DownloadsEraseFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Erase::Params> params(
extensions::api::downloads::Erase::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadManager* manager = NULL;
DownloadManager* incognito_manager = NULL;
GetManagers(profile(), include_incognito(), &manager, &incognito_manager);
DownloadQuery::DownloadVector results;
RunDownloadQuery(params->query,
manager,
incognito_manager,
&error_,
&results);
if (!error_.empty())
return false;
base::ListValue* json_results = new base::ListValue();
for (DownloadManager::DownloadVector::const_iterator it = results.begin();
it != results.end(); ++it) {
json_results->Append(base::Value::CreateIntegerValue((*it)->GetId()));
(*it)->Remove();
}
SetResult(json_results);
RecordApiFunctions(DOWNLOADS_FUNCTION_ERASE);
return true;
}
DownloadsAcceptDangerFunction::DownloadsAcceptDangerFunction() {}
DownloadsAcceptDangerFunction::~DownloadsAcceptDangerFunction() {}
bool DownloadsAcceptDangerFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::AcceptDanger::Params> params(
extensions::api::downloads::AcceptDanger::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownloadIfInProgress(
profile(), include_incognito(), params->download_id);
content::WebContents* web_contents =
dispatcher()->delegate()->GetAssociatedWebContents();
if (!download_item ||
!download_item->IsDangerous() ||
!web_contents) {
error_ = download_extension_errors::kInvalidOperationError;
return false;
}
RecordApiFunctions(DOWNLOADS_FUNCTION_ACCEPT_DANGER);
// DownloadDangerPrompt displays a modal dialog using native widgets that the
// user must either accept or cancel. It cannot be scripted.
DownloadDangerPrompt::Create(
download_item,
web_contents,
true,
base::Bind(&DownloadsAcceptDangerFunction::DangerPromptCallback,
this, true, params->download_id),
base::Bind(&DownloadsAcceptDangerFunction::DangerPromptCallback,
this, false, params->download_id));
// DownloadDangerPrompt deletes itself
return true;
}
void DownloadsAcceptDangerFunction::DangerPromptCallback(
bool accept, int download_id) {
if (accept) {
DownloadItem* download_item = GetDownloadIfInProgress(
profile(), include_incognito(), download_id);
if (download_item)
download_item->DangerousDownloadValidated();
}
SendResponse(error_.empty());
}
DownloadsShowFunction::DownloadsShowFunction() {}
DownloadsShowFunction::~DownloadsShowFunction() {}
bool DownloadsShowFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Show::Params> params(
extensions::api::downloads::Show::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownload(
profile(), include_incognito(), params->download_id);
if (!download_item) {
error_ = download_extension_errors::kInvalidOperationError;
return false;
}
download_item->ShowDownloadInShell();
RecordApiFunctions(DOWNLOADS_FUNCTION_SHOW);
return true;
}
DownloadsOpenFunction::DownloadsOpenFunction() {}
DownloadsOpenFunction::~DownloadsOpenFunction() {}
bool DownloadsOpenFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Open::Params> params(
extensions::api::downloads::Open::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownload(
profile(), include_incognito(), params->download_id);
if (!download_item || !download_item->IsComplete()) {
error_ = download_extension_errors::kInvalidOperationError;
return false;
}
download_item->OpenDownload();
RecordApiFunctions(DOWNLOADS_FUNCTION_OPEN);
return true;
}
DownloadsDragFunction::DownloadsDragFunction() {}
DownloadsDragFunction::~DownloadsDragFunction() {}
bool DownloadsDragFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::Drag::Params> params(
extensions::api::downloads::Drag::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
DownloadItem* download_item = GetDownload(
profile(), include_incognito(), params->download_id);
content::WebContents* web_contents =
dispatcher()->delegate()->GetAssociatedWebContents();
if (!download_item || !web_contents) {
error_ = download_extension_errors::kInvalidOperationError;
return false;
}
RecordApiFunctions(DOWNLOADS_FUNCTION_DRAG);
gfx::Image* icon = g_browser_process->icon_manager()->LookupIcon(
download_item->GetUserVerifiedFilePath(), IconLoader::NORMAL);
gfx::NativeView view = web_contents->GetView()->GetNativeView();
{
// Enable nested tasks during DnD, while |DragDownload()| blocks.
MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
download_util::DragDownload(download_item, icon, view);
}
return true;
}
DownloadsGetFileIconFunction::DownloadsGetFileIconFunction()
: icon_extractor_(new DownloadFileIconExtractorImpl()) {
}
DownloadsGetFileIconFunction::~DownloadsGetFileIconFunction() {}
void DownloadsGetFileIconFunction::SetIconExtractorForTesting(
DownloadFileIconExtractor* extractor) {
DCHECK(extractor);
icon_extractor_.reset(extractor);
}
bool DownloadsGetFileIconFunction::RunImpl() {
scoped_ptr<extensions::api::downloads::GetFileIcon::Params> params(
extensions::api::downloads::GetFileIcon::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
const extensions::api::downloads::GetFileIconOptions* options =
params->options.get();
int icon_size = kDefaultIconSize;
if (options && options->size.get())
icon_size = *options->size.get();
DownloadItem* download_item = GetDownload(
profile(), include_incognito(), params->download_id);
if (!download_item || download_item->GetTargetFilePath().empty()) {
error_ = download_extension_errors::kInvalidOperationError;
return false;
}
// In-progress downloads return the intermediate filename for GetFullPath()
// which doesn't have the final extension. Therefore a good file icon can't be
// found, so use GetTargetFilePath() instead.
DCHECK(icon_extractor_.get());
DCHECK(icon_size == 16 || icon_size == 32);
EXTENSION_FUNCTION_VALIDATE(icon_extractor_->ExtractIconURLForPath(
download_item->GetTargetFilePath(),
IconLoaderSizeFromPixelSize(icon_size),
base::Bind(&DownloadsGetFileIconFunction::OnIconURLExtracted, this)));
return true;
}
void DownloadsGetFileIconFunction::OnIconURLExtracted(const std::string& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (url.empty()) {
error_ = download_extension_errors::kIconNotFoundError;
} else {
RecordApiFunctions(DOWNLOADS_FUNCTION_GET_FILE_ICON);
SetResult(base::Value::CreateStringValue(url));
}
SendResponse(error_.empty());
}
ExtensionDownloadsEventRouter::ExtensionDownloadsEventRouter(
Profile* profile,
DownloadManager* manager)
: profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(notifier_(manager, this)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(profile_);
extensions::EventRouter* router = extensions::ExtensionSystem::Get(profile_)->
event_router();
if (router)
router->RegisterObserver(
this, extensions::event_names::kOnDownloadDeterminingFilename);
}
ExtensionDownloadsEventRouter::~ExtensionDownloadsEventRouter() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
extensions::EventRouter* router = extensions::ExtensionSystem::Get(profile_)->
event_router();
if (router)
router->UnregisterObserver(this);
}
// The method by which extensions hook into the filename determination process
// is based on the method by which the omnibox API allows extensions to hook
// into the omnibox autocompletion process. Extensions that wish to play a part
// in the filename determination process call
// chrome.downloads.onDeterminingFilename.addListener, which adds an
// EventListener object to ExtensionEventRouter::listeners().
//
// When a download's filename is being determined,
// ChromeDownloadManagerDelegate::CheckVisitedReferrerBeforeDone (CVRBD) passes
// 2 callbacks to ExtensionDownloadsEventRouter::OnDeterminingFilename (ODF),
// which stores the callbacks in the item's ExtensionDownloadsEventRouterData
// (EDERD) along with all of the extension IDs that are listening for
// onDeterminingFilename events. ODF dispatches
// chrome.downloads.onDeterminingFilename.
//
// When the extension's event handler calls |suggestCallback|,
// downloads_custom_bindings.js calls
// DownloadsInternalDetermineFilenameFunction::RunImpl, which calls
// EDER::DetermineFilename, which notifies the item's EDERD.
//
// When the last extension's event handler returns, EDERD calls one of the two
// callbacks that CVRBD passed to ODF, allowing CDMD to complete the filename
// determination process. If multiple extensions wish to override the filename,
// then the extension that was last installed wins.
void ExtensionDownloadsEventRouter::OnDeterminingFilename(
DownloadItem* item,
const base::FilePath& suggested_path,
const base::Closure& no_change,
const FilenameChangedCallback& change) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ExtensionDownloadsEventRouterData* data =
ExtensionDownloadsEventRouterData::Get(item);
data->ClearPendingDeterminers();
data->set_filename_change_callbacks(no_change, change);
bool any_determiners = false;
base::DictionaryValue* json = DownloadItemToJSON(
item, profile_->IsOffTheRecord()).release();
json->SetString(kFilenameKey, suggested_path.LossyDisplayName());
DispatchEvent(extensions::event_names::kOnDownloadDeterminingFilename,
false,
base::Bind(&OnDeterminingFilenameWillDispatchCallback,
&any_determiners,
data),
json);
if (!any_determiners) {
data->ClearPendingDeterminers();
no_change.Run();
}
}
bool ExtensionDownloadsEventRouter::DetermineFilename(
Profile* profile,
bool include_incognito,
const std::string& ext_id,
int download_id,
const base::FilePath& filename,
bool overwrite,
std::string* error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DownloadItem* item = GetDownload(profile, include_incognito, download_id);
if (!item) {
*error = download_extension_errors::kInvalidOperationError;
return false;
}
ExtensionDownloadsEventRouterData* data =
ExtensionDownloadsEventRouterData::Get(item);
if (!data) {
*error = download_extension_errors::kInvalidOperationError;
return false;
}
// maxListeners=1 in downloads.idl and suggestCallback in
// downloads_custom_bindings.js should prevent duplicate DeterminerCallback
// calls from the same renderer, but an extension may have more than one
// renderer, so don't DCHECK(!reported).
if (data->DeterminerAlreadyReported(ext_id)) {
*error = download_extension_errors::kTooManyListenersError;
return false;
}
if (!item->IsInProgress()) {
*error = download_extension_errors::kInvalidOperationError;
return false;
}
if (!data->DeterminerCallback(ext_id, filename, overwrite)) {
// Nobody expects this ext_id!
*error = download_extension_errors::kInvalidOperationError;
return false;
}
if (!filename.empty() && !ValidateFilename(filename)) {
// If this is moved to before DeterminerCallback(), then it will block
// forever waiting for this ext_id to report.
*error = download_extension_errors::kInvalidFilenameError;
return false;
}
return true;
}
void ExtensionDownloadsEventRouter::OnListenerRemoved(
const extensions::EventListenerInfo& details) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (details.event_name !=
extensions::event_names::kOnDownloadDeterminingFilename)
return;
DownloadManager* manager = notifier_.GetManager();
if (!manager)
return;
DownloadManager::DownloadVector items;
manager->GetAllDownloads(&items);
// Notify any items that may be waiting for callbacks from this
// extension/determiner.
for (DownloadManager::DownloadVector::const_iterator iter =
items.begin();
iter != items.end(); ++iter) {
ExtensionDownloadsEventRouterData* data =
ExtensionDownloadsEventRouterData::Get(*iter);
// This will almost always be a no-op, however, it is possible for an
// extension renderer to be unloaded while a download item is waiting
// for a determiner. In that case, the download item should proceed.
if (data)
data->DeterminerRemoved(details.extension_id);
}
}
// That's all the methods that have to do with filename determination. The rest
// have to do with the other, less special events.
void ExtensionDownloadsEventRouter::OnDownloadCreated(
DownloadManager* manager, DownloadItem* download_item) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (download_item->IsTemporary())
return;
scoped_ptr<base::DictionaryValue> json_item(
DownloadItemToJSON(download_item, profile_->IsOffTheRecord()));
DispatchEvent(extensions::event_names::kOnDownloadCreated,
true,
extensions::Event::WillDispatchCallback(),
json_item->DeepCopy());
if (!ExtensionDownloadsEventRouterData::Get(download_item))
new ExtensionDownloadsEventRouterData(download_item, json_item.Pass());
}
void ExtensionDownloadsEventRouter::OnDownloadUpdated(
DownloadManager* manager, DownloadItem* download_item) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (download_item->IsTemporary())
return;
ExtensionDownloadsEventRouterData* data =
ExtensionDownloadsEventRouterData::Get(download_item);
if (!data) {
// The download_item probably transitioned from temporary to not temporary.
OnDownloadCreated(manager, download_item);
return;
}
scoped_ptr<base::DictionaryValue> new_json(DownloadItemToJSON(
download_item, profile_->IsOffTheRecord()));
scoped_ptr<base::DictionaryValue> delta(new base::DictionaryValue());
delta->SetInteger(kIdKey, download_item->GetId());
std::set<std::string> new_fields;
bool changed = false;
// For each field in the new json representation of the download_item except
// the bytesReceived field, if the field has changed from the previous old
// json, set the differences in the |delta| object and remember that something
// significant changed.
for (base::DictionaryValue::Iterator iter(*new_json.get());
iter.HasNext(); iter.Advance()) {
new_fields.insert(iter.key());
if (iter.key() != kBytesReceivedKey) {
const base::Value* old_value = NULL;
if (!data->json().HasKey(iter.key()) ||
(data->json().Get(iter.key(), &old_value) &&
!iter.value().Equals(old_value))) {
delta->Set(iter.key() + ".current", iter.value().DeepCopy());
if (old_value)
delta->Set(iter.key() + ".previous", old_value->DeepCopy());
changed = true;
}
}
}
// If a field was in the previous json but is not in the new json, set the
// difference in |delta|.
for (base::DictionaryValue::Iterator iter(data->json());
iter.HasNext(); iter.Advance()) {
if (new_fields.find(iter.key()) == new_fields.end()) {
delta->Set(iter.key() + ".previous", iter.value().DeepCopy());
changed = true;
}
}
// Update the OnChangedStat and dispatch the event if something significant
// changed. Replace the stored json with the new json.
data->OnItemUpdated();
if (changed) {
DispatchEvent(extensions::event_names::kOnDownloadChanged,
true,
extensions::Event::WillDispatchCallback(),
delta.release());
data->OnChangedFired();
}
data->set_json(new_json.Pass());
}
void ExtensionDownloadsEventRouter::OnDownloadRemoved(
DownloadManager* manager, DownloadItem* download_item) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (download_item->IsTemporary())
return;
DispatchEvent(extensions::event_names::kOnDownloadErased,
true,
extensions::Event::WillDispatchCallback(),
base::Value::CreateIntegerValue(download_item->GetId()));
}
void ExtensionDownloadsEventRouter::DispatchEvent(
const char* event_name,
bool include_incognito,
const extensions::Event::WillDispatchCallback& will_dispatch_callback,
base::Value* arg) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!extensions::ExtensionSystem::Get(profile_)->event_router())
return;
scoped_ptr<base::ListValue> args(new base::ListValue());
args->Append(arg);
std::string json_args;
base::JSONWriter::Write(args.get(), &json_args);
scoped_ptr<extensions::Event> event(new extensions::Event(
event_name, args.Pass()));
// The downloads system wants to share on-record events with off-record
// extension renderers even in incognito_split_mode because that's how
// chrome://downloads works. The "restrict_to_profile" mechanism does not
// anticipate this, so it does not automatically prevent sharing off-record
// events with on-record extension renderers.
event->restrict_to_profile =
(include_incognito && !profile_->IsOffTheRecord()) ? NULL : profile_;
event->will_dispatch_callback = will_dispatch_callback;
extensions::ExtensionSystem::Get(profile_)->event_router()->
BroadcastEvent(event.Pass());
DownloadsNotificationSource notification_source;
notification_source.event_name = event_name;
notification_source.profile = profile_;
content::Source<DownloadsNotificationSource> content_source(
¬ification_source);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT,
content_source,
content::Details<std::string>(&json_args));
}
| 38.087405 | 80 | 0.731718 | [
"object",
"vector"
] |
608370353eea26484aec09b5b30b96e666b94952 | 4,711 | hpp | C++ | src/qasm-simulator-cpp/src/backends/rng_engine.hpp | Shark-y/qiskit-sdk-py | c1361b823dc1a3fab76545e62975c2afb02e442d | [
"Apache-2.0"
] | null | null | null | src/qasm-simulator-cpp/src/backends/rng_engine.hpp | Shark-y/qiskit-sdk-py | c1361b823dc1a3fab76545e62975c2afb02e442d | [
"Apache-2.0"
] | 38 | 2017-08-04T09:57:36.000Z | 2017-08-23T10:35:32.000Z | src/qasm-simulator-cpp/src/backends/rng_engine.hpp | Shark-y/qiskit-sdk-py | c1361b823dc1a3fab76545e62975c2afb02e442d | [
"Apache-2.0"
] | 1 | 2017-08-18T08:22:50.000Z | 2017-08-18T08:22:50.000Z | /*
Copyright (c) 2017 IBM Corporation. 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.
*/
/**
* @file rng_engine.hpp
* @brief RngEngine use by the BaseBackend simulator class
* @author Christopher J. Wood <cjwood@us.ibm.com>
*/
#ifndef _RngEngine_hpp_
#define _RngEngine_hpp_
#include <random>
#include "types.hpp"
/***************************************************************************/ /**
*
* RngEngine Class
*
* Objects of this class are used to generate random numbers for backends.
*These
* are used to decide outcomes of measurements and resets, and for implementing
* noise.
*
******************************************************************************/
class RngEngine {
public:
/**
* Generate a uniformly distributed pseudo random real in the half-open
* interval [a,b)
* @param a closed lower bound on interval
* @param b open upper bound on interval
* @return the generated double
*/
double rand(double a, double b);
/**
* Generate a uniformly distributed pseudo random real in the half-open
* interval [0,b)
* @param b open upper bound on interval
* @return the generated double
*/
inline double rand(double b) { return rand(0., b); };
/**
* Generate a uniformly distributed pseudo random real in the half-open
* interval [0,1)
* @return the generated double
*/
inline double rand() { return rand(0., 1.); };
/**
* Generate a uniformly distributed pseudo random integer in the closed
* interval [a,b]
* @param a lower bound on interval
* @param b upper bound on interval
* @return the generated integer
*/
int_t rand_int(int_t a, int_t b);
/**
* Generate a pseudo random integer from an input discrete distribution
* @param probs the discrete distribution to sample from
* @return the generated integer
*/
int_t rand_int(std::discrete_distribution<> probs);
/**
* Generate a pseudo random integer from a a discrete distribution
* constructed from an input vector of probabilities for [0,..,n-1]
* where n is the lenght of the vector. If this vector is not normalized
* it will be scaled when it is converted to a discrete_distribution
* @param probs the vector of probabilities
* @return the generated integer
*/
int_t rand_int(std::vector<double> probs);
/**
* Default constructor initialize RNG engine with a random seed
*/
RngEngine() {
std::random_device rd;
rng.seed(rd());
};
/**
* Seeded constructor initialize RNG engine with a fixed seed
* @param seed integer to use as seed for mt19937 engine
*/
explicit RngEngine(uint_t seed) { rng.seed(seed); };
private:
std::mt19937 rng; // Mersenne twister rng engine
};
/*******************************************************************************
*
* RngEngine Methods
*
******************************************************************************/
double RngEngine::rand(double a, double b) {
double p = std::uniform_real_distribution<double>(a, b)(rng);
#ifdef DEBUG
std::stringstream ss;
ss << "DEBUG: rand(" << a << "," << b << ") = " << p;
std::clog << ss.str() << std::endl;
#endif
return p;
}
// randomly distributed integers in [a,b]
int_t RngEngine::rand_int(int_t a, int_t b) {
uint_t n = std::uniform_int_distribution<>(a, b)(rng);
#ifdef DEBUG
std::stringstream ss;
ss << "DEBUG: rand_int( " << a << "," << b << ") = " << n;
std::clog << ss.str() << std::endl;
#endif
return n;
}
// randomly distributed integers from discrete distribution
int_t RngEngine::rand_int(std::discrete_distribution<> probs) {
uint_t n = probs(rng);
#ifdef DEBUG
std::stringstream ss;
ss << "DEBUG: rand_int(" << probs.probabilities() << ") = " << n;
std::clog << ss.str() << std::endl;
#endif
return n;
}
// randomly distributed integers from vector
int_t RngEngine::rand_int(std::vector<double> probs) {
uint_t n = std::discrete_distribution<>(probs.begin(), probs.end())(rng);
#ifdef DEBUG
std::stringstream ss;
ss << "DEBUG: rand_int(" << probs << ") = " << n;
std::clog << ss.str() << std::endl;
#endif
return n;
}
//------------------------------------------------------------------------------
#endif
| 29.080247 | 81 | 0.622798 | [
"vector"
] |
6085caa8f50b1b685ac9ddcf8974d07f0a4337de | 35,831 | cc | C++ | ns-allinone-3.27/ns-3.27/src/wifi/model/sta-wifi-mac.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 93 | 2019-04-21T08:22:26.000Z | 2022-03-30T04:26:29.000Z | ns-allinone-3.27/ns-3.27/src/wifi/model/sta-wifi-mac.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 12 | 2019-04-19T16:39:58.000Z | 2021-06-22T13:18:32.000Z | ns-allinone-3.27/ns-3.27/src/wifi/model/sta-wifi-mac.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 21 | 2019-05-27T19:36:12.000Z | 2021-07-26T02:37:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2006, 2009 INRIA
* Copyright (c) 2009 MIRKO BANCHI
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
* Mirko Banchi <mk.banchi@gmail.com>
*/
#include "sta-wifi-mac.h"
#include "ns3/log.h"
#include "ns3/simulator.h"
#include "mac-low.h"
/*
* The state machine for this STA is:
-------------- -----------
| Associated | <-------------------- -------> | Refused |
-------------- \ / -----------
\ \ /
\ ----------------- -----------------------------
\-> | Beacon Missed | --> | Wait Association Response |
----------------- -----------------------------
\ ^
\ |
\ -----------------------
\-> | Wait Probe Response |
-----------------------
*/
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("StaWifiMac");
NS_OBJECT_ENSURE_REGISTERED (StaWifiMac);
TypeId
StaWifiMac::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::StaWifiMac")
.SetParent<RegularWifiMac> ()
.SetGroupName ("Wifi")
.AddConstructor<StaWifiMac> ()
.AddAttribute ("ProbeRequestTimeout", "The interval between two consecutive probe request attempts.",
TimeValue (Seconds (0.05)),
MakeTimeAccessor (&StaWifiMac::m_probeRequestTimeout),
MakeTimeChecker ())
.AddAttribute ("AssocRequestTimeout", "The interval between two consecutive assoc request attempts.",
TimeValue (Seconds (0.5)),
MakeTimeAccessor (&StaWifiMac::m_assocRequestTimeout),
MakeTimeChecker ())
.AddAttribute ("MaxMissedBeacons",
"Number of beacons which much be consecutively missed before "
"we attempt to restart association.",
UintegerValue (10),
MakeUintegerAccessor (&StaWifiMac::m_maxMissedBeacons),
MakeUintegerChecker<uint32_t> ())
.AddAttribute ("ActiveProbing",
"If true, we send probe requests. If false, we don't."
"NOTE: if more than one STA in your simulation is using active probing, "
"you should enable it at a different simulation time for each STA, "
"otherwise all the STAs will start sending probes at the same time resulting in collisions. "
"See bug 1060 for more info.",
BooleanValue (false),
MakeBooleanAccessor (&StaWifiMac::SetActiveProbing, &StaWifiMac::GetActiveProbing),
MakeBooleanChecker ())
.AddTraceSource ("Assoc", "Associated with an access point.",
MakeTraceSourceAccessor (&StaWifiMac::m_assocLogger),
"ns3::Mac48Address::TracedCallback")
.AddTraceSource ("DeAssoc", "Association with an access point lost.",
MakeTraceSourceAccessor (&StaWifiMac::m_deAssocLogger),
"ns3::Mac48Address::TracedCallback")
;
return tid;
}
StaWifiMac::StaWifiMac ()
: m_state (BEACON_MISSED),
m_probeRequestEvent (),
m_assocRequestEvent (),
m_beaconWatchdogEnd (Seconds (0))
{
NS_LOG_FUNCTION (this);
//Let the lower layers know that we are acting as a non-AP STA in
//an infrastructure BSS.
SetTypeOfStation (STA);
}
StaWifiMac::~StaWifiMac ()
{
NS_LOG_FUNCTION (this);
}
void
StaWifiMac::SetMaxMissedBeacons (uint32_t missed)
{
NS_LOG_FUNCTION (this << missed);
m_maxMissedBeacons = missed;
}
void
StaWifiMac::SetProbeRequestTimeout (Time timeout)
{
NS_LOG_FUNCTION (this << timeout);
m_probeRequestTimeout = timeout;
}
void
StaWifiMac::SetAssocRequestTimeout (Time timeout)
{
NS_LOG_FUNCTION (this << timeout);
m_assocRequestTimeout = timeout;
}
void
StaWifiMac::StartActiveAssociation (void)
{
NS_LOG_FUNCTION (this);
TryToEnsureAssociated ();
}
void
StaWifiMac::SetActiveProbing (bool enable)
{
NS_LOG_FUNCTION (this << enable);
if (enable)
{
Simulator::ScheduleNow (&StaWifiMac::TryToEnsureAssociated, this);
}
else
{
m_probeRequestEvent.Cancel ();
}
m_activeProbing = enable;
}
bool StaWifiMac::GetActiveProbing (void) const
{
return m_activeProbing;
}
void
StaWifiMac::SendProbeRequest (void)
{
NS_LOG_FUNCTION (this);
WifiMacHeader hdr;
hdr.SetProbeReq ();
hdr.SetAddr1 (Mac48Address::GetBroadcast ());
hdr.SetAddr2 (GetAddress ());
hdr.SetAddr3 (Mac48Address::GetBroadcast ());
hdr.SetDsNotFrom ();
hdr.SetDsNotTo ();
hdr.SetNoOrder ();
Ptr<Packet> packet = Create<Packet> ();
MgtProbeRequestHeader probe;
probe.SetSsid (GetSsid ());
probe.SetSupportedRates (GetSupportedRates ());
if (m_htSupported || m_vhtSupported || m_heSupported)
{
probe.SetHtCapabilities (GetHtCapabilities ());
}
if (m_vhtSupported || m_heSupported)
{
probe.SetVhtCapabilities (GetVhtCapabilities ());
}
if (m_heSupported)
{
probe.SetHeCapabilities (GetHeCapabilities ());
}
packet->AddHeader (probe);
//The standard is not clear on the correct queue for management
//frames if we are a QoS AP. The approach taken here is to always
//use the DCF for these regardless of whether we have a QoS
//association or not.
m_dca->Queue (packet, hdr);
if (m_probeRequestEvent.IsRunning ())
{
m_probeRequestEvent.Cancel ();
}
m_probeRequestEvent = Simulator::Schedule (m_probeRequestTimeout,
&StaWifiMac::ProbeRequestTimeout, this);
}
void
StaWifiMac::SendAssociationRequest (void)
{
NS_LOG_FUNCTION (this << GetBssid ());
WifiMacHeader hdr;
hdr.SetAssocReq ();
hdr.SetAddr1 (GetBssid ());
hdr.SetAddr2 (GetAddress ());
hdr.SetAddr3 (GetBssid ());
hdr.SetDsNotFrom ();
hdr.SetDsNotTo ();
hdr.SetNoOrder ();
Ptr<Packet> packet = Create<Packet> ();
MgtAssocRequestHeader assoc;
assoc.SetSsid (GetSsid ());
assoc.SetSupportedRates (GetSupportedRates ());
assoc.SetCapabilities (GetCapabilities ());
if (m_htSupported || m_vhtSupported || m_heSupported)
{
assoc.SetHtCapabilities (GetHtCapabilities ());
}
if (m_vhtSupported || m_heSupported)
{
assoc.SetVhtCapabilities (GetVhtCapabilities ());
}
if (m_heSupported)
{
assoc.SetHeCapabilities (GetHeCapabilities ());
}
packet->AddHeader (assoc);
//The standard is not clear on the correct queue for management
//frames if we are a QoS AP. The approach taken here is to always
//use the DCF for these regardless of whether we have a QoS
//association or not.
m_dca->Queue (packet, hdr);
if (m_assocRequestEvent.IsRunning ())
{
m_assocRequestEvent.Cancel ();
}
m_assocRequestEvent = Simulator::Schedule (m_assocRequestTimeout,
&StaWifiMac::AssocRequestTimeout, this);
}
void
StaWifiMac::TryToEnsureAssociated (void)
{
NS_LOG_FUNCTION (this);
switch (m_state)
{
case ASSOCIATED:
return;
break;
case WAIT_PROBE_RESP:
/* we have sent a probe request earlier so we
do not need to re-send a probe request immediately.
We just need to wait until probe-request-timeout
or until we get a probe response
*/
break;
case BEACON_MISSED:
/* we were associated but we missed a bunch of beacons
* so we should assume we are not associated anymore.
* We try to initiate a probe request now.
*/
m_linkDown ();
if (m_activeProbing)
{
SetState (WAIT_PROBE_RESP);
SendProbeRequest ();
}
break;
case WAIT_ASSOC_RESP:
/* we have sent an assoc request so we do not need to
re-send an assoc request right now. We just need to
wait until either assoc-request-timeout or until
we get an assoc response.
*/
break;
case REFUSED:
/* we have sent an assoc request and received a negative
assoc resp. We wait until someone restarts an
association with a given ssid.
*/
break;
}
}
void
StaWifiMac::AssocRequestTimeout (void)
{
NS_LOG_FUNCTION (this);
SetState (WAIT_ASSOC_RESP);
SendAssociationRequest ();
}
void
StaWifiMac::ProbeRequestTimeout (void)
{
NS_LOG_FUNCTION (this);
SetState (WAIT_PROBE_RESP);
SendProbeRequest ();
}
void
StaWifiMac::MissedBeacons (void)
{
NS_LOG_FUNCTION (this);
if (m_beaconWatchdogEnd > Simulator::Now ())
{
if (m_beaconWatchdog.IsRunning ())
{
m_beaconWatchdog.Cancel ();
}
m_beaconWatchdog = Simulator::Schedule (m_beaconWatchdogEnd - Simulator::Now (),
&StaWifiMac::MissedBeacons, this);
return;
}
NS_LOG_DEBUG ("beacon missed");
SetState (BEACON_MISSED);
TryToEnsureAssociated ();
}
void
StaWifiMac::RestartBeaconWatchdog (Time delay)
{
NS_LOG_FUNCTION (this << delay);
m_beaconWatchdogEnd = std::max (Simulator::Now () + delay, m_beaconWatchdogEnd);
if (Simulator::GetDelayLeft (m_beaconWatchdog) < delay
&& m_beaconWatchdog.IsExpired ())
{
NS_LOG_DEBUG ("really restart watchdog.");
m_beaconWatchdog = Simulator::Schedule (delay, &StaWifiMac::MissedBeacons, this);
}
}
bool
StaWifiMac::IsAssociated (void) const
{
return m_state == ASSOCIATED;
}
bool
StaWifiMac::IsWaitAssocResp (void) const
{
return m_state == WAIT_ASSOC_RESP;
}
void
StaWifiMac::Enqueue (Ptr<const Packet> packet, Mac48Address to)
{
NS_LOG_FUNCTION (this << packet << to);
if (!IsAssociated ())
{
NotifyTxDrop (packet);
TryToEnsureAssociated ();
return;
}
WifiMacHeader hdr;
//If we are not a QoS AP then we definitely want to use AC_BE to
//transmit the packet. A TID of zero will map to AC_BE (through \c
//QosUtilsMapTidToAc()), so we use that as our default here.
uint8_t tid = 0;
//For now, an AP that supports QoS does not support non-QoS
//associations, and vice versa. In future the AP model should
//support simultaneously associated QoS and non-QoS STAs, at which
//point there will need to be per-association QoS state maintained
//by the association state machine, and consulted here.
if (m_qosSupported)
{
hdr.SetType (WIFI_MAC_QOSDATA);
hdr.SetQosAckPolicy (WifiMacHeader::NORMAL_ACK);
hdr.SetQosNoEosp ();
hdr.SetQosNoAmsdu ();
//Transmission of multiple frames in the same TXOP is not
//supported for now
hdr.SetQosTxopLimit (0);
//Fill in the QoS control field in the MAC header
tid = QosUtilsGetTidForPacket (packet);
//Any value greater than 7 is invalid and likely indicates that
//the packet had no QoS tag, so we revert to zero, which'll
//mean that AC_BE is used.
if (tid > 7)
{
tid = 0;
}
hdr.SetQosTid (tid);
}
else
{
hdr.SetTypeData ();
}
if (m_htSupported || m_vhtSupported || m_heSupported)
{
hdr.SetNoOrder ();
}
hdr.SetAddr1 (GetBssid ());
hdr.SetAddr2 (m_low->GetAddress ());
hdr.SetAddr3 (to);
hdr.SetDsNotFrom ();
hdr.SetDsTo ();
if (m_qosSupported)
{
//Sanity check that the TID is valid
NS_ASSERT (tid < 8);
m_edca[QosUtilsMapTidToAc (tid)]->Queue (packet, hdr);
}
else
{
m_dca->Queue (packet, hdr);
}
}
void
StaWifiMac::Receive (Ptr<Packet> packet, const WifiMacHeader *hdr)
{
NS_LOG_FUNCTION (this << packet << hdr);
NS_ASSERT (!hdr->IsCtl ());
if (hdr->GetAddr3 () == GetAddress ())
{
NS_LOG_LOGIC ("packet sent by us.");
return;
}
else if (hdr->GetAddr1 () != GetAddress ()
&& !hdr->GetAddr1 ().IsGroup ())
{
NS_LOG_LOGIC ("packet is not for us");
NotifyRxDrop (packet);
return;
}
else if (hdr->IsData ())
{
if (!IsAssociated ())
{
NS_LOG_LOGIC ("Received data frame while not associated: ignore");
NotifyRxDrop (packet);
return;
}
if (!(hdr->IsFromDs () && !hdr->IsToDs ()))
{
NS_LOG_LOGIC ("Received data frame not from the DS: ignore");
NotifyRxDrop (packet);
return;
}
if (hdr->GetAddr2 () != GetBssid ())
{
NS_LOG_LOGIC ("Received data frame not from the BSS we are associated with: ignore");
NotifyRxDrop (packet);
return;
}
if (hdr->IsQosData ())
{
if (hdr->IsQosAmsdu ())
{
NS_ASSERT (hdr->GetAddr3 () == GetBssid ());
DeaggregateAmsduAndForward (packet, hdr);
packet = 0;
}
else
{
ForwardUp (packet, hdr->GetAddr3 (), hdr->GetAddr1 ());
}
}
else
{
ForwardUp (packet, hdr->GetAddr3 (), hdr->GetAddr1 ());
}
return;
}
else if (hdr->IsProbeReq ()
|| hdr->IsAssocReq ())
{
//This is a frame aimed at an AP, so we can safely ignore it.
NotifyRxDrop (packet);
return;
}
else if (hdr->IsBeacon ())
{
MgtBeaconHeader beacon;
packet->RemoveHeader (beacon);
CapabilityInformation capabilities = beacon.GetCapabilities ();
bool goodBeacon = false;
if (GetSsid ().IsBroadcast ()
|| beacon.GetSsid ().IsEqual (GetSsid ()))
{
NS_LOG_LOGIC ("Beacon is for our SSID");
goodBeacon = true;
}
SupportedRates rates = beacon.GetSupportedRates ();
bool bssMembershipSelectorMatch = false;
for (uint32_t i = 0; i < m_phy->GetNBssMembershipSelectors (); i++)
{
uint32_t selector = m_phy->GetBssMembershipSelector (i);
if (rates.IsBssMembershipSelectorRate (selector))
{
NS_LOG_LOGIC ("Beacon is matched to our BSS membership selector");
bssMembershipSelectorMatch = true;
}
}
if (m_phy->GetNBssMembershipSelectors () > 0 && bssMembershipSelectorMatch == false)
{
NS_LOG_LOGIC ("No match for BSS membership selector");
goodBeacon = false;
}
if ((IsWaitAssocResp () || IsAssociated ()) && hdr->GetAddr3 () != GetBssid ())
{
NS_LOG_LOGIC ("Beacon is not for us");
goodBeacon = false;
}
if (goodBeacon)
{
Time delay = MicroSeconds (beacon.GetBeaconIntervalUs () * m_maxMissedBeacons);
RestartBeaconWatchdog (delay);
SetBssid (hdr->GetAddr3 ());
SupportedRates rates = beacon.GetSupportedRates ();
for (uint32_t i = 0; i < m_phy->GetNModes (); i++)
{
WifiMode mode = m_phy->GetMode (i);
if (rates.IsSupportedRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
m_stationManager->AddSupportedMode (hdr->GetAddr2 (), mode);
}
}
bool isShortPreambleEnabled = capabilities.IsShortPreamble ();
if (m_erpSupported)
{
ErpInformation erpInformation = beacon.GetErpInformation ();
isShortPreambleEnabled &= !erpInformation.GetBarkerPreambleMode ();
if (erpInformation.GetUseProtection () == true)
{
m_stationManager->SetUseNonErpProtection (true);
}
else
{
m_stationManager->SetUseNonErpProtection (false);
}
if (capabilities.IsShortSlotTime () == true)
{
//enable short slot time
SetSlot (MicroSeconds (9));
}
else
{
//disable short slot time
SetSlot (MicroSeconds (20));
}
}
if (m_qosSupported)
{
bool qosSupported = false;
EdcaParameterSet edcaParameters = beacon.GetEdcaParameterSet ();
if (edcaParameters.IsQosSupported ())
{
qosSupported = true;
//The value of the TXOP Limit field is specified as an unsigned integer, with the least significant octet transmitted first, in units of 32 μs.
SetEdcaParameters (AC_BE, edcaParameters.GetBeCWmin (), edcaParameters.GetBeCWmax (), edcaParameters.GetBeAifsn (), 32 * MicroSeconds (edcaParameters.GetBeTXOPLimit ()));
SetEdcaParameters (AC_BK, edcaParameters.GetBkCWmin (), edcaParameters.GetBkCWmax (), edcaParameters.GetBkAifsn (), 32 * MicroSeconds (edcaParameters.GetBkTXOPLimit ()));
SetEdcaParameters (AC_VI, edcaParameters.GetViCWmin (), edcaParameters.GetViCWmax (), edcaParameters.GetViAifsn (), 32 * MicroSeconds (edcaParameters.GetViTXOPLimit ()));
SetEdcaParameters (AC_VO, edcaParameters.GetVoCWmin (), edcaParameters.GetVoCWmax (), edcaParameters.GetVoAifsn (), 32 * MicroSeconds (edcaParameters.GetVoTXOPLimit ()));
}
m_stationManager->SetQosSupport (hdr->GetAddr2 (), qosSupported);
}
if (m_htSupported)
{
HtCapabilities htCapabilities = beacon.GetHtCapabilities ();
if (!htCapabilities.IsSupportedMcs (0))
{
m_stationManager->RemoveAllSupportedMcs (hdr->GetAddr2 ());
}
else
{
m_stationManager->AddStationHtCapabilities (hdr->GetAddr2 (), htCapabilities);
HtOperation htOperation = beacon.GetHtOperation ();
if (htOperation.GetNonGfHtStasPresent ())
{
m_stationManager->SetUseGreenfieldProtection (true);
}
else
{
m_stationManager->SetUseGreenfieldProtection (false);
}
if (!m_vhtSupported && GetRifsSupported () && htOperation.GetRifsMode ())
{
m_stationManager->SetRifsPermitted (true);
}
else
{
m_stationManager->SetRifsPermitted (false);
}
for (uint32_t i = 0; i < m_phy->GetNMcs (); i++)
{
WifiMode mcs = m_phy->GetMcs (i);
if (mcs.GetModulationClass () == WIFI_MOD_CLASS_HT && htCapabilities.IsSupportedMcs (mcs.GetMcsValue ()))
{
m_stationManager->AddSupportedMcs (hdr->GetAddr2 (), mcs);
}
}
}
}
if (m_vhtSupported)
{
VhtCapabilities vhtCapabilities = beacon.GetVhtCapabilities ();
//we will always fill in RxHighestSupportedLgiDataRate field at TX, so this can be used to check whether it supports VHT
if (vhtCapabilities.GetRxHighestSupportedLgiDataRate () > 0)
{
m_stationManager->AddStationVhtCapabilities (hdr->GetAddr2 (), vhtCapabilities);
VhtOperation vhtOperation = beacon.GetVhtOperation ();
for (uint32_t i = 0; i < m_phy->GetNMcs (); i++)
{
WifiMode mcs = m_phy->GetMcs (i);
if (mcs.GetModulationClass () == WIFI_MOD_CLASS_VHT && vhtCapabilities.IsSupportedRxMcs (mcs.GetMcsValue ()))
{
m_stationManager->AddSupportedMcs (hdr->GetAddr2 (), mcs);
}
}
}
}
if (m_heSupported)
{
HeCapabilities heCapabilities = beacon.GetHeCapabilities ();
//todo: once we support non constant rate managers, we should add checks here whether HE is supported by the peer
m_stationManager->AddStationHeCapabilities (hdr->GetAddr2 (), heCapabilities);
for (uint32_t i = 0; i < m_phy->GetNMcs (); i++)
{
WifiMode mcs = m_phy->GetMcs (i);
if (mcs.GetModulationClass () == WIFI_MOD_CLASS_HE && heCapabilities.IsSupportedRxMcs (mcs.GetMcsValue ()))
{
m_stationManager->AddSupportedMcs (hdr->GetAddr2 (), mcs);
}
}
}
m_stationManager->SetShortPreambleEnabled (isShortPreambleEnabled);
m_stationManager->SetShortSlotTimeEnabled (capabilities.IsShortSlotTime ());
}
if (goodBeacon && m_state == BEACON_MISSED)
{
SetState (WAIT_ASSOC_RESP);
SendAssociationRequest ();
}
return;
}
else if (hdr->IsProbeResp ())
{
if (m_state == WAIT_PROBE_RESP)
{
MgtProbeResponseHeader probeResp;
packet->RemoveHeader (probeResp);
CapabilityInformation capabilities = probeResp.GetCapabilities ();
if (!probeResp.GetSsid ().IsEqual (GetSsid ()))
{
//not a probe resp for our ssid.
return;
}
SupportedRates rates = probeResp.GetSupportedRates ();
for (uint32_t i = 0; i < m_phy->GetNBssMembershipSelectors (); i++)
{
uint32_t selector = m_phy->GetBssMembershipSelector (i);
if (!rates.IsSupportedRate (selector))
{
return;
}
}
for (uint32_t i = 0; i < m_phy->GetNModes (); i++)
{
WifiMode mode = m_phy->GetMode (i);
if (rates.IsSupportedRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
m_stationManager->AddSupportedMode (hdr->GetAddr2 (), mode);
if (rates.IsBasicRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
m_stationManager->AddBasicMode (mode);
}
}
}
bool isShortPreambleEnabled = capabilities.IsShortPreamble ();
if (m_erpSupported)
{
bool isErpAllowed = false;
for (uint32_t i = 0; i < m_phy->GetNModes (); i++)
{
WifiMode mode = m_phy->GetMode (i);
if (mode.GetModulationClass () == WIFI_MOD_CLASS_ERP_OFDM && rates.IsSupportedRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
isErpAllowed = true;
break;
}
}
if (!isErpAllowed)
{
//disable short slot time and set cwMin to 31
SetSlot (MicroSeconds (20));
ConfigureContentionWindow (31, 1023);
}
else
{
ErpInformation erpInformation = probeResp.GetErpInformation ();
isShortPreambleEnabled &= !erpInformation.GetBarkerPreambleMode ();
if (m_stationManager->GetShortSlotTimeEnabled ())
{
//enable short slot time
SetSlot (MicroSeconds (9));
}
else
{
//disable short slot time
SetSlot (MicroSeconds (20));
}
ConfigureContentionWindow (15, 1023);
}
}
m_stationManager->SetShortPreambleEnabled (isShortPreambleEnabled);
m_stationManager->SetShortSlotTimeEnabled (capabilities.IsShortSlotTime ());
SetBssid (hdr->GetAddr3 ());
Time delay = MicroSeconds (probeResp.GetBeaconIntervalUs () * m_maxMissedBeacons);
RestartBeaconWatchdog (delay);
if (m_probeRequestEvent.IsRunning ())
{
m_probeRequestEvent.Cancel ();
}
SetState (WAIT_ASSOC_RESP);
SendAssociationRequest ();
}
return;
}
else if (hdr->IsAssocResp ())
{
if (m_state == WAIT_ASSOC_RESP)
{
MgtAssocResponseHeader assocResp;
packet->RemoveHeader (assocResp);
if (m_assocRequestEvent.IsRunning ())
{
m_assocRequestEvent.Cancel ();
}
if (assocResp.GetStatusCode ().IsSuccess ())
{
SetState (ASSOCIATED);
NS_LOG_DEBUG ("assoc completed");
CapabilityInformation capabilities = assocResp.GetCapabilities ();
SupportedRates rates = assocResp.GetSupportedRates ();
bool isShortPreambleEnabled = capabilities.IsShortPreamble ();
if (m_erpSupported)
{
bool isErpAllowed = false;
for (uint32_t i = 0; i < m_phy->GetNModes (); i++)
{
WifiMode mode = m_phy->GetMode (i);
if (mode.GetModulationClass () == WIFI_MOD_CLASS_ERP_OFDM && rates.IsSupportedRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
isErpAllowed = true;
break;
}
}
if (!isErpAllowed)
{
//disable short slot time and set cwMin to 31
SetSlot (MicroSeconds (20));
ConfigureContentionWindow (31, 1023);
}
else
{
ErpInformation erpInformation = assocResp.GetErpInformation ();
isShortPreambleEnabled &= !erpInformation.GetBarkerPreambleMode ();
if (m_stationManager->GetShortSlotTimeEnabled ())
{
//enable short slot time
SetSlot (MicroSeconds (9));
}
else
{
//disable short slot time
SetSlot (MicroSeconds (20));
}
ConfigureContentionWindow (15, 1023);
}
}
m_stationManager->SetShortPreambleEnabled (isShortPreambleEnabled);
m_stationManager->SetShortSlotTimeEnabled (capabilities.IsShortSlotTime ());
if (m_qosSupported)
{
bool qosSupported = false;
EdcaParameterSet edcaParameters = assocResp.GetEdcaParameterSet ();
if (edcaParameters.IsQosSupported ())
{
qosSupported = true;
//The value of the TXOP Limit field is specified as an unsigned integer, with the least significant octet transmitted first, in units of 32 μs.
SetEdcaParameters (AC_BE, edcaParameters.GetBeCWmin (), edcaParameters.GetBeCWmax (), edcaParameters.GetBeAifsn (), 32 * MicroSeconds (edcaParameters.GetBeTXOPLimit ()));
SetEdcaParameters (AC_BK, edcaParameters.GetBkCWmin (), edcaParameters.GetBkCWmax (), edcaParameters.GetBkAifsn (), 32 * MicroSeconds (edcaParameters.GetBkTXOPLimit ()));
SetEdcaParameters (AC_VI, edcaParameters.GetViCWmin (), edcaParameters.GetViCWmax (), edcaParameters.GetViAifsn (), 32 * MicroSeconds (edcaParameters.GetViTXOPLimit ()));
SetEdcaParameters (AC_VO, edcaParameters.GetVoCWmin (), edcaParameters.GetVoCWmax (), edcaParameters.GetVoAifsn (), 32 * MicroSeconds (edcaParameters.GetVoTXOPLimit ()));
}
m_stationManager->SetQosSupport (hdr->GetAddr2 (), qosSupported);
}
if (m_htSupported)
{
HtCapabilities htCapabilities = assocResp.GetHtCapabilities ();
if (!htCapabilities.IsSupportedMcs (0))
{
m_stationManager->RemoveAllSupportedMcs (hdr->GetAddr2 ());
}
else
{
m_stationManager->AddStationHtCapabilities (hdr->GetAddr2 (), htCapabilities);
HtOperation htOperation = assocResp.GetHtOperation ();
if (htOperation.GetNonGfHtStasPresent ())
{
m_stationManager->SetUseGreenfieldProtection (true);
}
else
{
m_stationManager->SetUseGreenfieldProtection (false);
}
if (!m_vhtSupported && GetRifsSupported () && htOperation.GetRifsMode ())
{
m_stationManager->SetRifsPermitted (true);
}
else
{
m_stationManager->SetRifsPermitted (false);
}
}
}
if (m_vhtSupported)
{
VhtCapabilities vhtCapabilities = assocResp.GetVhtCapabilities ();
//we will always fill in RxHighestSupportedLgiDataRate field at TX, so this can be used to check whether it supports VHT
if (vhtCapabilities.GetRxHighestSupportedLgiDataRate () > 0)
{
m_stationManager->AddStationVhtCapabilities (hdr->GetAddr2 (), vhtCapabilities);
VhtOperation vhtOperation = assocResp.GetVhtOperation ();
}
}
if (m_heSupported)
{
HeCapabilities hecapabilities = assocResp.GetHeCapabilities ();
//todo: once we support non constant rate managers, we should add checks here whether HE is supported by the peer
m_stationManager->AddStationHeCapabilities (hdr->GetAddr2 (), hecapabilities);
}
for (uint32_t i = 0; i < m_phy->GetNModes (); i++)
{
WifiMode mode = m_phy->GetMode (i);
if (rates.IsSupportedRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
m_stationManager->AddSupportedMode (hdr->GetAddr2 (), mode);
if (rates.IsBasicRate (mode.GetDataRate (m_phy->GetChannelWidth ())))
{
m_stationManager->AddBasicMode (mode);
}
}
}
if (m_htSupported)
{
HtCapabilities htCapabilities = assocResp.GetHtCapabilities ();
for (uint32_t i = 0; i < m_phy->GetNMcs (); i++)
{
WifiMode mcs = m_phy->GetMcs (i);
if (mcs.GetModulationClass () == WIFI_MOD_CLASS_HT && htCapabilities.IsSupportedMcs (mcs.GetMcsValue ()))
{
m_stationManager->AddSupportedMcs (hdr->GetAddr2 (), mcs);
//here should add a control to add basic MCS when it is implemented
}
}
}
if (m_vhtSupported)
{
VhtCapabilities vhtcapabilities = assocResp.GetVhtCapabilities ();
for (uint32_t i = 0; i < m_phy->GetNMcs (); i++)
{
WifiMode mcs = m_phy->GetMcs (i);
if (mcs.GetModulationClass () == WIFI_MOD_CLASS_VHT && vhtcapabilities.IsSupportedRxMcs (mcs.GetMcsValue ()))
{
m_stationManager->AddSupportedMcs (hdr->GetAddr2 (), mcs);
//here should add a control to add basic MCS when it is implemented
}
}
}
if (m_heSupported)
{
HeCapabilities heCapabilities = assocResp.GetHeCapabilities ();
for (uint32_t i = 0; i < m_phy->GetNMcs (); i++)
{
WifiMode mcs = m_phy->GetMcs (i);
if (mcs.GetModulationClass () == WIFI_MOD_CLASS_HE && heCapabilities.IsSupportedRxMcs (mcs.GetMcsValue ()))
{
m_stationManager->AddSupportedMcs (hdr->GetAddr2 (), mcs);
//here should add a control to add basic MCS when it is implemented
}
}
}
if (!m_linkUp.IsNull ())
{
m_linkUp ();
}
}
else
{
NS_LOG_DEBUG ("assoc refused");
SetState (REFUSED);
}
}
return;
}
//Invoke the receive handler of our parent class to deal with any
//other frames. Specifically, this will handle Block Ack-related
//Management Action frames.
RegularWifiMac::Receive (packet, hdr);
}
SupportedRates
StaWifiMac::GetSupportedRates (void) const
{
SupportedRates rates;
if (m_htSupported || m_vhtSupported || m_heSupported)
{
for (uint32_t i = 0; i < m_phy->GetNBssMembershipSelectors (); i++)
{
rates.AddBssMembershipSelectorRate (m_phy->GetBssMembershipSelector (i));
}
}
for (uint32_t i = 0; i < m_phy->GetNModes (); i++)
{
WifiMode mode = m_phy->GetMode (i);
uint64_t modeDataRate = mode.GetDataRate (m_phy->GetChannelWidth ());
NS_LOG_DEBUG ("Adding supported rate of " << modeDataRate);
rates.AddSupportedRate (modeDataRate);
}
return rates;
}
CapabilityInformation
StaWifiMac::GetCapabilities (void) const
{
CapabilityInformation capabilities;
capabilities.SetShortPreamble (m_phy->GetShortPlcpPreambleSupported () || m_erpSupported);
capabilities.SetShortSlotTime (GetShortSlotTimeSupported () && m_erpSupported);
return capabilities;
}
void
StaWifiMac::SetState (MacState value)
{
if (value == ASSOCIATED
&& m_state != ASSOCIATED)
{
m_assocLogger (GetBssid ());
}
else if (value != ASSOCIATED
&& m_state == ASSOCIATED)
{
m_deAssocLogger (GetBssid ());
}
m_state = value;
}
void
StaWifiMac::SetEdcaParameters (AcIndex ac, uint8_t cwMin, uint8_t cwMax, uint8_t aifsn, Time txopLimit)
{
Ptr<EdcaTxopN> edca = m_edca.find (ac)->second;
edca->SetMinCw (cwMin);
edca->SetMaxCw (cwMax);
edca->SetAifsn (aifsn);
edca->SetTxopLimit (txopLimit);
}
} //namespace ns3
| 36.825283 | 192 | 0.551868 | [
"model"
] |
60872d8b4c1ee1eca925a0c764e590058ee48952 | 468 | cc | C++ | cn/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | cn/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | cn/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | #include <vector>
class Solution
{
public:
int majorityElement(std::vector<int> &nums)
{
int cur_num = nums[0];
int freq = 1;
for (int i = 1; i < nums.size(); i++)
{
if (cur_num != nums[i])
freq--;
else
freq++;
if (freq < 0)
{
cur_num = nums[i];
freq = 1;
}
}
return cur_num;
}
}; | 17.333333 | 47 | 0.363248 | [
"vector"
] |
608bca7198d2609c0a7bcc53a3a43752af6f7963 | 2,083 | cpp | C++ | src/Model.cpp | emctague/horre | e6631ecc10c17fba3e7938280c292181b18e7242 | [
"MIT"
] | null | null | null | src/Model.cpp | emctague/horre | e6631ecc10c17fba3e7938280c292181b18e7242 | [
"MIT"
] | null | null | null | src/Model.cpp | emctague/horre | e6631ecc10c17fba3e7938280c292181b18e7242 | [
"MIT"
] | null | null | null | // Created by Ethan McTague on 2019-09-22.
#include <string>
#include <fstream>
#include <vector>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include "Model.h"
Model::Model(ResourceSet *set, const std::string &path) {
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(GlobalConfig_ModelPath + path, aiProcess_Triangulate |
aiProcess_FlipUVs |
aiProcess_OptimizeMeshes |
aiProcess_GenNormals |
aiProcess_CalcTangentSpace |
aiProcess_RemoveRedundantMaterials);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
throw std::runtime_error("Unable to open file: " + path + " (reason: " + importer.GetErrorString() + ")");
processNode(set, scene, scene->mRootNode, glm::mat4{1});
MESHLOG(std::endl)
}
Model::~Model() {
}
void Model::processNode(ResourceSet *set, const aiScene *scene, aiNode *node, glm::mat4 transform) {
#if GlobalConfig_DoMeshLoadLog
std::cout << "Node: " << node->mName.C_Str() << " (";
#endif
aiMatrix4x4 &m = node->mTransformation;
glm::mat4 nodeTransform = transform * glm::mat4{
m.a1, m.b1, m.c1, m.d1,
m.a2, m.b2, m.c2, m.d2,
m.a3, m.b3, m.c3, m.d3,
m.a4, m.b4, m.c4, m.d4
};
for (unsigned i = 0; i < node->mNumMeshes; i++) {
MESHLOG(scene->mMeshes[node->mMeshes[i]]->mName.C_Str() << "( ")
meshes.emplace_back(std::make_unique<Mesh>(set, scene, scene->mMeshes[node->mMeshes[i]], nodeTransform));
MESHLOG("), ")
}
MESHLOG(")" << std::endl << "\t")
for (unsigned i = 0; i < node->mNumChildren; i++) {
processNode(set, scene, node->mChildren[i], nodeTransform);
}
}
| 37.872727 | 114 | 0.522804 | [
"mesh",
"vector",
"model",
"transform"
] |
608c28fb5da74bcd1015520c313b16b746bb8f01 | 8,495 | hpp | C++ | setup/xapp-sm-connector/src/xapp-mgmt/subs_mgmt.hpp | wineslab/colosseum-near-rt-ric | e41cd25e500c527ee60fd8095bb6f40e96b7ccce | [
"Apache-2.0"
] | 1 | 2022-02-24T21:40:00.000Z | 2022-02-24T21:40:00.000Z | setup/xapp-sm-connector/src/xapp-mgmt/subs_mgmt.hpp | wineslab/colosseum-near-rt-ric | e41cd25e500c527ee60fd8095bb6f40e96b7ccce | [
"Apache-2.0"
] | null | null | null | setup/xapp-sm-connector/src/xapp-mgmt/subs_mgmt.hpp | wineslab/colosseum-near-rt-ric | e41cd25e500c527ee60fd8095bb6f40e96b7ccce | [
"Apache-2.0"
] | null | null | null | /*
==================================================================================
Copyright (c) 2019-2020 AT&T Intellectual Property.
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.
==================================================================================
*/
/*
* subs_mgmt.hpp
* Created on: 2019
* Author: Ashwin Shridharan, Shraboni Jana
*/
#pragma once
#ifndef SUBSCRIPTION_HANDLER
#define SUBSCRIPTION_HANDLER
#include <functional>
#include <mdclog/mdclog.h>
#include <mutex>
#include <condition_variable>
#include <unordered_map>
#include <chrono>
#include <tuple>
#include "../xapp-asn/e2ap/subscription_delete_request.hpp"
#include "../xapp-asn/e2ap/subscription_delete_response.hpp"
#include "../xapp-asn/e2ap/subscription_request.hpp"
#include "../xapp-asn/e2ap/subscription_response.hpp"
#define SUBSCR_SUCCESS 1
#define SUBSCR_ERR_TX -1
#define SUBSCR_ERR_TIMEOUT -2
#define SUBSCR_ERR_FAIL -3
#define SUBSCR_ERR_UNKNOWN -4
#define SUBSCR_ERR_DUPLICATE -5
using namespace std;
class TransmitterBase
{
public:
virtual ~TransmitterBase() {}
template<class T>
const T& getParam() const; //to be implemented after Parameter
template<class T, class U>
void setParam(const U& rhs); //to be implemented after Parameter
};
template <typename T>
class Transmitter : public TransmitterBase
{
public:
Transmitter(const T& tx) :obj(tx) {}
const T& getParam() const {return obj;}
void setParam(const T& tx) {obj=tx;}
private:
T obj;
};
//Here's the trick: dynamic_cast rather than virtual
template<class T> const T& TransmitterBase::getParam() const
{
return dynamic_cast<const Transmitter<T>&>(*this).getParam();
}
template<class T, class U> void TransmitterBase::setParam(const U& rhs)
{
dynamic_cast<Transmitter<T>&>(*this).setParam(rhs);
return;
}
typedef enum {
request_pending = 1,
request_success,
request_failed,
delete_request_pending,
delete_request_success,
delete_request_failed,
request_duplicate
}Subscription_Status_Types;
using transaction_identifier = unsigned char*;
using transaction_status = Subscription_Status_Types;
class SubscriptionHandler {
public:
SubscriptionHandler(unsigned int timeout_seconds = 10);
template <typename AppTransmitter>
int manage_subscription_request(transaction_identifier, AppTransmitter &&);
template <typename AppTransmitter>
int manage_subscription_delete_request(transaction_identifier, AppTransmitter &&);
void manage_subscription_response(int message_type, transaction_identifier id, const void *message_payload, size_t message_len);
int const get_request_status(transaction_identifier);
bool set_request_status(transaction_identifier, transaction_status);
bool is_request_entry(transaction_identifier);
void set_timeout(unsigned int);
void clear(void);
void set_ignore_subs_resp(bool b){_ignore_subs_resp = b;};
private:
bool add_request_entry(transaction_identifier, transaction_status);
bool delete_request_entry(transaction_identifier);
template <typename AppTransmitter>
bool add_transmitter_entry(transaction_identifier, AppTransmitter&&);
std::unordered_map<transaction_identifier, TransmitterBase> trans_table;
std::unordered_map<transaction_identifier, transaction_status> status_table;
std::unique_ptr<std::mutex> _data_lock;
std::unique_ptr<std::condition_variable> _cv;
std::chrono::seconds _time_out;
bool _ignore_subs_resp = false;
};
template <typename AppTransmitter>
bool SubscriptionHandler::add_transmitter_entry(transaction_identifier id, AppTransmitter &&trans){
// add entry in hash table if it does not exist
//auto search = trans_table.find(id);
auto search = trans_table.begin();
while (search != trans_table.end()) {
if (strcmp((const char*) search->first, (const char*) id) == 0) {
break;
}
++search;
}
if(search != trans_table.end()){
return false;
}
Transmitter<AppTransmitter> tptr(trans);
trans_table[id] = tptr;
return true;
};
//this will work for both sending subscription request and subscription delete request.
//The handler is oblivious of the message content and follows the transaction id.
template<typename AppTransmitter>
int SubscriptionHandler::manage_subscription_request(transaction_identifier rmr_trans_id, AppTransmitter && tx){
int res;
// put entry in request table
{
std::lock_guard<std::mutex> lock(*(_data_lock.get()));
res = add_request_entry(rmr_trans_id, request_pending);
if(! res){
mdclog_write(MDCLOG_ERR, "%s, %d : Error adding new subscription request %s to queue because request with identical key already present", __FILE__, __LINE__, rmr_trans_id);
return SUBSCR_ERR_DUPLICATE;
}
else {
std::cout << "Added status pending to request " << rmr_trans_id << std::endl;
}}
// acquire lock ...
std::unique_lock<std::mutex> _local_lock(*(_data_lock.get()));
// Send the message
bool flg = tx();
if (!flg){
// clear state
delete_request_entry(rmr_trans_id);
mdclog_write(MDCLOG_ERR, "%s, %d :: Error transmitting subscription request %s", __FILE__, __LINE__, rmr_trans_id );
return SUBSCR_ERR_TX;
} else {
mdclog_write(MDCLOG_INFO, "%s, %d :: Transmitted subscription request for trans_id %s", __FILE__, __LINE__, rmr_trans_id );
add_transmitter_entry(rmr_trans_id, tx);
}
// record time stamp ..
auto start = std::chrono::system_clock::now();
res = SUBSCR_ERR_UNKNOWN;
while(1){
// release lock and wait to be woken up
_cv.get()->wait_for(_local_lock, _time_out);
// we have woken and acquired data_lock
// check status and return appropriate object
int status = get_request_status(rmr_trans_id);
if (status == request_success){
mdclog_write(MDCLOG_INFO, "Successfully subscribed for request for trans_id %s", rmr_trans_id);
res = SUBSCR_SUCCESS;
break;
}
if (status == request_pending){
// woken up spuriously or timed out
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> f = end - start;
if ( f > _time_out){
mdclog_write(MDCLOG_ERR, "%s, %d:: Subscription request with transaction id %s timed out waiting for response ", __FILE__, __LINE__, rmr_trans_id);
//res = SUBSCR_ERR_TIMEOUT;
//sunny side scenario. assuming subscription response is received.
res = SUBSCR_SUCCESS;
break;
}
else{
mdclog_write(MDCLOG_INFO, "Subscription request with transaction id %s Waiting for response....", rmr_trans_id);
continue;
}
}
if(status == request_failed){
mdclog_write(MDCLOG_ERR, "Error :: %s, %d : Subscription Request with transaction id %s got failure response .. \n", __FILE__, __LINE__, rmr_trans_id);
res = SUBSCR_ERR_FAIL;
break;
}
if (status == request_duplicate){
mdclog_write(MDCLOG_ERR, "Error :: %s, %d : Subscription Request with transaction id %s is duplicate : subscription already present in table .. \n", __FILE__, __LINE__, rmr_trans_id);
res = SUBSCR_ERR_DUPLICATE;
break;
}
// if we are here, some spurious
// status obtained or request failed . we return appropriate error code
mdclog_write(MDCLOG_ERR, "Error :: %s, %d : Spurious time out caused by invalid state of request %s, and state = %d. Deleting request entry and failing .. \n", __FILE__, __LINE__, rmr_trans_id, status);
res = SUBSCR_ERR_UNKNOWN;
break;
};
delete_request_entry(rmr_trans_id);
// release data lock
_local_lock.unlock();
// std::cout <<"Returning res = " << res << " for request = " << rmr_trans_id << std::endl;
return res;
};
std::unordered_map<transaction_identifier, transaction_status>::iterator find_transaction(std::unordered_map<transaction_identifier, transaction_status> map,
transaction_identifier id);
bool transaction_present(std::unordered_map<transaction_identifier, transaction_status> map, transaction_identifier id);
#endif
| 31.462963 | 205 | 0.717245 | [
"object"
] |
6095c9c1d0b8f2310ced48bdfdeaffe40207ca31 | 1,391 | hpp | C++ | src/kernels/cpu/caffe/blob.hpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | src/kernels/cpu/caffe/blob.hpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | src/kernels/cpu/caffe/blob.hpp | ViewFaceCore/TenniS | c1d21a71c1cd025ddbbe29924c8b3296b3520fc0 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by kier on 2020/6/2.
//
#ifndef TENNIS_BLOB_HPP
#define TENNIS_BLOB_HPP
#include "core/tensor.h"
namespace ts {
namespace caffe {
template <typename T>
class Blob {
private:
using Dtype = T;
using self = Blob;
Tensor data_cpu;
public:
int count() const {
return data_cpu.count();
}
const Dtype *cpu_data() const {
return data_cpu.data<Dtype>();
}
Dtype *mutable_cpu_data() {
return data_cpu.data<Dtype>();
}
void Reshape(const std::vector<int> &shape) {
Tensor::Prototype proto(dtypeid<Dtype>::id, shape);
if (data_cpu.count() == proto.count()) {
data_cpu = data_cpu.reshape(shape);
} else {
data_cpu = Tensor(Tensor::InFlow::HOST, proto);
}
}
const std::vector<int> shape() const {
return data_cpu.sizes().std();
}
void dispose() {
data_cpu = Tensor();
}
const self *operator->() const { return this; }
self *operator->() { return this; }
Tensor tensor() const { return data_cpu; }
};
}
}
#endif //TENNIS_BLOB_HPP
| 23.183333 | 67 | 0.465852 | [
"shape",
"vector"
] |
6096e09fbd173fb23311e38fb9d62c004b576195 | 130,902 | hpp | C++ | Code/Runtime/Source/Math/Matrix.hpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 167 | 2020-06-17T06:09:41.000Z | 2022-03-13T20:31:26.000Z | Code/Runtime/Source/Math/Matrix.hpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 2 | 2020-07-11T15:12:50.000Z | 2021-06-01T01:45:49.000Z | Code/Runtime/Source/Math/Matrix.hpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 22 | 2020-06-12T02:26:10.000Z | 2022-01-02T14:04:32.000Z | // Copyright 2018-2021 JXMaster. All rights reserved.
/*
* @file Matrix.hpp
* @author JXMaster
* @date 2019/1/5
*/
#pragma once
#include "Quaternion.hpp"
#include "Transform.hpp"
#include "SimdMatrix.hpp"
#include "SimdMisc.hpp"
namespace Luna
{
//using namespace Simd;
struct alignas(16) Float3x3
{
union
{
struct
{
f32 _11, _12, _13, _padding1;
f32 _21, _22, _23, _padding2;
f32 _31, _32, _33, _padding3;
};
f32 m[3][4];
};
Float3x3() = default;
Float3x3(const Float3x3&) = default;
Float3x3& operator=(const Float3x3&) = default;
Float3x3(Float3x3&&) = default;
Float3x3& operator=(Float3x3&&) = default;
constexpr Float3x3(f32 m00, f32 m01, f32 m02,
f32 m10, f32 m11, f32 m12,
f32 m20, f32 m21, f32 m22)
: _11(m00), _12(m01), _13(m02),
_21(m10), _22(m11), _23(m12),
_31(m20), _32(m21), _33(m22) {}
explicit Float3x3(const f32 *arr)
{
_11 = arr[0]; _12 = arr[1]; _13 = arr[2];
_21 = arr[3]; _22 = arr[4]; _23 = arr[5];
_31 = arr[6]; _32 = arr[7]; _33 = arr[8];
}
// Comparison operators
bool operator == (const Float3x3& m) const;
bool operator != (const Float3x3& m) const;
// Assignment operators
Float3x3(const Float3& row1, const Float3& row2, const Float3& row3);
// Element access.
f32* operator[](usize i) { return &(m[i][0]); }
Float3 r1() const { return Float3(_11, _12, _13); }
Float3 r2() const { return Float3(_21, _22, _23); }
Float3 r3() const { return Float3(_31, _32, _33); }
Float3 c1() const { return Float3(_11, _21, _31); }
Float3 c2() const { return Float3(_12, _22, _32); }
Float3 c3() const { return Float3(_13, _23, _33); }
// Unary operators.
Float3x3 operator+() const { return *this; }
Float3x3 operator-() const;
// per-component operations.
Float3x3& operator+=(const Float3x3&);
Float3x3& operator-=(const Float3x3&);
Float3x3& operator*=(const Float3x3&);
Float3x3& operator/=(const Float3x3&);
Float3x3& operator+=(f32 s);
Float3x3& operator-=(f32 s);
Float3x3& operator*=(f32 s);
Float3x3& operator/=(f32 s);
// Constants
static constexpr Float3x3 identity()
{
return Float3x3(
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f);
}
};
// per-component operations.
Float3x3 operator+(const Float3x3& m1, const Float3x3& m2);
Float3x3 operator+(const Float3x3& m1, f32 s);
Float3x3 operator+(f32 s, const Float3x3& m1);
Float3x3 operator-(const Float3x3& m1, const Float3x3& m2);
Float3x3 operator-(const Float3x3& m1, f32 s);
Float3x3 operator-(f32 s, const Float3x3& m1);
Float3x3 operator*(const Float3x3& m1, const Float3x3& m2);
Float3x3 operator*(const Float3x3& m1, f32 s);
Float3x3 operator*(f32 s, const Float3x3& m1);
Float3x3 operator/(const Float3x3& m1, const Float3x3& m2);
Float3x3 operator/(const Float3x3& m1, f32 s);
Float3x3 operator/(f32 s, const Float3x3& m1);
// matrix math.
Float3 mul(const Float3& vec, const Float3x3& mat);
Float3 mul(const Float3x3& mat, const Float3& vec);
Float3x3 mul(const Float3x3& m1, const Float3x3& m2);
static_assert(sizeof(Float3x3) == 12 * sizeof(f32), "Incorrect Float3x3 size.");
struct alignas(16) Float4x3
{
union
{
struct
{
f32 _11, _12, _13, _padding1;
f32 _21, _22, _23, _padding2;
f32 _31, _32, _33, _padding3;
f32 _41, _42, _43, _padding4;
};
f32 m[4][4];
};
Float4x3() = default;
Float4x3(const Float4x3&) = default;
Float4x3& operator=(const Float4x3&) = default;
Float4x3(Float4x3&&) = default;
Float4x3& operator=(Float4x3&&) = default;
constexpr Float4x3(f32 m00, f32 m01, f32 m02,
f32 m10, f32 m11, f32 m12,
f32 m20, f32 m21, f32 m22,
f32 m30, f32 m31, f32 m32)
: _11(m00), _12(m01), _13(m02),
_21(m10), _22(m11), _23(m12),
_31(m20), _32(m21), _33(m22),
_41(m30), _42(m31), _43(m32) {}
explicit Float4x3(const f32 *arr)
{
_11 = arr[0]; _12 = arr[1]; _13 = arr[2];
_21 = arr[3]; _22 = arr[4]; _23 = arr[5];
_31 = arr[6]; _32 = arr[7]; _33 = arr[8];
_41 = arr[9]; _42 = arr[10]; _43 = arr[11];
}
// Comparison operators
bool operator == (const Float4x3& m) const;
bool operator != (const Float4x3& m) const;
// Assignment operators.
Float4x3(const Float3x3& m, const Float3& row4 = Float3(0.0f, 0.0f, 0.0f));
Float4x3(const Float3& row1, const Float3& row2, const Float3& row3, const Float3& row4);
// Element access.
f32* operator[](usize i) { return &(m[i][0]); }
Float3 r1() const { return Float3(_11, _12, _13); }
Float3 r2() const { return Float3(_21, _22, _23); }
Float3 r3() const { return Float3(_31, _32, _33); }
Float3 r4() const { return Float3(_41, _42, _43); }
Float4 c1() const { return Float4(_11, _21, _31, _41); }
Float4 c2() const { return Float4(_12, _22, _32, _42); }
Float4 c3() const { return Float4(_13, _23, _33, _43); }
// Unary operators.
Float4x3 operator+() const { return *this; }
Float4x3 operator-() const;
// per-component operations.
Float4x3& operator+=(const Float4x3&);
Float4x3& operator-=(const Float4x3&);
Float4x3& operator*=(const Float4x3&);
Float4x3& operator/=(const Float4x3&);
Float4x3& operator+=(f32 s);
Float4x3& operator-=(f32 s);
Float4x3& operator*=(f32 s);
Float4x3& operator/=(f32 s);
// Constants
static constexpr Float4x3 identity()
{
return Float4x3(
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 0.0f);
}
};
// per-component operations.
Float4x3 operator+(const Float4x3& m1, const Float4x3& m2);
Float4x3 operator+(const Float4x3& m1, f32 s);
Float4x3 operator+(f32 s, const Float4x3& m1);
Float4x3 operator-(const Float4x3& m1, const Float4x3& m2);
Float4x3 operator-(const Float4x3& m1, f32 s);
Float4x3 operator-(f32 s, const Float4x3& m1);
Float4x3 operator*(const Float4x3& m1, const Float4x3& m2);
Float4x3 operator*(const Float4x3& m1, f32 s);
Float4x3 operator*(f32 s, const Float4x3& m1);
Float4x3 operator/(const Float4x3& m1, const Float4x3& m2);
Float4x3 operator/(const Float4x3& m1, f32 s);
Float4x3 operator/(f32 s, const Float4x3& m1);
// matrix math.
Float3 mul(const Float4& vec, const Float4x3& mat);
Float4 mul(const Float4x3& mat, const Float3& vec);
static_assert(sizeof(Float4x3) == 16 * sizeof(f32), "Incorrect Float4x3 size.");
struct alignas(16) Float3x4
{
union
{
struct
{
f32 _11, _12, _13, _14;
f32 _21, _22, _23, _24;
f32 _31, _32, _33, _34;
};
f32 m[3][4];
};
Float3x4() = default;
Float3x4(const Float3x4&) = default;
Float3x4& operator=(const Float3x4&) = default;
Float3x4(Float3x4&&) = default;
Float3x4& operator=(Float3x4&&) = default;
constexpr Float3x4(f32 m00, f32 m01, f32 m02, f32 m03,
f32 m10, f32 m11, f32 m12, f32 m13,
f32 m20, f32 m21, f32 m22, f32 m23)
: _11(m00), _12(m01), _13(m02), _14(m03),
_21(m10), _22(m11), _23(m12), _24(m13),
_31(m20), _32(m21), _33(m22), _34(m23) {}
explicit Float3x4(const f32 *arr)
{
_11 = arr[0]; _12 = arr[1]; _13 = arr[2]; _14 = arr[3];
_21 = arr[4]; _22 = arr[5]; _23 = arr[6]; _24 = arr[7];
_31 = arr[8]; _32 = arr[9]; _33 = arr[10]; _34 = arr[11];
}
// Comparison operators
bool operator == (const Float3x4& m) const;
bool operator != (const Float3x4& m) const;
// Assignment operators.
Float3x4(const Float3x3& m, const Float3& col4 = Float3(0.0f, 0.0f, 0.0f));
Float3x4(const Float4& row1, const Float4& row2, const Float4& row3);
// Element access.
f32* operator[](usize i) { return &(m[i][0]); }
Float4 r1() { return Float4(_11, _12, _13, _14); }
Float4 r2() { return Float4(_21, _22, _23, _24); }
Float4 r3() { return Float4(_31, _32, _33, _34); }
Float3 c1() { return Float3(_11, _21, _31); }
Float3 c2() { return Float3(_12, _22, _32); }
Float3 c3() { return Float3(_13, _23, _33); }
Float3 c4() { return Float3(_14, _24, _34); }
// Unary operators.
Float3x4 operator+() const { return *this; }
Float3x4 operator-() const;
// per-component operations.
Float3x4& operator+=(const Float3x4&);
Float3x4& operator-=(const Float3x4&);
Float3x4& operator*=(const Float3x4&);
Float3x4& operator/=(const Float3x4&);
Float3x4& operator+=(f32 s);
Float3x4& operator-=(f32 s);
Float3x4& operator*=(f32 s);
Float3x4& operator/=(f32 s);
static constexpr Float3x4 identity()
{
return Float3x4(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f);
}
};
// per-component operations.
Float3x4 operator+(const Float3x4& m1, const Float3x4& m2);
Float3x4 operator+(const Float3x4& m1, f32 s);
Float3x4 operator+(f32 s, const Float3x4& m1);
Float3x4 operator-(const Float3x4& m1, const Float3x4& m2);
Float3x4 operator-(const Float3x4& m1, f32 s);
Float3x4 operator-(f32 s, const Float3x4& m1);
Float3x4 operator*(const Float3x4& m1, const Float3x4& m2);
Float3x4 operator*(const Float3x4& m1, f32 s);
Float3x4 operator*(f32 s, const Float3x4& m1);
Float3x4 operator/(const Float3x4& m1, const Float3x4& m2);
Float3x4 operator/(const Float3x4& m1, f32 s);
Float3x4 operator/(f32 s, const Float3x4& m1);
// matrix math.
Float4 mul(const Float3& vec, const Float3x4& mat);
Float3 mul(const Float3x4& mat, const Float4& vec);
static_assert(sizeof(Float3x4) == 12 * sizeof(f32), "Incorrect Float3x4 size.");
struct alignas(16) Float4x4
{
union
{
struct
{
f32 _11, _12, _13, _14;
f32 _21, _22, _23, _24;
f32 _31, _32, _33, _34;
f32 _41, _42, _43, _44;
};
f32 m[4][4];
};
Float4x4() = default;
Float4x4(const Float4x4&) = default;
Float4x4& operator=(const Float4x4&) = default;
Float4x4(Float4x4&&) = default;
Float4x4& operator=(Float4x4&&) = default;
constexpr Float4x4(f32 m00, f32 m01, f32 m02, f32 m03,
f32 m10, f32 m11, f32 m12, f32 m13,
f32 m20, f32 m21, f32 m22, f32 m23,
f32 m30, f32 m31, f32 m32, f32 m33)
: _11(m00), _12(m01), _13(m02), _14(m03),
_21(m10), _22(m11), _23(m12), _24(m13),
_31(m20), _32(m21), _33(m22), _34(m23),
_41(m30), _42(m31), _43(m32), _44(m33) {}
explicit Float4x4(const f32 *arr)
{
_11 = arr[0]; _12 = arr[1]; _13 = arr[2]; _14 = arr[3];
_21 = arr[4]; _22 = arr[5]; _23 = arr[6]; _24 = arr[7];
_31 = arr[8]; _32 = arr[9]; _33 = arr[10]; _34 = arr[11];
_41 = arr[12]; _42 = arr[13]; _43 = arr[14]; _44 = arr[15];
}
#ifdef LUNA_SIMD_ENABLED
Float4x4(Simd::mat_float_p1_t m)
{
Simd::store_float4x4a(&_11, m);
}
operator Simd::mat_float_t() const { return Simd::load_float4x4a(&_11); }
#endif
// Comparison operators
bool operator == (const Float4x4& m) const;
bool operator != (const Float4x4& m) const;
// Assignment operators
Float4x4(const Float4x3& m, const Float4& col4 = Float4(0.0f, 0.0f, 0.0f, 1.0f));
Float4x4(const Float3x4& m, const Float4& row4 = Float4(0.0f, 0.0f, 0.0f, 1.0f));
Float4x4(const Float4& row1, const Float4& row2, const Float4& row3, const Float4& row4);
// Element Access.
f32* operator[](usize i) { return &(m[i][0]); }
Float4 r1() const { return Float4(_11, _12, _13, _14); }
Float4 r2() const { return Float4(_21, _22, _23, _24); }
Float4 r3() const { return Float4(_31, _32, _33, _34); }
Float4 r4() const { return Float4(_41, _42, _43, _44); }
Float4 c1() const { return Float4(_11, _21, _31, _41); }
Float4 c2() const { return Float4(_12, _22, _32, _42); }
Float4 c3() const { return Float4(_13, _23, _33, _43); }
Float4 c4() const { return Float4(_14, _24, _34, _44); }
//! Returns the up direction if this matrix represents a rotation or an affine matrix.
//!
//! The returned vector is scaled by the Y factor of the scale component of the affine
//! matrix.
Float3 up() const { return Float3(_21, _22, _23); }
//! Returns the down direction if this matrix represents a rotation or an affine matrix.
//!
//! The returned vector is scaled by the Y factor of the scale component of the affine
//! matrix.
Float3 down() const { return Float3(-_21, -_22, -_23); }
//! Returns the right direction if this matrix represents a rotation or an affine matrix.
//!
//! The returned vector is scaled by the X factor of the scale component of the affine
//! matrix.
Float3 right() const { return Float3(_11, _12, _13); }
//! Returns the left direction if this matrix represents a rotation or an affine matrix.
//!
//! The returned vector is scaled by the X factor of the scale component of the affine
//! matrix.
Float3 left() const { return Float3(-_11, -_12, -_13); }
//! Returns the forward direction if this matrix represents a rotation or an affine matrix.
//!
//! The returned vector is scaled by the Z factor of the scale component of the affine
//! matrix.
Float3 forward() const { return Float3(_31, _32, _33); }
//! Returns the backward direction if this matrix represents a rotation or an affine matrix.
//!
//! The returned vector is scaled by the Z factor of the scale component of the affine
//! matrix.
Float3 backward() const { return Float3(-_31, -_32, -_33); }
//! Returns the translation component if this matrix represents a rotation or an affine matrix.
Float3 translation() const { return Float3(_41, _42, _43); }
//! Extracts the unscaled rotation matrix from this affine matrix.
Float4x4 rotation_matrix() const;
//! Computes the euler angles from this rotation matrix. This method cannot be used for affine matrix directly,
//! to use this method for affine matrix, call `rotation_matrix` to extract the rotation matrix from affine matrix
//! first.
//!
//! The returned euler angles represents the radians of clockwise rotation along Z(roll), X(pitch), Y(yaw) axis in
//! that order.
Float3 euler_angles() const;
//! Computes the quaternion from this rotation matrix. This method cannot be used for affine matrix directly,
//! to use this method for affine matrix, call `rotation_matrix` to extract the rotation matrix from affine matrix
//! first.
Quaternion quaternion() const;
//! Returns the scale component if this matrix represents a rotation or an affine matrix.
Float3 scale_factor() const;
// Unary operators
Float4x4 operator+() const { return *this; }
Float4x4 operator- () const;
// per-component operations.
Float4x4& operator+=(const Float4x4&);
Float4x4& operator-=(const Float4x4&);
Float4x4& operator*=(const Float4x4&);
Float4x4& operator/=(const Float4x4&);
Float4x4& operator+=(f32 s);
Float4x4& operator-=(f32 s);
Float4x4& operator*=(f32 s);
Float4x4& operator/=(f32 s);
// Constants
static constexpr Float4x4 identity()
{
return Float4x4(
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
static Float4x4 make_billboard(const Float3& object_pos, const Float3& camera_pos,
const Float3& camera_up, const Float3& camera_forward = { 0.0f, 0.0f, 1.0f});
static Float4x4 make_constrained_billboard(const Float3& object_pos, const Float3& camera_pos,
const Float3& rotate_axis, const Float3& camera_forward = { 0.0f, 0.0f, 1.0f}, const Float3& object_forward = { 0.0f, 0.0f, -1.0f});
static Float4x4 make_translation(const Float3& position);
static Float4x4 make_scale(const Float3& scales);
static Float4x4 make_rotation_x(f32 radians);
static Float4x4 make_rotation_y(f32 radians);
static Float4x4 make_rotation_z(f32 radians);
static Float4x4 make_rotation_quaternion(const Quaternion& quaternion);
static Float4x4 make_from_axis_angle(const Float3& axis, f32 angle);
static Float4x4 make_perspective_field_of_view(f32 fov, f32 aspect_ratio,
f32 near_plane_distance, f32 far_plance_distance);
static Float4x4 make_perspective(f32 width, f32 height, f32 near_plane_distance,
f32 far_plane_distance);
static Float4x4 make_perspective_off_center(f32 left, f32 right, f32 bottom,
f32 top, f32 near_plane_distance, f32 far_plance_distance);
static Float4x4 make_orthographic(f32 width, f32 height, f32 z_near_place_distance,
f32 z_far_plane_distance);
static Float4x4 make_orthographic_off_center(f32 left, f32 right, f32 bottom,
f32 top, f32 near_plane_distance, f32 far_plance_distance);
static Float4x4 make_look_at(const Float3& camera_position, const Float3& target_position, const Float3& up_dir);
static Float4x4 make_world(const Float3& position, const Float3& forward, const Float3& up);
// Local to world matrix.
static Float4x4 make_affine_position_rotation_scale(const Float3& position, const Quaternion& rotation, const Float3& scale);
static Float4x4 make_transform3d(const Tranform3D& transform);
};
static_assert(sizeof(Float4x4) == 16 * sizeof(f32), "Incorrect Float4x4 size.");
// Binary operators
Float4x4 operator+(const Float4x4& m1, const Float4x4& m2);
Float4x4 operator+(const Float4x4& m1, f32 s);
Float4x4 operator+(f32 s, const Float4x4& m1);
Float4x4 operator-(const Float4x4& m1, const Float4x4& m2);
Float4x4 operator-(const Float4x4& m1, f32 s);
Float4x4 operator-(f32 s, const Float4x4& m1);
Float4x4 operator*(const Float4x4& m1, const Float4x4& m2);
Float4x4 operator*(const Float4x4& m1, f32 s);
Float4x4 operator*(f32 s, const Float4x4& m1);
Float4x4 operator/(const Float4x4& m1, const Float4x4& m2);
Float4x4 operator/(const Float4x4& m1, f32 s);
Float4x4 operator/(f32 s, const Float4x4& m1);
f32 determinant(const Float3x3& mat);
f32 determinant(const Float4x4& mat);
Float4 mul(const Float4& vec, const Float4x4& mat);
Float4 mul(const Float4x4& mat, const Float4& vec);
Float4x4 mul(const Float4x4& mat1, const Float4x4& mat2);
Float3x3 transpose(const Float3x3& m);
Float3x4 transpose(const Float4x3& m);
Float4x3 transpose(const Float3x4& m);
Float4x4 transpose(const Float4x4& m);
Float3x3 inverse(const Float3x3& m, f32* out_determinant = nullptr);
Float4x4 inverse(const Float4x4& m, f32* out_determinant = nullptr);
//------------------------------------------------------------------------------------
//
// Implementation part.
//
//------------------------------------------------------------------------------------
inline bool Float3x3::operator == (const Float3x3& m) const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y1 = load_float3a(&m._11);
vec_float_t y2 = load_float3a(&m._21);
vec_float_t y3 = load_float3a(&m._31);
return (Vector3Equal(x1, y1) && Vector3Equal(x2, y2) && Vector3Equal(x3, y3));
#else
return ((_11 == m._11) && (_12 == m._12) && (_13 == m._13) &&
(_21 == m._21) && (_22 == m._22) && (_23 == m._23) &&
(_31 == m._31) && (_32 == m._32) && (_33 == m._33));
#endif
}
inline bool Float3x3::operator != (const Float3x3& m) const
{
return !(*this == m);
}
inline bool Float4x3::operator == (const Float4x3& m) const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y1 = load_float3a(&m._11);
vec_float_t y2 = load_float3a(&m._21);
vec_float_t y3 = load_float3a(&m._31);
vec_float_t y4 = load_float3a(&m._41);
return (Vector3Equal(x1, y1) && Vector3Equal(x2, y2) && Vector3Equal(x3, y3)) && Vector3Equal(x4, y4);
#else
return ((_11 == m._11) && (_12 == m._12) && (_13 == m._13) &&
(_21 == m._21) && (_22 == m._22) && (_23 == m._23) &&
(_31 == m._31) && (_32 == m._32) && (_33 == m._33) &&
(_41 == m._41) && (_42 == m._42) && (_43 == m._43));
#endif
}
inline bool Float4x3::operator != (const Float4x3& m) const
{
return !(*this == m);
}
inline bool Float3x4::operator == (const Float3x4& m) const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y1 = load_float4a(&m._11);
vec_float_t y2 = load_float4a(&m._21);
vec_float_t y3 = load_float4a(&m._31);
return (Vector4Equal(x1, y1) && Vector4Equal(x2, y2) && Vector4Equal(x3, y3));
#else
return ((_11 == m._11) && (_12 == m._12) && (_13 == m._13) && (_14 == m._14) &&
(_21 == m._21) && (_22 == m._22) && (_23 == m._23) && (_24 == m._24) &&
(_31 == m._31) && (_32 == m._32) && (_33 == m._33) && (_34 == m._34));
#endif
}
inline bool Float3x4::operator != (const Float3x4& m) const
{
return !(*this == m);
}
inline bool Float4x4::operator == (const Float4x4& m) const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y1 = load_float4a(&m._11);
vec_float_t y2 = load_float4a(&m._21);
vec_float_t y3 = load_float4a(&m._31);
vec_float_t y4 = load_float4a(&m._41);
return (Vector4Equal(x1, y1) && Vector4Equal(x2, y2) && Vector4Equal(x3, y3) && Vector4Equal(x4, y4));
#else
return ((_11 == m._11) && (_12 == m._12) && (_13 == m._13) && (_14 == m._14) &&
(_21 == m._21) && (_22 == m._22) && (_23 == m._23) && (_24 == m._24) &&
(_31 == m._31) && (_32 == m._32) && (_33 == m._33) && (_34 == m._34) &&
(_41 == m._41) && (_42 == m._42) && (_43 == m._43) && (_44 == m._44));
#endif
}
inline bool Float4x4::operator != (const Float4x4& m) const
{
return !(*this == m);
}
inline Float3x3::Float3x3(const Float3& row1, const Float3& row2, const Float3& row3)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r1 = load_float3a(row1.m);
vec_float_t r2 = load_float3a(row2.m);
vec_float_t r3 = load_float3a(row3.m);
store_float3a(&_11, r1);
store_float3a(&_21, r2);
store_float3a(&_31, r3);
#else
_11 = row1.x;
_12 = row1.y;
_13 = row1.z;
_21 = row2.x;
_22 = row2.y;
_23 = row2.z;
_31 = row3.x;
_32 = row3.y;
_33 = row3.z;
#endif
}
inline Float4x3::Float4x3(const Float3& row1, const Float3& row2, const Float3& row3, const Float3& row4)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r1 = load_float3a(row1.m);
vec_float_t r2 = load_float3a(row2.m);
vec_float_t r3 = load_float3a(row3.m);
vec_float_t r4 = load_float3a(row4.m);
store_float3a(&_11, r1);
store_float3a(&_21, r2);
store_float3a(&_31, r3);
store_float3a(&_41, r4);
#else
_11 = row1.x;
_12 = row1.y;
_13 = row1.z;
_21 = row2.x;
_22 = row2.y;
_23 = row2.z;
_31 = row3.x;
_32 = row3.y;
_33 = row3.z;
_41 = row4.x;
_42 = row4.y;
_43 = row4.z;
#endif
}
inline Float3x4::Float3x4(const Float4& row1, const Float4& row2, const Float4& row3)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r1 = load_float4a(row1.m);
vec_float_t r2 = load_float4a(row2.m);
vec_float_t r3 = load_float4a(row3.m);
store_float4a(&_11, r1);
store_float4a(&_21, r2);
store_float4a(&_31, r3);
#else
_11 = row1.x;
_12 = row1.y;
_13 = row1.z;
_14 = row1.w;
_21 = row2.x;
_22 = row2.y;
_23 = row2.z;
_24 = row2.w;
_31 = row3.x;
_32 = row3.y;
_33 = row3.z;
_34 = row3.w;
#endif
}
inline Float4x4::Float4x4(const Float4& row1, const Float4& row2, const Float4& row3, const Float4& row4)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r1 = load_float4a(row1.m);
vec_float_t r2 = load_float4a(row2.m);
vec_float_t r3 = load_float4a(row3.m);
vec_float_t r4 = load_float4a(row4.m);
store_float4a(&_11, r1);
store_float4a(&_21, r2);
store_float4a(&_31, r3);
store_float4a(&_41, r4);
#else
_11 = row1.x;
_12 = row1.y;
_13 = row1.z;
_14 = row1.w;
_21 = row2.x;
_22 = row2.y;
_23 = row2.z;
_24 = row2.w;
_31 = row3.x;
_32 = row3.y;
_33 = row3.z;
_34 = row3.w;
_41 = row4.x;
_42 = row4.y;
_43 = row4.z;
_44 = row4.w;
#endif
}
inline Float3x3 Float3x3::operator-() const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t v1 = load_float3a(&_11);
vec_float_t v2 = load_float3a(&_21);
vec_float_t v3 = load_float3a(&_31);
v1 = VectorNegate(v1);
v2 = VectorNegate(v2);
v3 = VectorNegate(v3);
Float3x3 r;
store_float3a(&(r._11), v1);
store_float3a(&(r._21), v2);
store_float3a(&(r._31), v3);
return r;
#else
Float3x3 r;
r._11 = -_11;
r._12 = -_12;
r._13 = -_13;
r._21 = -_21;
r._22 = -_22;
r._23 = -_23;
r._31 = -_31;
r._32 = -_32;
r._33 = -_33;
return r;
#endif
}
inline Float4x3 Float4x3::operator-() const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t v1 = load_float3a(&_11);
vec_float_t v2 = load_float3a(&_21);
vec_float_t v3 = load_float3a(&_31);
vec_float_t v4 = load_float3a(&_41);
v1 = VectorNegate(v1);
v2 = VectorNegate(v2);
v3 = VectorNegate(v3);
v4 = VectorNegate(v4);
Float4x3 r;
store_float3a(&(r._11), v1);
store_float3a(&(r._21), v2);
store_float3a(&(r._31), v3);
store_float3a(&(r._41), v4);
return r;
#else
Float4x3 r;
r._11 = -_11;
r._12 = -_12;
r._13 = -_13;
r._21 = -_21;
r._22 = -_22;
r._23 = -_23;
r._31 = -_31;
r._32 = -_32;
r._33 = -_33;
r._41 = -_41;
r._42 = -_42;
r._43 = -_43;
return r;
#endif
}
inline Float3x4 Float3x4::operator-() const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t v1 = load_float4a(&_11);
vec_float_t v2 = load_float4a(&_21);
vec_float_t v3 = load_float4a(&_31);
v1 = VectorNegate(v1);
v2 = VectorNegate(v2);
v3 = VectorNegate(v3);
Float3x4 r;
store_float4a(&(r._11), v1);
store_float4a(&(r._21), v2);
store_float4a(&(r._31), v3);
return r;
#else
Float3x4 r;
r._11 = -_11;
r._12 = -_12;
r._13 = -_13;
r._14 = -_14;
r._21 = -_21;
r._22 = -_22;
r._23 = -_23;
r._24 = -_24;
r._31 = -_31;
r._32 = -_32;
r._33 = -_33;
r._34 = -_34;
return r;
#endif
}
namespace impl
{
inline void make_eular_positive(Float3& euler)
{
const float l = -0.0001f;
const float h = (pi * 2.0F) - 0.0001f;
if (euler.x < l)
euler.x += 2.0f * pi;
else if (euler.x > h)
euler.x -= 2.0f * pi;
if (euler.y < l)
euler.y += 2.0f * pi;
else if (euler.y > h)
euler.y -= 2.0f * pi;
if (euler.z < l)
euler.z += 2.0f * pi;
else if (euler.z > h)
euler.z -= 2.0f * pi;
}
}
inline Float4x4 Float4x4::rotation_matrix() const
{
Float3 scale = scale_factor();
return Float4x4(
r1() / scale.x,
r2() / scale.y,
r3() / scale.z,
Float4(0.0f, 0.0f, 0.0f, 1.0f)
);
}
inline Float3 Float4x4::euler_angles() const
{
// Roll, Pitch, Yaw (ZXY).
Float3 v;
if (_32 < 0.999f)
{
if (_32 > -0.999f)
{
v.x = -asinf(_32);
v.z = -atan2f(-_12, _22);
v.y = -atan2f(-_31, _33);
}
else
{
v.x = pi / 2.0f;
v.z = atan2f(_13, _11);
v.y = 0.0f;
}
}
else
{
v.x = -pi / 2.0f;
v.z = -atan2f(_13, _11);
v.y = 0.0f;
}
return v;
}
inline Quaternion Float4x4::quaternion() const
{
return Quaternion::from_euler_angles(euler_angles());
/*Quaternion r;
f32 t;
if (_33 < 0.0f)
{
if (_11 > _22)
{
t = 1.0f + _11 - _22 - _33;
r = Quaternion(t, _12 + _21, _31 + _13, _23 - _32);
}
else
{
t = 1.0f - _11 + _22 - _33;
r = Quaternion(_12 + _21, t, _23 + _32, _31 - _13);
}
}
else
{
if (_11 < -_22)
{
t = 1.0f - _11 - _22 + _33;
r = Quaternion(_31 + _13, _23 + _32, t, _12 - _21);
}
else
{
t = 1.0f + _11 + _22 + _33;
r = Quaternion(_23 - _32, _31 - _13, _12 - _21, t);
}
}
r *= 0.5f / sqrtf(t);
return r;*/
}
inline Float3 Float4x4::scale_factor() const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t v1 = vector_set(_11, _21, _31, 0.0f);
vec_float_t v2 = vector_set(_12, _22, _32, 0.0f);
vec_float_t v3 = vector_set(_13, _23, _33, 0.0f);
v1 = VectorMultiply(v1, v1);
v2 = VectorMultiply(v2, v2);
v3 = VectorMultiply(v3, v3);
v1 = VectorAdd(v1, VectorAdd(v2, v3));
v1 = VectorSqrt(v1);
Float3 ret;
store_float3a(ret.m, v1);
return ret;
#else
return Float3(
sqrtf(_11 * _11 + _12 * _12 + _13 * _13),
sqrtf(_21 * _21 + _22 * _22 + _23 * _23),
sqrtf(_31 * _31 + _32 * _32 + _33 * _33)
);
#endif
}
inline Float4x4 Float4x4::operator-() const
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t v1 = load_float4a(&_11);
vec_float_t v2 = load_float4a(&_21);
vec_float_t v3 = load_float4a(&_31);
vec_float_t v4 = load_float4a(&_41);
v1 = VectorNegate(v1);
v2 = VectorNegate(v2);
v3 = VectorNegate(v3);
v4 = VectorNegate(v4);
Float4x4 r;
store_float4a(&(r._11), v1);
store_float4a(&(r._21), v2);
store_float4a(&(r._31), v3);
store_float4a(&(r._41), v4);
return r;
#else
Float4x4 r;
r._11 = -_11;
r._12 = -_12;
r._13 = -_13;
r._14 = -_14;
r._21 = -_21;
r._22 = -_22;
r._23 = -_23;
r._24 = -_24;
r._31 = -_31;
r._32 = -_32;
r._33 = -_33;
r._34 = -_34;
r._41 = -_41;
r._42 = -_42;
r._43 = -_43;
r._44 = -_44;
return r;
#endif
}
inline Float3x3& Float3x3::operator+=(const Float3x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 += rhs._11;
_12 += rhs._12;
_13 += rhs._13;
_21 += rhs._21;
_22 += rhs._22;
_23 += rhs._23;
_31 += rhs._31;
_32 += rhs._32;
_33 += rhs._33;
return *this;
#endif
}
inline Float4x3& Float4x3::operator+=(const Float4x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
vec_float_t y4 = load_float3a(&(rhs._41));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
x4 = VectorAdd(x4, y4);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 += rhs._11;
_12 += rhs._12;
_13 += rhs._13;
_21 += rhs._21;
_22 += rhs._22;
_23 += rhs._23;
_31 += rhs._31;
_32 += rhs._32;
_33 += rhs._33;
_41 += rhs._41;
_42 += rhs._42;
_43 += rhs._43;
return *this;
#endif
}
inline Float3x4& Float3x4::operator+=(const Float3x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 += rhs._11;
_12 += rhs._12;
_13 += rhs._13;
_14 += rhs._14;
_21 += rhs._21;
_22 += rhs._22;
_23 += rhs._23;
_24 += rhs._24;
_31 += rhs._31;
_32 += rhs._32;
_33 += rhs._33;
_34 += rhs._34;
return *this;
#endif
}
inline Float4x4& Float4x4::operator+=(const Float4x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
vec_float_t y4 = load_float4a(&(rhs._41));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
x4 = VectorAdd(x4, y4);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 += rhs._11;
_12 += rhs._12;
_13 += rhs._13;
_14 += rhs._14;
_21 += rhs._21;
_22 += rhs._22;
_23 += rhs._23;
_24 += rhs._24;
_31 += rhs._31;
_32 += rhs._32;
_33 += rhs._33;
_34 += rhs._34;
_41 += rhs._41;
_42 += rhs._42;
_43 += rhs._43;
_44 += rhs._44;
return *this;
#endif
}
inline Float3x3& Float3x3::operator-=(const Float3x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 -= rhs._11;
_12 -= rhs._12;
_13 -= rhs._13;
_21 -= rhs._21;
_22 -= rhs._22;
_23 -= rhs._23;
_31 -= rhs._31;
_32 -= rhs._32;
_33 -= rhs._33;
return *this;
#endif
}
inline Float4x3& Float4x3::operator-=(const Float4x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
vec_float_t y4 = load_float3a(&(rhs._41));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
x4 = VectorSubtract(x4, y4);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 -= rhs._11;
_12 -= rhs._12;
_13 -= rhs._13;
_21 -= rhs._21;
_22 -= rhs._22;
_23 -= rhs._23;
_31 -= rhs._31;
_32 -= rhs._32;
_33 -= rhs._33;
_41 -= rhs._41;
_42 -= rhs._42;
_43 -= rhs._43;
return *this;
#endif
}
inline Float3x4& Float3x4::operator-=(const Float3x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 -= rhs._11;
_12 -= rhs._12;
_13 -= rhs._13;
_14 -= rhs._14;
_21 -= rhs._21;
_22 -= rhs._22;
_23 -= rhs._23;
_24 -= rhs._24;
_31 -= rhs._31;
_32 -= rhs._32;
_33 -= rhs._33;
_34 -= rhs._34;
return *this;
#endif
}
inline Float4x4& Float4x4::operator-=(const Float4x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
vec_float_t y4 = load_float4a(&(rhs._41));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
x4 = VectorSubtract(x4, y4);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 -= rhs._11;
_12 -= rhs._12;
_13 -= rhs._13;
_14 -= rhs._14;
_21 -= rhs._21;
_22 -= rhs._22;
_23 -= rhs._23;
_24 -= rhs._24;
_31 -= rhs._31;
_32 -= rhs._32;
_33 -= rhs._33;
_34 -= rhs._34;
_41 -= rhs._41;
_42 -= rhs._42;
_43 -= rhs._43;
_44 -= rhs._44;
return *this;
#endif
}
inline Float3x3& Float3x3::operator*=(const Float3x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 *= rhs._11;
_12 *= rhs._12;
_13 *= rhs._13;
_21 *= rhs._21;
_22 *= rhs._22;
_23 *= rhs._23;
_31 *= rhs._31;
_32 *= rhs._32;
_33 *= rhs._33;
return *this;
#endif
}
inline Float4x3& Float4x3::operator*=(const Float4x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
vec_float_t y4 = load_float3a(&(rhs._41));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
x4 = VectorMultiply(x4, y4);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 *= rhs._11;
_12 *= rhs._12;
_13 *= rhs._13;
_21 *= rhs._21;
_22 *= rhs._22;
_23 *= rhs._23;
_31 *= rhs._31;
_32 *= rhs._32;
_33 *= rhs._33;
_41 *= rhs._41;
_42 *= rhs._42;
_43 *= rhs._43;
return *this;
#endif
}
inline Float3x4& Float3x4::operator*=(const Float3x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 *= rhs._11;
_12 *= rhs._12;
_13 *= rhs._13;
_14 *= rhs._14;
_21 *= rhs._21;
_22 *= rhs._22;
_23 *= rhs._23;
_24 *= rhs._24;
_31 *= rhs._31;
_32 *= rhs._32;
_33 *= rhs._33;
_34 *= rhs._34;
return *this;
#endif
}
inline Float4x4& Float4x4::operator*=(const Float4x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
vec_float_t y4 = load_float4a(&(rhs._41));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
x4 = VectorMultiply(x4, y4);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 *= rhs._11;
_12 *= rhs._12;
_13 *= rhs._13;
_14 *= rhs._14;
_21 *= rhs._21;
_22 *= rhs._22;
_23 *= rhs._23;
_24 *= rhs._24;
_31 *= rhs._31;
_32 *= rhs._32;
_33 *= rhs._33;
_34 *= rhs._34;
_41 *= rhs._41;
_42 *= rhs._42;
_43 *= rhs._43;
_44 *= rhs._44;
return *this;
#endif
}
inline Float3x3& Float3x3::operator/=(const Float3x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 /= rhs._11;
_12 /= rhs._12;
_13 /= rhs._13;
_21 /= rhs._21;
_22 /= rhs._22;
_23 /= rhs._23;
_31 /= rhs._31;
_32 /= rhs._32;
_33 /= rhs._33;
return *this;
#endif
}
inline Float4x3& Float4x3::operator/=(const Float4x3& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y1 = load_float3a(&(rhs._11));
vec_float_t y2 = load_float3a(&(rhs._21));
vec_float_t y3 = load_float3a(&(rhs._31));
vec_float_t y4 = load_float3a(&(rhs._41));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
x4 = VectorDivide(x4, y4);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 /= rhs._11;
_12 /= rhs._12;
_13 /= rhs._13;
_21 /= rhs._21;
_22 /= rhs._22;
_23 /= rhs._23;
_31 /= rhs._31;
_32 /= rhs._32;
_33 /= rhs._33;
_41 /= rhs._41;
_42 /= rhs._42;
_43 /= rhs._43;
return *this;
#endif
}
inline Float3x4& Float3x4::operator/=(const Float3x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 /= rhs._11;
_12 /= rhs._12;
_13 /= rhs._13;
_14 /= rhs._14;
_21 /= rhs._21;
_22 /= rhs._22;
_23 /= rhs._23;
_24 /= rhs._24;
_31 /= rhs._31;
_32 /= rhs._32;
_33 /= rhs._33;
_34 /= rhs._34;
return *this;
#endif
}
inline Float4x4& Float4x4::operator/=(const Float4x4& rhs)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y1 = load_float4a(&(rhs._11));
vec_float_t y2 = load_float4a(&(rhs._21));
vec_float_t y3 = load_float4a(&(rhs._31));
vec_float_t y4 = load_float4a(&(rhs._41));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
x4 = VectorDivide(x4, y4);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 /= rhs._11;
_12 /= rhs._12;
_13 /= rhs._13;
_14 /= rhs._14;
_21 /= rhs._21;
_22 /= rhs._22;
_23 /= rhs._23;
_24 /= rhs._24;
_31 /= rhs._31;
_32 /= rhs._32;
_33 /= rhs._33;
_34 /= rhs._34;
_41 /= rhs._41;
_42 /= rhs._42;
_43 /= rhs._43;
_44 /= rhs._44;
return *this;
#endif
}
inline Float3x3& Float3x3::operator+=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 += s;
_12 += s;
_13 += s;
_21 += s;
_22 += s;
_23 += s;
_31 += s;
_32 += s;
_33 += s;
return *this;
#endif
}
inline Float4x3& Float4x3::operator+=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
x4 = VectorAdd(x4, y);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 += s;
_12 += s;
_13 += s;
_21 += s;
_22 += s;
_23 += s;
_31 += s;
_32 += s;
_33 += s;
_41 += s;
_42 += s;
_43 += s;
return *this;
#endif
}
inline Float3x4& Float3x4::operator+=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 += s;
_12 += s;
_13 += s;
_14 += s;
_21 += s;
_22 += s;
_23 += s;
_24 += s;
_31 += s;
_32 += s;
_33 += s;
_34 += s;
return *this;
#endif
}
inline Float4x4& Float4x4::operator+=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
x4 = VectorAdd(x4, y);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 += s;
_12 += s;
_13 += s;
_14 += s;
_21 += s;
_22 += s;
_23 += s;
_24 += s;
_31 += s;
_32 += s;
_33 += s;
_34 += s;
_41 += s;
_42 += s;
_43 += s;
_44 += s;
return *this;
#endif
}
inline Float3x3& Float3x3::operator-=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 -= s;
_12 -= s;
_13 -= s;
_21 -= s;
_22 -= s;
_23 -= s;
_31 -= s;
_32 -= s;
_33 -= s;
return *this;
#endif
}
inline Float4x3& Float4x3::operator-=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
x4 = VectorSubtract(x4, y);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 -= s;
_12 -= s;
_13 -= s;
_21 -= s;
_22 -= s;
_23 -= s;
_31 -= s;
_32 -= s;
_33 -= s;
_41 -= s;
_42 -= s;
_43 -= s;
return *this;
#endif
}
inline Float3x4& Float3x4::operator-=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 -= s;
_12 -= s;
_13 -= s;
_14 -= s;
_21 -= s;
_22 -= s;
_23 -= s;
_24 -= s;
_31 -= s;
_32 -= s;
_33 -= s;
_34 -= s;
return *this;
#endif
}
inline Float4x4& Float4x4::operator-=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
x4 = VectorSubtract(x4, y);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 -= s;
_12 -= s;
_13 -= s;
_14 -= s;
_21 -= s;
_22 -= s;
_23 -= s;
_24 -= s;
_31 -= s;
_32 -= s;
_33 -= s;
_34 -= s;
_41 -= s;
_42 -= s;
_43 -= s;
_44 -= s;
return *this;
#endif
}
inline Float3x3& Float3x3::operator*=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
_11 *= s;
_12 *= s;
_13 *= s;
_21 *= s;
_22 *= s;
_23 *= s;
_31 *= s;
_32 *= s;
_33 *= s;
return *this;
#endif
}
inline Float4x3& Float4x3::operator*=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 *= s;
_12 *= s;
_13 *= s;
_21 *= s;
_22 *= s;
_23 *= s;
_31 *= s;
_32 *= s;
_33 *= s;
_41 *= s;
_42 *= s;
_43 *= s;
return *this;
#endif
}
inline Float3x4& Float3x4::operator*=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 *= s;
_12 *= s;
_13 *= s;
_14 *= s;
_21 *= s;
_22 *= s;
_23 *= s;
_24 *= s;
_31 *= s;
_32 *= s;
_33 *= s;
_34 *= s;
return *this;
#endif
}
inline Float4x4& Float4x4::operator*=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 *= s;
_12 *= s;
_13 *= s;
_14 *= s;
_21 *= s;
_22 *= s;
_23 *= s;
_24 *= s;
_31 *= s;
_32 *= s;
_33 *= s;
_34 *= s;
_41 *= s;
_42 *= s;
_43 *= s;
_44 *= s;
return *this;
#endif
}
inline Float3x3& Float3x3::operator/=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
f32 rs = 1.0f / s;
x1 = VectorScale(x1, rs);
x2 = VectorScale(x2, rs);
x3 = VectorScale(x3, rs);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
return *this;
#else
s = 1.0f / s;
_11 *= s;
_12 *= s;
_13 *= s;
_21 *= s;
_22 *= s;
_23 *= s;
_31 *= s;
_32 *= s;
_33 *= s;
return *this;
#endif
}
inline Float4x3& Float4x3::operator/=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&_11);
vec_float_t x2 = load_float3a(&_21);
vec_float_t x3 = load_float3a(&_31);
vec_float_t x4 = load_float3a(&_41);
s = 1.0f / s;
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
store_float3a(&_11, x1);
store_float3a(&_21, x2);
store_float3a(&_31, x3);
store_float3a(&_41, x4);
return *this;
#else
_11 /= s;
_12 /= s;
_13 /= s;
_21 /= s;
_22 /= s;
_23 /= s;
_31 /= s;
_32 /= s;
_33 /= s;
_41 /= s;
_42 /= s;
_43 /= s;
return *this;
#endif
}
inline Float3x4& Float3x4::operator/=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
s = 1.0f / s;
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
return *this;
#else
_11 /= s;
_12 /= s;
_13 /= s;
_14 /= s;
_21 /= s;
_22 /= s;
_23 /= s;
_24 /= s;
_31 /= s;
_32 /= s;
_33 /= s;
_34 /= s;
return *this;
#endif
}
inline Float4x4& Float4x4::operator/=(f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&_11);
vec_float_t x2 = load_float4a(&_21);
vec_float_t x3 = load_float4a(&_31);
vec_float_t x4 = load_float4a(&_41);
s = 1.0f / s;
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
store_float4a(&_11, x1);
store_float4a(&_21, x2);
store_float4a(&_31, x3);
store_float4a(&_41, x4);
return *this;
#else
_11 /= s;
_12 /= s;
_13 /= s;
_14 /= s;
_21 /= s;
_22 /= s;
_23 /= s;
_24 /= s;
_31 /= s;
_32 /= s;
_33 /= s;
_34 /= s;
_41 /= s;
_42 /= s;
_43 /= s;
_44 /= s;
return *this;
#endif
}
inline Float3x3 operator+(const Float3x3& m1, const Float3x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
Float3x3 result;
store_float3a(&(result._11), x1);
store_float3a(&(result._21), x2);
store_float3a(&(result._31), x3);
return result;
#else
Float3x3 result;
result._11 = m1._11 + m2._11;
result._12 = m1._12 + m2._12;
result._13 = m1._13 + m2._13;
result._21 = m1._21 + m2._21;
result._22 = m1._22 + m2._22;
result._23 = m1._23 + m2._23;
result._31 = m1._31 + m2._31;
result._32 = m1._32 + m2._32;
result._33 = m1._33 + m2._33;
return result;
#endif
}
inline Float4x3 operator+(const Float4x3& m1, const Float4x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
vec_float_t y4 = load_float3a(&(m2._41));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
x4 = VectorAdd(x4, y4);
Float4x3 result;
store_float3a(&(result._11), x1);
store_float3a(&(result._21), x2);
store_float3a(&(result._31), x3);
store_float3a(&(result._41), x4);
return result;
#else
Float4x3 result;
result._11 = m1._11 + m2._11;
result._12 = m1._12 + m2._12;
result._13 = m1._13 + m2._13;
result._21 = m1._21 + m2._21;
result._22 = m1._22 + m2._22;
result._23 = m1._23 + m2._23;
result._31 = m1._31 + m2._31;
result._32 = m1._32 + m2._32;
result._33 = m1._33 + m2._33;
result._41 = m1._41 + m2._41;
result._42 = m1._42 + m2._42;
result._43 = m1._43 + m2._43;
return result;
#endif
}
inline Float3x4 operator+(const Float3x4& m1, const Float3x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
Float3x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
return result;
#else
Float3x4 result;
result._11 = m1._11 + m2._11;
result._12 = m1._12 + m2._12;
result._13 = m1._13 + m2._13;
result._14 = m1._14 + m2._14;
result._21 = m1._21 + m2._21;
result._22 = m1._22 + m2._22;
result._23 = m1._23 + m2._23;
result._24 = m1._24 + m2._24;
result._31 = m1._31 + m2._31;
result._32 = m1._32 + m2._32;
result._33 = m1._33 + m2._33;
result._34 = m1._34 + m2._34;
return result;
#endif
}
inline Float4x4 operator+(const Float4x4& m1, const Float4x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
vec_float_t y4 = load_float4a(&(m2._41));
x1 = VectorAdd(x1, y1);
x2 = VectorAdd(x2, y2);
x3 = VectorAdd(x3, y3);
x4 = VectorAdd(x4, y4);
Float4x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
store_float4a(&(result._41), x4);
return result;
#else
Float4x4 result;
result._11 = m1._11 + m2._11;
result._12 = m1._12 + m2._12;
result._13 = m1._13 + m2._13;
result._14 = m1._14 + m2._14;
result._21 = m1._21 + m2._21;
result._22 = m1._22 + m2._22;
result._23 = m1._23 + m2._23;
result._24 = m1._24 + m2._24;
result._31 = m1._31 + m2._31;
result._32 = m1._32 + m2._32;
result._33 = m1._33 + m2._33;
result._34 = m1._34 + m2._34;
result._41 = m1._41 + m2._41;
result._42 = m1._42 + m2._42;
result._43 = m1._43 + m2._43;
result._44 = m1._44 + m2._44;
return result;
#endif
}
inline Float3x3 operator+(const Float3x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = m1._11 + s;
result._12 = m1._12 + s;
result._13 = m1._13 + s;
result._21 = m1._21 + s;
result._22 = m1._22 + s;
result._23 = m1._23 + s;
result._31 = m1._31 + s;
result._32 = m1._32 + s;
result._33 = m1._33 + s;
return result;
#endif
}
inline Float4x3 operator+(const Float4x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
x4 = VectorAdd(x4, y);
Float4x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
store_float3a(&(r._41), x4);
return r;
#else
Float4x3 result;
result._11 = m1._11 + s;
result._12 = m1._12 + s;
result._13 = m1._13 + s;
result._21 = m1._21 + s;
result._22 = m1._22 + s;
result._23 = m1._23 + s;
result._31 = m1._31 + s;
result._32 = m1._32 + s;
result._33 = m1._33 + s;
result._41 = m1._41 + s;
result._42 = m1._42 + s;
result._43 = m1._43 + s;
return result;
#endif
}
inline Float3x4 operator+(const Float3x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
Float3x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
return r;
#else
Float3x4 result;
result._11 = m1._11 + s;
result._12 = m1._12 + s;
result._13 = m1._13 + s;
result._14 = m1._14 + s;
result._21 = m1._21 + s;
result._22 = m1._22 + s;
result._23 = m1._23 + s;
result._24 = m1._24 + s;
result._31 = m1._31 + s;
result._32 = m1._32 + s;
result._33 = m1._33 + s;
result._34 = m1._34 + s;
return result;
#endif
}
inline Float4x4 operator+(const Float4x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorAdd(x1, y);
x2 = VectorAdd(x2, y);
x3 = VectorAdd(x3, y);
x4 = VectorAdd(x4, y);
Float4x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
store_float4a(&(r._41), x4);
return r;
#else
Float4x4 result;
result._11 = m1._11 + s;
result._12 = m1._12 + s;
result._13 = m1._13 + s;
result._14 = m1._14 + s;
result._21 = m1._21 + s;
result._22 = m1._22 + s;
result._23 = m1._23 + s;
result._24 = m1._24 + s;
result._31 = m1._31 + s;
result._32 = m1._32 + s;
result._33 = m1._33 + s;
result._34 = m1._34 + s;
result._41 = m1._41 + s;
result._42 = m1._42 + s;
result._43 = m1._43 + s;
result._44 = m1._44 + s;
return result;
#endif
}
inline Float3x3 operator+(f32 s, const Float3x3& m1)
{
return m1 + s;
}
inline Float4x3 operator+(f32 s, const Float4x3& m1)
{
return m1 + s;
}
inline Float3x4 operator+(f32 s, const Float3x4& m1)
{
return m1 + s;
}
inline Float4x4 operator+(f32 s, const Float4x4& m1)
{
return m1 + s;
}
inline Float3x3 operator-(const Float3x3& m1, const Float3x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
Float3x3 result;
store_float3a(&(result._11), x1);
store_float3a(&(result._21), x2);
store_float3a(&(result._31), x3);
return result;
#else
Float3x3 result;
result._11 = m1._11 - m2._11;
result._12 = m1._12 - m2._12;
result._13 = m1._13 - m2._13;
result._21 = m1._21 - m2._21;
result._22 = m1._22 - m2._22;
result._23 = m1._23 - m2._23;
result._31 = m1._31 - m2._31;
result._32 = m1._32 - m2._32;
result._33 = m1._33 - m2._33;
return result;
#endif
}
inline Float4x3 operator-(const Float4x3& m1, const Float4x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
vec_float_t y4 = load_float3a(&(m2._41));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
x4 = VectorSubtract(x4, y4);
Float4x3 result;
store_float3a(&(result._11), x1);
store_float3a(&(result._21), x2);
store_float3a(&(result._31), x3);
store_float3a(&(result._41), x4);
return result;
#else
Float4x3 result;
result._11 = m1._11 - m2._11;
result._12 = m1._12 - m2._12;
result._13 = m1._13 - m2._13;
result._21 = m1._21 - m2._21;
result._22 = m1._22 - m2._22;
result._23 = m1._23 - m2._23;
result._31 = m1._31 - m2._31;
result._32 = m1._32 - m2._32;
result._33 = m1._33 - m2._33;
result._41 = m1._41 - m2._41;
result._42 = m1._42 - m2._42;
result._43 = m1._43 - m2._43;
return result;
#endif
}
inline Float3x4 operator-(const Float3x4& m1, const Float3x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
Float3x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
return result;
#else
Float3x4 result;
result._11 = m1._11 - m2._11;
result._12 = m1._12 - m2._12;
result._13 = m1._13 - m2._13;
result._14 = m1._14 - m2._14;
result._21 = m1._21 - m2._21;
result._22 = m1._22 - m2._22;
result._23 = m1._23 - m2._23;
result._24 = m1._24 - m2._24;
result._31 = m1._31 - m2._31;
result._32 = m1._32 - m2._32;
result._33 = m1._33 - m2._33;
result._34 = m1._34 - m2._34;
return result;
#endif
}
inline Float4x4 operator-(const Float4x4& m1, const Float4x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
vec_float_t y4 = load_float4a(&(m2._41));
x1 = VectorSubtract(x1, y1);
x2 = VectorSubtract(x2, y2);
x3 = VectorSubtract(x3, y3);
x4 = VectorSubtract(x4, y4);
Float4x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
store_float4a(&(result._41), x4);
return result;
#else
Float4x4 result;
result._11 = m1._11 - m2._11;
result._12 = m1._12 - m2._12;
result._13 = m1._13 - m2._13;
result._14 = m1._14 - m2._14;
result._21 = m1._21 - m2._21;
result._22 = m1._22 - m2._22;
result._23 = m1._23 - m2._23;
result._24 = m1._24 - m2._24;
result._31 = m1._31 - m2._31;
result._32 = m1._32 - m2._32;
result._33 = m1._33 - m2._33;
result._34 = m1._34 - m2._34;
result._41 = m1._41 - m2._41;
result._42 = m1._42 - m2._42;
result._43 = m1._43 - m2._43;
result._44 = m1._44 - m2._44;
return result;
#endif
}
inline Float3x3 operator-(const Float3x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = m1._11 - s;
result._12 = m1._12 - s;
result._13 = m1._13 - s;
result._21 = m1._21 - s;
result._22 = m1._22 - s;
result._23 = m1._23 - s;
result._31 = m1._31 - s;
result._32 = m1._32 - s;
result._33 = m1._33 - s;
return result;
#endif
}
inline Float4x3 operator-(const Float4x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
x4 = VectorSubtract(x4, y);
Float4x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
store_float3a(&(r._41), x4);
return r;
#else
Float4x3 result;
result._11 = m1._11 - s;
result._12 = m1._12 - s;
result._13 = m1._13 - s;
result._21 = m1._21 - s;
result._22 = m1._22 - s;
result._23 = m1._23 - s;
result._31 = m1._31 - s;
result._32 = m1._32 - s;
result._33 = m1._33 - s;
result._41 = m1._41 - s;
result._42 = m1._42 - s;
result._43 = m1._43 - s;
return result;
#endif
}
inline Float3x4 operator-(const Float3x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
Float3x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
return r;
#else
Float3x4 result;
result._11 = m1._11 - s;
result._12 = m1._12 - s;
result._13 = m1._13 - s;
result._14 = m1._14 - s;
result._21 = m1._21 - s;
result._22 = m1._22 - s;
result._23 = m1._23 - s;
result._24 = m1._24 - s;
result._31 = m1._31 - s;
result._32 = m1._32 - s;
result._33 = m1._33 - s;
result._34 = m1._34 - s;
return result;
#endif
}
inline Float4x4 operator-(const Float4x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(x1, y);
x2 = VectorSubtract(x2, y);
x3 = VectorSubtract(x3, y);
x4 = VectorSubtract(x4, y);
Float4x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
store_float4a(&(r._41), x4);
return r;
#else
Float4x4 result;
result._11 = m1._11 - s;
result._12 = m1._12 - s;
result._13 = m1._13 - s;
result._14 = m1._14 - s;
result._21 = m1._21 - s;
result._22 = m1._22 - s;
result._23 = m1._23 - s;
result._24 = m1._24 - s;
result._31 = m1._31 - s;
result._32 = m1._32 - s;
result._33 = m1._33 - s;
result._34 = m1._34 - s;
result._41 = m1._41 - s;
result._42 = m1._42 - s;
result._43 = m1._43 - s;
result._44 = m1._44 - s;
return result;
#endif
}
inline Float3x3 operator-(f32 s, const Float3x3& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(y, x1);
x2 = VectorSubtract(y, x2);
x3 = VectorSubtract(y, x3);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = s - m1._11;
result._12 = s - m1._12;
result._13 = s - m1._13;
result._21 = s - m1._21;
result._22 = s - m1._22;
result._23 = s - m1._23;
result._31 = s - m1._31;
result._32 = s - m1._32;
result._33 = s - m1._33;
return result;
#endif
}
inline Float4x3 operator-(f32 s, const Float4x3& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(y, x1);
x2 = VectorSubtract(y, x2);
x3 = VectorSubtract(y, x3);
x4 = VectorSubtract(y, x4);
Float4x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
store_float3a(&(r._41), x4);
return r;
#else
Float4x3 result;
result._11 = s - m1._11;
result._12 = s - m1._12;
result._13 = s - m1._13;
result._21 = s - m1._21;
result._22 = s - m1._22;
result._23 = s - m1._23;
result._31 = s - m1._31;
result._32 = s - m1._32;
result._33 = s - m1._33;
result._41 = s - m1._41;
result._42 = s - m1._42;
result._43 = s - m1._43;
return result;
#endif
}
inline Float3x4 operator-(f32 s, const Float3x4& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(y, x1);
x2 = VectorSubtract(y, x2);
x3 = VectorSubtract(y, x3);
Float3x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
return r;
#else
Float3x4 result;
result._11 = s - m1._11;
result._12 = s - m1._12;
result._13 = s - m1._13;
result._14 = s - m1._14;
result._21 = s - m1._21;
result._22 = s - m1._22;
result._23 = s - m1._23;
result._24 = s - m1._24;
result._31 = s - m1._31;
result._32 = s - m1._32;
result._33 = s - m1._33;
result._34 = s - m1._34;
return result;
#endif
}
inline Float4x4 operator-(f32 s, const Float4x4& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorSubtract(y, x1);
x2 = VectorSubtract(y, x2);
x3 = VectorSubtract(y, x3);
x4 = VectorSubtract(y, x4);
Float4x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
store_float4a(&(r._41), x4);
return r;
#else
Float4x4 result;
result._11 = s - m1._11;
result._12 = s - m1._12;
result._13 = s - m1._13;
result._14 = s - m1._14;
result._21 = s - m1._21;
result._22 = s - m1._22;
result._23 = s - m1._23;
result._24 = s - m1._24;
result._31 = s - m1._31;
result._32 = s - m1._32;
result._33 = s - m1._33;
result._34 = s - m1._34;
result._41 = s - m1._41;
result._42 = s - m1._42;
result._43 = s - m1._43;
result._44 = s - m1._44;
return result;
#endif
}
inline Float3x3 operator*(const Float3x3& m1, const Float3x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = m1._11 * m2._11;
result._12 = m1._12 * m2._12;
result._13 = m1._13 * m2._13;
result._21 = m1._21 * m2._21;
result._22 = m1._22 * m2._22;
result._23 = m1._23 * m2._23;
result._31 = m1._31 * m2._31;
result._32 = m1._32 * m2._32;
result._33 = m1._33 * m2._33;
return result;
#endif
}
inline Float4x3 operator*(const Float4x3& m1, const Float4x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
vec_float_t y4 = load_float3a(&(m2._41));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
x4 = VectorMultiply(x4, y4);
Float4x3 result;
store_float3a(&(result._11), x1);
store_float3a(&(result._21), x2);
store_float3a(&(result._31), x3);
store_float3a(&(result._41), x4);
return result;
#else
Float4x3 result;
result._11 = m1._11 * m2._11;
result._12 = m1._12 * m2._12;
result._13 = m1._13 * m2._13;
result._21 = m1._21 * m2._21;
result._22 = m1._22 * m2._22;
result._23 = m1._23 * m2._23;
result._31 = m1._31 * m2._31;
result._32 = m1._32 * m2._32;
result._33 = m1._33 * m2._33;
result._41 = m1._41 * m2._41;
result._42 = m1._42 * m2._42;
result._43 = m1._43 * m2._43;
return result;
#endif
}
inline Float3x4 operator*(const Float3x4& m1, const Float3x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
Float3x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
return result;
#else
Float3x4 result;
result._11 = m1._11 * m2._11;
result._12 = m1._12 * m2._12;
result._13 = m1._13 * m2._13;
result._14 = m1._14 * m2._14;
result._21 = m1._21 * m2._21;
result._22 = m1._22 * m2._22;
result._23 = m1._23 * m2._23;
result._24 = m1._24 * m2._24;
result._31 = m1._31 * m2._31;
result._32 = m1._32 * m2._32;
result._33 = m1._33 * m2._33;
result._34 = m1._34 * m2._34;
return result;
#endif
}
inline Float4x4 operator*(const Float4x4& m1, const Float4x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
vec_float_t y4 = load_float4a(&(m2._41));
x1 = VectorMultiply(x1, y1);
x2 = VectorMultiply(x2, y2);
x3 = VectorMultiply(x3, y3);
x4 = VectorMultiply(x4, y4);
Float4x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
store_float4a(&(result._41), x4);
return result;
#else
Float4x4 result;
result._11 = m1._11 * m2._11;
result._12 = m1._12 * m2._12;
result._13 = m1._13 * m2._13;
result._14 = m1._14 * m2._14;
result._21 = m1._21 * m2._21;
result._22 = m1._22 * m2._22;
result._23 = m1._23 * m2._23;
result._24 = m1._24 * m2._24;
result._31 = m1._31 * m2._31;
result._32 = m1._32 * m2._32;
result._33 = m1._33 * m2._33;
result._34 = m1._34 * m2._34;
result._41 = m1._41 * m2._41;
result._42 = m1._42 * m2._42;
result._43 = m1._43 * m2._43;
result._44 = m1._44 * m2._44;
return result;
#endif
}
inline Float3x3 operator*(const Float3x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = m1._11 * s;
result._12 = m1._12 * s;
result._13 = m1._13 * s;
result._21 = m1._21 * s;
result._22 = m1._22 * s;
result._23 = m1._23 * s;
result._31 = m1._31 * s;
result._32 = m1._32 * s;
result._33 = m1._33 * s;
return result;
#endif
}
inline Float4x3 operator*(const Float4x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
Float4x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
store_float3a(&(r._41), x4);
return r;
#else
Float4x3 result;
result._11 = m1._11 * s;
result._12 = m1._12 * s;
result._13 = m1._13 * s;
result._21 = m1._21 * s;
result._22 = m1._22 * s;
result._23 = m1._23 * s;
result._31 = m1._31 * s;
result._32 = m1._32 * s;
result._33 = m1._33 * s;
result._41 = m1._41 * s;
result._42 = m1._42 * s;
result._43 = m1._43 * s;
return result;
#endif
}
inline Float3x4 operator*(const Float3x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
Float3x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
return r;
#else
Float3x4 result;
result._11 = m1._11 * s;
result._12 = m1._12 * s;
result._13 = m1._13 * s;
result._14 = m1._14 * s;
result._21 = m1._21 * s;
result._22 = m1._22 * s;
result._23 = m1._23 * s;
result._24 = m1._24 * s;
result._31 = m1._31 * s;
result._32 = m1._32 * s;
result._33 = m1._33 * s;
result._34 = m1._34 * s;
return result;
#endif
}
inline Float4x4 operator*(const Float4x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
Float4x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
store_float4a(&(r._41), x4);
return r;
#else
Float4x4 result;
result._11 = m1._11 * s;
result._12 = m1._12 * s;
result._13 = m1._13 * s;
result._14 = m1._14 * s;
result._21 = m1._21 * s;
result._22 = m1._22 * s;
result._23 = m1._23 * s;
result._24 = m1._24 * s;
result._31 = m1._31 * s;
result._32 = m1._32 * s;
result._33 = m1._33 * s;
result._34 = m1._34 * s;
result._41 = m1._41 * s;
result._42 = m1._42 * s;
result._43 = m1._43 * s;
result._44 = m1._44 * s;
return result;
#endif
}
inline Float3x3 operator*(f32 s, const Float3x3& m1)
{
return m1 * s;
}
inline Float4x3 operator*(f32 s, const Float4x3& m1)
{
return m1 * s;
}
inline Float3x4 operator*(f32 s, const Float3x4& m1)
{
return m1 * s;
}
inline Float4x4 operator*(f32 s, const Float4x4& m1)
{
return m1 * s;
}
inline Float3x3 operator/(const Float3x3& m1, const Float3x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = m1._11 / m2._11;
result._12 = m1._12 / m2._12;
result._13 = m1._13 / m2._13;
result._21 = m1._21 / m2._21;
result._22 = m1._22 / m2._22;
result._23 = m1._23 / m2._23;
result._31 = m1._31 / m2._31;
result._32 = m1._32 / m2._32;
result._33 = m1._33 / m2._33;
return result;
#endif
}
inline Float4x3 operator/(const Float4x3& m1, const Float4x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y1 = load_float3a(&(m2._11));
vec_float_t y2 = load_float3a(&(m2._21));
vec_float_t y3 = load_float3a(&(m2._31));
vec_float_t y4 = load_float3a(&(m2._41));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
x4 = VectorDivide(x4, y4);
Float4x3 result;
store_float3a(&(result._11), x1);
store_float3a(&(result._21), x2);
store_float3a(&(result._31), x3);
store_float3a(&(result._41), x4);
return result;
#else
Float4x3 result;
result._11 = m1._11 / m2._11;
result._12 = m1._12 / m2._12;
result._13 = m1._13 / m2._13;
result._21 = m1._21 / m2._21;
result._22 = m1._22 / m2._22;
result._23 = m1._23 / m2._23;
result._31 = m1._31 / m2._31;
result._32 = m1._32 / m2._32;
result._33 = m1._33 / m2._33;
result._41 = m1._41 / m2._41;
result._42 = m1._42 / m2._42;
result._43 = m1._43 / m2._43;
return result;
#endif
}
inline Float3x4 operator/(const Float3x4& m1, const Float3x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
Float3x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
return result;
#else
Float3x4 result;
result._11 = m1._11 / m2._11;
result._12 = m1._12 / m2._12;
result._13 = m1._13 / m2._13;
result._14 = m1._14 / m2._14;
result._21 = m1._21 / m2._21;
result._22 = m1._22 / m2._22;
result._23 = m1._23 / m2._23;
result._24 = m1._24 / m2._24;
result._31 = m1._31 / m2._31;
result._32 = m1._32 / m2._32;
result._33 = m1._33 / m2._33;
result._34 = m1._34 / m2._34;
return result;
#endif
}
inline Float4x4 operator/(const Float4x4& m1, const Float4x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y1 = load_float4a(&(m2._11));
vec_float_t y2 = load_float4a(&(m2._21));
vec_float_t y3 = load_float4a(&(m2._31));
vec_float_t y4 = load_float4a(&(m2._41));
x1 = VectorDivide(x1, y1);
x2 = VectorDivide(x2, y2);
x3 = VectorDivide(x3, y3);
x4 = VectorDivide(x4, y4);
Float4x4 result;
store_float4a(&(result._11), x1);
store_float4a(&(result._21), x2);
store_float4a(&(result._31), x3);
store_float4a(&(result._41), x4);
return result;
#else
Float4x4 result;
result._11 = m1._11 / m2._11;
result._12 = m1._12 / m2._12;
result._13 = m1._13 / m2._13;
result._14 = m1._14 / m2._14;
result._21 = m1._21 / m2._21;
result._22 = m1._22 / m2._22;
result._23 = m1._23 / m2._23;
result._24 = m1._24 / m2._24;
result._31 = m1._31 / m2._31;
result._32 = m1._32 / m2._32;
result._33 = m1._33 / m2._33;
result._34 = m1._34 / m2._34;
result._41 = m1._41 / m2._41;
result._42 = m1._42 / m2._42;
result._43 = m1._43 / m2._43;
result._44 = m1._44 / m2._44;
return result;
#endif
}
inline Float3x3 operator/(const Float3x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
f32 rs = 1.0f / s;
x1 = VectorScale(x1, rs);
x2 = VectorScale(x2, rs);
x3 = VectorScale(x3, rs);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = m1._11 / s;
result._12 = m1._12 / s;
result._13 = m1._13 / s;
result._21 = m1._21 / s;
result._22 = m1._22 / s;
result._23 = m1._23 / s;
result._31 = m1._31 / s;
result._32 = m1._32 / s;
result._33 = m1._33 / s;
return result;
#endif
}
inline Float4x3 operator/(const Float4x3& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
s = 1.0f / s;
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
Float4x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
store_float3a(&(r._41), x4);
return r;
#else
Float4x3 result;
result._11 = m1._11 / s;
result._12 = m1._12 / s;
result._13 = m1._13 / s;
result._21 = m1._21 / s;
result._22 = m1._22 / s;
result._23 = m1._23 / s;
result._31 = m1._31 / s;
result._32 = m1._32 / s;
result._33 = m1._33 / s;
result._41 = m1._41 / s;
result._42 = m1._42 / s;
result._43 = m1._43 / s;
return result;
#endif
}
inline Float3x4 operator/(const Float3x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
s = 1.0f / s;
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
Float3x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
return r;
#else
Float3x4 result;
result._11 = m1._11 / s;
result._12 = m1._12 / s;
result._13 = m1._13 / s;
result._14 = m1._14 / s;
result._21 = m1._21 / s;
result._22 = m1._22 / s;
result._23 = m1._23 / s;
result._24 = m1._24 / s;
result._31 = m1._31 / s;
result._32 = m1._32 / s;
result._33 = m1._33 / s;
result._34 = m1._34 / s;
return result;
#endif
}
inline Float4x4 operator/(const Float4x4& m1, f32 s)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
s = 1.0f / s;
x1 = VectorScale(x1, s);
x2 = VectorScale(x2, s);
x3 = VectorScale(x3, s);
x4 = VectorScale(x4, s);
Float4x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
store_float4a(&(r._41), x4);
return r;
#else
Float4x4 result;
result._11 = m1._11 / s;
result._12 = m1._12 / s;
result._13 = m1._13 / s;
result._14 = m1._14 / s;
result._21 = m1._21 / s;
result._22 = m1._22 / s;
result._23 = m1._23 / s;
result._24 = m1._24 / s;
result._31 = m1._31 / s;
result._32 = m1._32 / s;
result._33 = m1._33 / s;
result._34 = m1._34 / s;
result._41 = m1._41 / s;
result._42 = m1._42 / s;
result._43 = m1._43 / s;
result._44 = m1._44 / s;
return result;
#endif
}
inline Float3x3 operator/(f32 s, const Float3x3& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t sv = vector_replicate(s);
x1 = VectorDivide(sv, x1);
x2 = VectorDivide(sv, x2);
x3 = VectorDivide(sv, x3);
Float3x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
return r;
#else
Float3x3 result;
result._11 = s / m1._11;
result._12 = s / m1._12;
result._13 = s / m1._13;
result._21 = s / m1._21;
result._22 = s / m1._22;
result._23 = s / m1._23;
result._31 = s / m1._31;
result._32 = s / m1._32;
result._33 = s / m1._33;
return result;
#endif
}
inline Float4x3 operator/(f32 s, const Float4x3& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float3a(&(m1._11));
vec_float_t x2 = load_float3a(&(m1._21));
vec_float_t x3 = load_float3a(&(m1._31));
vec_float_t x4 = load_float3a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorDivide(y, x1);
x2 = VectorDivide(y, x2);
x3 = VectorDivide(y, x3);
x4 = VectorDivide(y, x4);
Float4x3 r;
store_float3a(&(r._11), x1);
store_float3a(&(r._21), x2);
store_float3a(&(r._31), x3);
store_float3a(&(r._41), x4);
return r;
#else
Float4x3 result;
result._11 = s / m1._11;
result._12 = s / m1._12;
result._13 = s / m1._13;
result._21 = s / m1._21;
result._22 = s / m1._22;
result._23 = s / m1._23;
result._31 = s / m1._31;
result._32 = s / m1._32;
result._33 = s / m1._33;
result._41 = s / m1._41;
result._42 = s / m1._42;
result._43 = s / m1._43;
return result;
#endif
}
inline Float3x4 operator/(f32 s, const Float3x4& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t y = vector_replicate(s);
x1 = VectorDivide(y, x1);
x2 = VectorDivide(y, x2);
x3 = VectorDivide(y, x3);
Float3x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
return r;
#else
Float3x4 result;
result._11 = s / m1._11;
result._12 = s / m1._12;
result._13 = s / m1._13;
result._14 = s / m1._14;
result._21 = s / m1._21;
result._22 = s / m1._22;
result._23 = s / m1._23;
result._24 = s / m1._24;
result._31 = s / m1._31;
result._32 = s / m1._32;
result._33 = s / m1._33;
result._34 = s / m1._34;
return result;
#endif
}
inline Float4x4 operator/(f32 s, const Float4x4& m1)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t x1 = load_float4a(&(m1._11));
vec_float_t x2 = load_float4a(&(m1._21));
vec_float_t x3 = load_float4a(&(m1._31));
vec_float_t x4 = load_float4a(&(m1._41));
vec_float_t y = vector_replicate(s);
x1 = VectorDivide(y, x1);
x2 = VectorDivide(y, x2);
x3 = VectorDivide(y, x3);
x4 = VectorDivide(y, x4);
Float4x4 r;
store_float4a(&(r._11), x1);
store_float4a(&(r._21), x2);
store_float4a(&(r._31), x3);
store_float4a(&(r._41), x4);
return r;
#else
Float4x4 result;
result._11 = s / m1._11;
result._12 = s / m1._12;
result._13 = s / m1._13;
result._14 = s / m1._14;
result._21 = s / m1._21;
result._22 = s / m1._22;
result._23 = s / m1._23;
result._24 = s / m1._24;
result._31 = s / m1._31;
result._32 = s / m1._32;
result._33 = s / m1._33;
result._34 = s / m1._34;
result._41 = s / m1._41;
result._42 = s / m1._42;
result._43 = s / m1._43;
result._44 = s / m1._44;
return result;
#endif
}
inline Float3 mul(const Float3& vec, const Float3x3& mat)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t s = vector_replicate(vec.x);
vec_float_t m = load_float3a(&(mat._11));
vec_float_t r = VectorMultiply(s, m);
s = vector_replicate(vec.y);
m = load_float3a(&(mat._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(vec.z);
m = load_float3a(&(mat._31));
r = VectorMultiplyAdd(s, m, r);
Float3 result;
store_float3a(result.m, r);
return result;
#else
return Float3(
vec.x * mat._11 + vec.y * mat._21 + vec.z * mat._31,
vec.x * mat._12 + vec.y * mat._22 + vec.z * mat._32,
vec.x * mat._13 + vec.y * mat._23 + vec.z * mat._33);
#endif
}
inline Float3 mul(const Float3x3& mat, const Float3& vec)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float3 t;
Float3 result;
vec_float_t s = load_float3a(vec.m);
vec_float_t m = load_float3a(&(mat._11));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.x = t.x + t.y + t.z;
m = load_float3a(&(mat._21));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.y = t.x + t.y + t.z;
m = load_float3a(&(mat._31));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.z = t.x + t.y + t.z;
return result;
#else
return Float3(
vec.x * mat._11 + vec.y * mat._12 + vec.z * mat._13,
vec.x * mat._21 + vec.y * mat._22 + vec.z * mat._23,
vec.x * mat._31 + vec.y * mat._32 + vec.z * mat._33);
#endif
}
inline Float3x3 mul(const Float3x3& m1, const Float3x3& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float3x3 result;
vec_float_t s = vector_replicate(m1._11);
vec_float_t m = load_float3a(&(m2._11));
vec_float_t r = VectorMultiply(s, m);
s = vector_replicate(m1._12);
m = load_float3a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._13);
m = load_float3a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
store_float3a(&(result._11), r);
s = vector_replicate(m1._21);
m = load_float3a(&(m2._11));
r = VectorMultiply(s, m);
s = vector_replicate(m1._22);
m = load_float3a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._23);
m = load_float3a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
store_float3a(&(result._21), r);
s = vector_replicate(m1._31);
m = load_float3a(&(m2._11));
r = VectorMultiply(s, m);
s = vector_replicate(m1._32);
m = load_float3a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._33);
m = load_float3a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
store_float3a(&(result._31), r);
return result;
#else
return Float3x3(
m1._11 * m2._11 + m1._12 * m2._21 + m1._13 * m2._31,
m1._11 * m2._12 + m1._12 * m2._22 + m1._13 * m2._32,
m1._11 * m2._13 + m1._12 * m2._23 + m1._13 * m2._33,
m1._21 * m2._11 + m1._22 * m2._21 + m1._23 * m2._31,
m1._21 * m2._12 + m1._22 * m2._22 + m1._23 * m2._32,
m1._21 * m2._13 + m1._22 * m2._23 + m1._23 * m2._33,
m1._31 * m2._11 + m1._32 * m2._21 + m1._33 * m2._31,
m1._31 * m2._12 + m1._32 * m2._22 + m1._33 * m2._32,
m1._31 * m2._13 + m1._32 * m2._23 + m1._33 * m2._33);
#endif
}
inline Float4x3::Float4x3(const Float3x3& m, const Float3& row4)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r = load_float3a(&(m._11));
store_float3a(&(_11), r);
r = load_float3a(&(m._21));
store_float3a(&(_21), r);
r = load_float3a(&(m._31));
store_float3a(&(_31), r);
r = load_float3a(row4.m);
store_float3a(&(_41), r);
#else
_11 = m._11;
_12 = m._12;
_13 = m._13;
_21 = m._21;
_22 = m._22;
_23 = m._23;
_31 = m._31;
_32 = m._32;
_33 = m._33;
_41 = row4.x;
_42 = row4.y;
_43 = row4.z;
#endif
}
inline Float3 mul(const Float4& vec, const Float4x3& mat)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t s = vector_replicate(vec.x);
vec_float_t m = load_float3a(&(mat._11));
vec_float_t r = VectorMultiply(s, m);
s = vector_replicate(vec.y);
m = load_float3a(&(mat._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(vec.z);
m = load_float3a(&(mat._31));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(vec.w);
m = load_float3a(&(mat._41));
r = VectorMultiplyAdd(s, m, r);
Float3 result;
store_float3a(result.m, r);
return result;
#else
return Float3(
vec.x * mat._11 + vec.y * mat._21 + vec.z * mat._31 + vec.w * mat._41,
vec.x * mat._12 + vec.y * mat._22 + vec.z * mat._32 + vec.w * mat._42,
vec.x * mat._13 + vec.y * mat._23 + vec.z * mat._33 + vec.w * mat._43);
#endif
}
inline Float4 mul(const Float4x3& mat, const Float3& vec)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float3 t;
Float4 result;
vec_float_t s = load_float3a(vec.m);
vec_float_t m = load_float3a(&(mat._11));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.x = t.x + t.y + t.z;
m = load_float3a(&(mat._21));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.y = t.x + t.y + t.z;
m = load_float3a(&(mat._31));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.z = t.x + t.y + t.z;
m = load_float3a(&(mat._41));
m = VectorMultiply(m, s);
store_float3a(t.m, m);
result.w = t.x + t.y + t.z;
return result;
#else
return Float4(
vec.x * mat._11 + vec.y * mat._12 + vec.z * mat._13,
vec.x * mat._21 + vec.y * mat._22 + vec.z * mat._23,
vec.x * mat._31 + vec.y * mat._32 + vec.z * mat._33,
vec.x * mat._41 + vec.y * mat._42 + vec.z * mat._43);
#endif
}
inline Float3x4::Float3x4(const Float3x3& m, const Float3& col4)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r = load_float3a(&(m._11));
store_float3a(&(_11), r);
r = load_float3a(&(m._21));
store_float3a(&(_21), r);
r = load_float3a(&(m._31));
store_float3a(&(_31), r);
_14 = col4.x;
_24 = col4.y;
_34 = col4.z;
#else
_11 = m._11;
_12 = m._12;
_13 = m._13;
_14 = col4.x;
_21 = m._21;
_22 = m._22;
_23 = m._23;
_24 = col4.y;
_31 = m._31;
_32 = m._32;
_33 = m._33;
_34 = col4.z;
#endif
}
inline Float4 mul(const Float3& vec, const Float3x4& mat)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t s = vector_replicate(vec.x);
vec_float_t m = load_float4a(&(mat._11));
vec_float_t r = VectorMultiply(s, m);
s = vector_replicate(vec.y);
m = load_float4a(&(mat._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(vec.z);
m = load_float4a(&(mat._31));
r = VectorMultiplyAdd(s, m, r);
Float4 result;
store_float4a(result.m, r);
return result;
#else
return Float4(
vec.x * mat._11 + vec.y * mat._21 + vec.z * mat._31,
vec.x * mat._12 + vec.y * mat._22 + vec.z * mat._32,
vec.x * mat._13 + vec.y * mat._23 + vec.z * mat._33,
vec.x * mat._14 + vec.y * mat._24 + vec.z * mat._34);
#endif
}
inline Float3 mul(const Float3x4& mat, const Float4& vec)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4 t;
Float3 result;
vec_float_t s = load_float4a(vec.m);
vec_float_t m = load_float4a(&(mat._11));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.x = t.x + t.y + t.z + t.w;
m = load_float4a(&(mat._21));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.y = t.x + t.y + t.z + t.w;
m = load_float4a(&(mat._31));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.z = t.x + t.y + t.z + t.w;
return result;
#else
return Float3(
vec.x * mat._11 + vec.y * mat._12 + vec.z * mat._13 + vec.w * mat._14,
vec.x * mat._21 + vec.y * mat._22 + vec.z * mat._23 + vec.w * mat._24,
vec.x * mat._31 + vec.y * mat._32 + vec.z * mat._33 + vec.w * mat._34);
#endif
}
inline Float4x4::Float4x4(const Float4x3& m, const Float4& col4)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r = load_float3a(&(m._11));
store_float3a(&(_11), r);
r = load_float3a(&(m._21));
store_float3a(&(_21), r);
r = load_float3a(&(m._31));
store_float3a(&(_31), r);
r = load_float3a(&(m._41));
store_float3a(&(_41), r);
_14 = col4.x;
_24 = col4.y;
_34 = col4.z;
_44 = col4.w;
#else
_11 = m._11;
_12 = m._12;
_13 = m._13;
_14 = col4.x;
_21 = m._21;
_22 = m._22;
_23 = m._23;
_24 = col4.y;
_31 = m._31;
_32 = m._32;
_33 = m._33;
_34 = col4.z;
_41 = m._41;
_42 = m._42;
_43 = m._43;
_44 = col4.w;
#endif
}
inline Float4x4::Float4x4(const Float3x4& m, const Float4& row4)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t r = load_float4a(&(m._11));
store_float4a(&(_11), r);
r = load_float4a(&(m._21));
store_float4a(&(_21), r);
r = load_float4a(&(m._31));
store_float4a(&(_31), r);
r = load_float4a(row4.m);
store_float4a(&(_41), r);
#else
_11 = m._11;
_12 = m._12;
_13 = m._13;
_14 = m._14;
_21 = m._21;
_22 = m._22;
_23 = m._23;
_24 = m._24;
_31 = m._31;
_32 = m._32;
_33 = m._33;
_34 = m._34;
_41 = row4.x;
_42 = row4.y;
_43 = row4.z;
_44 = row4.w;
#endif
}
inline Float4 mul(const Float4& vec, const Float4x4& mat)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t s = vector_replicate(vec.x);
vec_float_t m = load_float4a(&(mat._11));
vec_float_t r = VectorMultiply(s, m);
s = vector_replicate(vec.y);
m = load_float4a(&(mat._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(vec.z);
m = load_float4a(&(mat._31));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(vec.w);
m = load_float4a(&(mat._41));
r = VectorMultiplyAdd(s, m, r);
Float4 result;
store_float4a(result.m, r);
return result;
#else
return Float4(
vec.x * mat._11 + vec.y * mat._21 + vec.z * mat._31 + vec.w * mat._41,
vec.x * mat._12 + vec.y * mat._22 + vec.z * mat._32 + vec.w * mat._42,
vec.x * mat._13 + vec.y * mat._23 + vec.z * mat._33 + vec.w * mat._43,
vec.x * mat._14 + vec.y * mat._24 + vec.z * mat._34 + vec.w * mat._44);
#endif
}
inline Float4 mul(const Float4x4& mat, const Float4& vec)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4 t;
Float4 result;
vec_float_t s = load_float4a(vec.m);
vec_float_t m = load_float4a(&(mat._11));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.x = t.x + t.y + t.z + t.w;
m = load_float4a(&(mat._21));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.y = t.x + t.y + t.z + t.w;
m = load_float4a(&(mat._31));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.z = t.x + t.y + t.z + t.w;
m = load_float4a(&(mat._41));
m = VectorMultiply(m, s);
store_float4a(t.m, m);
result.w = t.x + t.y + t.z + t.w;
return result;
#else
return Float4(
vec.x * mat._11 + vec.y * mat._12 + vec.z * mat._13 + vec.w * mat._14,
vec.x * mat._21 + vec.y * mat._22 + vec.z * mat._23 + vec.w * mat._24,
vec.x * mat._31 + vec.y * mat._32 + vec.z * mat._33 + vec.w * mat._34,
vec.x * mat._41 + vec.y * mat._42 + vec.z * mat._43 + vec.w * mat._44);
#endif
}
inline Float4x4 mul(const Float4x4& m1, const Float4x4& m2)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 result;
vec_float_t s = vector_replicate(m1._11);
vec_float_t m = load_float4a(&(m2._11));
vec_float_t r = VectorMultiply(s, m);
s = vector_replicate(m1._12);
m = load_float4a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._13);
m = load_float4a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._14);
m = load_float4a(&(m2._41));
r = VectorMultiplyAdd(s, m, r);
store_float4a(&(result._11), r);
s = vector_replicate(m1._21);
m = load_float4a(&(m2._11));
r = VectorMultiply(s, m);
s = vector_replicate(m1._22);
m = load_float4a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._23);
m = load_float4a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._24);
m = load_float4a(&(m2._41));
r = VectorMultiplyAdd(s, m, r);
store_float4a(&(result._21), r);
s = vector_replicate(m1._31);
m = load_float4a(&(m2._11));
r = VectorMultiply(s, m);
s = vector_replicate(m1._32);
m = load_float4a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._33);
m = load_float4a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._34);
m = load_float4a(&(m2._41));
r = VectorMultiplyAdd(s, m, r);
store_float4a(&(result._31), r);
s = vector_replicate(m1._41);
m = load_float4a(&(m2._11));
r = VectorMultiply(s, m);
s = vector_replicate(m1._42);
m = load_float4a(&(m2._21));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._43);
m = load_float4a(&(m2._31));
r = VectorMultiplyAdd(s, m, r);
s = vector_replicate(m1._44);
m = load_float4a(&(m2._41));
r = VectorMultiplyAdd(s, m, r);
store_float4a(&(result._41), r);
return result;
#else
return Float4x4(
m1._11 * m2._11 + m1._12 * m2._21 + m1._13 * m2._31 + m1._14 * m2._41,
m1._11 * m2._12 + m1._12 * m2._22 + m1._13 * m2._32 + m1._14 * m2._42,
m1._11 * m2._13 + m1._12 * m2._23 + m1._13 * m2._33 + m1._14 * m2._43,
m1._11 * m2._14 + m1._12 * m2._24 + m1._13 * m2._34 + m1._14 * m2._44,
m1._21 * m2._11 + m1._22 * m2._21 + m1._23 * m2._31 + m1._24 * m2._41,
m1._21 * m2._12 + m1._22 * m2._22 + m1._23 * m2._32 + m1._24 * m2._42,
m1._21 * m2._13 + m1._22 * m2._23 + m1._23 * m2._33 + m1._24 * m2._43,
m1._21 * m2._14 + m1._22 * m2._24 + m1._23 * m2._34 + m1._24 * m2._44,
m1._31 * m2._11 + m1._32 * m2._21 + m1._33 * m2._31 + m1._34 * m2._41,
m1._31 * m2._12 + m1._32 * m2._22 + m1._33 * m2._32 + m1._34 * m2._42,
m1._31 * m2._13 + m1._32 * m2._23 + m1._33 * m2._33 + m1._34 * m2._43,
m1._31 * m2._14 + m1._32 * m2._24 + m1._33 * m2._34 + m1._34 * m2._44,
m1._41 * m2._11 + m1._42 * m2._21 + m1._43 * m2._31 + m1._44 * m2._41,
m1._41 * m2._12 + m1._42 * m2._22 + m1._43 * m2._32 + m1._44 * m2._42,
m1._41 * m2._13 + m1._42 * m2._23 + m1._43 * m2._33 + m1._44 * m2._43,
m1._41 * m2._14 + m1._42 * m2._24 + m1._43 * m2._34 + m1._44 * m2._44);
#endif
}
inline f32 determinant(const Float3x3& mat)
{
return
mat._11 * mat._22 * mat._33 +
mat._12 * mat._23 * mat._31 +
mat._13 * mat._21 * mat._32 -
mat._13 * mat._22 * mat._31 -
mat._12 * mat._21 * mat._33 -
mat._11 * mat._23 * mat._32;
}
inline f32 determinant(const Float4x4& mat)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
mat_float_t m = load_float4x4a(&(mat._11));
return VectorGetX(MatrixDeterminant(m));
#else
return
mat._11 *
(mat._22 * mat._33 * mat._44 +
mat._23 * mat._34 * mat._42 +
mat._24 * mat._32 * mat._43 -
mat._24 * mat._33 * mat._42 -
mat._23 * mat._32 * mat._44 -
mat._22 * mat._34 * mat._43)
- mat._12 *
(mat._21 * mat._33 * mat._44 +
mat._23 * mat._34 * mat._41 +
mat._24 * mat._31 * mat._43 -
mat._24 * mat._33 * mat._41 -
mat._23 * mat._31 * mat._44 -
mat._21 * mat._34 * mat._43)
+ mat._13 *
(mat._21 * mat._32 * mat._44 +
mat._22 * mat._34 * mat._41 +
mat._24 * mat._31 * mat._42 -
mat._24 * mat._32 * mat._41 -
mat._22 * mat._31 * mat._44 -
mat._21 * mat._34 * mat._42)
- mat._14 *
(mat._21 * mat._32 * mat._43 +
mat._22 * mat._33 * mat._41 +
mat._23 * mat._31 * mat._42 -
mat._23 * mat._32 * mat._41 -
mat._22 * mat._31 * mat._43 -
mat._21 * mat._33 * mat._42);
#endif
}
inline Float3x3 transpose(const Float3x3& m)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
mat_float_t M = load_float3x4a(&(m._11));
Float3x3 result;
store_float3x4a(&(result._11), MatrixTranspose(M));
return result;
#else
return Float3x3(
m._11, m._21, m._31,
m._12, m._22, m._32,
m._13, m._23, m._33
);
#endif
}
inline Float3x4 transpose(const Float4x3& m)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
mat_float_t M = load_float4x4a(&(m._11));
Float3x4 result;
M = MatrixTranspose(M);
store_float4a(&(result._11), M.r[0]);
store_float4a(&(result._21), M.r[1]);
store_float4a(&(result._31), M.r[2]);
return result;
#else
return Float3x4(
m._11, m._21, m._31, m._41,
m._12, m._22, m._32, m._42,
m._13, m._23, m._33, m._43
);
#endif
}
inline Float4x3 transpose(const Float3x4& m)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
mat_float_t M;
M.r[0] = load_float4a(&(m._11));
M.r[1] = load_float4a(&(m._21));
M.r[2] = load_float4a(&(m._31));
Float4x3 result;
M = MatrixTranspose(M);
store_float4x4a(&(result._11), M);
return result;
#else
return Float4x3(
m._11, m._21, m._31,
m._12, m._22, m._32,
m._13, m._23, m._33,
m._14, m._24, m._34
);
#endif
}
inline Float4x4 transpose(const Float4x4& m)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
mat_float_t M = load_float4x4a(&(m._11));
Float4x4 result;
store_float4x4a(&(result._11), MatrixTranspose(M));
return result;
#else
return Float4x4(
m._11, m._21, m._31, m._41,
m._12, m._22, m._32, m._42,
m._13, m._23, m._33, m._43,
m._14, m._24, m._34, m._44
);
#endif
}
inline Float3x3 inverse(const Float3x3& m, f32* out_determinant)
{
f32 det = determinant(m);
if (out_determinant)
{
*out_determinant = det;
}
if (det > -FLT_EPSILON && det < FLT_EPSILON)
{
det = FLT_EPSILON;
}
f32 det_inv = 1.0f / det;
Float3x3 r;
r._11 = det_inv * (m._22 * m._33 - m._32 * m._23);
r._21 = -det_inv * (m._21 * m._33 - m._31 * m._23);
r._31 = det_inv * (m._21 * m._32 - m._31 * m._22);
r._12 = -det_inv * (m._12 * m._33 - m._32 * m._13);
r._22 = det_inv * (m._11 * m._33 - m._31 * m._13);
r._32 = -det_inv * (m._11 * m._32 - m._31 * m._12);
r._13 = det_inv * (m._12 * m._23 - m._22 * m._13);
r._23 = -det_inv * (m._11 * m._23 - m._21 * m._13);
r._33 = det_inv * (m._11 * m._22 - m._21 * m._12);
return r;
}
inline Float4x4 inverse(const Float4x4& m, f32* out_determinant)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
mat_float_t M = load_float4x4a(&(m._11));
vec_float_t det;
Float4x4 result;
store_float4x4a(&(result._11), MatrixInverse(&det, M));
if (out_determinant)
{
store_float(out_determinant, det);
}
return result;
#else
f32 det = determinant(m);
if (out_determinant)
{
*out_determinant = det;
}
if (det > -f32_epsilon && det < f32_epsilon)
{
det = f32_epsilon;
}
f32 det_inv = 1.0f / det;
Float4x4 r;
r._11 = (m._22 * m._33 * m._44 + m._23 * m._34 * m._42 + m._24 * m._32 * m._43 - m._24 * m._33 * m._42 - m._23 * m._32 * m._44 - m._22 * m._34 * m._43) / det;
r._21 = (m._21 * m._33 * m._44 + m._23 * m._34 * m._41 + m._24 * m._31 * m._43 - m._24 * m._33 * m._41 - m._23 * m._31 * m._44 - m._21 * m._34 * m._43) / -det;
r._31 = (m._21 * m._32 * m._44 + m._22 * m._34 * m._41 + m._24 * m._31 * m._42 - m._24 * m._32 * m._41 - m._22 * m._31 * m._44 - m._21 * m._34 * m._42) / det;
r._41 = (m._21 * m._32 * m._43 + m._22 * m._33 * m._41 + m._23 * m._31 * m._42 - m._23 * m._32 * m._41 - m._22 * m._31 * m._43 - m._21 * m._33 * m._42) / -det;
r._12 = (m._12 * m._33 * m._44 + m._13 * m._34 * m._42 + m._14 * m._32 * m._43 - m._14 * m._33 * m._42 - m._13 * m._32 * m._44 - m._12 * m._34 * m._43) / -det;
r._22 = (m._11 * m._33 * m._44 + m._13 * m._34 * m._41 + m._14 * m._31 * m._43 - m._14 * m._33 * m._41 - m._13 * m._31 * m._44 - m._11 * m._34 * m._43) / det;
r._32 = (m._11 * m._32 * m._44 + m._12 * m._34 * m._41 + m._14 * m._31 * m._42 - m._14 * m._32 * m._41 - m._12 * m._31 * m._44 - m._11 * m._34 * m._42) / -det;
r._42 = (m._11 * m._32 * m._43 + m._12 * m._33 * m._41 + m._13 * m._31 * m._42 - m._13 * m._32 * m._41 - m._12 * m._31 * m._43 - m._11 * m._33 * m._42) / det;
r._13 = (m._12 * m._23 * m._44 + m._13 * m._24 * m._42 + m._14 * m._22 * m._43 - m._14 * m._23 * m._42 - m._13 * m._22 * m._44 - m._12 * m._24 * m._43) / det;
r._23 = (m._11 * m._23 * m._44 + m._13 * m._24 * m._41 + m._14 * m._21 * m._43 - m._14 * m._23 * m._41 - m._13 * m._21 * m._44 - m._11 * m._24 * m._43) / -det;
r._33 = (m._11 * m._22 * m._44 + m._12 * m._24 * m._41 + m._14 * m._21 * m._42 - m._14 * m._22 * m._41 - m._12 * m._21 * m._44 - m._11 * m._24 * m._42) / det;
r._43 = (m._11 * m._22 * m._43 + m._12 * m._23 * m._41 + m._13 * m._21 * m._42 - m._13 * m._22 * m._41 - m._12 * m._21 * m._43 - m._11 * m._23 * m._42) / -det;
r._14 = (m._12 * m._23 * m._34 + m._13 * m._24 * m._32 + m._14 * m._22 * m._33 - m._14 * m._23 * m._32 - m._13 * m._22 * m._34 - m._12 * m._24 * m._33) / -det;
r._24 = (m._11 * m._23 * m._34 + m._13 * m._24 * m._31 + m._14 * m._21 * m._33 - m._14 * m._23 * m._31 - m._13 * m._21 * m._34 - m._11 * m._24 * m._33) / det;
r._34 = (m._11 * m._22 * m._34 + m._12 * m._24 * m._31 + m._14 * m._21 * m._32 - m._14 * m._22 * m._31 - m._12 * m._21 * m._34 - m._11 * m._24 * m._32) / -det;
r._44 = (m._11 * m._22 * m._33 + m._12 * m._23 * m._31 + m._13 * m._21 * m._32 - m._13 * m._22 * m._31 - m._12 * m._21 * m._33 - m._11 * m._23 * m._32) / det;
return r;
#endif
}
inline Float4x4 Float4x4::make_billboard(const Float3& object_pos, const Float3& camera_pos,
const Float3& camera_up, const Float3& camera_forward)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t O = load_float3a(object_pos.m);
vec_float_t C = load_float3a(camera_pos.m);
vec_float_t Z = VectorSubtract(O, C);
vec_float_t N = Vector3LengthSq(Z);
if (Vector3Less(N, g_Epsilon))
{
vec_float_t F = load_float3a(camera_forward.m);
Z = VectorNegate(F);
}
else
{
Z = Vector3Normalize(Z);
}
vec_float_t up = load_float3a(camera_up.m);
vec_float_t X = Vector3Cross(up, Z);
X = Vector3Normalize(X);
vec_float_t Y = Vector3Cross(Z, X);
mat_float_t M;
M.r[0] = X;
M.r[1] = Y;
M.r[2] = Z;
M.r[3] = VectorSetW(O, 1.f);
Float4x4 R;
store_float4x4a(R.m[0], M);
return R;
#else
Float3 Z = object_pos - camera_pos;
f32 N = length_squared(Z);
if (N < 1.192092896e-7f)
{
Z = -camera_forward;
}
else
{
Z = normalize(Z);
}
Float3 X = cross(camera_up, Z);
X = normalize(X);
Float3 Y = cross(Z, X);
Float4x4 M(
X.x, X.y, X.z, 0.0f,
Y.x, Y.y, Y.z, 0.0f,
Z.x, Z.y, Z.z, 0.0f,
object_pos.x, object_pos.y, object_pos.z, 1.0f
);
return M;
#endif
}
inline Float4x4 Float4x4::make_constrained_billboard(const Float3& object_pos, const Float3& camera_pos,
const Float3& rotate_axis, const Float3& camera_forward, const Float3& object_forward)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
constexpr Float4 s_minAngle = { 0.99825467075f, 0.99825467075f, 0.99825467075f, 0.99825467075f };// 1.0 - ConvertToRadians( 0.1f );
vec_float_t O = load_float3a(object_pos.m);
vec_float_t C = load_float3a(camera_pos.m);
vec_float_t faceDir = VectorSubtract(O, C);
vec_float_t N = Vector3LengthSq(faceDir);
if (Vector3Less(N, g_Epsilon))
{
vec_float_t F = load_float3a(camera_forward.m);
faceDir = VectorNegate(F);
}
else
{
faceDir = Vector3Normalize(faceDir);
}
vec_float_t Y = load_float3a(rotate_axis.m);
vec_float_t X, Z;
vec_float_t dot = VectorAbs(Vector3Dot(Y, faceDir));
if (Vector3Greater(dot, s_minAngle))
{
Z = load_float3a(object_forward.m);
dot = VectorAbs(Vector3Dot(Y, Z));
if (Vector3Greater(dot, s_minAngle))
{
dot = VectorAbs(Vector3Dot(Y, g_NegIdentityR2));
Z = (Vector3Greater(dot, s_minAngle)) ? g_IdentityR0 : g_NegIdentityR2;
}
X = Vector3Cross(Y, Z);
X = Vector3Normalize(X);
Z = Vector3Cross(X, Y);
Z = Vector3Normalize(Z);
}
else
{
X = Vector3Cross(Y, faceDir);
X = Vector3Normalize(X);
Z = Vector3Cross(X, Y);
Z = Vector3Normalize(Z);
}
mat_float_t M;
M.r[0] = X;
M.r[1] = Y;
M.r[2] = Z;
M.r[3] = VectorSetW(O, 1.f);
Float4x4 R;
store_float4x4a(R.m[0], M);
return R;
#else
static const f32 s_minAngle{ 0.99825467075f }; // 1.0 - ConvertToRadians( 0.1f );
//vec_float_t O = LoadFloat3(object.m);
//vec_float_t C = LoadFloat3(cameraPosition.m);
Float3 faceDir = object_pos - camera_pos;
f32 N = length_squared(faceDir);
if (N < 1.192092896e-7f)
{
faceDir = -camera_forward;
}
else
{
faceDir = normalize(faceDir);
}
Float3 Y = rotate_axis;
Float3 X, Z;
f32 d = fabsf(dot(Y, faceDir));
if (d > s_minAngle)
{
Z = object_forward;
d = fabsf(dot(Y, Z));
if (d > s_minAngle)
{
d = fabsf(dot(Y, Float3(0.0f, 0.0f, -1.0f)));
Z = (d > s_minAngle) ? Float3(1.0f, 0.0f, 0.0f) : Float3(0.0f, 0.0f, -1.0f);
}
X = cross(Y, Z);
X = normalize(X);
Z = cross(X, Y);
Z = normalize(Z);
}
else
{
X = cross(Y, faceDir);
X = normalize(X);
Z = cross(X, Y);
Z = normalize(Z);
}
Float4x4 M(
X.x, X.y, X.z, 0.0f,
Y.x, Y.y, Y.z, 0.0f,
Z.x, Z.y, Z.z, 0.0f,
object_pos.x, object_pos.y, object_pos.z, 1.0f
);
return M;
#endif
}
inline Float4x4 Float4x4::make_translation(const Float3& position)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixTranslation(position.x, position.y, position.z));
return R;
#else
Float4x4 M;
M.m[0][0] = 1.0f;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = 1.0f;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = 1.0f;
M.m[2][3] = 0.0f;
M.m[3][0] = position.x;
M.m[3][1] = position.y;
M.m[3][2] = position.z;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_scale(const Float3& scales)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixScaling(scales.x, scales.y, scales.z));
return R;
#else
Float4x4 M;
M.m[0][0] = scales.x;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = scales.y;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = scales.z;
M.m[2][3] = 0.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = 0.0f;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_rotation_x(f32 radians)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixRotationX(radians));
return R;
#else
f32 fSinAngle = sinf(radians);
f32 fCosAngle = cosf(radians);
Float4x4 M;
M.m[0][0] = 1.0f;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = fCosAngle;
M.m[1][2] = fSinAngle;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = -fSinAngle;
M.m[2][2] = fCosAngle;
M.m[2][3] = 0.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = 0.0f;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_rotation_y(f32 radians)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixRotationY(radians));
return R;
#else
f32 fSinAngle = sinf(radians);
f32 fCosAngle = cosf(radians);
Float4x4 M;
M.m[0][0] = fCosAngle;
M.m[0][1] = 0.0f;
M.m[0][2] = -fSinAngle;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = 1.0f;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = fSinAngle;
M.m[2][1] = 0.0f;
M.m[2][2] = fCosAngle;
M.m[2][3] = 0.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = 0.0f;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_rotation_z(f32 radians)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixRotationZ(radians));
return R;
#else
f32 fSinAngle = sinf(radians);
f32 fCosAngle = cosf(radians);
Float4x4 M;
M.m[0][0] = fCosAngle;
M.m[0][1] = fSinAngle;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = -fSinAngle;
M.m[1][1] = fCosAngle;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = 1.0f;
M.m[2][3] = 0.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = 0.0f;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_rotation_quaternion(const Quaternion& quaternion)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixRotationQuaternion(quaternion));
return R;
#else
lupanic("Not implemented");
#endif
}
inline Float4x4 Float4x4::make_from_axis_angle(const Float3& axis, f32 angle)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
vec_float_t a = load_float3(axis.m);
store_float4x4a(R.m[0], MatrixRotationAxis(a, angle));
return R;
#else
Float3 norm = normalize(axis);
f32 fSinAngle = sinf(angle);
f32 fCosAngle = cosf(angle);
Float4 A(fSinAngle, fCosAngle, 1.0f - fCosAngle, 0.0f);
Float4 C2(A.z, A.z, A.z, A.z);
Float4 C1(A.y, A.y, A.y, A.y);
Float4 C0(A.x, A.x, A.x, A.x);
Float4 N0(norm.y, norm.z, norm.x, 0.0f);
Float4 N1(norm.z, norm.x, norm.y, 0.0f);
Float4 V0 = C2 * N0;
V0 = V0 * N1;
Float4 R0 = C2 * Float4(norm.x, norm.y, norm.z, 0.0f);
R0 = (R0 * Float4(norm.x, norm.y, norm.z, 0.0f)) + C1;
Float4 R1 = (C0 * Float4(norm.x, norm.y, norm.z, 0.0f)) + V0;
Float4 R2 = C0 - (Float4(norm.x, norm.y, norm.z, 0.0f) * V0);
V0 = Float4(R0.x, R0.y, R0.z, A.w);
Float4 V1(R1.z, R2.y, R2.z, R1.x);
Float4 V2(R1.y, R2.x, R1.y, R2.x);
Float4x4 M(
V0.x, V1.x, V1.y, V0.w,
V1.z, V0.y, V1.w, V0.w,
V2.x, V2.y, V0.z, V0.w,
0.0f, 0.0f, 0.0f, 1.0f
);
return M;
#endif
}
inline Float4x4 Float4x4::make_perspective_field_of_view(f32 fov, f32 aspect_ratio,
f32 near_plane_distance, f32 far_plance_distance)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixPerspectiveFovLH(fov, aspect_ratio, near_plane_distance, far_plance_distance));
return R;
#else
f32 SinFov = sinf(0.5f * fov);
f32 CosFov = cosf(0.5f * fov);
f32 Height = CosFov / SinFov;
f32 Width = Height / aspect_ratio;
f32 fRange = far_plance_distance / (near_plane_distance - far_plance_distance);
Float4x4 M;
M.m[0][0] = Width;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = Height;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = fRange;
M.m[2][3] = -1.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = fRange * near_plane_distance;
M.m[3][3] = 0.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_perspective(f32 width, f32 height, f32 near_plane_distance,
f32 far_plane_distance)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixPerspectiveLH(width, height, near_plane_distance, far_plane_distance));
return R;
#else
f32 TwoNearZ = near_plane_distance + near_plane_distance;
f32 fRange = far_plane_distance / (near_plane_distance - far_plane_distance);
Float4x4 M;
M.m[0][0] = TwoNearZ / width;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = TwoNearZ / height;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = fRange;
M.m[2][3] = -1.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = fRange * near_plane_distance;
M.m[3][3] = 0.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_perspective_off_center(f32 left, f32 right, f32 bottom,
f32 top, f32 near_plane_distance, f32 far_plance_distance)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixPerspectiveOffCenterLH(left, right, bottom, top, near_plane_distance, far_plance_distance));
return R;
#else
f32 TwoNearZ = near_plane_distance + near_plane_distance;
f32 ReciprocalWidth = 1.0f / (right - left);
f32 ReciprocalHeight = 1.0f / (top - bottom);
f32 fRange = far_plance_distance / (near_plane_distance - far_plance_distance);
Float4x4 M;
M.m[0][0] = TwoNearZ * ReciprocalWidth;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = TwoNearZ * ReciprocalHeight;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = (left + right) * ReciprocalWidth;
M.m[2][1] = (top + bottom) * ReciprocalHeight;
M.m[2][2] = fRange;
M.m[2][3] = -1.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = fRange * near_plane_distance;
M.m[3][3] = 0.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_orthographic(f32 width, f32 height, f32 z_near_place_distance,
f32 z_far_plane_distance)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixOrthographicLH(width, height, z_near_place_distance, z_far_plane_distance));
return R;
#else
f32 fRange = 1.0f / (z_near_place_distance - z_far_plane_distance);
Float4x4 M;
M.m[0][0] = 2.0f / width;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = 2.0f / height;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = fRange;
M.m[2][3] = 0.0f;
M.m[3][0] = 0.0f;
M.m[3][1] = 0.0f;
M.m[3][2] = fRange * z_near_place_distance;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_orthographic_off_center(f32 left, f32 right, f32 bottom,
f32 top, f32 near_plane_distance, f32 far_plance_distance)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
store_float4x4a(R.m[0], MatrixOrthographicOffCenterLH(left, right, bottom, top, near_plane_distance, far_plance_distance));
return R;
#else
f32 ReciprocalWidth = 1.0f / (right - left);
f32 ReciprocalHeight = 1.0f / (top - bottom);
f32 fRange = 1.0f / (near_plane_distance - far_plance_distance);
Float4x4 M;
M.m[0][0] = ReciprocalWidth + ReciprocalWidth;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = ReciprocalHeight + ReciprocalHeight;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = fRange;
M.m[2][3] = 0.0f;
M.m[3][0] = -(left + right) * ReciprocalWidth;
M.m[3][1] = -(top + bottom) * ReciprocalHeight;
M.m[3][2] = fRange * near_plane_distance;
M.m[3][3] = 1.0f;
return M;
#endif
}
inline Float4x4 Float4x4::make_look_at(const Float3& camera_position, const Float3& target_position, const Float3& up_dir)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
Float4x4 R;
vec_float_t eyev = load_float3a(camera_position.m);
vec_float_t targetv = load_float3a(target_position.m);
vec_float_t upv = load_float3a(up_dir.m);
store_float4x4(R.m[0], MatrixLookAtLH(eyev, targetv, upv));
return R;
#else
Float3 NegEyeDirection = camera_position - target_position;
Float3 R2 = normalize(NegEyeDirection);
Float3 R0 = normalize(cross(up_dir, R2));
Float3 R1 = cross(R2, R0);
Float3 NegEyePosition = -camera_position;
f32 D0 = dot(R0, NegEyePosition);
f32 D1 = dot(R1, NegEyePosition);
f32 D2 = dot(R2, NegEyePosition);
Float4x4 M(
R0.x, R0.y, R0.z, D0,
R1.x, R1.y, R1.z, D1,
R2.x, R2.y, R2.z, D2,
0.0f, 0.0f, 0.0f, 1.0f
);
return transpose(M);
#endif
}
inline Float4x4 Float4x4::make_world(const Float3& position, const Float3& forward, const Float3& up)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t zaxis = Vector3Normalize(VectorNegate(load_float3a(forward.m)));
vec_float_t yaxis = load_float3a(up.m);
vec_float_t xaxis = Vector3Normalize(Vector3Cross(yaxis, zaxis));
yaxis = Vector3Cross(zaxis, xaxis);
Float4x4 R;
store_float3a(reinterpret_cast<f32*>(&R._11), xaxis);
store_float3a(reinterpret_cast<f32*>(&R._21), yaxis);
store_float3a(reinterpret_cast<f32*>(&R._31), zaxis);
R._14 = R._24 = R._34 = 0.f;
R._41 = position.x; R._42 = position.y; R._43 = position.z;
R._44 = 1.f;
return R;
#else
Float3 zaxis = normalize(-forward);
Float3 yaxis = up;
Float3 xaxis = normalize(cross(yaxis, zaxis));
yaxis = cross(zaxis, xaxis);
Float4x4 R (
xaxis.x, xaxis.y, xaxis.z, 0.0f,
yaxis.x, yaxis.y, yaxis.z, 0.0f,
zaxis.x, zaxis.y, zaxis.z, 0.0f,
position.x, position.y, position.z, 1.0f
);
return R;
#endif
}
inline Float4x4 Float4x4::make_affine_position_rotation_scale(const Float3& position, const Quaternion& rotation, const Float3& scale)
{
#ifdef LUNA_SIMD_ENABLED
using namespace Simd;
vec_float_t s = load_float3a(scale.m);
vec_float_t p = load_float3a(position.m);
vec_float_t q = load_float4a(rotation.m);
vec_float_t zero = vector_set(0.0f, 0.0f, 0.0f, 1.0f);
mat_float_t r = MatrixAffineTransformation(s, zero, q, p);
return Float4x4(r);
#else
lupanic("Not Implemented");
#endif
}
inline Float4x4 Float4x4::make_transform3d(const Tranform3D& transform)
{
return make_affine_position_rotation_scale(transform.position, transform.rotation, transform.scale);
}
} | 24.938464 | 161 | 0.625804 | [
"object",
"vector",
"transform"
] |
60971e8335aa0795320895c8fefc18a37c88c389 | 2,144 | cpp | C++ | OTHERS/codejam practise/min scalar product.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | OTHERS/codejam practise/min scalar product.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | null | null | null | OTHERS/codejam practise/min scalar product.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | #include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#define F(i,L,R) for (int i = L; i < R; i++) //next four are for "for loops"
#define FE(i,L,R) for (int i = L; i <= R; i++)
#define FF(i,L,R) for (int i = L; i > R; i--)
#define FFE(i,L,R) for (int i = L; i >= R; i--)
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define ALL(p) p.begin(),p.end()
#define ALLR(p) p.rbegin(),p.rend()
#define MP(x, y) make_pair(x, y)
#define SET(p) memset(p, -1, sizeof(p))
#define CLR(p) memset(p, 0, sizeof(p))
#define MEM(p, v) memset(p, v, sizeof(p))
#define CPY(d, s) memcpy(d, s, sizeof(s))
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define SZ(c) (int)c.size()
#define PB(x) push_back(x)
#define ff first
#define ss second
#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define ld long double
#define pii pair< int, int >
#define psi pair< string, int >
#define vi vector < int >
#define vii vector < vector < int > >
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
#define PI 3.1415926535897932384626
int main() {
READ("in.in");
WRITE("out.in");
int t;
scanf("%d",&t);
for(int C=1;C<=t;C++)
{
int n;
scanf("%d",&n);
vector < int > x,y;
for(int i=0;i<n;i++)
{
int k;
scanf("%d",&k);
x.PB(k);
}
for(int i=0;i<n;i++)
{
int k;
scanf("%d",&k);
y.PB(k);
}
sort(x.begin(),x.end());
sort(y.rbegin(),y.rend());
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum + (x[i]*y[i]);
}
printf("Case #%d: %d\n",C,sum);
}
return 0;
}
| 23.053763 | 76 | 0.557369 | [
"vector"
] |
6097a08c2f4d98991b484bcd3b4d9bc1c91ce73b | 2,423 | cpp | C++ | code/source/visual/entitylogic_model.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/visual/entitylogic_model.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/visual/entitylogic_model.cpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #include "entitylogic_model.hpp"
#include "entity_def_model.hpp"
#include "entity_mgr.hpp"
#include "global/event.hpp"
#include "util/profiling.hpp"
#include "util/tuple.hpp"
namespace clover {
namespace visual {
ModelEntityLogic::ModelEntityLogic(const ModelEntityDef& def):
EntityLogic(def),
useCustomDrawPriority(false),
customDrawPriority(0){
}
ModelEntityLogic::~ModelEntityLogic(){
}
void ModelEntityLogic::setDrawPriority(DrawPriority p){
useCustomDrawPriority= true;
customDrawPriority= p;
}
ModelEntityLogic::DrawPriority ModelEntityLogic::getDrawPriority() const {
if (useCustomDrawPriority)
return customDrawPriority;
return getDef().getDrawPriority();
}
void ModelEntityLogic::apply(const EntityLogic& other){
EntityLogic::apply(other);
if (other.getDef().getType() == EntityDef::Type::Model){
auto o= static_cast<const ModelEntityLogic*>(&other);
useCustomDrawPriority= o->useCustomDrawPriority;
customDrawPriority= o->useCustomDrawPriority;
colorMul= o->colorMul;
}
}
util::BoundingBox<util::Vec3d> ModelEntityLogic::getBoundingBox() const {
PROFILE();
if (!getDef().getModel())
return BoundingBox::zero();
ensure(getDef().getModel());
auto model_bb= getDef().getModel()->getBoundingBox();
if (!model_bb.isSet())
return BoundingBox::zero();
/// @todo More precise solution
std::array<util::Vec3f, 4> bb_v= {
model_bb.getMin(),
model_bb.getMax(),
util::Vec3f{ model_bb.getMin().x,
model_bb.getMax().y,
model_bb.getMin().z },
util::Vec3f{ model_bb.getMax().x,
model_bb.getMin().y,
model_bb.getMax().z }
};
util::Vec3d rad= util::Vec3d(1.0)*sqrt( std::max({ bb_v[0].lengthSqr(),
bb_v[1].lengthSqr(),
bb_v[2].lengthSqr(),
bb_v[3].lengthSqr()})*
getDef().getOffset().scale.lengthSqr()*
getTransform().scale.lengthSqr());
return util::BoundingBox<util::Vec3d>(-rad, rad);
}
uint32 ModelEntityLogic::getContentHash() const {
return util::hash32(
util::makeTuple(
getDef().getContentHash(),
customDrawPriority,
useCustomDrawPriority,
colorMul,
getTransform()
)
);
}
uint32 ModelEntityLogic::getBatchCompatibilityHash() const {
return util::hash32(
util::makeTuple(
getDef().getBatchCompatibilityHash(),
customDrawPriority,
useCustomDrawPriority,
static_cast<int32>(getLayer())
)
);
}
} // visual
} // clover
| 23.524272 | 74 | 0.695006 | [
"model"
] |
60980f4240d1cb25bbb2381a52477af618d78c85 | 1,388 | cpp | C++ | src/LowPassFilter.cpp | dwes7/bobble_controllers | 8d33153bdc33a7dc3bfbf9996df80a0ffde3dda2 | [
"BSD-3-Clause"
] | 64 | 2019-04-20T09:23:59.000Z | 2022-03-22T06:14:56.000Z | src/LowPassFilter.cpp | dwes7/bobble_controllers | 8d33153bdc33a7dc3bfbf9996df80a0ffde3dda2 | [
"BSD-3-Clause"
] | 13 | 2019-08-12T19:27:34.000Z | 2022-03-22T05:56:16.000Z | src/LowPassFilter.cpp | dwes7/bobble_controllers | 8d33153bdc33a7dc3bfbf9996df80a0ffde3dda2 | [
"BSD-3-Clause"
] | 18 | 2019-04-22T19:48:19.000Z | 2021-08-05T14:02:00.000Z | //
// Created by james on 3/28/20.
//
#include <bobble_controllers/LowPassFilter.h>
LowPassFilter::LowPassFilter(double Ts, double fc, double zeta) {
resetFilterParameters(Ts, fc, zeta);
}
void LowPassFilter::resetFilterParameters(double Ts, double fc, double zeta) {
/// Initialize buffers to 0
initBuffer(_inputBuffer, 3);
initBuffer(_outputBuffer, 3);
_numInWeights = 3;
_numOutWeights = 3;
double wc = 2.0 * M_PI * fc;
/// The following calculations are the implementation of a second order high pass filter
/// converted from continuous space to discrete space using the bilinear transform.
/// The continuous time filter is 1 / (s^2 + 2*zeta*wc*s + wc^2)
double numeratorWeights[3] = {Ts*Ts*wc*wc, 2*Ts*Ts*wc*wc, Ts*Ts*wc*wc};
double denominatorWeights[3] = {Ts*Ts*wc*wc+4*Ts*wc*zeta+4,
2*Ts*Ts*wc*wc-8,
Ts*Ts*wc*wc-4*Ts*wc*zeta+4};
/// First initialize all weights to 0.0
for (unsigned int i = 0; i<MAX_FILTER_SIZE; i++){
_inputWeights[i] = 0.0;
_outputWeights[i] = 0.0;
}
/// Apply the passed in weights.
for (unsigned int i = 0; i<_numInWeights; i++){
_inputWeights[i] = numeratorWeights[i];
}
for (unsigned int i = 0; i<_numOutWeights; i++){
_outputWeights[i] = denominatorWeights[i];
}
}
| 33.047619 | 92 | 0.620317 | [
"transform"
] |
6099022a23a64a3bea83675e1b3e428978d2adc1 | 9,123 | hpp | C++ | include/System/Security/Cryptography/TripleDES.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Security/Cryptography/TripleDES.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Security/Cryptography/TripleDES.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Security.Cryptography.SymmetricAlgorithm
#include "System/Security/Cryptography/SymmetricAlgorithm.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: KeySizes
class KeySizes;
}
// Completed forward declares
// Type namespace: System.Security.Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: TripleDES
class TripleDES;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Security::Cryptography::TripleDES);
DEFINE_IL2CPP_ARG_TYPE(::System::Security::Cryptography::TripleDES*, "System.Security.Cryptography", "TripleDES");
// Type namespace: System.Security.Cryptography
namespace System::Security::Cryptography {
// Size: 0x44
#pragma pack(push, 1)
// Autogenerated type: System.Security.Cryptography.TripleDES
// [TokenAttribute] Offset: FFFFFFFF
// [ComVisibleAttribute] Offset: 684890
class TripleDES : public ::System::Security::Cryptography::SymmetricAlgorithm {
public:
// Get static field: static private System.Security.Cryptography.KeySizes[] s_legalBlockSizes
static ::ArrayW<::System::Security::Cryptography::KeySizes*> _get_s_legalBlockSizes();
// Set static field: static private System.Security.Cryptography.KeySizes[] s_legalBlockSizes
static void _set_s_legalBlockSizes(::ArrayW<::System::Security::Cryptography::KeySizes*> value);
// Get static field: static private System.Security.Cryptography.KeySizes[] s_legalKeySizes
static ::ArrayW<::System::Security::Cryptography::KeySizes*> _get_s_legalKeySizes();
// Set static field: static private System.Security.Cryptography.KeySizes[] s_legalKeySizes
static void _set_s_legalKeySizes(::ArrayW<::System::Security::Cryptography::KeySizes*> value);
// static private System.Void .cctor()
// Offset: 0x12ACAAC
static void _cctor();
// static public System.Security.Cryptography.TripleDES Create()
// Offset: 0x12AC7C0
static ::System::Security::Cryptography::TripleDES* Create();
// static public System.Boolean IsWeakKey(System.Byte[] rgbKey)
// Offset: 0x12AC4A0
static bool IsWeakKey(::ArrayW<uint8_t> rgbKey);
// static private System.Boolean EqualBytes(System.Byte[] rgbKey, System.Int32 start1, System.Int32 start2, System.Int32 count)
// Offset: 0x12AC908
static bool EqualBytes(::ArrayW<uint8_t> rgbKey, int start1, int start2, int count);
// static private System.Boolean IsLegalKeySize(System.Byte[] rgbKey)
// Offset: 0x12AC8E4
static bool IsLegalKeySize(::ArrayW<uint8_t> rgbKey);
// public override System.Byte[] get_Key()
// Offset: 0x12AC3C4
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Byte[] SymmetricAlgorithm::get_Key()
::ArrayW<uint8_t> get_Key();
// public override System.Void set_Key(System.Byte[] value)
// Offset: 0x12AC5F4
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::set_Key(System.Byte[] value)
void set_Key(::ArrayW<uint8_t> value);
// protected System.Void .ctor()
// Offset: 0x12AC330
// Implemented from: System.Security.Cryptography.SymmetricAlgorithm
// Base method: System.Void SymmetricAlgorithm::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TripleDES* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Security::Cryptography::TripleDES::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TripleDES*, creationType>()));
}
}; // System.Security.Cryptography.TripleDES
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Security::Cryptography::TripleDES::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::Create
// Il2CppName: Create
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::TripleDES* (*)()>(&System::Security::Cryptography::TripleDES::Create)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), "Create", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::IsWeakKey
// Il2CppName: IsWeakKey
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::ArrayW<uint8_t>)>(&System::Security::Cryptography::TripleDES::IsWeakKey)> {
static const MethodInfo* get() {
static auto* rgbKey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), "IsWeakKey", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rgbKey});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::EqualBytes
// Il2CppName: EqualBytes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::ArrayW<uint8_t>, int, int, int)>(&System::Security::Cryptography::TripleDES::EqualBytes)> {
static const MethodInfo* get() {
static auto* rgbKey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* start1 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* start2 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), "EqualBytes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rgbKey, start1, start2, count});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::IsLegalKeySize
// Il2CppName: IsLegalKeySize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::ArrayW<uint8_t>)>(&System::Security::Cryptography::TripleDES::IsLegalKeySize)> {
static const MethodInfo* get() {
static auto* rgbKey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), "IsLegalKeySize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rgbKey});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::get_Key
// Il2CppName: get_Key
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (System::Security::Cryptography::TripleDES::*)()>(&System::Security::Cryptography::TripleDES::get_Key)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), "get_Key", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::set_Key
// Il2CppName: set_Key
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::TripleDES::*)(::ArrayW<uint8_t>)>(&System::Security::Cryptography::TripleDES::set_Key)> {
static const MethodInfo* get() {
static auto* value = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::TripleDES*), "set_Key", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::TripleDES::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 59.24026 | 199 | 0.74208 | [
"object",
"vector"
] |
609abf8963e628a824ebe502a2ae559e63cd1c78 | 24,618 | cpp | C++ | src/asset_loader.cpp | atxi/Polymer | ca1bdb59ff425ec4496380ccf860ff7aaa86cab0 | [
"MIT"
] | 21 | 2020-12-14T05:25:41.000Z | 2022-03-23T15:30:19.000Z | src/asset_loader.cpp | atxi/Polymer | ca1bdb59ff425ec4496380ccf860ff7aaa86cab0 | [
"MIT"
] | 1 | 2021-01-27T17:56:16.000Z | 2021-01-28T17:31:30.000Z | src/asset_loader.cpp | atxi/Polymer | ca1bdb59ff425ec4496380ccf860ff7aaa86cab0 | [
"MIT"
] | null | null | null | #include "asset_loader.h"
#include "stb_image.h"
#include <cstdio>
#include <cstring>
namespace polymer {
constexpr size_t kTextureSize = 16 * 16 * 4;
u32 Hash(const char* str) {
u32 hash = 5381;
char c;
while (c = *str++) {
hash = hash * 33 ^ c;
}
return hash;
}
u32 Hash(const char* str, size_t len) {
u32 hash = 5381;
for (size_t i = 0; i < len; ++i) {
hash = hash * 33 ^ str[i];
}
return hash;
}
TextureIdMap::TextureIdMap(MemoryArena* arena) : arena(arena), free(nullptr) {
for (size_t i = 0; i < kTextureIdBuckets; ++i) {
elements[i] = nullptr;
}
for (size_t i = 0; i < 1024; ++i) {
TextureIdElement* element = memory_arena_push_type(arena, TextureIdElement);
element->next = free;
free = element;
}
}
TextureIdElement* TextureIdMap::Allocate() {
TextureIdElement* result = nullptr;
if (free) {
result = free;
free = free->next;
} else {
result = memory_arena_push_type(arena, TextureIdElement);
}
result->next = nullptr;
return result;
}
void TextureIdMap::Insert(const char* name, u32 value) {
u32 bucket = Hash(name) & (kTextureIdBuckets - 1);
TextureIdElement* element = elements[bucket];
while (element) {
if (strcmp(element->name, name) == 0) {
break;
}
element = element->next;
}
if (element == nullptr) {
element = Allocate();
assert(strlen(name) < polymer_array_count(element->name));
strcpy(element->name, name);
element->value = value;
element->next = elements[bucket];
elements[bucket] = element;
}
}
u32* TextureIdMap::Find(const char* name) {
u32 bucket = Hash(name) & (kTextureIdBuckets - 1);
TextureIdElement* element = elements[bucket];
while (element) {
if (strcmp(element->name, name) == 0) {
return &element->value;
}
element = element->next;
}
return nullptr;
}
FaceTextureMap::FaceTextureMap(MemoryArena* arena) : arena(arena), free(nullptr) {
for (size_t i = 0; i < kTextureMapBuckets; ++i) {
elements[i] = nullptr;
}
for (size_t i = 0; i < 32; ++i) {
FaceTextureElement* element = memory_arena_push_type(arena, FaceTextureElement);
element->next = free;
free = element;
}
}
FaceTextureElement* FaceTextureMap::Allocate() {
FaceTextureElement* result = nullptr;
if (free) {
result = free;
free = free->next;
} else {
result = memory_arena_push_type(arena, FaceTextureElement);
}
result->next = nullptr;
return result;
}
void FaceTextureMap::Insert(const char* name, size_t namelen, const char* value, size_t valuelen) {
u32 bucket = Hash(name, namelen) & (kTextureMapBuckets - 1);
FaceTextureElement* element = elements[bucket];
while (element) {
if (strcmp(element->name, name) == 0) {
break;
}
element = element->next;
}
if (element == nullptr) {
element = Allocate();
assert(namelen < polymer_array_count(element->name));
assert(valuelen < polymer_array_count(element->value));
strncpy(element->name, name, namelen);
strncpy(element->value, value, valuelen);
element->name[namelen] = 0;
element->value[valuelen] = 0;
element->next = elements[bucket];
elements[bucket] = element;
}
}
const char* FaceTextureMap::Find(const char* name, size_t namelen) {
u32 bucket = Hash(name, namelen) & (kTextureMapBuckets - 1);
FaceTextureElement* element = elements[bucket];
while (element) {
if (strncmp(element->name, name, namelen) == 0) {
return element->value;
}
element = element->next;
}
return nullptr;
}
void ParsedBlockModel::InsertTextureMap(FaceTextureMap* map) {
json_object_element_s* root_element = root->start;
while (root_element) {
if (strcmp(root_element->name->string, "textures") == 0) {
json_object_element_s* texture_element = json_value_as_object(root_element->value)->start;
while (texture_element) {
json_string_s* value_string = json_value_as_string(texture_element->value);
map->Insert(texture_element->name->string, texture_element->name->string_size, value_string->string,
value_string->string_size);
texture_element = texture_element->next;
}
break;
}
root_element = root_element->next;
}
}
void ParsedBlockModel::InsertElements(BlockModel* model, FaceTextureMap* texture_face_map,
TextureIdMap* texture_id_map) {
json_object_element_s* root_element = root->start;
while (root_element) {
if (strcmp(root_element->name->string, "elements") == 0) {
json_array_s* element_array = json_value_as_array(root_element->value);
json_array_element_s* element_array_element = element_array->start;
while (element_array_element) {
json_object_s* element_obj = json_value_as_object(element_array_element->value);
model->elements[model->element_count].shade = true;
json_object_element_s* element_property = element_obj->start;
while (element_property) {
const char* property_name = element_property->name->string;
if (strcmp(property_name, "from") == 0) {
json_array_element_s* vector_element = json_value_as_array(element_property->value)->start;
for (int i = 0; i < 3; ++i) {
model->elements[model->element_count].from[i] =
strtol(json_value_as_number(vector_element->value)->number, nullptr, 10) / 16.0f;
vector_element = vector_element->next;
}
} else if (strcmp(property_name, "to") == 0) {
json_array_element_s* vector_element = json_value_as_array(element_property->value)->start;
for (int i = 0; i < 3; ++i) {
model->elements[model->element_count].to[i] =
strtol(json_value_as_number(vector_element->value)->number, nullptr, 10) / 16.0f;
vector_element = vector_element->next;
}
} else if (strcmp(property_name, "shade") == 0) {
model->elements[model->element_count].shade = json_value_is_true(element_property->value);
} else if (strcmp(property_name, "faces") == 0) {
json_object_element_s* face_obj_element = json_value_as_object(element_property->value)->start;
while (face_obj_element) {
const char* facename = face_obj_element->name->string;
size_t face_index = 0;
if (strcmp(facename, "down") == 0) {
face_index = 0;
} else if (strcmp(facename, "up") == 0) {
face_index = 1;
} else if (strcmp(facename, "north") == 0) {
face_index = 2;
} else if (strcmp(facename, "south") == 0) {
face_index = 3;
} else if (strcmp(facename, "west") == 0) {
face_index = 4;
} else if (strcmp(facename, "east") == 0) {
face_index = 5;
}
json_object_element_s* face_element = json_value_as_object(face_obj_element->value)->start;
RenderableFace* face = model->elements[model->element_count].faces + face_index;
face->uv_from = Vector2f(0, 0);
face->uv_to = Vector2f(1, 1);
face->render = true;
face->tintindex = 0xFFFF;
while (face_element) {
const char* face_property = face_element->name->string;
if (strcmp(face_property, "texture") == 0) {
json_string_s* texture_str = json_value_as_string(face_element->value);
const char* texture_name = texture_str->string;
size_t namelen = texture_str->string_size;
while (texture_name[0] == '#') {
texture_name = texture_face_map->Find(texture_name + 1, namelen - 1);
if (texture_name == nullptr) {
return;
}
namelen = strlen(texture_name);
}
size_t prefix_size = 6;
if (strstr(texture_name, ":")) {
prefix_size = 16;
}
char lookup[1024];
sprintf(lookup, "%.*s.png", (u32)(namelen - prefix_size), texture_name + prefix_size);
u32* texture_id = texture_id_map->Find(lookup);
if (texture_id) {
face->texture_id = *texture_id;
} else {
face->texture_id = 0;
}
} else if (strcmp(face_property, "uv") == 0) {
Vector2f uv_from;
Vector2f uv_to;
json_array_element_s* value = json_value_as_array(face_element->value)->start;
uv_from[0] = strtol(json_value_as_number(value->value)->number, nullptr, 10) / 16.0f;
value = value->next;
uv_from[1] = strtol(json_value_as_number(value->value)->number, nullptr, 10) / 16.0f;
value = value->next;
uv_to[0] = strtol(json_value_as_number(value->value)->number, nullptr, 10) / 16.0f;
value = value->next;
uv_to[1] = strtol(json_value_as_number(value->value)->number, nullptr, 10) / 16.0f;
face->uv_from = uv_from;
face->uv_to = uv_to;
} else if (strcmp(face_property, "tintindex") == 0) {
face->tintindex = (u32)strtol(json_value_as_number(face_element->value)->number, nullptr, 10);
// if (strstr(path, "leaves") != 0) {
// face->tintindex = 1;
//}
}
face_element = face_element->next;
}
face_obj_element = face_obj_element->next;
}
}
element_property = element_property->next;
}
++model->element_count;
assert(model->element_count < polymer_array_count(model->elements));
element_array_element = element_array_element->next;
}
}
root_element = root_element->next;
}
}
AssetLoader::~AssetLoader() {
Cleanup();
}
bool AssetLoader::OpenArchive(const char* filename) {
snapshot = arena->GetSnapshot();
return archive.Open(filename);
}
void AssetLoader::CloseArchive() {
archive.Close();
arena->Revert(snapshot);
}
bool AssetLoader::Load(const char* jar_path, const char* blocks_path) {
if (!OpenArchive(jar_path)) {
return false;
}
if (ParseBlockModels() == 0) {
CloseArchive();
return false;
}
if (ParseBlockStates() == 0) {
CloseArchive();
return false;
}
if (LoadTextures() == 0) {
CloseArchive();
return false;
}
if (!ParseBlocks(blocks_path)) {
CloseArchive();
return false;
}
for (size_t i = 0; i < state_count; ++i) {
json_object_element_s* root_element = states[i].root->start;
char* blockstate_filename = states[i].filename;
blockstate_filename[strlen(blockstate_filename) - 5] = 0;
while (root_element) {
if (strncmp("variants", root_element->name->string, root_element->name->string_size) == 0) {
json_object_s* variant_obj = json_value_as_object(root_element->value);
for (size_t bid = 0; bid < final_state_count; ++bid) {
char* name = final_states[bid].info->name + 10;
if (final_states[bid].model.element_count > 0) {
continue;
}
if (strcmp(name, blockstate_filename) != 0) {
continue;
}
json_object_element_s* variant_element = variant_obj->start;
while (variant_element) {
const char* variant_name = variant_element->name->string;
if ((variant_element->name->string_size == 0 && properties[bid] == nullptr) ||
(properties[bid] != nullptr && strcmp(variant_name, properties[bid]) == 0) ||
variant_element->next == nullptr) {
json_object_s* state_details = nullptr;
if (variant_element->value->type == json_type_array) {
// TODO: Find out why multiple models are listed under one variant type. Just default to first for now.
state_details = json_value_as_object(json_value_as_array(variant_element->value)->start->value);
} else {
state_details = json_value_as_object(variant_element->value);
}
json_object_element_s* state_element = state_details->start;
while (state_element) {
if (strcmp(state_element->name->string, "model") == 0) {
json_string_s* model_name_str = json_value_as_string(state_element->value);
// Do a lookup on the model name then store the model in the BlockState.
// Model lookup is going to need to be recursive with the root parent data being filled out first then
// cascaded down.
const size_t kPrefixSize = 16;
ArenaSnapshot snapshot = arena->GetSnapshot();
FaceTextureMap texture_face_map(arena);
final_states[bid].model =
LoadModel(model_name_str->string + kPrefixSize, model_name_str->string_size - kPrefixSize,
&texture_face_map, &texture_id_map);
arena->Revert(snapshot);
variant_element = nullptr;
break;
}
state_element = state_element->next;
}
}
if (variant_element) {
variant_element = variant_element->next;
}
}
}
}
root_element = root_element->next;
}
blockstate_filename[strlen(blockstate_filename) - 5] = '.';
}
CloseArchive();
return true;
}
BlockModel AssetLoader::LoadModel(const char* path, size_t path_size, FaceTextureMap* texture_face_map,
TextureIdMap* texture_id_map) {
BlockModel result = {};
ParsedBlockModel* parsed_model = nullptr;
const size_t kPrefixSkip = 30;
for (size_t i = 0; i < model_count; ++i) {
char* check = models[i].filename + kPrefixSkip;
if (strcmp(check, path) == 0) {
parsed_model = models + i;
break;
}
}
if (parsed_model == nullptr) {
return result;
}
parsed_model->InsertTextureMap(texture_face_map);
parsed_model->InsertElements(&result, texture_face_map, texture_id_map);
json_object_element_s* root_element = parsed_model->root->start;
while (root_element) {
if (strcmp(root_element->name->string, "parent") == 0) {
size_t prefix_size = 6;
json_string_s* parent_name = json_value_as_string(root_element->value);
for (size_t i = 0; i < parent_name->string_size; ++i) {
if (parent_name->string[i] == ':') {
prefix_size = 16;
break;
}
}
BlockModel parent =
LoadModel(parent_name->string + prefix_size, parent_name->string_size, texture_face_map, texture_id_map);
for (size_t i = 0; i < parent.element_count; ++i) {
result.elements[result.element_count++] = parent.elements[i];
assert(result.element_count < polymer_array_count(result.elements));
}
}
root_element = root_element->next;
}
for (size_t i = 0; i < result.element_count; ++i) {
BlockElement* element = result.elements + i;
element->occluding = element->from == Vector3f(0, 0, 0) && element->to == Vector3f(1, 1, 1);
}
return result;
}
bool AssetLoader::ParseBlocks(const char* blocks_filename) {
FILE* f = fopen(blocks_filename, "r");
fseek(f, 0, SEEK_END);
long file_size = ftell(f);
fseek(f, 0, SEEK_SET);
char* buffer = memory_arena_push_type_count(arena, char, file_size);
fread(buffer, 1, file_size, f);
fclose(f);
json_value_s* root = json_parse(buffer, file_size);
assert(root->type == json_type_object);
json_object_s* root_obj = json_value_as_object(root);
assert(root_obj);
assert(root_obj->length > 0);
final_state_count = (size_t)GetLastStateId(root_obj) + 1;
assert(final_state_count > 1);
// Create a list of pointers to property strings stored in the transient arena
properties = (char**)arena->Allocate(sizeof(char*) * final_state_count);
final_states = memory_arena_push_type_count(perm_arena, BlockState, final_state_count);
block_infos = (BlockStateInfo*)memory_arena_push_type_count(perm_arena, BlockStateInfo, root_obj->length);
json_object_element_s* element = root_obj->start;
size_t block_state_index = 0;
while (element) {
json_object_s* block_obj = json_value_as_object(element->value);
assert(block_obj);
BlockStateInfo* info = block_infos + block_info_count++;
assert(element->name->string_size < polymer_array_count(info->name));
memcpy(info->name, element->name->string, element->name->string_size);
json_object_element_s* block_element = block_obj->start;
while (block_element) {
if (strncmp(block_element->name->string, "states", block_element->name->string_size) == 0) {
json_array_s* states = json_value_as_array(block_element->value);
json_array_element_s* state_array_element = states->start;
while (state_array_element) {
json_object_s* state_obj = json_value_as_object(state_array_element->value);
properties[block_state_index] = nullptr;
json_object_element_s* state_element = state_obj->start;
u32 id = 0;
size_t index = 0;
while (state_element) {
if (strncmp(state_element->name->string, "id", state_element->name->string_size) == 0) {
final_states[block_state_index].info = info;
long block_id = strtol(json_value_as_number(state_element->value)->number, nullptr, 10);
final_states[block_state_index].id = block_id;
id = (u32)block_id;
index = block_state_index;
++block_state_index;
}
state_element = state_element->next;
}
state_element = state_obj->start;
while (state_element) {
if (strncmp(state_element->name->string, "properties", state_element->name->string_size) == 0) {
// Loop over each property and create a single string that matches the format of blockstates in the jar
json_object_s* property_object = json_value_as_object(state_element->value);
json_object_element_s* property_element = property_object->start;
// Realign the arena for the property pointer to be 32-bit aligned.
char* property = (char*)arena->Allocate(0, 4);
properties[index] = property;
size_t property_length = 0;
while (property_element) {
json_string_s* property_value = json_value_as_string(property_element->value);
if (strcmp(property_element->name->string, "waterlogged") == 0) {
property_element = property_element->next;
continue;
}
// Allocate enough for property_name=property_value
size_t alloc_size = property_element->name->string_size + 1 + property_value->string_size;
property_length += alloc_size;
char* p = (char*)arena->Allocate(alloc_size, 1);
// Allocate space for a comma to separate the properties
if (property_element != property_object->start) {
arena->Allocate(1, 1);
p[0] = ',';
++p;
++property_length;
}
memcpy(p, property_element->name->string, property_element->name->string_size);
p[property_element->name->string_size] = '=';
memcpy(p + property_element->name->string_size + 1, property_value->string,
property_value->string_size);
property_element = property_element->next;
}
arena->Allocate(1, 1);
properties[index][property_length] = 0;
}
state_element = state_element->next;
}
state_array_element = state_array_element->next;
}
}
block_element = block_element->next;
}
element = element->next;
}
free(root);
return true;
}
u32 AssetLoader::GetLastStateId(json_object_s* root) {
json_object_element_s* last_root_ele = root->start;
for (size_t i = 0; i < root->length - 1; ++i) {
last_root_ele = last_root_ele->next;
}
json_object_s* block_obj = json_value_as_object(last_root_ele->value);
json_object_element_s* block_element = block_obj->start;
while (block_element) {
if (strncmp(block_element->name->string, "states", block_element->name->string_size) == 0) {
json_array_s* states = json_value_as_array(block_element->value);
json_array_element_s* state_array_element = states->start;
assert(states->length > 0);
for (size_t i = 0; i < states->length - 1; ++i) {
state_array_element = state_array_element->next;
}
json_object_s* state_obj = json_value_as_object(state_array_element->value);
json_object_element_s* state_element = state_obj->start;
while (state_element) {
if (strncmp(state_element->name->string, "id", state_element->name->string_size) == 0) {
return (u32)strtol(json_value_as_number(state_element->value)->number, nullptr, 10);
}
state_element = state_element->next;
}
}
block_element = block_element->next;
}
return 0;
}
size_t AssetLoader::LoadTextures() {
ZipArchiveElement* texture_files = archive.ListFiles(arena, "assets/minecraft/textures/block/", &texture_count);
if (texture_count == 0) {
return 0;
}
this->texture_images = memory_arena_push_type_count(arena, u8, kTextureSize * texture_count);
for (u32 i = 0; i < texture_count; ++i) {
size_t size = 0;
u8* raw_image = (u8*)archive.ReadFile(arena, texture_files[i].name, &size);
int width, height, channels;
// TODO: Can it be loaded directly into memory?
stbi_uc* image = stbi_load_from_memory(raw_image, (int)size, &width, &height, &channels, STBI_rgb_alpha);
if (image == nullptr) {
continue;
}
char* texture_name = texture_files[i].name + 32;
this->texture_id_map.Insert(texture_name, i);
u8* destination = texture_images + i * kTextureSize;
memcpy(destination, image, kTextureSize);
stbi_image_free(image);
}
return texture_count;
}
size_t AssetLoader::ParseBlockStates() {
// Amount of characters to skip over to get to the blockstate asset name
constexpr size_t kBlockStateAssetSkip = 29;
ZipArchiveElement* state_files = archive.ListFiles(arena, "assets/minecraft/blockstates/", &state_count);
if (state_count == 0) {
return 0;
}
states = memory_arena_push_type_count(arena, ParsedBlockState, state_count);
for (size_t i = 0; i < state_count; ++i) {
size_t file_size;
char* data = archive.ReadFile(arena, state_files[i].name, &file_size);
assert(data);
states[i].root_value = json_parse(data, file_size);
states[i].root = json_value_as_object(states[i].root_value);
strcpy(states[i].filename, state_files[i].name + kBlockStateAssetSkip);
}
return state_count;
}
size_t AssetLoader::ParseBlockModels() {
ZipArchiveElement* files = archive.ListFiles(arena, "assets/minecraft/models/block", &model_count);
models = memory_arena_push_type_count(arena, ParsedBlockModel, model_count);
for (size_t i = 0; i < model_count; ++i) {
size_t size = 0;
char* data = archive.ReadFile(arena, files[i].name, &size);
assert(data);
strcpy(models[i].filename, files[i].name);
char* separator = strstr(models[i].filename, ".");
if (separator) {
*separator = 0;
}
models[i].root_value = json_parse(data, size);
assert(models[i].root_value->type == json_type_object);
models[i].root = json_value_as_object(models[i].root_value);
}
return model_count;
}
u8* AssetLoader::GetTexture(size_t index) {
assert(index < texture_count);
return texture_images + index * kTextureSize;
}
void AssetLoader::Cleanup() {
for (size_t i = 0; i < model_count; ++i) {
free(models[i].root_value);
}
model_count = 0;
CloseArchive();
}
} // namespace polymer
| 31.40051 | 120 | 0.614307 | [
"render",
"model"
] |
609c0f90c5307922696eabf7a69f2709f4f16755 | 19,317 | cpp | C++ | source/loaders/js_loader/source/js_loader_impl.cpp | 0xAnarz/core | 0c9310d9c9c2074782b3641a639b1e1a931f1afe | [
"Apache-2.0"
] | 928 | 2018-12-26T22:40:59.000Z | 2022-03-31T12:17:43.000Z | source/loaders/js_loader/source/js_loader_impl.cpp | 0xAnarz/core | 0c9310d9c9c2074782b3641a639b1e1a931f1afe | [
"Apache-2.0"
] | 132 | 2019-03-01T21:01:17.000Z | 2022-03-17T09:00:42.000Z | source/loaders/js_loader/source/js_loader_impl.cpp | 0xAnarz/core | 0c9310d9c9c2074782b3641a639b1e1a931f1afe | [
"Apache-2.0"
] | 112 | 2019-01-15T09:36:11.000Z | 2022-03-12T06:39:01.000Z | /*
* Loader Library by Parra Studios
* A plugin for loading javascript code at run-time into a process.
*
* Copyright (C) 2016 - 2021 Vicente Eduardo Ferrer Garcia <vic798@gmail.com>
*
* 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 <js_loader/js_loader_impl.h>
#include <js_loader/js_loader_impl_guard.hpp>
#include <loader/loader.h>
#include <loader/loader_impl.h>
#include <reflect/reflect_context.h>
#include <reflect/reflect_function.h>
#include <reflect/reflect_scope.h>
#include <reflect/reflect_type.h>
#include <log/log.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <new>
#include <streambuf>
#include <string>
#include <libplatform/libplatform.h>
#include <v8.h> /* version: 5.1.117 */
#ifdef ENABLE_DEBUGGER_SUPPORT
#include <v8-debug.h>
#endif /* ENALBLE_DEBUGGER_SUPPORT */
using namespace v8;
MaybeLocal<String> js_loader_impl_read_script(Isolate *isolate, const loader_naming_path path, std::map<std::string, js_function *> &functions);
MaybeLocal<String> js_loader_impl_read_script(Isolate *isolate, const char *buffer, size_t size, std::map<std::string, js_function *> &functions);
void js_loader_impl_obj_to_string(Handle<Value> object, std::string &str);
function_interface function_js_singleton();
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator
{
public:
virtual void *Allocate(size_t length)
{
void *data = AllocateUninitialized(length);
if (data != NULL)
{
return memset(data, 0, length);
}
return NULL;
}
virtual void *AllocateUninitialized(size_t length)
{
return malloc(length);
}
virtual void Free(void *data, size_t)
{
free(data);
}
};
typedef struct loader_impl_js_type
{
Platform *platform;
Isolate *isolate;
Isolate::CreateParams isolate_create_params;
Isolate::Scope *isolate_scope;
ArrayBufferAllocator allocator;
} * loader_impl_js;
typedef class loader_impl_js_function_type
{
public:
loader_impl_js_function_type(loader_impl_js js_impl, Local<Context> &ctx_impl,
Isolate *isolate, Local<Function> func) :
js_impl(js_impl), ctx_impl(ctx_impl), isolate_ref(isolate), p_func(isolate, func)
{
}
loader_impl_js get_js_impl()
{
return js_impl;
}
Local<Context> &get_ctx_impl()
{
return ctx_impl;
}
Isolate *get_isolate()
{
return isolate_ref;
}
Local<Function> materialize_handle()
{
return Local<Function>::New(isolate_ref, p_func);
}
~loader_impl_js_function_type()
{
p_func.Reset();
}
private:
loader_impl_js js_impl;
Local<Context> &ctx_impl;
Isolate *isolate_ref;
Persistent<Function> p_func;
} * loader_impl_js_function;
typedef class loader_impl_js_handle_type
{
public:
loader_impl_js_handle_type(loader_impl impl, loader_impl_js js_impl,
const loader_naming_path paths[], size_t size) :
impl(impl),
handle_scope(js_impl->isolate),
ctx_impl(Context::New(js_impl->isolate)),
ctx_scope(ctx_impl)
{
for (size_t i = 0; i < size; ++i)
{
Local<String> source = js_loader_impl_read_script(js_impl->isolate, paths[i], functions).ToLocalChecked();
script = Script::Compile(ctx_impl, source).ToLocalChecked();
Local<Value> result = script->Run(ctx_impl).ToLocalChecked();
String::Utf8Value utf8(result);
log_write("metacall", LOG_LEVEL_DEBUG, "JS load from file result: %s", *utf8);
}
}
loader_impl_js_handle_type(loader_impl impl, loader_impl_js js_impl,
const char *buffer, size_t size) :
impl(impl),
handle_scope(js_impl->isolate),
ctx_impl(Context::New(js_impl->isolate)),
ctx_scope(ctx_impl)
{
Local<String> source = js_loader_impl_read_script(js_impl->isolate, buffer, size, functions).ToLocalChecked();
script = Script::Compile(ctx_impl, source).ToLocalChecked();
Local<Value> result = script->Run(ctx_impl).ToLocalChecked();
String::Utf8Value utf8(result);
log_write("metacall", LOG_LEVEL_DEBUG, "JS load from file result: %s", *utf8);
}
int discover(loader_impl_js js_impl, context ctx)
{
Local<Object> global = ctx_impl->Global();
Local<Array> prop_array = global->GetOwnPropertyNames(ctx_impl).ToLocalChecked();
return discover_functions(js_impl, ctx, prop_array);
}
int discover_functions(loader_impl_js js_impl, context ctx, Local<Array> func_array)
{
int length = func_array->Length();
for (int i = 0; i < length; ++i)
{
Local<Value> element = func_array->Get(i);
Local<Value> func_val;
if (ctx_impl->Global()->Get(ctx_impl, element).ToLocal(&func_val) &&
func_val->IsFunction())
{
Local<Function> func = Local<Function>::Cast(func_val);
loader_impl_js_function js_func = new loader_impl_js_function_type(js_impl, ctx_impl, js_impl->isolate, func);
int arg_count = discover_function_args_count(js_impl, func);
if (arg_count >= 0)
{
std::string func_name, func_obj_name;
js_loader_impl_obj_to_string(element, func_name);
js_loader_impl_obj_to_string(func, func_obj_name);
log_write("metacall", LOG_LEVEL_DEBUG,
"Function (%d) { %s, %d-arity } => %s",
i, func_name.c_str(), func_obj_name.c_str());
function f = function_create(func_name.c_str(),
arg_count,
static_cast<void *>(js_func),
&function_js_singleton);
if (f != NULL)
{
if (discover_function_signature(f) == 0)
{
scope sp = context_scope(ctx);
if (scope_define(sp, function_name(f), value_create_function(f)) != 0)
{
return 1;
}
}
}
}
}
}
return 0;
}
int discover_function_signature(function f)
{
signature s = function_signature(f);
std::map<std::string, js_function *>::iterator func_it;
func_it = functions.find(function_name(f));
if (func_it != functions.end())
{
js_function *js_f = func_it->second;
parameter_list::iterator param_it;
type ret_type = loader_impl_type(impl, js_f->return_type.c_str());
signature_set_return(s, ret_type);
for (param_it = js_f->parameters.begin();
param_it != js_f->parameters.end(); ++param_it)
{
type t = loader_impl_type(impl, param_it->type.c_str());
signature_set(s, param_it->index, param_it->name.c_str(), t);
}
return 0;
}
return 1;
}
int discover_function_args_count(loader_impl_js js_impl, Local<Function> func)
{
Local<String> length_name = String::NewFromUtf8(js_impl->isolate,
"length", NewStringType::kNormal)
.ToLocalChecked();
Local<Value> length_val;
if (func->Get(ctx_impl, length_name).ToLocal(&length_val) && length_val->IsNumber())
{
return length_val->Int32Value();
}
return -1;
}
~loader_impl_js_handle_type()
{
std::map<std::string, js_function *>::iterator it;
for (it = functions.begin(); it != functions.end(); ++it)
{
js_function *js_f = it->second;
delete js_f;
}
}
private:
loader_impl impl;
std::map<std::string, js_function *> functions;
HandleScope handle_scope;
Local<Context> ctx_impl;
Context::Scope ctx_scope;
Local<Script> script;
} * loader_impl_js_handle;
int function_js_interface_create(function func, function_impl impl)
{
(void)func;
(void)impl;
return 0;
}
function_return function_js_interface_invoke(function func, function_impl impl, function_args args, size_t size)
{
loader_impl_js_function js_func = static_cast<loader_impl_js_function>(impl);
Local<Function> func_impl_local = js_func->materialize_handle();
signature s = function_signature(func);
Local<Value> result;
if (size > 0)
{
std::vector<Local<Value>> value_args(size);
size_t args_count;
for (args_count = 0; args_count < size; ++args_count)
{
type t = signature_get_type(s, args_count);
type_id id = TYPE_INVALID;
if (t == NULL)
{
id = value_type_id((value)args[args_count]);
}
else
{
id = type_index(t);
}
if (id == TYPE_BOOL)
{
boolean *value_ptr = (boolean *)(args[args_count]);
bool b = (*value_ptr == 1) ? true : false;
value_args[args_count] = Boolean::New(js_func->get_isolate(), b);
}
else if (id == TYPE_INT)
{
int *value_ptr = (int *)(args[args_count]);
value_args[args_count] = Int32::New(js_func->get_isolate(), *value_ptr);
}
else if (id == TYPE_LONG)
{
long *value_ptr = (long *)(args[args_count]);
value_args[args_count] = Integer::New(js_func->get_isolate(), *value_ptr);
}
else if (id == TYPE_FLOAT)
{
float *value_ptr = (float *)(args[args_count]);
value_args[args_count] = Number::New(js_func->get_isolate(), (double)*value_ptr);
}
else if (id == TYPE_DOUBLE)
{
double *value_ptr = (double *)(args[args_count]);
value_args[args_count] = Number::New(js_func->get_isolate(), *value_ptr);
}
else if (id == TYPE_STRING)
{
const char *value_ptr = (const char *)(args[args_count]);
Local<String> local_str = String::NewFromUtf8(js_func->get_isolate(),
value_ptr, NewStringType::kNormal)
.ToLocalChecked();
value_args[args_count] = local_str;
}
else if (id == TYPE_PTR)
{
/*
void * value_ptr = (void *)(args[args_count]);
*/
/* TODO */
/*
value_args[args_count] = Number::New(js_func->get_isolate(), *value_ptr);
*/
}
else
{
/* handle undefined */
}
}
result = func_impl_local->Call(js_func->get_ctx_impl()->Global(), args_count, &value_args[0]);
}
else
{
result = func_impl_local->Call(js_func->get_ctx_impl()->Global(), 0, nullptr);
}
if (!result->IsUndefined())
{
type ret_type = signature_get_return(s);
type_id id = TYPE_INVALID;
if (ret_type == NULL)
{
if (result->IsNull())
{
return NULL;
}
else if (result->IsTrue() || result->IsFalse() || result->IsBoolean())
{
id = TYPE_BOOL;
}
else if (result->IsNumber())
{
id = TYPE_DOUBLE;
}
else if (result->IsInt32() || result->IsUint32())
{
id = TYPE_INT;
}
else if (result->IsString())
{
id = TYPE_STRING;
}
}
else
{
id = type_index(ret_type);
}
if (id == TYPE_BOOL)
{
bool b = result->BooleanValue();
boolean bo = (b == true) ? 1 : 0;
return value_create_bool(bo);
}
else if (id == TYPE_CHAR)
{
/* TODO: Check signed / unsigned for avoid integer overflow */
/* TODO: Check rage for avoid integer overflow */
int i = result->Int32Value();
return value_create_char((char)i);
}
else if (id == TYPE_SHORT)
{
/* TODO: Check signed / unsigned for avoid integer overflow */
/* TODO: Check rage for avoid integer overflow */
int i = result->Int32Value();
return value_create_short((short)i);
}
else if (id == TYPE_INT)
{
/* TODO: Check signed / unsigned for avoid integer overflow */
int i = result->Int32Value();
return value_create_int(i);
}
else if (id == TYPE_LONG)
{
long l = result->IntegerValue();
return value_create_long(l);
}
else if (id == TYPE_FLOAT)
{
double d = result->NumberValue();
return value_create_float((float)d);
}
else if (id == TYPE_DOUBLE)
{
double d = result->NumberValue();
return value_create_double(d);
}
else if (id == TYPE_STRING)
{
Local<String> str_value = result->ToString();
String::Utf8Value utf8_value(str_value);
int utf8_length = str_value->Utf8Length();
if (utf8_length > 0)
{
const char *str = *utf8_value;
size_t length = (size_t)utf8_length;
return value_create_string(str, length);
}
}
else if (id == TYPE_PTR)
{
/* TODO */
}
else
{
log_write("metacall", LOG_LEVEL_ERROR, "Unrecognized return type");
}
}
return NULL;
}
function_return function_js_interface_await(function func, function_impl impl, function_args args, size_t size, function_resolve_callback resolve_callback, function_reject_callback reject_callback, void *context)
{
/* TODO */
(void)func;
(void)impl;
(void)args;
(void)size;
(void)resolve_callback;
(void)reject_callback;
(void)context;
return NULL;
}
void function_js_interface_destroy(function func, function_impl impl)
{
loader_impl_js_function js_func = static_cast<loader_impl_js_function>(impl);
(void)func;
delete js_func;
}
function_interface function_js_singleton(void)
{
static struct function_interface_type js_interface = {
&function_js_interface_create,
&function_js_interface_invoke,
&function_js_interface_await,
&function_js_interface_destroy
};
return &js_interface;
}
void js_loader_impl_read_file(const loader_naming_path path, std::string &source)
{
std::ifstream file(path);
file.seekg(0, std::ios::end);
source.reserve(file.tellg());
file.seekg(0, std::ios::beg);
source.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
MaybeLocal<String> js_loader_impl_read_script(Isolate *isolate, const loader_naming_path path, std::map<std::string, js_function *> &functions)
{
MaybeLocal<String> result;
std::string source;
js_loader_impl_read_file(path, source);
if (!source.empty())
{
std::string output;
// shebang
if (source[0] == '#' && source[1] == '!')
{
source[0] = '/';
source[1] = '/';
}
if (js_loader_impl_guard_parse(source, functions, output) == true)
{
result = String::NewFromUtf8(isolate, output.c_str(),
NewStringType::kNormal, output.length());
}
}
return result;
}
MaybeLocal<String> js_loader_impl_read_script(Isolate *isolate, const char *buffer, size_t size, std::map<std::string, js_function *> &functions)
{
MaybeLocal<String> result;
std::string source(buffer, size - 1);
if (!source.empty())
{
std::string output;
// shebang
if (source[0] == '#' && source[1] == '!')
{
source[0] = '/';
source[1] = '/';
}
if (js_loader_impl_guard_parse(source, functions, output) == true)
{
result = String::NewFromUtf8(isolate, output.c_str(),
NewStringType::kNormal, output.length());
}
}
return result;
}
void js_loader_impl_obj_to_string(Handle<Value> object, std::string &str)
{
String::Utf8Value utf8_value(object);
str = *utf8_value;
}
int js_loader_impl_get_builtin_type(loader_impl impl, loader_impl_js js_impl, type_id id, const char *name)
{
/* TODO: add type table implementation? */
type builtin_type = type_create(id, name, NULL, NULL);
(void)js_impl;
if (builtin_type != NULL)
{
if (loader_impl_type_define(impl, type_name(builtin_type), builtin_type) == 0)
{
return 0;
}
type_destroy(builtin_type);
}
return 1;
}
int js_loader_impl_initialize_inspect_types(loader_impl impl, loader_impl_js js_impl)
{
/* TODO: move this to loader_impl */
static struct
{
type_id id;
const char *name;
} type_id_name_pair[] = {
{ TYPE_BOOL, "Boolean" },
{ TYPE_CHAR, "Int8" },
{ TYPE_SHORT, "Int16" },
{ TYPE_INT, "Int32" },
{ TYPE_LONG, "Integer" },
{ TYPE_FLOAT, "Float" },
{ TYPE_DOUBLE, "Number" },
{ TYPE_STRING, "String" },
{ TYPE_PTR, "Object" },
{ TYPE_PTR, "Array" },
{ TYPE_PTR, "Function" }
};
size_t index, size = sizeof(type_id_name_pair) / sizeof(type_id_name_pair[0]);
for (index = 0; index < size; ++index)
{
if (js_loader_impl_get_builtin_type(impl, js_impl,
type_id_name_pair[index].id,
type_id_name_pair[index].name) != 0)
{
return 1;
}
}
return 0;
}
loader_impl_data js_loader_impl_initialize(loader_impl impl, configuration config)
{
loader_impl_js js_impl;
(void)impl;
(void)config;
js_impl = new loader_impl_js_type();
if (js_impl != nullptr)
{
/* TODO: Implement by config */
#if 0 /* V8 5.7 */
V8::InitializeICUDefaultLocation("/../metacall/build", "/../v8/out/x64.debug/icudtl.dat");
V8::InitializeExternalStartupData("/../v8/out/x64.debug/");
#else /* V8 5.1 */
if (V8::InitializeICU() == true)
#endif
{
js_impl->platform = platform::CreateDefaultPlatform();
if (js_impl->platform != nullptr)
{
V8::InitializePlatform(js_impl->platform);
if (V8::Initialize())
{
js_impl->isolate_create_params.array_buffer_allocator = &js_impl->allocator;
js_impl->isolate = Isolate::New(js_impl->isolate_create_params);
js_impl->isolate_scope = new Isolate::Scope(js_impl->isolate);
if (js_impl->isolate != nullptr &&
js_impl->isolate_scope != nullptr)
{
if (js_loader_impl_initialize_inspect_types(impl, js_impl) == 0)
{
/* Register initialization */
loader_initialization_register(impl);
return static_cast<loader_impl_data>(js_impl);
}
}
}
}
}
delete js_impl;
}
return NULL;
}
int js_loader_impl_execution_path(loader_impl impl, const loader_naming_path path)
{
(void)impl;
(void)path;
return 0;
}
loader_handle js_loader_impl_load_from_file(loader_impl impl, const loader_naming_path paths[], size_t size)
{
loader_impl_js js_impl = static_cast<loader_impl_js>(loader_impl_get(impl));
if (js_impl != nullptr)
{
loader_impl_js_handle js_handle = new loader_impl_js_handle_type(impl, js_impl, paths, size);
if (js_handle != nullptr)
{
return js_handle;
}
}
return NULL;
}
loader_handle js_loader_impl_load_from_memory(loader_impl impl, const loader_naming_name name, const char *buffer, size_t size)
{
loader_impl_js js_impl = static_cast<loader_impl_js>(loader_impl_get(impl));
(void)name;
if (js_impl != nullptr)
{
loader_impl_js_handle js_handle = new loader_impl_js_handle_type(impl, js_impl, buffer, size);
if (js_handle != nullptr)
{
return js_handle;
}
}
return NULL;
}
loader_handle js_loader_impl_load_from_package(loader_impl impl, const loader_naming_path path)
{
/* TODO */
(void)impl;
(void)path;
return NULL;
}
int js_loader_impl_clear(loader_impl impl, loader_handle handle)
{
loader_impl_js_handle js_handle = static_cast<loader_impl_js_handle>(handle);
(void)impl;
if (js_handle != nullptr)
{
delete js_handle;
return 0;
}
return 1;
}
int js_loader_impl_discover(loader_impl impl, loader_handle handle, context ctx)
{
loader_impl_js js_impl = static_cast<loader_impl_js>(loader_impl_get(impl));
if (js_impl != nullptr)
{
loader_impl_js_handle js_handle = (loader_impl_js_handle)handle;
if (js_handle != nullptr)
{
return js_handle->discover(js_impl, ctx);
}
}
return 1;
}
int js_loader_impl_destroy(loader_impl impl)
{
loader_impl_js js_impl = static_cast<loader_impl_js>(loader_impl_get(impl));
if (js_impl != nullptr)
{
/* Destroy children loaders */
loader_unload_children(impl, 0);
/* Destroy V8 */
if (js_impl->isolate_scope != nullptr)
{
delete js_impl->isolate_scope;
js_impl->isolate_scope = nullptr;
}
if (js_impl->isolate != nullptr)
{
js_impl->isolate->Dispose();
js_impl->isolate = nullptr;
}
V8::Dispose();
V8::ShutdownPlatform();
if (js_impl->platform != nullptr)
{
delete js_impl->platform;
js_impl->platform = nullptr;
}
delete js_impl;
return 0;
}
return 1;
}
| 21.802483 | 212 | 0.688306 | [
"object",
"vector"
] |
60a53f30fa8b0e66c99ce6695b610ebdaece0247 | 5,032 | cc | C++ | Alignment/Geners/test/cdump.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | Alignment/Geners/test/cdump.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | Alignment/Geners/test/cdump.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-04-03T19:23:27.000Z | 2019-04-03T19:23:27.000Z | // The following program dumps contents of an object catalog stored
// in a "geners" binary metafile to the standard output
#include <map>
#include <fstream>
#include <iostream>
#include "Alignment/Geners/interface/IOException.hh"
#include "Alignment/Geners/interface/CPP11_auto_ptr.hh"
#include "Alignment/Geners/interface/ContiguousCatalog.hh"
#include "Alignment/Geners/interface/CatalogIO.hh"
#include "Alignment/Geners/interface/CStringStream.hh"
#include "CmdLine.hh"
using namespace gs;
using namespace std;
static void print_usage(const char* progname)
{
cout << "\nUsage: " << progname << " [-a] [-c] [-f] [-i] [-s] filename\n\n"
<< "This program prints the contents of \"geners\" catalog files to the standard\n"
<< "output. These files can be usually recognized by their \".gsbmf\" extension\n"
<< "(Generic Serialization Binary MetaFile). Normally, the program prints class\n"
<< "names, item names in the archive, and archive categories for all items in\n"
<< "the catalog. This default behavior can be modified with option switches.\n"
<< "The meaning of the switches is as follows:\n\n"
<< " -a Print catalog annotations, if any.\n\n"
<< " -c Print default archive compression mode.\n\n"
<< " -f Full dump. Print complete info for each catalog entry.\n\n"
<< " -i Include the catalog item ids into the printout.\n\n"
<< " -s Print only the summary statistics for item types. If option \"-f\" is given\n"
<< " together with \"-s\", the summary will be printed after the full dump.\n"
<< endl;
}
int main(int argc, char const* argv[])
{
CmdLine cmdline(argc, argv);
if (argc == 1)
{
print_usage(cmdline.progname());
return 0;
}
std::string inputfile;
bool printAnnotations = false;
bool printCompressionMode = false;
bool fullDump = false;
bool printIds = false;
bool summaryMode = false;
try {
printAnnotations = cmdline.has("-a");
printCompressionMode = cmdline.has("-c");
fullDump = cmdline.has("-f");
printIds = cmdline.has("-i");
summaryMode = cmdline.has("-s");
cmdline.optend();
if (cmdline.argc() != 1)
throw CmdLineError("wrong number of command line arguments");
cmdline >> inputfile;
}
catch (CmdLineError& e) {
cerr << "Error in " << cmdline.progname() << ": "
<< e.str() << endl;
print_usage(cmdline.progname());
return 1;
}
ifstream in(inputfile.c_str(), ios_base::binary);
if (!in.is_open())
{
cerr << "Error: failed to open file \"" << inputfile << "\"" << endl;
return 1;
}
unsigned compressionCode = 0, mergeLevel = 0;
std::vector<std::string> annotations;
CPP11_auto_ptr<ContiguousCatalog> cat;
try
{
cat = CPP11_auto_ptr<ContiguousCatalog>(readBinaryCatalog<ContiguousCatalog>(
in, &compressionCode, &mergeLevel, &annotations, true));
}
catch (std::exception& e)
{
cerr << "Failed to read catalog from file \""
<< inputfile << "\". " << e.what() << endl;
return 1;
}
if (printCompressionMode)
{
CStringStream::CompressionMode mode =
static_cast<CStringStream::CompressionMode>(compressionCode);
cout << "Default compression mode: "
<< CStringStream::compressionModeName(mode, false) << endl;
}
if (printAnnotations)
{
const unsigned nAnnotations = annotations.size();
for (unsigned i=0; i<nAnnotations; ++i)
{
if (i) cout << '\n';
cout << "Annotation " << i << ": " << annotations[i] << endl;
}
if (!nAnnotations)
cout << "This catalog does not have any annotations" << endl;
}
std::map<std::string,unsigned> typecount;
const unsigned long long first = cat->smallestId();
const unsigned long long last = cat->largestId();
for (unsigned long long id = first; id <= last; ++id)
{
if (!cat->itemExists(id)) continue;
CPP11_shared_ptr<const CatalogEntry> e = cat->retrieveEntry(id);
if (fullDump)
{
if (id != first) cout << '\n';
e->humanReadable(cout);
}
else if (!summaryMode)
{
if (printIds)
cout << e->id() << " ";
cout << e->type().name() << " " << '"' << e->name() << '"'
<< " " << '"' << e->category() << '"' << endl;
}
if (summaryMode)
typecount[e->type().name()]++;
}
if (summaryMode)
{
if (fullDump)
cout << '\n';
for (std::map<std::string,unsigned>::const_iterator it = typecount.begin();
it != typecount.end(); ++it)
cout << it->second << ' ' << it->first << endl;
}
return 0;
}
| 33.324503 | 97 | 0.564785 | [
"object",
"vector"
] |
60a9c9a5d98b6b01e2bc0b641814f950d16a384b | 82,476 | cpp | C++ | Analysis/src/Unifier.cpp | XanderYZZ/luau | 362428f8b4b6f5c9d43f4daf55bcf7873f536c3f | [
"MIT"
] | 1 | 2022-03-18T04:10:20.000Z | 2022-03-18T04:10:20.000Z | Analysis/src/Unifier.cpp | XanderYZZ/luau | 362428f8b4b6f5c9d43f4daf55bcf7873f536c3f | [
"MIT"
] | null | null | null | Analysis/src/Unifier.cpp | XanderYZZ/luau | 362428f8b4b6f5c9d43f4daf55bcf7873f536c3f | [
"MIT"
] | null | null | null | // This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
#include "Luau/Unifier.h"
#include "Luau/Common.h"
#include "Luau/RecursionCounter.h"
#include "Luau/Scope.h"
#include "Luau/TypePack.h"
#include "Luau/TypeUtils.h"
#include "Luau/TimeTrace.h"
#include "Luau/VisitTypeVar.h"
#include "Luau/ToString.h"
#include <algorithm>
LUAU_FASTINT(LuauTypeInferRecursionLimit);
LUAU_FASTINT(LuauTypeInferTypePackLoopLimit);
LUAU_FASTFLAG(LuauImmutableTypes)
LUAU_FASTINTVARIABLE(LuauTypeInferIterationLimit, 2000);
LUAU_FASTFLAGVARIABLE(LuauTableSubtypingVariance2, false);
LUAU_FASTFLAG(LuauSingletonTypes)
LUAU_FASTFLAG(LuauErrorRecoveryType);
LUAU_FASTFLAGVARIABLE(LuauSubtypingAddOptPropsToUnsealedTables, false)
LUAU_FASTFLAGVARIABLE(LuauWidenIfSupertypeIsFree2, false)
LUAU_FASTFLAGVARIABLE(LuauDifferentOrderOfUnificationDoesntMatter, false)
LUAU_FASTFLAGVARIABLE(LuauTxnLogSeesTypePacks2, false)
LUAU_FASTFLAGVARIABLE(LuauTxnLogCheckForInvalidation, false)
LUAU_FASTFLAGVARIABLE(LuauTxnLogRefreshFunctionPointers, false)
LUAU_FASTFLAGVARIABLE(LuauTxnLogDontRetryForIndexers, false)
LUAU_FASTFLAG(LuauAnyInIsOptionalIsOptional)
namespace Luau
{
struct PromoteTypeLevels
{
TxnLog& log;
const TypeArena* typeArena = nullptr;
TypeLevel minLevel;
PromoteTypeLevels(TxnLog& log, const TypeArena* typeArena, TypeLevel minLevel)
: log(log)
, typeArena(typeArena)
, minLevel(minLevel)
{
}
template<typename TID, typename T>
void promote(TID ty, T* t)
{
LUAU_ASSERT(t);
if (minLevel.subsumesStrict(t->level))
{
log.changeLevel(ty, minLevel);
}
}
template<typename TID>
void cycle(TID)
{
}
template<typename TID, typename T>
bool operator()(TID ty, const T&)
{
// Type levels of types from other modules are already global, so we don't need to promote anything inside
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
return false;
return true;
}
bool operator()(TypeId ty, const FreeTypeVar&)
{
// Surprise, it's actually a BoundTypeVar that hasn't been committed yet.
// Calling getMutable on this will trigger an assertion.
if (!log.is<FreeTypeVar>(ty))
return true;
promote(ty, log.getMutable<FreeTypeVar>(ty));
return true;
}
bool operator()(TypeId ty, const FunctionTypeVar&)
{
// Type levels of types from other modules are already global, so we don't need to promote anything inside
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
return false;
promote(ty, log.getMutable<FunctionTypeVar>(ty));
return true;
}
bool operator()(TypeId ty, const TableTypeVar& ttv)
{
// Type levels of types from other modules are already global, so we don't need to promote anything inside
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
return false;
if (ttv.state != TableState::Free && ttv.state != TableState::Generic)
return true;
promote(ty, log.getMutable<TableTypeVar>(ty));
return true;
}
bool operator()(TypePackId tp, const FreeTypePack&)
{
// Surprise, it's actually a BoundTypePack that hasn't been committed yet.
// Calling getMutable on this will trigger an assertion.
if (!log.is<FreeTypePack>(tp))
return true;
promote(tp, log.getMutable<FreeTypePack>(tp));
return true;
}
};
static void promoteTypeLevels(TxnLog& log, const TypeArena* typeArena, TypeLevel minLevel, TypeId ty)
{
// Type levels of types from other modules are already global, so we don't need to promote anything inside
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
return;
PromoteTypeLevels ptl{log, typeArena, minLevel};
DenseHashSet<void*> seen{nullptr};
visitTypeVarOnce(ty, ptl, seen);
}
// TODO: use this and make it static.
void promoteTypeLevels(TxnLog& log, const TypeArena* typeArena, TypeLevel minLevel, TypePackId tp)
{
// Type levels of types from other modules are already global, so we don't need to promote anything inside
if (FFlag::LuauImmutableTypes && tp->owningArena != typeArena)
return;
PromoteTypeLevels ptl{log, typeArena, minLevel};
DenseHashSet<void*> seen{nullptr};
visitTypeVarOnce(tp, ptl, seen);
}
struct SkipCacheForType
{
SkipCacheForType(const DenseHashMap<TypeId, bool>& skipCacheForType, const TypeArena* typeArena)
: skipCacheForType(skipCacheForType)
, typeArena(typeArena)
{
}
void cycle(TypeId) {}
void cycle(TypePackId) {}
bool operator()(TypeId ty, const FreeTypeVar& ftv)
{
result = true;
return false;
}
bool operator()(TypeId ty, const BoundTypeVar& btv)
{
result = true;
return false;
}
bool operator()(TypeId ty, const GenericTypeVar& btv)
{
result = true;
return false;
}
bool operator()(TypeId ty, const TableTypeVar&)
{
// Types from other modules don't contain mutable elements and are ok to cache
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
return false;
TableTypeVar& ttv = *getMutable<TableTypeVar>(ty);
if (ttv.boundTo)
{
result = true;
return false;
}
if (ttv.state != TableState::Sealed)
{
result = true;
return false;
}
return true;
}
template<typename T>
bool operator()(TypeId ty, const T& t)
{
// Types from other modules don't contain mutable elements and are ok to cache
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
return false;
const bool* prev = skipCacheForType.find(ty);
if (prev && *prev)
{
result = true;
return false;
}
return true;
}
template<typename T>
bool operator()(TypePackId tp, const T&)
{
// Types from other modules don't contain mutable elements and are ok to cache
if (FFlag::LuauImmutableTypes && tp->owningArena != typeArena)
return false;
return true;
}
bool operator()(TypePackId tp, const FreeTypePack& ftp)
{
result = true;
return false;
}
bool operator()(TypePackId tp, const BoundTypePack& ftp)
{
result = true;
return false;
}
bool operator()(TypePackId tp, const GenericTypePack& ftp)
{
result = true;
return false;
}
const DenseHashMap<TypeId, bool>& skipCacheForType;
const TypeArena* typeArena = nullptr;
bool result = false;
};
bool Widen::isDirty(TypeId ty)
{
return log->is<SingletonTypeVar>(ty);
}
bool Widen::isDirty(TypePackId)
{
return false;
}
TypeId Widen::clean(TypeId ty)
{
LUAU_ASSERT(isDirty(ty));
auto stv = log->getMutable<SingletonTypeVar>(ty);
LUAU_ASSERT(stv);
if (get<StringSingleton>(stv))
return getSingletonTypes().stringType;
else
{
// If this assert trips, it's likely we now have number singletons.
LUAU_ASSERT(get<BooleanSingleton>(stv));
return getSingletonTypes().booleanType;
}
}
TypePackId Widen::clean(TypePackId)
{
throw std::runtime_error("Widen attempted to clean a dirty type pack?");
}
bool Widen::ignoreChildren(TypeId ty)
{
return !log->is<UnionTypeVar>(ty);
}
static std::optional<TypeError> hasUnificationTooComplex(const ErrorVec& errors)
{
auto isUnificationTooComplex = [](const TypeError& te) {
return nullptr != get<UnificationTooComplex>(te);
};
auto it = std::find_if(errors.begin(), errors.end(), isUnificationTooComplex);
if (it == errors.end())
return std::nullopt;
else
return *it;
}
// Used for tagged union matching heuristic, returns first singleton type field
static std::optional<std::pair<Luau::Name, const SingletonTypeVar*>> getTableMatchTag(TypeId type)
{
if (auto ttv = getTableType(type))
{
for (auto&& [name, prop] : ttv->props)
{
if (auto sing = get<SingletonTypeVar>(follow(prop.type)))
return {{name, sing}};
}
}
return std::nullopt;
}
Unifier::Unifier(TypeArena* types, Mode mode, const Location& location, Variance variance, UnifierSharedState& sharedState,
TxnLog* parentLog)
: types(types)
, mode(mode)
, log(parentLog)
, location(location)
, variance(variance)
, sharedState(sharedState)
{
LUAU_ASSERT(sharedState.iceHandler);
}
Unifier::Unifier(TypeArena* types, Mode mode, std::vector<std::pair<TypeOrPackId, TypeOrPackId>>* sharedSeen, const Location& location,
Variance variance, UnifierSharedState& sharedState, TxnLog* parentLog)
: types(types)
, mode(mode)
, log(parentLog, sharedSeen)
, location(location)
, variance(variance)
, sharedState(sharedState)
{
LUAU_ASSERT(sharedState.iceHandler);
}
void Unifier::tryUnify(TypeId subTy, TypeId superTy, bool isFunctionCall, bool isIntersection)
{
sharedState.counters.iterationCount = 0;
tryUnify_(subTy, superTy, isFunctionCall, isIntersection);
}
void Unifier::tryUnify_(TypeId subTy, TypeId superTy, bool isFunctionCall, bool isIntersection)
{
RecursionLimiter _ra(&sharedState.counters.recursionCount, FInt::LuauTypeInferRecursionLimit);
++sharedState.counters.iterationCount;
if (FInt::LuauTypeInferIterationLimit > 0 && FInt::LuauTypeInferIterationLimit < sharedState.counters.iterationCount)
{
reportError(TypeError{location, UnificationTooComplex{}});
return;
}
superTy = log.follow(superTy);
subTy = log.follow(subTy);
if (superTy == subTy)
return;
auto superFree = log.getMutable<FreeTypeVar>(superTy);
auto subFree = log.getMutable<FreeTypeVar>(subTy);
if (superFree && subFree && superFree->level.subsumes(subFree->level))
{
occursCheck(subTy, superTy);
// The occurrence check might have caused superTy no longer to be a free type
bool occursFailed = bool(log.getMutable<ErrorTypeVar>(subTy));
if (!occursFailed)
{
log.replace(subTy, BoundTypeVar(superTy));
}
return;
}
else if (superFree && subFree)
{
occursCheck(superTy, subTy);
bool occursFailed = bool(log.getMutable<ErrorTypeVar>(superTy));
if (!occursFailed)
{
if (superFree->level.subsumes(subFree->level))
{
log.changeLevel(subTy, superFree->level);
}
log.replace(superTy, BoundTypeVar(subTy));
}
return;
}
else if (superFree)
{
TypeLevel superLevel = superFree->level;
occursCheck(superTy, subTy);
bool occursFailed = bool(log.getMutable<ErrorTypeVar>(superTy));
// Unification can't change the level of a generic.
auto subGeneric = log.getMutable<GenericTypeVar>(subTy);
if (subGeneric && !subGeneric->level.subsumes(superLevel))
{
// TODO: a more informative error message? CLI-39912
reportError(TypeError{location, GenericError{"Generic subtype escaping scope"}});
return;
}
// The occurrence check might have caused superTy no longer to be a free type
if (!occursFailed)
{
promoteTypeLevels(log, types, superLevel, subTy);
log.replace(superTy, BoundTypeVar(widen(subTy)));
}
return;
}
else if (subFree)
{
TypeLevel subLevel = subFree->level;
occursCheck(subTy, superTy);
bool occursFailed = bool(log.getMutable<ErrorTypeVar>(subTy));
// Unification can't change the level of a generic.
auto superGeneric = log.getMutable<GenericTypeVar>(superTy);
if (superGeneric && !superGeneric->level.subsumes(subFree->level))
{
// TODO: a more informative error message? CLI-39912
reportError(TypeError{location, GenericError{"Generic supertype escaping scope"}});
return;
}
if (!occursFailed)
{
promoteTypeLevels(log, types, subLevel, superTy);
log.replace(subTy, BoundTypeVar(superTy));
}
return;
}
if (get<ErrorTypeVar>(superTy) || get<AnyTypeVar>(superTy))
return tryUnifyWithAny(subTy, superTy);
if (get<ErrorTypeVar>(subTy) || get<AnyTypeVar>(subTy))
return tryUnifyWithAny(superTy, subTy);
bool cacheEnabled = !isFunctionCall && !isIntersection;
auto& cache = sharedState.cachedUnify;
// What if the types are immutable and we proved their relation before
if (cacheEnabled && cache.contains({superTy, subTy}) && (variance == Covariant || cache.contains({subTy, superTy})))
return;
// If we have seen this pair of types before, we are currently recursing into cyclic types.
// Here, we assume that the types unify. If they do not, we will find out as we roll back
// the stack.
if (log.haveSeen(superTy, subTy))
return;
log.pushSeen(superTy, subTy);
if (const UnionTypeVar* uv = log.getMutable<UnionTypeVar>(subTy))
{
tryUnifyUnionWithType(subTy, uv, superTy);
}
else if (const UnionTypeVar* uv = log.getMutable<UnionTypeVar>(superTy))
{
tryUnifyTypeWithUnion(subTy, superTy, uv, cacheEnabled, isFunctionCall);
}
else if (const IntersectionTypeVar* uv = log.getMutable<IntersectionTypeVar>(superTy))
{
tryUnifyTypeWithIntersection(subTy, superTy, uv);
}
else if (const IntersectionTypeVar* uv = log.getMutable<IntersectionTypeVar>(subTy))
{
tryUnifyIntersectionWithType(subTy, uv, superTy, cacheEnabled, isFunctionCall);
}
else if (log.getMutable<PrimitiveTypeVar>(superTy) && log.getMutable<PrimitiveTypeVar>(subTy))
tryUnifyPrimitives(subTy, superTy);
else if (FFlag::LuauSingletonTypes && (log.getMutable<PrimitiveTypeVar>(superTy) || log.getMutable<SingletonTypeVar>(superTy)) &&
log.getMutable<SingletonTypeVar>(subTy))
tryUnifySingletons(subTy, superTy);
else if (log.getMutable<FunctionTypeVar>(superTy) && log.getMutable<FunctionTypeVar>(subTy))
tryUnifyFunctions(subTy, superTy, isFunctionCall);
else if (log.getMutable<TableTypeVar>(superTy) && log.getMutable<TableTypeVar>(subTy))
{
tryUnifyTables(subTy, superTy, isIntersection);
if (cacheEnabled && errors.empty())
cacheResult(subTy, superTy);
}
// tryUnifyWithMetatable assumes its first argument is a MetatableTypeVar. The check is otherwise symmetrical.
else if (log.getMutable<MetatableTypeVar>(superTy))
tryUnifyWithMetatable(subTy, superTy, /*reversed*/ false);
else if (log.getMutable<MetatableTypeVar>(subTy))
tryUnifyWithMetatable(superTy, subTy, /*reversed*/ true);
else if (log.getMutable<ClassTypeVar>(superTy))
tryUnifyWithClass(subTy, superTy, /*reversed*/ false);
// Unification of nonclasses with classes is almost, but not quite symmetrical.
// The order in which we perform this test is significant in the case that both types are classes.
else if (log.getMutable<ClassTypeVar>(subTy))
tryUnifyWithClass(subTy, superTy, /*reversed*/ true);
else
reportError(TypeError{location, TypeMismatch{superTy, subTy}});
log.popSeen(superTy, subTy);
}
void Unifier::tryUnifyUnionWithType(TypeId subTy, const UnionTypeVar* uv, TypeId superTy)
{
// A | B <: T if A <: T and B <: T
bool failed = false;
std::optional<TypeError> unificationTooComplex;
std::optional<TypeError> firstFailedOption;
size_t count = uv->options.size();
size_t i = 0;
for (TypeId type : uv->options)
{
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(type, superTy);
if (auto e = hasUnificationTooComplex(innerState.errors))
unificationTooComplex = e;
else if (!innerState.errors.empty())
{
// 'nil' option is skipped from extended report because we present the type in a special way - 'T?'
if (!firstFailedOption && !isNil(type))
firstFailedOption = {innerState.errors.front()};
failed = true;
}
if (FFlag::LuauDifferentOrderOfUnificationDoesntMatter)
{
}
else
{
if (i == count - 1)
{
log.concat(std::move(innerState.log));
}
++i;
}
}
// even if A | B <: T fails, we want to bind some options of T with A | B iff A | B was a subtype of that option.
if (FFlag::LuauDifferentOrderOfUnificationDoesntMatter)
{
auto tryBind = [this, subTy](TypeId superOption) {
superOption = log.follow(superOption);
// just skip if the superOption is not free-ish.
auto ttv = log.getMutable<TableTypeVar>(superOption);
if (!log.is<FreeTypeVar>(superOption) && (!ttv || ttv->state != TableState::Free))
return;
// Since we have already checked if S <: T, checking it again will not queue up the type for replacement.
// So we'll have to do it ourselves. We assume they unified cleanly if they are still in the seen set.
if (log.haveSeen(subTy, superOption))
{
// TODO: would it be nice for TxnLog::replace to do this?
if (log.is<TableTypeVar>(superOption))
log.bindTable(superOption, subTy);
else
log.replace(superOption, *subTy);
}
};
if (auto utv = log.getMutable<UnionTypeVar>(superTy))
{
for (TypeId ty : utv)
tryBind(ty);
}
else
tryBind(superTy);
}
if (unificationTooComplex)
reportError(*unificationTooComplex);
else if (failed)
{
if (firstFailedOption)
reportError(TypeError{location, TypeMismatch{superTy, subTy, "Not all union options are compatible.", *firstFailedOption}});
else
reportError(TypeError{location, TypeMismatch{superTy, subTy}});
}
}
void Unifier::tryUnifyTypeWithUnion(TypeId subTy, TypeId superTy, const UnionTypeVar* uv, bool cacheEnabled, bool isFunctionCall)
{
// T <: A | B if T <: A or T <: B
bool found = false;
std::optional<TypeError> unificationTooComplex;
size_t failedOptionCount = 0;
std::optional<TypeError> failedOption;
bool foundHeuristic = false;
size_t startIndex = 0;
if (const std::string* subName = getName(subTy))
{
for (size_t i = 0; i < uv->options.size(); ++i)
{
const std::string* optionName = getName(uv->options[i]);
if (optionName && *optionName == *subName)
{
foundHeuristic = true;
startIndex = i;
break;
}
}
}
if (auto subMatchTag = getTableMatchTag(subTy))
{
for (size_t i = 0; i < uv->options.size(); ++i)
{
auto optionMatchTag = getTableMatchTag(uv->options[i]);
if (optionMatchTag && optionMatchTag->first == subMatchTag->first && *optionMatchTag->second == *subMatchTag->second)
{
foundHeuristic = true;
startIndex = i;
break;
}
}
}
if (!foundHeuristic && cacheEnabled)
{
auto& cache = sharedState.cachedUnify;
for (size_t i = 0; i < uv->options.size(); ++i)
{
TypeId type = uv->options[i];
if (cache.contains({type, subTy}) && (variance == Covariant || cache.contains({subTy, type})))
{
startIndex = i;
break;
}
}
}
for (size_t i = 0; i < uv->options.size(); ++i)
{
TypeId type = uv->options[(i + startIndex) % uv->options.size()];
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(subTy, type, isFunctionCall);
if (innerState.errors.empty())
{
found = true;
log.concat(std::move(innerState.log));
break;
}
else if (auto e = hasUnificationTooComplex(innerState.errors))
{
unificationTooComplex = e;
}
else if (!isNil(type))
{
failedOptionCount++;
if (!failedOption)
failedOption = {innerState.errors.front()};
}
}
if (unificationTooComplex)
{
reportError(*unificationTooComplex);
}
else if (!found)
{
if ((failedOptionCount == 1 || foundHeuristic) && failedOption)
reportError(TypeError{location, TypeMismatch{superTy, subTy, "None of the union options are compatible. For example:", *failedOption}});
else
reportError(TypeError{location, TypeMismatch{superTy, subTy, "none of the union options are compatible"}});
}
}
void Unifier::tryUnifyTypeWithIntersection(TypeId subTy, TypeId superTy, const IntersectionTypeVar* uv)
{
std::optional<TypeError> unificationTooComplex;
std::optional<TypeError> firstFailedOption;
// T <: A & B if A <: T and B <: T
for (TypeId type : uv->parts)
{
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(subTy, type, /*isFunctionCall*/ false, /*isIntersection*/ true);
if (auto e = hasUnificationTooComplex(innerState.errors))
unificationTooComplex = e;
else if (!innerState.errors.empty())
{
if (!firstFailedOption)
firstFailedOption = {innerState.errors.front()};
}
log.concat(std::move(innerState.log));
}
if (unificationTooComplex)
reportError(*unificationTooComplex);
else if (firstFailedOption)
reportError(TypeError{location, TypeMismatch{superTy, subTy, "Not all intersection parts are compatible.", *firstFailedOption}});
}
void Unifier::tryUnifyIntersectionWithType(TypeId subTy, const IntersectionTypeVar* uv, TypeId superTy, bool cacheEnabled, bool isFunctionCall)
{
// A & B <: T if T <: A or T <: B
bool found = false;
std::optional<TypeError> unificationTooComplex;
size_t startIndex = 0;
if (cacheEnabled)
{
auto& cache = sharedState.cachedUnify;
for (size_t i = 0; i < uv->parts.size(); ++i)
{
TypeId type = uv->parts[i];
if (cache.contains({superTy, type}) && (variance == Covariant || cache.contains({type, superTy})))
{
startIndex = i;
break;
}
}
}
for (size_t i = 0; i < uv->parts.size(); ++i)
{
TypeId type = uv->parts[(i + startIndex) % uv->parts.size()];
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(type, superTy, isFunctionCall);
if (innerState.errors.empty())
{
found = true;
log.concat(std::move(innerState.log));
break;
}
else if (auto e = hasUnificationTooComplex(innerState.errors))
{
unificationTooComplex = e;
}
}
if (unificationTooComplex)
reportError(*unificationTooComplex);
else if (!found)
{
reportError(TypeError{location, TypeMismatch{superTy, subTy, "none of the intersection parts are compatible"}});
}
}
void Unifier::cacheResult(TypeId subTy, TypeId superTy)
{
bool* superTyInfo = sharedState.skipCacheForType.find(superTy);
if (superTyInfo && *superTyInfo)
return;
bool* subTyInfo = sharedState.skipCacheForType.find(subTy);
if (subTyInfo && *subTyInfo)
return;
auto skipCacheFor = [this](TypeId ty) {
SkipCacheForType visitor{sharedState.skipCacheForType, types};
visitTypeVarOnce(ty, visitor, sharedState.seenAny);
sharedState.skipCacheForType[ty] = visitor.result;
return visitor.result;
};
if (!superTyInfo && skipCacheFor(superTy))
return;
if (!subTyInfo && skipCacheFor(subTy))
return;
sharedState.cachedUnify.insert({superTy, subTy});
if (variance == Invariant)
sharedState.cachedUnify.insert({subTy, superTy});
}
struct WeirdIter
{
TypePackId packId;
TxnLog& log;
TypePack* pack;
size_t index;
bool growing;
TypeLevel level;
WeirdIter(TypePackId packId, TxnLog& log)
: packId(packId)
, log(log)
, pack(log.getMutable<TypePack>(packId))
, index(0)
, growing(false)
{
while (pack && pack->head.empty() && pack->tail)
{
packId = *pack->tail;
pack = log.getMutable<TypePack>(packId);
}
}
WeirdIter(const WeirdIter&) = default;
TypeId& operator*()
{
LUAU_ASSERT(good());
return pack->head[index];
}
bool good() const
{
return pack != nullptr && index < pack->head.size();
}
bool advance()
{
if (!pack)
return good();
if (index < pack->head.size())
++index;
if (growing || index < pack->head.size())
return good();
if (pack->tail)
{
packId = log.follow(*pack->tail);
pack = log.getMutable<TypePack>(packId);
index = 0;
}
return good();
}
bool canGrow() const
{
return nullptr != log.getMutable<Unifiable::Free>(packId);
}
void grow(TypePackId newTail)
{
LUAU_ASSERT(canGrow());
LUAU_ASSERT(log.getMutable<TypePack>(newTail));
level = log.getMutable<Unifiable::Free>(packId)->level;
log.replace(packId, Unifiable::Bound<TypePackId>(newTail));
packId = newTail;
pack = log.getMutable<TypePack>(newTail);
index = 0;
growing = true;
}
void pushType(TypeId ty)
{
LUAU_ASSERT(pack);
PendingTypePack* pendingPack = log.queue(packId);
if (TypePack* pending = getMutable<TypePack>(pendingPack))
{
pending->head.push_back(ty);
// We've potentially just replaced the TypePack* that we need to look
// in. We need to replace pack.
pack = pending;
}
else
{
LUAU_ASSERT(!"Pending state for this pack was not a TypePack");
}
}
};
ErrorVec Unifier::canUnify(TypeId subTy, TypeId superTy)
{
Unifier s = makeChildUnifier();
s.tryUnify_(subTy, superTy);
return s.errors;
}
ErrorVec Unifier::canUnify(TypePackId subTy, TypePackId superTy, bool isFunctionCall)
{
Unifier s = makeChildUnifier();
s.tryUnify_(subTy, superTy, isFunctionCall);
return s.errors;
}
void Unifier::tryUnify(TypePackId subTp, TypePackId superTp, bool isFunctionCall)
{
sharedState.counters.iterationCount = 0;
tryUnify_(subTp, superTp, isFunctionCall);
}
static std::pair<std::vector<TypeId>, std::optional<TypePackId>> logAwareFlatten(TypePackId tp, const TxnLog& log)
{
tp = log.follow(tp);
std::vector<TypeId> flattened;
std::optional<TypePackId> tail = std::nullopt;
TypePackIterator it(tp, &log);
for (; it != end(tp); ++it)
{
flattened.push_back(*it);
}
tail = it.tail();
return {flattened, tail};
}
/*
* This is quite tricky: we are walking two rope-like structures and unifying corresponding elements.
* If one is longer than the other, but the short end is free, we grow it to the required length.
*/
void Unifier::tryUnify_(TypePackId subTp, TypePackId superTp, bool isFunctionCall)
{
RecursionLimiter _ra(&sharedState.counters.recursionCount, FInt::LuauTypeInferRecursionLimit);
++sharedState.counters.iterationCount;
if (FInt::LuauTypeInferIterationLimit > 0 && FInt::LuauTypeInferIterationLimit < sharedState.counters.iterationCount)
{
reportError(TypeError{location, UnificationTooComplex{}});
return;
}
superTp = log.follow(superTp);
subTp = log.follow(subTp);
while (auto tp = log.getMutable<TypePack>(subTp))
{
if (tp->head.empty() && tp->tail)
subTp = log.follow(*tp->tail);
else
break;
}
while (auto tp = log.getMutable<TypePack>(superTp))
{
if (tp->head.empty() && tp->tail)
superTp = log.follow(*tp->tail);
else
break;
}
if (superTp == subTp)
return;
if (FFlag::LuauTxnLogSeesTypePacks2 && log.haveSeen(superTp, subTp))
return;
if (log.getMutable<Unifiable::Free>(superTp))
{
occursCheck(superTp, subTp);
if (!log.getMutable<ErrorTypeVar>(superTp))
{
log.replace(superTp, Unifiable::Bound<TypePackId>(widen(subTp)));
}
}
else if (log.getMutable<Unifiable::Free>(subTp))
{
occursCheck(subTp, superTp);
if (!log.getMutable<ErrorTypeVar>(subTp))
{
log.replace(subTp, Unifiable::Bound<TypePackId>(superTp));
}
}
else if (log.getMutable<Unifiable::Error>(superTp))
tryUnifyWithAny(subTp, superTp);
else if (log.getMutable<Unifiable::Error>(subTp))
tryUnifyWithAny(superTp, subTp);
else if (log.getMutable<VariadicTypePack>(superTp))
tryUnifyVariadics(subTp, superTp, false);
else if (log.getMutable<VariadicTypePack>(subTp))
tryUnifyVariadics(superTp, subTp, true);
else if (log.getMutable<TypePack>(superTp) && log.getMutable<TypePack>(subTp))
{
auto superTpv = log.getMutable<TypePack>(superTp);
auto subTpv = log.getMutable<TypePack>(subTp);
// If the size of two heads does not match, but both packs have free tail
// We set the sentinel variable to say so to avoid growing it forever.
auto [superTypes, superTail] = logAwareFlatten(superTp, log);
auto [subTypes, subTail] = logAwareFlatten(subTp, log);
bool noInfiniteGrowth = (superTypes.size() != subTypes.size()) && (superTail && log.getMutable<FreeTypePack>(*superTail)) &&
(subTail && log.getMutable<FreeTypePack>(*subTail));
auto superIter = WeirdIter(superTp, log);
auto subIter = WeirdIter(subTp, log);
auto mkFreshType = [this](TypeLevel level) {
return types->freshType(level);
};
const TypePackId emptyTp = types->addTypePack(TypePack{{}, std::nullopt});
int loopCount = 0;
do
{
if (FInt::LuauTypeInferTypePackLoopLimit > 0 && loopCount >= FInt::LuauTypeInferTypePackLoopLimit)
ice("Detected possibly infinite TypePack growth");
++loopCount;
if (superIter.good() && subIter.growing)
{
subIter.pushType(mkFreshType(subIter.level));
}
if (subIter.good() && superIter.growing)
{
superIter.pushType(mkFreshType(superIter.level));
}
if (superIter.good() && subIter.good())
{
tryUnify_(*subIter, *superIter);
if (!errors.empty() && !firstPackErrorPos)
firstPackErrorPos = loopCount;
superIter.advance();
subIter.advance();
continue;
}
// If both are at the end, we're done
if (!superIter.good() && !subIter.good())
{
if (subTpv->tail && superTpv->tail)
{
tryUnify_(*subTpv->tail, *superTpv->tail);
break;
}
const bool lFreeTail = superTpv->tail && log.getMutable<FreeTypePack>(log.follow(*superTpv->tail)) != nullptr;
const bool rFreeTail = subTpv->tail && log.getMutable<FreeTypePack>(log.follow(*subTpv->tail)) != nullptr;
if (lFreeTail)
tryUnify_(emptyTp, *superTpv->tail);
else if (rFreeTail)
tryUnify_(emptyTp, *subTpv->tail);
break;
}
// If both tails are free, bind one to the other and call it a day
if (superIter.canGrow() && subIter.canGrow())
return tryUnify_(*subIter.pack->tail, *superIter.pack->tail);
// If just one side is free on its tail, grow it to fit the other side.
// FIXME: The tail-most tail of the growing pack should be the same as the tail-most tail of the non-growing pack.
if (superIter.canGrow())
superIter.grow(types->addTypePack(TypePackVar(TypePack{})));
else if (subIter.canGrow())
subIter.grow(types->addTypePack(TypePackVar(TypePack{})));
else
{
// A union type including nil marks an optional argument
if (superIter.good() && isOptional(*superIter))
{
superIter.advance();
continue;
}
else if (subIter.good() && isOptional(*subIter))
{
subIter.advance();
continue;
}
// In nonstrict mode, any also marks an optional argument.
else if (!FFlag::LuauAnyInIsOptionalIsOptional && superIter.good() && isNonstrictMode() && log.getMutable<AnyTypeVar>(log.follow(*superIter)))
{
superIter.advance();
continue;
}
if (log.getMutable<VariadicTypePack>(superIter.packId))
{
tryUnifyVariadics(subIter.packId, superIter.packId, false, int(subIter.index));
return;
}
if (log.getMutable<VariadicTypePack>(subIter.packId))
{
tryUnifyVariadics(superIter.packId, subIter.packId, true, int(superIter.index));
return;
}
if (!isFunctionCall && subIter.good())
{
// Sometimes it is ok to pass too many arguments
return;
}
// This is a bit weird because we don't actually know expected vs actual. We just know
// subtype vs supertype. If we are checking the values returned by a function, we swap
// these to produce the expected error message.
size_t expectedSize = size(superTp);
size_t actualSize = size(subTp);
if (ctx == CountMismatch::Result)
std::swap(expectedSize, actualSize);
reportError(TypeError{location, CountMismatch{expectedSize, actualSize, ctx}});
while (superIter.good())
{
tryUnify_(*superIter, getSingletonTypes().errorRecoveryType());
superIter.advance();
}
while (subIter.good())
{
tryUnify_(*subIter, getSingletonTypes().errorRecoveryType());
subIter.advance();
}
return;
}
} while (!noInfiniteGrowth);
}
else
{
reportError(TypeError{location, GenericError{"Failed to unify type packs"}});
}
}
void Unifier::tryUnifyPrimitives(TypeId subTy, TypeId superTy)
{
const PrimitiveTypeVar* superPrim = get<PrimitiveTypeVar>(superTy);
const PrimitiveTypeVar* subPrim = get<PrimitiveTypeVar>(subTy);
if (!superPrim || !subPrim)
ice("passed non primitive types to unifyPrimitives");
if (superPrim->type != subPrim->type)
reportError(TypeError{location, TypeMismatch{superTy, subTy}});
}
void Unifier::tryUnifySingletons(TypeId subTy, TypeId superTy)
{
const PrimitiveTypeVar* superPrim = get<PrimitiveTypeVar>(superTy);
const SingletonTypeVar* superSingleton = get<SingletonTypeVar>(superTy);
const SingletonTypeVar* subSingleton = get<SingletonTypeVar>(subTy);
if ((!superPrim && !superSingleton) || !subSingleton)
ice("passed non singleton/primitive types to unifySingletons");
if (superSingleton && *superSingleton == *subSingleton)
return;
if (superPrim && superPrim->type == PrimitiveTypeVar::Boolean && get<BooleanSingleton>(subSingleton) && variance == Covariant)
return;
if (superPrim && superPrim->type == PrimitiveTypeVar::String && get<StringSingleton>(subSingleton) && variance == Covariant)
return;
reportError(TypeError{location, TypeMismatch{superTy, subTy}});
}
void Unifier::tryUnifyFunctions(TypeId subTy, TypeId superTy, bool isFunctionCall)
{
FunctionTypeVar* superFunction = log.getMutable<FunctionTypeVar>(superTy);
FunctionTypeVar* subFunction = log.getMutable<FunctionTypeVar>(subTy);
if (!superFunction || !subFunction)
ice("passed non-function types to unifyFunction");
size_t numGenerics = superFunction->generics.size();
if (numGenerics != subFunction->generics.size())
{
numGenerics = std::min(superFunction->generics.size(), subFunction->generics.size());
reportError(TypeError{location, TypeMismatch{superTy, subTy, "different number of generic type parameters"}});
}
size_t numGenericPacks = superFunction->genericPacks.size();
if (numGenericPacks != subFunction->genericPacks.size())
{
numGenericPacks = std::min(superFunction->genericPacks.size(), subFunction->genericPacks.size());
reportError(TypeError{location, TypeMismatch{superTy, subTy, "different number of generic type pack parameters"}});
}
for (size_t i = 0; i < numGenerics; i++)
{
log.pushSeen(superFunction->generics[i], subFunction->generics[i]);
}
if (FFlag::LuauTxnLogSeesTypePacks2)
{
for (size_t i = 0; i < numGenericPacks; i++)
{
log.pushSeen(superFunction->genericPacks[i], subFunction->genericPacks[i]);
}
}
CountMismatch::Context context = ctx;
if (!isFunctionCall)
{
Unifier innerState = makeChildUnifier();
innerState.ctx = CountMismatch::Arg;
innerState.tryUnify_(superFunction->argTypes, subFunction->argTypes, isFunctionCall);
bool reported = !innerState.errors.empty();
if (auto e = hasUnificationTooComplex(innerState.errors))
reportError(*e);
else if (!innerState.errors.empty() && innerState.firstPackErrorPos)
reportError(
TypeError{location, TypeMismatch{superTy, subTy, format("Argument #%d type is not compatible.", *innerState.firstPackErrorPos),
innerState.errors.front()}});
else if (!innerState.errors.empty())
reportError(TypeError{location, TypeMismatch{superTy, subTy, "", innerState.errors.front()}});
innerState.ctx = CountMismatch::Result;
innerState.tryUnify_(subFunction->retType, superFunction->retType);
if (!reported)
{
if (auto e = hasUnificationTooComplex(innerState.errors))
reportError(*e);
else if (!innerState.errors.empty() && size(superFunction->retType) == 1 && finite(superFunction->retType))
reportError(TypeError{location, TypeMismatch{superTy, subTy, "Return type is not compatible.", innerState.errors.front()}});
else if (!innerState.errors.empty() && innerState.firstPackErrorPos)
reportError(
TypeError{location, TypeMismatch{superTy, subTy, format("Return #%d type is not compatible.", *innerState.firstPackErrorPos),
innerState.errors.front()}});
else if (!innerState.errors.empty())
reportError(TypeError{location, TypeMismatch{superTy, subTy, "", innerState.errors.front()}});
}
log.concat(std::move(innerState.log));
}
else
{
ctx = CountMismatch::Arg;
tryUnify_(superFunction->argTypes, subFunction->argTypes, isFunctionCall);
ctx = CountMismatch::Result;
tryUnify_(subFunction->retType, superFunction->retType);
}
if (FFlag::LuauTxnLogRefreshFunctionPointers)
{
// Updating the log may have invalidated the function pointers
superFunction = log.getMutable<FunctionTypeVar>(superTy);
subFunction = log.getMutable<FunctionTypeVar>(subTy);
}
if (!FFlag::LuauImmutableTypes)
{
if (superFunction->definition && !subFunction->definition && !subTy->persistent)
{
PendingType* newSubTy = log.queue(subTy);
FunctionTypeVar* newSubFtv = getMutable<FunctionTypeVar>(newSubTy);
LUAU_ASSERT(newSubFtv);
newSubFtv->definition = superFunction->definition;
}
else if (!superFunction->definition && subFunction->definition && !superTy->persistent)
{
PendingType* newSuperTy = log.queue(superTy);
FunctionTypeVar* newSuperFtv = getMutable<FunctionTypeVar>(newSuperTy);
LUAU_ASSERT(newSuperFtv);
newSuperFtv->definition = subFunction->definition;
}
}
ctx = context;
if (FFlag::LuauTxnLogSeesTypePacks2)
{
for (int i = int(numGenericPacks) - 1; 0 <= i; i--)
{
log.popSeen(superFunction->genericPacks[i], subFunction->genericPacks[i]);
}
}
for (int i = int(numGenerics) - 1; 0 <= i; i--)
{
log.popSeen(superFunction->generics[i], subFunction->generics[i]);
}
}
namespace
{
struct Resetter
{
explicit Resetter(Variance* variance)
: oldValue(*variance)
, variance(variance)
{
}
Variance oldValue;
Variance* variance;
~Resetter()
{
*variance = oldValue;
}
};
} // namespace
void Unifier::tryUnifyTables(TypeId subTy, TypeId superTy, bool isIntersection)
{
if (!FFlag::LuauTableSubtypingVariance2)
return DEPRECATED_tryUnifyTables(subTy, superTy, isIntersection);
TableTypeVar* superTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* subTable = log.getMutable<TableTypeVar>(subTy);
if (!superTable || !subTable)
ice("passed non-table types to unifyTables");
std::vector<std::string> missingProperties;
std::vector<std::string> extraProperties;
// Optimization: First test that the property sets are compatible without doing any recursive unification
if (!subTable->indexer && subTable->state != TableState::Free)
{
for (const auto& [propName, superProp] : superTable->props)
{
auto subIter = subTable->props.find(propName);
if (FFlag::LuauAnyInIsOptionalIsOptional)
{
if (subIter == subTable->props.end() && (!FFlag::LuauSubtypingAddOptPropsToUnsealedTables || subTable->state == TableState::Unsealed) && !isOptional(superProp.type))
missingProperties.push_back(propName);
}
else
{
bool isAny = log.getMutable<AnyTypeVar>(log.follow(superProp.type));
if (subIter == subTable->props.end() && (!FFlag::LuauSubtypingAddOptPropsToUnsealedTables || subTable->state == TableState::Unsealed) && !isOptional(superProp.type) && !isAny)
missingProperties.push_back(propName);
}
}
if (!missingProperties.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(missingProperties)}});
return;
}
}
// And vice versa if we're invariant
if (variance == Invariant && !superTable->indexer && superTable->state != TableState::Unsealed &&
superTable->state != TableState::Free)
{
for (const auto& [propName, subProp] : subTable->props)
{
auto superIter = superTable->props.find(propName);
if (FFlag::LuauAnyInIsOptionalIsOptional)
{
if (superIter == superTable->props.end() && (FFlag::LuauSubtypingAddOptPropsToUnsealedTables || !isOptional(subProp.type)))
extraProperties.push_back(propName);
}
else
{
bool isAny = log.is<AnyTypeVar>(log.follow(subProp.type));
if (superIter == superTable->props.end() && (FFlag::LuauSubtypingAddOptPropsToUnsealedTables || (!isOptional(subProp.type) && !isAny)))
extraProperties.push_back(propName);
}
}
if (!extraProperties.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(extraProperties), MissingProperties::Extra}});
return;
}
}
// Width subtyping: any property in the supertype must be in the subtype,
// and the types must agree.
for (const auto& [name, prop] : superTable->props)
{
const auto& r = subTable->props.find(name);
if (r != subTable->props.end())
{
// TODO: read-only properties don't need invariance
Resetter resetter{&variance};
variance = Invariant;
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(r->second.type, prop.type);
checkChildUnifierTypeMismatch(innerState.errors, name, superTy, subTy);
if (innerState.errors.empty())
log.concat(std::move(innerState.log));
}
else if (subTable->indexer && maybeString(subTable->indexer->indexType))
{
// TODO: read-only indexers don't need invariance
// TODO: really we should only allow this if prop.type is optional.
Resetter resetter{&variance};
variance = Invariant;
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(subTable->indexer->indexResultType, prop.type);
checkChildUnifierTypeMismatch(innerState.errors, name, superTy, subTy);
if (innerState.errors.empty())
log.concat(std::move(innerState.log));
}
else if (FFlag::LuauAnyInIsOptionalIsOptional && (!FFlag::LuauSubtypingAddOptPropsToUnsealedTables || subTable->state == TableState::Unsealed) && isOptional(prop.type))
// This is sound because unsealed table types are precise, so `{ p : T } <: { p : T, q : U? }`
// since if `t : { p : T }` then we are guaranteed that `t.q` is `nil`.
// TODO: if the supertype is written to, the subtype may no longer be precise (alias analysis?)
{
}
else if ((!FFlag::LuauSubtypingAddOptPropsToUnsealedTables || subTable->state == TableState::Unsealed) && (isOptional(prop.type) || get<AnyTypeVar>(follow(prop.type))))
// This is sound because unsealed table types are precise, so `{ p : T } <: { p : T, q : U? }`
// since if `t : { p : T }` then we are guaranteed that `t.q` is `nil`.
// TODO: should isOptional(anyType) be true?
// TODO: if the supertype is written to, the subtype may no longer be precise (alias analysis?)
{
}
else if (subTable->state == TableState::Free)
{
PendingType* pendingSub = log.queue(subTy);
TableTypeVar* ttv = getMutable<TableTypeVar>(pendingSub);
LUAU_ASSERT(ttv);
ttv->props[name] = prop;
subTable = ttv;
}
else
missingProperties.push_back(name);
if (FFlag::LuauTxnLogCheckForInvalidation)
{
// Recursive unification can change the txn log, and invalidate the old
// table. If we detect that this has happened, we start over, with the updated
// txn log.
TableTypeVar* newSuperTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* newSubTable = log.getMutable<TableTypeVar>(subTy);
if (superTable != newSuperTable || subTable != newSubTable)
{
if (errors.empty())
return tryUnifyTables(subTy, superTy, isIntersection);
else
return;
}
}
}
for (const auto& [name, prop] : subTable->props)
{
if (superTable->props.count(name))
{
// If both lt and rt contain the property, then
// we're done since we already unified them above
}
else if (superTable->indexer && maybeString(superTable->indexer->indexType))
{
// TODO: read-only indexers don't need invariance
// TODO: really we should only allow this if prop.type is optional.
Resetter resetter{&variance};
variance = Invariant;
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(superTable->indexer->indexResultType, prop.type);
checkChildUnifierTypeMismatch(innerState.errors, name, superTy, subTy);
if (innerState.errors.empty())
log.concat(std::move(innerState.log));
}
else if (superTable->state == TableState::Unsealed)
{
// TODO: this case is unsound when variance is Invariant, but without it lua-apps fails to typecheck.
// TODO: file a JIRA
// TODO: hopefully readonly/writeonly properties will fix this.
Property clone = prop;
clone.type = deeplyOptional(clone.type);
PendingType* pendingSuper = log.queue(superTy);
TableTypeVar* pendingSuperTtv = getMutable<TableTypeVar>(pendingSuper);
pendingSuperTtv->props[name] = clone;
superTable = pendingSuperTtv;
}
else if (variance == Covariant)
{
}
else if (FFlag::LuauAnyInIsOptionalIsOptional && !FFlag::LuauSubtypingAddOptPropsToUnsealedTables && isOptional(prop.type))
{
}
else if (!FFlag::LuauSubtypingAddOptPropsToUnsealedTables && (isOptional(prop.type) || get<AnyTypeVar>(follow(prop.type))))
{
}
else if (superTable->state == TableState::Free)
{
PendingType* pendingSuper = log.queue(superTy);
TableTypeVar* pendingSuperTtv = getMutable<TableTypeVar>(pendingSuper);
pendingSuperTtv->props[name] = prop;
superTable = pendingSuperTtv;
}
else
extraProperties.push_back(name);
if (FFlag::LuauTxnLogCheckForInvalidation)
{
// Recursive unification can change the txn log, and invalidate the old
// table. If we detect that this has happened, we start over, with the updated
// txn log.
TableTypeVar* newSuperTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* newSubTable = log.getMutable<TableTypeVar>(subTy);
if (superTable != newSuperTable || subTable != newSubTable)
{
if (errors.empty())
return tryUnifyTables(subTy, superTy, isIntersection);
else
return;
}
}
}
// Unify indexers
if (superTable->indexer && subTable->indexer)
{
// TODO: read-only indexers don't need invariance
Resetter resetter{&variance};
variance = Invariant;
Unifier innerState = makeChildUnifier();
innerState.tryUnifyIndexer(*subTable->indexer, *superTable->indexer);
checkChildUnifierTypeMismatch(innerState.errors, superTy, subTy);
if (innerState.errors.empty())
log.concat(std::move(innerState.log));
}
else if (superTable->indexer)
{
if (subTable->state == TableState::Unsealed || subTable->state == TableState::Free)
{
// passing/assigning a table without an indexer to something that has one
// e.g. table.insert(t, 1) where t is a non-sealed table and doesn't have an indexer.
// TODO: we only need to do this if the supertype's indexer is read/write
// since that can add indexed elements.
log.changeIndexer(subTy, superTable->indexer);
}
}
else if (subTable->indexer && variance == Invariant)
{
// Symmetric if we are invariant
if (superTable->state == TableState::Unsealed || superTable->state == TableState::Free)
{
log.changeIndexer(superTy, subTable->indexer);
}
}
if (FFlag::LuauTxnLogDontRetryForIndexers)
{
// Changing the indexer can invalidate the table pointers.
superTable = log.getMutable<TableTypeVar>(superTy);
subTable = log.getMutable<TableTypeVar>(subTy);
}
else if (FFlag::LuauTxnLogCheckForInvalidation)
{
// Recursive unification can change the txn log, and invalidate the old
// table. If we detect that this has happened, we start over, with the updated
// txn log.
TableTypeVar* newSuperTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* newSubTable = log.getMutable<TableTypeVar>(subTy);
if (superTable != newSuperTable || subTable != newSubTable)
{
if (errors.empty())
return tryUnifyTables(subTy, superTy, isIntersection);
else
return;
}
}
if (!missingProperties.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(missingProperties)}});
return;
}
if (!extraProperties.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(extraProperties), MissingProperties::Extra}});
return;
}
/*
* TypeVars are commonly cyclic, so it is entirely possible
* for unifying a property of a table to change the table itself!
* We need to check for this and start over if we notice this occurring.
*
* I believe this is guaranteed to terminate eventually because this will
* only happen when a free table is bound to another table.
*/
if (superTable->boundTo || subTable->boundTo)
return tryUnify_(subTy, superTy);
if (superTable->state == TableState::Free)
{
log.bindTable(superTy, subTy);
}
else if (subTable->state == TableState::Free)
{
log.bindTable(subTy, superTy);
}
}
TypeId Unifier::widen(TypeId ty)
{
if (!FFlag::LuauWidenIfSupertypeIsFree2)
return ty;
Widen widen{types};
std::optional<TypeId> result = widen.substitute(ty);
// TODO: what does it mean for substitution to fail to widen?
return result.value_or(ty);
}
TypePackId Unifier::widen(TypePackId tp)
{
if (!FFlag::LuauWidenIfSupertypeIsFree2)
return tp;
Widen widen{types};
std::optional<TypePackId> result = widen.substitute(tp);
// TODO: what does it mean for substitution to fail to widen?
return result.value_or(tp);
}
TypeId Unifier::deeplyOptional(TypeId ty, std::unordered_map<TypeId, TypeId> seen)
{
ty = follow(ty);
if (!FFlag::LuauAnyInIsOptionalIsOptional && get<AnyTypeVar>(ty))
return ty;
else if (isOptional(ty))
return ty;
else if (const TableTypeVar* ttv = get<TableTypeVar>(ty))
{
TypeId& result = seen[ty];
if (result)
return result;
result = types->addType(*ttv);
TableTypeVar* resultTtv = getMutable<TableTypeVar>(result);
for (auto& [name, prop] : resultTtv->props)
prop.type = deeplyOptional(prop.type, seen);
return types->addType(UnionTypeVar{{getSingletonTypes().nilType, result}});
}
else
return types->addType(UnionTypeVar{{getSingletonTypes().nilType, ty}});
}
void Unifier::DEPRECATED_tryUnifyTables(TypeId subTy, TypeId superTy, bool isIntersection)
{
LUAU_ASSERT(!FFlag::LuauTableSubtypingVariance2);
Resetter resetter{&variance};
variance = Invariant;
TableTypeVar* superTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* subTable = log.getMutable<TableTypeVar>(subTy);
if (!superTable || !subTable)
ice("passed non-table types to unifyTables");
if (superTable->state == TableState::Sealed && subTable->state == TableState::Sealed)
return tryUnifySealedTables(subTy, superTy, isIntersection);
else if ((superTable->state == TableState::Sealed && subTable->state == TableState::Unsealed) ||
(superTable->state == TableState::Unsealed && subTable->state == TableState::Sealed))
return tryUnifySealedTables(subTy, superTy, isIntersection);
else if ((superTable->state == TableState::Sealed && subTable->state == TableState::Generic) ||
(superTable->state == TableState::Generic && subTable->state == TableState::Sealed))
reportError(TypeError{location, TypeMismatch{superTy, subTy}});
else if ((superTable->state == TableState::Free) != (subTable->state == TableState::Free)) // one table is free and the other is not
{
TypeId freeTypeId = subTable->state == TableState::Free ? subTy : superTy;
TypeId otherTypeId = subTable->state == TableState::Free ? superTy : subTy;
return tryUnifyFreeTable(otherTypeId, freeTypeId);
}
else if (superTable->state == TableState::Free && subTable->state == TableState::Free)
{
tryUnifyFreeTable(subTy, superTy);
// avoid creating a cycle when the types are already pointing at each other
if (follow(superTy) != follow(subTy))
{
log.bindTable(superTy, subTy);
}
return;
}
else if (superTable->state != TableState::Sealed && subTable->state != TableState::Sealed)
{
// All free tables are checked in one of the branches above
LUAU_ASSERT(superTable->state != TableState::Free);
LUAU_ASSERT(subTable->state != TableState::Free);
// Tables must have exactly the same props and their types must all unify
// I honestly have no idea if this is remotely close to reasonable.
for (const auto& [name, prop] : superTable->props)
{
const auto& r = subTable->props.find(name);
if (r == subTable->props.end())
reportError(TypeError{location, UnknownProperty{subTy, name}});
else
tryUnify_(r->second.type, prop.type);
}
if (superTable->indexer && subTable->indexer)
tryUnifyIndexer(*subTable->indexer, *superTable->indexer);
else if (superTable->indexer)
{
// passing/assigning a table without an indexer to something that has one
// e.g. table.insert(t, 1) where t is a non-sealed table and doesn't have an indexer.
if (subTable->state == TableState::Unsealed)
{
log.changeIndexer(subTy, superTable->indexer);
}
else
reportError(TypeError{location, CannotExtendTable{subTy, CannotExtendTable::Indexer}});
}
}
else if (superTable->state == TableState::Sealed)
{
// lt is sealed and so it must be possible for rt to have precisely the same shape
// Verify that this is the case, then bind rt to lt.
ice("unsealed tables are not working yet", location);
}
else if (subTable->state == TableState::Sealed)
return tryUnifyTables(superTy, subTy, isIntersection);
else
ice("tryUnifyTables");
}
void Unifier::tryUnifyFreeTable(TypeId subTy, TypeId superTy)
{
TableTypeVar* freeTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* subTable = log.getMutable<TableTypeVar>(subTy);
if (!freeTable || !subTable)
ice("passed non-table types to tryUnifyFreeTable");
// Any properties in freeTable must unify with those in otherTable.
// Then bind freeTable to otherTable.
for (const auto& [freeName, freeProp] : freeTable->props)
{
if (auto subProp = findTablePropertyRespectingMeta(subTy, freeName))
{
if (FFlag::LuauWidenIfSupertypeIsFree2)
tryUnify_(*subProp, freeProp.type);
else
tryUnify_(freeProp.type, *subProp);
/*
* TypeVars are commonly cyclic, so it is entirely possible
* for unifying a property of a table to change the table itself!
* We need to check for this and start over if we notice this occurring.
*
* I believe this is guaranteed to terminate eventually because this will
* only happen when a free table is bound to another table.
*/
if (!log.getMutable<TableTypeVar>(superTy) || !log.getMutable<TableTypeVar>(subTy))
return tryUnify_(subTy, superTy);
if (TableTypeVar* pendingFreeTtv = log.getMutable<TableTypeVar>(superTy); pendingFreeTtv && pendingFreeTtv->boundTo)
return tryUnify_(subTy, superTy);
}
else
{
// If the other table is also free, then we are learning that it has more
// properties than we previously thought. Else, it is an error.
if (subTable->state == TableState::Free)
{
PendingType* pendingSub = log.queue(subTy);
TableTypeVar* pendingSubTtv = getMutable<TableTypeVar>(pendingSub);
LUAU_ASSERT(pendingSubTtv);
pendingSubTtv->props.insert({freeName, freeProp});
}
else
reportError(TypeError{location, UnknownProperty{subTy, freeName}});
}
}
if (freeTable->indexer && subTable->indexer)
{
Unifier innerState = makeChildUnifier();
innerState.tryUnifyIndexer(*subTable->indexer, *freeTable->indexer);
checkChildUnifierTypeMismatch(innerState.errors, superTy, subTy);
log.concat(std::move(innerState.log));
}
else if (subTable->state == TableState::Free && freeTable->indexer)
{
log.changeIndexer(superTy, subTable->indexer);
}
if (!freeTable->boundTo && subTable->state != TableState::Free)
{
log.bindTable(superTy, subTy);
}
}
void Unifier::tryUnifySealedTables(TypeId subTy, TypeId superTy, bool isIntersection)
{
TableTypeVar* superTable = log.getMutable<TableTypeVar>(superTy);
TableTypeVar* subTable = log.getMutable<TableTypeVar>(subTy);
if (!superTable || !subTable)
ice("passed non-table types to unifySealedTables");
Unifier innerState = makeChildUnifier();
std::vector<std::string> missingPropertiesInSuper;
bool isUnnamedTable = subTable->name == std::nullopt && subTable->syntheticName == std::nullopt;
bool errorReported = false;
// Optimization: First test that the property sets are compatible without doing any recursive unification
if (!subTable->indexer)
{
for (const auto& [propName, superProp] : superTable->props)
{
auto subIter = subTable->props.find(propName);
if (subIter == subTable->props.end() && !isOptional(superProp.type))
missingPropertiesInSuper.push_back(propName);
}
if (!missingPropertiesInSuper.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(missingPropertiesInSuper)}});
return;
}
}
// Tables must have exactly the same props and their types must all unify
for (const auto& it : superTable->props)
{
const auto& r = subTable->props.find(it.first);
if (r == subTable->props.end())
{
if (isOptional(it.second.type))
continue;
missingPropertiesInSuper.push_back(it.first);
innerState.reportError(TypeError{location, TypeMismatch{superTy, subTy}});
}
else
{
if (isUnnamedTable && r->second.location)
{
size_t oldErrorSize = innerState.errors.size();
Location old = innerState.location;
innerState.location = *r->second.location;
innerState.tryUnify_(r->second.type, it.second.type);
innerState.location = old;
if (oldErrorSize != innerState.errors.size() && !errorReported)
{
errorReported = true;
reportError(innerState.errors.back());
}
}
else
{
innerState.tryUnify_(r->second.type, it.second.type);
}
}
}
if (superTable->indexer || subTable->indexer)
{
if (superTable->indexer && subTable->indexer)
innerState.tryUnifyIndexer(*subTable->indexer, *superTable->indexer);
else if (subTable->state == TableState::Unsealed)
{
if (superTable->indexer && !subTable->indexer)
{
log.changeIndexer(subTy, superTable->indexer);
}
}
else if (superTable->state == TableState::Unsealed)
{
if (subTable->indexer && !superTable->indexer)
{
log.changeIndexer(superTy, subTable->indexer);
}
}
else if (superTable->indexer)
{
innerState.tryUnify_(getSingletonTypes().stringType, superTable->indexer->indexType);
for (const auto& [name, type] : subTable->props)
{
const auto& it = superTable->props.find(name);
if (it == superTable->props.end())
innerState.tryUnify_(type.type, superTable->indexer->indexResultType);
}
}
else
innerState.reportError(TypeError{location, TypeMismatch{superTy, subTy}});
}
if (!errorReported)
log.concat(std::move(innerState.log));
else
return;
if (!missingPropertiesInSuper.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(missingPropertiesInSuper)}});
return;
}
// If the superTy is an immediate part of an intersection type, do not do extra-property check.
// Otherwise, we would falsely generate an extra-property-error for 's' in this code:
// local a: {n: number} & {s: string} = {n=1, s=""}
// When checking against the table '{n: number}'.
if (!isIntersection && superTable->state != TableState::Unsealed && !superTable->indexer)
{
// Check for extra properties in the subTy
std::vector<std::string> extraPropertiesInSub;
for (const auto& [subKey, subProp] : subTable->props)
{
const auto& superIt = superTable->props.find(subKey);
if (superIt == superTable->props.end())
{
if (isOptional(subProp.type))
continue;
extraPropertiesInSub.push_back(subKey);
}
}
if (!extraPropertiesInSub.empty())
{
reportError(TypeError{location, MissingProperties{superTy, subTy, std::move(extraPropertiesInSub), MissingProperties::Extra}});
return;
}
}
checkChildUnifierTypeMismatch(innerState.errors, superTy, subTy);
}
void Unifier::tryUnifyWithMetatable(TypeId subTy, TypeId superTy, bool reversed)
{
const MetatableTypeVar* superMetatable = get<MetatableTypeVar>(superTy);
if (!superMetatable)
ice("tryUnifyMetatable invoked with non-metatable TypeVar");
TypeError mismatchError = TypeError{location, TypeMismatch{reversed ? subTy : superTy, reversed ? superTy : subTy}};
if (const MetatableTypeVar* subMetatable = log.getMutable<MetatableTypeVar>(subTy))
{
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(subMetatable->table, superMetatable->table);
innerState.tryUnify_(subMetatable->metatable, superMetatable->metatable);
if (auto e = hasUnificationTooComplex(innerState.errors))
reportError(*e);
else if (!innerState.errors.empty())
reportError(TypeError{location, TypeMismatch{reversed ? subTy : superTy, reversed ? superTy : subTy, "", innerState.errors.front()}});
log.concat(std::move(innerState.log));
}
else if (TableTypeVar* subTable = log.getMutable<TableTypeVar>(subTy))
{
switch (subTable->state)
{
case TableState::Free:
{
tryUnify_(subTy, superMetatable->table);
log.bindTable(subTy, superTy);
break;
}
// We know the shape of sealed, unsealed, and generic tables; you can't add a metatable on to any of these.
case TableState::Sealed:
case TableState::Unsealed:
case TableState::Generic:
reportError(mismatchError);
}
}
else if (log.getMutable<AnyTypeVar>(subTy) || log.getMutable<ErrorTypeVar>(subTy))
{
}
else
{
reportError(mismatchError);
}
}
// Class unification is almost, but not quite symmetrical. We use the 'reversed' boolean to indicate which scenario we are evaluating.
void Unifier::tryUnifyWithClass(TypeId subTy, TypeId superTy, bool reversed)
{
if (reversed)
std::swap(superTy, subTy);
auto fail = [&]() {
if (!reversed)
reportError(TypeError{location, TypeMismatch{superTy, subTy}});
else
reportError(TypeError{location, TypeMismatch{subTy, superTy}});
};
const ClassTypeVar* superClass = get<ClassTypeVar>(superTy);
if (!superClass)
ice("tryUnifyClass invoked with non-class TypeVar");
if (const ClassTypeVar* subClass = get<ClassTypeVar>(subTy))
{
switch (variance)
{
case Covariant:
if (!isSubclass(subClass, superClass))
return fail();
return;
case Invariant:
if (subClass != superClass)
return fail();
return;
}
ice("Illegal variance setting!");
}
else if (TableTypeVar* subTable = getMutable<TableTypeVar>(subTy))
{
/**
* A free table is something whose shape we do not exactly know yet.
* Thus, it is entirely reasonable that we might discover that it is being used as some class type.
* In this case, the free table must indeed be that exact class.
* For this to hold, the table must not have any properties that the class does not.
* Further, all properties of the table should unify cleanly with the matching class properties.
* TODO: What does it mean for the table to have an indexer? (probably failure?)
*
* Tables that are not free are known to be actual tables.
*/
if (subTable->state != TableState::Free)
return fail();
bool ok = true;
for (const auto& [propName, prop] : subTable->props)
{
const Property* classProp = lookupClassProp(superClass, propName);
if (!classProp)
{
ok = false;
reportError(TypeError{location, UnknownProperty{superTy, propName}});
}
else
{
Unifier innerState = makeChildUnifier();
innerState.tryUnify_(classProp->type, prop.type);
checkChildUnifierTypeMismatch(innerState.errors, propName, reversed ? subTy : superTy, reversed ? superTy : subTy);
if (innerState.errors.empty())
{
log.concat(std::move(innerState.log));
}
else
{
ok = false;
}
}
}
if (subTable->indexer)
{
ok = false;
std::string msg = "Class " + superClass->name + " does not have an indexer";
reportError(TypeError{location, GenericError{msg}});
}
if (!ok)
return;
log.bindTable(subTy, superTy);
}
else
return fail();
}
void Unifier::tryUnifyIndexer(const TableIndexer& subIndexer, const TableIndexer& superIndexer)
{
tryUnify_(subIndexer.indexType, superIndexer.indexType);
tryUnify_(subIndexer.indexResultType, superIndexer.indexResultType);
}
static void queueTypePack(std::vector<TypeId>& queue, DenseHashSet<TypePackId>& seenTypePacks, Unifier& state, TypePackId a, TypePackId anyTypePack)
{
while (true)
{
a = state.log.follow(a);
if (seenTypePacks.find(a))
break;
seenTypePacks.insert(a);
if (state.log.getMutable<Unifiable::Free>(a))
{
state.log.replace(a, Unifiable::Bound{anyTypePack});
}
else if (auto tp = state.log.getMutable<TypePack>(a))
{
queue.insert(queue.end(), tp->head.begin(), tp->head.end());
if (tp->tail)
a = *tp->tail;
else
break;
}
}
}
void Unifier::tryUnifyVariadics(TypePackId subTp, TypePackId superTp, bool reversed, int subOffset)
{
const VariadicTypePack* superVariadic = log.getMutable<VariadicTypePack>(superTp);
if (!superVariadic)
ice("passed non-variadic pack to tryUnifyVariadics");
if (const VariadicTypePack* subVariadic = get<VariadicTypePack>(subTp))
tryUnify_(reversed ? superVariadic->ty : subVariadic->ty, reversed ? subVariadic->ty : superVariadic->ty);
else if (get<TypePack>(subTp))
{
TypePackIterator subIter = begin(subTp, &log);
TypePackIterator subEnd = end(subTp);
std::advance(subIter, subOffset);
while (subIter != subEnd)
{
tryUnify_(reversed ? superVariadic->ty : *subIter, reversed ? *subIter : superVariadic->ty);
++subIter;
}
if (std::optional<TypePackId> maybeTail = subIter.tail())
{
TypePackId tail = follow(*maybeTail);
if (get<FreeTypePack>(tail))
{
log.replace(tail, BoundTypePack(superTp));
}
else if (const VariadicTypePack* vtp = get<VariadicTypePack>(tail))
{
tryUnify_(vtp->ty, superVariadic->ty);
}
else if (get<Unifiable::Generic>(tail))
{
reportError(TypeError{location, GenericError{"Cannot unify variadic and generic packs"}});
}
else if (get<Unifiable::Error>(tail))
{
// Nothing to do here.
}
else
{
ice("Unknown TypePack kind");
}
}
}
else
{
reportError(TypeError{location, GenericError{"Failed to unify variadic packs"}});
}
}
static void tryUnifyWithAny(std::vector<TypeId>& queue, Unifier& state, DenseHashSet<TypeId>& seen, DenseHashSet<TypePackId>& seenTypePacks,
const TypeArena* typeArena, TypeId anyType, TypePackId anyTypePack)
{
while (!queue.empty())
{
TypeId ty = state.log.follow(queue.back());
queue.pop_back();
// Types from other modules don't have free types
if (FFlag::LuauImmutableTypes && ty->owningArena != typeArena)
continue;
if (seen.find(ty))
continue;
seen.insert(ty);
if (state.log.getMutable<FreeTypeVar>(ty))
{
state.log.replace(ty, BoundTypeVar{anyType});
}
else if (auto fun = state.log.getMutable<FunctionTypeVar>(ty))
{
queueTypePack(queue, seenTypePacks, state, fun->argTypes, anyTypePack);
queueTypePack(queue, seenTypePacks, state, fun->retType, anyTypePack);
}
else if (auto table = state.log.getMutable<TableTypeVar>(ty))
{
for (const auto& [_name, prop] : table->props)
queue.push_back(prop.type);
if (table->indexer)
{
queue.push_back(table->indexer->indexType);
queue.push_back(table->indexer->indexResultType);
}
}
else if (auto mt = state.log.getMutable<MetatableTypeVar>(ty))
{
queue.push_back(mt->table);
queue.push_back(mt->metatable);
}
else if (state.log.getMutable<ClassTypeVar>(ty))
{
// ClassTypeVars never contain free typevars.
}
else if (auto union_ = state.log.getMutable<UnionTypeVar>(ty))
queue.insert(queue.end(), union_->options.begin(), union_->options.end());
else if (auto intersection = state.log.getMutable<IntersectionTypeVar>(ty))
queue.insert(queue.end(), intersection->parts.begin(), intersection->parts.end());
else
{
} // Primitives, any, errors, and generics are left untouched.
}
}
void Unifier::tryUnifyWithAny(TypeId subTy, TypeId anyTy)
{
LUAU_ASSERT(get<AnyTypeVar>(anyTy) || get<ErrorTypeVar>(anyTy));
// These types are not visited in general loop below
if (get<PrimitiveTypeVar>(subTy) || get<AnyTypeVar>(subTy) || get<ClassTypeVar>(subTy))
return;
const TypePackId anyTypePack = types->addTypePack(TypePackVar{VariadicTypePack{getSingletonTypes().anyType}});
const TypePackId anyTP = get<AnyTypeVar>(anyTy) ? anyTypePack : types->addTypePack(TypePackVar{Unifiable::Error{}});
std::vector<TypeId> queue = {subTy};
sharedState.tempSeenTy.clear();
sharedState.tempSeenTp.clear();
Luau::tryUnifyWithAny(queue, *this, sharedState.tempSeenTy, sharedState.tempSeenTp, types, getSingletonTypes().anyType, anyTP);
}
void Unifier::tryUnifyWithAny(TypePackId subTy, TypePackId anyTp)
{
LUAU_ASSERT(get<Unifiable::Error>(anyTp));
const TypeId anyTy = getSingletonTypes().errorRecoveryType();
std::vector<TypeId> queue;
sharedState.tempSeenTy.clear();
sharedState.tempSeenTp.clear();
queueTypePack(queue, sharedState.tempSeenTp, *this, subTy, anyTp);
Luau::tryUnifyWithAny(queue, *this, sharedState.tempSeenTy, sharedState.tempSeenTp, types, anyTy, anyTp);
}
std::optional<TypeId> Unifier::findTablePropertyRespectingMeta(TypeId lhsType, Name name)
{
return Luau::findTablePropertyRespectingMeta(errors, lhsType, name, location);
}
void Unifier::occursCheck(TypeId needle, TypeId haystack)
{
sharedState.tempSeenTy.clear();
return occursCheck(sharedState.tempSeenTy, needle, haystack);
}
void Unifier::occursCheck(DenseHashSet<TypeId>& seen, TypeId needle, TypeId haystack)
{
RecursionLimiter _ra(&sharedState.counters.recursionCount, FInt::LuauTypeInferRecursionLimit);
auto check = [&](TypeId tv) {
occursCheck(seen, needle, tv);
};
needle = log.follow(needle);
haystack = log.follow(haystack);
if (seen.find(haystack))
return;
seen.insert(haystack);
if (log.getMutable<Unifiable::Error>(needle))
return;
if (!log.getMutable<Unifiable::Free>(needle))
ice("Expected needle to be free");
if (needle == haystack)
{
reportError(TypeError{location, OccursCheckFailed{}});
log.replace(needle, *getSingletonTypes().errorRecoveryType());
return;
}
if (log.getMutable<FreeTypeVar>(haystack))
return;
else if (auto a = log.getMutable<UnionTypeVar>(haystack))
{
for (TypeId ty : a->options)
check(ty);
}
else if (auto a = log.getMutable<IntersectionTypeVar>(haystack))
{
for (TypeId ty : a->parts)
check(ty);
}
}
void Unifier::occursCheck(TypePackId needle, TypePackId haystack)
{
sharedState.tempSeenTp.clear();
return occursCheck(sharedState.tempSeenTp, needle, haystack);
}
void Unifier::occursCheck(DenseHashSet<TypePackId>& seen, TypePackId needle, TypePackId haystack)
{
needle = log.follow(needle);
haystack = log.follow(haystack);
if (seen.find(haystack))
return;
seen.insert(haystack);
if (log.getMutable<Unifiable::Error>(needle))
return;
if (!log.getMutable<Unifiable::Free>(needle))
ice("Expected needle pack to be free");
RecursionLimiter _ra(&sharedState.counters.recursionCount, FInt::LuauTypeInferRecursionLimit);
while (!log.getMutable<ErrorTypeVar>(haystack))
{
if (needle == haystack)
{
reportError(TypeError{location, OccursCheckFailed{}});
log.replace(needle, *getSingletonTypes().errorRecoveryTypePack());
return;
}
if (auto a = get<TypePack>(haystack); a && a->tail)
{
haystack = log.follow(*a->tail);
continue;
}
break;
}
}
Unifier Unifier::makeChildUnifier()
{
return Unifier{types, mode, log.sharedSeen, location, variance, sharedState, &log};
}
bool Unifier::isNonstrictMode() const
{
return (mode == Mode::Nonstrict) || (mode == Mode::NoCheck);
}
void Unifier::checkChildUnifierTypeMismatch(const ErrorVec& innerErrors, TypeId wantedType, TypeId givenType)
{
if (auto e = hasUnificationTooComplex(innerErrors))
reportError(*e);
else if (!innerErrors.empty())
reportError(TypeError{location, TypeMismatch{wantedType, givenType}});
}
void Unifier::checkChildUnifierTypeMismatch(const ErrorVec& innerErrors, const std::string& prop, TypeId wantedType, TypeId givenType)
{
if (auto e = hasUnificationTooComplex(innerErrors))
reportError(*e);
else if (!innerErrors.empty())
reportError(
TypeError{location, TypeMismatch{wantedType, givenType, format("Property '%s' is not compatible.", prop.c_str()), innerErrors.front()}});
}
void Unifier::ice(const std::string& message, const Location& location)
{
sharedState.iceHandler->ice(message, location);
}
void Unifier::ice(const std::string& message)
{
sharedState.iceHandler->ice(message);
}
} // namespace Luau
| 33.857143 | 191 | 0.61299 | [
"shape",
"vector"
] |
60a9ca64a072a4ad903089b5d04624e4431914b5 | 2,905 | cpp | C++ | aws-cpp-sdk-greengrassv2/source/model/CloudComponentState.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-greengrassv2/source/model/CloudComponentState.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-greengrassv2/source/model/CloudComponentState.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/greengrassv2/model/CloudComponentState.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace GreengrassV2
{
namespace Model
{
namespace CloudComponentStateMapper
{
static const int REQUESTED_HASH = HashingUtils::HashString("REQUESTED");
static const int INITIATED_HASH = HashingUtils::HashString("INITIATED");
static const int DEPLOYABLE_HASH = HashingUtils::HashString("DEPLOYABLE");
static const int FAILED_HASH = HashingUtils::HashString("FAILED");
static const int DEPRECATED_HASH = HashingUtils::HashString("DEPRECATED");
CloudComponentState GetCloudComponentStateForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == REQUESTED_HASH)
{
return CloudComponentState::REQUESTED;
}
else if (hashCode == INITIATED_HASH)
{
return CloudComponentState::INITIATED;
}
else if (hashCode == DEPLOYABLE_HASH)
{
return CloudComponentState::DEPLOYABLE;
}
else if (hashCode == FAILED_HASH)
{
return CloudComponentState::FAILED;
}
else if (hashCode == DEPRECATED_HASH)
{
return CloudComponentState::DEPRECATED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<CloudComponentState>(hashCode);
}
return CloudComponentState::NOT_SET;
}
Aws::String GetNameForCloudComponentState(CloudComponentState enumValue)
{
switch(enumValue)
{
case CloudComponentState::REQUESTED:
return "REQUESTED";
case CloudComponentState::INITIATED:
return "INITIATED";
case CloudComponentState::DEPLOYABLE:
return "DEPLOYABLE";
case CloudComponentState::FAILED:
return "FAILED";
case CloudComponentState::DEPRECATED:
return "DEPRECATED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace CloudComponentStateMapper
} // namespace Model
} // namespace GreengrassV2
} // namespace Aws
| 31.576087 | 92 | 0.620654 | [
"model"
] |
60aadfea6e6af59eb98e56e8201968e05cd53d75 | 867 | hpp | C++ | src/GUI/DropDown.hpp | scawful/project-awful | ebf5908b4a9e9fc0b12bf24cb8c7e21983d88ba6 | [
"MIT"
] | 4 | 2021-05-12T15:02:40.000Z | 2021-06-04T23:01:16.000Z | src/GUI/DropDown.hpp | scawful/project-awful | ebf5908b4a9e9fc0b12bf24cb8c7e21983d88ba6 | [
"MIT"
] | null | null | null | src/GUI/DropDown.hpp | scawful/project-awful | ebf5908b4a9e9fc0b12bf24cb8c7e21983d88ba6 | [
"MIT"
] | 9 | 2021-05-13T21:54:52.000Z | 2021-12-11T01:55:55.000Z | #ifndef DropDown_hpp
#define DropDown_hpp
#include "../core.hpp"
#include "Button.hpp"
class DropDown
{
private:
float keytime;
float keytimeMax;
sf::Font& font;
Button* activeElement;
std::vector<Button*> list;
bool showList;
public:
DropDown(sf::Vector2f position, sf::Vector2f size, sf::Font& font, std::string list[], unsigned numElements, const unsigned default_index = 0);
~DropDown();
// Modifiers
void setColors( sf::Color text_idle, sf::Color text_hover, sf::Color text_active, sf::Color active, sf::Color idle, sf::Color hover );
// Accessors
const bool getKeytime();
// Update routines
void updateKeytime(const float& dt);
void update(const sf::Vector2f& mousePos, const float& dt);
// Render routine
void render(sf::RenderTarget& target);
};
#endif /* DropDown_hpp */ | 24.771429 | 147 | 0.670127 | [
"render",
"vector"
] |
60b69da1d23e275e8c43da760db90444428c940e | 10,359 | hxx | C++ | odb-tests-2.4.0/common/section/basics/test.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/common/section/basics/test.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | odb-tests-2.4.0/common/section/basics/test.hxx | edidada/odb | 78ed750a9dde65a627fc33078225410306c2e78b | [
"MIT"
] | null | null | null | // file : common/section/basics/test.hxx
// copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC
// license : GNU GPL v2; see accompanying LICENSE file
#ifndef TEST_HXX
#define TEST_HXX
#include <string>
#include <vector>
#include <odb/core.hxx>
#include <odb/section.hxx>
#include <odb/vector.hxx>
#ifdef ODB_COMPILER
# if defined(ODB_DATABASE_PGSQL)
# define BLOB_TYPE "BYTEA"
# elif defined(ODB_DATABASE_MSSQL)
# define BLOB_TYPE "VARBINARY(max)"
# else
# define BLOB_TYPE "BLOB"
# endif
#endif
// Test lazy-loaded, always-updated section.
//
#pragma db namespace table("t1_")
namespace test1
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
#pragma db load(lazy)
odb::section s;
#pragma db section(s)
int sn;
int n;
#pragma db section(s)
std::string ss;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test lazy-loaded, change-updated section.
//
#pragma db namespace table("t2_")
namespace test2
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
#pragma db load(lazy) update(change)
odb::section s;
#pragma db section(s)
int sn;
int n;
#pragma db section(s)
std::string ss;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test lazy-loaded, manually-updated section.
//
#pragma db namespace table("t3_")
namespace test3
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
#pragma db load(lazy) update(manual)
odb::section s;
#pragma db section(s)
int sn;
int n;
#pragma db section(s)
std::string ss;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test eager-loaded, change-updated section.
//
#pragma db namespace table("t4_")
namespace test4
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
#pragma db section(s)
int sn;
#pragma db update(change)
odb::section s;
int n;
#pragma db section(s)
std::string ss;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test eager-loaded, manually-updated section.
//
#pragma db namespace table("t5_")
namespace test5
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
#pragma db section(s)
int sn;
#pragma db update(manual)
odb::section s;
int n;
#pragma db section(s)
std::string ss;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test value-only and container-only section. Also multiple sections
// in an object.
//
#pragma db namespace table("t6_")
namespace test6
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: n (n_), sn (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
int n;
#pragma db load(lazy)
odb::section s1;
#pragma db load(lazy)
odb::section s2;
#pragma db section(s1)
int sn;
#pragma db section(s1)
std::string ss;
#pragma db section(s2)
std::vector<int> sv;
};
}
// Test sections and reuse inheritance.
//
#pragma db namespace table("t7_")
namespace test7
{
#pragma db object abstract
struct base
{
#pragma db id auto
unsigned long id;
#pragma db load(lazy)
odb::section s1; // Empty section.
#pragma db load(lazy)
odb::section s2;
#pragma db section(s2)
int sn2;
};
#pragma db object abstract
struct interm: base
{
// Section s1 is still empty.
#pragma db section(s2)
std::string ss2;
};
#pragma db object
struct derived: interm
{
#pragma db section(s1)
int sn1;
};
#pragma db object
struct object: derived
{
object (int n = 999, const std::string& s = "xxx", bool b = false)
{
sn1 = sn2 = n;
ss1 = ss2 = s;
sb2 = b;
}
#pragma db section(s1)
std::string ss1;
#pragma db section(s2)
bool sb2;
};
}
// Test readonly and inverse section members.
//
#pragma db namespace table("t8_")
namespace test8
{
struct object1;
#pragma db object session
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx", object1* p_ = 0)
: n (n_), sn (n_), ss (s_), sp (p_) {}
#pragma db id auto
unsigned long id;
int n;
#pragma db load(lazy)
odb::section s;
#pragma db section(s) readonly
int sn;
#pragma db section(s)
std::string ss;
#pragma db inverse(p) section(s)
object1* sp;
};
#pragma db object session
struct object1
{
object1 (object* p_ = 0): p (p_) {}
~object1 () {delete p;}
#pragma db id auto
unsigned long id;
object* p;
};
}
// Test object without any columns to load or update.
//
#pragma db namespace table("t9_")
namespace test9
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx"): sn (n_), ss (s_) {}
#pragma db id auto
unsigned long id;
#pragma db load(lazy) update(manual)
odb::section s;
#pragma db section(s)
int sn;
#pragma db section(s)
std::string ss;
};
}
// Test section without any columns or containers to update.
//
#pragma db namespace table("t10_")
namespace test10
{
#pragma db object
struct object
{
object (int n_ = 999): n (n_), sn (n_) {}
#pragma db id auto
unsigned long id;
int n;
#pragma db load(lazy)
odb::section s;
#pragma db section(s) readonly
int sn;
};
}
// Test section with composite member.
//
#pragma db namespace table("t11_")
namespace test11
{
#pragma db value
struct comp
{
comp (int n_, const std::string& s_): s (s_) {v.push_back (n_);}
std::string s;
std::vector<int> v;
};
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: n (n_), sn (n_), sc (n_, s_) {}
#pragma db id auto
unsigned long id;
int n;
#pragma db load(lazy)
odb::section s;
#pragma db section(s)
int sn;
#pragma db section(s)
comp sc;
};
}
// Test change state restoration on transaction rollback.
//
#pragma db namespace table("t12_")
namespace test12
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {}
#pragma db id auto
unsigned long id;
#pragma db load(lazy) update(change)
odb::section s;
#pragma db section(s)
int sn;
int n;
#pragma db section(s)
std::string ss;
};
}
// Test section accessor/modifier.
//
#pragma db namespace table("t13_")
namespace test13
{
#pragma db object
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: n (n_), sn (n_), ss (s_) {}
#pragma db id auto
unsigned long id;
int n;
#pragma db section(s_)
int sn;
#pragma db section(s_)
std::string ss;
public:
const odb::section&
s () const {return s_;}
odb::section&
rw_s () {return s_;}
private:
#pragma db load(lazy) update(manual)
odb::section s_;
};
}
// Test LOB in section streaming, column re-ordering.
//
#pragma db namespace table("t14_")
namespace test14
{
#pragma db object
struct object
{
object (unsigned long id_ = 0, int n_ = 999, const std::string& s_ = "xxx")
: id (id_), sb (s_.begin (), s_.end ()), sn (n_), n (n_) {}
#pragma db id
unsigned long id;
#pragma db load(lazy)
odb::section s;
#pragma db section(s) type(BLOB_TYPE)
std::vector<char> sb; // Comes before sn.
#pragma db section(s)
int sn;
int n;
};
}
// Test sections and optimistic concurrency.
//
#pragma db namespace table("t15_")
namespace test15
{
#pragma db object optimistic
struct object
{
object (int n_ = 999, const std::string& s_ = "xxx")
: sn (n_), n (n_), ss (s_) {sv.push_back (n_);}
#pragma db id auto
unsigned long id;
#pragma db version mssql:type("ROWVERSION")
unsigned long long v;
#pragma db load(lazy)
odb::section s;
#pragma db section(s)
int sn;
int n;
#pragma db section(s)
std::string ss;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test container-only sections and optimistic concurrency.
//
#pragma db namespace table("t16_")
namespace test16
{
#pragma db object optimistic
struct object
{
object (int n = 999) {sv.push_back (n);}
#pragma db id auto
unsigned long id;
#pragma db version // mssql:type("ROWVERSION")
unsigned long long v;
#pragma db load(lazy)
odb::section s;
#pragma db section(s)
std::vector<int> sv;
};
}
// Test reuse-inheritance, sections, and optimistic concurrency.
//
#pragma db namespace table("t17_")
namespace test17
{
#pragma db object optimistic sectionable abstract
struct root
{
#pragma db id auto
unsigned long id;
#pragma db version
unsigned long long v;
};
#pragma db object
struct base: root
{
};
#pragma db object
struct object: base
{
object (int n = 999): s1n (n) {s2v.push_back (n);}
#pragma db load(lazy)
odb::section s1;
#pragma db section(s1)
int s1n;
#pragma db load(lazy)
odb::section s2;
#pragma db section(s2)
std::vector<int> s2v;
};
}
// Test change-updated section and change-tracking container.
//
#pragma db namespace table("t18_")
namespace test18
{
#pragma db object
struct object
{
object (int n = 999): sn (n) {sv.push_back (n);}
#pragma db id auto
unsigned long id;
#pragma db load(lazy) update(change)
odb::section s;
#pragma db section(s)
int sn;
#pragma db section(s)
odb::vector<int> sv;
};
}
#endif // TEST_HXX
| 17.236273 | 79 | 0.602375 | [
"object",
"vector"
] |
60b7577b398a5caf1eff1e00f0f015a7470d03e9 | 4,860 | hpp | C++ | source/coo.hpp | cyanpelican/cs6235-gpu-hicoo | debcda712e60706b99001808196d43c8f19ce1f9 | [
"MIT"
] | 2 | 2020-07-10T05:30:21.000Z | 2020-07-10T05:30:27.000Z | source/coo.hpp | cyanpelican/cs6235-gpu-hicoo | debcda712e60706b99001808196d43c8f19ce1f9 | [
"MIT"
] | 4 | 2019-04-30T23:27:34.000Z | 2019-04-30T23:27:39.000Z | source/coo.hpp | cyanpelican/cs6235-gpu-hicoo | debcda712e60706b99001808196d43c8f19ce1f9 | [
"MIT"
] | null | null | null |
#ifndef COO_HPP
#define COO_HPP
#include <memory>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>
#include <assert.h>
#include "common.hpp"
#include "dense.hpp"
struct CooPoint {
unsigned int x, y, z;
float value;
};
enum PointSorting {
UNSORTED,
XYZ,
ZYX,
Z_MORTON
};
class DenseMatrixManager;
class HicooTensorManager;
class DenseTensorManager;
struct CooTensor {
CooPoint* points_h;
CooPoint* points_d;
PointSorting sorting;
unsigned long long numElements;
unsigned int width, height, depth;
CooTensor() {
DEBUG_PRINT("CT: constructor\n");
points_h = nullptr;
points_d = nullptr;
sorting = UNSORTED;
numElements = 0;
width = 0;
height = 0;
depth = 0;
}
~CooTensor() {
// handled by an owner
}
/* utility functions */
// dangerous; deletes everything
void freeAllArrays();
void freeHostArrays();
void freeDeviceArrays();
// safely uploads to gpu
void uploadToDevice();
// safely downloads from gpu
void downloadToHost();
// a handy function to get an element on either host or device
CooPoint& __host__ __device__ access(unsigned int element) {
#ifdef __CUDA_ARCH__
return points_d[element];
#else
#if ENABLE_ACCESS_ASSERTS
assert(element < numElements);
#endif
return points_h[element];
#endif
}
// float __host__ __device__ access(int x, int y, int z) {
// for (unsigned int i = 0; i < this->numElements; i++) {
// if(access(i).x == x && access(i).y == y && access(i).z == z) {
// #ifdef __CUDA_ARCH__
// return points_d[i].value;
// #else
// return points_h[i].value;
// #endif
// }
// }
//
// //value not found: it's a 0
// return 0.0;
// }
//
// __host__ __device__ float access_sorted(int x, int y, int z) {
// for (unsigned int i = 0; i < this->numElements; i++) {
// if (access(i).x == x && access(i).y == y && access(i).z == z) {
// #ifdef __CUDA_ARCH__
// return points_d[i].value;
// #else
// return points_h[i].value;
// #endif
// }
// //or is it the z we should be checking...?
// if (access(i).x > x)
// break;
// }
//
// //value not found: it's a 0
// return 0.0;
// }
void setSize(int numPoints, int depth, int height, int width) {
DEBUG_PRINT("CT: setSize (# %d, d %d, h %d, w %d)\n", numPoints, depth, height, width);
freeAllArrays();
points_h = (CooPoint*)malloc(sizeof(CooPoint) * numPoints);
assert(points_h != nullptr);
this->numElements = numPoints;
this->width = width;
this->height = height;
this->depth = depth;
}
unsigned long long getTotalMemory() {
DEBUG_PRINT("CT: get total memory\n");
return sizeof(CooPoint) * numElements + sizeof(CooTensor);
}
/* conversion functions */
HicooTensorManager toHicoo(int blockWidth = 2, int blockHeight = 2, int blockDepth = 2);
DenseTensorManager toDense();
/* compute functions */
// A(i,j) = B(i,k,l) * D(l,j) * C(k,j);
DenseMatrixManager mttkrp_naive_cpu(DenseMatrixManager d, DenseMatrixManager c);
DenseMatrixManager mttkrp_naive_gpu(DenseMatrixManager d, DenseMatrixManager c);
DenseMatrixManager mttkrp_kevin1(DenseMatrixManager d, DenseMatrixManager c);
};
// Don't make these. They're just middlemen.
struct CooTensorUnique {
CooTensor tensor;
CooTensorUnique() {
// nothing exciting to do
}
~CooTensorUnique() {
DEBUG_PRINT("CTU: auto-free from unique destructor\n");
tensor.freeAllArrays();
}
};
// NOTE - build these, not CooTensors; this does memory management
// However, when performing compute, just pass CooTensors, since they're lighter.
// The cast operator is overloaded, so it's possible to also use/pass these as if they're CooTensors
// MAKE SURE that when you cast it, you:
// - keep it as a CooTensor& [don't forget the ampersand] if you're going to modify any properties or alloc/free pointers
// - pass it as a CooTensor [no ampersand] when passing to the GPU
struct CooTensorManager {
std::shared_ptr<CooTensorUnique> tensor;
CooTensorManager():
tensor(new CooTensorUnique()) {
DEBUG_PRINT("CTM: constructor\n");
}
/* utility functions */
operator CooTensor&() {
return tensor->tensor;
}
/* parsing, conversion & creation functions */
// TODO
void create(char *tensorFileName);
};
#endif
| 26.413043 | 122 | 0.589506 | [
"vector"
] |
60bbf39da7345e3cf6a68e63a8a38178405d6680 | 3,211 | cpp | C++ | quickstart/cpp/windows/translate-speech-to-text/helloworld/helloworld.cpp | LeeJAJA/cognitive-services-speech-sdk | 44076b1011d845867a55bc40cd250364657a1c6b | [
"MIT"
] | 1 | 2019-10-08T23:38:55.000Z | 2019-10-08T23:38:55.000Z | quickstart/cpp/windows/translate-speech-to-text/helloworld/helloworld.cpp | LeeJAJA/cognitive-services-speech-sdk | 44076b1011d845867a55bc40cd250364657a1c6b | [
"MIT"
] | 1 | 2021-12-09T23:05:00.000Z | 2021-12-09T23:05:00.000Z | quickstart/cpp/windows/translate-speech-to-text/helloworld/helloworld.cpp | LeeJAJA/cognitive-services-speech-sdk | 44076b1011d845867a55bc40cd250364657a1c6b | [
"MIT"
] | null | null | null | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "pch.h"
// <code>
#include <iostream>
#include <vector>
#include <speechapi_cxx.h>
using namespace std;
using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Translation;
// Translation with microphone input.
void TranslationWithMicrophone()
{
// Creates an instance of a speech translation config with specified subscription key and service region.
// Replace with your own subscription key and service region (e.g., "westus").
auto config = SpeechTranslationConfig::FromSubscription("YourSubscriptionKey", "YourServiceRegion");
// Sets source and target languages
// Replace with the languages of your choice.
auto fromLanguage = "en-US";
config->SetSpeechRecognitionLanguage(fromLanguage);
config->AddTargetLanguage("de");
config->AddTargetLanguage("fr");
// Creates a translation recognizer using microphone as audio input.
auto recognizer = TranslationRecognizer::FromConfig(config);
cout << "Say something...\n";
// Starts translation, and returns after a single utterance is recognized. The end of a
// single utterance is determined by listening for silence at the end or until a maximum of 15
// seconds of audio is processed. The task returns the recognized text as well as the translation.
// Note: Since RecognizeOnceAsync() returns only a single utterance, it is suitable only for single
// shot recognition like command or query.
// For long-running multi-utterance recognition, use StartContinuousRecognitionAsync() instead.
auto result = recognizer->RecognizeOnceAsync().get();
// Checks result.
if (result->Reason == ResultReason::TranslatedSpeech)
{
cout << "RECOGNIZED: Text=" << result->Text << std::endl
<< " Language=" << fromLanguage << std::endl;
for (const auto& it : result->Translations)
{
cout << "TRANSLATED into '" << it.first.c_str() << "': " << it.second.c_str() << std::endl;
}
}
else if (result->Reason == ResultReason::RecognizedSpeech)
{
cout << "RECOGNIZED: Text=" << result->Text << " (text could not be translated)" << std::endl;
}
else if (result->Reason == ResultReason::NoMatch)
{
cout << "NOMATCH: Speech could not be recognized." << std::endl;
}
else if (result->Reason == ResultReason::Canceled)
{
auto cancellation = CancellationDetails::FromResult(result);
cout << "CANCELED: Reason=" << (int)cancellation->Reason << std::endl;
if (cancellation->Reason == CancellationReason::Error)
{
cout << "CANCELED: ErrorCode=" << (int)cancellation->ErrorCode << std::endl;
cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails << std::endl;
cout << "CANCELED: Did you update the subscription info?" << std::endl;
}
}
}
int wmain()
{
TranslationWithMicrophone();
cout << "Please press a key to continue.\n";
cin.get();
return 0;
}
// </code>
| 38.686747 | 109 | 0.66895 | [
"vector"
] |
60c214b3e2310529c38ab8396af4ce040f670e8c | 3,658 | cpp | C++ | apps/point_cloud/image_transport_plugins/compressed_depth_image_transport/src/compressed_depth_publisher.cpp | ramonidea/prl_wireless_perception | 69dd79d7b150dfc2be38d6e38ed650931564b03a | [
"MIT"
] | 742 | 2017-07-05T02:49:36.000Z | 2022-03-30T12:55:43.000Z | apps/point_cloud/image_transport_plugins/compressed_depth_image_transport/src/compressed_depth_publisher.cpp | ramonidea/prl_wireless_perception | 69dd79d7b150dfc2be38d6e38ed650931564b03a | [
"MIT"
] | 73 | 2017-07-06T12:50:51.000Z | 2022-03-07T08:07:07.000Z | apps/point_cloud/image_transport_plugins/compressed_depth_image_transport/src/compressed_depth_publisher.cpp | ramonidea/prl_wireless_perception | 69dd79d7b150dfc2be38d6e38ed650931564b03a | [
"MIT"
] | 425 | 2017-07-04T22:03:29.000Z | 2022-03-29T06:59:06.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 20012, Willow Garage, 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:
*
* * 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 Willow Garage 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.
*********************************************************************/
#include "compressed_depth_image_transport/compressed_depth_publisher.h"
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/highgui/highgui.hpp>
#include <boost/make_shared.hpp>
#include "compressed_depth_image_transport/codec.h"
#include "compressed_depth_image_transport/compression_common.h"
#include <vector>
#include <sstream>
using namespace cv;
using namespace std;
namespace enc = sensor_msgs::image_encodings;
namespace compressed_depth_image_transport
{
void CompressedDepthPublisher::advertiseImpl(ros::NodeHandle &nh, const std::string &base_topic, uint32_t queue_size,
const image_transport::SubscriberStatusCallback &user_connect_cb,
const image_transport::SubscriberStatusCallback &user_disconnect_cb,
const ros::VoidPtr &tracked_object, bool latch)
{
typedef image_transport::SimplePublisherPlugin<sensor_msgs::CompressedImage> Base;
Base::advertiseImpl(nh, base_topic, queue_size, user_connect_cb, user_disconnect_cb, tracked_object, latch);
// Set up reconfigure server for this topic
reconfigure_server_ = boost::make_shared<ReconfigureServer>(this->nh());
ReconfigureServer::CallbackType f = boost::bind(&CompressedDepthPublisher::configCb, this, _1, _2);
reconfigure_server_->setCallback(f);
}
void CompressedDepthPublisher::configCb(Config& config, uint32_t level)
{
config_ = config;
}
void CompressedDepthPublisher::publish(const sensor_msgs::Image& message, const PublishFn& publish_fn) const
{
sensor_msgs::CompressedImage::Ptr compressed_image =
encodeCompressedDepthImage(message, config_.depth_max, config_.depth_quantization, config_.png_level);
if (compressed_image)
{
publish_fn(*compressed_image);
}
}
} //namespace compressed_depth_image_transport
| 42.534884 | 117 | 0.732094 | [
"vector"
] |
60c6b2bf6be7747e25bc4e7ea16406133b5e260b | 7,212 | cpp | C++ | ReactAndroid/build/third-party-ndk/folly/folly/test/MathTest.cpp | kimwoongkyu/react-native-0-36-1-woogie | 4fb2d44945a6305ae3ca87be3872f9432d16f1fb | [
"BSD-3-Clause"
] | 199 | 2016-09-08T03:44:56.000Z | 2022-03-19T04:18:30.000Z | ReactAndroid/build/third-party-ndk/folly/folly/test/MathTest.cpp | kimwoongkyu/react-native-0-36-1-woogie | 4fb2d44945a6305ae3ca87be3872f9432d16f1fb | [
"BSD-3-Clause"
] | 50 | 2016-09-07T23:44:14.000Z | 2022-02-16T16:50:25.000Z | ReactAndroid/build/third-party-ndk/folly/folly/test/MathTest.cpp | kimwoongkyu/react-native-0-36-1-woogie | 4fb2d44945a6305ae3ca87be3872f9432d16f1fb | [
"BSD-3-Clause"
] | 67 | 2016-09-19T10:18:45.000Z | 2022-02-16T09:42:47.000Z | /*
* Copyright 2016 Facebook, 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 <folly/Math.h>
#include <algorithm>
#include <type_traits>
#include <utility>
#include <vector>
#include <glog/logging.h>
#include <folly/Portability.h>
#include <folly/portability/GTest.h>
using namespace folly;
using namespace folly::detail;
namespace {
// Workaround for https://llvm.org/bugs/show_bug.cgi?id=16404,
// issues with __int128 multiplication and UBSAN
template <typename T>
T mul(T lhs, T rhs) {
if (rhs < 0) {
rhs = -rhs;
lhs = -lhs;
}
T accum = 0;
while (rhs != 0) {
if ((rhs & 1) != 0) {
accum += lhs;
}
lhs += lhs;
rhs >>= 1;
}
return accum;
}
template <typename T, typename B>
T referenceDivFloor(T numer, T denom) {
// rv = largest integral value <= numer / denom
B n = numer;
B d = denom;
if (d < 0) {
d = -d;
n = -n;
}
B r = n / d;
while (mul(r, d) > n) {
--r;
}
while (mul(r + 1, d) <= n) {
++r;
}
T rv = static_cast<T>(r);
assert(static_cast<B>(rv) == r);
return rv;
}
template <typename T, typename B>
T referenceDivCeil(T numer, T denom) {
// rv = smallest integral value >= numer / denom
B n = numer;
B d = denom;
if (d < 0) {
d = -d;
n = -n;
}
B r = n / d;
while (mul(r, d) < n) {
++r;
}
while (mul(r - 1, d) >= n) {
--r;
}
T rv = static_cast<T>(r);
assert(static_cast<B>(rv) == r);
return rv;
}
template <typename T, typename B>
T referenceDivRoundAway(T numer, T denom) {
if ((numer < 0) != (denom < 0)) {
return referenceDivFloor<T, B>(numer, denom);
} else {
return referenceDivCeil<T, B>(numer, denom);
}
}
template <typename T>
std::vector<T> cornerValues() {
std::vector<T> rv;
for (T i = 1; i < 24; ++i) {
rv.push_back(i);
rv.push_back(std::numeric_limits<T>::max() / i);
rv.push_back(std::numeric_limits<T>::max() - i);
rv.push_back(std::numeric_limits<T>::max() / 2 - i);
if (std::is_signed<T>::value) {
rv.push_back(-i);
rv.push_back(std::numeric_limits<T>::min() / i);
rv.push_back(std::numeric_limits<T>::min() + i);
rv.push_back(std::numeric_limits<T>::min() / 2 + i);
}
}
return rv;
}
template <typename A, typename B, typename C>
void runDivTests() {
using T = decltype(static_cast<A>(1) / static_cast<B>(1));
auto numers = cornerValues<A>();
numers.push_back(0);
auto denoms = cornerValues<B>();
for (A n : numers) {
for (B d : denoms) {
if (std::is_signed<T>::value && n == std::numeric_limits<T>::min() &&
d == static_cast<T>(-1)) {
// n / d overflows in two's complement
continue;
}
EXPECT_EQ(divCeil(n, d), (referenceDivCeil<T, C>(n, d))) << n << "/" << d;
EXPECT_EQ(divFloor(n, d), (referenceDivFloor<T, C>(n, d))) << n << "/"
<< d;
EXPECT_EQ(divTrunc(n, d), n / d) << n << "/" << d;
EXPECT_EQ(divRoundAway(n, d), (referenceDivRoundAway<T, C>(n, d)))
<< n << "/" << d;
T nn = n;
T dd = d;
EXPECT_EQ(divCeilBranchless(nn, dd), divCeilBranchful(nn, dd));
EXPECT_EQ(divFloorBranchless(nn, dd), divFloorBranchful(nn, dd));
EXPECT_EQ(divRoundAwayBranchless(nn, dd), divRoundAwayBranchful(nn, dd));
}
}
}
}
TEST(Bits, divTestInt8) {
runDivTests<int8_t, int8_t, int64_t>();
runDivTests<int8_t, uint8_t, int64_t>();
runDivTests<int8_t, int16_t, int64_t>();
runDivTests<int8_t, uint16_t, int64_t>();
runDivTests<int8_t, int32_t, int64_t>();
runDivTests<int8_t, uint32_t, int64_t>();
#if FOLLY_HAVE_INT128_T
runDivTests<int8_t, int64_t, __int128>();
runDivTests<int8_t, uint64_t, __int128>();
#endif
}
TEST(Bits, divTestInt16) {
runDivTests<int16_t, int8_t, int64_t>();
runDivTests<int16_t, uint8_t, int64_t>();
runDivTests<int16_t, int16_t, int64_t>();
runDivTests<int16_t, uint16_t, int64_t>();
runDivTests<int16_t, int32_t, int64_t>();
runDivTests<int16_t, uint32_t, int64_t>();
#if FOLLY_HAVE_INT128_T
runDivTests<int16_t, int64_t, __int128>();
runDivTests<int16_t, uint64_t, __int128>();
#endif
}
TEST(Bits, divTestInt32) {
runDivTests<int32_t, int8_t, int64_t>();
runDivTests<int32_t, uint8_t, int64_t>();
runDivTests<int32_t, int16_t, int64_t>();
runDivTests<int32_t, uint16_t, int64_t>();
runDivTests<int32_t, int32_t, int64_t>();
runDivTests<int32_t, uint32_t, int64_t>();
#if FOLLY_HAVE_INT128_T
runDivTests<int32_t, int64_t, __int128>();
runDivTests<int32_t, uint64_t, __int128>();
#endif
}
#if FOLLY_HAVE_INT128_T
TEST(Bits, divTestInt64) {
runDivTests<int64_t, int8_t, __int128>();
runDivTests<int64_t, uint8_t, __int128>();
runDivTests<int64_t, int16_t, __int128>();
runDivTests<int64_t, uint16_t, __int128>();
runDivTests<int64_t, int32_t, __int128>();
runDivTests<int64_t, uint32_t, __int128>();
runDivTests<int64_t, int64_t, __int128>();
runDivTests<int64_t, uint64_t, __int128>();
}
#endif
TEST(Bits, divTestUint8) {
runDivTests<uint8_t, int8_t, int64_t>();
runDivTests<uint8_t, uint8_t, int64_t>();
runDivTests<uint8_t, int16_t, int64_t>();
runDivTests<uint8_t, uint16_t, int64_t>();
runDivTests<uint8_t, int32_t, int64_t>();
runDivTests<uint8_t, uint32_t, int64_t>();
#if FOLLY_HAVE_INT128_T
runDivTests<uint8_t, int64_t, __int128>();
runDivTests<uint8_t, uint64_t, __int128>();
#endif
}
TEST(Bits, divTestUint16) {
runDivTests<uint16_t, int8_t, int64_t>();
runDivTests<uint16_t, uint8_t, int64_t>();
runDivTests<uint16_t, int16_t, int64_t>();
runDivTests<uint16_t, uint16_t, int64_t>();
runDivTests<uint16_t, int32_t, int64_t>();
runDivTests<uint16_t, uint32_t, int64_t>();
#if FOLLY_HAVE_INT128_T
runDivTests<uint16_t, int64_t, __int128>();
runDivTests<uint16_t, uint64_t, __int128>();
#endif
}
TEST(Bits, divTestUint32) {
runDivTests<uint32_t, int8_t, int64_t>();
runDivTests<uint32_t, uint8_t, int64_t>();
runDivTests<uint32_t, int16_t, int64_t>();
runDivTests<uint32_t, uint16_t, int64_t>();
runDivTests<uint32_t, int32_t, int64_t>();
runDivTests<uint32_t, uint32_t, int64_t>();
#if FOLLY_HAVE_INT128_T
runDivTests<uint32_t, int64_t, __int128>();
runDivTests<uint32_t, uint64_t, __int128>();
#endif
}
#if FOLLY_HAVE_INT128_T
TEST(Bits, divTestUint64) {
runDivTests<uint64_t, int8_t, __int128>();
runDivTests<uint64_t, uint8_t, __int128>();
runDivTests<uint64_t, int16_t, __int128>();
runDivTests<uint64_t, uint16_t, __int128>();
runDivTests<uint64_t, int32_t, __int128>();
runDivTests<uint64_t, uint32_t, __int128>();
runDivTests<uint64_t, int64_t, __int128>();
runDivTests<uint64_t, uint64_t, __int128>();
}
#endif
| 29.198381 | 80 | 0.655158 | [
"vector"
] |
60cb69ac9d058b724fdd155e529d4774223f40fa | 1,155 | cpp | C++ | src/bt_composite_node.cpp | quabug/godot_behavior_tree | 9881a4977f87daf3d0506a9ad915cfbeb58b5f02 | [
"MIT"
] | 44 | 2015-01-20T15:44:30.000Z | 2021-11-13T04:39:12.000Z | src/bt_composite_node.cpp | quabug/godot_behavior_tree | 9881a4977f87daf3d0506a9ad915cfbeb58b5f02 | [
"MIT"
] | null | null | null | src/bt_composite_node.cpp | quabug/godot_behavior_tree | 9881a4977f87daf3d0506a9ad915cfbeb58b5f02 | [
"MIT"
] | 13 | 2015-01-10T19:16:15.000Z | 2021-03-08T19:09:08.000Z | #include "bt_composite_node.h"
void BTCompositeNode::add_child_node(BTNode& child, Vector<BehaviorTree::Node*>& node_hierarchy) {
BTNode* p_parent = get_parent() ? get_parent()->cast_to<BTNode>() : NULL;
ERR_EXPLAIN("Parent node is not a BTNode.");
ERR_FAIL_NULL(p_parent);
if (p_parent) {
node_hierarchy.push_back(get_behavior_node());
p_parent->add_child_node(child, node_hierarchy);
}
}
void BTCompositeNode::remove_child_node(BTNode& child, Vector<BehaviorTree::Node*>& node_hierarchy) {
BTNode* p_parent = get_parent() ? get_parent()->cast_to<BTNode>() : NULL;
//ERR_EXPLAIN("Parent node is not a BTNode.");
//ERR_FAIL_NULL(p_parent);
if (p_parent) {
node_hierarchy.push_back(get_behavior_node());
p_parent->remove_child_node(child, node_hierarchy);
}
}
void BTCompositeNode::move_child_node(BTNode& child, Vector<BehaviorTree::Node*>& node_hierarchy) {
BTNode* p_parent = get_parent() ? get_parent()->cast_to<BTNode>() : NULL;
//ERR_EXPLAIN("Parent node is not a BTNode.");
//ERR_FAIL_NULL(p_parent);
if (p_parent) {
node_hierarchy.push_back(get_behavior_node());
p_parent->move_child_node(child, node_hierarchy);
}
}
| 35 | 101 | 0.745455 | [
"vector"
] |
60cbd674872749cff34b15b064800756bb2f0280 | 5,302 | cpp | C++ | inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_matmul.cpp | monroid/openvino | 8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6 | [
"Apache-2.0"
] | 2,406 | 2020-04-22T15:47:54.000Z | 2022-03-31T10:27:37.000Z | inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_matmul.cpp | monroid/openvino | 8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6 | [
"Apache-2.0"
] | 4,948 | 2020-04-22T15:12:39.000Z | 2022-03-31T18:45:42.000Z | inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_matmul.cpp | monroid/openvino | 8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6 | [
"Apache-2.0"
] | 991 | 2020-04-23T18:21:09.000Z | 2022-03-31T18:40:57.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "vpu/ngraph/transformations/dynamic_to_static_shape_matmul.hpp"
#include "vpu/ngraph/operations/dynamic_shape_resolver.hpp"
#include "vpu/ngraph/utilities.hpp"
#include <vpu/utils/error.hpp>
#include "ngraph/graph_util.hpp"
#include "ngraph/opsets/opset3.hpp"
#include <memory>
#include <numeric>
namespace vpu {
void get_normalized_shape(ngraph::Output<ngraph::Node>& shape, size_t actual_rank_value, size_t max_rank_value, bool transpose,
const ngraph::element::Type& elementType) {
if (const size_t rank_diff = max_rank_value - actual_rank_value) {
ngraph::OutputVector extended_shape_parts =
{ngraph::opset3::Constant::create(elementType, {rank_diff}, std::vector<int64_t>(rank_diff, 1)), shape};
shape = std::make_shared<ngraph::opset3::Concat>(extended_shape_parts, 0);
}
if (transpose) {
std::vector<int64_t> indices_value(max_rank_value);
std::iota(indices_value.begin(), indices_value.end(), 0);
std::iter_swap(indices_value.rbegin(), indices_value.rbegin() + 1);
const auto indices = ngraph::opset3::Constant::create(ngraph::element::i64, {indices_value.size()}, indices_value);
const auto axis = ngraph::opset3::Constant::create(ngraph::element::i64, {}, std::vector<int64_t>{0});
shape = std::make_shared<ngraph::opset3::Gather>(shape, indices, axis);
}
}
void dynamicToStaticShapeMatMul(std::shared_ptr<ngraph::Node> target) {
const auto matmul = ngraph::as_type_ptr<ngraph::opset3::MatMul>(target);
VPU_THROW_UNLESS(matmul, "dynamicToStaticShapeMatMul transformation is not applicable for {}, it should be {} instead",
target, ngraph::opset3::MatMul::get_type_info_static());
const auto a_input_DSR = ngraph::as_type_ptr<ngraph::vpu::op::DynamicShapeResolver>(target->input_value(0).get_node_shared_ptr());
const auto b_input_DSR = ngraph::as_type_ptr<ngraph::vpu::op::DynamicShapeResolver>(target->input_value(1).get_node_shared_ptr());
if (a_input_DSR && b_input_DSR) {
VPU_THROW_UNLESS(a_input_DSR->get_input_element_type(1) == b_input_DSR->get_input_element_type(1),
"DynamicToStaticShape transformation for {} of type {} expects equal shapes data types, actual {} vs {}",
matmul->get_friendly_name(), matmul->get_type_info(),
a_input_DSR->get_input_element_type(1), b_input_DSR->get_input_element_type(1));
}
VPU_THROW_UNLESS(a_input_DSR || b_input_DSR, "DynamicToStaticShape transformation for {} of type {} expects at least one DSR as input",
target->get_friendly_name(), target->get_type_info());
const auto shapeElementType = a_input_DSR ? a_input_DSR->get_input_element_type(1) : b_input_DSR->get_input_element_type(1);
ngraph::Output<ngraph::Node> a_input_shape = a_input_DSR ? a_input_DSR->input_value(1) :
shapeToConstant(shapeElementType, target->get_input_shape(0));
ngraph::Output<ngraph::Node> b_input_shape = b_input_DSR ? b_input_DSR->input_value(1) :
shapeToConstant(shapeElementType, target->get_input_shape(1));
const auto& a_rank = a_input_shape.get_partial_shape();
const auto& b_rank = b_input_shape.get_partial_shape();
VPU_THROW_UNLESS(a_rank.is_static() && b_rank.is_static(), "DynamicToStaticShape transformation for {} doesn't support dynamic rank", matmul);
const auto a_rank_value = a_rank[0].get_length();
const auto b_rank_value = b_rank[0].get_length();
const auto max_rank_value = std::max(ngraph::Dimension::value_type(2), std::max(a_rank_value, b_rank_value));
get_normalized_shape(a_input_shape, a_rank_value, max_rank_value, matmul->get_transpose_a(), shapeElementType);
get_normalized_shape(b_input_shape, b_rank_value, max_rank_value, matmul->get_transpose_b(), shapeElementType);
ngraph::OutputVector output_dims;
if (max_rank_value > 2) {
// batch broadcasting
const auto max_shape = std::make_shared<ngraph::opset3::Maximum>(a_input_shape, b_input_shape);
output_dims.push_back(gatherShapeElements(max_shape, 0, max_rank_value - 2));
}
const auto input_channels = std::make_shared<ngraph::opset3::Gather>(
a_input_shape,
ngraph::opset3::Constant::create(ngraph::element::i64, {1}, {max_rank_value - 2}),
ngraph::opset3::Constant::create(ngraph::element::i64, {}, std::vector<int64_t>{0}));
const auto output_channels = std::make_shared<ngraph::opset3::Gather>(
b_input_shape,
ngraph::opset3::Constant::create(ngraph::element::i64, {1}, {max_rank_value - 1}),
ngraph::opset3::Constant::create(ngraph::element::i64, {}, std::vector<int64_t>{0}));
output_dims.push_back(input_channels);
output_dims.push_back(output_channels);
const auto output_shape = std::make_shared<ngraph::opset3::Concat>(output_dims, 0);
const auto copied = target->clone_with_new_inputs(target->input_values());
auto outDsr = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(copied, output_shape);
outDsr->set_friendly_name(target->get_friendly_name());
ngraph::replace_node(target, outDsr);
}
} // namespace vpu
| 55.810526 | 146 | 0.715579 | [
"shape",
"vector"
] |
f598fda019fea085177b1fa0243979d8efc31da4 | 148,515 | cpp | C++ | src/ast/ast_simulate.cpp | eguskov/daScript | faf2ae8ddfeab9e4a6cf9adbee738a8d9175a27c | [
"BSD-3-Clause"
] | null | null | null | src/ast/ast_simulate.cpp | eguskov/daScript | faf2ae8ddfeab9e4a6cf9adbee738a8d9175a27c | [
"BSD-3-Clause"
] | null | null | null | src/ast/ast_simulate.cpp | eguskov/daScript | faf2ae8ddfeab9e4a6cf9adbee738a8d9175a27c | [
"BSD-3-Clause"
] | null | null | null | #include "daScript/misc/platform.h"
#include "daScript/ast/ast.h"
#include "daScript/ast/ast_match.h"
#include "daScript/ast/ast_expressions.h"
#include "daScript/simulate/runtime_array.h"
#include "daScript/simulate/runtime_table_nodes.h"
#include "daScript/simulate/runtime_range.h"
#include "daScript/simulate/runtime_string_delete.h"
#include "daScript/simulate/hash.h"
#include "daScript/simulate/simulate_nodes.h"
#include "daScript/simulate/simulate_visit_op.h"
namespace das
{
// common for move and copy
SimNode * makeLocalCMResMove (const LineInfo & at, Context & context, uint32_t offset, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetCMResOfs>(rE->at, offset);
return right;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetCMResOfs>(rE->at, offset);
return right;
}
}
// now, to the regular move
auto left = context.code->makeNode<SimNode_GetCMResOfs>(at, offset);
auto right = rE->simulate(context);
if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_MoveRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeLocalCMResCopy(const LineInfo & at, Context & context, uint32_t offset, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
DAS_ASSERT ( rightType.canCopy() &&
"we are calling makeLocalCMResCopy on a type, which can't be copied."
"we should not be here, script compiler should have caught this during compilation."
"compiler later will likely report internal compilation error.");
auto right = rE->simulate(context);
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * rightC = (SimNode_CallBase *) right;
rightC->cmresEval = context.code->makeNode<SimNode_GetCMResOfs>(rE->at, offset);
return rightC;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * rightC = (SimNode_CallBase *) right;
rightC->cmresEval = context.code->makeNode<SimNode_GetCMResOfs>(rE->at, offset);
return rightC;
}
}
// wo standard path
auto left = context.code->makeNode<SimNode_GetCMResOfs>(rE->at, offset);
if ( rightType.isHandle() ) {
auto resN = rightType.annotation->simulateCopy(context, at, left,
(!rightType.isRefType() && rightType.ref) ? rightType.annotation->simulateRef2Value(context, at, right) : right);
if ( !resN ) {
context.thisProgram->error("integration error, simulateCopy returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_CopyRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeLocalRefMove (const LineInfo & at, Context & context, uint32_t stackTop, uint32_t offset, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetLocalRefOff>(rE->at, stackTop, offset);
return right;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetLocalRefOff>(rE->at, stackTop, offset);
return right;
}
}
// now, to the regular move
auto left = context.code->makeNode<SimNode_GetLocalRefOff>(at, stackTop, offset);
auto right = rE->simulate(context);
if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_MoveRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeLocalRefCopy(const LineInfo & at, Context & context, uint32_t stackTop, uint32_t offset, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
DAS_ASSERT ( rightType.canCopy() &&
"we are calling makeLocalRefCopy on a type, which can't be copied."
"we should not be here, script compiler should have caught this during compilation."
"compiler later will likely report internal compilation error.");
auto right = rE->simulate(context);
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * rightC = (SimNode_CallBase *) right;
rightC->cmresEval = context.code->makeNode<SimNode_GetLocalRefOff>(rE->at, stackTop, offset);
return rightC;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * rightC = (SimNode_CallBase *) right;
rightC->cmresEval = context.code->makeNode<SimNode_GetLocalRefOff>(rE->at, stackTop, offset);
return rightC;
}
}
// wo standard path
auto left = context.code->makeNode<SimNode_GetLocalRefOff>(rE->at, stackTop, offset);
if ( rightType.isHandle() ) {
auto resN = rightType.annotation->simulateCopy(context, at, left,
(!rightType.isRefType() && rightType.ref) ? rightType.annotation->simulateRef2Value(context, at, right) : right);
if ( !resN ) {
context.thisProgram->error("integration error, simulateCopy returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_CopyRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeLocalMove (const LineInfo & at, Context & context, uint32_t stackTop, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetLocal>(rE->at, stackTop);
return right;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetLocal>(rE->at, stackTop);
return right;
}
}
// now, to the regular move
auto left = context.code->makeNode<SimNode_GetLocal>(at, stackTop);
auto right = rE->simulate(context);
if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_MoveRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeLocalCopy(const LineInfo & at, Context & context, uint32_t stackTop, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
DAS_ASSERT ( rightType.canCopy() &&
"we are calling makeLocalCopy on a type, which can't be copied."
"we should not be here, script compiler should have caught this during compilation."
"compiler later will likely report internal compilation error.");
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetLocal>(rE->at, stackTop);
return right;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = context.code->makeNode<SimNode_GetLocal>(rE->at, stackTop);
return right;
}
}
// now, to the regular copy
auto left = context.code->makeNode<SimNode_GetLocal>(rE->at, stackTop);
auto right = rE->simulate(context);
if ( rightType.isHandle() ) {
auto resN = rightType.annotation->simulateCopy(context, at, left,
(!rightType.isRefType() && rightType.ref) ? rightType.annotation->simulateRef2Value(context, at, right) : right);
if ( !resN ) {
context.thisProgram->error("integration error, simulateCopy returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_CopyRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeCopy(const LineInfo & at, Context & context, const ExpressionPtr & lE, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
DAS_ASSERT ( rightType.canCopy() &&
"we are calling makeCopy on a type, which can't be copied."
"we should not be here, script compiler should have caught this during compilation."
"compiler later will likely report internal compilation error.");
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = lE->simulate(context);
return right;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = lE->simulate(context);
return right;
}
}
// now, to the regular copy
auto left = lE->simulate(context);
auto right = rE->simulate(context);
if ( rightType.isHandle() ) {
auto resN = rightType.annotation->simulateCopy(context, at, left,
(!rightType.isRefType() && rightType.ref) ? rightType.annotation->simulateRef2Value(context, at, right) : right);
if ( !resN ) {
context.thisProgram->error("integration error, simulateCopy returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else if ( rightType.isRef() ) {
return context.code->makeNode<SimNode_CopyRefValue>(at, left, right, rightType.getSizeOf());
} else {
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * makeMove (const LineInfo & at, Context & context, const ExpressionPtr & lE, const ExpressionPtr & rE ) {
const auto & rightType = *rE->type;
// now, call with CMRES
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = lE->simulate(context);
return right;
}
}
// now, invoke with CMRES
if ( rE->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(rE);
if ( cll->isCopyOrMove() ) {
SimNode_CallBase * right = (SimNode_CallBase *) rE->simulate(context);
right->cmresEval = lE->simulate(context);
return right;
}
}
// now to the regular one
if ( rightType.isRef() ) {
auto left = lE->simulate(context);
auto right = rE->simulate(context);
return context.code->makeNode<SimNode_MoveRefValue>(at, left, right, rightType.getSizeOf());
} else {
// this here might happen during initialization, by moving value types
// like var t <- 5
// its ok to generate simplified set here
auto left = lE->simulate(context);
auto right = rE->simulate(context);
return context.code->makeValueNode<SimNode_Set>(rightType.baseType, at, left, right);
}
}
SimNode * Function::makeSimNode ( Context & context, const vector<ExpressionPtr> & ) {
{
if ( copyOnReturn || moveOnReturn ) {
return context.code->makeNodeUnrollAny<SimNode_CallAndCopyOrMove>(int(arguments.size()), at);
} else if ( fastCall ) {
return context.code->makeNodeUnrollAny<SimNode_FastCall>(int(arguments.size()), at);
} else {
return context.code->makeNodeUnrollAny<SimNode_Call>(int(arguments.size()), at);
}
}
}
SimNode * Function::simulate (Context & context) const {
if ( builtIn ) {
DAS_ASSERTF(0, "can only simulate non built-in function");
return nullptr;
}
for ( auto & ann : annotations ) {
if ( ann->annotation->rtti_isFunctionAnnotation() ) {
auto fann = (FunctionAnnotation *)(ann->annotation.get());
string err;
auto node = fann->simulate(&context, (Function*)this, ann->arguments, err);
if ( !node ) {
if ( !err.empty() ) {
context.thisProgram->error("integration error, function failed to simulate", err, "",
at, CompilationError::missing_node );
return nullptr;
}
} else {
return node;
}
}
}
if ( fastCall ) {
DAS_ASSERT(totalStackSize == sizeof(Prologue) && "function can't allocate stack");
DAS_ASSERT((result->isWorkhorseType() || result->isVoid()) && "fastcall can only return a workhorse type");
DAS_ASSERT(body->rtti_isBlock() && "function must contain a block");
auto block = static_pointer_cast<ExprBlock>(body);
if ( block->list.size()==0 ) {
DAS_ASSERT(block->inFunction && block->inFunction->result->isVoid() && "only void function produces fastcall NOP");
return context.code->makeNode<SimNode_NOP>(block->at);
}
if ( block->list.back()->rtti_isReturn() ) {
DAS_ASSERT(block->list.back()->rtti_isReturn() && "fastcall body expr is return");
auto retE = static_pointer_cast<ExprReturn>(block->list.back());
if ( retE->subexpr ) {
return retE->subexpr->simulate(context);
} else {
return context.code->makeNode<SimNode_NOP>(retE->at);
}
} else {
return block->list.back()->simulate(context);
}
} else {
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
auto sbody = body->simulate(context);
if ( !sbody->rtti_node_isBlock() ) {
auto block = context.code->makeNode<SimNodeDebug_BlockNF>(sbody->debugInfo);
block->total = 1;
block->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*1);
block->list[0] = sbody;
return block;
} else {
return sbody;
}
} else {
return body->simulate(context);
}
#else
return body->simulate(context);
#endif
}
}
SimNode * Expression::trySimulate (Context &, uint32_t, const TypeDeclPtr &) const {
return nullptr;
}
void ExprMakeLocal::setRefSp ( bool ref, bool cmres, uint32_t sp, uint32_t off ) {
useStackRef = ref;
useCMRES = cmres;
doesNotNeedSp = true;
doesNotNeedInit = true;
stackTop = sp;
extraOffset = off;
}
vector<SimNode *> ExprMakeLocal::simulateLocal ( Context & /*context*/ ) const {
return vector<SimNode *>();
}
// variant
void ExprMakeVariant::setRefSp ( bool ref, bool cmres, uint32_t sp, uint32_t off ) {
ExprMakeLocal::setRefSp(ref, cmres, sp, off);
int stride = makeType->getStride();
// we go through all fields, and if its [[ ]] field
// we tell it to piggy-back on our current sp, with appropriate offset
int index = 0;
for ( const auto & decl : variants ) {
auto fieldVariant = makeType->findArgumentIndex(decl->name);
DAS_ASSERT(fieldVariant!=-1 && "should have failed in type infer otherwise");
auto fieldType = makeType->argTypes[fieldVariant];
if ( decl->value->rtti_isMakeLocal() ) {
auto fieldOffset = makeType->getVariantFieldOffset(fieldVariant);
uint32_t offset = extraOffset + index*stride + fieldOffset;
auto mkl = static_pointer_cast<ExprMakeLocal>(decl->value);
mkl->setRefSp(ref, cmres, sp, offset);
} else if ( decl->value->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(decl->value);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
cll->doesNotNeedSp = true;
}
} else if ( decl->value->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(decl->value);
if ( cll->isCopyOrMove() ) {
cll->doesNotNeedSp = true;
}
}
index++;
}
}
vector<SimNode *> ExprMakeVariant::simulateLocal (Context & context) const {
vector<SimNode *> simlist;
int index = 0;
int stride = makeType->getStride();
// init with 0 it its 'default' initialization
if ( stride && variants.empty() ) {
int bytes = stride;
SimNode * init0;
if ( useCMRES ) {
if ( bytes <= 32 ) {
init0 = context.code->makeNodeUnrollNZ<SimNode_InitLocalCMResN>(bytes, at,extraOffset);
} else {
init0 = context.code->makeNode<SimNode_InitLocalCMRes>(at,extraOffset,bytes);
}
} else if ( useStackRef ) {
init0 = context.code->makeNode<SimNode_InitLocalRef>(at,stackTop,extraOffset,bytes);
} else {
init0 = context.code->makeNode<SimNode_InitLocal>(at,stackTop + extraOffset,bytes);
}
simlist.push_back(init0);
}
// now fields
for ( const auto & decl : variants ) {
auto fieldVariant = makeType->findArgumentIndex(decl->name);
DAS_ASSERT(fieldVariant!=-1 && "should have failed in type infer otherwise");
// lets set variant index
uint32_t voffset = extraOffset + index*stride;
auto vconst = make_smart<ExprConstInt>(at, int32_t(fieldVariant));
vconst->type = make_smart<TypeDecl>(Type::tInt);
SimNode * svi;
if ( useCMRES ) {
svi = makeLocalCMResCopy(at,context,voffset,vconst);
} else if (useStackRef) {
svi = makeLocalRefCopy(at,context,stackTop,voffset,vconst);
} else {
svi = makeLocalCopy(at,context,stackTop+voffset,vconst);
}
simlist.push_back(svi);
// field itself
auto fieldOffset = makeType->getVariantFieldOffset(fieldVariant);
uint32_t offset = voffset + fieldOffset;
SimNode * cpy;
if ( decl->value->rtti_isMakeLocal() ) {
// so what happens here, is we ask it for the generated commands and append it to this list only
auto mkl = static_pointer_cast<ExprMakeLocal>(decl->value);
auto lsim = mkl->simulateLocal(context);
simlist.insert(simlist.end(), lsim.begin(), lsim.end());
continue;
} else if ( useCMRES ) {
if ( decl->moveSemantics ){
cpy = makeLocalCMResMove(at,context,offset,decl->value);
} else {
cpy = makeLocalCMResCopy(at,context,offset,decl->value);
}
} else if ( useStackRef ) {
if ( decl->moveSemantics ){
cpy = makeLocalRefMove(at,context,stackTop,offset,decl->value);
} else {
cpy = makeLocalRefCopy(at,context,stackTop,offset,decl->value);
}
} else {
if ( decl->moveSemantics ){
cpy = makeLocalMove(at,context,stackTop+offset,decl->value);
} else {
cpy = makeLocalCopy(at,context,stackTop+offset,decl->value);
}
}
if ( !cpy ) {
context.thisProgram->error("internal compilation error, can't generate structure initialization", "", "", at);
}
simlist.push_back(cpy);
index++;
}
return simlist;
}
SimNode * ExprMakeVariant::simulate (Context & context) const {
SimNode_Block * block;
if ( useCMRES ) {
block = context.code->makeNode<SimNode_MakeLocalCMRes>(at);
} else {
block = context.code->makeNode<SimNode_MakeLocal>(at, stackTop);
}
auto simlist = simulateLocal(context);
block->total = int(simlist.size());
block->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*block->total);
for ( uint32_t i = 0; i != block->total; ++i )
block->list[i] = simlist[i];
return block;
}
// structure
void ExprMakeStruct::setRefSp ( bool ref, bool cmres, uint32_t sp, uint32_t off ) {
ExprMakeLocal::setRefSp(ref, cmres, sp, off);
// if it's a handle type, we can't reuse the make-local chain
if ( makeType->baseType == Type::tHandle ) return;
// we go through all fields, and if its [[ ]] field
// we tell it to piggy-back on our current sp, with appropriate offset
int total = int(structs.size());
int stride = makeType->getStride();
for ( int index=0; index != total; ++index ) {
auto & fields = structs[index];
for ( const auto & decl : *fields ) {
auto field = makeType->structType->findField(decl->name);
DAS_ASSERT(field && "should have failed in type infer otherwise");
if ( decl->value->rtti_isMakeLocal() ) {
uint32_t offset = extraOffset + index*stride + field->offset;
auto mkl = static_pointer_cast<ExprMakeLocal>(decl->value);
mkl->setRefSp(ref, cmres, sp, offset);
} else if ( decl->value->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(decl->value);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
cll->doesNotNeedSp = true;
}
} else if ( decl->value->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(decl->value);
if ( cll->isCopyOrMove() ) {
cll->doesNotNeedSp = true;
}
}
}
}
}
vector<SimNode *> ExprMakeStruct::simulateLocal (Context & context) const {
vector<SimNode *> simlist;
// init with 0
int total = int(structs.size());
int stride = makeType->getStride();
if ( !doesNotNeedInit && !initAllFields && stride ) {
int bytes = das::max(total,1) * stride;
SimNode * init0;
if ( useCMRES ) {
if ( bytes <= 32 ) {
init0 = context.code->makeNodeUnrollNZ<SimNode_InitLocalCMResN>(bytes, at,extraOffset);
} else {
init0 = context.code->makeNode<SimNode_InitLocalCMRes>(at,extraOffset,bytes);
}
} else if ( useStackRef ) {
init0 = context.code->makeNode<SimNode_InitLocalRef>(at,stackTop,extraOffset,bytes);
} else {
init0 = context.code->makeNode<SimNode_InitLocal>(at,stackTop + extraOffset,bytes);
}
simlist.push_back(init0);
}
if ( makeType->baseType == Type::tStructure ) {
for ( int index=0; index != total; ++index ) {
auto & fields = structs[index];
for ( const auto & decl : *fields ) {
auto field = makeType->structType->findField(decl->name);
DAS_ASSERT(field && "should have failed in type infer otherwise");
uint32_t offset = extraOffset + index*stride + field->offset;
SimNode * cpy;
if ( decl->value->rtti_isMakeLocal() ) {
// so what happens here, is we ask it for the generated commands and append it to this list only
auto mkl = static_pointer_cast<ExprMakeLocal>(decl->value);
auto lsim = mkl->simulateLocal(context);
simlist.insert(simlist.end(), lsim.begin(), lsim.end());
continue;
} else if ( useCMRES ) {
if ( decl->moveSemantics ){
cpy = makeLocalCMResMove(at,context,offset,decl->value);
} else {
cpy = makeLocalCMResCopy(at,context,offset,decl->value);
}
} else if ( useStackRef ) {
if ( decl->moveSemantics ){
cpy = makeLocalRefMove(at,context,stackTop,offset,decl->value);
} else {
cpy = makeLocalRefCopy(at,context,stackTop,offset,decl->value);
}
} else {
if ( decl->moveSemantics ){
cpy = makeLocalMove(at,context,stackTop+offset,decl->value);
} else {
cpy = makeLocalCopy(at,context,stackTop+offset,decl->value);
}
}
if ( !cpy ) {
context.thisProgram->error("internal compilation error, can't generate structure initialization", "", "", at);
}
simlist.push_back(cpy);
}
}
} else {
auto ann = makeType->annotation;
// making fake variable, which points to out field
string fakeName = "__makelocal";
auto fakeVariable = make_smart<Variable>();
fakeVariable->name = fakeName;
fakeVariable->type = make_smart<TypeDecl>(Type::tHandle);
fakeVariable->type->annotation = ann;
fakeVariable->at = at;
if ( useCMRES ) {
fakeVariable->aliasCMRES = true;
} else if ( useStackRef ) {
fakeVariable->stackTop = stackTop + extraOffset;
fakeVariable->type->ref = true;
if ( total != 1 ) {
fakeVariable->type->dim.push_back(total);
}
}
fakeVariable->generated = true;
// make fake ExprVar which is that field
auto fakeVar = make_smart<ExprVar>(at, fakeName);
fakeVar->type = fakeVariable->type;
fakeVar->variable = fakeVariable;
fakeVar->local = true;
// make fake expression
ExpressionPtr fakeExpr = fakeVar;
smart_ptr<ExprConstInt> indexExpr;
if ( useStackRef && total > 1 ) {
// if its stackRef with multiple indices, its actually var[total], and lookup is var[index]
indexExpr = make_smart<ExprConstInt>(at, 0);
indexExpr->type = make_smart<TypeDecl>(Type::tInt);
fakeExpr = make_smart<ExprAt>(at, fakeExpr, indexExpr);
fakeExpr->type = make_smart<TypeDecl>(Type::tHandle);
fakeExpr->type->annotation = ann;
fakeExpr->type->ref = true;
}
for ( int index=0; index != total; ++index ) {
auto & fields = structs[index];
// adjust var for index
if ( useCMRES ) {
fakeVariable->stackTop = extraOffset + index*stride;
} else if ( useStackRef ) {
if ( total > 1 ) {
indexExpr->value = cast<int32_t>::from(index);
}
} else {
fakeVariable->stackTop = stackTop + extraOffset + index*stride;
}
// now, setup fields
for ( const auto & decl : *fields ) {
auto fieldType = ann->makeFieldType(decl->name, false);
DAS_ASSERT(fieldType && "how did this infer?");
uint32_t fieldSize = fieldType->getSizeOf();
SimNode * cpy = nullptr;
auto left = ann->simulateGetField(decl->name, context, at, fakeExpr);
auto right = decl->value->simulate(context);
if ( !decl->value->type->isRef() ) {
if ( decl->value->type->isHandle() ) {
auto rightType = decl->value->type;
cpy = rightType->annotation->simulateCopy(context, at, left,
(!rightType->isRefType() && rightType->ref) ? rightType->annotation->simulateRef2Value(context, at, right) : right);
if ( !cpy ) {
context.thisProgram->error("integration error, simulateCopy returned null", "", "",
at, CompilationError::missing_node );
}
} else {
cpy = context.code->makeValueNode<SimNode_Set>(decl->value->type->baseType, decl->at, left, right);
}
} else if ( decl->moveSemantics ) {
cpy = context.code->makeNode<SimNode_MoveRefValue>(decl->at, left, right, fieldSize);
} else {
cpy = context.code->makeNode<SimNode_CopyRefValue>(decl->at, left, right, fieldSize);
}
simlist.push_back(cpy);
}
}
}
if ( block ) {
/*
TODO: optimize
there is no point in making fake invoke expression, we can replace 'self' with fake variable we've made
however this needs to happen during infer, and this needs to have different visitor,
so that stack is allocated properly in subexpressions etc
*/
// making fake variable, which points to entire structure
string fakeName = "__makelocal";
auto fakeVariable = make_smart<Variable>();
fakeVariable->name = fakeName;
fakeVariable->type = make_smart<TypeDecl>(*type);
if ( useCMRES ) {
fakeVariable->aliasCMRES = true;
} else if ( useStackRef ) {
fakeVariable->stackTop = stackTop + extraOffset;
fakeVariable->type->ref = true;
} else {
fakeVariable->stackTop = stackTop + extraOffset;
}
fakeVariable->generated = true;
// make fake ExprVar which is that field
auto fakeVar = make_smart<ExprVar>(at, fakeName);
fakeVar->type = fakeVariable->type;
fakeVar->variable = fakeVariable;
fakeVar->local = true;
// make fake invoke expression
auto fakeInvoke = make_smart<ExprInvoke>(at,"invoke");
fakeInvoke->arguments.push_back(block);
fakeInvoke->arguments.push_back(fakeVar);
// simulate it
auto simI = fakeInvoke->simulate(context);
simlist.push_back(simI);
}
return simlist;
}
SimNode * ExprMakeStruct::simulate (Context & context) const {
SimNode_Block * blk;
if ( useCMRES ) {
blk = context.code->makeNode<SimNode_MakeLocalCMRes>(at);
} else {
blk = context.code->makeNode<SimNode_MakeLocal>(at, stackTop);
}
auto simlist = simulateLocal(context);
blk->total = int(simlist.size());
blk->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*blk->total);
for ( uint32_t i = 0; i != blk->total; ++i )
blk->list[i] = simlist[i];
return blk;
}
// make array
void ExprMakeArray::setRefSp ( bool ref, bool cmres, uint32_t sp, uint32_t off ) {
ExprMakeLocal::setRefSp(ref, cmres, sp, off);
int total = int(values.size());
uint32_t stride = recordType->getSizeOf();
for ( int index=0; index != total; ++index ) {
auto & val = values[index];
if ( val->rtti_isMakeLocal() ) {
uint32_t offset = extraOffset + index*stride;
auto mkl = static_pointer_cast<ExprMakeLocal>(val);
mkl->setRefSp(ref, cmres, sp, offset);
} else if ( val->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(val);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
cll->doesNotNeedSp = true;
}
} else if ( val->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(val);
if ( cll->isCopyOrMove() ) {
cll->doesNotNeedSp = true;
}
}
}
}
vector<SimNode *> ExprMakeArray::simulateLocal (Context & context) const {
vector<SimNode *> simlist;
// init with 0
int total = int(values.size());
uint32_t stride = recordType->getSizeOf();
if ( !doesNotNeedInit && !initAllFields ) {
int bytes = total * stride;
SimNode * init0;
if ( useCMRES ) {
if ( bytes <= 32 ) {
init0 = context.code->makeNodeUnrollNZ<SimNode_InitLocalCMResN>(bytes, at,extraOffset);
} else {
init0 = context.code->makeNode<SimNode_InitLocalCMRes>(at,extraOffset,bytes);
}
} else if ( useStackRef ) {
init0 = context.code->makeNode<SimNode_InitLocalRef>(at,stackTop,extraOffset,stride * total);
} else {
init0 = context.code->makeNode<SimNode_InitLocal>(at,stackTop + extraOffset,stride * total);
}
simlist.push_back(init0);
}
for ( int index=0; index != total; ++index ) {
auto & val = values[index];
uint32_t offset = extraOffset + index*stride;
SimNode * cpy;
if ( val->rtti_isMakeLocal() ) {
// so what happens here, is we ask it for the generated commands and append it to this list only
auto mkl = static_pointer_cast<ExprMakeLocal>(val);
auto lsim = mkl->simulateLocal(context);
simlist.insert(simlist.end(), lsim.begin(), lsim.end());
continue;
} else if ( useCMRES ) {
if (val->type->canCopy()) {
cpy = makeLocalCMResCopy(at, context, offset, val);
} else {
cpy = makeLocalCMResMove(at, context, offset, val);
}
} else if ( useStackRef ) {
if (val->type->canCopy()) {
cpy = makeLocalRefCopy(at, context, stackTop, offset, val);
} else {
cpy = makeLocalRefMove(at, context, stackTop, offset, val);
}
} else {
if (val->type->canCopy()) {
cpy = makeLocalCopy(at, context, stackTop + offset, val);
} else {
cpy = makeLocalMove(at, context, stackTop + offset, val);
}
}
if ( !cpy ) {
context.thisProgram->error("internal compilation error, can't generate array initialization", "", "", at);
}
simlist.push_back(cpy);
}
return simlist;
}
SimNode * ExprMakeArray::simulate (Context & context) const {
SimNode_Block * block;
if ( useCMRES ) {
block = context.code->makeNode<SimNode_MakeLocalCMRes>(at);
} else {
block = context.code->makeNode<SimNode_MakeLocal>(at, stackTop);
}
auto simlist = simulateLocal(context);
block->total = int(simlist.size());
block->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*block->total);
for ( uint32_t i = 0; i != block->total; ++i )
block->list[i] = simlist[i];
return block;
}
// make tuple
void ExprMakeTuple::setRefSp ( bool ref, bool cmres, uint32_t sp, uint32_t off ) {
ExprMakeLocal::setRefSp(ref, cmres, sp, off);
int total = int(values.size());
for ( int index=0; index != total; ++index ) {
auto & val = values[index];
if ( val->rtti_isMakeLocal() ) {
uint32_t offset = extraOffset + makeType->getTupleFieldOffset(index);
auto mkl = static_pointer_cast<ExprMakeLocal>(val);
mkl->setRefSp(ref, cmres, sp, offset);
} else if ( val->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(val);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
cll->doesNotNeedSp = true;
}
} else if ( val->rtti_isInvoke() ) {
auto cll = static_pointer_cast<ExprInvoke>(val);
if ( cll->isCopyOrMove() ) {
cll->doesNotNeedSp = true;
}
}
}
}
vector<SimNode *> ExprMakeTuple::simulateLocal (Context & context) const {
vector<SimNode *> simlist;
// init with 0
int total = int(values.size());
if ( !doesNotNeedInit && !initAllFields ) {
uint32_t sizeOf = makeType->getSizeOf();
SimNode * init0;
if ( useCMRES ) {
if ( sizeOf <= 32 ) {
init0 = context.code->makeNodeUnrollNZ<SimNode_InitLocalCMResN>(sizeOf, at,extraOffset);
} else {
init0 = context.code->makeNode<SimNode_InitLocalCMRes>(at,extraOffset,sizeOf);
}
} else if ( useStackRef ) {
init0 = context.code->makeNode<SimNode_InitLocalRef>(at,stackTop,extraOffset,sizeOf);
} else {
init0 = context.code->makeNode<SimNode_InitLocal>(at,stackTop + extraOffset,sizeOf);
}
simlist.push_back(init0);
}
for ( int index=0; index != total; ++index ) {
auto & val = values[index];
uint32_t offset = extraOffset + makeType->getTupleFieldOffset(index);
SimNode * cpy;
if ( val->rtti_isMakeLocal() ) {
// so what happens here, is we ask it for the generated commands and append it to this list only
auto mkl = static_pointer_cast<ExprMakeLocal>(val);
auto lsim = mkl->simulateLocal(context);
simlist.insert(simlist.end(), lsim.begin(), lsim.end());
continue;
} else if ( useCMRES ) {
if (val->type->canCopy()) {
cpy = makeLocalCMResCopy(at, context, offset, val);
} else {
cpy = makeLocalCMResMove(at, context, offset, val);
}
} else if ( useStackRef ) {
if (val->type->canCopy()) {
cpy = makeLocalRefCopy(at, context, stackTop, offset, val);
} else {
cpy = makeLocalRefMove(at, context, stackTop, offset, val);
}
} else {
if (val->type->canCopy()) {
cpy = makeLocalCopy(at, context, stackTop + offset, val);
} else {
cpy = makeLocalMove(at, context, stackTop + offset, val);
}
}
if ( !cpy ) {
context.thisProgram->error("internal compilation error, can't generate array initialization", "", "", at);
}
simlist.push_back(cpy);
}
return simlist;
}
SimNode * ExprMakeTuple::simulate (Context & context) const {
SimNode_Block * block;
if ( useCMRES ) {
block = context.code->makeNode<SimNode_MakeLocalCMRes>(at);
} else {
block = context.code->makeNode<SimNode_MakeLocal>(at, stackTop);
}
auto simlist = simulateLocal(context);
block->total = int(simlist.size());
block->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*block->total);
for ( uint32_t i = 0; i != block->total; ++i )
block->list[i] = simlist[i];
return block;
}
// reader
SimNode * ExprReader::simulate (Context & context) const {
context.thisProgram->error("internal compilation error, calling 'simulate' on reader", "", "", at);
return nullptr;
}
// label
SimNode * ExprLabel::simulate (Context & context) const {
context.thisProgram->error("internal compilation error, calling 'simulate' on label", "", "", at);
return nullptr;
}
// goto
SimNode * ExprGoto::simulate (Context & context) const {
if ( subexpr ) {
return context.code->makeNode<SimNode_Goto>(at, subexpr->simulate(context));
} else {
return context.code->makeNode<SimNode_GotoLabel>(at,label);
}
}
// r2v
SimNode * ExprRef2Value::GetR2V ( Context & context, const LineInfo & at, const TypeDeclPtr & type, SimNode * expr ) {
if ( type->isHandle() ) {
auto resN = type->annotation->simulateRef2Value(context, at, expr);
if ( !resN ) {
context.thisProgram->error("integration error, simulateRef2Value returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else {
if ( type->isRefType() ) {
return expr;
} else {
return context.code->makeValueNode<SimNode_Ref2Value>(type->baseType, at, expr);
}
}
}
SimNode * ExprRef2Value::simulate (Context & context) const {
return GetR2V(context, at, type, subexpr->simulate(context));
}
SimNode * ExprAddr::simulate (Context & context) const {
if ( !func ) {
context.thisProgram->error("internal compilation error, ExprAddr func is null", "", "", at);
return nullptr;
} else if ( func->index<0 ) {
context.thisProgram->error("internal compilation error, ExprAddr func->index is unused", "", "", at);
return nullptr;
}
union {
uint32_t mnh;
vec4f cval;
} temp;
temp.cval = v_zero();
if ( func->module->isSolidContext ) {
DAS_ASSERT(func->index>=0 && "address of unsued function? how?");
temp.mnh = uint32_t(func->index);
return context.code->makeNode<SimNode_FuncConstValue>(at,temp.cval);
} else {
temp.mnh = func->getMangledNameHash();
return context.code->makeNode<SimNode_FuncConstValueMnh>(at,temp.cval);
}
}
SimNode * ExprPtr2Ref::simulate (Context & context) const {
if ( unsafeDeref ) {
return subexpr->simulate(context);
} else {
return context.code->makeNode<SimNode_Ptr2Ref>(at,subexpr->simulate(context));
}
}
SimNode * ExprRef2Ptr::simulate (Context & context) const {
return subexpr->simulate(context);
}
SimNode * ExprNullCoalescing::simulate (Context & context) const {
if ( type->isRef() ) {
return context.code->makeNode<SimNode_NullCoalescingRef>(at,subexpr->simulate(context),defaultValue->simulate(context));
} else {
return context.code->makeValueNode<SimNode_NullCoalescing>(type->baseType,at,subexpr->simulate(context),defaultValue->simulate(context));
}
}
SimNode * ExprConst::simulate (Context & context) const {
return context.code->makeNode<SimNode_ConstValue>(at,value);
}
SimNode * ExprConstEnumeration::simulate (Context & context) const {
return context.code->makeNode<SimNode_ConstValue>(at, value);
}
SimNode * ExprConstString::simulate (Context & context) const {
if ( !text.empty() ) {
char* str = context.constStringHeap->allocateString(text);
return context.code->makeNode<SimNode_ConstString>(at, str);
} else {
return context.code->makeNode<SimNode_ConstString>(at, nullptr);
}
}
SimNode * ExprStaticAssert::simulate (Context &) const {
return nullptr;
}
SimNode * ExprAssert::simulate (Context & context) const {
string message;
if ( arguments.size()==2 && arguments[1]->rtti_isStringConstant() )
message = static_pointer_cast<ExprConstString>(arguments[1])->getValue();
return context.code->makeNode<SimNode_Assert>(at,arguments[0]->simulate(context),context.constStringHeap->allocateString(message));
}
struct SimNode_AstGetExpression : SimNode_CallBase {
DAS_PTR_NODE;
SimNode_AstGetExpression ( const LineInfo & at, const ExpressionPtr & e, char * d )
: SimNode_CallBase(at) {
expr = e.get();
descr = d;
}
virtual SimNode * copyNode ( Context & context, NodeAllocator * code ) override {
auto that = (SimNode_AstGetExpression *) SimNode::copyNode(context, code);
that->descr = code->allocateName(descr);
return that;
}
virtual SimNode * visit ( SimVisitor & vis ) override {
V_BEGIN();
V_OP(AstGetExpression);
V_ARG(descr);
V_END();
}
__forceinline char * compute(Context &) {
DAS_PROFILE_NODE
return (char *) expr->clone().orphan();
}
Expression * expr; // requires RTTI
char * descr;
};
SimNode * ExprQuote::simulate (Context & context) const {
DAS_ASSERTF(arguments.size()==1,"Quote expects to return only one ExpressionPtr."
"We should not be here, since typeinfer should catch the mismatch.");
TextWriter ss;
ss << *arguments[0];
char * descr = context.code->allocateName(ss.str());
return context.code->makeNode<SimNode_AstGetExpression>(at, arguments[0], descr);
}
SimNode * ExprDebug::simulate (Context & context) const {
TypeInfo * pTypeInfo = context.thisHelper->makeTypeInfo(nullptr, arguments[0]->type);
string message;
if ( arguments.size()==2 && arguments[1]->rtti_isStringConstant() )
message = static_pointer_cast<ExprConstString>(arguments[1])->getValue();
return context.code->makeNode<SimNode_Debug>(at,
arguments[0]->simulate(context),
pTypeInfo,
context.constStringHeap->allocateString(message));
}
SimNode * ExprMemZero::simulate (Context & context) const {
const auto & subexpr = arguments[0];
uint32_t dataSize = subexpr->type->getSizeOf();
return context.code->makeNode<SimNode_MemZero>(at, subexpr->simulate(context), dataSize);
}
SimNode * ExprMakeGenerator::simulate (Context & context) const {
DAS_ASSERTF(0, "we should not be here ever, ExprMakeGenerator should completly fold during type inference.");
context.thisProgram->error("internal compilation error, generating node for ExprMakeGenerator", "", "", at);
return nullptr;
}
SimNode * ExprYield::simulate (Context & context) const {
DAS_ASSERTF(0, "we should not be here ever, ExprYield should completly fold during type inference.");
context.thisProgram->error("internal compilation error, generating node for ExprYield", "", "", at);
return nullptr;
}
SimNode * ExprArrayComprehension::simulate (Context & context) const {
DAS_ASSERTF(0, "we should not be here ever, ExprArrayComprehension should completly fold during type inference.");
context.thisProgram->error("internal compilation error, generating node for ExprArrayComprehension", "", "", at);
return nullptr;
}
SimNode * ExprMakeBlock::simulate (Context & context) const {
auto blk = static_pointer_cast<ExprBlock>(block);
uint32_t argSp = blk->stackTop;
auto info = context.thisHelper->makeInvokeableTypeDebugInfo(blk->makeBlockType(),blk->at);
if ( context.thisProgram->getDebugger() || context.thisProgram->options.getBoolOption("gc",false) ) {
context.thisHelper->appendLocalVariables(info, (Expression *)this);
}
return context.code->makeNode<SimNode_MakeBlock>(at,block->simulate(context),argSp,stackTop,info);
}
bool ExprInvoke::isCopyOrMove() const {
auto blockT = arguments[0]->type;
return blockT->firstType && blockT->firstType->isRefType() && !blockT->firstType->ref;
}
SimNode * ExprInvoke::simulate (Context & context) const {
auto blockT = arguments[0]->type;
SimNode_CallBase * pInvoke;
{
if ( isCopyOrMove() ) {
auto getSp = context.code->makeNode<SimNode_GetLocal>(at,stackTop);
if ( blockT->baseType==Type::tBlock ) {
pInvoke = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_InvokeAndCopyOrMove>(
int(arguments.size()), at, getSp);
} else if ( blockT->baseType==Type::tFunction ) {
pInvoke = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_InvokeAndCopyOrMoveFn>(
int(arguments.size()), at, getSp);
} else {
pInvoke = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_InvokeAndCopyOrMoveLambda>(
int(arguments.size()), at, getSp);
}
} else {
if ( blockT->baseType==Type::tBlock ) {
pInvoke = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_Invoke>(int(arguments.size()),at);
} else if ( blockT->baseType==Type::tFunction ) {
pInvoke = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_InvokeFn>(int(arguments.size()),at);
} else {
pInvoke = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_InvokeLambda>(int(arguments.size()),at);
}
}
}
pInvoke->debugInfo = at;
if ( int nArg = (int) arguments.size() ) {
pInvoke->arguments = (SimNode **) context.code->allocate(nArg * sizeof(SimNode *));
pInvoke->nArguments = nArg;
for ( int a=0; a!=nArg; ++a ) {
pInvoke->arguments[a] = arguments[a]->simulate(context);
}
} else {
pInvoke->arguments = nullptr;
pInvoke->nArguments = 0;
}
return pInvoke;
}
SimNode * ExprErase::simulate (Context & context) const {
auto cont = arguments[0]->simulate(context);
auto val = arguments[1]->simulate(context);
if ( arguments[0]->type->isGoodTableType() ) {
uint32_t valueTypeSize = arguments[0]->type->secondType->getSizeOf();
return context.code->makeValueNode<SimNode_TableErase>(arguments[0]->type->firstType->baseType, at, cont, val, valueTypeSize);
} else {
DAS_ASSERTF(0, "we should not even be here. erase can only accept tables. infer type should have failed.");
context.thisProgram->error("internal compilation error, generating erase for non-table type", "", "", at);
return nullptr;
}
}
SimNode * ExprFind::simulate (Context & context) const {
auto cont = arguments[0]->simulate(context);
auto val = arguments[1]->simulate(context);
if ( arguments[0]->type->isGoodTableType() ) {
uint32_t valueTypeSize = arguments[0]->type->secondType->getSizeOf();
return context.code->makeValueNode<SimNode_TableFind>(arguments[0]->type->firstType->baseType, at, cont, val, valueTypeSize);
} else {
DAS_ASSERTF(0, "we should not even be here. find can only accept tables. infer type should have failed.");
context.thisProgram->error("internal compilation error, generating find for non-table type", "", "", at);
return nullptr;
}
}
SimNode * ExprKeyExists::simulate (Context & context) const {
auto cont = arguments[0]->simulate(context);
auto val = arguments[1]->simulate(context);
if ( arguments[0]->type->isGoodTableType() ) {
uint32_t valueTypeSize = arguments[0]->type->secondType->getSizeOf();
return context.code->makeValueNode<SimNode_KeyExists>(arguments[0]->type->firstType->baseType, at, cont, val, valueTypeSize);
} else {
DAS_ASSERTF(0, "we should not even be here. find can only accept tables. infer type should have failed.");
context.thisProgram->error("internal compilation error, generating find for non-table type", "", "", at);
return nullptr;
}
}
SimNode * ExprIs::simulate (Context & context) const {
DAS_ASSERTF(0, "we should not even be here. 'is' should resolve to const during infer pass.");
context.thisProgram->error("internal compilation error, generating 'is'", "", "", at);
return nullptr;
}
SimNode * ExprTypeDecl::simulate (Context & context) const {
return context.code->makeNode<SimNode_ConstValue>(at,v_zero());
}
SimNode * ExprTypeInfo::simulate (Context & context) const {
if ( !macro ) {
DAS_ASSERTF(0, "we should not even be here. typeinfo should resolve to const during infer pass.");
context.thisProgram->error("internal compilation error, generating typeinfo(...)", "", "", at);
return nullptr;
} else {
string errors;
auto node = macro->simluate(&context, (Expression*)this, errors);
if ( !node || !errors.empty() ) {
context.thisProgram->error("typeinfo(" + trait + "...) macro generated no node; " + errors,
"", "", at, CompilationError::typeinfo_macro_error);
}
return node;
}
}
SimNode * ExprDelete::simulate (Context & context) const {
uint32_t total = uint32_t(subexpr->type->getCountOf());
DAS_ASSERTF(total==1,"we should not be deleting more than one at a time");
auto sube = subexpr->simulate(context);
if ( subexpr->type->baseType==Type::tArray ) {
auto stride = subexpr->type->firstType->getSizeOf();
return context.code->makeNode<SimNode_DeleteArray>(at, sube, total, stride);
} else if ( subexpr->type->baseType==Type::tTable ) {
auto vts_add_kts = subexpr->type->firstType->getSizeOf() +
subexpr->type->secondType->getSizeOf();
return context.code->makeNode<SimNode_DeleteTable>(at, sube, total, vts_add_kts);
} else if ( subexpr->type->baseType==Type::tPointer ) {
if ( subexpr->type->firstType->baseType==Type::tStructure ) {
if ( subexpr->type->firstType->structType->isClass ) {
if ( sizeexpr ) {
auto sze = sizeexpr->simulate(context);
return context.code->makeNode<SimNode_DeleteClassPtr>(at, sube, total, sze);
} else {
context.thisProgram->error("internal compiler error, SimNode_DeleteClassPtr needs size expression", "", "",
at, CompilationError::missing_node );
return nullptr;
}
} else {
auto structSize = subexpr->type->firstType->getSizeOf();
bool persistent = subexpr->type->firstType->structType->persistent;
bool isLambda = subexpr->type->firstType->structType->isLambda;
return context.code->makeNode<SimNode_DeleteStructPtr>(at, sube, total, structSize, persistent, isLambda);
}
} else if ( subexpr->type->firstType->baseType==Type::tTuple ) {
auto structSize = subexpr->type->firstType->getSizeOf();
return context.code->makeNode<SimNode_DeleteStructPtr>(at, sube, total, structSize, false, false);
} else if ( subexpr->type->firstType->baseType==Type::tVariant ) {
auto structSize = subexpr->type->firstType->getSizeOf();
return context.code->makeNode<SimNode_DeleteStructPtr>(at, sube, total, structSize, false, false);
} else {
auto ann = subexpr->type->firstType->annotation;
DAS_ASSERT(ann->canDeletePtr() && "has to be able to delete ptr");
auto resN = ann->simulateDeletePtr(context, at, sube, total);
if ( !resN ) {
context.thisProgram->error("integration error, simulateDelete returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
}
} else if ( subexpr->type->baseType==Type::tHandle ) {
auto ann = subexpr->type->annotation;
DAS_ASSERT(ann->canDelete() && "has to be able to delete");
auto resN = ann->simulateDelete(context, at, sube, total);
if ( !resN ) {
context.thisProgram->error("integration error, simulateDelete returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else if ( subexpr->type->baseType==Type::tLambda ) {
return context.code->makeNode<SimNode_DeleteLambda>(at, sube, total);
} else {
DAS_ASSERTF(0, "we should not be here. this is delete for unsupported type. infer types should have failed.");
context.thisProgram->error("internal compilation error, generating node for unsupported ExprDelete", "", "", at);
return nullptr;
}
}
SimNode * ExprCast::trySimulate (Context & context, uint32_t extraOffset, const TypeDeclPtr & r2vType ) const {
return subexpr->trySimulate(context, extraOffset, r2vType);
}
SimNode * ExprCast::simulate (Context & context) const {
return subexpr->simulate(context);
}
SimNode * ExprAscend::simulate (Context & context) const {
auto se = subexpr->simulate(context);
auto bytes = subexpr->type->getSizeOf();
TypeInfo * typeInfo = nullptr;
if ( needTypeInfo ) {
typeInfo = context.thisHelper->makeTypeInfo(nullptr, subexpr->type);
}
if ( subexpr->type->baseType==Type::tHandle ) {
DAS_ASSERTF(useStackRef,"new of handled type should always be over stackref");
auto ne = subexpr->type->annotation->simulateGetNew(context, at);
return context.code->makeNode<SimNode_AscendNewHandleAndRef>(at, se, ne, bytes, stackTop);
} else {
bool peristent = false;
if ( subexpr->type->baseType==Type::tStructure ) {
peristent = subexpr->type->structType->persistent;
}
if ( useStackRef ) {
return context.code->makeNode<SimNode_AscendAndRef>(at, se, bytes, stackTop, typeInfo, peristent);
} else {
return context.code->makeNode<SimNode_Ascend<false>>(at, se, bytes, typeInfo, peristent);
}
}
}
SimNode * ExprNew::simulate (Context & context) const {
SimNode * newNode;
if ( typeexpr->baseType == Type::tHandle ) {
DAS_ASSERT(typeexpr->annotation->canNew() && "how???");
newNode = typeexpr->annotation->simulateGetNew(context, at);
if ( !newNode ) {
context.thisProgram->error("integration error, simulateGetNew returned null", "", "",
at, CompilationError::missing_node );
}
} else {
bool persistent = false;
if ( typeexpr->baseType == Type::tStructure ) {
persistent = typeexpr->structType->persistent;
}
int32_t bytes = type->firstType->getSizeOf();
if ( initializer ) {
auto pCall = (SimNode_CallBase *) context.code->makeNodeUnrollAny<SimNode_NewWithInitializer>(
int(arguments.size()),at,bytes,persistent);
pCall->cmresEval = nullptr;
newNode = ExprCall::simulateCall(func, this, context, pCall);
} else {
newNode = context.code->makeNode<SimNode_New>(at,bytes,persistent);
}
}
if ( type->dim.size() ) {
uint32_t count = type->getCountOf();
return context.code->makeNode<SimNode_NewArray>(at,newNode,stackTop,count);
} else {
return newNode;
}
}
SimNode * ExprAt::trySimulate (Context & context, uint32_t extraOffset, const TypeDeclPtr & r2vType ) const {
if ( subexpr->type->isVectorType() ) {
return nullptr;
} else if ( subexpr->type->isGoodTableType() ) {
return nullptr;
} else if ( subexpr->type->isHandle() ) {
SimNode * result;
if ( r2vType->baseType!=Type::none ) {
result = subexpr->type->annotation->simulateGetAtR2V(context, at, r2vType, subexpr, index, extraOffset);
if ( !result ) {
context.thisProgram->error("integration error, simulateGetAtR2V returned null", "", "",
at, CompilationError::missing_node );
}
} else {
result = subexpr->type->annotation->simulateGetAt(context, at, r2vType, subexpr, index, extraOffset);
if ( !result ) {
context.thisProgram->error("integration error, simulateGetAt returned null", "", "",
at, CompilationError::missing_node );
}
}
return result;
} else if ( subexpr->type->isGoodArrayType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t stride = subexpr->type->firstType->getSizeOf();
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_ArrayAtR2V>(r2vType->baseType, at, prv, pidx, stride, extraOffset);
} else {
return context.code->makeNode<SimNode_ArrayAt>(at, prv, pidx, stride, extraOffset);
}
} else if ( subexpr->type->isPointer() ) {
uint32_t range = 0xffffffff;
uint32_t stride = subexpr->type->firstType->getSizeOf();
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_AtR2V>(r2vType->baseType, at, prv, pidx, stride, extraOffset, range);
} else {
return context.code->makeNode<SimNode_At>(at, prv, pidx, stride, extraOffset, range);
}
} else {
uint32_t range = subexpr->type->dim[0];
uint32_t stride = subexpr->type->getStride();
if ( index->rtti_isConstant() ) {
// if its constant index, like a[3]..., we try to let node bellow simulate
auto idxCE = static_pointer_cast<ExprConst>(index);
uint32_t idxC = cast<uint32_t>::to(idxCE->value);
if ( idxC >= range ) {
context.thisProgram->error("index out of range", "", "",
at, CompilationError::index_out_of_range);
return nullptr;
}
auto tnode = subexpr->trySimulate(context, extraOffset + idxC*stride, r2vType);
if ( tnode ) {
return tnode;
}
}
// regular scenario
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_AtR2V>(r2vType->baseType, at, prv, pidx, stride, extraOffset, range);
} else {
return context.code->makeNode<SimNode_At>(at, prv, pidx, stride, extraOffset, range);
}
}
}
SimNode * ExprAt::simulate (Context & context) const {
if ( subexpr->type->isVectorType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t range = subexpr->type->getVectorDim();
uint32_t stride = type->getSizeOf();
if ( subexpr->type->ref ) {
auto res = context.code->makeNode<SimNode_At>(at, prv, pidx, stride, 0, range);
if ( r2v ) {
return ExprRef2Value::GetR2V(context, at, type, res);
} else {
return res;
}
} else {
switch ( type->baseType ) {
case tInt: return context.code->makeNode<SimNode_AtVector<int32_t>>(at, prv, pidx, range);
case tUInt:
case tBitfield:
return context.code->makeNode<SimNode_AtVector<uint32_t>>(at, prv, pidx, range);
case tFloat: return context.code->makeNode<SimNode_AtVector<float>>(at, prv, pidx, range);
default:
DAS_ASSERTF(0, "we should not even be here. infer type should have failed on unsupported_vector[blah]");
context.thisProgram->error("internal compilation error, generating vector at for unsupported vector type.", "", "", at);
return nullptr;
}
}
} else if ( subexpr->type->isGoodTableType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t valueTypeSize = subexpr->type->secondType->getSizeOf();
auto res = context.code->makeValueNode<SimNode_TableIndex>(subexpr->type->firstType->baseType, at, prv, pidx, valueTypeSize, 0);
if ( r2v ) {
return ExprRef2Value::GetR2V(context, at, type, res);
} else {
return res;
}
} else {
if ( r2v ) {
return trySimulate(context, 0, type);
} else {
return trySimulate(context, 0, make_smart<TypeDecl>(Type::none));
}
}
}
SimNode * ExprSafeAt::trySimulate (Context &, uint32_t, const TypeDeclPtr &) const {
return nullptr;
}
SimNode * ExprSafeAt::simulate (Context & context) const {
if ( subexpr->type->isPointer() ) {
const auto & seT = subexpr->type->firstType;
if ( seT->isGoodArrayType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t stride = seT->firstType->getSizeOf();
return context.code->makeNode<SimNode_SafeArrayAt>(at, prv, pidx, stride, 0);
} else if ( seT->isGoodTableType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t valueTypeSize = seT->secondType->getSizeOf();
return context.code->makeValueNode<SimNode_SafeTableIndex>(seT->firstType->baseType, at, prv, pidx, valueTypeSize, 0);
} else if ( seT->dim.size() ) {
uint32_t range = seT->dim[0];
uint32_t stride = seT->getStride();
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
return context.code->makeNode<SimNode_SafeAt>(at, prv, pidx, stride, 0, range);
} else if ( seT->isVectorType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t range = seT->getVectorDim();
uint32_t stride = type->getSizeOf();
return context.code->makeNode<SimNode_SafeAt>(at, prv, pidx, stride, 0, range);
} else {
DAS_VERIFY(0 && "TODO: safe-at not implemented");
}
} else {
const auto & seT = subexpr->type;
if ( seT->isGoodArrayType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t stride = seT->firstType->getSizeOf();
return context.code->makeNode<SimNode_SafeArrayAt>(at, prv, pidx, stride, 0);
} else if ( subexpr->type->isGoodTableType() ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t valueTypeSize = seT->secondType->getSizeOf();
return context.code->makeValueNode<SimNode_SafeTableIndex>(seT->firstType->baseType, at, prv, pidx, valueTypeSize, 0);
} else if ( seT->dim.size() ) {
uint32_t range = seT->dim[0];
uint32_t stride = seT->getStride();
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
return context.code->makeNode<SimNode_SafeAt>(at, prv, pidx, stride, 0, range);
} else if ( seT->isVectorType() && seT->ref ) {
auto prv = subexpr->simulate(context);
auto pidx = index->simulate(context);
uint32_t range = seT->getVectorDim();
uint32_t stride = type->getSizeOf();
return context.code->makeNode<SimNode_SafeAt>(at, prv, pidx, stride, 0, range);
} else {
DAS_VERIFY(0 && "TODO: safe-at not implemented");
}
}
return nullptr;
}
vector<SimNode *> ExprBlock::collectExpressions ( Context & context,
const vector<ExpressionPtr> & lis,
das_map<int32_t,uint32_t> * ofsmap ) const {
vector<SimNode *> simlist;
for ( auto & node : lis ) {
if ( node->rtti_isLet()) {
auto pLet = static_pointer_cast<ExprLet>(node);
auto letInit = ExprLet::simulateInit(context, pLet.get());
simlist.insert(simlist.end(), letInit.begin(), letInit.end());
continue;
}
if ( node->rtti_isLabel() ) {
if ( ofsmap ) {
auto lnode = static_pointer_cast<ExprLabel>(node);
(*ofsmap)[lnode->label] = uint32_t(simlist.size());
}
continue;
}
if ( auto simE = node->simulate(context) ) {
simlist.push_back(simE);
}
}
return simlist;
}
void ExprBlock::simulateFinal ( Context & context, SimNode_Final * block ) const {
vector<SimNode *> simFList = collectExpressions(context, finalList);
block->totalFinal = int(simFList.size());
if ( block->totalFinal ) {
block->finalList = (SimNode **) context.code->allocate(sizeof(SimNode *)*block->totalFinal);
for ( uint32_t i = 0; i != block->totalFinal; ++i )
block->finalList[i] = simFList[i];
}
}
void ExprBlock::simulateBlock ( Context & context, SimNode_Block * block ) const {
das_map<int32_t,uint32_t> ofsmap;
vector<SimNode *> simlist = collectExpressions(context, list, &ofsmap);
block->total = int(simlist.size());
if ( block->total ) {
block->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*block->total);
for ( uint32_t i = 0; i != block->total; ++i )
block->list[i] = simlist[i];
}
simulateLabels(context, block, ofsmap);
}
void ExprBlock::simulateLabels ( Context & context, SimNode_Block * block, const das_map<int32_t,uint32_t> & ofsmap ) const {
if ( maxLabelIndex!=-1 ) {
block->totalLabels = maxLabelIndex + 1;
block->labels = (uint32_t *) context.code->allocate(block->totalLabels * sizeof(uint32_t));
for ( uint32_t i=0; i!=block->totalLabels; ++i ) {
block->labels[i] = -1U;
}
for ( auto & it : ofsmap ) {
block->labels[it.first] = it.second;
}
}
}
SimNode * ExprBlock::simulate (Context & context) const {
das_map<int32_t,uint32_t> ofsmap;
vector<SimNode *> simlist = collectExpressions(context, list, &ofsmap);
// wow, such empty
if ( finalList.size()==0 && simlist.size()==0 && !annotationDataSid ) {
return context.code->makeNode<SimNode_NOP>(at);
}
// we memzero block's stack memory, if there is a finally section
// bad scenario we fight is ( in scope X ; return ; in scope Y )
if ( finalList.size() ) {
uint32_t blockDataSize = stackVarBottom - stackVarTop;
if ( blockDataSize ) {
for ( const auto & svr : stackCleanVars ) {
SimNode * fakeVar = context.code->makeNode<SimNode_GetLocal>(at, svr.first);
SimNode * memZ = context.code->makeNode<SimNode_MemZero>(at, fakeVar, svr.second );
simlist.insert( simlist.begin(), memZ );
}
}
}
// TODO: what if list size is 0?
if ( simlist.size()!=1 || isClosure || finalList.size() ) {
SimNode_Block * block;
if ( isClosure ) {
bool needResult = type!=nullptr && type->baseType!=Type::tVoid;
bool C0 = !needResult && simlist.size()==1 && finalList.size()==0;
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
block = context.code->makeNode<SimNodeDebug_ClosureBlock>(at, needResult, C0, annotationData);
} else
#endif
{
block = context.code->makeNode<SimNode_ClosureBlock>(at, needResult, C0, annotationData);
}
} else {
if ( maxLabelIndex!=-1 ) {
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
block = context.code->makeNode<SimNodeDebug_BlockWithLabels>(at);
} else
#endif
{
block = context.code->makeNode<SimNode_BlockWithLabels>(at);
}
simulateLabels(context, block, ofsmap);
} else {
if ( finalList.size()==0 ) {
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
block = context.code->makeNode<SimNodeDebug_BlockNF>(at);
} else
#endif
{
block = context.code->makeNode<SimNode_BlockNF>(at);
}
} else {
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
block = context.code->makeNode<SimNodeDebug_Block>(at);
} else
#endif
{
block = context.code->makeNode<SimNode_Block>(at);
}
}
}
}
block->annotationDataSid = annotationDataSid;
block->total = int(simlist.size());
if ( block->total ) {
block->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*block->total);
for ( uint32_t i = 0; i != block->total; ++i )
block->list[i] = simlist[i];
}
if ( !inTheLoop ) {
simulateFinal(context, block);
}
return block;
} else {
return simlist[0];
}
}
SimNode * ExprSwizzle::trySimulate (Context & context, uint32_t extraOffset, const TypeDeclPtr & r2vType ) const {
if ( !value->type->ref ) {
return nullptr;
}
uint32_t offset = fields[0] * sizeof(float);
if ( auto chain = value->trySimulate(context, extraOffset + offset, r2vType) ) {
return chain;
}
auto simV = value->simulate(context);
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_FieldDerefR2V>(r2vType->baseType,at,simV,offset + extraOffset);
} else {
return context.code->makeNode<SimNode_FieldDeref>(at,simV,offset + extraOffset);
}
}
SimNode * ExprSwizzle::simulate (Context & context) const {
if ( !type->ref ) {
bool seq = TypeDecl::isSequencialMask(fields);
if (seq && value->type->ref) {
return trySimulate(context, 0, type);
} else {
auto fsz = fields.size();
uint8_t fs[4];
fs[0] = fields[0];
fs[1] = fsz >= 2 ? fields[1] : fields[0];
fs[2] = fsz >= 3 ? fields[2] : fields[0];
fs[3] = fsz >= 4 ? fields[3] : fields[0];
auto simV = value->simulate(context);
return context.code->makeNode<SimNode_Swizzle>(at, simV, fs);
}
} else {
return trySimulate(context, 0, r2v ? type : make_smart<TypeDecl>(Type::none));
}
}
SimNode * ExprField::simulate (Context & context) const {
if ( value->type->isBitfield() ) {
auto simV = value->simulate(context);
uint32_t mask = 1u << fieldIndex;
return context.code->makeNode<SimNode_GetBitField>(at, simV, mask);
} else if ( !field && fieldIndex==-1 ) {
if ( r2v ) {
auto resN = annotation->simulateGetFieldR2V(name, context, at, value);
if ( !resN ) {
context.thisProgram->error("integration error, simulateGetFieldR2V returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else {
auto resN = annotation->simulateGetField(name, context, at, value);
if ( !resN ) {
context.thisProgram->error("integration error, simulateGetField returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
}
} else {
return trySimulate(context, 0, r2v ? type : make_smart<TypeDecl>(Type::none));
}
}
SimNode * ExprField::trySimulate (Context & context, uint32_t extraOffset, const TypeDeclPtr & r2vType ) const {
if ( !field && fieldIndex==-1 ) {
return nullptr;
}
if ( value->type->isBitfield() ) {
return nullptr;
}
int fieldOffset = -1;
if ( fieldIndex != - 1 ) {
if ( value->type->isPointer() ) {
if ( value->type->firstType->isVariant() ) {
fieldOffset = value->type->firstType->getVariantFieldOffset(fieldIndex);
} else {
fieldOffset = value->type->firstType->getTupleFieldOffset(fieldIndex);
}
} else {
if ( value->type->isVariant() ) {
fieldOffset = value->type->getVariantFieldOffset(fieldIndex);
} else {
fieldOffset = value->type->getTupleFieldOffset(fieldIndex);
}
}
} else {
DAS_ASSERTF(field, "field can't be null");
if (!field) return nullptr;
fieldOffset = field->offset;
}
DAS_ASSERTF(fieldOffset>=0,"field offset is somehow not there");
if (value->type->isPointer()) {
if ( unsafeDeref ) {
auto simV = value->simulate(context);
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_FieldDerefR2V>(r2vType->baseType, at, simV, fieldOffset + extraOffset);
}
else {
return context.code->makeNode<SimNode_FieldDeref>(at, simV, fieldOffset + extraOffset);
}
} else {
auto simV = value->simulate(context);
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_PtrFieldDerefR2V>(r2vType->baseType, at, simV, fieldOffset + extraOffset);
}
else {
return context.code->makeNode<SimNode_PtrFieldDeref>(at, simV, fieldOffset + extraOffset);
}
}
} else {
if ( auto chain = value->trySimulate(context, extraOffset + fieldOffset, r2vType) ) {
return chain;
}
auto simV = value->simulate(context);
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_FieldDerefR2V>(r2vType->baseType, at, simV, extraOffset + fieldOffset);
} else {
return context.code->makeNode<SimNode_FieldDeref>(at, simV, extraOffset + fieldOffset);
}
}
}
SimNode * ExprIsVariant::simulate(Context & context) const {
DAS_ASSERT(fieldIndex != -1);
return context.code->makeNode<SimNode_IsVariant>(at, value->simulate(context), fieldIndex);
}
SimNode * ExprAsVariant::simulate (Context & context) const {
int fieldOffset = value->type->getVariantFieldOffset(fieldIndex);
auto simV = value->simulate(context);
if ( r2v ) {
return context.code->makeValueNode<SimNode_VariantFieldDerefR2V>(type->baseType, at, simV, fieldOffset, fieldIndex);
} else {
return context.code->makeNode<SimNode_VariantFieldDeref>(at, simV, fieldOffset, fieldIndex);
}
}
SimNode * ExprSafeAsVariant::simulate (Context & context) const {
int fieldOffset = value->type->isPointer() ?
value->type->firstType->getVariantFieldOffset(fieldIndex) :
value->type->getVariantFieldOffset(fieldIndex);
auto simV = value->simulate(context);
if ( skipQQ ) {
return context.code->makeNode<SimNode_SafeVariantFieldDerefPtr>(at,simV,fieldOffset, fieldIndex);
} else {
return context.code->makeNode<SimNode_SafeVariantFieldDeref>(at,simV,fieldOffset, fieldIndex);
}
}
SimNode * ExprSafeField::trySimulate(Context &, uint32_t, const TypeDeclPtr &) const {
return nullptr;
}
SimNode * ExprSafeField::simulate (Context & context) const {
int fieldOffset = -1;
if ( !annotation ) {
if ( fieldIndex != - 1 ) {
if ( value->type->firstType->isVariant() ) {
fieldOffset = value->type->firstType->getVariantFieldOffset(fieldIndex);
} else {
fieldOffset = value->type->firstType->getTupleFieldOffset(fieldIndex);
}
} else {
fieldOffset = field->offset;
}
DAS_ASSERTF(fieldOffset>=0,"field offset is somehow not there");
}
if ( skipQQ ) {
if ( annotation ) {
auto resN = annotation->simulateSafeGetFieldPtr(name, context, at, value);
if ( !resN ) {
context.thisProgram->error("integration error, simulateSafeGetFieldPtr returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else {
return context.code->makeNode<SimNode_SafeFieldDerefPtr>(at,value->simulate(context),fieldOffset);
}
} else {
if ( annotation ) {
auto resN = annotation->simulateSafeGetField(name, context, at, value);
if ( !resN ) {
context.thisProgram->error("integration error, simulateSafeGetField returned null", "", "",
at, CompilationError::missing_node );
}
return resN;
} else {
return context.code->makeNode<SimNode_SafeFieldDeref>(at,value->simulate(context),fieldOffset);
}
}
}
SimNode * ExprStringBuilder::simulate (Context & context) const {
SimNode_StringBuilder * pSB = context.code->makeNode<SimNode_StringBuilder>(at);
if ( int nArg = (int) elements.size() ) {
pSB->arguments = (SimNode **) context.code->allocate(nArg * sizeof(SimNode *));
pSB->types = (TypeInfo **) context.code->allocate(nArg * sizeof(TypeInfo *));
pSB->nArguments = nArg;
for ( int a=0; a!=nArg; ++a ) {
pSB->arguments[a] = elements[a]->simulate(context);
pSB->types[a] = context.thisHelper->makeTypeInfo(nullptr, elements[a]->type);
}
} else {
pSB->arguments = nullptr;
pSB->types = nullptr;
pSB->nArguments = 0;
}
return pSB;
}
SimNode * ExprVar::trySimulate (Context & context, uint32_t extraOffset, const TypeDeclPtr & r2vType ) const {
if ( block ) {
} else if ( local ) {
if ( variable->type->ref ) {
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_GetLocalRefOffR2V>(r2vType->baseType, at,
variable->stackTop, extraOffset);
} else {
return context.code->makeNode<SimNode_GetLocalRefOff>(at,
variable->stackTop, extraOffset);
}
} else if ( variable->aliasCMRES ) {
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_GetCMResOfsR2V>(r2vType->baseType, at,extraOffset);
} else {
return context.code->makeNode<SimNode_GetCMResOfs>(at, extraOffset);
}
} else {
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_GetLocalR2V>(r2vType->baseType, at,
variable->stackTop + extraOffset);
} else {
return context.code->makeNode<SimNode_GetLocal>(at, variable->stackTop + extraOffset);
}
}
} else if ( argument ) {
if ( variable->type->isPointer() && variable->type->isRef() ) {
return nullptr;
} else if ( variable->type->isPointer() ) {
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_GetArgumentRefOffR2V>(r2vType->baseType, at, argumentIndex, extraOffset);
} else {
return context.code->makeNode<SimNode_GetArgumentRefOff>(at, argumentIndex, extraOffset);
}
} else if (variable->type->isRef()) {
if ( r2vType->baseType!=Type::none ) {
return context.code->makeValueNode<SimNode_GetArgumentRefOffR2V>(r2vType->baseType, at, argumentIndex, extraOffset);
} else {
return context.code->makeNode<SimNode_GetArgumentRefOff>(at, argumentIndex, extraOffset);
}
}
} else { // global
}
return nullptr;
}
SimNode * ExprVar::simulate (Context & context) const {
if ( block ) {
auto blk = pBlock;
if (variable->type->isRef()) {
if (r2v && !type->isRefType()) {
if ( thisBlock ) {
return context.code->makeValueNode<SimNode_GetThisBlockArgumentR2V>(type->baseType, at, argumentIndex);
} else {
return context.code->makeValueNode<SimNode_GetBlockArgumentR2V>(type->baseType, at, argumentIndex, blk->stackTop);
}
} else {
if ( thisBlock ) {
return context.code->makeNode<SimNode_GetThisBlockArgument>(at, argumentIndex);
} else {
return context.code->makeNode<SimNode_GetBlockArgument>(at, argumentIndex, blk->stackTop);
}
}
} else {
if (r2v && !type->isRefType()) {
if ( thisBlock ) {
return context.code->makeNode<SimNode_GetThisBlockArgument>(at, argumentIndex);
} else {
return context.code->makeNode<SimNode_GetBlockArgument>(at, argumentIndex, blk->stackTop);
}
}
else {
if ( thisBlock ) {
return context.code->makeNode<SimNode_GetThisBlockArgumentRef>(at, argumentIndex);
} else {
return context.code->makeNode<SimNode_GetBlockArgumentRef>(at, argumentIndex, blk->stackTop);
}
}
}
} else if ( local ) {
if ( r2v ) {
return trySimulate(context, 0, type);
} else {
return trySimulate(context, 0, make_smart<TypeDecl>(Type::none));
}
} else if ( argument) {
if (variable->type->isRef()) {
if (r2v && !type->isRefType()) {
return context.code->makeValueNode<SimNode_GetArgumentR2V>(type->baseType, at, argumentIndex);
} else {
return context.code->makeNode<SimNode_GetArgument>(at, argumentIndex);
}
} else {
if (r2v && !type->isRefType()) {
return context.code->makeNode<SimNode_GetArgument>(at, argumentIndex);
}
else {
return context.code->makeNode<SimNode_GetArgumentRef>(at, argumentIndex);
}
}
} else {
DAS_ASSERT(variable->index >= 0 && "using variable which is not used. how?");
uint32_t mnh = variable->getMangledNameHash();
if ( !variable->module->isSolidContext ) {
if ( variable->global_shared ) {
if ( r2v ) {
return context.code->makeValueNode<SimNode_GetSharedMnhR2V>(type->baseType, at, variable->stackTop, mnh);
} else {
return context.code->makeNode<SimNode_GetSharedMnh>(at, variable->stackTop, mnh);
}
} else {
if ( r2v ) {
return context.code->makeValueNode<SimNode_GetGlobalMnhR2V>(type->baseType, at, variable->stackTop, mnh);
} else {
return context.code->makeNode<SimNode_GetGlobalMnh>(at, variable->stackTop, mnh);
}
}
} else {
if ( variable->global_shared ) {
if ( r2v ) {
return context.code->makeValueNode<SimNode_GetSharedR2V>(type->baseType, at, variable->stackTop, mnh);
} else {
return context.code->makeNode<SimNode_GetShared>(at, variable->stackTop, mnh);
}
} else {
if ( r2v ) {
return context.code->makeValueNode<SimNode_GetGlobalR2V>(type->baseType, at, variable->stackTop, mnh);
} else {
return context.code->makeNode<SimNode_GetGlobal>(at, variable->stackTop, mnh);
}
}
}
}
}
SimNode * ExprOp1::simulate (Context & context) const {
vector<ExpressionPtr> sarguments = { subexpr };
if ( func->builtIn && !func->callBased ) {
auto pSimOp1 = static_cast<SimNode_Op1 *>(func->makeSimNode(context,sarguments));
pSimOp1->debugInfo = at;
pSimOp1->x = subexpr->simulate(context);
return pSimOp1;
} else {
auto pCall = static_cast<SimNode_CallBase *>(func->makeSimNode(context,sarguments));
pCall->debugInfo = at;
pCall->fnPtr = context.getFunction(func->index);
pCall->arguments = (SimNode **) context.code->allocate(1 * sizeof(SimNode *));
pCall->nArguments = 1;
pCall->arguments[0] = subexpr->simulate(context);
pCall->cmresEval = context.code->makeNode<SimNode_GetLocal>(at,stackTop);
return pCall;
}
}
SimNode * ExprOp2::simulate (Context & context) const {
vector<ExpressionPtr> sarguments = { left, right };
if ( func->builtIn && !func->callBased ) {
auto pSimOp2 = static_cast<SimNode_Op2 *>(func->makeSimNode(context,sarguments));
pSimOp2->debugInfo = at;
pSimOp2->l = left->simulate(context);
pSimOp2->r = right->simulate(context);
return pSimOp2;
} else {
auto pCall = static_cast<SimNode_CallBase *>(func->makeSimNode(context,sarguments));
pCall->debugInfo = at;
pCall->fnPtr = context.getFunction(func->index);
pCall->arguments = (SimNode **) context.code->allocate(2 * sizeof(SimNode *));
pCall->nArguments = 2;
pCall->arguments[0] = left->simulate(context);
pCall->arguments[1] = right->simulate(context);
pCall->cmresEval = context.code->makeNode<SimNode_GetLocal>(at,stackTop);
return pCall;
}
}
SimNode * ExprOp3::simulate (Context & context) const {
return context.code->makeNode<SimNode_IfThenElse>(at,
subexpr->simulate(context),
left->simulate(context),
right->simulate(context));
}
SimNode * ExprMove::simulate (Context & context) const {
auto retN = makeMove(at,context,left,right);
if ( !retN ) {
context.thisProgram->error("internal compilation error, can't generate move", "", "", at);
}
return retN;
}
SimNode * ExprClone::simulate (Context & context) const {
SimNode * retN = nullptr;
if ( left->type->isHandle() ) {
auto lN = left->simulate(context);
auto rN = right->simulate(context);
retN = left->type->annotation->simulateClone(context, at, lN, rN);
} else if ( left->type->canCopy() ) {
retN = makeCopy(at, context, left, right );
} else {
retN = nullptr;
}
if ( !retN ) {
context.thisProgram->error("internal compilation error, can't generate clone", "", "", at);
}
return retN;
}
SimNode * ExprCopy::simulate (Context & context) const {
if ( takeOverRightStack ) {
auto sl = left->simulate(context);
auto sr = right->simulate(context);
return context.code->makeNode<SimNode_SetLocalRefAndEval>(at, sl, sr, stackTop);
} else {
auto retN = makeCopy(at, context, left, right);
if ( !retN ) {
context.thisProgram->error("internal compilation error, can't generate copy", "", "", at);
}
return retN;
}
}
SimNode * ExprTryCatch::simulate (Context & context) const {
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
return context.code->makeNode<SimNodeDebug_TryCatch>(at,
try_block->simulate(context),
catch_block->simulate(context));
} else
#endif
{
return context.code->makeNode<SimNode_TryCatch>(at,
try_block->simulate(context),
catch_block->simulate(context));
}
}
SimNode * ExprReturn::simulate (Context & context) const {
// return string is its own thing
if (subexpr && subexpr->type && subexpr->rtti_isConstant()) {
if (subexpr->type->isSimpleType(Type::tString)) {
auto cVal = static_pointer_cast<ExprConstString>(subexpr);
char * str = context.constStringHeap->allocateString(cVal->text);
return context.code->makeNode<SimNode_ReturnConstString>(at, str);
}
}
// now, lets do the standard everything
bool skipIt = false;
if ( subexpr && subexpr->rtti_isMakeLocal() ) {
if ( static_pointer_cast<ExprMakeLocal>(subexpr)->useCMRES ) {
skipIt = true;
}
}
SimNode * simSubE = (subexpr && !skipIt) ? subexpr->simulate(context) : nullptr;
if (!subexpr) {
return context.code->makeNode<SimNode_ReturnNothing>(at);
} else if ( subexpr->rtti_isConstant() ) {
auto cVal = static_pointer_cast<ExprConst>(subexpr);
return context.code->makeNode<SimNode_ReturnConst>(at, cVal->value);
}
if ( returnReference ) {
if ( returnInBlock ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnReferenceFromBlock>(at, simSubE);
} else {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnReference>(at, simSubE);
}
} else if ( returnInBlock ) {
if ( returnCallCMRES ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
SimNode_CallBase * simRet = (SimNode_CallBase *) simSubE;
simRet->cmresEval = context.code->makeNode<SimNode_GetBlockCMResOfs>(at,0,stackTop);
return context.code->makeNode<SimNode_Return>(at, simSubE);
} else if ( takeOverRightStack ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnRefAndEvalFromBlock>(at,
simSubE, refStackTop, stackTop);
} else if ( block->copyOnReturn ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnAndCopyFromBlock>(at,
simSubE, subexpr->type->getSizeOf(), stackTop);
} else if ( block->moveOnReturn ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnAndMoveFromBlock>(at,
simSubE, subexpr->type->getSizeOf(), stackTop);
}
} else if ( subexpr ) {
if ( returnCallCMRES ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
SimNode_CallBase * simRet = (SimNode_CallBase *) simSubE;
simRet->cmresEval = context.code->makeNode<SimNode_GetCMResOfs>(at,0);
return context.code->makeNode<SimNode_Return>(at, simSubE);
} else if ( returnCMRES ) {
// ReturnLocalCMRes
if ( subexpr->rtti_isMakeLocal() ) {
auto mkl = static_pointer_cast<ExprMakeLocal>(subexpr);
if ( mkl->useCMRES ) {
SimNode_Block * blockT = context.code->makeNode<SimNode_ReturnLocalCMRes>(at);
auto simlist = mkl->simulateLocal(context);
blockT->total = int(simlist.size());
blockT->list = (SimNode **) context.code->allocate(sizeof(SimNode *)*blockT->total);
for ( uint32_t i = 0; i != blockT->total; ++i )
blockT->list[i] = simlist[i];
return blockT;
}
}
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_Return>(at, simSubE);
} else if ( takeOverRightStack ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnRefAndEval>(at, simSubE, refStackTop);
} else if ( returnFunc && returnFunc->copyOnReturn ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnAndCopy>(at, simSubE, subexpr->type->getSizeOf());
} else if ( returnFunc && returnFunc->moveOnReturn ) {
DAS_ASSERTF(simSubE, "internal error. can't be zero");
return context.code->makeNode<SimNode_ReturnAndMove>(at, simSubE, subexpr->type->getSizeOf());
}
}
DAS_ASSERTF(simSubE, "internal error. can't be zero");
if ( moveSemantics ) {
// TODO: support by-value annotations?
if ( subexpr->type->isRef() ) {
return context.code->makeValueNode<SimNode_ReturnAndMoveR2V>(subexpr->type->baseType, at, simSubE);
} else {
return context.code->makeNode<SimNode_Return>(at, simSubE);
}
} else {
return context.code->makeNode<SimNode_Return>(at, simSubE);
}
}
SimNode * ExprBreak::simulate (Context & context) const {
return context.code->makeNode<SimNode_Break>(at);
}
SimNode * ExprContinue::simulate (Context & context) const {
return context.code->makeNode<SimNode_Continue>(at);
}
SimNode * ExprIfThenElse::simulate (Context & context) const {
ExpressionPtr zeroCond;
bool condIfZero = false;
bool match0 = matchEquNequZero(cond, zeroCond, condIfZero);
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
if ( match0 && zeroCond->type->isWorkhorseType() ) {
if ( condIfZero ) {
if ( if_false ) {
return context.code->makeNumericValueNode<SimNodeDebug_IfZeroThenElse>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context),
if_false->simulate(context));
} else {
return context.code->makeNumericValueNode<SimNodeDebug_IfZeroThen>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context));
}
} else {
if ( if_false ) {
return context.code->makeNumericValueNode<SimNodeDebug_IfNotZeroThenElse>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context),
if_false->simulate(context));
} else {
return context.code->makeNumericValueNode<SimNodeDebug_IfNotZeroThen>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context));
}
}
} else {
// good old if
if ( if_false ) {
return context.code->makeNode<SimNodeDebug_IfThenElse>(at, cond->simulate(context),
if_true->simulate(context), if_false->simulate(context));
} else {
return context.code->makeNode<SimNodeDebug_IfThen>(at, cond->simulate(context),
if_true->simulate(context));
}
}
} else
#endif
{
if ( match0 && zeroCond->type->isWorkhorseType() ) {
if ( condIfZero ) {
if ( if_false ) {
return context.code->makeNumericValueNode<SimNode_IfZeroThenElse>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context),
if_false->simulate(context));
} else {
return context.code->makeNumericValueNode<SimNode_IfZeroThen>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context));
}
} else {
if ( if_false ) {
return context.code->makeNumericValueNode<SimNode_IfNotZeroThenElse>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context),
if_false->simulate(context));
} else {
return context.code->makeNumericValueNode<SimNode_IfNotZeroThen>(zeroCond->type->baseType,
at, zeroCond->simulate(context), if_true->simulate(context));
}
}
} else {
// good old if
if ( if_false ) {
return context.code->makeNode<SimNode_IfThenElse>(at, cond->simulate(context),
if_true->simulate(context), if_false->simulate(context));
} else {
return context.code->makeNode<SimNode_IfThen>(at, cond->simulate(context),
if_true->simulate(context));
}
}
}
}
SimNode * ExprWith::simulate (Context & context) const {
return body->simulate(context);
}
SimNode * ExprAssume::simulate (Context &) const {
return nullptr;
}
void ExprWhile::simulateFinal ( Context & context, const ExpressionPtr & bod, SimNode_Block * blk ) {
if ( bod->rtti_isBlock() ) {
auto pBlock = static_pointer_cast<ExprBlock>(bod);
pBlock->simulateBlock(context, blk);
pBlock->simulateFinal(context, blk);
} else {
context.thisProgram->error("internal error, expecting block", "", "", bod->at);
}
}
SimNode * ExprWhile::simulate (Context & context) const {
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
auto node = context.code->makeNode<SimNodeDebug_While>(at, cond->simulate(context));
simulateFinal(context, body, node);
return node;
} else
#endif
{
auto node = context.code->makeNode<SimNode_While>(at, cond->simulate(context));
simulateFinal(context, body, node);
return node;
}
}
SimNode * ExprUnsafe::simulate (Context & context) const {
return body->simulate(context);
}
SimNode * ExprFor::simulate (Context & context) const {
// determine iteration types
bool nativeIterators = false;
bool fixedArrays = false;
bool dynamicArrays = false;
bool stringChars = false;
bool rangeBase = false;
int32_t fixedSize = INT32_MAX;
for ( auto & src : sources ) {
if ( !src->type ) continue;
if ( src->type->isArray() ) {
fixedSize = das::min(fixedSize, src->type->dim[0]);
fixedArrays = true;
} else if ( src->type->isGoodArrayType() ) {
dynamicArrays = true;
} else if ( src->type->isGoodIteratorType() ) {
nativeIterators = true;
} else if ( src->type->isHandle() ) {
nativeIterators = true;
} else if ( src->type->isRange() ) {
rangeBase = true;
} else if ( src->type->isString() ) {
stringChars = true;
}
}
// create loops based on
int total = int(sources.size());
int sourceTypes = int(dynamicArrays) + int(fixedArrays) + int(rangeBase) + int(stringChars);
bool hybridRange = rangeBase && (total>1);
if ( (sourceTypes>1) || hybridRange || nativeIterators || stringChars || /* this is how much we can unroll */ total>MAX_FOR_UNROLL ) {
SimNode_ForWithIteratorBase * result;
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
if ( total>MAX_FOR_UNROLL ) {
result = (SimNode_ForWithIteratorBase *) context.code->makeNode<SimNodeDebug_ForWithIteratorBase>(at);
} else {
result = (SimNode_ForWithIteratorBase *) context.code->makeNodeUnrollNZ_FOR<SimNodeDebug_ForWithIterator>(total, at);
}
} else
#endif
{
if ( total>MAX_FOR_UNROLL ) {
result = (SimNode_ForWithIteratorBase *) context.code->makeNode<SimNode_ForWithIteratorBase>(at);
} else {
result = (SimNode_ForWithIteratorBase *) context.code->makeNodeUnrollNZ_FOR<SimNode_ForWithIterator>(total, at);
}
}
result->allocateFor(context.code.get(), total);
for ( int t=0; t!=total; ++t ) {
if ( sources[t]->type->isGoodIteratorType() ) {
result->source_iterators[t] = context.code->makeNode<SimNode_Seq2Iter>(
sources[t]->at,
sources[t]->simulate(context));
} else if ( sources[t]->type->isGoodArrayType() ) {
result->source_iterators[t] = context.code->makeNode<SimNode_GoodArrayIterator>(
sources[t]->at,
sources[t]->simulate(context),
sources[t]->type->firstType->getStride());
} else if ( sources[t]->type->isRange() ) {
result->source_iterators[t] = context.code->makeNode<SimNode_RangeIterator>(
sources[t]->at,
sources[t]->simulate(context),
sources[t]->type->baseType==Type::tRange);
} else if ( sources[t]->type->isString() ) {
result->source_iterators[t] = context.code->makeNode<SimNode_StringIterator>(
sources[t]->at,
sources[t]->simulate(context));
} else if ( sources[t]->type->isHandle() ) {
if ( !result ) {
context.thisProgram->error("integration error, simulateGetIterator returned null", "", "",
at, CompilationError::missing_node );
return nullptr;
} else {
result->source_iterators[t] = sources[t]->type->annotation->simulateGetIterator(
context,
sources[t]->at,
sources[t]
);
}
} else if ( sources[t]->type->dim.size() ) {
result->source_iterators[t] = context.code->makeNode<SimNode_FixedArrayIterator>(
sources[t]->at,
sources[t]->simulate(context),
sources[t]->type->dim[0],
sources[t]->type->getStride());
} else {
DAS_ASSERTF(0, "we should not be here. we are doing iterator for on an unsupported type.");
context.thisProgram->error("internal compilation error, generating for-with-iterator", "", "", at);
return nullptr;
}
result->stackTop[t] = iteratorVariables[t]->stackTop;
}
ExprWhile::simulateFinal(context, body, result);
return result;
} else {
auto flagsE = body->getEvalFlags();
bool NF = flagsE == 0;
SimNode_ForBase * result;
DAS_ASSERT(body->rtti_isBlock() && "there would be internal error otherwise");
auto subB = static_pointer_cast<ExprBlock>(body);
bool loop1 = (subB->list.size() == 1);
#if DAS_DEBUGGER
if ( context.thisProgram->getDebugger() ) {
if ( dynamicArrays ) {
if (loop1) {
result = (SimNode_ForBase *) context.code->makeNodeUnrollNZ_FOR<SimNodeDebug_ForGoodArray1>(total, at);
} else {
result = (SimNode_ForBase *) context.code->makeNodeUnrollNZ_FOR<SimNodeDebug_ForGoodArray>(total, at);
}
} else if ( fixedArrays ) {
if (loop1) {
result = (SimNode_ForBase *)context.code->makeNodeUnrollNZ_FOR<SimNodeDebug_ForFixedArray1>(total, at);
} else {
result = (SimNode_ForBase *)context.code->makeNodeUnrollNZ_FOR<SimNodeDebug_ForFixedArray>(total, at);
}
} else if ( rangeBase ) {
DAS_ASSERT(total==1 && "simple range on 1 loop only");
bool isSigned = sources[0]->type->baseType == Type::tRange;
if ( NF ) {
if (loop1) {
result = context.code->makeNode<SimNodeDebug_ForRangeNF1>(at,isSigned);
} else {
result = context.code->makeNode<SimNodeDebug_ForRangeNF>(at,isSigned);
}
} else {
if (loop1) {
result = context.code->makeNode<SimNodeDebug_ForRange1>(at,isSigned);
} else {
result = context.code->makeNode<SimNodeDebug_ForRange>(at,isSigned);
}
}
} else {
DAS_ASSERTF(0, "we should not be here yet. logic above assumes optimized for path of some kind.");
context.thisProgram->error("internal compilation error, generating for", "", "", at);
return nullptr;
}
} else
#endif
{
if ( dynamicArrays ) {
if (loop1) {
result = (SimNode_ForBase *) context.code->makeNodeUnrollNZ_FOR<SimNode_ForGoodArray1>(total, at);
} else {
result = (SimNode_ForBase *) context.code->makeNodeUnrollNZ_FOR<SimNode_ForGoodArray>(total, at);
}
} else if ( fixedArrays ) {
if (loop1) {
result = (SimNode_ForBase *)context.code->makeNodeUnrollNZ_FOR<SimNode_ForFixedArray1>(total, at);
} else {
result = (SimNode_ForBase *)context.code->makeNodeUnrollNZ_FOR<SimNode_ForFixedArray>(total, at);
}
} else if ( rangeBase ) {
DAS_ASSERT(total==1 && "simple range on 1 loop only");
bool isSigned = sources[0]->type->baseType == Type::tRange;
if ( NF ) {
if (loop1) {
result = context.code->makeNode<SimNode_ForRangeNF1>(at,isSigned);
} else {
result = context.code->makeNode<SimNode_ForRangeNF>(at,isSigned);
}
} else {
if (loop1) {
result = context.code->makeNode<SimNode_ForRange1>(at,isSigned);
} else {
result = context.code->makeNode<SimNode_ForRange>(at,isSigned);
}
}
} else {
DAS_ASSERTF(0, "we should not be here yet. logic above assumes optimized for path of some kind.");
context.thisProgram->error("internal compilation error, generating for", "", "", at);
return nullptr;
}
}
result->allocateFor(context.code.get(), total);
for ( int t=0; t!=total; ++t ) {
result->sources[t] = sources[t]->simulate(context);
if ( sources[t]->type->isGoodArrayType() ) {
result->strides[t] = sources[t]->type->firstType->getStride();
} else {
result->strides[t] = sources[t]->type->getStride();
}
result->stackTop[t] = iteratorVariables[t]->stackTop;
}
result->size = fixedSize;
ExprWhile::simulateFinal(context, body, result);
return result;
}
}
vector<SimNode *> ExprLet::simulateInit(Context & context, const ExprLet * pLet) {
vector<SimNode *> simlist;
simlist.reserve(pLet->variables.size());
for (auto & var : pLet->variables) {
SimNode * init;
if (var->init) {
init = ExprLet::simulateInit(context, var, true);
} else if (var->aliasCMRES ) {
int bytes = var->type->getSizeOf();
if ( bytes <= 32 ) {
init = context.code->makeNodeUnrollNZ<SimNode_InitLocalCMResN>(bytes, pLet->at,0);
} else {
init = context.code->makeNode<SimNode_InitLocalCMRes>(pLet->at,0,bytes);
}
} else {
init = context.code->makeNode<SimNode_InitLocal>(pLet->at, var->stackTop, var->type->getSizeOf());
}
if (init)
simlist.push_back(init);
}
return simlist;
}
SimNode * ExprLet::simulateInit(Context & context, const VariablePtr & var, bool local) {
SimNode * get;
if ( local ) {
if ( var->init && var->init->rtti_isMakeLocal() ) {
return var->init->simulate(context);
} else {
get = context.code->makeNode<SimNode_GetLocal>(var->init->at, var->stackTop);
}
} else {
if ( var->init && var->init->rtti_isMakeLocal() ) {
return var->init->simulate(context);
} else {
if ( !var->module->isSolidContext ) {
if ( var->global_shared ) {
get = context.code->makeNode<SimNode_GetSharedMnh>(var->init->at, var->index, var->getMangledNameHash());
} else {
get = context.code->makeNode<SimNode_GetGlobalMnh>(var->init->at, var->index, var->getMangledNameHash());
}
} else {
if ( var->global_shared ) {
get = context.code->makeNode<SimNode_GetShared>(var->init->at, var->index, var->getMangledNameHash());
} else {
get = context.code->makeNode<SimNode_GetGlobal>(var->init->at, var->index, var->getMangledNameHash());
}
}
}
}
if ( var->type->ref ) {
return context.code->makeNode<SimNode_CopyReference>(var->init->at, get,
var->init->simulate(context));
} else if ( var->init_via_move && var->type->canMove() ) {
auto varExpr = make_smart<ExprVar>(var->at, var->name);
varExpr->variable = var;
varExpr->local = local;
varExpr->type = make_smart<TypeDecl>(*var->type);
auto retN = makeMove(var->init->at, context, varExpr, var->init);
if ( !retN ) {
context.thisProgram->error("internal compilation error, can't generate move", "", "", var->at);
}
return retN;
} else if ( !var->init_via_move && var->type->canCopy() ) {
auto varExpr = make_smart<ExprVar>(var->at, var->name);
varExpr->variable = var;
varExpr->local = local;
varExpr->type = make_smart<TypeDecl>(*var->type);
auto retN = makeCopy(var->init->at, context, varExpr, var->init);
if ( !retN ) {
context.thisProgram->error("internal compilation error, can't generate copy", "", "", var->at);
}
return retN;
} else if ( var->isCtorInitialized() ) {
auto varExpr = make_smart<ExprVar>(var->at, var->name);
varExpr->variable = var;
varExpr->local = local;
varExpr->type = make_smart<TypeDecl>(*var->type);
SimNode_CallBase * retN = nullptr; // it has to be CALL with CMRES
const auto & rE = var->init;
if ( rE->rtti_isCall() ) {
auto cll = static_pointer_cast<ExprCall>(rE);
if ( cll->func->copyOnReturn || cll->func->moveOnReturn ) {
retN = (SimNode_CallBase *) rE->simulate(context);
retN->cmresEval = varExpr->simulate(context);
}
}
if ( !retN ) {
context.thisProgram->error("internal compilation error, can't generate class constructor", "", "", var->at);
}
return retN;
} else {
context.thisProgram->error("internal compilation error, initializing variable which can't be copied or moved", "", "", var->at);
return nullptr;
}
}
SimNode * ExprLet::simulate (Context & context) const {
auto let = context.code->makeNode<SimNode_Let>(at);
let->total = (uint32_t) variables.size();
let->list = (SimNode **) context.code->allocate(let->total * sizeof(SimNode*));
auto simList = ExprLet::simulateInit(context, this);
copy(simList.data(), simList.data() + simList.size(), let->list);
return let;
}
SimNode_CallBase * ExprCall::simulateCall (const FunctionPtr & func,
const ExprLooksLikeCall * expr,
Context & context,
SimNode_CallBase * pCall) {
bool needTypeInfo = false;
for ( auto & arg : func->arguments ) {
if ( arg->type->baseType==Type::anyArgument )
needTypeInfo = true;
}
pCall->debugInfo = expr->at;
if ( func->builtIn) {
pCall->fnPtr = nullptr;
} else if ( func->index>=0 ) {
pCall->fnPtr = context.getFunction(func->index);
DAS_ASSERTF(pCall->fnPtr, "calling function which null. how?");
} else {
DAS_ASSERTF(0, "calling function which is not used. how?");
}
if ( int nArg = (int) expr->arguments.size() ) {
pCall->arguments = (SimNode **) context.code->allocate(nArg * sizeof(SimNode *));
if ( needTypeInfo ) {
pCall->types = (TypeInfo **) context.code->allocate(nArg * sizeof(TypeInfo *));
} else {
pCall->types = nullptr;
}
pCall->nArguments = nArg;
for ( int a=0; a!=nArg; ++a ) {
pCall->arguments[a] = expr->arguments[a]->simulate(context);
if ( pCall->types ) {
if ( func->arguments[a]->type->baseType==Type::anyArgument ) {
pCall->types[a] = context.thisHelper->makeTypeInfo(nullptr, expr->arguments[a]->type);
} else {
pCall->types[a] = nullptr;
}
}
}
} else {
pCall->arguments = nullptr;
pCall->nArguments = 0;
}
return pCall;
}
SimNode * ExprCall::simulate (Context & context) const {
auto pCall = static_cast<SimNode_CallBase *>(func->makeSimNode(context,arguments));
simulateCall(func, this, context, pCall);
if ( !doesNotNeedSp && stackTop ) {
pCall->cmresEval = context.code->makeNode<SimNode_GetLocal>(at,stackTop);
}
return pCall;
}
SimNode * ExprNamedCall::simulate (Context &) const {
DAS_ASSERTF(false, "we should not be here. named call should be promoted to regular call");
return nullptr;
}
void Program::buildGMNLookup ( Context & context, TextWriter & logs ) {
context.tabGMnLookup.clear();
for ( int i=0; i!=context.totalVariables; ++i ) {
auto mnh = context.globalVariables[i].mangledNameHash;
context.tabGMnLookup[mnh] = context.globalVariables[i].offset;
}
if ( options.getBoolOption("log_gmn_hash",false) ) {
logs
<< "totalGlobals: " << context.totalVariables << "\n"
<< "tabGMnLookup:" << context.tabGMnLookup.size() << "\n";
}
for ( int i=0; i!=context.totalVariables; ++i ) {
auto & gvar = context.globalVariables[i];
uint32_t voffset = context.globalOffsetByMangledName(gvar.mangledNameHash);
if ( voffset != gvar.offset ) {
error("internal compiler error. global variable mangled name hash collision "
+ string(context.functions[i].mangledName), "", "", LineInfo());
return;
}
}
}
void Program::buildMNLookup ( Context & context, const vector<FunctionPtr> & lookupFunctions, TextWriter & logs ) {
context.tabMnLookup.clear();
for ( const auto & fn : lookupFunctions ) {
auto mnh = fn->getMangledNameHash();
context.tabMnLookup[mnh] = context.functions + fn->index;
}
if ( options.getBoolOption("log_mn_hash",false) ) {
logs
<< "totalFunctions: " << context.totalFunctions << "\n"
<< "tabMnLookup:" << context.tabMnLookup.size() << "\n";
}
}
void Program::buildADLookup ( Context & context, TextWriter & logs ) {
for (auto & pm : library.modules ) {
for(auto s2d : pm->annotationData ) {
context.tabAdLookup[s2d.first] = s2d.second;
}
}
if ( options.getBoolOption("log_ad_hash",false) ) {
logs<< "tabAdLookup:" << context.tabAdLookup.size() << "\n";
}
}
void Program::makeMacroModule ( TextWriter & logs ) {
isCompilingMacros = true;
thisModule->macroContext = make_smart<Context>(getContextStackSize());
auto oldAot = policies.aot;
policies.aot = false;
simulate(*thisModule->macroContext, logs);
policies.aot = oldAot;
isCompilingMacros = false;
}
extern "C" int64_t ref_time_ticks ();
extern "C" int get_time_usec (int64_t reft);
bool Program::simulate ( Context & context, TextWriter & logs, StackAllocator * sharedStack ) {
auto time0 = ref_time_ticks();
isSimulating = true;
context.thisProgram = this;
context.persistent = options.getBoolOption("persistent_heap", policies.persistent_heap);
if ( context.persistent ) {
context.heap = make_smart<PersistentHeapAllocator>();
context.stringHeap = make_smart<PersistentStringAllocator>();
} else {
context.heap = make_smart<LinearHeapAllocator>();
context.stringHeap = make_smart<LinearStringAllocator>();
}
context.heap->setInitialSize ( options.getIntOption("heap_size_hint", policies.heap_size_hint) );
context.stringHeap->setInitialSize ( options.getIntOption("string_heap_size_hint", policies.string_heap_size_hint) );
context.constStringHeap = make_shared<ConstStringAllocator>();
if ( globalStringHeapSize ) {
context.constStringHeap->setInitialSize(globalStringHeapSize);
}
DebugInfoHelper helper(context.debugInfo);
helper.rtti = options.getBoolOption("rtti",policies.rtti);
context.thisHelper = &helper;
context.globalVariables = (GlobalVariable *) context.code->allocate( totalVariables*sizeof(GlobalVariable) );
context.globalsSize = 0;
context.sharedSize = 0;
if ( totalVariables ) {
for (auto & pm : library.modules ) {
pm->globals.foreach([&](auto pvar){
if (!pvar->used)
return;
if ( pvar->index<0 ) {
error("Internalc compiler errors. Simulating variable which is not used" + pvar->name,
"", "", LineInfo());
return;
}
auto & gvar = context.globalVariables[pvar->index];
gvar.name = context.code->allocateName(pvar->name);
gvar.size = pvar->type->getSizeOf();
gvar.debugInfo = helper.makeVariableDebugInfo(*pvar);
gvar.flags = 0;
if ( pvar->global_shared ) {
gvar.offset = pvar->stackTop = context.sharedSize;
gvar.shared = true;
context.sharedSize = (context.sharedSize + gvar.size + 0xf) & ~0xf;
} else {
gvar.offset = pvar->stackTop = context.globalsSize;
context.globalsSize = (context.globalsSize + gvar.size + 0xf) & ~0xf;
}
gvar.mangledNameHash = pvar->getMangledNameHash();
});
}
}
context.globals = (char *) das_aligned_alloc16(context.globalsSize);
context.shared = (char *) das_aligned_alloc16(context.sharedSize);
context.sharedOwner = true;
context.totalVariables = totalVariables;
context.functions = (SimFunction *) context.code->allocate( totalFunctions*sizeof(SimFunction) );
context.totalFunctions = totalFunctions;
auto debuggerOrGC = getDebugger() || context.thisProgram->options.getBoolOption("gc",false);
vector<FunctionPtr> lookupFunctionTable;
das_map<uint32_t,SimFunction *> sharedLookup;
if ( totalFunctions ) {
for (auto & pm : library.modules) {
pm->functions.foreach([&](auto pfun){
if (pfun->index < 0 || !pfun->used)
return;
auto mangledName = pfun->getMangledName();
auto MNH = hash_blockz32((uint8_t *)mangledName.c_str());
if ( MNH==0 ) {
error("Internalc compiler errors. Mangled name hash is zero. Function " + pfun->name,
"\tMangled name " + mangledName + " hash is " + to_string(MNH), "",
pfun->at);
}
auto & gfun = context.functions[pfun->index];
gfun.name = context.code->allocateName(pfun->name);
gfun.mangledName = context.code->allocateName(mangledName);
gfun.debugInfo = helper.makeFunctionDebugInfo(*pfun);
if ( folding ) {
gfun.debugInfo->flags &= ~ (FuncInfo::flag_init | FuncInfo::flag_shutdown);
}
if ( debuggerOrGC ) {
helper.appendLocalVariables(gfun.debugInfo, pfun->body);
}
gfun.stackSize = pfun->totalStackSize;
gfun.mangledNameHash = MNH;
gfun.aotFunction = nullptr;
gfun.flags = 0;
gfun.fastcall = pfun->fastCall;
if ( pfun->module->builtIn && !pfun->module->promoted ) {
gfun.builtin = true;
}
gfun.code = pfun->simulate(context);
lookupFunctionTable.push_back(pfun);
});
}
}
if ( totalVariables ) {
for (auto & pm : library.modules ) {
pm->globals.foreach([&](auto pvar){
if (!pvar->used)
return;
auto & gvar = context.globalVariables[pvar->index];
if ( !folding && pvar->init ) {
if ( pvar->init->rtti_isMakeLocal() ) {
if ( pvar->global_shared ) {
auto sl = context.code->makeNode<SimNode_GetSharedMnh>(pvar->init->at, pvar->stackTop, pvar->getMangledNameHash());
auto sr = ExprLet::simulateInit(context, pvar, false);
auto gvari = context.code->makeNode<SimNode_SetLocalRefAndEval>(pvar->init->at, sl, sr, uint32_t(sizeof(Prologue)));
auto cndb = context.code->makeNode<SimNode_GetArgument>(pvar->init->at, 1); // arg 1 of init script is "init_globals"
gvar.init = context.code->makeNode<SimNode_IfThen>(pvar->init->at, cndb, gvari);
} else {
auto sl = context.code->makeNode<SimNode_GetGlobalMnh>(pvar->init->at, pvar->stackTop, pvar->getMangledNameHash());
auto sr = ExprLet::simulateInit(context, pvar, false);
gvar.init = context.code->makeNode<SimNode_SetLocalRefAndEval>(pvar->init->at, sl, sr, uint32_t(sizeof(Prologue)));
}
} else {
gvar.init = ExprLet::simulateInit(context, pvar, false);
}
} else {
gvar.init = nullptr;
}
});
}
}
//
context.globalInitStackSize = globalInitStackSize;
buildMNLookup(context, lookupFunctionTable, logs);
buildGMNLookup(context, logs);
buildADLookup(context, logs);
context.simEnd();
// if RTTI is enabled
if (errors.size()) {
isSimulating = false;
return false;
}
bool aot_hint = policies.aot && !folding && !thisModule->isModule;
#if DAS_FUSION
if ( !folding ) { // note: only run fusion when not folding
fusion(context, logs);
context.relocateCode(true); // this to get better estimate on relocated size. its fust enough
}
#else
if ( !folding ) {
context.relocateCode(true);
}
#endif
if ( !folding ) {
if ( !aot_hint ) {
context.relocateCode();
}
}
context.restart();
// now call annotation simulate
das_hash_map<int,Function *> indexToFunction;
for (auto & pm : library.modules) {
pm->functions.foreach([&](auto pfun){
if (pfun->index < 0 || !pfun->used)
return;
auto & gfun = context.functions[pfun->index];
for ( const auto & an : pfun->annotations ) {
auto fna = static_pointer_cast<FunctionAnnotation>(an->annotation);
if (!fna->simulate(&context, &gfun)) {
error("function " + pfun->describe() + " annotation " + fna->name + " simulation failed", "", "",
LineInfo(), CompilationError::cant_initialize);
}
}
indexToFunction[pfun->index] = pfun.get();
});
}
// verify code and string heaps
#if DAS_FUSION
if ( !folding ) {
// note: this only matters if code has significant jumping around
// which is always introduced by fusion
DAS_ASSERTF(context.code->depth()<=1, "code must come in one page");
}
#endif
DAS_ASSERTF(context.constStringHeap->depth()<=1, "strings must come in one page");
context.stringHeap->setIntern(options.getBoolOption("intern_strings", policies.intern_strings));
// log all functions
if ( options.getBoolOption("log_nodes",false) ) {
bool displayHash = options.getBoolOption("log_nodes_aot_hash",false);
for ( int i=0; i!=context.totalVariables; ++i ) {
auto & pv = context.globalVariables[i];
if ( pv.init ) {
logs << "// init " << pv.name << "\n";
printSimNode(logs, &context, pv.init, displayHash);
logs << "\n\n";
}
}
for ( int i=0; i!=context.totalFunctions; ++i ) {
if (SimFunction * fn = context.getFunction(i)) {
logs << "// " << fn->name << " " << fn->mangledName << "\n";
printSimFunction(logs, &context, indexToFunction[i], fn->code, displayHash);
logs << "\n\n";
}
}
}
// now relocate before we run that init script
if ( aot_hint ) {
linkCppAot(context, getGlobalAotLibrary(), logs);
context.relocateCode(true);
context.relocateCode();
}
// run init script and restart
if ( !folding ) {
auto time1 = ref_time_ticks();
if (!context.runWithCatch([&]() {
if ( context.stack.size() && context.stack.size()>globalInitStackSize ) {
context.runInitScript();
} else if ( sharedStack && sharedStack->size()>globalInitStackSize ) {
SharedStackGuard guard(context, *sharedStack);
context.runInitScript();
} else {
auto ssz = max ( getContextStackSize(), 16384 ) + globalInitStackSize;
StackAllocator init_stack(ssz);
SharedStackGuard guard(context, init_stack);
context.runInitScript();
}
})) {
error("exception during init script", context.getException(), "",
context.exceptionAt, CompilationError::cant_initialize);
}
if ( options.getBoolOption("log_total_compile_time",false) ) {
auto dt = get_time_usec(time1) / 1000000.;
logs << "init script took " << dt << "\n";
}
}
context.restart();
if (options.getBoolOption("log_mem",false) ) {
context.logMemInfo(logs);
logs << "shared " << context.getSharedMemorySize() << "\n";
logs << "unique " << context.getUniqueMemorySize() << "\n";
}
// debug info
if ( options.getBoolOption("log_debug_mem",false) ) {
helper.logMemInfo(logs);
}
// log CPP
if (options.getBoolOption("log_cpp")) {
aotCpp(context,logs);
registerAotCpp(logs,context);
}
if ( !options.getBoolOption("rtti",policies.rtti) ) {
context.thisProgram = nullptr;
}
context.debugger = getDebugger();
isSimulating = false;
for ( int i=0; i!=context.totalFunctions; ++i ) {
Function *func = indexToFunction[i];
for (auto &ann : func->annotations) {
if (ann->annotation->rtti_isFunctionAnnotation()) {
auto fann = static_pointer_cast<FunctionAnnotation>(ann->annotation);
fann->complete(&context);
}
}
}
if ( options.getBoolOption("log_total_compile_time",false) ) {
auto dt = get_time_usec(time0) / 1000000.;
logs << "simulate (including init script) took " << dt << "\n";
}
return errors.size() == 0;
}
uint64_t Program::getInitSemanticHashWithDep( uint64_t initHash ) const {
vector<const Variable *> globs;
globs.reserve(totalVariables);
for (auto & pm : library.modules) {
pm->globals.foreach([&](auto var){
if (var->used) {
globs.push_back(var.get());
}
});
}
uint64_t res = getVariableListAotHash(globs, initHash);
// add init functions to dependencies
const uint64_t fnv_prime = 1099511628211ul;
for (auto& pm : library.modules) {
pm->functions.foreach([&](auto pfun){
if (pfun->index < 0 || !pfun->used || !pfun->init)
return;
res = (res ^ pfun->aotHash) * fnv_prime;
});
}
return res;
}
void Program::linkCppAot ( Context & context, AotLibrary & aotLib, TextWriter & logs ) {
bool logIt = options.getBoolOption("log_aot",false);
// make list of functions
vector<Function *> fnn; fnn.reserve(totalFunctions);
das_hash_map<int,Function *> indexToFunction;
for (auto & pm : library.modules) {
pm->functions.foreach([&](auto pfun){
if (pfun->index < 0 || !pfun->used)
return;
fnn.push_back(pfun.get());
indexToFunction[pfun->index] = pfun.get();
});
}
for ( int fni=0; fni!=context.totalFunctions; ++fni ) {
if ( !fnn[fni]->noAot ) {
SimFunction & fn = context.functions[fni];
fnn[fni]->hash = getFunctionHash(fnn[fni], fn.code, &context);
}
}
for ( int fni=0; fni!=context.totalFunctions; ++fni ) {
if ( !fnn[fni]->noAot ) {
SimFunction & fn = context.functions[fni];
uint64_t semHash = fnn[fni]->aotHash = getFunctionAotHash(fnn[fni]);
auto it = aotLib.find(semHash);
if ( it != aotLib.end() ) {
fn.code = (it->second)(context);
fn.aot = true;
if ( logIt ) logs << fn.mangledName << " AOT=0x" << HEX << semHash << DEC << "\n";
auto fcb = (SimNode_CallBase *) fn.code;
fn.aotFunction = fcb->aotFunction;
} else {
if ( logIt ) logs << "NOT FOUND " << fn.mangledName << " AOT=0x" << HEX << semHash << DEC << "\n";
TextWriter tp;
tp << "semantic hash is " << HEX << semHash << DEC << "\n";
printSimFunction(tp, &context, indexToFunction[fni], fn.code, true);
linkError(string(fn.mangledName), tp.str() );
}
}
}
}
}
| 47.877176 | 149 | 0.530391 | [
"vector"
] |
f599bb219782b4265d6462c03aef3fcedd4c28ae | 34,182 | cpp | C++ | apps/mysql-5.1.65/storage/ndb/tools/restore/Restore.cpp | vusec/firestarter | 2048c1f731b8f3c5570a920757f9d7730d5f716a | [
"Apache-2.0"
] | 3 | 2021-04-29T07:59:16.000Z | 2021-12-10T02:23:05.000Z | apps/mysql-5.1.65/storage/ndb/tools/restore/Restore.cpp | vusec/firestarter | 2048c1f731b8f3c5570a920757f9d7730d5f716a | [
"Apache-2.0"
] | null | null | null | apps/mysql-5.1.65/storage/ndb/tools/restore/Restore.cpp | vusec/firestarter | 2048c1f731b8f3c5570a920757f9d7730d5f716a | [
"Apache-2.0"
] | null | null | null | /* Copyright (C) 2003 MySQL AB
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; version 2 of the License.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "Restore.hpp"
#include <NdbTCP.h>
#include <NdbMem.h>
#include <OutputStream.hpp>
#include <Bitmask.hpp>
#include <AttributeHeader.hpp>
#include <trigger_definitions.h>
#include <SimpleProperties.hpp>
#include <signaldata/DictTabInfo.hpp>
#include <ndb_limits.h>
#include <NdbAutoPtr.hpp>
#include "../../../../sql/ha_ndbcluster_tables.h"
extern NdbRecordPrintFormat g_ndbrecord_print_format;
Uint16 Twiddle16(Uint16 in); // Byte shift 16-bit data
Uint32 Twiddle32(Uint32 in); // Byte shift 32-bit data
Uint64 Twiddle64(Uint64 in); // Byte shift 64-bit data
bool
BackupFile::Twiddle(const AttributeDesc* attr_desc, AttributeData* attr_data, Uint32 arraySize){
Uint32 i;
if(m_hostByteOrder)
return true;
if(arraySize == 0){
arraySize = attr_desc->arraySize;
}
switch(attr_desc->size){
case 8:
return true;
case 16:
for(i = 0; i<arraySize; i++){
attr_data->u_int16_value[i] = Twiddle16(attr_data->u_int16_value[i]);
}
return true;
case 32:
for(i = 0; i<arraySize; i++){
attr_data->u_int32_value[i] = Twiddle32(attr_data->u_int32_value[i]);
}
return true;
case 64:
for(i = 0; i<arraySize; i++){
// allow unaligned
char* p = (char*)&attr_data->u_int64_value[i];
Uint64 x;
memcpy(&x, p, sizeof(Uint64));
x = Twiddle64(x);
memcpy(p, &x, sizeof(Uint64));
}
return true;
default:
return false;
} // switch
} // Twiddle
FilteredNdbOut err(* new FileOutputStream(stderr), 0, 0);
FilteredNdbOut info(* new FileOutputStream(stdout), 1, 1);
FilteredNdbOut debug(* new FileOutputStream(stdout), 2, 0);
// To decide in what byte order data is
const Uint32 magicByteOrder = 0x12345678;
const Uint32 swappedMagicByteOrder = 0x78563412;
RestoreMetaData::RestoreMetaData(const char* path, Uint32 nodeId, Uint32 bNo) {
debug << "RestoreMetaData constructor" << endl;
setCtlFile(nodeId, bNo, path);
}
RestoreMetaData::~RestoreMetaData(){
for(Uint32 i= 0; i < allTables.size(); i++)
{
TableS *table = allTables[i];
for(Uint32 j= 0; j < table->m_fragmentInfo.size(); j++)
delete table->m_fragmentInfo[j];
delete table;
}
allTables.clear();
}
TableS *
RestoreMetaData::getTable(Uint32 tableId) const {
for(Uint32 i= 0; i < allTables.size(); i++)
if(allTables[i]->getTableId() == tableId)
return allTables[i];
return NULL;
}
Uint32
RestoreMetaData::getStopGCP() const {
return m_stopGCP;
}
int
RestoreMetaData::loadContent()
{
Uint32 noOfTables = readMetaTableList();
if(noOfTables == 0) {
return 1;
}
for(Uint32 i = 0; i<noOfTables; i++){
if(!readMetaTableDesc()){
return 0;
}
}
if (! markSysTables())
return 0;
if(!readGCPEntry())
return 0;
if(!readFragmentInfo())
return 0;
return 1;
}
Uint32
RestoreMetaData::readMetaTableList() {
Uint32 sectionInfo[2];
if (buffer_read(§ionInfo, sizeof(sectionInfo), 1) != 1){
err << "readMetaTableList read header error" << endl;
return 0;
}
sectionInfo[0] = ntohl(sectionInfo[0]);
sectionInfo[1] = ntohl(sectionInfo[1]);
const Uint32 tabCount = sectionInfo[1] - 2;
void *tmp;
if (buffer_get_ptr(&tmp, 4, tabCount) != tabCount){
err << "readMetaTableList read tabCount error" << endl;
return 0;
}
return tabCount;
}
bool
RestoreMetaData::readMetaTableDesc() {
Uint32 sectionInfo[3];
// Read section header
Uint32 sz = sizeof(sectionInfo) >> 2;
if (m_fileHeader.NdbVersion < NDBD_ROWID_VERSION)
{
sz = 2;
sectionInfo[2] = htonl(DictTabInfo::UserTable);
}
if (buffer_read(§ionInfo, 4*sz, 1) != 1){
err << "readMetaTableDesc read header error" << endl;
return false;
} // if
sectionInfo[0] = ntohl(sectionInfo[0]);
sectionInfo[1] = ntohl(sectionInfo[1]);
sectionInfo[2] = ntohl(sectionInfo[2]);
assert(sectionInfo[0] == BackupFormat::TABLE_DESCRIPTION);
// Read dictTabInfo buffer
const Uint32 len = (sectionInfo[1] - sz);
void *ptr;
if (buffer_get_ptr(&ptr, 4, len) != len){
err << "readMetaTableDesc read error" << endl;
return false;
} // if
int errcode = 0;
DictObject obj = { sectionInfo[2], 0 };
switch(obj.m_objType){
case DictTabInfo::SystemTable:
case DictTabInfo::UserTable:
case DictTabInfo::UniqueHashIndex:
case DictTabInfo::OrderedIndex:
return parseTableDescriptor((Uint32*)ptr, len);
break;
case DictTabInfo::Tablespace:
{
NdbDictionary::Tablespace * dst = new NdbDictionary::Tablespace;
errcode =
NdbDictInterface::parseFilegroupInfo(NdbTablespaceImpl::getImpl(* dst),
(Uint32*)ptr, len);
if (errcode)
delete dst;
obj.m_objPtr = dst;
debug << hex << obj.m_objPtr << " "
<< dec << dst->getObjectId() << " " << dst->getName() << endl;
break;
}
case DictTabInfo::LogfileGroup:
{
NdbDictionary::LogfileGroup * dst = new NdbDictionary::LogfileGroup;
errcode =
NdbDictInterface::parseFilegroupInfo(NdbLogfileGroupImpl::getImpl(* dst),
(Uint32*)ptr, len);
if (errcode)
delete dst;
obj.m_objPtr = dst;
debug << hex << obj.m_objPtr << " "
<< dec << dst->getObjectId() << " " << dst->getName() << endl;
break;
}
case DictTabInfo::Datafile:
{
NdbDictionary::Datafile * dst = new NdbDictionary::Datafile;
errcode =
NdbDictInterface::parseFileInfo(NdbDatafileImpl::getImpl(* dst),
(Uint32*)ptr, len);
if (errcode)
delete dst;
obj.m_objPtr = dst;
debug << hex << obj.m_objPtr << " "
<< dec << dst->getObjectId() << " " << dst->getPath() << endl;
break;
}
case DictTabInfo::Undofile:
{
NdbDictionary::Undofile * dst = new NdbDictionary::Undofile;
errcode =
NdbDictInterface::parseFileInfo(NdbUndofileImpl::getImpl(* dst),
(Uint32*)ptr, len);
if (errcode)
delete dst;
obj.m_objPtr = dst;
debug << hex << obj.m_objPtr << " "
<< dec << dst->getObjectId() << " " << dst->getPath() << endl;
break;
}
default:
err << "Unsupported table type!! " << sectionInfo[2] << endl;
return false;
}
if (errcode)
{
err << "Unable to parse dict info..."
<< sectionInfo[2] << " " << errcode << endl;
return false;
}
/**
* DD objects need to be sorted...
*/
for(Uint32 i = 0; i<m_objects.size(); i++)
{
switch(sectionInfo[2]){
case DictTabInfo::Tablespace:
if (DictTabInfo::isFile(m_objects[i].m_objType))
{
m_objects.push(obj, i);
goto end;
}
break;
case DictTabInfo::LogfileGroup:
{
if (DictTabInfo::isFile(m_objects[i].m_objType) ||
m_objects[i].m_objType == DictTabInfo::Tablespace)
{
m_objects.push(obj, i);
goto end;
}
break;
}
default:
m_objects.push_back(obj);
goto end;
}
}
m_objects.push_back(obj);
end:
return true;
}
bool
RestoreMetaData::markSysTables()
{
Uint32 i;
for (i = 0; i < getNoOfTables(); i++) {
TableS* table = allTables[i];
table->m_local_id = i;
const char* tableName = table->getTableName();
if ( // XXX should use type
strcmp(tableName, "SYSTAB_0") == 0 ||
strcmp(tableName, "NDB$EVENTS_0") == 0 ||
strcmp(tableName, "sys/def/SYSTAB_0") == 0 ||
strcmp(tableName, "sys/def/NDB$EVENTS_0") == 0 ||
/*
The following is for old MySQL versions,
before we changed the database name of the tables from
"cluster_replication" -> "cluster" -> "mysql"
*/
strcmp(tableName, "cluster_replication/def/" OLD_NDB_APPLY_TABLE) == 0 ||
strcmp(tableName, OLD_NDB_REP_DB "/def/" OLD_NDB_APPLY_TABLE) == 0 ||
strcmp(tableName, OLD_NDB_REP_DB "/def/" OLD_NDB_SCHEMA_TABLE) == 0 ||
strcmp(tableName, NDB_REP_DB "/def/" NDB_APPLY_TABLE) == 0 ||
strcmp(tableName, NDB_REP_DB "/def/" NDB_SCHEMA_TABLE)== 0 )
table->isSysTable = true;
}
for (i = 0; i < getNoOfTables(); i++) {
TableS* blobTable = allTables[i];
const char* blobTableName = blobTable->getTableName();
// yet another match blob
int cnt, id1, id2;
char buf[256];
cnt = sscanf(blobTableName, "%[^/]/%[^/]/NDB$BLOB_%d_%d",
buf, buf, &id1, &id2);
if (cnt == 4) {
Uint32 j;
for (j = 0; j < getNoOfTables(); j++) {
TableS* table = allTables[j];
if (table->getTableId() == (Uint32) id1) {
if (table->isSysTable)
blobTable->isSysTable = true;
blobTable->m_main_table = table;
break;
}
}
if (j == getNoOfTables()) {
err << "Restore: Bad primary table id in " << blobTableName << endl;
return false;
}
}
}
return true;
}
bool
RestoreMetaData::readGCPEntry() {
Uint32 data[4];
BackupFormat::CtlFile::GCPEntry * dst =
(BackupFormat::CtlFile::GCPEntry *)&data[0];
if(buffer_read(dst, 4, 4) != 4){
err << "readGCPEntry read error" << endl;
return false;
}
dst->SectionType = ntohl(dst->SectionType);
dst->SectionLength = ntohl(dst->SectionLength);
if(dst->SectionType != BackupFormat::GCP_ENTRY){
err << "readGCPEntry invalid format" << endl;
return false;
}
dst->StartGCP = ntohl(dst->StartGCP);
dst->StopGCP = ntohl(dst->StopGCP);
m_startGCP = dst->StartGCP;
m_stopGCP = dst->StopGCP;
return true;
}
bool
RestoreMetaData::readFragmentInfo()
{
BackupFormat::CtlFile::FragmentInfo fragInfo;
TableS * table = 0;
Uint32 tableId = RNIL;
while (buffer_read(&fragInfo, 4, 2) == 2)
{
fragInfo.SectionType = ntohl(fragInfo.SectionType);
fragInfo.SectionLength = ntohl(fragInfo.SectionLength);
if (fragInfo.SectionType != BackupFormat::FRAGMENT_INFO)
{
err << "readFragmentInfo invalid section type: " <<
fragInfo.SectionType << endl;
return false;
}
if (buffer_read(&fragInfo.TableId, (fragInfo.SectionLength-2)*4, 1) != 1)
{
err << "readFragmentInfo invalid section length: " <<
fragInfo.SectionLength << endl;
return false;
}
fragInfo.TableId = ntohl(fragInfo.TableId);
if (fragInfo.TableId != tableId)
{
tableId = fragInfo.TableId;
table = getTable(tableId);
}
FragmentInfo * tmp = new FragmentInfo;
tmp->fragmentNo = ntohl(fragInfo.FragmentNo);
tmp->noOfRecords = ntohl(fragInfo.NoOfRecordsLow) +
(((Uint64)ntohl(fragInfo.NoOfRecordsHigh)) << 32);
tmp->filePosLow = ntohl(fragInfo.FilePosLow);
tmp->filePosHigh = ntohl(fragInfo.FilePosHigh);
table->m_fragmentInfo.push_back(tmp);
table->m_noOfRecords += tmp->noOfRecords;
}
return true;
}
TableS::TableS(Uint32 version, NdbTableImpl* tableImpl)
: m_dictTable(tableImpl)
{
m_dictTable = tableImpl;
m_noOfNullable = m_nullBitmaskSize = 0;
m_auto_val_id= ~(Uint32)0;
m_max_auto_val= 0;
m_noOfRecords= 0;
backupVersion = version;
isSysTable = false;
m_main_table = NULL;
for (int i = 0; i < tableImpl->getNoOfColumns(); i++)
createAttr(tableImpl->getColumn(i));
}
TableS::~TableS()
{
for (Uint32 i= 0; i < allAttributesDesc.size(); i++)
delete allAttributesDesc[i];
}
// Parse dictTabInfo buffer and pushback to to vector storage
bool
RestoreMetaData::parseTableDescriptor(const Uint32 * data, Uint32 len)
{
NdbTableImpl* tableImpl = 0;
int ret = NdbDictInterface::parseTableInfo(&tableImpl, data, len, false,
m_fileHeader.NdbVersion);
if (ret != 0) {
err << "parseTableInfo " << " failed" << endl;
return false;
}
if(tableImpl == 0)
return false;
debug << "parseTableInfo " << tableImpl->getName() << " done" << endl;
TableS * table = new TableS(m_fileHeader.NdbVersion, tableImpl);
if(table == NULL) {
return false;
}
debug << "Parsed table id " << table->getTableId() << endl;
debug << "Parsed table #attr " << table->getNoOfAttributes() << endl;
debug << "Parsed table schema version not used " << endl;
debug << "Pushing table " << table->getTableName() << endl;
debug << " with " << table->getNoOfAttributes() << " attributes" << endl;
allTables.push_back(table);
return true;
}
// Constructor
RestoreDataIterator::RestoreDataIterator(const RestoreMetaData & md, void (* _free_data_callback)())
: BackupFile(_free_data_callback), m_metaData(md)
{
debug << "RestoreDataIterator constructor" << endl;
setDataFile(md, 0);
}
TupleS & TupleS::operator=(const TupleS& tuple)
{
prepareRecord(*tuple.m_currentTable);
if (allAttrData)
memcpy(allAttrData, tuple.allAttrData, getNoOfAttributes()*sizeof(AttributeData));
return *this;
}
int TupleS::getNoOfAttributes() const {
if (m_currentTable == 0)
return 0;
return m_currentTable->getNoOfAttributes();
}
TableS * TupleS::getTable() const {
return m_currentTable;
}
const AttributeDesc * TupleS::getDesc(int i) const {
return m_currentTable->allAttributesDesc[i];
}
AttributeData * TupleS::getData(int i) const{
return &(allAttrData[i]);
}
bool
TupleS::prepareRecord(TableS & tab){
if (allAttrData) {
if (getNoOfAttributes() == tab.getNoOfAttributes())
{
m_currentTable = &tab;
return true;
}
delete [] allAttrData;
m_currentTable= 0;
}
allAttrData = new AttributeData[tab.getNoOfAttributes()];
if (allAttrData == 0)
return false;
m_currentTable = &tab;
return true;
}
int
RestoreDataIterator::readTupleData(Uint32 *buf_ptr, Uint32 *ptr,
Uint32 dataLength)
{
while (ptr + 2 < buf_ptr + dataLength)
{
typedef BackupFormat::DataFile::VariableData VarData;
VarData * data = (VarData *)ptr;
Uint32 sz = ntohl(data->Sz);
Uint32 attrId = ntohl(data->Id); // column_no
AttributeData * attr_data = m_tuple.getData(attrId);
const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);
// just a reminder - remove when backwards compat implemented
if (m_currentTable->backupVersion < MAKE_VERSION(5,1,3) &&
attr_desc->m_column->getNullable())
{
const Uint32 ind = attr_desc->m_nullBitIndex;
if(BitmaskImpl::get(m_currentTable->m_nullBitmaskSize,
buf_ptr,ind))
{
attr_data->null = true;
attr_data->void_value = NULL;
continue;
}
}
if (m_currentTable->backupVersion < MAKE_VERSION(5,1,3))
{
sz *= 4;
}
attr_data->null = false;
attr_data->void_value = &data->Data[0];
attr_data->size = sz;
//if (m_currentTable->getTableId() >= 2) { ndbout << "var off=" << ptr-buf_ptr << " attrId=" << attrId << endl; }
/**
* Compute array size
*/
const Uint32 arraySize = sz / (attr_desc->size / 8);
assert(arraySize <= attr_desc->arraySize);
//convert the length of blob(v1) and text(v1)
if(!m_hostByteOrder
&& (attr_desc->m_column->getType() == NdbDictionary::Column::Blob
|| attr_desc->m_column->getType() == NdbDictionary::Column::Text)
&& attr_desc->m_column->getArrayType() == NdbDictionary::Column::ArrayTypeFixed)
{
char* p = (char*)&attr_data->u_int64_value[0];
Uint64 x;
memcpy(&x, p, sizeof(Uint64));
x = Twiddle64(x);
memcpy(p, &x, sizeof(Uint64));
}
//convert datetime type
if(!m_hostByteOrder
&& attr_desc->m_column->getType() == NdbDictionary::Column::Datetime)
{
char* p = (char*)&attr_data->u_int64_value[0];
Uint64 x;
memcpy(&x, p, sizeof(Uint64));
x = Twiddle64(x);
memcpy(p, &x, sizeof(Uint64));
}
if(!Twiddle(attr_desc, attr_data, attr_desc->arraySize))
{
return -1;
}
ptr += ((sz + 3) >> 2) + 2;
}
assert(ptr == buf_ptr + dataLength);
return 0;
}
const TupleS *
RestoreDataIterator::getNextTuple(int & res)
{
Uint32 dataLength = 0;
// Read record length
if (buffer_read(&dataLength, sizeof(dataLength), 1) != 1){
err << "getNextTuple:Error reading length of data part" << endl;
res = -1;
return NULL;
} // if
// Convert length from network byte order
dataLength = ntohl(dataLength);
const Uint32 dataLenBytes = 4 * dataLength;
if (dataLength == 0) {
// Zero length for last tuple
// End of this data fragment
debug << "End of fragment" << endl;
res = 0;
return NULL;
} // if
// Read tuple data
void *_buf_ptr;
if (buffer_get_ptr(&_buf_ptr, 1, dataLenBytes) != dataLenBytes) {
err << "getNextTuple:Read error: " << endl;
res = -1;
return NULL;
}
//if (m_currentTable->getTableId() >= 2) { for (uint ii=0; ii<dataLenBytes; ii+=4) ndbout << "*" << hex << *(Uint32*)( (char*)_buf_ptr+ii ); ndbout << endl; }
Uint32 *buf_ptr = (Uint32*)_buf_ptr, *ptr = buf_ptr;
ptr += m_currentTable->m_nullBitmaskSize;
Uint32 i;
for(i= 0; i < m_currentTable->m_fixedKeys.size(); i++){
assert(ptr < buf_ptr + dataLength);
const Uint32 attrId = m_currentTable->m_fixedKeys[i]->attrId;
AttributeData * attr_data = m_tuple.getData(attrId);
const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);
const Uint32 sz = attr_desc->getSizeInWords();
attr_data->null = false;
attr_data->void_value = ptr;
attr_data->size = 4*sz;
if(!Twiddle(attr_desc, attr_data))
{
res = -1;
return NULL;
}
ptr += sz;
}
for(i = 0; i < m_currentTable->m_fixedAttribs.size(); i++){
assert(ptr < buf_ptr + dataLength);
const Uint32 attrId = m_currentTable->m_fixedAttribs[i]->attrId;
AttributeData * attr_data = m_tuple.getData(attrId);
const AttributeDesc * attr_desc = m_tuple.getDesc(attrId);
const Uint32 sz = attr_desc->getSizeInWords();
attr_data->null = false;
attr_data->void_value = ptr;
attr_data->size = 4*sz;
//if (m_currentTable->getTableId() >= 2) { ndbout << "fix i=" << i << " off=" << ptr-buf_ptr << " attrId=" << attrId << endl; }
if(!m_hostByteOrder
&& attr_desc->m_column->getType() == NdbDictionary::Column::Timestamp)
attr_data->u_int32_value[0] = Twiddle32(attr_data->u_int32_value[0]);
if(!Twiddle(attr_desc, attr_data))
{
res = -1;
return NULL;
}
ptr += sz;
}
// init to NULL
for(i = 0; i < m_currentTable->m_variableAttribs.size(); i++){
const Uint32 attrId = m_currentTable->m_variableAttribs[i]->attrId;
AttributeData * attr_data = m_tuple.getData(attrId);
attr_data->null = true;
attr_data->void_value = NULL;
}
if ((res = readTupleData(buf_ptr, ptr, dataLength)))
return NULL;
m_count ++;
res = 0;
return &m_tuple;
} // RestoreDataIterator::getNextTuple
BackupFile::BackupFile(void (* _free_data_callback)())
: free_data_callback(_free_data_callback)
{
m_file = 0;
m_path[0] = 0;
m_fileName[0] = 0;
m_buffer_sz = 64*1024;
m_buffer = malloc(m_buffer_sz);
m_buffer_ptr = m_buffer;
m_buffer_data_left = 0;
}
BackupFile::~BackupFile(){
if(m_file != 0)
fclose(m_file);
if(m_buffer != 0)
free(m_buffer);
}
bool
BackupFile::openFile(){
if(m_file != NULL){
fclose(m_file);
m_file = 0;
}
m_file = fopen(m_fileName, "r");
return m_file != 0;
}
Uint32 BackupFile::buffer_get_ptr_ahead(void **p_buf_ptr, Uint32 size, Uint32 nmemb)
{
Uint32 sz = size*nmemb;
if (sz > m_buffer_data_left) {
if (free_data_callback)
(*free_data_callback)();
memcpy(m_buffer, m_buffer_ptr, m_buffer_data_left);
size_t r = fread(((char *)m_buffer) + m_buffer_data_left, 1, m_buffer_sz - m_buffer_data_left, m_file);
m_buffer_data_left += r;
m_buffer_ptr = m_buffer;
if (sz > m_buffer_data_left)
sz = size * (m_buffer_data_left / size);
}
*p_buf_ptr = m_buffer_ptr;
return sz/size;
}
Uint32 BackupFile::buffer_get_ptr(void **p_buf_ptr, Uint32 size, Uint32 nmemb)
{
Uint32 r = buffer_get_ptr_ahead(p_buf_ptr, size, nmemb);
m_buffer_ptr = ((char*)m_buffer_ptr)+(r*size);
m_buffer_data_left -= (r*size);
return r;
}
Uint32 BackupFile::buffer_read_ahead(void *ptr, Uint32 size, Uint32 nmemb)
{
void *buf_ptr;
Uint32 r = buffer_get_ptr_ahead(&buf_ptr, size, nmemb);
memcpy(ptr, buf_ptr, r*size);
return r;
}
Uint32 BackupFile::buffer_read(void *ptr, Uint32 size, Uint32 nmemb)
{
void *buf_ptr;
Uint32 r = buffer_get_ptr(&buf_ptr, size, nmemb);
memcpy(ptr, buf_ptr, r*size);
return r;
}
void
BackupFile::setCtlFile(Uint32 nodeId, Uint32 backupId, const char * path){
m_nodeId = nodeId;
m_expectedFileHeader.BackupId = backupId;
m_expectedFileHeader.FileType = BackupFormat::CTL_FILE;
char name[PATH_MAX]; const Uint32 sz = sizeof(name);
BaseString::snprintf(name, sz, "BACKUP-%d.%d.ctl", backupId, nodeId);
setName(path, name);
}
void
BackupFile::setDataFile(const BackupFile & bf, Uint32 no){
m_nodeId = bf.m_nodeId;
m_expectedFileHeader = bf.m_fileHeader;
m_expectedFileHeader.FileType = BackupFormat::DATA_FILE;
char name[PATH_MAX]; const Uint32 sz = sizeof(name);
BaseString::snprintf(name, sz, "BACKUP-%d-%d.%d.Data",
m_expectedFileHeader.BackupId, no, m_nodeId);
setName(bf.m_path, name);
}
void
BackupFile::setLogFile(const BackupFile & bf, Uint32 no){
m_nodeId = bf.m_nodeId;
m_expectedFileHeader = bf.m_fileHeader;
m_expectedFileHeader.FileType = BackupFormat::LOG_FILE;
char name[PATH_MAX]; const Uint32 sz = sizeof(name);
BaseString::snprintf(name, sz, "BACKUP-%d.%d.log",
m_expectedFileHeader.BackupId, m_nodeId);
setName(bf.m_path, name);
}
void
BackupFile::setName(const char * p, const char * n){
const Uint32 sz = sizeof(m_path);
if(p != 0 && strlen(p) > 0){
if(p[strlen(p)-1] == '/'){
BaseString::snprintf(m_path, sz, "%s", p);
} else {
BaseString::snprintf(m_path, sz, "%s%s", p, "/");
}
} else {
m_path[0] = 0;
}
BaseString::snprintf(m_fileName, sizeof(m_fileName), "%s%s", m_path, n);
debug << "Filename = " << m_fileName << endl;
}
bool
BackupFile::readHeader(){
if(!openFile()){
return false;
}
if(buffer_read(&m_fileHeader, sizeof(m_fileHeader), 1) != 1){
err << "readDataFileHeader: Error reading header" << endl;
return false;
}
// Convert from network to host byte order for platform compatibility
m_fileHeader.NdbVersion = ntohl(m_fileHeader.NdbVersion);
m_fileHeader.SectionType = ntohl(m_fileHeader.SectionType);
m_fileHeader.SectionLength = ntohl(m_fileHeader.SectionLength);
m_fileHeader.FileType = ntohl(m_fileHeader.FileType);
m_fileHeader.BackupId = ntohl(m_fileHeader.BackupId);
m_fileHeader.BackupKey_0 = ntohl(m_fileHeader.BackupKey_0);
m_fileHeader.BackupKey_1 = ntohl(m_fileHeader.BackupKey_1);
debug << "FileHeader: " << m_fileHeader.Magic << " " <<
m_fileHeader.NdbVersion << " " <<
m_fileHeader.SectionType << " " <<
m_fileHeader.SectionLength << " " <<
m_fileHeader.FileType << " " <<
m_fileHeader.BackupId << " " <<
m_fileHeader.BackupKey_0 << " " <<
m_fileHeader.BackupKey_1 << " " <<
m_fileHeader.ByteOrder << endl;
debug << "ByteOrder is " << m_fileHeader.ByteOrder << endl;
debug << "magicByteOrder is " << magicByteOrder << endl;
if (m_fileHeader.FileType != m_expectedFileHeader.FileType){
abort();
}
// Check for BackupFormat::FileHeader::ByteOrder if swapping is needed
if (m_fileHeader.ByteOrder == magicByteOrder) {
m_hostByteOrder = true;
} else if (m_fileHeader.ByteOrder == swappedMagicByteOrder){
m_hostByteOrder = false;
} else {
abort();
}
return true;
} // BackupFile::readHeader
bool
BackupFile::validateFooter(){
return true;
}
bool RestoreDataIterator::readFragmentHeader(int & ret, Uint32 *fragmentId)
{
BackupFormat::DataFile::FragmentHeader Header;
debug << "RestoreDataIterator::getNextFragment" << endl;
while (1)
{
/* read first part of header */
if (buffer_read(&Header, 8, 1) != 1)
{
ret = 0;
return false;
} // if
/* skip if EMPTY_ENTRY */
Header.SectionType = ntohl(Header.SectionType);
Header.SectionLength = ntohl(Header.SectionLength);
if (Header.SectionType == BackupFormat::EMPTY_ENTRY)
{
void *tmp;
buffer_get_ptr(&tmp, Header.SectionLength*4-8, 1);
continue;
}
break;
}
/* read rest of header */
if (buffer_read(((char*)&Header)+8, sizeof(Header)-8, 1) != 1)
{
ret = 0;
return false;
}
Header.TableId = ntohl(Header.TableId);
Header.FragmentNo = ntohl(Header.FragmentNo);
Header.ChecksumType = ntohl(Header.ChecksumType);
debug << "FragmentHeader: " << Header.SectionType
<< " " << Header.SectionLength
<< " " << Header.TableId
<< " " << Header.FragmentNo
<< " " << Header.ChecksumType << endl;
m_currentTable = m_metaData.getTable(Header.TableId);
if(m_currentTable == 0){
ret = -1;
return false;
}
if(!m_tuple.prepareRecord(*m_currentTable))
{
ret =-1;
return false;
}
info.setLevel(254);
info << "_____________________________________________________" << endl
<< "Processing data in table: " << m_currentTable->getTableName()
<< "(" << Header.TableId << ") fragment "
<< Header.FragmentNo << endl;
m_count = 0;
ret = 0;
*fragmentId = Header.FragmentNo;
return true;
} // RestoreDataIterator::getNextFragment
bool
RestoreDataIterator::validateFragmentFooter() {
BackupFormat::DataFile::FragmentFooter footer;
if (buffer_read(&footer, sizeof(footer), 1) != 1){
err << "getFragmentFooter:Error reading fragment footer" << endl;
return false;
}
// TODO: Handle footer, nothing yet
footer.SectionType = ntohl(footer.SectionType);
footer.SectionLength = ntohl(footer.SectionLength);
footer.TableId = ntohl(footer.TableId);
footer.FragmentNo = ntohl(footer.FragmentNo);
footer.NoOfRecords = ntohl(footer.NoOfRecords);
footer.Checksum = ntohl(footer.Checksum);
assert(m_count == footer.NoOfRecords);
return true;
} // RestoreDataIterator::getFragmentFooter
AttributeDesc::AttributeDesc(NdbDictionary::Column *c)
: m_column(c)
{
size = 8*NdbColumnImpl::getImpl(* c).m_attrSize;
arraySize = NdbColumnImpl::getImpl(* c).m_arraySize;
}
void TableS::createAttr(NdbDictionary::Column *column)
{
AttributeDesc * d = new AttributeDesc(column);
if(d == NULL) {
ndbout_c("Restore: Failed to allocate memory");
abort();
}
d->attrId = allAttributesDesc.size();
allAttributesDesc.push_back(d);
if (d->m_column->getAutoIncrement())
m_auto_val_id= d->attrId;
if(d->m_column->getPrimaryKey() && backupVersion <= MAKE_VERSION(4,1,7))
{
m_fixedKeys.push_back(d);
return;
}
if (d->m_column->getArrayType() == NDB_ARRAYTYPE_FIXED &&
! d->m_column->getNullable())
{
m_fixedAttribs.push_back(d);
return;
}
// just a reminder - does not solve backwards compat
if (backupVersion < MAKE_VERSION(5,1,3))
{
d->m_nullBitIndex = m_noOfNullable;
m_noOfNullable++;
m_nullBitmaskSize = (m_noOfNullable + 31) / 32;
}
m_variableAttribs.push_back(d);
} // TableS::createAttr
Uint16 Twiddle16(Uint16 in)
{
Uint16 retVal = 0;
retVal = ((in & 0xFF00) >> 8) |
((in & 0x00FF) << 8);
return(retVal);
} // Twiddle16
Uint32 Twiddle32(Uint32 in)
{
Uint32 retVal = 0;
retVal = ((in & 0x000000FF) << 24) |
((in & 0x0000FF00) << 8) |
((in & 0x00FF0000) >> 8) |
((in & 0xFF000000) >> 24);
return(retVal);
} // Twiddle32
Uint64 Twiddle64(Uint64 in)
{
Uint64 retVal = 0;
retVal =
((in & (Uint64)0x00000000000000FFLL) << 56) |
((in & (Uint64)0x000000000000FF00LL) << 40) |
((in & (Uint64)0x0000000000FF0000LL) << 24) |
((in & (Uint64)0x00000000FF000000LL) << 8) |
((in & (Uint64)0x000000FF00000000LL) >> 8) |
((in & (Uint64)0x0000FF0000000000LL) >> 24) |
((in & (Uint64)0x00FF000000000000LL) >> 40) |
((in & (Uint64)0xFF00000000000000LL) >> 56);
return(retVal);
} // Twiddle64
RestoreLogIterator::RestoreLogIterator(const RestoreMetaData & md)
: m_metaData(md)
{
debug << "RestoreLog constructor" << endl;
setLogFile(md, 0);
m_count = 0;
m_last_gci = 0;
}
const LogEntry *
RestoreLogIterator::getNextLogEntry(int & res) {
// Read record length
const Uint32 stopGCP = m_metaData.getStopGCP();
Uint32 tableId;
Uint32 triggerEvent;
Uint32 frag_id;
Uint32 *attr_data;
Uint32 attr_data_len;
do {
Uint32 len;
Uint32 *logEntryPtr;
if (buffer_read_ahead(&len, sizeof(Uint32), 1) != 1){
res= -1;
return 0;
}
len= ntohl(len);
Uint32 data_len = sizeof(Uint32) + len*4;
if (buffer_get_ptr((void **)(&logEntryPtr), 1, data_len) != data_len) {
res= -2;
return 0;
}
if(len == 0){
res= 0;
return 0;
}
if (unlikely(m_metaData.getFileHeader().NdbVersion < NDBD_FRAGID_VERSION))
{
/*
FragId was introduced in LogEntry in version
5.1.6
We set FragId to 0 in older versions (these versions
do not support restore of user defined partitioned
tables.
*/
typedef BackupFormat::LogFile::LogEntry_no_fragid LogE_no_fragid;
LogE_no_fragid * logE_no_fragid= (LogE_no_fragid *)logEntryPtr;
tableId= ntohl(logE_no_fragid->TableId);
triggerEvent= ntohl(logE_no_fragid->TriggerEvent);
frag_id= 0;
attr_data= &logE_no_fragid->Data[0];
attr_data_len= len - ((offsetof(LogE_no_fragid, Data) >> 2) - 1);
}
else /* normal case */
{
typedef BackupFormat::LogFile::LogEntry LogE;
LogE * logE= (LogE *)logEntryPtr;
tableId= ntohl(logE->TableId);
triggerEvent= ntohl(logE->TriggerEvent);
frag_id= ntohl(logE->FragId);
attr_data= &logE->Data[0];
attr_data_len= len - ((offsetof(LogE, Data) >> 2) - 1);
}
const bool hasGcp= (triggerEvent & 0x10000) != 0;
triggerEvent &= 0xFFFF;
if(hasGcp){
// last attr_data is gci info
attr_data_len--;
m_last_gci = ntohl(*(attr_data + attr_data_len));
}
} while(m_last_gci > stopGCP + 1);
m_logEntry.m_table = m_metaData.getTable(tableId);
switch(triggerEvent){
case TriggerEvent::TE_INSERT:
m_logEntry.m_type = LogEntry::LE_INSERT;
break;
case TriggerEvent::TE_UPDATE:
m_logEntry.m_type = LogEntry::LE_UPDATE;
break;
case TriggerEvent::TE_DELETE:
m_logEntry.m_type = LogEntry::LE_DELETE;
break;
default:
res = -1;
return NULL;
}
const TableS * tab = m_logEntry.m_table;
m_logEntry.clear();
AttributeHeader * ah = (AttributeHeader *)attr_data;
AttributeHeader *end = (AttributeHeader *)(attr_data + attr_data_len);
AttributeS * attr;
m_logEntry.m_frag_id = frag_id;
while(ah < end){
attr= m_logEntry.add_attr();
if(attr == NULL) {
ndbout_c("Restore: Failed to allocate memory");
res = -1;
return 0;
}
if(unlikely(!m_hostByteOrder))
*(Uint32*)ah = Twiddle32(*(Uint32*)ah);
attr->Desc = (* tab)[ah->getAttributeId()];
assert(attr->Desc != 0);
const Uint32 sz = ah->getDataSize();
if(sz == 0){
attr->Data.null = true;
attr->Data.void_value = NULL;
} else {
attr->Data.null = false;
attr->Data.void_value = ah->getDataPtr();
}
Twiddle(attr->Desc, &(attr->Data));
ah = ah->getNext();
}
m_count ++;
res = 0;
return &m_logEntry;
}
NdbOut &
operator<<(NdbOut& ndbout, const AttributeS& attr){
const AttributeData & data = attr.Data;
const AttributeDesc & desc = *(attr.Desc);
if (data.null)
{
ndbout << g_ndbrecord_print_format.null_string;
return ndbout;
}
NdbRecAttr tmprec(0);
tmprec.setup(desc.m_column, 0);
tmprec.receive_data((Uint32*)data.void_value, data.size);
ndbrecattr_print_formatted(ndbout, tmprec, g_ndbrecord_print_format);
return ndbout;
}
// Print tuple data
NdbOut&
operator<<(NdbOut& ndbout, const TupleS& tuple)
{
for (int i = 0; i < tuple.getNoOfAttributes(); i++)
{
if (i > 0)
ndbout << g_ndbrecord_print_format.fields_terminated_by;
AttributeData * attr_data = tuple.getData(i);
const AttributeDesc * attr_desc = tuple.getDesc(i);
const AttributeS attr = {attr_desc, *attr_data};
debug << i << " " << attr_desc->m_column->getName();
ndbout << attr;
} // for
return ndbout;
}
// Print tuple data
NdbOut&
operator<<(NdbOut& ndbout, const LogEntry& logE)
{
switch(logE.m_type)
{
case LogEntry::LE_INSERT:
ndbout << "INSERT " << logE.m_table->getTableName() << " ";
break;
case LogEntry::LE_DELETE:
ndbout << "DELETE " << logE.m_table->getTableName() << " ";
break;
case LogEntry::LE_UPDATE:
ndbout << "UPDATE " << logE.m_table->getTableName() << " ";
break;
default:
ndbout << "Unknown log entry type (not insert, delete or update)" ;
}
for (Uint32 i= 0; i < logE.size();i++)
{
const AttributeS * attr = logE[i];
ndbout << attr->Desc->m_column->getName() << "=";
ndbout << (* attr);
if (i < (logE.size() - 1))
ndbout << ", ";
}
return ndbout;
}
#include <NDBT.hpp>
NdbOut &
operator<<(NdbOut& ndbout, const TableS & table){
ndbout << (* (NDBT_Table*)table.m_dictTable) << endl;
return ndbout;
}
template class Vector<TableS*>;
template class Vector<AttributeS*>;
template class Vector<AttributeDesc*>;
template class Vector<FragmentInfo*>;
template class Vector<DictObject>;
| 26.395367 | 160 | 0.64218 | [
"vector"
] |
f59fe1ce7c49e8c9e90360fc492dfad943db3b81 | 12,776 | cc | C++ | src/base/statistics.cc | takekoputa/gem5-sst | af966e28f96fd4670f3e294ff33c16b816c3ca47 | [
"BSD-3-Clause"
] | 1 | 2022-02-17T20:02:57.000Z | 2022-02-17T20:02:57.000Z | src/base/statistics.cc | takekoputa/gem5-sst | af966e28f96fd4670f3e294ff33c16b816c3ca47 | [
"BSD-3-Clause"
] | null | null | null | src/base/statistics.cc | takekoputa/gem5-sst | af966e28f96fd4670f3e294ff33c16b816c3ca47 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019-2020 Arm Limited
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* 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 copyright holders 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.
*/
#include "base/statistics.hh"
#include <fstream>
#include <iomanip>
#include <list>
#include <map>
#include <string>
#include "base/callback.hh"
#include "base/cprintf.hh"
#include "base/debug.hh"
#include "base/hostinfo.hh"
#include "base/logging.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "base/trace.hh"
#include "sim/root.hh"
namespace Stats {
std::string Info::separatorString = "::";
// We wrap these in a function to make sure they're built in time.
std::list<Info *> &
statsList()
{
static std::list<Info *> the_list;
return the_list;
}
MapType &
statsMap()
{
static MapType the_map;
return the_map;
}
void
InfoAccess::setInfo(Group *parent, Info *info)
{
panic_if(statsMap().find(this) != statsMap().end() ||
_info != nullptr,
"shouldn't register stat twice!");
// New-style stats are reachable through the hierarchy and
// shouldn't be added to the global lists.
if (parent) {
_info = info;
return;
}
statsList().push_back(info);
#ifndef NDEBUG
std::pair<MapType::iterator, bool> result =
#endif
statsMap().insert(std::make_pair(this, info));
assert(result.second && "this should never fail");
assert(statsMap().find(this) != statsMap().end());
}
void
InfoAccess::setParams(const StorageParams *params)
{
info()->storageParams = params;
}
void
InfoAccess::setInit()
{
info()->flags.set(init);
}
Info *
InfoAccess::info()
{
if (_info) {
// New-style stats
return _info;
} else {
// Legacy stats
MapType::const_iterator i = statsMap().find(this);
assert(i != statsMap().end());
return (*i).second;
}
}
const Info *
InfoAccess::info() const
{
if (_info) {
// New-style stats
return _info;
} else {
// Legacy stats
MapType::const_iterator i = statsMap().find(this);
assert(i != statsMap().end());
return (*i).second;
}
}
StorageParams::~StorageParams()
{
}
NameMapType &
nameMap()
{
static NameMapType the_map;
return the_map;
}
int Info::id_count = 0;
int debug_break_id = -1;
Info::Info()
: flags(none), precision(-1), prereq(0), storageParams(NULL)
{
id = id_count++;
if (debug_break_id >= 0 and debug_break_id == id)
Debug::breakpoint();
}
Info::~Info()
{
}
bool
validateStatName(const std::string &name)
{
if (name.empty())
return false;
std::vector<std::string> vec;
tokenize(vec, name, '.');
std::vector<std::string>::const_iterator item = vec.begin();
while (item != vec.end()) {
if (item->empty())
return false;
std::string::const_iterator c = item->begin();
// The first character is different
if (!isalpha(*c) && *c != '_')
return false;
// The rest of the characters have different rules.
while (++c != item->end()) {
if (!isalnum(*c) && *c != '_')
return false;
}
++item;
}
return true;
}
void
Info::setName(const std::string &name)
{
setName(nullptr, name);
}
void
Info::setName(const Group *parent, const std::string &name)
{
if (!validateStatName(name))
panic("invalid stat name '%s'", name);
// We only register the stat with the nameMap() if we are using
// old-style stats without a parent group. New-style stats should
// be unique since their names should correspond to a member
// variable.
if (!parent) {
auto p = nameMap().insert(make_pair(name, this));
if (!p.second)
panic("same statistic name used twice! name=%s\n",
name);
}
this->name = name;
}
bool
Info::less(Info *stat1, Info *stat2)
{
const std::string &name1 = stat1->name;
const std::string &name2 = stat2->name;
std::vector<std::string> v1;
std::vector<std::string> v2;
tokenize(v1, name1, '.');
tokenize(v2, name2, '.');
size_type last = std::min(v1.size(), v2.size()) - 1;
for (off_type i = 0; i < last; ++i)
if (v1[i] != v2[i])
return v1[i] < v2[i];
// Special compare for last element.
if (v1[last] == v2[last])
return v1.size() < v2.size();
else
return v1[last] < v2[last];
return false;
}
bool
Info::baseCheck() const
{
if (!(flags & Stats::init)) {
#ifdef DEBUG
cprintf("this is stat number %d\n", id);
#endif
panic("Not all stats have been initialized.\n"
"You may need to add <ParentClass>::regStats() to a"
" new SimObject's regStats() function. Name: %s",
name);
return false;
}
if ((flags & display) && name.empty()) {
panic("all printable stats must be named");
return false;
}
return true;
}
void
Info::enable()
{
}
void
VectorInfo::enable()
{
size_type s = size();
if (subnames.size() < s)
subnames.resize(s);
if (subdescs.size() < s)
subdescs.resize(s);
}
void
VectorDistInfo::enable()
{
size_type s = size();
if (subnames.size() < s)
subnames.resize(s);
if (subdescs.size() < s)
subdescs.resize(s);
}
void
Vector2dInfo::enable()
{
if (subnames.size() < x)
subnames.resize(x);
if (subdescs.size() < x)
subdescs.resize(x);
if (y_subnames.size() < y)
y_subnames.resize(y);
}
void
HistStor::grow_out()
{
int size = cvec.size();
int zero = size / 2; // round down!
int top_half = zero + (size - zero + 1) / 2; // round up!
int bottom_half = (size - zero) / 2; // round down!
// grow down
int low_pair = zero - 1;
for (int i = zero - 1; i >= bottom_half; i--) {
cvec[i] = cvec[low_pair];
if (low_pair - 1 >= 0)
cvec[i] += cvec[low_pair - 1];
low_pair -= 2;
}
assert(low_pair == 0 || low_pair == -1 || low_pair == -2);
for (int i = bottom_half - 1; i >= 0; i--)
cvec[i] = Counter();
// grow up
int high_pair = zero;
for (int i = zero; i < top_half; i++) {
cvec[i] = cvec[high_pair];
if (high_pair + 1 < size)
cvec[i] += cvec[high_pair + 1];
high_pair += 2;
}
assert(high_pair == size || high_pair == size + 1);
for (int i = top_half; i < size; i++)
cvec[i] = Counter();
max_bucket *= 2;
min_bucket *= 2;
bucket_size *= 2;
}
void
HistStor::grow_convert()
{
int size = cvec.size();
int half = (size + 1) / 2; // round up!
//bool even = (size & 1) == 0;
int pair = size - 1;
for (int i = size - 1; i >= half; --i) {
cvec[i] = cvec[pair];
if (pair - 1 >= 0)
cvec[i] += cvec[pair - 1];
pair -= 2;
}
for (int i = half - 1; i >= 0; i--)
cvec[i] = Counter();
min_bucket = -max_bucket;// - (even ? bucket_size : 0);
bucket_size *= 2;
}
void
HistStor::grow_up()
{
int size = cvec.size();
int half = (size + 1) / 2; // round up!
int pair = 0;
for (int i = 0; i < half; i++) {
cvec[i] = cvec[pair];
if (pair + 1 < size)
cvec[i] += cvec[pair + 1];
pair += 2;
}
assert(pair == size || pair == size + 1);
for (int i = half; i < size; i++)
cvec[i] = Counter();
max_bucket *= 2;
bucket_size *= 2;
}
void
HistStor::add(HistStor *hs)
{
int b_size = hs->size();
assert(size() == b_size);
assert(min_bucket == hs->min_bucket);
sum += hs->sum;
logs += hs->logs;
squares += hs->squares;
samples += hs->samples;
while (bucket_size > hs->bucket_size)
hs->grow_up();
while (bucket_size < hs->bucket_size)
grow_up();
for (uint32_t i = 0; i < b_size; i++)
cvec[i] += hs->cvec[i];
}
Formula::Formula(Group *parent, const char *name, const char *desc)
: DataWrapVec<Formula, FormulaInfoProxy>(parent, name, desc)
{
}
Formula::Formula(Group *parent, const char *name, const char *desc,
const Temp &r)
: DataWrapVec<Formula, FormulaInfoProxy>(parent, name, desc)
{
*this = r;
}
const Formula &
Formula::operator=(const Temp &r)
{
assert(!root && "Can't change formulas");
root = r.getNodePtr();
setInit();
assert(size());
return *this;
}
const Formula &
Formula::operator+=(Temp r)
{
if (root)
root = NodePtr(new BinaryNode<std::plus<Result> >(root, r));
else {
root = r.getNodePtr();
setInit();
}
assert(size());
return *this;
}
const Formula &
Formula::operator/=(Temp r)
{
assert (root);
root = NodePtr(new BinaryNode<std::divides<Result> >(root, r));
assert(size());
return *this;
}
void
Formula::result(VResult &vec) const
{
if (root)
vec = root->result();
}
Result
Formula::total() const
{
return root ? root->total() : 0.0;
}
size_type
Formula::size() const
{
if (!root)
return 0;
else
return root->size();
}
void
Formula::reset()
{
}
bool
Formula::zero() const
{
VResult vec;
result(vec);
for (VResult::size_type i = 0; i < vec.size(); ++i)
if (vec[i] != 0.0)
return false;
return true;
}
std::string
Formula::str() const
{
return root ? root->str() : "";
}
Handler resetHandler = NULL;
Handler dumpHandler = NULL;
void
registerHandlers(Handler reset_handler, Handler dump_handler)
{
resetHandler = reset_handler;
dumpHandler = dump_handler;
}
CallbackQueue dumpQueue;
CallbackQueue resetQueue;
void
processResetQueue()
{
resetQueue.process();
}
void
processDumpQueue()
{
dumpQueue.process();
}
void
registerResetCallback(const std::function<void()> &callback)
{
resetQueue.push_back(callback);
}
bool _enabled = false;
bool
enabled()
{
return _enabled;
}
void
enable()
{
if (_enabled)
fatal("Stats are already enabled");
_enabled = true;
}
void
dump()
{
if (dumpHandler)
dumpHandler();
else
fatal("No registered Stats::dump handler");
}
void
reset()
{
if (resetHandler)
resetHandler();
else
fatal("No registered Stats::reset handler");
}
const Info *
resolve(const std::string &name)
{
const auto &it = nameMap().find(name);
if (it != nameMap().cend()) {
return it->second;
} else {
return Root::root()->resolveStat(name);
}
}
void
registerDumpCallback(const std::function<void()> &callback)
{
dumpQueue.push_back(callback);
}
} // namespace Stats
void
debugDumpStats()
{
Stats::dump();
}
| 21.328881 | 73 | 0.603084 | [
"vector"
] |
f5a1f13c1b0f08a273c5d9321a40ac87b33f63f9 | 2,437 | hpp | C++ | libraries/chain/include/graphene/chain/seeder_object.hpp | f3chain/fff | 707bb1f0791206fe8f1ed9d610c1b6efa34d8bab | [
"Apache-2.0"
] | null | null | null | libraries/chain/include/graphene/chain/seeder_object.hpp | f3chain/fff | 707bb1f0791206fe8f1ed9d610c1b6efa34d8bab | [
"Apache-2.0"
] | null | null | null | libraries/chain/include/graphene/chain/seeder_object.hpp | f3chain/fff | 707bb1f0791206fe8f1ed9d610c1b6efa34d8bab | [
"Apache-2.0"
] | null | null | null | /* (c) 2016, 2021 FFF Services. For details refers to LICENSE.txt */
#pragma once
#include <graphene/chain/protocol/asset.hpp>
#include <graphene/db/object.hpp>
#include <graphene/db/generic_index.hpp>
#include <fc/reflect/reflect.hpp>
#include <stdint.h>
namespace graphene { namespace chain {
class seeder_object : public graphene::db::abstract_object<implementation_ids, impl_publisher_object_type, seeder_object>
{
public:
account_id_type seeder;
uint64_t free_space;
asset price;
fc::time_point_sec expiration;
decent::encrypt::DIntegerString pubKey;
std::string ipfs_ID;
// seeding stats used to compute seeder's rating
seeding_statistics_id_type stats;
// seeder's rating
uint32_t rating = 0;
// optional ISO 3166-1 alpha-2 two-letter region code
std::string region_code;
};
struct by_seeder;
struct by_free_space;
struct by_price;
struct by_expiration;
struct by_region;
struct by_rating;
typedef boost::multi_index_container<
seeder_object,
db::mi::indexed_by<
db::object_id_index,
db::mi::ordered_unique<db::mi::tag<by_seeder>,
db::mi::member<seeder_object, account_id_type, &seeder_object::seeder>
>,
db::mi::ordered_non_unique<db::mi::tag<by_free_space>,
db::mi::member<seeder_object, uint64_t, &seeder_object::free_space>
>,
db::mi::ordered_non_unique<db::mi::tag<by_price>,
db::mi::member<seeder_object, asset, &seeder_object::price>
>,
db::mi::ordered_non_unique<db::mi::tag<by_expiration>,
db::mi::member<seeder_object, fc::time_point_sec, &seeder_object::expiration>
>,
db::mi::ordered_non_unique<db::mi::tag<by_region>,
db::mi::member<seeder_object, std::string, &seeder_object::region_code>
>,
db::mi::ordered_non_unique<db::mi::tag<by_rating>,
db::mi::member<seeder_object, uint32_t, &seeder_object::rating>,std::greater<uint32_t>
>
>
>seeder_object_multi_index_type;
typedef graphene::db::generic_index< seeder_object, seeder_object_multi_index_type > seeder_index;
}} // graphene::chain
FC_REFLECT_DERIVED(graphene::chain::seeder_object,
(graphene::db::object),
(seeder)(free_space)(price)(expiration)(pubKey)(ipfs_ID)(stats)(rating)(region_code) )
| 34.814286 | 124 | 0.664752 | [
"object"
] |
f5a2d3b217116fa0cda421ee58d5181f2c6b2bbd | 188,499 | cpp | C++ | tests/IResearch/IResearchViewNodeTest.cpp | JiMu-Bao/arangodb | d41e9b93e558cd65de1f015910655cbaf299fe64 | [
"Apache-2.0"
] | null | null | null | tests/IResearch/IResearchViewNodeTest.cpp | JiMu-Bao/arangodb | d41e9b93e558cd65de1f015910655cbaf299fe64 | [
"Apache-2.0"
] | null | null | null | tests/IResearch/IResearchViewNodeTest.cpp | JiMu-Bao/arangodb | d41e9b93e558cd65de1f015910655cbaf299fe64 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#include "Basics/DownCast.h"
#include "gtest/gtest.h"
#include "analysis/analyzers.hpp"
#include "analysis/token_attributes.hpp"
#include "velocypack/Iterator.h"
#include "IResearch/common.h"
#include "Mocks/IResearchLinkMock.h"
#include "Mocks/LogLevels.h"
#include "Mocks/Servers.h"
#include "Mocks/StorageEngineMock.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/Ast.h"
#include "Aql/Collection.h"
#include "Aql/ExecutionBlockImpl.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/ExecutionPlan.h"
#include "Aql/IResearchViewExecutor.h"
#include "Aql/IResearchViewNode.h"
#include "Aql/NoResultsExecutor.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Aql/Query.h"
#include "Aql/RegisterPlan.h"
#include "Aql/SingleRowFetcher.h"
#include "Basics/VelocyPackHelper.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "IResearch/ApplicationServerHelper.h"
#include "IResearch/IResearchAnalyzerFeature.h"
#include "IResearch/IResearchCommon.h"
#include "IResearch/IResearchFeature.h"
#include "IResearch/IResearchLinkMeta.h"
#include "IResearch/IResearchView.h"
#include "Logger/LogTopic.h"
#include "Logger/Logger.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/FlushFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/SystemDatabaseFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "Sharding/ShardingFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "Transaction/StandaloneContext.h"
#include "Utils/OperationOptions.h"
#include "Utils/SingleCollectionTransaction.h"
#include "V8Server/V8DealerFeature.h"
#include "VocBase/LogicalCollection.h"
#include "VocBase/LogicalView.h"
#include "VocBase/ManagedDocumentResult.h"
#if USE_ENTERPRISE
#include "Enterprise/Ldap/LdapFeature.h"
#endif
namespace {
class IResearchViewNodeTest
: public ::testing::Test,
public arangodb::tests::LogSuppressor<arangodb::Logger::AUTHENTICATION,
arangodb::LogLevel::ERR> {
protected:
arangodb::tests::mocks::MockAqlServer server;
IResearchViewNodeTest() : server(false) {
arangodb::tests::init(true);
server.addFeature<arangodb::FlushFeature>(false);
server.startFeatures();
auto& dbPathFeature = server.getFeature<arangodb::DatabasePathFeature>();
arangodb::tests::setDatabasePath(
dbPathFeature); // ensure test data is stored in a unique directory
}
}; // IResearchViewNodeSetup
struct MockQuery final : arangodb::aql::Query {
MockQuery(std::shared_ptr<arangodb::transaction::Context> const& ctx,
arangodb::aql::QueryString const& queryString)
: arangodb::aql::Query(ctx, queryString, nullptr) {}
arangodb::transaction::Methods& trxForOptimization() override {
// original version contains an assertion
return *_trx;
}
};
} // namespace
TEST_F(IResearchViewNodeTest, constructSortedView) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ "
" \"name\": \"testView\", "
" \"type\": \"arangosearch\", "
" \"primarySort\": [ "
" { \"field\": \"my.nested.Fields\", \"asc\": false }, "
" { \"field\": \"another.field\", \"asc\": true } ] "
"}");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_TRUE(logicalView);
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collections\":[42] }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", "
"\"primarySort\": [ { \"field\": \"my.nested.Fields\", \"asc\": "
"false}, { \"field\": \"another.field\", \"asc\":true } ] }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_TRUE(node.sort().first); // primary sort is set
EXPECT_EQ(2, node.sort().second);
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_TRUE(node.options().restrictSources);
EXPECT_EQ(1, node.options().sources.size());
EXPECT_EQ(42, node.options().sources.begin()->id());
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collections\":[42] }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", "
"\"primarySort\": [ { \"field\": \"my.nested.Fields\", \"asc\": "
"false}, { \"field\": \"another.field\", \"asc\":true } ], "
"\"primarySortBuckets\": 1 }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_TRUE(node.sort().first); // primary sort is set
EXPECT_EQ(1, node.sort().second);
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_TRUE(node.options().restrictSources);
EXPECT_EQ(1, node.options().sources.size());
EXPECT_EQ(42, node.options().sources.begin()->id());
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// invalid 'primarySortBuckets' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", "
"\"primarySort\": [ { \"field\": \"my.nested.Fields\", \"asc\": "
"false}, { \"field\": \"another.field\", \"asc\":true } ], "
"\"primarySortBuckets\": false }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'primarySortBuckets' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", "
"\"primarySort\": [ { \"field\": \"my.nested.Fields\", \"asc\": "
"false}, { \"field\": \"another.field\", \"asc\":true } ], "
"\"primarySortBuckets\": 3 }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
}
TEST_F(IResearchViewNodeTest, construct) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
// no options
{
arangodb::aql::SingletonNode singleton(query.plan(),
arangodb::aql::ExecutionNodeId{0});
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
node.addDependency(&singleton);
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(1., node.getCost().estimatedCost);
EXPECT_EQ(0, node.getCost().estimatedNrItems);
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with options
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(true);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
attributeName.setStringValue("waitForSync", strlen("waitForSync"));
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_TRUE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::Auto,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with options default optimization
{
// build options node
std::string value{"auto"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"conditionOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::Auto,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with options none optimization
{
// build options node
std::string value{"none"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"conditionOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::None,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with options noneg optimization
{
// build options node
std::string value{"noneg"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"conditionOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::NoNegation,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with options nodnf optimization
{
// build options node
std::string value{"nodnf"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"conditionOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::NoDNF,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with options exact countApproximate
{
// build options node
std::string value{"exact"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"countApproximate"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::Auto,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// with optionscost countApproximate
{
// build options node
std::string value{"cost"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"countApproximate"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(arangodb::aql::ConditionOptimization::Auto,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Cost);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
}
// invalid options
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setBoolValue(true);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
attributeName.setStringValue("waitForSync", strlen("waitForSync"));
attributeName.addMember(&attributeName);
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
EXPECT_ANY_THROW(arangodb::iresearch::IResearchViewNode(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {})); // no sort condition
}
// invalid option conditionOptimization
{
// build options node
std::string value{"none2"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"conditionOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
EXPECT_ANY_THROW(arangodb::iresearch::IResearchViewNode(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {})); // no sort condition
}
// invalid option conditionOptimization non-string
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(false);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"conditionOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
EXPECT_ANY_THROW(arangodb::iresearch::IResearchViewNode(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {})); // no sort condition
}
// invalid option countApproximate non-string
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(false);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"countApproximate"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
EXPECT_ANY_THROW(arangodb::iresearch::IResearchViewNode(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {})); // no sort condition
}
// invalid option countApproximate invalid string
{
// build options node
std::string value{"unknown_count_approximate"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"countApproximate"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
EXPECT_ANY_THROW(arangodb::iresearch::IResearchViewNode(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {})); // no sort condition
}
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(true);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.setStringValue("waitForSync1", strlen("waitForSync1"));
attributeName.addMember(&attributeValue);
attributeName.addMember(&attributeName);
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), // plan
arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable, // out variable
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(&outVariable, &node.outVariable());
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(&outVariable, setHere[0]);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(0, node.getScorersSortLimit());
EXPECT_TRUE(node.getScorersSort().empty());
std::vector<std::pair<size_t, bool>> scorersSort{
{1, true}, {2, false}, {4, true}};
auto expectedScorersSort = scorersSort;
node.setScorersSort(std::move(scorersSort), 42);
EXPECT_EQ(42, node.getScorersSortLimit());
auto actualScorersSort = node.getScorersSort();
EXPECT_EQ(expectedScorersSort.size(), actualScorersSort.size());
EXPECT_TRUE(std::equal(expectedScorersSort.begin(),
expectedScorersSort.end(), actualScorersSort.begin(),
actualScorersSort.end()));
}
}
TEST_F(IResearchViewNodeTest, constructFromVPackSingleServer) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(
std::string_view("LET variable = 42 LET scoreVariable1 = "
"1 LET scoreVariable2 = 2 RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
// missing 'viewId'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 } }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'viewId' type (string expected)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\":123 }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'viewId' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"foo\"}");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND, ex.code());
}
}
// invalid 'primarySort' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"primarySort\": false }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// only 'scorersSortLimit' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\": 100 }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// only 'scorersSort' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSort\": [{\"index\":1, \"asc\":true}]}");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'scorersSort.index' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":10, \"scorersSort\": [{\"index\":true, "
"\"asc\":true}]}");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'scorersSort.asc' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":10, \"scorersSort\": [{\"index\":1, "
"\"asc\":42}]}");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'scorersSort' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":10, \"scorersSort\":false }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// invalid 'scorersSortLimit' specified
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":false, \"scorersSort\": [{\"index\":1, "
"\"asc\":true}]}");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// no options
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\", \"primarySort\": [] }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
// no options, ignore 'primarySortBuckets'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"primarySort\": [], \"primarySortBuckets\": false }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
// no options
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"primarySort\": [], \"primarySortBuckets\": 42 }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
// no options with scorersSort
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":42, \"scorersSort\":[{\"index\":0, "
"\"asc\":true}, {\"index\":1, \"asc\":false}], "
"\"scorers\": [ { \"id\": 1, \"name\": \"5\", \"node\": { "
"\"type\": \"function call\", \"typeID\": 47, \"name\": \"TFIDF\", "
"\"subNodes\": [{\"type\": \"array\", \"typeID\": 41, \"sorted\": "
"false, "
"\"subNodes\": [{\"type\": \"reference\", \"typeID\": 45, "
"\"name\": \"d\",\"id\": 0 }]}]}}, "
"{ \"id\": 2, \"name\": \"5\", \"node\": { "
"\"type\": \"function call\", \"typeID\": 47, \"name\": \"BM25\", "
"\"subNodes\": [{\"type\": \"array\", \"typeID\": 41, \"sorted\": "
"false, "
"\"subNodes\": [{\"type\": \"reference\", \"typeID\": 45, "
"\"name\": \"d\",\"id\": 0 }]}]}}] "
" }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_EQ(2, node.scorers().size());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(3, setHere.size());
EXPECT_FALSE(node.options().forceSync);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(42, node.getScorersSortLimit());
auto actualScorersSort = node.getScorersSort();
EXPECT_EQ(2, actualScorersSort.size());
EXPECT_EQ(0, actualScorersSort[0].first);
EXPECT_TRUE(actualScorersSort[0].second);
EXPECT_EQ(1, actualScorersSort[1].first);
EXPECT_FALSE(actualScorersSort[1].second);
}
// no options with invalid index scorersSort
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":42, \"scorersSort\":[{\"index\":10, "
"\"asc\":true}, {\"index\":1, \"asc\":false}], "
"\"scorers\": [ { \"id\": 1, \"name\": \"5\", \"node\": { "
"\"type\": \"function call\", \"typeID\": 47, \"name\": \"TFIDF\", "
"\"subNodes\": [{\"type\": \"array\", \"typeID\": 41, \"sorted\": "
"false, "
"\"subNodes\": [{\"type\": \"reference\", \"typeID\": 45, "
"\"name\": \"d\",\"id\": 0 }]}]}}, "
"{ \"id\": 2, \"name\": \"5\", \"node\": { "
"\"type\": \"function call\", \"typeID\": 47, \"name\": \"BM25\", "
"\"subNodes\": [{\"type\": \"array\", \"typeID\": 41, \"sorted\": "
"false, "
"\"subNodes\": [{\"type\": \"reference\", \"typeID\": 45, "
"\"name\": \"d\",\"id\": 0 }]}]}}] "
" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& ex) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, ex.code());
}
}
// with options
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collections\":[42] }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\", \"primarySort\": [] }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_TRUE(node.options().restrictSources);
EXPECT_EQ(1, node.options().sources.size());
EXPECT_EQ(42, node.options().sources.begin()->id());
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
// with options
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collections\":[] }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_TRUE(node.options().restrictSources);
EXPECT_EQ(arangodb::aql::ConditionOptimization::Auto,
node.options().conditionOptimization); // default value
EXPECT_EQ(0, node.options().sources.size());
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
// with options none condition optimization
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collection\":null, \"conditionOptimization\": \"none\" }, "
"\"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_FALSE(node.options().restrictSources);
EXPECT_EQ(0, node.options().sources.size());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(arangodb::aql::ConditionOptimization::None,
node.options().conditionOptimization);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
}
// with options noneg conditionOptimization
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collection\":null, \"conditionOptimization\": \"noneg\" }, "
"\"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_FALSE(node.options().restrictSources);
EXPECT_EQ(0, node.options().sources.size());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(arangodb::aql::ConditionOptimization::NoNegation,
node.options().conditionOptimization);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
}
// with options nodnf conditionOptimization
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collection\":null, \"conditionOptimization\": \"nodnf\" }, "
"\"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_FALSE(node.options().restrictSources);
EXPECT_EQ(0, node.options().sources.size());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(arangodb::aql::ConditionOptimization::NoDNF,
node.options().conditionOptimization);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
}
// with cost countApproximate
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"true, \"collection\":null, \"conditionOptimization\": \"nodnf\","
"\"countApproximate\":\"cost\" }, "
"\"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.sort().first); // primary sort is not set by default
EXPECT_EQ(0, node.sort().second); // primary sort is not set by default
EXPECT_EQ(arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW,
node.getType());
EXPECT_EQ(outVariable.id, node.outVariable().id);
EXPECT_EQ(outVariable.name, node.outVariable().name);
EXPECT_EQ(query.plan(), node.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{42}, node.id());
EXPECT_EQ(logicalView, node.view());
EXPECT_TRUE(node.scorers().empty());
EXPECT_FALSE(node.volatility().first); // filter volatility
EXPECT_FALSE(node.volatility().second); // sort volatility
arangodb::aql::VarSet usedHere;
node.getVariablesUsedHere(usedHere);
EXPECT_TRUE(usedHere.empty());
auto const setHere = node.getVariablesSetHere();
EXPECT_EQ(1, setHere.size());
EXPECT_EQ(outVariable.id, setHere[0]->id);
EXPECT_EQ(outVariable.name, setHere[0]->name);
EXPECT_TRUE(node.options().forceSync);
EXPECT_FALSE(node.options().restrictSources);
EXPECT_EQ(0, node.options().sources.size());
EXPECT_EQ(arangodb::aql::ConditionOptimization::NoDNF,
node.options().conditionOptimization);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Cost);
EXPECT_EQ(0., node.getCost().estimatedCost); // no dependencies
EXPECT_EQ(0, node.getCost().estimatedNrItems); // no dependencies
}
// invalid option 'waitForSync'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"waitForSync\" : "
"\"false\"}, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// invalid option 'collections'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"collections\" : "
"\"false\"}, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// invalid option 'collections'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"collections\" : "
"{}}, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// invalid option 'primarySort'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { \"collections\" : "
"{}}, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", "
"\"primarySort\": true }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_TRUE(TRI_ERROR_BAD_PARAMETER == e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// invalid option 'conditionOptimization'
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"options\": { "
"\"conditionOptimization\" : "
"\"invalid\"}, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", "
"\"primarySort\": true }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_TRUE(TRI_ERROR_BAD_PARAMETER == e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid late materialization (no collection variable)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmDocId\": { "
"\"name\":\"variable100\", \"id\":100 },"
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid late materialization (no local document id variable)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 },"
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid late materialization (invalid view values vars)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 }, "
"\"outNmDocId\": { \"name\":\"variable100\", \"id\":100 }, "
"\"viewValuesVars\":{\"fieldNumber\":0, \"id\":101}, "
"\"noMaterialization\":false, "
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid late materialization (invalid field number)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 }, "
"\"outNmDocId\": { \"name\":\"variable100\", \"id\":100 }, "
"\"viewValuesVars\":[{\"fieldNumber\":\"0\", \"id\":101}], "
"\"noMaterialization\":false, "
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid late materialization (invalid variable id)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 }, "
"\"outNmDocId\": { \"name\":\"variable100\", \"id\":100 }, "
"\"viewValuesVars\":[{\"fieldNumber\":0, \"id\":\"101\"}], "
"\"noMaterialization\":false, "
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid no materialization (invalid noMaterialization)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 }, "
"\"outNmDocId\": { \"name\":\"variable100\", \"id\":100 }, "
"\"viewValuesVars\":[], "
"\"noMaterialization\":1, "
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid costApproximate (invalid type)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 }, "
"\"outNmDocId\": { \"name\":\"variable100\", \"id\":100 }, "
"\"viewValuesVars\":[], "
"\"noMaterialization\":false, "
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null, \"countApproximate\":1 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
// with invalid costApproximate (invalid value)
{
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLater\":[], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"outNmColPtr\": { "
"\"name\":\"variable100\", \"id\":100 }, "
"\"outNmDocId\": { \"name\":\"variable100\", \"id\":100 }, "
"\"viewValuesVars\":[], "
"\"noMaterialization\":\"unknown_approximate_type\", "
"\"options\": { \"waitForSync\" : "
"true, \"collection\":null, \"countApproximate\":1 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) + "\" }");
try {
arangodb::iresearch::IResearchViewNode node(*query.plan(), // plan
json->slice());
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_BAD_PARAMETER, e.code());
} catch (...) {
EXPECT_TRUE(false);
}
}
}
// FIXME TODO
// TEST_F(IResearchViewNodeTest, constructFromVPackCluster) {
//}
TEST_F(IResearchViewNodeTest, clone) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
// no filter condition, no sort condition, no shards, no options
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
// clone without properties into the same plan
{
auto const nextId = node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(query.plan(), true, false));
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(node.plan(), cloned.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{nextId.id() + 1}, cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone with properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, true));
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_NE(&node.outVariable(),
&cloned.outVariable()); // different objects
EXPECT_EQ(node.outVariable().id, cloned.outVariable().id);
EXPECT_EQ(node.outVariable().name, cloned.outVariable().name);
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone without properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, false));
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
}
// no filter condition, no sort condition, no shards, options
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(true);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
attributeName.setStringValue("waitForSync", strlen("waitForSync"));
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_TRUE(node.options().forceSync);
// clone without properties into the same plan
{
auto const nextId = node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(query.plan(), true, false));
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(node.plan(), cloned.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{nextId.id() + 1}, cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone with properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, true));
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_NE(&node.outVariable(),
&cloned.outVariable()); // different objects
EXPECT_EQ(node.outVariable().id, cloned.outVariable().id);
EXPECT_EQ(node.outVariable().name, cloned.outVariable().name);
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone without properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, false));
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
}
// no filter condition, no sort condition, with shards, no options
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
node.shards().emplace_back("abc");
node.shards().emplace_back("def");
// clone without properties into the same plan
{
auto const nextId = node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(query.plan(), true, false));
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(node.plan(), cloned.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{nextId.id() + 1}, cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone with properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, true));
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_NE(&node.outVariable(),
&cloned.outVariable()); // different objects
EXPECT_EQ(node.outVariable().id, cloned.outVariable().id);
EXPECT_EQ(node.outVariable().name, cloned.outVariable().name);
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone without properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, false));
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
}
// no filter condition, sort condition, with shards, no options
{
arangodb::iresearch::IResearchViewSort sort;
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no scorers
node.sort(&sort, 0);
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
node.shards().emplace_back("abc");
node.shards().emplace_back("def");
// clone without properties into the same plan
{
auto const nextId = node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(query.plan(), true, false));
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(node.plan(), cloned.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{nextId.id() + 1}, cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone with properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, true));
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_NE(&node.outVariable(),
&cloned.outVariable()); // different objects
EXPECT_EQ(node.outVariable().id, cloned.outVariable().id);
EXPECT_EQ(node.outVariable().name, cloned.outVariable().name);
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone without properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, false));
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
}
// with late materialization
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
arangodb::aql::Variable const outNmColPtr("variable100", 100, false);
arangodb::aql::Variable const outNmDocId("variable101", 101, false);
node.setLateMaterialized(outNmColPtr, outNmDocId);
ASSERT_TRUE(node.isLateMaterialized());
auto varsSetOriginal = node.getVariablesSetHere();
ASSERT_EQ(2, varsSetOriginal.size());
// clone without properties into the same plan
{
auto const nextId = node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(query.plan(), true, false));
auto varsSetCloned = cloned.getVariablesSetHere();
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(node.plan(), cloned.plan());
EXPECT_EQ(arangodb::aql::ExecutionNodeId{nextId.id() + 1}, cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.isLateMaterialized(), cloned.isLateMaterialized());
ASSERT_EQ(varsSetOriginal.size(), varsSetCloned.size());
EXPECT_EQ(varsSetOriginal[0], varsSetCloned[0]);
EXPECT_EQ(varsSetOriginal[1], varsSetCloned[1]);
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone with properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, true));
auto varsSetCloned = cloned.getVariablesSetHere();
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_NE(&node.outVariable(),
&cloned.outVariable()); // different objects
EXPECT_EQ(node.outVariable().id, cloned.outVariable().id);
EXPECT_EQ(node.outVariable().name, cloned.outVariable().name);
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_EQ(node.getCost(), cloned.getCost());
EXPECT_EQ(node.isLateMaterialized(), cloned.isLateMaterialized());
ASSERT_EQ(varsSetOriginal.size(), varsSetCloned.size());
EXPECT_NE(varsSetOriginal[0], varsSetCloned[0]);
EXPECT_NE(varsSetOriginal[1], varsSetCloned[1]);
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
// clone without properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, false));
auto varsSetCloned = cloned.getVariablesSetHere();
EXPECT_TRUE(cloned.collections().empty());
EXPECT_EQ(node.empty(), cloned.empty());
EXPECT_EQ(node.shards(), cloned.shards());
EXPECT_EQ(node.getType(), cloned.getType());
EXPECT_EQ(&node.outVariable(), &cloned.outVariable()); // same objects
EXPECT_EQ(otherQuery.plan(), cloned.plan());
EXPECT_EQ(node.id(), cloned.id());
EXPECT_EQ(&node.vocbase(), &cloned.vocbase());
EXPECT_EQ(node.view(), cloned.view());
EXPECT_EQ(&node.filterCondition(), &cloned.filterCondition());
EXPECT_EQ(node.scorers(), cloned.scorers());
EXPECT_EQ(node.volatility(), cloned.volatility());
EXPECT_EQ(node.options().forceSync, cloned.options().forceSync);
EXPECT_EQ(node.sort(), cloned.sort());
EXPECT_TRUE(node.getCost() == cloned.getCost());
EXPECT_EQ(node.isLateMaterialized(), cloned.isLateMaterialized());
ASSERT_EQ(varsSetOriginal.size(), varsSetCloned.size());
EXPECT_EQ(varsSetOriginal[0], varsSetCloned[0]);
EXPECT_EQ(varsSetOriginal[1], varsSetCloned[1]);
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
}
}
// with scorers sort
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
arangodb::aql::Variable const outNmColPtr("variable100", 100, false);
arangodb::aql::Variable const outNmDocId("variable101", 101, false);
std::vector<std::pair<size_t, bool>> scorersSort{{0, true}};
node.setScorersSort(std::move(scorersSort), 42);
auto varsSetOriginal = node.getVariablesSetHere();
// clone without properties into the same plan
{
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(query.plan(), true, false));
auto varsSetCloned = cloned.getVariablesSetHere();
EXPECT_EQ(varsSetCloned, varsSetOriginal);
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
auto orig = node.getScorersSort();
auto clone = cloned.getScorersSort();
EXPECT_TRUE(
std::equal(orig.begin(), orig.end(), clone.begin(), clone.end()));
}
// clone with properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, false));
auto varsSetCloned = cloned.getVariablesSetHere();
ASSERT_EQ(varsSetOriginal.size(), varsSetCloned.size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
auto orig = node.getScorersSort();
auto clone = cloned.getScorersSort();
EXPECT_TRUE(
std::equal(orig.begin(), orig.end(), clone.begin(), clone.end()));
}
// clone without properties into another plan
{
// another dummy query
MockQuery otherQuery(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
otherQuery.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
node.plan()->nextId();
auto& cloned = dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*node.clone(otherQuery.plan(), true, true));
auto varsSetCloned = cloned.getVariablesSetHere();
ASSERT_EQ(varsSetOriginal.size(), varsSetCloned.size());
EXPECT_EQ(node.getScorersSortLimit(), cloned.getScorersSortLimit());
EXPECT_EQ(node.getScorersSort().size(), cloned.getScorersSort().size());
auto orig = node.getScorersSort();
auto clone = cloned.getScorersSort();
EXPECT_TRUE(
std::equal(orig.begin(), orig.end(), clone.begin(), clone.end()));
}
}
}
TEST_F(IResearchViewNodeTest, serialize) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(
std::string_view("let variable = 1 let variable100 = 3 "
"let variable101 = 2 RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
// no filter condition, no sort condition
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(node.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(node.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
}
// no filter condition, no sort condition, options
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(true);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
attributeName.setStringValue("waitForSync", strlen("waitForSync"));
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_TRUE(node.options().forceSync);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(node.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(node.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
}
// with late materialization
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
arangodb::aql::Variable const outNmColPtr("variable100", 1, false);
arangodb::aql::Variable const outNmDocId("variable101", 2, false);
node.setLateMaterialized(outNmColPtr, outNmDocId);
node.setVarsUsedLater({arangodb::aql::VarSet{&outNmColPtr, &outNmDocId}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.isLateMaterialized(), deserialized.isLateMaterialized());
auto varsSetHere = deserialized.getVariablesSetHere();
ASSERT_EQ(2, varsSetHere.size());
EXPECT_EQ(outNmColPtr.id, varsSetHere[0]->id);
EXPECT_EQ(outNmColPtr.name, varsSetHere[0]->name);
EXPECT_EQ(outNmDocId.id, varsSetHere[1]->id);
EXPECT_EQ(outNmDocId.name, varsSetHere[1]->name);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(node.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.isLateMaterialized(), deserialized.isLateMaterialized());
auto varsSetHere = deserialized.getVariablesSetHere();
ASSERT_EQ(2, varsSetHere.size());
EXPECT_EQ(outNmColPtr.id, varsSetHere[0]->id);
EXPECT_EQ(outNmColPtr.name, varsSetHere[0]->name);
EXPECT_EQ(outNmDocId.id, varsSetHere[1]->id);
EXPECT_EQ(outNmDocId.name, varsSetHere[1]->name);
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
EXPECT_EQ(node.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
}
// with countApproximate cost
{
std::string value{"cost"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"countApproximate"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, // no options
{}); // no sort condition
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(deserialized.options().countApproximate,
arangodb::iresearch::CountApproximate::Cost);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(deserialized.options().countApproximate,
arangodb::iresearch::CountApproximate::Cost);
}
}
// with countApproximate exact
{
std::string value{"exact"};
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_STRING);
attributeValue.setStringValue(value.c_str(), value.size());
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"countApproximate"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, // no options
{}); // no sort condition
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(deserialized.options().countApproximate,
arangodb::iresearch::CountApproximate::Exact);
}
}
// with allowed merge filters
{
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_INT);
attributeValue.setIntValue(
static_cast<int64_t>(arangodb::iresearch::FilterOptimization::MAX));
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"filterOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, // no options
{}); // no sort condition
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(deserialized.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(deserialized.options().filterOptimization,
arangodb::iresearch::FilterOptimization::MAX);
}
}
// with forbidden merge filters
{
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_INT);
attributeValue.setIntValue(
static_cast<int64_t>(arangodb::iresearch::FilterOptimization::NONE));
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
std::string name{"filterOptimization"};
attributeName.setStringValue(name.c_str(), name.size());
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, // no options
{}); // no sort condition
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(deserialized.options().filterOptimization,
arangodb::iresearch::FilterOptimization::NONE);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(deserialized.options().filterOptimization,
arangodb::iresearch::FilterOptimization::NONE);
}
}
// with scorers sort
{
MockQuery queryScores(
arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(
std::string_view("LET variable = 42 LET scoreVariable1 = 1 LET "
"scoreVariable2 = 2 RETURN 1")));
auto json = arangodb::velocypack::Parser::fromJson(
"{ \"id\":42, \"depth\":0, \"totalNrRegs\":0, \"varInfoList\":[], "
"\"nrRegs\":[], \"nrRegsHere\":[], \"regsToClear\":[], "
"\"varsUsedLaterStack\":[[]], \"varsValid\":[], \"outVariable\": { "
"\"name\":\"variable\", \"id\":0 }, \"viewId\": \"" +
std::to_string(logicalView->id().id()) +
"\", \"scorersSortLimit\":42, \"scorersSort\":[{\"index\":0, "
"\"asc\":true}, {\"index\":1, \"asc\":false}], "
"\"scorers\": [ { \"id\": 1, \"name\": \"5\", \"node\": { "
"\"type\": \"function call\", \"typeID\": 47, \"name\": \"TFIDF\", "
"\"subNodes\": [{\"type\": \"array\", \"typeID\": 41, \"sorted\": "
"false, "
"\"subNodes\": [{\"type\": \"reference\", \"typeID\": 45, "
"\"name\": \"d\",\"id\": 0 }]}]}}, "
"{ \"id\": 2, \"name\": \"5\", \"node\": { "
"\"type\": \"function call\", \"typeID\": 47, \"name\": \"BM25\", "
"\"subNodes\": [{\"type\": \"array\", \"typeID\": 41, \"sorted\": "
"false, "
"\"subNodes\": [{\"type\": \"reference\", \"typeID\": 45, "
"\"name\": \"d\",\"id\": 0 }]}]}}] "
" }");
queryScores.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
arangodb::aql::Variable const outScore0("variable100", 1, false);
arangodb::aql::Variable const outScore1("variable101", 2, false);
arangodb::iresearch::IResearchViewNode node(
*queryScores.plan(), json->slice()); // no sort condition
node.setVarsUsedLater(
{arangodb::aql::VarSet{&outVariable, &outScore0, &outScore1}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(
*queryScores.plan(), nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(deserialized.getScorersSortLimit(), 42);
EXPECT_EQ(node.getScorersSort().size(),
deserialized.getScorersSort().size());
auto orig = node.getScorersSort();
auto clone = deserialized.getScorersSort();
EXPECT_TRUE(
std::equal(orig.begin(), orig.end(), clone.begin(), clone.end()));
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(deserialized.getScorersSortLimit(), 42);
EXPECT_EQ(node.getScorersSort().size(),
deserialized.getScorersSort().size());
auto orig = node.getScorersSort();
auto clone = deserialized.getScorersSort();
EXPECT_TRUE(
std::equal(orig.begin(), orig.end(), clone.begin(), clone.end()));
}
}
}
TEST_F(IResearchViewNodeTest, serializeSortedView) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\", \"primarySort\" : "
"[ { \"field\":\"_key\", \"direction\":\"desc\"} ] }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
auto& viewImpl =
arangodb::basics::downCast<arangodb::iresearch::IResearchView>(
*logicalView);
EXPECT_FALSE(viewImpl.primarySort().empty());
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(
std::string_view("let variable = 1 let variable100 = 3 "
"let variable101 = 2 RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
// no filter condition, no sort condition
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
node.sort(&viewImpl.primarySort(), 1);
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(1, node.sort().second);
EXPECT_EQ(node.getCost(), deserialized.getCost());
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(1, node.sort().second);
EXPECT_EQ(node.getCost(), deserialized.getCost());
}
}
// no filter condition, no sort condition, options
{
// build options node
arangodb::aql::AstNode attributeValue(arangodb::aql::NODE_TYPE_VALUE);
attributeValue.setValueType(arangodb::aql::VALUE_TYPE_BOOL);
attributeValue.setBoolValue(true);
arangodb::aql::AstNode attributeName(
arangodb::aql::NODE_TYPE_OBJECT_ELEMENT);
attributeName.addMember(&attributeValue);
attributeName.setStringValue("waitForSync", strlen("waitForSync"));
arangodb::aql::AstNode options(arangodb::aql::NODE_TYPE_OBJECT);
options.addMember(&attributeName);
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
&options, {}); // no sort condition
EXPECT_TRUE(node.empty()); // view has no links
EXPECT_TRUE(node.collections().empty()); // view has no links
EXPECT_TRUE(node.shards().empty());
EXPECT_TRUE(node.options().forceSync);
node.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(0, node.sort().second);
EXPECT_EQ(node.getCost(), deserialized.getCost());
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(0, node.sort().second);
EXPECT_EQ(node.getCost(), deserialized.getCost());
}
}
// with late materialization
{
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
arangodb::aql::Variable const outNmColPtr("variable100", 1, false);
arangodb::aql::Variable const outNmDocId("variable101", 2, false);
node.sort(&viewImpl.primarySort(), 1);
node.setLateMaterialized(outNmColPtr, outNmDocId);
node.setVarsUsedLater({arangodb::aql::VarSet{&outNmColPtr, &outNmDocId}});
node.setVarsValid({{}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
arangodb::velocypack::Builder builder;
unsigned flags = arangodb::aql::ExecutionNode::SERIALIZE_DETAILS;
node.toVelocyPack(builder, flags); // object with array of objects
auto nodeSlice = builder.slice();
// constructor
{
arangodb::iresearch::IResearchViewNode const deserialized(*query.plan(),
nodeSlice);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(1, node.sort().second);
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.isLateMaterialized(), deserialized.isLateMaterialized());
auto varsSetHere = deserialized.getVariablesSetHere();
ASSERT_EQ(2, varsSetHere.size());
EXPECT_EQ(outNmColPtr.id, varsSetHere[0]->id);
EXPECT_EQ(outNmColPtr.name, varsSetHere[0]->name);
EXPECT_EQ(outNmDocId.id, varsSetHere[1]->id);
EXPECT_EQ(outNmDocId.name, varsSetHere[1]->name);
}
// factory method
{
std::unique_ptr<arangodb::aql::ExecutionNode> deserializedNode(
arangodb::aql::ExecutionNode::fromVPackFactory(query.plan(),
nodeSlice));
auto& deserialized =
dynamic_cast<arangodb::iresearch::IResearchViewNode&>(
*deserializedNode);
EXPECT_EQ(node.empty(), deserialized.empty());
EXPECT_EQ(node.shards(), deserialized.shards());
EXPECT_TRUE(deserialized.collections().empty());
EXPECT_EQ(node.getType(), deserialized.getType());
EXPECT_EQ(node.outVariable().id, deserialized.outVariable().id);
EXPECT_EQ(node.outVariable().name, deserialized.outVariable().name);
EXPECT_EQ(node.plan(), deserialized.plan());
EXPECT_EQ(node.id(), deserialized.id());
EXPECT_EQ(&node.vocbase(), &deserialized.vocbase());
EXPECT_EQ(node.view(), deserialized.view());
EXPECT_EQ(&node.filterCondition(), &deserialized.filterCondition());
EXPECT_EQ(node.scorers(), deserialized.scorers());
EXPECT_EQ(node.volatility(), deserialized.volatility());
EXPECT_EQ(node.options().forceSync, deserialized.options().forceSync);
EXPECT_EQ(node.sort(), deserialized.sort());
EXPECT_EQ(1, node.sort().second);
EXPECT_EQ(node.getCost(), deserialized.getCost());
EXPECT_EQ(node.isLateMaterialized(), deserialized.isLateMaterialized());
auto varsSetHere = deserialized.getVariablesSetHere();
ASSERT_EQ(2, varsSetHere.size());
EXPECT_EQ(outNmColPtr.id, varsSetHere[0]->id);
EXPECT_EQ(outNmColPtr.name, varsSetHere[0]->name);
EXPECT_EQ(outNmDocId.id, varsSetHere[1]->id);
EXPECT_EQ(outNmDocId.name, varsSetHere[1]->name);
}
}
}
TEST_F(IResearchViewNodeTest, collections) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
std::shared_ptr<arangodb::LogicalCollection> collection0;
std::shared_ptr<arangodb::LogicalCollection> collection1;
// create collection0
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection0\", \"id\" : \"42\" }");
collection0 = vocbase.createCollection(createJson->slice());
ASSERT_NE(nullptr, collection0);
}
// create collection1
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection1\", \"id\" : \"4242\" }");
collection1 = vocbase.createCollection(createJson->slice());
ASSERT_NE(nullptr, collection1);
}
// create collection2
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection2\" , \"id\" : \"424242\" }");
ASSERT_NE(nullptr, vocbase.createCollection(createJson->slice()));
}
// create view
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// link collections
auto updateJson = arangodb::velocypack::Parser::fromJson(
"{ \"links\": {"
"\"testCollection0\": { \"includeAllFields\": true, "
"\"trackListPositions\": true },"
"\"testCollection1\": { \"includeAllFields\": true },"
"\"testCollection2\": { \"includeAllFields\": true }"
"}}");
EXPECT_TRUE(logicalView->properties(updateJson->slice(), true, true).ok());
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
// register collections with the query
query.collections().add(std::to_string(collection0->id().id()),
arangodb::AccessMode::Type::READ,
arangodb::aql::Collection::Hint::None);
query.collections().add(std::to_string(collection1->id().id()),
arangodb::AccessMode::Type::READ,
arangodb::aql::Collection::Hint::None);
// prepare query
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::Variable const outVariable("variable", 0, false);
// no filter condition, no sort condition
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
EXPECT_TRUE(node.shards().empty());
EXPECT_FALSE(node.empty()); // view has no links
auto collections = node.collections();
EXPECT_FALSE(collections.empty()); // view has no links
EXPECT_EQ(2, collections.size());
// we expect only collections 'collection0', 'collection1' to be
// present since 'collection2' is not registered with the query
std::unordered_set<std::string> expectedCollections{
std::to_string(collection0->id().id()),
std::to_string(collection1->id().id())};
for (arangodb::aql::Collection const& collection : collections) {
EXPECT_EQ(1, expectedCollections.erase(collection.name()));
}
EXPECT_TRUE(expectedCollections.empty());
}
TEST_F(IResearchViewNodeTest, createBlockSingleServer) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// create collection0
std::shared_ptr<arangodb::LogicalCollection> collection0;
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection0\", \"id\" : \"42\" }");
collection0 = vocbase.createCollection(createJson->slice());
ASSERT_NE(nullptr, collection0);
}
// link collections
auto updateJson = arangodb::velocypack::Parser::fromJson(
"{ \"links\": {"
"\"testCollection0\": { \"includeAllFields\": true, "
"\"trackListPositions\": true }"
"}}");
EXPECT_TRUE(logicalView->properties(updateJson->slice(), true, true).ok());
// insert into collection
{
std::vector<std::string> const EMPTY;
arangodb::OperationOptions opt;
arangodb::ManagedDocumentResult mmdoc;
arangodb::transaction::Methods trx(
arangodb::transaction::StandaloneContext::Create(vocbase), EMPTY, EMPTY,
EMPTY, arangodb::transaction::Options());
EXPECT_TRUE(trx.begin().ok());
auto json = arangodb::velocypack::Parser::fromJson("{}");
auto const res = collection0->insert(&trx, json->slice(), mmdoc, opt);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(trx.commit().ok());
EXPECT_TRUE(
(arangodb::tests::executeQuery(vocbase,
"FOR d IN testView SEARCH 1 ==1 OPTIONS "
"{ waitForSync: true } RETURN d")
.result.ok())); // commit
}
// dummy query
auto ctx = arangodb::transaction::StandaloneContext::Create(vocbase);
MockQuery query(ctx,
arangodb::aql::QueryString(std::string_view("RETURN 1")));
query.initForTests();
// query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
// dummy engine
arangodb::aql::ExecutionEngine engine(
0, query, query.itemBlockManager(),
arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::ExecutionPlan plan(query.ast(), false);
arangodb::aql::Variable const outVariable("variable", 0, false);
// no filter condition, no sort condition
{
arangodb::aql::SingletonNode singleton(&plan,
arangodb::aql::ExecutionNodeId{0});
arangodb::iresearch::IResearchViewNode node(
plan, arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
node.addDependency(&singleton);
// "Trust me, I'm an IT professional"
singleton.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
singleton.setVarsValid({{}});
singleton.setRegsToKeep({{}});
node.setVarsUsedLater({{}});
node.setVarsValid({arangodb::aql::VarSet{&outVariable}});
node.setRegsToKeep({{}});
node.setVarUsageValid();
singleton.setVarUsageValid();
node.planRegisters();
std::unordered_map<arangodb::aql::ExecutionNode*,
arangodb::aql::ExecutionBlock*>
EMPTY;
// before transaction has started (no snapshot)
try {
auto block = node.createBlock(engine, EMPTY);
EXPECT_TRUE(false);
} catch (arangodb::basics::Exception const& e) {
EXPECT_EQ(TRI_ERROR_INTERNAL, e.code());
}
arangodb::transaction::Methods trx(ctx);
ASSERT_TRUE(trx.state());
// start transaction (put snapshot into)
EXPECT_TRUE(
nullptr ==
arangodb::basics::downCast<arangodb::iresearch::IResearchView>(
*logicalView)
.snapshot(trx,
arangodb::iresearch::IResearchView::SnapshotMode::Find));
auto* snapshot =
arangodb::basics::downCast<arangodb::iresearch::IResearchView>(
*logicalView)
.snapshot(
trx,
arangodb::iresearch::IResearchView::SnapshotMode::FindOrCreate);
EXPECT_TRUE(
snapshot ==
arangodb::basics::downCast<arangodb::iresearch::IResearchView>(
*logicalView)
.snapshot(trx,
arangodb::iresearch::IResearchView::SnapshotMode::Find));
EXPECT_TRUE(snapshot ==
arangodb::basics::downCast<arangodb::iresearch::IResearchView>(
*logicalView)
.snapshot(trx, arangodb::iresearch::IResearchView::
SnapshotMode::FindOrCreate));
EXPECT_TRUE(snapshot ==
arangodb::basics::downCast<arangodb::iresearch::IResearchView>(
*logicalView)
.snapshot(trx, arangodb::iresearch::IResearchView::
SnapshotMode::SyncAndReplace));
// after transaction has started
{
auto block = node.createBlock(engine, EMPTY);
EXPECT_NE(nullptr, block);
EXPECT_NE(nullptr,
(dynamic_cast<arangodb::aql::ExecutionBlockImpl<
arangodb::aql::IResearchViewExecutor<
false, false,
arangodb::iresearch::MaterializeType::Materialize>>*>(
block.get())));
}
}
}
// FIXME TODO
// TEST_F(IResearchViewNodeTest, createBlockDBServer) {
//}
TEST_F(IResearchViewNodeTest, createBlockCoordinator) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server()));
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_FALSE(!logicalView);
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
query.initForTests();
// query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
// dummy engine
arangodb::aql::ExecutionEngine engine(
0, query, query.itemBlockManager(),
arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::ExecutionPlan plan(query.ast(), false);
// dummy engine
arangodb::aql::SingletonNode singleton(&plan,
arangodb::aql::ExecutionNodeId{0});
arangodb::aql::Variable const outVariable("variable", 0, false);
// no filter condition, no sort condition
arangodb::iresearch::IResearchViewNode node(
plan, arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
node.addDependency(&singleton);
std::unordered_map<arangodb::aql::ExecutionNode*,
arangodb::aql::ExecutionBlock*>
EMPTY;
singleton.setVarsUsedLater({arangodb::aql::VarSet{&outVariable}});
singleton.setVarsValid({{}});
node.setVarsUsedLater({{}});
node.setVarsValid({arangodb::aql::VarSet{&outVariable}});
singleton.setVarUsageValid();
node.setVarUsageValid();
singleton.planRegisters();
node.planRegisters();
arangodb::ServerState::instance()->setRole(
arangodb::ServerState::ROLE_COORDINATOR);
auto emptyBlock = node.createBlock(engine, EMPTY);
arangodb::ServerState::instance()->setRole(
arangodb::ServerState::ROLE_SINGLE);
EXPECT_NE(nullptr, emptyBlock);
EXPECT_TRUE(
nullptr !=
dynamic_cast<
arangodb::aql::ExecutionBlockImpl<arangodb::aql::NoResultsExecutor>*>(
emptyBlock.get()));
}
TEST_F(IResearchViewNodeTest, createBlockCoordinatorLateMaterialize) {
TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL,
testDBInfo(server.server(), "testVocbase", 1));
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase.createView(createJson->slice());
ASSERT_TRUE((false == !logicalView));
// dummy query
MockQuery query(arangodb::transaction::StandaloneContext::Create(vocbase),
arangodb::aql::QueryString(std::string_view("RETURN 1")));
query.prepareQuery(arangodb::aql::SerializationFormat::SHADOWROWS);
// dummy engine
arangodb::aql::ExecutionEngine engine(
0, query, query.itemBlockManager(),
arangodb::aql::SerializationFormat::SHADOWROWS);
arangodb::aql::SingletonNode singleton(query.plan(),
arangodb::aql::ExecutionNodeId{0});
arangodb::aql::Variable const outVariable("variable", 0, false);
arangodb::aql::Variable const outNmColPtr("variable100", 100, false);
arangodb::aql::Variable const outNmDocId("variable101", 101, false);
// no filter condition, no sort condition
arangodb::iresearch::IResearchViewNode node(
*query.plan(), arangodb::aql::ExecutionNodeId{42},
vocbase, // database
logicalView, // view
outVariable,
nullptr, // no filter condition
nullptr, // no options
{}); // no sort condition
node.addDependency(&singleton);
node.setLateMaterialized(outNmColPtr, outNmDocId);
std::unordered_map<arangodb::aql::ExecutionNode*,
arangodb::aql::ExecutionBlock*>
EMPTY;
singleton.setVarsUsedLater(
{arangodb::aql::VarSet{&outNmColPtr, &outNmDocId}});
singleton.setVarsValid({{}});
node.setVarsUsedLater({{}});
node.setVarsValid({arangodb::aql::VarSet{&outNmColPtr, &outNmDocId}});
singleton.setVarUsageValid();
node.setVarUsageValid();
singleton.planRegisters();
node.planRegisters();
arangodb::ServerState::instance()->setRole(
arangodb::ServerState::ROLE_COORDINATOR);
auto emptyBlock = node.createBlock(engine, EMPTY);
arangodb::ServerState::instance()->setRole(
arangodb::ServerState::ROLE_SINGLE);
EXPECT_TRUE(nullptr != emptyBlock);
EXPECT_TRUE(
nullptr !=
dynamic_cast<
arangodb::aql::ExecutionBlockImpl<arangodb::aql::NoResultsExecutor>*>(
emptyBlock.get()));
}
class IResearchViewVolatitlityTest
: public ::testing::Test,
public arangodb::tests::LogSuppressor<arangodb::Logger::AUTHENTICATION,
arangodb::LogLevel::ERR> {
protected:
arangodb::tests::mocks::MockAqlServer server;
TRI_vocbase_t* vocbase{nullptr};
IResearchViewVolatitlityTest() : server(false) {
arangodb::tests::init(true);
server.addFeature<arangodb::FlushFeature>(false);
server.startFeatures();
auto& dbPathFeature = server.getFeature<arangodb::DatabasePathFeature>();
arangodb::tests::setDatabasePath(
dbPathFeature); // ensure test data is stored in a unique directory
auto& dbFeature = server.getFeature<arangodb::DatabaseFeature>();
vocbase = dbFeature.useDatabase(arangodb::StaticStrings::SystemDatabase);
EXPECT_NE(nullptr, vocbase);
std::shared_ptr<arangodb::LogicalCollection> collection0;
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection0\", \"id\" : \"42\" }");
collection0 = vocbase->createCollection(createJson->slice());
EXPECT_NE(nullptr, collection0);
}
std::shared_ptr<arangodb::LogicalCollection> collection1;
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection1\", \"id\" : \"43\" }");
collection1 = vocbase->createCollection(createJson->slice());
EXPECT_NE(nullptr, collection1);
}
arangodb::LogicalView::ptr logicalView0;
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView0\", \"type\": \"arangosearch\" }");
logicalView0 = vocbase->createView(createJson->slice());
EXPECT_NE(nullptr, logicalView0);
auto updateJson = arangodb::velocypack::Parser::fromJson(
"{ \"links\": {"
"\"testCollection0\": { \"includeAllFields\": true, "
"\"trackListPositions\": true }"
"}}");
EXPECT_TRUE(
logicalView0->properties(updateJson->slice(), true, true).ok());
}
arangodb::LogicalView::ptr logicalView1;
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView1\", \"type\": \"arangosearch\" }");
logicalView1 = vocbase->createView(createJson->slice());
EXPECT_NE(nullptr, logicalView1);
auto updateJson = arangodb::velocypack::Parser::fromJson(
"{ \"links\": {"
"\"testCollection1\": { \"includeAllFields\": true, "
"\"trackListPositions\": true }"
"}}");
EXPECT_TRUE(
logicalView1->properties(updateJson->slice(), true, true).ok());
}
std::vector<std::string> EMPTY_VECTOR;
auto trx = std::make_shared<arangodb::transaction::Methods>(
arangodb::transaction::StandaloneContext::Create(*vocbase),
EMPTY_VECTOR, EMPTY_VECTOR, EMPTY_VECTOR,
arangodb::transaction::Options());
EXPECT_TRUE(trx->begin().ok());
// in collection only one alive doc
{
auto aliveDoc0 = arangodb::velocypack::Parser::fromJson("{ \"key\": 1 }");
arangodb::ManagedDocumentResult insertResult;
arangodb::OperationOptions options;
EXPECT_TRUE(
collection0
->insert(trx.get(), aliveDoc0->slice(), insertResult, options)
.ok());
auto aliveDoc1 = arangodb::velocypack::Parser::fromJson("{ \"key\": 2 }");
arangodb::ManagedDocumentResult insertResult1;
arangodb::OperationOptions options1;
EXPECT_TRUE(
collection0
->insert(trx.get(), aliveDoc1->slice(), insertResult1, options1)
.ok());
}
{
auto aliveDoc1 = arangodb::velocypack::Parser::fromJson("{ \"key\": 1 }");
arangodb::ManagedDocumentResult insertResult;
arangodb::OperationOptions options;
EXPECT_TRUE(
collection1
->insert(trx.get(), aliveDoc1->slice(), insertResult, options)
.ok());
arangodb::iresearch::IResearchLinkMeta meta;
}
EXPECT_TRUE(trx->commit().ok());
// force views sync
auto res = arangodb::tests::executeQuery(
*vocbase,
"FOR s IN testView0 OPTIONS { waitForSync: true } LET kk = s.key "
"FOR d IN testView1 SEARCH d.key == kk "
"OPTIONS { waitForSync: true } RETURN d ");
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_NE(0, res.data->slice().length());
}
};
TEST_F(IResearchViewVolatitlityTest, volatilityFilterSubqueryWithVar) {
std::string const queryString =
"FOR s IN testView0 LET kk = s.key "
"FOR d IN testView1 SEARCH d.key == kk RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(1, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterSubquery) {
std::string const queryString =
"FOR s IN testView0 "
"FOR d IN testView1 SEARCH d.key == s.key RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(1, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterNonDetVar) {
std::string const queryString =
"FOR s IN testView0 LET kk = NOOPT(s.key) "
"FOR d IN testView1 SEARCH d.key == kk RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(1, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterListWithVar) {
std::string const queryString =
"FOR s IN 1..2 LET kk = s "
"FOR d IN testView1 SEARCH d.key == kk RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(1, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(1, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterList) {
std::string const queryString =
"FOR s IN 1..2 "
"FOR d IN testView1 SEARCH d.key == s RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(1, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(1, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterListNonVolatile) {
std::string const queryString =
"FOR s IN 1..20 LET kk = NOEVAL(1) "
"FOR d IN testView1 SEARCH d.key == kk RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(1, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(20, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterQueryNonVolatile) {
std::string const queryString =
"FOR s IN testView0 COLLECT WITH COUNT INTO c LET kk = NOEVAL(c) "
"FOR d IN testView1 SEARCH d.key == kk RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(0, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilityFilterListSubquery) {
std::string const queryString =
"FOR s IN 1..20 LET kk = (FOR v IN testView0 SEARCH v.key == 1 RETURN "
"v.key)[0] "
"FOR d IN testView1 SEARCH d.key == kk RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(20, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilitySortFilterListSubquery) {
std::string const queryString =
"FOR s IN 1..20 LET kk = (FOR v IN testView0 SEARCH v.key == 1 RETURN "
"v.key)[0] "
"FOR d IN testView1 SEARCH d.key == kk SORT BM25(d, kk) RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_TRUE(view->volatility().first);
ASSERT_TRUE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(20, res.data->slice().length());
}
TEST_F(IResearchViewVolatitlityTest, volatilitySortNonVolatileFilter) {
std::string const queryString =
"FOR s IN 1..20 LET kk = (FOR v IN testView0 SEARCH v.key == 1 RETURN "
"v.key)[0] "
"FOR d IN testView1 SEARCH d.key == 1 SORT BM25(d, kk) RETURN d";
auto prepared = arangodb::tests::prepareQuery(*vocbase, queryString);
auto plan = prepared->plan();
ASSERT_NE(nullptr, plan);
::arangodb::containers::SmallVector<
arangodb::aql::ExecutionNode*>::allocator_type::arena_type a;
::arangodb::containers::SmallVector<arangodb::aql::ExecutionNode*> nodes{a};
plan->findNodesOfType(
nodes, {arangodb::aql::ExecutionNode::ENUMERATE_IRESEARCH_VIEW}, true);
ASSERT_EQ(2, nodes.size());
for (auto const* n : nodes) {
arangodb::iresearch::IResearchViewNode const* view =
static_cast<arangodb::iresearch::IResearchViewNode const*>(n);
if (view->view()->name() == "testView1") {
ASSERT_FALSE(view->volatility().first);
ASSERT_TRUE(view->volatility().second);
} else if (view->view()->name() == "testView0") {
ASSERT_FALSE(view->volatility().first);
ASSERT_FALSE(view->volatility().second);
} else {
ASSERT_TRUE(false); // unexpected node
}
}
// check volatility affects results
auto res = arangodb::tests::executeQuery(*vocbase, queryString);
EXPECT_TRUE(res.ok());
EXPECT_TRUE(res.data->slice().isArray());
EXPECT_EQ(20, res.data->slice().length());
}
class IResearchViewBlockTest
: public ::testing::Test,
public arangodb::tests::LogSuppressor<arangodb::Logger::AUTHENTICATION,
arangodb::LogLevel::ERR> {
protected:
arangodb::tests::mocks::MockAqlServer server;
IResearchViewBlockTest() : server(false) {
arangodb::tests::init(true);
server.addFeature<arangodb::FlushFeature>(false);
server.startFeatures();
auto& dbPathFeature = server.getFeature<arangodb::DatabasePathFeature>();
arangodb::tests::setDatabasePath(
dbPathFeature); // ensure test data is stored in a unique directory
auto& dbFeature = server.getFeature<arangodb::DatabaseFeature>();
auto vocbase =
dbFeature.useDatabase(arangodb::StaticStrings::SystemDatabase);
std::shared_ptr<arangodb::LogicalCollection> collection0;
{
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testCollection0\", \"id\" : \"42\" }");
collection0 = vocbase->createCollection(createJson->slice());
EXPECT_NE(nullptr, collection0);
}
auto createJson = arangodb::velocypack::Parser::fromJson(
"{ \"name\": \"testView\", \"type\": \"arangosearch\" }");
auto logicalView = vocbase->createView(createJson->slice());
EXPECT_NE(nullptr, logicalView);
auto updateJson = arangodb::velocypack::Parser::fromJson(
"{ \"links\": {"
"\"testCollection0\": { \"includeAllFields\": true, "
"\"trackListPositions\": true }"
"}}");
EXPECT_TRUE(logicalView->properties(updateJson->slice(), true, true).ok());
std::vector<std::string> EMPTY_VECTOR;
auto trx = std::make_shared<arangodb::transaction::Methods>(
arangodb::transaction::StandaloneContext::Create(*vocbase),
EMPTY_VECTOR, EMPTY_VECTOR, EMPTY_VECTOR,
arangodb::transaction::Options());
EXPECT_TRUE(trx->begin().ok());
// Fill dummy data in index only (to simulate some documents where already
// removed from collection)
arangodb::iresearch::IResearchLinkMeta meta;
meta._includeAllFields = true;
{
auto doc = arangodb::velocypack::Parser::fromJson("{ \"key\": 1 }");
auto indexes = collection0->getIndexes();
EXPECT_FALSE(indexes.empty());
auto* l = static_cast<arangodb::iresearch::IResearchLinkMock*>(
indexes[0].get());
for (size_t i = 2; i < 10; ++i) {
l->insert(*trx, arangodb::LocalDocumentId(i), doc->slice());
}
}
// in collection only one alive doc
auto aliveDoc = arangodb::velocypack::Parser::fromJson("{ \"key\": 1 }");
arangodb::ManagedDocumentResult insertResult;
arangodb::OperationOptions options;
EXPECT_TRUE(
collection0->insert(trx.get(), aliveDoc->slice(), insertResult, options)
.ok());
EXPECT_TRUE(trx->commit().ok());
}
};
TEST_F(IResearchViewBlockTest, retrieveWithMissingInCollectionUnordered) {
auto& dbFeature = server.getFeature<arangodb::DatabaseFeature>();
auto vocbase = dbFeature.useDatabase(arangodb::StaticStrings::SystemDatabase);
auto queryResult = arangodb::tests::executeQuery(
*vocbase, "FOR d IN testView OPTIONS { waitForSync: true } RETURN d");
ASSERT_TRUE(queryResult.result.ok());
auto result = queryResult.data->slice();
EXPECT_TRUE(result.isArray());
arangodb::velocypack::ArrayIterator resultIt(result);
ASSERT_EQ(1, resultIt.size());
}
TEST_F(IResearchViewBlockTest, retrieveWithMissingInCollection) {
auto& dbFeature = server.getFeature<arangodb::DatabaseFeature>();
auto vocbase = dbFeature.useDatabase(arangodb::StaticStrings::SystemDatabase);
auto queryResult = arangodb::tests::executeQuery(
*vocbase,
"FOR d IN testView OPTIONS { waitForSync: true } SORT BM25(d) RETURN d");
ASSERT_TRUE(queryResult.result.ok());
auto result = queryResult.data->slice();
EXPECT_TRUE(result.isArray());
arangodb::velocypack::ArrayIterator resultIt(result);
ASSERT_EQ(1, resultIt.size());
}
| 43.949405 | 80 | 0.628773 | [
"object",
"vector"
] |
f5a3cd22f41c0659c53bd9556b6e48b97d817ed8 | 3,692 | cc | C++ | tensorflow/core/common_runtime/eager/process_function_library_runtime.cc | abhaikollara/tensorflow | 4f96df3659696990cb34d0ad07dc67843c4225a9 | [
"Apache-2.0"
] | 7 | 2018-04-12T07:48:57.000Z | 2021-12-03T12:35:02.000Z | tensorflow/core/common_runtime/eager/process_function_library_runtime.cc | abhaikollara/tensorflow | 4f96df3659696990cb34d0ad07dc67843c4225a9 | [
"Apache-2.0"
] | 6 | 2022-01-15T07:17:47.000Z | 2022-02-14T15:28:22.000Z | tensorflow/core/common_runtime/eager/process_function_library_runtime.cc | abhaikollara/tensorflow | 4f96df3659696990cb34d0ad07dc67843c4225a9 | [
"Apache-2.0"
] | 2 | 2018-04-06T14:28:15.000Z | 2018-11-30T03:53:55.000Z | /* Copyright 2019 The TensorFlow Authors. 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 "tensorflow/core/common_runtime/eager/process_function_library_runtime.h"
#include <iterator>
#include <memory>
#include <utility>
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/util/reffed_status_callback.h"
namespace tensorflow {
namespace eager {
#if !defined(IS_MOBILE_PLATFORM)
Status EagerFunctionArgs::GetLocalArg(const int index, Tensor* val) const {
const absl::optional<Tensor>& arg = tensor_args_->at(index);
if (arg.has_value()) {
*val = arg.value();
return Status::OK();
} else {
return errors::NotFound("Argument ", index, " has no local tensor.");
}
}
Status EagerFunctionArgs::GetRemoteArg(const int index,
RemoteTensorHandle* val) const {
return serialize_remote_handle_(index, val);
}
void EagerProcessFunctionLibraryRuntime::RunRemoteDevice(
const FunctionLibraryRuntime::Options& opts,
FunctionLibraryRuntime::Handle local_handle, const InternalArgsView& args,
std::vector<Tensor>* rets,
FunctionLibraryRuntime::DoneCallback done) const {
if (!rets->empty()) {
done(
errors::Unimplemented("Remote outputs are not supported by "
"EagerClusterFunctionLibraryRuntime yet."));
return;
}
if (!args.local_args.empty()) {
done(
errors::Unimplemented("Local inputs are not by supported by "
"EagerClusterFunctionLibraryRuntime."));
return;
}
if (args.remote_args == nullptr) {
done(
errors::Internal("EagerClusterFunctionLibraryRuntime: remote_args "
"should never be null."));
return;
}
parent_->Run(opts, local_handle, args.remote_args, std::move(done));
}
void EagerProcessFunctionLibraryRuntime::Run(
const FunctionLibraryRuntime::Options& opts,
FunctionLibraryRuntime::Handle handle, const FunctionArgsInterface& args,
std::vector<Tensor>* rets,
FunctionLibraryRuntime::DoneCallback done) const {
auto* cleanup_items = new std::vector<std::unique_ptr<CleanUpItem>>;
done = ApplyCleanUpToDoneCallback(cleanup_items, done);
auto get_component_args = [&args](const ComponentFunctionData& comp_data,
InternalArgs* comp_args) -> Status {
for (int i = 0; i < comp_data.arg_indices_.size(); ++i) {
const int index = comp_data.arg_indices_.at(i);
Tensor tensor;
if (args.GetLocalArg(index, &tensor).ok()) {
comp_args->local_args.push_back(std::move(tensor));
} else {
RemoteTensorHandle remote_handle;
TF_RETURN_IF_ERROR(args.GetRemoteArg(index, &remote_handle));
comp_args->remote_args.push_back(std::move(remote_handle));
}
}
return Status::OK();
};
return RunMultiDevice(opts, handle, rets, cleanup_items, std::move(done),
std::move(get_component_args));
}
#endif // IS_MOBILE_PLATFORM
} // namespace eager
} // namespace tensorflow
| 36.92 | 82 | 0.680119 | [
"vector"
] |
f5a58a8b06c558fb7b303d7c12b1b4c52a8a0d36 | 4,670 | cpp | C++ | src/dxvk/dxvk_openxr.cpp | JenyaFTW/dxvk | 44d16bf16e885da6a020348d5a85981dcba71aaa | [
"Zlib"
] | 66 | 2021-11-10T00:03:12.000Z | 2022-03-31T21:03:22.000Z | src/dxvk/dxvk_openxr.cpp | JenyaFTW/dxvk | 44d16bf16e885da6a020348d5a85981dcba71aaa | [
"Zlib"
] | null | null | null | src/dxvk/dxvk_openxr.cpp | JenyaFTW/dxvk | 44d16bf16e885da6a020348d5a85981dcba71aaa | [
"Zlib"
] | 11 | 2021-11-29T07:56:52.000Z | 2022-03-31T22:45:27.000Z | #include "dxvk_instance.h"
#include "dxvk_openxr.h"
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#endif
using PFN___wineopenxr_GetVulkanInstanceExtensions = int (WINAPI *)(uint32_t, uint32_t *, char *);
using PFN___wineopenxr_GetVulkanDeviceExtensions = int (WINAPI *)(uint32_t, uint32_t *, char *);
namespace dxvk {
struct WineXrFunctions {
PFN___wineopenxr_GetVulkanInstanceExtensions __wineopenxr_GetVulkanInstanceExtensions = nullptr;
PFN___wineopenxr_GetVulkanDeviceExtensions __wineopenxr_GetVulkanDeviceExtensions = nullptr;
};
WineXrFunctions g_winexrFunctions;
DxvkXrProvider DxvkXrProvider::s_instance;
DxvkXrProvider:: DxvkXrProvider() { }
DxvkXrProvider::~DxvkXrProvider() { }
std::string_view DxvkXrProvider::getName() {
return "OpenXR";
}
DxvkNameSet DxvkXrProvider::getInstanceExtensions() {
std::lock_guard<std::mutex> lock(m_mutex);
return m_insExtensions;
}
DxvkNameSet DxvkXrProvider::getDeviceExtensions(uint32_t adapterId) {
std::lock_guard<std::mutex> lock(m_mutex);
return m_devExtensions;
}
void DxvkXrProvider::initInstanceExtensions() {
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_wineOxr)
m_wineOxr = this->loadLibrary();
if (!m_wineOxr || m_initializedInsExt)
return;
if (!this->loadFunctions()) {
this->shutdown();
return;
}
m_insExtensions = this->queryInstanceExtensions();
m_initializedInsExt = true;
}
bool DxvkXrProvider::loadFunctions() {
g_winexrFunctions.__wineopenxr_GetVulkanInstanceExtensions =
reinterpret_cast<PFN___wineopenxr_GetVulkanInstanceExtensions>(this->getSym("__wineopenxr_GetVulkanInstanceExtensions"));
g_winexrFunctions.__wineopenxr_GetVulkanDeviceExtensions =
reinterpret_cast<PFN___wineopenxr_GetVulkanDeviceExtensions>(this->getSym("__wineopenxr_GetVulkanDeviceExtensions"));
return g_winexrFunctions.__wineopenxr_GetVulkanInstanceExtensions != nullptr
&& g_winexrFunctions.__wineopenxr_GetVulkanDeviceExtensions != nullptr;
}
void DxvkXrProvider::initDeviceExtensions(const DxvkInstance* instance) {
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_wineOxr || m_initializedDevExt)
return;
m_devExtensions = this->queryDeviceExtensions();
m_initializedDevExt = true;
this->shutdown();
}
DxvkNameSet DxvkXrProvider::queryInstanceExtensions() const {
int res;
uint32_t len;
res = g_winexrFunctions.__wineopenxr_GetVulkanInstanceExtensions(0, &len, nullptr);
if (res != 0) {
Logger::warn("OpenXR: Unable to get required Vulkan instance extensions size");
return DxvkNameSet();
}
std::vector<char> extensionList(len);
res = g_winexrFunctions.__wineopenxr_GetVulkanInstanceExtensions(len, &len, &extensionList[0]);
if (res != 0) {
Logger::warn("OpenXR: Unable to get required Vulkan instance extensions");
return DxvkNameSet();
}
return parseExtensionList(std::string(extensionList.data(), len));
}
DxvkNameSet DxvkXrProvider::queryDeviceExtensions() const {
int res;
uint32_t len;
res = g_winexrFunctions.__wineopenxr_GetVulkanDeviceExtensions(0, &len, nullptr);
if (res != 0) {
Logger::warn("OpenXR: Unable to get required Vulkan Device extensions size");
return DxvkNameSet();
}
std::vector<char> extensionList(len);
res = g_winexrFunctions.__wineopenxr_GetVulkanDeviceExtensions(len, &len, &extensionList[0]);
if (res != 0) {
Logger::warn("OpenXR: Unable to get required Vulkan Device extensions");
return DxvkNameSet();
}
return parseExtensionList(std::string(extensionList.data(), len));
}
DxvkNameSet DxvkXrProvider::parseExtensionList(const std::string& str) const {
DxvkNameSet result;
std::stringstream strstream(str);
std::string section;
while (std::getline(strstream, section, ' '))
result.add(section.c_str());
return result;
}
void DxvkXrProvider::shutdown() {
if (m_loadedOxrApi)
this->freeLibrary();
m_loadedOxrApi = false;
m_wineOxr = nullptr;
}
HMODULE DxvkXrProvider::loadLibrary() {
HMODULE handle = nullptr;
if (!(handle = ::GetModuleHandle("wineopenxr.dll"))) {
handle = ::LoadLibrary("wineopenxr.dll");
m_loadedOxrApi = handle != nullptr;
}
return handle;
}
void DxvkXrProvider::freeLibrary() {
::FreeLibrary(m_wineOxr);
}
void* DxvkXrProvider::getSym(const char* sym) {
return reinterpret_cast<void*>(
::GetProcAddress(m_wineOxr, sym));
}
}
| 27.633136 | 129 | 0.706638 | [
"vector"
] |
f5a598b54950a29e75073c00f269755c67c6b613 | 4,107 | cpp | C++ | tests/unit_tests/ut_math.cpp | alandefreitas/scistats | 6f20e47b5a8d6f82aa56991889395f12955e5384 | [
"MIT"
] | 3 | 2020-10-28T21:47:31.000Z | 2021-02-06T22:39:05.000Z | tests/unit_tests/ut_math.cpp | alandefreitas/scistats | 6f20e47b5a8d6f82aa56991889395f12955e5384 | [
"MIT"
] | null | null | null | tests/unit_tests/ut_math.cpp | alandefreitas/scistats | 6f20e47b5a8d6f82aa56991889395f12955e5384 | [
"MIT"
] | null | null | null | #include <boost/ut.hpp>
#include <scistats/math/abs.h>
#include <scistats/math/acot.h>
#include <scistats/math/beta.h>
#include <scistats/math/beta_inc.h>
#include <scistats/math/beta_inc_inv.h>
#include <scistats/math/beta_inc_upper.h>
#include <scistats/math/betaln.h>
#include <scistats/math/constants.h>
#include <scistats/math/cot.h>
#include <scistats/math/erfinv.h>
#include <scistats/math/gammaln.h>
#include <scistats/math/is_even.h>
#include <scistats/math/is_odd.h>
#include <scistats/math/prod.h>
#include <scistats/math/sum.h>
#include <scistats/math/xinbta.h>
#include <vector>
int main() {
using namespace boost::ut;
using namespace scistats;
test("Constants") = [&] {
expect(pi<float>() == 3.14_f);
expect(pi<double>() == 3.14_d);
expect(pi<long double>() == 3.14_ld);
expect(pi<double>() == 3.14159_d);
expect(epsilon<double>() == 0.00000_d);
expect(std::isinf(inf<double>()));
expect(almost_equal(min<double>(), std::numeric_limits<double>::min()));
expect(almost_equal(max<double>(), std::numeric_limits<double>::max()));
expect(std::isnan(NaN<double>()));
expect(e<double>() == 2.71828_d);
expect(euler<double>() == 0.577216_d);
expect(log2_e<double>() == 1.4427_d);
expect(log10_e<double>() == 0.434294_d);
expect(sqrt2<double>() == 1.41421_d);
expect(sqrt1_2<double>() == 0.707107_d);
expect(sqrt3<double>() == 1.73205_d);
expect(pi_2<double>() == 1.5708_d);
expect(pi_4<double>() == 0.785398_d);
expect(sqrt_pi<double>() == 1.77245_d);
expect(two_sqrt_pi<double>() == 1.12838_d);
expect(one_by_pi<double>() == 0.31831_d);
expect(two_by_pi<double>() == 0.63662_d);
expect(ln10<double>() == 2.30259_d);
expect(ln2<double>() == 0.693147_d);
expect(lnpi<double>() == 1.14473_d);
};
std::vector<int> x = {6, 1, 1, 2, 3, 2, 1, 3, 2, 4, 2, 2};
std::vector<int> x2 = {29, 46, 58, 42, 2, 43, 20, 84, 84, 74,
45, 88, 51, 67, 54, 30, 73, 69, 39, 13,
16, 88, 45, 24, 22, 64, 77, 87, 77, 84};
test("Sum") = [&] {
expect(sum(x) == 29_i);
expect(sum(x.begin(), x.end()) == 29_i);
expect(sum(execution::seq, x) == 29_i);
expect(sum(execution::par, x) == 29_i);
expect(sum(x2) == 1595_i);
expect(sum(x2.begin(), x2.end()) == 1595_i);
expect(sum(execution::seq, x2) == 1595_i);
expect(sum(execution::par, x2) == 1595_i);
};
test("Prod") = [&] {
expect(prod(x) == 6912_i);
expect(prod(x.begin(), x.end()) == 6912_i);
expect(prod(execution::seq, x) == 6912_i);
expect(prod(execution::par, x) == 6912_i);
};
test("C++ constrained overloads") = [&] {
expect(abs(2 - 6) == 4_i);
expect(abs(2. - 6.) == 4._d);
};
test("Trigonometry") = [&] {
expect(acot(0.) == 1.5708_d);
expect(std::isinf(cot(0.)));
expect(cot(1.) == 0.6420_d);
};
test("Test functions") = [&] {
expect(almost_equal(1., 1.));
expect(is_even(0));
expect(is_odd(1));
expect(is_even(2));
expect(is_odd(3));
expect(is_even(4));
};
test("Special Functions") = [&] {
expect(std::isinf(betaln(0., 1.)));
expect(std::isinf(beta(0., 1.)));
expect(beta_inc(0., 1., 1.) == 0._d);
expect(beta_inc_inv(0., 1., 1.) == 0._d);
expect(beta_inc_upper(0., 1., 1.) == 1._d);
expect(std::isnan(erfinv(42.)));
expect(std::isinf(erfinv(1.)));
expect(std::isinf(erfinv(-1.)));
expect(erfinv(0.5) == 0.476936_d);
expect(std::isnan(erfinv_simple(42.)));
expect(std::isinf(erfinv_simple(1.)));
expect(std::isinf(erfinv_simple(-1.)));
expect(erfinv_simple(0.5) == 0.476996_d);
expect(gammaln(42.) == 114.034_d);
expect(xinbta(1., 1., 0.0, 0.0) == 0.0_d);
expect(xinbta(1., 1., 0.0, 1.0) == 1.0_d);
};
return 0;
}
| 34.805085 | 80 | 0.543219 | [
"vector"
] |
f5a7378cd8ee287f9f4fdb4b3d9962b98a6d8325 | 1,562 | hpp | C++ | contrib/libboost/boost_1_62_0/boost/numeric/odeint/external/vexcl/vexcl_same_instance.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | contrib/libboost/boost_1_62_0/boost/numeric/odeint/external/vexcl/vexcl_same_instance.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | contrib/libboost/boost_1_62_0/boost/numeric/odeint/external/vexcl/vexcl_same_instance.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /*
[auto_generated]
boost/numeric/odeint/external/vexcl/vexcl_same_instance.hpp
[begin_description]
Check if two VexCL containers are the same instance.
[end_description]
Copyright 2009-2011 Karsten Ahnert
Copyright 2009-2011 Mario Mulansky
Distributed under 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)
*/
#ifndef BOOST_NUMERIC_ODEINT_EXTERNAL_VEXCL_VEXCL_SAME_INSTANCE_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_EXTERNAL_VEXCL_VEXCL_SAME_INSTANCE_HPP_INCLUDED
#include <vexcl/vector.hpp>
#include <vexcl/multivector.hpp>
#include <boost/numeric/odeint/util/same_instance.hpp>
namespace boost {
namespace numeric {
namespace odeint {
template <typename T>
struct same_instance_impl< vex::vector<T> , vex::vector<T> >
{
static bool same_instance( const vex::vector<T> &x1 , const vex::vector<T> &x2 )
{
return
static_cast<const vex::vector<T>*>(&x1) ==
static_cast<const vex::vector<T>*>(&x2);
}
};
template <typename T, size_t N>
struct same_instance_impl< vex::multivector<T, N> , vex::multivector<T, N> >
{
static bool same_instance( const vex::multivector<T, N> &x1 , const vex::multivector<T, N> &x2 )
{
return
static_cast<const vex::multivector<T, N>*>(&x1) ==
static_cast<const vex::multivector<T, N>*>(&x2);
}
};
} // namespace odeint
} // namespace numeric
} // namespace boost
#endif // BOOST_NUMERIC_ODEINT_EXTERNAL_VEXCL_VEXCL_SAME_INSTANCE_HPP_INCLUDED
| 26.474576 | 100 | 0.720871 | [
"vector"
] |
f5acb7b59a32f0ea152538ab5f10aaf24018ca18 | 2,538 | cpp | C++ | stichingImages/src/main.cpp | valbuenaster/OpenCV-Codes | c5bd19e36e406ded660ec002c2829fffacbb0759 | [
"MIT"
] | null | null | null | stichingImages/src/main.cpp | valbuenaster/OpenCV-Codes | c5bd19e36e406ded660ec002c2829fffacbb0759 | [
"MIT"
] | null | null | null | stichingImages/src/main.cpp | valbuenaster/OpenCV-Codes | c5bd19e36e406ded660ec002c2829fffacbb0759 | [
"MIT"
] | null | null | null | /*
* main.cpp
*
* Created on: Dec 28, 2020
* Author: Luis
*/
#include <iostream>
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/stitching.hpp"
using namespace std;
using namespace cv;
int processArguments(int argC,char** argV,
bool & divImg,
string & Str,
Stitcher::Mode & mode,
vector<Mat> &vecImages)
{
if(argC == 1)
{
cout << "Wrong input parameters" << endl;
return EXIT_FAILURE;
}
for(int ii = 1; ii < argC; ++ii)
{
if((string(argV[ii]) == "--help")||(string(argV[ii]) == "/?"))
{
cout << "The arguments are the pictures you want stitched and the options after" << endl;
return EXIT_FAILURE;
}else if(string(argV[ii]) == "--d3")
{
divImg = true;
}else if(string(argV[ii]) == "--output")
{
Str = argV[ii+1];
ii++;
}else if(string(argV[ii]) == "--mode")
{
if(string(argV[ii + 1]) == "panorama")
{
mode = Stitcher::PANORAMA;
}else if (string(argV[ii + 1]) == "scans")
{
mode = Stitcher::SCANS;
}else
{
cout << "Bad -- mode flag value" << endl;
return EXIT_FAILURE;
}
ii++;
}else{
cout << argV[ii] << endl;
Mat img = imread(samples::findFile(argV[ii]));
if(img.empty())
{
cout << "Could not read your file:" << argV[ii] << endl;
return EXIT_FAILURE;
}
if(divImg)
{
Rect rect(0, 0, img.cols/2, img.rows);
vecImages.push_back(img(rect).clone());
rect.x = img.cols/3;
vecImages.push_back(img(rect).clone());
rect.x = img.cols/2;
vecImages.push_back(img(rect).clone());
}else{
vecImages.push_back(img);
}
}
}
return EXIT_SUCCESS;
}
int main(int argc, char** argv)
{
bool divide_images = false;
Mat pano;
vector<Mat> Images;
Stitcher::Mode mode = Stitcher::PANORAMA;
string result_name = "result.jpg";
int rValue = processArguments(argc,argv, divide_images, result_name, mode, Images);
if(rValue) return EXIT_FAILURE;
Ptr<Stitcher> stitcher = Stitcher::create(mode);
int counter = 1;
for(auto el: Images)
{
namedWindow("Stitching" + to_string(counter),WINDOW_NORMAL);
imshow("Stitching" + to_string(counter), el);
counter++;
waitKey(0);
}
Stitcher::Status status = stitcher->stitch(Images, pano);
if(status != Stitcher::OK)
{
cout << "Could not stitch images. Sucks, doesn't it? error code = "
<< static_cast<int>(status) << endl;
return EXIT_FAILURE;
}
imwrite(result_name,pano);
cout << "Stitching done successfully, Ciao..." << endl;
return EXIT_SUCCESS;
}
| 21.327731 | 92 | 0.614657 | [
"vector"
] |
f5ad3d54cb9769bb8a107ff4ee09dba7cda90fda | 1,409 | hpp | C++ | sources/LycanthEngine/LycanthEngine/Src/Mesh.hpp | Euxiniar/LycanthEngine | d4c962ddbbb2123778dbb4e1e3104c86eb57f768 | [
"MIT"
] | null | null | null | sources/LycanthEngine/LycanthEngine/Src/Mesh.hpp | Euxiniar/LycanthEngine | d4c962ddbbb2123778dbb4e1e3104c86eb57f768 | [
"MIT"
] | null | null | null | sources/LycanthEngine/LycanthEngine/Src/Mesh.hpp | Euxiniar/LycanthEngine | d4c962ddbbb2123778dbb4e1e3104c86eb57f768 | [
"MIT"
] | null | null | null | #pragma once
#include "Prerequisites.hpp"
#include <cstdint>
#include <misc/formats.h>
#include <array>
namespace Ly
{
class Mesh
{
public:
const unsigned char* get_mesh_data() const;
static Anvil::Format get_mesh_data_color_format();
static uint32_t get_mesh_data_color_start_offset();
static uint32_t get_mesh_data_color_stride();
static Anvil::Format get_mesh_data_position_format();
static uint32_t get_mesh_data_position_start_offset();
static uint32_t get_mesh_data_position_stride();
uint32_t get_mesh_data_size() const;
static uint32_t Mesh::get_mesh_n_vertices();
static void get_luminance_data(std::unique_ptr<float[]>* out_result_ptr,
uint32_t* out_result_size_ptr);
private:
const std::array<float, 21> g_mesh_data =
{
-1.0f, 1.0f, 0.0f, 1.0f, /* position */
0.75f, 0.25f, 0.1f, /* color */
-1.0f, -1.0f, 0.0f, 1.0f, /* position */
0.25f, 0.75f, 0.2f, /* color */
1.0f, -1.0f, 0.0f, 1.0f, /* position */
0.1f, 0.3f, 0.5f, /* color */
};
static const uint32_t g_mesh_data_color_start_offset = sizeof(float) * 4;
static const uint32_t g_mesh_data_color_stride = sizeof(float) * 7;
static const uint32_t g_mesh_data_n_vertices = 3;
static const uint32_t g_mesh_data_position_start_offset = 0;
static const uint32_t g_mesh_data_position_stride = sizeof(float) * 7;
};
} | 32.767442 | 75 | 0.69127 | [
"mesh"
] |
f5ae46b4f98dd5f3198bcb6ef647a74a97c72097 | 80,117 | cpp | C++ | mitab/mitab_feature_mif.cpp | grig27/mitab | 0e87a24116af40cb2ec9b122a531b4043bf5154a | [
"Unlicense"
] | 19 | 2015-04-21T05:34:04.000Z | 2021-12-30T03:03:36.000Z | mitab/mitab_feature_mif.cpp | grig27/mitab | 0e87a24116af40cb2ec9b122a531b4043bf5154a | [
"Unlicense"
] | 1 | 2019-03-07T15:25:14.000Z | 2019-03-07T15:25:14.000Z | mitab/mitab_feature_mif.cpp | grig27/mitab | 0e87a24116af40cb2ec9b122a531b4043bf5154a | [
"Unlicense"
] | 21 | 2015-02-27T10:42:38.000Z | 2021-01-18T10:34:24.000Z | /**********************************************************************
* $Id: mitab_feature_mif.cpp,v 1.39 2010-09-07 16:07:53 aboudreault Exp $
*
* Name: mitab_feature.cpp
* Project: MapInfo TAB Read/Write library
* Language: C++
* Purpose: Implementation of R/W Fcts for (Mid/Mif) in feature classes
* specific to MapInfo files.
* Author: Stephane Villeneuve, stephane.v@videotron.ca
*
**********************************************************************
* Copyright (c) 1999-2002, Stephane Villeneuve
*
* 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.
**********************************************************************
*
* $Log: mitab_feature_mif.cpp,v $
* Revision 1.39 2010-09-07 16:07:53 aboudreault
* Added the use of OGRGeometryFactory::organizePolygons for mif features
*
* Revision 1.38 2010-07-07 19:00:15 aboudreault
* Cleanup Win32 Compile Warnings (GDAL bug #2930)
*
* Revision 1.37 2008-12-17 14:55:20 aboudreault
* Fixed mitab mif/mid importer fails when a Text geometry have an empty
* text value (bug 1978)
*
* Revision 1.36 2008-11-27 20:50:22 aboudreault
* Improved support for OGR date/time types. New Read/Write methods (bug 1948)
* Added support of OGR date/time types for MIF features.
*
* Revision 1.35 2008/09/23 14:56:03 aboudreault
* Fixed an error related to the " character when converting mif to tab file.
*
* Revision 1.34 2008/09/23 13:45:03 aboudreault
* Fixed bug with the characters ",\n in the tab2tab application. (bug 1945)
*
* Revision 1.33 2008/02/01 20:30:59 dmorissette
* Use %.15g instead of %.16g as number precision in .MIF output
*
* Revision 1.32 2007/06/07 20:27:21 dmorissette
* Fixed memory leaks when reading multipoint objects from .MIF files
*
* Revision 1.31 2006/01/27 13:44:44 fwarmerdam
* fixed Mills.mif reading, crash at file end
*
* Revision 1.30 2006/01/26 21:26:36 fwarmerdam
* fixed bug with multi character delimeters in .mid file
*
* Revision 1.29 2005/10/04 19:36:10 dmorissette
* Added support for reading collections from MIF files (bug 1126)
*
* Revision 1.28 2005/10/04 15:44:31 dmorissette
* First round of support for Collection objects. Currently supports reading
* from .TAB/.MAP and writing to .MIF. Still lacks symbol support and write
* support. (Based in part on patch and docs from Jim Hope, bug 1126)
*
* Revision 1.27 2005/10/04 15:35:52 dmorissette
* Fixed an instance of hardcoded delimiter (",") in WriteRecordToMIDFile()
* (patch by KB Kieron, bug 1126)
*
* Revision 1.26 2005/07/14 16:15:05 jlacroix
* \n and \ are now unescaped internally.
*
* Revision 1.25 2003/12/19 07:52:34 fwarmerdam
* write 3d as 2d
*
* Revision 1.24 2002/11/27 22:51:52 daniel
* Bug 1631:Do not produce an error if .mid data records end with a stray ','
* Treat tabs (\t) as a blank space delimiter when reading .mif coordinates
*
* Revision 1.23 2002/10/29 21:09:20 warmerda
* Ensure that a blank line in a mid file is treated as one field containing
* an empty string.
*
* Revision 1.22 2002/04/26 14:16:49 julien
* Finishing the implementation of Multipoint (support for MIF)
*
* Revision 1.21 2002/03/26 01:48:40 daniel
* Added Multipoint object type (V650)
*
* Revision 1.20 2002/01/23 20:31:21 daniel
* Fixed warning produced by CPLAssert() in non-DEBUG mode.
*
* Revision 1.19 2001/06/25 01:50:42 daniel
* Fixed MIF Text object output: negative text angles were lost. Also use
* TABText::SetTextAngle() when reading MIF instead of setting class members
* directly so that negative angles get converted to the [0..360] range.
*
* Revision 1.18 2001/02/28 07:15:09 daniel
* Added support for text label line end point
*
* Revision 1.17 2001/01/22 16:03:58 warmerda
* expanded tabs
*
* Revision 1.16 2000/10/03 19:29:51 daniel
* Include OGR StyleString stuff (implemented by Stephane)
*
* Revision 1.15 2000/09/28 16:39:44 warmerda
* avoid warnings for unused, and unitialized variables
*
* Revision 1.14 2000/09/19 17:23:53 daniel
* Maintain and/or compute valid region and polyline center/label point
*
* Revision 1.13 2000/03/27 03:33:45 daniel
* Treat SYMBOL line as optional when reading TABPoint
*
* Revision 1.12 2000/02/28 16:56:32 daniel
* Support pen width in points (width values 11 to 2047)
*
* Revision 1.11 2000/01/15 22:30:44 daniel
* Switch to MIT/X-Consortium OpenSource license
*
* Revision 1.10 2000/01/14 23:51:37 daniel
* Fixed handling of "\n" in TABText strings... now the external interface
* of the lib returns and expects escaped "\"+"n" as described in MIF specs
*
* Revision 1.9 1999/12/19 17:37:14 daniel
* Fixed memory leaks
*
* Revision 1.8 1999/12/19 01:02:50 stephane
* Add a test on the CENTER information
*
* Revision 1.7 1999/12/18 23:23:23 stephane
* Change the format of the output double from %g to %.16g
*
* Revision 1.6 1999/12/18 08:22:57 daniel
* Removed stray break statement in PLINE MULTIPLE write code
*
* Revision 1.5 1999/12/18 07:21:30 daniel
* Fixed test on geometry type when writing OGRMultiLineStrings
*
* Revision 1.4 1999/12/18 07:11:57 daniel
* Return regions as OGRMultiPolygons instead of multiple rings OGRPolygons
*
* Revision 1.3 1999/12/16 17:16:44 daniel
* Use addRing/GeometryDirectly() (prevents leak), and rounded rectangles
* always return real corner radius from file even if it is bigger than MBR
*
* Revision 1.2 1999/11/11 01:22:05 stephane
* Remove DebugFeature call, Point Reading error, add IsValidFeature() to
* test correctly if we are on a feature
*
* Revision 1.1 1999/11/08 19:20:30 stephane
* First version
*
* Revision 1.1 1999/11/08 04:16:07 stephane
* First Revision
*
*
**********************************************************************/
#include "mitab.h"
#include "mitab_utils.h"
#include <ctype.h>
/*=====================================================================
* class TABFeature
*====================================================================*/
/************************************************************************/
/* MIDTokenize() */
/* */
/* We implement a special tokenize function so we can handle */
/* multibyte delimeters (ie. MITAB bug 1266). */
/* */
/* http://bugzilla.maptools.org/show_bug.cgi?id=1266 */
/************************************************************************/
static char **MIDTokenize( const char *pszLine, const char *pszDelim )
{
char **papszResult = NULL;
int iChar, iTokenChar = 0, bInQuotes = FALSE;
char *pszToken = (char *) CPLMalloc(strlen(pszLine)+1);
int nDelimLen = strlen(pszDelim);
for( iChar = 0; pszLine[iChar] != '\0'; iChar++ )
{
if( bInQuotes && pszLine[iChar] == '"' && pszLine[iChar+1] == '"' )
{
pszToken[iTokenChar++] = '"';
iChar++;
}
else if( pszLine[iChar] == '"' )
{
bInQuotes = !bInQuotes;
}
else if( !bInQuotes && strncmp(pszLine+iChar,pszDelim,nDelimLen) == 0 )
{
pszToken[iTokenChar++] = '\0';
papszResult = CSLAddString( papszResult, pszToken );
iChar += strlen(pszDelim) - 1;
iTokenChar = 0;
}
else
{
pszToken[iTokenChar++] = pszLine[iChar];
}
}
pszToken[iTokenChar++] = '\0';
papszResult = CSLAddString( papszResult, pszToken );
CPLFree( pszToken );
return papszResult;
}
/**********************************************************************
* TABFeature::ReadRecordFromMIDFile()
*
* This method is used to read the Record (Attributs) for all type of
* feature included in a mid/mif file.
*
* Returns 0 on success, -1 on error, in which case CPLError() will have
* been called.
**********************************************************************/
int TABFeature::ReadRecordFromMIDFile(MIDDATAFile *fp)
{
const char *pszLine;
char **papszToken;
int nFields,i;
OGRFieldDefn *poFDefn = NULL;
#ifdef MITAB_USE_OFTDATETIME
int nYear, nMonth, nDay, nHour, nMin, nSec, nMS, nTZFlag;
nYear = nMonth = nDay = nHour = nMin = nSec = nMS = nTZFlag = 0;
#endif
nFields = GetFieldCount();
pszLine = fp->GetLastLine();
if (pszLine == NULL)
{
CPLError(CE_Failure, CPLE_FileIO,
"Unexpected EOF while reading attribute record from MID file.");
return -1;
}
papszToken = MIDTokenize( pszLine, fp->GetDelimiter() );
// Ensure that a blank line in a mid file is treated as one field
// containing an empty string.
if( nFields == 1 && CSLCount(papszToken) == 0 && pszLine[0] == '\0' )
papszToken = CSLAddString(papszToken,"");
// Make sure we found at least the expected number of field values.
// Note that it is possible to have a stray delimiter at the end of
// the line (mif/mid files from Geomedia), so don't produce an error
// if we find more tokens than expected.
if (CSLCount(papszToken) < nFields)
{
CSLDestroy(papszToken);
return -1;
}
for (i=0;i<nFields;i++)
{
poFDefn = GetFieldDefnRef(i);
switch(poFDefn->GetType())
{
#ifdef MITAB_USE_OFTDATETIME
case OFTTime:
{
if (strlen(papszToken[i]) == 9)
{
sscanf(papszToken[i],"%2d%2d%2d%3d",&nHour, &nMin, &nSec, &nMS);
SetField(i, nYear, nMonth, nDay, nHour, nMin, nSec, 0);
}
break;
}
case OFTDate:
{
if (strlen(papszToken[i]) == 8)
{
sscanf(papszToken[i], "%4d%2d%2d", &nYear, &nMonth, &nDay);
SetField(i, nYear, nMonth, nDay, nHour, nMin, nSec, 0);
}
break;
}
case OFTDateTime:
{
if (strlen(papszToken[i]) == 17)
{
sscanf(papszToken[i], "%4d%2d%2d%2d%2d%2d%3d",
&nYear, &nMonth, &nDay, &nHour, &nMin, &nSec, &nMS);
SetField(i, nYear, nMonth, nDay, nHour, nMin, nSec, 0);
}
break;
}
#endif
default:
SetField(i,papszToken[i]);
}
}
fp->GetLine();
CSLDestroy(papszToken);
return 0;
}
/**********************************************************************
* TABFeature::WriteRecordToMIDFile()
*
* This methode is used to write the Record (Attributs) for all type
* of feature included in a mid file.
*
* Return 0 on success, -1 on error
**********************************************************************/
int TABFeature::WriteRecordToMIDFile(MIDDATAFile *fp)
{
int iField, numFields;
OGRFieldDefn *poFDefn = NULL;
#ifdef MITAB_USE_OFTDATETIME
char szBuffer[20];
int nYear, nMonth, nDay, nHour, nMin, nSec, nMS, nTZFlag;
nYear = nMonth = nDay = nHour = nMin = nSec = nMS = nTZFlag = 0;
#endif
CPLAssert(fp);
const char *delimiter = fp->GetDelimiter();
numFields = GetFieldCount();
for(iField=0; iField<numFields; iField++)
{
if (iField != 0)
fp->WriteLine(delimiter);
poFDefn = GetFieldDefnRef( iField );
switch(poFDefn->GetType())
{
case OFTString:
{
int nStringLen = strlen(GetFieldAsString(iField));
char *pszString = (char*)CPLMalloc((nStringLen+1)*sizeof(char));
strcpy(pszString, GetFieldAsString(iField));
char *pszWorkString = (char*)CPLMalloc((2*(nStringLen)+1)*sizeof(char));
int j = 0;
for (int i =0; i < nStringLen; ++i)
{
if (pszString[i] == '"')
{
pszWorkString[j] = pszString[i];
++j;
pszWorkString[j] = pszString[i];
}
else if (pszString[i] == '\n')
{
pszWorkString[j] = '\\';
++j;
pszWorkString[j] = 'n';
}
else
pszWorkString[j] = pszString[i];
++j;
}
pszWorkString[j] = '\0';
CPLFree(pszString);
pszString = (char*)CPLMalloc((strlen(pszWorkString)+1)*sizeof(char));
strcpy(pszString, pszWorkString);
CPLFree(pszWorkString);
fp->WriteLine("\"%s\"",pszString);
CPLFree(pszString);
break;
}
#ifdef MITAB_USE_OFTDATETIME
case OFTTime:
{
if (!IsFieldSet(iField))
{
szBuffer[0] = '\0';
}
else
{
GetFieldAsDateTime(iField, &nYear, &nMonth, &nDay,
&nHour, &nMin, &nSec, &nTZFlag);
sprintf(szBuffer, "%2.2d%2.2d%2.2d%3.3d", nHour, nMin, nSec, nMS);
}
fp->WriteLine("%s",szBuffer);
break;
}
case OFTDate:
{
if (!IsFieldSet(iField))
{
szBuffer[0] = '\0';
}
else
{
GetFieldAsDateTime(iField, &nYear, &nMonth, &nDay,
&nHour, &nMin, &nSec, &nTZFlag);
sprintf(szBuffer, "%4.4d%2.2d%2.2d", nYear, nMonth, nDay);
}
fp->WriteLine("%s",szBuffer);
break;
}
case OFTDateTime:
{
if (!IsFieldSet(iField))
{
szBuffer[0] = '\0';
}
else
{
GetFieldAsDateTime(iField, &nYear, &nMonth, &nDay,
&nHour, &nMin, &nSec, &nTZFlag);
sprintf(szBuffer, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",
nYear, nMonth, nDay, nHour, nMin, nSec, nMS);
}
fp->WriteLine("%s",szBuffer);
break;
}
#endif
default:
fp->WriteLine("%s",GetFieldAsString(iField));
}
}
fp->WriteLine("\n");
return 0;
}
/**********************************************************************
* TABFeature::ReadGeometryFromMIFFile()
*
* In derived classes, this method should be reimplemented to
* fill the geometry and representation (color, etc...) part of the
* feature from the contents of the .MAP object pointed to by poMAPFile.
*
* It is assumed that before calling ReadGeometryFromMAPFile(), poMAPFile
* currently points to the beginning of a map object.
*
* The current implementation does nothing since instances of TABFeature
* objects contain no geometry (i.e. TAB_GEOM_NONE).
*
* Returns 0 on success, -1 on error, in which case CPLError() will have
* been called.
**********************************************************************/
int TABFeature::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
const char *pszLine;
/* Go to the first line of the next feature */
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
;
return 0;
}
/**********************************************************************
* TABFeature::WriteGeometryToMIFFile()
*
*
* In derived classes, this method should be reimplemented to
* write the geometry and representation (color, etc...) part of the
* feature to the .MAP object pointed to by poMAPFile.
*
* It is assumed that before calling WriteGeometryToMAPFile(), poMAPFile
* currently points to a valid map object.
*
* The current implementation does nothing since instances of TABFeature
* objects contain no geometry.
*
* Returns 0 on success, -1 on error, in which case CPLError() will have
* been called.
**********************************************************************/
int TABFeature::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
fp->WriteLine("NONE\n");
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABPoint::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeometry;
char **papszToken;
const char *pszLine;
double dfX,dfY;
papszToken = CSLTokenizeString2(fp->GetSavedLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=3)
{
CSLDestroy(papszToken);
return -1;
}
dfX = fp->GetXTrans(atof(papszToken[1]));
dfY = fp->GetYTrans(atof(papszToken[2]));
CSLDestroy(papszToken);
papszToken = NULL;
// Read optional SYMBOL line...
pszLine = fp->GetLastLine();
if( pszLine != NULL )
papszToken = CSLTokenizeStringComplex(pszLine," ,()\t",
TRUE,FALSE);
if (CSLCount(papszToken) == 4 && EQUAL(papszToken[0], "SYMBOL") )
{
SetSymbolNo((GInt16)atoi(papszToken[1]));
SetSymbolColor((GInt32)atoi(papszToken[2]));
SetSymbolSize((GInt16)atoi(papszToken[3]));
}
CSLDestroy(papszToken);
papszToken = NULL;
// scan until we reach 1st line of next feature
// Since SYMBOL is optional, we have to test IsValidFeature() on that
// line as well.
while (pszLine && fp->IsValidFeature(pszLine) == FALSE)
{
pszLine = fp->GetLine();
}
poGeometry = new OGRPoint(dfX, dfY);
SetGeometryDirectly(poGeometry);
SetMBR(dfX, dfY, dfX, dfY);
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABPoint::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGRPoint *poPoint;
/*-----------------------------------------------------------------
* Fetch and validate geometry
*----------------------------------------------------------------*/
poGeom = GetGeometryRef();
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint)
poPoint = (OGRPoint*)poGeom;
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABPoint: Missing or Invalid Geometry!");
return -1;
}
fp->WriteLine("Point %.15g %.15g\n",poPoint->getX(),poPoint->getY());
fp->WriteLine(" Symbol (%d,%d,%d)\n",GetSymbolNo(),GetSymbolColor(),
GetSymbolSize());
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABFontPoint::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeometry;
char **papszToken;
const char *pszLine;
double dfX,dfY;
papszToken = CSLTokenizeString2(fp->GetSavedLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=3)
{
CSLDestroy(papszToken);
return -1;
}
dfX = fp->GetXTrans(atof(papszToken[1]));
dfY = fp->GetYTrans(atof(papszToken[2]));
CSLDestroy(papszToken);
papszToken = CSLTokenizeStringComplex(fp->GetLastLine()," ,()\t",
TRUE,FALSE);
if (CSLCount(papszToken) !=7)
{
CSLDestroy(papszToken);
return -1;
}
SetSymbolNo((GInt16)atoi(papszToken[1]));
SetSymbolColor((GInt32)atoi(papszToken[2]));
SetSymbolSize((GInt16)atoi(papszToken[3]));
SetFontName(papszToken[4]);
SetFontStyleMIFValue(atoi(papszToken[5]));
SetSymbolAngle(atof(papszToken[6]));
CSLDestroy(papszToken);
poGeometry = new OGRPoint(dfX, dfY);
SetGeometryDirectly(poGeometry);
SetMBR(dfX, dfY, dfX, dfY);
/* Go to the first line of the next feature */
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
;
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABFontPoint::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGRPoint *poPoint;
/*-----------------------------------------------------------------
* Fetch and validate geometry
*----------------------------------------------------------------*/
poGeom = GetGeometryRef();
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint)
poPoint = (OGRPoint*)poGeom;
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABFontPoint: Missing or Invalid Geometry!");
return -1;
}
fp->WriteLine("Point %.15g %.15g\n",poPoint->getX(),poPoint->getY());
fp->WriteLine(" Symbol (%d,%d,%d,\"%s\",%d,%.15g)\n",
GetSymbolNo(),GetSymbolColor(),
GetSymbolSize(),GetFontNameRef(),GetFontStyleMIFValue(),
GetSymbolAngle());
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABCustomPoint::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeometry;
char **papszToken;
const char *pszLine;
double dfX,dfY;
papszToken = CSLTokenizeString2(fp->GetSavedLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=3)
{
CSLDestroy(papszToken);
return -1;
}
dfX = fp->GetXTrans(atof(papszToken[1]));
dfY = fp->GetYTrans(atof(papszToken[2]));
CSLDestroy(papszToken);
papszToken = CSLTokenizeStringComplex(fp->GetLastLine()," ,()\t",
TRUE,FALSE);
if (CSLCount(papszToken) !=5)
{
CSLDestroy(papszToken);
return -1;
}
SetFontName(papszToken[1]);
SetSymbolColor((GInt32)atoi(papszToken[2]));
SetSymbolSize((GInt16)atoi(papszToken[3]));
m_nCustomStyle = (GByte)atoi(papszToken[4]);
CSLDestroy(papszToken);
poGeometry = new OGRPoint(dfX, dfY);
SetGeometryDirectly(poGeometry);
SetMBR(dfX, dfY, dfX, dfY);
/* Go to the first line of the next feature */
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
;
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABCustomPoint::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGRPoint *poPoint;
/*-----------------------------------------------------------------
* Fetch and validate geometry
*----------------------------------------------------------------*/
poGeom = GetGeometryRef();
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint)
poPoint = (OGRPoint*)poGeom;
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABCustomPoint: Missing or Invalid Geometry!");
return -1;
}
fp->WriteLine("Point %.15g %.15g\n",poPoint->getX(),poPoint->getY());
fp->WriteLine(" Symbol (\"%s\",%d,%d,%d)\n",GetFontNameRef(),
GetSymbolColor(), GetSymbolSize(),m_nCustomStyle);
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABPolyline::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
const char *pszLine;
char **papszToken;
OGRLineString *poLine;
OGRMultiLineString *poMultiLine;
GBool bMultiple = FALSE;
int nNumPoints,nNumSec=0,i,j;
OGREnvelope sEnvelope;
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) < 1)
{
CSLDestroy(papszToken);
return -1;
}
if (EQUALN(papszToken[0],"LINE",4))
{
if (CSLCount(papszToken) != 5)
return -1;
poLine = new OGRLineString();
poLine->setNumPoints(2);
poLine->setPoint(0, fp->GetXTrans(atof(papszToken[1])),
fp->GetYTrans(atof(papszToken[2])));
poLine->setPoint(1, fp->GetXTrans(atof(papszToken[3])),
fp->GetYTrans(atof(papszToken[4])));
SetGeometryDirectly(poLine);
poLine->getEnvelope(&sEnvelope);
SetMBR(sEnvelope.MinX, sEnvelope.MinY,sEnvelope.MaxX,sEnvelope.MaxY);
}
else if (EQUALN(papszToken[0],"PLINE",5))
{
switch (CSLCount(papszToken))
{
case 1:
bMultiple = FALSE;
pszLine = fp->GetLine();
nNumPoints = atoi(pszLine);
break;
case 2:
bMultiple = FALSE;
nNumPoints = atoi(papszToken[1]);
break;
case 3:
if (EQUALN(papszToken[1],"MULTIPLE",8))
{
bMultiple = TRUE;
nNumSec = atoi(papszToken[2]);
pszLine = fp->GetLine();
nNumPoints = atoi(pszLine);
break;
}
else
{
CSLDestroy(papszToken);
return -1;
}
break;
case 4:
if (EQUALN(papszToken[1],"MULTIPLE",8))
{
bMultiple = TRUE;
nNumSec = atoi(papszToken[2]);
nNumPoints = atoi(papszToken[3]);
break;
}
else
{
CSLDestroy(papszToken);
return -1;
}
break;
default:
CSLDestroy(papszToken);
return -1;
break;
}
if (bMultiple)
{
poMultiLine = new OGRMultiLineString();
for (j=0;j<nNumSec;j++)
{
poLine = new OGRLineString();
if (j != 0)
nNumPoints = atoi(fp->GetLine());
if (nNumPoints < 2)
{
CPLError(CE_Failure, CPLE_FileIO,
"Invalid number of vertices (%d) in PLINE "
"MULTIPLE segment.", nNumPoints);
return -1;
}
poLine->setNumPoints(nNumPoints);
for (i=0;i<nNumPoints;i++)
{
CSLDestroy(papszToken);
papszToken = CSLTokenizeString2(fp->GetLine(),
" \t", CSLT_HONOURSTRINGS);
poLine->setPoint(i,fp->GetXTrans(atof(papszToken[0])),
fp->GetYTrans(atof(papszToken[1])));
}
if (poMultiLine->addGeometryDirectly(poLine) != OGRERR_NONE)
{
CPLAssert(FALSE); // Just in case OGR is modified
}
}
if (SetGeometryDirectly(poMultiLine) != OGRERR_NONE)
{
CPLAssert(FALSE); // Just in case OGR is modified
}
poMultiLine->getEnvelope(&sEnvelope);
SetMBR(sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX,sEnvelope.MaxY);
}
else
{
poLine = new OGRLineString();
poLine->setNumPoints(nNumPoints);
for (i=0;i<nNumPoints;i++)
{
CSLDestroy(papszToken);
papszToken = CSLTokenizeString2(fp->GetLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) != 2)
return -1;
poLine->setPoint(i,fp->GetXTrans(atof(papszToken[0])),
fp->GetYTrans(atof(papszToken[1])));
}
SetGeometryDirectly(poLine);
poLine->getEnvelope(&sEnvelope);
SetMBR(sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX,sEnvelope.MaxY);
}
}
CSLDestroy(papszToken);
papszToken = NULL;
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine,"() ,",
TRUE,FALSE);
if (CSLCount(papszToken) >= 1)
{
if (EQUALN(papszToken[0],"PEN",3))
{
if (CSLCount(papszToken) == 4)
{
SetPenWidthMIF(atoi(papszToken[1]));
SetPenPattern((GByte)atoi(papszToken[2]));
SetPenColor((GInt32)atoi(papszToken[3]));
}
}
else if (EQUALN(papszToken[0],"SMOOTH",6))
{
m_bSmooth = TRUE;
}
}
CSLDestroy(papszToken);
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABPolyline::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGRMultiLineString *poMultiLine = NULL;
OGRLineString *poLine = NULL;
int nNumPoints,i;
/*-----------------------------------------------------------------
* Fetch and validate geometry
*----------------------------------------------------------------*/
poGeom = GetGeometryRef();
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbLineString)
{
/*-------------------------------------------------------------
* Simple polyline
*------------------------------------------------------------*/
poLine = (OGRLineString*)poGeom;
nNumPoints = poLine->getNumPoints();
if (nNumPoints == 2)
{
fp->WriteLine("Line %.15g %.15g %.15g %.15g\n",poLine->getX(0),poLine->getY(0),
poLine->getX(1),poLine->getY(1));
}
else
{
fp->WriteLine("Pline %d\n",nNumPoints);
for (i=0;i<nNumPoints;i++)
{
fp->WriteLine("%.15g %.15g\n",poLine->getX(i),poLine->getY(i));
}
}
}
else if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbMultiLineString)
{
/*-------------------------------------------------------------
* Multiple polyline... validate all components
*------------------------------------------------------------*/
int iLine, numLines;
poMultiLine = (OGRMultiLineString*)poGeom;
numLines = poMultiLine->getNumGeometries();
fp->WriteLine("PLINE MULTIPLE %d\n", numLines);
for(iLine=0; iLine < numLines; iLine++)
{
poGeom = poMultiLine->getGeometryRef(iLine);
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbLineString)
{
poLine = (OGRLineString*)poGeom;
nNumPoints = poLine->getNumPoints();
fp->WriteLine(" %d\n",nNumPoints);
for (i=0;i<nNumPoints;i++)
{
fp->WriteLine("%.15g %.15g\n",poLine->getX(i),poLine->getY(i));
}
}
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABPolyline: Object contains an invalid Geometry!");
}
}
}
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABPolyline: Missing or Invalid Geometry!");
}
if (GetPenPattern())
fp->WriteLine(" Pen (%d,%d,%d)\n",GetPenWidthMIF(),GetPenPattern(),
GetPenColor());
if (m_bSmooth)
fp->WriteLine(" Smooth\n");
return 0;
}
/**********************************************************************
* TABRegion::ReadGeometryFromMIFFile()
*
* Fill the geometry and representation (color, etc...) part of the
* feature from the contents of the .MIF file
*
* Returns 0 on success, -1 on error, in which case CPLError() will have
* been called.
**********************************************************************/
int TABRegion::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
double dX, dY;
OGRLinearRing *poRing;
OGRGeometry *poGeometry = NULL;
OGRPolygon **tabPolygons = NULL;
int i,iSection, numLineSections=0;
char **papszToken;
const char *pszLine;
OGREnvelope sEnvelope;
m_bSmooth = FALSE;
/*=============================================================
* REGION (Similar to PLINE MULTIPLE)
*============================================================*/
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) ==2)
numLineSections = atoi(papszToken[1]);
CSLDestroy(papszToken);
papszToken = NULL;
if (numLineSections > 0)
tabPolygons = new OGRPolygon*[numLineSections];
for(iSection=0; iSection<numLineSections; iSection++)
{
int numSectionVertices = 0;
tabPolygons[iSection] = new OGRPolygon();
if ((pszLine = fp->GetLine()) != NULL)
{
numSectionVertices = atoi(pszLine);
}
poRing = new OGRLinearRing();
poRing->setNumPoints(numSectionVertices);
for(i=0; i<numSectionVertices; i++)
{
pszLine = fp->GetLine();
if (pszLine)
{
papszToken = CSLTokenizeStringComplex(pszLine," ,\t",
TRUE,FALSE);
if (CSLCount(papszToken) == 2)
{
dX = fp->GetXTrans(atof(papszToken[0]));
dY = fp->GetYTrans(atof(papszToken[1]));
poRing->setPoint(i, dX, dY);
}
CSLDestroy(papszToken);
papszToken = NULL;
}
}
tabPolygons[iSection]->addRingDirectly(poRing);
if (numLineSections == 1)
poGeometry = tabPolygons[iSection];
poRing = NULL;
}
if (numLineSections > 1)
{
int isValidGeometry;
const char* papszOptions[] = { "METHOD=DEFAULT", NULL };
poGeometry = OGRGeometryFactory::organizePolygons(
(OGRGeometry**)tabPolygons, numLineSections, &isValidGeometry, papszOptions );
if (!isValidGeometry)
{
CPLError(CE_Warning, CPLE_AppDefined,
"Geometry of polygon cannot be translated to Simple Geometry. "
"All polygons will be contained in a multipolygon.\n");
}
}
if (tabPolygons)
delete[] tabPolygons;
SetGeometryDirectly(poGeometry);
poGeometry->getEnvelope(&sEnvelope);
SetMBR(sEnvelope.MinX, sEnvelope.MinY, sEnvelope.MaxX, sEnvelope.MaxY);
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine,"() ,",
TRUE,FALSE);
if (CSLCount(papszToken) > 1)
{
if (EQUALN(papszToken[0],"PEN",3))
{
if (CSLCount(papszToken) == 4)
{
SetPenWidthMIF(atoi(papszToken[1]));
SetPenPattern((GByte)atoi(papszToken[2]));
SetPenColor((GInt32)atoi(papszToken[3]));
}
}
else if (EQUALN(papszToken[0],"BRUSH", 5))
{
if (CSLCount(papszToken) >= 3)
{
SetBrushFGColor((GInt32)atoi(papszToken[2]));
SetBrushPattern((GByte)atoi(papszToken[1]));
if (CSLCount(papszToken) == 4)
SetBrushBGColor(atoi(papszToken[3]));
else
SetBrushTransparent(TRUE);
}
}
else if (EQUALN(papszToken[0],"CENTER",6))
{
if (CSLCount(papszToken) == 3)
{
SetCenter(fp->GetXTrans(atof(papszToken[1])),
fp->GetYTrans(atof(papszToken[2])) );
}
}
}
CSLDestroy(papszToken);
papszToken = NULL;
}
return 0;
}
/**********************************************************************
* TABRegion::WriteGeometryToMIFFile()
*
* Write the geometry and representation (color, etc...) part of the
* feature to the .MIF file
*
* Returns 0 on success, -1 on error, in which case CPLError() will have
* been called.
**********************************************************************/
int TABRegion::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
poGeom = GetGeometryRef();
if (poGeom && (wkbFlatten(poGeom->getGeometryType()) == wkbPolygon ||
wkbFlatten(poGeom->getGeometryType()) == wkbMultiPolygon ) )
{
/*=============================================================
* REGIONs are similar to PLINE MULTIPLE
*
* We accept both OGRPolygons (with one or multiple rings) and
* OGRMultiPolygons as input.
*============================================================*/
int i, iRing, numRingsTotal, numPoints;
numRingsTotal = GetNumRings();
fp->WriteLine("Region %d\n",numRingsTotal);
for(iRing=0; iRing < numRingsTotal; iRing++)
{
OGRLinearRing *poRing;
poRing = GetRingRef(iRing);
if (poRing == NULL)
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABRegion: Object Geometry contains NULL rings!");
return -1;
}
numPoints = poRing->getNumPoints();
fp->WriteLine(" %d\n",numPoints);
for(i=0; i<numPoints; i++)
{
fp->WriteLine("%.15g %.15g\n",poRing->getX(i), poRing->getY(i));
}
}
if (GetPenPattern())
fp->WriteLine(" Pen (%d,%d,%d)\n",
GetPenWidthMIF(),GetPenPattern(),
GetPenColor());
if (GetBrushPattern())
{
if (GetBrushTransparent() == 0)
fp->WriteLine(" Brush (%d,%d,%d)\n",GetBrushPattern(),
GetBrushFGColor(),GetBrushBGColor());
else
fp->WriteLine(" Brush (%d,%d)\n",GetBrushPattern(),
GetBrushFGColor());
}
if (m_bCenterIsSet)
{
fp->WriteLine(" Center %.15g %.15g\n", m_dCenterX, m_dCenterY);
}
}
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABRegion: Object contains an invalid Geometry!");
return -1;
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABRectangle::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
const char *pszLine;
char **papszToken;
double dXMin, dYMin, dXMax, dYMax;
OGRPolygon *poPolygon;
OGRLinearRing *poRing;
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) < 5)
{
CSLDestroy(papszToken);
return -1;
}
dXMin = fp->GetXTrans(atof(papszToken[1]));
dXMax = fp->GetXTrans(atof(papszToken[3]));
dYMin = fp->GetYTrans(atof(papszToken[2]));
dYMax = fp->GetYTrans(atof(papszToken[4]));
/*-----------------------------------------------------------------
* Call SetMBR() and GetMBR() now to make sure that min values are
* really smaller than max values.
*----------------------------------------------------------------*/
SetMBR(dXMin, dYMin, dXMax, dYMax);
GetMBR(dXMin, dYMin, dXMax, dYMax);
m_bRoundCorners = FALSE;
m_dRoundXRadius = 0.0;
m_dRoundYRadius = 0.0;
if (EQUALN(papszToken[0],"ROUNDRECT",9))
{
m_bRoundCorners = TRUE;
if (CSLCount(papszToken) == 6)
m_dRoundXRadius = m_dRoundYRadius = atof(papszToken[5])/2.0;
else
{
CSLDestroy(papszToken);
papszToken = CSLTokenizeString2(fp->GetLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=1 )
m_dRoundXRadius = m_dRoundYRadius = atof(papszToken[1])/2.0;
}
}
CSLDestroy(papszToken);
papszToken = NULL;
/*-----------------------------------------------------------------
* Create and fill geometry object
*----------------------------------------------------------------*/
poPolygon = new OGRPolygon;
poRing = new OGRLinearRing();
if (m_bRoundCorners && m_dRoundXRadius != 0.0 && m_dRoundYRadius != 0.0)
{
/*-------------------------------------------------------------
* For rounded rectangles, we generate arcs with 45 line
* segments for each corner. We start with lower-left corner
* and proceed counterclockwise
* We also have to make sure that rounding radius is not too
* large for the MBR however, we
* always return the true X/Y radius (not adjusted) since this
* is the way MapInfo seems to do it when a radius bigger than
* the MBR is passed from TBA to MIF.
*------------------------------------------------------------*/
double dXRadius = MIN(m_dRoundXRadius, (dXMax-dXMin)/2.0);
double dYRadius = MIN(m_dRoundYRadius, (dYMax-dYMin)/2.0);
TABGenerateArc(poRing, 45,
dXMin + dXRadius, dYMin + dYRadius, dXRadius, dYRadius,
PI, 3.0*PI/2.0);
TABGenerateArc(poRing, 45,
dXMax - dXRadius, dYMin + dYRadius, dXRadius, dYRadius,
3.0*PI/2.0, 2.0*PI);
TABGenerateArc(poRing, 45,
dXMax - dXRadius, dYMax - dYRadius, dXRadius, dYRadius,
0.0, PI/2.0);
TABGenerateArc(poRing, 45,
dXMin + dXRadius, dYMax - dYRadius, dXRadius, dYRadius,
PI/2.0, PI);
TABCloseRing(poRing);
}
else
{
poRing->addPoint(dXMin, dYMin);
poRing->addPoint(dXMax, dYMin);
poRing->addPoint(dXMax, dYMax);
poRing->addPoint(dXMin, dYMax);
poRing->addPoint(dXMin, dYMin);
}
poPolygon->addRingDirectly(poRing);
SetGeometryDirectly(poPolygon);
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine,"() ,",
TRUE,FALSE);
if (CSLCount(papszToken) > 1)
{
if (EQUALN(papszToken[0],"PEN",3))
{
if (CSLCount(papszToken) == 4)
{
SetPenWidthMIF(atoi(papszToken[1]));
SetPenPattern((GByte)atoi(papszToken[2]));
SetPenColor((GInt32)atoi(papszToken[3]));
}
}
else if (EQUALN(papszToken[0],"BRUSH", 5))
{
if (CSLCount(papszToken) >=3)
{
SetBrushFGColor((GInt32)atoi(papszToken[2]));
SetBrushPattern((GByte)atoi(papszToken[1]));
if (CSLCount(papszToken) == 4)
SetBrushBGColor(atoi(papszToken[3]));
else
SetBrushTransparent(TRUE);
}
}
}
CSLDestroy(papszToken);
papszToken = NULL;
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABRectangle::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGRPolygon *poPolygon;
OGREnvelope sEnvelope;
/*-----------------------------------------------------------------
* Fetch and validate geometry
*----------------------------------------------------------------*/
poGeom = GetGeometryRef();
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPolygon)
poPolygon = (OGRPolygon*)poGeom;
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABRectangle: Missing or Invalid Geometry!");
return -1;
}
/*-----------------------------------------------------------------
* Note that we will simply use the rectangle's MBR and don't really
* read the polygon geometry... this should be OK unless the
* polygon geometry was not really a rectangle.
*----------------------------------------------------------------*/
poPolygon->getEnvelope(&sEnvelope);
if (m_bRoundCorners == TRUE)
{
fp->WriteLine("Roundrect %.15g %.15g %.15g %.15g %.15g\n",
sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX, sEnvelope.MaxY, m_dRoundXRadius*2.0);
}
else
{
fp->WriteLine("Rect %.15g %.15g %.15g %.15g\n",
sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX, sEnvelope.MaxY);
}
if (GetPenPattern())
fp->WriteLine(" Pen (%d,%d,%d)\n",GetPenWidthMIF(),GetPenPattern(),
GetPenColor());
if (GetBrushPattern())
{
if (GetBrushTransparent() == 0)
fp->WriteLine(" Brush (%d,%d,%d)\n",GetBrushPattern(),
GetBrushFGColor(),GetBrushBGColor());
else
fp->WriteLine(" Brush (%d,%d)\n",GetBrushPattern(),
GetBrushFGColor());
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABEllipse::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
const char *pszLine;
char **papszToken;
double dXMin, dYMin, dXMax, dYMax;
OGRPolygon *poPolygon;
OGRLinearRing *poRing;
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) != 5)
{
CSLDestroy(papszToken);
return -1;
}
dXMin = fp->GetXTrans(atof(papszToken[1]));
dXMax = fp->GetXTrans(atof(papszToken[3]));
dYMin = fp->GetYTrans(atof(papszToken[2]));
dYMax = fp->GetYTrans(atof(papszToken[4]));
CSLDestroy(papszToken);
papszToken = NULL;
/*-----------------------------------------------------------------
* Save info about the ellipse def. inside class members
*----------------------------------------------------------------*/
m_dCenterX = (dXMin + dXMax) / 2.0;
m_dCenterY = (dYMin + dYMax) / 2.0;
m_dXRadius = ABS( (dXMax - dXMin) / 2.0 );
m_dYRadius = ABS( (dYMax - dYMin) / 2.0 );
SetMBR(dXMin, dYMin, dXMax, dYMax);
/*-----------------------------------------------------------------
* Create and fill geometry object
*----------------------------------------------------------------*/
poPolygon = new OGRPolygon;
poRing = new OGRLinearRing();
/*-----------------------------------------------------------------
* For the OGR geometry, we generate an ellipse with 2 degrees line
* segments.
*----------------------------------------------------------------*/
TABGenerateArc(poRing, 180,
m_dCenterX, m_dCenterY,
m_dXRadius, m_dYRadius,
0.0, 2.0*PI);
TABCloseRing(poRing);
poPolygon->addRingDirectly(poRing);
SetGeometryDirectly(poPolygon);
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine,"() ,",
TRUE,FALSE);
if (CSLCount(papszToken) > 1)
{
if (EQUALN(papszToken[0],"PEN",3))
{
if (CSLCount(papszToken) == 4)
{
SetPenWidthMIF(atoi(papszToken[1]));
SetPenPattern((GByte)atoi(papszToken[2]));
SetPenColor((GInt32)atoi(papszToken[3]));
}
}
else if (EQUALN(papszToken[0],"BRUSH", 5))
{
if (CSLCount(papszToken) >= 3)
{
SetBrushFGColor((GInt32)atoi(papszToken[2]));
SetBrushPattern((GByte)atoi(papszToken[1]));
if (CSLCount(papszToken) == 4)
SetBrushBGColor(atoi(papszToken[3]));
else
SetBrushTransparent(TRUE);
}
}
}
CSLDestroy(papszToken);
papszToken = NULL;
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABEllipse::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGREnvelope sEnvelope;
poGeom = GetGeometryRef();
if ( (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPolygon ) ||
(poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint ) )
poGeom->getEnvelope(&sEnvelope);
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABEllipse: Missing or Invalid Geometry!");
return -1;
}
fp->WriteLine("Ellipse %.15g %.15g %.15g %.15g\n",sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX,sEnvelope.MaxY);
if (GetPenPattern())
fp->WriteLine(" Pen (%d,%d,%d)\n",GetPenWidthMIF(),GetPenPattern(),
GetPenColor());
if (GetBrushPattern())
{
if (GetBrushTransparent() == 0)
fp->WriteLine(" Brush (%d,%d,%d)\n",GetBrushPattern(),
GetBrushFGColor(),GetBrushBGColor());
else
fp->WriteLine(" Brush (%d,%d)\n",GetBrushPattern(),
GetBrushFGColor());
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABArc::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
const char *pszLine;
OGRLineString *poLine;
char **papszToken;
double dXMin,dXMax, dYMin,dYMax;
int numPts;
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) == 5)
{
dXMin = fp->GetXTrans(atof(papszToken[1]));
dXMax = fp->GetXTrans(atof(papszToken[3]));
dYMin = fp->GetYTrans(atof(papszToken[2]));
dYMax = fp->GetYTrans(atof(papszToken[4]));
CSLDestroy(papszToken);
papszToken = CSLTokenizeString2(fp->GetLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) != 2)
{
CSLDestroy(papszToken);
return -1;
}
m_dStartAngle = atof(papszToken[0]);
m_dEndAngle = atof(papszToken[1]);
}
else if (CSLCount(papszToken) == 7)
{
dXMin = fp->GetXTrans(atof(papszToken[1]));
dXMax = fp->GetXTrans(atof(papszToken[3]));
dYMin = fp->GetYTrans(atof(papszToken[2]));
dYMax = fp->GetYTrans(atof(papszToken[4]));
m_dStartAngle = atof(papszToken[5]);
m_dEndAngle = atof(papszToken[6]);
}
else
{
CSLDestroy(papszToken);
return -1;
}
CSLDestroy(papszToken);
papszToken = NULL;
/*-------------------------------------------------------------
* Start/End angles
* Since the angles are specified for integer coordinates, and
* that these coordinates can have the X axis reversed, we have to
* adjust the angle values for the change in the X axis
* direction.
*
* This should be necessary only when X axis is flipped.
* __TODO__ Why is order of start/end values reversed as well???
*------------------------------------------------------------*/
if (fp->GetXMultiplier() <= 0.0)
{
m_dStartAngle = 360.0 - m_dStartAngle;
m_dEndAngle = 360.0 - m_dEndAngle;
}
m_dCenterX = (dXMin + dXMax) / 2.0;
m_dCenterY = (dYMin + dYMax) / 2.0;
m_dXRadius = ABS( (dXMax - dXMin) / 2.0 );
m_dYRadius = ABS( (dYMax - dYMin) / 2.0 );
/*-----------------------------------------------------------------
* Create and fill geometry object
* For the OGR geometry, we generate an arc with 2 degrees line
* segments.
*----------------------------------------------------------------*/
poLine = new OGRLineString;
if (m_dEndAngle < m_dStartAngle)
numPts = (int) ABS( ((m_dEndAngle+360.0)-m_dStartAngle)/2.0 ) + 1;
else
numPts = (int) ABS( (m_dEndAngle-m_dStartAngle)/2.0 ) + 1;
numPts = MAX(2, numPts);
TABGenerateArc(poLine, numPts,
m_dCenterX, m_dCenterY,
m_dXRadius, m_dYRadius,
m_dStartAngle*PI/180.0, m_dEndAngle*PI/180.0);
SetMBR(dXMin, dYMin, dXMax, dYMax);
SetGeometryDirectly(poLine);
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine,"() ,",
TRUE,FALSE);
if (CSLCount(papszToken) > 1)
{
if (EQUALN(papszToken[0],"PEN",3))
{
if (CSLCount(papszToken) == 4)
{
SetPenWidthMIF(atoi(papszToken[1]));
SetPenPattern((GByte)atoi(papszToken[2]));
SetPenColor((GInt32)atoi(papszToken[3]));
}
}
}
CSLDestroy(papszToken);
papszToken = NULL;
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABArc::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
/*-------------------------------------------------------------
* Start/End angles
* Since we ALWAYS produce files in quadrant 1 then we can
* ignore the special angle conversion required by flipped axis.
*------------------------------------------------------------*/
// Write the Arc's actual MBR
fp->WriteLine("Arc %.15g %.15g %.15g %.15g\n", m_dCenterX-m_dXRadius,
m_dCenterY-m_dYRadius, m_dCenterX+m_dXRadius,
m_dCenterY+m_dYRadius);
fp->WriteLine(" %.15g %.15g\n",m_dStartAngle,m_dEndAngle);
if (GetPenPattern())
fp->WriteLine(" Pen (%d,%d,%d)\n",GetPenWidthMIF(),GetPenPattern(),
GetPenColor());
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABText::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
double dXMin, dYMin, dXMax, dYMax;
OGRGeometry *poGeometry;
const char *pszLine;
char **papszToken;
const char *pszString;
char *pszTmpString;
int bXYBoxRead = 0;
int tokenLen;
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) == 1)
{
CSLDestroy(papszToken);
papszToken = CSLTokenizeString2(fp->GetLine(),
" \t", CSLT_HONOURSTRINGS);
tokenLen = CSLCount(papszToken);
if (tokenLen == 4)
{
pszString = NULL;
bXYBoxRead = 1;
}
else if (tokenLen == 0)
{
pszString = NULL;
}
else if (tokenLen != 1)
{
CSLDestroy(papszToken);
return -1;
}
else
{
pszString = papszToken[0];
}
}
else if (CSLCount(papszToken) == 2)
{
pszString = papszToken[1];
}
else
{
CSLDestroy(papszToken);
return -1;
}
/*-------------------------------------------------------------
* Note: The text string may contain escaped "\n" chars, and we
* sstore them in memory in the UnEscaped form to be OGR
* compliant. See Maptools bug 1107 for more details.
*------------------------------------------------------------*/
pszTmpString = CPLStrdup(pszString);
m_pszString = TABUnEscapeString(pszTmpString, TRUE);
if (pszTmpString != m_pszString)
CPLFree(pszTmpString);
if (!bXYBoxRead)
{
CSLDestroy(papszToken);
papszToken = CSLTokenizeString2(fp->GetLine(),
" \t", CSLT_HONOURSTRINGS);
}
if (CSLCount(papszToken) != 4)
{
CSLDestroy(papszToken);
return -1;
}
else
{
dXMin = fp->GetXTrans(atof(papszToken[0]));
dXMax = fp->GetXTrans(atof(papszToken[2]));
dYMin = fp->GetYTrans(atof(papszToken[1]));
dYMax = fp->GetYTrans(atof(papszToken[3]));
m_dHeight = dYMax - dYMin; //SetTextBoxHeight(dYMax - dYMin);
m_dWidth = dXMax - dXMin; //SetTextBoxWidth(dXMax - dXMin);
if (m_dHeight <0.0)
m_dHeight*=-1.0;
if (m_dWidth <0.0)
m_dWidth*=-1.0;
}
CSLDestroy(papszToken);
papszToken = NULL;
/* Set/retrieve the MBR to make sure Mins are smaller than Maxs
*/
SetMBR(dXMin, dYMin, dXMax, dYMax);
GetMBR(dXMin, dYMin, dXMax, dYMax);
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine,"() ,",
TRUE,FALSE);
if (CSLCount(papszToken) > 1)
{
if (EQUALN(papszToken[0],"FONT",4))
{
if (CSLCount(papszToken) >= 5)
{
SetFontName(papszToken[1]);
SetFontFGColor(atoi(papszToken[4]));
if (CSLCount(papszToken) ==6)
{
SetFontBGColor(atoi(papszToken[5]));
SetFontStyleMIFValue(atoi(papszToken[2]),TRUE);
}
else
SetFontStyleMIFValue(atoi(papszToken[2]));
// papsztoken[3] = Size ???
}
}
else if (EQUALN(papszToken[0],"SPACING",7))
{
if (CSLCount(papszToken) >= 2)
{
if (EQUALN(papszToken[1],"2",1))
{
SetTextSpacing(TABTSDouble);
}
else if (EQUALN(papszToken[1],"1.5",3))
{
SetTextSpacing(TABTS1_5);
}
}
if (CSLCount(papszToken) == 7)
{
if (EQUALN(papszToken[2],"LAbel",5))
{
if (EQUALN(papszToken[4],"simple",6))
{
SetTextLineType(TABTLSimple);
SetTextLineEndPoint(fp->GetXTrans(atof(papszToken[5])),
fp->GetYTrans(atof(papszToken[6])));
}
else if (EQUALN(papszToken[4],"arrow", 5))
{
SetTextLineType(TABTLArrow);
SetTextLineEndPoint(fp->GetXTrans(atof(papszToken[5])),
fp->GetYTrans(atof(papszToken[6])));
}
}
}
}
else if (EQUALN(papszToken[0],"Justify",7))
{
if (CSLCount(papszToken) == 2)
{
if (EQUALN( papszToken[1],"Center",6))
{
SetTextJustification(TABTJCenter);
}
else if (EQUALN( papszToken[1],"Right",5))
{
SetTextJustification(TABTJRight);
}
}
}
else if (EQUALN(papszToken[0],"Angle",5))
{
if (CSLCount(papszToken) == 2)
{
SetTextAngle(atof(papszToken[1]));
}
}
else if (EQUALN(papszToken[0],"LAbel",5))
{
if (CSLCount(papszToken) == 5)
{
if (EQUALN(papszToken[2],"simple",6))
{
SetTextLineType(TABTLSimple);
SetTextLineEndPoint(fp->GetXTrans(atof(papszToken[3])),
fp->GetYTrans(atof(papszToken[4])));
}
else if (EQUALN(papszToken[2],"arrow", 5))
{
SetTextLineType(TABTLArrow);
SetTextLineEndPoint(fp->GetXTrans(atof(papszToken[3])),
fp->GetYTrans(atof(papszToken[4])));
}
}
// What I do with the XY coordonate
}
}
CSLDestroy(papszToken);
papszToken = NULL;
}
/*-----------------------------------------------------------------
* Create an OGRPoint Geometry...
* The point X,Y values will be the coords of the lower-left corner before
* rotation is applied. (Note that the rotation in MapInfo is done around
* the upper-left corner)
* We need to calculate the true lower left corner of the text based
* on the MBR after rotation, the text height and the rotation angle.
*---------------------------------------------------------------- */
double dCos, dSin, dX, dY;
dSin = sin(m_dAngle*PI/180.0);
dCos = cos(m_dAngle*PI/180.0);
if (dSin > 0.0 && dCos > 0.0)
{
dX = dXMin + m_dHeight * dSin;
dY = dYMin;
}
else if (dSin > 0.0 && dCos < 0.0)
{
dX = dXMax;
dY = dYMin - m_dHeight * dCos;
}
else if (dSin < 0.0 && dCos < 0.0)
{
dX = dXMax + m_dHeight * dSin;
dY = dYMax;
}
else // dSin < 0 && dCos > 0
{
dX = dXMin;
dY = dYMax - m_dHeight * dCos;
}
poGeometry = new OGRPoint(dX, dY);
SetGeometryDirectly(poGeometry);
/*-----------------------------------------------------------------
* Compute Text Width: the width of the Text MBR before rotation
* in ground units... unfortunately this value is not stored in the
* file, so we have to compute it with the MBR after rotation and
* the height of the MBR before rotation:
* With W = Width of MBR before rotation
* H = Height of MBR before rotation
* dX = Width of MBR after rotation
* dY = Height of MBR after rotation
* teta = rotation angle
*
* For [-PI/4..teta..+PI/4] or [3*PI/4..teta..5*PI/4], we'll use:
* W = H * (dX - H * sin(teta)) / (H * cos(teta))
*
* and for other teta values, use:
* W = H * (dY - H * cos(teta)) / (H * sin(teta))
*---------------------------------------------------------------- */
dSin = ABS(dSin);
dCos = ABS(dCos);
if (m_dHeight == 0.0)
m_dWidth = 0.0;
else if ( dCos > dSin )
m_dWidth = m_dHeight * ((dXMax-dXMin) - m_dHeight*dSin) /
(m_dHeight*dCos);
else
m_dWidth = m_dHeight * ((dYMax-dYMin) - m_dHeight*dCos) /
(m_dHeight*dSin);
m_dWidth = ABS(m_dWidth);
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABText::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
double dXMin,dYMin,dXMax,dYMax;
char *pszTmpString;
/*-------------------------------------------------------------
* Note: The text string may contain unescaped "\n" chars or
* "\\" chars and we expect to receive them in an unescaped
* form. Those characters are unescaped in memory to be like
* other OGR drivers. See MapTools bug 1107 for more details.
*------------------------------------------------------------*/
pszTmpString = TABEscapeString(m_pszString);
if(pszTmpString == NULL)
fp->WriteLine("Text \"\"\n" );
else
fp->WriteLine("Text \"%s\"\n", pszTmpString );
if (pszTmpString != m_pszString)
CPLFree(pszTmpString);
// UpdateTextMBR();
GetMBR(dXMin, dYMin, dXMax, dYMax);
fp->WriteLine(" %.15g %.15g %.15g %.15g\n",dXMin, dYMin,dXMax, dYMax);
if (IsFontBGColorUsed())
fp->WriteLine(" Font (\"%s\",%d,%d,%d,%d)\n", GetFontNameRef(),
GetFontStyleMIFValue(),0,GetFontFGColor(),
GetFontBGColor());
else
fp->WriteLine(" Font (\"%s\",%d,%d,%d)\n", GetFontNameRef(),
GetFontStyleMIFValue(),0,GetFontFGColor());
switch (GetTextSpacing())
{
case TABTS1_5:
fp->WriteLine(" Spacing 1.5\n");
break;
case TABTSDouble:
fp->WriteLine(" Spacing 2.0\n");
break;
case TABTSSingle:
default:
break;
}
switch (GetTextJustification())
{
case TABTJCenter:
fp->WriteLine(" Justify Center\n");
break;
case TABTJRight:
fp->WriteLine(" Justify Right\n");
break;
case TABTJLeft:
default:
break;
}
if (ABS(GetTextAngle()) > 0.000001)
fp->WriteLine(" Angle %.15g\n",GetTextAngle());
switch (GetTextLineType())
{
case TABTLSimple:
if (m_bLineEndSet)
fp->WriteLine(" Label Line Simple %.15g %.15g \n",
m_dfLineEndX, m_dfLineEndY );
break;
case TABTLArrow:
if (m_bLineEndSet)
fp->WriteLine(" Label Line Arrow %.15g %.15g \n",
m_dfLineEndX, m_dfLineEndY );
break;
case TABTLNoLine:
default:
break;
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABMultiPoint::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
OGRPoint *poPoint;
OGRMultiPoint *poMultiPoint;
char **papszToken;
const char *pszLine;
int nNumPoint, i;
double dfX,dfY;
OGREnvelope sEnvelope;
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=2)
{
CSLDestroy(papszToken);
return -1;
}
nNumPoint = atoi(papszToken[1]);
poMultiPoint = new OGRMultiPoint;
CSLDestroy(papszToken);
papszToken = NULL;
// Get each point and add them to the multipoint feature
for(i=0; i<nNumPoint; i++)
{
pszLine = fp->GetLine();
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=2)
{
CSLDestroy(papszToken);
return -1;
}
dfX = fp->GetXTrans(atof(papszToken[0]));
dfY = fp->GetXTrans(atof(papszToken[1]));
poPoint = new OGRPoint(dfX, dfY);
if ( poMultiPoint->addGeometryDirectly( poPoint ) != OGRERR_NONE)
{
CPLAssert(FALSE); // Just in case OGR is modified
}
// Set center
if(i == 0)
{
SetCenter( dfX, dfY );
}
CSLDestroy(papszToken);
}
if( SetGeometryDirectly( poMultiPoint ) != OGRERR_NONE)
{
CPLAssert(FALSE); // Just in case OGR is modified
}
poMultiPoint->getEnvelope(&sEnvelope);
SetMBR(sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX,sEnvelope.MaxY);
// Read optional SYMBOL line...
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
{
papszToken = CSLTokenizeStringComplex(pszLine," ,()\t",
TRUE,FALSE);
if (CSLCount(papszToken) == 4 && EQUAL(papszToken[0], "SYMBOL") )
{
SetSymbolNo((GInt16)atoi(papszToken[1]));
SetSymbolColor((GInt32)atoi(papszToken[2]));
SetSymbolSize((GInt16)atoi(papszToken[3]));
}
CSLDestroy(papszToken);
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABMultiPoint::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
OGRGeometry *poGeom;
OGRPoint *poPoint;
OGRMultiPoint *poMultiPoint;
int nNumPoints, iPoint;
/*-----------------------------------------------------------------
* Fetch and validate geometry
*----------------------------------------------------------------*/
poGeom = GetGeometryRef();
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbMultiPoint)
{
poMultiPoint = (OGRMultiPoint*)poGeom;
nNumPoints = poMultiPoint->getNumGeometries();
fp->WriteLine("MultiPoint %d\n", nNumPoints);
for(iPoint=0; iPoint < nNumPoints; iPoint++)
{
/*------------------------------------------------------------
* Validate each point
*-----------------------------------------------------------*/
poGeom = poMultiPoint->getGeometryRef(iPoint);
if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint)
{
poPoint = (OGRPoint*)poGeom;
fp->WriteLine("%.15g %.15g\n",poPoint->getX(),poPoint->getY());
}
else
{
CPLError(CE_Failure, CPLE_AssertionFailed,
"TABMultiPoint: Missing or Invalid Geometry!");
return -1;
}
}
// Write symbol
fp->WriteLine(" Symbol (%d,%d,%d)\n",GetSymbolNo(),GetSymbolColor(),
GetSymbolSize());
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABCollection::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
char **papszToken;
const char *pszLine;
int numParts, i;
OGREnvelope sEnvelope;
/*-----------------------------------------------------------------
* Fetch number of parts in "COLLECTION %d" line
*----------------------------------------------------------------*/
papszToken = CSLTokenizeString2(fp->GetLastLine(),
" \t", CSLT_HONOURSTRINGS);
if (CSLCount(papszToken) !=2)
{
CSLDestroy(papszToken);
return -1;
}
numParts = atoi(papszToken[1]);
CSLDestroy(papszToken);
papszToken = NULL;
// Make sure collection is empty
EmptyCollection();
pszLine = fp->GetLine();
/*-----------------------------------------------------------------
* Read each part and add them to the feature
*----------------------------------------------------------------*/
for (i=0; i < numParts; i++)
{
if (pszLine == NULL)
{
CPLError(CE_Failure, CPLE_FileIO,
"Unexpected EOF while reading TABCollection from MIF file.");
return -1;
}
while(*pszLine == ' ' || *pszLine == '\t')
pszLine++; // skip leading spaces
if (*pszLine == '\0')
continue; // Skip blank lines
if (EQUALN(pszLine,"REGION",6))
{
m_poRegion = new TABRegion(GetDefnRef());
if (m_poRegion->ReadGeometryFromMIFFile(fp) != 0)
{
CPLError(CE_Failure, CPLE_NotSupported,
"TABCollection: Error reading REGION part.");
delete m_poRegion;
m_poRegion = NULL;
return -1;
}
}
else if (EQUALN(pszLine,"LINE",4) ||
EQUALN(pszLine,"PLINE",5))
{
m_poPline = new TABPolyline(GetDefnRef());
if (m_poPline->ReadGeometryFromMIFFile(fp) != 0)
{
CPLError(CE_Failure, CPLE_NotSupported,
"TABCollection: Error reading PLINE part.");
delete m_poPline;
m_poPline = NULL;
return -1;
}
}
else if (EQUALN(pszLine,"MULTIPOINT",10))
{
m_poMpoint = new TABMultiPoint(GetDefnRef());
if (m_poMpoint->ReadGeometryFromMIFFile(fp) != 0)
{
CPLError(CE_Failure, CPLE_NotSupported,
"TABCollection: Error reading MULTIPOINT part.");
delete m_poMpoint;
m_poMpoint = NULL;
return -1;
}
}
else
{
CPLError(CE_Failure, CPLE_FileIO,
"Reading TABCollection from MIF failed, expecting one "
"of REGION, PLINE or MULTIPOINT, got: '%s'",
pszLine);
return -1;
}
pszLine = fp->GetLastLine();
}
/*-----------------------------------------------------------------
* Set the main OGRFeature Geometry
* (this is actually duplicating geometries from each member)
*----------------------------------------------------------------*/
// use addGeometry() rather than addGeometryDirectly() as this clones
// the added geometry so won't leave dangling ptrs when the above features
// are deleted
OGRGeometryCollection *poGeomColl = new OGRGeometryCollection();
if(m_poRegion && m_poRegion->GetGeometryRef() != NULL)
poGeomColl->addGeometry(m_poRegion->GetGeometryRef());
if(m_poPline && m_poPline->GetGeometryRef() != NULL)
poGeomColl->addGeometry(m_poPline->GetGeometryRef());
if(m_poMpoint && m_poMpoint->GetGeometryRef() != NULL)
poGeomColl->addGeometry(m_poMpoint->GetGeometryRef());
this->SetGeometryDirectly(poGeomColl);
poGeomColl->getEnvelope(&sEnvelope);
SetMBR(sEnvelope.MinX, sEnvelope.MinY,
sEnvelope.MaxX, sEnvelope.MaxY);
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABCollection::WriteGeometryToMIFFile(MIDDATAFile *fp)
{
int numParts = 0;
if (m_poRegion) numParts++;
if (m_poPline) numParts++;
if (m_poMpoint) numParts++;
fp->WriteLine("COLLECTION %d\n", numParts);
if (m_poRegion)
{
if (m_poRegion->WriteGeometryToMIFFile(fp) != 0)
return -1;
}
if (m_poPline)
{
if (m_poPline->WriteGeometryToMIFFile(fp) != 0)
return -1;
}
if (m_poMpoint)
{
if (m_poMpoint->WriteGeometryToMIFFile(fp) != 0)
return -1;
}
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABDebugFeature::ReadGeometryFromMIFFile(MIDDATAFile *fp)
{
const char *pszLine;
/* Go to the first line of the next feature */
printf("%s\n", fp->GetLastLine());
while (((pszLine = fp->GetLine()) != NULL) &&
fp->IsValidFeature(pszLine) == FALSE)
;
return 0;
}
/**********************************************************************
*
**********************************************************************/
int TABDebugFeature::WriteGeometryToMIFFile(MIDDATAFile *fp){ return -1; }
| 33.243568 | 91 | 0.469314 | [
"geometry",
"object",
"3d"
] |
f5b1b9092cb31e170903db96e7c1c319cae8d1a5 | 13,052 | cpp | C++ | src/ukfnew.cpp | lb5160482/Sensor-Fusion-Unscented-Kalman-Filter | 4636755b6a5dcc25f181684796d3ade82cb943f9 | [
"MIT"
] | 1 | 2018-08-09T00:37:40.000Z | 2018-08-09T00:37:40.000Z | src/ukfnew.cpp | lb5160482/Sensor-Fusion-Unscented-Kalman-Filter | 4636755b6a5dcc25f181684796d3ade82cb943f9 | [
"MIT"
] | null | null | null | src/ukfnew.cpp | lb5160482/Sensor-Fusion-Unscented-Kalman-Filter | 4636755b6a5dcc25f181684796d3ade82cb943f9 | [
"MIT"
] | null | null | null | #include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
/**
* Initializes Unscented Kalman filter
* This is scaffolding, do not modify
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 2;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.3;
//DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer.
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
//DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer.
/**
TODO:
Complete the initialization. See ukf.h for other member properties.
Hint: one or more values initialized above might be wildly off...
*/
is_initialized_ = false;
n_x_ = 5;
n_aug_ = 7;
Xsig_pred_ = MatrixXd(5, 2 * n_aug_ + 1);
weights_ = VectorXd(2 * n_aug_ + 1);
lambda_ = 3 - n_x_;
}
UKF::~UKF() {}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
// check sensor usage, ignore if specified not to use
if ((!use_laser_ && meas_package.sensor_type_ == MeasurementPackage::LASER) ||
(!use_radar_ && meas_package.sensor_type_ == MeasurementPackage::RADAR)) {
return;
}
/*****************************************************************************
* Initialization
****************************************************************************/
if (!is_initialized_) {
x_ << 1, 1, 1, 1, 0.1;
P_ << 0.15, 0, 0, 0, 0,
0, 0.15, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1;
if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
float px = meas_package.raw_measurements_(0);
float py = meas_package.raw_measurements_(1);
x_(0) = px;
x_(1) = py;
cout << "Initialization finished with Laser data!" << endl;
}
else {
float rho = meas_package.raw_measurements_(0);
float phi = meas_package.raw_measurements_(1);
float px = cos(phi) * rho;
float py = sin(phi) * rho;
x_(0) = px;
x_(1) = py;
cout << "Initialization finished with Radar data!" << endl;
}
// Finish initialization
is_initialized_ = true;
time_us_ = meas_package.timestamp_;
// set weights
weights_(0) = lambda_ / (lambda_ + n_aug_);
for (int i = 1; i < 2 * n_aug_ + 1; ++i) {
weights_(i) = 0.5 / (lambda_ + n_aug_);
}
return;
}
/*****************************************************************************
* Prediction
****************************************************************************/
double delta_t = (meas_package.timestamp_ - time_us_) / 1000000.0;
time_us_ = meas_package.timestamp_;
Prediction(delta_t);
/*****************************************************************************
* Update
****************************************************************************/
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
UpdateRadar(meas_package);
}
else {
UpdateLidar(meas_package);
}
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
/*****************************************************************************
* Generate augmented sigma points
****************************************************************************/
// Create augmented mean vector
VectorXd xAug = VectorXd(n_aug_);
xAug.head(n_x_) = x_;
xAug[5] = 0;
xAug[6] = 0;
// Create angmented state covariance
MatrixXd PAug = MatrixXd(n_aug_, n_aug_);
PAug.fill(0.0);
PAug.topLeftCorner(5, 5) = P_;
PAug(5, 5) = std_a_ * std_a_;
PAug(6, 6) = std_yawdd_ * std_yawdd_;
// Calculate the square root of PAug
MatrixXd L = PAug.llt().matrixL();
// Create augmented sigma points matrix
MatrixXd XSigAug = MatrixXd(n_aug_, 2 * n_aug_ + 1);
XSigAug.col(0) = xAug;
for (int i = 0; i < n_aug_; ++i) {
XSigAug.col(i + 1) = xAug + sqrt(lambda_ + n_aug_) * L.col(i);
XSigAug.col(i + 1 + n_aug_) = xAug - sqrt(lambda_ + n_aug_) * L.col(i);
}
/*****************************************************************************
* Convert augmented sigma points to state space as prediction(update Xsig_pred_)
****************************************************************************/
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
VectorXd xSigAug = XSigAug.col(i);
double px = xSigAug(0);
double py = xSigAug(1);
double v = xSigAug(2);
double yaw = xSigAug(3);
double yawRate = xSigAug(4);
double aV = xSigAug(5);
double aYaw = xSigAug(6);
// avoid dividing by zero
if (fabs(yawRate) < 0.001) {
Xsig_pred_(0, i) = px + v * cos(yaw) * delta_t + 0.5 * pow(delta_t, 2) * cos(yaw) * aV;
Xsig_pred_(1, i) = py + v * sin(yaw) * delta_t + 0.5 * pow(delta_t, 2) * sin(yaw) * aV;
}
else {
Xsig_pred_(0, i) = px + v / yawRate * (sin(yaw + yawRate * delta_t) - sin(yaw)) + 0.5 * pow(delta_t, 2) * cos(yaw) * aV;
Xsig_pred_(1, i) = py + v / yawRate * (-cos(yaw + yawRate * delta_t) + cos(yaw)) + 0.5 * pow(delta_t, 2) * sin(yaw) * aV;
}
Xsig_pred_(2, i) = v + delta_t * aV;
Xsig_pred_(3, i) = yaw + yawRate * delta_t + 0.5 * pow(delta_t, 2) * aYaw;
Xsig_pred_(4, i) = yawRate + delta_t * aYaw;
}
/*****************************************************************************
* Using predidcted sigma points to approximate predicted state mean and covariance
****************************************************************************/
// predict x
x_.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
x_ += weights_(i) * Xsig_pred_.col(i);
}
// predict P
P_.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
VectorXd diff = Xsig_pred_.col(i) - x_;
// normalization
while (diff(3) < -M_PI) {
diff(3) += 2 * M_PI;
}
while (diff(3) > M_PI) {
diff(3) -= 2 * M_PI;
}
P_ += weights_(i) * diff * diff.transpose();
}
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
int n_z = 2;
// compute matrix for sigma points in measurement space
MatrixXd ZSig = MatrixXd(n_z, 2 * n_aug_ + 1);
// transform predicted sigma points into measurement space
ZSig.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
VectorXd xsigPred = Xsig_pred_.col(i);
double px = xsigPred(0);
double py = xsigPred(1);
ZSig(0, i) = px;
ZSig(1, i) = py;
}
// mean predicted measurement
VectorXd zPred = VectorXd(n_z);
zPred.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
zPred += weights_(i) * ZSig.col(i);
}
//measurement covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
VectorXd diff = ZSig.col(i) - zPred;
// normalization
while (diff(1) < -M_PI) {
diff(1) += 2 * M_PI;
}
while (diff(1) > M_PI) {
diff(1) -= 2 * M_PI;
}
S += weights_(i) * diff * diff.transpose();
}
// add measurement noise covariance matrix
MatrixXd R = MatrixXd(n_z, n_z);
R << std_laspx_ * std_laspx_, 0,
0, std_laspy_ * std_laspy_;
S += R;
/************* Update states *************/
// create and computecross correlation matrix
MatrixXd Tc = MatrixXd(n_x_, n_z);
Tc.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
// state difference
VectorXd diffX = Xsig_pred_.col(i) - x_;
while (diffX(3) < -M_PI) {
diffX(3) += 2 * M_PI;
}
while (diffX(3) > M_PI) {
diffX(3) -= 2 * M_PI;
}
// measurement difference
VectorXd diffZ = ZSig.col(i) - zPred;
Tc += weights_(i) * diffX * diffZ.transpose();
}
// compute Kalman gain
MatrixXd K = Tc * S.inverse();
// compute diffZ(between measurement and predicted, note different defination from the above one)
VectorXd diffZ = meas_package.raw_measurements_ - zPred;
// udpate state and state covariance
x_ = x_ + K * diffZ;
P_ = P_ - K * S * K.transpose();
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
int n_z = 3;
// compute matrix for sigma points in measurement space
MatrixXd ZSig = MatrixXd(n_z, 2 * n_aug_ + 1);
// transform predicted sigma points into measurement space
ZSig.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
VectorXd xsigPred = Xsig_pred_.col(i);
double px = xsigPred(0);
double py = xsigPred(1);
double v = xsigPred(2);
double yaw = xsigPred(3);
double c1 = sqrt(px * px + py * py);
ZSig(0, i) = c1;
ZSig(1, i) = atan2(py, px);
ZSig(2, i) = (px * cos(yaw) * v + py * sin(yaw) * v) / c1;
}
// mean predicted measurement
VectorXd zPred = VectorXd(n_z);
zPred.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
zPred += weights_(i) * ZSig.col(i);
}
//measurement covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
VectorXd diff = ZSig.col(i) - zPred;
// normalization
while (diff(1) < -M_PI) {
diff(1) += 2 * M_PI;
}
while (diff(1) > M_PI) {
diff(1) -= 2 * M_PI;
}
S += weights_(i) * diff * diff.transpose();
}
// add measurement noise covariance matrix
MatrixXd R = MatrixXd(3, 3);
R << std_radr_ * std_radr_, 0, 0,
0, std_radphi_ * std_radphi_, 0,
0, 0, std_radrd_ * std_radrd_;
S += R;
/************* Update states *************/
// create and computecross correlation matrix
MatrixXd Tc = MatrixXd(n_x_, n_z);
Tc.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; ++i) {
// state difference
VectorXd diffX = Xsig_pred_.col(i) - x_;
while (diffX(3) < -M_PI) {
diffX(3) += 2 * M_PI;
}
while (diffX(3) > M_PI) {
diffX(3) -= 2 * M_PI;
}
// measurement difference
VectorXd diffZ = ZSig.col(i) - zPred;
while (diffZ(1) < -M_PI) {
diffZ(1) += 2 * M_PI;
}
while (diffZ(1) > M_PI) {
diffZ(1) -= 2 * M_PI;
}
Tc += weights_(i) * diffX * diffZ.transpose();
}
// compute Kalman gain
MatrixXd K = Tc * S.inverse();
// compute diffZ(between measurement and predicted, note different defination from the above one)
VectorXd diffZ = meas_package.raw_measurements_ - zPred;
while (diffZ(1) < -M_PI) {
diffZ(1) += 2 * M_PI;
}
while (diffZ(1) > M_PI) {
diffZ(1) -= 2 * M_PI;
}
// udpate state and state covariance
x_ = x_ + K * diffZ;
P_ = P_ - K * S * K.transpose();
}
| 32.959596 | 133 | 0.501073 | [
"vector",
"transform"
] |
f5b2ac1db3068092bb8de4a5e50beb2873fb0dfc | 10,784 | cc | C++ | components/flags_ui/flags_test_helpers.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 | components/flags_ui/flags_test_helpers.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 | components/flags_ui/flags_test_helpers.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 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/flags_ui/flags_test_helpers.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/json/json_file_value_serializer.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "components/flags_ui/feature_entry.h"
#include "components/flags_ui/flags_state.h"
namespace {
// Type of flag ownership file.
enum class FlagFile { kFlagMetadata, kFlagNeverExpire };
// Returns the filename based on the file enum.
std::string FlagFileName(FlagFile file) {
switch (file) {
case FlagFile::kFlagMetadata:
return "flag-metadata.json";
case FlagFile::kFlagNeverExpire:
return "flag-never-expire-list.json";
}
}
// Returns the JSON file contents.
base::Value FileContents(FlagFile file) {
std::string filename = FlagFileName(file);
base::FilePath metadata_path;
base::PathService::Get(base::DIR_SOURCE_ROOT, &metadata_path);
JSONFileValueDeserializer deserializer(
metadata_path.AppendASCII("chrome").AppendASCII("browser").AppendASCII(
filename));
int error_code;
std::string error_message;
std::unique_ptr<base::Value> json =
deserializer.Deserialize(&error_code, &error_message);
DCHECK(json) << "Failed to load " << filename << ": " << error_code << " "
<< error_message;
return std::move(*json);
}
// Data structure capturing the metadata of the flag.
struct FlagMetadataEntry {
std::vector<std::string> owners;
int expiry_milestone;
};
// Lookup of metadata by flag name.
using FlagMetadataMap = std::map<std::string, FlagMetadataEntry>;
// Reads the flag metadata file.
FlagMetadataMap LoadFlagMetadata() {
base::Value metadata_json = FileContents(FlagFile::kFlagMetadata);
FlagMetadataMap metadata;
for (const auto& entry : metadata_json.GetList()) {
std::string name = entry.FindKey("name")->GetString();
std::vector<std::string> owners;
if (const base::Value* e = entry.FindKey("owners")) {
for (const auto& owner : e->GetList())
owners.push_back(owner.GetString());
}
int expiry_milestone = entry.FindKey("expiry_milestone")->GetInt();
metadata[name] = FlagMetadataEntry{owners, expiry_milestone};
}
return metadata;
}
std::vector<std::string> LoadFlagNeverExpireList() {
base::Value list_json = FileContents(FlagFile::kFlagNeverExpire);
std::vector<std::string> result;
for (const auto& entry : list_json.GetList()) {
result.push_back(entry.GetString());
}
return result;
}
bool IsValidLookingOwner(base::StringPiece owner) {
// Per the specification at the top of flag-metadata.json, an owner is one of:
// 1) A string containing '@', which is treated as a full email address
// 2) A string beginning with '//', which is a path to an OWNERS file
// 3) Any other string, which is the username part of an @chromium.org email
const size_t at_pos = owner.find("@");
if (at_pos != std::string::npos) {
// If there's an @, check for a . after it. This catches one common error:
// writing "foo@" in the owners list rather than bare "foo" or full
// "foo@domain.com".
return owner.find(".", at_pos) != std::string::npos;
}
if (base::StartsWith(owner, "//")) {
// Looks like a path to a file. It would be nice to check that the file
// actually exists here, but that's not possible because when this test
// runs it runs in an isolated environment. To check for the presence of the
// file the test would need a build-time declaration that it depends on that
// file. Instead, just assume any file path ending in 'OWNERS' is valid.
// This doesn't check that the entire filename part of the path is 'OWNERS'
// because sometimes it is instead 'IPC_OWNERS' or similar.
return base::EndsWith(owner, "OWNERS");
}
// Otherwise, look for something that seems like the username part of an
// @chromium.org email. The criteria here is that it must look like an RFC5322
// "atom", which is neatly defined as any printable character *outside* a
// specific set:
// https://tools.ietf.org/html/rfc5322#section-3.2.3
//
// Note two extra wrinkles here:
// 1) while '.' IS NOT allowed in atoms by RFC5322 gmail and other mail
// handlers do allow it, so this does not reject '.'.
// 2) while '/' IS allowed in atoms by RFC5322, this is not commonly done, and
// checking for it here detects another common syntax error - namely
// writing:
// "owners": [ "foo/bar/OWNERS" ]
// where
// "owners": [ "//foo/bar/OWNERS" ]
// is meant.
return owner.find_first_of(R"(()<>[]:;@\,/)") == std::string::npos;
}
void EnsureNamesAreAlphabetical(
const std::vector<std::string>& normalized_names,
const std::vector<std::string>& names,
FlagFile file) {
if (normalized_names.size() < 2)
return;
for (size_t i = 1; i < normalized_names.size(); ++i) {
if (i == normalized_names.size() - 1) {
// The last item on the list has less context.
EXPECT_TRUE(normalized_names[i - 1] < normalized_names[i])
<< "Correct alphabetical order does not place '" << names[i]
<< "' after '" << names[i - 1] << "' in " << FlagFileName(file);
} else {
EXPECT_TRUE(normalized_names[i - 1] < normalized_names[i] &&
normalized_names[i] < normalized_names[i + 1])
<< "Correct alphabetical order does not place '" << names[i]
<< "' between '" << names[i - 1] << "' and '" << names[i + 1]
<< "' in " << FlagFileName(file);
}
}
}
std::string NormalizeName(const std::string& name) {
std::string normalized_name = base::ToLowerASCII(name);
std::replace(normalized_name.begin(), normalized_name.end(), '_', '-');
return normalized_name;
}
bool IsUnexpireFlagFor(const flags_ui::FeatureEntry& entry, int milestone) {
std::string expected_flag =
base::StringPrintf("temporary-unexpire-flags-m%d", milestone);
if (entry.internal_name != expected_flag)
return false;
if (!(entry.supported_platforms & flags_ui::kFlagInfrastructure))
return false;
if (entry.type != flags_ui::FeatureEntry::FEATURE_VALUE)
return false;
std::string expected_feature =
base::StringPrintf("UnexpireFlagsM%d", milestone);
const auto* feature = entry.feature.feature;
if (!feature || feature->name != expected_feature)
return false;
return true;
}
} // namespace
namespace flags_ui {
namespace testing {
void EnsureEveryFlagHasMetadata(const flags_ui::FeatureEntry* entries,
size_t count) {
EnsureEveryFlagHasMetadata(base::make_span(entries, count));
}
void EnsureEveryFlagHasMetadata(
const base::span<const flags_ui::FeatureEntry>& entries) {
FlagMetadataMap metadata = LoadFlagMetadata();
std::vector<std::string> missing_flags;
for (const auto& entry : entries) {
// Flags that are part of the flags system itself (like unexpiry meta-flags)
// don't have metadata, so skip them here.
if (entry.supported_platforms & flags_ui::kFlagInfrastructure)
continue;
if (metadata.count(entry.internal_name) == 0)
missing_flags.push_back(entry.internal_name);
}
std::sort(missing_flags.begin(), missing_flags.end());
EXPECT_EQ(0u, missing_flags.size())
<< "Missing flags: " << base::JoinString(missing_flags, "\n ");
}
void EnsureOnlyPermittedFlagsNeverExpire() {
FlagMetadataMap metadata = LoadFlagMetadata();
std::vector<std::string> listed_flags = LoadFlagNeverExpireList();
std::vector<std::string> missing_flags;
for (const auto& entry : metadata) {
if (entry.second.expiry_milestone == -1 &&
std::find(listed_flags.begin(), listed_flags.end(), entry.first) ==
listed_flags.end()) {
missing_flags.push_back(entry.first);
}
}
std::sort(missing_flags.begin(), missing_flags.end());
EXPECT_EQ(0u, missing_flags.size())
<< "Flags not listed for no-expire: "
<< base::JoinString(missing_flags, "\n ");
}
void EnsureEveryFlagHasNonEmptyOwners() {
FlagMetadataMap metadata = LoadFlagMetadata();
std::vector<std::string> sad_flags;
for (const auto& it : metadata) {
if (it.second.owners.empty())
sad_flags.push_back(it.first);
}
std::sort(sad_flags.begin(), sad_flags.end());
EXPECT_EQ(0u, sad_flags.size())
<< "Flags missing owners: " << base::JoinString(sad_flags, "\n ");
}
void EnsureOwnersLookValid() {
FlagMetadataMap metadata = LoadFlagMetadata();
std::vector<std::string> sad_flags;
for (const auto& flag : metadata) {
for (const auto& owner : flag.second.owners) {
if (!IsValidLookingOwner(owner))
sad_flags.push_back(flag.first);
}
}
EXPECT_EQ(0u, sad_flags.size()) << "Flags with invalid-looking owners: "
<< base::JoinString(sad_flags, "\n");
}
void EnsureFlagsAreListedInAlphabeticalOrder() {
base::Value metadata_json = FileContents(FlagFile::kFlagMetadata);
std::vector<std::string> normalized_names;
std::vector<std::string> names;
for (const auto& entry : metadata_json.GetList()) {
normalized_names.push_back(
NormalizeName(entry.FindKey("name")->GetString()));
names.push_back(entry.FindKey("name")->GetString());
}
EnsureNamesAreAlphabetical(normalized_names, names, FlagFile::kFlagMetadata);
base::Value expiration_json = FileContents(FlagFile::kFlagNeverExpire);
normalized_names.clear();
names.clear();
for (const auto& entry : expiration_json.GetList()) {
normalized_names.push_back(NormalizeName(entry.GetString()));
names.push_back(entry.GetString());
}
EnsureNamesAreAlphabetical(normalized_names, names,
FlagFile::kFlagNeverExpire);
}
// TODO(ellyjones): Does this / should this run on iOS as well?
void EnsureRecentUnexpireFlagsArePresent(
const base::span<const flags_ui::FeatureEntry>& entries,
int current_milestone) {
auto contains_unexpire_for = [&](int mstone) {
for (const auto& entry : entries) {
if (IsUnexpireFlagFor(entry, mstone))
return true;
}
return false;
};
EXPECT_FALSE(contains_unexpire_for(current_milestone));
EXPECT_TRUE(contains_unexpire_for(current_milestone - 1));
EXPECT_TRUE(contains_unexpire_for(current_milestone - 2));
EXPECT_FALSE(contains_unexpire_for(current_milestone - 3));
}
} // namespace testing
} // namespace flags_ui
| 34.234921 | 80 | 0.685367 | [
"vector"
] |
f5b2f9580672253424169d988297e431e17c852a | 305 | cpp | C++ | Algoritmi & Structuri Date (ASD)/Laborator/Teme/2/5.cpp | DLarisa/FMI-Materials-BachelorDegree | 138e1a20bc33617772e9cd9e4432fbae99c0250c | [
"W3C"
] | 4 | 2022-02-12T02:05:36.000Z | 2022-03-26T14:44:43.000Z | Algoritmi & Structuri Date (ASD)/Laborator/Teme/2/5.cpp | DLarisa/FMI-Materials-BachelorDegree-UniBuc | 138e1a20bc33617772e9cd9e4432fbae99c0250c | [
"W3C"
] | null | null | null | Algoritmi & Structuri Date (ASD)/Laborator/Teme/2/5.cpp | DLarisa/FMI-Materials-BachelorDegree-UniBuc | 138e1a20bc33617772e9cd9e4432fbae99c0250c | [
"W3C"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int v[100], n, t, i, nr=0;
//Citire Vector
cin>>n; n++;
for(i=0; i<n; i++) cin>>v[i]; // End Citire
cin>>t; //Citire t
for(i=0; i<n; i++) nr=nr+v[i]*(pow(t,i));
cout<<nr;
return 0;
}
| 17.941176 | 48 | 0.478689 | [
"vector"
] |
f5b56fd8e54ef706a8ed60db4536900a79e12b57 | 584 | cc | C++ | operational/src/visitor/inventory.cc | rachwal/DesignPatterns | 0645544706c915a69e1ca64addba5cc14453f64c | [
"MIT"
] | 9 | 2016-08-03T16:15:57.000Z | 2021-11-08T13:15:46.000Z | operational/src/visitor/inventory.cc | rachwal/DesignPatterns | 0645544706c915a69e1ca64addba5cc14453f64c | [
"MIT"
] | null | null | null | operational/src/visitor/inventory.cc | rachwal/DesignPatterns | 0645544706c915a69e1ca64addba5cc14453f64c | [
"MIT"
] | 4 | 2016-08-03T16:16:01.000Z | 2017-12-27T05:14:55.000Z | // Based on "Design Patterns: Elements of Reusable Object-Oriented Software"
// book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm
//
// Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan.
#include "inventory.h"
namespace operational
{
namespace visitor
{
Inventory::Inventory() : count_(0) {}
Inventory::Inventory(const Inventory& inventory) : count_(inventory.count_) {}
void Inventory::Accumulate(VisitedEquipmentInterface* equipment)
{
count_++;
}
int Inventory::count() const
{
return count_;
}
}
}
| 20.857143 | 107 | 0.755137 | [
"object"
] |
f5b8e9bf7c406463a520ca2138403583fdb95218 | 2,306 | cc | C++ | utils/utils.cc | mikuh/dudulu-nlp | 3fb066b34db1a59340366a851b9df685726c52b2 | [
"MIT"
] | null | null | null | utils/utils.cc | mikuh/dudulu-nlp | 3fb066b34db1a59340366a851b9df685726c52b2 | [
"MIT"
] | null | null | null | utils/utils.cc | mikuh/dudulu-nlp | 3fb066b34db1a59340366a851b9df685726c52b2 | [
"MIT"
] | null | null | null | #include "utils.h"
namespace dudulu
{
void string_split(const std::string& str, const std::string& delimiters, std::vector<std::string>& tokens)
{
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters.
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
void wstring_split(const std::wstring& str, const std::wstring& delimiters, std::vector<std::wstring>& tokens)
{
// Skip delimiters at beginning.
std::wstring::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::wstring::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::wstring::npos != pos || std::wstring::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters.
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
std::wstring string2wstring(const std::string& str)
{
static std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.from_bytes(str);
}
std::string wstring2string(const std::wstring& wstr)
{
static std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.to_bytes(wstr);
}
// trim from start (in place)
inline void ltrim(std::string& s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
inline void rtrim(std::string& s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(),
s.end());
}
// trim from both ends (in place)
inline void trim(std::string& s)
{
ltrim(s);
rtrim(s);
}
} // namespace dududlu
| 30.746667 | 110 | 0.638768 | [
"vector"
] |
f5b9ef99145310f3ead26a9e28f45330daffc053 | 10,652 | hpp | C++ | include/nil/crypto3/zk/components/merkle_tree/check_read.hpp | skywinder/crypto3-blueprint | c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20 | [
"MIT"
] | null | null | null | include/nil/crypto3/zk/components/merkle_tree/check_read.hpp | skywinder/crypto3-blueprint | c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20 | [
"MIT"
] | null | null | null | include/nil/crypto3/zk/components/merkle_tree/check_read.hpp | skywinder/crypto3-blueprint | c2b033eaaff1a19ab5332b9f49a32bb4fdd1dc20 | [
"MIT"
] | 1 | 2021-09-15T20:27:27.000Z | 2021-09-15T20:27:27.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//
// @file Declaration of interfaces for the Merkle tree check read component.
//
// The component checks the following: given a root R, address A, value V, and
// authentication path P, check that P is a valid authentication path for the
// value V as the A-th leaf in a Merkle tree with root R.
//---------------------------------------------------------------------------//
#ifndef CRYPTO3_ZK_BLUEPRINT_MERKLE_TREE_CHECK_READ_COMPONENT_HPP
#define CRYPTO3_ZK_BLUEPRINT_MERKLE_TREE_CHECK_READ_COMPONENT_HPP
#include <nil/crypto3/zk/snark/merkle_tree.hpp>
#include <nil/crypto3/zk/components/component.hpp>
#include <nil/crypto3/zk/components/hashes/crh_component.hpp>
#include <nil/crypto3/zk/components/hashes/digest_selector_component.hpp>
#include <nil/crypto3/zk/components/hashes/hash_io.hpp>
#include <nil/crypto3/zk/components/merkle_tree/merkle_authentication_path_variable.hpp>
namespace nil {
namespace crypto3 {
namespace zk {
namespace components {
template<typename FieldType, typename Hash>
class merkle_tree_check_read_component : public component<FieldType> {
private:
std::vector<Hash> hashers;
std::vector<block_variable<FieldType>> hasher_inputs;
std::vector<digest_selector_component<FieldType>> propagators;
std::vector<digest_variable<FieldType>> internal_output;
std::shared_ptr<digest_variable<FieldType>> computed_root;
std::shared_ptr<bit_vector_copy_component<FieldType>> check_root;
public:
const std::size_t digest_size;
const std::size_t tree_depth;
blueprint_linear_combination_vector<FieldType> address_bits;
digest_variable<FieldType> leaf;
digest_variable<FieldType> root;
merkle_authentication_path_variable<FieldType, Hash> path;
blueprint_linear_combination<FieldType> read_successful;
merkle_tree_check_read_component(blueprint<FieldType> &bp,
const std::size_t tree_depth,
const blueprint_linear_combination_vector<FieldType> &address_bits,
const digest_variable<FieldType> &leaf_digest,
const digest_variable<FieldType> &root_digest,
const merkle_authentication_path_variable<FieldType, Hash> &path,
const blueprint_linear_combination<FieldType> &read_successful);
void generate_r1cs_constraints();
void generate_r1cs_witness();
static std::size_t root_size_in_bits();
/* for debugging purposes */
static std::size_t expected_constraints(const std::size_t tree_depth);
};
template<typename FieldType, typename Hash>
merkle_tree_check_read_component<FieldType, Hash>::merkle_tree_check_read_component(
blueprint<FieldType> &bp,
const std::size_t tree_depth,
const blueprint_linear_combination_vector<FieldType> &address_bits,
const digest_variable<FieldType> &leaf,
const digest_variable<FieldType> &root,
const merkle_authentication_path_variable<FieldType, Hash> &path,
const blueprint_linear_combination<FieldType> &read_successful) :
component<FieldType>(bp),
digest_size(Hash::get_digest_len()), tree_depth(tree_depth), address_bits(address_bits), leaf(leaf),
root(root), path(path), read_successful(read_successful) {
/*
The tricky part here is ordering. For Merkle tree
authentication paths, path[0] corresponds to one layer below
the root (and path[tree_depth-1] corresponds to the layer
containing the leaf), while address_bits has the reverse order:
address_bits[0] is LSB, and corresponds to layer containing the
leaf, and address_bits[tree_depth-1] is MSB, and corresponds to
the subtree directly under the root.
*/
assert(tree_depth > 0);
assert(tree_depth == address_bits.size());
for (std::size_t i = 0; i < tree_depth - 1; ++i) {
internal_output.emplace_back(digest_variable<FieldType>(bp, digest_size));
}
computed_root.reset(new digest_variable<FieldType>(bp, digest_size));
for (std::size_t i = 0; i < tree_depth; ++i) {
block_variable<FieldType> inp(bp, path.left_digests[i], path.right_digests[i]);
hasher_inputs.emplace_back(inp);
hashers.emplace_back(
Hash(bp, 2 * digest_size, inp, (i == 0 ? *computed_root : internal_output[i - 1])));
}
for (std::size_t i = 0; i < tree_depth; ++i) {
/*
The propagators take a computed hash value (or leaf in the
base case) and propagate it one layer up, either in the left
or the right slot of authentication_path_variable.
*/
propagators.emplace_back(digest_selector_component<FieldType>(
bp, digest_size, i < tree_depth - 1 ? internal_output[i] : leaf,
address_bits[tree_depth - 1 - i], path.left_digests[i], path.right_digests[i]));
}
check_root.reset(new bit_vector_copy_component<FieldType>(bp, computed_root->bits, root.bits,
read_successful, FieldType::number_bits));
}
template<typename FieldType, typename Hash>
void merkle_tree_check_read_component<FieldType, Hash>::generate_r1cs_constraints() {
/* ensure correct hash computations */
for (std::size_t i = 0; i < tree_depth; ++i) {
// Note that we check root outside and have enforced booleanity of
// path.left_digests/path.right_digests outside in path.generate_r1cs_constraints
hashers[i].generate_r1cs_constraints(false);
}
/* ensure consistency of path.left_digests/path.right_digests with internal_output */
for (std::size_t i = 0; i < tree_depth; ++i) {
propagators[i].generate_r1cs_constraints();
}
check_root->generate_r1cs_constraints(false, false);
}
template<typename FieldType, typename Hash>
void merkle_tree_check_read_component<FieldType, Hash>::generate_r1cs_witness() {
/* do the hash computations bottom-up */
for (int i = tree_depth - 1; i >= 0; --i) {
/* propagate previous input */
propagators[i].generate_r1cs_witness();
/* compute hash */
hashers[i].generate_r1cs_witness();
}
check_root->generate_r1cs_witness();
}
template<typename FieldType, typename Hash>
std::size_t merkle_tree_check_read_component<FieldType, Hash>::root_size_in_bits() {
return Hash::get_digest_len();
}
template<typename FieldType, typename Hash>
std::size_t merkle_tree_check_read_component<FieldType, Hash>::expected_constraints(
const std::size_t tree_depth) {
/* NB: this includes path constraints */
const std::size_t hasher_constraints = tree_depth * Hash::expected_constraints(false);
const std::size_t propagator_constraints = tree_depth * Hash::get_digest_len();
const std::size_t authentication_path_constraints = 2 * tree_depth * Hash::get_digest_len();
const std::size_t check_root_constraints =
3 * (Hash::get_digest_len() + (FieldType::capacity()) - 1) / FieldType::capacity();
return hasher_constraints + propagator_constraints + authentication_path_constraints +
check_root_constraints;
}
} // namespace components
} // namespace zk
} // namespace crypto3
} // namespace nil
#endif // CRYPTO3_ZK_BLUEPRINT_MERKLE_TREE_CHECK_READ_COMPONENT_HPP
| 55.769634 | 120 | 0.572475 | [
"vector"
] |
f5c2545adc737dff4a717bbbea3b404eacb21fcb | 4,103 | cpp | C++ | hackathon/linus/sholl_swc_R/sholl_swc.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/linus/sholl_swc_R/sholl_swc.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/linus/sholl_swc_R/sholl_swc.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "sholl_swc.h"
#include <vector>
#include <iostream>
#include <algorithm>
bool combine_linker(vector<QList<NeuronSWC> > & linker, QList<NeuronSWC> & combined)
{
V3DLONG neuronNum = linker.size();
if (neuronNum<=0)
{
cout<<"the linker file is empty, please check your data."<<endl;
return false;
}
V3DLONG offset = 0;
combined = linker[0];
for (V3DLONG i=1;i<neuronNum;i++)
{
V3DLONG maxid = -1;
for (V3DLONG j=0;j<linker[i-1].size();j++)
if (linker[i-1][j].n>maxid) maxid = linker[i-1][j].n;
offset += maxid+1;
for (V3DLONG j=0;j<linker[i].size();j++)
{
NeuronSWC S = linker[i][j];
S.n = S.n+offset;
if (S.pn>=0) S.pn = S.pn+offset;
combined.append(S);
}
}
};
double computeDist2(const NeuronSWC & s1, const NeuronSWC & s2)
{
double xx = s1.x-s2.x;
double yy = s1.y-s2.y;
double zz = s1.z-s2.z;
return (xx*xx+yy*yy+zz*zz);
};
vector<double> ShollSWC(QList<NeuronSWC> & neuron, double step)
{
vector<long> ids;
// Reorder tree ids so that neuron.at(i).n=i+1
for(V3DLONG i=0;i<neuron.size();i++)
{
ids.push_back(neuron.at(i).n);
}
for(V3DLONG i=0;i<neuron.size();i++)
{
neuron[i].n=i+1;
if(neuron.at(i).pn !=-1)
{
neuron[i].pn=find(ids.begin(), ids.end(),neuron.at(i).pn) - ids.begin()+1;
}
}
//double somax,somay,somaz;
int soma_line;
vector <double> distance;
// This loop finds the soma
for(int i= 0; i<neuron.size(); i++)
{
if (neuron.at(i).pn == -1)
{
//somax= neuron.at(i).x;
//somay= neuron.at(i).y;
//somaz= neuron.at(i).z;
soma_line = i; // This line assigns the value i to the variable soma_line. Given that all the nodes of neuron will be explored (line 44) and only the node that has parent id -1 will be true in the if (line 46), soma_line will be assigned the soma node.
}
}
for(int i=0;i<neuron.size();i++)
{
double s;
s=computeDist2(neuron.at(i),neuron.at(soma_line));
distance.push_back(s);
}
double max = *max_element(distance.begin(),distance.end());
//int sum=0;(distance.at(parent
//for(int r=1;r<max;r+=50)
//{
// for(int j=o;j<distance.size();j++)
//{
// if(dis.[j]<r)
//{
// sum=sum+1;
// }
//}
vector<int> tipslist;
for (int i=0;i<neuron.size();i++)
{
int sum=0;
for (int j=0;j<neuron.size();j++)
{
if (neuron.at(i).n==neuron.at(j).pn)
{
sum=sum+1;
}
}
if (sum<1)
{
tipslist.push_back(i);
}
}
qDebug()<< tipslist.size();
vector<double> radius;
vector<double> crossings;
if(step<1 || step==VOID)
{
step=1;
}
radius.push_back(0);
crossings.push_back(0);
for (int i=int(step);i<max;i+=int(step))
{
radius.push_back(i);
int crss = 0;
for(int j=0; j<distance.size();j++)
{
if(distance.at(j)>=double(i) && distance.at(j)<double(i+step))
{
V3DLONG parent = neuron.at(j).pn-1;
if(parent == -2) parent = soma_line;
if(distance.at(parent)<double(i))
{
crss++;
}
}
if(distance.at(j)<=double(i) && distance.at(j)>double(i-step))
{
V3DLONG parent = neuron.at(j).pn-1;
if(parent == -2) parent = soma_line;
if(distance.at(parent)>double(i))
{
crss++;
}
}
}
crossings.push_back(crss);
}
for(int i=0; i<crossings.size(); i++)
{
qDebug() << radius.at(i) << crossings.at(i);
}
//qDebug() << max << somay << somaz;
return crossings;
}
| 26.993421 | 264 | 0.483305 | [
"vector"
] |
f5c57cf396a47d51066d7f463727f986cf1b272a | 3,125 | cc | C++ | iot/src/model/QueryProductListResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | iot/src/model/QueryProductListResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | iot/src/model/QueryProductListResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/iot/model/QueryProductListResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Iot;
using namespace AlibabaCloud::Iot::Model;
QueryProductListResult::QueryProductListResult() :
ServiceResult()
{}
QueryProductListResult::QueryProductListResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryProductListResult::~QueryProductListResult()
{}
void QueryProductListResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["CurrentPage"].isNull())
data_.currentPage = std::stoi(dataNode["CurrentPage"].asString());
if(!dataNode["PageCount"].isNull())
data_.pageCount = std::stoi(dataNode["PageCount"].asString());
if(!dataNode["PageSize"].isNull())
data_.pageSize = std::stoi(dataNode["PageSize"].asString());
if(!dataNode["Total"].isNull())
data_.total = std::stoi(dataNode["Total"].asString());
auto allList = value["List"]["ProductInfo"];
for (auto value : allList)
{
Data::ProductInfo productInfoObject;
if(!value["GmtCreate"].isNull())
productInfoObject.gmtCreate = std::stol(value["GmtCreate"].asString());
if(!value["DataFormat"].isNull())
productInfoObject.dataFormat = std::stoi(value["DataFormat"].asString());
if(!value["Description"].isNull())
productInfoObject.description = value["Description"].asString();
if(!value["DeviceCount"].isNull())
productInfoObject.deviceCount = std::stoi(value["DeviceCount"].asString());
if(!value["NodeType"].isNull())
productInfoObject.nodeType = std::stoi(value["NodeType"].asString());
if(!value["ProductKey"].isNull())
productInfoObject.productKey = value["ProductKey"].asString();
if(!value["ProductName"].isNull())
productInfoObject.productName = value["ProductName"].asString();
data_.list.push_back(productInfoObject);
}
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["ErrorMessage"].isNull())
errorMessage_ = value["ErrorMessage"].asString();
}
QueryProductListResult::Data QueryProductListResult::getData()const
{
return data_;
}
std::string QueryProductListResult::getErrorMessage()const
{
return errorMessage_;
}
std::string QueryProductListResult::getCode()const
{
return code_;
}
bool QueryProductListResult::getSuccess()const
{
return success_;
}
| 30.940594 | 78 | 0.72864 | [
"model"
] |
f5c6dcf5906b681a35fafca9308b350ab335606c | 5,380 | cpp | C++ | admin/activec/samples/sdksamples/multisel/basesnap.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/activec/samples/sdksamples/wmi/basesnap.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/activec/samples/sdksamples/wmi/basesnap.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //==============================================================;
//
// This source code is only intended as a supplement to existing Microsoft documentation.
//
//
//
//
// 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) 1999 Microsoft Corporation. All Rights Reserved.
//
//
//
//==============================================================;
#include <objbase.h>
#include <olectl.h>
#include <initguid.h>
#include "guids.h"
#include "basesnap.h"
#include "Comp.h"
#include "CompData.h"
#include "About.h"
#include "Registry.h"
// our globals
HINSTANCE g_hinst;
BOOL WINAPI DllMain(HINSTANCE hinstDLL,
DWORD fdwReason,
void* lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH) {
g_hinst = hinstDLL;
}
return TRUE;
}
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvObj)
{
if ((rclsid != CLSID_CComponentData) && (rclsid != CLSID_CSnapinAbout))
return CLASS_E_CLASSNOTAVAILABLE;
if (!ppvObj)
return E_FAIL;
*ppvObj = NULL;
// We can only hand out IUnknown and IClassFactory pointers. Fail
// if they ask for anything else.
if (!IsEqualIID(riid, IID_IUnknown) && !IsEqualIID(riid, IID_IClassFactory))
return E_NOINTERFACE;
CClassFactory *pFactory = NULL;
// make the factory passing in the creation function for the type of object they want
if (rclsid == CLSID_CComponentData)
pFactory = new CClassFactory(CClassFactory::COMPONENT);
else if (rclsid == CLSID_CSnapinAbout)
pFactory = new CClassFactory(CClassFactory::ABOUT);
if (NULL == pFactory)
return E_OUTOFMEMORY;
HRESULT hr = pFactory->QueryInterface(riid, ppvObj);
return hr;
}
STDAPI DllCanUnloadNow(void)
{
if (g_uObjects == 0 && g_uSrvLock == 0)
return S_OK;
else
return S_FALSE;
}
CClassFactory::CClassFactory(FACTORY_TYPE factoryType)
: m_cref(0), m_factoryType(factoryType)
{
OBJECT_CREATED
}
CClassFactory::~CClassFactory()
{
OBJECT_DESTROYED
}
STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, LPVOID *ppv)
{
if (!ppv)
return E_FAIL;
*ppv = NULL;
if (IsEqualIID(riid, IID_IUnknown))
*ppv = static_cast<IClassFactory *>(this);
else
if (IsEqualIID(riid, IID_IClassFactory))
*ppv = static_cast<IClassFactory *>(this);
if (*ppv)
{
reinterpret_cast<IUnknown *>(*ppv)->AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) CClassFactory::AddRef()
{
return InterlockedIncrement((LONG *)&m_cref);
}
STDMETHODIMP_(ULONG) CClassFactory::Release()
{
if (InterlockedDecrement((LONG *)&m_cref) == 0)
{
delete this;
return 0;
}
return m_cref;
}
STDMETHODIMP CClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, LPVOID * ppvObj)
{
HRESULT hr;
void* pObj;
if (!ppvObj)
return E_FAIL;
*ppvObj = NULL;
// Our object does does not support aggregation, so we need to
// fail if they ask us to do aggregation.
if (pUnkOuter)
return CLASS_E_NOAGGREGATION;
if (COMPONENT == m_factoryType) {
pObj = new CComponentData();
} else {
pObj = new CSnapinAbout();
}
if (!pObj)
return E_OUTOFMEMORY;
// QueryInterface will do the AddRef() for us, so we do not
// do it in this function
hr = ((LPUNKNOWN)pObj)->QueryInterface(riid, ppvObj);
if (FAILED(hr))
delete pObj;
return hr;
}
STDMETHODIMP CClassFactory::LockServer(BOOL fLock)
{
if (fLock)
InterlockedIncrement((LONG *)&g_uSrvLock);
else
InterlockedDecrement((LONG *)&g_uSrvLock);
return S_OK;
}
//////////////////////////////////////////////////////////
//
// Exported functions
//
//
// Server registration
//
STDAPI DllRegisterServer()
{
HRESULT hr = SELFREG_E_CLASS;
_TCHAR szName[256];
_TCHAR szSnapInName[256];
LoadString(g_hinst, IDS_NAME, szName, sizeof(szName));
LoadString(g_hinst, IDS_SNAPINNAME, szSnapInName, sizeof(szSnapInName));
_TCHAR szAboutName[256];
LoadString(g_hinst, IDS_ABOUTNAME, szAboutName, sizeof(szAboutName));
// register our CoClasses
hr = RegisterServer(g_hinst,
CLSID_CComponentData,
szName);
if SUCCEEDED(hr)
hr = RegisterServer(g_hinst,
CLSID_CSnapinAbout,
szAboutName);
// place the registry information for SnapIns
if SUCCEEDED(hr)
hr = RegisterSnapin(CLSID_CComponentData, szSnapInName, CLSID_CSnapinAbout, FALSE);
return hr;
}
STDAPI DllUnregisterServer()
{
if (UnregisterServer(CLSID_CComponentData) == S_OK)
return UnregisterSnapin(CLSID_CComponentData);
else
return E_FAIL;
}
| 23.80531 | 94 | 0.588848 | [
"object"
] |
f5c8f60cd8cc0aee3b4d473d6648b66fe2cb2737 | 5,704 | cc | C++ | unittests/libtests/meshio/TestDataWriterHDF5ExtFaultMesh.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | 1 | 2021-09-09T06:24:11.000Z | 2021-09-09T06:24:11.000Z | unittests/libtests/meshio/TestDataWriterHDF5ExtFaultMesh.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | null | null | null | unittests/libtests/meshio/TestDataWriterHDF5ExtFaultMesh.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | null | null | null | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestDataWriterHDF5ExtFaultMesh.hh" // Implementation of class methods
#include "data/DataWriterData.hh" // USES DataWriterData
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/Field.hh" // USES Field
#include "pylith/topology/Fields.hh" // USES Fields
#include "pylith/meshio/MeshIOAscii.hh" // USES MeshIOAscii
#include "pylith/meshio/DataWriterHDF5Ext.hh" // USES DataWriterHDF5Ext
#include "pylith/faults/FaultCohesiveKin.hh" // USES FaultCohesiveKin
#include "pylith/faults/CohesiveTopology.hh" // USES CohesiveTopology
#include <map> // USES std::map
// ----------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( pylith::meshio::TestDataWriterHDF5ExtFaultMesh );
// ----------------------------------------------------------------------
// Setup testing data.
void
pylith::meshio::TestDataWriterHDF5ExtFaultMesh::setUp(void)
{ // setUp
PYLITH_METHOD_BEGIN;
TestDataWriterFaultMesh::setUp();
PYLITH_METHOD_END;
} // setUp
// ----------------------------------------------------------------------
// Tear down testing data.
void
pylith::meshio::TestDataWriterHDF5ExtFaultMesh::tearDown(void)
{ // tearDown
PYLITH_METHOD_BEGIN;
TestDataWriterFaultMesh::tearDown();
PYLITH_METHOD_END;
} // tearDown
// ----------------------------------------------------------------------
// Test constructor
void
pylith::meshio::TestDataWriterHDF5ExtFaultMesh::testConstructor(void)
{ // testConstructor
PYLITH_METHOD_BEGIN;
DataWriterHDF5Ext writer;
PYLITH_METHOD_END;
} // testConstructor
// ----------------------------------------------------------------------
// Test openTimeStep() and closeTimeStep()
void
pylith::meshio::TestDataWriterHDF5ExtFaultMesh::testOpenClose(void)
{ // testOpenClose
PYLITH_METHOD_BEGIN;
CPPUNIT_ASSERT(_mesh);
CPPUNIT_ASSERT(_data);
DataWriterHDF5Ext writer;
writer.filename(_data->timestepFilename);
const PylithScalar t = _data->time;
const int numTimeSteps = 1;
if (!_data->cellsLabel) {
writer.open(*_faultMesh, numTimeSteps);
writer.openTimeStep(t, *_faultMesh);
} else {
const char* label = _data->cellsLabel;
const int id = _data->labelId;
writer.open(*_faultMesh, numTimeSteps, label, id);
writer.openTimeStep(t, *_faultMesh, label, id);
} // else
writer.closeTimeStep();
writer.close();
checkFile(_data->timestepFilename);
PYLITH_METHOD_END;
} // testOpenClose
// ----------------------------------------------------------------------
// Test writeVertexField.
void
pylith::meshio::TestDataWriterHDF5ExtFaultMesh::testWriteVertexField(void)
{ // testWriteVertexField
PYLITH_METHOD_BEGIN;
CPPUNIT_ASSERT(_mesh);
CPPUNIT_ASSERT(_data);
DataWriterHDF5Ext writer;
topology::Fields vertexFields(*_faultMesh);
_createVertexFields(&vertexFields);
writer.filename(_data->vertexFilename);
const PylithScalar timeScale = 4.0;
writer.timeScale(timeScale);
const PylithScalar t = _data->time / timeScale;
const int nfields = _data->numVertexFields;
const int numTimeSteps = 1;
if (!_data->cellsLabel) {
writer.open(*_faultMesh, numTimeSteps);
writer.openTimeStep(t, *_faultMesh);
} else {
const char* label = _data->cellsLabel;
const int id = _data->labelId;
writer.open(*_faultMesh, numTimeSteps, label, id);
writer.openTimeStep(t, *_faultMesh, label, id);
} // else
for (int i=0; i < nfields; ++i) {
topology::Field& field = vertexFields.get(_data->vertexFieldsInfo[i].name);
writer.writeVertexField(t, field, *_faultMesh);
} // for
writer.closeTimeStep();
writer.close();
checkFile(_data->vertexFilename);
PYLITH_METHOD_END;
} // testWriteVertexField
// ----------------------------------------------------------------------
// Test writeCellField.
void
pylith::meshio::TestDataWriterHDF5ExtFaultMesh::testWriteCellField(void)
{ // testWriteCellField
PYLITH_METHOD_BEGIN;
CPPUNIT_ASSERT(_mesh);
CPPUNIT_ASSERT(_data);
DataWriterHDF5Ext writer;
topology::Fields cellFields(*_faultMesh);
_createCellFields(&cellFields);
writer.filename(_data->cellFilename);
const PylithScalar timeScale = 4.0;
writer.timeScale(timeScale);
const PylithScalar t = _data->time / timeScale;
const int nfields = _data->numCellFields;
const int numTimeSteps = 1;
if (!_data->cellsLabel) {
writer.open(*_faultMesh, numTimeSteps);
writer.openTimeStep(t, *_faultMesh);
for (int i=0; i < nfields; ++i) {
topology::Field& field = cellFields.get(_data->cellFieldsInfo[i].name);
writer.writeCellField(t, field);
} // for
} else {
const char* label = _data->cellsLabel;
const int id = _data->labelId;
writer.open(*_faultMesh, numTimeSteps, label, id);
writer.openTimeStep(t, *_faultMesh, label, id);
for (int i=0; i < nfields; ++i) {
topology::Field& field = cellFields.get(_data->cellFieldsInfo[i].name);
writer.writeCellField(t, field, label, id);
} // for
} // else
writer.closeTimeStep();
writer.close();
checkFile(_data->cellFilename);
PYLITH_METHOD_END;
} // testWriteCellField
// End of file
| 28.237624 | 82 | 0.640252 | [
"mesh"
] |
f5cbf35727352238e2356a064bc01d5eab5f0aa8 | 3,960 | cpp | C++ | src/cppad.git/speed/src/link_poly.cpp | yinzixuan126/my_udacity | cada1bc047cd21282b008a0eb85a1df52fd94034 | [
"MIT"
] | 1 | 2019-11-05T02:23:47.000Z | 2019-11-05T02:23:47.000Z | src/cppad.git/speed/src/link_poly.cpp | yinzixuan126/my_udacity | cada1bc047cd21282b008a0eb85a1df52fd94034 | [
"MIT"
] | null | null | null | src/cppad.git/speed/src/link_poly.cpp | yinzixuan126/my_udacity | cada1bc047cd21282b008a0eb85a1df52fd94034 | [
"MIT"
] | 1 | 2019-11-05T02:23:51.000Z | 2019-11-05T02:23:51.000Z | /* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
/*
$begin link_poly$$
$spell
poly
bool
CppAD
ddp
$$
$section Speed Testing Second Derivative of a Polynomial$$
$head Prototype$$
$codei%extern bool link_poly(
size_t %size% ,
size_t %repeat% ,
CppAD::vector<double> &%a% ,
CppAD::vector<double> &%z% ,
CppAD::vector<double> &%ddp
);
%$$
$head Purpose$$
Each $cref/package/speed_main/package/$$
must define a version of this routine as specified below.
This is used by the $cref speed_main$$ program
to run the corresponding speed and correctness tests.
$head Method$$
The same template routine $cref Poly$$ is used
by the different AD packages.
$head Return Value$$
If this speed test is not yet
supported by a particular $icode package$$,
the corresponding return value for $code link_poly$$
should be $code false$$.
$head size$$
The argument $icode size$$ is the order of the polynomial
(the number of coefficients in the polynomial).
$head repeat$$
The argument $icode repeat$$ is the number of different argument values
that the second derivative (or just the polynomial) will be computed at.
$head a$$
The argument $icode a$$ is a vector with $icode%size%$$ elements.
The input value of its elements does not matter.
The output value of its elements is the coefficients of the
polynomial that is differentiated
($th i$$ element is coefficient of order $icode i$$).
$head z$$
The argument $icode z$$ is a vector with one element.
The input value of the element does not matter.
The output of its element is the polynomial argument value
were the last second derivative (or polynomial value) was computed.
$head ddp$$
The argument $icode ddp$$ is a vector with one element.
The input value of its element does not matter.
The output value of its element is the
second derivative of the polynomial with respect to it's argument value.
$subhead double$$
In the case where $icode package$$ is $code double$$,
the output value of the element of $icode ddp$$
is the polynomial value (the second derivative is not computed).
$end
-----------------------------------------------------------------------------
*/
# include <cppad/utility/vector.hpp>
# include <cppad/utility/poly.hpp>
# include <cppad/utility/near_equal.hpp>
extern bool link_poly(
size_t size ,
size_t repeat ,
CppAD::vector<double> &a ,
CppAD::vector<double> &z ,
CppAD::vector<double> &ddp
);
bool available_poly(void)
{ size_t size = 10;
size_t repeat = 1;
CppAD::vector<double> a(size), z(1), ddp(1);
return link_poly(size, repeat, a, z, ddp);
}
bool correct_poly(bool is_package_double)
{ size_t size = 10;
size_t repeat = 1;
CppAD::vector<double> a(size), z(1), ddp(1);
double eps99 = 99.0 * std::numeric_limits<double>::epsilon();
link_poly(size, repeat, a, z, ddp);
size_t k;
double check;
if( is_package_double )
k = 0;
else
k = 2;
check = CppAD::Poly(k, a, z[0]);
bool ok = CppAD::NearEqual(check, ddp[0], eps99, eps99);
return ok;
}
void speed_poly(size_t size, size_t repeat)
{ // free statically allocated memory
if( size == 0 && repeat == 0 )
return;
//
CppAD::vector<double> a(size), z(1), ddp(1);
link_poly(size, repeat, a, z, ddp);
return;
}
| 29.774436 | 79 | 0.637121 | [
"vector"
] |
f5cf7a293ccc48e078ea3e9bc5600036b1d3f843 | 132,414 | hpp | C++ | jitify.hpp | trevorsm7/jitify | 62ebea908da1eddd1da9394ae36965d773a6adda | [
"BSD-3-Clause"
] | null | null | null | jitify.hpp | trevorsm7/jitify | 62ebea908da1eddd1da9394ae36965d773a6adda | [
"BSD-3-Clause"
] | null | null | null | jitify.hpp | trevorsm7/jitify | 62ebea908da1eddd1da9394ae36965d773a6adda | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017-2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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.
*/
/*
-----------
Jitify 0.9
-----------
A C++ library for easy integration of CUDA runtime compilation into
existing codes.
--------------
How to compile
--------------
Compiler dependencies: <jitify.hpp>, -std=c++11
Linker dependencies: dl cuda nvrtc
--------------------------------------
Embedding source files into executable
--------------------------------------
g++ ... -ldl -rdynamic
-Wl,-b,binary,my_kernel.cu,include/my_header.cuh,-b,default nvcc ... -ldl
-Xcompiler "-rdynamic
-Wl\,-b\,binary\,my_kernel.cu\,include/my_header.cuh\,-b\,default"
JITIFY_INCLUDE_EMBEDDED_FILE(my_kernel_cu);
JITIFY_INCLUDE_EMBEDDED_FILE(include_my_header_cuh);
----
TODO
----
Extract valid compile options and pass the rest to cuModuleLoadDataEx
See if can have stringified headers automatically looked-up
by having stringify add them to a (static) global map.
The global map can be updated by creating a static class instance
whose constructor performs the registration.
Can then remove all headers from JitCache constructor in example code
See other TODOs in code
*/
/*! \file jitify.hpp
* \brief The Jitify library header
*/
/*! \mainpage Jitify - A C++ library that simplifies the use of NVRTC
* \p Use class jitify::JitCache to manage and launch JIT-compiled CUDA
* kernels.
*
* \p Use namespace jitify::reflection to reflect types and values into
* code-strings.
*
* \p Use JITIFY_INCLUDE_EMBEDDED_FILE() to declare files that have been
* embedded into the executable using the GCC linker.
*
* \p Use jitify::parallel_for and JITIFY_LAMBDA() to generate and launch
* simple kernels.
*/
#pragma once
#ifndef JITIFY_THREAD_SAFE
#define JITIFY_THREAD_SAFE 1
#endif
// WAR for MSVC not correctly defining __cplusplus (before MSVC 2017)
#ifdef _MSVC_LANG
#pragma push_macro("__cplusplus")
#undef __cplusplus
#define __cplusplus _MSVC_LANG
#endif
#if defined(_WIN32) || defined(_WIN64)
// WAR for strtok_r being called strtok_s on Windows
#pragma push_macro("strtok_r")
#undef strtok_r
#define strtok_r strtok_s
#endif
#include <dlfcn.h>
#include <stdint.h>
#include <algorithm>
#include <cstring> // For strtok_r etc.
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <vector>
#if JITIFY_THREAD_SAFE
#include <mutex>
#endif
#include <cuda.h>
#include <cuda_runtime_api.h> // For dim3, cudaStream_t
#if CUDA_VERSION >= 8000
#define NVRTC_GET_TYPE_NAME 1
#endif
#include <nvrtc.h>
#ifndef JITIFY_PRINT_LOG
#define JITIFY_PRINT_LOG 1
#endif
#if JITIFY_PRINT_ALL
#define JITIFY_PRINT_INSTANTIATION 1
#define JITIFY_PRINT_SOURCE 1
#define JITIFY_PRINT_LOG 1
#define JITIFY_PRINT_PTX 1
#define JITIFY_PRINT_LINKER_LOG 1
#define JITIFY_PRINT_LAUNCH 1
#endif
#define JITIFY_FORCE_UNDEFINED_SYMBOL(x) void* x##_forced = (void*)&x
/*! Include a source file that has been embedded into the executable using the
* GCC linker.
* \param name The name of the source file (<b>not</b> as a string), which must
* be sanitized by replacing non-alpha-numeric characters with underscores.
* E.g., \code{.cpp}JITIFY_INCLUDE_EMBEDDED_FILE(my_header_h)\endcode will
* include the embedded file "my_header.h".
* \note Files declared with this macro can be referenced using
* their original (unsanitized) filenames when creating a \p
* jitify::Program instance.
*/
#define JITIFY_INCLUDE_EMBEDDED_FILE(name) \
extern "C" uint8_t _jitify_binary_##name##_start[] asm("_binary_" #name \
"_start"); \
extern "C" uint8_t _jitify_binary_##name##_end[] asm("_binary_" #name \
"_end"); \
JITIFY_FORCE_UNDEFINED_SYMBOL(_jitify_binary_##name##_start); \
JITIFY_FORCE_UNDEFINED_SYMBOL(_jitify_binary_##name##_end)
/*! Jitify library namespace
*/
namespace jitify {
/*! Source-file load callback.
*
* \param filename The name of the requested source file.
* \param tmp_stream A temporary stream that can be used to hold source code.
* \return A pointer to an input stream containing the source code, or NULL
* to defer loading of the file to Jitify's file-loading mechanisms.
*/
typedef std::istream* (*file_callback_type)(std::string filename,
std::iostream& tmp_stream);
// Exclude from Doxygen
//! \cond
class JitCache;
// Simple cache using LRU discard policy
template <typename KeyType, typename ValueType>
class ObjectCache {
public:
typedef KeyType key_type;
typedef ValueType value_type;
private:
typedef std::map<key_type, value_type> object_map;
typedef std::deque<key_type> key_rank;
typedef typename key_rank::iterator rank_iterator;
object_map _objects;
key_rank _ranked_keys;
size_t _capacity;
inline void discard_old(size_t n = 0) {
if (n > _capacity) {
throw std::runtime_error("Insufficient capacity in cache");
}
while (_objects.size() > _capacity - n) {
key_type discard_key = _ranked_keys.back();
_ranked_keys.pop_back();
_objects.erase(discard_key);
}
}
public:
inline ObjectCache(size_t capacity = 8) : _capacity(capacity) {}
inline void resize(size_t capacity) {
_capacity = capacity;
this->discard_old();
}
inline bool contains(const key_type& k) const { return _objects.count(k); }
inline void touch(const key_type& k) {
if (!this->contains(k)) {
throw std::runtime_error("Key not found in cache");
}
rank_iterator rank = std::find(_ranked_keys.begin(), _ranked_keys.end(), k);
if (rank != _ranked_keys.begin()) {
// Move key to front of ranks
_ranked_keys.erase(rank);
_ranked_keys.push_front(k);
}
}
inline value_type& get(const key_type& k) {
if (!this->contains(k)) {
throw std::runtime_error("Key not found in cache");
}
this->touch(k);
return _objects[k];
}
inline value_type& insert(const key_type& k,
const value_type& v = value_type()) {
this->discard_old(1);
_ranked_keys.push_front(k);
return _objects.insert(std::make_pair(k, v)).first->second;
}
template <typename... Args>
inline value_type& emplace(const key_type& k, Args&&... args) {
this->discard_old(1);
// Note: Use of piecewise_construct allows non-movable non-copyable types
auto iter = _objects
.emplace(std::piecewise_construct, std::forward_as_tuple(k),
std::forward_as_tuple(args...))
.first;
_ranked_keys.push_front(iter->first);
return iter->second;
}
};
namespace detail {
// Convenience wrapper for std::vector that provides handy constructors
template <typename T>
class vector : public std::vector<T> {
typedef std::vector<T> super_type;
public:
vector() : super_type() {}
vector(size_t n) : super_type(n) {} // Note: Not explicit, allows =0
vector(std::vector<T> const& vals) : super_type(vals) {}
template <int N>
vector(T const (&vals)[N]) : super_type(vals, vals + N) {}
#if defined __cplusplus && __cplusplus >= 201103L
vector(std::vector<T>&& vals) : super_type(vals) {}
vector(std::initializer_list<T> vals) : super_type(vals) {}
#endif
};
// Helper functions for parsing/manipulating source code
inline std::string replace_characters(std::string str,
std::string const& oldchars,
char newchar) {
size_t i = str.find_first_of(oldchars);
while (i != std::string::npos) {
str[i] = newchar;
i = str.find_first_of(oldchars, i + 1);
}
return str;
}
inline std::string sanitize_filename(std::string name) {
return replace_characters(name, "/\\.-: ?%*|\"<>", '_');
}
class EmbeddedData {
void* _app;
EmbeddedData(EmbeddedData const&);
EmbeddedData& operator=(EmbeddedData const&);
public:
EmbeddedData() {
_app = dlopen(NULL, RTLD_LAZY);
if (!_app) {
throw std::runtime_error(std::string("dlopen failed: ") + dlerror());
}
dlerror(); // Clear any existing error
}
~EmbeddedData() {
if (_app) {
dlclose(_app);
}
}
const uint8_t* operator[](std::string key) const {
key = sanitize_filename(key);
key = "_binary_" + key;
uint8_t const* data = (uint8_t const*)dlsym(_app, key.c_str());
if (!data) {
throw std::runtime_error(std::string("dlsym failed: ") + dlerror());
}
return data;
}
const uint8_t* begin(std::string key) const {
return (*this)[key + "_start"];
}
const uint8_t* end(std::string key) const { return (*this)[key + "_end"]; }
};
inline bool is_tokenchar(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_';
}
inline std::string replace_token(std::string src, std::string token,
std::string replacement) {
size_t i = src.find(token);
while (i != std::string::npos) {
if (i == 0 || i == src.size() - token.size() ||
(!is_tokenchar(src[i - 1]) && !is_tokenchar(src[i + token.size()]))) {
src.replace(i, token.size(), replacement);
i += replacement.size();
} else {
i += token.size();
}
i = src.find(token, i);
}
return src;
}
inline std::string path_base(std::string p) {
// "/usr/local/myfile.dat" -> "/usr/local"
// "foo/bar" -> "foo"
// "foo/bar/" -> "foo/bar"
#if defined _WIN32 || defined _WIN64
char sep = '\\';
#else
char sep = '/';
#endif
size_t i = p.find_last_of(sep);
if (i != std::string::npos) {
return p.substr(0, i);
} else {
return "";
}
}
inline std::string path_join(std::string p1, std::string p2) {
#ifdef _WIN32
char sep = '\\';
#else
char sep = '/';
#endif
if (p1.size() && p2.size() && p2[0] == sep) {
throw std::invalid_argument("Cannot join to absolute path");
}
if (p1.size() && p1[p1.size() - 1] != sep) {
p1 += sep;
}
return p1 + p2;
}
inline unsigned long long hash_larson64(const char* s,
unsigned long long seed = 0) {
unsigned long long hash = seed;
while (*s) {
hash = hash * 101 + *s++;
}
return hash;
}
inline uint64_t hash_combine(uint64_t a, uint64_t b) {
// Note: The magic number comes from the golden ratio
return a ^ (0x9E3779B97F4A7C17ull + b + (b >> 2) + (a << 6));
}
inline bool extract_include_info_from_compile_error(std::string log,
std::string& name,
std::string& parent,
int& line_num) {
static const std::string pattern = "cannot open source file \"";
size_t beg = log.find(pattern);
if (beg == std::string::npos) {
return false;
}
beg += pattern.size();
size_t end = log.find("\"", beg);
name = log.substr(beg, end - beg);
size_t line_beg = log.rfind("\n", beg);
if (line_beg == std::string::npos) {
line_beg = 0;
} else {
line_beg += 1;
}
size_t split = log.find("(", line_beg);
parent = log.substr(line_beg, split - line_beg);
line_num = atoi(
log.substr(split + 1, log.find(")", split + 1) - (split + 1)).c_str());
return true;
}
inline std::string comment_out_code_line(int line_num, std::string source) {
size_t beg = 0;
for (int i = 1; i < line_num; ++i) {
beg = source.find("\n", beg) + 1;
}
return (source.substr(0, beg) + "//" + source.substr(beg));
}
inline void print_with_line_numbers(std::string const& source) {
int linenum = 1;
std::stringstream source_ss(source);
for (std::string line; std::getline(source_ss, line); ++linenum) {
std::cout << std::setfill(' ') << std::setw(3) << linenum << " " << line
<< std::endl;
}
}
inline void print_compile_log(std::string program_name,
std::string const& log) {
std::cout << "---------------------------------------------------"
<< std::endl;
std::cout << "--- JIT compile log for " << program_name << " ---"
<< std::endl;
std::cout << "---------------------------------------------------"
<< std::endl;
std::cout << log << std::endl;
std::cout << "---------------------------------------------------"
<< std::endl;
}
inline std::vector<std::string> split_string(std::string str,
long maxsplit = -1,
std::string delims = " \t") {
std::vector<std::string> results;
if (maxsplit == 0) {
results.push_back(str);
return results;
}
// Note: +1 to include NULL-terminator
std::vector<char> v_str(str.c_str(), str.c_str() + (str.size() + 1));
char* c_str = v_str.data();
char* saveptr = c_str;
char* token = nullptr;
for (long i = 0; i != maxsplit; ++i) {
token = ::strtok_r(c_str, delims.c_str(), &saveptr);
c_str = 0;
if (!token) {
return results;
}
results.push_back(token);
}
// Check if there's a final piece
token += ::strlen(token) + 1;
if (token - v_str.data() < (ptrdiff_t)str.size()) {
// Find the start of the final piece
token += ::strspn(token, delims.c_str());
if (*token) {
results.push_back(token);
}
}
return results;
}
inline bool load_source(
std::string filename, std::map<std::string, std::string>& sources,
std::string current_dir = "",
std::vector<std::string> include_paths = std::vector<std::string>(),
file_callback_type file_callback = 0,
std::map<std::string, std::string>* fullpaths = nullptr) {
std::istream* source_stream = 0;
std::stringstream string_stream;
std::ifstream file_stream;
// First detect direct source-code string ("my_program\nprogram_code...")
size_t newline_pos = filename.find("\n");
if (newline_pos != std::string::npos) {
std::string source = filename.substr(newline_pos + 1);
filename = filename.substr(0, newline_pos);
string_stream << source;
source_stream = &string_stream;
}
if (sources.count(filename)) {
// Already got this one
return true;
}
if (!source_stream) {
std::string fullpath = path_join(current_dir, filename);
// Try loading from callback
if (!file_callback ||
!(source_stream = file_callback(fullpath, string_stream))) {
// Try loading as embedded file
EmbeddedData embedded;
std::string source;
try {
source.assign(embedded.begin(fullpath), embedded.end(fullpath));
string_stream << source;
source_stream = &string_stream;
} catch (std::runtime_error) {
// Finally, try loading from filesystem
file_stream.open(fullpath.c_str());
if (!file_stream) {
bool found_file = false;
for (int i = 0; i < (int)include_paths.size(); ++i) {
fullpath = path_join(include_paths[i], filename);
file_stream.open(fullpath.c_str());
if (file_stream) {
found_file = true;
break;
}
}
if (!found_file) {
return false;
}
}
source_stream = &file_stream;
}
}
if (fullpaths) {
// Record the full file path corresponding to this include name.
(*fullpaths)[filename] = fullpath;
}
}
sources[filename] = std::string();
std::string& source = sources[filename];
std::string line;
size_t linenum = 0;
unsigned long long hash = 0;
bool pragma_once = false;
bool remove_next_blank_line = false;
while (std::getline(*source_stream, line)) {
++linenum;
// HACK WAR for static variables not allowed on the device (unless
// __shared__)
// TODO: This breaks static member variables
// line = replace_token(line, "static const", "/*static*/ const");
// TODO: Need to watch out for /* */ comments too
std::string cleanline =
line.substr(0, line.find("//")); // Strip line comments
// if( cleanline.back() == "\r" ) { // Remove Windows line ending
// cleanline = cleanline.substr(0, cleanline.size()-1);
//}
// TODO: Should trim whitespace before checking .empty()
if (cleanline.empty() && remove_next_blank_line) {
remove_next_blank_line = false;
continue;
}
// Maintain a file hash for use in #pragma once WAR
hash = hash_larson64(line.c_str(), hash);
if (cleanline.find("#pragma once") != std::string::npos) {
pragma_once = true;
// Note: This is an attempt to recover the original line numbering,
// which otherwise gets off-by-one due to the include guard.
remove_next_blank_line = true;
// line = "//" + line; // Comment out the #pragma once line
continue;
}
// HACK WAR for Thrust using "#define FOO #pragma bar"
size_t pragma_beg = cleanline.find("#pragma ");
if (pragma_beg != std::string::npos) {
std::string line_after_pragma = line.substr(pragma_beg);
std::vector<std::string> pragma_split =
split_string(line_after_pragma, 2);
line =
(line.substr(0, pragma_beg) + "_Pragma(\"" + pragma_split[1] + "\")");
if (pragma_split.size() == 3) {
line += " " + pragma_split[2];
}
}
source += line + "\n";
}
// HACK TESTING (WAR for cub)
// source = "#define cudaDeviceSynchronize() cudaSuccess\n" + source;
////source = "cudaError_t cudaDeviceSynchronize() { return cudaSuccess; }\n" +
/// source;
// WAR for #pragma once causing problems when there are multiple inclusions
// of the same header from different paths.
if (pragma_once) {
std::stringstream ss;
ss << std::uppercase << std::hex << std::setw(8) << std::setfill('0')
<< hash;
std::string include_guard_name = "_JITIFY_INCLUDE_GUARD_" + ss.str() + "\n";
std::string include_guard_header;
include_guard_header += "#ifndef " + include_guard_name;
include_guard_header += "#define " + include_guard_name;
std::string include_guard_footer;
include_guard_footer += "#endif // " + include_guard_name;
source = include_guard_header + source + "\n" + include_guard_footer;
}
// return filename;
return true;
}
} // namespace detail
//! \endcond
/*! Jitify reflection utilities namespace
*/
namespace reflection {
// Provides type and value reflection via a function 'reflect':
// reflect<Type>() -> "Type"
// reflect(value) -> "(T)value"
// reflect<VAL>() -> "VAL"
// reflect<Type,VAL> -> "VAL"
// reflect_template<float,NonType<int,7>,char>() -> "<float,7,char>"
// reflect_template({"float", "7", "char"}) -> "<float,7,char>"
/*! A wrapper class for non-type template parameters.
*/
template <typename T, T VALUE_>
struct NonType {
#if defined __cplusplus && __cplusplus >= 201103L
constexpr
#endif
static T VALUE = VALUE_;
};
// Forward declaration
template <typename T>
inline std::string reflect(T const& value);
//! \cond
namespace detail {
template <typename T>
inline std::string value_string(const T& x) {
std::stringstream ss;
ss << x;
return ss.str();
}
// WAR for non-printable characters
template <>
inline std::string value_string<char>(const char& x) {
std::stringstream ss;
ss << (int)x;
return ss.str();
}
template <>
inline std::string value_string<signed char>(const signed char& x) {
std::stringstream ss;
ss << (int)x;
return ss.str();
}
template <>
inline std::string value_string<unsigned char>(const unsigned char& x) {
std::stringstream ss;
ss << (int)x;
return ss.str();
}
template <>
inline std::string value_string<wchar_t>(const wchar_t& x) {
std::stringstream ss;
ss << (long)x;
return ss.str();
}
// Specialisation for bool true/false literals
template <>
inline std::string value_string<bool>(const bool& x) {
return x ? "true" : "false";
}
//#if CUDA_VERSION < 8000
#ifdef _MSC_VER // MSVC compiler
inline std::string demangle(const char* verbose_name) {
// Strips annotations from the verbose name returned by typeid(X).name()
std::string result = verbose_name;
result = jitify::detail::replace_token(result, "__ptr64", "");
result = jitify::detail::replace_token(result, "__cdecl", "");
result = jitify::detail::replace_token(result, "class", "");
result = jitify::detail::replace_token(result, "struct", "");
return result;
}
#else // not MSVC
#include <cxxabi.h>
inline std::string demangle(const char* mangled_name) {
size_t bufsize = 1024;
auto buf = std::unique_ptr<char, decltype(free)*>(
reinterpret_cast<char*>(malloc(bufsize)), free);
std::string demangled_name;
int status;
char* demangled_ptr =
abi::__cxa_demangle(mangled_name, buf.get(), &bufsize, &status);
if (status == 0) {
demangled_name = demangled_ptr; // all worked as expected
} else if (status == -2) {
demangled_name = mangled_name; // we interpret this as plain C name
} else if (status == -1) {
throw std::runtime_error(
std::string("memory allocation failure in __cxa_demangle"));
} else if (status == -3) {
throw std::runtime_error(std::string("invalid argument to __cxa_demangle"));
}
return demangled_name;
}
#endif // not MSVC
//#endif // CUDA_VERSION < 8000
template <typename T>
struct type_reflection {
inline static std::string name() {
//#if CUDA_VERSION < 8000
// WAR for typeid discarding cv qualifiers on value-types
// We use a pointer type to maintain cv qualifiers, then strip out the '*'
std::string no_cv_name = demangle(typeid(T).name());
std::string ptr_name = demangle(typeid(T*).name());
// Find the right '*' by diffing the type name and ptr name
// Note that the '*' will also be prefixed with the cv qualifiers
size_t diff_begin =
std::mismatch(no_cv_name.begin(), no_cv_name.end(), ptr_name.begin())
.first -
no_cv_name.begin();
size_t star_begin = ptr_name.find("*", diff_begin);
if (star_begin == std::string::npos) {
throw std::runtime_error("Type reflection failed: " + ptr_name);
}
std::string name =
ptr_name.substr(0, star_begin) + ptr_name.substr(star_begin + 1);
return name;
//#else
// std::string ret;
// nvrtcResult status = nvrtcGetTypeName<T>(&ret);
// if( status != NVRTC_SUCCESS ) {
// throw std::runtime_error(std::string("nvrtcGetTypeName
// failed:
//")+ nvrtcGetErrorString(status));
// }
// return ret;
//#endif
}
};
template <typename T, T VALUE>
struct type_reflection<NonType<T, VALUE> > {
inline static std::string name() {
return jitify::reflection::reflect(VALUE);
}
};
} // namespace detail
//! \endcond
/*! Create an Instance object that contains a const reference to the
* value. We use this to wrap abstract objects from which we want to extract
* their type at runtime (e.g., derived type). This is used to facilitate
* templating on derived type when all we know at compile time is abstract
* type.
*/
template <typename T>
struct Instance {
const T& value;
Instance(const T& value) : value(value) {}
};
/*! Create an Instance object from which we can extract the value's run-time
* type.
* \param value The const value to be captured.
*/
template <typename T>
inline Instance<T const> instance_of(T const& value) {
return Instance<T const>(value);
}
/*! A wrapper used for representing types as values.
*/
template <typename T>
struct Type {};
// Type reflection
// E.g., reflect<float>() -> "float"
// Note: This strips trailing const and volatile qualifiers
/*! Generate a code-string for a type.
* \code{.cpp}reflect<float>() --> "float"\endcode
*/
template <typename T>
inline std::string reflect() {
return detail::type_reflection<T>::name();
}
// Value reflection
// E.g., reflect(3.14f) -> "(float)3.14"
/*! Generate a code-string for a value.
* \code{.cpp}reflect(3.14f) --> "(float)3.14"\endcode
*/
template <typename T>
inline std::string reflect(T const& value) {
return "(" + reflect<T>() + ")" + detail::value_string(value);
}
// Non-type template arg reflection (implicit conversion to int64_t)
// E.g., reflect<7>() -> "(int64_t)7"
/*! Generate a code-string for an integer non-type template argument.
* \code{.cpp}reflect<7>() --> "(int64_t)7"\endcode
*/
template <long long N>
inline std::string reflect() {
return reflect<NonType<int, N> >();
}
// Non-type template arg reflection (explicit type)
// E.g., reflect<int,7>() -> "(int)7"
/*! Generate a code-string for a generic non-type template argument.
* \code{.cpp} reflect<int,7>() --> "(int)7" \endcode
*/
template <typename T, T N>
inline std::string reflect() {
return reflect<NonType<T, N> >();
}
// Type reflection via value
// E.g., reflect(Type<float>()) -> "float"
/*! Generate a code-string for a type wrapped as a Type instance.
* \code{.cpp}reflect(Type<float>()) --> "float"\endcode
*/
template <typename T>
inline std::string reflect(jitify::reflection::Type<T>) {
return reflect<T>();
}
/*! Generate a code-string for a type wrapped as an Instance instance.
* \code{.cpp}reflect(Instance<float>(3.1f)) --> "float"\endcode
* or more simply when passed to a instance_of helper
* \code{.cpp}reflect(instance_of(3.1f)) --> "float"\endcodei
* This is specifically for the case where we want to extract the run-time
* type, e.g., derived type, of an object pointer.
*/
template <typename T>
inline std::string reflect(jitify::reflection::Instance<T>& value) {
return detail::demangle(typeid(value.value).name());
}
// Type from value
// E.g., type_of(3.14f) -> Type<float>()
/*! Create a Type object representing a value's type.
* \param value The value whose type is to be captured.
*/
template <typename T>
inline Type<T> type_of(T& value) {
return Type<T>();
}
/*! Create a Type object representing a value's type.
* \param value The const value whose type is to be captured.
*/
template <typename T>
inline Type<T const> type_of(T const& value) {
return Type<T const>();
}
#if __cplusplus >= 201103L
// Multiple value reflections one call, returning list of strings
template <typename... Args>
inline std::vector<std::string> reflect_all(Args... args) {
return {reflect(args)...};
}
#endif // __cplusplus >= 201103L
inline std::string reflect_list(jitify::detail::vector<std::string> const& args,
std::string opener = "",
std::string closer = "") {
std::stringstream ss;
ss << opener;
for (int i = 0; i < (int)args.size(); ++i) {
if (i > 0) ss << ",";
ss << args[i];
}
ss << closer;
return ss.str();
}
// Template instantiation reflection
// inline std::string reflect_template(std::vector<std::string> const& args) {
inline std::string reflect_template(
jitify::detail::vector<std::string> const& args) {
// Note: The space in " >" is a WAR to avoid '>>' appearing
return reflect_list(args, "<", " >");
}
#if __cplusplus >= 201103L
// TODO: See if can make this evaluate completely at compile-time
template <typename... Ts>
inline std::string reflect_template() {
return reflect_template({reflect<Ts>()...});
// return reflect_template<sizeof...(Ts)>({reflect<Ts>()...});
}
#endif
} // namespace reflection
//! \cond
namespace detail {
class CUDAKernel {
std::vector<std::string> _link_files;
std::vector<std::string> _link_paths;
CUlinkState _link_state;
CUmodule _module;
CUfunction _kernel;
std::string _func_name;
std::string _ptx;
std::map<std::string, std::string> _constant_map;
std::vector<CUjit_option> _opts;
std::vector<void*> _optvals;
#ifdef JITIFY_PRINT_LINKER_LOG
static const unsigned int _log_size = 8192;
char _info_log[_log_size];
#endif
inline void cuda_safe_call(CUresult res) const {
if (res != CUDA_SUCCESS) {
const char* msg;
cuGetErrorName(res, &msg);
throw std::runtime_error(msg);
}
}
inline void create_module(std::vector<std::string> link_files,
std::vector<std::string> link_paths) {
#ifndef JITIFY_PRINT_LINKER_LOG
// WAR since linker log does not seem to be constructed using a single call
// to cuModuleLoadDataEx.
if (link_files.empty()) {
cuda_safe_call(cuModuleLoadDataEx(&_module, _ptx.c_str(), _opts.size(),
_opts.data(), _optvals.data()));
} else
#endif
{
cuda_safe_call(cuLinkCreate(_opts.size(), _opts.data(), _optvals.data(),
&_link_state));
cuda_safe_call(cuLinkAddData(_link_state, CU_JIT_INPUT_PTX,
(void*)_ptx.c_str(), _ptx.size(),
"jitified_source.ptx", 0, 0, 0));
for (int i = 0; i < (int)link_files.size(); ++i) {
std::string link_file = link_files[i];
#if defined _WIN32 || defined _WIN64
link_file = link_file + ".lib";
#else
link_file = "lib" + link_file + ".a";
#endif
CUresult result = cuLinkAddFile(_link_state, CU_JIT_INPUT_LIBRARY,
link_file.c_str(), 0, 0, 0);
int path_num = 0;
while (result == CUDA_ERROR_FILE_NOT_FOUND &&
path_num < (int)link_paths.size()) {
std::string filename = path_join(link_paths[path_num++], link_file);
result = cuLinkAddFile(_link_state, CU_JIT_INPUT_LIBRARY,
filename.c_str(), 0, 0, 0);
}
#if JITIFY_PRINT_LOG
if (result == CUDA_ERROR_FILE_NOT_FOUND) {
std::cout << "Error: Device library not found: " << link_file
<< std::endl;
}
#endif
cuda_safe_call(result);
}
size_t cubin_size;
void* cubin;
cuda_safe_call(cuLinkComplete(_link_state, &cubin, &cubin_size));
cuda_safe_call(cuModuleLoadData(&_module, cubin));
}
#ifdef JITIFY_PRINT_LINKER_LOG
std::cout << "---------------------------------------" << std::endl;
std::cout << "--- Linker for "
<< reflection::detail::demangle(_func_name.c_str()) << " ---"
<< std::endl;
std::cout << "---------------------------------------" << std::endl;
std::cout << _info_log << std::endl;
std::cout << "---------------------------------------" << std::endl;
#endif
cuda_safe_call(cuModuleGetFunction(&_kernel, _module, _func_name.c_str()));
}
inline void destroy_module() {
if (_link_state) {
cuda_safe_call(cuLinkDestroy(_link_state));
}
_link_state = 0;
if (_module) {
cuModuleUnload(_module);
}
_module = 0;
}
// create a map of constants in the ptx file mapping demangled to mangled name
inline void create_constant_map() {
size_t pos = 0;
while (pos < _ptx.size()) {
pos = _ptx.find(".const .align", pos);
if (pos == std::string::npos) break;
size_t end = _ptx.find(";", pos);
std::string line = _ptx.substr(pos, end - pos);
size_t constant_start = line.find_last_of(" ") + 1;
size_t constant_end = line.find_last_of("[");
std::string entry =
line.substr(constant_start, constant_end - constant_start);
#ifdef _MSC_VER // interpret anything that doesn't begine ? as unmangled name
std::string key = (entry[0] != '?')
? entry.c_str()
: reflection::detail::demangle(entry.c_str());
#else // interpret anything that doesn't begine _Z as unmangled name
std::string key = (entry[0] != '_' && entry[1] != 'Z')
? entry.c_str()
: reflection::detail::demangle(entry.c_str());
#endif
_constant_map[key] = entry;
pos = end;
}
}
inline void set_linker_log() {
#ifdef JITIFY_PRINT_LINKER_LOG
_opts.push_back(CU_JIT_INFO_LOG_BUFFER);
_optvals.push_back((void*)_info_log);
_opts.push_back(CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES);
_optvals.push_back((void*)(long)_log_size);
_opts.push_back(CU_JIT_LOG_VERBOSE);
_optvals.push_back((void*)1);
#endif
}
public:
inline CUDAKernel() : _link_state(0), _module(0), _kernel(0) {}
inline CUDAKernel(const CUDAKernel& other) = delete;
inline CUDAKernel& operator=(const CUDAKernel& other) = delete;
inline CUDAKernel(CUDAKernel&& other) = delete;
inline CUDAKernel& operator=(CUDAKernel&& other) = delete;
inline CUDAKernel(const char* func_name, const char* ptx,
std::vector<std::string> link_files,
std::vector<std::string> link_paths, unsigned int nopts = 0,
CUjit_option* opts = 0, void** optvals = 0)
: _link_files(link_files),
_link_paths(link_paths),
_link_state(0),
_module(0),
_kernel(0),
_func_name(func_name),
_ptx(ptx),
_opts(opts, opts + nopts),
_optvals(optvals, optvals + nopts) {
this->set_linker_log();
this->create_module(link_files, link_paths);
this->create_constant_map();
}
inline CUDAKernel& set(const char* func_name, const char* ptx,
std::vector<std::string> link_files,
std::vector<std::string> link_paths,
unsigned int nopts = 0, CUjit_option* opts = 0,
void** optvals = 0) {
this->destroy_module();
_func_name = func_name;
_ptx = ptx;
_link_files = link_files;
_link_paths = link_paths;
_opts.assign(opts, opts + nopts);
_optvals.assign(optvals, optvals + nopts);
this->set_linker_log();
this->create_module(link_files, link_paths);
this->create_constant_map();
return *this;
}
inline ~CUDAKernel() { this->destroy_module(); }
inline operator CUfunction() const { return _kernel; }
inline CUresult launch(dim3 grid, dim3 block, unsigned int smem,
CUstream stream, std::vector<void*> arg_ptrs) const {
return cuLaunchKernel(_kernel, grid.x, grid.y, grid.z, block.x, block.y,
block.z, smem, stream, arg_ptrs.data(), NULL);
}
inline CUdeviceptr get_constant_ptr(const char* name) const {
CUdeviceptr const_ptr = 0;
auto constant = _constant_map.find(name);
if (constant != _constant_map.end()) {
cuda_safe_call(
cuModuleGetGlobal(&const_ptr, 0, _module, constant->second.c_str()));
} else {
throw std::runtime_error(std::string("failed to look up constant ") +
name);
}
return const_ptr;
}
const std::string& function_name() const { return _func_name; }
const std::string& ptx() const { return _ptx; }
const std::vector<std::string>& link_files() const { return _link_files; }
const std::vector<std::string>& link_paths() const { return _link_paths; }
};
static const char* jitsafe_header_preinclude_h = R"(
// WAR for Thrust (which appears to have forgotten to include this in result_of_adaptable_function.h
#include <type_traits>
// WAR for Thrust (which appear to have forgotten to include this in error_code.h)
#include <string>
// WAR for Thrust (which only supports gnuc, clang or msvc)
#define __GNUC__ 4
// WAR for generics/shfl.h
#define THRUST_STATIC_ASSERT(x)
// WAR for CUB
#ifdef __host__
#undef __host__
#endif
#define __host__
// WAR to allow exceptions to be parsed
#define try
#define catch(...)
)";
static const char* jitsafe_header_float_h =
"#pragma once\n"
"\n"
"inline __host__ __device__ float jitify_int_as_float(int i) "
"{ union FloatInt { float f; int i; } fi; fi.i = i; return fi.f; }\n"
"inline __host__ __device__ double jitify_longlong_as_double(long long i) "
"{ union DoubleLongLong { double f; long long i; } fi; fi.i = i; return "
"fi.f; }\n"
"#define FLT_RADIX 2\n"
"#define FLT_MANT_DIG 24\n"
"#define DBL_MANT_DIG 53\n"
"#define FLT_DIG 6\n"
"#define DBL_DIG 15\n"
"#define FLT_MIN_EXP -125\n"
"#define DBL_MIN_EXP -1021\n"
"#define FLT_MIN_10_EXP -37\n"
"#define DBL_MIN_10_EXP -307\n"
"#define FLT_MAX_EXP 128\n"
"#define DBL_MAX_EXP 1024\n"
"#define FLT_MAX_10_EXP 38\n"
"#define DBL_MAX_10_EXP 308\n"
"#define FLT_MAX jitify_int_as_float(2139095039)\n"
"#define DBL_MAX jitify_longlong_as_double(9218868437227405311)\n"
"#define FLT_EPSILON jitify_int_as_float(872415232)\n"
"#define DBL_EPSILON jitify_longlong_as_double(4372995238176751616)\n"
"#define FLT_MIN jitify_int_as_float(8388608)\n"
"#define DBL_MIN jitify_longlong_as_double(4503599627370496)\n"
"#define FLT_ROUNDS 1\n"
"#if defined __cplusplus && __cplusplus >= 201103L\n"
"#define FLT_EVAL_METHOD 0\n"
"#define DECIMAL_DIG 21\n"
"#endif\n";
static const char* jitsafe_header_limits_h =
"#pragma once\n"
"\n"
"#if defined _WIN32 || defined _WIN64\n"
" #define __WORDSIZE 32\n"
"#else\n"
" #if defined __x86_64__ && !defined __ILP32__\n"
" #define __WORDSIZE 64\n"
" #else\n"
" #define __WORDSIZE 32\n"
" #endif\n"
"#endif\n"
"#define MB_LEN_MAX 16\n"
"#define CHAR_BIT 8\n"
"#define SCHAR_MIN (-128)\n"
"#define SCHAR_MAX 127\n"
"#define UCHAR_MAX 255\n"
"#ifdef __CHAR_UNSIGNED__\n"
" #define CHAR_MIN 0\n"
" #define CHAR_MAX UCHAR_MAX\n"
"#else\n"
" #define CHAR_MIN SCHAR_MIN\n"
" #define CHAR_MAX SCHAR_MAX\n"
"#endif\n"
"#define SHRT_MIN (-32768)\n"
"#define SHRT_MAX 32767\n"
"#define USHRT_MAX 65535\n"
"#define INT_MIN (-INT_MAX - 1)\n"
"#define INT_MAX 2147483647\n"
"#define UINT_MAX 4294967295U\n"
"#if __WORDSIZE == 64\n"
" # define LONG_MAX 9223372036854775807L\n"
"#else\n"
" # define LONG_MAX 2147483647L\n"
"#endif\n"
"#define LONG_MIN (-LONG_MAX - 1L)\n"
"#if __WORDSIZE == 64\n"
" #define ULONG_MAX 18446744073709551615UL\n"
"#else\n"
" #define ULONG_MAX 4294967295UL\n"
"#endif\n"
"#define LLONG_MAX 9223372036854775807LL\n"
"#define LLONG_MIN (-LLONG_MAX - 1LL)\n"
"#define ULLONG_MAX 18446744073709551615ULL\n";
static const char* jitsafe_header_iterator =
"#pragma once\n"
"\n"
"namespace __jitify_iterator_ns {\n"
"struct output_iterator_tag {};\n"
"struct input_iterator_tag {};\n"
"struct forward_iterator_tag {};\n"
"struct bidirectional_iterator_tag {};\n"
"struct random_access_iterator_tag {};\n"
"template<class Iterator>\n"
"struct iterator_traits {\n"
" typedef typename Iterator::iterator_category iterator_category;\n"
" typedef typename Iterator::value_type value_type;\n"
" typedef typename Iterator::difference_type difference_type;\n"
" typedef typename Iterator::pointer pointer;\n"
" typedef typename Iterator::reference reference;\n"
"};\n"
"template<class T>\n"
"struct iterator_traits<T*> {\n"
" typedef random_access_iterator_tag iterator_category;\n"
" typedef T value_type;\n"
" typedef ptrdiff_t difference_type;\n"
" typedef T* pointer;\n"
" typedef T& reference;\n"
"};\n"
"template<class T>\n"
"struct iterator_traits<T const*> {\n"
" typedef random_access_iterator_tag iterator_category;\n"
" typedef T value_type;\n"
" typedef ptrdiff_t difference_type;\n"
" typedef T const* pointer;\n"
" typedef T const& reference;\n"
"};\n"
"} // namespace __jitify_iterator_ns\n"
"namespace std { using namespace __jitify_iterator_ns; }\n"
"using namespace __jitify_iterator_ns;\n";
// TODO: This is incomplete; need floating point limits
static const char* jitsafe_header_limits =
"#pragma once\n"
"#include <climits>\n"
"\n"
"namespace __jitify_limits_ns {\n"
"// TODO: Floating-point limits\n"
"namespace __jitify_detail {\n"
"template<class T, T Min, T Max, int Digits=-1>\n"
"struct IntegerLimits {\n"
" static inline __host__ __device__ T min() { return Min; }\n"
" static inline __host__ __device__ T max() { return Max; }\n"
" enum {\n"
" is_specialized = true,\n"
" digits = (Digits == -1) ? (int)(sizeof(T)*8 - (Min != 0)) "
": Digits,\n"
" digits10 = (digits * 30103) / 100000,\n"
" is_signed = ((T)(-1)<0),\n"
" is_integer = true,\n"
" is_exact = true,\n"
" radix = 2,\n"
" is_bounded = true,\n"
" is_modulo = false\n"
" };\n"
"};\n"
"} // namespace detail\n"
"template<typename T> struct numeric_limits {\n"
" enum { is_specialized = false };\n"
"};\n"
"template<> struct numeric_limits<bool> : public "
"__jitify_detail::IntegerLimits<bool, false, true,1> {};\n"
"template<> struct numeric_limits<char> : public "
"__jitify_detail::IntegerLimits<char, CHAR_MIN, CHAR_MAX> "
"{};\n"
"template<> struct numeric_limits<signed char> : public "
"__jitify_detail::IntegerLimits<signed char, SCHAR_MIN,SCHAR_MAX> "
"{};\n"
"template<> struct numeric_limits<unsigned char> : public "
"__jitify_detail::IntegerLimits<unsigned char, 0, UCHAR_MAX> "
"{};\n"
"template<> struct numeric_limits<wchar_t> : public "
"__jitify_detail::IntegerLimits<wchar_t, INT_MIN, INT_MAX> {};\n"
"template<> struct numeric_limits<short> : public "
"__jitify_detail::IntegerLimits<short, SHRT_MIN, SHRT_MAX> "
"{};\n"
"template<> struct numeric_limits<unsigned short> : public "
"__jitify_detail::IntegerLimits<unsigned short, 0, USHRT_MAX> "
"{};\n"
"template<> struct numeric_limits<int> : public "
"__jitify_detail::IntegerLimits<int, INT_MIN, INT_MAX> {};\n"
"template<> struct numeric_limits<unsigned int> : public "
"__jitify_detail::IntegerLimits<unsigned int, 0, UINT_MAX> "
"{};\n"
"template<> struct numeric_limits<long> : public "
"__jitify_detail::IntegerLimits<long, LONG_MIN, LONG_MAX> "
"{};\n"
"template<> struct numeric_limits<unsigned long> : public "
"__jitify_detail::IntegerLimits<unsigned long, 0, ULONG_MAX> "
"{};\n"
"template<> struct numeric_limits<long long> : public "
"__jitify_detail::IntegerLimits<long long, LLONG_MIN,LLONG_MAX> "
"{};\n"
"template<> struct numeric_limits<unsigned long long> : public "
"__jitify_detail::IntegerLimits<unsigned long long,0, ULLONG_MAX> "
"{};\n"
"//template<typename T> struct numeric_limits { static const bool "
"is_signed = ((T)(-1)<0); };\n"
"} // namespace __jitify_limits_ns\n"
"namespace std { using namespace __jitify_limits_ns; }\n"
"using namespace __jitify_limits_ns;\n";
// TODO: This is highly incomplete
static const char* jitsafe_header_type_traits = R"(
#pragma once
#if __cplusplus >= 201103L
namespace __jitify_type_traits_ns {
template<bool B, class T = void> struct enable_if {};
template<class T> struct enable_if<true, T> { typedef T type; };
#if __cplusplus >= 201402L
template< bool B, class T = void > using enable_if_t = typename enable_if<B,T>::type;
#endif
struct true_type {
enum { value = true };
operator bool() const { return true; }
};
struct false_type {
enum { value = false };
operator bool() const { return false; }
};
template<typename T> struct is_floating_point : false_type {};
template<> struct is_floating_point<float> : true_type {};
template<> struct is_floating_point<double> : true_type {};
template<> struct is_floating_point<long double> : true_type {};
template<class T> struct is_integral : false_type {};
template<> struct is_integral<bool> : true_type {};
template<> struct is_integral<char> : true_type {};
template<> struct is_integral<signed char> : true_type {};
template<> struct is_integral<unsigned char> : true_type {};
template<> struct is_integral<short> : true_type {};
template<> struct is_integral<unsigned short> : true_type {};
template<> struct is_integral<int> : true_type {};
template<> struct is_integral<unsigned int> : true_type {};
template<> struct is_integral<long> : true_type {};
template<> struct is_integral<unsigned long> : true_type {};
template<> struct is_integral<long long> : true_type {};
template<> struct is_integral<unsigned long long> : true_type {};
template<typename T> struct is_signed : false_type {};
template<> struct is_signed<float> : true_type {};
template<> struct is_signed<double> : true_type {};
template<> struct is_signed<long double> : true_type {};
template<> struct is_signed<signed char> : true_type {};
template<> struct is_signed<short> : true_type {};
template<> struct is_signed<int> : true_type {};
template<> struct is_signed<long> : true_type {};
template<> struct is_signed<long long> : true_type {};
template<typename T> struct is_unsigned : false_type {};
template<> struct is_unsigned<unsigned char> : true_type {};
template<> struct is_unsigned<unsigned short> : true_type {};
template<> struct is_unsigned<unsigned int> : true_type {};
template<> struct is_unsigned<unsigned long> : true_type {};
template<> struct is_unsigned<unsigned long long> : true_type {};
template<typename T, typename U> struct is_same : false_type {};
template<typename T> struct is_same<T,T> : true_type {};
template<class T> struct is_array : false_type {};
template<class T> struct is_array<T[]> : true_type {};
template<class T, size_t N> struct is_array<T[N]> : true_type {};
//partial implementation only of is_function
template<class> struct is_function : false_type { };
template<class Ret, class... Args> struct is_function<Ret(Args...)> : true_type {}; //regular
template<class Ret, class... Args> struct is_function<Ret(Args......)> : true_type {}; // variadic
template<class> struct result_of;
template<class F, typename... Args>
struct result_of<F(Args...)> {
// TODO: This is a hack; a proper implem is quite complicated.
typedef typename F::result_type type;
};
template <class T> struct remove_reference { typedef T type; };
template <class T> struct remove_reference<T&> { typedef T type; };
template <class T> struct remove_reference<T&&> { typedef T type; };
#if __cplusplus >= 201402L
template< class T > using remove_reference_t = typename remove_reference<T>::type;
#endif
template<class T> struct remove_extent { typedef T type; };
template<class T> struct remove_extent<T[]> { typedef T type; };
template<class T, size_t N> struct remove_extent<T[N]> { typedef T type; };
#if __cplusplus >= 201402L
template< class T > using remove_extent_t = typename remove_extent<T>::type;
#endif
template< class T > struct remove_const { typedef T type; };
template< class T > struct remove_const<const T> { typedef T type; };
template< class T > struct remove_volatile { typedef T type; };
template< class T > struct remove_volatile<volatile T> { typedef T type; };
template< class T > struct remove_cv { typedef typename remove_volatile<typename remove_const<T>::type>::type type; };
#if __cplusplus >= 201402L
template< class T > using remove_cv_t = typename remove_cv<T>::type;
template< class T > using remove_const_t = typename remove_const<T>::type;
template< class T > using remove_volatile_t = typename remove_volatile<T>::type;
#endif
template<bool B, class T, class F> struct conditional { typedef T type; };
template<class T, class F> struct conditional<false, T, F> { typedef F type; };
#if __cplusplus >= 201402L
template< bool B, class T, class F > using conditional_t = typename conditional<B,T,F>::type;
#endif
namespace __jitify_detail {
template< class T, bool is_function_type = false > struct add_pointer { using type = typename remove_reference<T>::type*; };
template< class T > struct add_pointer<T, true> { using type = T; };
template< class T, class... Args > struct add_pointer<T(Args...), true> { using type = T(*)(Args...); };
template< class T, class... Args > struct add_pointer<T(Args..., ...), true> { using type = T(*)(Args..., ...); };
}
template< class T > struct add_pointer : __jitify_detail::add_pointer<T, is_function<T>::value> {};
#if __cplusplus >= 201402L
template< class T > using add_pointer_t = typename add_pointer<T>::type;
#endif
template< class T > struct decay {
private:
typedef typename remove_reference<T>::type U;
public:
typedef typename conditional<is_array<U>::value, typename remove_extent<U>::type*,
typename conditional<is_function<U>::value,typename add_pointer<U>::type,typename remove_cv<U>::type
>::type>::type type;
};
#if __cplusplus >= 201402L
template< class T > using decay_t = typename decay<T>::type;
#endif
} // namespace __jtiify_type_traits_ns
namespace std { using namespace __jitify_type_traits_ns; }
using namespace __jitify_type_traits_ns;
#endif // c++11
)";
// TODO: INT_FAST8_MAX et al. and a few other misc constants
static const char* jitsafe_header_stdint_h =
"#pragma once\n"
"#include <climits>\n"
"namespace __jitify_stdint_ns {\n"
"typedef signed char int8_t;\n"
"typedef signed short int16_t;\n"
"typedef signed int int32_t;\n"
"typedef signed long long int64_t;\n"
"typedef signed char int_fast8_t;\n"
"typedef signed short int_fast16_t;\n"
"typedef signed int int_fast32_t;\n"
"typedef signed long long int_fast64_t;\n"
"typedef signed char int_least8_t;\n"
"typedef signed short int_least16_t;\n"
"typedef signed int int_least32_t;\n"
"typedef signed long long int_least64_t;\n"
"typedef signed long long intmax_t;\n"
"typedef signed long intptr_t; //optional\n"
"typedef unsigned char uint8_t;\n"
"typedef unsigned short uint16_t;\n"
"typedef unsigned int uint32_t;\n"
"typedef unsigned long long uint64_t;\n"
"typedef unsigned char uint_fast8_t;\n"
"typedef unsigned short uint_fast16_t;\n"
"typedef unsigned int uint_fast32_t;\n"
"typedef unsigned long long uint_fast64_t;\n"
"typedef unsigned char uint_least8_t;\n"
"typedef unsigned short uint_least16_t;\n"
"typedef unsigned int uint_least32_t;\n"
"typedef unsigned long long uint_least64_t;\n"
"typedef unsigned long long uintmax_t;\n"
"typedef unsigned long uintptr_t; //optional\n"
"#define INT8_MIN SCHAR_MIN\n"
"#define INT16_MIN SHRT_MIN\n"
"#define INT32_MIN INT_MIN\n"
"#define INT64_MIN LLONG_MIN\n"
"#define INT8_MAX SCHAR_MAX\n"
"#define INT16_MAX SHRT_MAX\n"
"#define INT32_MAX INT_MAX\n"
"#define INT64_MAX LLONG_MAX\n"
"#define UINT8_MAX UCHAR_MAX\n"
"#define UINT16_MAX USHRT_MAX\n"
"#define UINT32_MAX UINT_MAX\n"
"#define UINT64_MAX ULLONG_MAX\n"
"#define INTPTR_MIN LONG_MIN\n"
"#define INTMAX_MIN LLONG_MIN\n"
"#define INTPTR_MAX LONG_MAX\n"
"#define INTMAX_MAX LLONG_MAX\n"
"#define UINTPTR_MAX ULONG_MAX\n"
"#define UINTMAX_MAX ULLONG_MAX\n"
"#define PTRDIFF_MIN INTPTR_MIN\n"
"#define PTRDIFF_MAX INTPTR_MAX\n"
"#define SIZE_MAX UINT64_MAX\n"
"} // namespace __jitify_stdint_ns\n"
"namespace std { using namespace __jitify_stdint_ns; }\n"
"using namespace __jitify_stdint_ns;\n";
// TODO: offsetof
static const char* jitsafe_header_stddef_h =
"#pragma once\n"
"#include <climits>\n"
"namespace __jitify_stddef_ns {\n"
//"enum { NULL = 0 };\n"
"typedef unsigned long size_t;\n"
"typedef signed long ptrdiff_t;\n"
"} // namespace __jitify_stddef_ns\n"
"namespace std { using namespace __jitify_stddef_ns; }\n"
"using namespace __jitify_stddef_ns;\n";
static const char* jitsafe_header_stdlib_h =
"#pragma once\n"
"#include <stddef.h>\n";
static const char* jitsafe_header_stdio_h =
"#pragma once\n"
"#include <stddef.h>\n"
"#define FILE int\n"
"int fflush ( FILE * stream );\n"
"int fprintf ( FILE * stream, const char * format, ... );\n";
static const char* jitsafe_header_string_h =
"#pragma once\n"
"char* strcpy ( char * destination, const char * source );\n"
"int strcmp ( const char * str1, const char * str2 );\n"
"char* strerror( int errnum );\n";
static const char* jitsafe_header_cstring =
"#pragma once\n"
"\n"
"namespace __jitify_cstring_ns {\n"
"char* strcpy ( char * destination, const char * source );\n"
"int strcmp ( const char * str1, const char * str2 );\n"
"char* strerror( int errnum );\n"
"} // namespace __jitify_cstring_ns\n"
"namespace std { using namespace __jitify_cstring_ns; }\n"
"using namespace __jitify_cstring_ns;\n";
// HACK TESTING (WAR for cub)
static const char* jitsafe_header_iostream =
"#pragma once\n"
"#include <ostream>\n"
"#include <istream>\n";
// HACK TESTING (WAR for Thrust)
static const char* jitsafe_header_ostream =
"#pragma once\n"
"\n"
"namespace __jitify_ostream_ns {\n"
"template<class CharT,class Traits=void>\n" // = std::char_traits<CharT>
// >\n"
"struct basic_ostream {\n"
"};\n"
"typedef basic_ostream<char> ostream;\n"
"ostream& endl(ostream& os);\n"
"ostream& operator<<( ostream&, ostream& (*f)( ostream& ) );\n"
"template< class CharT, class Traits > basic_ostream<CharT, Traits>& endl( "
"basic_ostream<CharT, Traits>& os );\n"
"template< class CharT, class Traits > basic_ostream<CharT, Traits>& "
"operator<<( basic_ostream<CharT,Traits>& os, const char* c );\n"
"#if __cplusplus >= 201103L\n"
"template< class CharT, class Traits, class T > basic_ostream<CharT, "
"Traits>& operator<<( basic_ostream<CharT,Traits>&& os, const T& value );\n"
"#endif // __cplusplus >= 201103L\n"
"} // namespace __jitify_ostream_ns\n"
"namespace std { using namespace __jitify_ostream_ns; }\n"
"using namespace __jitify_ostream_ns;\n";
static const char* jitsafe_header_istream =
"#pragma once\n"
"\n"
"namespace __jitify_istream_ns {\n"
"template<class CharT,class Traits=void>\n" // = std::char_traits<CharT>
// >\n"
"struct basic_istream {\n"
"};\n"
"typedef basic_istream<char> istream;\n"
"} // namespace __jitify_istream_ns\n"
"namespace std { using namespace __jitify_istream_ns; }\n"
"using namespace __jitify_istream_ns;\n";
static const char* jitsafe_header_sstream =
"#pragma once\n"
"#include <ostream>\n"
"#include <istream>\n";
static const char* jitsafe_header_utility =
"#pragma once\n"
"namespace __jitify_utility_ns {\n"
"template<class T1, class T2>\n"
"struct pair {\n"
" T1 first;\n"
" T2 second;\n"
" inline pair() {}\n"
" inline pair(T1 const& first_, T2 const& second_)\n"
" : first(first_), second(second_) {}\n"
" // TODO: Standard includes many more constructors...\n"
" // TODO: Comparison operators\n"
"};\n"
"template<class T1, class T2>\n"
"pair<T1,T2> make_pair(T1 const& first, T2 const& second) {\n"
" return pair<T1,T2>(first, second);\n"
"}\n"
"} // namespace __jitify_utility_ns\n"
"namespace std { using namespace __jitify_utility_ns; }\n"
"using namespace __jitify_utility_ns;\n";
// TODO: incomplete
static const char* jitsafe_header_vector =
"#pragma once\n"
"namespace __jitify_vector_ns {\n"
"template<class T, class Allocator=void>\n" // = std::allocator> \n"
"struct vector {\n"
"};\n"
"} // namespace __jitify_vector_ns\n"
"namespace std { using namespace __jitify_vector_ns; }\n"
"using namespace __jitify_vector_ns;\n";
// TODO: incomplete
static const char* jitsafe_header_string =
"#pragma once\n"
"namespace __jitify_string_ns {\n"
"template<class CharT,class Traits=void,class Allocator=void>\n"
"struct basic_string {\n"
"basic_string();\n"
"basic_string( const CharT* s );\n" //, const Allocator& alloc =
// Allocator() );\n"
"const CharT* c_str() const;\n"
"bool empty() const;\n"
"void operator+=(const char *);\n"
"void operator+=(const basic_string &);\n"
"};\n"
"typedef basic_string<char> string;\n"
"} // namespace __jitify_string_ns\n"
"namespace std { using namespace __jitify_string_ns; }\n"
"using namespace __jitify_string_ns;\n";
// TODO: incomplete
static const char* jitsafe_header_stdexcept =
"#pragma once\n"
"namespace __jitify_stdexcept_ns {\n"
"struct runtime_error {\n"
"explicit runtime_error( const std::string& what_arg );"
"explicit runtime_error( const char* what_arg );"
"virtual const char* what() const;\n"
"};\n"
"} // namespace __jitify_stdexcept_ns\n"
"namespace std { using namespace __jitify_stdexcept_ns; }\n"
"using namespace __jitify_stdexcept_ns;\n";
// TODO: incomplete
static const char* jitsafe_header_complex =
"#pragma once\n"
"namespace __jitify_complex_ns {\n"
"template<typename T>\n"
"class complex {\n"
" T _real;\n"
" T _imag;\n"
"public:\n"
" complex() : _real(0), _imag(0) {}\n"
" complex(T const& real, T const& imag)\n"
" : _real(real), _imag(imag) {}\n"
" complex(T const& real)\n"
" : _real(real), _imag(static_cast<T>(0)) {}\n"
" T const& real() const { return _real; }\n"
" T& real() { return _real; }\n"
" void real(const T &r) { _real = r; }\n"
" T const& imag() const { return _imag; }\n"
" T& imag() { return _imag; }\n"
" void imag(const T &i) { _imag = i; }\n"
" complex<T>& operator+=(const complex<T> z)\n"
" { _real += z.real(); _imag += z.imag(); return *this; }\n"
"};\n"
"template<typename T>\n"
"complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs)\n"
" { return complex<T>(lhs.real()*rhs.real()-lhs.imag()*rhs.imag(),\n"
" lhs.real()*rhs.imag()+lhs.imag()*rhs.real()); }\n"
"template<typename T>\n"
"complex<T> operator*(const complex<T>& lhs, const T & rhs)\n"
" { return complexs<T>(lhs.real()*rhs,lhs.imag()*rhs); }\n"
"template<typename T>\n"
"complex<T> operator*(const T& lhs, const complex<T>& rhs)\n"
" { return complexs<T>(rhs.real()*lhs,rhs.imag()*lhs); }\n"
"} // namespace __jitify_complex_ns\n"
"namespace std { using namespace __jitify_complex_ns; }\n"
"using namespace __jitify_complex_ns;\n";
// TODO: This is incomplete (missing binary and integer funcs, macros,
// constants, types)
static const char* jitsafe_header_math =
"#pragma once\n"
"namespace __jitify_math_ns {\n"
"#if __cplusplus >= 201103L\n"
"#define DEFINE_MATH_UNARY_FUNC_WRAPPER(f) \\\n"
" inline double f(double x) { return ::f(x); } \\\n"
" inline float f##f(float x) { return ::f(x); } \\\n"
" /*inline long double f##l(long double x) { return ::f(x); }*/ \\\n"
" inline float f(float x) { return ::f(x); } \\\n"
" /*inline long double f(long double x) { return ::f(x); }*/\n"
"#else\n"
"#define DEFINE_MATH_UNARY_FUNC_WRAPPER(f) \\\n"
" inline double f(double x) { return ::f(x); } \\\n"
" inline float f##f(float x) { return ::f(x); } \\\n"
" /*inline long double f##l(long double x) { return ::f(x); }*/\n"
"#endif\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(cos)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(sin)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(tan)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(acos)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(asin)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(atan)\n"
"template<typename T> inline T atan2(T y, T x) { return ::atan2(y, x); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(cosh)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(sinh)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(tanh)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(exp)\n"
"template<typename T> inline T frexp(T x, int* exp) { return ::frexp(x, "
"exp); }\n"
"template<typename T> inline T ldexp(T x, int exp) { return ::ldexp(x, "
"exp); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(log)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(log10)\n"
"template<typename T> inline T modf(T x, T* intpart) { return ::modf(x, "
"intpart); }\n"
"template<typename T> inline T pow(T x, T y) { return ::pow(x, y); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(sqrt)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(ceil)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(floor)\n"
"template<typename T> inline T fmod(T n, T d) { return ::fmod(n, d); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(fabs)\n"
"template<typename T> inline T abs(T x) { return ::abs(x); }\n"
"#if __cplusplus >= 201103L\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(acosh)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(asinh)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(atanh)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(exp2)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(expm1)\n"
"template<typename T> inline int ilogb(T x) { return ::ilogb(x); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(log1p)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(log2)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(logb)\n"
"template<typename T> inline T scalbn (T x, int n) { return ::scalbn(x, "
"n); }\n"
"template<typename T> inline T scalbln(T x, long n) { return ::scalbn(x, "
"n); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(cbrt)\n"
"template<typename T> inline T hypot(T x, T y) { return ::hypot(x, y); }\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(erf)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(erfc)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(tgamma)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(lgamma)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(trunc)\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(round)\n"
"template<typename T> inline long lround(T x) { return ::lround(x); }\n"
"template<typename T> inline long long llround(T x) { return ::llround(x); "
"}\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(rint)\n"
"template<typename T> inline long lrint(T x) { return ::lrint(x); }\n"
"template<typename T> inline long long llrint(T x) { return ::llrint(x); "
"}\n"
"DEFINE_MATH_UNARY_FUNC_WRAPPER(nearbyint)\n"
// TODO: remainder, remquo, copysign, nan, nextafter, nexttoward, fdim,
// fmax, fmin, fma
"#endif\n"
"#undef DEFINE_MATH_UNARY_FUNC_WRAPPER\n"
"} // namespace __jitify_math_ns\n"
"namespace std { using namespace __jitify_math_ns; }\n"
"#define M_PI 3.14159265358979323846\n"
// Note: Global namespace already includes CUDA math funcs
"//using namespace __jitify_math_ns;\n";
// TODO: incomplete
static const char* jitsafe_header_mutex = R"(
#pragma once
#if __cplusplus >= 201103L
namespace __jitify_mutex_ns {
class mutex {
public:
void lock();
bool try_lock();
void unlock();
};
} // namespace __jitify_mutex_ns
namespace std { using namespace __jitify_mutex_ns; }
using namespace __jitify_mutex_ns;
#endif
)";
static const char* jitsafe_header_algorithm = R"(
#pragma once
#if __cplusplus >= 201103L
namespace __jitify_algorithm_ns {
#if __cplusplus == 201103L
#define JITIFY_CXX14_CONSTEXPR
#else
#define JITIFY_CXX14_CONSTEXPR constexpr
#endif
template<class T> JITIFY_CXX14_CONSTEXPR const T& max(const T& a, const T& b)
{
return (b > a) ? b : a;
}
template<class T> JITIFY_CXX14_CONSTEXPR const T& min(const T& a, const T& b)
{
return (b < a) ? b : a;
}
#endif
} // namespace __jitify_algorithm_ns
namespace std { using namespace __jitify_algorithm_ns; }
using namespace __jitify_algorithm_ns;
#endif
)";
static const char* jitsafe_header_time_h = R"(
#pragma once
#define NULL 0
#define CLOCKS_PER_SEC 1000000
namespace __jitify_time_ns {
typedef unsigned long size_t;
typedef long clock_t;
typedef long time_t;
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
#if __cplusplus >= 201703L
struct timespec {
time_t tv_sec;
long tv_nsec;
};
#endif
} // namespace __jitify_time_ns
namespace std { using namespace __jitify_time_ns; }
using namespace __jitify_time_ns;
)";
static const char* jitsafe_headers[] = {
jitsafe_header_preinclude_h, jitsafe_header_float_h,
jitsafe_header_float_h, jitsafe_header_limits_h,
jitsafe_header_limits_h, jitsafe_header_stdint_h,
jitsafe_header_stdint_h, jitsafe_header_stddef_h,
jitsafe_header_stddef_h, jitsafe_header_stdlib_h,
jitsafe_header_stdlib_h, jitsafe_header_stdio_h,
jitsafe_header_stdio_h, jitsafe_header_string_h,
jitsafe_header_cstring, jitsafe_header_iterator,
jitsafe_header_limits, jitsafe_header_type_traits,
jitsafe_header_utility, jitsafe_header_math,
jitsafe_header_math, jitsafe_header_complex,
jitsafe_header_iostream, jitsafe_header_ostream,
jitsafe_header_istream, jitsafe_header_sstream,
jitsafe_header_vector, jitsafe_header_string,
jitsafe_header_stdexcept, jitsafe_header_mutex,
jitsafe_header_algorithm, jitsafe_header_time_h,
jitsafe_header_time_h};
static const char* jitsafe_header_names[] = {"jitify_preinclude.h",
"float.h",
"cfloat",
"limits.h",
"climits",
"stdint.h",
"cstdint",
"stddef.h",
"cstddef",
"stdlib.h",
"cstdlib",
"stdio.h",
"cstdio",
"string.h",
"cstring",
"iterator",
"limits",
"type_traits",
"utility",
"math",
"cmath",
"complex",
"iostream",
"ostream",
"istream",
"sstream",
"vector",
"string",
"stdexcept",
"mutex",
"algorithm",
"time.h",
"ctime"};
template <class T, size_t N>
size_t array_size(T (&)[N]) {
return N;
}
const int jitsafe_headers_count = array_size(jitsafe_headers);
inline void add_options_from_env(std::vector<std::string>& options) {
// Add options from environment variable
const char* env_options = std::getenv("JITIFY_OPTIONS");
if (env_options) {
std::stringstream ss;
ss << env_options;
std::string opt;
while (!(ss >> opt).fail()) {
options.push_back(opt);
}
}
// Add options from JITIFY_OPTIONS macro
#ifdef JITIFY_OPTIONS
#define JITIFY_TOSTRING_IMPL(x) #x
#define JITIFY_TOSTRING(x) JITIFY_TOSTRING_IMPL(x)
std::stringstream ss;
ss << JITIFY_TOSTRING(JITIFY_OPTIONS);
std::string opt;
while (!(ss >> opt).fail()) {
options.push_back(opt);
}
#undef JITIFY_TOSTRING
#undef JITIFY_TOSTRING_IMPL
#endif
}
inline void detect_and_add_cuda_arch(std::vector<std::string>& options) {
for (int i = 0; i < (int)options.size(); ++i) {
// Note that this will also match the middle of "--gpu-architecture".
if (options[i].find("-arch") != std::string::npos) {
// Arch already specified in options
return;
}
}
// Use the compute capability of the current device
// TODO: Check these API calls for errors
cudaError_t status;
int device;
status = cudaGetDevice(&device);
if (status != cudaSuccess) {
throw std::runtime_error(
std::string(
"Failed to detect GPU architecture: cudaGetDevice failed: ") +
cudaGetErrorString(status));
}
int cc_major;
cudaDeviceGetAttribute(&cc_major, cudaDevAttrComputeCapabilityMajor, device);
int cc_minor;
cudaDeviceGetAttribute(&cc_minor, cudaDevAttrComputeCapabilityMinor, device);
int cc = cc_major * 10 + cc_minor;
// Note: We must limit the architecture to the max supported by the current
// version of NVRTC, otherwise newer hardware will cause errors
// on older versions of CUDA.
// TODO: It would be better to detect this somehow, rather than hard-coding it
// Tegra chips do not have forwards compatibility so we need to special case
// them.
bool is_tegra = ((cc_major == 3 && cc_minor == 2) || // Logan
(cc_major == 5 && cc_minor == 3) || // Erista
(cc_major == 6 && cc_minor == 2) || // Parker
(cc_major == 7 && cc_minor == 2)); // Xavier
if (!is_tegra) {
// ensure that future CUDA versions just work (even if suboptimal)
const int cuda_major = std::min(10, CUDA_VERSION / 1000);
// clang-format off
switch (cuda_major) {
case 10: cc = std::min(cc, 75); break; // Turing
case 9: cc = std::min(cc, 70); break; // Volta
case 8: cc = std::min(cc, 61); break; // Pascal
case 7: cc = std::min(cc, 52); break; // Maxwell
default:
throw std::runtime_error("Unexpected CUDA major version " +
std::to_string(cuda_major));
}
// clang-format on
}
std::stringstream ss;
ss << cc;
options.push_back("-arch=compute_" + ss.str());
}
inline void detect_and_add_cxx11_flag(std::vector<std::string>& options) {
// Reverse loop so we can erase on the fly.
for (int i = (int)options.size() - 1; i >= 0; --i) {
if (options[i].find("-std=c++98") != std::string::npos) {
// NVRTC doesn't support specifying c++98 explicitly, so we remove it.
options.erase(options.begin() + i);
return;
} else if (options[i].find("-std") != std::string::npos) {
// Some other standard was explicitly specified, don't change anything.
return;
}
}
// Jitify must be compiled with C++11 support, so we default to enabling it
// for the JIT-compiled code too.
options.push_back("-std=c++11");
}
inline void split_compiler_and_linker_options(
std::vector<std::string> options,
std::vector<std::string>* compiler_options,
std::vector<std::string>* linker_files,
std::vector<std::string>* linker_paths) {
for (int i = 0; i < (int)options.size(); ++i) {
std::string opt = options[i];
std::string flag = opt.substr(0, 2);
std::string value = opt.substr(2);
if (flag == "-l") {
linker_files->push_back(value);
} else if (flag == "-L") {
linker_paths->push_back(value);
} else {
compiler_options->push_back(opt);
}
}
}
inline nvrtcResult compile_kernel(std::string program_name,
std::map<std::string, std::string> sources,
std::vector<std::string> options,
std::string instantiation = "",
std::string* log = 0, std::string* ptx = 0,
std::string* mangled_instantiation = 0) {
std::string program_source = sources[program_name];
// Build arrays of header names and sources
std::vector<const char*> header_names_c;
std::vector<const char*> header_sources_c;
int num_headers = sources.size() - 1;
header_names_c.reserve(num_headers);
header_sources_c.reserve(num_headers);
typedef std::map<std::string, std::string> source_map;
for (source_map::const_iterator iter = sources.begin(); iter != sources.end();
++iter) {
std::string const& name = iter->first;
std::string const& code = iter->second;
if (name == program_name) {
continue;
}
header_names_c.push_back(name.c_str());
header_sources_c.push_back(code.c_str());
}
std::vector<const char*> options_c(options.size() + 2);
options_c[0] = "--device-as-default-execution-space";
options_c[1] = "--pre-include=jitify_preinclude.h";
for (int i = 0; i < (int)options.size(); ++i) {
options_c[i + 2] = options[i].c_str();
}
#if CUDA_VERSION < 8000
std::string inst_dummy;
if (!instantiation.empty()) {
// WAR for no nvrtcAddNameExpression before CUDA 8.0
// Force template instantiation by adding dummy reference to kernel
inst_dummy = "__jitify_instantiation";
program_source +=
"\nvoid* " + inst_dummy + " = (void*)" + instantiation + ";\n";
}
#endif
#define CHECK_NVRTC(call) \
do { \
nvrtcResult ret = call; \
if (ret != NVRTC_SUCCESS) { \
return ret; \
} \
} while (0)
nvrtcProgram nvrtc_program;
CHECK_NVRTC(nvrtcCreateProgram(
&nvrtc_program, program_source.c_str(), program_name.c_str(), num_headers,
header_sources_c.data(), header_names_c.data()));
#if CUDA_VERSION >= 8000
if (!instantiation.empty()) {
CHECK_NVRTC(nvrtcAddNameExpression(nvrtc_program, instantiation.c_str()));
}
#endif
nvrtcResult ret =
nvrtcCompileProgram(nvrtc_program, options_c.size(), options_c.data());
if (log) {
size_t logsize;
CHECK_NVRTC(nvrtcGetProgramLogSize(nvrtc_program, &logsize));
std::vector<char> vlog(logsize, 0);
CHECK_NVRTC(nvrtcGetProgramLog(nvrtc_program, vlog.data()));
log->assign(vlog.data(), logsize);
if (ret != NVRTC_SUCCESS) {
return ret;
}
}
if (ptx) {
size_t ptxsize;
CHECK_NVRTC(nvrtcGetPTXSize(nvrtc_program, &ptxsize));
std::vector<char> vptx(ptxsize);
CHECK_NVRTC(nvrtcGetPTX(nvrtc_program, vptx.data()));
ptx->assign(vptx.data(), ptxsize);
}
if (!instantiation.empty() && mangled_instantiation) {
#if CUDA_VERSION >= 8000
const char* mangled_instantiation_cstr;
// Note: The returned string pointer becomes invalid after
// nvrtcDestroyProgram has been called, so we save it.
CHECK_NVRTC(nvrtcGetLoweredName(nvrtc_program, instantiation.c_str(),
&mangled_instantiation_cstr));
*mangled_instantiation = mangled_instantiation_cstr;
#else
// Extract mangled kernel template instantiation from PTX
inst_dummy += " = "; // Note: This must match how the PTX is generated
int mi_beg = ptx->find(inst_dummy) + inst_dummy.size();
int mi_end = ptx->find(";", mi_beg);
*mangled_instantiation = ptx->substr(mi_beg, mi_end - mi_beg);
#endif
}
CHECK_NVRTC(nvrtcDestroyProgram(&nvrtc_program));
#undef CHECK_NVRTC
return NVRTC_SUCCESS;
}
inline void load_program(std::string const& cuda_source,
std::vector<std::string> const& headers,
file_callback_type file_callback,
std::vector<std::string>* include_paths,
std::map<std::string, std::string>* program_sources,
std::vector<std::string>* program_options,
std::string* program_name) {
// Extract include paths from compile options
std::vector<std::string>::iterator iter = program_options->begin();
while (iter != program_options->end()) {
std::string const& opt = *iter;
if (opt.substr(0, 2) == "-I") {
include_paths->push_back(opt.substr(2));
program_options->erase(iter);
} else {
++iter;
}
}
// Load program source
if (!detail::load_source(cuda_source, *program_sources, "", *include_paths,
file_callback)) {
throw std::runtime_error("Source not found: " + cuda_source);
}
*program_name = program_sources->begin()->first;
// Maps header include names to their full file paths.
std::map<std::string, std::string> header_fullpaths;
// Load header sources
for (std::string const& header : headers) {
if (!detail::load_source(header, *program_sources, "", *include_paths,
file_callback, &header_fullpaths)) {
// **TODO: Deal with source not found
throw std::runtime_error("Source not found: " + header);
}
}
#if JITIFY_PRINT_SOURCE
std::string& program_source = (*program_sources)[*program_name];
std::cout << "---------------------------------------" << std::endl;
std::cout << "--- Source of " << *program_name << " ---" << std::endl;
std::cout << "---------------------------------------" << std::endl;
detail::print_with_line_numbers(program_source);
std::cout << "---------------------------------------" << std::endl;
#endif
std::vector<std::string> compiler_options, linker_files, linker_paths;
detail::split_compiler_and_linker_options(*program_options, &compiler_options,
&linker_files, &linker_paths);
// If no arch is specified at this point we use whatever the current
// context is. This ensures we pick up the correct internal headers
// for arch-dependent compilation, e.g., some intrinsics are only
// present for specific architectures.
detail::detect_and_add_cuda_arch(compiler_options);
detail::detect_and_add_cxx11_flag(compiler_options);
// Iteratively try to compile the sources, and use the resulting errors to
// identify missing headers.
std::string log;
nvrtcResult ret;
while ((ret = detail::compile_kernel(*program_name, *program_sources,
compiler_options, "", &log)) ==
NVRTC_ERROR_COMPILATION) {
std::string include_name;
std::string include_parent;
int line_num = 0;
if (!detail::extract_include_info_from_compile_error(
log, include_name, include_parent, line_num)) {
#if JITIFY_PRINT_LOG
detail::print_compile_log(*program_name, log);
#endif
// There was a non include-related compilation error
// TODO: How to handle error?
throw std::runtime_error("Runtime compilation failed");
}
// Try to load the new header
// Note: This fullpath lookup is needed because the compiler error
// messages have the include name of the header instead of its full path.
std::string include_parent_fullpath = header_fullpaths[include_parent];
std::string include_path = detail::path_base(include_parent_fullpath);
if (!detail::load_source(include_name, *program_sources, include_path,
*include_paths, file_callback,
&header_fullpaths)) {
// Comment-out the include line and print a warning
if (!program_sources->count(include_parent)) {
// ***TODO: Unless there's another mechanism (e.g., potentially
// the parent path vs. filename problem), getting
// here means include_parent was found automatically
// in a system include path.
// We need a WAR to zap it from *its parent*.
typedef std::map<std::string, std::string> source_map;
for (source_map::const_iterator it = program_sources->begin();
it != program_sources->end(); ++it) {
std::cout << " " << it->first << std::endl;
}
throw std::out_of_range(include_parent +
" not in loaded sources!"
" This may be due to a header being loaded by"
" NVRTC without Jitify's knowledge.");
}
std::string& parent_source = (*program_sources)[include_parent];
parent_source = detail::comment_out_code_line(line_num, parent_source);
#if JITIFY_PRINT_LOG
std::cout << include_parent << "(" << line_num
<< "): warning: " << include_name << ": File not found"
<< std::endl;
#endif
}
}
if (ret != NVRTC_SUCCESS) {
#if JITIFY_PRINT_LOG
if (ret == NVRTC_ERROR_INVALID_OPTION) {
std::cout << "Compiler options: ";
for (int i = 0; i < (int)compiler_options.size(); ++i) {
std::cout << compiler_options[i] << " ";
}
std::cout << std::endl;
}
#endif
throw std::runtime_error(std::string("NVRTC error: ") +
nvrtcGetErrorString(ret));
}
}
inline void instantiate_kernel(
std::string const& program_name,
std::map<std::string, std::string> const& program_sources,
std::string const& instantiation, std::vector<std::string> const& options,
std::string* log, std::string* ptx, std::string* mangled_instantiation,
std::vector<std::string>* linker_files,
std::vector<std::string>* linker_paths) {
std::vector<std::string> compiler_options;
detail::split_compiler_and_linker_options(options, &compiler_options,
linker_files, linker_paths);
nvrtcResult ret =
detail::compile_kernel(program_name, program_sources, compiler_options,
instantiation, log, ptx, mangled_instantiation);
#if JITIFY_PRINT_LOG
if (log->size() > 1) {
detail::print_compile_log(program_name, *log);
}
#endif
if (ret != NVRTC_SUCCESS) {
throw std::runtime_error(std::string("NVRTC error: ") +
nvrtcGetErrorString(ret));
}
#if JITIFY_PRINT_PTX
std::cout << "---------------------------------------" << std::endl;
std::cout << *mangled_instantiation << std::endl;
std::cout << "---------------------------------------" << std::endl;
std::cout << "--- PTX for " << mangled_instantiation << " in " << program_name
<< " ---" << std::endl;
std::cout << "---------------------------------------" << std::endl;
std::cout << *ptx << std::endl;
std::cout << "---------------------------------------" << std::endl;
#endif
}
inline void get_1d_max_occupancy(CUfunction func,
CUoccupancyB2DSize smem_callback, size_t* smem,
int max_block_size, unsigned int flags,
int* grid, int* block) {
if (!func) {
throw std::runtime_error(
"Kernel pointer is NULL; you may need to define JITIFY_THREAD_SAFE "
"1");
}
CUresult res = cuOccupancyMaxPotentialBlockSizeWithFlags(
grid, block, func, smem_callback, *smem, max_block_size, flags);
if (res != CUDA_SUCCESS) {
const char* msg;
cuGetErrorName(res, &msg);
throw std::runtime_error(msg);
}
if (smem_callback) {
*smem = smem_callback(*block);
}
}
} // namespace detail
//! \endcond
class KernelInstantiation;
class Kernel;
class Program;
class JitCache;
struct ProgramConfig {
std::vector<std::string> options;
std::vector<std::string> include_paths;
std::string name;
typedef std::map<std::string, std::string> source_map;
source_map sources;
};
class JitCache_impl {
friend class Program_impl;
friend class KernelInstantiation_impl;
friend class KernelLauncher_impl;
typedef uint64_t key_type;
jitify::ObjectCache<key_type, detail::CUDAKernel> _kernel_cache;
jitify::ObjectCache<key_type, ProgramConfig> _program_config_cache;
std::vector<std::string> _options;
#if JITIFY_THREAD_SAFE
std::mutex _kernel_cache_mutex;
std::mutex _program_cache_mutex;
#endif
public:
inline JitCache_impl(size_t cache_size)
: _kernel_cache(cache_size), _program_config_cache(cache_size) {
detail::add_options_from_env(_options);
// Bootstrap the cuda context to avoid errors
cudaFree(0);
}
};
class Program_impl {
// A friendly class
friend class Kernel_impl;
friend class KernelLauncher_impl;
friend class KernelInstantiation_impl;
// TODO: This can become invalid if JitCache is destroyed before the
// Program object is. However, this can't happen if JitCache
// instances are static.
JitCache_impl& _cache;
uint64_t _hash;
ProgramConfig* _config;
void load_sources(std::string source, std::vector<std::string> headers,
std::vector<std::string> options,
file_callback_type file_callback);
public:
inline Program_impl(JitCache_impl& cache, std::string source,
jitify::detail::vector<std::string> headers = 0,
jitify::detail::vector<std::string> options = 0,
file_callback_type file_callback = 0);
#if __cplusplus >= 201103L
inline Program_impl(Program_impl const&) = default;
inline Program_impl(Program_impl&&) = default;
#endif
inline std::vector<std::string> const& options() const {
return _config->options;
}
inline std::string const& name() const { return _config->name; }
inline ProgramConfig::source_map const& sources() const {
return _config->sources;
}
inline std::vector<std::string> const& include_paths() const {
return _config->include_paths;
}
};
class Kernel_impl {
friend class KernelLauncher_impl;
friend class KernelInstantiation_impl;
Program_impl _program;
std::string _name;
std::vector<std::string> _options;
uint64_t _hash;
public:
inline Kernel_impl(Program_impl const& program, std::string name,
jitify::detail::vector<std::string> options = 0);
#if __cplusplus >= 201103L
inline Kernel_impl(Kernel_impl const&) = default;
inline Kernel_impl(Kernel_impl&&) = default;
#endif
};
class KernelInstantiation_impl {
friend class KernelLauncher_impl;
Kernel_impl _kernel;
uint64_t _hash;
std::string _template_inst;
std::vector<std::string> _options;
detail::CUDAKernel* _cuda_kernel;
inline void print() const;
void build_kernel();
public:
inline KernelInstantiation_impl(
Kernel_impl const& kernel, std::vector<std::string> const& template_args);
#if __cplusplus >= 201103L
inline KernelInstantiation_impl(KernelInstantiation_impl const&) = default;
inline KernelInstantiation_impl(KernelInstantiation_impl&&) = default;
#endif
detail::CUDAKernel const& cuda_kernel() const { return *_cuda_kernel; }
};
class KernelLauncher_impl {
KernelInstantiation_impl _kernel_inst;
dim3 _grid;
dim3 _block;
size_t _smem;
cudaStream_t _stream;
public:
inline KernelLauncher_impl(KernelInstantiation_impl const& kernel_inst,
dim3 grid, dim3 block, size_t smem = 0,
cudaStream_t stream = 0)
: _kernel_inst(kernel_inst),
_grid(grid),
_block(block),
_smem(smem),
_stream(stream) {}
#if __cplusplus >= 201103L
inline KernelLauncher_impl(KernelLauncher_impl const&) = default;
inline KernelLauncher_impl(KernelLauncher_impl&&) = default;
#endif
inline CUresult launch(
jitify::detail::vector<void*> arg_ptrs,
jitify::detail::vector<std::string> arg_types = 0) const;
};
/*! An object representing a configured and instantiated kernel ready
* for launching.
*/
class KernelLauncher {
std::unique_ptr<KernelLauncher_impl const> _impl;
public:
inline KernelLauncher(KernelInstantiation const& kernel_inst, dim3 grid,
dim3 block, size_t smem = 0, cudaStream_t stream = 0);
// Note: It's important that there is no implicit conversion required
// for arg_ptrs, because otherwise the parameter pack version
// below gets called instead (probably resulting in a segfault).
/*! Launch the kernel.
*
* \param arg_ptrs A vector of pointers to each function argument for the
* kernel.
* \param arg_types A vector of function argument types represented
* as code-strings. This parameter is optional and is only used to print
* out the function signature.
*/
inline CUresult launch(
std::vector<void*> arg_ptrs = std::vector<void*>(),
jitify::detail::vector<std::string> arg_types = 0) const {
return _impl->launch(arg_ptrs, arg_types);
}
#if __cplusplus >= 201103L
// Regular function call syntax
/*! Launch the kernel.
*
* \see launch
*/
template <typename... ArgTypes>
inline CUresult operator()(ArgTypes... args) const {
return this->launch(args...);
}
/*! Launch the kernel.
*
* \param args Function arguments for the kernel.
*/
template <typename... ArgTypes>
inline CUresult launch(ArgTypes... args) const {
return this->launch(std::vector<void*>({(void*)&args...}),
{reflection::reflect<ArgTypes>()...});
}
#endif
};
/*! An object representing a kernel instantiation made up of a Kernel and
* template arguments.
*/
class KernelInstantiation {
friend class KernelLauncher;
std::unique_ptr<KernelInstantiation_impl const> _impl;
public:
inline KernelInstantiation(Kernel const& kernel,
std::vector<std::string> const& template_args);
/*! Configure the kernel launch.
*
* \see configure
*/
inline KernelLauncher operator()(dim3 grid, dim3 block, size_t smem = 0,
cudaStream_t stream = 0) const {
return this->configure(grid, block, smem, stream);
}
/*! Configure the kernel launch.
*
* \param grid The thread grid dimensions for the launch.
* \param block The thread block dimensions for the launch.
* \param smem The amount of shared memory to dynamically allocate, in
* bytes.
* \param stream The CUDA stream to launch the kernel in.
*/
inline KernelLauncher configure(dim3 grid, dim3 block, size_t smem = 0,
cudaStream_t stream = 0) const {
return KernelLauncher(*this, grid, block, smem, stream);
}
/*! Configure the kernel launch with a 1-dimensional block and grid chosen
* automatically to maximise occupancy.
*
* \param max_block_size The upper limit on the block size, or 0 for no
* limit.
* \param smem The amount of shared memory to dynamically allocate, in bytes.
* \param smem_callback A function returning smem for a given block size (overrides \p smem).
* \param stream The CUDA stream to launch the kernel in.
* \param flags The flags to pass to cuOccupancyMaxPotentialBlockSizeWithFlags.
*/
inline KernelLauncher configure_1d_max_occupancy(
int max_block_size = 0, size_t smem = 0,
CUoccupancyB2DSize smem_callback = 0, cudaStream_t stream = 0,
unsigned int flags = 0) const {
int grid;
int block;
CUfunction func = _impl->cuda_kernel();
detail::get_1d_max_occupancy(func, smem_callback, &smem, max_block_size,
flags, &grid, &block);
return this->configure(grid, block, smem, stream);
}
inline CUdeviceptr get_constant_ptr(const char* name) const {
return _impl->cuda_kernel().get_constant_ptr(name);
}
const std::string& mangled_name() const {
return _impl->cuda_kernel().function_name();
}
const std::string& ptx() const { return _impl->cuda_kernel().ptx(); }
const std::vector<std::string>& link_files() const {
return _impl->cuda_kernel().link_files();
}
const std::vector<std::string>& link_paths() const {
return _impl->cuda_kernel().link_paths();
}
};
/*! An object representing a kernel made up of a Program, a name and options.
*/
class Kernel {
friend class KernelInstantiation;
std::unique_ptr<Kernel_impl const> _impl;
public:
Kernel(Program const& program, std::string name,
jitify::detail::vector<std::string> options = 0);
/*! Instantiate the kernel.
*
* \param template_args A vector of template arguments represented as
* code-strings. These can be generated using
* \code{.cpp}jitify::reflection::reflect<type>()\endcode or
* \code{.cpp}jitify::reflection::reflect(value)\endcode
*
* \note Template type deduction is not possible, so all types must be
* explicitly specified.
*/
// inline KernelInstantiation instantiate(std::vector<std::string> const&
// template_args) const {
inline KernelInstantiation instantiate(
std::vector<std::string> const& template_args =
std::vector<std::string>()) const {
return KernelInstantiation(*this, template_args);
}
#if __cplusplus >= 201103L
// Regular template instantiation syntax (note limited flexibility)
/*! Instantiate the kernel.
*
* \note The template arguments specified on this function are
* used to instantiate the kernel. Non-type template arguments must
* be wrapped with
* \code{.cpp}jitify::reflection::NonType<type,value>\endcode
*
* \note Template type deduction is not possible, so all types must be
* explicitly specified.
*/
template <typename... TemplateArgs>
inline KernelInstantiation instantiate() const {
return this->instantiate(
std::vector<std::string>({reflection::reflect<TemplateArgs>()...}));
}
// Template-like instantiation syntax
// E.g., instantiate(myvar,Type<MyType>())(grid,block)
/*! Instantiate the kernel.
*
* \param targs The template arguments for the kernel, represented as
* values. Types must be wrapped with
* \code{.cpp}jitify::reflection::Type<type>()\endcode or
* \code{.cpp}jitify::reflection::type_of(value)\endcode
*
* \note Template type deduction is not possible, so all types must be
* explicitly specified.
*/
template <typename... TemplateArgs>
inline KernelInstantiation instantiate(TemplateArgs... targs) const {
return this->instantiate(
std::vector<std::string>({reflection::reflect(targs)...}));
}
#endif
};
/*! An object representing a program made up of source code, headers
* and options.
*/
class Program {
friend class Kernel;
std::unique_ptr<Program_impl const> _impl;
public:
Program(JitCache& cache, std::string source,
jitify::detail::vector<std::string> headers = 0,
jitify::detail::vector<std::string> options = 0,
file_callback_type file_callback = 0);
/*! Select a kernel.
*
* \param name The name of the kernel (unmangled and without
* template arguments).
* \param options A vector of options to be passed to the NVRTC
* compiler when compiling this kernel.
*/
inline Kernel kernel(std::string name,
jitify::detail::vector<std::string> options = 0) const {
return Kernel(*this, name, options);
}
/*! Select a kernel.
*
* \see kernel
*/
inline Kernel operator()(
std::string name, jitify::detail::vector<std::string> options = 0) const {
return this->kernel(name, options);
}
};
/*! An object that manages a cache of JIT-compiled CUDA kernels.
*
*/
class JitCache {
friend class Program;
std::unique_ptr<JitCache_impl> _impl;
public:
/*! JitCache constructor.
* \param cache_size The number of kernels to hold in the cache
* before overwriting the least-recently-used ones.
*/
enum { DEFAULT_CACHE_SIZE = 128 };
JitCache(size_t cache_size = DEFAULT_CACHE_SIZE)
: _impl(new JitCache_impl(cache_size)) {}
/*! Create a program.
*
* \param source A string containing either the source filename or
* the source itself; in the latter case, the first line must be
* the name of the program.
* \param headers A vector of strings representing the source of
* each header file required by the program. Each entry can be
* either the header filename or the header source itself; in
* the latter case, the first line must be the name of the header
* (i.e., the name by which the header is #included).
* \param options A vector of options to be passed to the
* NVRTC compiler. Include paths specified with \p -I
* are added to the search paths used by Jitify. The environment
* variable JITIFY_OPTIONS can also be used to define additional
* options.
* \param file_callback A pointer to a callback function that is
* invoked whenever a source file needs to be loaded. Inside this
* function, the user can either load/specify the source themselves
* or defer to Jitify's file-loading mechanisms.
* \note Program or header source files referenced by filename are
* looked-up using the following mechanisms (in this order):
* \note 1) By calling file_callback.
* \note 2) By looking for the file embedded in the executable via the GCC
* linker.
* \note 3) By looking for the file in the filesystem.
*
* \note Jitify recursively scans all source files for \p #include
* directives and automatically adds them to the set of headers needed
* by the program.
* If a \p #include directive references a header that cannot be found,
* the directive is automatically removed from the source code to prevent
* immediate compilation failure. This may result in compilation errors
* if the header was required by the program.
*
* \note Jitify automatically includes NVRTC-safe versions of some
* standard library headers.
*/
inline Program program(std::string source,
jitify::detail::vector<std::string> headers = 0,
jitify::detail::vector<std::string> options = 0,
file_callback_type file_callback = 0) {
return Program(*this, source, headers, options, file_callback);
}
};
inline Program::Program(JitCache& cache, std::string source,
jitify::detail::vector<std::string> headers,
jitify::detail::vector<std::string> options,
file_callback_type file_callback)
: _impl(new Program_impl(*cache._impl, source, headers, options,
file_callback)) {}
inline Kernel::Kernel(Program const& program, std::string name,
jitify::detail::vector<std::string> options)
: _impl(new Kernel_impl(*program._impl, name, options)) {}
inline KernelInstantiation::KernelInstantiation(
Kernel const& kernel, std::vector<std::string> const& template_args)
: _impl(new KernelInstantiation_impl(*kernel._impl, template_args)) {}
inline KernelLauncher::KernelLauncher(KernelInstantiation const& kernel_inst,
dim3 grid, dim3 block, size_t smem,
cudaStream_t stream)
: _impl(new KernelLauncher_impl(*kernel_inst._impl, grid, block, smem,
stream)) {}
inline std::ostream& operator<<(std::ostream& stream, dim3 d) {
if (d.y == 1 && d.z == 1) {
stream << d.x;
} else {
stream << "(" << d.x << "," << d.y << "," << d.z << ")";
}
return stream;
}
inline CUresult KernelLauncher_impl::launch(
jitify::detail::vector<void*> arg_ptrs,
jitify::detail::vector<std::string> arg_types) const {
#if JITIFY_PRINT_LAUNCH
Kernel_impl const& kernel = _kernel_inst._kernel;
std::string arg_types_string =
(arg_types.empty() ? "..." : reflection::reflect_list(arg_types));
std::cout << "Launching " << kernel._name << _kernel_inst._template_inst
<< "<<<" << _grid << "," << _block << "," << _smem << "," << _stream
<< ">>>"
<< "(" << arg_types_string << ")" << std::endl;
#endif
if (!_kernel_inst._cuda_kernel) {
throw std::runtime_error(
"Kernel pointer is NULL; you may need to define JITIFY_THREAD_SAFE 1");
}
return _kernel_inst._cuda_kernel->launch(_grid, _block, _smem, _stream,
arg_ptrs);
}
inline KernelInstantiation_impl::KernelInstantiation_impl(
Kernel_impl const& kernel, std::vector<std::string> const& template_args)
: _kernel(kernel), _options(kernel._options) {
_template_inst =
(template_args.empty() ? ""
: reflection::reflect_template(template_args));
using detail::hash_combine;
using detail::hash_larson64;
_hash = _kernel._hash;
_hash = hash_combine(_hash, hash_larson64(_template_inst.c_str()));
JitCache_impl& cache = _kernel._program._cache;
uint64_t cache_key = _hash;
#if JITIFY_THREAD_SAFE
std::lock_guard<std::mutex> lock(cache._kernel_cache_mutex);
#endif
if (cache._kernel_cache.contains(cache_key)) {
#if JITIFY_PRINT_INSTANTIATION
std::cout << "Found ";
this->print();
#endif
_cuda_kernel = &cache._kernel_cache.get(cache_key);
} else {
#if JITIFY_PRINT_INSTANTIATION
std::cout << "Building ";
this->print();
#endif
_cuda_kernel = &cache._kernel_cache.emplace(cache_key);
this->build_kernel();
}
}
inline void KernelInstantiation_impl::print() const {
std::string options_string = reflection::reflect_list(_options);
std::cout << _kernel._name << _template_inst << " [" << options_string << "]"
<< std::endl;
}
inline void KernelInstantiation_impl::build_kernel() {
Program_impl const& program = _kernel._program;
std::string instantiation = _kernel._name + _template_inst;
std::string log, ptx, mangled_instantiation;
std::vector<std::string> linker_files, linker_paths;
detail::instantiate_kernel(program.name(), program.sources(), instantiation,
_options, &log, &ptx, &mangled_instantiation,
&linker_files, &linker_paths);
_cuda_kernel->set(mangled_instantiation.c_str(), ptx.c_str(), linker_files,
linker_paths);
}
Kernel_impl::Kernel_impl(Program_impl const& program, std::string name,
jitify::detail::vector<std::string> options)
: _program(program), _name(name), _options(options) {
// Merge options from parent
_options.insert(_options.end(), _program.options().begin(),
_program.options().end());
detail::detect_and_add_cuda_arch(_options);
detail::detect_and_add_cxx11_flag(_options);
std::string options_string = reflection::reflect_list(_options);
using detail::hash_combine;
using detail::hash_larson64;
_hash = _program._hash;
_hash = hash_combine(_hash, hash_larson64(_name.c_str()));
_hash = hash_combine(_hash, hash_larson64(options_string.c_str()));
}
Program_impl::Program_impl(JitCache_impl& cache, std::string source,
jitify::detail::vector<std::string> headers,
jitify::detail::vector<std::string> options,
file_callback_type file_callback)
: _cache(cache) {
// Compute hash of source, headers and options
std::string options_string = reflection::reflect_list(options);
using detail::hash_combine;
using detail::hash_larson64;
_hash = hash_combine(hash_larson64(source.c_str()),
hash_larson64(options_string.c_str()));
for (size_t i = 0; i < headers.size(); ++i) {
_hash = hash_combine(_hash, hash_larson64(headers[i].c_str()));
}
_hash = hash_combine(_hash, (uint64_t)file_callback);
// Add built-in JIT-safe headers
for (int i = 0; i < detail::jitsafe_headers_count; ++i) {
const char* hdr_name = detail::jitsafe_header_names[i];
const char* hdr_source = detail::jitsafe_headers[i];
headers.push_back(std::string(hdr_name) + "\n" + hdr_source);
}
// Merge options from parent
options.insert(options.end(), _cache._options.begin(), _cache._options.end());
// Load sources
#if JITIFY_THREAD_SAFE
std::lock_guard<std::mutex> lock(cache._program_cache_mutex);
#endif
if (!cache._program_config_cache.contains(_hash)) {
_config = &cache._program_config_cache.insert(_hash);
this->load_sources(source, headers, options, file_callback);
} else {
_config = &cache._program_config_cache.get(_hash);
}
}
inline void Program_impl::load_sources(std::string source,
std::vector<std::string> headers,
std::vector<std::string> options,
file_callback_type file_callback) {
_config->options = options;
detail::load_program(source, headers, file_callback, &_config->include_paths,
&_config->sources, &_config->options, &_config->name);
}
#if __cplusplus >= 201103L
enum Location { HOST, DEVICE };
/*! Specifies location and parameters for execution of an algorithm.
* \param stream The CUDA stream on which to execute.
* \param headers A vector of headers to include in the code.
* \param options Options to pass to the NVRTC compiler.
* \param file_callback See jitify::Program.
* \param block_size The size of the CUDA thread block with which to
* execute.
* \param cache_size The number of kernels to store in the cache
* before overwriting the least-recently-used ones.
*/
struct ExecutionPolicy {
/*! Location (HOST or DEVICE) on which to execute.*/
Location location;
/*! List of headers to include when compiling the algorithm.*/
std::vector<std::string> headers;
/*! List of compiler options.*/
std::vector<std::string> options;
/*! Optional callback for loading source files.*/
file_callback_type file_callback;
/*! CUDA stream on which to execute.*/
cudaStream_t stream;
/*! CUDA device on which to execute.*/
int device;
/*! CUDA block size with which to execute.*/
int block_size;
/*! The number of instantiations to store in the cache before overwriting
* the least-recently-used ones.*/
size_t cache_size;
ExecutionPolicy(Location location_ = DEVICE,
jitify::detail::vector<std::string> headers_ = 0,
jitify::detail::vector<std::string> options_ = 0,
file_callback_type file_callback_ = 0,
cudaStream_t stream_ = 0, int device_ = 0,
int block_size_ = 256,
size_t cache_size_ = JitCache::DEFAULT_CACHE_SIZE)
: location(location_),
headers(headers_),
options(options_),
file_callback(file_callback_),
stream(stream_),
device(device_),
block_size(block_size_),
cache_size(cache_size_) {}
};
template <class Func>
class Lambda;
/*! An object that captures a set of variables for use in a parallel_for
* expression. See JITIFY_CAPTURE().
*/
class Capture {
public:
std::vector<std::string> _arg_decls;
std::vector<void*> _arg_ptrs;
public:
template <typename... Args>
inline Capture(std::vector<std::string> arg_names, Args const&... args)
: _arg_ptrs{(void*)&args...} {
std::vector<std::string> arg_types = {reflection::reflect<Args>()...};
_arg_decls.resize(arg_names.size());
for (int i = 0; i < (int)arg_names.size(); ++i) {
_arg_decls[i] = arg_types[i] + " " + arg_names[i];
}
}
};
/*! An object that captures the instantiated Lambda function for use
in a parallel_for expression and the function string for NVRTC
compilation
*/
template <class Func>
class Lambda {
public:
Capture _capture;
std::string _func_string;
Func _func;
public:
inline Lambda(Capture const& capture, std::string func_string, Func func)
: _capture(capture), _func_string(func_string), _func(func) {}
};
template <typename T>
inline Lambda<T> make_Lambda(Capture const& capture, std::string func,
T lambda) {
return Lambda<T>(capture, func, lambda);
}
#define JITIFY_CAPTURE(...) \
jitify::Capture(jitify::detail::split_string(#__VA_ARGS__, -1, ","), \
__VA_ARGS__)
#define JITIFY_MAKE_LAMBDA(capture, x, ...) \
jitify::make_Lambda(capture, std::string(#__VA_ARGS__), \
[x](int i) { __VA_ARGS__; })
#define JITIFY_ARGS(...) __VA_ARGS__
#define JITIFY_LAMBDA_(x, ...) \
JITIFY_MAKE_LAMBDA(JITIFY_CAPTURE(x), JITIFY_ARGS(x), __VA_ARGS__)
// macro sequence to strip surrounding brackets
#define JITIFY_STRIP_PARENS(X) X
#define JITIFY_PASS_PARAMETERS(X) JITIFY_STRIP_PARENS(JITIFY_ARGS X)
/*! Creates a Lambda object with captured variables and a function
* definition.
* \param capture A bracket-enclosed list of variables to capture.
* \param ... The function definition.
*
* \code{.cpp}
* float* capture_me;
* int capture_me_too;
* auto my_lambda = JITIFY_LAMBDA( (capture_me, capture_me_too),
* capture_me[i] = i*capture_me_too );
* \endcode
*/
#define JITIFY_LAMBDA(capture, ...) \
JITIFY_LAMBDA_(JITIFY_ARGS(JITIFY_PASS_PARAMETERS(capture)), \
JITIFY_ARGS(__VA_ARGS__))
// TODO: Try to implement for_each that accepts iterators instead of indices
// Add compile guard for NOCUDA compilation
/*! Call a function for a range of indices
*
* \param policy Determines the location and device parameters for
* execution of the parallel_for.
* \param begin The starting index.
* \param end The ending index.
* \param lambda A Lambda object created using the JITIFY_LAMBDA() macro.
*
* \code{.cpp}
* char const* in;
* float* out;
* parallel_for(0, 100, JITIFY_LAMBDA( (in, out), {char x = in[i]; out[i] =
* x*x; } ); \endcode
*/
template <typename IndexType, class Func>
CUresult parallel_for(ExecutionPolicy policy, IndexType begin, IndexType end,
Lambda<Func> const& lambda) {
using namespace jitify;
if (policy.location == HOST) {
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (IndexType i = begin; i < end; i++) {
lambda._func(i);
}
return CUDA_SUCCESS; // FIXME - replace with non-CUDA enum type?
}
thread_local static JitCache kernel_cache(policy.cache_size);
std::vector<std::string> arg_decls;
arg_decls.push_back("I begin, I end");
arg_decls.insert(arg_decls.end(), lambda._capture._arg_decls.begin(),
lambda._capture._arg_decls.end());
std::stringstream source_ss;
source_ss << "parallel_for_program\n";
for (auto const& header : policy.headers) {
std::string header_name = header.substr(0, header.find("\n"));
source_ss << "#include <" << header_name << ">\n";
}
source_ss << "template<typename I>\n"
"__global__\n"
"void parallel_for_kernel("
<< reflection::reflect_list(arg_decls)
<< ") {\n"
" I i0 = threadIdx.x + blockDim.x*blockIdx.x;\n"
" for( I i=i0+begin; i<end; i+=blockDim.x*gridDim.x ) {\n"
" "
<< "\t" << lambda._func_string << ";\n"
<< " }\n"
"}\n";
Program program = kernel_cache.program(source_ss.str(), policy.headers,
policy.options, policy.file_callback);
std::vector<void*> arg_ptrs;
arg_ptrs.push_back(&begin);
arg_ptrs.push_back(&end);
arg_ptrs.insert(arg_ptrs.end(), lambda._capture._arg_ptrs.begin(),
lambda._capture._arg_ptrs.end());
size_t n = end - begin;
dim3 block(policy.block_size);
dim3 grid(std::min((n - 1) / block.x + 1, size_t(65535)));
cudaSetDevice(policy.device);
return program.kernel("parallel_for_kernel")
.instantiate<IndexType>()
.configure(grid, block, 0, policy.stream)
.launch(arg_ptrs);
}
#endif // __cplusplus >= 201103L
namespace experimental {
using jitify::file_callback_type;
namespace serialization {
namespace detail {
// This should be incremented whenever the serialization format changes in any
// incompatible way.
static constexpr const size_t kSerializationVersion = 1;
inline void serialize(std::ostream& stream, size_t u) {
uint64_t u64 = u;
stream.write(reinterpret_cast<char*>(&u64), sizeof(u64));
}
inline bool deserialize(std::istream& stream, size_t* size) {
uint64_t u64;
stream.read(reinterpret_cast<char*>(&u64), sizeof(u64));
*size = u64;
return stream.good();
}
inline void serialize(std::ostream& stream, std::string const& s) {
serialize(stream, s.size());
stream.write(s.data(), s.size());
}
inline bool deserialize(std::istream& stream, std::string* s) {
size_t size;
if (!deserialize(stream, &size)) return false;
s->resize(size);
if (s->size()) {
stream.read(&(*s)[0], s->size());
}
return stream.good();
}
inline void serialize(std::ostream& stream, std::vector<std::string> const& v) {
serialize(stream, v.size());
for (auto const& s : v) {
serialize(stream, s);
}
}
inline bool deserialize(std::istream& stream, std::vector<std::string>* v) {
size_t size;
if (!deserialize(stream, &size)) return false;
v->resize(size);
for (auto& s : *v) {
if (!deserialize(stream, &s)) return false;
}
return true;
}
inline void serialize(std::ostream& stream,
std::map<std::string, std::string> const& m) {
serialize(stream, m.size());
for (auto const& kv : m) {
serialize(stream, kv.first);
serialize(stream, kv.second);
}
}
inline bool deserialize(std::istream& stream,
std::map<std::string, std::string>* m) {
size_t size;
if (!deserialize(stream, &size)) return false;
for (size_t i = 0; i < size; ++i) {
std::string key;
if (!deserialize(stream, &key)) return false;
if (!deserialize(stream, &(*m)[key])) return false;
}
return true;
}
template <typename T, typename... Rest>
inline void serialize(std::ostream& stream, T const& value, Rest... rest) {
serialize(stream, value);
serialize(stream, rest...);
}
template <typename T, typename... Rest>
inline bool deserialize(std::istream& stream, T* value, Rest... rest) {
if (!deserialize(stream, value)) return false;
return deserialize(stream, rest...);
}
inline void serialize_magic_number(std::ostream& stream) {
stream.write("JTFY", 4);
serialize(stream, kSerializationVersion);
}
inline bool deserialize_magic_number(std::istream& stream) {
char magic_number[4] = {0, 0, 0, 0};
stream.read(&magic_number[0], 4);
if (!(magic_number[0] == 'J' && magic_number[1] == 'T' &&
magic_number[2] == 'F' && magic_number[3] == 'Y')) {
return false;
}
size_t serialization_version;
if (!deserialize(stream, &serialization_version)) return false;
return serialization_version == kSerializationVersion;
}
} // namespace detail
template <typename... Values>
inline std::string serialize(Values const&... values) {
std::ostringstream ss(std::stringstream::out | std::stringstream::binary);
detail::serialize_magic_number(ss);
detail::serialize(ss, values...);
return ss.str();
}
template <typename... Values>
inline bool deserialize(std::string const& serialized, Values*... values) {
std::istringstream ss(serialized,
std::stringstream::in | std::stringstream::binary);
if (!detail::deserialize_magic_number(ss)) return false;
return detail::deserialize(ss, values...);
}
} // namespace serialization
class Program;
class Kernel;
class KernelInstantiation;
class KernelLauncher;
/*! An object representing a program made up of source code, headers
* and options.
*/
class Program {
private:
friend class KernelInstantiation;
std::string _name;
std::vector<std::string> _options;
std::map<std::string, std::string> _sources;
// Private constructor used by deserialize()
Program() {}
public:
/*! Create a program.
*
* \param source A string containing either the source filename or
* the source itself; in the latter case, the first line must be
* the name of the program.
* \param headers A vector of strings representing the source of
* each header file required by the program. Each entry can be
* either the header filename or the header source itself; in
* the latter case, the first line must be the name of the header
* (i.e., the name by which the header is #included).
* \param options A vector of options to be passed to the
* NVRTC compiler. Include paths specified with \p -I
* are added to the search paths used by Jitify. The environment
* variable JITIFY_OPTIONS can also be used to define additional
* options.
* \param file_callback A pointer to a callback function that is
* invoked whenever a source file needs to be loaded. Inside this
* function, the user can either load/specify the source themselves
* or defer to Jitify's file-loading mechanisms.
* \note Program or header source files referenced by filename are
* looked-up using the following mechanisms (in this order):
* \note 1) By calling file_callback.
* \note 2) By looking for the file embedded in the executable via the GCC
* linker.
* \note 3) By looking for the file in the filesystem.
*
* \note Jitify recursively scans all source files for \p #include
* directives and automatically adds them to the set of headers needed
* by the program.
* If a \p #include directive references a header that cannot be found,
* the directive is automatically removed from the source code to prevent
* immediate compilation failure. This may result in compilation errors
* if the header was required by the program.
*
* \note Jitify automatically includes NVRTC-safe versions of some
* standard library headers.
*/
Program(std::string const& cuda_source,
std::vector<std::string> const& given_headers = {},
std::vector<std::string> const& given_options = {},
file_callback_type file_callback = nullptr) {
// Add built-in JIT-safe headers
std::vector<std::string> headers = given_headers;
for (int i = 0; i < detail::jitsafe_headers_count; ++i) {
const char* hdr_name = detail::jitsafe_header_names[i];
const char* hdr_source = detail::jitsafe_headers[i];
headers.push_back(std::string(hdr_name) + "\n" + hdr_source);
}
_options = given_options;
detail::add_options_from_env(_options);
std::vector<std::string> include_paths;
detail::load_program(cuda_source, headers, file_callback, &include_paths,
&_sources, &_options, &_name);
}
/*! Restore a serialized program.
*
* \param serialized_program The serialized program to restore.
*
* \see serialize
*/
static Program deserialize(std::string const& serialized_program) {
Program program;
if (!serialization::deserialize(serialized_program, &program._name,
&program._options, &program._sources)) {
throw std::runtime_error("Failed to deserialize program");
}
return program;
}
/*! Save the program.
*
* \see deserialize
*/
std::string serialize() const {
// Note: Must update kSerializationVersion if this is changed.
return serialization::serialize(_name, _options, _sources);
};
/*! Select a kernel.
*
* \param name The name of the kernel (unmangled and without
* template arguments).
* \param options A vector of options to be passed to the NVRTC
* compiler when compiling this kernel.
*/
Kernel kernel(std::string const& name,
std::vector<std::string> const& options = {}) const;
};
class Kernel {
friend class KernelInstantiation;
Program const* _program;
std::string _name;
std::vector<std::string> _options;
public:
Kernel(Program const* program, std::string const& name,
std::vector<std::string> const& options = {})
: _program(program), _name(name), _options(options) {}
/*! Instantiate the kernel.
*
* \param template_args A vector of template arguments represented as
* code-strings. These can be generated using
* \code{.cpp}jitify::reflection::reflect<type>()\endcode or
* \code{.cpp}jitify::reflection::reflect(value)\endcode
*
* \note Template type deduction is not possible, so all types must be
* explicitly specified.
*/
KernelInstantiation instantiate(
std::vector<std::string> const& template_args =
std::vector<std::string>()) const;
// Regular template instantiation syntax (note limited flexibility)
/*! Instantiate the kernel.
*
* \note The template arguments specified on this function are
* used to instantiate the kernel. Non-type template arguments must
* be wrapped with
* \code{.cpp}jitify::reflection::NonType<type,value>\endcode
*
* \note Template type deduction is not possible, so all types must be
* explicitly specified.
*/
template <typename... TemplateArgs>
KernelInstantiation instantiate() const;
// Template-like instantiation syntax
// E.g., instantiate(myvar,Type<MyType>())(grid,block)
/*! Instantiate the kernel.
*
* \param targs The template arguments for the kernel, represented as
* values. Types must be wrapped with
* \code{.cpp}jitify::reflection::Type<type>()\endcode or
* \code{.cpp}jitify::reflection::type_of(value)\endcode
*
* \note Template type deduction is not possible, so all types must be
* explicitly specified.
*/
template <typename... TemplateArgs>
KernelInstantiation instantiate(TemplateArgs... targs) const;
};
class KernelInstantiation {
friend class KernelLauncher;
std::unique_ptr<detail::CUDAKernel> _cuda_kernel;
// Private constructor used by deserialize()
KernelInstantiation(std::string const& func_name, std::string const& ptx,
std::vector<std::string> const& link_files,
std::vector<std::string> const& link_paths)
: _cuda_kernel(new detail::CUDAKernel(func_name.c_str(), ptx.c_str(),
link_files, link_paths)) {}
public:
KernelInstantiation(Kernel const& kernel,
std::vector<std::string> const& template_args) {
Program const* program = kernel._program;
std::string template_inst =
(template_args.empty() ? ""
: reflection::reflect_template(template_args));
std::string instantiation = kernel._name + template_inst;
std::vector<std::string> options;
options.insert(options.begin(), program->_options.begin(),
program->_options.end());
options.insert(options.begin(), kernel._options.begin(),
kernel._options.end());
detail::detect_and_add_cuda_arch(options);
detail::detect_and_add_cxx11_flag(options);
std::string log, ptx, mangled_instantiation;
std::vector<std::string> linker_files, linker_paths;
detail::instantiate_kernel(program->_name, program->_sources, instantiation,
options, &log, &ptx, &mangled_instantiation,
&linker_files, &linker_paths);
_cuda_kernel.reset(new detail::CUDAKernel(mangled_instantiation.c_str(),
ptx.c_str(), linker_files,
linker_paths));
}
/*! Restore a serialized kernel instantiation.
*
* \param serialized_kernel_inst The serialized kernel instantiation to
* restore.
*
* \see serialize
*/
static KernelInstantiation deserialize(
std::string const& serialized_kernel_inst) {
std::string func_name, ptx;
std::vector<std::string> link_files, link_paths;
if (!serialization::deserialize(serialized_kernel_inst, &func_name, &ptx,
&link_files, &link_paths)) {
throw std::runtime_error("Failed to deserialize kernel instantiation");
}
return KernelInstantiation(func_name, ptx, link_files, link_paths);
}
/*! Save the program.
*
* \see deserialize
*/
std::string serialize() const {
// Note: Must update kSerializationVersion if this is changed.
return serialization::serialize(
_cuda_kernel->function_name(), _cuda_kernel->ptx(),
_cuda_kernel->link_files(), _cuda_kernel->link_paths());
}
/*! Configure the kernel launch.
*
* \param grid The thread grid dimensions for the launch.
* \param block The thread block dimensions for the launch.
* \param smem The amount of shared memory to dynamically allocate, in
* bytes.
* \param stream The CUDA stream to launch the kernel in.
*/
KernelLauncher configure(dim3 grid, dim3 block, size_t smem = 0,
cudaStream_t stream = 0) const;
/*! Configure the kernel launch with a 1-dimensional block and grid chosen
* automatically to maximise occupancy.
*
* \param max_block_size The upper limit on the block size, or 0 for no
* limit.
* \param smem The amount of shared memory to dynamically allocate, in bytes.
* \param smem_callback A function returning smem for a given block size
* (overrides \p smem).
* \param stream The CUDA stream to launch the kernel in.
* \param flags The flags to pass to
* cuOccupancyMaxPotentialBlockSizeWithFlags.
*/
KernelLauncher configure_1d_max_occupancy(
int max_block_size = 0, size_t smem = 0,
CUoccupancyB2DSize smem_callback = 0, cudaStream_t stream = 0,
unsigned int flags = 0) const;
CUdeviceptr get_constant_ptr(const char* name) const {
return _cuda_kernel->get_constant_ptr(name);
}
const std::string& mangled_name() const {
return _cuda_kernel->function_name();
}
const std::string& ptx() const { return _cuda_kernel->ptx(); }
const std::vector<std::string>& link_files() const {
return _cuda_kernel->link_files();
}
const std::vector<std::string>& link_paths() const {
return _cuda_kernel->link_paths();
}
};
class KernelLauncher {
KernelInstantiation const* _kernel_inst;
dim3 _grid;
dim3 _block;
size_t _smem;
cudaStream_t _stream;
public:
KernelLauncher(KernelInstantiation const* kernel_inst, dim3 grid, dim3 block,
size_t smem = 0, cudaStream_t stream = 0)
: _kernel_inst(kernel_inst),
_grid(grid),
_block(block),
_smem(smem),
_stream(stream) {}
// Note: It's important that there is no implicit conversion required
// for arg_ptrs, because otherwise the parameter pack version
// below gets called instead (probably resulting in a segfault).
/*! Launch the kernel.
*
* \param arg_ptrs A vector of pointers to each function argument for the
* kernel.
* \param arg_types A vector of function argument types represented
* as code-strings. This parameter is optional and is only used to print
* out the function signature.
*/
CUresult launch(std::vector<void*> arg_ptrs = {},
std::vector<std::string> arg_types = {}) const {
#if JITIFY_PRINT_LAUNCH
std::string arg_types_string =
(arg_types.empty() ? "..." : reflection::reflect_list(arg_types));
std::cout << "Launching " << _kernel_inst->_cuda_kernel->function_name()
<< "<<<" << _grid << "," << _block << "," << _smem << ","
<< _stream << ">>>"
<< "(" << arg_types_string << ")" << std::endl;
#endif
return _kernel_inst->_cuda_kernel->launch(_grid, _block, _smem, _stream,
arg_ptrs);
}
/*! Launch the kernel.
*
* \param args Function arguments for the kernel.
*/
template <typename... ArgTypes>
CUresult launch(ArgTypes... args) const {
return this->launch(std::vector<void*>({(void*)&args...}),
{reflection::reflect<ArgTypes>()...});
}
};
inline Kernel Program::kernel(std::string const& name,
std::vector<std::string> const& options) const {
return Kernel(this, name, options);
}
inline KernelInstantiation Kernel::instantiate(
std::vector<std::string> const& template_args) const {
return KernelInstantiation(*this, template_args);
}
template <typename... TemplateArgs>
inline KernelInstantiation Kernel::instantiate() const {
return this->instantiate(
std::vector<std::string>({reflection::reflect<TemplateArgs>()...}));
}
template <typename... TemplateArgs>
inline KernelInstantiation Kernel::instantiate(TemplateArgs... targs) const {
return this->instantiate(
std::vector<std::string>({reflection::reflect(targs)...}));
}
inline KernelLauncher KernelInstantiation::configure(
dim3 grid, dim3 block, size_t smem, cudaStream_t stream) const {
return KernelLauncher(this, grid, block, smem, stream);
}
inline KernelLauncher KernelInstantiation::configure_1d_max_occupancy(
int max_block_size, size_t smem, CUoccupancyB2DSize smem_callback,
cudaStream_t stream, unsigned int flags) const {
int grid;
int block;
CUfunction func = *_cuda_kernel;
detail::get_1d_max_occupancy(func, smem_callback, &smem, max_block_size,
flags, &grid, &block);
return this->configure(grid, block, smem, stream);
}
} // namespace experimental
} // namespace jitify
#if defined(_WIN32) || defined(_WIN64)
#pragma pop_macro("strtok_r")
#endif
#ifdef _MSVC_LANG
#pragma pop_macro("__cplusplus")
#endif
| 36.761244 | 128 | 0.63491 | [
"object",
"vector"
] |
f5d042da93274c1e68e49875df86c88d38ad5f3d | 31,110 | cpp | C++ | src/Nazara/Shader/LangWriter.cpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | src/Nazara/Shader/LangWriter.cpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | src/Nazara/Shader/LangWriter.cpp | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Shader module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Shader/LangWriter.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Math/Algorithm.hpp>
#include <Nazara/Shader/Enums.hpp>
#include <Nazara/Shader/ShaderBuilder.hpp>
#include <Nazara/Shader/Ast/AstCloner.hpp>
#include <Nazara/Shader/Ast/AstRecursiveVisitor.hpp>
#include <Nazara/Shader/Ast/AstUtils.hpp>
#include <Nazara/Shader/Ast/SanitizeVisitor.hpp>
#include <optional>
#include <stdexcept>
#include <Nazara/Shader/Debug.hpp>
namespace Nz
{
struct LangWriter::BindingAttribute
{
const ShaderAst::ExpressionValue<UInt32>& bindingIndex;
bool HasValue() const { return bindingIndex.HasValue(); }
};
struct LangWriter::BuiltinAttribute
{
const ShaderAst::ExpressionValue<ShaderAst::BuiltinEntry>& builtin;
bool HasValue() const { return builtin.HasValue(); }
};
struct LangWriter::DepthWriteAttribute
{
const ShaderAst::ExpressionValue<ShaderAst::DepthWriteMode>& writeMode;
bool HasValue() const { return writeMode.HasValue(); }
};
struct LangWriter::EarlyFragmentTestsAttribute
{
const ShaderAst::ExpressionValue<bool>& earlyFragmentTests;
bool HasValue() const { return earlyFragmentTests.HasValue(); }
};
struct LangWriter::EntryAttribute
{
const ShaderAst::ExpressionValue<ShaderStageType>& stageType;
bool HasValue() const { return stageType.HasValue(); }
};
struct LangWriter::LangVersionAttribute
{
UInt32 version;
bool HasValue() const { return true; }
};
struct LangWriter::LayoutAttribute
{
const ShaderAst::ExpressionValue<StructLayout>& layout;
bool HasValue() const { return layout.HasValue(); }
};
struct LangWriter::LocationAttribute
{
const ShaderAst::ExpressionValue<UInt32>& locationIndex;
bool HasValue() const { return locationIndex.HasValue(); }
};
struct LangWriter::SetAttribute
{
const ShaderAst::ExpressionValue<UInt32>& setIndex;
bool HasValue() const { return setIndex.HasValue(); }
};
struct LangWriter::UnrollAttribute
{
const ShaderAst::ExpressionValue<ShaderAst::LoopUnroll>& unroll;
bool HasValue() const { return unroll.HasValue(); }
};
struct LangWriter::UuidAttribute
{
Uuid uuid;
bool HasValue() const { return true; }
};
struct LangWriter::State
{
struct Identifier
{
std::size_t moduleIndex;
std::string name;
};
const States* states = nullptr;
const ShaderAst::Module* module;
std::size_t currentModuleIndex;
std::stringstream stream;
std::unordered_map<std::size_t, Identifier> aliases;
std::unordered_map<std::size_t, Identifier> constants;
std::unordered_map<std::size_t, Identifier> functions;
std::unordered_map<std::size_t, Identifier> structs;
std::unordered_map<std::size_t, Identifier> variables;
std::vector<std::string> moduleNames;
bool isInEntryPoint = false;
unsigned int indentLevel = 0;
};
std::string LangWriter::Generate(const ShaderAst::Module& module, const States& /*states*/)
{
State state;
m_currentState = &state;
CallOnExit onExit([this]()
{
m_currentState = nullptr;
});
state.module = &module;
AppendHeader();
// Register imported modules
m_currentState->currentModuleIndex = 0;
for (const auto& importedModule : module.importedModules)
{
AppendAttributes(true, LangVersionAttribute{ importedModule.module->metadata->shaderLangVersion });
AppendAttributes(true, UuidAttribute{ importedModule.module->metadata->moduleId });
AppendLine("module ", importedModule.identifier);
EnterScope();
importedModule.module->rootNode->Visit(*this);
LeaveScope(true);
m_currentState->currentModuleIndex++;
m_currentState->moduleNames.push_back(importedModule.identifier);
}
m_currentState->currentModuleIndex = std::numeric_limits<std::size_t>::max();
module.rootNode->Visit(*this);
return state.stream.str();
}
void LangWriter::SetEnv(Environment environment)
{
m_environment = std::move(environment);
}
void LangWriter::Append(const ShaderAst::AliasType& type)
{
AppendIdentifier(m_currentState->aliases, type.aliasIndex);
}
void LangWriter::Append(const ShaderAst::ArrayType& type)
{
Append("array[", type.containedType->type, ", ", type.length, "]");
}
void LangWriter::Append(const ShaderAst::ExpressionType& type)
{
std::visit([&](auto&& arg)
{
Append(arg);
}, type);
}
void LangWriter::Append(const ShaderAst::ExpressionValue<ShaderAst::ExpressionType>& type)
{
assert(type.HasValue());
if (type.IsResultingValue())
Append(type.GetResultingValue());
else
type.GetExpression()->Visit(*this);
}
void LangWriter::Append(const ShaderAst::FunctionType& /*functionType*/)
{
throw std::runtime_error("unexpected function type");
}
void LangWriter::Append(const ShaderAst::IntrinsicFunctionType& /*functionType*/)
{
throw std::runtime_error("unexpected intrinsic function type");
}
void LangWriter::Append(const ShaderAst::MatrixType& matrixType)
{
if (matrixType.columnCount == matrixType.rowCount)
{
Append("mat");
Append(matrixType.columnCount);
}
else
{
Append("mat");
Append(matrixType.columnCount);
Append("x");
Append(matrixType.rowCount);
}
Append("[", matrixType.type, "]");
}
void LangWriter::Append(const ShaderAst::MethodType& /*functionType*/)
{
throw std::runtime_error("unexpected method type");
}
void LangWriter::Append(ShaderAst::PrimitiveType type)
{
switch (type)
{
case ShaderAst::PrimitiveType::Boolean: return Append("bool");
case ShaderAst::PrimitiveType::Float32: return Append("f32");
case ShaderAst::PrimitiveType::Int32: return Append("i32");
case ShaderAst::PrimitiveType::UInt32: return Append("u32");
case ShaderAst::PrimitiveType::String: return Append("string");
}
}
void LangWriter::Append(const ShaderAst::SamplerType& samplerType)
{
Append("sampler");
switch (samplerType.dim)
{
case ImageType::E1D: Append("1D"); break;
case ImageType::E1D_Array: Append("1DArray"); break;
case ImageType::E2D: Append("2D"); break;
case ImageType::E2D_Array: Append("2DArray"); break;
case ImageType::E3D: Append("3D"); break;
case ImageType::Cubemap: Append("Cube"); break;
}
Append("[", samplerType.sampledType, "]");
}
void LangWriter::Append(const ShaderAst::StructType& structType)
{
AppendIdentifier(m_currentState->structs, structType.structIndex);
}
void LangWriter::Append(const ShaderAst::Type& /*type*/)
{
throw std::runtime_error("unexpected type?");
}
void LangWriter::Append(const ShaderAst::UniformType& uniformType)
{
Append("uniform[", uniformType.containedType, "]");
}
void LangWriter::Append(const ShaderAst::VectorType& vecType)
{
Append("vec", vecType.componentCount, "[", vecType.type, "]");
}
void LangWriter::Append(ShaderAst::NoType)
{
return Append("()");
}
template<typename T>
void LangWriter::Append(const T& param)
{
NazaraAssert(m_currentState, "This function should only be called while processing an AST");
m_currentState->stream << param;
}
template<typename T1, typename T2, typename... Args>
void LangWriter::Append(const T1& firstParam, const T2& secondParam, Args&&... params)
{
Append(firstParam);
Append(secondParam, std::forward<Args>(params)...);
}
template<typename ...Args>
void LangWriter::AppendAttributes(bool appendLine, Args&&... params)
{
bool hasAnyAttribute = (params.HasValue() || ...);
if (!hasAnyAttribute)
return;
bool first = true;
Append("[");
AppendAttributesInternal(first, std::forward<Args>(params)...);
Append("]");
if (appendLine)
AppendLine();
else
Append(" ");
}
template<typename T>
void LangWriter::AppendAttributesInternal(bool& first, const T& param)
{
if (!param.HasValue())
return;
if (!first)
Append(", ");
first = false;
AppendAttribute(param);
}
template<typename T1, typename T2, typename... Rest>
void LangWriter::AppendAttributesInternal(bool& first, const T1& firstParam, const T2& secondParam, Rest&&... params)
{
AppendAttributesInternal(first, firstParam);
AppendAttributesInternal(first, secondParam, std::forward<Rest>(params)...);
}
void LangWriter::AppendAttribute(BindingAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("binding(");
if (attribute.bindingIndex.IsResultingValue())
Append(attribute.bindingIndex.GetResultingValue());
else
attribute.bindingIndex.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(BuiltinAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("builtin(");
if (attribute.builtin.IsResultingValue())
{
switch (attribute.builtin.GetResultingValue())
{
case ShaderAst::BuiltinEntry::FragCoord:
Append("fragcoord");
break;
case ShaderAst::BuiltinEntry::FragDepth:
Append("fragdepth");
break;
case ShaderAst::BuiltinEntry::VertexPosition:
Append("position");
break;
}
}
else
attribute.builtin.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(DepthWriteAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("depth_write(");
if (attribute.writeMode.IsResultingValue())
{
switch (attribute.writeMode.GetResultingValue())
{
case ShaderAst::DepthWriteMode::Greater:
Append("greater");
break;
case ShaderAst::DepthWriteMode::Less:
Append("less");
break;
case ShaderAst::DepthWriteMode::Replace:
Append("replace");
break;
case ShaderAst::DepthWriteMode::Unchanged:
Append("unchanged");
break;
}
}
else
attribute.writeMode.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(EarlyFragmentTestsAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("early_fragment_tests(");
if (attribute.earlyFragmentTests.IsResultingValue())
{
if (attribute.earlyFragmentTests.GetResultingValue())
Append("true");
else
Append("false");
}
else
attribute.earlyFragmentTests.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(EntryAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("entry(");
if (attribute.stageType.IsResultingValue())
{
switch (attribute.stageType.GetResultingValue())
{
case ShaderStageType::Fragment:
Append("frag");
break;
case ShaderStageType::Vertex:
Append("vert");
break;
}
}
else
attribute.stageType.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(LangVersionAttribute attribute)
{
UInt32 shaderLangVersion = attribute.version;
UInt32 majorVersion = shaderLangVersion / 100;
shaderLangVersion -= majorVersion * 100;
UInt32 minorVersion = shaderLangVersion / 10;
shaderLangVersion -= minorVersion * 100;
UInt32 patchVersion = shaderLangVersion;
// nzsl_version
Append("nzsl_version(\"", majorVersion, ".", minorVersion);
if (patchVersion != 0)
Append(".", patchVersion);
Append("\")");
}
void LangWriter::AppendAttribute(LayoutAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("layout(");
if (attribute.layout.IsResultingValue())
{
switch (attribute.layout.GetResultingValue())
{
case StructLayout::Packed:
Append("packed");
break;
case StructLayout::Std140:
Append("std140");
break;
}
}
else
attribute.layout.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(LocationAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("location(");
if (attribute.locationIndex.IsResultingValue())
Append(attribute.locationIndex.GetResultingValue());
else
attribute.locationIndex.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(SetAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("set(");
if (attribute.setIndex.IsResultingValue())
Append(attribute.setIndex.GetResultingValue());
else
attribute.setIndex.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(UnrollAttribute attribute)
{
if (!attribute.HasValue())
return;
Append("unroll(");
if (attribute.unroll.IsResultingValue())
{
switch (attribute.unroll.GetResultingValue())
{
case ShaderAst::LoopUnroll::Always:
Append("always");
break;
case ShaderAst::LoopUnroll::Hint:
Append("hint");
break;
case ShaderAst::LoopUnroll::Never:
Append("never");
break;
default:
break;
}
}
else
attribute.unroll.GetExpression()->Visit(*this);
Append(")");
}
void LangWriter::AppendAttribute(UuidAttribute attribute)
{
Append("uuid(\"", attribute.uuid.ToString(), "\")");
}
void LangWriter::AppendComment(const std::string& section)
{
std::size_t lineFeed = section.find('\n');
if (lineFeed != section.npos)
{
std::size_t previousCut = 0;
AppendLine("/*");
do
{
AppendLine(section.substr(previousCut, lineFeed - previousCut));
previousCut = lineFeed + 1;
}
while ((lineFeed = section.find('\n', previousCut)) != section.npos);
AppendLine(section.substr(previousCut));
AppendLine("*/");
}
else
AppendLine("// ", section);
}
void LangWriter::AppendCommentSection(const std::string& section)
{
NazaraAssert(m_currentState, "This function should only be called while processing an AST");
std::string stars((section.size() < 33) ? (36 - section.size()) / 2 : 3, '*');
m_currentState->stream << "/*" << stars << ' ' << section << ' ' << stars << "*/";
AppendLine();
}
void LangWriter::AppendLine(const std::string& txt)
{
NazaraAssert(m_currentState, "This function should only be called while processing an AST");
m_currentState->stream << txt << '\n' << std::string(m_currentState->indentLevel, '\t');
}
template<typename T>
void LangWriter::AppendIdentifier(const T& map, std::size_t id)
{
const auto& structIdentifier = Retrieve(map, id);
if (structIdentifier.moduleIndex != m_currentState->currentModuleIndex)
Append(m_currentState->moduleNames[structIdentifier.moduleIndex], '.');
Append(structIdentifier.name);
}
template<typename... Args>
void LangWriter::AppendLine(Args&&... params)
{
(Append(std::forward<Args>(params)), ...);
AppendLine();
}
void LangWriter::AppendStatementList(std::vector<ShaderAst::StatementPtr>& statements)
{
bool first = true;
for (const ShaderAst::StatementPtr& statement : statements)
{
if (statement->GetType() == ShaderAst::NodeType::NoOpStatement)
continue;
if (!first)
AppendLine();
statement->Visit(*this);
first = false;
}
}
void LangWriter::EnterScope()
{
NazaraAssert(m_currentState, "This function should only be called while processing an AST");
m_currentState->indentLevel++;
AppendLine("{");
}
void LangWriter::LeaveScope(bool skipLine)
{
NazaraAssert(m_currentState, "This function should only be called while processing an AST");
m_currentState->indentLevel--;
AppendLine();
if (skipLine)
AppendLine("}");
else
Append("}");
}
void LangWriter::RegisterAlias(std::size_t aliasIndex, std::string aliasName)
{
State::Identifier identifier;
identifier.moduleIndex = m_currentState->currentModuleIndex;
identifier.name = std::move(aliasName);
assert(m_currentState->aliases.find(aliasIndex) == m_currentState->aliases.end());
m_currentState->aliases.emplace(aliasIndex, std::move(identifier));
}
void LangWriter::RegisterConstant(std::size_t constantIndex, std::string constantName)
{
State::Identifier identifier;
identifier.moduleIndex = m_currentState->currentModuleIndex;
identifier.name = std::move(constantName);
assert(m_currentState->constants.find(constantIndex) == m_currentState->constants.end());
m_currentState->constants.emplace(constantIndex, std::move(identifier));
}
void LangWriter::RegisterFunction(std::size_t funcIndex, std::string functionName)
{
State::Identifier identifier;
identifier.moduleIndex = m_currentState->currentModuleIndex;
identifier.name = std::move(functionName);
assert(m_currentState->functions.find(funcIndex) == m_currentState->functions.end());
m_currentState->functions.emplace(funcIndex, std::move(identifier));
}
void LangWriter::RegisterStruct(std::size_t structIndex, std::string structName)
{
State::Identifier identifier;
identifier.moduleIndex = m_currentState->currentModuleIndex;
identifier.name = std::move(structName);
assert(m_currentState->structs.find(structIndex) == m_currentState->structs.end());
m_currentState->structs.emplace(structIndex, std::move(identifier));
}
void LangWriter::RegisterVariable(std::size_t varIndex, std::string varName)
{
State::Identifier identifier;
identifier.moduleIndex = m_currentState->currentModuleIndex;
identifier.name = std::move(varName);
assert(m_currentState->variables.find(varIndex) == m_currentState->variables.end());
m_currentState->variables.emplace(varIndex, std::move(identifier));
}
void LangWriter::ScopeVisit(ShaderAst::Statement& node)
{
if (node.GetType() != ShaderAst::NodeType::ScopedStatement)
{
EnterScope();
node.Visit(*this);
LeaveScope(true);
}
else
node.Visit(*this);
}
void LangWriter::Visit(ShaderAst::ExpressionPtr& expr, bool encloseIfRequired)
{
bool enclose = encloseIfRequired && (GetExpressionCategory(*expr) != ShaderAst::ExpressionCategory::LValue);
if (enclose)
Append("(");
expr->Visit(*this);
if (enclose)
Append(")");
}
void LangWriter::Visit(ShaderAst::AccessIdentifierExpression& node)
{
Visit(node.expr, true);
for (const auto& identifierEntry : node.identifiers)
Append(".", identifierEntry.identifier);
}
void LangWriter::Visit(ShaderAst::AccessIndexExpression& node)
{
Visit(node.expr, true);
// Array access
Append("[");
bool first = true;
for (ShaderAst::ExpressionPtr& expr : node.indices)
{
if (!first)
Append(", ");
expr->Visit(*this);
first = false;
}
Append("]");
}
void LangWriter::Visit(ShaderAst::AliasValueExpression& node)
{
AppendIdentifier(m_currentState->aliases, node.aliasId);
}
void LangWriter::Visit(ShaderAst::AssignExpression& node)
{
node.left->Visit(*this);
switch (node.op)
{
case ShaderAst::AssignType::Simple: Append(" = "); break;
case ShaderAst::AssignType::CompoundAdd: Append(" += "); break;
case ShaderAst::AssignType::CompoundDivide: Append(" /= "); break;
case ShaderAst::AssignType::CompoundMultiply: Append(" *= "); break;
case ShaderAst::AssignType::CompoundLogicalAnd: Append(" &&= "); break;
case ShaderAst::AssignType::CompoundLogicalOr: Append(" ||= "); break;
case ShaderAst::AssignType::CompoundSubtract: Append(" -= "); break;
}
node.right->Visit(*this);
}
void LangWriter::Visit(ShaderAst::BranchStatement& node)
{
bool first = true;
for (const auto& statement : node.condStatements)
{
if (first)
{
if (node.isConst)
Append("const ");
}
else
Append("else ");
Append("if (");
statement.condition->Visit(*this);
AppendLine(")");
ScopeVisit(*statement.statement);
first = false;
}
if (node.elseStatement)
{
AppendLine("else");
ScopeVisit(*node.elseStatement);
}
}
void LangWriter::Visit(ShaderAst::BinaryExpression& node)
{
Visit(node.left, true);
switch (node.op)
{
case ShaderAst::BinaryType::Add: Append(" + "); break;
case ShaderAst::BinaryType::Subtract: Append(" - "); break;
case ShaderAst::BinaryType::Multiply: Append(" * "); break;
case ShaderAst::BinaryType::Divide: Append(" / "); break;
case ShaderAst::BinaryType::CompEq: Append(" == "); break;
case ShaderAst::BinaryType::CompGe: Append(" >= "); break;
case ShaderAst::BinaryType::CompGt: Append(" > "); break;
case ShaderAst::BinaryType::CompLe: Append(" <= "); break;
case ShaderAst::BinaryType::CompLt: Append(" < "); break;
case ShaderAst::BinaryType::CompNe: Append(" != "); break;
case ShaderAst::BinaryType::LogicalAnd: Append(" && "); break;
case ShaderAst::BinaryType::LogicalOr: Append(" || "); break;
}
Visit(node.right, true);
}
void LangWriter::Visit(ShaderAst::CallFunctionExpression& node)
{
node.targetFunction->Visit(*this);
Append("(");
for (std::size_t i = 0; i < node.parameters.size(); ++i)
{
if (i != 0)
Append(", ");
node.parameters[i]->Visit(*this);
}
Append(")");
}
void LangWriter::Visit(ShaderAst::CastExpression& node)
{
Append(node.targetType);
Append("(");
bool first = true;
for (const auto& exprPtr : node.expressions)
{
if (!exprPtr)
break;
if (!first)
m_currentState->stream << ", ";
exprPtr->Visit(*this);
first = false;
}
Append(")");
}
void LangWriter::Visit(ShaderAst::ConditionalExpression& node)
{
Append("const_select(");
node.condition->Visit(*this);
Append(", ");
node.truePath->Visit(*this);
Append(", ");
node.falsePath->Visit(*this);
Append(")");
}
void LangWriter::Visit(ShaderAst::ConditionalStatement& node)
{
Append("[cond(");
node.condition->Visit(*this);
AppendLine(")]");
node.statement->Visit(*this);
}
void LangWriter::Visit(ShaderAst::DeclareAliasStatement& node)
{
if (node.aliasIndex)
RegisterAlias(*node.aliasIndex, node.name);
Append("alias ", node.name, " = ");
assert(node.expression);
node.expression->Visit(*this);
AppendLine(";");
}
void LangWriter::Visit(ShaderAst::DeclareConstStatement& node)
{
if (node.constIndex)
RegisterConstant(*node.constIndex, node.name);
Append("const ", node.name);
if (node.type.HasValue())
Append(": ", node.type);
if (node.expression)
{
Append(" = ");
node.expression->Visit(*this);
}
AppendLine(";");
}
void LangWriter::Visit(ShaderAst::ConstantValueExpression& node)
{
std::visit([&](auto&& arg)
{
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, ShaderAst::NoValue>)
throw std::runtime_error("invalid type (value expected)");
else if constexpr (std::is_same_v<T, bool>)
Append((arg) ? "true" : "false");
else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, Int32> || std::is_same_v<T, UInt32>)
Append(std::to_string(arg));
else if constexpr (std::is_same_v<T, std::string>)
Append('"', arg, '"'); //< TODO: Escape string
else if constexpr (std::is_same_v<T, Vector2f>)
Append("vec2[f32](" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ")");
else if constexpr (std::is_same_v<T, Vector2i32>)
Append("vec2<i32>(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ")");
else if constexpr (std::is_same_v<T, Vector3f>)
Append("vec3[f32](" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ")");
else if constexpr (std::is_same_v<T, Vector3i32>)
Append("vec3<i32>(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ")");
else if constexpr (std::is_same_v<T, Vector4f>)
Append("vec4[f32](" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ", " + std::to_string(arg.w) + ")");
else if constexpr (std::is_same_v<T, Vector4i32>)
Append("vec4<i32>(" + std::to_string(arg.x) + ", " + std::to_string(arg.y) + ", " + std::to_string(arg.z) + ", " + std::to_string(arg.w) + ")");
else
static_assert(AlwaysFalse<T>::value, "non-exhaustive visitor");
}, node.value);
}
void LangWriter::Visit(ShaderAst::ConstantExpression& node)
{
AppendIdentifier(m_currentState->constants, node.constantId);
}
void LangWriter::Visit(ShaderAst::FunctionExpression& node)
{
AppendIdentifier(m_currentState->functions, node.funcId);
}
void LangWriter::Visit(ShaderAst::IdentifierExpression& node)
{
Append(node.identifier);
}
void LangWriter::Visit(ShaderAst::DeclareExternalStatement& node)
{
AppendLine("external");
EnterScope();
bool first = true;
for (const auto& externalVar : node.externalVars)
{
if (!first)
AppendLine(",");
first = false;
AppendAttributes(false, SetAttribute{ externalVar.bindingSet }, BindingAttribute{ externalVar.bindingIndex });
Append(externalVar.name, ": ", externalVar.type);
if (externalVar.varIndex)
RegisterVariable(*externalVar.varIndex, externalVar.name);
}
LeaveScope();
}
void LangWriter::Visit(ShaderAst::DeclareFunctionStatement& node)
{
NazaraAssert(m_currentState, "This function should only be called while processing an AST");
if (node.funcIndex)
RegisterFunction(*node.funcIndex, node.name);
AppendAttributes(true, EntryAttribute{ node.entryStage }, EarlyFragmentTestsAttribute{ node.earlyFragmentTests }, DepthWriteAttribute{ node.depthWrite });
Append("fn ", node.name, "(");
for (std::size_t i = 0; i < node.parameters.size(); ++i)
{
const auto& parameter = node.parameters[i];
if (i != 0)
Append(", ");
Append(parameter.name);
Append(": ");
Append(parameter.type);
if (parameter.varIndex)
RegisterVariable(*parameter.varIndex, parameter.name);
}
Append(")");
if (node.returnType.HasValue())
{
if (!node.returnType.IsResultingValue() || !IsNoType(node.returnType.GetResultingValue()))
Append(" -> ", node.returnType);
}
AppendLine();
EnterScope();
{
AppendStatementList(node.statements);
}
LeaveScope();
}
void LangWriter::Visit(ShaderAst::DeclareOptionStatement& node)
{
if (node.optIndex)
RegisterConstant(*node.optIndex, node.optName);
Append("option ", node.optName);
if (node.optType.HasValue())
Append(": ", node.optType);
if (node.defaultValue)
{
Append(" = ");
node.defaultValue->Visit(*this);
}
Append(";");
}
void LangWriter::Visit(ShaderAst::DeclareStructStatement& node)
{
if (node.structIndex)
RegisterStruct(*node.structIndex, node.description.name);
AppendAttributes(true, LayoutAttribute{ node.description.layout });
Append("struct ");
AppendLine(node.description.name);
EnterScope();
{
bool first = true;
for (const auto& member : node.description.members)
{
if (!first)
AppendLine(",");
first = false;
AppendAttributes(false, LocationAttribute{ member.locationIndex }, BuiltinAttribute{ member.builtin });
Append(member.name, ": ", member.type);
}
}
LeaveScope();
}
void LangWriter::Visit(ShaderAst::DeclareVariableStatement& node)
{
if (node.varIndex)
RegisterVariable(*node.varIndex, node.varName);
Append("let ", node.varName);
if (node.varType.HasValue())
Append(": ", node.varType);
if (node.initialExpression)
{
Append(" = ");
node.initialExpression->Visit(*this);
}
Append(";");
}
void LangWriter::Visit(ShaderAst::DiscardStatement& /*node*/)
{
Append("discard;");
}
void LangWriter::Visit(ShaderAst::ExpressionStatement& node)
{
node.expression->Visit(*this);
Append(";");
}
void LangWriter::Visit(ShaderAst::ForStatement& node)
{
if (node.varIndex)
RegisterVariable(*node.varIndex, node.varName);
AppendAttributes(true, UnrollAttribute{ node.unroll });
Append("for ", node.varName, " in ");
node.fromExpr->Visit(*this);
Append(" -> ");
node.toExpr->Visit(*this);
if (node.stepExpr)
{
Append(" : ");
node.stepExpr->Visit(*this);
}
AppendLine();
ScopeVisit(*node.statement);
}
void LangWriter::Visit(ShaderAst::ForEachStatement& node)
{
if (node.varIndex)
RegisterVariable(*node.varIndex, node.varName);
AppendAttributes(true, UnrollAttribute{ node.unroll });
Append("for ", node.varName, " in ");
node.expression->Visit(*this);
AppendLine();
ScopeVisit(*node.statement);
}
void LangWriter::Visit(ShaderAst::ImportStatement& node)
{
Append("import ", node.moduleName, ";");
}
void LangWriter::Visit(ShaderAst::IntrinsicExpression& node)
{
bool method = false;
switch (node.intrinsic)
{
case ShaderAst::IntrinsicType::CrossProduct:
Append("cross");
break;
case ShaderAst::IntrinsicType::DotProduct:
Append("dot");
break;
case ShaderAst::IntrinsicType::Exp:
Append("exp");
break;
case ShaderAst::IntrinsicType::Length:
Append("length");
break;
case ShaderAst::IntrinsicType::Max:
Append("max");
break;
case ShaderAst::IntrinsicType::Min:
Append("min");
break;
case ShaderAst::IntrinsicType::Normalize:
Append("normalize");
break;
case ShaderAst::IntrinsicType::Pow:
Append("pow");
break;
case ShaderAst::IntrinsicType::Reflect:
Append("reflect");
break;
case ShaderAst::IntrinsicType::SampleTexture:
assert(!node.parameters.empty());
Visit(node.parameters.front(), true);
Append(".Sample");
method = true;
break;
}
Append("(");
bool first = true;
for (std::size_t i = (method) ? 1 : 0; i < node.parameters.size(); ++i)
{
if (!first)
Append(", ");
first = false;
node.parameters[i]->Visit(*this);
}
Append(")");
}
void LangWriter::Visit(ShaderAst::StructTypeExpression& node)
{
AppendIdentifier(m_currentState->structs, node.structTypeId);
}
void LangWriter::Visit(ShaderAst::MultiStatement& node)
{
AppendStatementList(node.statements);
}
void LangWriter::Visit(ShaderAst::NoOpStatement& /*node*/)
{
/* nothing to do */
}
void LangWriter::Visit(ShaderAst::ReturnStatement& node)
{
if (node.returnExpr)
{
Append("return ");
node.returnExpr->Visit(*this);
Append(";");
}
else
Append("return;");
}
void LangWriter::Visit(ShaderAst::ScopedStatement& node)
{
EnterScope();
node.statement->Visit(*this);
LeaveScope();
}
void LangWriter::Visit(ShaderAst::SwizzleExpression& node)
{
Visit(node.expression, true);
Append(".");
const char* componentStr = "xyzw";
for (std::size_t i = 0; i < node.componentCount; ++i)
Append(componentStr[node.components[i]]);
}
void LangWriter::Visit(ShaderAst::VariableValueExpression& node)
{
AppendIdentifier(m_currentState->variables, node.variableId);
}
void LangWriter::Visit(ShaderAst::UnaryExpression& node)
{
switch (node.op)
{
case ShaderAst::UnaryType::LogicalNot:
Append("!");
break;
case ShaderAst::UnaryType::Minus:
Append("-");
break;
case ShaderAst::UnaryType::Plus:
Append("+");
break;
}
node.expression->Visit(*this);
}
void LangWriter::Visit(ShaderAst::WhileStatement& node)
{
Append("while (");
node.condition->Visit(*this);
AppendLine(")");
ScopeVisit(*node.body);
}
void LangWriter::AppendHeader()
{
AppendAttributes(true, LangVersionAttribute{ m_currentState->module->metadata->shaderLangVersion });
AppendLine("module;");
AppendLine();
}
}
| 24.153727 | 156 | 0.682803 | [
"vector",
"3d"
] |
f5d34941cb51275c3afc5db4e160a5d22c11838b | 10,131 | cpp | C++ | test/t/relations/test_relations_manager.cpp | MateuszGrabka-TomTom/libosmium | 04506b22fca3e9660d65763c09755a99f3d7b985 | [
"BSL-1.0"
] | 335 | 2015-01-30T13:52:10.000Z | 2022-03-30T07:25:57.000Z | test/t/relations/test_relations_manager.cpp | MateuszGrabka-TomTom/libosmium | 04506b22fca3e9660d65763c09755a99f3d7b985 | [
"BSL-1.0"
] | 267 | 2015-01-05T07:46:29.000Z | 2022-03-18T13:24:41.000Z | test/t/relations/test_relations_manager.cpp | MateuszGrabka-TomTom/libosmium | 04506b22fca3e9660d65763c09755a99f3d7b985 | [
"BSL-1.0"
] | 120 | 2015-01-12T14:41:33.000Z | 2022-03-30T07:25:48.000Z | #include "catch.hpp"
#include "utils.hpp"
#include <osmium/io/xml_input.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/relations/relations_manager.hpp>
#include <iterator>
struct EmptyRM : public osmium::relations::RelationsManager<EmptyRM, true, true, true> {
};
struct TestRM : public osmium::relations::RelationsManager<TestRM, true, true, true> {
std::size_t count_new_rels = 0;
std::size_t count_new_members = 0;
std::size_t count_complete_rels = 0;
std::size_t count_before = 0;
std::size_t count_not_in_any = 0;
std::size_t count_after = 0;
bool new_relation(const osmium::Relation& /*relation*/) noexcept {
++count_new_rels;
return true;
}
bool new_member(const osmium::Relation& /*relation*/, const osmium::RelationMember& /*member*/, std::size_t /*n*/) noexcept {
++count_new_members;
return true;
}
void complete_relation(const osmium::Relation& /*relation*/) noexcept {
++count_complete_rels;
}
void before_node(const osmium::Node& /*node*/) noexcept {
++count_before;
}
void node_not_in_any_relation(const osmium::Node& /*node*/) noexcept {
++count_not_in_any;
}
void after_node(const osmium::Node& /*node*/) noexcept {
++count_after;
}
void before_way(const osmium::Way& /*way*/) noexcept {
++count_before;
}
void way_not_in_any_relation(const osmium::Way& /*way*/) noexcept {
++count_not_in_any;
}
void after_way(const osmium::Way& /*way*/) noexcept {
++count_after;
}
void before_relation(const osmium::Relation& /*relation*/) noexcept {
++count_before;
}
void relation_not_in_any_relation(const osmium::Relation& /*relation*/) noexcept {
++count_not_in_any;
}
void after_relation(const osmium::Relation& /*relation*/) noexcept {
++count_after;
}
};
struct CallbackRM : public osmium::relations::RelationsManager<CallbackRM, true, false, false> {
std::size_t count_nodes = 0;
static bool new_relation(const osmium::Relation& /*relation*/) noexcept {
return true;
}
static bool new_member(const osmium::Relation& /*relation*/, const osmium::RelationMember& member, std::size_t /*n*/) noexcept {
return member.type() == osmium::item_type::node;
}
void complete_relation(const osmium::Relation& relation) {
for (const auto& member : relation.members()) {
if (member.type() == osmium::item_type::node) {
++count_nodes;
const auto* node = get_member_node(member.ref());
REQUIRE(node);
buffer().add_item(*node);
buffer().commit();
}
}
}
};
struct AnyRM : public osmium::relations::RelationsManager<AnyRM, true, true, true> {
static bool new_relation(const osmium::Relation& /*relation*/) noexcept {
return true;
}
static bool new_member(const osmium::Relation& /*relation*/, const osmium::RelationMember& /*member*/, std::size_t /*n*/) noexcept {
return true;
}
};
TEST_CASE("Use RelationsManager without any overloaded functions in derived class") {
osmium::io::File file{with_data_dir("t/relations/data.osm")};
EmptyRM manager;
osmium::relations::read_relations(file, manager);
REQUIRE(manager.member_nodes_database().size() == 2);
REQUIRE(manager.member_ways_database().size() == 2);
REQUIRE(manager.member_relations_database().size() == 1);
REQUIRE(manager.member_database(osmium::item_type::node).size() == 2);
REQUIRE(manager.member_database(osmium::item_type::way).size() == 2);
REQUIRE(manager.member_database(osmium::item_type::relation).size() == 1);
const auto& m = manager;
REQUIRE(m.member_database(osmium::item_type::node).size() == 2);
REQUIRE(m.member_database(osmium::item_type::way).size() == 2);
REQUIRE(m.member_database(osmium::item_type::relation).size() == 1);
osmium::io::Reader reader{file};
osmium::apply(reader, manager.handler());
reader.close();
}
TEST_CASE("Relations manager derived class") {
osmium::io::File file{with_data_dir("t/relations/data.osm")};
TestRM manager;
osmium::relations::read_relations(file, manager);
REQUIRE(manager.member_nodes_database().size() == 2);
REQUIRE(manager.member_ways_database().size() == 2);
REQUIRE(manager.member_relations_database().size() == 1);
bool callback_called = false;
osmium::io::Reader reader{file};
osmium::apply(reader, manager.handler([&](osmium::memory::Buffer&& /*unused*/) {
callback_called = true;
}));
reader.close();
REQUIRE_FALSE(callback_called);
REQUIRE(manager.count_new_rels == 3);
REQUIRE(manager.count_new_members == 5);
REQUIRE(manager.count_complete_rels == 2);
REQUIRE(manager.count_before == 10);
REQUIRE(manager.count_not_in_any == 6);
REQUIRE(manager.count_after == 10);
int n = 0;
manager.for_each_incomplete_relation([&](const osmium::relations::RelationHandle& handle){
++n;
REQUIRE(handle->id() == 31);
for (const auto& member : handle->members()) {
const auto* obj = manager.get_member_object(member);
if (member.ref() == 22) {
REQUIRE_FALSE(obj);
} else {
REQUIRE(obj);
}
}
});
REQUIRE(n == 1);
}
TEST_CASE("Relations manager with callback") {
osmium::io::File file{with_data_dir("t/relations/data.osm")};
CallbackRM manager;
osmium::relations::read_relations(file, manager);
REQUIRE(manager.member_nodes_database().size() == 2);
REQUIRE(manager.member_ways_database().size() == 0);
REQUIRE(manager.member_relations_database().size() == 0);
bool callback_called = false;
osmium::io::Reader reader{file};
osmium::apply(reader, manager.handler([&](osmium::memory::Buffer&& buffer) {
callback_called = true;
REQUIRE(std::distance(buffer.begin(), buffer.end()) == 2);
}));
reader.close();
REQUIRE(manager.count_nodes == 2);
REQUIRE(callback_called);
}
TEST_CASE("Relations manager reading buffer without callback") {
osmium::io::File file{with_data_dir("t/relations/data.osm")};
CallbackRM manager;
osmium::relations::read_relations(file, manager);
REQUIRE(manager.member_nodes_database().size() == 2);
REQUIRE(manager.member_ways_database().size() == 0);
REQUIRE(manager.member_relations_database().size() == 0);
osmium::io::Reader reader{file};
osmium::apply(reader, manager.handler());
reader.close();
auto buffer = manager.read();
REQUIRE(std::distance(buffer.begin(), buffer.end()) == 2);
REQUIRE(manager.count_nodes == 2);
}
TEST_CASE("Access members via RelationsManager") {
EmptyRM manager;
manager.prepare_for_lookup();
REQUIRE(nullptr == manager.get_member_node(0));
REQUIRE(nullptr == manager.get_member_way(0));
REQUIRE(nullptr == manager.get_member_relation(0));
REQUIRE(nullptr == manager.get_member_node(17));
REQUIRE(nullptr == manager.get_member_way(17));
REQUIRE(nullptr == manager.get_member_relation(17));
}
TEST_CASE("Handle duplicate members correctly") {
osmium::io::File file{with_data_dir("t/relations/dupl_member.osm")};
TestRM manager;
osmium::relations::read_relations(file, manager);
auto c = manager.member_nodes_database().count();
REQUIRE(c.tracked == 5);
REQUIRE(c.available == 0);
REQUIRE(c.removed == 0);
osmium::io::Reader reader{file};
osmium::apply(reader, manager.handler());
reader.close();
c = manager.member_nodes_database().count();
REQUIRE(c.tracked == 0);
REQUIRE(c.available == 0);
REQUIRE(c.removed == 5);
REQUIRE(manager.count_new_rels == 2);
REQUIRE(manager.count_new_members == 5);
REQUIRE(manager.count_complete_rels == 2);
REQUIRE(manager.count_not_in_any == 2); // 2 relations
}
TEST_CASE("Check handling of missing members") {
osmium::io::File file{with_data_dir("t/relations/missing_members.osm")};
AnyRM manager;
osmium::relations::read_relations(file, manager);
osmium::io::Reader reader{file};
osmium::apply(reader, manager.handler());
reader.close();
size_t nodes = 0;
size_t ways = 0;
size_t relations = 0;
size_t missing_nodes = 0;
size_t missing_ways = 0;
size_t missing_relations = 0;
manager.for_each_incomplete_relation([&](const osmium::relations::RelationHandle& handle){
if (handle->id() != 31) {
// count relation 31 only
return;
}
for (const auto& member : handle->members()) {
// RelationMember::ref() is supposed to returns 0 if we are interested in the member.
// RelationsManagerBase::get_member_object() is supposed to return a nullptr if the
// member is not available (missing in the input file).
const osmium::OSMObject* object = manager.get_member_object(member);
switch (member.type()) {
case osmium::item_type::node :
++nodes;
if (member.ref() != 0 && !object) {
++missing_nodes;
}
break;
case osmium::item_type::way :
++ways;
if (member.ref() != 0 && !object) {
++missing_ways;
}
break;
case osmium::item_type::relation :
++relations;
if (member.ref() != 0 && !object) {
++missing_relations;
}
break;
default:
break;
}
}
});
REQUIRE(nodes == 2);
REQUIRE(ways == 3);
REQUIRE(relations == 3);
REQUIRE(missing_nodes == 1);
REQUIRE(missing_ways == 1);
REQUIRE(missing_relations == 2);
}
| 31.365325 | 136 | 0.618202 | [
"object"
] |
f5d6957fcf661b61a2e906dc5c139aa7b4d258a8 | 10,734 | cc | C++ | rtc_base/criticalsection_unittest.cc | Aexyn/webrtc2 | daea5bf2deb843567a792f22ea2047a037e09d78 | [
"DOC",
"BSD-3-Clause"
] | 6 | 2020-03-18T08:21:45.000Z | 2021-02-06T14:37:57.000Z | rtc_base/criticalsection_unittest.cc | modulesio/webrtc | ea143e774b4c00a74b617f272f5a8f71169cf24e | [
"DOC",
"BSD-3-Clause"
] | 1 | 2017-10-11T23:38:42.000Z | 2017-10-11T23:38:42.000Z | rtc_base/criticalsection_unittest.cc | modulesio/webrtc | ea143e774b4c00a74b617f272f5a8f71169cf24e | [
"DOC",
"BSD-3-Clause"
] | 3 | 2018-07-23T04:52:42.000Z | 2021-12-18T07:37:15.000Z | /*
* Copyright 2014 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <memory>
#include <set>
#include <vector>
#include "rtc_base/arraysize.h"
#include "rtc_base/checks.h"
#include "rtc_base/criticalsection.h"
#include "rtc_base/event.h"
#include "rtc_base/gunit.h"
#include "rtc_base/platform_thread.h"
#include "rtc_base/thread.h"
namespace rtc {
namespace {
const int kLongTime = 10000; // 10 seconds
const int kNumThreads = 16;
const int kOperationsToRun = 1000;
class UniqueValueVerifier {
public:
void Verify(const std::vector<int>& values) {
for (size_t i = 0; i < values.size(); ++i) {
std::pair<std::set<int>::iterator, bool> result =
all_values_.insert(values[i]);
// Each value should only be taken by one thread, so if this value
// has already been added, something went wrong.
EXPECT_TRUE(result.second)
<< " Thread=" << Thread::Current() << " value=" << values[i];
}
}
void Finalize() {}
private:
std::set<int> all_values_;
};
class CompareAndSwapVerifier {
public:
CompareAndSwapVerifier() : zero_count_(0) {}
void Verify(const std::vector<int>& values) {
for (auto v : values) {
if (v == 0) {
EXPECT_EQ(0, zero_count_) << "Thread=" << Thread::Current();
++zero_count_;
} else {
EXPECT_EQ(1, v) << " Thread=" << Thread::Current();
}
}
}
void Finalize() {
EXPECT_EQ(1, zero_count_);
}
private:
int zero_count_;
};
class RunnerBase : public MessageHandler {
public:
explicit RunnerBase(int value)
: threads_active_(0),
start_event_(true, false),
done_event_(true, false),
shared_value_(value) {}
bool Run() {
// Signal all threads to start.
start_event_.Set();
// Wait for all threads to finish.
return done_event_.Wait(kLongTime);
}
void SetExpectedThreadCount(int count) {
threads_active_ = count;
}
int shared_value() const { return shared_value_; }
protected:
// Derived classes must override OnMessage, and call BeforeStart and AfterEnd
// at the beginning and the end of OnMessage respectively.
void BeforeStart() {
ASSERT_TRUE(start_event_.Wait(kLongTime));
}
// Returns true if all threads have finished.
bool AfterEnd() {
if (AtomicOps::Decrement(&threads_active_) == 0) {
done_event_.Set();
return true;
}
return false;
}
int threads_active_;
Event start_event_;
Event done_event_;
int shared_value_;
};
class RTC_LOCKABLE CriticalSectionLock {
public:
void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { cs_.Enter(); }
void Unlock() RTC_UNLOCK_FUNCTION() { cs_.Leave(); }
private:
CriticalSection cs_;
};
template <class Lock>
class LockRunner : public RunnerBase {
public:
LockRunner() : RunnerBase(0) {}
void OnMessage(Message* msg) override {
BeforeStart();
lock_.Lock();
EXPECT_EQ(0, shared_value_);
int old = shared_value_;
// Use a loop to increase the chance of race.
for (int i = 0; i < kOperationsToRun; ++i) {
++shared_value_;
}
EXPECT_EQ(old + kOperationsToRun, shared_value_);
shared_value_ = 0;
lock_.Unlock();
AfterEnd();
}
private:
Lock lock_;
};
template <class Op, class Verifier>
class AtomicOpRunner : public RunnerBase {
public:
explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {}
void OnMessage(Message* msg) override {
BeforeStart();
std::vector<int> values;
values.reserve(kOperationsToRun);
// Generate a bunch of values by updating shared_value_ atomically.
for (int i = 0; i < kOperationsToRun; ++i) {
values.push_back(Op::AtomicOp(&shared_value_));
}
{ // Add them all to the set.
CritScope cs(&all_values_crit_);
verifier_.Verify(values);
}
if (AfterEnd()) {
verifier_.Finalize();
}
}
private:
CriticalSection all_values_crit_;
Verifier verifier_;
};
struct IncrementOp {
static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
};
struct DecrementOp {
static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
};
struct CompareAndSwapOp {
static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); }
};
void StartThreads(std::vector<std::unique_ptr<Thread>>* threads,
MessageHandler* handler) {
for (int i = 0; i < kNumThreads; ++i) {
std::unique_ptr<Thread> thread(Thread::Create());
thread->Start();
thread->Post(RTC_FROM_HERE, handler);
threads->push_back(std::move(thread));
}
}
} // namespace
TEST(AtomicOpsTest, Simple) {
int value = 0;
EXPECT_EQ(1, AtomicOps::Increment(&value));
EXPECT_EQ(1, value);
EXPECT_EQ(2, AtomicOps::Increment(&value));
EXPECT_EQ(2, value);
EXPECT_EQ(1, AtomicOps::Decrement(&value));
EXPECT_EQ(1, value);
EXPECT_EQ(0, AtomicOps::Decrement(&value));
EXPECT_EQ(0, value);
}
TEST(AtomicOpsTest, SimplePtr) {
class Foo {};
Foo* volatile foo = nullptr;
std::unique_ptr<Foo> a(new Foo());
std::unique_ptr<Foo> b(new Foo());
// Reading the initial value should work as expected.
EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr);
// Setting using compare and swap should work.
EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
&foo, static_cast<Foo*>(nullptr), a.get()) == nullptr);
EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
// Setting another value but with the wrong previous pointer should fail
// (remain a).
EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
&foo, static_cast<Foo*>(nullptr), b.get()) == a.get());
EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
// Replacing a with b should work.
EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) ==
a.get());
EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get());
}
TEST(AtomicOpsTest, Increment) {
// Create and start lots of threads.
AtomicOpRunner<IncrementOp, UniqueValueVerifier> runner(0);
std::vector<std::unique_ptr<Thread>> threads;
StartThreads(&threads, &runner);
runner.SetExpectedThreadCount(kNumThreads);
// Release the hounds!
EXPECT_TRUE(runner.Run());
EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value());
}
TEST(AtomicOpsTest, Decrement) {
// Create and start lots of threads.
AtomicOpRunner<DecrementOp, UniqueValueVerifier> runner(
kOperationsToRun * kNumThreads);
std::vector<std::unique_ptr<Thread>> threads;
StartThreads(&threads, &runner);
runner.SetExpectedThreadCount(kNumThreads);
// Release the hounds!
EXPECT_TRUE(runner.Run());
EXPECT_EQ(0, runner.shared_value());
}
TEST(AtomicOpsTest, CompareAndSwap) {
// Create and start lots of threads.
AtomicOpRunner<CompareAndSwapOp, CompareAndSwapVerifier> runner(0);
std::vector<std::unique_ptr<Thread>> threads;
StartThreads(&threads, &runner);
runner.SetExpectedThreadCount(kNumThreads);
// Release the hounds!
EXPECT_TRUE(runner.Run());
EXPECT_EQ(1, runner.shared_value());
}
TEST(GlobalLockTest, Basic) {
// Create and start lots of threads.
LockRunner<GlobalLock> runner;
std::vector<std::unique_ptr<Thread>> threads;
StartThreads(&threads, &runner);
runner.SetExpectedThreadCount(kNumThreads);
// Release the hounds!
EXPECT_TRUE(runner.Run());
EXPECT_EQ(0, runner.shared_value());
}
TEST(CriticalSectionTest, Basic) {
// Create and start lots of threads.
LockRunner<CriticalSectionLock> runner;
std::vector<std::unique_ptr<Thread>> threads;
StartThreads(&threads, &runner);
runner.SetExpectedThreadCount(kNumThreads);
// Release the hounds!
EXPECT_TRUE(runner.Run());
EXPECT_EQ(0, runner.shared_value());
}
class PerfTestData {
public:
PerfTestData(int expected_count, Event* event)
: cache_line_barrier_1_(), cache_line_barrier_2_(),
expected_count_(expected_count), event_(event) {
cache_line_barrier_1_[0]++; // Avoid 'is not used'.
cache_line_barrier_2_[0]++; // Avoid 'is not used'.
}
~PerfTestData() {}
void AddToCounter(int add) {
rtc::CritScope cs(&lock_);
my_counter_ += add;
if (my_counter_ == expected_count_)
event_->Set();
}
int64_t total() const {
// Assume that only one thread is running now.
return my_counter_;
}
private:
uint8_t cache_line_barrier_1_[64];
CriticalSection lock_;
uint8_t cache_line_barrier_2_[64];
int64_t my_counter_ = 0;
const int expected_count_;
Event* const event_;
};
class PerfTestThread {
public:
PerfTestThread() : thread_(&ThreadFunc, this, "CsPerf") {}
void Start(PerfTestData* data, int repeats, int id) {
RTC_DCHECK(!thread_.IsRunning());
RTC_DCHECK(!data_);
data_ = data;
repeats_ = repeats;
my_id_ = id;
thread_.Start();
}
void Stop() {
RTC_DCHECK(thread_.IsRunning());
RTC_DCHECK(data_);
thread_.Stop();
repeats_ = 0;
data_ = nullptr;
my_id_ = 0;
}
private:
static bool ThreadFunc(void* param) {
PerfTestThread* me = static_cast<PerfTestThread*>(param);
for (int i = 0; i < me->repeats_; ++i)
me->data_->AddToCounter(me->my_id_);
return false;
}
PlatformThread thread_;
PerfTestData* data_ = nullptr;
int repeats_ = 0;
int my_id_ = 0;
};
// Comparison of output of this test as tested on a MacBook Pro Retina, 15-inch,
// Mid 2014, 2,8 GHz Intel Core i7, 16 GB 1600 MHz DDR3,
// running OS X El Capitan, 10.11.2.
//
// Native mutex implementation:
// Approximate CPU usage:
// System: ~16%
// User mode: ~1.3%
// Idle: ~82%
// Unit test output:
// [ OK ] CriticalSectionTest.Performance (234545 ms)
//
// Special partially spin lock based implementation:
// Approximate CPU usage:
// System: ~75%
// User mode: ~16%
// Idle: ~8%
// Unit test output:
// [ OK ] CriticalSectionTest.Performance (2107 ms)
//
// The test is disabled by default to avoid unecessarily loading the bots.
TEST(CriticalSectionTest, DISABLED_Performance) {
PerfTestThread threads[8];
Event event(false, false);
static const int kThreadRepeats = 10000000;
static const int kExpectedCount = kThreadRepeats * arraysize(threads);
PerfTestData test_data(kExpectedCount, &event);
for (auto& t : threads)
t.Start(&test_data, kThreadRepeats, 1);
event.Wait(Event::kForever);
for (auto& t : threads)
t.Stop();
}
} // namespace rtc
| 26.180488 | 80 | 0.677101 | [
"vector"
] |
f5df4bfa8358ea64c5d3d0299ea18e9c0251f33a | 8,698 | c++ | C++ | src/extern/inventor/apps/examples/Mentor/CXX/10.2.setEventCB.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/extern/inventor/apps/examples/Mentor/CXX/10.2.setEventCB.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/extern/inventor/apps/examples/Mentor/CXX/10.2.setEventCB.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*-------------------------------------------------------------
* This is an example from The Inventor Mentor
* chapter 10, example 2.
*
* This demonstrates using SoXtRenderArea::setEventCallback().
* which causes events to be sent directly to the application
* without being sent into the scene graph.
*
* Clicking the left mouse button and dragging will draw
* points in the xy plane beneath the mouse cursor.
* Clicking middle mouse and holding causes the point set
* to rotate about the Y axis.
* Clicking right mouse clears all points drawn so far out
* of the point set.
*-----------------------------------------------------------*/
#include <stdlib.h>
#include <X11/Intrinsic.h>
#include <Inventor/Sb.h>
#include <Inventor/Xt/SoXtRenderArea.h>
#include <Inventor/Xt/SoXt.h>
#include <Inventor/nodes/SoCamera.h>
#include <Inventor/nodes/SoCoordinate3.h>
#include <Inventor/nodes/SoGroup.h>
#include <Inventor/nodes/SoLightModel.h>
#include <Inventor/nodes/SoPerspectiveCamera.h>
#include <Inventor/nodes/SoPointSet.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/sensors/SoTimerSensor.h>
// Timer sensor
// Rotate 90 degrees every second, update 30 times a second
SoTimerSensor *myTicker;
#define UPDATE_RATE 1.0/30.0
#define ROTATION_ANGLE M_PI/60.0
void
myProjectPoint(SoXtRenderArea *myRenderArea,
int mousex, int mousey, SbVec3f &intersection)
{
// Take the x,y position of mouse, and normalize to [0,1].
// X windows have 0,0 at the upper left,
// Inventor expects 0,0 to be the lower left.
SbVec2s size = myRenderArea->getSize();
float x = float(mousex) / size[0];
float y = float(size[1] - mousey) / size[1];
// Get the camera and view volume
SoGroup *root = (SoGroup *) myRenderArea->getSceneGraph();
SoCamera *myCamera = (SoCamera *) root->getChild(0);
SbViewVolume myViewVolume;
myViewVolume = myCamera->getViewVolume();
// Project the mouse point to a line
SbVec3f p0, p1;
myViewVolume.projectPointToLine(SbVec2f(x,y), p0, p1);
// Midpoint of the line intersects a plane thru the origin
intersection = (p0 + p1) / 2.0;
}
void
myAddPoint(SoXtRenderArea *myRenderArea, const SbVec3f point)
{
SoGroup *root = (SoGroup *) myRenderArea->getSceneGraph();
SoCoordinate3 *coord = (SoCoordinate3 *) root->getChild(2);
SoPointSet *myPointSet = (SoPointSet *) root->getChild(3);
coord->point.set1Value(coord->point.getNum(), point);
myPointSet->numPoints.setValue(coord->point.getNum());
}
void
myClearPoints(SoXtRenderArea *myRenderArea)
{
SoGroup *root = (SoGroup *) myRenderArea->getSceneGraph();
SoCoordinate3 *coord = (SoCoordinate3 *) root->getChild(2);
SoPointSet *myPointSet = (SoPointSet *) root->getChild(3);
// Delete all values starting from 0
coord->point.deleteValues(0);
myPointSet->numPoints.setValue(0);
}
void
tickerCallback(void *userData, SoSensor *)
{
SoCamera *myCamera = (SoCamera *) userData;
SbRotation rot;
SbMatrix mtx;
SbVec3f pos;
// Adjust the position
pos = myCamera->position.getValue();
rot = SbRotation(SbVec3f(0,1,0), ROTATION_ANGLE);
mtx.setRotate(rot);
mtx.multVecMatrix(pos, pos);
myCamera->position.setValue(pos);
// Adjust the orientation
myCamera->orientation.setValue(
myCamera->orientation.getValue() * rot);
}
///////////////////////////////////////////////////////////////
// CODE FOR The Inventor Mentor STARTS HERE (part 1)
SbBool
myAppEventHandler(void *userData, XAnyEvent *anyevent)
{
SoXtRenderArea *myRenderArea = (SoXtRenderArea *) userData;
XButtonEvent *myButtonEvent;
XMotionEvent *myMotionEvent;
SbVec3f vec;
SbBool handled = TRUE;
switch (anyevent->type) {
case ButtonPress:
myButtonEvent = (XButtonEvent *) anyevent;
if (myButtonEvent->button == Button1) {
myProjectPoint(myRenderArea,
myButtonEvent->x, myButtonEvent->y, vec);
myAddPoint(myRenderArea, vec);
} else if (myButtonEvent->button == Button2) {
myTicker->schedule(); // start spinning the camera
} else if (myButtonEvent->button == Button3) {
myClearPoints(myRenderArea); // clear the point set
}
break;
case ButtonRelease:
myButtonEvent = (XButtonEvent *) anyevent;
if (myButtonEvent->button == Button2) {
myTicker->unschedule(); // stop spinning the camera
}
break;
case MotionNotify:
myMotionEvent = (XMotionEvent *) anyevent;
if (myMotionEvent->state & Button1Mask) {
myProjectPoint(myRenderArea,
myMotionEvent->x, myMotionEvent->y, vec);
myAddPoint(myRenderArea, vec);
}
break;
default:
handled = FALSE;
break;
}
return handled;
}
// CODE FOR The Inventor Mentor ENDS HERE
////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
// Print out usage instructions
printf("Mouse buttons:\n");
printf("\tLeft (with mouse motion): adds points\n");
printf("\tMiddle: rotates points about the Y axis\n");
printf("\tRight: deletes all the points\n");
// Initialize Inventor and Xt
Widget appWindow = SoXt::init(argv[0]);
if (appWindow == NULL) exit(1);
// Create and set up the root node
SoSeparator *root = new SoSeparator;
root->ref();
// Add a camera
SoPerspectiveCamera *myCamera = new SoPerspectiveCamera;
root->addChild(myCamera); // child 0
// Use the base color light model so we don't need to
// specify normals
SoLightModel *myLightModel = new SoLightModel;
myLightModel->model = SoLightModel::BASE_COLOR;
root->addChild(myLightModel); // child 1
// Set up the camera view volume
myCamera->position.setValue(0, 0, 4);
myCamera->nearDistance.setValue(1.0);
myCamera->farDistance.setValue(7.0);
myCamera->heightAngle.setValue(M_PI/3.0);
// Add a coordinate and point set
SoCoordinate3 *myCoord = new SoCoordinate3;
SoPointSet *myPointSet = new SoPointSet;
root->addChild(myCoord); // child 2
root->addChild(myPointSet); // child 3
// Timer sensor to tick off time while middle mouse is down
myTicker = new SoTimerSensor(tickerCallback, myCamera);
myTicker->setInterval(UPDATE_RATE);
// Create a render area for viewing the scene
SoXtRenderArea *myRenderArea = new SoXtRenderArea(appWindow);
myRenderArea->setSceneGraph(root);
myRenderArea->setTitle("My Event Handler");
//////////////////////////////////////////////////////////////
// CODE FOR The Inventor Mentor STARTS HERE (part 2)
// Have render area send events to us instead of the scene
// graph. We pass the render area as user data.
myRenderArea->setEventCallback(
myAppEventHandler, myRenderArea);
// CODE FOR The Inventor Mentor ENDS HERE
//////////////////////////////////////////////////////////////
// Show our application window, and loop forever...
myRenderArea->show();
SoXt::show(appWindow);
SoXt::mainLoop();
}
| 33.32567 | 77 | 0.656243 | [
"render",
"model"
] |
f5e0e246ae116174b90a43a1be093622fb4a58ad | 1,545 | hpp | C++ | include/transformation/treelikeString.hpp | knarloch/reflective | 0c0cdde8929719c0a42c8284dcfeae250578c95b | [
"MIT"
] | null | null | null | include/transformation/treelikeString.hpp | knarloch/reflective | 0c0cdde8929719c0a42c8284dcfeae250578c95b | [
"MIT"
] | null | null | null | include/transformation/treelikeString.hpp | knarloch/reflective | 0c0cdde8929719c0a42c8284dcfeae250578c95b | [
"MIT"
] | null | null | null | #ifndef REFLECTIVE_TREELIKESTRING_HPP
#define REFLECTIVE_TREELIKESTRING_HPP
#include "reflective.hpp"
#include <sstream>
namespace reflective {
struct ToTreelikeMultilineStringTransformation
{
std::string state;
ToTreelikeMultilineStringTransformation() = default;
template<typename ValueT>
explicit ToTreelikeMultilineStringTransformation(const ValueT& value)
{
std::stringstream ss;
ss << value;
state = move(ss).str();
}
static std::string addIndentation(std::string s)
{
s.insert(0 , 1u, '\n');
for (auto pos = 0; (pos = s.find('\n', pos)) < std::string::npos;) {
s.insert(pos+1 , 2u, ' ');
pos+=1;
}
return s;
}
template<typename MemberT>
void applyMember(MemberT&& member, ToTreelikeMultilineStringTransformation context)
{
std::stringstream ss;
ss << member.getMemberName() << ':' << addIndentation(move(context.state)) << '\n';
state.append(ss.str());
}
template<typename MemberT>
void applyMember(MemberT&& member, vector<ToTreelikeMultilineStringTransformation> contexts)
{
std::stringstream ss;
ss << member.getMemberName() << ':';
for (auto& context : contexts) {
ss << addIndentation(move(context.state)) << '\n';
}
state.append(ss.str());
}
};
template<typename Struct>
std::string
toTreelikeMultilineString(const Struct& s)
{
return ToTreelikeMultilineStringTransformation::addIndentation(move(forEachMember<ToTreelikeMultilineStringTransformation>(s).state));
}
}
#endif // REFLECTIVE_TREELIKESTRING_HPP
| 24.52381 | 136 | 0.698382 | [
"vector"
] |
f5e6228b9b421cd75763264756d61d4c4f94a38f | 34,338 | tcc | C++ | flens/lapack/ge/lsy.tcc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 98 | 2015-01-26T20:31:37.000Z | 2021-09-09T15:51:37.000Z | flens/lapack/ge/lsy.tcc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 16 | 2015-01-21T07:43:45.000Z | 2021-12-06T12:08:36.000Z | flens/lapack/ge/lsy.tcc | stip/FLENS | 80495fa97dda42a0acafc8f83fc9639ae36d2e10 | [
"BSD-3-Clause"
] | 31 | 2015-01-05T08:06:45.000Z | 2022-01-26T20:12:00.000Z | /*
* Copyright (c) 2012, Michael Lehn
*
* 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 the FLENS development group 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.
*/
/* Based on
*
SUBROUTINE DGELSY( M, N, NRHS, A, LDA, B, LDB, JPVT, RCOND, RANK,
$ WORK, LWORK, INFO )
SUBROUTINE ZGELSY( M, N, NRHS, A, LDA, B, LDB, JPVT, RCOND, RANK,
$ WORK, LWORK, RWORK, INFO )
*
* -- LAPACK driver routine (version 3.3.1) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* -- April 2011 --
*/
#ifndef FLENS_LAPACK_GE_LSY_TCC
#define FLENS_LAPACK_GE_LSY_TCC 1
#include <flens/blas/blas.h>
#include <flens/lapack/lapack.h>
namespace flens { namespace lapack {
//== generic lapack implementation =============================================
namespace generic {
//-- (ge)lsy [real variant] ----------------------------------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND,
typename RANK, typename VWORK>
void
lsy_impl(GeMatrix<MA> &A,
GeMatrix<MB> &B,
DenseVector<VJPIV> &jPiv,
RCOND rCond,
RANK &rank,
DenseVector<VWORK> &work)
{
using std::abs;
using flens::max;
using flens::min;
using LASCL::FullMatrix;
using LASCL::UpperTriangular;
typedef typename GeMatrix<MA>::ElementType ElementType;
typedef typename GeMatrix<MA>::IndexType IndexType;
const ElementType Zero(0), One(1);
const Underscore<IndexType> _;
const IndexType m = A.numRows();
const IndexType n = A.numCols();
const IndexType nRhs = B.numCols();
const IndexType mn = min(m, n);
//
// Figure out optimal block size
//
IndexType lWork = work.length();
IndexType lWorkMin;
IndexType lWorkOpt;
if (mn==0 || nRhs==0) {
lWorkMin = 1;
lWorkOpt = 1;
} else {
IndexType nb1 = ilaenv<ElementType>(1, "GEQRF", "", m, n);
IndexType nb2 = ilaenv<ElementType>(1, "GERQF", "", m, n);
IndexType nb3 = ilaenv<ElementType>(1, "ORMQR", "", m, n, nRhs);
IndexType nb4 = ilaenv<ElementType>(1, "ORMRQ", "", m, n, nRhs);
IndexType nb = max(nb1, nb2, nb3, nb4);
lWorkMin = mn + max(2*mn, n+1, mn+nRhs);
lWorkOpt = max(lWorkMin, mn+2*n+nb*(n+1), 2*mn+nb*nRhs);
}
if (lWork==0) {
work.resize(lWorkOpt);
lWork = work.length();
}
work(1) = lWorkOpt;
auto sMinWork = work(_(mn+1,2*mn));
auto sMaxWork = work(_(2*mn+1,3*mn));
//
// Quick return if possible
//
if (mn==0 || nRhs==0) {
rank = 0;
return;
}
//
// Get machine parameters
//
ElementType smallNum = lamch<ElementType>(SafeMin)
/ lamch<ElementType>(Precision);
ElementType bigNum = One / smallNum;
labad(smallNum, bigNum);
//
// Scale A, B if max entries outside range [SMLNUM,BIGNUM]
//
ElementType normA = lan(MaximumNorm, A);
IndexType scaleA = 0;
if (normA>Zero && normA<smallNum) {
//
// Scale matrix norm up to SMLNUM
//
lascl(FullMatrix, 0, 0, normA, smallNum, A);
scaleA = 1;
} else if (normA>bigNum) {
//
// Scale matrix norm down to BIGNUM
//
lascl(FullMatrix, 0, 0, normA, bigNum, A);
scaleA = 2;
} else if (normA==Zero) {
//
// Matrix all zero. Return zero solution.
//
B = Zero;
rank = 0;
work(1) = lWorkOpt;
return;
}
auto B_ = B(_(1,m),_);
ElementType normB = lan(MaximumNorm, B_);
IndexType scaleB = 0;
if (normB>Zero && normB<smallNum) {
//
// Scale matrix norm up to SMLNUM
//
lascl(FullMatrix, 0, 0, normB, smallNum, B_);
scaleB = 1;
} else if (normB>bigNum) {
//
// Scale matrix norm down to BIGNUM
//
lascl(FullMatrix, 0, 0, normB, bigNum, B_);
scaleB = 2;
}
//
// Compute QR factorization with column pivoting of A:
// A * P = Q * R
//
auto tau1 = work(_(1,mn));
auto qp3Work = work(_(mn+1,lWork));
qp3(A, jPiv, tau1, qp3Work);
//
// workspace: MN+2*N+NB*(N+1).
// Details of Householder rotations stored in WORK(1:MN).
//
// Determine RANK using incremental condition estimation
//
sMinWork(1) = One;
sMaxWork(1) = One;
ElementType sMax = abs(A(1,1));
ElementType sMin = sMax;
if (abs(A(1,1))==Zero) {
rank = 0;
B = Zero;
work(1) = lWorkOpt;
return;
} else {
rank = 1;
}
while (rank<mn) {
IndexType i = rank+1;
const auto sMinWork_ = sMinWork(_(1,rank));
const auto sMaxWork_ = sMaxWork(_(1,rank));
const auto A_i = A(_(1,rank),i);
ElementType sMinPr, sMaxPr, s1, s2, c1, c2;
laic1(LAIC1::Min, sMinWork_, sMin, A_i, A(i,i), sMinPr, s1, c1);
laic1(LAIC1::Max, sMaxWork_, sMax, A_i, A(i,i), sMaxPr, s2, c2);
if (sMaxPr*rCond<=sMinPr) {
for (IndexType i=1; i<=rank; ++i) {
sMinWork(i) *= s1;
sMaxWork(i) *= s2;
}
sMinWork(rank+1) = c1;
sMaxWork(rank+1) = c2;
sMin = sMinPr;
sMax = sMaxPr;
++rank;
} else {
break;
}
}
//
// workspace: 3*MN.
//
// Logically partition R = [ R11 R12 ]
// [ 0 R22 ]
// where R11 = R(1:RANK,1:RANK)
//
// [R11,R12] = [ T11, 0 ] * Y
//
auto tau2 = work(_(mn+1,mn+rank));
auto work_ = work(_(2*mn+1,lWork));
if (rank<n) {
auto A_ = A(_(1,rank),_);
tzrzf(A_, tau2, work_);
}
auto T11 = A(_(1,rank),_(1,rank)).upper();
//
// workspace: 2*MN.
// Details of Householder rotations stored in WORK(MN+1:2*MN)
//
// B(1:M,1:NRHS) := Q**T * B(1:M,1:NRHS)
//
ormqr(Left, Trans, A(_,_(1,mn)), tau1, B_, work_);
//
// workspace: 2*MN+NB*NRHS.
//
// B(1:RANK,1:NRHS) := inv(T11) * B(1:RANK,1:NRHS)
//
blas::sm(Left, NoTrans, One, T11, B(_(1,rank),_));
B(_(rank+1,n),_) = Zero;
//
// B(1:N,1:NRHS) := Y**T * B(1:N,1:NRHS)
//
if (rank<n) {
ormrz(Left, Trans, n-rank, A(_(1,rank),_), tau2, B(_(1,n),_), work_);
}
//
// workspace: 2*MN+NRHS.
//
// B(1:N,1:NRHS) := P * B(1:N,1:NRHS)
//
for (IndexType j=1; j<=nRhs; ++j) {
for (IndexType i=1; i<=n; ++i) {
work(jPiv(i)) = B(i,j);
}
B(_(1,n),j) = work(_(1,n));
}
//
// workspace: N
//
// Undo scaling
//
if (scaleA==1) {
lascl(FullMatrix, 0, 0, normA, smallNum, B(_(1,n),_));
lascl(UpperTriangular, 0, 0, smallNum, normA, A(_(1,rank),_(1,rank)));
} else if (scaleA==2) {
lascl(FullMatrix, 0, 0, normA, bigNum, B(_(1,n),_));
lascl(UpperTriangular, 0, 0, bigNum, normA, A(_(1,rank),_(1,rank)));
}
if (scaleB==1) {
lascl(FullMatrix, 0, 0, smallNum, normB, B(_(1,n),_));
} else if (scaleB==2) {
lascl(FullMatrix, 0, 0, bigNum, normB, B(_(1,n),_));
}
work(1) = lWorkOpt;
}
//-- (ge)lsy [complex variant] -------------------------------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND,
typename RANK, typename VWORK, typename VRWORK>
void
lsy_impl(GeMatrix<MA> &A,
GeMatrix<MB> &B,
DenseVector<VJPIV> &jPiv,
RCOND rCond,
RANK &rank,
DenseVector<VWORK> &work,
DenseVector<VRWORK> &rwork)
{
using std::abs;
using flens::max;
using flens::min;
using LASCL::FullMatrix;
using LASCL::UpperTriangular;
typedef typename GeMatrix<MA>::ElementType ElementType;
typedef typename ComplexTrait<ElementType>::PrimitiveType PrimitiveType;
typedef typename GeMatrix<MA>::IndexType IndexType;
const PrimitiveType Zero(0), One(1);
const Underscore<IndexType> _;
const IndexType m = A.numRows();
const IndexType n = A.numCols();
const IndexType nRhs = B.numCols();
const IndexType mn = min(m, n);
//
// Figure out optimal block size
//
IndexType lWork = work.length();
IndexType lWorkMin;
IndexType lWorkOpt;
if (mn==0 || nRhs==0) {
lWorkMin = 1;
lWorkOpt = 1;
} else {
IndexType nb1 = ilaenv<ElementType>(1, "GEQRF", "", m, n);
IndexType nb2 = ilaenv<ElementType>(1, "GERQF", "", m, n);
IndexType nb3 = ilaenv<ElementType>(1, "UNMQR", "", m, n, nRhs);
IndexType nb4 = ilaenv<ElementType>(1, "UNMRQ", "", m, n, nRhs);
IndexType nb = max(nb1, nb2, nb3, nb4);
lWorkMin = mn + max(2*mn, n+1, mn+nRhs);
lWorkOpt = max( 1, mn+2*n+nb*( n+1 ), 2*nb+nb*nRhs );
}
if (lWork==0) {
work.resize(lWorkOpt);
lWork = work.length();
}
work(1) = lWorkOpt;
auto sMinWork = work(_(mn+1,2*mn));
auto sMaxWork = work(_(2*mn+1,3*mn));
//
// Quick return if possible
//
if (mn==0 || nRhs==0) {
rank = 0;
return;
}
//
// Get machine parameters
//
PrimitiveType smallNum = lamch<PrimitiveType>(SafeMin)
/ lamch<PrimitiveType>(Precision);
PrimitiveType bigNum = One / smallNum;
labad(smallNum, bigNum);
//
// Scale A, B if max entries outside range [SMLNUM,BIGNUM]
//
PrimitiveType normA = lan(MaximumNorm, A);
IndexType scaleA = 0;
if (normA>Zero && normA<smallNum) {
//
// Scale matrix norm up to SMLNUM
//
lascl(FullMatrix, 0, 0, normA, smallNum, A);
scaleA = 1;
} else if (normA>bigNum) {
//
// Scale matrix norm down to BIGNUM
//
lascl(FullMatrix, 0, 0, normA, bigNum, A);
scaleA = 2;
} else if (normA==Zero) {
//
// Matrix all zero. Return zero solution.
//
B = Zero;
rank = 0;
work(1) = lWorkOpt;
return;
}
auto B_ = B(_(1,m),_);
PrimitiveType normB = lan(MaximumNorm, B_);
IndexType scaleB = 0;
if (normB>Zero && normB<smallNum) {
//
// Scale matrix norm up to SMLNUM
//
lascl(FullMatrix, 0, 0, normB, smallNum, B_);
scaleB = 1;
} else if (normB>bigNum) {
//
// Scale matrix norm down to BIGNUM
//
lascl(FullMatrix, 0, 0, normB, bigNum, B_);
scaleB = 2;
}
//
// Compute QR factorization with column pivoting of A:
// A * P = Q * R
//
auto tau1 = work(_(1,mn));
auto qp3Work = work(_(mn+1,lWork));
qp3(A, jPiv, tau1, qp3Work, rwork);
//
// workspace: MN+2*N+NB*(N+1).
// Details of Householder rotations stored in WORK(1:MN).
//
// Determine RANK using incremental condition estimation
//
sMinWork(1) = One;
sMaxWork(1) = One;
PrimitiveType sMax = abs(A(1,1));
PrimitiveType sMin = sMax;
if (abs(A(1,1))==Zero) {
rank = 0;
B = Zero;
work(1) = lWorkOpt;
return;
} else {
rank = 1;
}
while (rank<mn) {
IndexType i = rank+1;
const auto sMinWork_ = sMinWork(_(1,rank));
const auto sMaxWork_ = sMaxWork(_(1,rank));
const auto A_i = A(_(1,rank),i);
PrimitiveType sMinPr, sMaxPr;
ElementType s1, s2, c1, c2;
laic1(LAIC1::Min, sMinWork_, sMin, A_i, A(i,i), sMinPr, s1, c1);
laic1(LAIC1::Max, sMaxWork_, sMax, A_i, A(i,i), sMaxPr, s2, c2);
if (sMaxPr*rCond<=sMinPr) {
for (IndexType i=1; i<=rank; ++i) {
sMinWork(i) *= s1;
sMaxWork(i) *= s2;
}
sMinWork(rank+1) = c1;
sMaxWork(rank+1) = c2;
sMin = sMinPr;
sMax = sMaxPr;
++rank;
} else {
break;
}
}
//
// workspace: 3*MN.
//
// Logically partition R = [ R11 R12 ]
// [ 0 R22 ]
// where R11 = R(1:RANK,1:RANK)
//
// [R11,R12] = [ T11, 0 ] * Y
//
auto tau2 = work(_(mn+1,mn+rank));
auto work_ = work(_(2*mn+1,lWork));
if (rank<n) {
auto A_ = A(_(1,rank),_);
tzrzf(A_, tau2, work_);
}
auto T11 = A(_(1,rank),_(1,rank)).upper();
//
// workspace: 2*MN.
// Details of Householder rotations stored in WORK(MN+1:2*MN)
//
// B(1:M,1:NRHS) := Q**T * B(1:M,1:NRHS)
//
unmqr(Left, ConjTrans, A(_,_(1,mn)), tau1, B_, work_);
//
// workspace: 2*MN+NB*NRHS.
//
// B(1:RANK,1:NRHS) := inv(T11) * B(1:RANK,1:NRHS)
//
blas::sm(Left, NoTrans, One, T11, B(_(1,rank),_));
B(_(rank+1,n),_) = Zero;
//
// B(1:N,1:NRHS) := Y**H * B(1:N,1:NRHS)
//
if (rank<n) {
unmrz(Left, ConjTrans, n-rank,
A(_(1,rank),_), tau2, B(_(1,n),_),
work_);
}
//
// workspace: 2*MN+NRHS.
//
// B(1:N,1:NRHS) := P * B(1:N,1:NRHS)
//
for (IndexType j=1; j<=nRhs; ++j) {
for (IndexType i=1; i<=n; ++i) {
work(jPiv(i)) = B(i,j);
}
B(_(1,n),j) = work(_(1,n));
}
//
// workspace: N
//
// Undo scaling
//
if (scaleA==1) {
lascl(FullMatrix, 0, 0, normA, smallNum, B(_(1,n),_));
lascl(UpperTriangular, 0, 0, smallNum, normA, A(_(1,rank),_(1,rank)));
} else if (scaleA==2) {
lascl(FullMatrix, 0, 0, normA, bigNum, B(_(1,n),_));
lascl(UpperTriangular, 0, 0, bigNum, normA, A(_(1,rank),_(1,rank)));
}
if (scaleB==1) {
lascl(FullMatrix, 0, 0, smallNum, normB, B(_(1,n),_));
} else if (scaleB==2) {
lascl(FullMatrix, 0, 0, bigNum, normB, B(_(1,n),_));
}
work(1) = lWorkOpt;
}
} // namespace generic
//== interface for native lapack ===============================================
#ifdef USE_CXXLAPACK
namespace external {
//-- (ge)lsy [real variant] ----------------------------------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND,
typename RANK, typename VWORK>
void
lsy_impl(GeMatrix<MA> &A,
GeMatrix<MB> &B,
DenseVector<VJPIV> &jPiv,
RCOND rCond,
RANK &rank,
DenseVector<VWORK> &work)
{
typedef typename GeMatrix<MA>::ElementType ElementType;
typedef typename GeMatrix<MA>::IndexType IndexType;
if (work.length()==0) {
ElementType WORK;
IndexType LWORK = -1;
cxxlapack::gelsy<IndexType>(A.numRows(),
A.numCols(),
B.numCols(),
A.data(),
A.leadingDimension(),
B.data(),
B.leadingDimension(),
jPiv.data(),
rCond,
rank,
&WORK,
LWORK);
work.resize(IndexType(WORK));
}
cxxlapack::gelsy<IndexType>(A.numRows(),
A.numCols(),
B.numCols(),
A.data(),
A.leadingDimension(),
B.data(),
B.leadingDimension(),
jPiv.data(),
rCond,
rank,
work.data(),
work.length());
}
//-- (ge)lsy [complex variant] -------------------------------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND,
typename RANK, typename VWORK, typename VRWORK>
void
lsy_impl(GeMatrix<MA> &A,
GeMatrix<MB> &B,
DenseVector<VJPIV> &jPiv,
RCOND rCond,
RANK &rank,
DenseVector<VWORK> &work,
DenseVector<VRWORK> &rwork)
{
typedef typename GeMatrix<MA>::ElementType ElementType;
typedef typename GeMatrix<MA>::IndexType IndexType;
if (work.length()==0) {
ElementType WORK;
IndexType LWORK = -1;
cxxlapack::gelsy<IndexType>(A.numRows(),
A.numCols(),
B.numCols(),
A.data(),
A.leadingDimension(),
B.data(),
B.leadingDimension(),
jPiv.data(),
rCond,
rank,
&WORK,
LWORK,
rwork.data());
work.resize(IndexType(cxxblas::real(WORK)));
}
cxxlapack::gelsy<IndexType>(A.numRows(),
A.numCols(),
B.numCols(),
A.data(),
A.leadingDimension(),
B.data(),
B.leadingDimension(),
jPiv.data(),
rCond,
rank,
work.data(),
work.length(),
rwork.data());
}
} // namespace external
#endif // USE_CXXLAPACK
//== public interface ==========================================================
//-- (ge)lsy [real variant] ----------------------------------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND,
typename VWORK>
typename RestrictTo<IsRealGeMatrix<MA>::value
&& IsRealGeMatrix<MB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value
&& IsRealDenseVector<VWORK>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
MB &&B,
VJPIV &&jPiv,
RCOND rCond,
VWORK &&work)
{
using flens::max;
using std::min;
LAPACK_DEBUG_OUT("(ge)lsy [real]");
//
// Remove references from rvalue types
//
typedef typename RemoveRef<MA>::Type MatrixA;
typedef typename MatrixA::IndexType IndexType;
//
// Test the input parameters
//
const IndexType m = A.numRows();
const IndexType n = A.numCols();
const IndexType nRhs = B.numCols();
# ifndef NDEBUG
ASSERT(A.firstRow()==1);
ASSERT(A.firstCol()==1);
ASSERT(B.firstRow()==1);
ASSERT(B.firstCol()==1);
ASSERT(jPiv.firstIndex()==1);
ASSERT(work.firstIndex()==1);
ASSERT(B.numRows()==max(m,n));
ASSERT(jPiv.length()==0 || jPiv.length()==n);
# endif
if (work.length()>0) {
const IndexType mn = min(m, n);
const IndexType lWorkMin = mn + max(2*mn, n + 1, mn + nRhs);
ASSERT(work.length()>=lWorkMin);
FAKE_USE_NDEBUG(lWorkMin);
}
if (jPiv.length()==0) {
jPiv.resize(n, jPiv.firstIndex(), IndexType(0));
}
//
// Make copies of output arguments
//
# ifdef CHECK_CXXLAPACK
typedef typename RemoveRef<MB>::Type MatrixB;
typedef typename RemoveRef<VJPIV>::Type VectorJPiv;
typedef typename RemoveRef<VWORK>::Type VectorWork;
typename MatrixA::NoView A_org = A;
typename MatrixB::NoView B_org = B;
typename VectorJPiv::NoView jPiv_org = jPiv;
typename VectorWork::NoView work_org = work;
# endif
//
// Call implementation
//
IndexType rank;
LAPACK_SELECT::lsy_impl(A, B, jPiv, rCond, rank, work);
# ifdef CHECK_CXXLAPACK
//
// Make copies of results computed by the generic implementation
//
typename MatrixA::NoView A_generic = A;
typename MatrixB::NoView B_generic = B;
typename VectorJPiv::NoView jPiv_generic = jPiv;
IndexType rank_generic = rank;
typename VectorWork::NoView work_generic = work;
//
// restore output arguments
//
A = A_org;
B = B_org;
jPiv = jPiv_org;
rank = 0;
work = work_org;
//
// Compare generic results with results from the native implementation
//
external::lsy_impl(A, B, jPiv, rCond, rank, work);
bool failed = false;
if (! isIdentical(A_generic, A, "A_generic", "A")) {
std::cerr << "CXXLAPACK: A_generic = " << A_generic << std::endl;
std::cerr << "F77LAPACK: A = " << A << std::endl;
failed = true;
}
if (! isIdentical(B_generic, B, "B_generic", "B")) {
std::cerr << "CXXLAPACK: B_generic = " << B_generic << std::endl;
std::cerr << "F77LAPACK: B = " << B << std::endl;
failed = true;
}
if (! isIdentical(jPiv_generic, jPiv, "jPiv_generic", "jPiv")) {
std::cerr << "CXXLAPACK: jPiv_generic = " << jPiv_generic << std::endl;
std::cerr << "F77LAPACK: jPiv = " << jPiv << std::endl;
failed = true;
}
if (! isIdentical(rank_generic, rank, "rank_generic", "rank")) {
std::cerr << "CXXLAPACK: rank_generic = " << rank_generic << std::endl;
std::cerr << "F77LAPACK: rank = " << rank << std::endl;
failed = true;
}
if (! isIdentical(work_generic, work, "work_generic", "work")) {
std::cerr << "CXXLAPACK: work_generic = " << work_generic << std::endl;
std::cerr << "F77LAPACK: work = " << work << std::endl;
failed = true;
}
if (failed) {
std::cerr << "A.numRows() = " << A.numRows() << std::endl;
std::cerr << "A.numCols() = " << A.numCols() << std::endl;
std::cerr << "A = " << A << std::endl;
std::cerr << "rank_generic = " << rank_generic << std::endl;
std::cerr << "rank = " << rank << std::endl;
std::cerr << "error in: lsy.tcc" << std::endl;
ASSERT(0);
} else {
// std::cerr << "passed: lsy.tcc" << std::endl;
}
# endif
return rank;
}
//-- (ge)lsy [complex variant] -------------------------------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND,
typename VWORK, typename VRWORK>
typename RestrictTo<IsComplexGeMatrix<MA>::value
&& IsComplexGeMatrix<MB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value
&& IsComplexDenseVector<VWORK>::value
&& IsRealDenseVector<VRWORK>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
MB &&B,
VJPIV &&jPiv,
RCOND rCond,
VWORK &&work,
VRWORK &&rwork)
{
using flens::max;
using std::min;
LAPACK_DEBUG_OUT("(ge)lsy [real]");
//
// Remove references from rvalue types
//
typedef typename RemoveRef<MA>::Type MatrixA;
typedef typename MatrixA::IndexType IndexType;
//
// Test the input parameters
//
const IndexType m = A.numRows();
const IndexType n = A.numCols();
const IndexType nRhs = B.numCols();
# ifndef NDEBUG
ASSERT(A.firstRow()==1);
ASSERT(A.firstCol()==1);
ASSERT(B.firstRow()==1);
ASSERT(B.firstCol()==1);
ASSERT(jPiv.firstIndex()==1);
ASSERT(work.firstIndex()==1);
ASSERT(B.numRows()==max(m,n));
ASSERT(jPiv.length()==0 || jPiv.length()==n);
if (work.length()>0) {
const IndexType mn = min(m, n);
const IndexType lWorkMin = mn + max(2*mn, n + 1, mn + nRhs);
ASSERT(work.length()>=lWorkMin);
}
ASSERT(rwork.length()==0 || rwork.length()==2*n);
# endif
if (jPiv.length()==0) {
jPiv.resize(n, jPiv.firstIndex(), IndexType(0));
}
if (rwork.length()==0) {
rwork.resize(2*n);
}
//
// Make copies of output arguments
//
# ifdef CHECK_CXXLAPACK
typedef typename RemoveRef<MB>::Type MatrixB;
typedef typename RemoveRef<VJPIV>::Type VectorJPiv;
typedef typename RemoveRef<VWORK>::Type VectorWork;
typedef typename RemoveRef<VRWORK>::Type VectorRWork;
typename MatrixA::NoView A_org = A;
typename MatrixB::NoView B_org = B;
typename VectorJPiv::NoView jPiv_org = jPiv;
typename VectorWork::NoView work_org = work;
typename VectorRWork::NoView rwork_org = rwork;
# endif
//
// Call implementation
//
IndexType rank;
LAPACK_SELECT::lsy_impl(A, B, jPiv, rCond, rank, work, rwork);
# ifdef CHECK_CXXLAPACK
//
// Make copies of results computed by the generic implementation
//
typename MatrixA::NoView A_generic = A;
typename MatrixB::NoView B_generic = B;
typename VectorJPiv::NoView jPiv_generic = jPiv;
IndexType rank_generic = rank;
typename VectorWork::NoView work_generic = work;
typename VectorRWork::NoView rwork_generic = rwork;
//
// restore output arguments
//
A = A_org;
B = B_org;
jPiv = jPiv_org;
rank = 0;
work = work_org;
rwork = rwork_org;
//
// Compare generic results with results from the native implementation
//
external::lsy_impl(A, B, jPiv, rCond, rank, work, rwork);
bool failed = false;
if (! isIdentical(A_generic, A, "A_generic", "A")) {
std::cerr << "CXXLAPACK: A_generic = " << A_generic << std::endl;
std::cerr << "F77LAPACK: A = " << A << std::endl;
failed = true;
}
if (! isIdentical(B_generic, B, "B_generic", "B")) {
std::cerr << "CXXLAPACK: B_generic = " << B_generic << std::endl;
std::cerr << "F77LAPACK: B = " << B << std::endl;
failed = true;
}
if (! isIdentical(jPiv_generic, jPiv, "jPiv_generic", "jPiv")) {
std::cerr << "CXXLAPACK: jPiv_generic = " << jPiv_generic << std::endl;
std::cerr << "F77LAPACK: jPiv = " << jPiv << std::endl;
failed = true;
}
if (! isIdentical(rank_generic, rank, "rank_generic", "rank")) {
std::cerr << "CXXLAPACK: rank_generic = " << rank_generic << std::endl;
std::cerr << "F77LAPACK: rank = " << rank << std::endl;
failed = true;
}
if (! isIdentical(work_generic, work, "work_generic", "work")) {
std::cerr << "CXXLAPACK: work_generic = " << work_generic << std::endl;
std::cerr << "F77LAPACK: work = " << work << std::endl;
failed = true;
}
if (! isIdentical(rwork_generic, rwork, "rwork_generic", "rwork")) {
std::cerr << "CXXLAPACK: rwork_generic = " << rwork_generic
<< std::endl;
std::cerr << "F77LAPACK: rwork = " << rwork << std::endl;
failed = true;
}
if (failed) {
std::cerr << "A.numRows() = " << A.numRows() << std::endl;
std::cerr << "A.numCols() = " << A.numCols() << std::endl;
std::cerr << "A = " << A << std::endl;
std::cerr << "rank_generic = " << rank_generic << std::endl;
std::cerr << "rank = " << rank << std::endl;
std::cerr << "error in: lsy.tcc" << std::endl;
ASSERT(0);
} else {
// std::cerr << "passed: lsy.tcc" << std::endl;
}
# endif
return rank;
}
//-- (ge)lsy [real variant with temporary workspace] ---------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND>
typename RestrictTo<IsRealGeMatrix<MA>::value
&& IsRealGeMatrix<MB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
MB &&B,
VJPIV &&jPiv,
RCOND rCond)
{
typedef typename RemoveRef<MA>::Type::Vector WorkVector;
WorkVector work;
return lsy(A, B, jPiv, rCond);
}
//-- (ge)lsy [complex variant with temporary workspace] ------------------------
template <typename MA, typename MB, typename VJPIV, typename RCOND>
typename RestrictTo<IsComplexGeMatrix<MA>::value
&& IsComplexGeMatrix<MB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
MB &&B,
VJPIV &&jPiv,
RCOND rCond)
{
typedef typename RemoveRef<MA>::Type::Vector WorkVector;
typedef typename RemoveRef<MA>::Type::ElementType T;
typedef typename ComplexTrait<T>::PrimitiveType PT;
typedef DenseVector<Array<PT> > RealWorkVector;
WorkVector work;
RealWorkVector rwork;
return lsy(A, B, jPiv, rCond, work, rwork);
}
//== (ge)lsy variant if B is vector ============================================
//-- (ge)lsy [real variant] ----------------------------------------------------
template <typename MA, typename VB, typename VJPIV, typename RCOND,
typename VWORK>
typename RestrictTo<IsRealGeMatrix<MA>::value
&& IsRealDenseVector<VB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value
&& IsRealDenseVector<VWORK>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
VB &&b,
VJPIV &&jPiv,
RCOND rCond,
VWORK &&work)
{
//
// Remove references from rvalue types
//
typedef typename RemoveRef<MA>::Type MatrixA;
typedef typename RemoveRef<VB>::Type VectorB;
typedef typename VectorB::ElementType ElementType;
typedef typename VectorB::IndexType IndexType;
const IndexType n = b.length();
const StorageOrder order = MatrixA::Engine::order;
GeMatrix<FullStorageView<ElementType, order> > B(n, 1, b, n);
return lsy(A, B, jPiv, rCond, work);
}
//-- (ge)lsy [complex variant] -------------------------------------------------
template <typename MA, typename VB, typename VJPIV, typename RCOND,
typename VWORK, typename VRWORK>
typename RestrictTo<IsComplexGeMatrix<MA>::value
&& IsComplexDenseVector<VB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value
&& IsComplexDenseVector<VWORK>::value
&& IsRealDenseVector<VRWORK>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
VB &&b,
VJPIV &&jPiv,
RCOND rCond,
VWORK &&work,
VRWORK &&rwork)
{
//
// Remove references from rvalue types
//
typedef typename RemoveRef<MA>::Type MatrixA;
typedef typename RemoveRef<VB>::Type VectorB;
typedef typename VectorB::ElementType ElementType;
typedef typename VectorB::IndexType IndexType;
const IndexType n = b.length();
const StorageOrder order = MatrixA::Engine::order;
GeMatrix<FullStorageView<ElementType, order> > B(n, 1, b, n);
return lsy(A, B, jPiv, rCond, work, rwork);
}
//-- (ge)lsy [real variant with temporary workspace] ---------------------------
template <typename MA, typename VB, typename VJPIV, typename RCOND>
typename RestrictTo<IsRealGeMatrix<MA>::value
&& IsRealDenseVector<VB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
VB &&b,
VJPIV &&jPiv,
RCOND rCond)
{
typedef typename RemoveRef<MA>::Type::Vector WorkVector;
WorkVector work;
return lsy(A, b, jPiv, rCond, work);
}
//-- (ge)lsy [complex variant with temporary workspace] ------------------------
template <typename MA, typename VB, typename VJPIV, typename RCOND>
typename RestrictTo<IsComplexGeMatrix<MA>::value
&& IsComplexDenseVector<VB>::value
&& IsIntegerDenseVector<VJPIV>::value
&& IsReal<RCOND>::value,
typename RemoveRef<MA>::Type::IndexType>::Type
lsy(MA &&A,
VB &&b,
VJPIV &&jPiv,
RCOND rCond)
{
typedef typename RemoveRef<MA>::Type::Vector WorkVector;
typedef typename RemoveRef<MA>::Type::ElementType T;
typedef typename ComplexTrait<T>::PrimitiveType PT;
typedef DenseVector<Array<PT> > RealWorkVector;
WorkVector work;
RealWorkVector rwork;
return lsy(A, b, jPiv, rCond, work, rwork);
}
} } // namespace lapack, flens
#endif // FLENS_LAPACK_GE_LSY_TCC
| 30.280423 | 80 | 0.525831 | [
"vector"
] |
f5f1649d78f440a11cfc9d7c04e046a1aed35e6a | 11,447 | cpp | C++ | src/invariant/ConservationOfLumensTests.cpp | thanigaivel97/sellar-core | b6ae3ca418a19a3f10708f3cd2d26edb9d138c6b | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 3 | 2019-06-07T19:54:47.000Z | 2019-11-06T02:45:51.000Z | src/invariant/ConservationOfLumensTests.cpp | imMoHaNNaD/stellar-core | 8eb4171ce4b037b028d65f7a592b8dcb360e90ef | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 4 | 2018-10-16T13:19:32.000Z | 2019-01-07T10:41:03.000Z | src/invariant/ConservationOfLumensTests.cpp | imMoHaNNaD/stellar-core | 8eb4171ce4b037b028d65f7a592b8dcb360e90ef | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | 7 | 2018-11-05T17:54:50.000Z | 2019-02-27T09:18:12.000Z | // Copyright 2017 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "invariant/ConservationOfLumens.h"
#include "invariant/InvariantDoesNotHold.h"
#include "invariant/InvariantManager.h"
#include "invariant/InvariantTestUtils.h"
#include "lib/catch.hpp"
#include "main/Application.h"
#include "test/TestUtils.h"
#include "test/test.h"
#include <numeric>
#include <random>
#include <xdrpp/autocheck.h>
using namespace stellar;
using namespace stellar::InvariantTestUtils;
int64_t
getTotalBalance(std::vector<LedgerEntry> const& entries)
{
return std::accumulate(entries.begin(), entries.end(),
static_cast<int64_t>(0),
[](int64_t lhs, LedgerEntry const& rhs) {
return lhs + rhs.data.account().balance;
});
}
int64_t
getCoinsAboveReserve(std::vector<LedgerEntry> const& entries, Application& app)
{
return std::accumulate(entries.begin(), entries.end(),
static_cast<int64_t>(0),
[&app](int64_t lhs, LedgerEntry const& rhs) {
auto& lm = app.getLedgerManager();
auto& account = rhs.data.account();
return lhs + account.balance -
lm.getMinBalance(account.numSubEntries);
});
}
std::vector<LedgerEntry>
updateBalances(std::vector<LedgerEntry> entries, Application& app,
std::default_random_engine& gen, int64_t netChange)
{
int64_t initialCoins = getTotalBalance(entries);
int64_t pool = netChange + getCoinsAboveReserve(entries, app);
int64_t totalDelta = 0;
for (auto iter = entries.begin(); iter != entries.end(); ++iter)
{
auto& account = iter->data.account();
auto minBalance =
app.getLedgerManager().getMinBalance(account.numSubEntries);
pool -= account.balance - minBalance;
int64_t delta = 0;
if (iter + 1 != entries.end())
{
int64_t maxDecrease = minBalance - account.balance;
int64_t maxIncrease = pool;
REQUIRE(maxIncrease >= maxDecrease);
std::uniform_int_distribution<int64_t> dist(maxDecrease,
maxIncrease);
delta = dist(gen);
}
else
{
delta = netChange - totalDelta;
}
pool -= delta;
account.balance += delta;
totalDelta += delta;
REQUIRE(account.balance >= minBalance);
}
REQUIRE(totalDelta == netChange);
auto finalCoins = getTotalBalance(entries);
REQUIRE(initialCoins + netChange == finalCoins);
auto& lh = app.getLedgerManager().getCurrentLedgerHeader();
lh.totalCoins += netChange;
return entries;
}
std::vector<LedgerEntry>
updateBalances(std::vector<LedgerEntry> const& entries, Application& app,
std::default_random_engine& gen)
{
int64_t coinsAboveReserve = getCoinsAboveReserve(entries, app);
auto& lh = app.getLedgerManager().getCurrentLedgerHeader();
std::uniform_int_distribution<int64_t> dist(
lh.totalCoins - coinsAboveReserve, INT64_MAX);
int64_t newTotalCoins = dist(gen);
return updateBalances(entries, app, gen, newTotalCoins - lh.totalCoins);
}
std::vector<EntryFrame::pointer>
generateEntryFrames(std::vector<LedgerEntry> const& entries)
{
std::vector<EntryFrame::pointer> result;
std::transform(
entries.begin(), entries.end(), std::back_inserter(result),
[](LedgerEntry const& le) { return EntryFrame::FromXDR(le); });
return result;
}
UpdateList
generateUpdateList(std::vector<EntryFrame::pointer> const& current,
std::vector<EntryFrame::pointer> const& previous)
{
assert(current.size() == previous.size());
UpdateList updates;
std::transform(
current.begin(), current.end(), previous.begin(),
std::back_inserter(updates),
[](EntryFrame::pointer const& curr, EntryFrame::pointer const& prev) {
return UpdateList::value_type{curr, prev};
});
return updates;
}
TEST_CASE("Total coins change without inflation",
"[invariant][conservationoflumens]")
{
std::default_random_engine gen;
Config cfg = getTestConfig(0);
cfg.INVARIANT_CHECKS = {"ConservationOfLumens"};
std::uniform_int_distribution<int64_t> dist(0, INT64_MAX);
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
LedgerHeader lh(app->getLedgerManager().getCurrentLedgerHeader());
LedgerDelta ld(lh, app->getDatabase(), false);
ld.getHeader().totalCoins = dist(gen);
OperationResult res;
REQUIRE_THROWS_AS(
app->getInvariantManager().checkOnOperationApply({}, res, ld),
InvariantDoesNotHold);
}
TEST_CASE("Fee pool change without inflation",
"[invariant][conservationoflumens]")
{
std::default_random_engine gen;
Config cfg = getTestConfig(0);
cfg.INVARIANT_CHECKS = {"ConservationOfLumens"};
std::uniform_int_distribution<int64_t> dist(0, INT64_MAX);
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
LedgerHeader lh(app->getLedgerManager().getCurrentLedgerHeader());
LedgerDelta ld(lh, app->getDatabase(), false);
ld.getHeader().feePool = dist(gen);
OperationResult res;
REQUIRE_THROWS_AS(
app->getInvariantManager().checkOnOperationApply({}, res, ld),
InvariantDoesNotHold);
}
TEST_CASE("Account balances changed without inflation",
"[invariant][conservationoflumens]")
{
std::default_random_engine gen;
Config cfg = getTestConfig(0);
cfg.INVARIANT_CHECKS = {"ConservationOfLumens"};
uint32_t const N = 10;
for (uint32_t i = 0; i < 100; ++i)
{
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
std::vector<LedgerEntry> entries1;
std::generate_n(std::back_inserter(entries1), N,
std::bind(generateRandomAccount, 2));
entries1 = updateBalances(entries1, *app, gen);
{
UpdateList updates = generateUpdateList(
generateEntryFrames(entries1),
std::vector<EntryFrame::pointer>(entries1.size()));
REQUIRE(!store(*app, updates));
}
auto entries2 = updateBalances(entries1, *app, gen);
{
UpdateList updates = generateUpdateList(
generateEntryFrames(entries2), generateEntryFrames(entries1));
REQUIRE(!store(*app, updates));
}
{
UpdateList updates = generateUpdateList(
std::vector<EntryFrame::pointer>(entries1.size()),
generateEntryFrames(entries1));
REQUIRE(!store(*app, updates));
}
}
}
TEST_CASE("Account balances unchanged without inflation",
"[invariant][conservationoflumens]")
{
std::default_random_engine gen;
Config cfg = getTestConfig(0);
cfg.INVARIANT_CHECKS = {"ConservationOfLumens"};
uint32_t const N = 10;
for (uint32_t i = 0; i < 100; ++i)
{
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
std::vector<LedgerEntry> entries1;
std::generate_n(std::back_inserter(entries1), N,
std::bind(generateRandomAccount, 2));
entries1 = updateBalances(entries1, *app, gen);
{
UpdateList updates = generateUpdateList(
generateEntryFrames(entries1),
std::vector<EntryFrame::pointer>(entries1.size()));
REQUIRE(!store(*app, updates));
}
auto entries2 = updateBalances(entries1, *app, gen, 0);
{
UpdateList updates = generateUpdateList(
generateEntryFrames(entries2), generateEntryFrames(entries1));
REQUIRE(store(*app, updates));
}
auto keepEnd = entries2.begin() + N / 2;
std::vector<LedgerEntry> entries3(entries2.begin(), keepEnd);
std::vector<LedgerEntry> toDelete(keepEnd, entries2.end());
int64_t balanceToDelete = getTotalBalance(toDelete);
entries3 = updateBalances(entries3, *app, gen, balanceToDelete);
{
auto entryFrames3 = generateEntryFrames(entries3);
std::fill_n(std::back_inserter(entryFrames3), toDelete.size(),
nullptr);
UpdateList updates =
generateUpdateList(entryFrames3, generateEntryFrames(entries2));
REQUIRE(store(*app, updates));
}
}
}
TEST_CASE("Inflation changes are consistent",
"[invariant][conservationoflumens]")
{
std::default_random_engine gen;
Config cfg = getTestConfig(0);
cfg.INVARIANT_CHECKS = {"ConservationOfLumens"};
std::uniform_int_distribution<uint32_t> payoutsDist(1, 100);
std::uniform_int_distribution<int64_t> amountDist(1, 100000);
uint32_t const N = 10;
for (uint32_t i = 0; i < 100; ++i)
{
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
std::vector<LedgerEntry> entries1;
std::generate_n(std::back_inserter(entries1), N,
std::bind(generateRandomAccount, 2));
entries1 = updateBalances(entries1, *app, gen);
{
UpdateList updates = generateUpdateList(
generateEntryFrames(entries1),
std::vector<EntryFrame::pointer>(entries1.size()));
REQUIRE(!store(*app, updates));
}
OperationResult opRes;
opRes.tr().type(INFLATION);
opRes.tr().inflationResult().code(INFLATION_SUCCESS);
int64_t inflationAmount = 0;
auto& payouts = opRes.tr().inflationResult().payouts();
std::generate_n(std::back_inserter(payouts), payoutsDist(gen),
[&gen, &amountDist, &inflationAmount]() {
InflationPayout ip;
ip.amount = amountDist(gen);
inflationAmount += ip.amount;
return ip;
});
std::uniform_int_distribution<int64_t> deltaFeePoolDist(
0, 2 * inflationAmount);
auto deltaFeePool = deltaFeePoolDist(gen);
LedgerHeader lh(app->getLedgerManager().getCurrentLedgerHeader());
LedgerDelta ld(lh, app->getDatabase(), false);
ld.getHeader().feePool += deltaFeePool;
REQUIRE_THROWS_AS(
app->getInvariantManager().checkOnOperationApply({}, opRes, ld),
InvariantDoesNotHold);
ld.getHeader().totalCoins += deltaFeePool + inflationAmount;
REQUIRE_THROWS_AS(
app->getInvariantManager().checkOnOperationApply({}, opRes, ld),
InvariantDoesNotHold);
auto entries2 = updateBalances(entries1, *app, gen, inflationAmount);
{
UpdateList updates = generateUpdateList(
generateEntryFrames(entries2), generateEntryFrames(entries1));
REQUIRE(store(*app, updates, &ld, &opRes));
}
}
}
| 36.224684 | 80 | 0.620512 | [
"vector",
"transform"
] |
f5f6d9bddf6f7e741e95f28a42ad6b65d2625527 | 1,533 | cpp | C++ | test/yosupo/scc.test.cpp | satashun/algorithm | ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4 | [
"MIT"
] | null | null | null | test/yosupo/scc.test.cpp | satashun/algorithm | ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4 | [
"MIT"
] | 4 | 2020-04-07T16:11:30.000Z | 2021-02-23T23:26:03.000Z | test/yosupo/scc.test.cpp | satashun/algorithm | ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4 | [
"MIT"
] | null | null | null | #define PROBLEM "https://judge.yosupo.jp/problem/scc"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
template<class T> using V = vector<T>;
template<class T> using VV = V<V<T>>;
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define ALL(c) (c).begin(),(c).end()
#ifdef LOCAL
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define dump(x) true
#endif
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n-1); }
template<class T, class U> void chmin(T& t, const U& u) { if (t > u) t = u; }
template<class T, class U> void chmax(T& t, const U& u) { if (t < u) t = u; }
template<class T, class U>
ostream& operator<<(ostream& os, const pair<T, U>& p) {
os<<"("<<p.first<<","<<p.second<<")";
return os;
}
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os<<"{";
rep(i, v.size()) {
if (i) os<<",";
os<<v[i];
}
os<<"}";
return os;
}
#define call_from_test
#include "../../cpp_src/graph/SCC.hpp"
#undef call_from_test
int main() {
int N, M; scanf("%d %d", &N, &M);
SCC scc(N);
rep(i, M) {
int a, b;
scanf("%d %d", &a, &b);
scc.add_edge(a, b);
}
auto v = scc.calc();
printf("%d\n", v.size());
rep(i, v.size()) {
auto &vec = v[i];
int sz = vec.size();
printf("%d", sz);
for (int j = 0; j < vec.size(); ++j) {
printf(" %d", vec[j]);
}
puts("");
}
return 0;
} | 21.291667 | 77 | 0.569472 | [
"vector"
] |
f5f960864c5325613c1b708c61cf50672ceda7b1 | 2,637 | cpp | C++ | examples/circuits/circuit_builder.cpp | jonesmz/longeronpp | 48a2eeee071376b7ed995a5668bebe56a1d73a82 | [
"MIT"
] | 19 | 2022-02-21T22:13:39.000Z | 2022-03-06T22:39:35.000Z | examples/circuits/circuit_builder.cpp | jonesmz/longeronpp | 48a2eeee071376b7ed995a5668bebe56a1d73a82 | [
"MIT"
] | 6 | 2022-01-10T02:32:21.000Z | 2022-03-09T23:53:50.000Z | examples/circuits/circuit_builder.cpp | jonesmz/longeronpp | 48a2eeee071376b7ed995a5668bebe56a1d73a82 | [
"MIT"
] | 2 | 2022-01-10T02:34:03.000Z | 2022-02-22T08:08:55.000Z | /**
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: 2022 Neal Nicdao <chrisnicdao0@gmail.com>
*/
#include "circuit_builder.hpp"
namespace circuits
{
ElementId gate_combinatinal(CombinationalGates::GateDesc desc, std::initializer_list<NodeId> in, NodeId out)
{
Nodes *pNodes = WipNodes<ELogic>::smt_pNodes;
LGRN_ASSERTM(pNodes != nullptr, "No logic nodes in construction");
LGRN_ASSERTM(t_wipElements != nullptr, "No elements in construction");
LGRN_ASSERTM(t_wipGates != nullptr, "No elements in construction");
PerElemType &rPerType = t_wipElements->m_perType[gc_elemGate];
// Create Element Id and Local Id
ElementId const elemId = t_wipElements->m_ids.create();
ElemLocalId const localId = rPerType.m_localIds.create();
// Assign Type and Local ID
rPerType.m_localToElem[localId] = elemId;
t_wipElements->m_elemTypes[elemId] = gc_elemGate;
t_wipElements->m_elemToLocal[elemId] = localId;
// Assign gate description
t_wipGates->m_localGates[localId] = desc;
NodeId *pData = pNodes->m_elemConnect.emplace(elemId, in.size() + 1);
pData[0] = out; // Port 0 is output
std::copy(std::begin(in), std::end(in), pData + 1); // the rest are inputs
return elemId;
}
void populate_pub_sub(Elements const& elements, Nodes &rNodes)
{
std::vector<int> nodeSubCount(rNodes.m_nodeIds.capacity(), 0); // can we reach 1 million subscribers?
for (ElementId elem : elements.m_ids.bitview().zeros())
{
auto nodes = rNodes.m_elemConnect[elem];
// skip first, port 0 is the publisher
for (auto it = nodes.begin() + 1; it != nodes.end(); ++it)
{
nodeSubCount[*it] ++;
}
}
// reserve subscriber partitions
for (NodeId node : rNodes.m_nodeIds.bitview().zeros())
{
rNodes.m_nodeSubscribers.emplace(node, nodeSubCount[node]);
}
// assign publishers and subscribers
for (ElementId elem : elements.m_ids.bitview().zeros())
{
auto nodes = rNodes.m_elemConnect[elem];
for (auto it = nodes.begin() + 1; it != nodes.end(); ++it)
{
// A bit hacky, but now using subscriber counts to keep track of how
// many subscribers had currently been added
int &rSubCount = nodeSubCount[*it];
rSubCount --;
ElemTypeId const type = elements.m_elemTypes[elem];
ElemLocalId const local = elements.m_elemToLocal[elem];
rNodes.m_nodeSubscribers[*it][rSubCount] = {local, type};
}
// assign publisher
rNodes.m_nodePublisher[nodes[0]] = elem;
}
}
}
| 32.9625 | 108 | 0.653394 | [
"vector"
] |
f5fb1dc44be844c04bfbd2d5aabbc99d7c740f1c | 6,243 | cpp | C++ | probot_grasping/src/vision_manager.cpp | ZJUBinPicking/ZJUBinPicking | a38b729f61c796ca4584cd3a8ca494443f870407 | [
"Apache-2.0"
] | 13 | 2020-04-25T13:56:39.000Z | 2022-01-20T09:07:59.000Z | probot_grasping/src/vision_manager.cpp | ZJUBinPicking/ZJUBinPicking | a38b729f61c796ca4584cd3a8ca494443f870407 | [
"Apache-2.0"
] | null | null | null | probot_grasping/src/vision_manager.cpp | ZJUBinPicking/ZJUBinPicking | a38b729f61c796ca4584cd3a8ca494443f870407 | [
"Apache-2.0"
] | 1 | 2021-09-28T15:54:12.000Z | 2021-09-28T15:54:12.000Z | /***********************************************************************
Copyright 2019 Wuhan PS-Micro Technology Co., Itd.
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 "probot_grasping/vision_manager.h"
VisionManager::VisionManager(float length, float breadth)
{
this->table_length = length;
this->table_breadth = breadth;
}
void VisionManager::get2DLocation(cv::Mat img, float &x, float &y)
{
this->curr_img = img;
img_centre_x_ = img.rows / 2;
img_centre_y_ = img.cols / 2;
cv::Rect tablePos;
detectTable(tablePos);
detect2DObject(x, y, tablePos);
convertToMM(x, y);
}
void VisionManager::detectTable(cv::Rect &tablePos)
{
// Extract Table from the image and assign values to pixel_per_mm fields
cv::Mat BGR[3];
cv::Mat image = curr_img.clone();
split(image, BGR);
cv::Mat gray_image_red = BGR[2];
cv::Mat gray_image_green = BGR[1];
cv::Mat denoiseImage;
cv::medianBlur(gray_image_red, denoiseImage, 3);
// Threshold the Image
cv::Mat binaryImage = denoiseImage;
for (int i = 0; i < binaryImage.rows; i++)
{
for (int j = 0; j < binaryImage.cols; j++)
{
int editValue = binaryImage.at<uchar>(i, j);
int editValue2 = gray_image_green.at<uchar>(i, j);
if ((editValue >= 0) && (editValue < 20) && (editValue2 >= 0) && (editValue2 < 20))
{ // check whether value is within range.
binaryImage.at<uchar>(i, j) = 255;
}
else
{
binaryImage.at<uchar>(i, j) = 0;
}
}
}
dilate(binaryImage, binaryImage, cv::Mat());
// Get the centroid of the of the blob
std::vector<cv::Point> nonZeroPoints;
cv::findNonZero(binaryImage, nonZeroPoints);
cv::Rect bbox = cv::boundingRect(nonZeroPoints);
cv::Point pt;
pt.x = bbox.x + bbox.width / 2;
pt.y = bbox.y + bbox.height / 2;
cv::circle(image, pt, 2, cv::Scalar(0, 0, 255), -1, 8);
// Update pixels_per_mm fields
pixels_permm_y = bbox.height / table_length;
pixels_permm_x = bbox.width / table_breadth;
tablePos = bbox;
// Test the conversion values
std::cout << "Pixels in y" << pixels_permm_y << std::endl;
std::cout << "Pixels in x" << pixels_permm_x << std::endl;
// Draw Contours - For Debugging
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(binaryImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
for (int i = 0; i < contours.size(); i++)
{
cv::Scalar color = cv::Scalar(255, 0, 0);
cv::drawContours(image, contours, i, color, 1, 8, hierarchy, 0, cv::Point());
}
// cv::namedWindow("Table Detection", cv::WINDOW_AUTOSIZE);
// cv::imshow("Table Detection", image);
// cv::waitKey(100);
}
void VisionManager::detect2DObject(float &pixel_x, float &pixel_y, cv::Rect &tablePos)
{
// Implement Color Thresholding and contour findings to get the location of object to be grasped in 2D
cv::Mat image, gray_image_green;
cv::Mat BGR[3];
image = curr_img.clone();
cv::split(image, BGR);
gray_image_green = BGR[1];
// Denoise the Image
cv::Mat denoiseImage;
cv::medianBlur(gray_image_green, denoiseImage, 3);
// Threshold the Image
cv::Mat binaryImage = denoiseImage;
for (int i = 0; i < binaryImage.rows; i++)
{
for (int j = 0; j < binaryImage.cols; j++)
{
if((j<tablePos.x+3) || j>(tablePos.x+tablePos.width-3) || (i<tablePos.y+3) || i>(tablePos.y + tablePos.height-3))
{
binaryImage.at<uchar>(i, j) = 0;
}
else
{
int editValue = binaryImage.at<uchar>(i, j);
if ((editValue > 100) && (editValue <= 255))
{ // check whether value is within range.
binaryImage.at<uchar>(i, j) = 255;
}
else
{
binaryImage.at<uchar>(i, j) = 0;
}
}
}
}
dilate(binaryImage, binaryImage, cv::Mat());
// Get the centroid of the of the blob
std::vector<cv::Point> nonZeroPoints;
cv::findNonZero(binaryImage, nonZeroPoints);
cv::Rect bbox = cv::boundingRect(nonZeroPoints);
cv::Point pt;
pixel_x = bbox.x + bbox.width / 2;
pixel_y = bbox.y + bbox.height / 2;
// Test the conversion values
std::cout << "pixel_x" << pixel_x << std::endl;
std::cout << "pixel_y" << pixel_y << std::endl;
// For Drawing
pt.x = bbox.x + bbox.width / 2;
pt.y = bbox.y + bbox.height / 2;
cv::circle(image, pt, 2, cv::Scalar(0, 0, 255), -1, 8);
// Draw Contours
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(binaryImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
for (int i = 0; i < contours.size(); i++)
{
cv::Scalar color = cv::Scalar(255, 0, 0);
cv::drawContours(image, contours, i, color, 1, 8, hierarchy, 0, cv::Point());
}
// cv::namedWindow("Centre point", cv::WINDOW_AUTOSIZE);
// cv::imshow("Centre point", image);
// cv::waitKey(100);
}
void VisionManager::convertToMM(float &x, float &y)
{
// Convert from pixel to world co-ordinates in the camera frame
x = (x - img_centre_x_) / pixels_permm_x;
y = (y - img_centre_y_) / pixels_permm_y;
}
// Temporary Main Function for testing- This should go away later
// int main(int argc, char** argv ) {
// if ( argc != 2 )
// {
// printf("usage: VisionManager <Image_Path>\n");
// return -1;
// }
// cv::Mat image;
// image = cv::imread( argv[1], 1 );
// if ( !image.data )
// {
// printf("No image data \n");
// return -1;
// }
// float length = 0.3;
// float breadth = 0.3;
// float obj_x, obj_y;
// VisionManager vm(length, breadth);
// vm.get2DLocation(image, obj_x, obj_y);
// std::cout<< " X-Co-ordinate in Camera Frame :" << obj_x << std::endl;
// std::cout<< " Y-Co-ordinate in Camera Frame :" << obj_y << std::endl;
// cv::waitKey(0);
// }
| 29.037209 | 116 | 0.637834 | [
"object",
"vector"
] |
eb03ea3b0fc6eea4d7152da734668022fea21353 | 3,167 | cpp | C++ | apps/dlg_sQ1/sQ1App.cpp | luodalei/sq1_windows | 0e71405fadd25cf2d34c1db4ed353a9e0baa6bcc | [
"Apache-2.0"
] | 2 | 2019-08-27T14:10:21.000Z | 2019-08-27T14:10:24.000Z | apps/dlg_sQ1/sQ1App.cpp | luodalei/sq1_windows | 0e71405fadd25cf2d34c1db4ed353a9e0baa6bcc | [
"Apache-2.0"
] | null | null | null | apps/dlg_sQ1/sQ1App.cpp | luodalei/sq1_windows | 0e71405fadd25cf2d34c1db4ed353a9e0baa6bcc | [
"Apache-2.0"
] | 1 | 2019-08-27T14:10:03.000Z | 2019-08-27T14:10:03.000Z |
#include <wx/menu.h>
#include <wx/cmdline.h>
#include <wx/treectrl.h>
#include <wx/aui/framemanager.h>
#include "sQ1App.h"
#include "sQ1MainFrame.h"
#include "sQ1Resource.h"
#include "sQ1CANImpl.h"
#include "canopenAPI.h"
USING_NAMESPACE_SQ1
static const wxCmdLineEntryDesc g_cmdLineDesc [] =
{
{ wxCMD_LINE_SWITCH, "h", "help", "displays help on the command line parameters",
wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
/*{ wxCMD_LINE_OPTION, "port", "port", "port number",
wxCMD_LINE_VAL_NUMBER, wxCMD_LINE_PARAM_OPTIONAL},*/
{ wxCMD_LINE_NONE }
};
/////////////////////////////////////////////////////////////////////////////
//
IMPLEMENT_APP(sQ1App)
BEGIN_EVENT_TABLE(sQ1App, wxApp)
EVT_MENU(wxID_NEW, sQ1App::OnFileNew)
EVT_MENU(wxID_OPEN, sQ1App::OnFileOpen)
END_EVENT_TABLE()
sQ1App::sQ1App()
: wxApp()
{
}
sQ1App::~sQ1App()
{
sq1::DriveOff();
sq1::CloseCAN();
}
bool sQ1App::OnInit()
{
sq1::InitVariables();
// open CAN channel:
if (!sq1::OpenCAN())
return false;
sq1::DriveReset();
sq1::DriveInit();
wxInitAllImageHandlers();
int width = 285;
int height = 540;
MainFrame *pFrame = new MainFrame(wxT("sQ1 Control Panel"), width, height);
wxCmdLineParser parser(argc, argv);
OnInitCmdLine(parser);
parser.Parse();
OnCmdLineParsed(parser);
pFrame->Show(true);
SetTopWindow(pFrame);
Connect( wxID_ANY, wxEVT_IDLE, wxIdleEventHandler(sQ1App::OnIdle) );
return true;
};
void sQ1App::OnIdle(wxIdleEvent& evt)
{
static int sync_counter = 0;
sync_counter++;
if (sync_counter == 1) {
for (int ch = 0; ch < (int)CAN_Ch_COUNT; ch++)
{
if (!CAN_Ch_Enabled[ch]) continue;
for (int node = 0; node < (int)NODE_COUNT; node++)
{
if (!NODE_Enabled[ch][node]) continue;
if (GetHomingDone() == HOMING_DONE &&
(statusWord[ch][node]&0x1000) != 0 &&
(controlWord[ch][node]&0x0010) != 0) { // when "Set new point" bit is set...
controlWord[ch][node] &= 0xDF8F; // masking irrelevant bits
controlWord[ch][node] |= 0x0000; // clear all operation mode specific bits
}
can_pdo_rx1(CAN_Ch[ch], JointNodeID[ch][node], targetPosition[ch][node], targetVelocity[ch][node]);
can_pdo_rx3(CAN_Ch[ch], JointNodeID[ch][node], controlWord[ch][node], modeOfOperation);
}
}
for (int ch = 0; ch < (int)CAN_Ch_COUNT; ch++)
{
if (!CAN_Ch_Enabled[ch]) continue;
can_sync(CAN_Ch[ch]);
}
sync_counter = 0;
}
Sleep(5);
for (int ch = 0; ch < (int)CAN_Ch_COUNT; ch++)
{
if (!CAN_Ch_Enabled[ch]) continue;
ProcessCANMessage(ch);
}
evt.RequestMore(); // render continuously, not only once on idle
}
void sQ1App::OnFileNew(wxCommandEvent &event)
{
}
void sQ1App::OnFileOpen(wxCommandEvent &event)
{
wxFileDialog* dlg = new wxFileDialog(NULL);
if (wxID_OK != dlg->ShowModal() ) {
dlg->Destroy();
return;
}
wxString path = dlg->GetPath();
dlg->Destroy();
}
void sQ1App::OnInitCmdLine(wxCmdLineParser &parser)
{
parser.SetDesc(g_cmdLineDesc);
parser.SetSwitchChars(wxT("-"));
}
bool sQ1App::OnCmdLineParsed(wxCmdLineParser &parser)
{
//long port = 5150;
//if (parser.Found(wxT("port"), &port)) {
//}
return true;
}
| 20.432258 | 103 | 0.656457 | [
"render"
] |
eb07f637869c7793db3c17d58439a51afd13b82f | 15,791 | hpp | C++ | src/beast/examples/http_stream.hpp | gcbpay/R9Ripple | 98f878cf10a32e26021b6a6ed44990bccbbc92c2 | [
"BSL-1.0"
] | 2 | 2017-06-09T10:56:26.000Z | 2021-05-28T12:58:33.000Z | examples/http_stream.hpp | somayeghahari/beast | 999e2fa0318b5982736d3ea01a418770ea802671 | [
"BSL-1.0"
] | 1 | 2016-06-22T17:13:44.000Z | 2016-06-22T17:13:44.000Z | examples/http_stream.hpp | somayeghahari/beast | 999e2fa0318b5982736d3ea01a418770ea802671 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under 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)
//
#ifndef BEAST_HTTP_STREAM_H_INCLUDED
#define BEAST_HTTP_STREAM_H_INCLUDED
#include <beast/core/async_completion.hpp>
#include <beast/core/basic_streambuf.hpp>
#include <beast/http.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/intrusive/list.hpp>
#include <memory>
namespace beast {
namespace http {
namespace detail {
class stream_base
{
protected:
struct op
: boost::intrusive::list_base_hook<
boost::intrusive::link_mode<
boost::intrusive::normal_link>>
{
virtual ~op() = default;
virtual void operator()() = 0;
virtual void cancel() = 0;
};
using op_list = typename boost::intrusive::make_list<
op, boost::intrusive::constant_time_size<false>>::type;
op_list wr_q_;
bool wr_active_ = false;
};
} // detail
/** Provides message-oriented functionality using HTTP.
The stream class template provides asynchronous and blocking
message-oriented functionality necessary for clients and servers
to utilize the HTTP protocol.
@par Thread Safety
@e Distinct @e objects: Safe.@n
@e Shared @e objects: Unsafe. The application must ensure that
all asynchronous operations are performed within the same
implicit or explicit strand.
@par Example
To use the class template with an `ip::tcp::socket`, you would write:
@code
http::stream<ip::tcp::socket> hs(io_service);
@endcode
Alternatively, you can write:
@code
ip::tcp::socket sock(io_service);
http::stream<ip::tcp::socket&> hs(sock);
@endcode
@note A stream object must not be destroyed while there are
pending asynchronous operations associated with it.
@par Concepts
AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
*/
template<class NextLayer,
class Allocator = std::allocator<char>>
class stream : public detail::stream_base
{
NextLayer next_layer_;
basic_streambuf<Allocator> rd_buf_;
public:
/// The type of the next layer.
using next_layer_type =
typename std::remove_reference<NextLayer>::type;
/// The type of the lowest layer.
using lowest_layer_type =
typename next_layer_type::lowest_layer_type;
/// The type of endpoint of the lowest layer.
using endpoint_type =
typename lowest_layer_type::endpoint_type;
/// The protocol of the next layer.
using protocol_type =
typename lowest_layer_type::protocol_type;
/// The type of resolver of the next layer.
using resolver_type =
typename protocol_type::resolver;
/** Destructor.
@note A stream object must not be destroyed while there
are pending asynchronous operations associated with it.
*/
~stream();
/** Move constructor.
Undefined behavior if operations are active or pending.
*/
stream(stream&&) = default;
/** Move assignment.
Undefined behavior if operations are active or pending.
*/
stream& operator=(stream&&) = default;
/** Construct a HTTP stream.
This constructor creates a HTTP stream and initialises
the next layer.
@throws Any exceptions thrown by the Stream constructor.
@param args The arguments to be passed to initialise the
next layer. The arguments are forwarded to the next layer's
constructor.
*/
template<class... Args>
explicit
stream(Args&&... args);
/** Get the io_service associated with the stream.
This function may be used to obtain the io_service object
that the stream uses to dispatch handlers for asynchronous
operations.
@return A reference to the io_service object that the stream
will use to dispatch handlers. Ownership is not transferred
to the caller.
*/
boost::asio::io_service&
get_io_service()
{
return next_layer_.lowest_layer().get_io_service();
}
/** Get a reference to the next layer.
This function returns a reference to the next layer
in a stack of stream layers.
@return A reference to the next layer in the stack of
stream layers. Ownership is not transferred to the caller.
*/
next_layer_type&
next_layer()
{
return next_layer_;
}
/** Get a reference to the next layer.
This function returns a reference to the next layer in a
stack of stream layers.
@return A reference to the next layer in the stack of
stream layers. Ownership is not transferred to the caller.
*/
next_layer_type const&
next_layer() const
{
return next_layer_;
}
/** Get a reference to the lowest layer.
This function returns a reference to the lowest layer
in a stack of stream layers.
@return A reference to the lowest layer in the stack of
stream layers. Ownership is not transferred to the caller.
*/
lowest_layer_type&
lowest_layer()
{
return next_layer_.lowest_layer();
}
/** Get a reference to the lowest layer.
This function returns a reference to the lowest layer
in a stack of stream layers.
@return A reference to the lowest layer in the stack of
stream layers. Ownership is not transferred to the caller.
*/
lowest_layer_type const&
lowest_layer() const
{
return next_layer_.lowest_layer();
}
/** Cancel pending operations.
This will cancel all of the asynchronous operations pending,
including pipelined writes that have not been started. Handlers for
canceled writes will be called with
`boost::asio::error::operation_aborted`.
@throws boost::system::system_error Thrown on failure.
*/
void
cancel()
{
error_code ec;
cancel(ec);
if(ec)
throw system_error{ec};
}
/** Cancel pending operations.
This will cancel all of the asynchronous operations pending,
including pipelined writes that have not been started. Handlers for
canceled writes will be called with
`boost::asio::error::operation_aborted`.
@param ec Set to indicate what error occurred, if any.
*/
void
cancel(error_code& ec);
/** Read a HTTP message from the stream.
This function is used to read a single HTTP message from the stream.
The call will block until one of the followign conditions is true:
@li A message has been read.
@li An error occurred.
The operation is implemented in terms of zero or more calls to the
next layer's `read_some` function.
@param msg An object used to store the message. The previous
contents of the object will be overwritten.
@throws boost::system::system_error Thrown on failure.
*/
template<bool isRequest, class Body, class Headers>
void
read(message_v1<isRequest, Body, Headers>& msg)
{
error_code ec;
read(msg, ec);
if(ec)
throw system_error{ec};
}
/** Read a HTTP message from the stream.
This function is used to read a single HTTP message from the stream.
The call will block until one of the followign conditions is true:
@li A message has been read.
@li An error occurred.
The operation is implemented in terms of zero or more calls to the
next layer's `read_some` function.
@param msg An object used to store the message. The previous
contents of the object will be overwritten.
@param ec Set to indicate what error occurred, if any.
*/
template<bool isRequest, class Body, class Headers>
void
read(message_v1<isRequest, Body, Headers>& msg,
error_code& ec);
/** Start reading a HTTP message from the stream asynchronously.
This function is used to asynchronously read a single HTTP message
from the stream. The function call always returns immediately. The
asynchronous operation will continue until one of the following
conditions is true:
@li The message has been written.
@li An error occurred.
This operation is implemented in terms of zero or more calls to the
next layer's async_read_some function, and is known as a composed
operation. The program must ensure that the stream performs no other
read operations or any other composed operations that perform reads
until this operation completes.
@param msg An object used to store the message. The previous
contents of the object will be overwritten. Ownership of the message
is not transferred; the caller must guarantee that the object remains
valid until the handler is called.
@param handler The handler to be called when the request completes.
Copies will be made of the handler as required. The equivalent
function signature of the handler must be:
@code void handler(
error_code const& error // result of operation
); @endcode
Regardless of whether the asynchronous operation completes
immediately or not, the handler will not be invoked from within
this function. Invocation of the handler will be performed in a
manner equivalent to using boost::asio::io_service::post().
*/
template<bool isRequest, class Body, class Headers,
class ReadHandler>
#if GENERATING_DOCS
void_or_deduced
#else
typename async_completion<
ReadHandler, void(error_code)>::result_type
#endif
async_read(message_v1<isRequest, Body, Headers>& msg,
ReadHandler&& handler);
/** Write a HTTP message to the stream.
This function is used to write a single HTTP message to the
stream. The call will block until one of the following conditions
is true:
@li The entire message is sent.
@li An error occurred.
If the semantics of the message require that the connection is
closed to indicate the end of the content body,
`boost::asio::error::eof` is thrown after the message is sent.
successfuly. The caller is responsible for actually closing the
connection. For regular TCP/IP streams this means shutting down the
send side, while SSL streams may call the SSL shutdown function.
@param msg The message to send.
@throws boost::system::system_error Thrown on failure.
*/
template<bool isRequest, class Body, class Headers>
void
write(message_v1<isRequest, Body, Headers> const& msg)
{
error_code ec;
write(msg, ec);
if(ec)
throw system_error{ec};
}
/** Write a HTTP message to the stream.
This function is used to write a single HTTP message to the
stream. The call will block until one of the following conditions
is true:
@li The entire message is sent.
@li An error occurred.
If the semantics of the message require that the connection is
closed to indicate the end of the content body,
`boost::asio::error::eof` is returned after the message is sent.
successfuly. The caller is responsible for actually closing the
connection. For regular TCP/IP streams this means shutting down the
send side, while SSL streams may call the SSL shutdown function.
@param msg The message to send.
@param ec Set to the error, if any occurred.
*/
template<bool isRequest, class Body, class Headers>
void
write(message_v1<isRequest, Body, Headers> const& msg,
error_code& ec);
/** Start pipelining a HTTP message to the stream asynchronously.
This function is used to queue a message to be sent on the stream.
Unlike the free function, this version will place the message on an
outgoing message queue if there is already a write pending.
If the semantics of the message require that the connection is
closed to indicate the end of the content body, the handler
is called with the error `boost::asio::error::eof` after the message
has been sent successfully. The caller is responsible for actually
closing the connection. For regular TCP/IP streams this means
shutting down the send side, while SSL streams may call the SSL
`async_shutdown` function.
@param msg The message to send. A copy of the message will be made.
@param handler The handler to be called when the request completes.
Copies will be made of the handler as required. The equivalent
function signature of the handler must be:
@code void handler(
error_code const& error // result of operation
); @endcode
Regardless of whether the asynchronous operation completes
immediately or not, the handler will not be invoked from within
this function. Invocation of the handler will be performed in a
manner equivalent to using boost::asio::io_service::post().
*/
template<bool isRequest, class Body, class Headers,
class WriteHandler>
#if GENERATING_DOCS
void_or_deduced
#else
typename async_completion<
WriteHandler, void(error_code)>::result_type
#endif
async_write(message_v1<isRequest, Body, Headers> const& msg,
WriteHandler&& handler);
/** Start pipelining a HTTP message to the stream asynchronously.
This function is used to queue a message to be sent on the stream.
Unlike the free function, this version will place the message on an
outgoing message queue if there is already a write pending.
If the semantics of the message require that the connection is
closed to indicate the end of the content body, the handler
is called with the error boost::asio::error::eof. The caller is
responsible for actually closing the connection. For regular
TCP/IP streams this means shutting down the send side, while SSL
streams may call the SSL async_shutdown function.
@param msg The message to send. Ownership of the message, which
must be movable, is transferred to the implementation. The message
will not be destroyed until the asynchronous operation completes.
@param handler The handler to be called when the request completes.
Copies will be made of the handler as required. The equivalent
function signature of the handler must be:
@code void handler(
error_code const& error // result of operation
); @endcode
Regardless of whether the asynchronous operation completes
immediately or not, the handler will not be invoked from within
this function. Invocation of the handler will be performed in a
manner equivalent to using boost::asio::io_service::post().
*/
template<bool isRequest, class Body, class Headers,
class WriteHandler>
#if GENERATING_DOCS
void_or_deduced
#else
typename async_completion<
WriteHandler, void(error_code)>::result_type
#endif
async_write(message_v1<isRequest, Body, Headers>&& msg,
WriteHandler&& handler);
private:
template<bool, class, class, class> class read_op;
template<bool, class, class, class> class write_op;
void
cancel_all();
};
} // http
} // beast
#include "http_stream.ipp"
#endif
| 32.829522 | 79 | 0.675131 | [
"object"
] |
eb0a6e7a755080dc927203e98cb1b92601f2b932 | 720 | cpp | C++ | Competitive Programming/Dynamic Programming Intro/houseRob.cpp | l0rdluc1f3r/CppCompetitiveProgramming | 71376b5a6182dc446811072c73a2b13f33110d4c | [
"Apache-2.0"
] | 1 | 2022-03-24T06:38:53.000Z | 2022-03-24T06:38:53.000Z | Competitive Programming/Dynamic Programming Intro/houseRob.cpp | l0rdluc1f3r/CppCompetitiveProgramming | 71376b5a6182dc446811072c73a2b13f33110d4c | [
"Apache-2.0"
] | null | null | null | Competitive Programming/Dynamic Programming Intro/houseRob.cpp | l0rdluc1f3r/CppCompetitiveProgramming | 71376b5a6182dc446811072c73a2b13f33110d4c | [
"Apache-2.0"
] | null | null | null | // you are given money present in n adjacent houses.There is a robber
// who wants to rob the houses but he can never rob from 2 adjacent houses,
// find max loot of robber.
// 2, 7 , 9 , 3, 1
#include <bits/stdc++.h>
using namespace std;
long long int loothouseTD(vector<long long int> &arr, vector<long long int> &dp, int i){
if(i == 0){
return dp[0] = arr[0];
}
if(i == 1){
return dp[1] = max(arr[0], arr[1]);
}
if(dp[i] != -1) return dp[i];
return dp[i] = max(loothouseTD(arr, dp, i-1), loothouseTD(arr, dp, i-2)+arr[i]);
}
int main(){
int n;
cin>>n;
vector<long long int> arr(n, 0);
for(int i=0; i<=n; i++){
cout<<arr[i];
}
vector<long long int> dp(n, -1);
cout<<loothouseTD(arr, dp, n-1);
} | 24 | 88 | 0.611111 | [
"vector"
] |
eb0e367641bd18ccacc35ac2e9bff96fa7fda4c1 | 2,084 | cc | C++ | imm/src/model/GetFaceSearchUserRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | imm/src/model/GetFaceSearchUserRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | imm/src/model/GetFaceSearchUserRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/imm/model/GetFaceSearchUserRequest.h>
using AlibabaCloud::Imm::Model::GetFaceSearchUserRequest;
GetFaceSearchUserRequest::GetFaceSearchUserRequest() :
RpcServiceRequest("imm", "2017-09-06", "GetFaceSearchUser")
{}
GetFaceSearchUserRequest::~GetFaceSearchUserRequest()
{}
std::string GetFaceSearchUserRequest::getRegionId()const
{
return regionId_;
}
void GetFaceSearchUserRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setCoreParameter("RegionId", regionId);
}
std::string GetFaceSearchUserRequest::getProject()const
{
return project_;
}
void GetFaceSearchUserRequest::setProject(const std::string& project)
{
project_ = project;
setCoreParameter("Project", project);
}
std::string GetFaceSearchUserRequest::getGroupName()const
{
return groupName_;
}
void GetFaceSearchUserRequest::setGroupName(const std::string& groupName)
{
groupName_ = groupName;
setCoreParameter("GroupName", groupName);
}
std::string GetFaceSearchUserRequest::getUser()const
{
return user_;
}
void GetFaceSearchUserRequest::setUser(const std::string& user)
{
user_ = user;
setCoreParameter("User", user);
}
std::string GetFaceSearchUserRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void GetFaceSearchUserRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setCoreParameter("AccessKeyId", accessKeyId);
}
| 25.108434 | 78 | 0.75144 | [
"model"
] |
eb1382810fe858f89ed596e9bd7e87af7408ae79 | 2,752 | cpp | C++ | src/thundergbm/scikit_tgbm.cpp | Haiga/thundergbm | e7a1cca68ad076f112c48642f05651fb1f01e43a | [
"Apache-2.0"
] | 1 | 2019-10-06T21:22:59.000Z | 2019-10-06T21:22:59.000Z | src/thundergbm/scikit_tgbm.cpp | Haiga/gbm | d7a3f98271f15bd94d064f93b4ae3ce57f3b67da | [
"Apache-2.0"
] | null | null | null | src/thundergbm/scikit_tgbm.cpp | Haiga/gbm | d7a3f98271f15bd94d064f93b4ae3ce57f3b67da | [
"Apache-2.0"
] | null | null | null | //
// Created by zeyi on 1/12/19.
//
#include <thundergbm/trainer.h>
#include "thundergbm/parser.h"
#include <thundergbm/dataset.h>
#include "thundergbm/predictor.h"
extern "C" {
void sparse_train_scikit(int row_size, float *val, int *row_ptr, int *col_ptr, float *label,
int depth, int n_trees, int n_device, float min_child_weight, float lambda,
float gamma, int max_num_bin, int verbose, float column_sampling_rate,
int bagging, int n_parallel_trees, float learning_rate, char *obj_type,
int num_class, char *path, char *out_model_name, char *in_model_name,
char *tree_method, int *train_succeed) {
train_succeed[0] = 1;
if (verbose)
el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Enabled, "true");
else
el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Enabled, "false");
DataSet train_dataset;
train_dataset.load_from_sparse(row_size, val, row_ptr, col_ptr, label);
//init model_param
GBMParam model_param;
model_param.depth = depth;
model_param.n_trees = n_trees;
model_param.n_device = n_device;
model_param.min_child_weight = min_child_weight;
model_param.lambda = lambda;
model_param.gamma = gamma;
model_param.max_num_bin = max_num_bin;
model_param.verbose = verbose;
model_param.column_sampling_rate = column_sampling_rate;
model_param.bagging = bagging;
model_param.n_parallel_trees = n_parallel_trees;
model_param.learning_rate = learning_rate;
model_param.objective = obj_type;
model_param.num_class = num_class;
model_param.path = path;
model_param.out_model_name = out_model_name;
model_param.in_model_name = in_model_name;
model_param.tree_method = tree_method;
model_param.rt_eps = 1e-6;
TreeTrainer trainer;
trainer.train(model_param);
}//end sparse_model_scikit
void sparse_predict_scikit(int row_size, float *val, int *row_ptr, int *col_ptr, float *label,
char *in_model_name){
//load model
vector<vector<Tree>> boosted_model;
GBMParam model_param;
model_param.in_model_name = in_model_name;
model_param.path = "../dataset/test_dataset.txt";
Parser parser;
parser.load_model(model_param, boosted_model);
DataSet dataSet;
dataSet.load_from_sparse(row_size, val, row_ptr, col_ptr, label);
//predict
Predictor pred;
pred.predict(model_param, boosted_model, dataSet);
}
} | 39.314286 | 104 | 0.643895 | [
"vector",
"model"
] |
eb1412dc69719d957d2d368096b741b640b5e136 | 1,078 | hpp | C++ | include/disccord/rest/models/modify_current_user_args.hpp | FiniteReality/disccord | 1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff | [
"MIT"
] | 44 | 2016-09-19T15:28:25.000Z | 2018-08-09T13:17:40.000Z | include/disccord/rest/models/modify_current_user_args.hpp | FiniteReality/disccord | 1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff | [
"MIT"
] | 44 | 2016-11-03T17:27:30.000Z | 2017-12-10T16:17:31.000Z | include/disccord/rest/models/modify_current_user_args.hpp | FiniteReality/disccord | 1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff | [
"MIT"
] | 13 | 2016-11-01T00:17:20.000Z | 2018-08-03T19:51:16.000Z | #ifndef _modify_current_user_args_hpp_
#define _modify_current_user_args_hpp_
#include <cpprest/streams.h>
#include <cpprest/containerstream.h>
#include <disccord/models/model.hpp>
#include <disccord/util/optional.hpp>
namespace disccord
{
namespace rest
{
namespace models
{
class modify_current_user_args : public disccord::models::model
{
public:
modify_current_user_args();
virtual ~modify_current_user_args();
void set_name(std::string name);
void set_avatar(
concurrency::streams::basic_istream<unsigned char>
avatar_stream);
protected:
virtual void encode_to(
std::unordered_map<std::string, web::json::value>& info
) override;
private:
util::optional<std::string> name, avatar;
};
}
}
}
#endif /* _modify_current_user_args_hpp_ */
| 26.95 | 79 | 0.546382 | [
"model"
] |
eb17728596bed38dcbfff0afc77187de4c8b74cf | 19,825 | cpp | C++ | src/phased_genome.cpp | YTLogos/vg | f389c5a8e24d84bbb5afdc728534d82a078b1b48 | [
"BSL-1.0"
] | null | null | null | src/phased_genome.cpp | YTLogos/vg | f389c5a8e24d84bbb5afdc728534d82a078b1b48 | [
"BSL-1.0"
] | 1 | 2020-04-27T23:28:51.000Z | 2020-04-27T23:28:51.000Z | src/phased_genome.cpp | YTLogos/vg | f389c5a8e24d84bbb5afdc728534d82a078b1b48 | [
"BSL-1.0"
] | null | null | null | //
// phased_genome.cpp
//
#include "phased_genome.hpp"
using namespace std;
namespace vg {
PhasedGenome::HaplotypeNode::HaplotypeNode(NodeTraversal node_traversal, HaplotypeNode* next, HaplotypeNode* prev) :
node_traversal(node_traversal), next(next), prev(prev) {
// nothing to do
}
PhasedGenome::HaplotypeNode::~HaplotypeNode() {
// nothing to do
}
PhasedGenome::Haplotype::Haplotype(NodeTraversal node_traversal) {
// construct seed node
left_telomere_node = new HaplotypeNode(node_traversal, nullptr, nullptr);
right_telomere_node = left_telomere_node;
}
PhasedGenome::Haplotype::~Haplotype() {
// destruct nodes
HaplotypeNode* haplo_node = this->left_telomere_node;
while (haplo_node) {
HaplotypeNode* next = haplo_node->next;
delete haplo_node;
haplo_node = next;
}
}
PhasedGenome::PhasedGenome(SnarlManager& snarl_manager) : snarl_manager(snarl_manager) {
// nothing to do
}
PhasedGenome::~PhasedGenome() {
for (Haplotype* haplotype : haplotypes) {
delete haplotype;
}
}
void PhasedGenome::build_indices() {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: building node id to site index" << endl;
#endif
// construct the start and end of site indices
for (const Snarl* snarl : snarl_manager.top_level_snarls()) {
build_site_indices_internal(snarl);
}
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: building site to haplotype node index" << endl;
#endif
// label the sites on each haplotype
for (Haplotype* haplotype : haplotypes) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: traversing haplotype at " << haplotype << endl;
#endif
// keep track of where we enter and leave sites
unordered_map<const Snarl*, HaplotypeNode*> site_start_sides;
unordered_map<const Snarl*, HaplotypeNode*> site_end_sides;
// iterate along the node path of the haplotype
HaplotypeNode* haplo_node = haplotype->left_telomere_node;
while (haplo_node != nullptr) {
int64_t node_id = haplo_node->node_traversal.node->id();
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: recording an instance of node " << node_id << " in a haplotype node at " << haplo_node << endl;
#endif
// mark this instance of the node in the node location index
node_locations[node_id].push_back(haplo_node);
// are we at the start of a site?
if (site_starts.count(node_id)) {
const Snarl* site = site_starts[node_id];
// are we leaving or entering the site?
if (site_start_sides.count(site)) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: leaving at start of site " << site->start.node->id() << "->" << site->end.node->id() << endl;
#endif
// leaving: put the site in the index in the orientation of haplotype travesal
HaplotypeNode* other_side_node = site_start_sides[site];
site_start_sides.erase(site);
haplotype->sites[site] = make_pair(other_side_node, haplo_node);
}
else {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: entering at start of site " << site->start.node->id() << "->" << site->end.node->id() << endl;
#endif
// entering: mark the node in the haplotype path where we entered
site_end_sides[site] = haplo_node;
}
}
// are we at the start of a site?
if (site_ends.count(node_id)) {
const Snarl* site = site_ends[node_id];
// are we leaving or entering the site?
if (site_end_sides.count(site)) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: leaving at end of site " << site->start.node->id() << "->" << site->end.node->id() << endl;
#endif
// leaving: put the site in the index in the orientation of haplotype travesal
HaplotypeNode* other_side_node = site_end_sides[site];
site_end_sides.erase(site);
haplotype->sites[site] = make_pair(other_side_node, haplo_node);
}
else {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: entering at end of site " << site->start.node->id() << "->" << site->end.node->id() << endl;
#endif
// entering: mark the node in the haplotype path where we entered
site_start_sides[site] = haplo_node;
}
}
// advance to next node in haplotype path
haplo_node = haplo_node->next;
}
}
}
void PhasedGenome::build_site_indices_internal(const Snarl* snarl) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::build_indices]: recording start and end of site " << snarl->start().node_id() << "->" << snarl->end().node_id() << " at " << snarl << endl;
#endif
// record start and end of site
site_starts[snarl->start().node_id()] = snarl;
site_ends[snarl->end().node_id()] = snarl;
// recurse through child sites
for (const Snarl* subsnarl : snarl_manager.children_of(snarl)) {
build_site_indices_internal(subsnarl);
}
}
void PhasedGenome::swap_label(const Snarl& site, Haplotype& haplotype_1, Haplotype& haplotype_2) {
// update index for this site
if (haplotype_1.sites.count(&site)) {
if (haplotype_2.sites.count(&site)) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::swap_label]: site " << site.start().node_id() << "->" << site.end().node_id() << " is present on both alleles, swapping the label" << endl;
#endif
// site is in both haplotypes, swap the labels
swap(haplotype_1.sites[&site], haplotype_2.sites[&site]);
}
else {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::swap_label]: site " << site.start().node_id() << "->" << site.end().node_id() << " is present on only haplotype 1, transferring the label" << endl;
#endif
// site is only in haplotype 1, transfer the label
haplotype_2.sites[&site] = haplotype_1.sites[&site];
haplotype_1.sites.erase(&site);
}
}
else if (haplotype_2.sites.count(&site)) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::swap_label]: site " << site.start().node_id() << "->" << site.end().node_id() << " is present on only haplotype 2, transferring the label" << endl;
#endif
// site is only in haplotype 2, transfer the label
haplotype_1.sites[&site] = haplotype_2.sites[&site];
haplotype_2.sites.erase(&site);
}
else {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::swap_label]: site " << site.start().node_id() << "->" << site.end().node_id() << " is present on neither allele, ending recursion" << endl;
#endif
// site is in neither haplotype
return;
}
// update index for child sites
for (const Snarl* child_site : snarl_manager.children_of(&site)) {
swap_label(*child_site, haplotype_1, haplotype_2);
}
}
size_t PhasedGenome::num_haplotypes() {
return haplotypes.size();
}
PhasedGenome::iterator PhasedGenome::begin(int which_haplotype) {
return iterator(1, which_haplotype, haplotypes[which_haplotype]->left_telomere_node);
}
PhasedGenome::iterator PhasedGenome::end(int which_haplotype) {
return iterator(0, which_haplotype, nullptr);
}
void PhasedGenome::swap_alleles(const Snarl& site, int haplotype_1, int haplotype_2) {
Haplotype& haplo_1 = *haplotypes[haplotype_1];
Haplotype& haplo_2 = *haplotypes[haplotype_2];
pair<HaplotypeNode*, HaplotypeNode*> haplo_nodes_1 = haplo_1.sites[&site];
pair<HaplotypeNode*, HaplotypeNode*> haplo_nodes_2 = haplo_2.sites[&site];
#ifdef debug_phased_genome
cerr << "[PhasedGenome::swap_alleles]: swapping allele at site " << site.start().node_id() << "->" << site.end().node_id() << " between chromosomes " << haplotype_1 << " and " << haplotype_2 << " with haplotype nodes " << haplo_nodes_1.first << "->" << haplo_nodes_1.second << " and " << haplo_nodes_2.first << "->" << haplo_nodes_2.second << endl;
#endif
bool is_deletion_1 = (haplo_nodes_1.first->next == haplo_nodes_1.second);
bool is_deletion_2 = (haplo_nodes_2.first->next == haplo_nodes_2.second);
if (is_deletion_1 && !is_deletion_2) {
haplo_nodes_2.first->next->prev = haplo_nodes_1.first;
haplo_nodes_2.second->prev->next = haplo_nodes_1.second;
haplo_nodes_1.first->next = haplo_nodes_2.first->next;
haplo_nodes_1.second->prev = haplo_nodes_2.second->prev;
haplo_nodes_2.first->next = haplo_nodes_2.second;
haplo_nodes_2.second->prev = haplo_nodes_2.first;
}
else if (is_deletion_2 && !is_deletion_1) {
haplo_nodes_1.first->next->prev = haplo_nodes_2.first;
haplo_nodes_1.second->prev->next = haplo_nodes_2.second;
haplo_nodes_2.first->next = haplo_nodes_1.first->next;
haplo_nodes_2.second->prev = haplo_nodes_1.second->prev;
haplo_nodes_1.first->next = haplo_nodes_1.second;
haplo_nodes_1.second->prev = haplo_nodes_1.first;
}
else if (!is_deletion_1 && !is_deletion_2) {
haplo_nodes_2.first->next->prev = haplo_nodes_1.first;
haplo_nodes_2.second->prev->next = haplo_nodes_1.second;
haplo_nodes_1.first->next->prev = haplo_nodes_2.first;
haplo_nodes_1.second->prev->next = haplo_nodes_2.second;
std::swap(haplo_nodes_1.first->next, haplo_nodes_2.first->next);
std::swap(haplo_nodes_1.second->prev, haplo_nodes_2.second->prev);
}
// else two deletions and nothing will change
#ifdef debug_phased_genome
cerr << "[PhasedGenome::swap_alleles]: swapping labels on nested sites" << endl;
#endif
// update index for child sites
for (const Snarl* child_site : snarl_manager.children_of(&site)) {
swap_label(*child_site, haplo_1, haplo_2);
}
}
int32_t PhasedGenome::optimal_score_on_genome(const MultipathAlignment& multipath_aln, VG& graph) {
// must have identified start subpaths before computing optimal score
assert(multipath_aln.start_size() > 0);
// iteration functions to facilitate iterating on forward/reverse strands
auto move_right = [](HaplotypeNode*& path_node) { path_node = path_node->next; };
auto move_left = [](HaplotypeNode*& path_node) { path_node = path_node->prev; };
int32_t optimal_score = 0;
// find the places in the path where the alignment might start
unordered_map< pair<HaplotypeNode*, bool>, vector<int>> candidate_start_positions;
for (int i = 0; i < multipath_aln.start_size(); i++) {
// a starting subpath in the multipath alignment
const Subpath& start_subpath = multipath_aln.subpath(multipath_aln.start(i));
const Position& start_pos = start_subpath.path().mapping(0).position();
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: looking for candidate start positions for subpath " << multipath_aln.start(i) << " on node " << start_pos.node_id() << endl;
#endif
// add each location the start nodes occur in the path to the candidate starts
for ( HaplotypeNode* haplo_node : node_locations[start_pos.node_id()] ) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: marking candidate start position at " << haplo_node->node_traversal.node->id() << " on haplotype node at " << haplo_node << endl;
#endif
// mark the start locations orientation relative to the start node
candidate_start_positions[make_pair(haplo_node, haplo_node->node_traversal.backward == start_pos.is_reverse())].push_back(i);
}
}
// check alignments starting at each node in the path that has a source subpath starting on it
for (pair< pair<HaplotypeNode*, bool>, vector<int> > path_starts : candidate_start_positions) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: checking for an alignment at candidate start position on node " << path_starts.first.first->node_traversal.node->id() << " on " << (path_starts.first.second ? "forward" : "reverse" ) << " strand of haplotype" << endl;
#endif
HaplotypeNode* path_start_node = path_starts.first.first;
bool oriented_forward = path_starts.first.second;
const vector<int>& aln_starts = path_starts.second;
// match up forward and backward traversal on the path to forward and backward traversal through
// the multipath alignment
auto move_forward = oriented_forward ? move_right : move_left;
auto move_backward = oriented_forward ? move_left : move_right;
// initialize dynamic programming structures:
// pointer to place in haplotype path corresponding to the beginning of a subpath
vector<HaplotypeNode*> subpath_nodes = vector<HaplotypeNode*>(multipath_aln.subpath_size(), nullptr);
// score of the best preceding path before this subpath
vector<int32_t> subpath_prefix_score = vector<int32_t>(multipath_aln.subpath_size(), 0);
// set DP base case with the subpaths that start at this path node
for (int i : aln_starts) {
subpath_nodes[multipath_aln.start(i)] = path_start_node;
}
for (int i = 0; i < multipath_aln.subpath_size(); i++) {
HaplotypeNode* subpath_node = subpath_nodes[i];
// this subpath may be unreachable from subpaths consistent with the path
if (subpath_node == nullptr) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: subpath " << i << " is unreachable through consistent paths" << endl;
#endif
continue;
}
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: checking subpath " << i << " for consistent paths" << endl;
#endif
const Subpath& subpath = multipath_aln.subpath(i);
// iterate through mappings in this subpath (assumes one mapping per node)
bool subpath_follows_path = true;
for (int j = 0; j < subpath.path().mapping_size(); j++, move_forward(subpath_node)) {
// check if mapping corresponds to the next node in the path in the correct orientation
const Position& position = subpath.path().mapping(j).position();
if (position.node_id() != subpath_node->node_traversal.node->id()
|| ((position.is_reverse() == subpath_node->node_traversal.backward) != oriented_forward)) {
subpath_follows_path = false;
break;
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: subpath " << i << " is inconsistent with haplotype" << endl;
#endif
}
}
// if subpath followed haplotype path, extend to subsequent subpaths or record completed alignment
if (subpath_follows_path) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: subpath " << i << " is consistent with haplotype" << endl;
#endif
int32_t extended_prefix_score = subpath_prefix_score[i] + subpath.score();
if (subpath.next_size() == 0) {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: sink path, considering score of " << extended_prefix_score << endl;
#endif
// reached a sink subpath (thereby completing an alignment), check for optimality
if (extended_prefix_score > optimal_score) {
optimal_score = extended_prefix_score;
}
}
else {
#ifdef debug_phased_genome
cerr << "[PhasedGenome::optimal_score_on_genome]: non sink path, extending score of " << extended_prefix_score << endl;
#endif
// edge case: check if subpath_node was improperly incremented from a mapping that ended in the
// middle of a node
Position end_pos = last_path_position(subpath.path());
if (end_pos.offset() != graph.get_node(end_pos.node_id())->sequence().length()) {
move_backward(subpath_node);
}
// TODO: this could be a problem if the next node is the end of a chromosome (will seg fault
// because can't get the previous node from nullptr)
// mark which node the next subpath starts at
for (int j = 0; j < subpath.next_size(); j++) {
if (subpath_prefix_score[subpath.next(j)] < extended_prefix_score) {
subpath_prefix_score[subpath.next(j)] = extended_prefix_score;
subpath_nodes[subpath.next(j)] = subpath_node;
}
}
}
}
}
}
return optimal_score;
}
PhasedGenome::iterator::iterator() : rank(0), haplotype_number(-1), haplo_node(nullptr) {
}
PhasedGenome::iterator::iterator(size_t rank, int haplotype_number, HaplotypeNode* haplo_node) :
rank(rank), haplotype_number(haplotype_number), haplo_node(haplo_node) {
}
PhasedGenome::iterator::iterator(const iterator& other) : rank(other.rank),
haplotype_number(other.haplotype_number),
haplo_node(other.haplo_node) {
}
PhasedGenome::iterator::~iterator() {
}
}
| 47.42823 | 356 | 0.580832 | [
"vector"
] |
eb17e58bd95d0a3af4b09e94750abc19f1b50c7e | 11,980 | cpp | C++ | libs/core/runtime_local/src/interval_timer.cpp | bhumitattarde/hpx | 5b34d8d77b1664fa552445d44cd98e51dc69a74a | [
"BSL-1.0"
] | 1 | 2022-02-08T05:55:09.000Z | 2022-02-08T05:55:09.000Z | libs/core/runtime_local/src/interval_timer.cpp | deepaksuresh1411/hpx | aa18024d35fe9884a977d4b6076c764dbb8b26d1 | [
"BSL-1.0"
] | null | null | null | libs/core/runtime_local/src/interval_timer.cpp | deepaksuresh1411/hpx | aa18024d35fe9884a977d4b6076c764dbb8b26d1 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2017 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under 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)
#include <hpx/config.hpp>
#include <hpx/assert.hpp>
#include <hpx/functional/bind_front.hpp>
#include <hpx/functional/deferred_call.hpp>
#include <hpx/modules/errors.hpp>
#include <hpx/runtime_local/interval_timer.hpp>
#include <hpx/runtime_local/shutdown_function.hpp>
#include <hpx/thread_support/unlock_guard.hpp>
#include <hpx/threading_base/thread_helpers.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
namespace hpx { namespace util { namespace detail {
///////////////////////////////////////////////////////////////////////////
interval_timer::interval_timer()
: microsecs_(0)
, id_()
, timerid_()
, pre_shutdown_(false)
, is_started_(false)
, first_start_(true)
, is_terminated_(false)
, is_stopped_(false)
{
}
interval_timer::interval_timer(hpx::function<bool()> const& f,
std::int64_t microsecs, std::string const& description,
bool pre_shutdown)
: f_(f)
, on_term_()
, microsecs_(microsecs)
, id_()
, timerid_()
, description_(description)
, pre_shutdown_(pre_shutdown)
, is_started_(false)
, first_start_(true)
, is_terminated_(false)
, is_stopped_(false)
{
}
interval_timer::interval_timer(hpx::function<bool()> const& f,
hpx::function<void()> const& on_term, std::int64_t microsecs,
std::string const& description, bool pre_shutdown)
: f_(f)
, on_term_(on_term)
, microsecs_(microsecs)
, id_()
, timerid_()
, description_(description)
, pre_shutdown_(pre_shutdown)
, is_started_(false)
, first_start_(true)
, is_terminated_(false)
, is_stopped_(false)
{
}
bool interval_timer::start(bool evaluate_)
{
std::unique_lock<mutex_type> l(mtx_);
if (is_terminated_)
return false;
if (!is_started_)
{
if (first_start_)
{
first_start_ = false;
util::unlock_guard<std::unique_lock<mutex_type>> ul(l);
if (pre_shutdown_)
{
register_pre_shutdown_function(util::deferred_call(
&interval_timer::terminate, this->shared_from_this()));
}
else
{
register_shutdown_function(util::deferred_call(
&interval_timer::terminate, this->shared_from_this()));
}
}
is_stopped_ = false;
if (evaluate_)
{
l.unlock();
evaluate(threads::thread_restart_state::signaled);
}
else
{
schedule_thread(l);
}
return true;
}
return false;
}
bool interval_timer::restart(bool evaluate_)
{
if (!is_started_)
return start(evaluate_);
std::unique_lock<mutex_type> l(mtx_);
if (is_terminated_)
return false;
// interrupt timer thread, if needed
stop_locked();
// reschedule evaluation thread
if (evaluate_)
{
l.unlock();
evaluate(threads::thread_restart_state::signaled);
}
else
{
schedule_thread(l);
}
return true;
}
bool interval_timer::stop(bool terminate_timer)
{
if (terminate_timer)
{
terminate();
return true;
}
std::lock_guard<mutex_type> l(mtx_);
is_stopped_ = true;
return stop_locked();
}
bool interval_timer::stop_locked()
{
if (is_started_)
{
is_started_ = false;
if (timerid_)
{
error_code ec(
throwmode::lightweight); // avoid throwing on error
threads::set_thread_state(timerid_.noref(),
threads::thread_schedule_state::pending,
threads::thread_restart_state::abort,
threads::thread_priority::boost, true, ec);
timerid_.reset();
}
if (id_)
{
error_code ec(
throwmode::lightweight); // avoid throwing on error
threads::set_thread_state(id_.noref(),
threads::thread_schedule_state::pending,
threads::thread_restart_state::abort,
threads::thread_priority::boost, true, ec);
id_.reset();
}
return true;
}
HPX_ASSERT(id_ == nullptr);
HPX_ASSERT(timerid_ == nullptr);
return false;
}
void interval_timer::terminate()
{
std::unique_lock<mutex_type> l(mtx_);
if (!is_terminated_)
{
is_terminated_ = true;
stop_locked();
if (on_term_)
{
l.unlock();
on_term_();
}
}
}
interval_timer::~interval_timer()
{
try
{
terminate();
}
catch (...)
{
; // there is nothing we can do here
}
}
std::int64_t interval_timer::get_interval() const
{
std::lock_guard<mutex_type> l(mtx_);
return microsecs_;
}
void interval_timer::change_interval(std::int64_t new_interval)
{
HPX_ASSERT(new_interval > 0);
std::lock_guard<mutex_type> l(mtx_);
microsecs_ = new_interval;
}
threads::thread_result_type interval_timer::evaluate(
threads::thread_restart_state statex)
{
try
{
std::unique_lock<mutex_type> l(mtx_);
if (is_stopped_ || is_terminated_ ||
statex == threads::thread_restart_state::abort ||
0 == microsecs_)
{
// object has been finalized, exit
return threads::thread_result_type(
threads::thread_schedule_state::terminated,
threads::invalid_thread_id);
}
if (id_ != nullptr && id_ != threads::get_self_id())
{
// obsolete timer thread
return threads::thread_result_type(
threads::thread_schedule_state::terminated,
threads::invalid_thread_id);
}
id_.reset();
timerid_.reset();
is_started_ = false;
bool result = false;
{
util::unlock_guard<std::unique_lock<mutex_type>> ul(l);
result = f_(); // invoke the supplied function
}
// some other thread might already have started the timer
if (nullptr == id_ && result)
{
HPX_ASSERT(!is_started_);
schedule_thread(l); // wait and repeat
}
if (!result)
is_terminated_ = true;
}
catch (hpx::exception const& e)
{
// the lock above might throw yield_aborted
if (e.get_error() != yield_aborted)
throw;
}
// do not re-schedule this thread
return threads::thread_result_type(
threads::thread_schedule_state::terminated,
threads::invalid_thread_id);
}
// schedule a high priority task after a given time interval
void interval_timer::schedule_thread(std::unique_lock<mutex_type>& l)
{
HPX_ASSERT(l.owns_lock());
HPX_UNUSED(l);
using namespace hpx::threads;
error_code ec;
// create a new suspended thread
threads::thread_id_ref_type id;
{
// FIXME: registering threads might lead to thread suspension since
// the allocators use hpx::spinlock. Unlocking the lock here would
// be the right thing but leads to crashes and hangs at shutdown.
// util::unlock_guard<std::unique_lock<mutex_type> > ul(l);
hpx::threads::thread_init_data data(
hpx::threads::make_thread_function(hpx::bind_front(
&interval_timer::evaluate, this->shared_from_this())),
description_.c_str(), threads::thread_priority::boost,
threads::thread_schedule_hint(),
threads::thread_stacksize::default_,
threads::thread_schedule_state::suspended, true);
id = hpx::threads::register_thread(data, ec);
}
if (ec)
{
is_terminated_ = true;
is_started_ = false;
return;
}
// schedule this thread to be run after the given amount of seconds
threads::thread_id_ref_type timerid = threads::set_thread_state(
id.noref(), std::chrono::microseconds(microsecs_),
threads::thread_schedule_state::pending,
threads::thread_restart_state::signaled,
threads::thread_priority::boost, true, ec);
if (ec)
{
is_terminated_ = true;
is_started_ = false;
// abort the newly created thread
threads::set_thread_state(id.noref(),
threads::thread_schedule_state::pending,
threads::thread_restart_state::abort,
threads::thread_priority::boost, true, ec);
return;
}
id_ = id;
timerid_ = timerid;
is_started_ = true;
}
}}} // namespace hpx::util::detail
namespace hpx { namespace util {
interval_timer::interval_timer() {} // -V730
interval_timer::interval_timer( // -V730
hpx::function<bool()> const& f, std::int64_t microsecs,
std::string const& description, bool pre_shutdown)
: timer_(std::make_shared<detail::interval_timer>(
f, microsecs, description, pre_shutdown))
{
}
interval_timer::interval_timer( // -V730
hpx::function<bool()> const& f, hpx::function<void()> const& on_term,
std::int64_t microsecs, std::string const& description,
bool pre_shutdown)
: timer_(std::make_shared<detail::interval_timer>(
f, on_term, microsecs, description, pre_shutdown))
{
}
interval_timer::interval_timer( // -V730
hpx::function<bool()> const& f,
hpx::chrono::steady_duration const& rel_time, char const* description,
bool pre_shutdown)
: timer_(std::make_shared<detail::interval_timer>(
f, rel_time.value().count() / 1000, description, pre_shutdown))
{
}
interval_timer::interval_timer( // -V730
hpx::function<bool()> const& f, hpx::function<void()> const& on_term,
hpx::chrono::steady_duration const& rel_time, char const* description,
bool pre_shutdown)
: timer_(std::make_shared<detail::interval_timer>(f, on_term,
rel_time.value().count() / 1000, description, pre_shutdown))
{
}
interval_timer::~interval_timer()
{
timer_->terminate();
}
std::int64_t interval_timer::get_interval() const
{
return timer_->get_interval();
}
void interval_timer::change_interval(std::int64_t new_interval)
{
return timer_->change_interval(new_interval);
}
void interval_timer::change_interval(
hpx::chrono::steady_duration const& new_interval)
{
return timer_->change_interval(new_interval.value().count() / 1000);
}
}} // namespace hpx::util
| 29.362745 | 80 | 0.550835 | [
"object"
] |
a3e33ecce13e30410ed06be1ef1374260a8e3eef | 41,495 | cpp | C++ | lib/aptree.cpp | wzh99/AP-Tree | 4bf80fbbb70e2b6dba302c774c72545eb8f2797b | [
"MIT"
] | 1 | 2021-01-07T06:51:52.000Z | 2021-01-07T06:51:52.000Z | lib/aptree.cpp | wzh99/AP-Tree | 4bf80fbbb70e2b6dba302c774c72545eb8f2797b | [
"MIT"
] | null | null | null | lib/aptree.cpp | wzh99/AP-Tree | 4bf80fbbb70e2b6dba302c774c72545eb8f2797b | [
"MIT"
] | 1 | 2019-12-12T07:10:56.000Z | 2019-12-12T07:10:56.000Z | #include "../include/aptree.hpp"
#include <cmath>
#include <iostream>
#include <limits>
#include <numeric>
#define COUT(expr) std::cout << expr << std::endl;
static constexpr auto INDEX_NOT_FOUND = std::numeric_limits<size_t>::max();
// For indicating range of space or keyword
// Array pointer version
template <class Type>
static size_t rangeSearch(const Type *ranges, size_t size, const Type target) noexcept {
size_t start = 0, end = size - 1, mid = (start + end) / 2;
if (target < ranges[start] || target >= ranges[end])
return INDEX_NOT_FOUND; // can't be in any range
while (true) {
if (end - start == 1) return start; // range is obvious
mid = (start + end) / 2;
auto startEle = ranges[start], midEle = ranges[mid], endEle = ranges[end];
if (target == startEle) return start;
if (target == midEle) return mid;
if (target == endEle) return end;
if (target > startEle && target < midEle) {
end = mid;
continue;
}
else if (target > midEle && target < endEle) {
start = mid;
continue;
}
}
return INDEX_NOT_FOUND;
}
// std::vector version
template <class Type>
static inline size_t rangeSearch(const std::vector<Type> &ranges, const Type target) noexcept {
return rangeSearch(ranges.data(), ranges.size(), target);
}
// For verifying selected queries, elements in two input vector must be sorted
template <class Type>
static bool isSubset(const std::vector<Type> &super, const std::vector<Type> &sub) noexcept {
auto superIte = super.begin(), subIte = sub.begin();
while (subIte != sub.end()) {
if (superIte == super.end()) return false;
auto superVal = *superIte, subVal = *subIte;
if (superVal > subVal) return false;
else if (superVal == subVal) {
superIte++;
subIte++;
} else
while (superIte != super.end() && *superIte < *subIte)
superIte++;
}
return true;
}
// For selecting common queries from two ranges in corresponding axis
template <class Type>
static std::vector<Type> commonElements(const std::set<Type> &v1, const std::set<Type> &v2) noexcept {
std::vector<Type> common;
if (v1.size() == 0 || v2.size() == 0) return common;
auto ite1 = v1.begin(), ite2 = v2.begin();
while (ite1 != v1.end() && ite2 != v2.end()) {
if (*ite1 == *ite2) {
common.push_back(*ite1);
ite1++;
ite2++;
}
else if (*ite1 < *ite2)
ite1++;
else
ite2++;
}
return common;
}
struct APTree::QueryNested {
Boundf region;
std::vector<size_t> keywords; // stores indexes of keywords in dictionary for algorithm efficiency
bool operator < (const QueryNested &qry) const noexcept { return region.Area() < qry.region.Area(); }
bool operator == (const QueryNested &qry) const noexcept { return region == qry.region && keywords == qry.keywords; }
};
struct APTree::STObjectNested {
Pointf location;
std::vector<size_t> keywords; // the same as QueryNested
};
struct APTree::KeywordCut {
size_t start, end; // both ends included
KeywordCut() {}
KeywordCut(size_t start, size_t end) : start(start), end(end) {}
bool isInCut(size_t index) const noexcept { return index >= start && index <= end; }
bool operator == (const KeywordCut &other) const noexcept { return start == other.start && end == other.end; }
bool operator < (const KeywordCut &other) const noexcept {
if (start != other.start) return start < other.start;
return end < other.end;
}
};
struct APTree::KeywordPartition {
size_t nPart;
std::unique_ptr<KeywordCut[]> cuts;
std::unique_ptr<std::vector<QueryNested *>[]> queries;
std::vector<QueryNested *> dummy; // queries which has less queries than current offset
double cost = 0;
};
struct APTree::SpatialPartition {
size_t nPartX, nPartY;
std::unique_ptr<double[]> partX, partY; // start position of X and Y partition, respectively
std::unique_ptr<std::vector<QueryNested *>[]> cells; // column-major vector of query pointers in each cell
std::vector<QueryNested *> dummy; // queries which covers the whole region
double cost = 0;
};
struct APTree::Node {
enum NodeType { // assigned in callee code
QUERY, // stores queries
KEYWORD, // stores keyword cuts
SPATIAL // stores spatial quadtree cells
} type;
size_t offset; // assigned in caller code, for use of keyword partition
Boundf bound; // assigned in caller code, for use of spatial partition
bool useKw, useSp; // assigned in caller code, instead of arguments passed in build method
// Package different type of node data in a union will cause problems
struct QueryNode {
std::vector<QueryNested> queries;
};
std::unique_ptr<QueryNode> query = nullptr;
struct KeywordNode {
size_t offset; // the same with KeywordPartition
size_t nPart;
std::unique_ptr<KeywordCut[]> cuts; // sorted keyword cuts for binary search
std::unique_ptr<std::unique_ptr<Node>[]> children;
std::unique_ptr<size_t[]> nOld; // record number of descendent queries in last construction and
std::unique_ptr<size_t[]> nAdd; // record number of newly added queries since last construction
// Find corresponding cut based on object keywords, return index of cut found
// The algorithm is similar to rangeSearch(), but deals with keyword cuts instead of ranges
size_t Search(size_t target) const noexcept {
size_t start = 0, end = nPart - 1, mid = (start + end) / 2;
if (target < cuts[start].start || target > cuts[end].end)
return INDEX_NOT_FOUND; // can't be in any cut
while (true) {
if (end - start == 1) {
if (cuts[start].isInCut(target))
return start;
else
return INDEX_NOT_FOUND; // between gap of two cuts
}
mid = (start + end) / 2;
auto startCut = cuts[start], midCut = cuts[mid], endCut = cuts[end];
if (startCut.isInCut(target)) return start;
if (midCut.isInCut(target)) return mid;
if (endCut.isInCut(target)) return end;
if (target >= startCut.start && target < midCut.start) {
end = mid;
continue;
} else if (target >= midCut.start && target < endCut.start) {
start = mid;
continue;
}
}
return INDEX_NOT_FOUND;
}
};
std::unique_ptr<KeywordNode> keyword = nullptr;
struct SpatialNode {
size_t nPartX, nPartY;
std::unique_ptr<double[]> partX, partY; // has one more element than nPart
std::unique_ptr<std::unique_ptr<Node>[]> cells; // 1D vector of m * n cells [0 ... m-1][0 ... n-1]
std::unique_ptr<size_t[]> nOld, nAdd; // the same as
Pointu GetCellIndex(const Pointf &pt) const noexcept {
size_t ix = rangeSearch(partX.get(), nPartX, pt.x);
size_t iy = rangeSearch(partY.get(), nPartY, pt.y);
return {ix, iy};
}
};
std::unique_ptr<SpatialNode> spatial = nullptr;
// Shared
std::unique_ptr<Node> dummy = nullptr; // shared by query and spatial node, can be null
Node() {}
Node(const Node &node)
: offset(node.offset), bound(node.bound), useKw(node.useKw), useSp(node.useSp) {}
Node(size_t offset, const Boundf &bd, bool useKw, bool useSp)
: offset(offset), bound(bd), useKw(useKw), useSp(useSp) {}
~Node() {} // explicit destructor for std::unique_ptr
};
APTree::APTree(const std::vector<std::string> &vocab, const std::vector<Query> &queries, size_t f, size_t theta_Q, double theta_KL)
: dict(vocab.begin(), vocab.end()), nQry(0), f(f), theta_Q(theta_Q), theta_KL(theta_KL)
{
// Build vocabulary index map
for (size_t i = 0; i < dict.size(); i++)
dictIndex[dict[i]] = i;
// Build nested queries
std::vector<QueryNested> nestedQueries;
for (const auto &qry : queries) {
std::vector<size_t> indexVec;
for (const auto &str : qry.keywords)
indexVec.push_back(dictIndex[str]);
std::sort(indexVec.begin(), indexVec.end()); // indexes must be sorted for verifying subset
nestedQueries.push_back({qry.region, std::move(indexVec)});
}
// Remove repeated queries
std::sort(nestedQueries.begin(), nestedQueries.end());
auto newEnd = std::unique(nestedQueries.begin(), nestedQueries.end());
nestedQueries.erase(newEnd, nestedQueries.end());
nQry = nestedQueries.size();
// Build nested query pointer vector
std::vector<QueryNested *> nstdQryPtrs;
auto qryArrPtr = nestedQueries.data();
for (size_t i = 0; i < nestedQueries.size(); i++)
nstdQryPtrs.push_back(qryArrPtr + i);
// Start building tree
root = new Node(0, Boundf({ 0, 0 }, { 1, 1 }), true, true);
build(root, nstdQryPtrs); // different from paper, offset is 0-indexed instead of 1-indexed
}
APTree::~APTree() { delete root; }
void APTree::build(Node *node, const std::vector<QueryNested *> &subQry)
{
// Build query node
if ((!node->useKw && !node->useSp) || subQry.size() < theta_Q) {
node->type = Node::QUERY;
node->query = std::make_unique<Node::QueryNode>();
// Copy queries into node
auto &queries = node->query->queries;
for (const auto ptr : subQry)
queries.push_back(*ptr);
return;
}
// Compute cost for both keyword and spatial partitions
double kwCost, spCost;
kwCost = spCost = std::numeric_limits<double>::infinity();
KeywordPartition kwPart;
SpatialPartition spPart;
if (node->useKw) { // try keyword partition
kwPart = keywordHeuristic(subQry, node->offset);
kwCost = kwPart.cost;
}
if (node->useSp) { // try spatial partition
spPart = spatialHeuristic(subQry, node->bound);
spCost = spPart.cost;
}
// Build keyword or partition node according to computed costs
if (kwCost < spCost) { // keyword partition is chosen
node->type = Node::KEYWORD;
node->keyword = std::make_unique<Node::KeywordNode>();
if (kwPart.dummy.size() > 0) {
node->dummy = std::make_unique<Node>(node->offset + 1, node->bound, false, node->useSp);
build(node->dummy.get(), kwPart.dummy);
// keyword dummy node can no longer be partitioned by keyword again
}
size_t nPart = node->keyword->nPart = kwPart.nPart;
node->keyword->cuts = std::move(kwPart.cuts);
node->keyword->children = std::make_unique<std::unique_ptr<Node>[]>(nPart);
node->keyword->nOld = std::make_unique<size_t[]>(nPart);
node->keyword->nAdd = std::make_unique<size_t[]>(nPart);
memset(node->keyword->nAdd.get(), 0, nPart * sizeof(size_t)); // set nOld to zeros
for (size_t i = 0; i < nPart; i++) {
auto ptr = new Node(node->offset + 1, node->bound, node->useKw, node->useSp);
node->keyword->children[i] = std::unique_ptr<Node>(ptr);
node->keyword->nOld[i] = kwPart.queries[i].size();
build(ptr, kwPart.queries[i]);
}
} else { // spatial partition is chosen
node->type = Node::SPATIAL;
node->spatial = std::make_unique<Node::SpatialNode>();
if (spPart.dummy.size() > 0) {
node->dummy = std::make_unique<Node>(node->offset, node->bound, node->useKw, false);
build(node->dummy.get(), spPart.dummy);
// spatial dummy node can no longer be partitioned by space again
}
// Move data from partition strategy to node
auto nPartX = node->spatial->nPartX = spPart.nPartX;
auto nPartY = node->spatial->nPartY = spPart.nPartY;
auto nPart = nPartX * nPartY;
node->spatial->partX = std::move(spPart.partX);
node->spatial->partY = std::move(spPart.partY);
node->spatial->cells = std::make_unique<std::unique_ptr<Node>[]>(nPart);
node->spatial->nOld = std::make_unique<size_t[]>(nPart);
node->spatial->nAdd = std::make_unique<size_t[]>(nPart);
memset(node->spatial->nAdd.get(), 0, nPart * sizeof(size_t)); // set nAdd to zeros
auto partX = node->spatial->partX.get(), partY = node->spatial->partY.get();
for (size_t i = 0; i < nPartX; i++)
for (size_t j = 0; j < nPartY; j++) {
size_t index = j + i * nPartY;
auto bound = Boundf{ {partX[i], partY[j]}, {partX[i + 1], partY[j + 1]} };
auto ptr = new Node(node->offset, bound, node->useKw, node->useSp);
node->spatial->cells[index] = std::unique_ptr<Node>(ptr);
node->spatial->nOld[index] = spPart.cells[index].size();
build(ptr, spPart.cells[index]);
}
}
}
// Bucket problem for heuristic algorithm
// Put m queries in n buckets. Suppose buckets have the same capacity, what is the minimum capacity required?
inline static size_t bucketCapacity(size_t m, size_t n) noexcept {
return m % n == 0 ? (m / n) : (m / n + 1);
}
APTree::KeywordPartition APTree::keywordHeuristic(const std::vector<QueryNested *> &subQry, size_t offset)
{
KeywordPartition partition;
// Get statistics of query keywords to be partitioned
std::map<size_t, std::vector<QueryNested *>> offsetWordQryMap; // queries related to keywords of current offset
std::map<size_t, size_t> allWordFreqMap; // frequencies related to keywords of all offsets
std::vector<QueryNested *> dummy;
double dictSize = 0;
for (const auto ptr : subQry) {
// Count keyword frequencies in all query offsets
dictSize += ptr->keywords.size();
for (auto word : ptr->keywords)
if (allWordFreqMap.find(word) == allWordFreqMap.end())
allWordFreqMap[word] = 1;
else
allWordFreqMap[word]++;
// Divide keyword into dummies and descendents
if (ptr->keywords.size() <= offset)
dummy.push_back(ptr); // this query can't be partitioned by current offset
else {
size_t curWord = ptr->keywords[offset];
if (offsetWordQryMap.find(curWord) == offsetWordQryMap.end()) // new word to offset keyword map
offsetWordQryMap[curWord] = std::vector<QueryNested *>();
offsetWordQryMap[curWord].push_back(ptr); // count word frequency
}
}
dictSize /= subQry.size(); // get average keyword size in passed queries.
// Get total frequency of all appearing words
double totalFreq = 0;
for (const auto &pair : allWordFreqMap) totalFreq += double(pair.second);
totalFreq /= dictSize;
// Convert the word statistic map to vector for random access
std::vector<std::pair<size_t, std::vector<QueryNested *>>> offsetWordQryVec;
offsetWordQryVec.insert(offsetWordQryVec.begin(), offsetWordQryMap.begin(), offsetWordQryMap.end());
// Propose a partition which divides words by a fixed offset
size_t nPart = std::min(f, offsetWordQryVec.size()); // number of words to be partitioned may be less than nPart
size_t nWordPerPart = bucketCapacity(offsetWordQryVec.size(), nPart);
std::vector<KeywordCut> propCuts; // proposed cuts
propCuts.reserve(nPart);
for (size_t i = 0; i < nPart; i++) {
size_t cutStart = i * nWordPerPart; // cutStart and cutEnd are indexes in offsetWordQryVec, not actual word indexes
if (cutStart >= offsetWordQryVec.size()) {
nPart = i;
break; // break in case of empty buckets
}
size_t cutEnd = std::min(offsetWordQryVec.size(), cutStart + nWordPerPart) - 1;
propCuts.push_back({offsetWordQryVec[cutStart].first, offsetWordQryVec[cutEnd].first});
}
// Defines cost computing function for each keyword cut
auto computeCutCost = [&] (const KeywordCut &cut) {
double weight = 0; // number of queries associated to current cut(bucket)
double freqSum = 0; // sum of probabilities of all words in current cut
for (size_t word = cut.start; word <= cut.end; word++) {
if (offsetWordQryMap.find(word) == offsetWordQryMap.end()) // word not found
continue;
weight += offsetWordQryMap[word].size();
freqSum += allWordFreqMap[word]; // use local query distribution to estimate the whole one
}
return weight * freqSum / totalFreq;
};
// Find a partition which evenly partitions keywords by weight through heuristic algorithm
for (size_t i = 1; i < nPart; i++) {
// Compute current cost of proposed cuts
// Only account for two involved cuts, since other cuts has no change on total partition cost
double curCost = computeCutCost(propCuts[i - 1]) + computeCutCost(propCuts[i]);
// Try all possible cuts
size_t leftCutStart = propCuts[i - 1].start, rightCutEnd = propCuts[i].end;
for (size_t leftCutEnd = leftCutStart; leftCutEnd != rightCutEnd; leftCutEnd++) {
if (offsetWordQryMap.find(leftCutEnd) == offsetWordQryMap.end()) // proposed left cut ending word not found
continue;
size_t rightCutStart = leftCutEnd + 1;
while (offsetWordQryMap.find(rightCutStart) == offsetWordQryMap.end() && rightCutStart < rightCutEnd)
rightCutStart++; // set start of right cut to valid index for efficiency
double propCost = computeCutCost({leftCutStart, leftCutEnd}) + computeCutCost({rightCutStart, rightCutEnd});
if (propCost < curCost) { // better cut
curCost = propCost;
propCuts[i - 1].end = leftCutEnd; // update proposed cuts
propCuts[i].start = rightCutStart;
}
}
}
// Prepare partition strategy to be returned
partition.nPart = nPart;
partition.cost = 0;
partition.cuts = std::make_unique<KeywordCut[]>(nPart);
memcpy(partition.cuts.get(), propCuts.data(), nPart * sizeof(nPart));
partition.dummy = std::move(dummy);
partition.queries = std::make_unique<std::vector<QueryNested *>[]>(nPart);
for (size_t i = 0; i < nPart; i++) {
partition.cost += computeCutCost(propCuts[i]);
partition.queries[i] = std::vector<QueryNested *>();
auto &cutQryVec = partition.queries[i];
for (size_t word = propCuts[i].start; word <= propCuts[i].end; word++) {
if (offsetWordQryMap.find(word) == offsetWordQryMap.end()) continue;
auto &wordQryVec = offsetWordQryMap[word];
cutQryVec.insert(cutQryVec.end(), wordQryVec.begin(), wordQryVec.end());
}
}
return partition;
}
APTree::SpatialPartition APTree::spatialHeuristic(const std::vector<QueryNested *> &subQry, const Boundf &bound)
{
SpatialPartition partition;
size_t nPart = std::min(f, subQry.size());
size_t nPartX = partition.nPartX = std::floor(std::sqrt(nPart));
size_t nPartY = partition.nPartY = nPart / nPartX;
// Prune dummy queries
std::vector<QueryNested *> cellQry, dummy;
for (const auto qry : subQry)
if (qry->region.Contains(bound))
dummy.push_back(qry);
else
cellQry.push_back(qry);
partition.dummy = std::move(dummy);
std::map<double, std::vector<QueryNested *>> bndQryMapX, bndQryMapY;
{ // X axis
// Get statistics of all query bounds
std::set<double> bndStatSet;
for (const auto qry : cellQry) {
bndStatSet.insert(qry->region.min.x);
bndStatSet.insert(qry->region.max.x);
}
bndStatSet.insert(bound.max.x);
std::vector<double> bndStatVec;
bndStatVec.insert(bndStatVec.end(), bndStatSet.begin(), bndStatSet.end());
// Get statistics of queries related to each bound
for (size_t i = 0; i < bndStatVec.size(); i++) {
auto &qryVec = bndQryMapX[bndStatVec[i]] = std::vector<QueryNested *>();
if (i == bndStatSet.size() - 1) continue;
Boundf curBnd = {{bndStatVec[i], bound.min.y}, {bndStatVec[i + 1], bound.max.y}};
for (const auto qry : subQry)
if (curBnd.Overlaps(qry->region))
qryVec.push_back(qry);
}
// Convert query map to vector for random access
std::vector<std::pair<double, std::vector<QueryNested *>>> bndQryVec;
bndQryVec.insert(bndQryVec.end(), bndQryMapX.begin(), bndQryMapX.end());
// Propose a partition which divides queries by a fixed bound number offset
size_t nBndPerPart = bucketCapacity(bndStatVec.size(), nPartX);
std::unique_ptr<size_t[]> partIdx(new size_t[nPartX + 1]); // indexes in bound statistics vector
for (size_t i = 0; i < nPartX; i++) {
if (i * nBndPerPart >= bndStatVec.size()) {
nPartX = i;
break;
}
partIdx[i] = i * nBndPerPart;
}
partIdx[nPartX] = bndStatVec.size() - 1;
// Define cost function for each proposed axis partition
auto computeCost = [&] (size_t thisIndex, size_t nextIndex) {
size_t weight = 0;
for (size_t i = thisIndex; i < nextIndex; i++)
weight += bndQryVec[i].second.size();
double length = bndStatVec[nextIndex] - bndStatVec[thisIndex];
return weight * length / (bound.max.x - bound.min.x);
};
// Find a partition which evenly partitions X axis by weight through heuristic algorithm
for (size_t i = 1; i < nPartX; i++) {
// Compute current cost of proposed partition
double curCost = computeCost(partIdx[i - 1], partIdx[i]) + computeCost(partIdx[i], partIdx[i + 1]);
// Try all possible partition
size_t leftPartIdx = partIdx[i - 1], nextPartIdx = partIdx[i + 1];
for (size_t curPartIdx = leftPartIdx + 1; curPartIdx < nextPartIdx; curPartIdx++) {
double newCost = computeCost(leftPartIdx, curPartIdx) + computeCost(curPartIdx, nextPartIdx);
if (newCost < curCost) { // better partition
curCost = newCost;
partIdx[i] = curPartIdx;
}
}
}
// Convert index into real number partitions
partition.partX = std::make_unique<double[]>(nPartX + 1);
for (size_t i = 0; i <= nPartX; i++)
partition.partX[i] = bndStatVec[partIdx[i]];
}
{ // Y axis
// Get statistics of all query bounds
std::set<double> bndStatSet;
for (const auto qry : cellQry) {
bndStatSet.insert(qry->region.min.y);
bndStatSet.insert(qry->region.max.y);
}
bndStatSet.insert(bound.max.y);
std::vector<double> bndStatVec;
bndStatVec.insert(bndStatVec.end(), bndStatSet.begin(), bndStatSet.end());
// Get statistics of queries related to each bound
for (size_t i = 0; i < bndStatVec.size(); i++) {
auto &qryVec = bndQryMapY[bndStatVec[i]] = std::vector<QueryNested *>();
if (i == bndStatSet.size() - 1) continue;
Boundf curBnd = {{bound.min.x, bndStatVec[i]}, {bound.max.x, bndStatVec[i + 1]}};
for (const auto qry : subQry)
if (curBnd.Overlaps(qry->region))
qryVec.push_back(qry);
}
// Convert query map to vector for random access
std::vector<std::pair<double, std::vector<QueryNested *>>> bndQryVec;
bndQryVec.insert(bndQryVec.end(), bndQryMapY.begin(), bndQryMapY.end());
// Propose a partition which divides queries by a fixed bound number offset
size_t nBndPerPart = bucketCapacity(bndStatVec.size(), nPartY);
std::unique_ptr<size_t[]> partIdx(new size_t[nPartY + 1]);
for (size_t i = 0; i < nPartY; i++) {
if (i * nBndPerPart >= bndStatVec.size()) {
nPartY = i;
break;
}
partIdx[i] = i * nBndPerPart;
}
partIdx[nPartY] = bndStatVec.size() - 1;
// Define cost function for each proposed axis partition
auto computeCost = [&] (size_t thisIndex, size_t nextIndex) {
size_t weight = 0;
for (size_t i = thisIndex; i < nextIndex; i++)
weight += bndQryVec[i].second.size();
double length = bndStatVec[nextIndex] - bndStatVec[thisIndex];
return weight * length / (bound.max.y - bound.min.y);
};
// Find a partition which evenly partitions Y axis by weight through heuristic algorithm
for (size_t i = 1; i < nPartY; i++) {
// Compute current cost of proposed partition
double curCost = computeCost(partIdx[i - 1], partIdx[i]) + computeCost(partIdx[i], partIdx[i + 1]);
// Try all possible partition
size_t leftPartIdx = partIdx[i - 1], nextPartIdx = partIdx[i + 1];
for (size_t curPartIdx = leftPartIdx + 1; curPartIdx < nextPartIdx; curPartIdx++) {
double newCost = computeCost(leftPartIdx, curPartIdx) + computeCost(curPartIdx, nextPartIdx);
if (newCost < curCost) { // better partition
curCost = newCost;
partIdx[i] = curPartIdx;
}
}
}
// Convert index into real number partitions
partition.partY = std::make_unique<double[]>(nPartY + 1);
for (size_t i = 0; i <= nPartY; i++)
partition.partY[i] = bndStatVec[partIdx[i]];
}
// Generate cells and compute final cost
partition.cost = 0;
partition.cells = std::unique_ptr<std::vector<QueryNested *>[]>(new std::vector<QueryNested *>[nPartX * nPartY]);
for (size_t i = 0; i < nPartX; i++) {
for (size_t j = 0; j < nPartY; j++) {
size_t index = j + i * nPartY;
// Pick up queries between bounds
double thisBndX = partition.partX[i], nextBndX = partition.partX[i + 1];
auto bndIteX = bndQryMapX.find(thisBndX);
std::set<QueryNested *> qrySetX;
while (bndIteX->first != nextBndX) {
qrySetX.insert(bndIteX->second.begin(), bndIteX->second.end());
bndIteX++;
}
double thisBndY = partition.partY[j], nextBndY = partition.partY[j + 1];
auto bndIteY = bndQryMapY.find(thisBndY);
std::set<QueryNested *> qrySetY;
while (bndIteY->first != nextBndY) {
qrySetY.insert(bndIteY->second.begin(), bndIteY->second.end());
bndIteY++;
}
// Find common queries of two axes
auto qryCell = commonElements(qrySetX, qrySetY);
partition.cells[index] = std::vector<QueryNested *>();
if (qryCell.size() > 0) {
size_t weight = qryCell.size();
double prob = (partition.partX[i + 1] - partition.partX[i]) *
(partition.partY[i + 1] - partition.partY[i]);
prob /= bound.Area();
partition.cost += weight * prob;
partition.cells[index] = std::move(qryCell);
}
}
}
return partition;
}
std::vector<Query> APTree::Match(const STObject &obj) const {
// Convert input spatial-textual object to nested one
STObjectNested stObjN{obj.location, std::vector<size_t>()};
for (const auto &kw : obj.keywords)
stObjN.keywords.push_back(dictIndex.find(kw)->second);
std::sort(stObjN.keywords.begin(), stObjN.keywords.end());
// Start match recursion
std::set<QueryNested> queries;
match(stObjN, 0, root, queries);
// Convert nested queries to output struct
std::vector<Query> output;
for (const auto &qry : queries) {
Query oQry{qry.region, std::set<std::string>()};
for (const size_t i : qry.keywords)
oQry.keywords.insert(dict[i]);
output.push_back(std::move(oQry));
}
return output;
}
void APTree::match(const STObjectNested &obj, size_t offset, const Node *node, std::set<QueryNested> &out) const
{
if (node->type == Node::QUERY) {
// Verify queries in query storage and insert the matched ones to output set
for (const auto &qry : node->query->queries)
if (qry.region.Contains(obj.location) && isSubset(obj.keywords, qry.keywords))
out.insert(qry);
} else if (node->type == Node::KEYWORD) {
// Record if certain cut has been visited before
auto nPart = node->keyword->nPart;
auto visited = std::make_unique<bool[]>(nPart);
for (size_t i = 0; i < nPart; i++)
visited[i] = false;
// Find the corresponding cut based on ith word in object keywords
for (size_t i = offset; i < obj.keywords.size(); i++) {
auto cutIdx = node->keyword->Search(obj.keywords[i]);
if (cutIdx == INDEX_NOT_FOUND)
continue;
auto cut = node->keyword->cuts[cutIdx];
if (!visited[cutIdx]) {
visited[cutIdx] = true;
match(obj, i + 1, node->keyword->children[cutIdx].get(), out);
}
}
// Search in dummy cut if it exists
if (node->dummy.get())
match(obj, offset, node->dummy.get(), out);
} else if (node->type == Node::SPATIAL) {
// Find the cell which covers the location of object
auto cellIdx = node->spatial->GetCellIndex(obj.location);
if (cellIdx.x != INDEX_NOT_FOUND && cellIdx.y != INDEX_NOT_FOUND) { // index is valid
size_t vecIdx = cellIdx.y + cellIdx.x * node->spatial->nPartY;
match(obj, offset, node->spatial->cells[vecIdx].get(), out);
}
// Search in dummy cell if it exists
if (node->dummy.get())
match(obj, offset, node->dummy.get(), out);
}
}
/*
Index Maintenance Strategy
Since index maintenance is just briefly introduced in original paper, it should be elaborated on for practical implementation
Algorithm:
# Return new node if reconstructed, or the original one if not
register(node, newQry):
if node is q-node:
if node.Q.size() + newQry.size() < theta_q:
node.Q = Merge node.Q and newQry
return node
else:
subQry := Merge node.Q and newQry
build(newNode, subQry)
return newNode
else: # the same for k-node and s-node
Get statistics of queries
D_KL := Compute KL-Divergence of new node
if D_KL > theta_KL:
subQry := Merge node.Q and newQry
build(newNode, subQry)
return newNode
else:
dmyQry := Find dummy queries in newQry
if dmyQry is not empty:
if node has dummy:
newDummy := register(dummy, dmyQry)
if newDummy != dummy:
Reset dummy node
else:
build(dummy, dmyQry)
for each bucket:
bcktNewQry := Find matched queries in newQry
newBucket := register(bucket, bcktNewQry)
if newBucket != bucket:
Reset bucket node
return node
Modification:
1. Change prototype of private build function to void APTree::build(Node *node, const std::vector<QueryNested *> &subQry)
size_t offset, bool useKw, bool useSp become members in Node
2. Add members recording weights(numbers of queries related) in Node for KL-Divergence computation
*/
void APTree::Register(const std::vector<Query> &newQry)
{
// Convert queries to nested type
std::vector<QueryNested> nstdQry;
for (const auto q : newQry) {
QueryNested nq{ q.region, std::vector<size_t>() };
for (const auto kw : q.keywords)
nq.keywords.push_back(dictIndex[kw]);
nstdQry.push_back(std::move(nq));
}
// Remove repeated queries
std::sort(nstdQry.begin(), nstdQry.end());
auto newEnd = std::unique(nstdQry.begin(), nstdQry.end());
nstdQry.erase(newEnd, nstdQry.end());
// Get nested query pointers
std::vector<QueryNested *> nstdQryPtr;
for (auto &q : nstdQry)
nstdQryPtr.push_back(&q);
// Begin registration recursion
auto newRoot = regist(root, nstdQryPtr); // the whole tree may be reconstructed
if (newRoot != root) {
delete root;
root = newRoot;
}
nQry = collectAndMerge(root, std::vector<QueryNested *>()).size();
}
APTree::Node * APTree::regist(Node *node, const std::vector<QueryNested *> &newQry)
{
if (node->type == Node::QUERY) {
auto &query = node->query->queries;
size_t newSize = query.size() + newQry.size();
if (newSize < theta_Q || (!node->useKw && !node->useSp)) { // keep q-node structure
// Append new queries to q-node
for (const auto q : newQry)
query.push_back(*q);
// Remove repeated queries
std::sort(query.begin(), query.end());
auto newEnd = std::unique(query.begin(), query.end());
query.erase(newEnd, query.end());
return node; // not reconstructed
}
else { // should reconstruct
auto recQry = collectAndMerge(node, newQry);
auto newNode = new Node(*node);
build(newNode, recQry);
return newNode;
}
}
else if (node->type == Node::KEYWORD) {
// Get statistics of newly added queries
std::vector<QueryNested *> dmyQry;
auto nPart = node->keyword->nPart;
auto cutQryStat = std::make_unique<std::vector<QueryNested *>[]>(nPart);
for (size_t i = 0; i < nPart; i++) // initialize stat map
cutQryStat[i] = std::vector<QueryNested *>();
for (const auto q : newQry) {
if (q->keywords.size() <= node->offset) // is dummy query
dmyQry.push_back(q);
else {
auto cutIdx = node->keyword->Search(q->keywords[node->offset]);
if (cutIdx != INDEX_NOT_FOUND) // cut is valid
cutQryStat[cutIdx].push_back(q);
else { // current node should be rebuilt because query falls in gap
auto recQry = collectAndMerge(node, newQry);
auto newNode = new Node(*node);
build(newNode, recQry);
return newNode;
}
}
}
// Compute KL-Divergence D_KL(w_old|w) of current node
// See https://en.wikipedia.org/wiki/Kullback-Leibler_divergence for definition of KL-Divergence
// D_KL(P|Q) = \sum_{x\in X} P(x)*log(P(x)/Q(x))
// In terms of AP-Tree, D_KL(w_old|w) = \sum_{i=1}^f w_old(B_i)*log(w_old(B_i)/w(B_i))
double D_KL = 0;
for (size_t i = 0; i < node->keyword->nPart; i++) {
node->keyword->nAdd[i] += cutQryStat[i].size(); // update number of newly added queries
double wOld = node->keyword->nOld[i], wAdd = node->keyword->nAdd[i];
double bKL = wOld * std::log10(1.0 + wAdd / wOld);
D_KL += bKL;
}
D_KL /= double(nQry); // normalize D_KL to make the comparison between D_KL and theta_KL independent of actual workload
if (D_KL > theta_KL) {
// Reconstruct node if D_KL exceeds threshold theta_KL
auto recQry = collectAndMerge(node, newQry);
auto newNode = new Node(*node);
build(newNode, recQry);
return newNode;
}
else {
// Keep current node but modify it
// Build dummy node if possible
if (dmyQry.size() > 0) {
if (node->dummy.get()) { // previous node has dummy cut
auto newDmyNode = regist(node->dummy.get(), dmyQry);
if (newDmyNode != node->dummy.get())
node->dummy.reset(newDmyNode);
}
else {
node->dummy = std::make_unique<Node>(node->offset + 1, node->bound, false, node->useSp);
build(node->dummy.get(), dmyQry);
}
}
// Distribute queries to corresponding cuts
for (size_t i = 0; i < node->keyword->nPart; i++) {
auto &cutNewQry = cutQryStat[i];
auto oldNode = node->keyword->children[i].get();
auto newNode = regist(oldNode, cutNewQry);
if (newNode != oldNode)
node->keyword->children[i].reset(newNode);
}
return node;
}
}
else {
// Get statistics of newly added queries
size_t nPartX = node->spatial->nPartX, nPartY = node->spatial->nPartY;
std::vector<QueryNested *> dmyQry;
auto cellQryStat = std::make_unique<std::vector<QueryNested *>[]>(nPartX * nPartY);
for (size_t idx = 0; idx < nPartX * nPartY; idx++)
cellQryStat[idx] = std::vector<QueryNested *>();
for (const auto qry : newQry) {
// Pick out dummy query
if (qry->region.Contains(node->bound))
dmyQry.push_back(qry);
// Add query to overlapping cell
for (size_t idx = 0; idx < nPartX * nPartY; idx++)
if (qry->region.Overlaps(node->spatial->cells[idx]->bound))
cellQryStat[idx].push_back(qry);
}
// Compute KL-Divergence of current node
double D_KL = 0;
for (size_t idx = 0; idx < nPartX * nPartY; idx++) {
node->spatial->nAdd[idx] += cellQryStat[idx].size();
double wOld = node->spatial->nOld[idx], wAdd = node->spatial->nAdd[idx];
if (wOld == 0) continue; // account for empty cells
double bKL = wOld * std::log10(1.0 + wAdd / wOld);
D_KL += bKL;
}
D_KL /= double(nQry);
if (D_KL > theta_KL) {
// Reconstruct current node
auto recQry = collectAndMerge(node, newQry);
auto newNode = new Node(*node);
build(newNode, recQry);
return newNode;
}
else {
// Keep current node
// Build dummy node if possible
if (dmyQry.size() > 0) {
if (node->dummy.get()) {
auto newDmyNode = regist(node->dummy.get(), dmyQry);
if (newDmyNode != node->dummy.get())
node->dummy.reset(newDmyNode);
}
else {
node->dummy = std::make_unique<Node>(node->offset, node->bound, node->useKw, false);
build(node->dummy.get(), dmyQry);
}
}
// Distribute queries to corresponding cells
for (size_t idx = 0; idx < nPartX * nPartY; idx++) {
auto &cellNewQry = cellQryStat[idx];
auto newNode = regist(node->spatial->cells[idx].get(), cellNewQry);
if (newNode != node->spatial->cells[idx].get())
node->spatial->cells[idx].reset(newNode);
}
return node;
}
}
}
// Only collect query pointers for selected node, and merge with newly added ones.
// The actual value is fetched only when q-node is constructed.
std::vector<APTree::QueryNested *> APTree::collectAndMerge(const Node *node, const std::vector<QueryNested *> &newQry) const
{
// Begin collecting recursion
std::vector<QueryNested *> out;
collect(node, out);
// Merge newly added queries
out.insert(out.end(), newQry.begin(), newQry.end());
// Remove repeated elements
std::sort(out.begin(), out.end(), [](auto p1, auto p2) { return *p1 < *p2; });
auto newEnd = std::unique(out.begin(), out.end(), [](auto p1, auto p2) { return *p1 == *p2; });
out.erase(newEnd, out.end());
return out;
}
void APTree::collect(const Node *node, std::vector<QueryNested *> &out) const
{
if (node->type == Node::QUERY) {
auto &queries = node->query->queries;
for (auto &q : queries)
out.push_back(&q);
}
else if (node->type == Node::KEYWORD) {
if (node->dummy.get())
collect(node->dummy.get(), out);
for (size_t i = 0; i < node->keyword->nPart; i++)
if (node->keyword->children[i].get())
collect(node->keyword->children[i].get(), out);
}
else if (node->type == Node::SPATIAL) {
if (node->dummy.get())
collect(node->dummy.get(), out);
for (size_t idx = 0; idx < node->spatial->nPartX * node->spatial->nPartY; idx++)
collect(node->spatial->cells[idx].get(), out);
}
} | 43.26903 | 131 | 0.582432 | [
"object",
"vector"
] |
a3e6b6cd63b0ae378aba95d4f4ed822804d643ed | 8,176 | cc | C++ | code/render/materials/surfaceinstance.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/materials/surfaceinstance.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/materials/surfaceinstance.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// surfaceinstance.cc
// (C) 2015-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "surfaceinstance.h"
#include "material.h"
#include "surface.h"
#include "resources/resourcemanager.h"
#include "coregraphics/shaderinstance.h"
#include "surfaceconstant.h"
using namespace CoreGraphics;
namespace Materials
{
__ImplementClass(Materials::SurfaceInstance, 'SUIN', Core::RefCounted);
//------------------------------------------------------------------------------
/**
*/
SurfaceInstance::SurfaceInstance() :
originalSurface(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
SurfaceInstance::~SurfaceInstance()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::Setup(const Ptr<Surface>& surface)
{
n_assert(this->originalSurface == 0);
// set original surface
this->originalSurface = surface;
// create temporary dictionary mapping between shaders and their variables
Util::Dictionary<Util::StringAtom, Util::Array<Ptr<CoreGraphics::ShaderInstance>>> variableToShaderMap;
Util::Dictionary<Util::StringAtom, Util::Array<Frame::BatchGroup::Code>> variableToCodeMap;
Util::Dictionary<Util::StringAtom, Util::Array<Material::MaterialPass>> variableToPassMap;
const Ptr<Material>& materialTemplate = this->originalSurface->materialTemplate;
// get parameters from material
const Util::Dictionary<Util::StringAtom, Material::MaterialParameter>& parameters = materialTemplate->GetParameters();
this->code = this->originalSurface->code;
SizeT numPasses = materialTemplate->GetNumPasses();
IndexT passIndex;
for (passIndex = 0; passIndex < numPasses; passIndex++)
{
// get indexed data from material
const Material::MaterialPass& pass = materialTemplate->GetPassByIndex(passIndex);
const Frame::BatchGroup::Code& code = pass.code;
const Ptr<Shader>& shader = pass.shader;
const Ptr<ShaderInstance>& shdInst = shader->CreateShaderInstance();
// go through our materials parameter list and set them up
IndexT paramIndex;
for (paramIndex = 0; paramIndex < parameters.Size(); paramIndex++)
{
// get parameter name
const Util::StringAtom& paramName = parameters.KeyAtIndex(paramIndex);
const Material::MaterialParameter& param = parameters.ValueAtIndex(paramIndex);
// add to dictionary of parameter
if (!variableToShaderMap.Contains(paramName)) variableToShaderMap.Add(paramName, Util::Array<Ptr<CoreGraphics::ShaderInstance>>());
variableToShaderMap[paramName].Append(shdInst);
if (!variableToCodeMap.Contains(paramName)) variableToCodeMap.Add(paramName, Util::Array<Frame::BatchGroup::Code>());
variableToCodeMap[paramName].Append(code);
if (!variableToPassMap.Contains(paramName)) variableToPassMap.Add(paramName, Util::Array<Material::MaterialPass>());
variableToPassMap[paramName].Append(pass);
}
// add to dictionary
this->shaderInstances.Append(shdInst);
this->shaderInstancesByShader.Add(shader, shdInst);
}
// go through mappings
IndexT mappingIndex;
for (mappingIndex = 0; mappingIndex < variableToPassMap.Size(); mappingIndex++)
{
const Util::StringAtom& paramName = variableToPassMap.KeyAtIndex(mappingIndex);
const Util::Array<Material::MaterialPass>& passes = variableToPassMap.ValueAtIndex(mappingIndex);
const Util::Array<Ptr<CoreGraphics::ShaderInstance>>& shaders = variableToShaderMap.ValueAtIndex(mappingIndex);
//const Util::Array<Frame::BatchGroup::Code>& codes = variableToCodeMap.ValueAtIndex(mappingIndex);
// create a new multi-shader variable container (or surface constant)
Ptr<SurfaceConstant> constant = SurfaceConstant::Create();
// get parameter by name (which is used for its default value)
const Material::MaterialParameter& param = parameters[paramName];
// get the value defined in the surface resource
Surface::SurfaceValueBinding& val = this->originalSurface->staticValues[paramName];
// specially handle default values which are strings
if (val.value.GetType() == Util::Variant::String)
{
Ptr<Resources::ManagedTexture> tex = Resources::ResourceManager::Instance()->CreateManagedResource(CoreGraphics::Texture::RTTI, val.value.GetString() + NEBULA3_TEXTURE_EXTENSION, NULL, true).downcast<Resources::ManagedTexture>();
//this->SetTexture(paramName, tex);
val.value.SetType(Util::Variant::Object);
val.value.SetObject(tex->GetTexture());
}
// setup constant
constant->SetValue(val.value);
constant->Setup(paramName, passes, shaders);
constant->system = param.system;
// add constants to variable lists
this->constants.Append(constant);
this->constantsByName.Add(paramName, constant);
}
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::Discard()
{
this->originalSurface->DiscardInstance(this);
this->originalSurface = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::Cleanup()
{
IndexT i;
for (i = 0; i < this->constants.Size(); i++)
{
this->constants[i]->Discard();
}
for (i = 0; i < this->shaderInstances.Size(); i++)
{
this->shaderInstances[i]->Discard();
}
this->shaderInstances.Clear();
this->shaderInstancesByShader.Clear();
this->constants.Clear();
this->constantsByName.Clear();
this->managedTextures.Clear();
this->originalSurface = 0;
this->code = Materials::SurfaceName::InvalidSurfaceName;
}
//------------------------------------------------------------------------------
/**
*/
const Ptr<CoreGraphics::ShaderInstance>&
SurfaceInstance::GetShaderInstance(const IndexT passIndex)
{
return this->shaderInstances[passIndex];
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::SetValue(const Util::StringAtom& param, const Util::Variant& value)
{
n_assert(param.IsValid());
n_assert(this->constantsByName.Contains(param));
this->constantsByName[param]->SetValue(value);
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::SetTexture(const Util::StringAtom& param, const Ptr<CoreGraphics::Texture>& tex)
{
n_assert(param.IsValid());
n_assert(this->constantsByName.Contains(param));
this->constantsByName[param]->SetTexture(tex);
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::SetTexture(const Util::StringAtom& param, const Ptr<Resources::ManagedTexture>& tex)
{
n_assert(param.IsValid());
DeferredTextureBinding obj;
obj.tex = tex;
obj.var = param;
this->managedTextures.Append(obj);
}
//------------------------------------------------------------------------------
/**
*/
void
SurfaceInstance::Apply(const IndexT passIndex)
{
IndexT i;
// 'touch' textures which may not have been loaded when the material was first set up
for (i = 0; i < this->managedTextures.Size(); i++)
{
const DeferredTextureBinding& bind = this->managedTextures[i];
if (!bind.tex->IsPlaceholder())
{
this->constantsByName[bind.var]->SetTexture(bind.tex->GetTexture());
this->managedTextures.EraseIndex(i);
i--;
}
}
const Ptr<CoreGraphics::ShaderInstance>& shdInst = this->shaderInstances[passIndex];
for (i = 0; i < this->constants.Size(); i++)
{
this->constants[i]->Apply(passIndex);
}
// get shader instance by code
//this->shaderInstancesByCode[group]->Apply();
shdInst->Commit();
}
} // namespace Materials | 34.066667 | 241 | 0.607021 | [
"object"
] |
a3ec09a747c661b4ef4c1a07803e0f6884a95cc9 | 14,265 | cxx | C++ | Libs/Alignment/ICPRigid3DMeshRegistration.cxx | amylenz/ShapeWorks | 78c2ee067a23e31f5b83d0121e60addb1b0bf462 | [
"MIT"
] | null | null | null | Libs/Alignment/ICPRigid3DMeshRegistration.cxx | amylenz/ShapeWorks | 78c2ee067a23e31f5b83d0121e60addb1b0bf462 | [
"MIT"
] | null | null | null | Libs/Alignment/ICPRigid3DMeshRegistration.cxx | amylenz/ShapeWorks | 78c2ee067a23e31f5b83d0121e60addb1b0bf462 | [
"MIT"
] | null | null | null |
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: IcpRegid3DRegistration.cxx
Language: C++
Date: $Date: 2011/03/23 22:40:15 $
Version: $Revision: 1.1 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "vtkImageImport.h"
#include "vtkImageExport.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper.h"
#include "vtkContourFilter.h"
#include "vtkImageData.h"
#include "vtkDataSet.h"
#include "vtkProperty.h"
#include "vtkPolyDataWriter.h"
#include "vtkPolyDataReader.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkActor.h"
#include "vtkImagePlaneWidget.h"
#include "vtkCellPicker.h"
#include "vtkSmartPointer.h"
#include "vtkTransform.h"
#include "vtkVertexGlyphFilter.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkIterativeClosestPointTransform.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkLandmarkTransform.h"
#include "vtkMath.h"
#include "tinyxml.h"
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char * argv [] )
{
// check input
if( argc < 2 )
{
std::cerr << "-------------------------------" << std::endl;
std::cerr << "ICPRigid3DMeshRegistration " << std::endl;
std::cerr << "-------------------------------" << std::endl;
std::cerr << "Performs iterative closed point (ICP) rigid registration on a pair of vtk meshes." << std::endl << std::endl;
std::cerr << "It uses a parameter file that would enable to specify the source mesh (moving) and the target mesh (fixed)" << std::endl;
std::cerr << "to be used to estimated the rigid transformation matrix then apply the same transformation on other meshes defined " << std::endl;
std::cerr << "in the source mesh domain to be mapped to the target domain." << std::endl;
std::cerr << "parameter file tags are as follows:" << std::endl;
std::cerr << "\t - source_mesh: vtk filename of the moving mesh" << std::endl;
std::cerr << "\t - target_mesh: vtk filename of the fixed mesh" << std::endl;
std::cerr << "\t - out_mesh : vtk filename of the aligned moving mesh to be save" << std::endl;
std::cerr << "\t - out_transform : txt filename to save the estimated transformation" << std::endl;
std::cerr << "\t - mode : Registration mode rigid, similarity, affine (default: similarity) " << std::endl;
std::cerr << "\t - source_meshes: (optional) a list of vtk filenames for meshes defined in the source mesh domain " << std::endl;
std::cerr << "\t \t to be mapped to the target domain using the same transformation matrix estimated." << std::endl;
std::cerr << "\t - out_meshes : a list vtk filenames to save source_meshes after applying the transformation matrix." << std::endl;
std::cerr << "\t - icp_iterations: number of iterations" << std::endl;
std::cerr << "\t - debug: verbose debugging information" << std::endl;
std::cerr << "\t - visualize: display the resulting alignment" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " paramfile " << std::endl;
return EXIT_FAILURE;
}
std::string sourceMeshFilename;
std::string targetMeshFilename;
std::string outMeshFilename;
std::vector< std::string > sourceMeshesFilenames; sourceMeshesFilenames.clear();
std::vector< std::string > outMeshesFilenames; outMeshesFilenames.clear();
unsigned int icpIterations = 10;
bool debug = false;
bool visualize = false;
std::string mode = "similarity";
std::string out_transform;
// read parameters
TiXmlDocument doc(argv[1]);
bool loadOkay = doc.LoadFile();
if (loadOkay)
{
TiXmlHandle docHandle( &doc );
TiXmlElement *elem;
std::istringstream inputsBuffer;
std::string filename("/dev/null\0");
elem = docHandle.FirstChild( "source_mesh" ).Element();
if (elem)
{
inputsBuffer.str(elem->GetText());
inputsBuffer >> sourceMeshFilename;
inputsBuffer.clear();
inputsBuffer.str("");
}
else
{
std::cerr << "No source mesh to process!" << std::endl;
return EXIT_FAILURE;
}
elem = docHandle.FirstChild( "target_mesh" ).Element();
if (elem)
{
inputsBuffer.str(elem->GetText());
inputsBuffer >> targetMeshFilename;
inputsBuffer.clear();
inputsBuffer.str("");
}
else
{
std::cerr << "No target mesh to process!" << std::endl;
return EXIT_FAILURE;
}
elem = docHandle.FirstChild( "out_mesh" ).Element();
if (elem)
{
inputsBuffer.str(elem->GetText());
inputsBuffer >> outMeshFilename;
inputsBuffer.clear();
inputsBuffer.str("");
}
else
{
std::cerr << "No output mesh specified to save output!" << std::endl;
return EXIT_FAILURE;
}
elem = docHandle.FirstChild( "out_transform" ).Element();
if (elem)
{
inputsBuffer.str(elem->GetText());
inputsBuffer >> out_transform;
inputsBuffer.clear();
inputsBuffer.str("");
}
else
{
std::cerr << "No output transform file specified to save output!" << std::endl;
return EXIT_FAILURE;
}
elem = docHandle.FirstChild( "source_meshes" ).Element();
if (elem)
{
inputsBuffer.str(elem->GetText());
while (inputsBuffer >> filename)
{
sourceMeshesFilenames.push_back(filename);
}
inputsBuffer.clear();
inputsBuffer.str("");
}
elem = docHandle.FirstChild( "out_meshes" ).Element();
if (elem)
{
inputsBuffer.str(elem->GetText());
while (inputsBuffer >> filename)
{
outMeshesFilenames.push_back(filename);
}
inputsBuffer.clear();
inputsBuffer.str("");
}
elem = docHandle.FirstChild( "mode" ).Element();
if (elem)
{
mode = elem->GetText();
}
elem = docHandle.FirstChild( "icp_iterations" ).Element();
if (elem)
{
icpIterations = atoi(elem->GetText());
}
elem = docHandle.FirstChild( "debug" ).Element();
if (elem)
{
debug = atoi(elem->GetText()) == 1 ? true : false;
}
elem = docHandle.FirstChild( "visualize" ).Element();
if (elem)
{
visualize = atoi(elem->GetText()) == 1 ? true : false;
}
}
vtkSmartPointer<vtkPolyDataReader> targetReader = vtkSmartPointer<vtkPolyDataReader>::New();
targetReader->SetFileName( targetMeshFilename.c_str() );
targetReader->Update();
vtkSmartPointer<vtkPolyDataReader> movingReader = vtkSmartPointer<vtkPolyDataReader>::New();
movingReader->SetFileName(sourceMeshFilename.c_str());
movingReader->Update();
vtkSmartPointer<vtkPolyData> target = targetReader->GetOutput();
vtkSmartPointer<vtkPolyData> moving = movingReader->GetOutput();
// Setup ICP transform
vtkSmartPointer<vtkIterativeClosestPointTransform> icp =
vtkSmartPointer<vtkIterativeClosestPointTransform>::New();
icp->SetSource(moving);
icp->SetTarget(target);
if(mode.compare("rigid") == 0)
icp->GetLandmarkTransform()->SetModeToRigidBody();
if(mode.compare("similarity") == 0)
icp->GetLandmarkTransform()->SetModeToSimilarity();
if(mode.compare("affine") == 0)
icp->GetLandmarkTransform()->SetModeToAffine();
icp->SetMaximumNumberOfIterations(icpIterations);
icp->StartByMatchingCentroidsOn();
if(debug)
{
icp->SetDebug(1);
icp->SetMaximumMeanDistance(1e-5);
icp->CheckMeanDistanceOn();
}
icp->Modified();
icp->Update();
std::cout << "Mean dist : " << icp->GetMaximumMeanDistance() << std::endl;
vtkSmartPointer<vtkTransformPolyDataFilter> icpTransformFilter =
vtkSmartPointer<vtkTransformPolyDataFilter>::New();
icpTransformFilter->SetInputData(moving);
icpTransformFilter->SetTransform(icp);
icpTransformFilter->Update();
//Transform Segmentation
// Get the resulting transformation matrix (this matrix takes the source points to the target points)
vtkSmartPointer<vtkMatrix4x4> transformationMatrix = icp->GetMatrix();
std::ofstream ofs(out_transform.c_str());
for(unsigned int i = 0 ; i < 4 ; i++)
{
for(unsigned int j = 0 ; j < 4 ; j++)
ofs << transformationMatrix->GetElement(i,j) << " ";
ofs << "\n";
}
ofs.close();
std::cout << "The resulting transformation matrix is: " << *transformationMatrix << std::endl;
vtkTransform* transform = vtkTransform::New();
transform->SetMatrix(transformationMatrix);
vtkTransformPolyDataFilter* transformer = vtkTransformPolyDataFilter::New();
transformer->SetInputConnection( movingReader->GetOutputPort());
transformer->SetTransform( transform );
transformer->Update();
vtkSmartPointer<vtkPolyData> solution = vtkSmartPointer<vtkPolyData>::New();
solution = transformer->GetOutput();
vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
writer->SetFileName(outMeshFilename.c_str());
writer->SetInputConnection(transformer->GetOutputPort());
writer->Update();
//---------------------------------------------------
// VTK Render pipeline.
//---------------------------------------------------
if(visualize)
{
vtkRenderer* renderer = vtkRenderer::New();
vtkRenderWindow* renWin = vtkRenderWindow::New();
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
renWin->SetSize(500,500);
renWin->AddRenderer(renderer);
iren->SetRenderWindow(renWin);
renderer->SetBackground(0.4392, 0.5020, 0.5647);
vtkPolyDataMapper* tarMapper = vtkPolyDataMapper::New();
vtkActor* tarActor = vtkActor::New();
tarActor->SetMapper( tarMapper );
tarMapper->SetInputData( target );
tarMapper->ScalarVisibilityOff();
vtkPolyDataMapper* movMapper = vtkPolyDataMapper::New();
vtkActor* movActor = vtkActor::New();
movActor->SetMapper(movMapper);
movMapper->SetInputData(moving);
movMapper->ScalarVisibilityOff();
vtkPolyDataMapper* solMapper = vtkPolyDataMapper::New();
vtkActor* solActor = vtkActor::New();
solActor->SetMapper(solMapper);
solMapper->SetInputData(solution);
solMapper->ScalarVisibilityOff();
vtkProperty *targetProperty = vtkProperty::New();
targetProperty->SetAmbient(0.1);
targetProperty->SetDiffuse(0.1);
targetProperty->SetSpecular(0.5);
targetProperty->SetColor(0.0,0.0,1.0);
targetProperty->SetLineWidth(2.0);
targetProperty->SetRepresentationToSurface();
vtkProperty * movingProperty = vtkProperty::New();
movingProperty->SetAmbient(0.1);
movingProperty->SetDiffuse(0.1);
movingProperty->SetSpecular(0.5);
movingProperty->SetColor(1.0,0.0,0.0);
movingProperty->SetLineWidth(2.0);
movingProperty->SetRepresentationToSurface();
vtkProperty * solutionProperty = vtkProperty::New();
solutionProperty->SetAmbient(0.1);
solutionProperty->SetDiffuse(0.1);
solutionProperty->SetSpecular(0.5);
solutionProperty->SetColor(0.0,1.0,0.0);
solutionProperty->SetLineWidth(2.0);
solutionProperty->SetRepresentationToSurface();
movActor->SetProperty( movingProperty);
tarActor->SetProperty( targetProperty);
solActor->SetProperty( solutionProperty);
renderer->AddActor( movActor);
renderer->AddActor( tarActor);
renderer->AddActor( solActor);
renderer->ResetCamera();
renWin->Render();
iren->Start();
// Release VTK components
tarActor->Delete();
movActor->Delete();
solActor->Delete();
targetProperty->Delete();
movingProperty->Delete();
solutionProperty->Delete();
tarMapper->Delete();
movMapper->Delete();
solMapper->Delete();
renWin->Delete();
renderer->Delete();
iren->Delete();
}
if(sourceMeshesFilenames.size() > 0)
{
for (unsigned meshNo = 0; meshNo < sourceMeshesFilenames.size(); meshNo++)
{
vtkSmartPointer<vtkPolyDataReader> movingReader2 = vtkSmartPointer<vtkPolyDataReader>::New();
movingReader2->SetFileName(sourceMeshesFilenames[meshNo].c_str());
movingReader2->Update();
vtkTransformPolyDataFilter* transformer2 = vtkTransformPolyDataFilter::New();
transformer2->SetInputConnection( movingReader2->GetOutputPort());
transformer2->SetTransform( transform );
transformer2->Update();
vtkSmartPointer<vtkPolyData> solution2 = vtkSmartPointer<vtkPolyData>::New();
solution2 = transformer2->GetOutput();
vtkSmartPointer<vtkPolyDataWriter> writer2 = vtkSmartPointer<vtkPolyDataWriter>::New();
writer2->SetFileName(outMeshesFilenames[meshNo].c_str());
writer2->SetInputConnection(transformer2->GetOutputPort());
writer2->Update();
}
}
return 0;
}
| 35.04914 | 152 | 0.610585 | [
"mesh",
"render",
"vector",
"transform"
] |
a3ef18cf8c19da94b537bade4a2f7c9f7401a6e9 | 3,329 | hpp | C++ | src/GDALDatasetReader.hpp | a4chet/cesium-terrain-builder | ef70212c05d301fa7ad0a497a06765eaec663572 | [
"Apache-2.0"
] | 1 | 2021-08-03T02:19:29.000Z | 2021-08-03T02:19:29.000Z | src/GDALDatasetReader.hpp | a4chet/cesium-terrain-builder | ef70212c05d301fa7ad0a497a06765eaec663572 | [
"Apache-2.0"
] | 1 | 2020-12-07T23:27:48.000Z | 2020-12-26T23:00:45.000Z | src/GDALDatasetReader.hpp | a4chet/cesium-terrain-builder | ef70212c05d301fa7ad0a497a06765eaec663572 | [
"Apache-2.0"
] | 2 | 2021-08-03T02:19:30.000Z | 2021-11-02T11:50:41.000Z | #ifndef GDALDATASETREADER_HPP
#define GDALDATASETREADER_HPP
/*******************************************************************************
* Copyright 2018 GeoData <geodata@soton.ac.uk>
*
* 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.
*******************************************************************************/
/**
* @file GDALDatasetReader.hpp
* @brief This declares the `GDALDatasetReader` class
*/
#include <string>
#include <vector>
#include "gdalwarper.h"
#include "TileCoordinate.hpp"
#include "GDALTiler.hpp"
namespace ctb {
class GDALDatasetReader;
class GDALDatasetReaderWithOverviews;
}
/**
* @brief Read raster tiles from a GDAL Dataset
*
* This abstract base class is associated with a GDAL dataset.
* It allows to read a region of the raster according to
* a region defined by a Tile Coordinate.
*
* We can define our own
*/
class CTB_DLL ctb::GDALDatasetReader {
public:
/// Read a region of raster heights into an array for the specified Dataset and Coordinate
static float *
readRasterHeights(const GDALTiler &tiler, GDALDataset *dataset, const TileCoordinate &coord, ctb::i_tile tileSizeX, ctb::i_tile tileSizeY);
/// Read a region of raster heights into an array for the specified Dataset and Coordinate
virtual float *
readRasterHeights(GDALDataset *dataset, const TileCoordinate &coord, ctb::i_tile tileSizeX, ctb::i_tile tileSizeY) = 0;
protected:
/// Create a raster tile from a tile coordinate
static GDALTile *
createRasterTile(const GDALTiler &tiler, GDALDataset *dataset, const TileCoordinate &coord);
/// Create a VTR raster overview from a GDALDataset
static GDALDataset *
createOverview(const GDALTiler &tiler, GDALDataset *dataset, const TileCoordinate &coord, int overviewIndex);
};
/**
* @brief Implements a GDALDatasetReader that takes care of 'Integer overflow' errors.
*
* This class creates Overviews to avoid 'Integer overflow' errors when extracting
* raster data.
*/
class CTB_DLL ctb::GDALDatasetReaderWithOverviews : public ctb::GDALDatasetReader {
public:
/// Instantiate a GDALDatasetReaderWithOverviews
GDALDatasetReaderWithOverviews(const GDALTiler &tiler):
poTiler(tiler),
mOverviewIndex(0) {}
/// The destructor
~GDALDatasetReaderWithOverviews();
/// Read a region of raster heights into an array for the specified Dataset and Coordinate
virtual float *
readRasterHeights(GDALDataset *dataset, const TileCoordinate &coord, ctb::i_tile tileSizeX, ctb::i_tile tileSizeY) override;
/// Releases all overviews
void reset();
protected:
/// The tiler to use
const GDALTiler &poTiler;
/// List of VRT Overviews of the underlying GDAL dataset
std::vector<GDALDataset *> mOverviews;
/// Current VRT Overview
int mOverviewIndex;
};
#endif /* GDALDATASETREADER_HPP */
| 32.960396 | 141 | 0.71523 | [
"vector"
] |
a3f0b67608e91b0a731d9aa44b21dcac7f5e7ac5 | 723 | cc | C++ | P16497.cc | daily-boj/kiwiyou | ceca96ddfee95708871af67d1682048e0bed0257 | [
"Unlicense"
] | 6 | 2020-04-08T09:04:57.000Z | 2021-11-16T07:30:24.000Z | P16497.cc | daily-boj/kiwiyou | ceca96ddfee95708871af67d1682048e0bed0257 | [
"Unlicense"
] | null | null | null | P16497.cc | daily-boj/kiwiyou | ceca96ddfee95708871af67d1682048e0bed0257 | [
"Unlicense"
] | 2 | 2020-04-16T05:32:06.000Z | 2020-05-28T13:40:56.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
int count;
cin >> count;
vector<int> begins{count};
vector<int> ends{count};
while (count--) {
int from, to;
cin >> from >> to;
begins.push_back(from);
ends.push_back(to);
}
int books;
cin >> books;
for (int i = 1; i <= 31; ++i) {
for (auto& end : ends) {
if (i == end) {
++books;
}
}
for (auto& begin : begins) {
if (i == begin) {
--books;
if (books < 0) {
cout << '0';
return 0;
}
}
}
}
cout << '1';
} | 21.264706 | 36 | 0.366528 | [
"vector"
] |
a3f49784b92ee377d08135e2392c56c7ac434b38 | 7,810 | cpp | C++ | test/performance/core/simd/view_to_simd_chunk_benchmark.cpp | SGSSGene/seqan3 | ab9ccb94d02c2f27b9b73b134ee2713de91bf722 | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | test/performance/core/simd/view_to_simd_chunk_benchmark.cpp | SGSSGene/seqan3 | ab9ccb94d02c2f27b9b73b134ee2713de91bf722 | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | test/performance/core/simd/view_to_simd_chunk_benchmark.cpp | SGSSGene/seqan3 | ab9ccb94d02c2f27b9b73b134ee2713de91bf722 | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <deque>
#include <iterator>
#include <list>
#include <vector>
#include <benchmark/benchmark.h>
#include <seqan3/alphabet/concept.hpp>
#include <seqan3/alphabet/nucleotide/dna4.hpp>
#include <seqan3/core/simd/concept.hpp>
#include <seqan3/core/simd/simd_traits.hpp>
#include <seqan3/core/simd/simd.hpp>
#include <seqan3/core/simd/view_to_simd.hpp>
#include <seqan3/range/container/aligned_allocator.hpp>
#include <seqan3/range/views/to.hpp>
#include <seqan3/range/views/zip.hpp>
#include <seqan3/std/algorithm>
#include <seqan3/std/ranges>
#include <seqan3/test/performance/sequence_generator.hpp>
using namespace seqan3;
// ============================================================================
// naive implementation without condition inside of hot loop
// ============================================================================
template <typename container_t, typename simd_t>
void to_simd_naive_wo_condition(benchmark::State& state)
{
constexpr size_t simd_length = simd_traits<simd_t>::length;
// Preparing the sequences
std::vector<container_t> sequences;
sequences.resize(simd_length);
for (size_t i = 0; i < simd_length; ++i)
std::ranges::copy(test::generate_sequence<dna4>(500, 10), std::ranges::back_inserter(sequences[i]));
size_t value = 0;
for (auto _ : state)
{
// First sort the sequences by their lengths, but only use a proxy.
auto sorted_sequences =
std::views::transform(views::zip(sequences, std::views::iota(0u, simd_length)), [] (auto && tpl)
{
return std::pair{std::ranges::size(std::get<0>(tpl)), std::get<1>(tpl)};
})
| views::to<std::vector<std::pair<size_t, size_t>>>;
std::ranges::sort(sorted_sequences);
// Prepare the simd representation and transform the set.
std::vector<simd_t, aligned_allocator<simd_t, sizeof(simd_t)>> v;
v.resize(sorted_sequences.back().first, fill<simd_t>(alphabet_size<dna4>));
size_t start_offset = 0;
for (size_t k = 0; k < sorted_sequences.size(); ++k)
{
for (size_t i = start_offset; i < sorted_sequences[k].first; ++i)
for (size_t j = k; j < simd_length; ++j)
v[i][sorted_sequences[j].second] = seqan3::to_rank(sequences[sorted_sequences[j].second][i]);
start_offset = sorted_sequences[k].first;
}
for (simd_t & vec : v)
value += vec[0];
}
state.counters["value"] = value;
}
// runs with contiguous_range
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::vector<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::vector<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::vector<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::vector<dna4>, simd_type_t<int64_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::deque<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::deque<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::deque<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd_naive_wo_condition, std::deque<dna4>, simd_type_t<int64_t>);
// ============================================================================
// naive implementation with condition inside of hot loop
// ============================================================================
template <typename container_t, typename simd_t>
void to_simd_naive_w_condition(benchmark::State& state)
{
constexpr size_t simd_length = simd_traits<simd_t>::length;
// Preparing the sequences
std::vector<container_t> sequences;
sequences.resize(simd_length);
for (size_t i = 0; i < simd_length; ++i)
std::ranges::copy(test::generate_sequence<dna4>(500, 10), std::ranges::back_inserter(sequences[i]));
size_t value = 0;
for (auto _ : state)
{
size_t max_size = std::ranges::size(*(std::ranges::max_element(sequences, [] (auto const & lhs, auto const & rhs)
{
return std::ranges::size(lhs) < std::ranges::size(rhs);
})));
std::vector<simd_t, aligned_allocator<simd_t, sizeof(simd_t)>> v;
v.resize(max_size, fill<simd_t>(alphabet_size<dna4>));
for (size_t i = 0; i < max_size; ++i)
for (size_t j = 0; j < simd_length; ++j)
v[i][j] = (i < sequences[j].size()) ? seqan3::to_rank(sequences[j][i]) : 0;
for (simd_t & vec : v)
value += vec[0];
}
state.counters["value"] = value;
}
// runs with contiguous_range
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::vector<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::vector<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::vector<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::vector<dna4>, simd_type_t<int64_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::deque<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::deque<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::deque<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd_naive_w_condition, std::deque<dna4>, simd_type_t<int64_t>);
// ============================================================================
// view implementation
// ============================================================================
template <typename container_t, typename simd_t>
void to_simd(benchmark::State& state)
{
// Preparing the sequences
std::vector<container_t> sequences;
sequences.resize(simd_traits<simd_t>::length);
for (size_t i = 0; i < simd_traits<simd_t>::length; ++i)
std::ranges::copy(test::generate_sequence<dna4>(500, 10), std::ranges::back_inserter(sequences[i]));
size_t value = 0;
for (auto _ : state)
{
for (auto && chunk : sequences | views::to_simd<simd_t>)
for (simd_t const & vec : chunk)
value += vec[0];
}
state.counters["value"] = value;
}
// runs with contiguous_range
BENCHMARK_TEMPLATE(to_simd, std::vector<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd, std::vector<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd, std::vector<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd, std::vector<dna4>, simd_type_t<int64_t>);
BENCHMARK_TEMPLATE(to_simd, std::deque<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd, std::deque<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd, std::deque<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd, std::deque<dna4>, simd_type_t<int64_t>);
// runs without contiguous_range
BENCHMARK_TEMPLATE(to_simd, std::list<dna4>, simd_type_t<int8_t>);
BENCHMARK_TEMPLATE(to_simd, std::list<dna4>, simd_type_t<int16_t>);
BENCHMARK_TEMPLATE(to_simd, std::list<dna4>, simd_type_t<int32_t>);
BENCHMARK_TEMPLATE(to_simd, std::list<dna4>, simd_type_t<int64_t>);
// ============================================================================
// run
// ============================================================================
BENCHMARK_MAIN();
| 42.216216 | 121 | 0.628681 | [
"vector",
"transform"
] |
a3f7caa595176084ed3808023cdbdda953d7eb2a | 5,696 | cpp | C++ | kernel/src/modelingTools/LagrangianRheonomousR.cpp | fperignon/sandbox | 649f09d6db7bbd84c2418de74eb9453c0131f070 | [
"Apache-2.0"
] | null | null | null | kernel/src/modelingTools/LagrangianRheonomousR.cpp | fperignon/sandbox | 649f09d6db7bbd84c2418de74eb9453c0131f070 | [
"Apache-2.0"
] | null | null | null | kernel/src/modelingTools/LagrangianRheonomousR.cpp | fperignon/sandbox | 649f09d6db7bbd84c2418de74eb9453c0131f070 | [
"Apache-2.0"
] | null | null | null |
/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2020 INRIA.
*
* 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 "LagrangianRheonomousR.hpp"
#include "SiconosAlgebraProd.hpp" // for matrix-vector prod
#include "Interaction.hpp"
#include "LagrangianDS.hpp"
#include "BlockVector.hpp"
#include "SimulationGraphs.hpp"
//#define DEBUG_STDOUT
//#define DEBUG_MESSAGES
#include "debug.h"
using namespace RELATION;
// constructor from a set of data
LagrangianRheonomousR::LagrangianRheonomousR(const std::string& pluginh, const std::string& pluginJacobianhq, const std::string& pluginDoth):
LagrangianR(RheonomousR)
{
_zeroPlugin();
// h
setComputehFunction(SSLH::getPluginName(pluginh), SSLH::getPluginFunctionName(pluginh));
_pluginJachq->setComputeFunction(pluginJacobianhq);
// hDot
setComputehDotFunction(SSLH::getPluginName(pluginDoth), SSLH::getPluginFunctionName(pluginDoth));
}
void LagrangianRheonomousR::initialize(Interaction& inter)
{
if(!_jachq)
{
unsigned int sizeY = inter.dimension();
unsigned int sizeDS = inter.getSizeOfDS();
_jachq.reset(new SimpleMatrix(sizeY, sizeDS));
}
}
void LagrangianRheonomousR::checkSize(Interaction& inter)
{
LagrangianR::checkSize(inter);
}
void LagrangianRheonomousR::setComputehDotFunction(const std::string& pluginPath, const std::string& functionName)
{
_pluginhDot->setComputeFunction(pluginPath, functionName);
}
void LagrangianRheonomousR::_zeroPlugin()
{
LagrangianR::_zeroPlugin();
_pluginhDot.reset(new PluggedObject());
}
void LagrangianRheonomousR::computeh(double time, const BlockVector& q, BlockVector& z, SiconosVector& y)
{
DEBUG_PRINT(" LagrangianRheonomousR::computeh(double time,Interaction& inter, SP::BlockVector q, SP::BlockVector z)");
// arg= time. Unused in this function but required for interface.
if(_pluginh->fPtr)
{
auto qp = q.prepareVectorForPlugin();
auto zp = z.prepareVectorForPlugin();
((FPtr4)(_pluginh->fPtr))(qp->size(), &(*qp)(0), time, y.size(), &(y)(0), zp->size(), &(*zp)(0));
z = *zp;
}
}
void LagrangianRheonomousR::computehDot(double time, const BlockVector& q, BlockVector& z)
{
if(_hDot && _pluginhDot->fPtr)
{
auto qp = q.prepareVectorForPlugin();
auto zp = z.prepareVectorForPlugin();
((FPtr4)(_pluginhDot->fPtr))(qp->size(), &(*qp)(0), time, _hDot->size(), &(*_hDot)(0), zp->size(), &(*zp)(0));
z = *zp;
}
}
void LagrangianRheonomousR::computeJachq(double time, const BlockVector& q, BlockVector& z)
{
if(_jachq && _pluginJachq->fPtr)
{
auto qp = q.prepareVectorForPlugin();
auto zp = z.prepareVectorForPlugin();
((FPtr4)(_pluginJachq->fPtr))(qp->size(), &(*qp)(0), time, _jachq->size(0), &(*_jachq)(0, 0), zp->size(), &(*zp)(0));
z = *zp;
}
}
void LagrangianRheonomousR::computeOutput(double time, Interaction& inter, unsigned int derivativeNumber)
{
VectorOfBlockVectors& DSlink = inter.linkToDSVariables();
SiconosVector& y = *inter.y(derivativeNumber);
if(derivativeNumber == 0)
computeh(time, *DSlink[LagrangianR::q0], *DSlink[LagrangianR::z], y);
else
{
computeJachq(time, *DSlink[LagrangianR::q0], *DSlink[LagrangianR::z]);
if(derivativeNumber == 1)
{
if(!_hDot)
{
unsigned int sizeY = inter.dimension();
_hDot.reset(new SiconosVector(sizeY));
}
// Computation of the partial derivative w.r.t time of h(q,t)
computehDot(time, *DSlink[LagrangianR::q0], *DSlink[LagrangianR::z]);
assert(_jachq);
// Computation of the partial derivative w.r.t q of h(q,t) : \nabla_q h(q,t) \dot q
prod(*_jachq, *DSlink[LagrangianR::q1], y);
// Sum of the terms
y += *_hDot;
}
else if(derivativeNumber == 2)
{
assert(_jachq);
prod(*_jachq, *DSlink[LagrangianR::q2], y); // Approx:, ...
// \warning : the computation of y[2] (in event-driven
// simulation for instance) is approximated by y[2] =
// Jach[0]q[2]. For the moment, other terms are neglected
// (especially, partial derivatives with respect to time).
}
else
THROW_EXCEPTION("LagrangianRheonomousR::computeOutput(double time, Interaction& inter, InteractionProperties& interProp, unsigned int derivativeNumber) index >2 not yet implemented.");
}
}
void LagrangianRheonomousR::computeInput(double time, Interaction& inter, unsigned int level)
{
VectorOfBlockVectors& DSlink = inter.linkToDSVariables();
computeJachq(time, *DSlink[LagrangianR::q0], *DSlink[LagrangianR::z]);
// get lambda of the concerned interaction
SiconosVector& lambda = *inter.lambda(level);
// data[name] += trans(G) * lambda
prod(lambda, *_jachq, *DSlink[LagrangianR::p0 + level], false);
}
void LagrangianRheonomousR::computeJach(double time, Interaction& inter)
{
VectorOfBlockVectors& DSlink = inter.linkToDSVariables();
computeJachq(time, *DSlink[LagrangianR::q0], *DSlink[LagrangianR::z]);
// computeJachqDot(time, inter);
// computeDotJachq(time, q, z);
// computeJachlambda(time, inter);
computehDot(time, *DSlink[LagrangianR::q0], *DSlink[LagrangianR::z]);
}
| 33.904762 | 191 | 0.702072 | [
"vector"
] |
a3fa8746fd59eca38f539db08f18d1916fd0daaf | 1,636 | hpp | C++ | installed/x86-windows/include/mongocxx/options/pool.hpp | langxgm/vcpkg | b14b93eba876ceb71d5903f8a473c8be0bac9524 | [
"MIT"
] | 14 | 2018-06-16T04:49:50.000Z | 2021-04-10T03:18:40.000Z | installed/x86-windows/include/mongocxx/options/pool.hpp | langxgm/vcpkg | b14b93eba876ceb71d5903f8a473c8be0bac9524 | [
"MIT"
] | null | null | null | installed/x86-windows/include/mongocxx/options/pool.hpp | langxgm/vcpkg | b14b93eba876ceb71d5903f8a473c8be0bac9524 | [
"MIT"
] | 7 | 2018-06-14T10:15:32.000Z | 2020-11-06T17:07:09.000Z | // Copyright 2016 MongoDB 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.
#pragma once
#include <mongocxx/options/client.hpp>
#include <mongocxx/config/prelude.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
namespace options {
///
/// Class representing the optional arguments to a MongoDB driver pool object. Pool options
/// logically extend client options.
///
class MONGOCXX_API pool {
public:
///
/// Constructs a new pool options object. Note that options::pool is implictly convertible from
/// options::client.
///
/// @param client_opts
/// The client options.
///
pool(client client_opts = client());
///
/// The current client options.
///
/// @return The client options.
///
const client& client_opts() const;
private:
client _client_opts;
friend MONGOCXX_API bool MONGOCXX_CALL operator==(const pool&, const pool&);
friend MONGOCXX_API bool MONGOCXX_CALL operator!=(const pool&, const pool&);
};
} // namespace options
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
#include <mongocxx/config/postlude.hpp>
| 27.728814 | 99 | 0.712103 | [
"object"
] |
4301699e3aa349a243ef7ebde8fa649817a7e5e4 | 6,926 | hpp | C++ | src/test/utility.hpp | mcol/cmdstan | f85d83576280447bb3765d38c0dc765147833058 | [
"BSD-3-Clause"
] | 1 | 2020-05-04T17:15:40.000Z | 2020-05-04T17:15:40.000Z | src/test/utility.hpp | mcol/cmdstan | f85d83576280447bb3765d38c0dc765147833058 | [
"BSD-3-Clause"
] | null | null | null | src/test/utility.hpp | mcol/cmdstan | f85d83576280447bb3765d38c0dc765147833058 | [
"BSD-3-Clause"
] | null | null | null | #ifndef TEST__MODELS__UTILITY_HPP
#define TEST__MODELS__UTILITY_HPP
#include <stdexcept>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
namespace cmdstan {
namespace test {
// only counts non-overlapping matches; after match, advances to
// end of match;
// empty target returns -1
int count_matches(const std::string& target,
const std::string& s) {
if (target.size() == 0) return -1; // error
int count = 0;
for (size_t pos = 0; (pos = s.find(target,pos)) != std::string::npos; pos += target.size())
++count;
return count;
}
/**
* Gets the path separator for the OS.
*
* @return '\' for Windows, '/' otherwise.
*/
char get_path_separator() {
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
static char path_separator = '\\';
#else
static char path_separator = '/';
#endif
return path_separator;
}
/**
* Multiple command separator
*
* @return '&' for Windows, ';' otherwise.
*/
char multiple_command_separator() {
if (get_path_separator() == '/')
return ';';
else
return '&';
}
/**
* Returns the path as a string with the appropriate
* path separator.
*
* @param model_path vector of strings representing path to the model
*
* @return the string representation of the path with the appropriate
* path separator.
*/
std::string convert_model_path(const std::vector<std::string>& model_path) {
std::string path;
if (model_path.size() > 0) {
path.append(model_path[0]);
for (size_t i = 1; i < model_path.size(); i++) {
path.append(1, get_path_separator());
path.append(model_path[i]);
}
}
return path;
}
struct run_command_output {
std::string command;
std::string output;
long time;
int err_code;
bool hasError;
std::string header;
std::string body;
run_command_output(const std::string command,
const std::string output,
const long time,
const int err_code)
: command(command),
output(output),
time(time),
err_code(err_code),
hasError(err_code != 0),
header(),
body()
{
size_t end_of_header = output.find("\n\n");
if (end_of_header == std::string::npos)
end_of_header = 0;
else
end_of_header += 2;
header = output.substr(0, end_of_header);
body = output.substr(end_of_header);
}
run_command_output()
: command(),
output(),
time(0),
err_code(0),
hasError(false),
header(),
body()
{ }
};
std::ostream& operator<<(std::ostream& os, const run_command_output& out) {
os << "run_command output:" << "\n"
<< "- command: " << out.command << "\n"
<< "- output: " << out.output << "\n"
<< "- time (ms): " << out.time << "\n"
<< "- err_code: " << out.err_code << "\n"
<< "- hasError: " << (out.hasError ? "true" : "false") << "\n"
<< "- header: " << out.header << "\n"
<< "- body: " << out.body << std::endl;
return os;
}
/**
* Runs the command provided and returns the system output
* as a string.
*
* @param command A command that can be run from the shell
* @return the system output of the command
*/
run_command_output run_command(std::string command) {
using boost::posix_time::ptime;
using boost::posix_time::microsec_clock;
FILE *in;
in = popen(command.c_str(), "r");
if(!in) {
std::string err_msg;
err_msg = "Fatal error with popen; could not execute: \"";
err_msg+= command;
err_msg+= "\"";
throw std::runtime_error(err_msg.c_str());
}
std::string output;
char buf[1024];
size_t count;
ptime time_start(microsec_clock::universal_time()); // start timer
while ((count = fread(&buf, 1, 1024, in)) > 0)
output += std::string(&buf[0], &buf[count]);
ptime time_end(microsec_clock::universal_time()); // end timer
// bits 15-8 is err code, bit 7 if core dump, bits 6-0 is signal number
int err_code = pclose(in);
// on Windows, err code is the return code.
if (err_code != 0 && (err_code >> 8) > 0)
err_code >>= 8;
return run_command_output(command, output,
(time_end - time_start).total_milliseconds(),
err_code);
}
/**
* Returns the help options from the string provided.
* Help options start with "--".
*
* @param help_output output from "model/command --help"
* @return a vector of strings of the help options
*/
std::vector<std::string> parse_help_options(const std::string& help_output) {
std::vector<std::string> help_options;
size_t option_start = help_output.find("--");
while (option_start != std::string::npos) {
// find the option name (skip two characters for "--")
option_start += 2;
size_t option_end = help_output.find_first_of("= ", option_start);
help_options.push_back(help_output.substr(option_start, option_end-option_start));
option_start = help_output.find("--", option_start+1);
}
return help_options;
}
/**
* Parses output from a Stan model run from the command line.
* Returns option, value pairs.
*
* @param command_output The output from a Stan model run from the command line.
*
* @return Option, value pairs as indicated by the Stan model.
*/
std::vector<std::pair<std::string, std::string> >
parse_command_output(const std::string& command_output) {
using std::vector;
using std::pair;
using std::string;
vector<pair<string, string> > output;
string option, value;
size_t start = 0, end = command_output.find("\n", start);
start = end+1;
end = command_output.find("\n", start);
size_t equal_pos = command_output.find("=", start);
while (equal_pos != string::npos) {
using boost::trim;
option = command_output.substr(start, equal_pos-start);
value = command_output.substr(equal_pos+1, end - equal_pos - 1);
trim(option);
trim(value);
output.push_back(pair<string, string>(option, value));
start = end+1;
end = command_output.find("\n", start);
equal_pos = command_output.find("=", start);
}
return output;
}
}
}
#endif
| 30.919643 | 97 | 0.561074 | [
"vector",
"model"
] |
430403ccdf9dd869b67bd8294c943e2372127b56 | 72,911 | cpp | C++ | CAM_SubArray.cpp | LLiu6/Eva-CAM | 0ff4f725d12ef17066ee61a6c4b7ce713507a63a | [
"MIT"
] | null | null | null | CAM_SubArray.cpp | LLiu6/Eva-CAM | 0ff4f725d12ef17066ee61a6c4b7ce713507a63a | [
"MIT"
] | null | null | null | CAM_SubArray.cpp | LLiu6/Eva-CAM | 0ff4f725d12ef17066ee61a6c4b7ce713507a63a | [
"MIT"
] | null | null | null | /*
* CAM_SubArray.cpp
*
*/
#include "CAM_SubArray.h"
#include "formula.h"
#include "global.h"
#include "constant.h"
#include "CAM_Line.h"
#include "CAM_Cell.h"
#include <math.h>
CAM_SubArray::CAM_SubArray() {
// TODO Auto-generated constructor stub
initialized = false;
invalid = false;
}
CAM_SubArray::~CAM_SubArray() {
// TODO Auto-generated destructor stub
}
void CAM_SubArray::Initialize(long long _numRow, long long _numColumn, bool _multipleRowPerSet, bool _split,
int _muxSenseAmp, bool _internalSenseAmp, int _muxOutputLev1, int _muxOutputLev2,
BufferDesignTarget _DecMergeOptLevel, BufferDesignTarget _DriverOptLevel,
bool _withInputEnc, TypeOfInputEncoder _typeInputEnc, bool _customInputEnc,
TypeOfSenseAmp _typeSenseAmp, bool _customSenseAmp, bool _withWriteDriver,
bool _withOutputAcc, bool _withPriorityEnc, BufferDesignTarget _PriorityOptLevel,
bool _withInputBuf, bool _withOutputBuf, CAMType _camType, SearchFunction _searchFunction) {
if (initialized)
cout << "[CAM_SubArray] Warning: Already initialized!" << endl;
numRow = _numRow;
numColumn = _numColumn;
multipleRowPerSet = _multipleRowPerSet;
split = _split;
muxSenseAmp = _muxSenseAmp;
muxOutputLev1 = _muxOutputLev1;
muxOutputLev2 = _muxOutputLev2;
internalSenseAmp = _internalSenseAmp;
DecMergeOptLevel = _DecMergeOptLevel;
DriverOptLevel = _DriverOptLevel;
withInputEnc = _withInputEnc;
typeInputEnc = _typeInputEnc;
customInputEnc = _customInputEnc;
withWriteDriver = _withWriteDriver;
typeSenseAmp = _typeSenseAmp;
customSenseAmp = _customSenseAmp;
withOutputAcc = _withOutputAcc;
withPriorityEnc = _withPriorityEnc;
PriorityOptLevel = _PriorityOptLevel;
withInputBuf = _withInputBuf;
withOutputBuf = _withOutputBuf;
camType = _camType;
searchFunction = _searchFunction;
//////////////////////////////////////////////////////////////////////////////////
// input check: //
//////////////////////////////////////////////////////////////////////////////////
if (inputParameter->realCapacity != inputParameter->capacity && inputParameter->realCapacity != 0) {
// deal with the ASP-DAC12 fucking 72-bit word
numRow = inputParameter->realCapacity / inputParameter->minNumRowSubarray / inputParameter->minNumColumnSubarray
/ inputParameter->minNumActiveMatPerRow / inputParameter->minNumActiveMatPerColumn / numColumn;
}
if(CAM_cell->memCellType != FEFETRAM && inputParameter->searchFunction != EX){
invalid = true;
cout <<" [Search function Error]: Other search functions are under developmemt. " <<endl;
return;
}
if(CAM_cell->memCellType != FEFETRAM && inputParameter->camType != TCAM){
invalid = true;
cout <<" [CAM type Error]: Other CAM types are under developmemt. " <<endl;
return;
}
/*if (inputParameter->designTarget != CAM_chip || CAM_cell->memCellType > memristor || CAM_cell->memCellType == DRAM || CAM_cell->memCellType == eDRAM) {
invalid = true;
cout <<"[CAM_SubArray] Error: type input error" <<endl;
return;
}*/
if (CAM_cell->memCellType == SRAM) {
if (CAM_cell->camNumCol != 5 || CAM_cell->camNumRow != 3) {
// TODO: other types of SRAM based TCAM are under development
invalid = true;
cout <<"[CAM_SubArray] Error: other types of SRAM based TCAM are under development" <<endl;
return;
}
}
if (CAM_cell->camNumRow < 1 || CAM_cell->camNumCol < 1) {
invalid = true;
cout <<"[CAM_SubArray] Error: cell configuration error" <<endl;
return;
}
//////////////////////////////////////////////////////////////////////////////////
// defination: //
//////////////////////////////////////////////////////////////////////////////////
/* Derived parameters */
numSenseAmp = numColumn / muxSenseAmp;
lenRow = (double)numColumn * CAM_cell->widthInFeatureSize * tech->featureSize;
lenCol = (double)numRow * cell->heightInFeatureSize * tech->featureSize;
/* Add stitching overhead if necessary */
if (CAM_cell->stitching) {
lenRow += ((numColumn - 1) / CAM_cell->stitching + 1) * STITCHING_OVERHEAD * tech->featureSize;
}
//////////////////////////////////////////////////////////////////////////////////
// calculation for SA: //
//////////////////////////////////////////////////////////////////////////////////
// 1. setting SA sense mode
// TODO: note that cmos-based/doide-based has to be current-in voltage sensing
// 5. calc precharge voltage
// 6. calc for sensing: resMemCellOff, voltageMemCellOff
voltageSense = bool(CAM_cell->readMode > 0);
senseVoltage = CAM_cell->minSenseVoltage;
if (!internalSenseAmp && CAM_cell->memCellType != SRAM) {
invalid = true;
cout << "[CAM_SubArray] Error: nvTCAM does not support external sense amplifiers!" << endl;
return;
}
// calc voltage precharger
// TODO: for simple, all of the design are precharged to vdd
/* In fact, diode just need to charge to Vmatch+vth
* Cmos could be half swing
* none could be n*volatgeMemOff
*/
voltagePrecharge = tech->vdd;
resCellAccess = CalculateOnResistance(CAM_cell->widthAccessCMOS*tech->featureSize, NMOS, inputParameter->temperature, *tech);
capCellAccess = CalculateDrainCap(CAM_cell->widthAccessCMOS*tech->featureSize, NMOS, CAM_cell->widthInFeatureSize * tech->featureSize, *tech);
resMatchTran = CalculateOnResistance(CAM_cell->camWidthMatchTran * tech->featureSize, NMOS, inputParameter->temperature, *tech);
capMatchTran = CalculateDrainCap(CAM_cell->camWidthMatchTran * tech->featureSize, NMOS, CAM_cell->widthInFeatureSize * tech->featureSize, *tech);
if (CAM_cell->accessType == CMOS_access) {
resMemCellOff = tech->vdd / tech->currentOffNmos[inputParameter->temperature - 300]
/ tech->featureSize / CAM_cell->camWidthMatchTran;
resMemCellOn = resMatchTran;
if (CAM_cell->memCellType == SRAM)
resMemCellOn *=2;
} else if (CAM_cell->accessType == diode_access) {
resMemCellOff = tech->vdd / tech->currentOffNmos[inputParameter->temperature - 300]
/ tech->featureSize / CAM_cell->camWidthMatchTran;
resMemCellOn = resMatchTran + resCellAccess + CAM_cell->resistanceOn;
} else if (CAM_cell->accessType == none_access) {
resMemCellOff = resMatchTran + CAM_cell->resistanceOff;
resMemCellOn = resMatchTran+ CAM_cell->resistanceOn;
if (CAM_cell-> memCellType == FEFETRAM){ //2FEFET TCAM has no access transistor, and the Ron/off should be measured by HSPICE model
// resCellAccess = 0;
// capCellAccess = 0;
// resMatchTran = 0;
// capMatchTran = 0;
resCellAccess = CalculateOnResistance(CAM_cell->widthAccessCMOS * FEFET_tech->featureSize, NMOS, inputParameter->temperature, *FEFET_tech);
capCellAccess = CalculateDrainCap(CAM_cell->widthAccessCMOS * FEFET_tech->featureSize, NMOS, CAM_cell->widthInFeatureSize * FEFET_tech->featureSize, *FEFET_tech);
resMatchTran = CalculateOnResistance(CAM_cell->camWidthMatchTran * FEFET_tech->featureSize, NMOS, inputParameter->temperature, *tech);
capMatchTran = CalculateDrainCap(CAM_cell->camWidthMatchTran * FEFET_tech->featureSize, NMOS, CAM_cell->widthInFeatureSize * FEFET_tech->featureSize, *FEFET_tech);
resMemCellOn = CAM_cell->resistanceOn;
resMemCellOff = CAM_cell->resistanceOff;
}
} else {
// this will not happen
invalid = true;
cout << "[CAM_SubArray] Error: access type error!" << endl;
return;
}
// TODO: go back when design latency
if (CAM_cell->memCellType != SRAM) {
/* MRAM, PCRAM, and memristor have three types of access devices: CMOS, BJT, and diode */
if (voltageSense) { /* voltage-sensing */
if (CAM_cell->readVoltage == 0) { /* Current-in voltage sensing */
voltageMemCellOff = CAM_cell->readCurrent * resMemCellOff;
voltageMemCellOn = CAM_cell->readCurrent * resMemCellOn;
//voltagePrecharge = (voltageMemCellOff + voltageMemCellOn) / 2;
//voltagePrecharge = MIN(tech->vdd, voltagePrecharge); /* TO-DO: we can have charge bump to increase SA working point */
if ((voltagePrecharge - voltageMemCellOn) <= senseVoltage) {
cout <<"[CAM_SubArray] Error: Read current too large or too small that no reasonable precharge voltage existing" <<endl;
invalid = true;
return;
}
} else { /*Voltage-in voltage sensing */
resInSerialForSenseAmp = sqrt(resMemCellOn * resMemCellOff);
resEquivalentOn = resMemCellOn * resInSerialForSenseAmp / (resMemCellOn + resInSerialForSenseAmp);
resEquivalentOff = resMemCellOff * resInSerialForSenseAmp / (resMemCellOff + resInSerialForSenseAmp);
voltageMemCellOff = CAM_cell->readVoltage * resMemCellOff / (resMemCellOff + resInSerialForSenseAmp);
voltageMemCellOn = CAM_cell->readVoltage * resMemCellOn / (resMemCellOn + resInSerialForSenseAmp);
//voltagePrecharge = (voltageMemCellOff + voltageMemCellOn) / 2;
//voltagePrecharge = MIN(tech->vdd, voltagePrecharge); /* TO-DO: we can have charge bump to increase SA working point */
if ((voltagePrecharge - voltageMemCellOn) <= senseVoltage) {
// cout <<"[CAM_SubArray] Error: Read Voltage too large or too small that no reasonable precharge voltage existing" <<endl;
// invalid = true;
// return;
}
}
}
if(CAM_cell->accessType == CMOS_access) {
voltageMemCellOn = 0;
voltageMemCellOff = voltagePrecharge;
}
}
//////////////////////////////////////////////////////////////////////////////////
// calculation for driver: //
//////////////////////////////////////////////////////////////////////////////////
// 2. line resistance caclualtion
// 3. Mux load calculation: extended from signel bl to cols
// 4. transistor's impact on res and cap of the lines
for(int i=0;i<CAM_cell->camNumRow;i++){
Row[i].Initialize(true, i, lenRow, numColumn);
}
for(int i=0;i<CAM_cell->camNumCol;i++){
Col[i].Initialize(false, i, lenCol, numRow);
if (Col[i].minMuxWidth > inputParameter->maxNmosSize * tech->featureSize) {
invalid = true;
cout <<"[CAM_SubArray] Error: Mux width too large" <<endl;
return;
}
}
//////////////////////////////////////////////////////////////////////////////////
// validation check: //
//////////////////////////////////////////////////////////////////////////////////
// 2. ML length: match (all-Ih) v.s. 1-miss (Il+all-Ih) for search
if (CAM_cell->accessType == CMOS_access || CAM_cell->accessType == diode_access){
// ML is connected with the drain of NMOS, like ISSCC15-3t1r
// ML is connected with the diode (both gate and drain of nmos), like VSLIT12-4t2r
// the leakage cannot be too large
if(numRow * tech->currentOffNmos[inputParameter->temperature - 300] / BITLINE_LEAKAGE_TOLERANCE >
tech->currentOnNmos[inputParameter->temperature - 300]) {
invalid = true;
cout <<"[CAM_SubArray] Error: bitline too long" <<endl;
return;
}
} else if (CAM_cell->accessType == none_access) {
// ML is connected with cell, like JSSC11-2t2r and also for 2FEFET TCAM design
// TODO sth for 2FEFET TCAM
cout << "numRow: " << numRow;
if( inputParameter->withOutputAcc == false ) {
double Rh = numRow * resMemCellOff;
double Rl = resMemCellOn;
senseMargin = 2 * senseVoltage * (Rh - Rl) / (Rh + Rl);
if ( senseMargin < MIN_SENSE_MARGIN ) {
// TODO: the minimal sense margin is defined in the constant
invalid = true;
cout <<"[CAM_SubArray] Error: too many rows for sense" <<endl;
return;
}
}
} else {
invalid = true;
cout <<"[CAM_SubArray] Error: access type input error" <<endl;
return;
}
//////////////////////////////////////////////////////////////////////////////////
// Initialize //
//////////////////////////////////////////////////////////////////////////////////
double capNandInput, tmp;
if(withInputBuf) {
CalculateGateCapacitance(NAND, 2, 2 * MIN_NMOS_SIZE * tech->featureSize, tech->pnSizeRatio * MIN_NMOS_SIZE * tech->featureSize,
tech->featureSize*MAX_TRANSISTOR_HEIGHT, *tech, &capNandInput, &tmp);
inputBuf.Initialize(true /*TODO*/, capNandInput, 0);
}
if(withInputEnc) {
CalculateGateCapacitance(NAND, 2, 2 * MIN_NMOS_SIZE * tech->featureSize, tech->pnSizeRatio * MIN_NMOS_SIZE * tech->featureSize,
tech->featureSize*MAX_TRANSISTOR_HEIGHT, *tech, &capNandInput, &tmp);
inputEnc.Initialize(encoding_two_bit, false, capNandInput, 0 /* TODO*/);
inputEnc.CalculateRC();
}
// this NAND merges pre-decoder's result, output the WL activation signal
CalculateGateCapacitance(NAND, 2, 2 * MIN_NMOS_SIZE * tech->featureSize, tech->pnSizeRatio * MIN_NMOS_SIZE * tech->featureSize,
tech->featureSize*MAX_TRANSISTOR_HEIGHT, *tech, &capNandInput, &tmp);
if(!CAM_cell->camMLC && CAM_cell->memCellType != SRAM) {
RowDecMergeNand.Initialize(numRow * 2, capNandInput, 0, false/*TODO*/, true, DecMergeOptLevel, 0 /*TODO*/);
} else {
RowDecMergeNand.Initialize(numRow, capNandInput, 0, false/*TODO*/, true, DecMergeOptLevel, 0 /*TODO*/);
}
RowDecMergeNand.CalculateRC();
// those NAND merges the WL and SL signal
//RowDriver = new CAM_RowNand [CAM_cell->camNumRow];
for(int i=0;i<CAM_cell->camNumRow;i++){
RowDriver[i].Initialize(numRow, Row[i].cap*1.6, Row[i].res, false/*TODO*/, false, DriverOptLevel, Row[i].maxCurrent);
RowDriver[i].CalculateRC();
}
// if(CAM_cell->memCellType == FEFETRAM){
// for(int i=0;i<CAM_cell->camNumRow;i++){
// RowDriver[i].Initialize(numRow, Row[i].cap /* * 10 */, Row[i].res, false/*TODO*/, false, DriverOptLevel, Row[i].maxCurrent);
// RowDriver[i].CalculateRC();
// }
// }
// precharge
indexMatchline = -1;
for(int i=0;i<CAM_cell->camNumRow;i++){
if (Col[i].CellPort.Type == Matchline || Col[i].CellPort.Type == Matchline_Bitline) {
indexMatchline = i;
break;
}
}
if(indexMatchline == -1) {
invalid = true;
cout <<"[CAM_SubArray] Error: no matchline found" <<endl;
return;
}
precharger.Initialize(voltagePrecharge, numColumn, Col[indexMatchline].cap, Col[indexMatchline].res);
precharger.CalculateRC();
// colmn decoder signal merge
// TODO: I am too lazy to calculate very one, just use the index zero
Row[CAM_cell->camNumRow].Initialize(lenRow, numColumn, Col[0].minMuxWidth);
ColDecMergeNand.Initialize(CAM_cell->camNumCol * muxSenseAmp, Row[CAM_cell->camNumRow].cap, Row[CAM_cell->camNumRow].res, false, DecMergeOptLevel, 0);
ColDecMergeNand.CalculateRC();
senseAmpMuxLev1Nand.Initialize(muxOutputLev1, Row[CAM_cell->camNumRow].cap, Row[CAM_cell->camNumRow].res, false, DecMergeOptLevel, 0);
senseAmpMuxLev1Nand.CalculateRC();
senseAmpMuxLev2Nand.Initialize(muxOutputLev2, Row[CAM_cell->camNumRow].cap, Row[CAM_cell->camNumRow].res, false, DecMergeOptLevel, 0);
senseAmpMuxLev2Nand.CalculateRC();
// MUX
senseAmpMuxLev2.Initialize(muxOutputLev2, numColumn / muxSenseAmp / muxOutputLev1 / muxOutputLev2,
0, 0, Col[indexMatchline].maxCurrent);
senseAmpMuxLev2.CalculateRC();
senseAmpMuxLev1.Initialize(muxOutputLev1, numColumn / muxSenseAmp / muxOutputLev1,
senseAmpMuxLev2.capForPreviousDelayCalculation, senseAmpMuxLev2.capForPreviousPowerCalculation, Col[indexMatchline].maxCurrent);
senseAmpMuxLev1.CalculateRC();
if (internalSenseAmp) {
senseAmp.Initialize(numColumn / muxSenseAmp, typeSenseAmp, customSenseAmp, senseVoltage, lenRow / numColumn * muxSenseAmp);
senseAmp.CalculateRC();
for(int i=0;i<CAM_cell->camNumCol;i++){
ColMux[i].Initialize(muxSenseAmp, numColumn / muxSenseAmp, senseAmp.capLoad, senseAmp.capLoad, Col[i].maxCurrent);
ColMux[i].CalculateRC();
}
} else {
for(int i=0;i<CAM_cell->camNumCol;i++){
ColMux[i].Initialize(muxSenseAmp, numColumn / muxSenseAmp, senseAmpMuxLev1.capForPreviousDelayCalculation,
senseAmpMuxLev1.capForPreviousPowerCalculation, Col[i].maxCurrent);
ColMux[i].CalculateRC();
}
}
if (withWriteDriver) {
for(int i=0;i<CAM_cell->camNumCol;i++) {
if(CAM_cell->camPort[1][i].Type == Matchline) {
WriteDriver[i].initialized = false;
} else {
WriteDriver[i].Initialize(numColumn / muxSenseAmp, Col[i].cap, Col[i].res, false, DriverOptLevel, Col[i].maxCurrent);
WriteDriver[i].CalculateRC();
}
}
}
if (withPriorityEnc) {
priorityEnc.Initialize(numColumn, PriorityOptLevel, 0, 0 /*TODO: no output driver*/);
}
if (withOutputAcc) {
if (withPriorityEnc)
outputAcc.Initialize(priorityEnc.MMR.BasicMMR.capIn, 0);
else
outputAcc.Initialize(0, 0 /*TODO: no output driver*/);
outputAcc.CalculateRC();
}
if(withOutputBuf) {
CalculateGateCapacitance(NAND, 2, 2 * MIN_NMOS_SIZE * tech->featureSize, tech->pnSizeRatio * MIN_NMOS_SIZE * tech->featureSize,
tech->featureSize*MAX_TRANSISTOR_HEIGHT, *tech, &capNandInput, &tmp);
outputBuf.Initialize(true /*TODO*/, capNandInput, 0);
}
initialized = true;
}
void CAM_SubArray::CalculateArea() {
if (!initialized) {
cout << "[CAM_SubArray] Error: Require initialization first!" << endl;
} else if (invalid) {
cout << "[CAM_SubArray] Error: invalid!" << endl;
height = width = area = 1e41;
} else {
double addWidthArea = 0, addHeightArea = 0;
width = lenRow;
height = lenCol;
// cout << "width: height: " << width * 1e6 << ": " << height*1e6 << endl;
area = height * width;
if(withInputBuf) {
inputBuf.CalculateArea();
area += (inputBuf.area * numRow);
addWidthArea += (inputBuf.area * numRow);
}
if(withInputEnc) {
inputEnc.CalculateArea();
area += (inputEnc.area * numRow);
addWidthArea += (inputEnc.area * numRow);
}
RowDecMergeNand.CalculateArea();
area += (RowDecMergeNand.area);
addWidthArea += (RowDecMergeNand.area);
for(int i=0;i<CAM_cell->camNumRow;i++){
RowDriver[i].CalculateArea();
area += (RowDriver[i].area);
addWidthArea += (RowDriver[i].area);
}
// colmn decoder signal merge
ColDecMergeNand.CalculateArea();
area += (ColDecMergeNand.area);
addWidthArea += (ColDecMergeNand.area);
senseAmpMuxLev1Nand.CalculateArea();
area += (senseAmpMuxLev1Nand.area);
addWidthArea += (senseAmpMuxLev1Nand.area);
senseAmpMuxLev2Nand.CalculateArea();
area += (senseAmpMuxLev2Nand.area);
addWidthArea += (senseAmpMuxLev2Nand.area);
precharger.CalculateArea();
area += (precharger.area);
addHeightArea += (precharger.area);
for(int i=0;i<CAM_cell->camNumCol;i++){
ColMux[i].CalculateArea();
area += (ColMux[i].area);
addHeightArea += (ColMux[i].area);
}
// MUX
senseAmpMuxLev2.CalculateArea();
area += (senseAmpMuxLev2.area);
addHeightArea += (senseAmpMuxLev2.area);
senseAmpMuxLev1.CalculateArea();
area += (senseAmpMuxLev1.area);
addHeightArea += (senseAmpMuxLev1.area);
if (internalSenseAmp) {
senseAmp.CalculateArea();
area += (senseAmp.area);
addHeightArea += (senseAmp.area);
}
WriteDriverArea = 0;
if (withWriteDriver) {
for(int i=0;i<CAM_cell->camNumCol;i++){
if (WriteDriver[i].initialized) {
WriteDriver[i].CalculateArea();
if (i > 0 && Col[i].CellPort.Type == Bitline && Col[i-1].CellPort.Type == Bitline) {
//WriteDriverArea += (WriteDriver[i].outputDriver.area);
WriteDriverArea += (WriteDriver[i].area);
} else {
WriteDriverArea += (WriteDriver[i].area);
}
}
}
}
area += WriteDriverArea;
addHeightArea += WriteDriverArea;
if (withOutputAcc) {
outputAcc.CalculateArea();
area += (outputAcc.area * numColumn / muxSenseAmp);
addHeightArea += (outputAcc.area * numColumn / muxSenseAmp);
}
if (withPriorityEnc) {
priorityEnc.CalculateArea();
area += (priorityEnc.area);
addHeightArea += (priorityEnc.area);
}
if(withOutputBuf) {
outputBuf.CalculateArea();
area += (outputBuf.area * numColumn / muxSenseAmp);
addWidthArea += (outputBuf.area * numColumn / muxSenseAmp);
}
// TODO: a prefect layout
width = addWidthArea / lenCol + lenCol;
height = area / width;
// cout << "width: height: 22 " << width * 1e6 << ": " << height*1e6 << endl;
}
}
void CAM_SubArray::CalculateLatency(double _rampInput) {
if (!initialized) {
cout << "[CAM_SubArray] Error: Require initialization first!" << endl;
} else if (invalid) {
cout << "[CAM_SubArray] Error: invalid!" << endl;
searchLatency = readLatency = writeLatency = 1e41;
} else {
if(withInputBuf) {
inputBuf.CalculateLatency(_rampInput);
} else {
inputBuf.readLatency = 0;
inputBuf.rampOutput = _rampInput;
}
if(withInputEnc) {
inputEnc.CalculateLatency(_rampInput);
} else {
inputEnc.readLatency = 0;
inputEnc.rampOutput = _rampInput;
}
// this NAND merges pre-decoder's result, output the WL activation signal
RowDecMergeNand.CalculateLatency(_rampInput);
// those NAND merges the WL and SL signal
double maxRowDriver = 0;
int indexMaxRowDriver = 0;
for(int i=0;i<CAM_cell->camNumRow;i++){
RowDriver[i].CalculateLatency(MAX(inputEnc.rampOutput, RowDecMergeNand.rampOutput));
if (RowDriver[i].readLatency > maxRowDriver) {
maxRowDriver = RowDriver[i].readLatency;
indexMaxRowDriver = i;
}
}
// precharge
precharger.CalculateLatency(_rampInput);
// colmn decoder signal merge
ColDecMergeNand.CalculateLatency(_rampInput);
senseAmpMuxLev1Nand.CalculateLatency(_rampInput);
senseAmpMuxLev2Nand.CalculateLatency(_rampInput);
columnDecoderLatency = MAX(MAX(ColDecMergeNand.readLatency, senseAmpMuxLev1Nand.readLatency), senseAmpMuxLev2Nand.readLatency);
decoderLatency = MAX(RowDecMergeNand.readLatency + maxRowDriver, columnDecoderLatency);
//////////////////////////////////////////////////////////////////////////////////
// calc matchline & bitline //
//////////////////////////////////////////////////////////////////////////////////
double tau, gm, beta;
if (typeSenseAmp == discharge) {
if (CAM_cell->memCellType == SRAM || CAM_cell->accessType == CMOS_access) {
double resTotalCell = 0;
// 1-miss situation
resTotalCell = resMemCellOn; // + resMemCellOff / (numRow-1);
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
referDelay = tau * log((voltagePrecharge) / (CAM_cell->readVoltage));
// all-match situation
resTotalCell = resMemCellOff / CAM_opt.BitSerialWidth;// /numRow;
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
volMatchDrop = voltagePrecharge - voltagePrecharge * exp(-referDelay * tau);
// all-miss situation
resTotalCell = resMemCellOn / CAM_opt.BitSerialWidth; // / numRow;
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
volAllMissDrop = voltagePrecharge - voltagePrecharge * exp(-referDelay * tau);
senseMargin = voltagePrecharge - volMatchDrop - CAM_cell->readVoltage;
if (senseMargin < senseVoltage) {
cout << "[CAM_Subarray] Error: bitline too long to be sensed!" << endl;
invalid = true;
searchLatency = readLatency = writeLatency = 1e41;
return;
}
bitlineDelayOn = bitlineDelayOff = bitlineDelay = referDelay;
} else if (CAM_cell->accessType == diode_access) {
double resTotalCell = 0;
// 1-miss situation
resTotalCell = resMemCellOn; // + resMemCellOff / (numRow-1);
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
referDelay = tau * log((voltagePrecharge - tech->vth) / (CAM_cell->readVoltage));
// all-match situation
resTotalCell = resMemCellOff / CAM_opt.BitSerialWidth; // / numRow;
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
volMatchDrop = (voltagePrecharge - tech->vth) - (voltagePrecharge - tech->vth) * exp(-referDelay / tau);
// all-miss situation
resTotalCell = resMemCellOn / CAM_opt.BitSerialWidth; // / numRow;
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
volAllMissDrop = (voltagePrecharge - tech->vth) - (voltagePrecharge - tech->vth) * exp(-referDelay / tau);
senseMargin = voltagePrecharge - volMatchDrop - CAM_cell->readVoltage;
if (senseMargin < senseVoltage) {
cout << "[CAM_Subarray] Error: bitline too long to be sensed!" << endl;
invalid = true;
searchLatency = readLatency = writeLatency = 1e41;
return;
}
// pre-threshold drop
resTotalCell = resMemCellOn / CAM_opt.BitSerialWidth; // / numRow;
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
referDelay += tau * log((voltagePrecharge) / (voltagePrecharge - tech->vth));
bitlineDelayOn = bitlineDelayOff = bitlineDelay = referDelay;
} else if (CAM_cell->accessType == none_access) {
// double resTotalCell = 0;
// resTotalCell = resMemCellOn + resMemCellOff/(CAM_opt.BitSerialWidth-1);
// 1-miss situation may exist problems for PCM 2T2R design
// if (CAM_opt.BitSerialWidth == 1) {
// resTotalCell = resMemCellOn;
// } else {
// resTotalCell = resMemCellOn * resMemCellOff / (CAM_opt.BitSerialWidth - 1)
// / (resMemCellOn + resMemCellOff / (CAM_opt.BitSerialWidth - 1)); // / (numRow-1);
// }
// tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
// + Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
// referDelay = tau * log((voltagePrecharge) / (CAM_cell->readVoltage));
// // all-match situation
// resTotalCell = resMemCellOff / CAM_opt.BitSerialWidth; // / numRow;
// tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
// + Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
// volMatchDrop = (voltagePrecharge) - (voltagePrecharge) * exp(-referDelay / tau);
// // all-miss situation
// resTotalCell = resMemCellOn / CAM_opt.BitSerialWidth; // / numRow;
// tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
// + Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
// volAllMissDrop = voltagePrecharge - voltagePrecharge * exp(-referDelay * tau);
// senseMargin = voltagePrecharge - volMatchDrop - CAM_cell->readVoltage;
// if (senseMargin < senseVoltage) {
// cout << "[CAM_Subarray] Error: bitline too long to be sensed!" << endl;
// invalid = true;
// searchLatency = readLatency = writeLatency = 1e41;
// return;
// }
// bitlineDelayOn = bitlineDelayOff = bitlineDelay = referDelay;
if (CAM_cell -> memCellType == FEFETRAM){
double resTotalCell = 0;
double ArrayWidth = 0;
double BaseResTotalCell = 0;
resTotalCell = resMemCellOn + resMemCellOff/(CAM_opt.BitSerialWidth-1);
BaseResTotalCell = resMemCellOff/CAM_opt.BitSerialWidth;
// }
tau = resTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
Basetau = BaseResTotalCell * (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
SenseTime = log(2)*(tau-Basetau);
//BaseSenseTime = log(2)*Basetau;
}
} else {
// should not happen
cout << "[CAM_subarray]: Error input access tpye!" << endl;
exit(-1);
}
} else {
if (CAM_cell->memCellType == SRAM) {
/* Codes below calculate the bitline latency */
double resPullDown = CalculateOnResistance(CAM_cell->widthSRAMCellNMOS * tech->featureSize, NMOS,
inputParameter->temperature, *tech);
tau = (resMatchTran + resPullDown) * (capMatchTran + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
tau *= log(voltagePrecharge / (voltagePrecharge - senseVoltage));
gm = CalculateTransconductance(CAM_cell->camWidthMatchTran * tech->featureSize, NMOS, *tech);
beta = 1 / (resPullDown * gm);
bitlineDelay = horowitz(tau, beta, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
} else if (CAM_cell->memCellType == FEFETRAM) {
if (CAM_cell->accessType == none_access){
// 1-miss situation
resTotalCell = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-1)+resMemCellOff*1);
tau = resTotalCell*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Basetau = BaseResTotalCell * (capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (capCellAccess*CAM_opt.BitSerialWidth + ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
totalcapcell = Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation*1e9;
bitlineDelay = horowitz(tau, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
// //////////////////////MCAM//////////////////////////////////////////
double S0, S1, S2, S3, S4, S5, S6, S7;
S0 = 1.616E+06;
S1 = 8.547E+05;
S2 = 2.833E+05;
S3 = 1.083E+05;
S4 = 5.291E+04;
S5 = 3.300E+04;
S6 = 2.439E+04;
S7 = 2.004E+04;
//CAM_opt.BitSerialWidth = 32;
double resM0, resM1, resM2, resM3, resM4, resM5, resM6, resM7;
double Stau0, Stau1, Stau2, Stau3, Stau4, Stau5, Stau6, Stau7;
resM0 = S0/CAM_opt.BitSerialWidth;
resM1 = S1*S0/(S1*(CAM_opt.BitSerialWidth-1)+S0);
resM2 = S2*S0/(S2*(CAM_opt.BitSerialWidth-1)+S0);
resM3 = S3*S0/(S3*(CAM_opt.BitSerialWidth-1)+S0);
resM4 = S4*S0/(S4*(CAM_opt.BitSerialWidth-1)+S0);
resM5 = S5*S0/(S5*(CAM_opt.BitSerialWidth-1)+S0);
resM6 = S6*S0/(S6*(CAM_opt.BitSerialWidth-1)+S0);
resM7 = S7*S0/(S7*(CAM_opt.BitSerialWidth-1)+S0);
Stau0 = resM0*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau1 = resM1*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau2 = resM2*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau3 = resM3*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau4 = resM4*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau5 = resM5*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau6 = resM6*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
Stau7 = resM7*(capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad + inputParameter->AddCapOnML)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + capCellAccess*CAM_opt.BitSerialWidth + Col[indexMatchline].cap / 2);
double MbitlineDelay0 = horowitz(Stau0, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay1 = horowitz(Stau1, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay2 = horowitz(Stau2, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay3 = horowitz(Stau3, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay4 = horowitz(Stau4, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay5 = horowitz(Stau5, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay6 = horowitz(Stau6, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double MbitlineDelay7 = horowitz(Stau7, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
////////////////////////////////////////////////////////////////////
// cout << "-1/tau0, -1/tau1, -1/tau2, -1/tau3, -1/tau4, -1/tau5 = " << -1/tau0 <<": " << -1/tau1 << ": " << -1/tau2 << ": " << -1/tau3 << ": " << -1/tau4 << ": " << -1/tau5 << endl;
} else if(CAM_cell->accessType == CMOS_access){
double resOn = CalculateOnResistance( tech->featureSize, NMOS,inputParameter->temperature, *tech);
double tauM1 = (resOn) * (capMatchTran + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
double TotalCap = capMatchTran;
//cout << "total cap" << TotalCap *1e15<< endl;
gm = CalculateTransconductance( tech->featureSize, NMOS, *tech);
beta = 1 / (resOn * gm);
bitlineDelay = horowitz(tauM1, beta, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
}
} else if (CAM_cell->memCellType == MRAM || CAM_cell->memCellType == PCRAM || CAM_cell->memCellType == memristor || CAM_cell->memCellType == FBRAM /*|| CAM_cell->memCellType == FEFETRAM*/) {
if (CAM_cell->readMode == false) { /* current-sensing */
/* Use ICCAD 2009 model */
////////////////////////Approximate Match ////////////////////////
double res1 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-1)+resMemCellOff*1);
double res2 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-2)+resMemCellOff*2);
double res3 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-3)+resMemCellOff*3);
double res4 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-4)+resMemCellOff*4);
double res5 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-5)+resMemCellOff*5);
double tau1 = Col[indexMatchline].res * (Col[indexMatchline].cap+ 0.6e-13* CAM_opt.BitSerialWidth)/
2 * (res1 + Col[indexMatchline].res / 3) / (res1 + Col[indexMatchline].res);
double tau2 = Col[indexMatchline].res * (Col[indexMatchline].cap+ 0.6e-13* CAM_opt.BitSerialWidth)/
2 * (res2 + Col[indexMatchline].res / 3) / (res1 + Col[indexMatchline].res);
double tau3 = Col[indexMatchline].res * (Col[indexMatchline].cap+ 0.6e-13* CAM_opt.BitSerialWidth)/
2 * (res3 + Col[indexMatchline].res / 3) / (res1 + Col[indexMatchline].res);
double tau4 = Col[indexMatchline].res * (Col[indexMatchline].cap+ 0.6e-13* CAM_opt.BitSerialWidth)/
2 * (res4 + Col[indexMatchline].res / 3) / (res1 + Col[indexMatchline].res);
double tau5 = Col[indexMatchline].res * (Col[indexMatchline].cap+ 0.6e-13* CAM_opt.BitSerialWidth)/
2 * (res5 + Col[indexMatchline].res / 3) / (res1 + Col[indexMatchline].res);
double BL1 = horowitz(tau1, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double BL2 = horowitz(tau2, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double BL3 = horowitz(tau3, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double BL4 = horowitz(tau4, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
double BL5 = horowitz(tau5, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
// cout << "Bitline (current): " << BL1 *1e12 << ": " << BL2 *1e12 << ": " << BL3 *1e12 << ": " << BL4 *1e12 << ": " << BL5 *1e12 << endl;
/////////////////////////////////////////////////////////////////
tau = Col[indexMatchline].res * (Col[indexMatchline].cap+ CAM_opt.BitSerialWidth)/
2 * (resMemCellOff + Col[indexMatchline].res / 3) / (resMemCellOff + Col[indexMatchline].res);
bitlineDelay = horowitz(tau, 0, RowDriver[indexMaxRowDriver].rampOutput, &bitlineRamp);
} else { /* voltage-sensing */
if (CAM_cell->readVoltage == 0) { /* Current-in voltage sensing */
tau = resMemCellOn * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
/////// Approximate Match /////////////////////
double res1 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-1)+resMemCellOff*1);
double res2 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-2)+resMemCellOff*2);
double res3 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-3)+resMemCellOff*3);
double res4 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-4)+resMemCellOff*4);
double res5 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-5)+resMemCellOff*5);
double tau1 = res1 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau2 = res2 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau3 = res3 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau4 = res4 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau5 = res5 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double bitlineOn1 = tau1 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn2 = tau2 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn3 = tau3 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn4 = tau4 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn5 = tau5 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOff1 = tau1 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff2 = tau2 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff3 = tau3 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff4 = tau4 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff5 = tau5 * log((voltagePrecharge) / (voltageMemCellOff));
///////////////////////////////////////////////
bitlineDelayOn = tau * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
// TODO
//bitlineDelayOn = tau * log((voltagePrecharge) / (voltageMemCellOn));
tau = resMemCellOff * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
bitlineDelayOff = tau * log((voltagePrecharge) / (voltageMemCellOff));
bitlineDelay = MAX(bitlineDelayOn, bitlineDelayOff);
//////////////Approximate match////////////////////////////
// Used for test ////////////////////////////
} else { /*Voltage-in voltage sensing */
/////////////////////////////////test//////////////////////////
resTotalCell = resMemCellOn*resMemCellOff/(resMemCellOn+resMemCellOff/(CAM_opt.BitSerialWidth-1));
tau = resEquivalentOn * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
bitlineDelayOn = tau * log((voltagePrecharge - voltageMemCellOn)/(voltagePrecharge - voltageMemCellOn - senseVoltage));
tau = resEquivalentOff * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation + precharger.capOutputBitlinePrecharger + senseAmp.capLoad)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation + Col[indexMatchline].cap / 2);
bitlineDelayOff = tau * log((voltageMemCellOff - voltagePrecharge)/(voltageMemCellOff - voltagePrecharge - senseVoltage));
bitlineDelay = MAX(bitlineDelayOn, bitlineDelayOff);
/////// Approximate Match /////////////////////
double res1 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-1)+resMemCellOff*1);
double res2 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-2)+resMemCellOff*2);
double res3 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-3)+resMemCellOff*3);
double res4 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-4)+resMemCellOff*4);
double res5 = resMemCellOn*resMemCellOff/(resMemCellOn*(CAM_opt.BitSerialWidth-5)+resMemCellOff*5);
double tau1 = res1 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau2 = res2 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau3 = res3 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau4 = res4 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double tau5 = res5 * (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousDelayCalculation)
+ Col[indexMatchline].res * (ColMux[indexMatchline].capForPreviousDelayCalculation
+ Col[indexMatchline].cap / 2);
double bitlineOn1 = tau1 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn2 = tau2 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn3 = tau3 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn4 = tau4 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOn5 = tau5 * log((voltagePrecharge - voltageMemCellOn) / (voltagePrecharge - voltageMemCellOn - senseVoltage));
double bitlineOff1 = tau1 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff2 = tau2 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff3 = tau3 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff4 = tau4 * log((voltagePrecharge) / (voltageMemCellOff));
double bitlineOff5 = tau5 * log((voltagePrecharge) / (voltageMemCellOff));
}
}
}
}
for(int i=0;i<CAM_cell->camNumCol;i++){
ColMux[i].CalculateLatency(bitlineRamp);
}
if (internalSenseAmp) {
senseAmp.CalculateLatency(ColMux[indexMatchline].rampOutput);
senseAmpMuxLev1.CalculateLatency(1e20);
senseAmpMuxLev2.CalculateLatency(senseAmpMuxLev1.rampOutput);
} else {
senseAmpMuxLev1.CalculateLatency(ColMux[indexMatchline].rampOutput);
senseAmpMuxLev2.CalculateLatency(senseAmpMuxLev1.rampOutput);
}
if (withOutputAcc) {
outputAcc.CalculateLatency(1e20);
} else {
outputAcc.readLatency = 0;
outputAcc.rampOutput = 1e20;
}
if (withPriorityEnc) {
priorityEnc.CalculateLatency(outputAcc.rampOutput);
rampOutput = priorityEnc.rampOutput;
} else {
priorityEnc.readLatency = 0;
priorityEnc.rampOutput = outputAcc.rampOutput;
rampOutput = priorityEnc.rampOutput;
}
if(withOutputBuf) {
outputBuf.CalculateLatency(outputAcc.rampOutput);
} else {
outputBuf.readLatency = 0;
}
searchLatency = inputBuf.readLatency + precharger.readLatency + maxRowDriver + inputEnc.readLatency + bitlineDelay
+ ColMux[indexMatchline].readLatency + senseAmp.readLatency + outputAcc.readLatency + priorityEnc.readLatency
+ outputBuf.readLatency;
senseAmpLatency = senseAmp.readLatency;
readLatency = inputBuf.readLatency + MAX(precharger.readLatency, decoderLatency + inputEnc.readLatency) + bitlineDelay
+ ColMux[indexMatchline].readLatency + senseAmp.readLatency + senseAmpMuxLev1.readLatency + senseAmpMuxLev2.readLatency
+ outputAcc.readLatency + priorityEnc.readLatency + outputBuf.readLatency;
// for write
double capPassTransistor = ColMux[indexMatchline].capNMOSPassTransistor +
senseAmpMuxLev1.capNMOSPassTransistor + senseAmpMuxLev2.capNMOSPassTransistor;
double resPassTransistor = ColMux[indexMatchline].resNMOSPassTransistor +
senseAmpMuxLev1.resNMOSPassTransistor + senseAmpMuxLev2.resNMOSPassTransistor;
double tauChargeLatency = resPassTransistor * (capPassTransistor + Col[indexMatchline].cap) +
Col[indexMatchline].res * Col[indexMatchline].cap / 2;
chargeLatency = horowitz(tauChargeLatency, 0, 1e20, NULL);
WriteDriverLatency = 0;
if (inputParameter->writeScheme == write_and_verify) {
/*TODO: write and verify programming */
} else {
if (withWriteDriver) {
for(int i=0;i<CAM_cell->camNumCol;i++){
if (WriteDriver[i].initialized) {
WriteDriver[i].CalculateLatency(1e20);
WriteDriverLatency = MAX(WriteDriver[i].writeLatency, WriteDriverLatency);
}
}
}
writeLatency = MAX(RowDecMergeNand.readLatency + maxRowDriver, columnDecoderLatency + WriteDriverLatency + chargeLatency);
resetLatency = writeLatency + CAM_cell->resetPulse;
setLatency = writeLatency + CAM_cell->setPulse;
writeLatency += MAX(CAM_cell->resetPulse, CAM_cell->setPulse);
}
}
}
void CAM_SubArray::CalculatePower() {
if (!initialized) {
cout << "[CAM_SubArray] Error: Require initialization first!" << endl;
} else if (invalid) {
cout << "[CAM_SubArray] Error: invalid!" << endl;
readDynamicEnergy = writeDynamicEnergy = leakage = 1e41;
} else {
//////////////////////////////////////////////////////////////////////////////////
// calc components //
//////////////////////////////////////////////////////////////////////////////////
readDynamicEnergy = writeDynamicEnergy = leakage = 0;
if(withInputBuf) {
inputBuf.CalculatePower();
} else {
inputBuf.readDynamicEnergy = 0;
inputBuf.leakage = 0;
}
if(withInputEnc) {
inputEnc.CalculatePower();
} else {
inputEnc.readDynamicEnergy = 0;
inputEnc.leakage = 0;
}
// this NAND merges pre-decoder's result, output the WL activation signal
RowDecMergeNand.CalculatePower();
// those NAND merges the WL and SL signal
for(int i=0;i<CAM_cell->camNumRow;i++){
RowDriver[i].CalculatePower();
}
// precharge
precharger.CalculatePower();
// colmn decoder signal merge
ColDecMergeNand.CalculatePower();
senseAmpMuxLev1Nand.CalculatePower();
senseAmpMuxLev2Nand.CalculatePower();
if (internalSenseAmp) {
senseAmp.CalculatePower();
}
senseAmpMuxLev1.CalculatePower();
senseAmpMuxLev2.CalculatePower();
if (withOutputAcc) {
outputAcc.CalculatePower();
}
if (withPriorityEnc) {
priorityEnc.CalculatePower();
}
if(withOutputBuf) {
outputBuf.CalculatePower();
} else {
outputBuf.readDynamicEnergy = 0;
outputBuf.leakage = 0;
}
//////////////////////////////////////////////////////////////////////////////////
// calc read and search //
//////////////////////////////////////////////////////////////////////////////////
if (typeSenseAmp == discharge) {
searchDynamicEnergy = (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousPowerCalculation)
* (voltagePrecharge * voltagePrecharge - CAM_cell->readVoltage * CAM_cell->readVoltage)* numColumn;
} else {
if (CAM_cell->memCellType == SRAM) {
/* Codes below calculate the SRAM bitline power */
searchDynamicEnergy = (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousPowerCalculation)
* voltagePrecharge * voltagePrecharge * numColumn;
} else if (CAM_cell->memCellType == FEFETRAM){
double FEFETCap = CalculateDrainCap(CAM_cell->widthAccessCMOS * FEFET_tech->featureSize, NMOS, CAM_cell->widthInFeatureSize * FEFET_tech->featureSize, *FEFET_tech);
//if (CAM_cell->accessType == CMOS_access){
searchDynamicEnergy = (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousPowerCalculation+ FEFETCap)
* voltagePrecharge * voltagePrecharge * numColumn/ muxSenseAmp;
//} else if (CAM_cell->accessType == none_access)
} else if (CAM_cell->memCellType == MRAM || CAM_cell->memCellType == PCRAM || CAM_cell->memCellType == memristor) {
if (CAM_cell->readMode == false) { /* current-sensing */
/* Use ICCAD 2009 model */
double resBitlineMux = ColMux[indexMatchline].resNMOSPassTransistor;
double vpreMin = CAM_cell->readVoltage * resBitlineMux / (resBitlineMux + Col[indexMatchline].res + resMemCellOn);
double vpreMax = CAM_cell->readVoltage * (resBitlineMux + Col[indexMatchline].res) /
(resBitlineMux + Col[indexMatchline].res + resMemCellOn);
searchDynamicEnergy = capCellAccess * vpreMax * vpreMax + ColMux[indexMatchline].capForPreviousPowerCalculation
* vpreMin * vpreMin + Col[indexMatchline].cap * (vpreMax * vpreMax + vpreMin * vpreMin + vpreMax * vpreMin) / 3;
searchDynamicEnergy *= numColumn / muxSenseAmp;
} else { /* voltage-sensing */
searchDynamicEnergy = (capCellAccess + Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousPowerCalculation) *
(voltagePrecharge * voltagePrecharge - voltageMemCellOn * voltageMemCellOn ) * numColumn / muxSenseAmp;
}
// } else if (CAM_cell->memCellType ==FEFETRAM){
// double FEFETCap = CalculateDrainCap(CAM_cell->widthAccessCMOS * FEFET_tech->featureSize, NMOS, CAM_cell->widthInFeatureSize * FEFET_tech->featureSize, *FEFET_tech);
// searchDynamicEnergy = (Col[indexMatchline].cap + ColMux[indexMatchline].capForPreviousPowerCalculation + FEFETCap) *
// (voltagePrecharge * voltagePrecharge) * numColumn / muxSenseAmp;
}// }
}
if (CAM_cell->readPower == 0)
cellReadEnergy = 2 * CAM_cell->CalculateReadPower() * (senseAmp.readLatency + bitlineDelay); /* x2 is because of the reference cell */
else
cellReadEnergy = 2 * CAM_cell->readPower * (senseAmp.readLatency + bitlineDelay);
cellReadEnergy *= numColumn / muxSenseAmp;
// double Singlecellenrgy = 65e-15;
// cellReadEnergy = Singlecellenrgy*numColumn*numRow;
energyDriveSearch0 = 0;
energyDriveSearch1 = 0;
for(int i=0;i<CAM_cell->camNumRow;i++){
energyDriveSearch0 += RowDriver[i].readDynamicEnergy / tech->vdd / tech->vdd
* Row[i].CellPort.volSearch0 * Row[i].CellPort.volSearch0;
energyDriveSearch1 += RowDriver[i].readDynamicEnergy / tech->vdd / tech->vdd
* Row[i].CellPort.volSearch1 * Row[i].CellPort.volSearch1;
}
searchDynamicEnergy += (energyDriveSearch0 + energyDriveSearch1)/2;
readDynamicEnergy = searchDynamicEnergy + inputBuf.readDynamicEnergy * numRow + inputEnc.readDynamicEnergy * numRow
+ cellReadEnergy + ColDecMergeNand.readDynamicEnergy + precharger.readDynamicEnergy
+ senseAmpMuxLev1Nand.readDynamicEnergy + senseAmpMuxLev2Nand.readDynamicEnergy+ ColMux[indexMatchline].readDynamicEnergy
+ senseAmp.readDynamicEnergy + senseAmpMuxLev1.readDynamicEnergy + senseAmpMuxLev2.readDynamicEnergy
+ outputAcc.readDynamicEnergy + priorityEnc.readDynamicEnergy + outputBuf.readDynamicEnergy * numColumn;
searchDynamicEnergy += inputBuf.readDynamicEnergy * numRow + inputEnc.readDynamicEnergy * numRow
+ cellReadEnergy + ColDecMergeNand.readDynamicEnergy + precharger.readDynamicEnergy
+ ColMux[indexMatchline].readDynamicEnergy
+ senseAmp.readDynamicEnergy
+ outputAcc.readDynamicEnergy + priorityEnc.readDynamicEnergy + outputBuf.readDynamicEnergy * numColumn;
//////////////////////////////////////////////////////////////////////////////////
// calc write //
//////////////////////////////////////////////////////////////////////////////////
numBitline = 0;
indexBitline = 0;
// default status is using ML as the BL, as it is in the case of JSSC 2t2r
for(int i=0;i<CAM_cell->camNumCol;i++){
if (Col[i].CellPort.Type == Bitline) {
indexBitline = i;
numBitline++;
}
}
if (CAM_cell->memCellType == SRAM) {
// since the SRAM cell is not flexible, we can make the coding simpler
double capSRAMin;
double capSRAMout;
CalculateGateCapacitance(INV, 1, CAM_cell->widthSRAMCellNMOS, CAM_cell->widthSRAMCellPMOS,
tech->featureSize*MAX_TRANSISTOR_HEIGHT, *tech, &capSRAMin, &capSRAMout);
cellResetEnergy = (capSRAMin + capSRAMout) * tech->vdd * tech->vdd;
cellResetEnergy += (Col[indexBitline].cap + ColMux[indexBitline].capForPreviousPowerCalculation)
* tech->vdd * tech->vdd;
cellSetEnergy = cellResetEnergy;
} else if (CAM_cell->memCellType == MRAM || CAM_cell->memCellType == PCRAM || CAM_cell->memCellType == memristor || CAM_cell->memCellType == FEFETRAM) {
/* Ignore the dynamic transition during the SET/RESET operation */
/* Assume that the cell resistance keeps high for worst-case power estimation */
CAM_cell->CalculateWriteEnergy();
// TODO: MLC MRS set
resetEnergyPerBit = CAM_cell->resetEnergy;
setEnergyPerBit = CAM_cell->setEnergy;
for(int i=0;i<CAM_cell->camNumCol;i++){
// since each line has a description of the set/reset voltage already, we do not need setMode and resetMode in original nvsim anymore
// for current set/reset mode, it has to be converted to the description of voltage set/reset in the cell configuration file
// for example, the matchline voltage will be zero when writing in ISSCC'15 3t1r
setEnergyPerBit += (capCellAccess + Col[indexBitline].cap + ColMux[i].capForPreviousPowerCalculation)
* Col[i].CellPort.volSetLRS * Col[i].CellPort.volSetLRS;
resetEnergyPerBit += (capCellAccess + Col[indexBitline].cap + ColMux[i].capForPreviousPowerCalculation)
* Col[i].CellPort.volReset * Col[i].CellPort.volReset;
}
if (CAM_cell->memCellType == PCRAM) { //PCRAM write energy
if (inputParameter->writeScheme == write_and_verify) {
/*TO-DO: write and verify programming */
} else {
cellResetEnergy = resetEnergyPerBit / SHAPER_EFFICIENCY_CONSERVATIVE;
cellSetEnergy = setEnergyPerBit / SHAPER_EFFICIENCY_CONSERVATIVE; /* Due to the shaper inefficiency */
}
} else { //MRAM and memristor + FEFET write energy
cellResetEnergy = resetEnergyPerBit / SHAPER_EFFICIENCY_AGGRESSIVE;
cellSetEnergy = setEnergyPerBit / SHAPER_EFFICIENCY_AGGRESSIVE; /* Due to the shaper inefficiency */
}
leakage = 0; //TO-DO: cell leaks during read/write operation
}
writeDynamicEnergy = MAX(cellResetEnergy, cellSetEnergy);
cellResetEnergy *= numColumn / muxSenseAmp / muxOutputLev1 / muxOutputLev2;
cellSetEnergy *= numColumn / muxSenseAmp / muxOutputLev1 / muxOutputLev2;
writeDynamicEnergy *= numColumn / muxSenseAmp / muxOutputLev1 / muxOutputLev2;
// TODO: does not calculate MLC case
setDynamicEnergy = resetDynamicEnergy = 0;
for(int i=0;i<CAM_cell->camNumRow;i++){
setDynamicEnergy += RowDriver[i].writeDynamicEnergy / tech->vdd / tech->vdd
* Row[i].CellPort.volSetLRS * Row[i].CellPort.volSetLRS;
resetDynamicEnergy += RowDriver[i].writeDynamicEnergy / tech->vdd / tech->vdd
* Row[i].CellPort.volReset * Row[i].CellPort.volReset;
writeDynamicEnergy += RowDriver[i].writeDynamicEnergy /*/ tech->vdd / tech->vdd
* (Row[i].CellPort.volReset + Row[i].CellPort.volSetLRS) * (Row[i].CellPort.volSetLRS + Row[i].CellPort.volReset)*/;
}
for(int i=0;i<CAM_cell->camNumCol;i++){
if(indexBitline == i && i > 0) {
// this is skipping the matchline that is not used in writing
continue;
}
setDynamicEnergy += ColMux[i].writeDynamicEnergy;
resetDynamicEnergy += ColMux[i].writeDynamicEnergy;
writeDynamicEnergy += ColMux[i].writeDynamicEnergy;
}
if (indexBitline == 0) {
// ML is also used in the writing operations
setDynamicEnergy += senseAmp.writeDynamicEnergy;
resetDynamicEnergy += senseAmp.writeDynamicEnergy;
writeDynamicEnergy += senseAmp.writeDynamicEnergy;
}
WriteDriverDyn = 0;
WriteDriverLeakage = 0;
if (withWriteDriver) {
for(int i=0;i<CAM_cell->camNumCol;i++){
if (WriteDriver[i].initialized) {
WriteDriver[i].CalculatePower();
WriteDriverDyn += WriteDriver[i].writeDynamicEnergy;
}
}
}
writeDynamicEnergy += ColDecMergeNand.writeDynamicEnergy + WriteDriverDyn
+ senseAmpMuxLev1Nand.writeDynamicEnergy + senseAmpMuxLev2Nand.writeDynamicEnergy
+ senseAmpMuxLev1.writeDynamicEnergy + senseAmpMuxLev2.writeDynamicEnergy;
// cout << "Write Dynamic Energy in Subarray: " << writeDynamicEnergy << endl;
/* for assymetric RESET and SET latency calculation only */
setDynamicEnergy += cellSetEnergy + ColDecMergeNand.writeDynamicEnergy
+ senseAmpMuxLev1Nand.writeDynamicEnergy + senseAmpMuxLev2Nand.writeDynamicEnergy
+ senseAmpMuxLev1.writeDynamicEnergy + senseAmpMuxLev2.writeDynamicEnergy;
resetDynamicEnergy += setDynamicEnergy + ColDecMergeNand.writeDynamicEnergy
+ senseAmpMuxLev1Nand.writeDynamicEnergy + senseAmpMuxLev2Nand.writeDynamicEnergy
+ senseAmpMuxLev1.writeDynamicEnergy + senseAmpMuxLev2.writeDynamicEnergy;
//////////////////////////////////////////////////////////////////////////////////
// calc leakage //
//////////////////////////////////////////////////////////////////////////////////
// leakage inside the cell
if (CAM_cell->memCellType == SRAM) {
leakage = CalculateGateLeakage(INV, 1, CAM_cell->widthSRAMCellNMOS * tech->featureSize,
CAM_cell->widthSRAMCellPMOS * tech->featureSize, inputParameter->temperature, *tech)
* tech->vdd * 2; /* two inverters per SRAM cell */
leakage += CalculateGateLeakage(INV, 1, CAM_cell->widthAccessCMOS * tech->featureSize, 0,
inputParameter->temperature, *tech) * tech->vdd; /* two accesses NMOS, but combined as one with vdd crossed */
leakage += CalculateGateLeakage(INV, 1, CAM_cell->widthAccessCMOS * tech->featureSize, 0,
inputParameter->temperature, *tech) * tech->vdd; /* two accesses NMOS, but combined as one with vdd crossed */
leakage += CalculateGateLeakage(INV, 1, CAM_cell->camWidthMatchTran * tech->featureSize, 0,
inputParameter->temperature, *tech) * tech->vdd; /* two accesses NMOS, but combined as one with vdd crossed */
leakage *= 2;
} else if (CAM_cell->memCellType == MRAM || CAM_cell->memCellType == PCRAM || CAM_cell->memCellType == memristor || CAM_cell->memCellType ==FEFETRAM) {
// TODO: i am here
// basically count the transistors in the cell
// the trick here is that every thransistor in the cell should be connected by some line to the gate to control it
// the exception is the matchline transistor in cmos-access, like ISSCC'15 3t1r
leakage = 0;
for(int i=0;i<CAM_cell->camNumRow;i++){
if (Row[i].CellPort.ConnectedRegoin == gate && Row[i].CellPort.leak) {
if (Row[i].CellPort.isNMOS)
leakage += CalculateGateLeakage(INV, 1, Row[i].CellPort.widthCmos * tech->featureSize, 0,
inputParameter->temperature, *tech) * tech->vdd;
else
leakage += CalculateGateLeakage(INV, 1, 0, Row[i].CellPort.widthCmos * tech->featureSize,
inputParameter->temperature, *tech) * tech->vdd;
}
}
for(int i=0;i<CAM_cell->camNumCol;i++){
if (Col[i].CellPort.ConnectedRegoin == gate && Col[i].CellPort.leak) {
if (Col[i].CellPort.isNMOS)
leakage += CalculateGateLeakage(INV, 1, Col[i].CellPort.widthCmos * tech->featureSize, 0,
inputParameter->temperature, *tech) * tech->vdd;
else
leakage += CalculateGateLeakage(INV, 1, 0, Col[i].CellPort.widthCmos * tech->featureSize,
inputParameter->temperature, *tech) * tech->vdd;
}
}
if (CAM_cell->accessType == CMOS_access) {
leakage += CalculateGateLeakage(INV, 1, CAM_cell->camWidthMatchTran * tech->featureSize, 0,
inputParameter->temperature, *tech) * tech->vdd;
}
} else {
invalid = true;
cout <<"[CAM_SubArray] Error: cell type input error" <<endl;
return;
}
leakage *= numRow * numColumn;
//////////////////////////
double leak = 0;
for(int i=0;i<CAM_cell->camNumRow;i++){
leakage += RowDriver[i].leakage;
leak += RowDriver[i].leakage;
}
for(int i=0;i<CAM_cell->camNumCol;i++){
leakage += ColMux[i].leakage;
leak += ColMux[i].leakage;
}
leakage += inputBuf.leakage * numColumn + inputEnc.leakage + precharger.leakage + senseAmpMuxLev1Nand.leakage
+ senseAmpMuxLev2Nand.leakage + ColDecMergeNand.leakage + WriteDriverLeakage + senseAmp.leakage
+ senseAmpMuxLev1.leakage + senseAmpMuxLev2.leakage + outputAcc.leakage + priorityEnc.leakage
+ outputBuf.leakage * numColumn;
leak += inputBuf.leakage * numColumn + inputEnc.leakage + precharger.leakage + senseAmpMuxLev1Nand.leakage
+ senseAmpMuxLev2Nand.leakage + ColDecMergeNand.leakage + WriteDriverLeakage + senseAmp.leakage
+ senseAmpMuxLev1.leakage + senseAmpMuxLev2.leakage + outputAcc.leakage + priorityEnc.leakage
+ outputBuf.leakage * numColumn;
//cout << "leakage energy of peripherals: " << leak * 1e9 << endl;
}
}
void CAM_SubArray::PrintProperty() {
cout << "CAMSubarray Properties:" << endl;
//FunctionUnit::PrintProperty();
cout << "numRow:" << numRow << " numColumn:" << numColumn << endl;
// area wise
cout << "Input Encoder Area:" << inputEnc.area*1e12 << " um^2 (" << inputEnc.area/area*100 << "%)" << endl;
for(int i=0;i<CAM_cell->camNumRow;i++){
cout << "Row Driver " << i << " Area:" << RowDriver[i].area*1e12 << " um^2 (" << RowDriver[i].area/area*100 << "%)" <<endl;
}
cout << "lenWordline * lenBitline = " << lenRow*1e6 << " um * " << lenCol*1e6 << " um = " << lenRow * lenCol * 1e12
<< " um^2 (" << lenRow * lenCol/area*100 << "%)" << endl;
cout << "MergeDecoderNand Area:" << RowDecMergeNand.area*1e12 << " um^2 (" << RowDecMergeNand.area/area*100 << "%)" << endl;
for(int i=0;i<CAM_cell->camNumCol;i++){
cout << "Col Mux " << i << " Area:" << ColMux[i].area*1e12 << " um^2 (" << ColMux[i].area/area*100 << "%)" << endl;
}
cout << "Write Driver Area:" << WriteDriverArea*1e12 << " um^2 (" << WriteDriverArea/area*100 << "%)" << endl;
cout << "Mux Area:" << inputEnc.area*1e12 << " um^2" << endl;
cout << "Sense Amplifier Area:" << senseAmp.area*1e12 << " um^2 (" << senseAmp.area/area*100 << "%)" << endl;
cout << "Output Acc Area:" << outputAcc.area*1e12 << " um^2 (" << outputAcc.area/area*100 << "%)" << endl;
cout << "Priority Encoder Area:" << priorityEnc.area*1e12 << " um^2 (" << priorityEnc.area/area*100 << "%)" << endl;
// TODO: not done with debug interface yet
cout << "bitlineDelay: " << bitlineDelay*1e12 << "ps" << endl;
cout << "chargeLatency: " << chargeLatency*1e12 << "ps" << endl;
cout << "columnDecoderLatency: " << columnDecoderLatency*1e12 << "ps" << endl;
cout << "errors exist here!" << endl;
}
CAM_SubArray & CAM_SubArray::operator=(const CAM_SubArray &rhs) {
// TODO: did not go through clearly
height = rhs.height;
width = rhs.width;
area = rhs.area;
readLatency = rhs.readLatency;
writeLatency = rhs.writeLatency;
readDynamicEnergy = rhs.readDynamicEnergy;
writeDynamicEnergy = rhs.writeDynamicEnergy;
resetLatency = rhs.resetLatency;
setLatency = rhs.setLatency;
resetDynamicEnergy = rhs.resetDynamicEnergy;
setDynamicEnergy = rhs.setDynamicEnergy;
cellReadEnergy = rhs.cellReadEnergy;
cellResetEnergy = rhs.cellResetEnergy;
cellSetEnergy = rhs.cellSetEnergy;
leakage = rhs.leakage;
initialized = rhs.initialized;
numRow = rhs.numRow;
numColumn = rhs.numColumn;
multipleRowPerSet = rhs.multipleRowPerSet;
split = rhs.split;
muxSenseAmp = rhs.muxSenseAmp;
internalSenseAmp = rhs.internalSenseAmp;
muxOutputLev1 = rhs.muxOutputLev1;
muxOutputLev2 = rhs.muxOutputLev2;
voltageSense = rhs.voltageSense;
senseVoltage = rhs.senseVoltage;
numSenseAmp = rhs.numSenseAmp;
resCellAccess = rhs.resCellAccess;
capCellAccess = rhs.capCellAccess;
bitlineDelay = rhs.bitlineDelay;
chargeLatency = rhs.chargeLatency;
columnDecoderLatency = rhs.columnDecoderLatency;
bitlineDelayOn = rhs.bitlineDelayOn;
bitlineDelayOff = rhs.bitlineDelayOff;
/////////////////////////////
tau = rhs.tau;
Basetau = rhs.Basetau;
SenseTime = rhs.SenseTime;
MatchlineSenseMargin = rhs.MatchlineSenseMargin;
//////////////////////////////
resInSerialForSenseAmp = rhs.resInSerialForSenseAmp;
resEquivalentOn = rhs.resEquivalentOn;
resEquivalentOff = rhs.resEquivalentOff;
resMemCellOff = rhs.resMemCellOff;
resMemCellOn = rhs.resMemCellOn;
senseAmpMuxLev1 = rhs.senseAmpMuxLev1;
senseAmpMuxLev2 = rhs.senseAmpMuxLev2;
precharger = rhs.precharger;
senseAmp = rhs.senseAmp;
inputEnc = rhs.inputEnc;
RowDecMergeNand = rhs.RowDecMergeNand;
for(int i=0;i<MAX_PORT;i++){
RowDriver[i] = rhs.RowDriver[i];
}
precharger = rhs.precharger;
ColDecMergeNand = rhs.ColDecMergeNand;
for(int i=0;i<MAX_PORT;i++){
ColMux[i] = rhs.ColMux[i];
}
senseAmpMuxLev1Nand = rhs.senseAmpMuxLev1Nand;
senseAmpMuxLev2Nand = rhs.senseAmpMuxLev2Nand;
outputAcc = rhs.outputAcc;
priorityEnc = rhs.priorityEnc;
numRow = rhs.numRow;
numColumn = rhs.numColumn;
lenRow = rhs.lenRow;
lenCol = rhs.lenCol;
indexMatchline = rhs.indexMatchline;
indexBitline = rhs.indexBitline;
numBitline = rhs.numBitline;
for(int i=0;i<MAX_PORT;i++){
Row[i] = rhs.Row[i];
Col[i] = rhs.Col[i];
}
withInputEnc = rhs.withInputEnc;
typeInputEnc = rhs.typeInputEnc;
customInputEnc = rhs.customInputEnc;
DecMergeOptLevel = rhs.DecMergeOptLevel;
RowDecMergeInv = rhs.RowDecMergeInv;
DriverOptLevel = rhs.DriverOptLevel;
voltagePrecharge = rhs.voltagePrecharge;
typeSenseAmp = rhs.typeSenseAmp;
customSenseAmp = rhs.customSenseAmp;
senseMargin = rhs.senseMargin;
withOutputAcc = rhs.withOutputAcc;
withPriorityEnc = rhs.withPriorityEnc;
PriorityOptLevel = rhs.PriorityOptLevel;
withWriteDriver = rhs.withWriteDriver;
WriteDriverArea = rhs.WriteDriverArea;
WriteDriverLatency = rhs.WriteDriverLatency;
WriteDriverDyn = rhs.WriteDriverDyn;
WriteDriverLeakage = rhs.WriteDriverLeakage;
withInputBuf = rhs.withInputBuf;
withOutputBuf = rhs.withOutputBuf;
senseAmpLatency = rhs.senseAmpLatency;
referDelay = rhs.referDelay;
volMatchDrop = rhs.volMatchDrop;
volAllMissDrop = rhs.volAllMissDrop;
decoderLatency = rhs.decoderLatency;
bitlineRamp = rhs.bitlineRamp;
chargeLatency = rhs.chargeLatency;
searchLatency = rhs.searchLatency;
searchDynamicEnergy = rhs.searchDynamicEnergy;
energyDriveSearch0 = rhs.energyDriveSearch0;
energyDriveSearch1 = rhs.energyDriveSearch1;
rampOutput = rhs.rampOutput;
resetEnergyPerBit = rhs.resetEnergyPerBit;
setEnergyPerBit = rhs.setEnergyPerBit;
return *this;
}
| 50.352901 | 245 | 0.682037 | [
"model"
] |
430610f219e14def41284a48912cb9617d7bfc13 | 10,909 | cpp | C++ | external/bayesopt/tests/testchol.cpp | pchrapka/brain-modelling | f232b5a858e45f10b0b0735269010454129ab017 | [
"MIT"
] | 1 | 2017-10-13T19:37:52.000Z | 2017-10-13T19:37:52.000Z | external/bayesopt/tests/testchol.cpp | pchrapka/brain-modelling | f232b5a858e45f10b0b0735269010454129ab017 | [
"MIT"
] | null | null | null | external/bayesopt/tests/testchol.cpp | pchrapka/brain-modelling | f232b5a858e45f10b0b0735269010454129ab017 | [
"MIT"
] | 1 | 2019-11-25T12:22:05.000Z | 2019-11-25T12:22:05.000Z | /** -*- c++ -*- \file cholesky_test.cpp \brief test cholesky decomposition */
/*
- begin : 2005-08-24
- copyright : (C) 2005 by Gunter Winkler, Konstantin Kutzkow
- email : guwi17@gmx.de
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cassert>
#include <limits>
#include <boost/timer.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/banded.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/io.hpp>
#include "ublas_cholesky.hpp"
namespace ublas = boost::numeric::ublas;
namespace bayesopt
{
namespace utils
{
/** \brief make a immutable triangular adaptor from a matrix
*
* \usage:
<code>
A = triangular< lower >(B);
A = triangular(B, lower());
</code>
*/
template < class TYPE, class MATRIX >
ublas::triangular_adaptor<const MATRIX, TYPE>
triangular(const MATRIX & A, const TYPE& uplo = TYPE())
{
return ublas::triangular_adaptor<const MATRIX, TYPE>(A);
}
/** \brief make a immutable banded adaptor from a matrix
*
* \usage:
<code>
A = banded(B, lower, upper);
</code>
*/
template < class MATRIX >
ublas::banded_adaptor<const MATRIX>
banded(const MATRIX & A, const size_t lower, const size_t upper)
{
return ublas::banded_adaptor<const MATRIX>(A, lower, upper);
}
/** \brief make a immutable symmetric adaptor from a matrix
*
* \usage:
<code>
A = symmetric< lower >(B);
A = symmetric(B, lower());
</code>
*/
template < class TYPE, class MATRIX >
ublas::symmetric_adaptor<const MATRIX, TYPE>
symmetric(const MATRIX & A, const TYPE& uplo = TYPE())
{
return ublas::symmetric_adaptor<const MATRIX, TYPE>(A);
}
/** \brief fill lower triangular matrix L
*/
template < class MATRIX >
void fill_symm(MATRIX & L, const size_t bands = std::numeric_limits<size_t>::max() )
{
typedef typename MATRIX::size_type size_type;
assert(L.size1() == L.size2());
size_type size = L.size1();
for (size_type i=0; i<size; i++) {
for (size_type j = ((i>bands)?(i-bands):0); j<i; j++) {
L(i,j) = 1 + (1.0 + i)/(1.0 + j) + 1.0 / (0.5 + i - j);
}
L(i,i) = 1+i+size;
}
return;
}
int main_(int argc, char * argv[] )
{
size_t size = 10;
if (argc > 1)
size = ::atoi (argv [1]);
boost::timer t1;
double pr, de, sv;
typedef double DBL;
typedef ublas::row_major ORI;
{
// use dense matrix
ublas::matrix<DBL, ORI> A (size, size);
ublas::matrix<DBL, ORI> T (size, size);
ublas::matrix<DBL, ORI> L (size, size);
A = ublas::zero_matrix<DBL>(size, size);
ublas::vector<DBL> b (size);
ublas::vector<DBL> x (size);
ublas::vector<DBL> y (size);
std::fill(y.begin(), y.end(), 1.0);
fill_symm(T);
t1.restart();
A = ublas::prod(T, trans(T));
pr = t1.elapsed();
b = prod( A, y);
t1.restart();
size_t res = cholesky_decompose(A, L);
de = t1.elapsed();
t1.restart();
x = b;
cholesky_solve(L, x, ublas::lower());
sv = t1.elapsed();
std::cout << res << ": "
<< ublas::norm_inf(L-T) << " "
<< ublas::norm_2(x-y) << " "
<< " (deco: " << de << " sec)"
<< " (prod: " << pr << " sec)"
<< " (solve: " << sv << " sec)"
<< " " << size
<< std::endl;
}
{
// use dense triangular matrices
ublas::triangular_matrix<DBL, ublas::lower, ORI> A (size, size);
ublas::triangular_matrix<DBL, ublas::lower, ORI> T (size, size);
ublas::triangular_matrix<DBL, ublas::lower, ORI> L (size, size);
A = ublas::zero_matrix<DBL> (size, size) ;
A = triangular<ublas::lower>( ublas::zero_matrix<DBL> (size, size) );
A = triangular( ublas::zero_matrix<DBL> (size, size), ublas::lower() );
ublas::vector<DBL> b (size);
ublas::vector<DBL> x (size);
ublas::vector<DBL> y (size);
std::fill(y.begin(), y.end(), 1.0);
fill_symm(T);
t1.restart();
A = triangular<ublas::lower>( ublas::prod(T, trans(T)) );
pr = t1.elapsed();
b = prod( symmetric<ublas::lower>(A), y);
t1.restart();
size_t res = cholesky_decompose(A, L);
de = t1.elapsed();
t1.restart();
x = b;
cholesky_solve(L, x, ublas::lower());
sv = t1.elapsed();
std::cout << res << ": "
<< ublas::norm_inf(L-T) << " "
<< ublas::norm_2(x-y) << " "
<< " (deco: " << de << " sec)"
<< " (prod: " << pr << " sec)"
<< " (solve: " << sv << " sec)"
<< " " << size
<< std::endl;
// std::cout << L << std::endl;
// std::cout << b << std::endl;
// std::cout << x << std::endl;
// std::cout << y << std::endl;
// std::cout << (b - prod(symmetric<ublas::lower>(A), x)) << std::endl;
}
{
// use banded matrices matrix
typedef ublas::banded_matrix<DBL, ORI> MAT;
size_t bands = std::min<size_t>( size, 50 );
MAT A (size, size, bands, 0);
MAT T (size, size, bands, 0);
MAT L (size, size, bands, 0);
A = ublas::zero_matrix<DBL> (size, size) ;
A = banded( ublas::zero_matrix<DBL> (size, size), bands, 0 );
ublas::vector<DBL> b (size);
ublas::vector<DBL> x (size);
ublas::vector<DBL> y (size);
std::fill(y.begin(), y.end(), 1.0);
fill_symm(T, bands);
t1.restart();
A = banded( ublas::prod(T, trans(T)), bands, 0 );
pr = t1.elapsed();
b = prod( symmetric<ublas::lower>(A), y);
t1.restart();
size_t res = cholesky_decompose(A, L);
de = t1.elapsed();
t1.restart();
x = b;
cholesky_solve(L, x, ublas::lower());
sv = t1.elapsed();
std::cout << res << ": "
<< ublas::norm_inf(L-T) << " "
<< ublas::norm_2(x-y) << " "
<< " (deco: " << de << " sec)"
<< " (prod: " << pr << " sec)"
<< " (solve: " << sv << " sec)"
<< " " << size
<< std::endl;
}
return EXIT_SUCCESS;
}
}
}
int main(int argc, char * argv[] )
{ return bayesopt::utils::main_(argc,argv); }
/****************
(note: dense + tria + 50 banded)
$ g++-4.0 -I $HOME/include -o cholesky_test cholesky_test.cpp -Wall -g -O2 -DNDEBUG
(column major, double)
0: 3.05533e-13 1.78207e-14 (deco: 0 sec) (prod: 0 sec) (solve: 0 sec) 100
0: 3.05533e-13 1.78207e-14 (deco: 0 sec) (prod: 0.01 sec) (solve: 0 sec) 100
0: 1.97176e-13 9.0801e-15 (deco: 0 sec) (prod: 0 sec) (solve: 0 sec) 100
0: 1.18172e-12 5.82623e-14 (deco: 0 sec) (prod: 0.06 sec) (solve: 0 sec) 200
0: 1.18172e-12 5.82623e-14 (deco: 0.03 sec) (prod: 0.03 sec) (solve: 0 sec) 200
0: 1.15463e-13 1.01481e-14 (deco: 0.01 sec) (prod: 0.01 sec) (solve: 0 sec) 200
0: 4.80105e-12 2.13833e-13 (deco: 0.1 sec) (prod: 0.58 sec) (solve: 0 sec) 400
0: 4.80105e-12 2.13833e-13 (deco: 0.22 sec) (prod: 0.22 sec) (solve: 0.01 sec) 400
0: 6.39488e-14 1.14428e-14 (deco: 0.02 sec) (prod: 0.02 sec) (solve: 0.01 sec) 400
0: 1.80402e-11 3.72721e-13 (deco: 1.27 sec) (prod: 9.87 sec) (solve: 0 sec) 800
0: 1.80402e-11 3.72721e-13 (deco: 2.16 sec) (prod: 2.13 sec) (solve: 0.04 sec) 800
0: 4.04121e-14 1.52388e-14 (deco: 0.05 sec) (prod: 0.05 sec) (solve: 0.01 sec) 800
0: 7.85829e-11 1.51858e-12 (deco: 33.5 sec) (prod: 279.15 sec) (solve: 0.05 sec) 1600
0: 7.85829e-11 1.51858e-12 (deco: 21.8 sec) (prod: 22.45 sec) (solve: 0.18 sec) 1600
0: 2.26485e-14 1.98783e-14 (deco: 0.19 sec) (prod: 0.09 sec) (solve: 0.01 sec) 1600
(row major, double)
0: 3.05533e-13 1.78207e-14 (deco: 0 sec) (prod: 0 sec) (solve: 0 sec) 100
0: 3.05533e-13 1.78207e-14 (deco: 0 sec) (prod: 0 sec) (solve: 0 sec) 100
0: 1.97176e-13 9.0801e-15 (deco: 0.01 sec) (prod: 0 sec) (solve: 0 sec) 100
0: 1.18172e-12 5.82623e-14 (deco: 0.01 sec) (prod: 0.02 sec) (solve: 0 sec) 200
0: 1.18172e-12 5.82623e-14 (deco: 0.02 sec) (prod: 0.02 sec) (solve: 0 sec) 200
0: 1.15463e-13 1.01481e-14 (deco: 0.01 sec) (prod: 0.01 sec) (solve: 0 sec) 200
0: 4.80105e-12 2.13833e-13 (deco: 0.03 sec) (prod: 0.21 sec) (solve: 0.01 sec) 400
0: 4.80105e-12 2.13833e-13 (deco: 0.08 sec) (prod: 0.09 sec) (solve: 0.01 sec) 400
0: 6.39488e-14 1.14428e-14 (deco: 0.02 sec) (prod: 0.02 sec) (solve: 0 sec) 400
0: 1.80402e-11 3.72721e-13 (deco: 0.37 sec) (prod: 1.51 sec) (solve: 0 sec) 800
0: 1.80402e-11 3.72721e-13 (deco: 0.69 sec) (prod: 0.57 sec) (solve: 0.03 sec) 800
0: 4.04121e-14 1.52388e-14 (deco: 0.06 sec) (prod: 0.04 sec) (solve: 0 sec) 800
0: 7.85829e-11 1.51858e-12 (deco: 2.57 sec) (prod: 11.26 sec) (solve: 0.05 sec) 1600
0: 7.85829e-11 1.51858e-12 (deco: 4.98 sec) (prod: 4.43 sec) (solve: 0.15 sec) 1600
0: 2.26485e-14 1.98783e-14 (deco: 0.21 sec) (prod: 0.06 sec) (solve: 0.01 sec) 1600
$ g++-3.3.5 -I $HOME/include -o cholesky_test cholesky_test.cpp -Wall -g -O2 -DNDEBUG
0: 6.72351e-13 7.10356e-14 (deco: 0.01 sec) (prod: 0.02 sec) (solve: 0 sec) 100
0: 6.72351e-13 7.10356e-14 (deco: 0.01 sec) (prod: 0.01 sec) (solve: 0 sec) 100
0: 1.12355e-13 1.96079e-14 (deco: 0.01 sec) (prod: 0 sec) (solve: 0 sec) 100
0: 2.61746e-12 2.75266e-13 (deco: 0.02 sec) (prod: 0.15 sec) (solve: 0 sec) 200
0: 2.61746e-12 2.75266e-13 (deco: 0.05 sec) (prod: 0.07 sec) (solve: 0 sec) 200
0: 7.32747e-14 1.38831e-14 (deco: 0.02 sec) (prod: 0.02 sec) (solve: 0 sec) 200
0: 1.02713e-11 1.33167e-12 (deco: 0.18 sec) (prod: 1.04 sec) (solve: 0 sec) 400
0: 1.02713e-11 1.33167e-12 (deco: 0.39 sec) (prod: 0.4 sec) (solve: 0.01 sec) 400
0: 3.33067e-14 1.4327e-14 (deco: 0.03 sec) (prod: 0.04 sec) (solve: 0 sec) 400
0: 4.21783e-11 3.23897e-12 (deco: 1.55 sec) (prod: 8.1 sec) (solve: 0.01 sec) 800
0: 4.21783e-11 3.23897e-12 (deco: 3.17 sec) (prod: 3.07 sec) (solve: 0.02 sec) 800
0: 1.42109e-14 1.87039e-14 (deco: 0.09 sec) (prod: 0.06 sec) (solve: 0 sec) 800
0: 1.6946e-10 9.93422e-12 (deco: 12.09 sec) (prod: 64.96 sec) (solve: 0.07 sec) 1600
0: 1.6946e-10 9.93422e-12 (deco: 24.72 sec) (prod: 24.28 sec) (solve: 0.1 sec) 1600
0: 1.15463e-14 2.46404e-14 (deco: 0.28 sec) (prod: 0.1 sec) (solve: 0 sec) 1600
****************/
| 33.669753 | 86 | 0.591072 | [
"vector"
] |
4308d18ef743e1cbf756ff17bd0424016d1fe734 | 4,186 | cc | C++ | chrome/browser/debugger/devtools_remote_service.cc | zachlatta/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2021-09-24T22:49:10.000Z | 2021-09-24T22:49:10.000Z | chrome/browser/debugger/devtools_remote_service.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/debugger/devtools_remote_service.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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 "base/json_reader.h"
#include "base/json_writer.h"
#include "base/scoped_ptr.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_protocol_handler.h"
#include "chrome/browser/debugger/devtools_remote_message.h"
#include "chrome/browser/debugger/devtools_remote_service.h"
#include "chrome/browser/debugger/inspectable_tab_proxy.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/common/devtools_messages.h"
const std::string DevToolsRemoteServiceCommand::kPing = "ping";
const std::string DevToolsRemoteServiceCommand::kVersion = "version";
const std::string DevToolsRemoteServiceCommand::kListTabs = "list_tabs";
const std::wstring DevToolsRemoteService::kCommandWide = L"command";
const std::wstring DevToolsRemoteService::kDataWide = L"data";
const std::wstring DevToolsRemoteService::kResultWide = L"result";
const std::string DevToolsRemoteService::kToolName = "DevToolsService";
DevToolsRemoteService::DevToolsRemoteService(DevToolsProtocolHandler* delegate)
: delegate_(delegate) {}
DevToolsRemoteService::~DevToolsRemoteService() {}
void DevToolsRemoteService::HandleMessage(
const DevToolsRemoteMessage& message) {
scoped_ptr<Value> request(JSONReader::Read(message.content(), false));
if (request.get() == NULL) {
// Bad JSON
NOTREACHED();
return;
}
DictionaryValue* json;
if (request->IsType(Value::TYPE_DICTIONARY)) {
json = static_cast<DictionaryValue*>(request.get());
if (!json->HasKey(kCommandWide)) {
NOTREACHED(); // Broken protocol - no "command" specified
return;
}
} else {
NOTREACHED(); // Broken protocol - not a JS object
return;
}
ProcessJson(json, message);
}
void DevToolsRemoteService::ProcessJson(DictionaryValue* json,
const DevToolsRemoteMessage& message) {
static const std::string kOkResponse = "ok"; // "Ping" response
static const std::string kVersion = "0.1"; // Current protocol version
std::string command;
DictionaryValue response;
json->GetString(kCommandWide, &command);
response.SetString(kCommandWide, command);
if (command == DevToolsRemoteServiceCommand::kPing) {
response.SetInteger(kResultWide, Result::kOk);
response.SetString(kDataWide, kOkResponse);
} else if (command == DevToolsRemoteServiceCommand::kVersion) {
response.SetInteger(kResultWide, Result::kOk);
response.SetString(kDataWide, kVersion);
} else if (command == DevToolsRemoteServiceCommand::kListTabs) {
ListValue* data = new ListValue();
const InspectableTabProxy::ControllersMap& navcon_map =
delegate_->inspectable_tab_proxy()->controllers_map();
for (InspectableTabProxy::ControllersMap::const_iterator it =
navcon_map.begin(), end = navcon_map.end(); it != end; ++it) {
NavigationEntry* entry = it->second->GetActiveEntry();
if (entry == NULL) {
continue;
}
if (entry->url().is_valid()) {
ListValue* tab = new ListValue();
tab->Append(Value::CreateIntegerValue(
static_cast<int32>(it->second->session_id().id())));
tab->Append(Value::CreateStringValue(entry->url().spec()));
data->Append(tab);
}
}
response.SetInteger(kResultWide, Result::kOk);
response.Set(kDataWide, data);
} else {
// Unknown protocol command.
NOTREACHED();
response.SetInteger(kResultWide, Result::kUnknownCommand);
}
std::string response_json;
JSONWriter::Write(&response, false, &response_json);
scoped_ptr<DevToolsRemoteMessage> response_message(
DevToolsRemoteMessageBuilder::instance().Create(message.tool(),
message.destination(),
response_json));
delegate_->Send(*response_message.get());
}
| 40.25 | 79 | 0.704252 | [
"object"
] |
43097a449fcabf03f8b21a6c269cd2ac06c4173d | 1,011 | hpp | C++ | qubus/include/qubus/kernel_arguments.hpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/include/qubus/kernel_arguments.hpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/include/qubus/kernel_arguments.hpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | #ifndef QUBUS_KERNEL_ARGUMENTS_HPP
#define QUBUS_KERNEL_ARGUMENTS_HPP
#include <qubus/object.hpp>
#include <qubus/util/unused.hpp>
#include <memory>
#include <utility>
#include <vector>
namespace qubus
{
class kernel_arguments
{
public:
kernel_arguments() = default;
std::vector<object>& args()
{
return arguments_;
}
const std::vector<object>& args() const
{
return arguments_;
}
void push_back_arg(object arg)
{
arguments_.push_back(arg);
}
std::vector<object>& results()
{
return results_;
}
const std::vector<object>& results() const
{
return results_;
}
void push_back_result(object result)
{
results_.push_back(result);
}
template <typename Archive>
void serialize(Archive& ar, unsigned QUBUS_UNUSED(version))
{
ar& arguments_;
ar& results_;
}
private:
std::vector<object> arguments_;
std::vector<object> results_;
};
}
#endif
| 15.796875 | 63 | 0.626113 | [
"object",
"vector"
] |
430985d249898b2cd3fc929c9a5edb46edf47a72 | 1,015 | cpp | C++ | _includes/analises/regional2015/A-mania-de-par.cpp | leandrovianna/maratonago.github.io | 93789b5ce1f29d5dead774008efc4b00ee2966d4 | [
"Unlicense"
] | null | null | null | _includes/analises/regional2015/A-mania-de-par.cpp | leandrovianna/maratonago.github.io | 93789b5ce1f29d5dead774008efc4b00ee2966d4 | [
"Unlicense"
] | null | null | null | _includes/analises/regional2015/A-mania-de-par.cpp | leandrovianna/maratonago.github.io | 93789b5ce1f29d5dead774008efc4b00ee2966d4 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
typedef long long int64;
typedef unsigned long long uint64;
using namespace std;
int dist[1<<15];
vector<pair<int,int>> gr[1<<14];
int main(int argc, char* argv[]) {
ios::sync_with_stdio(false);
int C, V, C1, C2, G;
cin >> C >> V;
for (int i = 1; i <= C; ++i) dist[i<<1] = dist[(i<<1)|1] = 2e9;
while (V--) {
cin >> C1 >> C2 >> G;
gr[C1].push_back(make_pair(C2,G));
gr[C2].push_back(make_pair(C1,G));
}
priority_queue<pair<int,int>> q;
dist[2] = 0;
q.push(make_pair(0, 2));
while (!q.empty()) {
int d = -q.top().first;
int u = q.top().second; q.pop();
int p = u & 1;
u >>= 1;
if ((u == C) && !p) break;
p = 1-p;
for (auto &w : gr[u]) {
int v = (w.first<<1)|p;
int nd = d+w.second;
if (nd < dist[v]) {
dist[v] = nd;
q.push(make_pair(-nd, v));
}
}
}
if (dist[(C<<1)] == 2e9) dist[C<<1] = -1;
cout << dist[C<<1] << "\n";
return 0;
}
| 19.901961 | 67 | 0.471921 | [
"vector"
] |
430de0e09ae3a21753ac1d7f4e8f9b8bfd0a7787 | 4,525 | cpp | C++ | Dynamic Programming/472. Concatenated Words.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | Dynamic Programming/472. Concatenated Words.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | Dynamic Programming/472. Concatenated Words.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z |
class Solution {
public:
unordered_set<string>dict;
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
for(auto i: words)
dict.insert(i);
vector<string>res;
for(auto s: words)
if(check(s, 0, 0))
res.push_back(s);
return res;
}
bool check(const string& s, int beg, int count){
if(beg == s.size() && count > 1){
return true;
}
for(int i = beg; i<s.size();i++){
if(dict.count(s.substr(beg,i-beg+1)) && check(s, i+1, count+1)){
return true;
}
}
return false;
}
};
/*
更efficient的解
*/
class Solution {
vector<string> results;
unordered_set<string> dict;
int min_len = 1;
bool isConcatenated(string const & word)
{
if (dict.count(word)) return true;
for (int i = min_len; i < word.size() - min_len + 1 ; ++ i)
if (dict.count(word.substr(0, i)) > 0 && isConcatenated(word.substr(i, word.size() - i)))
return true;
return false;
}
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
sort(words.begin(), words.end(), [](const string &lhs, const string &rhs){return lhs.size() < rhs.size();});
min_len = max(1ul, words.front().size());
for (int i = 0; i < words.size(); dict.insert(words[i++]))
if (words[i].size() >= min_len * 2 && isConcatenated(words[i]))
results.push_back(words[i]);
return results;
}
};
/*
DP solution much slower, 慢的原因是比如dogcatsdog,找到0,3 是dog了,而不是继续往下找别的
而是继续(0,5), (0,6), (0,7)属不属于别的single word,而不是从(3,5),(3,6),(3,7)
0后是(1,3),(1,4),(1,5) 有没有来自dictionary,很没有效率
*/
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> s(words.begin(), words.end());
vector<string> res;
for (auto w : words) {
int n = w.size();
vector<int> dp(n+1);
dp[0] = 1;
for (int i = 0; i < n; i++) {
if (dp[i] == 0) continue;
for (int j = i+1; j <= n; j++) {
if (j - i < n && s.count(w.substr(i, j-i))) dp[j] = 1; // j - i < n 控制避免word只是来自于字典中的一个词,而不是多个词合成.
}
if (dp[n]) { res.push_back(w); break; }
}
}
return res;
}
/*
有memoization 反而变慢了
*/
class Solution {
public:
unordered_set<string>memo;
unordered_set<string>dict;
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
for(auto i: words)
dict.insert(i);
vector<string>res;
for(auto s: words)
if(check(s, 0, 0))
res.push_back(s);
return res;
}
bool check(const string& s, int beg, int count){
if(beg == s.size() && count > 1){
return true;
}
for(int i = beg; i<s.size();i++){
if(memo.count(s.substr(beg)))
return true;
if(dict.count(s.substr(beg,i-beg+1)) && check(s, i+1, count+1)){
if(i!=s.size()-1) //这里不用检查count, s.substr(beg,i-beg+1)是一个词, s[i+1:] 之后是另一个词,count>1
memo.insert(s.substr(beg));
return true;
}
}
return false;
}
};
//suffix Trie
class Solution {
public:
struct Trie{
unordered_map<char,Trie*>mp;
bool isleaf = false;
};
Trie *trie;
void build(const string& word){
Trie* t = trie;
for(auto w: word){
if(t->mp.count(w) == 0)
t->mp[w] = new Trie();
t = t->mp[w];
}
t->isleaf = true;
}
bool find(Trie* t, const string& word, int index, int count){
if(index == word.size())
return t->isleaf && count > 1;
if(t->mp.count(word[index]) == 0)
return false;
t = t->mp[word[index]];
if(t->isleaf){
if(find(trie, word, index+1, count+1))
return true;
}
return find(t, word, index+1, count);
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
trie = new Trie();
for(auto w: words)
if(w.size()>=1) //比如 word ["cat", ""], "cat" 不算是解
build(w);
vector<string>res;
for(auto w: words)
if(find(trie, w, 0, 1))
res.push_back(w);
return res;
}
}; | 27.095808 | 116 | 0.49768 | [
"vector"
] |
4318a738139d036197536002b9dc99a7c8b9ec5c | 2,527 | cpp | C++ | src/strategy/actions/DestroyItemAction.cpp | ZhengPeiRu21/mod-playerbots | 66e77e324d4b82f658bebce11e8f72215c5c2b3c | [
"MIT"
] | 12 | 2022-03-23T05:14:53.000Z | 2022-03-30T12:12:58.000Z | src/strategy/actions/DestroyItemAction.cpp | ZhengPeiRu21/mod-playerbots | 66e77e324d4b82f658bebce11e8f72215c5c2b3c | [
"MIT"
] | 24 | 2022-03-23T13:56:37.000Z | 2022-03-31T18:23:32.000Z | src/strategy/actions/DestroyItemAction.cpp | ZhengPeiRu21/mod-playerbots | 66e77e324d4b82f658bebce11e8f72215c5c2b3c | [
"MIT"
] | 3 | 2022-03-24T21:47:10.000Z | 2022-03-31T06:21:46.000Z | /*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
*/
#include "DestroyItemAction.h"
#include "Event.h"
#include "ItemCountValue.h"
#include "Playerbots.h"
bool DestroyItemAction::Execute(Event event)
{
std::string const text = event.getParam();
ItemIds ids = chat->parseItems(text);
for (ItemIds::iterator i = ids.begin(); i != ids.end(); i++)
{
FindItemByIdVisitor visitor(*i);
DestroyItem(&visitor);
}
return true;
}
void DestroyItemAction::DestroyItem(FindItemVisitor* visitor)
{
IterateItems(visitor);
std::vector<Item*> items = visitor->GetResult();
for (Item* item : items)
{
std::ostringstream out;
out << chat->FormatItem(item->GetTemplate()) << " destroyed";
botAI->TellMaster(out);
bot->DestroyItem(item->GetBagSlot(),item->GetSlot(), true);
}
}
bool SmartDestroyItemAction::isUseful()
{
return !botAI->HasActivePlayerMaster();
}
bool SmartDestroyItemAction::Execute(Event event)
{
uint8 bagSpace = AI_VALUE(uint8, "bag space");
if (bagSpace < 90)
return false;
std::vector<uint32> bestToDestroy = { ITEM_USAGE_NONE }; //First destroy anything useless.
if (!AI_VALUE(bool, "can sell") && AI_VALUE(bool, "should get money")) // We need money so quest items are less important since they can't directly be sold.
bestToDestroy.push_back(ITEM_USAGE_QUEST);
else // We don't need money so destroy the cheapest stuff.
{
bestToDestroy.push_back(ITEM_USAGE_VENDOR);
bestToDestroy.push_back(ITEM_USAGE_AH);
}
// If we still need room
bestToDestroy.push_back(ITEM_USAGE_SKILL); // Items that might help tradeskill are more important than above but still expenable.
bestToDestroy.push_back(ITEM_USAGE_USE); // These are more likely to be usefull 'soon' but still expenable.
for (auto& usage : bestToDestroy)
{
std::vector<Item*> items = AI_VALUE2(std::vector<Item*>, "inventory items", "usage " + std::to_string(usage));
std::reverse(items.begin(), items.end());
for (auto& item : items)
{
FindItemByIdVisitor visitor(item->GetTemplate()->ItemId);
DestroyItem(&visitor);
bagSpace = AI_VALUE(uint8, "bag space");
if (bagSpace < 90)
return true;
}
}
return false;
}
| 30.445783 | 205 | 0.654531 | [
"vector"
] |
4319e2a92518f7d60ef74f06d435bacfb2bf1a9b | 1,636 | hpp | C++ | lattice_snarg/algebra/lattice/lwe_params.hpp | dwu4/lattice-snarg | f5ef3e75d7200ee2b794d04b102fc7502b149628 | [
"MIT"
] | 5 | 2017-11-19T16:49:42.000Z | 2020-11-02T03:16:15.000Z | lattice_snarg/algebra/lattice/lwe_params.hpp | dwu4/lattice-snarg | f5ef3e75d7200ee2b794d04b102fc7502b149628 | [
"MIT"
] | null | null | null | lattice_snarg/algebra/lattice/lwe_params.hpp | dwu4/lattice-snarg | f5ef3e75d7200ee2b794d04b102fc7502b149628 | [
"MIT"
] | 2 | 2019-09-12T07:11:48.000Z | 2020-01-16T18:20:57.000Z | /** @file
*****************************************************************************
Sample parameters for the lattice-based vector encryption scheme for the
lattice-based R1CS ppSNARG. The LWE parameters are chosen to provide 80-bits
of security, and correctness error 2^{-40} for verifying QAPs with degree up
to 10000 (over a finite field of size ~10000). Parameter selection based on
the security analysis in [LP10].
The plaintext dimension is chosen based on the number of queries needed to
acheive soundness error 2^{-40} for the QAP-based linear PCP for verifying
R1CS systems with up to 10000 constraints (and a field of size ~10000).
References:
[LP10]: Richard Lindner and Chris Peikert. Better Key Sizes (and Attacks) for
LWE-Based Encryption. In CT-RSA, 2011.
*****************************************************************************
* @author Samir Menon, Brennan Shacklett, and David J. Wu
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LWE_PARAM_HPP_
#define LWE_PARAM_HPP_
#include <math.h>
#include <stdint.h>
#include <NTL/ZZ.h>
namespace LWE {
// Lattice dimension (parameters chosen to ensure 80-bits of security)
const uint32_t n = 1455;
// Noise distribution standard deviation
const double stddev = 6.0;
// 15 queries (~ 2^-40 soundness error for circuits of size < 10000)
const uint32_t l = 15;
const uint32_t pt_dim = l*4;
// Plaintext modulus
const uint64_t p_int = 65537;
const NTL::ZZ p(p_int);
// Ciphertext modulus
const NTL::ZZ q(1ul << 58);
}
#endif // LWE_PARAM_HPP_
| 31.461538 | 79 | 0.632029 | [
"vector"
] |
4321774c6fa95877cf526c08aa512db8fbcaede9 | 1,945 | hpp | C++ | inference-engine/src/transformations/include/transformations/init_node_info.hpp | cwzrad/openvino | ae4bd370eac7c695bd797a31e62317d328dbe742 | [
"Apache-2.0"
] | 1 | 2020-08-25T06:01:49.000Z | 2020-08-25T06:01:49.000Z | inference-engine/src/transformations/include/transformations/init_node_info.hpp | cwzrad/openvino | ae4bd370eac7c695bd797a31e62317d328dbe742 | [
"Apache-2.0"
] | 1 | 2021-07-24T15:22:27.000Z | 2021-07-24T15:22:27.000Z | inference-engine/src/transformations/include/transformations/init_node_info.hpp | cwzrad/openvino | ae4bd370eac7c695bd797a31e62317d328dbe742 | [
"Apache-2.0"
] | 1 | 2020-08-13T08:33:55.000Z | 2020-08-13T08:33:55.000Z | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
/**
* @brief Defines initialize node runtime information pass
* @file init_node_info.hpp
*/
#include <vector>
#include <memory>
#include <transformations_visibility.hpp>
#include <ngraph/pass/graph_rewrite.hpp>
/**
* @defgroup ie_transformation_api Inference Engine Transformation API
* @brief Defines Inference Engine Transformations API which is used to transform ngraph::Function
*
* @{
* @defgroup ie_runtime_attr_api Runtime information
* @brief A mechanism of runtime information extension
*
* @defgroup ie_transformation_common_api Common optimization passes
* @brief A set of common optimization passes
*
* @defgroup ie_transformation_to_opset2_api Conversion from opset3 to opset2
* @brief A set of conversion downgrade passes from opset3 to opset2
*
* @defgroup ie_transformation_to_opset1_api Conversion from opset2 to opset1
* @brief A set of conversion downgrade passes from opset2 to opset1
* @}
*/
/**
* @brief ngraph namespace
*/
namespace ngraph {
/**
* @brief ngraph::pass namespace
*/
namespace pass {
class TRANSFORMATIONS_API InitNodeInfo;
} // namespace pass
} // namespace ngraph
/**
* @ingroup ie_transformation_common_api
* @brief InitNodeInfo transformation helps to set runtime info attributes in a single place.
*
* Every runtime info attribute that needs to be initialized should be registered
* in run_on_function method. Also do not forget to override init methods for registered
* attribute.
* This transformations should be called first in transformation pipeline. If attribute was
* already set initialization will be skipped for this node.
*/
class ngraph::pass::InitNodeInfo: public ngraph::pass::FunctionPass {
public:
/**
* Constructor
*/
InitNodeInfo() : FunctionPass() {}
bool run_on_function(std::shared_ptr<ngraph::Function> f) override;
};
| 27.013889 | 98 | 0.756298 | [
"vector",
"transform"
] |
432505e4a1d64223c38a7173aa100c782e0f5a45 | 3,495 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/fp16/slice_fp16.cc | HappyKL/mindspore | 479cb89e8b5c9d859130891567038bb849a30bce | [
"Apache-2.0"
] | 1 | 2020-10-18T12:27:45.000Z | 2020-10-18T12:27:45.000Z | mindspore/lite/src/runtime/kernel/arm/fp16/slice_fp16.cc | ReIadnSan/mindspore | c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/fp16/slice_fp16.cc | ReIadnSan/mindspore | c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies 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 "src/runtime/kernel/arm/fp16/slice_fp16.h"
#include "src/runtime/kernel/arm/fp16/common_fp16.h"
#include "src/kernel_registry.h"
#include "nnacl/fp16/cast_fp16.h"
#include "nnacl/fp16/slice_fp16.h"
using mindspore::lite::KernelRegistrar;
using mindspore::schema::PrimitiveType_Slice;
namespace mindspore::kernel {
int SliceFp16CPUKernel::SliceParallelRun(int thread_id) {
DoSliceFp16(input_fp16_, output_fp16_, param_, thread_id);
return RET_OK;
}
int SliceFp16CPUKernel::Run() {
auto ret = Prepare();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Prepare fail!ret: " << ret;
return ret;
}
input_fp16_ = ConvertInputFp32toFp16(in_tensors_.at(0), context_);
output_fp16_ = MallocOutputFp16(out_tensors_.at(0), context_);
if (input_fp16_ == nullptr || output_fp16_ == nullptr) {
FreeInputAndOutput();
MS_LOG(ERROR) << "input or output is nullptr";
return RET_ERROR;
}
if (param_->size_[1] < op_parameter_->thread_num_) {
DoSliceFp16NoParallel(input_fp16_, output_fp16_, param_);
return RET_OK;
}
ret = ParallelLaunch(this->context_->thread_pool_, SliceLaunch, this, op_parameter_->thread_num_);
if (ret != RET_OK) {
MS_LOG(ERROR) << "slice launch fail!ret: " << ret;
}
if (out_tensors_.at(0)->data_type() == kNumberTypeFloat32) {
Float16ToFloat32(output_fp16_, reinterpret_cast<float *>(out_tensors_.at(0)->MutableData()),
out_tensors_.at(0)->ElementsNum());
}
FreeInputAndOutput();
return ret;
}
void SliceFp16CPUKernel::FreeInputAndOutput() {
if (in_tensors_.at(0)->data_type() == kNumberTypeFloat32) {
context_->allocator->Free(input_fp16_);
input_fp16_ = nullptr;
}
if (out_tensors_.at(0)->data_type() == kNumberTypeFloat32) {
context_->allocator->Free(output_fp16_);
output_fp16_ = nullptr;
}
}
kernel::LiteKernel *CpuSliceFp16KernelCreator(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *opParameter,
const lite::InnerContext *ctx, const kernel::KernelKey &desc,
const mindspore::lite::PrimitiveC *primitive) {
auto *kernel = new (std::nothrow) SliceFp16CPUKernel(opParameter, inputs, outputs, ctx, primitive);
if (kernel == nullptr) {
MS_LOG(ERROR) << "new SliceFp16CPUKernel fail!";
free(opParameter);
return nullptr;
}
auto ret = kernel->Init();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Init kernel failed, name: " << opParameter->name_ << ", type: "
<< schema::EnumNamePrimitiveType(static_cast<schema::PrimitiveType>(opParameter->type_));
delete kernel;
return nullptr;
}
return kernel;
}
REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_Slice, CpuSliceFp16KernelCreator)
} // namespace mindspore::kernel
| 37.580645 | 115 | 0.685265 | [
"vector"
] |
432a651ad8560a8c44238c670aa82944c6fc3c74 | 2,212 | cpp | C++ | Concurrency/Problem61/main.cpp | revsic/ModernCppChallengeStudy | 02c489cf03c5598799da0d33d4d32b6b95ce8600 | [
"MIT"
] | 1 | 2019-01-09T07:02:05.000Z | 2019-01-09T07:02:05.000Z | Concurrency/Problem61/main.cpp | revsic/ModernCppChallengeStudy | 02c489cf03c5598799da0d33d4d32b6b95ce8600 | [
"MIT"
] | null | null | null | Concurrency/Problem61/main.cpp | revsic/ModernCppChallengeStudy | 02c489cf03c5598799da0d33d4d32b6b95ce8600 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cassert>
#include <chrono>
#include <iostream>
#include <thread>
template <typename InputIter, typename OutputIter, typename F>
void par_transform(InputIter in_begin,
InputIter in_end,
OutputIter out_begin,
F&& unary)
{
using result_t =
std::invoke_result_t<F, typename std::iterator_traits<InputIter>::value_type>;
size_t num_thread = std::thread::hardware_concurrency();
auto pool = std::make_unique<std::thread[]>(num_thread);
size_t partition = std::distance(in_begin, in_end) / num_thread;
for (size_t i = 0; i < num_thread; ++i) {
InputIter in_iter = in_begin;
OutputIter out_iter = out_begin;
if (i == num_thread - 1) {
in_begin = in_end;
} else {
std::advance(in_begin, partition);
std::advance(out_begin, partition);
}
pool[i] = std::thread([=]{
std::transform(in_iter, in_begin, out_iter, unary);
// for (; in_iter != in_begin; ++in_iter, ++out_iter) {
// *out_iter = unary(*in_iter);
// }
});
}
for (size_t i = 0; i < num_thread; ++i) {
if (pool[i].joinable()) {
pool[i].join();
}
}
}
constexpr size_t TEST_SIZE = 100000000;
int input[TEST_SIZE];
int output[TEST_SIZE];
int main() {
for (size_t i = 0; i < TEST_SIZE; ++i) {
input[i] = i;
}
auto benchmark = [&](auto name, auto& func) {
using namespace std::chrono;
for (size_t i = 0; i < TEST_SIZE; ++i) {
output[i] = 0;
}
auto map_func = [](int n) { return n * 2; };
auto begin = steady_clock::now();
func(input, input + TEST_SIZE, output, map_func);
auto end = steady_clock::now();
std::cout << name << ": " << duration_cast<nanoseconds>(end - begin).count() << '\n';
for (size_t i = 0; i < TEST_SIZE; ++i) {
assert(output[i] == map_func(i));
}
};
benchmark("seq", std::transform<int*, int*, int(*)(int)>);
benchmark("par", par_transform<int*, int*, int(*)(int)>);
return 0;
}
| 27.308642 | 93 | 0.538427 | [
"transform"
] |
432ff4c889b47d79952f11b07e89321096be63a5 | 295 | cpp | C++ | Week1/minCostToMoveChips.cpp | AkashRajpurohit/leetcode-november-2020-challenge | aae9191db95b4b03133ff3cc049f760aa769872e | [
"MIT"
] | 2 | 2020-11-16T04:24:02.000Z | 2022-03-16T14:56:37.000Z | Week1/minCostToMoveChips.cpp | AkashRajpurohit/leetcode-november-2020-challenge | aae9191db95b4b03133ff3cc049f760aa769872e | [
"MIT"
] | null | null | null | Week1/minCostToMoveChips.cpp | AkashRajpurohit/leetcode-november-2020-challenge | aae9191db95b4b03133ff3cc049f760aa769872e | [
"MIT"
] | null | null | null | class Solution {
public:
int minCostToMoveChips(vector<int>& position) {
int even_count = 0, odd_count = 0;
for(int pos: position){
if(pos % 2 == 0) even_count++;
else odd_count++;
}
return min(even_count, odd_count);
}
}; | 24.583333 | 51 | 0.528814 | [
"vector"
] |
43315d7c6607f2bf8a2af2a8d48572db20933cad | 15,369 | cc | C++ | media/gpu/windows/d3d11_vp9_accelerator.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 | media/gpu/windows/d3d11_vp9_accelerator.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 | media/gpu/windows/d3d11_vp9_accelerator.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"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 "media/gpu/windows/d3d11_vp9_accelerator.h"
#include <windows.h>
#include <string>
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "media/gpu/windows/d3d11_vp9_picture.h"
namespace media {
using DecodeStatus = VP9Decoder::VP9Accelerator::Status;
#define RETURN_ON_HR_FAILURE(expr_name, expr, code) \
do { \
HRESULT expr_value = (expr); \
if (FAILED(expr_value)) { \
RecordFailure(#expr_name, logging::SystemErrorCodeToString(expr_value), \
code); \
return false; \
} \
} while (0)
std::vector<D3D11_VIDEO_DECODER_SUB_SAMPLE_MAPPING_BLOCK>
CreateSubsampleMappingBlock(const std::vector<SubsampleEntry>& from) {
std::vector<D3D11_VIDEO_DECODER_SUB_SAMPLE_MAPPING_BLOCK> to(from.size());
for (const auto& entry : from) {
D3D11_VIDEO_DECODER_SUB_SAMPLE_MAPPING_BLOCK subsample = {
.ClearSize = entry.clear_bytes, .EncryptedSize = entry.cypher_bytes};
to.push_back(subsample);
}
return to;
}
D3D11VP9Accelerator::D3D11VP9Accelerator(
D3D11VideoDecoderClient* client,
MediaLog* media_log,
ComD3D11VideoDevice video_device,
std::unique_ptr<VideoContextWrapper> video_context)
: client_(client),
media_log_(media_log),
status_feedback_(0),
video_device_(std::move(video_device)),
video_context_(std::move(video_context)) {
DCHECK(client);
DCHECK(media_log_);
client->SetDecoderCB(base::BindRepeating(
&D3D11VP9Accelerator::SetVideoDecoder, base::Unretained(this)));
}
D3D11VP9Accelerator::~D3D11VP9Accelerator() {}
void D3D11VP9Accelerator::RecordFailure(const std::string& fail_type,
const std::string& reason,
StatusCode code) {
MEDIA_LOG(ERROR, media_log_)
<< "DX11VP9Failure(" << fail_type << ")=" << reason;
base::UmaHistogramSparse("Media.D3D11.VP9Status", static_cast<int>(code));
}
scoped_refptr<VP9Picture> D3D11VP9Accelerator::CreateVP9Picture() {
D3D11PictureBuffer* picture_buffer = client_->GetPicture();
if (!picture_buffer)
return nullptr;
return base::MakeRefCounted<D3D11VP9Picture>(picture_buffer, client_);
}
bool D3D11VP9Accelerator::BeginFrame(const D3D11VP9Picture& pic) {
const bool is_encrypted = pic.decrypt_config();
if (is_encrypted) {
RecordFailure("crypto_config",
"Cannot find the decrypt context for the frame.",
StatusCode::kCryptoConfigFailed);
return false;
}
HRESULT hr;
do {
hr = video_context_->DecoderBeginFrame(
video_decoder_.Get(), pic.picture_buffer()->output_view().Get(), 0,
nullptr);
} while (hr == E_PENDING || hr == D3DERR_WASSTILLDRAWING);
if (FAILED(hr)) {
RecordFailure("DecoderBeginFrame", logging::SystemErrorCodeToString(hr),
StatusCode::kDecoderBeginFrameFailed);
return false;
}
return true;
}
void D3D11VP9Accelerator::CopyFrameParams(const D3D11VP9Picture& pic,
DXVA_PicParams_VP9* pic_params) {
#define SET_PARAM(a, b) pic_params->a = pic.frame_hdr->b
#define COPY_PARAM(a) SET_PARAM(a, a)
COPY_PARAM(profile);
COPY_PARAM(show_frame);
COPY_PARAM(error_resilient_mode);
COPY_PARAM(refresh_frame_context);
COPY_PARAM(frame_parallel_decoding_mode);
COPY_PARAM(intra_only);
COPY_PARAM(frame_context_idx);
COPY_PARAM(reset_frame_context);
COPY_PARAM(allow_high_precision_mv);
COPY_PARAM(frame_parallel_decoding_mode);
COPY_PARAM(intra_only);
COPY_PARAM(frame_context_idx);
COPY_PARAM(allow_high_precision_mv);
// extra_plane is initialized to zero.
pic_params->BitDepthMinus8Luma = pic_params->BitDepthMinus8Chroma =
pic.frame_hdr->bit_depth - 8;
pic_params->CurrPic.Index7Bits = pic.picture_index();
pic_params->frame_type = !pic.frame_hdr->IsKeyframe();
COPY_PARAM(subsampling_x);
COPY_PARAM(subsampling_y);
SET_PARAM(width, frame_width);
SET_PARAM(height, frame_height);
SET_PARAM(interp_filter, interpolation_filter);
SET_PARAM(log2_tile_cols, tile_cols_log2);
SET_PARAM(log2_tile_rows, tile_rows_log2);
#undef COPY_PARAM
#undef SET_PARAM
// This is taken, approximately, from libvpx.
gfx::Size this_frame_size(pic.frame_hdr->frame_width,
pic.frame_hdr->frame_height);
pic_params->use_prev_in_find_mv_refs = last_frame_size_ == this_frame_size &&
!pic.frame_hdr->error_resilient_mode &&
!pic.frame_hdr->intra_only &&
last_show_frame_;
// TODO(liberato): So, uh, do we ever need to reset this?
last_frame_size_ = this_frame_size;
last_show_frame_ = pic.frame_hdr->show_frame;
}
void D3D11VP9Accelerator::CopyReferenceFrames(
const D3D11VP9Picture& pic,
DXVA_PicParams_VP9* pic_params,
const Vp9ReferenceFrameVector& ref_frames) {
D3D11_TEXTURE2D_DESC texture_descriptor;
pic.picture_buffer()->Texture()->GetDesc(&texture_descriptor);
for (size_t i = 0; i < base::size(pic_params->ref_frame_map); i++) {
auto ref_pic = ref_frames.GetFrame(i);
if (ref_pic) {
scoped_refptr<D3D11VP9Picture> our_ref_pic(
static_cast<D3D11VP9Picture*>(ref_pic.get()));
pic_params->ref_frame_map[i].Index7Bits = our_ref_pic->picture_index();
pic_params->ref_frame_coded_width[i] = texture_descriptor.Width;
pic_params->ref_frame_coded_height[i] = texture_descriptor.Height;
} else {
pic_params->ref_frame_map[i].bPicEntry = 0xff;
pic_params->ref_frame_coded_width[i] = 0;
pic_params->ref_frame_coded_height[i] = 0;
}
}
}
void D3D11VP9Accelerator::CopyFrameRefs(DXVA_PicParams_VP9* pic_params,
const D3D11VP9Picture& pic) {
for (size_t i = 0; i < base::size(pic_params->frame_refs); i++) {
pic_params->frame_refs[i] =
pic_params->ref_frame_map[pic.frame_hdr->ref_frame_idx[i]];
}
for (size_t i = 0; i < base::size(pic_params->ref_frame_sign_bias); i++) {
pic_params->ref_frame_sign_bias[i] = pic.frame_hdr->ref_frame_sign_bias[i];
}
}
void D3D11VP9Accelerator::CopyLoopFilterParams(
DXVA_PicParams_VP9* pic_params,
const Vp9LoopFilterParams& loop_filter_params) {
#define SET_PARAM(a, b) pic_params->a = loop_filter_params.b
SET_PARAM(filter_level, level);
SET_PARAM(sharpness_level, sharpness);
SET_PARAM(mode_ref_delta_enabled, delta_enabled);
SET_PARAM(mode_ref_delta_update, delta_update);
#undef SET_PARAM
// base::size(...) doesn't work well in an array initializer.
DCHECK_EQ(4lu, base::size(pic_params->ref_deltas));
for (size_t i = 0; i < base::size(pic_params->ref_deltas); i++) {
// The update_ref_deltas[i] is _only_ for parsing! it allows omission of the
// 6 bytes that would otherwise be needed for a new value to overwrite the
// global one. It has nothing to do with setting the ref_deltas here.
pic_params->ref_deltas[i] = loop_filter_params.ref_deltas[i];
}
DCHECK_EQ(2lu, base::size(pic_params->mode_deltas));
for (size_t i = 0; i < base::size(pic_params->mode_deltas); i++) {
pic_params->mode_deltas[i] = loop_filter_params.mode_deltas[i];
}
}
void D3D11VP9Accelerator::CopyQuantParams(DXVA_PicParams_VP9* pic_params,
const D3D11VP9Picture& pic) {
#define SET_PARAM(a, b) pic_params->a = pic.frame_hdr->quant_params.b
SET_PARAM(base_qindex, base_q_idx);
SET_PARAM(y_dc_delta_q, delta_q_y_dc);
SET_PARAM(uv_dc_delta_q, delta_q_uv_dc);
SET_PARAM(uv_ac_delta_q, delta_q_uv_ac);
#undef SET_PARAM
}
void D3D11VP9Accelerator::CopySegmentationParams(
DXVA_PicParams_VP9* pic_params,
const Vp9SegmentationParams& segmentation_params) {
#define SET_PARAM(a, b) pic_params->stVP9Segments.a = segmentation_params.b
#define COPY_PARAM(a) SET_PARAM(a, a)
COPY_PARAM(enabled);
COPY_PARAM(update_map);
COPY_PARAM(temporal_update);
SET_PARAM(abs_delta, abs_or_delta_update);
for (size_t i = 0; i < base::size(segmentation_params.tree_probs); i++) {
COPY_PARAM(tree_probs[i]);
}
for (size_t i = 0; i < base::size(segmentation_params.pred_probs); i++) {
COPY_PARAM(pred_probs[i]);
}
for (size_t i = 0; i < 8; i++) {
for (size_t j = 0; j < 4; j++) {
COPY_PARAM(feature_data[i][j]);
if (segmentation_params.feature_enabled[i][j])
pic_params->stVP9Segments.feature_mask[i] |= (1 << j);
}
}
#undef COPY_PARAM
#undef SET_PARAM
}
void D3D11VP9Accelerator::CopyHeaderSizeAndID(DXVA_PicParams_VP9* pic_params,
const D3D11VP9Picture& pic) {
pic_params->uncompressed_header_size_byte_aligned =
static_cast<USHORT>(pic.frame_hdr->uncompressed_header_size);
pic_params->first_partition_size =
static_cast<USHORT>(pic.frame_hdr->header_size_in_bytes);
// StatusReportFeedbackNumber "should not be equal to 0".
pic_params->StatusReportFeedbackNumber = ++status_feedback_;
}
bool D3D11VP9Accelerator::SubmitDecoderBuffer(
const DXVA_PicParams_VP9& pic_params,
const D3D11VP9Picture& pic) {
#define GET_BUFFER(type, code) \
RETURN_ON_HR_FAILURE(GetDecoderBuffer, \
video_context_->GetDecoderBuffer( \
video_decoder_.Get(), type, &buffer_size, &buffer), \
code)
#define RELEASE_BUFFER(type, code) \
RETURN_ON_HR_FAILURE( \
ReleaseDecoderBuffer, \
video_context_->ReleaseDecoderBuffer(video_decoder_.Get(), type), code)
UINT buffer_size;
void* buffer;
GET_BUFFER(D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS,
StatusCode::kGetPicParamBufferFailed);
memcpy(buffer, &pic_params, sizeof(pic_params));
RELEASE_BUFFER(D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS,
StatusCode::kReleasePicParamBufferFailed);
size_t buffer_offset = 0;
while (buffer_offset < pic.frame_hdr->frame_size) {
GET_BUFFER(D3D11_VIDEO_DECODER_BUFFER_BITSTREAM,
StatusCode::kGetBitstreamBufferFailed);
size_t copy_size = pic.frame_hdr->frame_size - buffer_offset;
bool contains_end = true;
if (copy_size > buffer_size) {
copy_size = buffer_size;
contains_end = false;
}
memcpy(buffer, pic.frame_hdr->data + buffer_offset, copy_size);
RELEASE_BUFFER(D3D11_VIDEO_DECODER_BUFFER_BITSTREAM,
StatusCode::kReleaseBitstreamBufferFailed);
DXVA_Slice_VPx_Short slice_info;
GET_BUFFER(D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL,
StatusCode::kGetSliceControlBufferFailed);
slice_info.BSNALunitDataLocation = 0;
slice_info.SliceBytesInBuffer = (UINT)copy_size;
// See the DXVA header specification for values of wBadSliceChopping:
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/dxva/ns-dxva-_dxva_sliceinfo#wBadSliceChopping
if (buffer_offset == 0 && contains_end)
slice_info.wBadSliceChopping = 0;
else if (buffer_offset == 0 && !contains_end)
slice_info.wBadSliceChopping = 1;
else if (buffer_offset != 0 && contains_end)
slice_info.wBadSliceChopping = 2;
else if (buffer_offset != 0 && !contains_end)
slice_info.wBadSliceChopping = 3;
memcpy(buffer, &slice_info, sizeof(slice_info));
RELEASE_BUFFER(D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL,
StatusCode::kReleaseSliceControlBufferFailed);
constexpr int buffers_count = 3;
VideoContextWrapper::VideoBufferWrapper buffers[buffers_count] = {};
buffers[0].BufferType = D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS;
buffers[0].DataOffset = 0;
buffers[0].DataSize = sizeof(pic_params);
buffers[1].BufferType = D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL;
buffers[1].DataOffset = 0;
buffers[1].DataSize = sizeof(slice_info);
buffers[2].BufferType = D3D11_VIDEO_DECODER_BUFFER_BITSTREAM;
buffers[2].DataOffset = 0;
buffers[2].DataSize = copy_size;
const DecryptConfig* config = pic.decrypt_config();
if (config) {
buffers[2].pIV = const_cast<char*>(config->iv().data());
buffers[2].IVSize = config->iv().size();
// Subsamples matter iff there is IV, for decryption.
if (!config->subsamples().empty()) {
buffers[2].pSubSampleMappingBlock =
CreateSubsampleMappingBlock(config->subsamples()).data();
buffers[2].SubSampleMappingCount = config->subsamples().size();
}
}
RETURN_ON_HR_FAILURE(SubmitDecoderBuffers,
video_context_->SubmitDecoderBuffers(
video_decoder_.Get(), buffers_count, buffers),
StatusCode::kSubmitDecoderBuffersFailed);
buffer_offset += copy_size;
}
return true;
#undef GET_BUFFER
#undef RELEASE_BUFFER
}
DecodeStatus D3D11VP9Accelerator::SubmitDecode(
scoped_refptr<VP9Picture> picture,
const Vp9SegmentationParams& segmentation_params,
const Vp9LoopFilterParams& loop_filter_params,
const Vp9ReferenceFrameVector& reference_frames,
base::OnceClosure on_finished_cb) {
D3D11VP9Picture* pic = static_cast<D3D11VP9Picture*>(picture.get());
if (!BeginFrame(*pic))
return DecodeStatus::kFail;
DXVA_PicParams_VP9 pic_params = {};
CopyFrameParams(*pic, &pic_params);
CopyReferenceFrames(*pic, &pic_params, reference_frames);
CopyFrameRefs(&pic_params, *pic);
CopyLoopFilterParams(&pic_params, loop_filter_params);
CopyQuantParams(&pic_params, *pic);
CopySegmentationParams(&pic_params, segmentation_params);
CopyHeaderSizeAndID(&pic_params, *pic);
if (!SubmitDecoderBuffer(pic_params, *pic))
return DecodeStatus::kFail;
HRESULT hr = video_context_->DecoderEndFrame(video_decoder_.Get());
if (FAILED(hr)) {
RecordFailure("DecoderEndFrame", logging::SystemErrorCodeToString(hr),
StatusCode::kDecoderEndFrameFailed);
return DecodeStatus::kFail;
}
if (on_finished_cb)
std::move(on_finished_cb).Run();
return DecodeStatus::kOk;
}
bool D3D11VP9Accelerator::OutputPicture(scoped_refptr<VP9Picture> picture) {
D3D11VP9Picture* pic = static_cast<D3D11VP9Picture*>(picture.get());
return client_->OutputResult(picture.get(), pic->picture_buffer());
}
bool D3D11VP9Accelerator::IsFrameContextRequired() const {
return false;
}
bool D3D11VP9Accelerator::GetFrameContext(scoped_refptr<VP9Picture> picture,
Vp9FrameContext* frame_context) {
return false;
}
void D3D11VP9Accelerator::SetVideoDecoder(ComD3D11VideoDecoder video_decoder) {
video_decoder_ = std::move(video_decoder);
}
} // namespace media
| 37.761671 | 123 | 0.685536 | [
"vector"
] |
43327f7496c5ebf34d60e57977de739d7ccfd565 | 14,061 | cpp | C++ | ql/instruments/capfloor.cpp | sschlenkrich/quantlib | ff39ad2cd03d06d185044976b2e26ce34dca470c | [
"BSD-3-Clause"
] | null | null | null | ql/instruments/capfloor.cpp | sschlenkrich/quantlib | ff39ad2cd03d06d185044976b2e26ce34dca470c | [
"BSD-3-Clause"
] | 17 | 2020-11-23T07:24:16.000Z | 2022-03-28T10:29:06.000Z | ql/instruments/capfloor.cpp | sschlenkrich/quantlib | ff39ad2cd03d06d185044976b2e26ce34dca470c | [
"BSD-3-Clause"
] | 7 | 2017-04-24T08:28:43.000Z | 2022-03-15T08:59:54.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006, 2014 Ferdinando Ametrano
Copyright (C) 2006 François du Vignaud
Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb
Copyright (C) 2006, 2007 StatPro Italia srl
Copyright (C) 2016 Paolo Mazzocchi
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <ql/cashflows/cashflows.hpp>
#include <ql/instruments/capfloor.hpp>
#include <ql/math/solvers1d/newtonsafe.hpp>
#include <ql/pricingengines/capfloor/bacheliercapfloorengine.hpp>
#include <ql/pricingengines/capfloor/blackcapfloorengine.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <utility>
namespace QuantLib {
namespace {
class ImpliedCapVolHelper {
public:
ImpliedCapVolHelper(const CapFloor&,
Handle<YieldTermStructure> discountCurve,
Real targetValue,
Real displacement,
VolatilityType type);
Real operator()(Volatility x) const;
Real derivative(Volatility x) const;
private:
ext::shared_ptr<PricingEngine> engine_;
Handle<YieldTermStructure> discountCurve_;
Real targetValue_;
ext::shared_ptr<SimpleQuote> vol_;
const Instrument::results* results_;
};
ImpliedCapVolHelper::ImpliedCapVolHelper(const CapFloor& cap,
Handle<YieldTermStructure> discountCurve,
Real targetValue,
Real displacement,
VolatilityType type)
: discountCurve_(std::move(discountCurve)), targetValue_(targetValue),
vol_(ext::make_shared<SimpleQuote>(-1.0)) {
// vol_ is set an implausible value, so that calculation is forced
// at first ImpliedCapVolHelper::operator()(Volatility x) call
Handle<Quote> h(vol_);
switch (type) {
case ShiftedLognormal:
engine_ = ext::shared_ptr<PricingEngine>(new
BlackCapFloorEngine(discountCurve_, h, Actual365Fixed(),
displacement));
break;
case Normal:
engine_ = ext::shared_ptr<PricingEngine>(new
BachelierCapFloorEngine(discountCurve_, h,
Actual365Fixed()));
break;
default:
QL_FAIL("unknown VolatilityType (" << type << ")");
break;
}
cap.setupArguments(engine_->getArguments());
results_ = dynamic_cast<const Instrument::results*>(engine_->getResults());
}
Real ImpliedCapVolHelper::operator()(Volatility x) const {
if (x!=vol_->value()) {
vol_->setValue(x);
engine_->calculate();
}
return results_->value-targetValue_;
}
Real ImpliedCapVolHelper::derivative(Volatility x) const {
if (x!=vol_->value()) {
vol_->setValue(x);
engine_->calculate();
}
auto vega_ = results_->additionalResults.find("vega");
QL_REQUIRE(vega_ != results_->additionalResults.end(),
"vega not provided");
return boost::any_cast<Real>(vega_->second);
}
}
std::ostream& operator<<(std::ostream& out,
CapFloor::Type t) {
switch (t) {
case CapFloor::Cap:
return out << "Cap";
case CapFloor::Floor:
return out << "Floor";
case CapFloor::Collar:
return out << "Collar";
default:
QL_FAIL("unknown CapFloor::Type (" << Integer(t) << ")");
}
}
CapFloor::CapFloor(CapFloor::Type type,
Leg floatingLeg,
std::vector<Rate> capRates,
std::vector<Rate> floorRates)
: type_(type), floatingLeg_(std::move(floatingLeg)), capRates_(std::move(capRates)),
floorRates_(std::move(floorRates)) {
if (type_ == Cap || type_ == Collar) {
QL_REQUIRE(!capRates_.empty(), "no cap rates given");
capRates_.reserve(floatingLeg_.size());
while (capRates_.size() < floatingLeg_.size())
capRates_.push_back(capRates_.back());
}
if (type_ == Floor || type_ == Collar) {
QL_REQUIRE(!floorRates_.empty(), "no floor rates given");
floorRates_.reserve(floatingLeg_.size());
while (floorRates_.size() < floatingLeg_.size())
floorRates_.push_back(floorRates_.back());
}
Leg::const_iterator i;
for (i = floatingLeg_.begin(); i != floatingLeg_.end(); ++i)
registerWith(*i);
registerWith(Settings::instance().evaluationDate());
}
CapFloor::CapFloor(CapFloor::Type type, Leg floatingLeg, const std::vector<Rate>& strikes)
: type_(type), floatingLeg_(std::move(floatingLeg)) {
QL_REQUIRE(!strikes.empty(), "no strikes given");
if (type_ == Cap) {
capRates_ = strikes;
capRates_.reserve(floatingLeg_.size());
while (capRates_.size() < floatingLeg_.size())
capRates_.push_back(capRates_.back());
} else if (type_ == Floor) {
floorRates_ = strikes;
floorRates_.reserve(floatingLeg_.size());
while (floorRates_.size() < floatingLeg_.size())
floorRates_.push_back(floorRates_.back());
} else
QL_FAIL("only Cap/Floor types allowed in this constructor");
Leg::const_iterator i;
for (i = floatingLeg_.begin(); i != floatingLeg_.end(); ++i)
registerWith(*i);
registerWith(Settings::instance().evaluationDate());
}
bool CapFloor::isExpired() const {
for (Size i=floatingLeg_.size(); i>0; --i)
if (!floatingLeg_[i-1]->hasOccurred())
return false;
return true;
}
Date CapFloor::startDate() const {
return CashFlows::startDate(floatingLeg_);
}
Date CapFloor::maturityDate() const {
return CashFlows::maturityDate(floatingLeg_);
}
ext::shared_ptr<FloatingRateCoupon>
CapFloor::lastFloatingRateCoupon() const {
ext::shared_ptr<CashFlow> lastCF(floatingLeg_.back());
ext::shared_ptr<FloatingRateCoupon> lastFloatingCoupon =
ext::dynamic_pointer_cast<FloatingRateCoupon>(lastCF);
return lastFloatingCoupon;
}
ext::shared_ptr<CapFloor> CapFloor::optionlet(const Size i) const {
QL_REQUIRE(i < floatingLeg().size(),
io::ordinal(i+1) << " optionlet does not exist, only " <<
floatingLeg().size());
Leg cf(1, floatingLeg()[i]);
std::vector<Rate> cap, floor;
if (type() == Cap || type() == Collar)
cap.push_back(capRates()[i]);
if (type() == Floor || type() == Collar)
floor.push_back(floorRates()[i]);
return ext::make_shared<CapFloor>(type(), cf, cap, floor);
}
void CapFloor::setupArguments(PricingEngine::arguments* args) const {
auto* arguments = dynamic_cast<CapFloor::arguments*>(args);
QL_REQUIRE(arguments != nullptr, "wrong argument type");
Size n = floatingLeg_.size();
arguments->startDates.resize(n);
arguments->fixingDates.resize(n);
arguments->endDates.resize(n);
arguments->accrualTimes.resize(n);
arguments->forwards.resize(n);
arguments->nominals.resize(n);
arguments->gearings.resize(n);
arguments->capRates.resize(n);
arguments->floorRates.resize(n);
arguments->spreads.resize(n);
arguments->indexes.resize(n);
arguments->type = type_;
Date today = Settings::instance().evaluationDate();
for (Size i=0; i<n; ++i) {
ext::shared_ptr<FloatingRateCoupon> coupon =
ext::dynamic_pointer_cast<FloatingRateCoupon>(
floatingLeg_[i]);
QL_REQUIRE(coupon, "non-FloatingRateCoupon given");
arguments->startDates[i] = coupon->accrualStartDate();
arguments->fixingDates[i] = coupon->fixingDate();
arguments->endDates[i] = coupon->date();
// this is passed explicitly for precision
arguments->accrualTimes[i] = coupon->accrualPeriod();
// this is passed explicitly for precision...
if (arguments->endDates[i] >= today) { // ...but only if needed
arguments->forwards[i] = coupon->adjustedFixing();
} else {
arguments->forwards[i] = Null<Rate>();
}
arguments->nominals[i] = coupon->nominal();
Spread spread = coupon->spread();
Real gearing = coupon->gearing();
arguments->gearings[i] = gearing;
arguments->spreads[i] = spread;
if (type_ == Cap || type_ == Collar)
arguments->capRates[i] = (capRates_[i]-spread)/gearing;
else
arguments->capRates[i] = Null<Rate>();
if (type_ == Floor || type_ == Collar)
arguments->floorRates[i] = (floorRates_[i]-spread)/gearing;
else
arguments->floorRates[i] = Null<Rate>();
arguments->indexes[i] = coupon->index();
}
}
void CapFloor::deepUpdate() {
for (auto& i : floatingLeg_) {
ext::shared_ptr<LazyObject> f = ext::dynamic_pointer_cast<LazyObject>(i);
if (f != nullptr)
f->update();
}
update();
}
void CapFloor::arguments::validate() const {
QL_REQUIRE(endDates.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of end dates ("
<< endDates.size() << ")");
QL_REQUIRE(accrualTimes.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of accrual times ("
<< accrualTimes.size() << ")");
QL_REQUIRE(type == CapFloor::Floor ||
capRates.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of cap rates ("
<< capRates.size() << ")");
QL_REQUIRE(type == CapFloor::Cap ||
floorRates.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of floor rates ("
<< floorRates.size() << ")");
QL_REQUIRE(gearings.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of gearings ("
<< gearings.size() << ")");
QL_REQUIRE(spreads.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of spreads ("
<< spreads.size() << ")");
QL_REQUIRE(nominals.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of nominals ("
<< nominals.size() << ")");
QL_REQUIRE(forwards.size() == startDates.size(),
"number of start dates (" << startDates.size()
<< ") different from that of forwards ("
<< forwards.size() << ")");
}
Rate CapFloor::atmRate(const YieldTermStructure& discountCurve) const {
bool includeSettlementDateFlows = false;
Date settlementDate = discountCurve.referenceDate();
return CashFlows::atmRate(floatingLeg_, discountCurve,
includeSettlementDateFlows,
settlementDate);
}
Volatility CapFloor::impliedVolatility(Real targetValue,
const Handle<YieldTermStructure>& d,
Volatility guess,
Real accuracy,
Natural maxEvaluations,
Volatility minVol,
Volatility maxVol,
VolatilityType type,
Real displacement) const {
//calculate();
QL_REQUIRE(!isExpired(), "instrument expired");
ImpliedCapVolHelper f(*this, d, targetValue, displacement, type);
//Brent solver;
NewtonSafe solver;
solver.setMaxEvaluations(maxEvaluations);
return solver.solve(f, accuracy, guess, minVol, maxVol);
}
}
| 41.114035 | 94 | 0.543845 | [
"vector"
] |
433e9c25e421c5d55f5814ba089bbe5d77509bb6 | 3,815 | hpp | C++ | include/parsergen/lexer.hpp | Conqu3red/parsergen-cpp | 1435ce4b9fe64541142791ff75c32b968d88ac21 | [
"MIT"
] | 1 | 2021-09-04T14:18:39.000Z | 2021-09-04T14:18:39.000Z | include/parsergen/lexer.hpp | Conqu3red/parsergen-cpp | 1435ce4b9fe64541142791ff75c32b968d88ac21 | [
"MIT"
] | null | null | null | include/parsergen/lexer.hpp | Conqu3red/parsergen-cpp | 1435ce4b9fe64541142791ff75c32b968d88ac21 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <string_view>
#include <vector>
#include <stdio.h>
#include <string.h>
#include <functional>
#include <regex>
#include <memory>
#include <stdexcept>
#include "fmt/core.h"
#include "parsergen/utils.hpp"
const auto REGEX_SYNTAX_TYPE = (std::regex_constants::ECMAScript | std::regex_constants::optimize);
namespace Parsergen {
struct Position {
int lineno { 0 };
int column { 0 };
Position(){}
Position(int lineno, int column) : lineno(lineno), column(column) {}
bool operator ==(Position &other) const {
return lineno == other.lineno && column == other.column;
}
};
class Token {
public:
std::string type;
std::string value;
Position start;
Position end;
Token(std::string type, std::string value, Position start, Position end);
std::string error_format();
bool operator ==(Token &other) const;
};
class Lexer;
typedef std::function<void (Token &tok, utils::svmatch &sm)> TokenModifierFunc;
typedef std::function<void (Token &tok)> TokenFastModifierFunc;
class LexRule {
public:
std::string name;
std::vector<std::regex> patterns;
std::vector<std::string> string_patterns;
TokenModifierFunc modifier;
TokenFastModifierFunc fast_modifier;
LexRule(
std::string name,
std::vector<std::regex> patterns
);
LexRule(
std::string name,
std::vector<std::regex> patterns,
TokenModifierFunc modifier
);
LexRule(
std::string name,
std::vector<std::string> patterns
);
LexRule(
std::string name,
std::vector<std::string> patterns,
TokenFastModifierFunc fast_modifier
);
};
LexRule token_match(std::string name, std::initializer_list<std::string> patterns);
LexRule token_match(std::string name, std::initializer_list<std::string> patterns, TokenModifierFunc modifier);
LexRule token_match(std::string name, std::string pattern);
LexRule token_match(std::string name, std::string pattern, TokenModifierFunc modifier);
LexRule token_match_fast(std::string name, std::initializer_list<std::string> patterns);
LexRule token_match_fast(std::string name, std::initializer_list<std::string> patterns, TokenFastModifierFunc modifier);
LexRule token_match_fast(std::string name, std::string pattern);
LexRule token_match_fast(std::string name, std::string pattern, TokenFastModifierFunc modifier);
struct NoToken : std::exception {
const char *what() const throw() {
return "No Token";
}
};
struct LexError : std::runtime_error {
std::string m_msg, m_lineText;
int m_lineno, m_column;
LexError(
const std::string &msg,
const int lineno,
const int column,
const std::string &lineText
);
const char *what() const noexcept;
private:
std::string message;
void make_message();
};
class Lexer {
public:
std::string_view currentLine;
std::vector<Token> tokens;
std::vector<std::string> lines;
std::vector<LexRule> rules;
Lexer();
void setText(std::string text);
std::string getText();
void Lex();
Position cur_pos();
protected:
std::string text;
std::string_view source;
constexpr bool source_left() { return source.length() > 0; }
int column = 0;
int lineno = 1;
void newline();
Token GetNextToken();
void StepSource(int amount);
};
class TokenStream {
public:
TokenStream(std::unique_ptr<Lexer> lexer) : lexer(std::move(lexer)) {}
int mark();
void set_pos(int pos);
Token &get_token();
Token &peek_token();
Token &peek_token(int pos);
std::vector<std::string> &get_lines();
private:
std::unique_ptr<Lexer> lexer;
int m_pos = 0;
Token eof_tok { Token("EOF", "", Position(0, 0), Position(0, 0)) };
};
} | 24.934641 | 120 | 0.670773 | [
"vector"
] |
43407085392b0469083f96c5c13fbeb27c5a8125 | 3,192 | cpp | C++ | SpaghettiEngine/Framework/Engine/Containers/TileSet.cpp | CodingC1402/SpaghettiEngine | 80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a | [
"MIT"
] | 1 | 2021-06-02T09:31:15.000Z | 2021-06-02T09:31:15.000Z | SpaghettiEngine/Framework/Engine/Containers/TileSet.cpp | CornyCodingCorn/SpaghettiEngine | 80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a | [
"MIT"
] | 1 | 2021-07-13T13:56:18.000Z | 2021-07-13T13:56:18.000Z | SpaghettiEngine/Framework/Engine/Containers/TileSet.cpp | CodingC1402/SpaghettiEngine | 80fddf7c68ae7476a5880aae8fd0eac5bbf6ad1a | [
"MIT"
] | 2 | 2021-04-25T02:08:42.000Z | 2021-04-29T04:18:34.000Z | #include "TileSet.h"
#include "json.hpp"
#include "SpaghettiEnginePath.h"
#include "Sprite.h"
#include "GameTimer.h"
#include "SMath.h"
#include "CornException.h"
#include "LoadingJson.h"
CONTAINER_REGISTER(TileSetContainer, TileSet);
using namespace nlohmann;
void NormalTile::Load(Texture* texture, std::vector<unsigned> sprites, float fps)
{
sprite = texture->GetSprite(sprites[0]);
}
void NormalTile::Draw(const Vector3& position)
{
Graphics::DrawSprite(sprite, sprite->GetCenter(), position);
}
void AnimatedTile::Load(Texture* texture, std::vector<unsigned> sprites, float fps)
{
if (fps <= 0.0001)
{
std::wostringstream os;
os << "[Exception] the fps is too low";
throw CORN_EXCEPT_WITH_DESCRIPTION(os.str());
}
_delay = 1 / fps;
for (int i = 0; i < sprites.size(); i++)
_sprites.push_back(texture->GetSprite(sprites[i]));
_currentSprite = _sprites.front();
}
void AnimatedTile::Draw(const Vector3& position)
{
if (_currentTime != GameTimer::GetGameTime())
{
_currentTime = GameTimer::GetGameTime();
_currentSprite = _sprites[SMath::modulo<unsigned>(static_cast<unsigned>(GameTimer::GetGameTime() / _delay), static_cast<unsigned>(_sprites.size()))];
}
Vector3 center = _currentSprite->GetCenter();
Graphics::DrawSprite(_currentSprite, _currentSprite->GetCenter(), position);
}
TileSetContainer::TileSetContainer()
{
_name = RESOURCE_NAME(TileSet);
LoadEntries(SystemPath::TileSetPath);
}
WTile TileSet::GetTile(int index)
{
if (index < 0 || index > _tiles.size())
{
std::wostringstream os;
os << "[Exceptions] You are trying to get a tile with a non exist id";
throw CORN_EXCEPT_WITH_DESCRIPTION(os.str());
}
else
{
return _tiles[index];
}
}
void TileSet::Load(const std::string& path)
{
using namespace LoadingJson;
using namespace nlohmann;
std::ifstream file(path);
if (!file.is_open())
{
std::ostringstream os;
os << "[Exception] File ";
os << path.c_str();
os << " doesn't exist";
throw RESOURCE_LOAD_EXCEPTION(os.str(), Animation);
}
int fieldTracker = 0;
try
{
json jsonFile;
file >> jsonFile;
auto textureID = jsonFile[Field::textureField].get<CULL>();
fieldTracker++;
STexture texture = TextureContainer::GetInstance()->GetResource(textureID);
std::vector<unsigned> id = { 0 };
for (STile newTile; id[0] < texture->GetSpritesNumber(); id[0]++)
{
newTile.reset(new NormalTile());
newTile->Load(texture.get(), id, 1);
_tiles.push_back(newTile);
}
id.clear();
fieldTracker++;
for (STile newTile; auto & anim : jsonFile[Field::animationsField])
{
newTile.reset(new AnimatedTile());
id = anim[Field::spritesField].get<std::vector<unsigned>>();
newTile->Load(texture.get(), id, anim[Field::fpsField].get<float>());
_tiles[anim[Field::idField].get<unsigned>()] = newTile;
}
}
catch (...)
{
std::ostringstream os;
os << "[Field] ";
switch (fieldTracker)
{
case 0:
os << Field::textureField;
break;
case 1:
os << Field::spritesField;
break;
case 2:
os << Field::animationsField;
break;
}
os << std::endl;
os << "[Exception] Field doesn't have the right format";
throw RESOURCE_LOAD_EXCEPTION(os.str(), Animation);
}
}
| 24 | 151 | 0.686717 | [
"vector"
] |
434367ee8f41d5b5456ce47b1bae5cd1b99134d8 | 7,429 | hpp | C++ | opencv/sources/modules/videoio/src/backend_plugin_legacy.impl.hpp | vrushank-agrawal/opencv-x64-cmake | 3f9486510d706c8ac579ac82f5d58f667f948124 | [
"Apache-2.0"
] | null | null | null | opencv/sources/modules/videoio/src/backend_plugin_legacy.impl.hpp | vrushank-agrawal/opencv-x64-cmake | 3f9486510d706c8ac579ac82f5d58f667f948124 | [
"Apache-2.0"
] | null | null | null | opencv/sources/modules/videoio/src/backend_plugin_legacy.impl.hpp | vrushank-agrawal/opencv-x64-cmake | 3f9486510d706c8ac579ac82f5d58f667f948124 | [
"Apache-2.0"
] | null | null | null | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Not a standalone header.
//
namespace cv { namespace impl { namespace legacy {
//==================================================================================================
class PluginCapture : public cv::IVideoCapture
{
const OpenCV_VideoIO_Plugin_API_preview* plugin_api_;
CvPluginCapture capture_;
public:
static
Ptr<PluginCapture> create(const OpenCV_VideoIO_Plugin_API_preview* plugin_api,
const std::string &filename, int camera)
{
CV_Assert(plugin_api);
CvPluginCapture capture = NULL;
if (plugin_api->v0.Capture_open)
{
CV_Assert(plugin_api->v0.Capture_release);
if (CV_ERROR_OK == plugin_api->v0.Capture_open(filename.empty() ? 0 : filename.c_str(), camera, &capture))
{
CV_Assert(capture);
return makePtr<PluginCapture>(plugin_api, capture);
}
}
return Ptr<PluginCapture>();
}
PluginCapture(const OpenCV_VideoIO_Plugin_API_preview* plugin_api, CvPluginCapture capture)
: plugin_api_(plugin_api), capture_(capture)
{
CV_Assert(plugin_api_); CV_Assert(capture_);
}
~PluginCapture()
{
CV_DbgAssert(plugin_api_->v0.Capture_release);
if (CV_ERROR_OK != plugin_api_->v0.Capture_release(capture_))
CV_LOG_ERROR(NULL, "Video I/O: Can't release capture by plugin '" << plugin_api_->api_header.api_description << "'");
capture_ = NULL;
}
double getProperty(int prop) const CV_OVERRIDE
{
double val = -1;
if (plugin_api_->v0.Capture_getProperty)
if (CV_ERROR_OK != plugin_api_->v0.Capture_getProperty(capture_, prop, &val))
val = -1;
return val;
}
bool setProperty(int prop, double val) CV_OVERRIDE
{
if (plugin_api_->v0.Capture_setProperty)
if (CV_ERROR_OK == plugin_api_->v0.Capture_setProperty(capture_, prop, val))
return true;
return false;
}
bool grabFrame() CV_OVERRIDE
{
if (plugin_api_->v0.Capture_grab)
if (CV_ERROR_OK == plugin_api_->v0.Capture_grab(capture_))
return true;
return false;
}
static CvResult CV_API_CALL retrieve_callback(int stream_idx, const unsigned char* data, int step, int width, int height, int cn, void* userdata)
{
CV_UNUSED(stream_idx);
cv::_OutputArray* dst = static_cast<cv::_OutputArray*>(userdata);
if (!dst)
return CV_ERROR_FAIL;
cv::Mat(cv::Size(width, height), CV_MAKETYPE(CV_8U, cn), (void*)data, step).copyTo(*dst);
return CV_ERROR_OK;
}
bool retrieveFrame(int idx, cv::OutputArray img) CV_OVERRIDE
{
bool res = false;
if (plugin_api_->v0.Capture_retreive)
if (CV_ERROR_OK == plugin_api_->v0.Capture_retreive(capture_, idx, retrieve_callback, (cv::_OutputArray*)&img))
res = true;
return res;
}
bool isOpened() const CV_OVERRIDE
{
return capture_ != NULL; // TODO always true
}
int getCaptureDomain() CV_OVERRIDE
{
return plugin_api_->v0.captureAPI;
}
};
//==================================================================================================
class PluginWriter : public cv::IVideoWriter
{
const OpenCV_VideoIO_Plugin_API_preview* plugin_api_;
CvPluginWriter writer_;
public:
static
Ptr<PluginWriter> create(const OpenCV_VideoIO_Plugin_API_preview* plugin_api,
const std::string& filename, int fourcc, double fps, const cv::Size& sz,
const VideoWriterParameters& params)
{
CV_Assert(plugin_api);
CvPluginWriter writer = NULL;
if (plugin_api->api_header.api_version >= 1 && plugin_api->v1.Writer_open_with_params)
{
CV_Assert(plugin_api->v0.Writer_release);
CV_Assert(!filename.empty());
std::vector<int> vint_params = params.getIntVector();
int* c_params = &vint_params[0];
unsigned n_params = (unsigned)(vint_params.size() / 2);
if (CV_ERROR_OK == plugin_api->v1.Writer_open_with_params(filename.c_str(), fourcc, fps, sz.width, sz.height, c_params, n_params, &writer))
{
CV_Assert(writer);
return makePtr<PluginWriter>(plugin_api, writer);
}
}
else if (plugin_api->v0.Writer_open)
{
CV_Assert(plugin_api->v0.Writer_release);
CV_Assert(!filename.empty());
const bool isColor = params.get(VIDEOWRITER_PROP_IS_COLOR, true);
const int depth = params.get(VIDEOWRITER_PROP_DEPTH, CV_8U);
if (depth != CV_8U)
{
CV_LOG_WARNING(NULL, "Video I/O plugin doesn't support (due to lower API level) creation of VideoWriter with depth != CV_8U");
return Ptr<PluginWriter>();
}
if (CV_ERROR_OK == plugin_api->v0.Writer_open(filename.c_str(), fourcc, fps, sz.width, sz.height, isColor, &writer))
{
CV_Assert(writer);
return makePtr<PluginWriter>(plugin_api, writer);
}
}
return Ptr<PluginWriter>();
}
PluginWriter(const OpenCV_VideoIO_Plugin_API_preview* plugin_api, CvPluginWriter writer)
: plugin_api_(plugin_api), writer_(writer)
{
CV_Assert(plugin_api_); CV_Assert(writer_);
}
~PluginWriter()
{
CV_DbgAssert(plugin_api_->v0.Writer_release);
if (CV_ERROR_OK != plugin_api_->v0.Writer_release(writer_))
CV_LOG_ERROR(NULL, "Video I/O: Can't release writer by plugin '" << plugin_api_->api_header.api_description << "'");
writer_ = NULL;
}
double getProperty(int prop) const CV_OVERRIDE
{
double val = -1;
if (plugin_api_->v0.Writer_getProperty)
if (CV_ERROR_OK != plugin_api_->v0.Writer_getProperty(writer_, prop, &val))
val = -1;
return val;
}
bool setProperty(int prop, double val) CV_OVERRIDE
{
if (plugin_api_->v0.Writer_setProperty)
if (CV_ERROR_OK == plugin_api_->v0.Writer_setProperty(writer_, prop, val))
return true;
return false;
}
bool isOpened() const CV_OVERRIDE
{
return writer_ != NULL; // TODO always true
}
void write(cv::InputArray arr) CV_OVERRIDE
{
cv::Mat img = arr.getMat();
CV_DbgAssert(writer_);
CV_Assert(plugin_api_->v0.Writer_write);
if (CV_ERROR_OK != plugin_api_->v0.Writer_write(writer_, img.data, (int)img.step[0], img.cols, img.rows, img.channels()))
{
CV_LOG_DEBUG(NULL, "Video I/O: Can't write frame by plugin '" << plugin_api_->api_header.api_description << "'");
}
// TODO return bool result?
}
int getCaptureDomain() const CV_OVERRIDE
{
return plugin_api_->v0.captureAPI;
}
};
}}} // namespace
| 37.145 | 152 | 0.585947 | [
"vector"
] |
4346313e3c1620e57387538f88325df9abd7dae5 | 4,112 | cc | C++ | test/packet_test.cc | NilFoundation/actorio | 49ac3e87902d4388cd0bb29267207f89fb057e85 | [
"MIT"
] | null | null | null | test/packet_test.cc | NilFoundation/actorio | 49ac3e87902d4388cd0bb29267207f89fb057e85 | [
"MIT"
] | 3 | 2020-04-17T17:00:16.000Z | 2020-07-13T20:19:11.000Z | test/packet_test.cc | NilFoundation/actorio | 49ac3e87902d4388cd0bb29267207f89fb057e85 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------//
// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE core
#include <boost/test/included/unit_test.hpp>
#include <nil/actor/network/packet.hh>
#include <array>
using namespace nil::actor;
using namespace net;
BOOST_AUTO_TEST_CASE(test_many_fragments) {
std::vector<char> expected;
auto append = [&expected](net::packet p, char c, size_t n) {
auto tmp = temporary_buffer<char>(n);
std::fill_n(tmp.get_write(), n, c);
std::fill_n(std::back_inserter(expected), n, c);
return net::packet(std::move(p), std::move(tmp));
};
net::packet p;
p = append(std::move(p), 'a', 5);
p = append(std::move(p), 'b', 31);
p = append(std::move(p), 'c', 65);
p = append(std::move(p), 'c', 4096);
p = append(std::move(p), 'd', 4096);
auto verify = [&expected](const net::packet &p) {
BOOST_CHECK_EQUAL(p.len(), expected.size());
auto expected_it = expected.begin();
for (auto &&frag : p.fragments()) {
BOOST_CHECK_LE(frag.size, static_cast<size_t>(expected.end() - expected_it));
BOOST_CHECK(std::equal(frag.base, frag.base + frag.size, expected_it));
expected_it += frag.size;
}
};
auto trim_front = [&expected](net::packet &p, size_t n) {
p.trim_front(n);
expected.erase(expected.begin(), expected.begin() + n);
};
verify(p);
trim_front(p, 1);
verify(p);
trim_front(p, 6);
verify(p);
trim_front(p, 29);
verify(p);
trim_front(p, 1024);
verify(p);
net::packet p2;
p2 = append(std::move(p2), 'z', 9);
p2 = append(std::move(p2), 'x', 7);
p.append(std::move(p2));
verify(p);
}
BOOST_AUTO_TEST_CASE(test_headers_are_contiguous) {
using tcp_header = std::array<char, 20>;
using ip_header = std::array<char, 20>;
char data[1000] = {};
fragment f {data, sizeof(data)};
packet p(f);
p.prepend_header<tcp_header>();
p.prepend_header<ip_header>();
BOOST_REQUIRE_EQUAL(p.nr_frags(), 2u);
}
BOOST_AUTO_TEST_CASE(test_headers_are_contiguous_even_with_small_fragment) {
using tcp_header = std::array<char, 20>;
using ip_header = std::array<char, 20>;
char data[100] = {};
fragment f {data, sizeof(data)};
packet p(f);
p.prepend_header<tcp_header>();
p.prepend_header<ip_header>();
BOOST_REQUIRE_EQUAL(p.nr_frags(), 2u);
}
BOOST_AUTO_TEST_CASE(test_headers_are_contiguous_even_with_many_fragments) {
using tcp_header = std::array<char, 20>;
using ip_header = std::array<char, 20>;
char data[100] = {};
fragment f {data, sizeof(data)};
packet p(f);
for (int i = 0; i < 7; ++i) {
p.append(packet(f));
}
p.prepend_header<tcp_header>();
p.prepend_header<ip_header>();
BOOST_REQUIRE_EQUAL(p.nr_frags(), 9u);
}
| 33.16129 | 89 | 0.632539 | [
"vector"
] |
434c926bc929e33477c441c60b18a5ccb8589fdb | 25,096 | cc | C++ | src/vnsw/agent/test-xml/test_xml.cc | sagarc-contrail/contrail-controller | 834302367f3ff81f1ce93f4036b6b3788dfd6994 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/test-xml/test_xml.cc | sagarc-contrail/contrail-controller | 834302367f3ff81f1ce93f4036b6b3788dfd6994 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/test-xml/test_xml.cc | sagarc-contrail/contrail-controller | 834302367f3ff81f1ce93f4036b6b3788dfd6994 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
#include "base/os.h"
#include <iostream>
#include <fstream>
#include <pugixml/pugixml.hpp>
#include <boost/uuid/uuid.hpp>
#include <test/test_cmn_util.h>
#include <pkt/test/test_pkt_util.h>
#include <pkt/flow_mgmt.h>
#include <oper/global_vrouter.h>
#include "test_xml.h"
#include "test_xml_validate.h"
#include "test_xml_packet.h"
using namespace std;
using namespace pugi;
using namespace boost::uuids;
using namespace AgentUtXmlUtils;
class FlowExportTask : public Task {
public:
FlowExportTask(FlowEntry *fe, uint64_t bytes, uint64_t pkts) :
Task((TaskScheduler::GetInstance()->GetTaskId("Agent::StatsCollector")),
StatsCollector::FlowStatsCollector),
fe_(fe), bytes_(bytes), pkts_(pkts) {
}
virtual bool Run() {
FlowStatsCollector *fec = fe_->fsc();
if (!fec) {
return true;
}
FlowExportInfo *info = fec->FindFlowExportInfo(fe_);
if (!info) {
return true;
}
fec->ExportFlow(info, bytes_, pkts_, NULL, true);
return true;
}
std::string Description() const { return "FlowExportTask"; }
private:
FlowEntry *fe_;
uint64_t bytes_;
uint64_t pkts_;
};
namespace AgentUtXmlUtils {
bool GetStringAttribute(const xml_node &node, const string &name,
string *value) {
xml_attribute attr = node.attribute(name.c_str());
if (!attr) {
return false;;
}
*value = attr.as_string();
return true;
}
bool GetUintAttribute(const xml_node &node, const string &name,
uint16_t *value) {
xml_attribute attr = node.attribute(name.c_str());
if (!attr) {
return false;;
}
*value = attr.as_uint();
return true;
}
bool GetIntAttribute(const xml_node &node, const string &name, int *value) {
xml_attribute attr = node.attribute(name.c_str());
if (!attr) {
return false;;
}
*value = attr.as_int();
return true;
}
bool GetBoolAttribute(const xml_node &node, const string &name,
bool *value) {
xml_attribute attr = node.attribute(name.c_str());
if (!attr) {
return false;;
}
string str = attr.as_string();
if (str == "true" || str == "yes")
*value = true;
else
*value = false;
return true;
}
void NovaIntfAdd(bool op_delete, const uuid &id, const Ip4Address &ip,
const uuid &vm_uuid, const uuid vn_uuid, const string &name,
const string &mac, const string vm_name) {
if (op_delete) {
PortUnSubscribe(id);
cout << "Nova Del Interface Message " << endl;
return;
}
PortSubscribe(name, id, vm_uuid, vm_name, vn_uuid, MakeUuid(1), ip,
Ip6Address::v4_compatible(ip), mac);
cout << "Nova Add Interface Message " << endl;
return;
}
void LinkXmlNode(xml_node *parent, const string <ype, const string lname,
const string &rtype, const string rname) {
xml_node n = parent->append_child("link");
xml_node n1 = n.append_child("node");
n1.append_attribute("type") = ltype.c_str();
xml_node n2 = n1.append_child("name");
n2.append_child(pugi::node_pcdata).set_value(lname.c_str());
n1 = n.append_child("node");
n1.append_attribute("type") = rtype.c_str();
n2 = n1.append_child("name");
n2.append_child(pugi::node_pcdata).set_value(rname.c_str());
string mdata = GetMetadata(ltype.c_str(), rtype.c_str());
xml_node n3 = n.append_child("metadata");
n3.append_attribute("type") = mdata.c_str();
return;
}
xml_node AddXmlNodeWithAttr(xml_node *parent, const char *attr) {
xml_node n = parent->append_child("node");
n.append_attribute("type") = attr;
return n;
}
xml_node AddXmlNodeWithValue(xml_node *parent, const char *name,
const string &value) {
xml_node n = parent->append_child(name);
n.append_child(pugi::node_pcdata).set_value(value.c_str());
}
xml_node AddXmlNodeWithIntValue(xml_node *parent, const char *name,
int val) {
stringstream s;
s << val;
xml_node n = parent->append_child(name);
n.append_child(pugi::node_pcdata).set_value(s.str().c_str());
}
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlTest routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlTest::AgentUtXmlTest(const std::string &name) : file_name_(name) {
}
AgentUtXmlTest::~AgentUtXmlTest() {
for (AgentUtXmlTestList::iterator i = test_list_.begin();
i != test_list_.end(); i++) {
delete *i;
}
}
void AgentUtXmlTest::AddConfigEntry(const std::string &name,
AgentUtXmlTestConfigCreateFn fn) {
config_factory_[name] = fn;
}
void AgentUtXmlTest::AddValidateEntry(const std::string &name,
AgentUtXmlTestValidateCreateFn fn) {
validate_factory_[name] = fn;
}
AgentUtXmlTest::AgentUtXmlTestConfigCreateFn
AgentUtXmlTest::GetConfigCreateFn(const std::string &name) {
AgentUtXmlTestConfigFactory::iterator iter = config_factory_.find(name);
if (iter == config_factory_.end()) {
return AgentUtXmlTest::AgentUtXmlTestConfigCreateFn();
}
return iter->second;
}
AgentUtXmlTest::AgentUtXmlTestValidateCreateFn
AgentUtXmlTest::GetValidateCreateFn(const std::string &name) {
AgentUtXmlTestValidateFactory::iterator iter = validate_factory_.find(name);
if (iter == validate_factory_.end()) {
assert(0);
}
return iter->second;
}
bool AgentUtXmlTest::ReadXml() {
xml_node list = doc_.child("test_suite");
GetStringAttribute(list, "name", &name_);
for (xml_node node = list.first_child(); node; node = node.next_sibling()) {
if (strcmp(node.name(), "test") == 0) {
xml_attribute attr = node.attribute("name");
if (!attr) {
cout << "Missing attribute \"name\". Skipping" << endl;
continue;
}
AgentUtXmlTestCase *test = new AgentUtXmlTestCase(attr.value(),
node, this);
attr = node.attribute("verbose");
bool verbose = false;
if (!attr) {
verbose = false;
} else {
if (atoi(attr.value()))
verbose = true;
}
test->set_verbose(verbose);
test_list_.push_back(test);
test->ReadXml();
}
}
return true;
}
bool AgentUtXmlTest::Load() {
struct stat s;
if (stat(file_name_.c_str(), &s)) {
cout << "Error <" << strerror(errno) << "> opening file "
<< file_name_ << endl;
return false;
}
int fd = open(file_name_.c_str(), O_RDONLY);
if (fd < 0) {
cout << "Error <" << strerror(errno) << "> opening file "
<< file_name_ << endl;
return false;
}
char data[s.st_size + 1];
if (read(fd, data, s.st_size) < s.st_size) {
cout << "Error <" << strerror(errno) << "> reading file "
<< file_name_ << endl;
close(fd);
return false;
}
close(fd);
data[s.st_size] = '\0';
xml_parse_result result = doc_.load(data);
if (result) {
cout << "Loaded data file successfully" << endl;
} else {
cout << "Error in XML string at offset <: " << result.offset
<< "> (error at [..." << (data + result.offset) << "])" << endl;
return false;
}
return true;
}
void AgentUtXmlTest::ToString(string *str) {
stringstream s;
s << "Test Suite : " << name_ << endl;
*str += s.str();
for (AgentUtXmlTestList::iterator it = test_list_.begin();
it != test_list_.end(); it++) {
(*it)->ToString(str);
}
return;
}
bool AgentUtXmlTest::Run() {
for (AgentUtXmlTestList::iterator it = test_list_.begin();
it != test_list_.end(); it++) {
(*it)->Run();
}
return true;
}
bool AgentUtXmlTest::Run(std::string test_case) {
for (AgentUtXmlTestList::iterator it = test_list_.begin();
it != test_list_.end(); it++) {
if ((*it)->name().compare(test_case) == 0) {
(*it)->Run();
return true;
}
}
return false;
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlTestCase routines
/////////////////////////////////////////////////////////////////////////////
static bool CheckConfigNode(const string &node_name, const xml_node &node,
uuid *id, string *name) {
if (strcmp(node.name(), node_name.c_str()) != 0) {
return false;
}
xml_attribute attr = node.attribute("name");
if (!attr) {
cout << "Attribute \"name\" not found for " << node_name
<< ". Skipping..." << endl;
return false;
}
*name = attr.as_string();
if (*name == "") {
cout << "Invalid \"name\" for " << node_name << " Skipping" << endl;
return false;
}
if (node_name == "validate")
return false;
attr = node.attribute("uuid");
if (!attr) {
cout << "Attribute \"uuid\" not found for " << node_name
<< ". Skipping..." << endl;
return false;;
}
int x = attr.as_uint();
if (x == 0) {
cout << "Invalid \"uuid\" (0) for " << node_name << " Skipping" << endl;
return false;
}
*id = MakeUuid(x);
return true;
}
AgentUtXmlTestCase::AgentUtXmlTestCase(const std::string &name,
const xml_node &node,
AgentUtXmlTest *test)
: name_(name), xml_node_(node), test_(test), verbose_(false) {
cout << "Creating test-case <" << name_ << ">" << endl;
}
AgentUtXmlTestCase::~AgentUtXmlTestCase() {
for (AgentUtXmlNodeList::iterator i = node_list_.begin();
i != node_list_.end(); i++) {
delete *i;
}
}
bool AgentUtXmlTestCase::ReadXml() {
for (xml_node node = xml_node_.first_child(); node;
node = node.next_sibling()) {
string str;
bool op_delete = false;
if (GetStringAttribute(node, "delete", &str) == true ||
GetStringAttribute(node, "del", &str) == true) {
if (str != "false" && str != "0")
op_delete = true;
}
uuid id;
string name;
AgentUtXmlNode *cfg = NULL;
AgentUtXmlTest::AgentUtXmlTestConfigCreateFn fn =
test_->GetConfigCreateFn(node.name());
if (CheckConfigNode(node.name(), node, &id, &name) == true) {
if (fn.empty() == false)
cfg = fn(node.name(), name, id, node, this);
}
if (strcmp(node.name(), "link") == 0) {
cfg = new AgentUtXmlLink(node, this);
}
if (strcmp(node.name(), "packet") == 0) {
if (GetStringAttribute(node, "name", &name) == false) {
cout << "Attribute \"name\" not specified for Packet. Skipping"
<< endl;
continue;
}
cfg = new AgentUtXmlPacket(name, node, this);
}
if (strcmp(node.name(), "task") == 0) {
cfg = new AgentUtXmlTask(node, this);
}
if (strcmp(node.name(), "flow-export") == 0) {
cfg = new AgentUtXmlFlowExport(node, this);
}
if (strcmp(node.name(), "flow-threshold") == 0) {
cfg = new AgentUtXmlFlowThreshold(node, this);
}
if (strcmp(node.name(), "validate") == 0) {
if (GetStringAttribute(node, "name", &name) == false) {
cout << "Attribute \"name\" not specified for validate."
" Skipping" << endl;
continue;
}
cfg = new AgentUtXmlValidate(name, node, this);
}
if (cfg) {
cfg->set_op_delete(op_delete);
} else {
cout << "Unknown node name <" << node.name() << ">. Ignoring"
<< endl;
}
if (cfg) {
bool ret = cfg->ReadXml();
if (op_delete == false && ret == false) {
delete cfg;
cfg = NULL;
}
}
if (cfg) {
node_list_.push_back(cfg);
}
}
return true;
}
bool AgentUtXmlTestCase::Run() {
for (AgentUtXmlNodeList::iterator it = node_list_.begin();
it != node_list_.end(); it++) {
if ((*it)->gen_xml() == false) {
(*it)->Run();
TestClient::WaitForIdle();
continue;
}
xml_document doc;
xml_node decl = doc.prepend_child(pugi::node_declaration);
decl.append_attribute("version") = "1.0";
xml_node n = doc.append_child("config");
xml_node n1;
if ((*it)->op_delete()) {
n1 = n.append_child("delete");
} else {
n1 = n.append_child("update");
}
(*it)->ToXml(&n1);
if (verbose_) {
doc.print(std::cout);
}
Agent *agent = Agent::GetInstance();
agent->ifmap_parser()->ConfigParse(n, 0);
TestClient::WaitForIdle();
}
return true;
}
void AgentUtXmlTestCase::ToString(string *str) {
stringstream s;
s << "Test Case : " << name_ << endl;
*str += s.str();
for (AgentUtXmlNodeList::iterator it = node_list_.begin();
it != node_list_.end(); it++) {
(*it)->ToString(str);
}
return;
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlNode routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlNode::AgentUtXmlNode(const string &name, const xml_node &node,
AgentUtXmlTestCase *test_case) :
node_(node), name_(name), op_delete_(false), gen_xml_(true),
test_case_(test_case) {
}
AgentUtXmlNode::AgentUtXmlNode(const string &name, const xml_node &node,
bool gen_xml, AgentUtXmlTestCase *test_case) :
node_(node), name_(name), op_delete_(false), gen_xml_(gen_xml),
test_case_(test_case) {
}
AgentUtXmlNode::~AgentUtXmlNode() {
}
bool AgentUtXmlNode::ReadXml() {
string str;
op_delete_ = false;
if (GetStringAttribute(node_, "delete", &str) == true ||
GetStringAttribute(node_, "del", &str) == true) {
if (str != "false" && str != "0")
op_delete_ = true;
}
return true;
}
void AgentUtXmlNode::ToString(string *str) {
stringstream s;
if (op_delete_)
s << "Delete ";
else
s << "Add ";
s << NodeType() << " : " << name_ << " ";
*str += s.str();
return;
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlTask routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlTask::AgentUtXmlTask(const xml_node &node,
AgentUtXmlTestCase *test_case) :
AgentUtXmlNode("task", node, false, test_case) {
}
AgentUtXmlTask::~AgentUtXmlTask() {
}
bool AgentUtXmlTask::ReadXml() {
GetStringAttribute(node(), "stop", &stop_);
return true;
}
bool AgentUtXmlTask::ToXml(xml_node *parent) {
return true;
}
void AgentUtXmlTask::ToString(string *str) {
AgentUtXmlNode::ToString(str);
stringstream s;
s << "Stop : " << stop_ << endl;
*str += s.str();
return;
}
string AgentUtXmlTask::NodeType() {
return "Task";
}
bool AgentUtXmlTask::Run() {
if (boost::iequals(stop_, "1") || boost::iequals(stop_, "yes")) {
TestClient::WaitForIdle();
TaskScheduler::GetInstance()->Stop();
} else {
TaskScheduler::GetInstance()->Start();
TestClient::WaitForIdle();
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlLink routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlLink::AgentUtXmlLink(const xml_node &node,
AgentUtXmlTestCase *test_case) :
AgentUtXmlNode("link", node, test_case) {
}
AgentUtXmlLink::~AgentUtXmlLink() {
}
bool AgentUtXmlLink::ReadXml() {
if (GetStringAttribute(node(), "left", &l_node_) == false) {
cout << "Left node-type not specified for link. Skipping" << endl;
return false;
}
if (GetStringAttribute(node(), "left-name", &l_name_) == false) {
cout << "Right node-name not specified for link. Skipping" << endl;
return false;
}
if (GetStringAttribute(node(), "right", &r_node_) == false) {
cout << "Right node-type not specified for link. Skipping" << endl;
return false;
}
if (GetStringAttribute(node(), "right-name", &r_name_) == false) {
cout << "Right node-name not specified for link. Skipping" << endl;
return false;
}
return true;
}
bool AgentUtXmlLink::ToXml(xml_node *parent) {
LinkXmlNode(parent, l_node_, l_name_, r_node_, r_name_);
return true;
}
void AgentUtXmlLink::ToString(string *str) {
AgentUtXmlNode::ToString(str);
stringstream s;
s << "<" << l_node_ << " : " << l_name_ << "> <" << " right-node "
<< r_node_ << " : " << r_name_ << ">" << endl;
*str += s.str();
return;
}
string AgentUtXmlLink::NodeType() {
return "Link";
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlConfig routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlConfig::AgentUtXmlConfig(const string &name, const uuid &id,
const xml_node &node,
AgentUtXmlTestCase *test_case) :
AgentUtXmlNode(name, node, test_case), id_(id) {
}
AgentUtXmlConfig::AgentUtXmlConfig(const string &name, const uuid &id,
const xml_node &node, bool gen_xml,
AgentUtXmlTestCase *test_case) :
AgentUtXmlNode(name, node, gen_xml, test_case), id_(id) {
}
AgentUtXmlConfig::~AgentUtXmlConfig() {
}
bool AgentUtXmlConfig::ReadXml() {
return AgentUtXmlNode::ReadXml();
}
void AgentUtXmlConfig::ToString(std::string *str) {
AgentUtXmlNode::ToString(str);
stringstream s;
s << " UUID : " << id_;
*str += s.str();
}
static void AddPermissions(xml_node *parent) {
xml_node n = parent->append_child("permissions");
AddXmlNodeWithValue(&n, "owner", "cloud-admin");
AddXmlNodeWithValue(&n, "owner-access", "7");
AddXmlNodeWithValue(&n, "group", "cloud-admin-group");
AddXmlNodeWithValue(&n, "group-access", "7");
AddXmlNodeWithValue(&n, "other-access", "7");
}
static void AddUuid(xml_node *parent, const uuid &id) {
xml_node n = parent->append_child("uuid");
std::vector<uint8_t> v1(id.size());
std::vector<uint64_t> v(id.size());
std::copy(id.begin(), id.end(), v.begin());
uint64_t ms_val = v[7] + (v[6] << 8) + (v[5] << 16) + (v[4] << 24) +
(v[3] << 32) + (v[2] << 40) + (v[1] << 48) + (v[0] << 56);
uint64_t ls_val = v[15] + (v[14] << 8) + (v[13] << 16) + (v[12] << 24) +
(v[11] << 32) + (v[10] << 40) + (v[9] << 48) + (v[8] << 56);
stringstream s;
s << ms_val;
AddXmlNodeWithValue(&n, "uuid-mslong", s.str());
stringstream s1;
s1 << ls_val;
AddXmlNodeWithValue(&n, "uuid-lslong", s1.str());
}
bool AgentUtXmlConfig::AddIdPerms(xml_node *parent) {
if (op_delete())
return true;
xml_node n = parent->append_child("id-perms");
AddPermissions(&n);
AddUuid(&n, id());
AddXmlNodeWithValue(&n, "enable", "true");
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlFlowExport routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlFlowExport::AgentUtXmlFlowExport(const xml_node &node,
AgentUtXmlTestCase *test_case) :
AgentUtXmlNode("flow-export", node, false, test_case) {
}
AgentUtXmlFlowExport::~AgentUtXmlFlowExport() {
}
bool AgentUtXmlFlowExport::ReadXml() {
if (GetUintAttribute(node(), "nh", &nh_id_) == false) {
cout << "Attribute \"nh\" not specified for Flow. Skipping" << endl;
return false;
}
if (GetStringAttribute(node(), "sip", &sip_) == false) {
cout << "Attribute \"sip\" not specified for Flow. Skipping" << endl;
return false;
}
if (GetStringAttribute(node(), "dip", &dip_) == false) {
cout << "Attribute \"dip\" not specified for Flow. Skipping" << endl;
return false;
}
if (GetStringAttribute(node(), "proto", &proto_) == false &&
GetUintAttribute(node(), "proto", &proto_id_) == false) {
cout << "Attribute \"proto\" not specified for Flow. Skipping"
<< endl;
return false;
}
if (proto_ == "tcp" || proto_ == "udp") {
if (proto_ == "tcp")
proto_id_ = 6;
else
proto_id_ = 17;
if (GetUintAttribute(node(), "sport", &sport_) == false) {
cout << "Attribute \"sport\" not specified for Flow. Skipping"
<< endl;
return false;
}
if (GetUintAttribute(node(), "dport", &dport_) == false) {
cout << "Attribute \"dport\" not specified for Flow. Skipping"
<< endl; return false;
}
}
uint16_t bytes, pkts;
if (GetUintAttribute(node(), "bytes", &bytes) == false) {
bytes_ = 0;
} else {
bytes_ = (uint32_t)bytes;
}
if (GetUintAttribute(node(), "pkts", &pkts) == false) {
pkts_ = 0;
} else {
pkts_ = (uint32_t)pkts;
}
return true;
}
bool AgentUtXmlFlowExport::ToXml(xml_node *parent) {
return true;
}
void AgentUtXmlFlowExport::EnqueueFlowExport(FlowEntry *fe, uint64_t bytes,
uint64_t pkts) {
TaskScheduler *scheduler = TaskScheduler::GetInstance();
FlowExportTask *task = new FlowExportTask(fe, bytes, pkts);
scheduler->Enqueue(task);
}
bool AgentUtXmlFlowExport::Run() {
FlowEntry *flow = FlowGet(0, sip_, dip_, proto_id_, sport_, dport_,
nh_id_);
if (flow == NULL)
return false;
EnqueueFlowExport(flow, bytes_, pkts_);
TestClient::WaitForIdle();
return true;
}
void AgentUtXmlFlowExport::ToString(string *str) {
AgentUtXmlNode::ToString(str);
*str += "\n";
return;
}
string AgentUtXmlFlowExport::NodeType() {
return "flow-export";
}
/////////////////////////////////////////////////////////////////////////////
// AgentUtXmlFlowThreshold routines
/////////////////////////////////////////////////////////////////////////////
AgentUtXmlFlowThreshold::AgentUtXmlFlowThreshold(const xml_node &node,
AgentUtXmlTestCase *test_case) :
AgentUtXmlNode("flow-threshold", node, false, test_case) {
}
AgentUtXmlFlowThreshold::~AgentUtXmlFlowThreshold() {
}
bool AgentUtXmlFlowThreshold::ReadXml() {
uint16_t flow_export_count, configured_flow_export_rate, threshold;
if (GetUintAttribute(node(), "flow-export-count", &flow_export_count) ==
false) {
cout << "Attribute \"flow-export-count\" not specified for Flow. "
"Skipping" << endl;
return false;
}
flow_export_count_ = flow_export_count;
if (GetUintAttribute(node(), "configured-flow-export-rate",
&configured_flow_export_rate) == false) {
configured_flow_export_rate_ = GlobalVrouter::kDefaultFlowExportRate;
} else {
configured_flow_export_rate_ = configured_flow_export_rate;
}
if (GetUintAttribute(node(), "threshold", &threshold) == false) {
threshold_ = FlowStatsCollector::kDefaultFlowSamplingThreshold;
} else {
threshold_ = threshold;
}
return true;
}
bool AgentUtXmlFlowThreshold::ToXml(xml_node *parent) {
return true;
}
bool AgentUtXmlFlowThreshold::Run() {
Agent *agent = Agent::GetInstance();
uint64_t curr_time = UTCTimestampUsec();
FlowStatsManager *mgr = Agent::GetInstance()->flow_stats_manager();
mgr->prev_flow_export_rate_compute_time_ = curr_time - 1000000;
GlobalVrouter *vr = agent->oper_db()->global_vrouter();
vr->flow_export_rate_ = configured_flow_export_rate_;
mgr->flow_export_count_ = flow_export_count_;
mgr->threshold_ = threshold_;
mgr->UpdateFlowThreshold();
TestClient::WaitForIdle();
}
void AgentUtXmlFlowThreshold::ToString(string *str) {
AgentUtXmlNode::ToString(str);
*str += "\n";
return;
}
string AgentUtXmlFlowThreshold::NodeType() {
return "flow-threshold";
}
| 29.317757 | 80 | 0.546422 | [
"vector"
] |
434ce6d7029855d572965ba5fac5b74233fce067 | 2,702 | cc | C++ | vpc/src/model/DeleteSnatEntryRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | vpc/src/model/DeleteSnatEntryRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | vpc/src/model/DeleteSnatEntryRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/vpc/model/DeleteSnatEntryRequest.h>
using AlibabaCloud::Vpc::Model::DeleteSnatEntryRequest;
DeleteSnatEntryRequest::DeleteSnatEntryRequest() :
RpcServiceRequest("vpc", "2016-04-28", "DeleteSnatEntry")
{}
DeleteSnatEntryRequest::~DeleteSnatEntryRequest()
{}
long DeleteSnatEntryRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DeleteSnatEntryRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string DeleteSnatEntryRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void DeleteSnatEntryRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string DeleteSnatEntryRequest::getRegionId()const
{
return regionId_;
}
void DeleteSnatEntryRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
std::string DeleteSnatEntryRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void DeleteSnatEntryRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
std::string DeleteSnatEntryRequest::getSnatTableId()const
{
return snatTableId_;
}
void DeleteSnatEntryRequest::setSnatTableId(const std::string& snatTableId)
{
snatTableId_ = snatTableId;
setParameter("SnatTableId", snatTableId);
}
std::string DeleteSnatEntryRequest::getSnatEntryId()const
{
return snatEntryId_;
}
void DeleteSnatEntryRequest::setSnatEntryId(const std::string& snatEntryId)
{
snatEntryId_ = snatEntryId;
setParameter("SnatEntryId", snatEntryId);
}
long DeleteSnatEntryRequest::getOwnerId()const
{
return ownerId_;
}
void DeleteSnatEntryRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
| 25.733333 | 94 | 0.766099 | [
"model"
] |
43589a52c8b771e247045f4d016964fd3959f8cc | 40,414 | cpp | C++ | src/tool/abi/types.cpp | raffaeler/xlang | 986ff8784f47d36106c7e7b26b885ceb8569f6bc | [
"MIT"
] | 1 | 2019-10-23T20:33:45.000Z | 2019-10-23T20:33:45.000Z | src/tool/abi/types.cpp | raffaeler/xlang | 986ff8784f47d36106c7e7b26b885ceb8569f6bc | [
"MIT"
] | null | null | null | src/tool/abi/types.cpp | raffaeler/xlang | 986ff8784f47d36106c7e7b26b885ceb8569f6bc | [
"MIT"
] | null | null | null | #include "pch.h"
#include "abi_writer.h"
#include "code_writers.h"
#include "types.h"
#include "type_banners.h"
using namespace std::literals;
using namespace xlang::meta::reader;
using namespace xlang::text;
template <typename T>
static std::size_t push_type_contract_guards(writer& w, T const& type)
{
if (auto vers = get_contracts(type))
{
w.push_contract_guard(*vers);
return 1;
}
return 0;
}
std::size_t typedef_base::push_contract_guards(writer& w) const
{
XLANG_ASSERT(!is_generic());
return push_type_contract_guards(w, m_type);
}
void typedef_base::write_cpp_abi_name(writer& w) const
{
write_cpp_fully_qualified_type(w, clr_abi_namespace(), cpp_abi_name());
}
static std::string_view enum_string(writer& w)
{
return w.config().enum_class ? "MIDL_ENUM"sv : "enum"sv;
}
void enum_type::write_cpp_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.push_namespace(clr_abi_namespace());
auto typeStr = underlying_type() == ElementType::I4 ? "int"sv : "unsigned int"sv;
w.write("%typedef % % : % %;\n", indent{}, enum_string(w), cpp_abi_name(), typeStr, cpp_abi_name());
w.pop_namespace();
w.write('\n');
}
void enum_type::write_cpp_generic_param_abi_type(writer& w) const
{
w.write("% ", enum_string(w));
write_cpp_abi_param(w);
}
void enum_type::write_cpp_abi_param(writer& w) const
{
// Enums are passed by value
write_cpp_abi_name(w);
}
void enum_type::write_c_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.write("typedef enum % %;\n\n", bind_c_type_name(*this), bind_c_type_name(*this));
}
void enum_type::write_c_abi_param(writer& w) const
{
w.write("enum %", bind_c_type_name(*this));
}
void enum_type::write_cpp_definition(writer& w) const
{
auto name = cpp_abi_name();
write_type_banner(w, *this);
auto contractDepth = push_contract_guards(w);
w.push_namespace(clr_abi_namespace());
w.write("%%", indent{}, enum_string(w));
if (auto info = is_deprecated())
{
w.write("\n");
write_deprecation_message(w, *info);
w.write("%", indent{});
}
else
{
w.write(' ');
}
auto typeStr = underlying_type() == ElementType::I4 ? "int"sv : "unsigned int"sv;
w.write(R"^-^(% : %
%{
)^-^", name, typeStr, indent{});
for (auto const& field : m_type.FieldList())
{
if (auto value = field.Constant())
{
auto fieldContractDepth = push_type_contract_guards(w, field);
w.write("%", indent{ 1 });
if (!w.config().enum_class)
{
w.write("%_", name);
}
w.write(field.Name());
if (auto info = ::is_deprecated(field))
{
w.write("\n");
write_deprecation_message(w, *info, 1, "DEPRECATEDENUMERATOR");
w.write("%", indent{ 1 });
}
else
{
w.write(' ');
}
w.write("= %,\n", value);
w.pop_contract_guards(fieldContractDepth);
}
}
w.write("%};\n", indent{});
if (is_flags_enum(m_type))
{
w.write("\n%DEFINE_ENUM_FLAG_OPERATORS(%)\n", indent{}, name);
}
if (w.config().enum_class)
{
w.write('\n');
for (auto const& field : m_type.FieldList())
{
if (field.Constant())
{
w.write("%const % %_% = %::%;\n", indent{}, name, name, field.Name(), name, field.Name());
}
}
}
w.pop_namespace();
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void enum_type::write_c_definition(writer& w) const
{
write_type_banner(w, *this);
auto contractDepth = push_contract_guards(w);
w.write("enum");
if (auto info = is_deprecated())
{
w.write("\n");
write_deprecation_message(w, *info);
}
else
{
w.write(' ');
}
w.write(R"^-^(%
{
)^-^", bind_c_type_name(*this));
for (auto const& field : m_type.FieldList())
{
if (auto value = field.Constant())
{
auto fieldContractDepth = push_type_contract_guards(w, field);
w.write(" %_%", cpp_abi_name(), field.Name());
if (auto info = ::is_deprecated(field))
{
w.write("\n");
write_deprecation_message(w, *info, 1, "DEPRECATEDENUMERATOR");
w.write(" ");
}
w.write(" = %,\n", value);
w.pop_contract_guards(fieldContractDepth);
}
}
w.write("};\n");
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void struct_type::write_cpp_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.push_namespace(clr_abi_namespace());
w.write("%typedef struct % %;\n", indent{}, cpp_abi_name(), cpp_abi_name());
w.pop_namespace();
w.write('\n');
}
void struct_type::write_cpp_generic_param_abi_type(writer& w) const
{
w.write("struct ");
write_cpp_abi_param(w);
}
void struct_type::write_cpp_abi_param(writer& w) const
{
// Structs are passed by value
write_cpp_abi_name(w);
}
void struct_type::write_c_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.write("typedef struct % %;\n\n", bind_c_type_name(*this), bind_c_type_name(*this));
}
void struct_type::write_c_abi_param(writer& w) const
{
w.write("struct %", bind_c_type_name(*this));
}
void struct_type::write_cpp_definition(writer& w) const
{
write_type_banner(w, *this);
auto contractDepth = push_contract_guards(w);
w.push_namespace(clr_abi_namespace());
w.write("%struct", indent{});
if (auto info = is_deprecated())
{
w.write('\n');
write_deprecation_message(w, *info);
w.write("%", indent{});
}
else
{
w.write(' ');
}
w.write(R"^-^(%
%{
)^-^", cpp_abi_name(), indent{});
for (auto const& member : members)
{
if (auto info = ::is_deprecated(member.field))
{
write_deprecation_message(w, *info, 1);
}
w.write("%% %;\n", indent{ 1 }, [&](writer& w) { member.type->write_cpp_abi_param(w); }, member.field.Name());
}
w.write("%};\n", indent{});
w.pop_namespace();
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void struct_type::write_c_definition(writer& w) const
{
write_type_banner(w, *this);
auto contractDepth = push_contract_guards(w);
w.write("struct");
if (auto info = is_deprecated())
{
w.write('\n');
write_deprecation_message(w, *info);
}
else
{
w.write(' ');
}
w.write(R"^-^(%
{
)^-^", bind_c_type_name(*this));
for (auto const& member : members)
{
if (auto info = ::is_deprecated(member.field))
{
write_deprecation_message(w, *info, 1);
}
w.write(" % %;\n", [&](writer& w) { member.type->write_c_abi_param(w); }, member.field.Name());
}
w.write("};\n");
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void delegate_type::write_cpp_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.write(R"^-^(#ifndef __%_FWD_DEFINED__
#define __%_FWD_DEFINED__
)^-^", bind_mangled_name_macro(*this), bind_mangled_name_macro(*this));
w.push_namespace(clr_abi_namespace());
w.write("%interface %;\n", indent{}, m_abiName);
w.pop_namespace();
w.write(R"^-^(#define % %
#endif // __%_FWD_DEFINED__
)^-^",
bind_mangled_name_macro(*this),
bind_cpp_fully_qualified_type(clr_abi_namespace(), m_abiName),
bind_mangled_name_macro(*this));
}
void delegate_type::write_cpp_generic_param_abi_type(writer& w) const
{
write_cpp_abi_param(w);
}
void delegate_type::write_cpp_abi_param(writer& w) const
{
write_cpp_abi_name(w);
w.write('*');
}
static std::string_view function_name(MethodDef const& def)
{
// If this is an overload, use the unique name
auto fnName = def.Name();
if (auto overloadAttr = get_attribute(def, metadata_namespace, "OverloadAttribute"sv))
{
auto sig = overloadAttr.Value();
auto const& fixedArgs = sig.FixedArgs();
XLANG_ASSERT(fixedArgs.size() == 1);
fnName = std::get<std::string_view>(std::get<ElemSig>(fixedArgs[0].value).value);
}
return fnName;
}
static void write_cpp_function_declaration(writer& w, function_def const& func)
{
if (auto info = is_deprecated(func.def))
{
write_deprecation_message(w, *info, 1);
}
w.write("%virtual HRESULT STDMETHODCALLTYPE %(", indent{ 1 }, function_name(func.def));
std::string_view prefix = "\n"sv;
for (auto const& param : func.params)
{
auto refMod = param.signature.ByRef() ? "*"sv : ""sv;
if (param.signature.Type().is_szarray())
{
w.write("%%UINT32% %Length", prefix, indent{ 2 }, refMod, param.name);
refMod = param.signature.ByRef() ? "**"sv : "*"sv;
prefix = ",\n";
}
auto constMod = is_const(param.signature) ? "const "sv : ""sv;
w.write("%%%%% %",
prefix,
indent{ 2 },
constMod,
[&](writer& w) { param.type->write_cpp_abi_param(w); },
refMod,
param.name);
prefix = ",\n";
}
if (func.return_type)
{
auto refMod = "*"sv;
if (func.return_type->signature.Type().is_szarray())
{
w.write("%%UINT32* %Length", prefix, indent{ 2 }, func.return_type->name);
refMod = "**"sv;
prefix = ",\n";
}
w.write("%%%% %",
prefix,
indent{ 2 },
[&](writer& w) { func.return_type->type->write_cpp_abi_param(w); },
refMod,
func.return_type->name);
}
if (func.params.empty() && !func.return_type)
{
w.write("void) = 0;\n");
}
else
{
w.write("\n%) = 0;\n", indent{ 2 });
}
}
template <typename T>
static void write_cpp_interface_definition(writer& w, T const& type)
{
constexpr bool is_delegate = std::is_same_v<T, delegate_type>;
constexpr bool is_interface = std::is_same_v<T, interface_type>;
constexpr bool is_fastabi = std::is_same_v<T, fastabi_type>;
static_assert(is_delegate || is_interface || is_fastabi);
w.push_namespace(type.clr_abi_namespace());
w.write(R"^-^(%MIDL_INTERFACE("%")
)^-^", indent{}, bind_uuid(type));
if (auto info = is_deprecated(type.type()))
{
write_deprecation_message(w, *info);
}
w.write("%% : public ", indent{}, type.cpp_abi_name());
if constexpr (is_delegate)
{
w.write("IUnknown");
}
else if constexpr (is_interface)
{
w.write("IInspectable");
}
else
{
type.base().write_cpp_abi_name(w);
}
w.write(R"^-^(
%{
%public:
)^-^", indent{}, indent{});
if constexpr (is_fastabi)
{
for (auto const& func : type.current_interface().functions)
{
write_cpp_function_declaration(w, func);
}
}
else
{
for (auto const& func : type.functions)
{
write_cpp_function_declaration(w, func);
}
}
w.write(R"^-^(%};
%extern MIDL_CONST_ID IID& IID_% = _uuidof(%);
)^-^", indent{}, indent{}, type.cpp_abi_name(), type.cpp_abi_name());
w.pop_namespace();
}
template <typename T>
static void write_c_iunknown_interface(writer& w, T const& type)
{
w.write(R"^-^( HRESULT (STDMETHODCALLTYPE* QueryInterface)(%* This,
REFIID riid,
void** ppvObject);
ULONG (STDMETHODCALLTYPE* AddRef)(%* This);
ULONG (STDMETHODCALLTYPE* Release)(%* This);
)^-^", bind_c_type_name(type), bind_c_type_name(type), bind_c_type_name(type));
}
template <typename T>
static void write_c_iunknown_interface_macros(writer& w, T const& type)
{
w.write(R"^-^(#define %_QueryInterface(This, riid, ppvObject) \
((This)->lpVtbl->QueryInterface(This, riid, ppvObject))
#define %_AddRef(This) \
((This)->lpVtbl->AddRef(This))
#define %_Release(This) \
((This)->lpVtbl->Release(This))
)^-^", bind_mangled_name_macro(type), bind_mangled_name_macro(type), bind_mangled_name_macro(type));
}
template <typename T>
static void write_c_iinspectable_interface(writer& w, T const& type)
{
write_c_iunknown_interface(w, type);
w.write(R"^-^( HRESULT (STDMETHODCALLTYPE* GetIids)(%* This,
ULONG* iidCount,
IID** iids);
HRESULT (STDMETHODCALLTYPE* GetRuntimeClassName)(%* This,
HSTRING* className);
HRESULT (STDMETHODCALLTYPE* GetTrustLevel)(%* This,
TrustLevel* trustLevel);
)^-^", bind_c_type_name(type), bind_c_type_name(type), bind_c_type_name(type));
}
template <typename T>
static void write_c_iinspectable_interface_macros(writer& w, T const& type)
{
write_c_iunknown_interface_macros(w, type);
w.write(R"^-^(#define %_GetIids(This, iidCount, iids) \
((This)->lpVtbl->GetIids(This, iidCount, iids))
#define %_GetRuntimeClassName(This, className) \
((This)->lpVtbl->GetRuntimeClassName(This, className))
#define %_GetTrustLevel(This, trustLevel) \
((This)->lpVtbl->GetTrustLevel(This, trustLevel))
)^-^", bind_mangled_name_macro(type), bind_mangled_name_macro(type), bind_mangled_name_macro(type));
}
template <typename TypeName>
static void write_c_function_declaration(writer& w, TypeName&& typeName, function_def const& func)
{
if (auto info = is_deprecated(func.def))
{
write_deprecation_message(w, *info, 1);
}
w.write(" HRESULT (STDMETHODCALLTYPE* %)(%* This", function_name(func.def), typeName);
for (auto const& param : func.params)
{
auto refMod = param.signature.ByRef() ? "*"sv : ""sv;
if (param.signature.Type().is_szarray())
{
w.write(",\n UINT32% %Length", refMod, param.name);
refMod = param.signature.ByRef() ? "**"sv : "*"sv;
}
auto constMod = is_const(param.signature) ? "const "sv : ""sv;
w.write(",\n %%% %",
constMod,
[&](writer& w) { param.type->write_c_abi_param(w); },
refMod,
param.name);
}
if (func.return_type)
{
auto refMod = "*"sv;
if (func.return_type->signature.Type().is_szarray())
{
w.write(",\n UINT32* %Length", func.return_type->name);
refMod = "**"sv;
}
w.write(",\n %% %",
[&](writer& w) { func.return_type->type->write_c_abi_param(w); },
refMod,
func.return_type->name);
}
w.write(");\n");
}
template <typename T>
static void write_c_function_declaration_macro(writer& w, T const& type, function_def const& func)
{
if (auto info = is_deprecated(func.def))
{
write_deprecation_message(w, *info, 1);
}
auto fnName = function_name(func.def);
w.write("#define %_%(This", bind_mangled_name_macro(type), fnName);
for (auto const& param : func.params)
{
if (param.signature.Type().is_szarray())
{
w.write(", %Length", param.name);
}
w.write(", %", param.name);
}
if (func.return_type)
{
if (func.return_type->signature.Type().is_szarray())
{
w.write(", %Length", func.return_type->name);
}
w.write(", %", func.return_type->name);
}
w.write(R"^-^() \
((This)->lpVtbl->%(This)^-^", fnName);
for (auto const& param : func.params)
{
if (param.signature.Type().is_szarray())
{
w.write(", %Length", param.name);
}
w.write(", %", param.name);
}
if (func.return_type)
{
if (func.return_type->signature.Type().is_szarray())
{
w.write(", %Length", func.return_type->name);
}
w.write(", %", func.return_type->name);
}
w.write("))\n\n");
}
template <typename T>
static void write_c_interface_definition(writer& w, T const& type)
{
w.write("typedef struct");
if (auto info = type.is_deprecated())
{
w.write('\n');
write_deprecation_message(w, *info);
}
else
{
w.write(' ');
}
w.write(R"^-^(%
{
BEGIN_INTERFACE
)^-^", bind_c_type_name(type, "Vtbl"));
bool isDelegate = type.category() == category::delegate_type;
if (isDelegate)
{
write_c_iunknown_interface(w, type);
}
else
{
write_c_iinspectable_interface(w, type);
}
for (auto const& func : type.functions)
{
write_c_function_declaration(w, bind_c_type_name(type), func);
}
w.write(R"^-^(
END_INTERFACE
} %;
interface %
{
CONST_VTBL struct %* lpVtbl;
};
#ifdef COBJMACROS
)^-^", bind_c_type_name(type, "Vtbl"), bind_c_type_name(type), bind_c_type_name(type, "Vtbl"));
if (isDelegate)
{
write_c_iunknown_interface_macros(w, type);
}
else
{
write_c_iinspectable_interface_macros(w, type);
}
for (auto const& func : type.functions)
{
write_c_function_declaration_macro(w, type, func);
}
w.write(R"^-^(#endif /* COBJMACROS */
)^-^");
}
void delegate_type::write_c_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.write(R"^-^(#ifndef __%_FWD_DEFINED__
#define __%_FWD_DEFINED__
)^-^", bind_mangled_name_macro(*this), bind_mangled_name_macro(*this));
w.write(R"^-^(typedef interface % %;
#endif // __%_FWD_DEFINED__
)^-^",
bind_c_type_name(*this),
bind_c_type_name(*this),
bind_mangled_name_macro(*this));
}
void delegate_type::write_c_abi_param(writer& w) const
{
w.write("%*", bind_c_type_name(*this));
}
static void write_delegate_definition(writer& w, delegate_type const& type, void (*func)(writer&, delegate_type const&))
{
// Generics don't get generated definitions
if (type.is_generic())
{
return;
}
write_type_banner(w, type);
auto contractDepth = type.push_contract_guards(w);
w.write(R"^-^(#if !defined(__%_INTERFACE_DEFINED__)
#define __%_INTERFACE_DEFINED__
)^-^", bind_mangled_name_macro(type), bind_mangled_name_macro(type));
func(w, type);
w.write(R"^-^(
EXTERN_C const IID %;
#endif /* !defined(__%_INTERFACE_DEFINED__) */
)^-^", bind_iid_name(type), bind_mangled_name_macro(type));
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void delegate_type::write_cpp_definition(writer& w) const
{
write_delegate_definition(w, *this, &write_cpp_interface_definition<delegate_type>);
}
void delegate_type::write_c_definition(writer& w) const
{
write_delegate_definition(w, *this, &write_c_interface_definition<delegate_type>);
}
void interface_type::write_cpp_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.write(R"^-^(#ifndef __%_FWD_DEFINED__
#define __%_FWD_DEFINED__
)^-^", bind_mangled_name_macro(*this), bind_mangled_name_macro(*this));
w.push_namespace(clr_abi_namespace());
w.write("%interface %;\n", indent{}, m_type.TypeName());
w.pop_namespace();
w.write(R"^-^(#define % %
#endif // __%_FWD_DEFINED__
)^-^",
bind_mangled_name_macro(*this),
bind_cpp_fully_qualified_type(clr_abi_namespace(), m_type.TypeName()),
bind_mangled_name_macro(*this));
}
void interface_type::write_cpp_generic_param_abi_type(writer& w) const
{
write_cpp_abi_param(w);
}
void interface_type::write_cpp_abi_param(writer& w) const
{
write_cpp_abi_name(w);
w.write('*');
}
void interface_type::write_c_forward_declaration(writer& w) const
{
if (!w.should_forward_declare(m_mangledName))
{
return;
}
w.write(R"^-^(#ifndef __%_FWD_DEFINED__
#define __%_FWD_DEFINED__
typedef interface % %;
#endif // __%_FWD_DEFINED__
)^-^",
bind_mangled_name_macro(*this),
bind_mangled_name_macro(*this),
bind_c_type_name(*this),
bind_c_type_name(*this),
bind_mangled_name_macro(*this));
}
void interface_type::write_c_abi_param(writer& w) const
{
w.write("%*", bind_c_type_name(*this));
}
static void write_interface_definition(writer& w, interface_type const& type, void (*func)(writer&, interface_type const&))
{
// Generics don't get generated definitions
if (type.is_generic())
{
return;
}
write_type_banner(w, type);
auto contractDepth = type.push_contract_guards(w);
w.write(R"^-^(#if !defined(__%_INTERFACE_DEFINED__)
#define __%_INTERFACE_DEFINED__
extern const __declspec(selectany) _Null_terminated_ WCHAR InterfaceName_%_%[] = L"%";
)^-^",
bind_mangled_name_macro(type),
bind_mangled_name_macro(type),
bind_list("_", namespace_range{ type.clr_abi_namespace() }),
type.cpp_abi_name(),
type.clr_full_name());
func(w, type);
w.write(R"^-^(
EXTERN_C const IID %;
#endif /* !defined(__%_INTERFACE_DEFINED__) */
)^-^", bind_iid_name(type), bind_mangled_name_macro(type));
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void interface_type::write_cpp_definition(writer& w) const
{
write_interface_definition(w, *this, &write_cpp_interface_definition<interface_type>);
}
void interface_type::write_c_definition(writer& w) const
{
write_interface_definition(w, *this, &write_c_interface_definition<interface_type>);
}
void class_type::write_cpp_forward_declaration(writer& w) const
{
if (!default_interface)
{
XLANG_ASSERT(false);
xlang::throw_invalid("Cannot forward declare class '", m_clrFullName, "' since it has no default interface");
}
if (!w.should_forward_declare(m_mangledName))
{
return;
}
// We need to declare both the class as well as the default interface
w.push_namespace(clr_logical_namespace());
w.write("%class %;\n", indent{}, cpp_logical_name());
w.pop_namespace();
w.write('\n');
default_interface->write_cpp_forward_declaration(w);
}
void class_type::write_cpp_generic_param_logical_type(writer& w) const
{
w.write("%*", bind_cpp_fully_qualified_type(clr_logical_namespace(), cpp_logical_name()));
}
void class_type::write_cpp_generic_param_abi_type(writer& w) const
{
if (!default_interface)
{
XLANG_ASSERT(false);
xlang::throw_invalid("Class '", m_clrFullName, "' cannot be used as a generic parameter since it has no "
"default interface");
}
// The second template argument may look a bit odd, but it is correct. The default interface must be an interface,
// which won't be aggregated and this is the simplest way to write generics correctly
w.write("%<%*, %>",
bind_cpp_fully_qualified_type("Windows.Foundation.Internal"sv, "AggregateType"sv),
bind_cpp_fully_qualified_type(clr_logical_namespace(), cpp_logical_name()),
[&](writer& w) { default_interface->write_cpp_generic_param_abi_type(w); });
}
void class_type::write_cpp_abi_param(writer& w) const
{
if (!default_interface)
{
XLANG_ASSERT(false);
xlang::throw_invalid("Class '", m_clrFullName, "' cannot be used as a function argument since it has no "
"default interface");
}
default_interface->write_cpp_abi_param(w);
}
void class_type::write_c_forward_declaration(writer& w) const
{
if (!default_interface)
{
XLANG_ASSERT(false);
xlang::throw_invalid("Cannot forward declare class '", m_clrFullName, "' since it has no default interface");
}
default_interface->write_c_forward_declaration(w);
}
void class_type::write_c_abi_param(writer& w) const
{
if (!default_interface)
{
XLANG_ASSERT(false);
xlang::throw_invalid("Class '", m_clrFullName, "' cannot be used as a function argument since it has no "
"default interface");
}
default_interface->write_c_abi_param(w);
}
void class_type::write_cpp_definition(writer& w) const
{
write_type_banner(w, *this);
auto contractDepth = push_contract_guards(w);
w.write(R"^-^(#ifndef RUNTIMECLASS_%_%_DEFINED
#define RUNTIMECLASS_%_%_DEFINED
)^-^",
bind_list("_", namespace_range{ clr_logical_namespace() }),
cpp_logical_name(),
bind_list("_", namespace_range{ clr_logical_namespace() }),
cpp_logical_name());
if (auto info = is_deprecated())
{
write_deprecation_message(w, *info);
}
w.write(R"^-^(extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_%_%[] = L"%";
#endif
)^-^",
bind_list("_", namespace_range{ clr_logical_namespace() }),
cpp_logical_name(),
clr_full_name());
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void class_type::write_c_definition(writer& w) const
{
write_cpp_definition(w);
}
static void write_fastabi_definition(writer& w, fastabi_type const& type, void (*func)(writer&, fastabi_type const&))
{
write_type_banner(w, type);
auto contractDepth = type.push_contract_guards(w);
w.write(R"^-^(#if !defined(__%_INTERFACE_DEFINED__)
#define __%_INTERFACE_DEFINED__
)^-^", bind_mangled_name_macro(type), bind_mangled_name_macro(type));
func(w, type);
w.write(R"^-^(
#endif /* !defined(__%_INTERFACE_DEFINED__) */
)^-^", bind_mangled_name_macro(type));
w.pop_contract_guards(contractDepth);
w.write('\n');
}
void fastabi_type::write_cpp_abi_name(writer& w) const
{
write_cpp_fully_qualified_type(w, clr_abi_namespace(), m_typeName);
}
void fastabi_type::write_cpp_definition(writer& w) const
{
write_fastabi_definition(w, *this, &write_cpp_interface_definition<fastabi_type>);
}
static void write_c_interface_function_declarations(writer& w, fastabi_type const& type, interface_type const& iface)
{
for (auto const& func : iface.functions)
{
write_c_function_declaration(w, bind_c_type_name(type), func);
}
}
static void write_c_interface_function_declarations(writer& w, fastabi_type const& type, generic_inst const& genericInst)
{
for (auto const& func : genericInst.functions)
{
write_c_function_declaration(w, bind_c_type_name(type), func);
}
}
static void write_c_interface_function_declarations(writer& w, fastabi_type const& type, metadata_type const& targetType)
{
if (auto iface = dynamic_cast<interface_type const*>(&targetType))
{
write_c_interface_function_declarations(w, type, *iface);
}
else if (auto genericInst = dynamic_cast<generic_inst const*>(&targetType))
{
// NOTE: Default interfaces can be generic instantiations, hence the check here
write_c_interface_function_declarations(w, type, *genericInst);
}
else
{
auto const& fastAbi = dynamic_cast<fastabi_type const&>(targetType);
write_c_interface_function_declarations(w, type, fastAbi.base());
write_c_interface_function_declarations(w, type, fastAbi.current_interface());
}
}
static void write_c_interface_function_declaration_macros(writer& w, interface_type const& type)
{
for (auto const& func : type.functions)
{
write_c_function_declaration_macro(w, type, func);
}
}
static void write_c_interface_function_declaration_macros(writer& w, generic_inst const& type)
{
for (auto const& func : type.functions)
{
write_c_function_declaration_macro(w, type, func);
}
}
static void write_c_interface_function_declaration_macros(writer& w, metadata_type const& type)
{
if (auto iface = dynamic_cast<interface_type const*>(&type))
{
write_c_interface_function_declaration_macros(w, *iface);
}
else if (auto genericInst = dynamic_cast<generic_inst const*>(&type))
{
// NOTE: Default interfaces can be generic instantiations, hence the check here
write_c_interface_function_declaration_macros(w, *genericInst);
}
else
{
auto const& fastAbi = dynamic_cast<fastabi_type const&>(type);
write_c_interface_function_declaration_macros(w, fastAbi.base());
write_c_interface_function_declaration_macros(w, fastAbi.current_interface());
}
}
static void write_fastabi_c_interface_definition(writer& w, fastabi_type const& type)
{
// We don't forward declare fast ABI interfaces with the remainder of the interfaces, so go ahead and do so now
// since the vtable type needs to refer to it
w.write(R"^-^(typedef struct % %;
)^-^", bind_c_type_name(type), bind_c_type_name(type));
w.write(R"^-^(typedef struct %
{
BEGIN_INTERFACE
)^-^", bind_c_type_name(type, "Vtbl"));
write_c_iinspectable_interface(w, type);
write_c_interface_function_declarations(w, type, type.base());
write_c_interface_function_declarations(w, type, type.current_interface());
w.write(R"^-^(
END_INTERFACE
} %;
interface %
{
CONST_VTBL struct %* lpVtbl;
};
#ifdef COBJMACROS
)^-^", bind_c_type_name(type, "Vtbl"), bind_c_type_name(type), bind_c_type_name(type, "Vtbl"));
write_c_iinspectable_interface_macros(w, type);
write_c_interface_function_declaration_macros(w, type.base());
write_c_interface_function_declaration_macros(w, type.current_interface());
w.write(R"^-^(#endif /* COBJMACROS */
)^-^");
}
void fastabi_type::write_c_definition(writer& w) const
{
write_fastabi_definition(w, *this, &write_fastabi_c_interface_definition);
}
std::size_t generic_inst::push_contract_guards(writer& w) const
{
// Follow MIDLRT's lead and only write contract guards for the generic parameters
std::size_t result = 0;
for (auto param : m_genericParams)
{
result += param->push_contract_guards(w);
}
return result;
}
void generic_inst::write_cpp_forward_declaration(writer& w) const
{
if (!w.begin_declaration(m_mangledName))
{
return;
}
// First make sure that any generic requried interface/function argument/return types are declared
for (auto dep : dependencies)
{
dep->write_cpp_forward_declaration(w);
}
// Also need to make sure that all generic parameters are declared
for (auto param : m_genericParams)
{
param->write_cpp_forward_declaration(w);
}
auto contractDepth = push_contract_guards(w);
w.write('\n');
w.write(R"^-^(#ifndef DEF_%_USE
#define DEF_%_USE
#if !defined(RO_NO_TEMPLATE_NAME)
)^-^", m_mangledName, m_mangledName);
w.push_inline_namespace(clr_abi_namespace());
auto const cppName = generic_type_abi_name();
auto write_cpp_name = [&](writer& w)
{
w.write(cppName);
w.write('<');
std::string_view prefix;
for (auto param : m_genericParams)
{
w.write("%", prefix);
param->write_cpp_generic_param_logical_type(w);
prefix = ", "sv;
}
w.write('>');
};
w.write(R"^-^(template <>
struct __declspec(uuid("%"))
% : %_impl<)^-^", bind_uuid(*this), write_cpp_name, cppName);
std::string_view prefix;
for (auto param : m_genericParams)
{
w.write("%", prefix);
param->write_cpp_generic_param_abi_type(w);
prefix = ", "sv;
}
w.write(R"^-^(>
{
static const wchar_t* z_get_rc_name_impl()
{
return L"%";
}
};
// Define a typedef for the parameterized interface specialization's mangled name.
// This allows code which uses the mangled name for the parameterized interface to access the
// correct parameterized interface specialization.
typedef % %_t;
)^-^", m_clrFullName, write_cpp_name, m_mangledName);
if (w.config().ns_prefix_state == ns_prefix::optional)
{
w.write(R"^-^(#if defined(MIDL_NS_PREFIX)
#define % ABI::@::%_t
#else
#define % @::%_t
#endif // MIDL_NS_PREFIX
)^-^", m_mangledName, clr_abi_namespace(), m_mangledName, m_mangledName, clr_abi_namespace(), m_mangledName);
}
else
{
auto nsPrefix = (w.config().ns_prefix_state == ns_prefix::always) ? "ABI::"sv : "";
w.write(R"^-^(#define % %@::%_t
)^-^", m_mangledName, nsPrefix, clr_abi_namespace(), m_mangledName);
}
w.pop_inline_namespace();
w.write(R"^-^(
#endif // !defined(RO_NO_TEMPLATE_NAME)
#endif /* DEF_%_USE */
)^-^", m_mangledName);
w.pop_contract_guards(contractDepth);
w.write('\n');
w.end_declaration(m_mangledName);
}
void generic_inst::write_cpp_generic_param_logical_type(writer& w) const
{
// For generic instantiations, logical name == abi name
write_cpp_generic_param_abi_type(w);
}
void generic_inst::write_cpp_generic_param_abi_type(writer& w) const
{
write_cpp_abi_param(w);
}
void generic_inst::write_cpp_abi_name(writer& w) const
{
w.write(m_mangledName);
}
void generic_inst::write_cpp_abi_param(writer& w) const
{
w.write("%*", m_mangledName);
}
void generic_inst::write_c_forward_declaration(writer& w) const
{
if (!w.begin_declaration(m_mangledName))
{
if (w.should_forward_declare(m_mangledName))
{
w.write("typedef interface % %;\n\n", m_mangledName, m_mangledName);
}
return;
}
// Also need to make sure that all generic parameters are declared
for (auto param : m_genericParams)
{
param->write_c_forward_declaration(w);
}
// First make sure that any generic requried interface/function argument/return types are declared
for (auto dep : dependencies)
{
dep->write_c_forward_declaration(w);
}
auto contractDepth = push_contract_guards(w);
w.write(R"^-^(#if !defined(__%_INTERFACE_DEFINED__)
#define __%_INTERFACE_DEFINED__
typedef interface % %;
// Declare the parameterized interface IID.
EXTERN_C const IID IID_%;
)^-^", m_mangledName, m_mangledName, m_mangledName, m_mangledName, m_mangledName);
write_c_interface_definition(w, *this);
w.write(R"^-^(
#endif // __%_INTERFACE_DEFINED__
)^-^", m_mangledName);
w.pop_contract_guards(contractDepth);
w.write('\n');
w.end_declaration(m_mangledName);
}
void generic_inst::write_c_abi_param(writer& w) const
{
w.write("%*", m_mangledName);
}
element_type const& element_type::from_type(xlang::meta::reader::ElementType type)
{
static element_type const boolean_type{ "Boolean"sv, "bool"sv, "boolean"sv, "boolean"sv, "boolean"sv, "b1"sv };
static element_type const char_type{ "Char16"sv, "wchar_t"sv, "wchar_t"sv, "WCHAR"sv, "wchar__zt"sv, "c2"sv };
static element_type const u1_type{ "UInt8"sv, "::byte"sv, "::byte"sv, "BYTE"sv, "byte"sv, "u1"sv };
static element_type const i2_type{ "Int16"sv, "short"sv, "short"sv, "INT16"sv, "short"sv, "i2"sv };
static element_type const u2_type{ "UInt16"sv, "UINT16"sv, "UINT16"sv, "UINT16"sv, "UINT16"sv, "u2"sv };
static element_type const i4_type{ "Int32"sv, "int"sv, "int"sv, "INT32"sv, "int"sv, "i4"sv };
static element_type const u4_type{ "UInt32"sv, "UINT32"sv, "UINT32"sv, "UINT32"sv, "UINT32"sv, "u4"sv };
static element_type const i8_type{ "Int64"sv, "__int64"sv, "__int64"sv, "INT64"sv, "__z__zint64"sv, "i8"sv };
static element_type const u8_type{ "UInt64"sv, "UINT64"sv, "UINT64"sv, "UINT64"sv, "UINT64"sv, "u8"sv };
static element_type const r4_type{ "Single"sv, "float"sv, "float"sv, "FLOAT"sv, "float"sv, "f4"sv };
static element_type const r8_type{ "Double"sv, "double"sv, "double"sv, "DOUBLE"sv, "double"sv, "f8"sv };
static element_type const string_type{ "String"sv, "HSTRING"sv, "HSTRING"sv, "HSTRING"sv, "HSTRING"sv, "string"sv };
static element_type const object_type{ "Object"sv, "IInspectable*"sv, "IInspectable*"sv, "IInspectable*"sv, "IInspectable"sv, "cinterface(IInspectable)"sv };
switch (type)
{
case ElementType::Boolean: return boolean_type;
case ElementType::Char: return char_type;
case ElementType::U1: return u1_type;
case ElementType::I2: return i2_type;
case ElementType::U2: return u2_type;
case ElementType::I4: return i4_type;
case ElementType::U4: return u4_type;
case ElementType::I8: return i8_type;
case ElementType::U8: return u8_type;
case ElementType::R4: return r4_type;
case ElementType::R8: return r8_type;
case ElementType::String: return string_type;
case ElementType::Object: return object_type;
default: xlang::throw_invalid("Unrecognized ElementType: ", std::to_string(static_cast<int>(type)));
}
}
void element_type::write_cpp_generic_param_logical_type(writer& w) const
{
w.write(m_logicalName);
}
void element_type::write_cpp_generic_param_abi_type(writer& w) const
{
if (m_logicalName != m_abiName)
{
w.write("%<%, %>",
bind_cpp_fully_qualified_type("Windows.Foundation.Internal"sv, "AggregateType"sv),
m_logicalName,
m_abiName);
}
else
{
w.write(m_abiName);
}
}
void element_type::write_cpp_abi_name(writer& w) const
{
w.write(m_cppName);
}
void element_type::write_c_abi_param(writer& w) const
{
w.write(m_cppName);
}
system_type const& system_type::from_name(std::string_view typeName)
{
if (typeName == "Guid"sv)
{
static system_type const guid_type{ "Guid"sv, "GUID"sv, "g16"sv };
return guid_type;
}
XLANG_ASSERT(false);
xlang::throw_invalid("Unknown type '", typeName, "' in System namespace");
}
void system_type::write_cpp_generic_param_logical_type(writer& w) const
{
write_cpp_generic_param_abi_type(w);
}
void system_type::write_cpp_generic_param_abi_type(writer& w) const
{
w.write(m_cppName);
}
void system_type::write_cpp_abi_name(writer& w) const
{
w.write(m_cppName);
}
void system_type::write_c_abi_param(writer& w) const
{
w.write(m_cppName);
}
mapped_type const* mapped_type::from_typedef(xlang::meta::reader::TypeDef const& type)
{
if (type.TypeNamespace() == foundation_namespace)
{
if (type.TypeName() == "HResult"sv)
{
static mapped_type const hresult_type{ type, "HRESULT"sv, "HRESULT"sv, "struct(Windows.Foundation.HResult;i4)"sv };
return &hresult_type;
}
else if (type.TypeName() == "EventRegistrationToken"sv)
{
static mapped_type event_token_type{ type, "EventRegistrationToken"sv, "EventRegistrationToken"sv, "struct(Windows.Foundation.EventRegistrationToken;i8)"sv };
return &event_token_type;
}
else if (type.TypeName() == "AsyncStatus"sv)
{
static mapped_type const async_status_type{ type, "AsyncStatus"sv, "AsyncStatus"sv, "enum(Windows.Foundation.AsyncStatus;i4)"sv };
return &async_status_type;
}
else if (type.TypeName() == "IAsyncInfo"sv)
{
static mapped_type const async_info_type{ type, "IAsyncInfo"sv, "IAsyncInfo"sv, "{00000036-0000-0000-c000-000000000046}"sv };
return &async_info_type;
}
}
return nullptr;
}
void mapped_type::write_cpp_generic_param_logical_type(writer& w) const
{
write_cpp_generic_param_abi_type(w);
}
void mapped_type::write_cpp_generic_param_abi_type(writer& w) const
{
switch (get_category(m_type))
{
case category::enum_type:
w.write ("% ", enum_string(w));
break;
case category::struct_type:
w.write("struct ");
break;
default:
break; // Others don't get prefixes
}
write_cpp_abi_param(w);
}
void mapped_type::write_cpp_abi_name(writer& w) const
{
w.write(m_cppName);
}
void mapped_type::write_cpp_abi_param(writer& w) const
{
// Currently all mapped types are mapped because the underlying type is a C type
write_c_abi_param(w);
}
void mapped_type::write_c_abi_param(writer& w) const
{
w.write(m_cppName);
auto typeCategory = get_category(m_type);
if ((typeCategory == category::delegate_type) ||
(typeCategory == category::interface_type) ||
(typeCategory == category::class_type))
{
w.write('*');
}
}
| 26.96064 | 170 | 0.641981 | [
"object"
] |
435c533d285c7caf820d52407cb8ba6b062bff84 | 15,373 | cc | C++ | DQM/HcalTasks/src/DigiRunSummary.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DQM/HcalTasks/src/DigiRunSummary.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DQM/HcalTasks/src/DigiRunSummary.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "DQM/HcalTasks/interface/DigiRunSummary.h"
namespace hcaldqm {
using namespace constants;
DigiRunSummary::DigiRunSummary(std::string const& name,
std::string const& taskname,
edm::ParameterSet const& ps,
edm::ConsumesCollector& iC)
: DQClient(name, taskname, ps, iC), _booked(false) {
_thresh_unihf = ps.getUntrackedParameter<double>("thresh_unihf", 0.2);
std::vector<uint32_t> vrefDigiSize = ps.getUntrackedParameter<std::vector<uint32_t>>("refDigiSize");
_refDigiSize[HcalBarrel] = vrefDigiSize[0];
_refDigiSize[HcalEndcap] = vrefDigiSize[1];
_refDigiSize[HcalOuter] = vrefDigiSize[2];
_refDigiSize[HcalForward] = vrefDigiSize[3];
}
/* virtual */ void DigiRunSummary::beginRun(edm::Run const& r, edm::EventSetup const& es) {
DQClient::beginRun(r, es);
if (_ptype != fOffline)
return;
// INITIALIZE WHAT NEEDS TO BE INITIALIZE ONLY ONCE!
_ehashmap.initialize(_emap, electronicsmap::fD2EHashMap);
_vhashVME.push_back(
HcalElectronicsId(constants::FIBERCH_MIN, constants::FIBER_VME_MIN, SPIGOT_MIN, CRATE_VME_MIN).rawId());
_vhashuTCA.push_back(HcalElectronicsId(CRATE_uTCA_MIN, SLOT_uTCA_MIN, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_filter_VME.initialize(filter::fFilter, hashfunctions::fElectronics,
_vhashVME); // filter out VME
_filter_uTCA.initialize(filter::fFilter, hashfunctions::fElectronics,
_vhashuTCA); // filter out uTCA
_vhashFEDHF.push_back(HcalElectronicsId(22, SLOT_uTCA_MIN, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_vhashFEDHF.push_back(HcalElectronicsId(29, SLOT_uTCA_MIN, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_vhashFEDHF.push_back(HcalElectronicsId(32, SLOT_uTCA_MIN, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_vhashFEDHF.push_back(HcalElectronicsId(22, SLOT_uTCA_MIN + 6, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_vhashFEDHF.push_back(HcalElectronicsId(29, SLOT_uTCA_MIN + 6, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_vhashFEDHF.push_back(HcalElectronicsId(32, SLOT_uTCA_MIN + 6, FIBER_uTCA_MIN1, FIBERCH_MIN, false).rawId());
_filter_FEDHF.initialize(filter::fPreserver, hashfunctions::fFED,
_vhashFEDHF); // preserve only HF FEDs
_xDead.initialize(hashfunctions::fFED);
_xDigiSize.initialize(hashfunctions::fFED);
_xUni.initialize(hashfunctions::fFED);
_xUniHF.initialize(hashfunctions::fFEDSlot);
_xDead.book(_emap);
_xDigiSize.book(_emap);
_xUniHF.book(_emap);
_xUni.book(_emap, _filter_FEDHF);
_xNChs.initialize(hashfunctions::fFED);
_xNChsNominal.initialize(hashfunctions::fFED);
_xNChs.book(_emap);
_xNChsNominal.book(_emap);
_cOccupancy_depth.initialize(_name,
"Occupancy",
hashfunctions::fdepth,
new quantity::DetectorQuantity(quantity::fieta),
new quantity::DetectorQuantity(quantity::fiphi),
new quantity::ValueQuantity(quantity::fN),
0);
// GET THE NOMINAL NUMBER OF CHANNELS PER FED
std::vector<HcalGenericDetId> gids = _emap->allPrecisionId();
for (std::vector<HcalGenericDetId>::const_iterator it = gids.begin(); it != gids.end(); ++it) {
if (!it->isHcalDetId())
continue;
HcalDetId did(it->rawId());
HcalElectronicsId eid = HcalElectronicsId(_ehashmap.lookup(did));
_xNChsNominal.get(eid)++;
}
}
/*
* END LUMI. EVALUATE LUMI BASED FLAGS
*/
/* virtual */ void DigiRunSummary::endLuminosityBlock(DQMStore::IBooker& ib,
DQMStore::IGetter& ig,
edm::LuminosityBlock const& lb,
edm::EventSetup const& es) {
DQClient::endLuminosityBlock(ib, ig, lb, es);
if (_ptype != fOffline)
return;
LSSummary lssum;
lssum._LS = _currentLS;
_xDigiSize.reset();
_xNChs.reset();
// INITIALIZE LUMI BASED HISTOGRAMS
Container2D cDigiSize_Crate, cOccupancy_depth;
cDigiSize_Crate.initialize(_taskname,
"DigiSize",
hashfunctions::fCrate,
new quantity::ValueQuantity(quantity::fDigiSize),
new quantity::ValueQuantity(quantity::fN),
0);
cOccupancy_depth.initialize(_taskname,
"Occupancy",
hashfunctions::fdepth,
new quantity::DetectorQuantity(quantity::fieta),
new quantity::DetectorQuantity(quantity::fiphi),
new quantity::ValueQuantity(quantity::fN),
0);
// LOAD LUMI BASED HISTOGRAMS
cOccupancy_depth.load(ig, _emap, _subsystem);
cDigiSize_Crate.load(ig, _emap, _subsystem);
MonitorElement* meNumEvents = ig.get(_subsystem + "/RunInfo/NumberOfEvents");
int numEvents = meNumEvents->getBinContent(1);
bool unknownIdsPresent = ig.get(_subsystem + "/" + _taskname + "/UnknownIds")->getBinContent(1) > 0;
// book the Numer of Events - set axis extendable
if (!_booked) {
ib.setCurrentFolder(_subsystem + "/" + _taskname);
_meNumEvents = ib.book1DD("NumberOfEvents", "NumberOfEvents", 1000, 1, 1001); // 1000 to start with
_meNumEvents->getTH1()->SetCanExtend(TH1::kXaxis);
_cOccupancy_depth.book(ib, _emap, _subsystem);
_booked = true;
}
_meNumEvents->setBinContent(_currentLS, numEvents);
// ANALYZE THIS LS for LS BASED FLAGS
std::vector<HcalGenericDetId> gids = _emap->allPrecisionId();
for (std::vector<HcalGenericDetId>::const_iterator it = gids.begin(); it != gids.end(); ++it) {
if (!it->isHcalDetId())
continue;
HcalDetId did = HcalDetId(it->rawId());
HcalElectronicsId eid = HcalElectronicsId(_ehashmap.lookup(did));
cOccupancy_depth.getBinContent(did) > 0 ? _xNChs.get(eid)++ : _xNChs.get(eid) += 0;
_cOccupancy_depth.fill(did, cOccupancy_depth.getBinContent(did));
// digi size
cDigiSize_Crate.getMean(eid) != _refDigiSize[did.subdet()] ? _xDigiSize.get(eid)++ : _xDigiSize.get(eid) += 0;
cDigiSize_Crate.getRMS(eid) != 0 ? _xDigiSize.get(eid)++ : _xDigiSize.get(eid) += 0;
}
// GENERATE SUMMARY AND STORE IT
std::vector<flag::Flag> vtmpflags;
vtmpflags.resize(nLSFlags);
vtmpflags[fDigiSize] = flag::Flag("DigiSize");
vtmpflags[fNChsHF] = flag::Flag("NChsHF");
vtmpflags[fUnknownIds] = flag::Flag("UnknownIds");
vtmpflags[fLED] = flag::Flag("LEDMisfire");
for (std::vector<uint32_t>::const_iterator it = _vhashCrates.begin(); it != _vhashCrates.end(); ++it) {
HcalElectronicsId eid(*it);
HcalDetId did = HcalDetId(_emap->lookup(eid));
// reset all the tmp flags to fNA
// MUST DO IT NOW! AS NCDAQ MIGHT OVERWRITE IT!
for (std::vector<flag::Flag>::iterator ft = vtmpflags.begin(); ft != vtmpflags.end(); ++ft)
ft->reset();
if (_xDigiSize.get(eid) > 0)
vtmpflags[fDigiSize]._state = flag::fBAD;
else
vtmpflags[fDigiSize]._state = flag::fGOOD;
if (did.subdet() == HcalForward) {
if (_xNChs.get(eid) != _xNChsNominal.get(eid))
vtmpflags[fNChsHF]._state = flag::fBAD;
else
vtmpflags[fNChsHF]._state = flag::fGOOD;
} else {
vtmpflags[fNChsHF]._state = flag::fNA;
}
if (unknownIdsPresent)
vtmpflags[fUnknownIds]._state = flag::fBAD;
else
vtmpflags[fUnknownIds]._state = flag::fGOOD;
if ((did.subdet() == HcalBarrel) || (did.subdet() == HcalBarrel) || (did.subdet() == HcalBarrel) ||
(did.subdet() == HcalBarrel)) {
std::string ledHistName = _subsystem + "/" + _taskname + "/LED_CUCountvsLS/Subdet/";
if (did.subdet() == HcalBarrel) {
ledHistName += "HB";
} else if (did.subdet() == HcalEndcap) {
ledHistName += "HE";
} else if (did.subdet() == HcalOuter) {
ledHistName += "HO";
} else if (did.subdet() == HcalForward) {
ledHistName += "HF";
}
MonitorElement* ledHist = ig.get(ledHistName);
if (ledHist) {
bool ledSignalPresent = (ledHist->getEntries() > 0);
if (ledSignalPresent)
vtmpflags[fLED]._state = flag::fBAD;
else
vtmpflags[fLED]._state = flag::fGOOD;
} else {
vtmpflags[fLED]._state = flag::fNA;
}
} else {
vtmpflags[fLED]._state = flag::fNA;
}
// push all the flags for this crate
lssum._vflags.push_back(vtmpflags);
}
// push all the flags for all FEDs for this LS
_vflagsLS.push_back(lssum);
cDigiSize_Crate.reset();
cOccupancy_depth.reset();
}
/*
* End Job
*/
/* virtual */ std::vector<flag::Flag> DigiRunSummary::endJob(DQMStore::IBooker& ib, DQMStore::IGetter& ig) {
if (_ptype != fOffline)
return std::vector<flag::Flag>();
_xDead.reset();
_xUniHF.reset();
_xUni.reset();
// PREPARE LS AND RUN BASED FLAGS TO USE IT FOR BOOKING
std::vector<flag::Flag> vflagsPerLS;
std::vector<flag::Flag> vflagsPerRun;
vflagsPerLS.resize(nLSFlags);
vflagsPerRun.resize(nDigiFlag - nLSFlags + 1);
vflagsPerLS[fDigiSize] = flag::Flag("DigiSize");
vflagsPerLS[fNChsHF] = flag::Flag("NChsHF");
vflagsPerLS[fUnknownIds] = flag::Flag("UnknownIds");
vflagsPerLS[fLED] = flag::Flag("LEDMisfire");
vflagsPerRun[fDigiSize] = flag::Flag("DigiSize");
vflagsPerRun[fNChsHF] = flag::Flag("NChsHF");
vflagsPerRun[fUniHF - nLSFlags + 1] = flag::Flag("UniSlotHF");
vflagsPerRun[fDead - nLSFlags + 1] = flag::Flag("Dead");
// INITIALIZE SUMMARY CONTAINERS
ContainerSingle2D cSummaryvsLS;
Container2D cSummaryvsLS_Crate;
cSummaryvsLS.initialize(_name,
"SummaryvsLS",
new quantity::LumiSection(_maxProcessedLS),
new quantity::CrateQuantity(_emap),
new quantity::ValueQuantity(quantity::fState),
0);
cSummaryvsLS.book(ib, _subsystem);
cSummaryvsLS_Crate.initialize(_name,
"SummaryvsLS",
hashfunctions::fCrate,
new quantity::LumiSection(_maxProcessedLS),
new quantity::FlagQuantity(vflagsPerLS),
new quantity::ValueQuantity(quantity::fState),
0);
cSummaryvsLS_Crate.book(ib, _emap, _subsystem);
// INITIALIZE CONTAINERS WE NEED TO LOAD or BOOK
Container2D cOccupancyCut_depth;
Container2D cDead_depth, cDead_Crate;
cOccupancyCut_depth.initialize(_taskname,
"OccupancyCut",
hashfunctions::fdepth,
new quantity::DetectorQuantity(quantity::fieta),
new quantity::DetectorQuantity(quantity::fiphi),
new quantity::ValueQuantity(quantity::fN),
0);
cDead_depth.initialize(_name,
"Dead",
hashfunctions::fdepth,
new quantity::DetectorQuantity(quantity::fieta),
new quantity::DetectorQuantity(quantity::fiphi),
new quantity::ValueQuantity(quantity::fN),
0);
cDead_Crate.initialize(_name,
"Dead",
hashfunctions::fCrate,
new quantity::ElectronicsQuantity(quantity::fSpigot),
new quantity::ElectronicsQuantity(quantity::fFiberVMEFiberCh),
new quantity::ValueQuantity(quantity::fN),
0);
// LOAD
cOccupancyCut_depth.load(ig, _emap, _subsystem);
cDead_depth.book(ib, _emap, _subsystem);
cDead_Crate.book(ib, _emap, _subsystem);
// ANALYZE RUN BASED QUANTITIES
std::vector<HcalGenericDetId> gids = _emap->allPrecisionId();
for (std::vector<HcalGenericDetId>::const_iterator it = gids.begin(); it != gids.end(); ++it) {
if (!it->isHcalDetId())
continue;
HcalDetId did = HcalDetId(it->rawId());
HcalElectronicsId eid = HcalElectronicsId(_ehashmap.lookup(did));
if (_cOccupancy_depth.getBinContent(did) < 1) {
_xDead.get(eid)++;
cDead_depth.fill(did);
cDead_Crate.fill(eid);
}
if (did.subdet() == HcalForward)
_xUniHF.get(eid) += cOccupancyCut_depth.getBinContent(did);
}
// ANALYZE FOR HF SLOT UNIFORMITY
for (uintCompactMap::const_iterator it = _xUniHF.begin(); it != _xUniHF.end(); ++it) {
uint32_t hash1 = it->first;
HcalElectronicsId eid1(hash1);
double x1 = it->second;
for (uintCompactMap::const_iterator jt = _xUniHF.begin(); jt != _xUniHF.end(); ++jt) {
if (jt == it)
continue;
double x2 = jt->second;
if (x2 == 0)
continue;
if (x1 / x2 < _thresh_unihf)
_xUni.get(eid1)++;
}
}
/*
* Iterate over each crate
* Iterate over each LS Summary
* Iterate over all flags
* set...
*/
// iterate over all crates
std::vector<flag::Flag> sumflags;
int icrate = 0;
for (auto& it_crate : _vhashCrates) {
flag::Flag fSumRun("DIGI"); // summary flag for this FED
flag::Flag ffDead("Dead");
flag::Flag ffUniSlotHF("UniSlotHF");
HcalElectronicsId eid(it_crate);
HcalDetId did = HcalDetId(_emap->lookup(eid));
// ITERATE OVER EACH LS
for (std::vector<LSSummary>::const_iterator itls = _vflagsLS.begin(); itls != _vflagsLS.end(); ++itls) {
int iflag = 0;
flag::Flag fSumLS("DIGI");
for (std::vector<flag::Flag>::const_iterator ft = itls->_vflags[icrate].begin();
ft != itls->_vflags[icrate].end();
++ft) {
cSummaryvsLS_Crate.setBinContent(eid, itls->_LS, int(iflag), ft->_state);
fSumLS += (*ft);
iflag++;
}
cSummaryvsLS.setBinContent(eid, itls->_LS, fSumLS._state);
fSumRun += fSumLS;
}
// EVALUATE RUN BASED FLAGS
if (_xDead.get(eid) > 0)
ffDead._state = flag::fBAD;
else
ffDead._state = flag::fGOOD;
if (did.subdet() == HcalForward) {
if (_xUni.get(eid) > 0)
ffUniSlotHF._state = flag::fBAD;
else
ffUniSlotHF._state = flag::fGOOD;
}
fSumRun += ffDead + ffUniSlotHF;
// push the summary flag for this FED for the Whole Run
sumflags.push_back(fSumRun);
// increment fed
icrate++;
}
return sumflags;
}
} // namespace hcaldqm
| 40.669312 | 120 | 0.588304 | [
"vector"
] |
435f1fce058d465b216075930e1d765bac6a95ba | 477 | cc | C++ | project_templates/static_library/tests/test.cc | manavrion/cpp_project_template | 0874868c48d2810072bfeda54648bed2e43f05be | [
"MIT"
] | 2 | 2020-02-11T21:14:12.000Z | 2020-04-27T15:29:43.000Z | project_templates/static_library/tests/test.cc | manavrion/template_repository | 0874868c48d2810072bfeda54648bed2e43f05be | [
"MIT"
] | null | null | null | project_templates/static_library/tests/test.cc | manavrion/template_repository | 0874868c48d2810072bfeda54648bed2e43f05be | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "manavrion/static_library_sample.h"
using static_library_sample::add;
using static_library_sample::add_first3;
using static_library_sample::mul;
TEST(StaticLibrarySampleTest, Add) {
EXPECT_EQ(add(1, 2), 3);
EXPECT_EQ(add(2, 2), 4);
}
TEST(StaticLibrarySampleTest, Mul) {
EXPECT_EQ(mul(1, 2), 2);
EXPECT_EQ(mul(2, 2), 4);
}
TEST(StaticLibrarySampleTest, AddFirst3) {
EXPECT_EQ(add_first3(std::vector<int64_t>{1, 1, 1, 5}), 3);
}
| 21.681818 | 61 | 0.725367 | [
"vector"
] |
435f76f2b02d82951eb3ff66e597ef3730aee250 | 1,739 | cpp | C++ | 动态规划/状压DP/acwing_291.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | 3 | 2020-11-16T08:58:30.000Z | 2020-11-16T08:58:33.000Z | 动态规划/状压DP/acwing_291.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | 动态规划/状压DP/acwing_291.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
/*
核心思想: 只考虑横放的所有情况,然后判断剩下的位置能否被竖着放的填满
f[][]也只表示了横放的情况,f[0][0]就是所有都被竖着的填满
f[i][j]: 前i-1列已经摆好,且第i-1列伸出到第i列的状态是j的所有方案数
f[i-1][k] -> f[i][j] 转移,表示i-1列伸出到第i列后状态依然合法,然后加上方案数即可
*/
const int N = 12, M = 1 << N;
int n, m;
ll f[N][M];
vector<int> state[M];
bool st[M];
int main() {
while (cin >> n >> m, n || m) {
for (int i = 0; i < 1 << n; i++) { //每一列用n位二进制能组成的所有状态的合法性,也就是竖着连续的1的个数的奇偶性
int cnt = 0;
bool is_valid = true; //0表示当前列的该位置没有被之前的一列插进来,是空的,1代表已经被占用
for (int j = 0; j < n; j++) //状态i的所有连续0段, 0的个数,是否是偶数
if (i >> j & 1) { //遇到一个1,之前的cnt是否是偶数
if (cnt & 1) {
is_valid = false;
break;
}
cnt = 0;
}
else cnt ++;
if (cnt & 1) is_valid = false; //最后一段状态,也就是最下面的连续0段是否合法
st[i] = is_valid;
}
for (int i = 0; i < 1 << n; i++) { //枚举所有的列的二进制状态对,理解为第i列向后面一列伸出,此时的局面,预处理可达每个状态的所有合法状态
state[i].clear(); //多测试样例 ,vector 要清空
for (int j = 0; j < 1 << n; j++)
if ((i & j) == 0 && st[i | j]) //i&j==0该列的同一行不能有交集放置, i|j是所有是1的位置被填,剩余0此时的状态依然合法
state[i].push_back(j);
}
memset(f, 0, sizeof f);
f[0][0] = 1; //只放竖着的
for (int i = 1; i <= m; i++) //枚举所有的列来尝试填补残局
for (int j = 0; j < 1 << n; j++) // 枚举所有列的状态
for (auto k : state[j]) //每个能到状态j的合法状态,也就是第i列加上i-1列的某些状态,这些状态从i-1伸出到i列后当前局面依然合法。 已经在上面与处理过了。
f[i][j] += f[i - 1][k];
cout << f[m][0] << endl; //最后一列,且所有位置都被填满的总方案数
}
return 0;
} | 31.618182 | 108 | 0.474411 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.