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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c85b65a2b9311fcbade6847add3c70884fd2e289 | 3,286 | cc | C++ | third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.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 | third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.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 | third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2016 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 "third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h"
namespace blink {
// The root of the transform tree. The root transform node references the root
// scroll node.
const TransformPaintPropertyNode& TransformPaintPropertyNode::Root() {
DEFINE_STATIC_REF(
TransformPaintPropertyNode, root,
base::AdoptRef(new TransformPaintPropertyNode(
nullptr,
State{
FloatSize(), &ScrollPaintPropertyNode::Root(),
State::Flags{false /* flattens_inherited_transform */,
false /* in_subtree_of_page_scale */}})));
return *root;
}
bool TransformPaintPropertyNodeOrAlias::Changed(
PaintPropertyChangeType change,
const TransformPaintPropertyNodeOrAlias& relative_to_node) const {
for (const auto* node = this; node; node = node->Parent()) {
if (node == &relative_to_node)
return false;
if (node->NodeChanged() >= change)
return true;
}
// |this| is not a descendant of |relative_to_node|. We have seen no changed
// flag from |this| to the root. Now check |relative_to_node| to the root.
return relative_to_node.Changed(change, TransformPaintPropertyNode::Root());
}
const TransformPaintPropertyNode&
TransformPaintPropertyNode::NearestScrollTranslationNode() const {
const auto* transform = this;
while (!transform->ScrollNode()) {
transform = transform->UnaliasedParent();
// The transform should never be null because the root transform has an
// associated scroll node (see: TransformPaintPropertyNode::Root()).
DCHECK(transform);
}
return *transform;
}
std::unique_ptr<JSONObject> TransformPaintPropertyNode::ToJSON() const {
auto json = ToJSONBase();
if (IsIdentityOr2DTranslation()) {
if (!Translation2D().IsZero())
json->SetString("translation2d", Translation2D().ToString());
} else {
json->SetString("matrix", Matrix().ToString());
json->SetString("origin", Origin().ToString());
}
if (!state_.flags.flattens_inherited_transform)
json->SetBoolean("flattensInheritedTransform", false);
if (!state_.flags.in_subtree_of_page_scale)
json->SetBoolean("in_subtree_of_page_scale", false);
if (state_.backface_visibility != BackfaceVisibility::kInherited) {
json->SetString("backface",
state_.backface_visibility == BackfaceVisibility::kVisible
? "visible"
: "hidden");
}
if (state_.rendering_context_id) {
json->SetString("renderingContextId",
String::Format("%x", state_.rendering_context_id));
}
if (state_.direct_compositing_reasons != CompositingReason::kNone) {
json->SetString(
"directCompositingReasons",
CompositingReason::ToString(state_.direct_compositing_reasons));
}
if (state_.compositor_element_id) {
json->SetString("compositorElementId",
state_.compositor_element_id.ToString().c_str());
}
if (state_.scroll)
json->SetString("scroll", String::Format("%p", state_.scroll.get()));
return json;
}
} // namespace blink
| 37.340909 | 93 | 0.692635 | [
"transform"
] |
c85bc36ffbb2d27e8c9d2d3739a18aabb4fe581c | 7,345 | cpp | C++ | camera control/src/main.cpp | vugolfcart/zed-examples | eecbac1322725557056bc1344219d0a47113b8d0 | [
"MIT"
] | null | null | null | camera control/src/main.cpp | vugolfcart/zed-examples | eecbac1322725557056bc1344219d0a47113b8d0 | [
"MIT"
] | null | null | null | camera control/src/main.cpp | vugolfcart/zed-examples | eecbac1322725557056bc1344219d0a47113b8d0 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2018, STEREOLABS.
//
// All rights reserved.
//
// 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.
//
///////////////////////////////////////////////////////////////////////////
/********************************************************************************
** This sample demonstrates how to grab images and change the camera settings **
** with the ZED SDK **
********************************************************************************/
// Standard includes
#include <stdio.h>
#include <string.h>
// ZED include
#include <sl/Camera.hpp>
// OpenCV include (for display)
#include <opencv2/opencv.hpp>
// Using std and sl namespaces
using namespace std;
using namespace sl;
// Sample functions
void updateCameraSettings(char key, sl::Camera &zed);
void switchCameraSettings();
void printHelp();
// Sample variables
CAMERA_SETTINGS camera_settings_ = CAMERA_SETTINGS_BRIGHTNESS;
string str_camera_settings = "BRIGHTNESS";
int step_camera_setting = 1;
int main(int argc, char **argv) {
// Create a ZED Camera object
Camera zed;
// Open the camera
ERROR_CODE err = zed.open();
if (err != SUCCESS) {
cout << toString(err) << endl;
zed.close();
return 1; // Quit if an error occurred
}
// Print help in console
printHelp();
// Print camera information
printf("ZED Model : %s\n", toString(zed.getCameraInformation().camera_model).c_str());
printf("ZED Serial Number : %d\n", zed.getCameraInformation().serial_number);
printf("ZED Firmware : %d\n", zed.getCameraInformation().firmware_version);
printf("ZED Camera Resolution : %dx%d\n", (int) zed.getResolution().width, (int) zed.getResolution().height);
printf("ZED Camera FPS : %d\n", (int) zed.getCameraFPS());
// Create a Mat to store images
Mat zed_image;
// Capture new images until 'q' is pressed
char key = ' ';
while (key != 'q') {
// Check that grab() is successful
if (zed.grab() == SUCCESS) {
// Retrieve left image
zed.retrieveImage(zed_image, VIEW_LEFT);
// Display image with OpenCV
cv::imshow("VIEW", cv::Mat((int) zed_image.getHeight(), (int) zed_image.getWidth(), CV_8UC4, zed_image.getPtr<sl::uchar1>(sl::MEM_CPU)));
key = cv::waitKey(5);
// Change camera settings with keyboard
updateCameraSettings(key, zed);
} else
key = cv::waitKey(5);
}
// Exit
zed.close();
return EXIT_SUCCESS;
}
/**
This function updates camera settings
**/
void updateCameraSettings(char key, sl::Camera &zed) {
int current_value;
// Keyboard shortcuts
switch (key) {
// Switch to the next camera parameter
case 's':
switchCameraSettings();
break;
// Increase camera settings value ('+' key)
case '+':
current_value = zed.getCameraSettings(camera_settings_);
zed.setCameraSettings(camera_settings_, current_value + step_camera_setting);
std::cout << str_camera_settings << ": " << current_value + step_camera_setting << std::endl;
break;
// Decrease camera settings value ('-' key)
case '-':
current_value = zed.getCameraSettings(camera_settings_);
if (current_value >= 1) {
zed.setCameraSettings(camera_settings_, current_value - step_camera_setting);
std::cout << str_camera_settings << ": " << current_value - step_camera_setting << std::endl;
}
break;
// Reset to default parameters
case 'r':
std::cout << "Reset all settings to default" << std::endl;
zed.setCameraSettings(sl::CAMERA_SETTINGS_BRIGHTNESS, -1, true);
zed.setCameraSettings(sl::CAMERA_SETTINGS_CONTRAST, -1, true);
zed.setCameraSettings(sl::CAMERA_SETTINGS_HUE, -1, true);
zed.setCameraSettings(sl::CAMERA_SETTINGS_SATURATION, -1, true);
zed.setCameraSettings(sl::CAMERA_SETTINGS_GAIN, -1, true);
zed.setCameraSettings(sl::CAMERA_SETTINGS_EXPOSURE, -1, true);
zed.setCameraSettings(sl::CAMERA_SETTINGS_WHITEBALANCE, -1, true);
break;
}
}
/**
This function toggles between camera settings
**/
void switchCameraSettings() {
step_camera_setting = 1;
switch (camera_settings_) {
case CAMERA_SETTINGS_BRIGHTNESS:
camera_settings_ = CAMERA_SETTINGS_CONTRAST;
str_camera_settings = "Contrast";
std::cout << "Camera Settings: CONTRAST" << std::endl;
break;
case CAMERA_SETTINGS_CONTRAST:
camera_settings_ = CAMERA_SETTINGS_HUE;
str_camera_settings = "Hue";
std::cout << "Camera Settings: HUE" << std::endl;
break;
case CAMERA_SETTINGS_HUE:
camera_settings_ = CAMERA_SETTINGS_SATURATION;
str_camera_settings = "Saturation";
std::cout << "Camera Settings: SATURATION" << std::endl;
break;
case CAMERA_SETTINGS_SATURATION:
camera_settings_ = CAMERA_SETTINGS_GAIN;
str_camera_settings = "Gain";
std::cout << "Camera Settings: GAIN" << std::endl;
break;
case CAMERA_SETTINGS_GAIN:
camera_settings_ = CAMERA_SETTINGS_EXPOSURE;
str_camera_settings = "Exposure";
std::cout << "Camera Settings: EXPOSURE" << std::endl;
break;
case CAMERA_SETTINGS_EXPOSURE:
camera_settings_ = CAMERA_SETTINGS_WHITEBALANCE;
str_camera_settings = "White Balance";
step_camera_setting = 100;
std::cout << "Camera Settings: WHITE BALANCE" << std::endl;
break;
case CAMERA_SETTINGS_WHITEBALANCE:
camera_settings_ = CAMERA_SETTINGS_BRIGHTNESS;
str_camera_settings = "Brightness";
std::cout << "Camera Settings: BRIGHTNESS" << std::endl;
break;
}
}
/**
This function displays help
**/
void printHelp() {
cout << endl;
cout << endl;
cout << "Camera controls hotkeys: " << endl;
cout << " Increase camera settings value: '+'" << endl;
cout << " Decrease camera settings value: '-'" << endl;
cout << " Toggle camera settings: 's'" << endl;
cout << " Reset all parameters: 'r'" << endl;
cout << endl;
cout << "Exit : 'q'" << endl;
cout << endl;
cout << endl;
cout << endl;
}
| 34.162791 | 149 | 0.603131 | [
"object",
"model"
] |
c85c2b84f1e16fc89da163f0138344cb478f5dce | 13,123 | cpp | C++ | tools/PocoDoc/src/PocoDoc.cpp | Maximilian995/Macchina | b22cb4b87ffed86b9266889ad6bd44388792fbbe | [
"Apache-2.0"
] | 1 | 2021-12-04T04:07:20.000Z | 2021-12-04T04:07:20.000Z | tools/PocoDoc/src/PocoDoc.cpp | bas524/cmake.macchina.io | 22a21d78f8075fd145b788b41a23603591e91c9f | [
"Apache-2.0"
] | null | null | null | tools/PocoDoc/src/PocoDoc.cpp | bas524/cmake.macchina.io | 22a21d78f8075fd145b788b41a23603591e91c9f | [
"Apache-2.0"
] | 1 | 2022-01-11T02:51:18.000Z | 2022-01-11T02:51:18.000Z | //
// PocoDoc.cpp
//
// Copyright (c) 2005-2014, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/StringTokenizer.h"
#include "Poco/Glob.h"
#include "Poco/Path.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/Process.h"
#include "Poco/Pipe.h"
#include "Poco/PipeStream.h"
#include "Poco/Environment.h"
#include "Poco/NumberFormatter.h"
#include "Poco/Exception.h"
#include "Poco/Stopwatch.h"
#include "Poco/DateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/Timespan.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/Util/Application.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Util/AbstractConfiguration.h"
#include "Poco/CppParser/Parser.h"
#include "Poco/CppParser/NameSpace.h"
#include "Poco/CppParser/Struct.h"
#include "Poco/CppParser/Utility.h"
#include "DocWriter.h"
#include <set>
#include <utility>
#include <memory>
#include <fstream>
#include <sstream>
#include <iostream>
#include <clocale>
using Poco::StringTokenizer;
using Poco::Glob;
using Poco::Path;
using Poco::File;
using Poco::DirectoryIterator;
using Poco::Process;
using Poco::ProcessHandle;
using Poco::Environment;
using Poco::NumberFormatter;
using Poco::Exception;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::OptionCallback;
using Poco::Util::HelpFormatter;
using Poco::Util::AbstractConfiguration;
class Preprocessor
{
public:
Preprocessor(const ProcessHandle& proc, std::istream* pStream):
_proc(proc),
_pStream(pStream)
{
}
Preprocessor(const ProcessHandle& proc, std::istream* pStream, const std::string& file):
_proc(proc),
_pStream(pStream),
_file(file)
{
}
std::istream& stream()
{
return *_pStream;
}
~Preprocessor()
{
int c = _pStream->get();
while (c != -1) c = _pStream->get();
delete _pStream;
_proc.wait();
if (!_file.empty())
{
try
{
File f(_file);
f.remove();
}
catch (Exception&)
{
}
}
}
private:
ProcessHandle _proc;
std::istream* _pStream;
std::string _file;
};
class PocoDocApp: public Application
{
public:
PocoDocApp():
_helpRequested(false),
_writeEclipseTOC(false)
{
std::setlocale(LC_ALL, "");
}
~PocoDocApp()
{
}
protected:
void initialize(Application& self)
{
loadConfiguration(); // load default configuration files, if present
Application::initialize(self);
}
void uninitialize()
{
Application::uninitialize();
}
void reinitialize(Application& self)
{
Application::reinitialize(self);
}
void defineOptions(OptionSet& options)
{
Application::defineOptions(options);
options.addOption(
Option("help", "h", "Display help information on command line arguments.")
.required(false)
.repeatable(false)
.callback(OptionCallback<PocoDocApp>(this, &PocoDocApp::handleHelp)));
options.addOption(
Option("config", "f", "Load configuration data from a file.")
.required(false)
.repeatable(true)
.argument("file")
.callback(OptionCallback<PocoDocApp>(this, &PocoDocApp::handleConfig)));
options.addOption(
Option("define", "D", "Define a configuration property.")
.required(false)
.repeatable(true)
.argument("name=value")
.callback(OptionCallback<PocoDocApp>(this, &PocoDocApp::handleDefine)));
options.addOption(
Option("eclipse", "e", "Write Eclipse TOC file.")
.required(false)
.repeatable(false)
.callback(OptionCallback<PocoDocApp>(this, &PocoDocApp::handleEclipse)));
}
void handleHelp(const std::string& name, const std::string& value)
{
_helpRequested = true;
displayHelp();
stopOptionsProcessing();
}
void handleDefine(const std::string& name, const std::string& value)
{
defineProperty(value);
}
void defineProperty(const std::string& def)
{
std::string name;
std::string value;
std::string::size_type pos = def.find('=');
if (pos != std::string::npos)
{
name.assign(def, 0, pos);
value.assign(def, pos + 1, def.length() - pos);
}
else name = def;
config().setString(name, value);
}
void handleEclipse(const std::string& name, const std::string& value)
{
_writeEclipseTOC = true;
}
void handleConfig(const std::string& name, const std::string& value)
{
loadConfiguration(value, -200);
}
void displayHelp()
{
HelpFormatter helpFormatter(options());
helpFormatter.setCommand(commandName());
helpFormatter.setUsage("OPTIONS");
helpFormatter.setHeader("POCO C++ Libraries documentation builder.");
helpFormatter.format(std::cout);
}
void buildFileList(std::set<std::string>& files)
{
std::set<std::string> temp;
std::string includes = config().getString("PocoDoc.files.include");
std::string excludes = config().getString("PocoDoc.files.exclude", "");
StringTokenizer incTokenizer(includes, ",\n", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
for (StringTokenizer::Iterator it = incTokenizer.begin(); it != incTokenizer.end(); ++it)
{
Glob::glob(*it, temp);
}
StringTokenizer excTokenizer(excludes, ",\n", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
for (std::set<std::string>::const_iterator it = temp.begin(); it != temp.end(); ++it)
{
Path p(*it);
bool include = true;
for (StringTokenizer::Iterator itg = excTokenizer.begin(); itg != excTokenizer.end(); ++itg)
{
Glob glob(*itg);
if (glob.match(p.getFileName()))
include = false;
}
if (include)
files.insert(*it);
}
}
Preprocessor* preprocess(const std::string& file)
{
Path pp(file);
pp.setExtension("i");
std::string comp = "PocoDoc.compiler";
std::string platformComp(comp);
if (Environment::isWindows())
platformComp += ".windows";
else
platformComp += ".unix";
std::string exec = config().getString(platformComp + ".exec", config().getString(comp + ".exec", ""));
std::string opts = config().getString(platformComp + ".options", config().getString(comp + ".options", ""));
std::string path = config().getString(platformComp + ".path", config().getString(comp + ".path", ""));
bool usePipe = config().getBool(platformComp + ".usePipe", config().getBool(comp + ".usePipe", false));
std::string popts;
for (std::string::const_iterator it = opts.begin(); it != opts.end(); ++it)
{
if (*it == '%')
popts += pp.getBaseName();
else
popts += *it;
}
StringTokenizer tokenizer(popts, ",\n", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
std::vector<std::string> args(tokenizer.begin(), tokenizer.end());
args.push_back(file);
if (!path.empty())
{
std::string newPath(Environment::get("PATH"));
newPath += Path::pathSeparator();
newPath += path;
Environment::set("PATH", path);
}
if (usePipe)
{
Poco::Pipe inPipe;
ProcessHandle proc = Process::launch(exec, args, 0, &inPipe, 0);
return new Preprocessor(proc, new Poco::PipeInputStream(inPipe));
}
else
{
ProcessHandle proc = Process::launch(exec, args);
proc.wait();
return new Preprocessor(proc, new std::ifstream(pp.getFileName().c_str()), pp.getFileName());
}
}
void parse(const std::string& file)
{
logger().information("Preprocessing " + file);
std::unique_ptr<Preprocessor> pPreProc(preprocess(file));
logger().information("Parsing " + file);
if (pPreProc->stream().good())
{
Poco::CppParser::Parser parser(_gst, file, pPreProc->stream());
parser.parse();
}
else throw Poco::OpenFileException("cannot read from preprocessor");
}
int parseAll()
{
int errors = 0;
std::set<std::string> files;
buildFileList(files);
for (std::set<std::string>::const_iterator it = files.begin(); it != files.end(); ++it)
{
try
{
parse(*it);
}
catch (Exception& exc)
{
logger().log(exc);
++errors;
}
}
return errors;
}
void fixup()
{
logger().information("Fixing-up class hierarchies");
for (Poco::CppParser::NameSpace::SymbolTable::iterator it = _gst.begin(); it != _gst.end(); ++it)
{
Poco::CppParser::Struct* pStruct = dynamic_cast<Poco::CppParser::Struct*>(it->second);
if (pStruct)
{
pStruct->fixupBases();
}
}
}
void writeDoc()
{
logger().information("Generating documentation");
Path path(config().getString("PocoDoc.output", "doc"));
path.makeDirectory();
File file(path);
file.createDirectories();
DocWriter writer(_gst, path.toString(), config().getBool("PocoDoc.prettifyCode", false), _writeEclipseTOC);
if (config().hasProperty("PocoDoc.pages"))
{
std::string pages = config().getString("PocoDoc.pages");
StringTokenizer tokenizer(pages, ",\n", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
std::set<std::string> pageSet;
for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it)
{
Glob::glob(*it, pageSet);
}
for (std::set<std::string>::const_iterator it = pageSet.begin(); it != pageSet.end(); ++it)
{
writer.addPage(*it);
}
}
writer.write();
if (_writeEclipseTOC)
{
writer.writeEclipseTOC();
}
}
void copyResources()
{
logger().information("Copying resources");
Path path(config().getString("PocoDoc.output", "doc"));
if (config().hasProperty("PocoDoc.resources"))
{
std::string pages = config().getString("PocoDoc.resources");
StringTokenizer tokenizer(pages, ",\n", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM);
std::set<std::string> pageSet;
for (StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end(); ++it)
{
Glob::glob(*it, pageSet);
}
for (std::set<std::string>::const_iterator it = pageSet.begin(); it != pageSet.end(); ++it)
{
try
{
copyResource(Path(*it), path);
}
catch (Poco::Exception& exc)
{
logger().log(exc);
}
}
}
}
void copyResource(const Path& source, const Path& dest)
{
logger().information(std::string("Copying resource ") + source.toString() + " to " + dest.toString());
File sf(source);
if (sf.isDirectory())
copyDirectory(source, dest);
else
copyFile(source, dest);
}
void copyFile(const Path& source, const Path& dest)
{
Path dd(dest);
dd.makeDirectory();
File df(dd);
df.createDirectories();
dd.setFileName(source.getFileName());
if (source.getExtension() == "thtml")
{
dd.setExtension("html");
std::ifstream istr(source.toString().c_str());
std::ofstream ostr(dd.toString().c_str());
while (istr.good())
{
std::string line;
std::getline(istr, line);
ostr << config().expand(line) << std::endl;
}
}
else
{
File sf(source);
sf.copyTo(dd.toString());
}
}
void copyDirectory(const Path& source, const Path& dest)
{
Path src(source);
src.makeFile();
DirectoryIterator it(src);
DirectoryIterator end;
for (; it != end; ++it)
{
Path dd(dest);
dd.makeDirectory();
dd.pushDirectory(src.getFileName());
copyResource(it.path(), dd);
}
}
int main(const std::vector<std::string>& args)
{
if (!_helpRequested)
{
Poco::DateTime now;
config().setString("PocoDoc.date", Poco::DateTimeFormatter::format(now, "%Y-%m-%d"));
config().setString("PocoDoc.year", Poco::DateTimeFormatter::format(now, "%Y"));
config().setString("PocoDoc.googleAnalyticsCode", generateGoogleAnalyticsCode());
Poco::Stopwatch sw;
int errors = 0;
try
{
sw.start();
errors = parseAll();
fixup();
writeDoc();
copyResources();
sw.stop();
}
catch (Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
}
logger().information(NumberFormatter::format(errors) + " errors.");
logger().information(std::string("Time: ") + Poco::DateTimeFormatter::format(Poco::Timespan(sw.elapsed())));
}
return Application::EXIT_OK;
}
std::string generateGoogleAnalyticsCode()
{
std::stringstream ostr;
std::string googleAnalyticsId(config().getString("PocoDoc.googleAnalyticsId", ""));
if (!googleAnalyticsId.empty())
{
ostr << "<!-- Begin Google Analytics -->\n";
ostr << "<script type=\"text/javascript\">\n";
ostr << "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n";
ostr << "document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n";
ostr << "</script>\n";
ostr << "<script type=\"text/javascript\">\n";
ostr << "try {\n";
ostr << "var pageTracker = _gat._getTracker(\"" << googleAnalyticsId << "\");\n";
ostr << "pageTracker._trackPageview();\n";
ostr << "} catch(err) {}</script>\n";
ostr << "<!-- End Google Analytics -->\n";
}
return ostr.str();
}
private:
bool _helpRequested;
bool _writeEclipseTOC;
Poco::CppParser::NameSpace::SymbolTable _gst;
};
int main(int argc, char** argv)
{
PocoDocApp app;
try
{
app.init(argc, argv);
}
catch (Poco::Exception& exc)
{
app.logger().log(exc);
return Application::EXIT_CONFIG;
}
return app.run();
}
| 25.091778 | 146 | 0.659834 | [
"vector"
] |
c85daa1ed69d07543cedf3824c1cf78b3ba5ae53 | 1,641 | cpp | C++ | p773/p773.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | 1 | 2019-10-07T05:00:21.000Z | 2019-10-07T05:00:21.000Z | p773/p773.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | p773/p773.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | class Solution {
public:
const string target = "123450";
const int dir[4][2] = {{0,1}, {0,-1}, {1,0},{-1,0}};
deque<string> qu1, qu2;
unordered_set<string> vis1, vis2;
int slidingPuzzle(vector<vector<int>>& board) {
string start;
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
start += (char)(board[i][j] + '0');
if (start == target)
return 0;
qu1.push_back(start);
vis1.insert(start);
qu2.push_back(target);
vis2.insert(target);
int steps = 0;
while (!qu1.empty()) {
++steps;
int size = qu1.size();
while (size) {
--size;
string cur = qu1.front();
qu1.pop_front();
int pos = 0;
while (pos < 6 && cur[pos] != '0')
++pos;
int x = pos/3, y = pos%3;
for (int i = 0; i < 4; ++i) {
int tx = x + dir[i][0];
if (tx < 0 || tx > 1)
continue;
int ty = y + dir[i][1];
if (ty < 0 || ty > 2)
continue;
string tmp = cur;
tmp[pos] = tmp[tx*3 + ty];
tmp[tx*3 + ty] = '0';
if (vis2.count(tmp))
return steps;
if (!vis1.count(tmp)) {
qu1.push_back(tmp);
vis1.insert(tmp);
}
}
}
if (qu1.size() > qu2.size()) {
deque<string> tmp = qu1;
qu1 = qu2;
qu2 = tmp;
unordered_set<string> ts = vis1;
vis1 = vis2;
vis2 = ts;
}
}
return -1;
}
}; | 21.88 | 53 | 0.401584 | [
"vector"
] |
c85ef6d945c655b74020aba9201e9db025cc9d89 | 8,046 | cpp | C++ | code/editors/XTools/ETools.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/editors/XTools/ETools.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/editors/XTools/ETools.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2020-10-12T18:04:42.000Z | 2020-10-12T18:04:59.000Z | #include "stdafx.h"
#include "ETools.h"
#include "xrXRC.h"
#pragma warning(disable:4267)
BOOL APIENTRY DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved)
{
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
Debug._initialize();
Core._initialize("XRayEditorTools", 0, FALSE);
//FPU::m64r ();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
Core._destroy();
break;
}
return TRUE;
}
namespace ETOOLS
{
ETOOLS_API bool __stdcall TestRayTriA(const Fvector& C, const Fvector& D, Fvector** p, float& u, float& v, float& range, bool bCull)
{
Fvector edge1, edge2, tvec, pvec, qvec;
float det, inv_det;
// find vectors for two edges sharing vert0
edge1.sub(*p[1], *p[0]);
edge2.sub(*p[2], *p[0]);
// begin calculating determinant - also used to calculate U parameter
pvec.crossproduct(D, edge2);
// if determinant is near zero, ray lies in plane of triangle
det = edge1.dotproduct(pvec);
if (bCull) { // define TEST_CULL if culling is desired
if (det < EPS) return false;
tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec); // calculate U parameter and test bounds
if (u < 0.0 || u > det) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec); // calculate V parameter and test bounds
if (v < 0.0 || u + v > det) return false;
range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle
inv_det = 1.0f / det;
range *= inv_det;
u *= inv_det;
v *= inv_det;
}
else { // the non-culling branch
if (det > -EPS && det < EPS) return false;
inv_det = 1.0f / det;
tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
if (u < 0.0f || u > 1.0f) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
if (v < 0.0f || u + v > 1.0f) return false;
range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
}
return true;
}
//-- Ray-Triangle : 1st level of indirection --------------------------------
ETOOLS_API bool __stdcall TestRayTriB(const Fvector& C, const Fvector& D, Fvector* p, float& u, float& v, float& range, bool bCull)
{
Fvector edge1, edge2, tvec, pvec, qvec;
float det, inv_det;
// find vectors for two edges sharing vert0
edge1.sub(p[1], p[0]);
edge2.sub(p[2], p[0]);
// begin calculating determinant - also used to calculate U parameter
pvec.crossproduct(D, edge2);
// if determinant is near zero, ray lies in plane of triangle
det = edge1.dotproduct(pvec);
if (bCull) { // define TEST_CULL if culling is desired
if (det < EPS) return false;
tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec); // calculate U parameter and test bounds
if (u < 0.0f || u > det) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec); // calculate V parameter and test bounds
if (v < 0.0f || u + v > det) return false;
range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle
inv_det = 1.0f / det;
range *= inv_det;
u *= inv_det;
v *= inv_det;
}
else { // the non-culling branch
if (det > -EPS && det < EPS) return false;
inv_det = 1.0f / det;
tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
if (u < 0.0f || u > 1.0f) return false;
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
if (v < 0.0f || u + v > 1.0f) return false;
range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
}
return true;
}
//-- Ray-Triangle(always return range) : 1st level of indirection --------------------------------
ETOOLS_API bool __stdcall TestRayTri2(const Fvector& C, const Fvector& D, Fvector* p, float& range)
{
Fvector edge1, edge2, tvec, pvec, qvec;
float det, inv_det, u, v;
// find vectors for two edges sharing vert0
edge1.sub(p[1], p[0]);
edge2.sub(p[2], p[0]);
// begin calculating determinant - also used to calculate U parameter
pvec.crossproduct(D, edge2);
// if determinant is near zero, ray lies in plane of triangle
det = edge1.dotproduct(pvec);
if (_abs(det) < EPS_S) { range = -1; return false; }
inv_det = 1.0f / det;
tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
qvec.crossproduct(tvec, edge1); // prepare to test V parameter
range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects plane
if (u < 0.0f || u > 1.0f) return false;
v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
if (v < 0.0f || u + v > 1.0f) return false;
return true;
}
ETOOLS_API CDB::Collector* __stdcall create_collector()
{
return xr_new<CDB::Collector>();
}
ETOOLS_API void __stdcall destroy_collector(CDB::Collector*& M)
{
xr_delete(M);
}
ETOOLS_API void __stdcall collector_add_face_d(CDB::Collector* CL, const Fvector& v0, const Fvector& v1, const Fvector& v2, size_t dummy)
{
CL->add_face_D(v0, v1, v2, dummy);
}
ETOOLS_API void __stdcall collector_add_face_pd(CDB::Collector* CL, const Fvector& v0, const Fvector& v1, const Fvector& v2, size_t dummy, float eps)
{
CL->add_face_packed_D(v0, v1, v2, dummy, eps);
}
ETOOLS_API CDB::CollectorPacked* __stdcall create_collectorp(const Fbox &bb, int apx_vertices, int apx_faces)
{
return xr_new<CDB::CollectorPacked>(bb, apx_vertices, apx_faces);
}
ETOOLS_API void __stdcall destroy_collectorp(CDB::CollectorPacked*& M)
{
xr_delete(M);
}
ETOOLS_API void __stdcall collectorp_add_face_d(CDB::CollectorPacked* CL, const Fvector& v0, const Fvector& v1, const Fvector& v2, size_t dummy)
{
CL->add_face_D(v0, v1, v2, dummy, u32(-1));
}
ETOOLS_API CDB::COLLIDER* __stdcall get_collider() { return XRC.collider(); }
ETOOLS_API CDB::MODEL* __stdcall create_model_clp(CDB::CollectorPacked* CL)
{
return create_model(CL->getV(), CL->getVS(), CL->getT(), CL->getTS());
}
ETOOLS_API CDB::MODEL* __stdcall create_model_cl(CDB::Collector* CL)
{
return create_model(CL->getV(), CL->getVS(), CL->getT(), CL->getTS());
}
ETOOLS_API CDB::MODEL* __stdcall create_model(Fvector* V, int Vcnt, CDB::TRI* T, int Tcnt)
{
CDB::MODEL* M = xr_new<CDB::MODEL>();
M->build(V, Vcnt, T, Tcnt);
return M;
}
ETOOLS_API void __stdcall destroy_model(CDB::MODEL*& M)
{
xr_delete(M);
}
ETOOLS_API CDB::RESULT* __stdcall r_begin() { return XRC.r_begin(); };
ETOOLS_API CDB::RESULT* __stdcall r_end() { return XRC.r_end(); };
ETOOLS_API int __stdcall r_count() { return XRC.r_count(); };
ETOOLS_API void __stdcall ray_options(u32 flags)
{
XRC.ray_options(flags);
}
ETOOLS_API void __stdcall ray_query(const CDB::MODEL *m_def, const Fvector& r_start, const Fvector& r_dir, float r_range)
{
XRC.ray_query(m_def, r_start, r_dir, r_range);
}
ETOOLS_API void __stdcall ray_query_m(const Fmatrix& inv_parent, const CDB::MODEL *m_def, const Fvector& r_start, const Fvector& r_dir, float r_range)
{
XRC.ray_query(inv_parent, m_def, r_start, r_dir, r_range);
}
ETOOLS_API void __stdcall box_options(u32 flags)
{
XRC.box_options(flags);
}
ETOOLS_API void __stdcall box_query(const CDB::MODEL *m_def, const Fvector& b_center, const Fvector& b_dim)
{
XRC.box_query(m_def, b_center, b_dim);
}
ETOOLS_API void __stdcall box_query_m(const Fmatrix& inv_parent, const CDB::MODEL *m_def, const Fbox& src)
{
XRC.box_query(inv_parent, m_def, src);
}
} | 38.314286 | 156 | 0.672011 | [
"model"
] |
c8643a3ab54f7e4e5c366e043147334bd1f396c9 | 277 | hpp | C++ | include/oddlib/compressiontype2.hpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | 131 | 2015-03-21T14:10:21.000Z | 2021-01-19T03:54:04.000Z | include/oddlib/compressiontype2.hpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | 51 | 2015-04-06T17:24:45.000Z | 2018-02-03T14:36:37.000Z | include/oddlib/compressiontype2.hpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | 17 | 2015-10-07T10:20:47.000Z | 2021-08-02T04:14:11.000Z | #pragma once
#include <vector>
#include "types.hpp"
namespace Oddlib
{
class IStream;
class CompressionType2
{
public:
CompressionType2() = default;
std::vector<u8> Decompress(IStream& stream, u32 finalW, u32 w, u32 h, u32 dataSize);
};
}
| 17.3125 | 92 | 0.638989 | [
"vector"
] |
c868671a6c6e846808cf28200b5169c79da53377 | 194,815 | cc | C++ | src/torque/implementation-visitor.cc | vincent-unity/v8 | 6925c86b1dcec37ee5682049f6a07c8a62befb58 | [
"BSD-3-Clause"
] | null | null | null | src/torque/implementation-visitor.cc | vincent-unity/v8 | 6925c86b1dcec37ee5682049f6a07c8a62befb58 | [
"BSD-3-Clause"
] | null | null | null | src/torque/implementation-visitor.cc | vincent-unity/v8 | 6925c86b1dcec37ee5682049f6a07c8a62befb58 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 the V8 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.
#include "src/torque/implementation-visitor.h"
#include <algorithm>
#include <iomanip>
#include <string>
#include "src/base/optional.h"
#include "src/common/globals.h"
#include "src/torque/cc-generator.h"
#include "src/torque/constants.h"
#include "src/torque/csa-generator.h"
#include "src/torque/declaration-visitor.h"
#include "src/torque/global-context.h"
#include "src/torque/parameter-difference.h"
#include "src/torque/server-data.h"
#include "src/torque/type-inference.h"
#include "src/torque/type-visitor.h"
#include "src/torque/types.h"
namespace v8 {
namespace internal {
namespace torque {
VisitResult ImplementationVisitor::Visit(Expression* expr) {
CurrentSourcePosition::Scope scope(expr->pos);
switch (expr->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return Visit(name::cast(expr));
AST_EXPRESSION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNREACHABLE();
}
}
const Type* ImplementationVisitor::Visit(Statement* stmt) {
CurrentSourcePosition::Scope scope(stmt->pos);
StackScope stack_scope(this);
const Type* result;
switch (stmt->kind) {
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
result = Visit(name::cast(stmt)); \
break;
AST_STATEMENT_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
default:
UNREACHABLE();
}
DCHECK_EQ(result == TypeOracle::GetNeverType(),
assembler().CurrentBlockIsComplete());
return result;
}
void ImplementationVisitor::BeginGeneratedFiles() {
std::set<SourceId> contains_class_definitions;
for (const ClassType* type : TypeOracle::GetClasses()) {
if (type->GenerateCppClassDefinitions()) {
contains_class_definitions.insert(type->AttributedToFile());
}
}
for (SourceId file : SourceFileMap::AllSources()) {
// Output beginning of CSA .cc file.
{
std::ostream& out = GlobalContext::GeneratedPerFile(file).csa_ccfile;
for (const std::string& include_path : GlobalContext::CppIncludes()) {
out << "#include " << StringLiteralQuote(include_path) << "\n";
}
for (SourceId file : SourceFileMap::AllSources()) {
out << "#include \"torque-generated/" +
SourceFileMap::PathFromV8RootWithoutExtension(file) +
"-tq-csa.h\"\n";
}
out << "\n";
out << "namespace v8 {\n"
<< "namespace internal {\n"
<< "\n";
}
// Output beginning of CSA .h file.
{
std::ostream& out = GlobalContext::GeneratedPerFile(file).csa_headerfile;
std::string headerDefine =
"V8_GEN_TORQUE_GENERATED_" +
UnderlinifyPath(SourceFileMap::PathFromV8Root(file)) + "_H_";
out << "#ifndef " << headerDefine << "\n";
out << "#define " << headerDefine << "\n\n";
out << "#include \"src/builtins/torque-csa-header-includes.h\"\n";
out << "\n";
out << "namespace v8 {\n"
<< "namespace internal {\n"
<< "\n";
}
// Output beginning of class definition .cc file.
{
auto& streams = GlobalContext::GeneratedPerFile(file);
std::ostream& out = streams.class_definition_ccfile;
if (contains_class_definitions.count(file) != 0) {
out << "#include \""
<< SourceFileMap::PathFromV8RootWithoutExtension(file)
<< "-inl.h\"\n\n";
out << "#include \"torque-generated/class-verifiers.h\"\n";
out << "#include \"src/objects/instance-type-inl.h\"\n\n";
}
out << "namespace v8 {\n";
out << "namespace internal {\n";
}
}
}
void ImplementationVisitor::EndGeneratedFiles() {
for (SourceId file : SourceFileMap::AllSources()) {
{
std::ostream& out = GlobalContext::GeneratedPerFile(file).csa_ccfile;
out << "} // namespace internal\n"
<< "} // namespace v8\n"
<< "\n";
}
{
std::ostream& out = GlobalContext::GeneratedPerFile(file).csa_headerfile;
std::string headerDefine =
"V8_GEN_TORQUE_GENERATED_" +
UnderlinifyPath(SourceFileMap::PathFromV8Root(file)) + "_H_";
out << "} // namespace internal\n"
<< "} // namespace v8\n"
<< "\n";
out << "#endif // " << headerDefine << "\n";
}
{
std::ostream& out =
GlobalContext::GeneratedPerFile(file).class_definition_ccfile;
out << "} // namespace v8\n";
out << "} // namespace internal\n";
}
}
}
void ImplementationVisitor::BeginRuntimeMacrosFile() {
std::ostream& source = runtime_macros_cc_;
std::ostream& header = runtime_macros_h_;
source << "#include \"torque-generated/runtime-macros.h\"\n\n";
source << "#include \"src/torque/runtime-macro-shims.h\"\n";
for (const std::string& include_path : GlobalContext::CppIncludes()) {
source << "#include " << StringLiteralQuote(include_path) << "\n";
}
source << "\n";
source << "namespace v8 {\n"
<< "namespace internal {\n"
<< "\n";
const char* kHeaderDefine = "V8_GEN_TORQUE_GENERATED_RUNTIME_MACROS_H_";
header << "#ifndef " << kHeaderDefine << "\n";
header << "#define " << kHeaderDefine << "\n\n";
header << "#include \"src/builtins/torque-csa-header-includes.h\"\n";
header << "\n";
header << "namespace v8 {\n"
<< "namespace internal {\n"
<< "\n";
}
void ImplementationVisitor::EndRuntimeMacrosFile() {
std::ostream& source = runtime_macros_cc_;
std::ostream& header = runtime_macros_h_;
source << "} // namespace internal\n"
<< "} // namespace v8\n"
<< "\n";
header << "\n} // namespace internal\n"
<< "} // namespace v8\n"
<< "\n";
header << "#endif // V8_GEN_TORQUE_GENERATED_RUNTIME_MACROS_H_\n";
}
void ImplementationVisitor::Visit(NamespaceConstant* decl) {
Signature signature{{}, base::nullopt, {{}, false}, 0, decl->type(),
{}, false};
BindingsManagersScope bindings_managers_scope;
csa_headerfile() << " ";
GenerateFunctionDeclaration(csa_headerfile(), "", decl->external_name(),
signature, {});
csa_headerfile() << ";\n";
GenerateFunctionDeclaration(csa_ccfile(), "", decl->external_name(),
signature, {});
csa_ccfile() << " {\n";
csa_ccfile() << " compiler::CodeAssembler ca_(state_);\n";
DCHECK(!signature.return_type->IsVoidOrNever());
assembler_ = CfgAssembler(Stack<const Type*>{});
VisitResult expression_result = Visit(decl->body());
VisitResult return_result =
GenerateImplicitConvert(signature.return_type, expression_result);
CSAGenerator csa_generator{assembler().Result(), csa_ccfile()};
Stack<std::string> values = *csa_generator.EmitGraph(Stack<std::string>{});
assembler_ = base::nullopt;
csa_ccfile() << " return ";
CSAGenerator::EmitCSAValue(return_result, values, csa_ccfile());
csa_ccfile() << ";\n";
csa_ccfile() << "}\n\n";
}
void ImplementationVisitor::Visit(TypeAlias* alias) {
if (alias->IsRedeclaration()) return;
if (const ClassType* class_type = ClassType::DynamicCast(alias->type())) {
if (class_type->IsExtern() && !class_type->nspace()->IsDefaultNamespace()) {
Error(
"extern classes are currently only supported in the default "
"namespace");
}
}
}
VisitResult ImplementationVisitor::InlineMacro(
Macro* macro, base::Optional<LocationReference> this_reference,
const std::vector<VisitResult>& arguments,
const std::vector<Block*> label_blocks) {
CurrentScope::Scope current_scope(macro);
BindingsManagersScope bindings_managers_scope;
CurrentCallable::Scope current_callable(macro);
CurrentReturnValue::Scope current_return_value;
const Signature& signature = macro->signature();
const Type* return_type = macro->signature().return_type;
bool can_return = return_type != TypeOracle::GetNeverType();
BlockBindings<LocalValue> parameter_bindings(&ValueBindingsManager::Get());
BlockBindings<LocalLabel> label_bindings(&LabelBindingsManager::Get());
DCHECK_EQ(macro->signature().parameter_names.size(),
arguments.size() + (this_reference ? 1 : 0));
DCHECK_EQ(this_reference.has_value(), macro->IsMethod());
// Bind the this for methods. Methods that modify a struct-type "this" must
// only be called if the this is in a variable, in which case the
// LocalValue is non-const. Otherwise, the LocalValue used for the parameter
// binding is const, and thus read-only, which will cause errors if
// modified, e.g. when called by a struct method that sets the structs
// fields. This prevents using temporary struct values for anything other
// than read operations.
if (this_reference) {
DCHECK(macro->IsMethod());
parameter_bindings.Add(kThisParameterName, LocalValue{*this_reference},
true);
}
size_t i = 0;
for (auto arg : arguments) {
if (this_reference && i == signature.implicit_count) i++;
const bool mark_as_used = signature.implicit_count > i;
const Identifier* name = macro->parameter_names()[i++];
parameter_bindings.Add(name,
LocalValue{LocationReference::Temporary(
arg, "parameter " + name->value)},
mark_as_used);
}
DCHECK_EQ(label_blocks.size(), signature.labels.size());
for (size_t i = 0; i < signature.labels.size(); ++i) {
const LabelDeclaration& label_info = signature.labels[i];
label_bindings.Add(label_info.name,
LocalLabel{label_blocks[i], label_info.types});
}
Block* macro_end;
base::Optional<Binding<LocalLabel>> macro_end_binding;
if (can_return) {
Stack<const Type*> stack = assembler().CurrentStack();
std::vector<const Type*> lowered_return_types = LowerType(return_type);
stack.PushMany(lowered_return_types);
if (!return_type->IsConstexpr()) {
SetReturnValue(VisitResult(return_type,
stack.TopRange(lowered_return_types.size())));
}
// The stack copy used to initialize the _macro_end block is only used
// as a template for the actual gotos generated by return statements. It
// doesn't correspond to any real return values, and thus shouldn't contain
// top types, because these would pollute actual return value types that get
// unioned with them for return statements, erroneously forcing them to top.
for (auto i = stack.begin(); i != stack.end(); ++i) {
if ((*i)->IsTopType()) {
*i = TopType::cast(*i)->source_type();
}
}
macro_end = assembler().NewBlock(std::move(stack));
macro_end_binding.emplace(&LabelBindingsManager::Get(), kMacroEndLabelName,
LocalLabel{macro_end, {return_type}});
} else {
SetReturnValue(VisitResult::NeverResult());
}
const Type* result = Visit(*macro->body());
if (result->IsNever()) {
if (!return_type->IsNever() && !macro->HasReturns()) {
std::stringstream s;
s << "macro " << macro->ReadableName()
<< " that never returns must have return type never";
ReportError(s.str());
}
} else {
if (return_type->IsNever()) {
std::stringstream s;
s << "macro " << macro->ReadableName()
<< " has implicit return at end of its declartion but return type "
"never";
ReportError(s.str());
} else if (!macro->signature().return_type->IsVoid()) {
std::stringstream s;
s << "macro " << macro->ReadableName()
<< " expects to return a value but doesn't on all paths";
ReportError(s.str());
}
}
if (!result->IsNever()) {
assembler().Goto(macro_end);
}
if (macro->HasReturns() || !result->IsNever()) {
assembler().Bind(macro_end);
}
return GetAndClearReturnValue();
}
void ImplementationVisitor::VisitMacroCommon(Macro* macro) {
CurrentCallable::Scope current_callable(macro);
const Signature& signature = macro->signature();
const Type* return_type = macro->signature().return_type;
bool can_return = return_type != TypeOracle::GetNeverType();
bool has_return_value =
can_return && return_type != TypeOracle::GetVoidType();
GenerateMacroFunctionDeclaration(csa_headerfile(), macro);
csa_headerfile() << ";\n";
GenerateMacroFunctionDeclaration(csa_ccfile(), macro);
csa_ccfile() << " {\n";
if (output_type_ == OutputType::kCC) {
// For now, generated C++ is only for field offset computations. If we ever
// generate C++ code that can allocate, then it should be handlified.
csa_ccfile() << " DisallowHeapAllocation no_gc;\n";
} else {
csa_ccfile() << " compiler::CodeAssembler ca_(state_);\n";
csa_ccfile()
<< " compiler::CodeAssembler::SourcePositionScope pos_scope(&ca_);\n";
}
Stack<std::string> lowered_parameters;
Stack<const Type*> lowered_parameter_types;
std::vector<VisitResult> arguments;
base::Optional<LocationReference> this_reference;
if (Method* method = Method::DynamicCast(macro)) {
const Type* this_type = method->aggregate_type();
LowerParameter(this_type, ExternalParameterName(kThisParameterName),
&lowered_parameters);
StackRange range = lowered_parameter_types.PushMany(LowerType(this_type));
VisitResult this_result = VisitResult(this_type, range);
// For classes, mark 'this' as a temporary to prevent assignment to it.
// Note that using a VariableAccess for non-class types is technically
// incorrect because changes to the 'this' variable do not get reflected
// to the caller. Therefore struct methods should always be inlined and a
// C++ version should never be generated, since it would be incorrect.
// However, in order to be able to type- and semantics-check even unused
// struct methods, set the this_reference to be the local variable copy of
// the passed-in this, which allows the visitor to at least find and report
// errors.
this_reference =
(this_type->IsClassType())
? LocationReference::Temporary(this_result, "this parameter")
: LocationReference::VariableAccess(this_result);
}
for (size_t i = 0; i < macro->signature().parameter_names.size(); ++i) {
if (this_reference && i == macro->signature().implicit_count) continue;
const std::string& name = macro->parameter_names()[i]->value;
std::string external_name = ExternalParameterName(name);
const Type* type = macro->signature().types()[i];
if (type->IsConstexpr()) {
arguments.push_back(VisitResult(type, external_name));
} else {
LowerParameter(type, external_name, &lowered_parameters);
StackRange range = lowered_parameter_types.PushMany(LowerType(type));
arguments.push_back(VisitResult(type, range));
}
}
DCHECK_EQ(lowered_parameters.Size(), lowered_parameter_types.Size());
assembler_ = CfgAssembler(lowered_parameter_types);
std::vector<Block*> label_blocks;
for (const LabelDeclaration& label_info : signature.labels) {
Stack<const Type*> label_input_stack;
for (const Type* type : label_info.types) {
label_input_stack.PushMany(LowerType(type));
}
Block* block = assembler().NewBlock(std::move(label_input_stack));
label_blocks.push_back(block);
}
VisitResult return_value =
InlineMacro(macro, this_reference, arguments, label_blocks);
Block* end = assembler().NewBlock();
if (return_type != TypeOracle::GetNeverType()) {
assembler().Goto(end);
}
for (size_t i = 0; i < label_blocks.size(); ++i) {
Block* label_block = label_blocks[i];
const LabelDeclaration& label_info = signature.labels[i];
assembler().Bind(label_block);
std::vector<std::string> label_parameter_variables;
for (size_t i = 0; i < label_info.types.size(); ++i) {
LowerLabelParameter(label_info.types[i],
ExternalLabelParameterName(label_info.name->value, i),
&label_parameter_variables);
}
assembler().Emit(GotoExternalInstruction{
ExternalLabelName(label_info.name->value), label_parameter_variables});
}
if (return_type != TypeOracle::GetNeverType()) {
assembler().Bind(end);
}
base::Optional<Stack<std::string>> values;
if (output_type_ == OutputType::kCC) {
CCGenerator cc_generator{assembler().Result(), csa_ccfile()};
values = cc_generator.EmitGraph(lowered_parameters);
} else {
CSAGenerator csa_generator{assembler().Result(), csa_ccfile()};
values = csa_generator.EmitGraph(lowered_parameters);
}
assembler_ = base::nullopt;
if (has_return_value) {
csa_ccfile() << " return ";
if (output_type_ == OutputType::kCC) {
CCGenerator::EmitCCValue(return_value, *values, csa_ccfile());
} else {
CSAGenerator::EmitCSAValue(return_value, *values, csa_ccfile());
}
csa_ccfile() << ";\n";
}
csa_ccfile() << "}\n\n";
}
void ImplementationVisitor::Visit(TorqueMacro* macro) {
VisitMacroCommon(macro);
}
void ImplementationVisitor::Visit(Method* method) {
DCHECK(!method->IsExternal());
VisitMacroCommon(method);
}
namespace {
std::string AddParameter(size_t i, Builtin* builtin,
Stack<std::string>* parameters,
Stack<const Type*>* parameter_types,
BlockBindings<LocalValue>* parameter_bindings,
bool mark_as_used) {
const Identifier* name = builtin->signature().parameter_names[i];
const Type* type = builtin->signature().types()[i];
std::string external_name = "parameter" + std::to_string(i);
parameters->Push(external_name);
StackRange range = parameter_types->PushMany(LowerType(type));
parameter_bindings->Add(
name,
LocalValue{LocationReference::Temporary(VisitResult(type, range),
"parameter " + name->value)},
mark_as_used);
return external_name;
}
} // namespace
void ImplementationVisitor::Visit(Builtin* builtin) {
if (builtin->IsExternal()) return;
CurrentScope::Scope current_scope(builtin);
CurrentCallable::Scope current_callable(builtin);
CurrentReturnValue::Scope current_return_value;
const std::string& name = builtin->ExternalName();
const Signature& signature = builtin->signature();
csa_ccfile() << "TF_BUILTIN(" << name << ", CodeStubAssembler) {\n"
<< " compiler::CodeAssemblerState* state_ = state();"
<< " compiler::CodeAssembler ca_(state());\n";
Stack<const Type*> parameter_types;
Stack<std::string> parameters;
BindingsManagersScope bindings_managers_scope;
BlockBindings<LocalValue> parameter_bindings(&ValueBindingsManager::Get());
if (builtin->IsVarArgsJavaScript() || builtin->IsFixedArgsJavaScript()) {
if (builtin->IsVarArgsJavaScript()) {
DCHECK(signature.parameter_types.var_args);
if (signature.ExplicitCount() > 0) {
Error("Cannot mix explicit parameters with varargs.")
.Position(signature.parameter_names[signature.implicit_count]->pos);
}
csa_ccfile() << " TNode<Word32T> argc = UncheckedParameter<Word32T>("
<< "Descriptor::kJSActualArgumentsCount);\n";
csa_ccfile() << " TNode<IntPtrT> "
"arguments_length(ChangeInt32ToIntPtr(UncheckedCast<"
"Int32T>(argc)));\n";
csa_ccfile() << " TNode<RawPtrT> arguments_frame = "
"UncheckedCast<RawPtrT>(LoadFramePointer());\n";
csa_ccfile() << " TorqueStructArguments "
"torque_arguments(GetFrameArguments(arguments_frame, "
"arguments_length));\n";
csa_ccfile()
<< " CodeStubArguments arguments(this, torque_arguments);\n";
parameters.Push("torque_arguments.frame");
parameters.Push("torque_arguments.base");
parameters.Push("torque_arguments.length");
const Type* arguments_type = TypeOracle::GetArgumentsType();
StackRange range = parameter_types.PushMany(LowerType(arguments_type));
parameter_bindings.Add(*signature.arguments_variable,
LocalValue{LocationReference::Temporary(
VisitResult(arguments_type, range),
"parameter " + *signature.arguments_variable)},
true);
}
for (size_t i = 0; i < signature.implicit_count; ++i) {
const std::string& param_name = signature.parameter_names[i]->value;
SourcePosition param_pos = signature.parameter_names[i]->pos;
std::string generated_name = AddParameter(
i, builtin, ¶meters, ¶meter_types, ¶meter_bindings, true);
const Type* actual_type = signature.parameter_types.types[i];
std::vector<const Type*> expected_types;
if (param_name == "context") {
csa_ccfile() << " TNode<NativeContext> " << generated_name
<< " = UncheckedParameter<NativeContext>("
<< "Descriptor::kContext);\n";
csa_ccfile() << " USE(" << generated_name << ");\n";
expected_types = {TypeOracle::GetNativeContextType(),
TypeOracle::GetContextType()};
} else if (param_name == "receiver") {
csa_ccfile()
<< " TNode<Object> " << generated_name << " = "
<< (builtin->IsVarArgsJavaScript()
? "arguments.GetReceiver()"
: "UncheckedParameter<Object>(Descriptor::kReceiver)")
<< ";\n";
csa_ccfile() << "USE(" << generated_name << ");\n";
expected_types = {TypeOracle::GetJSAnyType()};
} else if (param_name == "newTarget") {
csa_ccfile() << " TNode<Object> " << generated_name
<< " = UncheckedParameter<Object>("
<< "Descriptor::kJSNewTarget);\n";
csa_ccfile() << "USE(" << generated_name << ");\n";
expected_types = {TypeOracle::GetJSAnyType()};
} else if (param_name == "target") {
csa_ccfile() << " TNode<JSFunction> " << generated_name
<< " = UncheckedParameter<JSFunction>("
<< "Descriptor::kJSTarget);\n";
csa_ccfile() << "USE(" << generated_name << ");\n";
expected_types = {TypeOracle::GetJSFunctionType()};
} else {
Error(
"Unexpected implicit parameter \"", param_name,
"\" for JavaScript calling convention, "
"expected \"context\", \"receiver\", \"target\", or \"newTarget\"")
.Position(param_pos);
expected_types = {actual_type};
}
if (std::find(expected_types.begin(), expected_types.end(),
actual_type) == expected_types.end()) {
Error("According to JavaScript calling convention, expected parameter ",
param_name, " to have type ", PrintList(expected_types, " or "),
" but found type ", *actual_type)
.Position(param_pos);
}
}
for (size_t i = signature.implicit_count;
i < signature.parameter_names.size(); ++i) {
const std::string& parameter_name = signature.parameter_names[i]->value;
const Type* type = signature.types()[i];
const bool mark_as_used = signature.implicit_count > i;
std::string var = AddParameter(i, builtin, ¶meters, ¶meter_types,
¶meter_bindings, mark_as_used);
csa_ccfile() << " " << type->GetGeneratedTypeName() << " " << var
<< " = "
<< "UncheckedParameter<" << type->GetGeneratedTNodeTypeName()
<< ">(Descriptor::k" << CamelifyString(parameter_name)
<< ");\n";
csa_ccfile() << " USE(" << var << ");\n";
}
} else {
DCHECK(builtin->IsStub());
bool has_context_parameter = signature.HasContextParameter();
for (size_t i = 0; i < signature.parameter_names.size(); ++i) {
const Type* type = signature.types()[i];
const bool mark_as_used = signature.implicit_count > i;
std::string var = AddParameter(i, builtin, ¶meters, ¶meter_types,
¶meter_bindings, mark_as_used);
csa_ccfile() << " " << type->GetGeneratedTypeName() << " " << var
<< " = "
<< "UncheckedParameter<" << type->GetGeneratedTNodeTypeName()
<< ">(";
if (i == 0 && has_context_parameter) {
csa_ccfile() << "Descriptor::kContext";
} else {
csa_ccfile() << "Descriptor::ParameterIndex<"
<< (has_context_parameter ? i - 1 : i) << ">()";
}
csa_ccfile() << ");\n";
csa_ccfile() << " USE(" << var << ");\n";
}
}
assembler_ = CfgAssembler(parameter_types);
const Type* body_result = Visit(*builtin->body());
if (body_result != TypeOracle::GetNeverType()) {
ReportError("control reaches end of builtin, expected return of a value");
}
CSAGenerator csa_generator{assembler().Result(), csa_ccfile(),
builtin->kind()};
csa_generator.EmitGraph(parameters);
assembler_ = base::nullopt;
csa_ccfile() << "}\n\n";
}
const Type* ImplementationVisitor::Visit(VarDeclarationStatement* stmt) {
BlockBindings<LocalValue> block_bindings(&ValueBindingsManager::Get());
return Visit(stmt, &block_bindings);
}
const Type* ImplementationVisitor::Visit(
VarDeclarationStatement* stmt, BlockBindings<LocalValue>* block_bindings) {
// const qualified variables are required to be initialized properly.
if (stmt->const_qualified && !stmt->initializer) {
ReportError("local constant \"", stmt->name, "\" is not initialized.");
}
base::Optional<const Type*> type;
if (stmt->type) {
type = TypeVisitor::ComputeType(*stmt->type);
}
base::Optional<VisitResult> init_result;
if (stmt->initializer) {
StackScope scope(this);
init_result = Visit(*stmt->initializer);
if (type) {
init_result = GenerateImplicitConvert(*type, *init_result);
}
type = init_result->type();
if ((*type)->IsConstexpr() && !stmt->const_qualified) {
Error("Use 'const' instead of 'let' for variable '", stmt->name->value,
"' of constexpr type '", (*type)->ToString(), "'.")
.Position(stmt->name->pos)
.Throw();
}
init_result = scope.Yield(*init_result);
} else {
DCHECK(type.has_value());
if ((*type)->IsConstexpr()) {
ReportError("constexpr variables need an initializer");
}
TypeVector lowered_types = LowerType(*type);
for (const Type* type : lowered_types) {
assembler().Emit(PushUninitializedInstruction{TypeOracle::GetTopType(
"uninitialized variable '" + stmt->name->value + "' of type " +
type->ToString() + " originally defined at " +
PositionAsString(stmt->pos),
type)});
}
init_result =
VisitResult(*type, assembler().TopRange(lowered_types.size()));
}
LocationReference ref = stmt->const_qualified
? LocationReference::Temporary(
*init_result, "const " + stmt->name->value)
: LocationReference::VariableAccess(*init_result);
block_bindings->Add(stmt->name, LocalValue{std::move(ref)});
return TypeOracle::GetVoidType();
}
const Type* ImplementationVisitor::Visit(TailCallStatement* stmt) {
return Visit(stmt->call, true).type();
}
VisitResult ImplementationVisitor::Visit(ConditionalExpression* expr) {
Block* true_block = assembler().NewBlock(assembler().CurrentStack());
Block* false_block = assembler().NewBlock(assembler().CurrentStack());
Block* done_block = assembler().NewBlock();
Block* true_conversion_block = assembler().NewBlock();
GenerateExpressionBranch(expr->condition, true_block, false_block);
VisitResult left;
VisitResult right;
{
// The code for both paths of the conditional need to be generated first
// before evaluating the conditional expression because the common type of
// the result of both the true and false of the condition needs to be known
// to convert both branches to a common type.
assembler().Bind(true_block);
StackScope left_scope(this);
left = Visit(expr->if_true);
assembler().Goto(true_conversion_block);
const Type* common_type;
{
assembler().Bind(false_block);
StackScope right_scope(this);
right = Visit(expr->if_false);
common_type = GetCommonType(left.type(), right.type());
right = right_scope.Yield(GenerateImplicitConvert(common_type, right));
assembler().Goto(done_block);
}
assembler().Bind(true_conversion_block);
left = left_scope.Yield(GenerateImplicitConvert(common_type, left));
assembler().Goto(done_block);
}
assembler().Bind(done_block);
CHECK_EQ(left, right);
return left;
}
VisitResult ImplementationVisitor::Visit(LogicalOrExpression* expr) {
StackScope outer_scope(this);
VisitResult left_result = Visit(expr->left);
if (left_result.type()->IsConstexprBool()) {
VisitResult right_result = Visit(expr->right);
if (!right_result.type()->IsConstexprBool()) {
ReportError(
"expected type constexpr bool on right-hand side of operator "
"||");
}
return VisitResult(TypeOracle::GetConstexprBoolType(),
std::string("(") + left_result.constexpr_value() +
" || " + right_result.constexpr_value() + ")");
}
Block* true_block = assembler().NewBlock();
Block* false_block = assembler().NewBlock();
Block* done_block = assembler().NewBlock();
left_result = GenerateImplicitConvert(TypeOracle::GetBoolType(), left_result);
GenerateBranch(left_result, true_block, false_block);
assembler().Bind(true_block);
VisitResult true_result = GenerateBoolConstant(true);
assembler().Goto(done_block);
assembler().Bind(false_block);
VisitResult false_result;
{
StackScope false_block_scope(this);
false_result = false_block_scope.Yield(
GenerateImplicitConvert(TypeOracle::GetBoolType(), Visit(expr->right)));
}
assembler().Goto(done_block);
assembler().Bind(done_block);
DCHECK_EQ(true_result, false_result);
return outer_scope.Yield(true_result);
}
VisitResult ImplementationVisitor::Visit(LogicalAndExpression* expr) {
StackScope outer_scope(this);
VisitResult left_result = Visit(expr->left);
if (left_result.type()->IsConstexprBool()) {
VisitResult right_result = Visit(expr->right);
if (!right_result.type()->IsConstexprBool()) {
ReportError(
"expected type constexpr bool on right-hand side of operator "
"&&");
}
return VisitResult(TypeOracle::GetConstexprBoolType(),
std::string("(") + left_result.constexpr_value() +
" && " + right_result.constexpr_value() + ")");
}
Block* true_block = assembler().NewBlock();
Block* false_block = assembler().NewBlock();
Block* done_block = assembler().NewBlock();
left_result = GenerateImplicitConvert(TypeOracle::GetBoolType(), left_result);
GenerateBranch(left_result, true_block, false_block);
assembler().Bind(true_block);
VisitResult true_result;
{
StackScope true_block_scope(this);
VisitResult right_result = Visit(expr->right);
if (TryGetSourceForBitfieldExpression(expr->left) != nullptr &&
TryGetSourceForBitfieldExpression(expr->right) != nullptr &&
TryGetSourceForBitfieldExpression(expr->left)->value ==
TryGetSourceForBitfieldExpression(expr->right)->value) {
Lint(
"Please use & rather than && when checking multiple bitfield "
"values, to avoid complexity in generated code.");
}
true_result = true_block_scope.Yield(
GenerateImplicitConvert(TypeOracle::GetBoolType(), right_result));
}
assembler().Goto(done_block);
assembler().Bind(false_block);
VisitResult false_result = GenerateBoolConstant(false);
assembler().Goto(done_block);
assembler().Bind(done_block);
DCHECK_EQ(true_result, false_result);
return outer_scope.Yield(true_result);
}
VisitResult ImplementationVisitor::Visit(IncrementDecrementExpression* expr) {
StackScope scope(this);
LocationReference location_ref = GetLocationReference(expr->location);
VisitResult current_value = GenerateFetchFromLocation(location_ref);
VisitResult one = {TypeOracle::GetConstInt31Type(), "1"};
Arguments args;
args.parameters = {current_value, one};
VisitResult assignment_value = GenerateCall(
expr->op == IncrementDecrementOperator::kIncrement ? "+" : "-", args);
GenerateAssignToLocation(location_ref, assignment_value);
return scope.Yield(expr->postfix ? current_value : assignment_value);
}
VisitResult ImplementationVisitor::Visit(AssignmentExpression* expr) {
StackScope scope(this);
LocationReference location_ref = GetLocationReference(expr->location);
VisitResult assignment_value;
if (expr->op) {
VisitResult location_value = GenerateFetchFromLocation(location_ref);
assignment_value = Visit(expr->value);
Arguments args;
args.parameters = {location_value, assignment_value};
assignment_value = GenerateCall(*expr->op, args);
GenerateAssignToLocation(location_ref, assignment_value);
} else {
assignment_value = Visit(expr->value);
GenerateAssignToLocation(location_ref, assignment_value);
}
return scope.Yield(assignment_value);
}
VisitResult ImplementationVisitor::Visit(NumberLiteralExpression* expr) {
const Type* result_type = TypeOracle::GetConstFloat64Type();
if (expr->number >= std::numeric_limits<int32_t>::min() &&
expr->number <= std::numeric_limits<int32_t>::max()) {
int32_t i = static_cast<int32_t>(expr->number);
if (i == expr->number) {
if ((i >> 30) == (i >> 31)) {
result_type = TypeOracle::GetConstInt31Type();
} else {
result_type = TypeOracle::GetConstInt32Type();
}
}
}
std::stringstream str;
str << std::setprecision(std::numeric_limits<double>::digits10 + 1)
<< expr->number;
return VisitResult{result_type, str.str()};
}
VisitResult ImplementationVisitor::Visit(AssumeTypeImpossibleExpression* expr) {
VisitResult result = Visit(expr->expression);
const Type* result_type = SubtractType(
result.type(), TypeVisitor::ComputeType(expr->excluded_type));
if (result_type->IsNever()) {
ReportError("unreachable code");
}
CHECK_EQ(LowerType(result_type), TypeVector{result_type});
assembler().Emit(UnsafeCastInstruction{result_type});
result.SetType(result_type);
return result;
}
VisitResult ImplementationVisitor::Visit(StringLiteralExpression* expr) {
return VisitResult{
TypeOracle::GetConstStringType(),
"\"" + expr->literal.substr(1, expr->literal.size() - 2) + "\""};
}
VisitResult ImplementationVisitor::GetBuiltinCode(Builtin* builtin) {
if (builtin->IsExternal() || builtin->kind() != Builtin::kStub) {
ReportError(
"creating function pointers is only allowed for internal builtins with "
"stub linkage");
}
const Type* type = TypeOracle::GetBuiltinPointerType(
builtin->signature().parameter_types.types,
builtin->signature().return_type);
assembler().Emit(
PushBuiltinPointerInstruction{builtin->ExternalName(), type});
return VisitResult(type, assembler().TopRange(1));
}
VisitResult ImplementationVisitor::Visit(LocationExpression* expr) {
StackScope scope(this);
return scope.Yield(GenerateFetchFromLocation(GetLocationReference(expr)));
}
VisitResult ImplementationVisitor::Visit(FieldAccessExpression* expr) {
StackScope scope(this);
LocationReference location = GetLocationReference(expr);
if (location.IsBitFieldAccess()) {
if (auto* identifier = IdentifierExpression::DynamicCast(expr->object)) {
bitfield_expressions_[expr] = identifier->name;
}
}
return scope.Yield(GenerateFetchFromLocation(location));
}
const Type* ImplementationVisitor::Visit(GotoStatement* stmt) {
Binding<LocalLabel>* label = LookupLabel(stmt->label->value);
size_t parameter_count = label->parameter_types.size();
if (stmt->arguments.size() != parameter_count) {
ReportError("goto to label has incorrect number of parameters (expected ",
parameter_count, " found ", stmt->arguments.size(), ")");
}
if (GlobalContext::collect_language_server_data()) {
LanguageServerData::AddDefinition(stmt->label->pos,
label->declaration_position());
}
size_t i = 0;
StackRange arguments = assembler().TopRange(0);
for (Expression* e : stmt->arguments) {
StackScope scope(this);
VisitResult result = Visit(e);
const Type* parameter_type = label->parameter_types[i++];
result = GenerateImplicitConvert(parameter_type, result);
arguments.Extend(scope.Yield(result).stack_range());
}
assembler().Goto(label->block, arguments.Size());
return TypeOracle::GetNeverType();
}
const Type* ImplementationVisitor::Visit(IfStatement* stmt) {
bool has_else = stmt->if_false.has_value();
if (stmt->is_constexpr) {
VisitResult expression_result = Visit(stmt->condition);
if (!(expression_result.type() == TypeOracle::GetConstexprBoolType())) {
std::stringstream stream;
stream << "expression should return type constexpr bool "
<< "but returns type " << *expression_result.type();
ReportError(stream.str());
}
Block* true_block = assembler().NewBlock();
Block* false_block = assembler().NewBlock();
Block* done_block = assembler().NewBlock();
assembler().Emit(ConstexprBranchInstruction{
expression_result.constexpr_value(), true_block, false_block});
assembler().Bind(true_block);
const Type* left_result = Visit(stmt->if_true);
if (left_result == TypeOracle::GetVoidType()) {
assembler().Goto(done_block);
}
assembler().Bind(false_block);
const Type* right_result = TypeOracle::GetVoidType();
if (has_else) {
right_result = Visit(*stmt->if_false);
}
if (right_result == TypeOracle::GetVoidType()) {
assembler().Goto(done_block);
}
if (left_result->IsNever() != right_result->IsNever()) {
std::stringstream stream;
stream << "either both or neither branches in a constexpr if statement "
"must reach their end at"
<< PositionAsString(stmt->pos);
ReportError(stream.str());
}
if (left_result != TypeOracle::GetNeverType()) {
assembler().Bind(done_block);
}
return left_result;
} else {
Block* true_block = assembler().NewBlock(assembler().CurrentStack(),
IsDeferred(stmt->if_true));
Block* false_block =
assembler().NewBlock(assembler().CurrentStack(),
stmt->if_false && IsDeferred(*stmt->if_false));
GenerateExpressionBranch(stmt->condition, true_block, false_block);
Block* done_block;
bool live = false;
if (has_else) {
done_block = assembler().NewBlock();
} else {
done_block = false_block;
live = true;
}
assembler().Bind(true_block);
{
const Type* result = Visit(stmt->if_true);
if (result == TypeOracle::GetVoidType()) {
live = true;
assembler().Goto(done_block);
}
}
if (has_else) {
assembler().Bind(false_block);
const Type* result = Visit(*stmt->if_false);
if (result == TypeOracle::GetVoidType()) {
live = true;
assembler().Goto(done_block);
}
}
if (live) {
assembler().Bind(done_block);
}
return live ? TypeOracle::GetVoidType() : TypeOracle::GetNeverType();
}
}
const Type* ImplementationVisitor::Visit(WhileStatement* stmt) {
Block* body_block = assembler().NewBlock(assembler().CurrentStack());
Block* exit_block = assembler().NewBlock(assembler().CurrentStack());
Block* header_block = assembler().NewBlock();
assembler().Goto(header_block);
assembler().Bind(header_block);
GenerateExpressionBranch(stmt->condition, body_block, exit_block);
assembler().Bind(body_block);
{
BreakContinueActivator activator{exit_block, header_block};
const Type* body_result = Visit(stmt->body);
if (body_result != TypeOracle::GetNeverType()) {
assembler().Goto(header_block);
}
}
assembler().Bind(exit_block);
return TypeOracle::GetVoidType();
}
const Type* ImplementationVisitor::Visit(BlockStatement* block) {
BlockBindings<LocalValue> block_bindings(&ValueBindingsManager::Get());
const Type* type = TypeOracle::GetVoidType();
for (Statement* s : block->statements) {
CurrentSourcePosition::Scope source_position(s->pos);
if (type->IsNever()) {
ReportError("statement after non-returning statement");
}
if (auto* var_declaration = VarDeclarationStatement::DynamicCast(s)) {
type = Visit(var_declaration, &block_bindings);
} else {
type = Visit(s);
}
}
return type;
}
const Type* ImplementationVisitor::Visit(DebugStatement* stmt) {
#if defined(DEBUG)
assembler().Emit(PrintConstantStringInstruction{"halting because of '" +
stmt->reason + "' at " +
PositionAsString(stmt->pos)});
#endif
assembler().Emit(AbortInstruction{stmt->never_continues
? AbortInstruction::Kind::kUnreachable
: AbortInstruction::Kind::kDebugBreak});
if (stmt->never_continues) {
return TypeOracle::GetNeverType();
} else {
return TypeOracle::GetVoidType();
}
}
namespace {
std::string FormatAssertSource(const std::string& str) {
// Replace all whitespace characters with a space character.
std::string str_no_newlines = str;
std::replace_if(
str_no_newlines.begin(), str_no_newlines.end(),
[](unsigned char c) { return isspace(c); }, ' ');
// str might include indentation, squash multiple space characters into one.
std::string result;
std::unique_copy(str_no_newlines.begin(), str_no_newlines.end(),
std::back_inserter(result),
[](char a, char b) { return a == ' ' && b == ' '; });
return result;
}
} // namespace
const Type* ImplementationVisitor::Visit(AssertStatement* stmt) {
if (stmt->kind == AssertStatement::AssertKind::kStaticAssert) {
std::string message =
"static_assert(" + stmt->source + ") at " + ToString(stmt->pos);
GenerateCall(QualifiedName({"", TORQUE_INTERNAL_NAMESPACE_STRING},
STATIC_ASSERT_MACRO_STRING),
Arguments{{Visit(stmt->expression),
VisitResult(TypeOracle::GetConstexprStringType(),
StringLiteralQuote(message))},
{}});
return TypeOracle::GetVoidType();
}
bool do_check = stmt->kind != AssertStatement::AssertKind::kAssert ||
GlobalContext::force_assert_statements();
#if defined(DEBUG)
do_check = true;
#endif
Block* resume_block;
if (!do_check) {
Block* unreachable_block = assembler().NewBlock(assembler().CurrentStack());
resume_block = assembler().NewBlock(assembler().CurrentStack());
assembler().Goto(resume_block);
assembler().Bind(unreachable_block);
}
// CSA_ASSERT & co. are not used here on purpose for two reasons. First,
// Torque allows and handles two types of expressions in the if protocol
// automagically, ones that return TNode<BoolT> and those that use the
// BranchIf(..., Label* true, Label* false) idiom. Because the machinery to
// handle this is embedded in the expression handling and to it's not
// possible to make the decision to use CSA_ASSERT or CSA_ASSERT_BRANCH
// isn't trivial up-front. Secondly, on failure, the assert text should be
// the corresponding Torque code, not the -gen.cc code, which would be the
// case when using CSA_ASSERT_XXX.
Block* true_block = assembler().NewBlock(assembler().CurrentStack());
Block* false_block = assembler().NewBlock(assembler().CurrentStack(), true);
GenerateExpressionBranch(stmt->expression, true_block, false_block);
assembler().Bind(false_block);
assembler().Emit(AbortInstruction{
AbortInstruction::Kind::kAssertionFailure,
"Torque assert '" + FormatAssertSource(stmt->source) + "' failed"});
assembler().Bind(true_block);
if (!do_check) {
assembler().Bind(resume_block);
}
return TypeOracle::GetVoidType();
}
const Type* ImplementationVisitor::Visit(ExpressionStatement* stmt) {
const Type* type = Visit(stmt->expression).type();
return type->IsNever() ? type : TypeOracle::GetVoidType();
}
const Type* ImplementationVisitor::Visit(ReturnStatement* stmt) {
Callable* current_callable = CurrentCallable::Get();
if (current_callable->signature().return_type->IsNever()) {
std::stringstream s;
s << "cannot return from a function with return type never";
ReportError(s.str());
}
LocalLabel* end =
current_callable->IsMacro() ? LookupLabel(kMacroEndLabelName) : nullptr;
if (current_callable->HasReturnValue()) {
if (!stmt->value) {
std::stringstream s;
s << "return expression needs to be specified for a return type of "
<< *current_callable->signature().return_type;
ReportError(s.str());
}
VisitResult expression_result = Visit(*stmt->value);
VisitResult return_result = GenerateImplicitConvert(
current_callable->signature().return_type, expression_result);
if (current_callable->IsMacro()) {
if (return_result.IsOnStack()) {
StackRange return_value_range =
GenerateLabelGoto(end, return_result.stack_range());
SetReturnValue(VisitResult(return_result.type(), return_value_range));
} else {
GenerateLabelGoto(end);
SetReturnValue(return_result);
}
} else if (current_callable->IsBuiltin()) {
assembler().Emit(ReturnInstruction{});
} else {
UNREACHABLE();
}
} else {
if (stmt->value) {
std::stringstream s;
s << "return expression can't be specified for a void or never return "
"type";
ReportError(s.str());
}
GenerateLabelGoto(end);
}
current_callable->IncrementReturns();
return TypeOracle::GetNeverType();
}
VisitResult ImplementationVisitor::Visit(TryLabelExpression* expr) {
size_t parameter_count = expr->label_block->parameters.names.size();
std::vector<VisitResult> parameters;
Block* label_block = nullptr;
Block* done_block = assembler().NewBlock();
VisitResult try_result;
{
CurrentSourcePosition::Scope source_position(expr->label_block->pos);
if (expr->label_block->parameters.has_varargs) {
ReportError("cannot use ... for label parameters");
}
Stack<const Type*> label_input_stack = assembler().CurrentStack();
TypeVector parameter_types;
for (size_t i = 0; i < parameter_count; ++i) {
const Type* type =
TypeVisitor::ComputeType(expr->label_block->parameters.types[i]);
parameter_types.push_back(type);
if (type->IsConstexpr()) {
ReportError("no constexpr type allowed for label arguments");
}
StackRange range = label_input_stack.PushMany(LowerType(type));
parameters.push_back(VisitResult(type, range));
}
label_block = assembler().NewBlock(label_input_stack,
IsDeferred(expr->label_block->body));
Binding<LocalLabel> label_binding{&LabelBindingsManager::Get(),
expr->label_block->label,
LocalLabel{label_block, parameter_types}};
// Visit try
StackScope stack_scope(this);
try_result = Visit(expr->try_expression);
if (try_result.type() != TypeOracle::GetNeverType()) {
try_result = stack_scope.Yield(try_result);
assembler().Goto(done_block);
}
}
// Visit and output the code for the label block. If the label block falls
// through, then the try must not return a value. Also, if the try doesn't
// fall through, but the label does, then overall the try-label block
// returns type void.
assembler().Bind(label_block);
const Type* label_result;
{
BlockBindings<LocalValue> parameter_bindings(&ValueBindingsManager::Get());
for (size_t i = 0; i < parameter_count; ++i) {
Identifier* name = expr->label_block->parameters.names[i];
parameter_bindings.Add(name,
LocalValue{LocationReference::Temporary(
parameters[i], "parameter " + name->value)});
}
label_result = Visit(expr->label_block->body);
}
if (!try_result.type()->IsVoidOrNever() && label_result->IsVoid()) {
ReportError(
"otherwise clauses cannot fall through in a non-void expression");
}
if (label_result != TypeOracle::GetNeverType()) {
assembler().Goto(done_block);
}
if (label_result->IsVoid() && try_result.type()->IsNever()) {
try_result =
VisitResult(TypeOracle::GetVoidType(), try_result.stack_range());
}
if (!try_result.type()->IsNever()) {
assembler().Bind(done_block);
}
return try_result;
}
VisitResult ImplementationVisitor::Visit(StatementExpression* expr) {
return VisitResult{Visit(expr->statement), assembler().TopRange(0)};
}
InitializerResults ImplementationVisitor::VisitInitializerResults(
const ClassType* class_type,
const std::vector<NameAndExpression>& initializers) {
InitializerResults result;
for (const NameAndExpression& initializer : initializers) {
result.names.push_back(initializer.name);
Expression* e = initializer.expression;
const Field& field = class_type->LookupField(initializer.name->value);
bool has_index = field.index.has_value();
if (SpreadExpression* s = SpreadExpression::DynamicCast(e)) {
if (!has_index) {
ReportError(
"spread expressions can only be used to initialize indexed class "
"fields ('",
initializer.name->value, "' is not)");
}
e = s->spreadee;
} else if (has_index) {
ReportError("the indexed class field '", initializer.name->value,
"' must be initialized with a spread operator");
}
result.field_value_map[field.name_and_type.name] = Visit(e);
}
return result;
}
LocationReference ImplementationVisitor::GenerateFieldReference(
VisitResult object, const Field& field, const ClassType* class_type) {
if (field.index.has_value()) {
return LocationReference::HeapSlice(
GenerateCall(class_type->GetSliceMacroName(field), {{object}, {}}));
}
DCHECK(field.offset.has_value());
StackRange result_range = assembler().TopRange(0);
result_range.Extend(GenerateCopy(object).stack_range());
VisitResult offset =
VisitResult(TypeOracle::GetConstInt31Type(), ToString(*field.offset));
offset = GenerateImplicitConvert(TypeOracle::GetIntPtrType(), offset);
result_range.Extend(offset.stack_range());
const Type* type = TypeOracle::GetReferenceType(field.name_and_type.type,
field.const_qualified);
return LocationReference::HeapReference(VisitResult(type, result_range));
}
// This is used to generate field references during initialization, where we can
// re-use the offsets used for computing the allocation size.
LocationReference ImplementationVisitor::GenerateFieldReferenceForInit(
VisitResult object, const Field& field,
const LayoutForInitialization& layout) {
StackRange result_range = assembler().TopRange(0);
result_range.Extend(GenerateCopy(object).stack_range());
VisitResult offset = GenerateImplicitConvert(
TypeOracle::GetIntPtrType(), layout.offsets.at(field.name_and_type.name));
result_range.Extend(offset.stack_range());
if (field.index) {
VisitResult length =
GenerateCopy(layout.array_lengths.at(field.name_and_type.name));
result_range.Extend(length.stack_range());
const Type* slice_type = TypeOracle::GetSliceType(field.name_and_type.type);
return LocationReference::HeapSlice(VisitResult(slice_type, result_range));
} else {
// Const fields are writable during initialization.
VisitResult heap_reference(
TypeOracle::GetMutableReferenceType(field.name_and_type.type),
result_range);
return LocationReference::HeapReference(heap_reference);
}
}
void ImplementationVisitor::InitializeClass(
const ClassType* class_type, VisitResult allocate_result,
const InitializerResults& initializer_results,
const LayoutForInitialization& layout) {
if (const ClassType* super = class_type->GetSuperClass()) {
InitializeClass(super, allocate_result, initializer_results, layout);
}
for (Field f : class_type->fields()) {
VisitResult initializer_value =
initializer_results.field_value_map.at(f.name_and_type.name);
LocationReference field =
GenerateFieldReferenceForInit(allocate_result, f, layout);
if (f.index) {
DCHECK(field.IsHeapSlice());
VisitResult slice = field.GetVisitResult();
GenerateCall(QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING},
"InitializeFieldsFromIterator"),
{{slice, initializer_value}, {}});
} else {
GenerateAssignToLocation(field, initializer_value);
}
}
}
VisitResult ImplementationVisitor::GenerateArrayLength(
Expression* array_length, Namespace* nspace,
const std::map<std::string, LocalValue>& bindings) {
StackScope stack_scope(this);
CurrentSourcePosition::Scope pos_scope(array_length->pos);
// Switch to the namespace where the class was declared.
CurrentScope::Scope current_scope_scope(nspace);
// Reset local bindings and install local binding for the preceding fields.
BindingsManagersScope bindings_managers_scope;
BlockBindings<LocalValue> field_bindings(&ValueBindingsManager::Get());
for (auto& p : bindings) {
field_bindings.Add(p.first, LocalValue{p.second}, true);
}
VisitResult length = Visit(array_length);
VisitResult converted_length =
GenerateCall("Convert", Arguments{{length}, {}},
{TypeOracle::GetIntPtrType(), length.type()}, false);
return stack_scope.Yield(converted_length);
}
VisitResult ImplementationVisitor::GenerateArrayLength(VisitResult object,
const Field& field) {
DCHECK(field.index);
StackScope stack_scope(this);
const ClassType* class_type = *object.type()->ClassSupertype();
std::map<std::string, LocalValue> bindings;
bool before_current = true;
for (Field f : class_type->ComputeAllFields()) {
if (field.name_and_type.name == f.name_and_type.name) {
before_current = false;
}
bindings.insert(
{f.name_and_type.name,
f.const_qualified
? (before_current
? LocalValue{GenerateFieldReference(object, f, class_type)}
: LocalValue("Array lengths may only refer to fields "
"defined earlier"))
: LocalValue(
"Non-const fields cannot be used for array lengths.")});
}
return stack_scope.Yield(
GenerateArrayLength(*field.index, class_type->nspace(), bindings));
}
VisitResult ImplementationVisitor::GenerateArrayLength(
const ClassType* class_type, const InitializerResults& initializer_results,
const Field& field) {
DCHECK(field.index);
StackScope stack_scope(this);
std::map<std::string, LocalValue> bindings;
for (Field f : class_type->ComputeAllFields()) {
if (f.index) break;
const std::string& fieldname = f.name_and_type.name;
VisitResult value = initializer_results.field_value_map.at(fieldname);
bindings.insert(
{fieldname,
f.const_qualified
? LocalValue{LocationReference::Temporary(
value, "initial field " + fieldname)}
: LocalValue(
"Non-const fields cannot be used for array lengths.")});
}
return stack_scope.Yield(
GenerateArrayLength(*field.index, class_type->nspace(), bindings));
}
LayoutForInitialization ImplementationVisitor::GenerateLayoutForInitialization(
const ClassType* class_type,
const InitializerResults& initializer_results) {
LayoutForInitialization layout;
VisitResult offset;
for (Field f : class_type->ComputeAllFields()) {
if (f.offset.has_value()) {
offset =
VisitResult(TypeOracle::GetConstInt31Type(), ToString(*f.offset));
}
layout.offsets[f.name_and_type.name] = offset;
if (f.index) {
size_t element_size;
std::string element_size_string;
std::tie(element_size, element_size_string) =
*SizeOf(f.name_and_type.type);
VisitResult array_element_size =
VisitResult(TypeOracle::GetConstInt31Type(), element_size_string);
VisitResult array_length =
GenerateArrayLength(class_type, initializer_results, f);
layout.array_lengths[f.name_and_type.name] = array_length;
Arguments arguments;
arguments.parameters = {offset, array_length, array_element_size};
offset = GenerateCall(QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING},
"AddIndexedFieldSizeToObjectSize"),
arguments);
} else {
DCHECK(f.offset.has_value());
}
}
if (class_type->size().SingleValue()) {
layout.size = VisitResult(TypeOracle::GetConstInt31Type(),
ToString(*class_type->size().SingleValue()));
} else {
layout.size = offset;
}
if ((size_t{1} << class_type->size().AlignmentLog2()) <
TargetArchitecture::TaggedSize()) {
Arguments arguments;
arguments.parameters = {layout.size};
layout.size = GenerateCall(
QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING}, "AlignTagged"),
arguments);
}
return layout;
}
VisitResult ImplementationVisitor::Visit(NewExpression* expr) {
StackScope stack_scope(this);
const Type* type = TypeVisitor::ComputeType(expr->type);
const ClassType* class_type = ClassType::DynamicCast(type);
if (class_type == nullptr) {
ReportError("type for new expression must be a class, \"", *type,
"\" is not");
}
if (!class_type->AllowInstantiation()) {
// Classes that are only used for testing should never be instantiated.
ReportError(*class_type,
" cannot be allocated with new (it's used for testing)");
}
InitializerResults initializer_results =
VisitInitializerResults(class_type, expr->initializers);
const Field& map_field = class_type->LookupField("map");
if (*map_field.offset != 0) {
ReportError("class initializers must have a map as first parameter");
}
const std::map<std::string, VisitResult>& initializer_fields =
initializer_results.field_value_map;
auto it_object_map = initializer_fields.find(map_field.name_and_type.name);
VisitResult object_map;
if (class_type->IsExtern()) {
if (it_object_map == initializer_fields.end()) {
ReportError("Constructor for ", class_type->name(),
" needs Map argument!");
}
object_map = it_object_map->second;
} else {
if (it_object_map != initializer_fields.end()) {
ReportError(
"Constructor for ", class_type->name(),
" must not specify Map argument; it is automatically inserted.");
}
Arguments get_struct_map_arguments;
get_struct_map_arguments.parameters.push_back(
VisitResult(TypeOracle::GetConstexprInstanceTypeType(),
CapifyStringWithUnderscores(class_type->name()) + "_TYPE"));
object_map = GenerateCall(
QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING}, "GetInstanceTypeMap"),
get_struct_map_arguments, {}, false);
CurrentSourcePosition::Scope current_pos(expr->pos);
initializer_results.names.insert(initializer_results.names.begin(),
MakeNode<Identifier>("map"));
initializer_results.field_value_map[map_field.name_and_type.name] =
object_map;
}
CheckInitializersWellformed(class_type->name(),
class_type->ComputeAllFields(),
expr->initializers, !class_type->IsExtern());
LayoutForInitialization layout =
GenerateLayoutForInitialization(class_type, initializer_results);
Arguments allocate_arguments;
allocate_arguments.parameters.push_back(layout.size);
allocate_arguments.parameters.push_back(object_map);
allocate_arguments.parameters.push_back(
GenerateBoolConstant(expr->pretenured));
VisitResult allocate_result = GenerateCall(
QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING}, "AllocateFromNew"),
allocate_arguments, {class_type}, false);
DCHECK(allocate_result.IsOnStack());
InitializeClass(class_type, allocate_result, initializer_results, layout);
return stack_scope.Yield(GenerateCall(
"%RawDownCast", Arguments{{allocate_result}, {}}, {class_type}));
}
const Type* ImplementationVisitor::Visit(BreakStatement* stmt) {
base::Optional<Binding<LocalLabel>*> break_label =
TryLookupLabel(kBreakLabelName);
if (!break_label) {
ReportError("break used outside of loop");
}
assembler().Goto((*break_label)->block);
return TypeOracle::GetNeverType();
}
const Type* ImplementationVisitor::Visit(ContinueStatement* stmt) {
base::Optional<Binding<LocalLabel>*> continue_label =
TryLookupLabel(kContinueLabelName);
if (!continue_label) {
ReportError("continue used outside of loop");
}
assembler().Goto((*continue_label)->block);
return TypeOracle::GetNeverType();
}
const Type* ImplementationVisitor::Visit(ForLoopStatement* stmt) {
BlockBindings<LocalValue> loop_bindings(&ValueBindingsManager::Get());
if (stmt->var_declaration) Visit(*stmt->var_declaration, &loop_bindings);
Block* body_block = assembler().NewBlock(assembler().CurrentStack());
Block* exit_block = assembler().NewBlock(assembler().CurrentStack());
Block* header_block = assembler().NewBlock();
assembler().Goto(header_block);
assembler().Bind(header_block);
// The continue label is where "continue" statements jump to. If no action
// expression is provided, we jump directly to the header.
Block* continue_block = header_block;
// The action label is only needed when an action expression was provided.
Block* action_block = nullptr;
if (stmt->action) {
action_block = assembler().NewBlock();
// The action expression needs to be executed on a continue.
continue_block = action_block;
}
if (stmt->test) {
GenerateExpressionBranch(*stmt->test, body_block, exit_block);
} else {
assembler().Goto(body_block);
}
assembler().Bind(body_block);
{
BreakContinueActivator activator(exit_block, continue_block);
const Type* body_result = Visit(stmt->body);
if (body_result != TypeOracle::GetNeverType()) {
assembler().Goto(continue_block);
}
}
if (stmt->action) {
assembler().Bind(action_block);
const Type* action_result = Visit(*stmt->action);
if (action_result != TypeOracle::GetNeverType()) {
assembler().Goto(header_block);
}
}
assembler().Bind(exit_block);
return TypeOracle::GetVoidType();
}
VisitResult ImplementationVisitor::Visit(SpreadExpression* expr) {
ReportError(
"spread operators are only currently supported in indexed class field "
"initialization expressions");
}
void ImplementationVisitor::GenerateImplementation(const std::string& dir) {
for (SourceId file : SourceFileMap::AllSources()) {
std::string base_filename =
dir + "/" + SourceFileMap::PathFromV8RootWithoutExtension(file);
GlobalContext::PerFileStreams& streams =
GlobalContext::GeneratedPerFile(file);
WriteFile(base_filename + "-tq-csa.cc", streams.csa_ccfile.str());
WriteFile(base_filename + "-tq-csa.h", streams.csa_headerfile.str());
WriteFile(base_filename + "-tq.inc",
streams.class_definition_headerfile.str());
WriteFile(base_filename + "-tq-inl.inc",
streams.class_definition_inline_headerfile.str());
WriteFile(base_filename + "-tq.cc", streams.class_definition_ccfile.str());
}
WriteFile(dir + "/runtime-macros.h", runtime_macros_h_.str());
WriteFile(dir + "/runtime-macros.cc", runtime_macros_cc_.str());
}
void ImplementationVisitor::GenerateMacroFunctionDeclaration(std::ostream& o,
Macro* macro) {
GenerateFunctionDeclaration(
o, "",
output_type_ == OutputType::kCC ? macro->CCName() : macro->ExternalName(),
macro->signature(), macro->parameter_names());
}
std::vector<std::string> ImplementationVisitor::GenerateFunctionDeclaration(
std::ostream& o, const std::string& macro_prefix, const std::string& name,
const Signature& signature, const NameVector& parameter_names,
bool pass_code_assembler_state) {
std::vector<std::string> generated_parameter_names;
if (signature.return_type->IsVoidOrNever()) {
o << "void";
} else {
o << (output_type_ == OutputType::kCC
? signature.return_type->GetRuntimeType()
: signature.return_type->GetGeneratedTypeName());
}
o << " " << macro_prefix << name << "(";
bool first = true;
if (output_type_ == OutputType::kCC) {
first = false;
o << "Isolate* isolate";
} else if (pass_code_assembler_state) {
first = false;
o << "compiler::CodeAssemblerState* state_";
}
DCHECK_GE(signature.types().size(), parameter_names.size());
for (size_t i = 0; i < signature.types().size(); ++i) {
if (!first) o << ", ";
first = false;
const Type* parameter_type = signature.types()[i];
const std::string& generated_type_name =
output_type_ == OutputType::kCC
? parameter_type->GetRuntimeType()
: parameter_type->GetGeneratedTypeName();
generated_parameter_names.push_back(ExternalParameterName(
i < parameter_names.size() ? parameter_names[i]->value
: std::to_string(i)));
o << generated_type_name << " " << generated_parameter_names.back();
}
for (const LabelDeclaration& label_info : signature.labels) {
if (output_type_ == OutputType::kCC) {
ReportError("Macros that generate runtime code can't have label exits");
}
if (!first) o << ", ";
first = false;
generated_parameter_names.push_back(
ExternalLabelName(label_info.name->value));
o << "compiler::CodeAssemblerLabel* " << generated_parameter_names.back();
size_t i = 0;
for (const Type* type : label_info.types) {
std::string generated_type_name;
if (type->StructSupertype()) {
generated_type_name = "\n#error no structs allowed in labels\n";
} else {
generated_type_name = "compiler::TypedCodeAssemblerVariable<";
generated_type_name += type->GetGeneratedTNodeTypeName();
generated_type_name += ">*";
}
o << ", ";
generated_parameter_names.push_back(
ExternalLabelParameterName(label_info.name->value, i));
o << generated_type_name << " " << generated_parameter_names.back();
++i;
}
}
o << ")";
return generated_parameter_names;
}
namespace {
void FailCallableLookup(
const std::string& reason, const QualifiedName& name,
const TypeVector& parameter_types,
const std::vector<Binding<LocalLabel>*>& labels,
const std::vector<Signature>& candidates,
const std::vector<std::pair<GenericCallable*, std::string>>
inapplicable_generics) {
std::stringstream stream;
stream << "\n" << reason << ": \n " << name << "(" << parameter_types << ")";
if (labels.size() != 0) {
stream << " labels ";
for (size_t i = 0; i < labels.size(); ++i) {
stream << labels[i]->name() << "(" << labels[i]->parameter_types << ")";
}
}
stream << "\ncandidates are:";
for (const Signature& signature : candidates) {
stream << "\n " << name;
PrintSignature(stream, signature, false);
}
if (inapplicable_generics.size() != 0) {
stream << "\nfailed to instantiate all of these generic declarations:";
for (auto& failure : inapplicable_generics) {
GenericCallable* generic = failure.first;
const std::string& reason = failure.second;
stream << "\n " << generic->name() << " defined at "
<< generic->Position() << ":\n " << reason << "\n";
}
}
ReportError(stream.str());
}
Callable* GetOrCreateSpecialization(
const SpecializationKey<GenericCallable>& key) {
if (base::Optional<Callable*> specialization =
key.generic->GetSpecialization(key.specialized_types)) {
return *specialization;
}
return DeclarationVisitor::SpecializeImplicit(key);
}
} // namespace
base::Optional<Binding<LocalValue>*> ImplementationVisitor::TryLookupLocalValue(
const std::string& name) {
return ValueBindingsManager::Get().TryLookup(name);
}
base::Optional<Binding<LocalLabel>*> ImplementationVisitor::TryLookupLabel(
const std::string& name) {
return LabelBindingsManager::Get().TryLookup(name);
}
Binding<LocalLabel>* ImplementationVisitor::LookupLabel(
const std::string& name) {
base::Optional<Binding<LocalLabel>*> label = TryLookupLabel(name);
if (!label) ReportError("cannot find label ", name);
return *label;
}
Block* ImplementationVisitor::LookupSimpleLabel(const std::string& name) {
LocalLabel* label = LookupLabel(name);
if (!label->parameter_types.empty()) {
ReportError("label ", name,
"was expected to have no parameters, but has parameters (",
label->parameter_types, ")");
}
return label->block;
}
// Try to lookup a callable with the provided argument types. Do not report
// an error if no matching callable was found, but return false instead.
// This is used to test the presence of overloaded field accessors.
bool ImplementationVisitor::TestLookupCallable(
const QualifiedName& name, const TypeVector& parameter_types) {
return LookupCallable(name, Declarations::TryLookup(name), parameter_types,
{}, {}, true) != nullptr;
}
TypeArgumentInference ImplementationVisitor::InferSpecializationTypes(
GenericCallable* generic, const TypeVector& explicit_specialization_types,
const TypeVector& explicit_arguments) {
std::vector<base::Optional<const Type*>> all_arguments;
const ParameterList& parameters = generic->declaration()->parameters;
for (size_t i = 0; i < parameters.implicit_count; ++i) {
base::Optional<Binding<LocalValue>*> val =
TryLookupLocalValue(parameters.names[i]->value);
all_arguments.push_back(
val ? (*val)->GetLocationReference(*val).ReferencedType()
: base::nullopt);
}
for (const Type* explicit_argument : explicit_arguments) {
all_arguments.push_back(explicit_argument);
}
return generic->InferSpecializationTypes(explicit_specialization_types,
all_arguments);
}
template <class Container>
Callable* ImplementationVisitor::LookupCallable(
const QualifiedName& name, const Container& declaration_container,
const TypeVector& parameter_types,
const std::vector<Binding<LocalLabel>*>& labels,
const TypeVector& specialization_types, bool silence_errors) {
Callable* result = nullptr;
std::vector<Declarable*> overloads;
std::vector<Signature> overload_signatures;
std::vector<std::pair<GenericCallable*, std::string>> inapplicable_generics;
for (auto* declarable : declaration_container) {
if (GenericCallable* generic = GenericCallable::DynamicCast(declarable)) {
TypeArgumentInference inference = InferSpecializationTypes(
generic, specialization_types, parameter_types);
if (inference.HasFailed()) {
inapplicable_generics.push_back(
std::make_pair(generic, inference.GetFailureReason()));
continue;
}
overloads.push_back(generic);
overload_signatures.push_back(
DeclarationVisitor::MakeSpecializedSignature(
SpecializationKey<GenericCallable>{generic,
inference.GetResult()}));
} else if (Callable* callable = Callable::DynamicCast(declarable)) {
overloads.push_back(callable);
overload_signatures.push_back(callable->signature());
}
}
// Indices of candidates in overloads/overload_signatures.
std::vector<size_t> candidates;
for (size_t i = 0; i < overloads.size(); ++i) {
const Signature& signature = overload_signatures[i];
if (IsCompatibleSignature(signature, parameter_types, labels.size())) {
candidates.push_back(i);
}
}
if (overloads.empty() && inapplicable_generics.empty()) {
if (silence_errors) return nullptr;
std::stringstream stream;
stream << "no matching declaration found for " << name;
ReportError(stream.str());
} else if (candidates.empty()) {
if (silence_errors) return nullptr;
FailCallableLookup("cannot find suitable callable with name", name,
parameter_types, labels, overload_signatures,
inapplicable_generics);
}
auto is_better_candidate = [&](size_t a, size_t b) {
return ParameterDifference(overload_signatures[a].GetExplicitTypes(),
parameter_types)
.StrictlyBetterThan(ParameterDifference(
overload_signatures[b].GetExplicitTypes(), parameter_types));
};
size_t best = *std::min_element(candidates.begin(), candidates.end(),
is_better_candidate);
// This check is contained in libstdc++'s std::min_element.
DCHECK(!is_better_candidate(best, best));
for (size_t candidate : candidates) {
if (candidate != best && !is_better_candidate(best, candidate)) {
std::vector<Signature> candidate_signatures;
for (size_t i : candidates) {
candidate_signatures.push_back(overload_signatures[i]);
}
FailCallableLookup("ambiguous callable ", name, parameter_types, labels,
candidate_signatures, inapplicable_generics);
}
}
if (GenericCallable* generic =
GenericCallable::DynamicCast(overloads[best])) {
TypeArgumentInference inference = InferSpecializationTypes(
generic, specialization_types, parameter_types);
result = GetOrCreateSpecialization(
SpecializationKey<GenericCallable>{generic, inference.GetResult()});
} else {
result = Callable::cast(overloads[best]);
}
size_t caller_size = parameter_types.size();
size_t callee_size =
result->signature().types().size() - result->signature().implicit_count;
if (caller_size != callee_size &&
!result->signature().parameter_types.var_args) {
std::stringstream stream;
stream << "parameter count mismatch calling " << *result << " - expected "
<< std::to_string(callee_size) << ", found "
<< std::to_string(caller_size);
ReportError(stream.str());
}
return result;
}
template <class Container>
Callable* ImplementationVisitor::LookupCallable(
const QualifiedName& name, const Container& declaration_container,
const Arguments& arguments, const TypeVector& specialization_types) {
return LookupCallable(name, declaration_container,
arguments.parameters.ComputeTypeVector(),
arguments.labels, specialization_types);
}
Method* ImplementationVisitor::LookupMethod(
const std::string& name, const AggregateType* receiver_type,
const Arguments& arguments, const TypeVector& specialization_types) {
TypeVector types(arguments.parameters.ComputeTypeVector());
types.insert(types.begin(), receiver_type);
return Method::cast(LookupCallable({{}, name}, receiver_type->Methods(name),
types, arguments.labels,
specialization_types));
}
const Type* ImplementationVisitor::GetCommonType(const Type* left,
const Type* right) {
const Type* common_type;
if (IsAssignableFrom(left, right)) {
common_type = left;
} else if (IsAssignableFrom(right, left)) {
common_type = right;
} else {
common_type = TypeOracle::GetUnionType(left, right);
}
common_type = common_type->NonConstexprVersion();
return common_type;
}
VisitResult ImplementationVisitor::GenerateCopy(const VisitResult& to_copy) {
if (to_copy.IsOnStack()) {
return VisitResult(to_copy.type(),
assembler().Peek(to_copy.stack_range(), to_copy.type()));
}
return to_copy;
}
VisitResult ImplementationVisitor::Visit(StructExpression* expr) {
StackScope stack_scope(this);
auto& initializers = expr->initializers;
std::vector<VisitResult> values;
std::vector<const Type*> term_argument_types;
values.reserve(initializers.size());
term_argument_types.reserve(initializers.size());
// Compute values and types of all initializer arguments
for (const NameAndExpression& initializer : initializers) {
VisitResult value = Visit(initializer.expression);
values.push_back(value);
term_argument_types.push_back(value.type());
}
// Compute and check struct type from given struct name and argument types
const Type* type = TypeVisitor::ComputeTypeForStructExpression(
expr->type, term_argument_types);
if (const auto* struct_type = StructType::DynamicCast(type)) {
CheckInitializersWellformed(struct_type->name(), struct_type->fields(),
initializers);
// Implicitly convert values and thereby build the struct on the stack
StackRange struct_range = assembler().TopRange(0);
auto& fields = struct_type->fields();
for (size_t i = 0; i < values.size(); i++) {
values[i] =
GenerateImplicitConvert(fields[i].name_and_type.type, values[i]);
struct_range.Extend(values[i].stack_range());
}
return stack_scope.Yield(VisitResult(struct_type, struct_range));
} else {
const auto* bitfield_struct_type = BitFieldStructType::cast(type);
CheckInitializersWellformed(bitfield_struct_type->name(),
bitfield_struct_type->fields(), initializers);
// Create a zero and cast it to the desired bitfield struct type.
VisitResult result{TypeOracle::GetConstInt32Type(), "0"};
result = GenerateImplicitConvert(TypeOracle::GetInt32Type(), result);
result = GenerateCall("Unsigned", Arguments{{result}, {}}, {});
result = GenerateCall("%RawDownCast", Arguments{{result}, {}},
{bitfield_struct_type});
// Set each field in the result. If these fields are constexpr, then all of
// this initialization will end up reduced to a single value during TurboFan
// optimization.
auto& fields = bitfield_struct_type->fields();
for (size_t i = 0; i < values.size(); i++) {
values[i] =
GenerateImplicitConvert(fields[i].name_and_type.type, values[i]);
result = GenerateSetBitField(bitfield_struct_type, fields[i], result,
values[i], /*starts_as_zero=*/true);
}
return stack_scope.Yield(result);
}
}
VisitResult ImplementationVisitor::GenerateSetBitField(
const Type* bitfield_struct_type, const BitField& bitfield,
VisitResult bitfield_struct, VisitResult value, bool starts_as_zero) {
GenerateCopy(bitfield_struct);
GenerateCopy(value);
assembler().Emit(
StoreBitFieldInstruction{bitfield_struct_type, bitfield, starts_as_zero});
return VisitResult(bitfield_struct_type, assembler().TopRange(1));
}
LocationReference ImplementationVisitor::GetLocationReference(
Expression* location) {
switch (location->kind) {
case AstNode::Kind::kIdentifierExpression:
return GetLocationReference(static_cast<IdentifierExpression*>(location));
case AstNode::Kind::kFieldAccessExpression:
return GetLocationReference(
static_cast<FieldAccessExpression*>(location));
case AstNode::Kind::kElementAccessExpression:
return GetLocationReference(
static_cast<ElementAccessExpression*>(location));
case AstNode::Kind::kDereferenceExpression:
return GetLocationReference(
static_cast<DereferenceExpression*>(location));
default:
return LocationReference::Temporary(Visit(location), "expression");
}
}
LocationReference ImplementationVisitor::GetLocationReference(
FieldAccessExpression* expr) {
return GenerateFieldAccess(GetLocationReference(expr->object),
expr->field->value, false, expr->field->pos);
}
LocationReference ImplementationVisitor::GenerateFieldAccess(
LocationReference reference, const std::string& fieldname,
bool ignore_stuct_field_constness, base::Optional<SourcePosition> pos) {
if (reference.IsVariableAccess() &&
reference.variable().type()->StructSupertype()) {
const StructType* type = *reference.variable().type()->StructSupertype();
const Field& field = type->LookupField(fieldname);
if (GlobalContext::collect_language_server_data() && pos.has_value()) {
LanguageServerData::AddDefinition(*pos, field.pos);
}
if (field.const_qualified) {
VisitResult t_value = ProjectStructField(reference.variable(), fieldname);
return LocationReference::Temporary(
t_value, "for constant field '" + field.name_and_type.name + "'");
} else {
return LocationReference::VariableAccess(
ProjectStructField(reference.variable(), fieldname));
}
}
if (reference.IsTemporary() &&
reference.temporary().type()->StructSupertype()) {
if (GlobalContext::collect_language_server_data() && pos.has_value()) {
const StructType* type = *reference.temporary().type()->StructSupertype();
const Field& field = type->LookupField(fieldname);
LanguageServerData::AddDefinition(*pos, field.pos);
}
return LocationReference::Temporary(
ProjectStructField(reference.temporary(), fieldname),
reference.temporary_description());
}
if (base::Optional<const Type*> referenced_type =
reference.ReferencedType()) {
if ((*referenced_type)->IsBitFieldStructType()) {
const BitFieldStructType* bitfield_struct =
BitFieldStructType::cast(*referenced_type);
const BitField& field = bitfield_struct->LookupField(fieldname);
return LocationReference::BitFieldAccess(reference, field);
}
if (const auto type_wrapped_in_smi = Type::MatchUnaryGeneric(
(*referenced_type), TypeOracle::GetSmiTaggedGeneric())) {
const BitFieldStructType* bitfield_struct =
BitFieldStructType::DynamicCast(*type_wrapped_in_smi);
if (bitfield_struct == nullptr) {
ReportError(
"When a value of type SmiTagged<T> is used in a field access "
"expression, T is expected to be a bitfield struct type. Instead, "
"T "
"is ",
**type_wrapped_in_smi);
}
const BitField& field = bitfield_struct->LookupField(fieldname);
return LocationReference::BitFieldAccess(reference, field);
}
}
if (reference.IsHeapReference()) {
VisitResult ref = reference.heap_reference();
bool is_const;
auto generic_type =
TypeOracle::MatchReferenceGeneric(ref.type(), &is_const);
if (!generic_type) {
ReportError(
"Left-hand side of field access expression is marked as a reference "
"but is not of type Reference<...>. Found type: ",
ref.type()->ToString());
}
if (auto struct_type = (*generic_type)->StructSupertype()) {
const Field& field = (*struct_type)->LookupField(fieldname);
// Update the Reference's type to refer to the field type within the
// struct.
ref.SetType(TypeOracle::GetReferenceType(
field.name_and_type.type,
is_const ||
(field.const_qualified && !ignore_stuct_field_constness)));
if (!field.offset.has_value()) {
Error("accessing field with unknown offset").Throw();
}
if (*field.offset != 0) {
// Copy the Reference struct up the stack and update the new copy's
// |offset| value to point to the struct field.
StackScope scope(this);
ref = GenerateCopy(ref);
VisitResult ref_offset = ProjectStructField(ref, "offset");
VisitResult struct_offset{
TypeOracle::GetIntPtrType()->ConstexprVersion(),
std::to_string(*field.offset)};
VisitResult updated_offset =
GenerateCall("+", Arguments{{ref_offset, struct_offset}, {}});
assembler().Poke(ref_offset.stack_range(), updated_offset.stack_range(),
ref_offset.type());
ref = scope.Yield(ref);
}
return LocationReference::HeapReference(ref);
}
}
VisitResult object_result = GenerateFetchFromLocation(reference);
if (base::Optional<const ClassType*> class_type =
object_result.type()->ClassSupertype()) {
// This is a hack to distinguish the situation where we want to use
// overloaded field accessors from when we want to create a reference.
bool has_explicit_overloads = TestLookupCallable(
QualifiedName{"." + fieldname}, {object_result.type()});
if ((*class_type)->HasField(fieldname) && !has_explicit_overloads) {
const Field& field = (*class_type)->LookupField(fieldname);
if (GlobalContext::collect_language_server_data() && pos.has_value()) {
LanguageServerData::AddDefinition(*pos, field.pos);
}
return GenerateFieldReference(object_result, field, *class_type);
}
}
return LocationReference::FieldAccess(object_result, fieldname);
}
LocationReference ImplementationVisitor::GetLocationReference(
ElementAccessExpression* expr) {
LocationReference reference = GetLocationReference(expr->array);
VisitResult index = Visit(expr->index);
if (reference.IsHeapSlice()) {
Arguments arguments{{index}, {}};
const AggregateType* slice_type =
AggregateType::cast(reference.heap_slice().type());
Method* method = LookupMethod("AtIndex", slice_type, arguments, {});
// The reference has to be treated like a normal value when calling methods
// on the underlying slice implementation.
LocationReference slice_value = LocationReference::Temporary(
reference.GetVisitResult(), "slice as value");
return LocationReference::HeapReference(
GenerateCall(method, std::move(slice_value), arguments, {}, false));
} else {
return LocationReference::ArrayAccess(GenerateFetchFromLocation(reference),
index);
}
}
LocationReference ImplementationVisitor::GetLocationReference(
IdentifierExpression* expr) {
if (expr->namespace_qualification.empty()) {
if (base::Optional<Binding<LocalValue>*> value =
TryLookupLocalValue(expr->name->value)) {
if (GlobalContext::collect_language_server_data()) {
LanguageServerData::AddDefinition(expr->name->pos,
(*value)->declaration_position());
}
if (expr->generic_arguments.size() != 0) {
ReportError("cannot have generic parameters on local name ",
expr->name);
}
return (*value)->GetLocationReference(*value);
}
}
if (expr->IsThis()) {
ReportError("\"this\" cannot be qualified");
}
QualifiedName name =
QualifiedName(expr->namespace_qualification, expr->name->value);
if (base::Optional<Builtin*> builtin = Declarations::TryLookupBuiltin(name)) {
if (GlobalContext::collect_language_server_data()) {
LanguageServerData::AddDefinition(expr->name->pos,
(*builtin)->Position());
}
return LocationReference::Temporary(GetBuiltinCode(*builtin),
"builtin " + expr->name->value);
}
if (expr->generic_arguments.size() != 0) {
GenericCallable* generic = Declarations::LookupUniqueGeneric(name);
Callable* specialization =
GetOrCreateSpecialization(SpecializationKey<GenericCallable>{
generic, TypeVisitor::ComputeTypeVector(expr->generic_arguments)});
if (Builtin* builtin = Builtin::DynamicCast(specialization)) {
DCHECK(!builtin->IsExternal());
return LocationReference::Temporary(GetBuiltinCode(builtin),
"builtin " + expr->name->value);
} else {
ReportError("cannot create function pointer for non-builtin ",
generic->name());
}
}
Value* value = Declarations::LookupValue(name);
if (GlobalContext::collect_language_server_data()) {
LanguageServerData::AddDefinition(expr->name->pos, value->name()->pos);
}
if (auto* constant = NamespaceConstant::DynamicCast(value)) {
if (constant->type()->IsConstexpr()) {
return LocationReference::Temporary(
VisitResult(constant->type(), constant->external_name() + "(state_)"),
"namespace constant " + expr->name->value);
}
assembler().Emit(NamespaceConstantInstruction{constant});
StackRange stack_range =
assembler().TopRange(LoweredSlotCount(constant->type()));
return LocationReference::Temporary(
VisitResult(constant->type(), stack_range),
"namespace constant " + expr->name->value);
}
ExternConstant* constant = ExternConstant::cast(value);
return LocationReference::Temporary(constant->value(),
"extern value " + expr->name->value);
}
LocationReference ImplementationVisitor::GetLocationReference(
DereferenceExpression* expr) {
VisitResult ref = Visit(expr->reference);
if (!TypeOracle::MatchReferenceGeneric(ref.type())) {
Error("Operator * expects a reference type but found a value of type ",
*ref.type())
.Throw();
}
return LocationReference::HeapReference(ref);
}
VisitResult ImplementationVisitor::GenerateFetchFromLocation(
const LocationReference& reference) {
if (reference.IsTemporary()) {
return GenerateCopy(reference.temporary());
} else if (reference.IsVariableAccess()) {
return GenerateCopy(reference.variable());
} else if (reference.IsHeapReference()) {
const Type* referenced_type = *reference.ReferencedType();
if (referenced_type == TypeOracle::GetFloat64OrHoleType()) {
return GenerateCall(QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING},
"LoadFloat64OrHole"),
Arguments{{reference.heap_reference()}, {}});
} else if (auto struct_type = referenced_type->StructSupertype()) {
StackRange result_range = assembler().TopRange(0);
for (const Field& field : (*struct_type)->fields()) {
StackScope scope(this);
const std::string& fieldname = field.name_and_type.name;
VisitResult field_value = scope.Yield(GenerateFetchFromLocation(
GenerateFieldAccess(reference, fieldname)));
result_range.Extend(field_value.stack_range());
}
return VisitResult(referenced_type, result_range);
} else {
GenerateCopy(reference.heap_reference());
assembler().Emit(LoadReferenceInstruction{referenced_type});
DCHECK_EQ(1, LoweredSlotCount(referenced_type));
return VisitResult(referenced_type, assembler().TopRange(1));
}
} else if (reference.IsBitFieldAccess()) {
// First fetch the bitfield struct, then get the bits out of it.
VisitResult bit_field_struct =
GenerateFetchFromLocation(reference.bit_field_struct_location());
assembler().Emit(LoadBitFieldInstruction{bit_field_struct.type(),
reference.bit_field()});
return VisitResult(*reference.ReferencedType(), assembler().TopRange(1));
} else {
if (reference.IsHeapSlice()) {
ReportError(
"fetching a value directly from an indexed field isn't allowed");
}
DCHECK(reference.IsCallAccess());
return GenerateCall(reference.eval_function(),
Arguments{reference.call_arguments(), {}});
}
}
void ImplementationVisitor::GenerateAssignToLocation(
const LocationReference& reference, const VisitResult& assignment_value) {
if (reference.IsCallAccess()) {
Arguments arguments{reference.call_arguments(), {}};
arguments.parameters.push_back(assignment_value);
GenerateCall(reference.assign_function(), arguments);
} else if (reference.IsVariableAccess()) {
VisitResult variable = reference.variable();
VisitResult converted_value =
GenerateImplicitConvert(variable.type(), assignment_value);
assembler().Poke(variable.stack_range(), converted_value.stack_range(),
variable.type());
// Local variables are detected by the existence of a binding. Assignment
// to local variables is recorded to support lint errors.
if (reference.binding()) {
(*reference.binding())->SetWritten();
}
} else if (reference.IsHeapSlice()) {
ReportError("assigning a value directly to an indexed field isn't allowed");
} else if (reference.IsHeapReference()) {
const Type* referenced_type = *reference.ReferencedType();
if (reference.IsConst()) {
Error("cannot assign to const value of type ", *referenced_type).Throw();
}
if (referenced_type == TypeOracle::GetFloat64OrHoleType()) {
GenerateCall(
QualifiedName({TORQUE_INTERNAL_NAMESPACE_STRING},
"StoreFloat64OrHole"),
Arguments{{reference.heap_reference(), assignment_value}, {}});
} else if (auto struct_type = referenced_type->StructSupertype()) {
if (!assignment_value.type()->IsSubtypeOf(referenced_type)) {
ReportError("Cannot assign to ", *referenced_type,
" with value of type ", *assignment_value.type());
}
for (const Field& field : (*struct_type)->fields()) {
const std::string& fieldname = field.name_and_type.name;
// Allow assignment of structs even if they contain const fields.
// Const on struct fields just disallows direct writes to them.
bool ignore_stuct_field_constness = true;
GenerateAssignToLocation(
GenerateFieldAccess(reference, fieldname,
ignore_stuct_field_constness),
ProjectStructField(assignment_value, fieldname));
}
} else {
GenerateCopy(reference.heap_reference());
VisitResult converted_assignment_value =
GenerateImplicitConvert(referenced_type, assignment_value);
if (referenced_type == TypeOracle::GetFloat64Type()) {
VisitResult silenced_float_value = GenerateCall(
"Float64SilenceNaN", Arguments{{assignment_value}, {}});
assembler().Poke(converted_assignment_value.stack_range(),
silenced_float_value.stack_range(), referenced_type);
}
assembler().Emit(StoreReferenceInstruction{referenced_type});
}
} else if (reference.IsBitFieldAccess()) {
// First fetch the bitfield struct, then set the updated bits, then store
// it back to where we found it.
VisitResult bit_field_struct =
GenerateFetchFromLocation(reference.bit_field_struct_location());
VisitResult converted_value =
GenerateImplicitConvert(*reference.ReferencedType(), assignment_value);
VisitResult updated_bit_field_struct =
GenerateSetBitField(bit_field_struct.type(), reference.bit_field(),
bit_field_struct, converted_value);
GenerateAssignToLocation(reference.bit_field_struct_location(),
updated_bit_field_struct);
} else {
DCHECK(reference.IsTemporary());
ReportError("cannot assign to const-bound or temporary ",
reference.temporary_description());
}
}
VisitResult ImplementationVisitor::GeneratePointerCall(
Expression* callee, const Arguments& arguments, bool is_tailcall) {
StackScope scope(this);
TypeVector parameter_types(arguments.parameters.ComputeTypeVector());
VisitResult callee_result = Visit(callee);
if (!callee_result.type()->IsBuiltinPointerType()) {
std::stringstream stream;
stream << "Expected a function pointer type but found "
<< *callee_result.type();
ReportError(stream.str());
}
const BuiltinPointerType* type =
BuiltinPointerType::cast(callee_result.type());
if (type->parameter_types().size() != parameter_types.size()) {
std::stringstream stream;
stream << "parameter count mismatch calling function pointer with Type: "
<< *type << " - expected "
<< std::to_string(type->parameter_types().size()) << ", found "
<< std::to_string(parameter_types.size());
ReportError(stream.str());
}
ParameterTypes types{type->parameter_types(), false};
Signature sig;
sig.parameter_types = types;
if (!IsCompatibleSignature(sig, parameter_types, 0)) {
std::stringstream stream;
stream << "parameters do not match function pointer signature. Expected: ("
<< type->parameter_types() << ") but got: (" << parameter_types
<< ")";
ReportError(stream.str());
}
callee_result = GenerateCopy(callee_result);
StackRange arg_range = assembler().TopRange(0);
for (size_t current = 0; current < arguments.parameters.size(); ++current) {
const Type* to_type = type->parameter_types()[current];
arg_range.Extend(
GenerateImplicitConvert(to_type, arguments.parameters[current])
.stack_range());
}
assembler().Emit(
CallBuiltinPointerInstruction{is_tailcall, type, arg_range.Size()});
if (is_tailcall) {
return VisitResult::NeverResult();
}
DCHECK_EQ(1, LoweredSlotCount(type->return_type()));
return scope.Yield(VisitResult(type->return_type(), assembler().TopRange(1)));
}
void ImplementationVisitor::AddCallParameter(
Callable* callable, VisitResult parameter, const Type* parameter_type,
std::vector<VisitResult>* converted_arguments, StackRange* argument_range,
std::vector<std::string>* constexpr_arguments, bool inline_macro) {
VisitResult converted;
if ((converted_arguments->size() < callable->signature().implicit_count) &&
parameter.type()->IsTopType()) {
converted = GenerateCopy(parameter);
} else {
converted = GenerateImplicitConvert(parameter_type, parameter);
}
converted_arguments->push_back(converted);
if (!inline_macro) {
if (converted.IsOnStack()) {
argument_range->Extend(converted.stack_range());
} else {
constexpr_arguments->push_back(converted.constexpr_value());
}
}
}
namespace {
std::pair<std::string, std::string> GetClassInstanceTypeRange(
const ClassType* class_type) {
std::pair<std::string, std::string> result;
if (class_type->InstanceTypeRange()) {
auto instance_type_range = *class_type->InstanceTypeRange();
std::string instance_type_string_first =
"static_cast<InstanceType>(" +
std::to_string(instance_type_range.first) + ")";
std::string instance_type_string_second =
"static_cast<InstanceType>(" +
std::to_string(instance_type_range.second) + ")";
result =
std::make_pair(instance_type_string_first, instance_type_string_second);
} else {
ReportError(
"%Min/MaxInstanceType must take a class type that is either a string "
"or has a generated instance type range");
}
return result;
}
} // namespace
VisitResult ImplementationVisitor::GenerateCall(
Callable* callable, base::Optional<LocationReference> this_reference,
Arguments arguments, const TypeVector& specialization_types,
bool is_tailcall) {
const Type* return_type = callable->signature().return_type;
if (is_tailcall) {
if (Builtin* builtin = Builtin::DynamicCast(CurrentCallable::Get())) {
const Type* outer_return_type = builtin->signature().return_type;
if (!return_type->IsSubtypeOf(outer_return_type)) {
Error("Cannot tailcall, type of result is ", *return_type,
" but should be a subtype of ", *outer_return_type, ".");
}
} else {
Error("Tail calls are only allowed from builtins");
}
}
bool inline_macro = callable->ShouldBeInlined(output_type_);
std::vector<VisitResult> implicit_arguments;
for (size_t i = 0; i < callable->signature().implicit_count; ++i) {
std::string implicit_name = callable->signature().parameter_names[i]->value;
base::Optional<Binding<LocalValue>*> val =
TryLookupLocalValue(implicit_name);
if (val) {
implicit_arguments.push_back(
GenerateFetchFromLocation((*val)->GetLocationReference(*val)));
} else {
VisitResult unititialized = VisitResult::TopTypeResult(
"implicit parameter '" + implicit_name +
"' is not defined when invoking " + callable->ReadableName() +
" at " + PositionAsString(CurrentSourcePosition::Get()),
callable->signature().parameter_types.types[i]);
implicit_arguments.push_back(unititialized);
}
const Type* type = implicit_arguments.back().type();
if (const TopType* top_type = TopType::DynamicCast(type)) {
if (!callable->IsMacro() || callable->IsExternal()) {
ReportError(
"unititialized implicit parameters can only be passed to "
"Torque-defined macros: the ",
top_type->reason());
}
inline_macro = true;
}
}
std::vector<VisitResult> converted_arguments;
StackRange argument_range = assembler().TopRange(0);
std::vector<std::string> constexpr_arguments;
size_t current = 0;
for (; current < callable->signature().implicit_count; ++current) {
AddCallParameter(callable, implicit_arguments[current],
callable->signature().parameter_types.types[current],
&converted_arguments, &argument_range,
&constexpr_arguments, inline_macro);
}
if (this_reference) {
DCHECK(callable->IsMethod());
Method* method = Method::cast(callable);
// By now, the this reference should either be a variable, a temporary or
// a Slice. In either case the fetch of the VisitResult should succeed.
VisitResult this_value = this_reference->GetVisitResult();
if (inline_macro) {
if (!this_value.type()->IsSubtypeOf(method->aggregate_type())) {
ReportError("this parameter must be a subtype of ",
*method->aggregate_type(), " but it is of type ",
this_value.type());
}
} else {
AddCallParameter(callable, this_value, method->aggregate_type(),
&converted_arguments, &argument_range,
&constexpr_arguments, inline_macro);
}
++current;
}
for (auto arg : arguments.parameters) {
const Type* to_type = (current >= callable->signature().types().size())
? TypeOracle::GetObjectType()
: callable->signature().types()[current++];
AddCallParameter(callable, arg, to_type, &converted_arguments,
&argument_range, &constexpr_arguments, inline_macro);
}
size_t label_count = callable->signature().labels.size();
if (label_count != arguments.labels.size()) {
std::stringstream s;
s << "unexpected number of otherwise labels for "
<< callable->ReadableName() << " (expected "
<< std::to_string(label_count) << " found "
<< std::to_string(arguments.labels.size()) << ")";
ReportError(s.str());
}
if (callable->IsTransitioning()) {
if (!CurrentCallable::Get()->IsTransitioning()) {
std::stringstream s;
s << *CurrentCallable::Get()
<< " isn't marked transitioning but calls the transitioning "
<< *callable;
ReportError(s.str());
}
}
if (auto* builtin = Builtin::DynamicCast(callable)) {
base::Optional<Block*> catch_block = GetCatchBlock();
assembler().Emit(CallBuiltinInstruction{
is_tailcall, builtin, argument_range.Size(), catch_block});
GenerateCatchBlock(catch_block);
if (is_tailcall) {
return VisitResult::NeverResult();
} else {
size_t slot_count = LoweredSlotCount(return_type);
DCHECK_LE(slot_count, 1);
// TODO(tebbi): Actually, builtins have to return a value, so we should
// assert slot_count == 1 here.
return VisitResult(return_type, assembler().TopRange(slot_count));
}
} else if (auto* macro = Macro::DynamicCast(callable)) {
if (is_tailcall) {
ReportError("can't tail call a macro");
}
macro->SetUsed();
// If we're currently generating a C++ macro and it's calling another macro,
// then we need to make sure that we also generate C++ code for the called
// macro.
if (output_type_ == OutputType::kCC && !inline_macro) {
if (auto* torque_macro = TorqueMacro::DynamicCast(macro)) {
GlobalContext::EnsureInCCOutputList(torque_macro);
}
}
if (return_type->IsConstexpr()) {
DCHECK_EQ(0, arguments.labels.size());
std::stringstream result;
result << "(";
bool first = true;
if (auto* extern_macro = ExternMacro::DynamicCast(macro)) {
result << extern_macro->external_assembler_name() << "(state_)."
<< extern_macro->ExternalName() << "(";
} else {
result << macro->ExternalName() << "(state_";
first = false;
}
for (VisitResult arg : arguments.parameters) {
DCHECK(!arg.IsOnStack());
if (!first) {
result << ", ";
}
first = false;
result << arg.constexpr_value();
}
result << "))";
return VisitResult(return_type, result.str());
} else if (inline_macro) {
std::vector<Block*> label_blocks;
for (Binding<LocalLabel>* label : arguments.labels) {
label_blocks.push_back(label->block);
}
return InlineMacro(macro, this_reference, converted_arguments,
label_blocks);
} else if (arguments.labels.empty() &&
return_type != TypeOracle::GetNeverType()) {
base::Optional<Block*> catch_block = GetCatchBlock();
assembler().Emit(
CallCsaMacroInstruction{macro, constexpr_arguments, catch_block});
GenerateCatchBlock(catch_block);
size_t return_slot_count = LoweredSlotCount(return_type);
return VisitResult(return_type, assembler().TopRange(return_slot_count));
} else {
base::Optional<Block*> return_continuation;
if (return_type != TypeOracle::GetNeverType()) {
return_continuation = assembler().NewBlock();
}
std::vector<Block*> label_blocks;
for (size_t i = 0; i < label_count; ++i) {
label_blocks.push_back(assembler().NewBlock());
}
base::Optional<Block*> catch_block = GetCatchBlock();
assembler().Emit(CallCsaMacroAndBranchInstruction{
macro, constexpr_arguments, return_continuation, label_blocks,
catch_block});
GenerateCatchBlock(catch_block);
for (size_t i = 0; i < label_count; ++i) {
Binding<LocalLabel>* label = arguments.labels[i];
size_t callee_label_parameters =
callable->signature().labels[i].types.size();
if (label->parameter_types.size() != callee_label_parameters) {
std::stringstream s;
s << "label " << label->name()
<< " doesn't have the right number of parameters (found "
<< std::to_string(label->parameter_types.size()) << " expected "
<< std::to_string(callee_label_parameters) << ")";
ReportError(s.str());
}
assembler().Bind(label_blocks[i]);
assembler().Goto(
label->block,
LowerParameterTypes(callable->signature().labels[i].types).size());
size_t j = 0;
for (auto t : callable->signature().labels[i].types) {
const Type* parameter_type = label->parameter_types[j];
if (!t->IsSubtypeOf(parameter_type)) {
ReportError("mismatch of label parameters (label expects ",
*parameter_type, " but macro produces ", *t,
" for parameter ", i + 1, ")");
}
j++;
}
}
if (return_continuation) {
assembler().Bind(*return_continuation);
size_t return_slot_count = LoweredSlotCount(return_type);
return VisitResult(return_type,
assembler().TopRange(return_slot_count));
} else {
return VisitResult::NeverResult();
}
}
} else if (auto* runtime_function = RuntimeFunction::DynamicCast(callable)) {
base::Optional<Block*> catch_block = GetCatchBlock();
assembler().Emit(CallRuntimeInstruction{
is_tailcall, runtime_function, argument_range.Size(), catch_block});
GenerateCatchBlock(catch_block);
if (is_tailcall || return_type == TypeOracle::GetNeverType()) {
return VisitResult::NeverResult();
} else {
size_t slot_count = LoweredSlotCount(return_type);
DCHECK_LE(slot_count, 1);
// TODO(tebbi): Actually, runtime functions have to return a value, so
// we should assert slot_count == 1 here.
return VisitResult(return_type, assembler().TopRange(slot_count));
}
} else if (auto* intrinsic = Intrinsic::DynamicCast(callable)) {
if (intrinsic->ExternalName() == "%SizeOf") {
if (specialization_types.size() != 1) {
ReportError("%SizeOf must take a single type parameter");
}
const Type* type = specialization_types[0];
std::string size_string;
if (base::Optional<std::tuple<size_t, std::string>> size = SizeOf(type)) {
size_string = std::get<1>(*size);
} else {
Error("size of ", *type, " is not known.");
}
return VisitResult(return_type, size_string);
} else if (intrinsic->ExternalName() == "%ClassHasMapConstant") {
const Type* type = specialization_types[0];
const ClassType* class_type = ClassType::DynamicCast(type);
if (!class_type) {
ReportError("%ClassHasMapConstant must take a class type parameter");
}
// If the class isn't actually used as the parameter to a TNode,
// then we can't rely on the class existing in C++ or being of the same
// type (e.g. it could be a template), so don't use the template CSA
// machinery for accessing the class' map.
if (class_type->name() != class_type->GetGeneratedTNodeTypeName()) {
return VisitResult(return_type, std::string("false"));
} else {
return VisitResult(
return_type,
std::string("CodeStubAssembler(state_).ClassHasMapConstant<") +
class_type->name() + ">()");
}
} else if (intrinsic->ExternalName() == "%MinInstanceType") {
if (specialization_types.size() != 1) {
ReportError("%MinInstanceType must take a single type parameter");
}
const Type* type = specialization_types[0];
const ClassType* class_type = ClassType::DynamicCast(type);
if (!class_type) {
ReportError("%MinInstanceType must take a class type parameter");
}
std::pair<std::string, std::string> instance_types =
GetClassInstanceTypeRange(class_type);
return VisitResult(return_type, instance_types.first);
} else if (intrinsic->ExternalName() == "%MaxInstanceType") {
if (specialization_types.size() != 1) {
ReportError("%MaxInstanceType must take a single type parameter");
}
const Type* type = specialization_types[0];
const ClassType* class_type = ClassType::DynamicCast(type);
if (!class_type) {
ReportError("%MaxInstanceType must take a class type parameter");
}
std::pair<std::string, std::string> instance_types =
GetClassInstanceTypeRange(class_type);
return VisitResult(return_type, instance_types.second);
} else if (intrinsic->ExternalName() == "%RawConstexprCast") {
if (intrinsic->signature().parameter_types.types.size() != 1 ||
constexpr_arguments.size() != 1) {
ReportError(
"%RawConstexprCast must take a single parameter with constexpr "
"type");
}
if (!return_type->IsConstexpr()) {
std::stringstream s;
s << *return_type
<< " return type for %RawConstexprCast is not constexpr";
ReportError(s.str());
}
std::stringstream result;
result << "static_cast<" << return_type->GetGeneratedTypeName() << ">(";
result << constexpr_arguments[0];
result << ")";
return VisitResult(return_type, result.str());
} else if (intrinsic->ExternalName() == "%IndexedFieldLength") {
const Type* type = specialization_types[0];
const ClassType* class_type = ClassType::DynamicCast(type);
if (!class_type) {
ReportError("%IndexedFieldLength must take a class type parameter");
}
const Field& field =
class_type->LookupField(StringLiteralUnquote(constexpr_arguments[0]));
return GenerateArrayLength(VisitResult(type, argument_range), field);
} else {
assembler().Emit(CallIntrinsicInstruction{intrinsic, specialization_types,
constexpr_arguments});
size_t return_slot_count =
LoweredSlotCount(intrinsic->signature().return_type);
return VisitResult(return_type, assembler().TopRange(return_slot_count));
}
} else {
UNREACHABLE();
}
}
VisitResult ImplementationVisitor::GenerateCall(
const QualifiedName& callable_name, Arguments arguments,
const TypeVector& specialization_types, bool is_tailcall) {
Callable* callable =
LookupCallable(callable_name, Declarations::Lookup(callable_name),
arguments, specialization_types);
return GenerateCall(callable, base::nullopt, arguments, specialization_types,
is_tailcall);
}
VisitResult ImplementationVisitor::Visit(CallExpression* expr,
bool is_tailcall) {
StackScope scope(this);
if (expr->callee->name->value == "&" && expr->arguments.size() == 1) {
if (auto* loc_expr = LocationExpression::DynamicCast(expr->arguments[0])) {
LocationReference ref = GetLocationReference(loc_expr);
if (ref.IsHeapReference()) return scope.Yield(ref.heap_reference());
if (ref.IsHeapSlice()) return scope.Yield(ref.heap_slice());
}
ReportError("Unable to create a heap reference.");
}
Arguments arguments;
QualifiedName name = QualifiedName(expr->callee->namespace_qualification,
expr->callee->name->value);
TypeVector specialization_types =
TypeVisitor::ComputeTypeVector(expr->callee->generic_arguments);
bool has_template_arguments = !specialization_types.empty();
for (Expression* arg : expr->arguments)
arguments.parameters.push_back(Visit(arg));
arguments.labels = LabelsFromIdentifiers(expr->labels);
if (!has_template_arguments && name.namespace_qualification.empty() &&
TryLookupLocalValue(name.name)) {
return scope.Yield(
GeneratePointerCall(expr->callee, arguments, is_tailcall));
} else {
if (GlobalContext::collect_language_server_data()) {
Callable* callable = LookupCallable(name, Declarations::Lookup(name),
arguments, specialization_types);
LanguageServerData::AddDefinition(expr->callee->name->pos,
callable->IdentifierPosition());
}
if (expr->callee->name->value == "!" && arguments.parameters.size() == 1) {
PropagateBitfieldMark(expr->arguments[0], expr);
}
if (expr->callee->name->value == "==" && arguments.parameters.size() == 2) {
if (arguments.parameters[0].type()->IsConstexpr()) {
PropagateBitfieldMark(expr->arguments[1], expr);
} else if (arguments.parameters[1].type()->IsConstexpr()) {
PropagateBitfieldMark(expr->arguments[0], expr);
}
}
return scope.Yield(
GenerateCall(name, arguments, specialization_types, is_tailcall));
}
}
VisitResult ImplementationVisitor::Visit(CallMethodExpression* expr) {
StackScope scope(this);
Arguments arguments;
std::string method_name = expr->method->name->value;
TypeVector specialization_types =
TypeVisitor::ComputeTypeVector(expr->method->generic_arguments);
LocationReference target = GetLocationReference(expr->target);
if (!target.IsVariableAccess()) {
VisitResult result = GenerateFetchFromLocation(target);
target = LocationReference::Temporary(result, "this parameter");
}
const AggregateType* target_type =
AggregateType::DynamicCast(*target.ReferencedType());
if (!target_type) {
ReportError("target of method call not a struct or class type");
}
for (Expression* arg : expr->arguments) {
arguments.parameters.push_back(Visit(arg));
}
arguments.labels = LabelsFromIdentifiers(expr->labels);
TypeVector argument_types = arguments.parameters.ComputeTypeVector();
DCHECK_EQ(expr->method->namespace_qualification.size(), 0);
QualifiedName qualified_name = QualifiedName(method_name);
Callable* callable = nullptr;
callable = LookupMethod(method_name, target_type, arguments, {});
if (GlobalContext::collect_language_server_data()) {
LanguageServerData::AddDefinition(expr->method->name->pos,
callable->IdentifierPosition());
}
return scope.Yield(GenerateCall(callable, target, arguments, {}, false));
}
VisitResult ImplementationVisitor::Visit(IntrinsicCallExpression* expr) {
StackScope scope(this);
Arguments arguments;
TypeVector specialization_types =
TypeVisitor::ComputeTypeVector(expr->generic_arguments);
for (Expression* arg : expr->arguments)
arguments.parameters.push_back(Visit(arg));
return scope.Yield(
GenerateCall(expr->name->value, arguments, specialization_types, false));
}
void ImplementationVisitor::GenerateBranch(const VisitResult& condition,
Block* true_block,
Block* false_block) {
DCHECK_EQ(condition,
VisitResult(TypeOracle::GetBoolType(), assembler().TopRange(1)));
assembler().Branch(true_block, false_block);
}
VisitResult ImplementationVisitor::GenerateBoolConstant(bool constant) {
return GenerateImplicitConvert(TypeOracle::GetBoolType(),
VisitResult(TypeOracle::GetConstexprBoolType(),
constant ? "true" : "false"));
}
void ImplementationVisitor::GenerateExpressionBranch(Expression* expression,
Block* true_block,
Block* false_block) {
StackScope stack_scope(this);
VisitResult expression_result = this->Visit(expression);
expression_result = stack_scope.Yield(
GenerateImplicitConvert(TypeOracle::GetBoolType(), expression_result));
GenerateBranch(expression_result, true_block, false_block);
}
VisitResult ImplementationVisitor::GenerateImplicitConvert(
const Type* destination_type, VisitResult source) {
StackScope scope(this);
if (source.type() == TypeOracle::GetNeverType()) {
ReportError("it is not allowed to use a value of type never");
}
if (destination_type == source.type()) {
return scope.Yield(GenerateCopy(source));
}
if (auto from = TypeOracle::ImplicitlyConvertableFrom(destination_type,
source.type())) {
return scope.Yield(GenerateCall(kFromConstexprMacroName,
Arguments{{source}, {}},
{destination_type, *from}, false));
} else if (IsAssignableFrom(destination_type, source.type())) {
source.SetType(destination_type);
return scope.Yield(GenerateCopy(source));
} else {
std::stringstream s;
if (const TopType* top_type = TopType::DynamicCast(source.type())) {
s << "undefined expression of type " << *destination_type << ": the "
<< top_type->reason();
} else {
s << "cannot use expression of type " << *source.type()
<< " as a value of type " << *destination_type;
}
ReportError(s.str());
}
}
StackRange ImplementationVisitor::GenerateLabelGoto(
LocalLabel* label, base::Optional<StackRange> arguments) {
return assembler().Goto(label->block, arguments ? arguments->Size() : 0);
}
std::vector<Binding<LocalLabel>*> ImplementationVisitor::LabelsFromIdentifiers(
const std::vector<Identifier*>& names) {
std::vector<Binding<LocalLabel>*> result;
result.reserve(names.size());
for (const auto& name : names) {
Binding<LocalLabel>* label = LookupLabel(name->value);
result.push_back(label);
// Link up labels in "otherwise" part of the call expression with
// either the label in the signature of the calling macro or the label
// block ofa surrounding "try".
if (GlobalContext::collect_language_server_data()) {
LanguageServerData::AddDefinition(name->pos,
label->declaration_position());
}
}
return result;
}
StackRange ImplementationVisitor::LowerParameter(
const Type* type, const std::string& parameter_name,
Stack<std::string>* lowered_parameters) {
if (base::Optional<const StructType*> struct_type = type->StructSupertype()) {
StackRange range = lowered_parameters->TopRange(0);
for (auto& field : (*struct_type)->fields()) {
StackRange parameter_range = LowerParameter(
field.name_and_type.type,
parameter_name + "." + field.name_and_type.name, lowered_parameters);
range.Extend(parameter_range);
}
return range;
} else {
lowered_parameters->Push(parameter_name);
return lowered_parameters->TopRange(1);
}
}
void ImplementationVisitor::LowerLabelParameter(
const Type* type, const std::string& parameter_name,
std::vector<std::string>* lowered_parameters) {
if (base::Optional<const StructType*> struct_type = type->StructSupertype()) {
for (auto& field : (*struct_type)->fields()) {
LowerLabelParameter(
field.name_and_type.type,
"&((*" + parameter_name + ")." + field.name_and_type.name + ")",
lowered_parameters);
}
} else {
lowered_parameters->push_back(parameter_name);
}
}
std::string ImplementationVisitor::ExternalLabelName(
const std::string& label_name) {
return "label_" + label_name;
}
std::string ImplementationVisitor::ExternalLabelParameterName(
const std::string& label_name, size_t i) {
return "label_" + label_name + "_parameter_" + std::to_string(i);
}
std::string ImplementationVisitor::ExternalParameterName(
const std::string& name) {
return std::string("p_") + name;
}
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::ValueBindingsManager)
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::LabelBindingsManager)
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::CurrentCallable)
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::CurrentFileStreams)
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::CurrentReturnValue)
bool IsCompatibleSignature(const Signature& sig, const TypeVector& types,
size_t label_count) {
auto i = sig.parameter_types.types.begin() + sig.implicit_count;
if ((sig.parameter_types.types.size() - sig.implicit_count) > types.size())
return false;
if (sig.labels.size() != label_count) return false;
for (auto current : types) {
if (i == sig.parameter_types.types.end()) {
if (!sig.parameter_types.var_args) return false;
if (!IsAssignableFrom(TypeOracle::GetObjectType(), current)) return false;
} else {
if (!IsAssignableFrom(*i++, current)) return false;
}
}
return true;
}
base::Optional<Block*> ImplementationVisitor::GetCatchBlock() {
base::Optional<Block*> catch_block;
if (base::Optional<Binding<LocalLabel>*> catch_handler =
TryLookupLabel(kCatchLabelName)) {
catch_block = assembler().NewBlock(base::nullopt, true);
}
return catch_block;
}
void ImplementationVisitor::GenerateCatchBlock(
base::Optional<Block*> catch_block) {
if (catch_block) {
base::Optional<Binding<LocalLabel>*> catch_handler =
TryLookupLabel(kCatchLabelName);
if (assembler().CurrentBlockIsComplete()) {
assembler().Bind(*catch_block);
assembler().Goto((*catch_handler)->block, 1);
} else {
CfgAssemblerScopedTemporaryBlock temp(&assembler(), *catch_block);
assembler().Goto((*catch_handler)->block, 1);
}
}
}
void ImplementationVisitor::VisitAllDeclarables() {
CurrentCallable::Scope current_callable(nullptr);
const std::vector<std::unique_ptr<Declarable>>& all_declarables =
GlobalContext::AllDeclarables();
// This has to be an index-based loop because all_declarables can be extended
// during the loop.
for (size_t i = 0; i < all_declarables.size(); ++i) {
try {
Visit(all_declarables[i].get());
} catch (TorqueAbortCompilation&) {
// Recover from compile errors here. The error is recorded already.
}
}
// Do the same for macros which generate C++ code.
output_type_ = OutputType::kCC;
const std::vector<TorqueMacro*>& cc_macros =
GlobalContext::AllMacrosForCCOutput();
for (size_t i = 0; i < cc_macros.size(); ++i) {
try {
Visit(static_cast<Declarable*>(cc_macros[i]));
} catch (TorqueAbortCompilation&) {
// Recover from compile errors here. The error is recorded already.
}
}
output_type_ = OutputType::kCSA;
}
void ImplementationVisitor::Visit(Declarable* declarable) {
CurrentScope::Scope current_scope(declarable->ParentScope());
CurrentSourcePosition::Scope current_source_position(declarable->Position());
CurrentFileStreams::Scope current_file_streams(
&GlobalContext::GeneratedPerFile(declarable->Position().source));
if (Callable* callable = Callable::DynamicCast(declarable)) {
if (!callable->ShouldGenerateExternalCode(output_type_))
CurrentFileStreams::Get() = nullptr;
}
switch (declarable->kind()) {
case Declarable::kExternMacro:
return Visit(ExternMacro::cast(declarable));
case Declarable::kTorqueMacro:
return Visit(TorqueMacro::cast(declarable));
case Declarable::kMethod:
return Visit(Method::cast(declarable));
case Declarable::kBuiltin:
return Visit(Builtin::cast(declarable));
case Declarable::kTypeAlias:
return Visit(TypeAlias::cast(declarable));
case Declarable::kNamespaceConstant:
return Visit(NamespaceConstant::cast(declarable));
case Declarable::kRuntimeFunction:
case Declarable::kIntrinsic:
case Declarable::kExternConstant:
case Declarable::kNamespace:
case Declarable::kGenericCallable:
case Declarable::kGenericType:
return;
}
}
std::string MachineTypeString(const Type* type) {
if (type->IsSubtypeOf(TypeOracle::GetSmiType())) {
return "MachineType::TaggedSigned()";
}
if (type->IsSubtypeOf(TypeOracle::GetHeapObjectType())) {
return "MachineType::TaggedPointer()";
}
if (type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
return "MachineType::AnyTagged()";
}
return "MachineTypeOf<" + type->GetGeneratedTNodeTypeName() + ">::value";
}
void ImplementationVisitor::GenerateBuiltinDefinitionsAndInterfaceDescriptors(
const std::string& output_directory) {
std::stringstream builtin_definitions;
std::string builtin_definitions_file_name = "builtin-definitions.h";
// This file contains plain interface descriptor definitions and has to be
// included in the middle of interface-descriptors.h. Thus it is not a normal
// header file and uses the .inc suffix instead of the .h suffix.
std::stringstream interface_descriptors;
std::string interface_descriptors_file_name = "interface-descriptors.inc";
{
IncludeGuardScope builtin_definitions_include_guard(
builtin_definitions, builtin_definitions_file_name);
builtin_definitions
<< "\n"
"#define BUILTIN_LIST_FROM_TORQUE(CPP, TFJ, TFC, TFS, TFH, "
"ASM) "
"\\\n";
for (auto& declarable : GlobalContext::AllDeclarables()) {
Builtin* builtin = Builtin::DynamicCast(declarable.get());
if (!builtin || builtin->IsExternal()) continue;
if (builtin->IsStub()) {
builtin_definitions << "TFC(" << builtin->ExternalName() << ", "
<< builtin->ExternalName();
std::string descriptor_name = builtin->ExternalName() + "Descriptor";
bool has_context_parameter = builtin->signature().HasContextParameter();
size_t kFirstNonContextParameter = has_context_parameter ? 1 : 0;
size_t parameter_count =
builtin->parameter_names().size() - kFirstNonContextParameter;
interface_descriptors
<< "class " << descriptor_name
<< " : public TorqueInterfaceDescriptor<" << parameter_count << ", "
<< (has_context_parameter ? "true" : "false") << "> {\n";
interface_descriptors << " DECLARE_DESCRIPTOR_WITH_BASE("
<< descriptor_name
<< ", TorqueInterfaceDescriptor)\n";
interface_descriptors << " MachineType ReturnType() override {\n";
interface_descriptors
<< " return "
<< MachineTypeString(builtin->signature().return_type) << ";\n";
interface_descriptors << " }\n";
interface_descriptors << " std::array<MachineType, " << parameter_count
<< "> ParameterTypes() override {\n";
interface_descriptors << " return {";
for (size_t i = kFirstNonContextParameter;
i < builtin->parameter_names().size(); ++i) {
bool last = i + 1 == builtin->parameter_names().size();
const Type* type = builtin->signature().parameter_types.types[i];
interface_descriptors << MachineTypeString(type)
<< (last ? "" : ", ");
}
interface_descriptors << "};\n";
interface_descriptors << " }\n";
interface_descriptors << "};\n\n";
} else {
builtin_definitions << "TFJ(" << builtin->ExternalName();
if (builtin->IsVarArgsJavaScript()) {
builtin_definitions << ", kDontAdaptArgumentsSentinel";
} else {
DCHECK(builtin->IsFixedArgsJavaScript());
// FixedArg javascript builtins need to offer the parameter
// count.
int parameter_count =
static_cast<int>(builtin->signature().ExplicitCount());
builtin_definitions << ", " << parameter_count;
// And the receiver is explicitly declared.
builtin_definitions << ", kReceiver";
for (size_t i = builtin->signature().implicit_count;
i < builtin->parameter_names().size(); ++i) {
Identifier* parameter = builtin->parameter_names()[i];
builtin_definitions << ", k" << CamelifyString(parameter->value);
}
}
}
builtin_definitions << ") \\\n";
}
builtin_definitions << "\n";
builtin_definitions
<< "#define TORQUE_FUNCTION_POINTER_TYPE_TO_BUILTIN_MAP(V) \\\n";
for (const BuiltinPointerType* type :
TypeOracle::AllBuiltinPointerTypes()) {
Builtin* example_builtin =
Declarations::FindSomeInternalBuiltinWithType(type);
if (!example_builtin) {
CurrentSourcePosition::Scope current_source_position(
SourcePosition{CurrentSourceFile::Get(), {-1, -1}, {-1, -1}});
ReportError("unable to find any builtin with type \"", *type, "\"");
}
builtin_definitions << " V(" << type->function_pointer_type_id() << ","
<< example_builtin->ExternalName() << ")\\\n";
}
builtin_definitions << "\n";
}
WriteFile(output_directory + "/" + builtin_definitions_file_name,
builtin_definitions.str());
WriteFile(output_directory + "/" + interface_descriptors_file_name,
interface_descriptors.str());
}
namespace {
enum class FieldSectionType : uint32_t {
kNoSection = 0,
kWeakSection = 1 << 0,
kStrongSection = 2 << 0,
kScalarSection = 3 << 0
};
bool IsPointerSection(FieldSectionType type) {
return type == FieldSectionType::kWeakSection ||
type == FieldSectionType::kStrongSection;
}
using FieldSections = base::Flags<FieldSectionType>;
std::string ToString(FieldSectionType type) {
switch (type) {
case FieldSectionType::kNoSection:
return "NoSection";
break;
case FieldSectionType::kWeakSection:
return "WeakFields";
break;
case FieldSectionType::kStrongSection:
return "StrongFields";
break;
case FieldSectionType::kScalarSection:
return "ScalarFields";
break;
}
UNREACHABLE();
}
class FieldOffsetsGenerator {
public:
explicit FieldOffsetsGenerator(const ClassType* type) : type_(type) {}
virtual void WriteField(const Field& f, const std::string& size_string) = 0;
virtual void WriteMarker(const std::string& marker) = 0;
virtual ~FieldOffsetsGenerator() { CHECK(is_finished_); }
void RecordOffsetFor(const Field& f) {
CHECK(!is_finished_);
UpdateSection(f);
// Emit kHeaderSize before any indexed field.
if (f.index.has_value() && !header_size_emitted_) {
WriteMarker("kHeaderSize");
header_size_emitted_ = true;
}
// We don't know statically how much space an indexed field takes, so report
// it as zero.
std::string size_string = "0";
if (!f.index.has_value()) {
size_t field_size;
std::tie(field_size, size_string) = f.GetFieldSizeInformation();
}
WriteField(f, size_string);
}
void Finish() {
End(current_section_);
if (!(completed_sections_ & FieldSectionType::kWeakSection)) {
Begin(FieldSectionType::kWeakSection);
End(FieldSectionType::kWeakSection);
}
if (!(completed_sections_ & FieldSectionType::kStrongSection)) {
Begin(FieldSectionType::kStrongSection);
End(FieldSectionType::kStrongSection);
}
is_finished_ = true;
// In the presence of indexed fields, we already emitted kHeaderSize before
// the indexed field.
if (!type_->IsShape() && !header_size_emitted_) {
WriteMarker("kHeaderSize");
}
if (!type_->IsAbstract() && type_->HasStaticSize()) {
WriteMarker("kSize");
}
}
protected:
const ClassType* type_;
private:
FieldSectionType GetSectionFor(const Field& f) {
const Type* field_type = f.name_and_type.type;
if (field_type == TypeOracle::GetVoidType()) {
// Allow void type for marker constants of size zero.
return current_section_;
}
StructType::Classification struct_contents =
StructType::ClassificationFlag::kEmpty;
if (auto field_as_struct = field_type->StructSupertype()) {
struct_contents = (*field_as_struct)->ClassifyContents();
}
if (struct_contents == StructType::ClassificationFlag::kMixed) {
// We can't declare what section a struct goes in if it has multiple
// categories of data within.
Error(
"Classes do not support fields which are structs containing both "
"tagged and untagged data.")
.Position(f.pos);
}
// Currently struct-valued fields are only allowed to have tagged data; see
// TypeVisitor::VisitClassFieldsAndMethods.
if (field_type->IsSubtypeOf(TypeOracle::GetTaggedType()) ||
struct_contents == StructType::ClassificationFlag::kTagged) {
if (f.is_weak) {
return FieldSectionType::kWeakSection;
} else {
return FieldSectionType::kStrongSection;
}
} else {
return FieldSectionType::kScalarSection;
}
}
void UpdateSection(const Field& f) {
FieldSectionType type = GetSectionFor(f);
if (current_section_ == type) return;
if (IsPointerSection(type)) {
if (completed_sections_ & type) {
std::stringstream s;
s << "cannot declare field " << f.name_and_type.name << " in class "
<< type_->name() << ", because section " << ToString(type)
<< " to which it belongs has already been finished.";
Error(s.str()).Position(f.pos);
}
}
End(current_section_);
current_section_ = type;
Begin(current_section_);
}
void Begin(FieldSectionType type) {
DCHECK(type != FieldSectionType::kNoSection);
if (!IsPointerSection(type)) return;
WriteMarker("kStartOf" + ToString(type) + "Offset");
}
void End(FieldSectionType type) {
if (!IsPointerSection(type)) return;
completed_sections_ |= type;
WriteMarker("kEndOf" + ToString(type) + "Offset");
}
FieldSectionType current_section_ = FieldSectionType::kNoSection;
FieldSections completed_sections_ = FieldSectionType::kNoSection;
bool is_finished_ = false;
bool header_size_emitted_ = false;
};
class MacroFieldOffsetsGenerator : public FieldOffsetsGenerator {
public:
MacroFieldOffsetsGenerator(std::ostream& out, const ClassType* type)
: FieldOffsetsGenerator(type), out_(out) {
out_ << "#define ";
out_ << "TORQUE_GENERATED_" << CapifyStringWithUnderscores(type_->name())
<< "_FIELDS(V) \\\n";
}
void WriteField(const Field& f, const std::string& size_string) override {
out_ << "V(k" << CamelifyString(f.name_and_type.name) << "Offset, "
<< size_string << ") \\\n";
}
void WriteMarker(const std::string& marker) override {
out_ << "V(" << marker << ", 0) \\\n";
}
private:
std::ostream& out_;
};
void GenerateClassExport(const ClassType* type, std::ostream& header,
std::ostream& inl_header) {
const ClassType* super = type->GetSuperClass();
std::string parent = "TorqueGenerated" + type->name() + "<" + type->name() +
", " + super->name() + ">";
header << "class " << type->name() << " : public " << parent << " {\n";
header << " public:\n";
if (type->ShouldGenerateBodyDescriptor()) {
header << " class BodyDescriptor;\n";
}
header << " TQ_OBJECT_CONSTRUCTORS(" << type->name() << ")\n";
header << "};\n\n";
inl_header << "TQ_OBJECT_CONSTRUCTORS_IMPL(" << type->name() << ")\n";
}
} // namespace
void ImplementationVisitor::GenerateClassFieldOffsets(
const std::string& output_directory) {
std::stringstream header;
std::string file_name = "field-offsets.h";
{
IncludeGuardScope include_guard(header, file_name);
for (const ClassType* type : TypeOracle::GetClasses()) {
// TODO(danno): Remove this once all classes use ClassFieldOffsetGenerator
// to generate field offsets without the use of macros.
if (!type->GenerateCppClassDefinitions() && !type->HasUndefinedLayout()) {
MacroFieldOffsetsGenerator g(header, type);
for (auto f : type->fields()) {
CurrentSourcePosition::Scope scope(f.pos);
g.RecordOffsetFor(f);
}
g.Finish();
header << "\n";
}
}
header << "#define TORQUE_INSTANCE_TYPE_TO_BODY_DESCRIPTOR_LIST(V)\\\n";
for (const ClassType* type : TypeOracle::GetClasses()) {
if (type->ShouldGenerateBodyDescriptor() && type->OwnInstanceType()) {
std::string type_name =
CapifyStringWithUnderscores(type->name()) + "_TYPE";
header << "V(" << type_name << "," << type->name() << ")\\\n";
}
}
header << "\n";
header << "#define TORQUE_DATA_ONLY_VISITOR_ID_LIST(V)\\\n";
for (const ClassType* type : TypeOracle::GetClasses()) {
if (type->ShouldGenerateBodyDescriptor() && type->HasNoPointerSlots()) {
header << "V(" << type->name() << ")\\\n";
}
}
header << "\n";
header << "#define TORQUE_POINTER_VISITOR_ID_LIST(V)\\\n";
for (const ClassType* type : TypeOracle::GetClasses()) {
if (type->ShouldGenerateBodyDescriptor() && !type->HasNoPointerSlots()) {
header << "V(" << type->name() << ")\\\n";
}
}
header << "\n";
}
const std::string output_header_path = output_directory + "/" + file_name;
WriteFile(output_header_path, header.str());
}
void ImplementationVisitor::GenerateBitFields(
const std::string& output_directory) {
std::stringstream header;
std::string file_name = "bit-fields.h";
{
IncludeGuardScope include_guard(header, file_name);
header << "#include \"src/base/bit-field.h\"\n\n";
NamespaceScope namespaces(header, {"v8", "internal"});
for (const auto& type : TypeOracle::GetBitFieldStructTypes()) {
bool all_single_bits = true; // Track whether every field is one bit.
header << "#define DEFINE_TORQUE_GENERATED_"
<< CapifyStringWithUnderscores(type->name()) << "() \\\n";
std::string type_name = type->GetConstexprGeneratedTypeName();
for (const auto& field : type->fields()) {
const char* suffix = field.num_bits == 1 ? "Bit" : "Bits";
all_single_bits = all_single_bits && field.num_bits == 1;
std::string field_type_name =
field.name_and_type.type->GetConstexprGeneratedTypeName();
header << " using " << CamelifyString(field.name_and_type.name)
<< suffix << " = base::BitField<" << field_type_name << ", "
<< field.offset << ", " << field.num_bits << ", " << type_name
<< ">; \\\n";
}
// If every field is one bit, we can also generate a convenient enum.
if (all_single_bits) {
header << " enum Flag { \\\n";
header << " kNone = 0, \\\n";
for (const auto& field : type->fields()) {
header << " k" << CamelifyString(field.name_and_type.name)
<< " = 1 << " << field.offset << ", \\\n";
}
header << " }; \\\n";
header << " using Flags = base::Flags<Flag>; \\\n";
header << " static constexpr int kFlagCount = "
<< type->fields().size() << "; \\\n";
}
header << "\n";
}
}
const std::string output_header_path = output_directory + "/" + file_name;
WriteFile(output_header_path, header.str());
}
namespace {
class ClassFieldOffsetGenerator : public FieldOffsetsGenerator {
public:
ClassFieldOffsetGenerator(std::ostream& header, const ClassType* type)
: FieldOffsetsGenerator(type),
hdr_(header),
previous_field_end_("P::kHeaderSize") {}
void WriteField(const Field& f, const std::string& size_string) override {
std::string field = "k" + CamelifyString(f.name_and_type.name) + "Offset";
std::string field_end = field + "End";
hdr_ << " static constexpr int " << field << " = " << previous_field_end_
<< ";\n";
hdr_ << " static constexpr int " << field_end << " = " << field << " + "
<< size_string << " - 1;\n";
previous_field_end_ = field_end + " + 1";
}
void WriteMarker(const std::string& marker) override {
hdr_ << " static constexpr int " << marker << " = " << previous_field_end_
<< ";\n";
}
private:
std::ostream& hdr_;
std::string previous_field_end_;
};
class CppClassGenerator {
public:
CppClassGenerator(const ClassType* type, std::ostream& header,
std::ostream& inl_header, std::ostream& impl)
: type_(type),
super_(type->GetSuperClass()),
name_(type->name()),
gen_name_("TorqueGenerated" + name_),
gen_name_T_(gen_name_ + "<D, P>"),
gen_name_I_(gen_name_ + "<" + name_ + ", " + super_->name() + ">"),
hdr_(header),
inl_(inl_header),
impl_(impl) {}
const std::string template_decl() const {
return "template <class D, class P>";
}
void GenerateClass();
private:
void GenerateClassConstructors();
void GenerateFieldAccessor(const Field& f);
void GenerateFieldAccessorForUntagged(const Field& f);
void GenerateFieldAccessorForSmi(const Field& f);
void GenerateFieldAccessorForTagged(const Field& f);
void GenerateClassCasts();
const ClassType* type_;
const ClassType* super_;
const std::string name_;
const std::string gen_name_;
const std::string gen_name_T_;
const std::string gen_name_I_;
std::ostream& hdr_;
std::ostream& inl_;
std::ostream& impl_;
};
base::Optional<std::vector<Field>> GetOrderedUniqueIndexFields(
const ClassType& type) {
std::vector<Field> result;
std::set<std::string> index_names;
for (const Field& field : type.ComputeAllFields()) {
if (field.index) {
auto name_and_type = ExtractSimpleFieldArraySize(type, *field.index);
if (!name_and_type) {
return base::nullopt;
}
index_names.insert(name_and_type->name);
}
}
for (const Field& field : type.ComputeAllFields()) {
if (index_names.count(field.name_and_type.name) != 0) {
result.push_back(field);
}
}
return result;
}
void CppClassGenerator::GenerateClass() {
hdr_ << "\n";
hdr_ << "// Alias for HeapObject::Is" << name_
<< "() that avoids inlining.\n";
hdr_ << "V8_EXPORT_PRIVATE bool Is" << name_ << "_NonInline(HeapObject o);\n";
hdr_ << "\n";
impl_ << "\n";
impl_ << "bool Is" << name_ << "_NonInline(HeapObject o) {\n";
impl_ << " return o.Is" << name_ << "();\n";
impl_ << "}\n\n";
hdr_ << template_decl() << "\n";
hdr_ << "class " << gen_name_ << " : public P {\n";
hdr_ << " static_assert(std::is_same<" << name_ << ", D>::value,\n"
<< " \"Use this class as direct base for " << name_ << ".\");\n";
hdr_ << " static_assert(std::is_same<" << super_->name() << ", P>::value,\n"
<< " \"Pass in " << super_->name()
<< " as second template parameter for " << gen_name_ << ".\");\n";
hdr_ << " public: \n";
hdr_ << " using Super = P;\n\n";
if (!type_->ShouldExport() && !type_->IsExtern()) {
hdr_ << " protected: // not extern or @export\n";
}
for (const Field& f : type_->fields()) {
GenerateFieldAccessor(f);
}
if (!type_->ShouldExport() && !type_->IsExtern()) {
hdr_ << " public:\n";
}
GenerateClassCasts();
if (type_->ShouldGeneratePrint()) {
hdr_ << "\n DECL_PRINTER(" << name_ << ")\n";
}
if (type_->ShouldGenerateVerify()) {
IfDefScope hdr_scope(hdr_, "VERIFY_HEAP");
hdr_ << " V8_EXPORT_PRIVATE void " << name_
<< "Verify(Isolate* isolate);\n";
IfDefScope impl_scope(impl_, "VERIFY_HEAP");
impl_ << "\ntemplate <>\n";
impl_ << "void " << gen_name_I_ << "::" << name_
<< "Verify(Isolate* isolate) {\n";
impl_ << " TorqueGeneratedClassVerifiers::" << name_ << "Verify(" << name_
<< "::cast(*this), "
"isolate);\n";
impl_ << "}\n";
}
hdr_ << "\n";
ClassFieldOffsetGenerator g(hdr_, type_);
for (auto f : type_->fields()) {
CurrentSourcePosition::Scope scope(f.pos);
g.RecordOffsetFor(f);
}
g.Finish();
hdr_ << "\n";
auto index_fields = GetOrderedUniqueIndexFields(*type_);
if (!index_fields.has_value()) {
hdr_ << " // SizeFor implementations not generated due to complex array "
"lengths\n\n";
} else if (!type_->IsAbstract() &&
!type_->IsSubtypeOf(TypeOracle::GetJSObjectType())) {
hdr_ << " V8_INLINE static constexpr int32_t SizeFor(";
bool first = true;
for (const Field& field : *index_fields) {
if (!first) hdr_ << ", ";
hdr_ << "int " << field.name_and_type.name;
first = false;
}
hdr_ << ") {\n";
if (index_fields->empty()) {
hdr_ << " DCHECK(kHeaderSize == kSize && kHeaderSize == "
<< *type_->size().SingleValue() << ");\n";
}
hdr_ << " int32_t size = kHeaderSize;\n";
for (const Field& field : type_->ComputeAllFields()) {
if (field.index) {
auto index_name_and_type =
*ExtractSimpleFieldArraySize(*type_, *field.index);
size_t field_size = 0;
std::tie(field_size, std::ignore) = field.GetFieldSizeInformation();
hdr_ << " size += " << index_name_and_type.name << " * "
<< field_size << ";\n";
}
if (type_->size().Alignment() < TargetArchitecture::TaggedSize()) {
hdr_ << " size = OBJECT_POINTER_ALIGN(size);\n";
}
}
hdr_ << " return size;\n";
hdr_ << " }\n\n";
hdr_ << " V8_INLINE int32_t AllocatedSize() {\n";
hdr_ << " return SizeFor(";
first = true;
for (auto field : *index_fields) {
if (!first) hdr_ << ", ";
hdr_ << "this->" << field.name_and_type.name << "()";
first = false;
}
hdr_ << ");\n }\n";
hdr_ << "\n";
}
hdr_ << " friend class Factory;\n\n";
GenerateClassConstructors();
hdr_ << "};\n\n";
if (!type_->IsExtern()) {
GenerateClassExport(type_, hdr_, inl_);
}
}
void CppClassGenerator::GenerateClassCasts() {
hdr_ << " V8_INLINE static D cast(Object object) {\n";
hdr_ << " return D(object.ptr());\n";
hdr_ << " }\n";
hdr_ << " V8_INLINE static D unchecked_cast(Object object) {\n";
hdr_ << " return bit_cast<D>(object);\n";
hdr_ << " }\n";
}
void CppClassGenerator::GenerateClassConstructors() {
hdr_ << " public:\n";
hdr_ << " template <class DAlias = D>\n";
hdr_ << " constexpr " << gen_name_ << "() : P() {\n";
hdr_ << " static_assert(std::is_base_of<" << gen_name_ << ", \n";
hdr_ << " DAlias>::value,\n";
hdr_ << " \"class " << gen_name_ << " should be used as direct base for "
<< name_ << ".\");\n";
hdr_ << " }\n";
hdr_ << " protected:\n";
hdr_ << " inline explicit " << gen_name_ << "(Address ptr);\n";
hdr_ << " // Special-purpose constructor for subclasses that have fast "
"paths where\n";
hdr_ << " // their ptr() is a Smi.\n";
hdr_ << " inline explicit " << gen_name_
<< "(Address ptr, HeapObject::AllowInlineSmiStorage allow_smi);\n";
inl_ << "template<class D, class P>\n";
inl_ << "inline " << gen_name_T_ << "::" << gen_name_ << "(Address ptr)\n";
inl_ << " : P(ptr) {\n";
inl_ << " SLOW_DCHECK(Is" << name_ << "_NonInline(*this));\n";
inl_ << "}\n";
inl_ << "template<class D, class P>\n";
inl_ << "inline " << gen_name_T_ << "::" << gen_name_
<< "(Address ptr, HeapObject::AllowInlineSmiStorage allow_smi)\n";
inl_ << " : P(ptr, allow_smi) {\n";
inl_ << " SLOW_DCHECK("
<< "(allow_smi == HeapObject::AllowInlineSmiStorage::kAllowBeingASmi"
" && this->IsSmi()) || Is"
<< name_ << "_NonInline(*this));\n";
inl_ << "}\n";
}
namespace {
std::string GenerateRuntimeTypeCheck(const Type* type,
const std::string& value) {
bool maybe_object = !type->IsSubtypeOf(TypeOracle::GetStrongTaggedType());
std::stringstream type_check;
bool at_start = true;
// If weak pointers are allowed, then start by checking for a cleared value.
if (maybe_object) {
type_check << value << ".IsCleared()";
at_start = false;
}
for (const TypeChecker& runtime_type : type->GetTypeCheckers()) {
if (!at_start) type_check << " || ";
at_start = false;
if (maybe_object) {
bool strong = runtime_type.weak_ref_to.empty();
if (strong && runtime_type.type == WEAK_HEAP_OBJECT) {
// Rather than a generic Weak<T>, this is the basic type WeakHeapObject.
// We can't validate anything more about the type of the object pointed
// to, so just check that it's weak.
type_check << value << ".IsWeak()";
} else {
type_check << "(" << (strong ? "!" : "") << value << ".IsWeak() && "
<< value << ".GetHeapObjectOrSmi().Is"
<< (strong ? runtime_type.type : runtime_type.weak_ref_to)
<< "())";
}
} else {
type_check << value << ".Is" << runtime_type.type << "()";
}
}
return type_check.str();
}
void GenerateBoundsDCheck(std::ostream& os, const std::string& index,
const ClassType* type, const Field& f) {
os << " DCHECK_GE(" << index << ", 0);\n";
if (base::Optional<NameAndType> array_length =
ExtractSimpleFieldArraySize(*type, *f.index)) {
os << " DCHECK_LT(" << index << ", this->" << array_length->name
<< "());\n";
}
}
} // namespace
// TODO(sigurds): Keep in sync with DECL_ACCESSORS and ACCESSORS macro.
void CppClassGenerator::GenerateFieldAccessor(const Field& f) {
const Type* field_type = f.name_and_type.type;
if (field_type == TypeOracle::GetVoidType()) return;
// TODO(danno): Support generation of struct accessors
if (f.name_and_type.type->IsStructType()) return;
// TODO(v8:10391) Generate accessors for external pointers
if (f.name_and_type.type->IsSubtypeOf(TypeOracle::GetExternalPointerType())) {
return;
}
if (!f.name_and_type.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
return GenerateFieldAccessorForUntagged(f);
}
if (f.name_and_type.type->IsSubtypeOf(TypeOracle::GetSmiType())) {
return GenerateFieldAccessorForSmi(f);
}
if (f.name_and_type.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
return GenerateFieldAccessorForTagged(f);
}
Error("Generation of field accessor for ", type_->name(),
"::", f.name_and_type.name, " failed (type ", *field_type,
" is not supported).")
.Position(f.pos);
}
void CppClassGenerator::GenerateFieldAccessorForUntagged(const Field& f) {
DCHECK(!f.name_and_type.type->IsSubtypeOf(TypeOracle::GetTaggedType()));
const Type* field_type = f.name_and_type.type;
if (field_type == TypeOracle::GetVoidType()) return;
const Type* constexpr_version = field_type->ConstexprVersion();
if (!constexpr_version) {
Error("Field accessor for ", type_->name(), ":: ", f.name_and_type.name,
" cannot be generated because its type ", *field_type,
" is neither a subclass of Object nor does the type have a constexpr "
"version.")
.Position(f.pos);
return;
}
const std::string& name = f.name_and_type.name;
const std::string type = constexpr_version->GetGeneratedTypeName();
std::string offset = "k" + CamelifyString(name) + "Offset";
// Generate declarations in header.
if (f.index) {
hdr_ << " inline " << type << " " << name << "(int i) const;\n";
hdr_ << " inline void set_" << name << "(int i, " << type
<< " value);\n\n";
} else {
hdr_ << " inline " << type << " " << name << "() const;\n";
hdr_ << " inline void set_" << name << "(" << type << " value);\n\n";
}
// Generate implementation in inline header.
inl_ << "template <class D, class P>\n";
inl_ << type << " " << gen_name_ << "<D, P>::" << name << "(";
if (f.index) {
inl_ << "int i";
}
inl_ << ") const {\n";
if (f.index) {
GenerateBoundsDCheck(inl_, "i", type_, f);
size_t field_size;
std::string size_string;
std::tie(field_size, size_string) = f.GetFieldSizeInformation();
inl_ << " int offset = " << offset << " + i * " << field_size << ";\n";
inl_ << " return this->template ReadField<" << type << ">(offset);\n";
} else {
inl_ << " return this->template ReadField<" << type << ">(" << offset
<< ");\n";
}
inl_ << "}\n";
inl_ << "template <class D, class P>\n";
inl_ << "void " << gen_name_ << "<D, P>::set_" << name << "(";
if (f.index) {
inl_ << "int i, ";
}
inl_ << type << " value) {\n";
if (f.index) {
GenerateBoundsDCheck(inl_, "i", type_, f);
size_t field_size;
std::string size_string;
std::tie(field_size, size_string) = f.GetFieldSizeInformation();
inl_ << " int offset = " << offset << " + i * " << field_size << ";\n";
inl_ << " this->template WriteField<" << type << ">(offset, value);\n";
} else {
inl_ << " this->template WriteField<" << type << ">(" << offset
<< ", value);\n";
}
inl_ << "}\n\n";
}
void CppClassGenerator::GenerateFieldAccessorForSmi(const Field& f) {
DCHECK(f.name_and_type.type->IsSubtypeOf(TypeOracle::GetSmiType()));
// Follow the convention to create Smi accessors with type int.
const std::string type = "int";
const std::string& name = f.name_and_type.name;
const std::string offset = "k" + CamelifyString(name) + "Offset";
// Generate declarations in header.
if (f.index) {
hdr_ << " inline " << type << " " << name << "(int i) const;\n";
hdr_ << " inline void set_" << name << "(int i, " << type
<< " value);\n\n";
}
hdr_ << " inline " << type << " " << name << "() const;\n";
hdr_ << " inline void set_" << name << "(" << type << " value);\n\n";
// Generate implementation in inline header.
inl_ << "template <class D, class P>\n";
inl_ << type << " " << gen_name_ << "<D, P>::" << name << "(";
if (f.index) {
inl_ << "int i";
}
inl_ << ") const {\n";
if (f.index) {
GenerateBoundsDCheck(inl_, "i", type_, f);
inl_ << " int offset = " << offset << " + i * kTaggedSize;\n";
inl_ << " return this->template ReadField<Smi>(offset).value();\n";
inl_ << "}\n";
} else {
inl_ << " return TaggedField<Smi, " << offset
<< ">::load(*this).value();\n";
inl_ << "}\n";
}
inl_ << "template <class D, class P>\n";
inl_ << "void " << gen_name_ << "<D, P>::set_" << name << "(";
if (f.index) {
inl_ << "int i, ";
}
inl_ << type << " value) {\n";
if (f.index) {
GenerateBoundsDCheck(inl_, "i", type_, f);
inl_ << " int offset = " << offset << " + i * kTaggedSize;\n";
inl_ << " WRITE_FIELD(*this, offset, Smi::FromInt(value));\n";
} else {
inl_ << " WRITE_FIELD(*this, " << offset << ", Smi::FromInt(value));\n";
}
inl_ << "}\n\n";
}
void CppClassGenerator::GenerateFieldAccessorForTagged(const Field& f) {
const Type* field_type = f.name_and_type.type;
DCHECK(field_type->IsSubtypeOf(TypeOracle::GetTaggedType()));
const std::string& name = f.name_and_type.name;
std::string offset = "k" + CamelifyString(name) + "Offset";
bool strong_pointer = field_type->IsSubtypeOf(TypeOracle::GetObjectType());
std::string type = field_type->UnhandlifiedCppTypeName();
// Generate declarations in header.
if (!field_type->IsClassType() && field_type != TypeOracle::GetObjectType()) {
hdr_ << " // Torque type: " << field_type->ToString() << "\n";
}
hdr_ << " inline " << type << " " << name << "(" << (f.index ? "int i" : "")
<< ") const;\n";
hdr_ << " inline " << type << " " << name << "(IsolateRoot isolates"
<< (f.index ? ", int i" : "") << ") const;\n";
hdr_ << " inline void set_" << name << "(" << (f.index ? "int i, " : "")
<< type << " value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);\n\n";
std::string type_check = GenerateRuntimeTypeCheck(field_type, "value");
// Generate implementation in inline header.
inl_ << "template <class D, class P>\n";
inl_ << type << " " << gen_name_ << "<D, P>::" << name << "("
<< (f.index ? "int i" : "") << ") const {\n";
inl_ << " IsolateRoot isolate = GetIsolateForPtrCompr(*this);\n";
inl_ << " return " << gen_name_ << "::" << name << "(isolate"
<< (f.index ? ", i" : "") << ");\n";
inl_ << "}\n";
inl_ << "template <class D, class P>\n";
inl_ << type << " " << gen_name_ << "<D, P>::" << name
<< "(IsolateRoot isolate" << (f.index ? ", int i" : "") << ") const {\n";
// TODO(tebbi): The distinction between relaxed and non-relaxed accesses here
// is pretty arbitrary and just tries to preserve what was there before.
// It currently doesn't really make a difference due to concurrent marking
// turning all loads and stores to be relaxed. We should probably drop the
// distinction at some point, even though in principle non-relaxed operations
// would give us TSAN protection.
if (f.index) {
GenerateBoundsDCheck(inl_, "i", type_, f);
inl_ << " int offset = " << offset << " + i * kTaggedSize;\n";
inl_ << " auto value = TaggedField<" << type
<< ">::Relaxed_Load(isolate, *this, offset);\n";
} else {
inl_ << " auto value = TaggedField<" << type << ", " << offset
<< ">::load(isolate, *this);\n";
}
if (!type_check.empty()) {
inl_ << " DCHECK(" << type_check << ");\n";
}
inl_ << " return value;\n";
inl_ << "}\n";
inl_ << "template <class D, class P>\n";
inl_ << "void " << gen_name_ << "<D, P>::set_" << name << "(";
if (f.index) {
inl_ << "int i, ";
}
inl_ << type << " value, WriteBarrierMode mode) {\n";
if (!type_check.empty()) {
inl_ << " SLOW_DCHECK(" << type_check << ");\n";
}
if (f.index) {
GenerateBoundsDCheck(inl_, "i", type_, f);
const char* write_macro =
strong_pointer ? "WRITE_FIELD" : "RELAXED_WRITE_WEAK_FIELD";
inl_ << " int offset = " << offset << " + i * kTaggedSize;\n";
offset = "offset";
inl_ << " " << write_macro << "(*this, offset, value);\n";
} else {
const char* write_macro =
strong_pointer ? "RELAXED_WRITE_FIELD" : "RELAXED_WRITE_WEAK_FIELD";
inl_ << " " << write_macro << "(*this, " << offset << ", value);\n";
}
const char* write_barrier = strong_pointer ? "CONDITIONAL_WRITE_BARRIER"
: "CONDITIONAL_WEAK_WRITE_BARRIER";
inl_ << " " << write_barrier << "(*this, " << offset << ", value, mode);\n";
inl_ << "}\n\n";
}
void GenerateStructLayoutDescription(std::ostream& header,
const StructType* type) {
header << "struct TorqueGenerated" << CamelifyString(type->name())
<< "Offsets {\n";
for (const Field& field : type->fields()) {
header << " static constexpr int k"
<< CamelifyString(field.name_and_type.name)
<< "Offset = " << *field.offset << ";\n";
}
header << " static constexpr int kSize = " << type->PackedSize() << ";\n";
header << "};\n\n";
}
} // namespace
void ImplementationVisitor::GenerateClassDefinitions(
const std::string& output_directory) {
std::stringstream factory_header;
std::stringstream factory_impl;
std::string factory_basename = "factory";
std::stringstream forward_declarations;
std::string forward_declarations_filename = "class-forward-declarations.h";
{
factory_impl << "#include \"src/heap/factory.h\"\n";
factory_impl << "#include \"src/heap/factory-inl.h\"\n";
factory_impl << "#include \"src/heap/heap.h\"\n";
factory_impl << "#include \"src/heap/heap-inl.h\"\n";
factory_impl << "#include \"src/execution/isolate.h\"\n";
factory_impl << "#include "
"\"src/objects/all-objects-inl.h\"\n\n";
NamespaceScope factory_impl_namespaces(factory_impl, {"v8", "internal"});
factory_impl << "\n";
IncludeGuardScope include_guard(forward_declarations,
forward_declarations_filename);
NamespaceScope forward_declarations_namespaces(forward_declarations,
{"v8", "internal"});
std::set<const StructType*, TypeLess> structs_used_in_classes;
// Emit forward declarations.
for (const ClassType* type : TypeOracle::GetClasses()) {
auto& streams = GlobalContext::GeneratedPerFile(type->AttributedToFile());
std::ostream& header = streams.class_definition_headerfile;
header << "class " << type->GetGeneratedTNodeTypeName() << ";\n";
forward_declarations << "class " << type->GetGeneratedTNodeTypeName()
<< ";\n";
}
for (const ClassType* type : TypeOracle::GetClasses()) {
auto& streams = GlobalContext::GeneratedPerFile(type->AttributedToFile());
std::ostream& header = streams.class_definition_headerfile;
std::ostream& inline_header = streams.class_definition_inline_headerfile;
std::ostream& implementation = streams.class_definition_ccfile;
if (type->GenerateCppClassDefinitions()) {
CppClassGenerator g(type, header, inline_header, implementation);
g.GenerateClass();
}
for (const Field& f : type->fields()) {
const Type* field_type = f.name_and_type.type;
if (auto field_as_struct = field_type->StructSupertype()) {
structs_used_in_classes.insert(*field_as_struct);
}
}
if (type->ShouldExport() && !type->IsAbstract()) {
factory_header << type->HandlifiedCppTypeName() << " New"
<< type->name() << "(";
factory_impl << type->HandlifiedCppTypeName() << " Factory::New"
<< type->name() << "(";
for (const Field& f : type->ComputeAllFields()) {
if (f.name_and_type.name == "map") continue;
if (!f.index) {
std::string type_string =
f.name_and_type.type->HandlifiedCppTypeName();
factory_header << type_string << " " << f.name_and_type.name
<< ", ";
factory_impl << type_string << " " << f.name_and_type.name << ", ";
}
}
factory_header << "AllocationType allocation_type);\n";
factory_impl << "AllocationType allocation_type) {\n";
factory_impl << " int size = ";
const ClassType* super = type->GetSuperClass();
std::string gen_name = "TorqueGenerated" + type->name();
std::string gen_name_T =
gen_name + "<" + type->name() + ", " + super->name() + ">";
factory_impl << gen_name_T << "::SizeFor(";
bool first = true;
auto index_fields = GetOrderedUniqueIndexFields(*type);
CHECK(index_fields.has_value());
for (auto index_field : *index_fields) {
if (!first) {
factory_impl << ", ";
}
factory_impl << index_field.name_and_type.name;
first = false;
}
factory_impl << ");\n";
factory_impl << " ReadOnlyRoots roots(isolate());\n";
factory_impl << " HeapObject result =\n";
factory_impl << " "
"isolate()->heap()->AllocateRawWith<Heap::kRetryOrFail>"
"(size, allocation_type);\n";
factory_impl << " WriteBarrierMode write_barrier_mode =\n"
<< " allocation_type == AllocationType::kYoung\n"
<< " ? SKIP_WRITE_BARRIER : UPDATE_WRITE_BARRIER;\n";
factory_impl << " result.set_map_after_allocation(roots."
<< SnakeifyString(type->name())
<< "_map(), write_barrier_mode);\n";
factory_impl << " " << type->HandlifiedCppTypeName()
<< " result_handle(" << type->name()
<< "::cast(result), isolate());\n";
for (const Field& f : type->ComputeAllFields()) {
if (f.name_and_type.name == "map") continue;
if (!f.index) {
factory_impl << " result_handle->set_"
<< SnakeifyString(f.name_and_type.name) << "(";
if (f.name_and_type.type->IsSubtypeOf(
TypeOracle::GetTaggedType()) &&
!f.name_and_type.type->IsSubtypeOf(TypeOracle::GetSmiType())) {
factory_impl << "*" << f.name_and_type.name
<< ", write_barrier_mode";
} else {
factory_impl << f.name_and_type.name;
}
factory_impl << ");\n";
}
}
factory_impl << " return result_handle;\n";
factory_impl << "}\n\n";
}
}
for (const StructType* type : structs_used_in_classes) {
std::ostream& header =
GlobalContext::GeneratedPerFile(type->GetPosition().source)
.class_definition_headerfile;
if (type != TypeOracle::GetFloat64OrHoleType()) {
GenerateStructLayoutDescription(header, type);
}
}
}
WriteFile(output_directory + "/" + factory_basename + ".inc",
factory_header.str());
WriteFile(output_directory + "/" + factory_basename + ".cc",
factory_impl.str());
WriteFile(output_directory + "/" + forward_declarations_filename,
forward_declarations.str());
}
namespace {
void GeneratePrintDefinitionsForClass(std::ostream& impl, const ClassType* type,
const std::string& gen_name,
const std::string& gen_name_T,
const std::string template_params) {
impl << template_params << "\n";
impl << "void " << gen_name_T << "::" << type->name()
<< "Print(std::ostream& os) {\n";
impl << " this->PrintHeader(os, \"" << type->name() << "\");\n";
auto hierarchy = type->GetHierarchy();
std::map<std::string, const AggregateType*> field_names;
for (const AggregateType* aggregate_type : hierarchy) {
for (const Field& f : aggregate_type->fields()) {
if (f.name_and_type.name == "map") continue;
if (!f.index.has_value()) {
if (f.name_and_type.type->IsSubtypeOf(TypeOracle::GetSmiType()) ||
!f.name_and_type.type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
impl << " os << \"\\n - " << f.name_and_type.name << ": \" << ";
if (f.name_and_type.type->StructSupertype()) {
// TODO(tebbi): Print struct fields too.
impl << "\" <struct field printing still unimplemented>\";\n";
} else {
impl << "this->" << f.name_and_type.name << "();\n";
}
} else {
impl << " os << \"\\n - " << f.name_and_type.name << ": \" << "
<< "Brief(this->" << f.name_and_type.name << "());\n";
}
}
}
}
impl << " os << '\\n';\n";
impl << "}\n\n";
}
} // namespace
void ImplementationVisitor::GeneratePrintDefinitions(
const std::string& output_directory) {
std::stringstream impl;
std::string file_name = "objects-printer.cc";
{
IfDefScope object_print(impl, "OBJECT_PRINT");
impl << "#include <iosfwd>\n\n";
impl << "#include \"src/objects/all-objects-inl.h\"\n\n";
NamespaceScope impl_namespaces(impl, {"v8", "internal"});
for (const ClassType* type : TypeOracle::GetClasses()) {
if (!type->ShouldGeneratePrint()) continue;
if (type->GenerateCppClassDefinitions()) {
const ClassType* super = type->GetSuperClass();
std::string gen_name = "TorqueGenerated" + type->name();
std::string gen_name_T =
gen_name + "<" + type->name() + ", " + super->name() + ">";
std::string template_decl = "template <>";
GeneratePrintDefinitionsForClass(impl, type, gen_name, gen_name_T,
template_decl);
} else {
GeneratePrintDefinitionsForClass(impl, type, type->name(), type->name(),
"");
}
}
}
std::string new_contents(impl.str());
WriteFile(output_directory + "/" + file_name, new_contents);
}
base::Optional<std::string> MatchSimpleBodyDescriptor(const ClassType* type) {
std::vector<ObjectSlotKind> slots = type->ComputeHeaderSlotKinds();
if (!type->HasStaticSize()) {
slots.push_back(*type->ComputeArraySlotKind());
}
// Skip the map slot.
size_t i = 1;
while (i < slots.size() && slots[i] == ObjectSlotKind::kNoPointer) ++i;
if (i == slots.size()) return "DataOnlyBodyDescriptor";
bool has_weak_pointers = false;
size_t start_index = i;
for (; i < slots.size(); ++i) {
if (slots[i] == ObjectSlotKind::kStrongPointer) {
continue;
} else if (slots[i] == ObjectSlotKind::kMaybeObjectPointer) {
has_weak_pointers = true;
} else if (slots[i] == ObjectSlotKind::kNoPointer) {
break;
} else {
return base::nullopt;
}
}
size_t end_index = i;
for (; i < slots.size(); ++i) {
if (slots[i] != ObjectSlotKind::kNoPointer) return base::nullopt;
}
size_t start_offset = start_index * TargetArchitecture::TaggedSize();
size_t end_offset = end_index * TargetArchitecture::TaggedSize();
// We pick a suffix-range body descriptor even in cases where the object size
// is fixed, to reduce the amount of code executed for object visitation.
if (end_index == slots.size()) {
return ToString("SuffixRange", has_weak_pointers ? "Weak" : "",
"BodyDescriptor<", start_offset, ">");
}
if (!has_weak_pointers) {
return ToString("FixedRangeDescriptor<", start_offset, ", ", end_offset,
", ", *type->size().SingleValue(), ">");
}
return base::nullopt;
}
void ImplementationVisitor::GenerateBodyDescriptors(
const std::string& output_directory) {
std::string file_name = "objects-body-descriptors-inl.inc";
std::stringstream h_contents;
for (const ClassType* type : TypeOracle::GetClasses()) {
std::string name = type->name();
if (!type->ShouldGenerateBodyDescriptor()) continue;
bool has_array_fields = !type->HasStaticSize();
std::vector<ObjectSlotKind> header_slot_kinds =
type->ComputeHeaderSlotKinds();
base::Optional<ObjectSlotKind> array_slot_kind =
type->ComputeArraySlotKind();
DCHECK_EQ(has_array_fields, array_slot_kind.has_value());
h_contents << "class " << name << "::BodyDescriptor final : public ";
if (auto descriptor_name = MatchSimpleBodyDescriptor(type)) {
h_contents << *descriptor_name << " {\n";
h_contents << " public:\n";
} else {
h_contents << "BodyDescriptorBase {\n";
h_contents << " public:\n";
h_contents << " static bool IsValidSlot(Map map, HeapObject obj, int "
"offset) {\n";
if (has_array_fields) {
h_contents << " if (offset < kHeaderSize) {\n";
}
h_contents << " bool valid_slots[] = {";
for (ObjectSlotKind slot : header_slot_kinds) {
h_contents << (slot != ObjectSlotKind::kNoPointer ? "1" : "0") << ",";
}
h_contents << "};\n"
<< " return valid_slots[static_cast<unsigned "
"int>(offset)/kTaggedSize];\n";
if (has_array_fields) {
h_contents << " }\n";
bool array_is_tagged = *array_slot_kind != ObjectSlotKind::kNoPointer;
h_contents << " return " << (array_is_tagged ? "true" : "false")
<< ";\n";
}
h_contents << " }\n\n";
h_contents << " template <typename ObjectVisitor>\n";
h_contents
<< " static inline void IterateBody(Map map, HeapObject obj, "
"int object_size, ObjectVisitor* v) {\n";
std::vector<ObjectSlotKind> slots = std::move(header_slot_kinds);
if (has_array_fields) slots.push_back(*array_slot_kind);
// Skip the map slot.
slots.erase(slots.begin());
size_t start_offset = TargetArchitecture::TaggedSize();
size_t end_offset = start_offset;
ObjectSlotKind section_kind;
for (size_t i = 0; i <= slots.size(); ++i) {
base::Optional<ObjectSlotKind> next_section_kind;
bool finished_section = false;
if (i == 0) {
next_section_kind = slots[i];
} else if (i < slots.size()) {
if (auto combined = Combine(section_kind, slots[i])) {
next_section_kind = *combined;
} else {
next_section_kind = slots[i];
finished_section = true;
}
} else {
finished_section = true;
}
if (finished_section) {
bool is_array_slot = i == slots.size() && has_array_fields;
bool multiple_slots =
is_array_slot ||
(end_offset - start_offset > TargetArchitecture::TaggedSize());
base::Optional<std::string> iterate_command;
switch (section_kind) {
case ObjectSlotKind::kStrongPointer:
iterate_command = "IteratePointer";
break;
case ObjectSlotKind::kMaybeObjectPointer:
iterate_command = "IterateMaybeWeakPointer";
break;
case ObjectSlotKind::kCustomWeakPointer:
iterate_command = "IterateCustomWeakPointer";
break;
case ObjectSlotKind::kNoPointer:
break;
}
if (iterate_command) {
if (multiple_slots) *iterate_command += "s";
h_contents << " " << *iterate_command << "(obj, "
<< start_offset;
if (multiple_slots) {
h_contents << ", "
<< (i == slots.size() ? "object_size"
: std::to_string(end_offset));
}
h_contents << ", v);\n";
}
start_offset = end_offset;
}
if (i < slots.size()) section_kind = *next_section_kind;
end_offset += TargetArchitecture::TaggedSize();
}
h_contents << " }\n\n";
}
h_contents
<< " static inline int SizeOf(Map map, HeapObject raw_object) {\n";
if (type->size().SingleValue()) {
h_contents << " return " << *type->size().SingleValue() << ";\n";
} else {
h_contents << " return " << name
<< "::cast(raw_object).AllocatedSize();\n";
}
h_contents << " }\n\n";
h_contents << "};\n";
}
WriteFile(output_directory + "/" + file_name, h_contents.str());
}
namespace {
// Generate verification code for a single piece of class data, which might be
// nested within a struct or might be a single element in an indexed field (or
// both).
void GenerateFieldValueVerifier(const std::string& class_name, bool indexed,
std::string offset, const Field& leaf_field,
std::string indexed_field_size,
std::ostream& cc_contents) {
const Type* field_type = leaf_field.name_and_type.type;
bool maybe_object =
!field_type->IsSubtypeOf(TypeOracle::GetStrongTaggedType());
const char* object_type = maybe_object ? "MaybeObject" : "Object";
const char* verify_fn =
maybe_object ? "VerifyMaybeObjectPointer" : "VerifyPointer";
if (indexed) {
offset += " + i * " + indexed_field_size;
}
// Name the local var based on the field name for nicer CHECK output.
const std::string value = leaf_field.name_and_type.name + "__value";
// Read the field.
cc_contents << " " << object_type << " " << value << " = TaggedField<"
<< object_type << ">::load(o, " << offset << ");\n";
// Call VerifyPointer or VerifyMaybeObjectPointer on it.
cc_contents << " " << object_type << "::" << verify_fn << "(isolate, "
<< value << ");\n";
// Check that the value is of an appropriate type. We can skip this part for
// the Object type because it would not check anything beyond what we already
// checked with VerifyPointer.
if (field_type != TypeOracle::GetObjectType()) {
cc_contents << " CHECK(" << GenerateRuntimeTypeCheck(field_type, value)
<< ");\n";
}
}
void GenerateClassFieldVerifier(const std::string& class_name,
const ClassType& class_type, const Field& f,
std::ostream& h_contents,
std::ostream& cc_contents) {
if (!f.generate_verify) return;
const Type* field_type = f.name_and_type.type;
// We only verify tagged types, not raw numbers or pointers. Structs
// consisting of tagged types are also included.
if (!field_type->IsSubtypeOf(TypeOracle::GetTaggedType()) &&
!field_type->StructSupertype())
return;
if (field_type == TypeOracle::GetFloat64OrHoleType()) return;
// Do not verify if the field may be uninitialized.
if (TypeOracle::GetUninitializedType()->IsSubtypeOf(field_type)) return;
std::string field_start_offset;
if (f.index) {
field_start_offset = f.name_and_type.name + "__offset";
std::string length = f.name_and_type.name + "__length";
cc_contents << " intptr_t " << field_start_offset << ", " << length
<< ";\n";
cc_contents << " std::tie(std::ignore, " << field_start_offset << ", "
<< length << ") = "
<< Callable::PrefixNameForCCOutput(
class_type.GetSliceMacroName(f))
<< "(isolate, o);\n";
// Slices use intptr, but TaggedField<T>.load() uses int, so verify that
// such a cast is valid.
cc_contents << " CHECK_EQ(" << field_start_offset << ", static_cast<int>("
<< field_start_offset << "));\n";
cc_contents << " CHECK_EQ(" << length << ", static_cast<int>(" << length
<< "));\n";
field_start_offset = "static_cast<int>(" + field_start_offset + ")";
length = "static_cast<int>(" + length + ")";
cc_contents << " for (int i = 0; i < " << length << "; ++i) {\n";
} else {
// Non-indexed fields have known offsets.
field_start_offset = std::to_string(*f.offset);
cc_contents << " {\n";
}
if (auto struct_type = field_type->StructSupertype()) {
for (const Field& struct_field : (*struct_type)->fields()) {
if (struct_field.name_and_type.type->IsSubtypeOf(
TypeOracle::GetTaggedType())) {
GenerateFieldValueVerifier(
class_name, f.index.has_value(),
field_start_offset + " + " + std::to_string(*struct_field.offset),
struct_field, std::to_string((*struct_type)->PackedSize()),
cc_contents);
}
}
} else {
GenerateFieldValueVerifier(class_name, f.index.has_value(),
field_start_offset, f, "kTaggedSize",
cc_contents);
}
cc_contents << " }\n";
}
} // namespace
void ImplementationVisitor::GenerateClassVerifiers(
const std::string& output_directory) {
std::string file_name = "class-verifiers";
std::stringstream h_contents;
std::stringstream cc_contents;
{
IncludeGuardScope include_guard(h_contents, file_name + ".h");
IfDefScope verify_heap_h(h_contents, "VERIFY_HEAP");
IfDefScope verify_heap_cc(cc_contents, "VERIFY_HEAP");
cc_contents << "\n#include \"src/objects/objects.h\"\n";
for (const std::string& include_path : GlobalContext::CppIncludes()) {
cc_contents << "#include " << StringLiteralQuote(include_path) << "\n";
}
cc_contents << "#include \"torque-generated/" << file_name << ".h\"\n";
cc_contents << "#include "
"\"src/objects/all-objects-inl.h\"\n";
cc_contents << "#include \"torque-generated/runtime-macros.h\"\n";
IncludeObjectMacrosScope object_macros(cc_contents);
NamespaceScope h_namespaces(h_contents, {"v8", "internal"});
NamespaceScope cc_namespaces(cc_contents, {"v8", "internal"});
// Generate forward declarations to avoid including any headers.
h_contents << "class Isolate;\n";
for (const ClassType* type : TypeOracle::GetClasses()) {
if (!type->ShouldGenerateVerify()) continue;
h_contents << "class " << type->name() << ";\n";
}
const char* verifier_class = "TorqueGeneratedClassVerifiers";
h_contents << "class V8_EXPORT_PRIVATE " << verifier_class << "{\n";
h_contents << " public:\n";
for (const ClassType* type : TypeOracle::GetClasses()) {
std::string name = type->name();
if (!type->ShouldGenerateVerify()) continue;
std::string method_name = name + "Verify";
h_contents << " static void " << method_name << "(" << name
<< " o, Isolate* isolate);\n";
cc_contents << "void " << verifier_class << "::" << method_name << "("
<< name << " o, Isolate* isolate) {\n";
// First, do any verification for the super class. Not all classes have
// verifiers, so skip to the nearest super class that has one.
const ClassType* super_type = type->GetSuperClass();
while (super_type && !super_type->ShouldGenerateVerify()) {
super_type = super_type->GetSuperClass();
}
if (super_type) {
std::string super_name = super_type->name();
if (super_name == "HeapObject") {
// Special case: HeapObjectVerify checks the Map type and dispatches
// to more specific types, so calling it here would cause infinite
// recursion. We could consider moving that behavior into a
// different method to make the contract of *Verify methods more
// consistent, but for now we'll just avoid the bad case.
cc_contents << " " << super_name << "Verify(o, isolate);\n";
} else {
cc_contents << " o." << super_name << "Verify(isolate);\n";
}
}
// Second, verify that this object is what it claims to be.
cc_contents << " CHECK(o.Is" << name << "());\n";
// Third, verify its properties.
for (auto f : type->fields()) {
GenerateClassFieldVerifier(name, *type, f, h_contents, cc_contents);
}
cc_contents << "}\n";
}
h_contents << "};\n";
}
WriteFile(output_directory + "/" + file_name + ".h", h_contents.str());
WriteFile(output_directory + "/" + file_name + ".cc", cc_contents.str());
}
void ImplementationVisitor::GenerateEnumVerifiers(
const std::string& output_directory) {
std::string file_name = "enum-verifiers";
std::stringstream cc_contents;
{
cc_contents << "#include \"src/compiler/code-assembler.h\"\n";
for (const std::string& include_path : GlobalContext::CppIncludes()) {
cc_contents << "#include " << StringLiteralQuote(include_path) << "\n";
}
cc_contents << "\n";
NamespaceScope cc_namespaces(cc_contents, {"v8", "internal", ""});
cc_contents << "class EnumVerifier {\n";
for (const auto& desc : GlobalContext::Get().ast()->EnumDescriptions()) {
cc_contents << " // " << desc.name << " (" << desc.pos << ")\n";
cc_contents << " void VerifyEnum_" << desc.name << "("
<< desc.constexpr_generates
<< " x) {\n"
" switch(x) {\n";
for (const auto& entry : desc.entries) {
cc_contents << " case " << entry << ": break;\n";
}
if (desc.is_open) cc_contents << " default: break;\n";
cc_contents << " }\n }\n\n";
}
cc_contents << "};\n";
}
WriteFile(output_directory + "/" + file_name + ".cc", cc_contents.str());
}
void ImplementationVisitor::GenerateExportedMacrosAssembler(
const std::string& output_directory) {
std::string file_name = "exported-macros-assembler";
std::stringstream h_contents;
std::stringstream cc_contents;
{
IncludeGuardScope include_guard(h_contents, file_name + ".h");
h_contents << "#include \"src/compiler/code-assembler.h\"\n";
h_contents << "#include \"src/execution/frames.h\"\n";
h_contents << "#include \"torque-generated/csa-types.h\"\n";
cc_contents << "#include \"src/objects/fixed-array-inl.h\"\n";
cc_contents << "#include \"src/objects/free-space.h\"\n";
cc_contents << "#include \"src/objects/js-regexp-string-iterator.h\"\n";
cc_contents << "#include \"src/objects/ordered-hash-table.h\"\n";
cc_contents << "#include \"src/objects/property-descriptor-object.h\"\n";
cc_contents << "#include \"src/objects/synthetic-module.h\"\n";
cc_contents << "#include \"src/objects/template-objects.h\"\n";
{
IfDefScope intl_scope(cc_contents, "V8_INTL_SUPPORT");
cc_contents << "#include \"src/objects/js-break-iterator.h\"\n";
cc_contents << "#include \"src/objects/js-collator.h\"\n";
cc_contents << "#include \"src/objects/js-date-time-format.h\"\n";
cc_contents << "#include \"src/objects/js-display-names.h\"\n";
cc_contents << "#include \"src/objects/js-list-format.h\"\n";
cc_contents << "#include \"src/objects/js-locale.h\"\n";
cc_contents << "#include \"src/objects/js-number-format.h\"\n";
cc_contents << "#include \"src/objects/js-plural-rules.h\"\n";
cc_contents << "#include \"src/objects/js-relative-time-format.h\"\n";
cc_contents << "#include \"src/objects/js-segment-iterator.h\"\n";
cc_contents << "#include \"src/objects/js-segmenter.h\"\n";
cc_contents << "#include \"src/objects/js-segments.h\"\n";
}
cc_contents << "#include \"torque-generated/" << file_name << ".h\"\n";
for (SourceId file : SourceFileMap::AllSources()) {
cc_contents << "#include \"torque-generated/" +
SourceFileMap::PathFromV8RootWithoutExtension(file) +
"-tq-csa.h\"\n";
}
NamespaceScope h_namespaces(h_contents, {"v8", "internal"});
NamespaceScope cc_namespaces(cc_contents, {"v8", "internal"});
h_contents << "class V8_EXPORT_PRIVATE "
"TorqueGeneratedExportedMacrosAssembler {\n"
<< " public:\n"
<< " explicit TorqueGeneratedExportedMacrosAssembler"
"(compiler::CodeAssemblerState* state) : state_(state) {\n"
<< " USE(state_);\n"
<< " }\n";
for (auto& declarable : GlobalContext::AllDeclarables()) {
TorqueMacro* macro = TorqueMacro::DynamicCast(declarable.get());
if (!(macro && macro->IsExportedToCSA())) continue;
h_contents << " ";
GenerateFunctionDeclaration(h_contents, "", macro->ReadableName(),
macro->signature(), macro->parameter_names(),
false);
h_contents << ";\n";
std::vector<std::string> parameter_names = GenerateFunctionDeclaration(
cc_contents,
"TorqueGeneratedExportedMacrosAssembler::", macro->ReadableName(),
macro->signature(), macro->parameter_names(), false);
cc_contents << "{\n";
cc_contents << "return " << macro->ExternalName() << "(state_";
for (auto& name : parameter_names) {
cc_contents << ", " << name;
}
cc_contents << ");\n";
cc_contents << "}\n";
}
h_contents << " private:\n"
<< " compiler::CodeAssemblerState* state_;\n"
<< "};\n";
}
WriteFile(output_directory + "/" + file_name + ".h", h_contents.str());
WriteFile(output_directory + "/" + file_name + ".cc", cc_contents.str());
}
void ImplementationVisitor::GenerateCSATypes(
const std::string& output_directory) {
std::string file_name = "csa-types";
std::stringstream h_contents;
{
IncludeGuardScope include_guard(h_contents, file_name + ".h");
h_contents << "#include \"src/compiler/code-assembler.h\"\n\n";
NamespaceScope h_namespaces(h_contents, {"v8", "internal"});
// Generates headers for all structs in a topologically-sorted order, since
// TypeOracle keeps them in the order of their resolution
for (const auto& type : TypeOracle::GetAggregateTypes()) {
const StructType* struct_type = StructType::DynamicCast(type.get());
if (!struct_type) continue;
h_contents << "struct " << struct_type->GetGeneratedTypeNameImpl()
<< " {\n";
for (auto& field : struct_type->fields()) {
h_contents << " " << field.name_and_type.type->GetGeneratedTypeName();
h_contents << " " << field.name_and_type.name << ";\n";
}
h_contents << "\n std::tuple<";
bool first = true;
for (const Type* type : LowerType(struct_type)) {
if (!first) {
h_contents << ", ";
}
first = false;
h_contents << type->GetGeneratedTypeName();
}
h_contents << "> Flatten() const {\n"
<< " return std::tuple_cat(";
first = true;
for (auto& field : struct_type->fields()) {
if (!first) {
h_contents << ", ";
}
first = false;
if (field.name_and_type.type->StructSupertype()) {
h_contents << field.name_and_type.name << ".Flatten()";
} else {
h_contents << "std::make_tuple(" << field.name_and_type.name << ")";
}
}
h_contents << ");\n";
h_contents << " }\n";
h_contents << "};\n";
}
}
WriteFile(output_directory + "/" + file_name + ".h", h_contents.str());
}
void ReportAllUnusedMacros() {
for (const auto& declarable : GlobalContext::AllDeclarables()) {
if (!declarable->IsMacro() || declarable->IsExternMacro()) continue;
Macro* macro = Macro::cast(declarable.get());
if (macro->IsUsed()) continue;
if (macro->IsTorqueMacro() && TorqueMacro::cast(macro)->IsExportedToCSA()) {
continue;
}
// TODO(gsps): Mark methods of generic structs used if they are used in any
// instantiation
if (Method* method = Method::DynamicCast(macro)) {
if (StructType* struct_type =
StructType::DynamicCast(method->aggregate_type())) {
if (struct_type->GetSpecializedFrom().has_value()) {
continue;
}
}
}
std::vector<std::string> ignored_prefixes = {"Convert<", "Cast<",
"FromConstexpr<"};
const std::string name = macro->ReadableName();
const bool ignore =
std::any_of(ignored_prefixes.begin(), ignored_prefixes.end(),
[&name](const std::string& prefix) {
return StringStartsWith(name, prefix);
});
if (!ignore) {
Lint("Macro '", macro->ReadableName(), "' is never used.")
.Position(macro->IdentifierPosition());
}
}
}
} // namespace torque
} // namespace internal
} // namespace v8
| 39.324788 | 80 | 0.638365 | [
"object",
"vector"
] |
c86d406bca4c61451ab68a159395cdef5c4b474f | 1,023 | cpp | C++ | test/utest/device_map/device_map_test.cpp | xjqbest/HugeCTR | 0b1c92d5e65891dfdd90d917bc6d520d0ca5d1e1 | [
"Apache-2.0"
] | 130 | 2021-10-11T11:55:28.000Z | 2022-03-31T21:53:07.000Z | test/utest/device_map/device_map_test.cpp | xjqbest/HugeCTR | 0b1c92d5e65891dfdd90d917bc6d520d0ca5d1e1 | [
"Apache-2.0"
] | 72 | 2021-10-09T04:59:09.000Z | 2022-03-31T11:27:54.000Z | test/utest/device_map/device_map_test.cpp | xjqbest/HugeCTR | 0b1c92d5e65891dfdd90d917bc6d520d0ca5d1e1 | [
"Apache-2.0"
] | 29 | 2021-11-03T22:35:01.000Z | 2022-03-30T13:11:59.000Z | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* 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 "HugeCTR/include/device_map.hpp"
#include "gtest/gtest.h"
using namespace HugeCTR;
TEST(device_map, device_map_basic_teste) {
std::vector<int> node1{0, 2, 3, 4}, node2{0, 1, 2}, node3{2, 3, 4, 5, 6};
std::vector<std::vector<int>> nodes;
nodes.push_back(node1);
nodes.push_back(node2);
nodes.push_back(node3);
DeviceMap dm0(nodes, 0);
DeviceMap dm1(nodes, 1);
DeviceMap dm2(nodes, 2);
}
| 31 | 75 | 0.715543 | [
"vector"
] |
c86fa34a2af4e2830b149b34ad2c77dc7aa97563 | 12,006 | cc | C++ | garnet/bin/fidl_compatibility_test/compatibility_test_server_llcpp.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | null | null | null | garnet/bin/fidl_compatibility_test/compatibility_test_server_llcpp.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | garnet/bin/fidl_compatibility_test/compatibility_test_server_llcpp.cc | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fidl/test/compatibility/llcpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/fdio.h>
#include <lib/fidl-async/cpp/bind.h>
#include <lib/fidl/cpp/interface_request.h>
#include <lib/sys/cpp/component_context.h>
#include <zircon/status.h>
#include <cstdlib>
#include <iostream>
#include <string>
constexpr const char kEchoInterfaceName[] = "fidl.test.compatibility.Echo";
namespace llcpp {
namespace fidl {
namespace test {
namespace compatibility {
class EchoClientApp {
public:
EchoClientApp(::fidl::StringView server_url)
: context_(sys::ComponentContext::Create()),
client_(Echo::SyncClient(ConnectTo(server_url))) {}
::fidl::DecodeResult<Echo::EchoStructResponse> EchoStruct(
::fidl::BytePart request_buffer, Struct value,
::fidl::StringView forward_to_server, ::fidl::BytePart response_buffer,
Struct* out_value) {
return client_.EchoStruct(std::move(request_buffer), std::move(value),
forward_to_server, std::move(response_buffer),
out_value);
}
zx_status_t EchoStructNoRetVal(Struct value,
::fidl::StringView forward_to_server,
Echo::EventHandlers event_handlers) {
auto status =
client_.EchoStructNoRetVal(std::move(value), forward_to_server);
if (status != ZX_OK) {
return status;
}
return client_.HandleEvents(std::move(event_handlers));
}
::fidl::DecodeResult<Echo::EchoArraysResponse> EchoArrays(
::fidl::BytePart request_buffer, ArraysStruct value,
::fidl::StringView forward_to_server, ::fidl::BytePart response_buffer,
ArraysStruct* out_value) {
return client_.EchoArrays(std::move(request_buffer), std::move(value),
forward_to_server, std::move(response_buffer),
out_value);
}
::fidl::DecodeResult<Echo::EchoVectorsResponse> EchoVectors(
::fidl::BytePart request_buffer, VectorsStruct value,
::fidl::StringView forward_to_server, ::fidl::BytePart response_buffer,
VectorsStruct* out_value) {
return client_.EchoVectors(std::move(request_buffer), std::move(value),
forward_to_server, std::move(response_buffer),
out_value);
}
::fidl::DecodeResult<Echo::EchoTableResponse> EchoTable(
::fidl::BytePart request_buffer, AllTypesTable value,
::fidl::StringView forward_to_server, ::fidl::BytePart response_buffer,
AllTypesTable* out_value) {
return client_.EchoTable(std::move(request_buffer), std::move(value),
forward_to_server, std::move(response_buffer),
out_value);
}
::fidl::DecodeResult<Echo::EchoXunionsResponse> EchoXunions(
::fidl::BytePart request_buffer, ::fidl::VectorView<AllTypesXunion> value,
::fidl::StringView forward_to_server, ::fidl::BytePart response_buffer,
::fidl::VectorView<AllTypesXunion>* out_value) {
return client_.EchoXunions(std::move(request_buffer), std::move(value),
forward_to_server, std::move(response_buffer),
out_value);
}
EchoClientApp(const EchoClientApp&) = delete;
EchoClientApp& operator=(const EchoClientApp&) = delete;
private:
// Called once upon construction to launch and connect to the server.
zx::channel ConnectTo(::fidl::StringView server_url) {
fuchsia::sys::LaunchInfo launch_info;
launch_info.url = std::string(server_url.data(), server_url.size());
echo_provider_ = sys::ServiceDirectory::CreateWithRequest(
&launch_info.directory_request);
fuchsia::sys::LauncherPtr launcher;
context_->svc()->Connect(launcher.NewRequest());
launcher->CreateComponent(std::move(launch_info), controller_.NewRequest());
zx::channel server_end, client_end;
ZX_ASSERT(zx::channel::create(0, &client_end, &server_end) == ZX_OK);
ZX_ASSERT(echo_provider_->Connect(kEchoInterfaceName,
std::move(server_end)) == ZX_OK);
return client_end;
}
std::unique_ptr<sys::ComponentContext> context_;
std::shared_ptr<sys::ServiceDirectory> echo_provider_;
fuchsia::sys::ComponentControllerPtr controller_;
Echo::SyncClient client_;
};
class EchoConnection final : public Echo::Interface {
public:
explicit EchoConnection(zx::unowned_channel channel) : channel_(channel) {}
void EchoStruct(Struct value, ::fidl::StringView forward_to_server,
EchoStructCompleter::Sync completer) override {
if (forward_to_server.empty()) {
completer.Reply(std::move(value));
} else {
std::vector<uint8_t> request_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
std::vector<uint8_t> response_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
EchoClientApp app(forward_to_server);
Struct out_value;
auto result = app.EchoStruct(
::fidl::BytePart(&request_buffer[0],
static_cast<uint32_t>(request_buffer.size())),
std::move(value), ::fidl::StringView{0, ""},
::fidl::BytePart(&response_buffer[0],
static_cast<uint32_t>(response_buffer.size())),
&out_value);
ZX_ASSERT_MSG(result.status == ZX_OK, "Forwarding failed: %s",
result.error);
completer.Reply(std::move(out_value));
}
}
void EchoStructNoRetVal(
Struct value, ::fidl::StringView forward_to_server,
EchoStructNoRetValCompleter::Sync completer) override {
if (forward_to_server.empty()) {
auto status = Echo::SendEchoEventEvent(zx::unowned_channel(channel_),
std::move(value));
ZX_ASSERT_MSG(status == ZX_OK, "Replying with event failed: %s",
zx_status_get_string(status));
} else {
EchoClientApp app(forward_to_server);
zx_status_t status = app.EchoStructNoRetVal(
std::move(value), ::fidl::StringView{0, ""},
Echo::EventHandlers{.echo_event =
[&](Struct value) {
return Echo::SendEchoEventEvent(
zx::unowned_channel(channel_),
std::move(value));
},
.unknown =
[] {
ZX_PANIC("Received unexpected event");
return ZX_ERR_INVALID_ARGS;
}});
ZX_ASSERT_MSG(status == ZX_OK, "Replying with event failed: %s",
zx_status_get_string(status));
}
}
void EchoArrays(ArraysStruct value, ::fidl::StringView forward_to_server,
EchoArraysCompleter::Sync completer) override {
if (forward_to_server.empty()) {
completer.Reply(std::move(value));
} else {
std::vector<uint8_t> request_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
std::vector<uint8_t> response_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
EchoClientApp app(forward_to_server);
ArraysStruct out_value;
auto result = app.EchoArrays(
::fidl::BytePart(&request_buffer[0],
static_cast<uint32_t>(request_buffer.size())),
std::move(value), ::fidl::StringView{0, ""},
::fidl::BytePart(&response_buffer[0],
static_cast<uint32_t>(response_buffer.size())),
&out_value);
ZX_ASSERT_MSG(result.status == ZX_OK, "Forwarding failed: %s",
result.error);
completer.Reply(std::move(out_value));
}
}
void EchoVectors(VectorsStruct value, ::fidl::StringView forward_to_server,
EchoVectorsCompleter::Sync completer) override {
if (forward_to_server.empty()) {
completer.Reply(std::move(value));
} else {
std::vector<uint8_t> request_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
std::vector<uint8_t> response_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
EchoClientApp app(forward_to_server);
VectorsStruct out_value;
auto result = app.EchoVectors(
::fidl::BytePart(&request_buffer[0],
static_cast<uint32_t>(request_buffer.size())),
std::move(value), ::fidl::StringView{0, ""},
::fidl::BytePart(&response_buffer[0],
static_cast<uint32_t>(response_buffer.size())),
&out_value);
ZX_ASSERT_MSG(result.status == ZX_OK, "Forwarding failed: %s",
result.error);
completer.Reply(std::move(out_value));
}
}
void EchoTable(AllTypesTable value, ::fidl::StringView forward_to_server,
EchoTableCompleter::Sync completer) override {
if (forward_to_server.empty()) {
completer.Reply(std::move(value));
} else {
std::vector<uint8_t> request_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
std::vector<uint8_t> response_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
EchoClientApp app(forward_to_server);
AllTypesTable out_value;
auto result = app.EchoTable(
::fidl::BytePart(&request_buffer[0],
static_cast<uint32_t>(request_buffer.size())),
std::move(value), ::fidl::StringView{0, ""},
::fidl::BytePart(&response_buffer[0],
static_cast<uint32_t>(response_buffer.size())),
&out_value);
ZX_ASSERT_MSG(result.status == ZX_OK, "Forwarding failed: %s",
result.error);
completer.Reply(std::move(out_value));
}
}
void EchoXunions(::fidl::VectorView<AllTypesXunion> value,
::fidl::StringView forward_to_server,
EchoXunionsCompleter::Sync completer) override {
if (forward_to_server.empty()) {
completer.Reply(std::move(value));
} else {
std::vector<uint8_t> request_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
std::vector<uint8_t> response_buffer(ZX_CHANNEL_MAX_MSG_BYTES);
EchoClientApp app(forward_to_server);
::fidl::VectorView<AllTypesXunion> out_value;
auto result = app.EchoXunions(
::fidl::BytePart(&request_buffer[0],
static_cast<uint32_t>(request_buffer.size())),
std::move(value), ::fidl::StringView{0, ""},
::fidl::BytePart(&response_buffer[0],
static_cast<uint32_t>(response_buffer.size())),
&out_value);
ZX_ASSERT_MSG(result.status == ZX_OK, "Forwarding failed: %s",
result.error);
completer.Reply(std::move(out_value));
}
}
private:
zx::unowned_channel channel_;
};
} // namespace compatibility
} // namespace test
} // namespace fidl
} // namespace llcpp
int main(int argc, const char** argv) {
// The FIDL support lib requires async_get_default_dispatcher() to return
// non-null.
async::Loop loop(&kAsyncLoopConfigAttachToThread);
auto context = sys::ComponentContext::Create();
std::vector<std::unique_ptr<llcpp::fidl::test::compatibility::EchoConnection>>
connections;
context->outgoing()->AddPublicService(
std::make_unique<vfs::Service>([&](zx::channel request,
async_dispatcher_t* dispatcher) {
auto conn =
std::make_unique<llcpp::fidl::test::compatibility::EchoConnection>(
zx::unowned_channel(request));
ZX_ASSERT(::fidl::Bind(dispatcher, std::move(request), conn.get()) ==
ZX_OK);
connections.push_back(std::move(conn));
}),
kEchoInterfaceName);
loop.Run();
return EXIT_SUCCESS;
}
| 40.976109 | 80 | 0.624854 | [
"vector"
] |
c871d53caf953ad8d49df2635233886d6d474063 | 5,428 | cc | C++ | caffe2/operators/lengths_top_k_op.cc | shigengtian/caffe2 | e19489d6acd17fea8ca98cd8e4b5b680e23a93c5 | [
"Apache-2.0"
] | 1 | 2018-03-26T13:25:03.000Z | 2018-03-26T13:25:03.000Z | caffe2/operators/lengths_top_k_op.cc | shigengtian/caffe2 | e19489d6acd17fea8ca98cd8e4b5b680e23a93c5 | [
"Apache-2.0"
] | null | null | null | caffe2/operators/lengths_top_k_op.cc | shigengtian/caffe2 | e19489d6acd17fea8ca98cd8e4b5b680e23a93c5 | [
"Apache-2.0"
] | 1 | 2018-12-20T09:14:48.000Z | 2018-12-20T09:14:48.000Z | #include "caffe2/operators/lengths_top_k_op.h"
namespace caffe2 {
template <typename T, class Context>
bool LengthsTopKOp<T, Context>::RunOnDevice() {
auto& X = Input(X_IN);
auto& Y = Input(Y_IN);
int N = Y.dim32(0);
const T* X_data = X.template data<T>();
const int* input_len = Y.template data<int>();
auto* output_topk_values = Output(TOPK_VALUES_OUT);
auto* output_topk_indices = Output(TOPK_INDICES_OUT);
output_topk_values->Resize(N * k_);
output_topk_indices->Resize(N * k_);
std::vector<int> output_dims = std::vector<int>({N, k_});
output_topk_values->Reshape(output_dims);
output_topk_indices->Reshape(output_dims);
T* output_topk_values_data = output_topk_values->template mutable_data<T>();
int* output_topk_indices_data =
output_topk_indices->template mutable_data<int>();
auto cmp = [](std::pair<T, TIndex>& lhs, std::pair<T, TIndex>& rhs) {
return lhs.first > rhs.first ||
(lhs.first == rhs.first && lhs.second < rhs.second);
};
// Sort preserving indices
int next_index = 0;
for (TIndex i = 0; i < N; ++i) {
// Build a min-heap, the heap element is pair of (value, idx)
// the top of the heap is the smallest value
std::priority_queue<
std::pair<T, TIndex>,
std::vector<std::pair<T, TIndex>>,
decltype(cmp)>
p_queue(cmp);
// Maintain the size of heap to be less or equal to k_, so the
// heap will hold the k_ largest values
for (TIndex j = 0; j < input_len[i]; ++j) {
const auto value = X_data[next_index++];
if (p_queue.size() < k_ || value > p_queue.top().first) {
p_queue.push(std::make_pair(value, j));
}
if (p_queue.size() > k_) {
p_queue.pop();
}
}
int last_index = p_queue.size();
for (TIndex j = 0; j < k_; ++j) {
if (p_queue.size() > 0) {
auto& pqElem = p_queue.top();
output_topk_values_data[i * k_ + last_index - j - 1] = pqElem.first;
output_topk_indices_data[i * k_ + last_index - j - 1] = pqElem.second;
p_queue.pop();
} else {
output_topk_values_data[i * k_ + j] = 0;
output_topk_indices_data[i * k_ + j] = -1;
}
}
}
return true;
}
template <typename T, class Context>
bool LengthsTopKGradientOp<T, Context>::RunOnDevice() {
auto& input_len = Input(LENGTH_IN);
int N = input_len.size();
auto& input_indices = Input(INDICES_IN);
CAFFE_ENFORCE_GE(input_indices.ndim(), 2, "input dim must be >= 2");
CAFFE_ENFORCE_EQ(
input_indices.size(), N * k_, "input_indices shape is not correct");
auto& input_topk = Input(DER_TOPK_IN);
CAFFE_ENFORCE_EQ(
input_topk.size(), N * k_, "input_topk shape is not correct");
auto* X_out = Output(DER_X_OUT);
const int* input_len_data = input_len.template data<int>();
const int* input_indices_data = input_indices.template data<int>();
const T* input_topk_data = input_topk.template data<T>();
int num_indices = 0;
for (int i = 0; i < N; i++) {
num_indices += input_len_data[i];
}
X_out->Resize(num_indices);
std::vector<int> output_dims = std::vector<int>({num_indices});
X_out->Reshape(output_dims);
T* X_out_data = X_out->template mutable_data<T>();
math::Set<T, Context>(num_indices, 0.0, X_out_data, &context_);
int index_offset = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < std::min(input_len_data[i], k_); j++) {
int cur_index = index_offset + input_indices_data[i * k_ + j];
CAFFE_ENFORCE_LT(
cur_index, num_indices, "cur_index should be less than num_indices");
X_out_data[cur_index] = input_topk_data[i * k_ + j];
}
index_offset += input_len_data[i];
}
return true;
}
REGISTER_CPU_OPERATOR(LengthsTopK, LengthsTopKOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(
LengthsTopKGradient,
LengthsTopKGradientOp<float, CPUContext>);
OPERATOR_SCHEMA(LengthsTopK)
.NumInputs(2)
.NumOutputs(2)
.SetDoc(R"DOC(
Apply TopK to each segment of the input tensor, where segments are defined by
their LENGTHS, and concatenate them in an output tensor of
shape=(SIZE(LENGTHs), k). In case there's less than k values in a segment,
the output value will be padded by 0, and the corresponding output indices will
be padded by -1.
)DOC")
.Input(
0,
"DATA",
"Tensor of rank 1. First dimension must be equal to the sum of "
"lengths")
.Input(1, "LENGTHS", "Tensor of int32 lengths of rank 1")
.Output(
0,
"TopKValue",
"Output top k elements for each segment, with"
"shape=(SIZE(lengths), k)")
.Output(
1,
"TopKIndices",
"Output indices in DATA corresponding to value in TopKValue")
.Arg(
"k",
"the number of top values to return for each segment, if the number "
"of values is smaller than k, the values would be padded with 0 and "
"indices would be padded with -1.");
OPERATOR_SCHEMA(LengthsTopKGradient).NumInputs(3).NumOutputs(1);
namespace {
class GetLengthsTopKGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"LengthsTopKGradient",
"",
vector<string>{I(1), O(1), GO(0)},
vector<string>{GI(0)});
}
};
} // namespace
REGISTER_GRADIENT(LengthsTopK, GetLengthsTopKGradient);
} // namespace caffe2
| 33.300613 | 79 | 0.649963 | [
"shape",
"vector"
] |
c873466cdfd74d8bbbe549b9b7c193d6e8b36cf8 | 3,619 | cpp | C++ | examples/src/webcam_mobilenet_example.cpp | Piaktipik/depthai-core | 06dcfd5daab08591a58811763c8bd28c22c0ca7f | [
"MIT"
] | null | null | null | examples/src/webcam_mobilenet_example.cpp | Piaktipik/depthai-core | 06dcfd5daab08591a58811763c8bd28c22c0ca7f | [
"MIT"
] | null | null | null | examples/src/webcam_mobilenet_example.cpp | Piaktipik/depthai-core | 06dcfd5daab08591a58811763c8bd28c22c0ca7f | [
"MIT"
] | null | null | null |
#include <cstdio>
#include <iostream>
#include "utility.hpp"
// Inludes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
int main(int argc, char** argv) {
using namespace std;
// Default blob path provided by Hunter private data download
// Applicable for easier example usage only
std::string nnPath(BLOB_PATH);
// If path to blob specified, use that
int camId = 0;
if(argc > 1) {
camId = std::stoi(argv[1]);
if(argc > 2) {
nnPath = std::string(argv[2]);
}
}
using namespace std;
// CREATE PIPELINE
dai::Pipeline p;
auto xin = p.create<dai::node::XLinkIn>();
auto nn = p.create<dai::node::NeuralNetwork>();
auto xout = p.create<dai::node::XLinkOut>();
// Properties
nn->setBlobPath(nnPath);
xin->setStreamName("nn_in");
xin->setMaxDataSize(300 * 300 * 3);
xin->setNumFrames(4);
xout->setStreamName("nn_out");
// Link plugins XLINK -> NN -> XLINK
xin->out.link(nn->input);
nn->out.link(xout->input);
// Open Webcam
cv::VideoCapture webcam(camId);
// Connect to device with above created pipeline
dai::Device d(p);
// Start the pipeline
d.startPipeline();
cv::Mat frame;
auto in = d.getInputQueue("nn_in");
auto detections = d.getOutputQueue("nn_out");
while(1) {
// data to send further
auto tensor = std::make_shared<dai::RawBuffer>();
// Read frame from webcam
webcam >> frame;
// crop and resize
frame = resizeKeepAspectRatio(frame, cv::Size(300, 300), cv::Scalar(0));
// transform to BGR planar 300x300
toPlanar(frame, tensor->data);
// tensor->data = std::vector<std::uint8_t>(frame.data, frame.data + frame.total());
in->send(tensor);
struct Detection {
unsigned int label;
float score;
float x_min;
float y_min;
float x_max;
float y_max;
};
vector<Detection> dets;
auto det = detections->get<dai::NNData>();
std::vector<float> detData = det->getFirstLayerFp16();
if(detData.size() > 0) {
int i = 0;
while(detData[i * 7] != -1.0f) {
Detection d;
d.label = detData[i * 7 + 1];
d.score = detData[i * 7 + 2];
d.x_min = detData[i * 7 + 3];
d.y_min = detData[i * 7 + 4];
d.x_max = detData[i * 7 + 5];
d.y_max = detData[i * 7 + 6];
i++;
dets.push_back(d);
}
}
for(const auto& d : dets) {
int x1 = d.x_min * frame.cols;
int y1 = d.y_min * frame.rows;
int x2 = d.x_max * frame.cols;
int y2 = d.y_max * frame.rows;
cv::rectangle(frame, cv::Rect(cv::Point(x1, y1), cv::Point(x2, y2)), cv::Scalar(255, 255, 255));
}
printf("===================== %lu detection(s) =======================\n", dets.size());
for(unsigned det = 0; det < dets.size(); ++det) {
printf("%5d | %6.4f | %7.4f | %7.4f | %7.4f | %7.4f\n",
dets[det].label,
dets[det].score,
dets[det].x_min,
dets[det].y_min,
dets[det].x_max,
dets[det].y_max);
}
cv::imshow("preview", frame);
int key = cv::waitKey(1);
if(key == 'q') {
return 0;
}
}
return 0;
}
| 27.210526 | 108 | 0.504007 | [
"vector",
"transform"
] |
c874f6bd8f0c8f2eba69d1928c1405c4f9585c8a | 28,401 | cpp | C++ | networkit/cpp/algebraic/test/MatricesGTest.cpp | valentin-noske/networkit | fc598542eb3815b0eb9c0a06bc40fe6c6ca0ae89 | [
"MIT"
] | null | null | null | networkit/cpp/algebraic/test/MatricesGTest.cpp | valentin-noske/networkit | fc598542eb3815b0eb9c0a06bc40fe6c6ca0ae89 | [
"MIT"
] | null | null | null | networkit/cpp/algebraic/test/MatricesGTest.cpp | valentin-noske/networkit | fc598542eb3815b0eb9c0a06bc40fe6c6ca0ae89 | [
"MIT"
] | null | null | null | // no-networkit-format
/*
* MatricesGTest.cpp
*
* Created on: May 31, 2016
* Author: Michael Wegner (michael.wegner@student.kit.edu)
*/
#include <gtest/gtest.h>
#include <networkit/auxiliary/Random.hpp>
#include <networkit/algebraic/AlgebraicGlobals.hpp>
#include <networkit/algebraic/Vector.hpp>
#include <networkit/io/METISGraphReader.hpp>
#include <networkit/algebraic/MatrixTools.hpp>
#include <networkit/algebraic/CSRMatrix.hpp>
#include <networkit/algebraic/DenseMatrix.hpp>
#include <networkit/algebraic/DynamicMatrix.hpp>
namespace NetworKit {
class MatricesGTest : public testing::Test {
protected:
virtual void SetUp() {
METISGraphReader reader;
graph = reader.read("input/PGPgiantcompo.graph");
}
Graph graph;
public:
MatricesGTest() = default;
virtual ~MatricesGTest() = default;
template<class Matrix>
void testDimension();
template<class Matrix>
void testNNZInRow();
template<class Matrix>
void testRowAndColumnAccess();
template<class Matrix>
void testDiagonalVector();
template<class Matrix>
void testTranspose();
template<class Matrix>
void testExtract();
template<class Matrix>
void testAssign();
template<class Matrix>
void testApply();
template<class Matrix>
void testMatrixAddition();
template<class Matrix>
void testMatrixSubtraction();
template<class Matrix>
void testScalarMultiplication();
template<class Matrix>
void testMatrixDivisionOperator();
template<class Matrix>
void testMatrixVectorProduct();
template<class Matrix>
void testMatrixMultiplication();
template<class Matrix>
void testBigMatrixMultiplication();
template<class Matrix>
void testAdjacencyMatrix();
template<class Matrix>
void testDiagonalMatrix();
template<class Matrix>
void testIncidenceMatrix();
template<class Matrix>
void testLaplacianOfGraph();
// TODO: Test other matrix classes
// TODO: Test mmT multiplication, etc.!
};
template<class Matrix>
void MatricesGTest::testDimension() {
Matrix mat(10);
ASSERT_EQ(10u, mat.numberOfRows());
ASSERT_EQ(10u, mat.numberOfColumns());
mat = Matrix(5, 10, 0.0);
ASSERT_EQ(5u, mat.numberOfRows());
ASSERT_EQ(10u, mat.numberOfColumns());
mat = Matrix(10, 5, 0.0);
ASSERT_EQ(10u, mat.numberOfRows());
ASSERT_EQ(5u, mat.numberOfColumns());
}
template<class Matrix>
void MatricesGTest::testNNZInRow() {
/*
* 1.0 0.0 2.0
* 4.0 0.0 0.0
* 0.0 0.0 0.0
* 0.0 0.0 2.0
*/
std::vector<Triplet> triplets = {{0,0,1.0}, {0,2,2.0}, {1,0,4.0}, {3,3,2.0}};
Matrix mat(4, triplets);
EXPECT_EQ(2u, mat.nnzInRow(0));
EXPECT_EQ(1u, mat.nnzInRow(1));
EXPECT_EQ(0u, mat.nnzInRow(2));
EXPECT_EQ(1u, mat.nnzInRow(3));
}
template<class Matrix>
void MatricesGTest::testRowAndColumnAccess() {
std::vector<Triplet> triplets;
for (index i = 0; i < 1000; ++i) {
triplets.push_back({3,i,(double)i});
}
triplets.push_back({10,10,42.123});
Matrix mat(1000, triplets);
Vector v = mat.row(3);
ASSERT_EQ(mat.numberOfColumns(), v.getDimension());
for (index i = 0; i < 1000; ++i) {
EXPECT_EQ(i, v[i]);
}
v = mat.row(10);
ASSERT_EQ(v.getDimension(), mat.numberOfColumns());
ASSERT_TRUE(v.isTransposed());
EXPECT_EQ(42.123, v[10]);
v = mat.column(10);
ASSERT_EQ(mat.numberOfRows(), v.getDimension());
ASSERT_FALSE(v.isTransposed());
EXPECT_EQ(10.0, v[3]);
EXPECT_EQ(42.123, v[10]);
// rectangular matrix
// n x m (n < m)
triplets.clear();
triplets.push_back({4,9,11});
triplets.push_back({0,0,42});
mat = Matrix(5, 10, triplets);
v = mat.row(0);
ASSERT_EQ(v.getDimension(), 10u);
for (index i = 0; i < v.getDimension(); ++i) {
if (i == 0) {
EXPECT_EQ(42, v[i]);
} else {
EXPECT_EQ(0, v[i]);
}
}
v = mat.column(9);
ASSERT_EQ(v.getDimension(), 5u);
for (index i = 0; i < v.getDimension(); ++i) {
if (i == v.getDimension() - 1) {
EXPECT_EQ(11, v[i]);
} else {
EXPECT_EQ(0, v[i]);
}
}
// rectangular matrix
// n x m (n > m)
triplets.clear();
triplets.push_back({9,4,11});
triplets.push_back({0,0,42});
mat = Matrix(10, 5, triplets);
v = mat.row(0);
ASSERT_EQ(v.getDimension(), 5u);
for (index i = 0; i < v.getDimension(); ++i) {
if (i == 0) {
EXPECT_EQ(42, v[i]);
} else {
EXPECT_EQ(0, v[i]);
}
}
v = mat.column(4);
ASSERT_EQ(v.getDimension(), 10u);
for (index i = 0; i < v.getDimension(); ++i) {
if (i == v.getDimension() - 1) {
EXPECT_EQ(11, v[i]);
} else {
EXPECT_EQ(0, v[i]);
}
}
}
template<class Matrix>
void MatricesGTest::testDiagonalVector() {
// 1 2 3 0
// 2 2 0 0
// 3 0 0 -1
// 0 0 -1 4
std::vector<Triplet> triplets = {{0,0,1}, {0,1,2}, {0,2,3}, {1,0,2}, {1,1,2}, {2,0,3}, {2,3,-1}, {3,2,-1}, {3,3,4}};
Matrix mat(4,4,triplets);
Vector diagonal = mat.diagonal();
EXPECT_EQ(4u, diagonal.getDimension());
EXPECT_EQ(1, diagonal[0]);
EXPECT_EQ(2, diagonal[1]);
EXPECT_EQ(0, diagonal[2]);
EXPECT_EQ(4, diagonal[3]);
// rectangular matrix
//
// 1 0 0 0 0
// 0 0 3 0 0
triplets = {{0,0,1}, {1,2,3}};
mat = Matrix(2,5,triplets);
diagonal = mat.diagonal();
EXPECT_EQ(2u, diagonal.getDimension());
EXPECT_EQ(1, diagonal[0]);
EXPECT_EQ(0, diagonal[1]);
// rectangular matrix
//
// 1 0
// 0 -3
// 0 0
// 0 0
// 0 0
triplets = {{0,0,1.0}, {1,1,-3.0}};
mat = Matrix(5,2,triplets);
diagonal = mat.diagonal();
EXPECT_EQ(2u, diagonal.getDimension());
EXPECT_EQ(1, diagonal[0]);
EXPECT_EQ(-3, diagonal[1]);
}
template<class Matrix>
void MatricesGTest::testTranspose() {
// 1 0 1 0
// 2 2 0 0
// 3 0 0 -1
// 0 0 1 4
std::vector<Triplet> triplets = {{0,0,1}, {0,2,1}, {1,0,2}, {1,1,2}, {2,0,3}, {2,3,-1}, {3,2,1}, {3,3,4}};
Matrix mat(4,4,triplets);
Matrix matT = mat.transpose();
EXPECT_EQ(4u, matT.numberOfRows());
EXPECT_EQ(4u, matT.numberOfColumns());
EXPECT_EQ(1, matT(0,0));
EXPECT_EQ(2, matT(0,1));
EXPECT_EQ(3, matT(0,2));
EXPECT_EQ(0, matT(0,3));
EXPECT_EQ(0, matT(1,0));
EXPECT_EQ(2, matT(1,1));
EXPECT_EQ(0, matT(1,2));
EXPECT_EQ(0, matT(1,3));
EXPECT_EQ(1, matT(2,0));
EXPECT_EQ(0, matT(2,1));
EXPECT_EQ(0, matT(2,2));
EXPECT_EQ(1, matT(2,3));
EXPECT_EQ(0, matT(3,0));
EXPECT_EQ(0, matT(3,1));
EXPECT_EQ(-1, matT(3,2));
EXPECT_EQ(4, matT(3,3));
// rectangular matrix
//
// 1 0 0 0 0
// 0 0 3 0 0
triplets = {{0,0,1}, {1,2,3}};
mat = Matrix(2,5,triplets);
matT = mat.transpose();
EXPECT_EQ(5u, matT.numberOfRows());
EXPECT_EQ(2u, matT.numberOfColumns());
EXPECT_EQ(1, matT(0,0));
EXPECT_EQ(0, matT(0,1));
EXPECT_EQ(0, matT(1,0));
EXPECT_EQ(0, matT(1,1));
EXPECT_EQ(0, matT(2,0));
EXPECT_EQ(3, matT(2,1));
EXPECT_EQ(0, matT(3,0));
EXPECT_EQ(0, matT(3,1));
EXPECT_EQ(0, matT(4,0));
EXPECT_EQ(0, matT(4,1));
// rectangular matrix
//
// 1 0
// 0 0
// 0 3
// 0 0
// 0 0
triplets = {{0,0,1.0}, {2,1,3.0}};
mat = Matrix(5,2,triplets);
matT = mat.transpose();
EXPECT_EQ(2u, matT.numberOfRows());
EXPECT_EQ(5u, matT.numberOfColumns());
EXPECT_EQ(1, matT(0,0));
EXPECT_EQ(0, matT(0,1));
EXPECT_EQ(0, matT(0,2));
EXPECT_EQ(0, matT(0,3));
EXPECT_EQ(0, matT(0,4));
EXPECT_EQ(0, matT(1,0));
EXPECT_EQ(0, matT(1,1));
EXPECT_EQ(3, matT(1,2));
EXPECT_EQ(0, matT(1,3));
EXPECT_EQ(0, matT(1,4));
}
template<class Matrix>
void MatricesGTest::testExtract() {
Matrix mat = Matrix::adjacencyMatrix(graph);
std::vector<index> rows(500);
std::vector<index> columns(500);
for (index i = 0; i < 500; ++i) {
rows[i] = Aux::Random::integer(graph.numberOfNodes()-1);
columns[i] = Aux::Random::integer(graph.numberOfNodes()-1);
}
Matrix subMatrix = mat.extract(rows, columns);
ASSERT_EQ(rows.size(), subMatrix.numberOfRows());
ASSERT_EQ(columns.size(), subMatrix.numberOfColumns());
for (index i = 0; i < subMatrix.numberOfRows(); ++i) {
for (index j = 0; j < subMatrix.numberOfColumns(); ++j) {
EXPECT_EQ(mat(rows[i], columns[j]), subMatrix(i,j));
}
}
// 1 0 1 0
// 2 2 0 0
// 3 0 0 -1
// 0 0 1 4
std::vector<Triplet> triplets = {{0,0,1}, {0,2,1}, {1,0,2}, {1,1,2}, {2,0,3}, {2,3,-1}, {3,2,1}, {3,3,4}};
mat = Matrix(4,4,triplets);
rows = {0,2,0};
columns = {1,0,2,1};
//
// 0 1 1 0
// 0 3 0 0
// 0 1 1 0
//
subMatrix = mat.extract(rows, columns);
ASSERT_EQ(3u, subMatrix.numberOfRows());
ASSERT_EQ(4u, subMatrix.numberOfColumns());
EXPECT_EQ(0, subMatrix(0,0));
EXPECT_EQ(1, subMatrix(0,1));
EXPECT_EQ(1, subMatrix(0,2));
EXPECT_EQ(0, subMatrix(0,3));
EXPECT_EQ(0, subMatrix(1,0));
EXPECT_EQ(3, subMatrix(1,1));
EXPECT_EQ(0, subMatrix(1,2));
EXPECT_EQ(0, subMatrix(1,3));
EXPECT_EQ(0, subMatrix(2,0));
EXPECT_EQ(1, subMatrix(2,1));
EXPECT_EQ(1, subMatrix(2,2));
EXPECT_EQ(0, subMatrix(2,3));
}
template<class Matrix>
void MatricesGTest::testAssign() {
// 1 0 1 0
// 2 2 0 0
// 3 0 0 -1
// 0 0 1 4
std::vector<Triplet> triplets = {{0,0,1}, {0,2,1}, {1,0,2}, {1,1,2}, {2,0,3}, {2,3,-1}, {3,2,1}, {3,3,4}};
Matrix mat(4,4,triplets);
// -1 1
// 3 0
std::vector<Triplet> subTriplets = {{0,0,-1}, {0,1,1}, {1,0,3}};
Matrix sourceMat(2,2,subTriplets);
std::vector<index> rows = {2,3};
std::vector<index> columns = {0, 2};
mat.assign(rows, columns, sourceMat);
EXPECT_EQ(1, mat(0,0));
EXPECT_EQ(0, mat(0,1));
EXPECT_EQ(1, mat(0,2));
EXPECT_EQ(0, mat(0,3));
EXPECT_EQ(2, mat(1,0));
EXPECT_EQ(2, mat(1,1));
EXPECT_EQ(0, mat(1,2));
EXPECT_EQ(0, mat(1,3));
EXPECT_EQ(-1, mat(2,0));
EXPECT_EQ(0, mat(2,1));
EXPECT_EQ(1, mat(2,2));
EXPECT_EQ(-1, mat(2,3));
EXPECT_EQ(3, mat(3,0));
EXPECT_EQ(0, mat(3,1));
EXPECT_EQ(0, mat(3,2));
EXPECT_EQ(4, mat(3,3));
rows = {2,3};
columns = {2,3};
mat.assign(rows, columns, sourceMat);
EXPECT_EQ(1, mat(0,0));
EXPECT_EQ(0, mat(0,1));
EXPECT_EQ(1, mat(0,2));
EXPECT_EQ(0, mat(0,3));
EXPECT_EQ(2, mat(1,0));
EXPECT_EQ(2, mat(1,1));
EXPECT_EQ(0, mat(1,2));
EXPECT_EQ(0, mat(1,3));
EXPECT_EQ(-1, mat(2,0));
EXPECT_EQ(0, mat(2,1));
EXPECT_EQ(-1, mat(2,2));
EXPECT_EQ(1, mat(2,3));
EXPECT_EQ(3, mat(3,0));
EXPECT_EQ(0, mat(3,1));
EXPECT_EQ(3, mat(3,2));
EXPECT_EQ(0, mat(3,3));
}
template<class Matrix>
void MatricesGTest::testApply() {
Matrix mat = Matrix::adjacencyMatrix(graph);
mat.apply([&](double value) {return 2 * value;});
graph.forEdges([&](index i, index j, double value) {
EXPECT_EQ(2 * value, mat(i,j));
});
}
template<class Matrix>
void MatricesGTest::testMatrixAddition() {
std::vector<Triplet> triplets1;
std::vector<Triplet> triplets2;
for (index i = 0; i < 100; ++i) {
triplets1.push_back({i,i,1});
triplets2.push_back({i,i,(double)i});
}
triplets1.push_back({2,71, 1.8});
triplets2.push_back({42,43,3.14});
Matrix mat1(100, triplets1);
Matrix mat2(100, triplets2);
Matrix result = mat1 + mat2;
ASSERT_EQ(mat1.numberOfRows(), result.numberOfRows());
ASSERT_EQ(mat1.numberOfColumns(), result.numberOfColumns());
EXPECT_EQ(0.0, result(10, 13));
for (index i = 0; i < result.numberOfRows(); ++i) {
EXPECT_EQ((i + 1), result(i, i));
}
EXPECT_EQ(1.8, result(2, 71));
EXPECT_EQ(3.14, result(42, 43));
EXPECT_EQ(0.0, result(3, 14));
// rectangular matrix
// n x m (n < m)
//
// 1 0 0 0 0
// 0 0 3 0 0
std::vector<Triplet> triplets = {{0,0,1.0}, {1,2,3.0}};
mat1 = Matrix(2,5,triplets);
// 0 0 1 0 0
// 0 0 1 0 0
triplets.clear();
triplets = {{0,2,1.0}, {1,2,1.0}};
mat2 = Matrix(2,5,triplets);
result = mat1 + mat2;
ASSERT_EQ(2u, result.numberOfRows());
ASSERT_EQ(5u, result.numberOfColumns());
EXPECT_EQ(1, result(0,0));
EXPECT_EQ(1, result(0,2));
EXPECT_EQ(4, result(1,2));
EXPECT_EQ(0, result(0,1));
EXPECT_EQ(0, result(1,4));
// rectangular matrix
// n x m (n > m)
//
// 1 0
// 0 0
// 0 3
// 0 0
// 0 0
triplets.clear();
triplets = {{0,0,1.0}, {2,1,3.0}};
mat1 = Matrix(5,2,triplets);
// 0 0
// 0 0
// 1 1
// 0 0
// 0 0
triplets.clear();
triplets = {{2,0,1.0}, {2,1,1.0}};
mat2 = Matrix(5,2,triplets);
result = mat1 + mat2;
ASSERT_EQ(5u, result.numberOfRows());
ASSERT_EQ(2u, result.numberOfColumns());
EXPECT_EQ(1, result(0,0));
EXPECT_EQ(1, result(2,0));
EXPECT_EQ(4, result(2,1));
EXPECT_EQ(0, result(0,1));
EXPECT_EQ(0, result(4,1));
}
template<class Matrix>
void MatricesGTest::testMatrixSubtraction() {
std::vector<Triplet> triplets1;
std::vector<Triplet> triplets2;
for (index i = 0; i < 100; ++i) {
triplets1.push_back({i,i,1});
triplets2.push_back({i,i,(double)i});
}
triplets1.push_back({2,71, 1.8});
triplets2.push_back({42,43,3.14});
Matrix mat1(100, triplets1);
Matrix mat2(100, triplets2);
Matrix result = mat2 - mat1;
ASSERT_EQ(mat1.numberOfRows(), result.numberOfRows());
ASSERT_EQ(mat1.numberOfColumns(), result.numberOfColumns());
EXPECT_EQ(0.0, result(10, 13));
for (index i = 0; i < result.numberOfRows(); ++i) {
EXPECT_EQ(((int) i - 1), result(i, i));
}
EXPECT_EQ(-1.8, result(2, 71));
EXPECT_EQ(3.14, result(42, 43));
EXPECT_EQ(0.0, result(3, 14));
// rectangular matrix
// n x m (n < m)
//
// 1 0 0 0 0
// 0 0 3 0 0
std::vector<Triplet> triplets = {{0,0,1.0}, {1,2,3.0}};
mat1 = Matrix(2,5,triplets);
// 0 0 1 0 0
// 0 0 1 0 0
triplets.clear();
triplets = {{0,2,1.0}, {1,2,1.0}};
mat2 = Matrix(2,5,triplets);
result = mat1 - mat2;
ASSERT_EQ(2u, result.numberOfRows());
ASSERT_EQ(5u, result.numberOfColumns());
EXPECT_EQ(1, result(0,0));
EXPECT_EQ(-1, result(0,2));
EXPECT_EQ(2, result(1,2));
EXPECT_EQ(0, result(0,1));
EXPECT_EQ(0, result(1,4));
// rectangular matrix
// n x m (n > m)
//
// 1 0
// 0 0
// 0 3
// 0 0
// 0 0
triplets.clear();
triplets = {{0,0,1.0}, {2,1,3.0}};
mat1 = Matrix(5,2,triplets);
// 0 0
// 0 0
// 1 1
// 0 0
// 0 0
triplets.clear();
triplets = {{2,0,1.0}, {2,1,1.0}};
mat2 = Matrix(5,2,triplets);
result = mat1 - mat2;
ASSERT_EQ(5u, result.numberOfRows());
ASSERT_EQ(2u, result.numberOfColumns());
EXPECT_EQ(1, result(0,0));
EXPECT_EQ(-1, result(2,0));
EXPECT_EQ(2, result(2,1));
EXPECT_EQ(0, result(0,1));
EXPECT_EQ(0, result(4,1));
}
template<class Matrix>
void MatricesGTest::testScalarMultiplication() {
std::vector<Triplet> triplets;
for (index i = 0; i < 100; ++i) {
triplets.push_back({i,i,(double) i});
}
triplets.push_back({42,43,42.0});
Matrix mat(100, triplets);
mat *= 2;
ASSERT_EQ(100u, mat.numberOfRows());
ASSERT_EQ(100u, mat.numberOfColumns());
for (index i = 0; i < 100; ++i) {
EXPECT_EQ(i*2, mat(i, i));
}
EXPECT_EQ(84.0, mat(42, 43));
EXPECT_EQ(0.0, mat(55, 99));
mat *= 0.5;
for (index i = 0; i < 100; ++i) {
EXPECT_EQ(i, mat(i, i));
}
EXPECT_EQ(42.0, mat(42, 43));
EXPECT_EQ(0.0, mat(55, 99));
// rectangular matrix
//
// 1 0 0 0 0
// 0 0 3 0 0
triplets = {{0,0,1.0}, {1,2,3.0}};
mat = Matrix(2,5,triplets);
mat *= 2;
EXPECT_EQ(2, mat(0,0));
EXPECT_EQ(6, mat(1,2));
}
template<class Matrix>
void MatricesGTest::testMatrixDivisionOperator() {
std::vector<Triplet> triplets;
for (index i = 0; i < 100; ++i) {
triplets.push_back({i,i, (double) i});
}
triplets.push_back({42,43,42.0});
Matrix mat(100, triplets);
mat /= (1.0 / 2.0);
ASSERT_EQ(100u, mat.numberOfRows());
ASSERT_EQ(100u, mat.numberOfColumns());
for (index i = 0; i < 100; ++i) {
EXPECT_EQ(i*2, mat(i, i));
}
EXPECT_EQ(84.0, mat(42, 43));
EXPECT_EQ(0.0, mat(55, 99));
mat /= 2;
for (index i = 0; i < 100; ++i) {
EXPECT_EQ(i, mat(i, i));
}
EXPECT_EQ(42.0, mat(42, 43));
EXPECT_EQ(0.0, mat(55, 99));
// rectangular matrix
//
// 1 0 0 0 0
// 0 0 3 0 0
triplets = {{0,0,1.0}, {1,2,3.0}};
mat = Matrix(2,5,triplets);
mat /= 2;
EXPECT_EQ(0.5, mat(0,0));
EXPECT_EQ(1.5, mat(1,2));
}
template<class Matrix>
void MatricesGTest::testMatrixVectorProduct() {
std::vector<Triplet> triplets;
for (index i = 0; i < 1000; ++i) {
triplets.push_back({i,i, (double) i});
}
triplets.push_back({42,43,42.0});
Vector vector(1000, 1.0);
vector[500] = 3.5;
Matrix mat(1000, triplets);
Vector result = mat * vector;
ASSERT_EQ(mat.numberOfRows(), result.getDimension());
for (index i = 0; i < 1000; ++i) {
if (i != 500 && i != 42 && i != 43) {
EXPECT_EQ(i, result[i]);
}
}
EXPECT_EQ(42.0, mat(42, 43));
EXPECT_EQ(84.0, result[42]);
EXPECT_EQ(1750.0, result[500]);
// 1 2 3 0
// 2 2 0 0
// mat2 = 3 0 3 -1
// 0 0 -1 4
triplets = {{0,0,1}, {0,1,2}, {0,2,3}, {1,0,2}, {1,1,2}, {2,0,3}, {2,2,3}, {2,3,-1}, {3,2,-1}, {3,3,4}};
Matrix mat2(4, triplets);
Vector v({1,2,3,0});
Vector res = mat2 * v;
ASSERT_EQ(mat2.numberOfRows(), res.getDimension());
EXPECT_EQ(14, res[0]);
EXPECT_EQ(6, res[1]);
EXPECT_EQ(12, res[2]);
EXPECT_EQ(-3, res[3]);
// rectangular matrix
//
// 1 0 0 0 0
// 0 0 3 0 0
triplets = {{0,0,1}, {1,2,3}};
mat = Matrix(2,5,triplets);
v = {0,1,2,3,0};
res = mat * v;
ASSERT_EQ(2u, res.getDimension());
EXPECT_EQ(0, res[0]);
EXPECT_EQ(6, res[1]);
}
template<class Matrix>
void MatricesGTest::testMatrixMultiplication() {
std::vector<Triplet> triplets = {{0,0,1}, {0,1,2}, {0,2,3}, {1,0,2}, {1,1,2}, {2,0,3}, {2,2,3}, {2,3,-1}, {3,2,-1}, {3,3,4}};
//
// 1 2 3 0
// 2 2 0 0
// mat1 = mat2 = 3 0 3 -1
// 0 0 -1 4
//
Matrix mat1(4, triplets);
ASSERT_EQ(4u, mat1.numberOfRows());
ASSERT_EQ(4u, mat1.numberOfColumns());
Matrix mat2(4, triplets);
ASSERT_EQ(4u, mat2.numberOfRows());
ASSERT_EQ(4u, mat2.numberOfColumns());
//
// 14 6 12 -3
// 6 8 6 0
// result = 12 6 19 -7
// -3 0 -7 17
//
Matrix result = mat1 * mat2;
ASSERT_EQ(mat1.numberOfRows(), result.numberOfRows());
ASSERT_EQ(mat1.numberOfColumns(), result.numberOfColumns());
EXPECT_EQ(14, result(0,0));
EXPECT_EQ(6, result(0,1));
EXPECT_EQ(12, result(0,2));
EXPECT_EQ(-3, result(0,3));
EXPECT_EQ(6, result(1,0));
EXPECT_EQ(8, result(1,1));
EXPECT_EQ(6, result(1,2));
EXPECT_EQ(0, result(1,3));
EXPECT_EQ(12, result(2,0));
EXPECT_EQ(6, result(2,1));
EXPECT_EQ(19, result(2,2));
EXPECT_EQ(-7, result(2,3));
EXPECT_EQ(-3, result(3,0));
EXPECT_EQ(0, result(3,1));
EXPECT_EQ(-7, result(3,2));
EXPECT_EQ(17, result(3,3));
// rectangular matrices
//
// 1 0 0 2
// 0 0 1 0
// 0 2 0 4
triplets = {{0,0,1}, {0,3,2}, {1,2,1}, {2,1,2}, {2,3,4}};
mat1 = Matrix(3,4,triplets);
//
// 1 0
// 0 0
// 0 0.5
// 42 1
triplets = {{0,0,1}, {2,1,0.5}, {3,0,42}, {3,1,1}};
mat2 = Matrix(4,2, triplets);
result = mat1 * mat2;
ASSERT_EQ(mat1.numberOfRows(), result.numberOfRows());
ASSERT_EQ(mat2.numberOfColumns(), result.numberOfColumns());
EXPECT_EQ(85, result(0,0));
EXPECT_EQ(2, result(0,1));
EXPECT_EQ(0, result(1,0));
EXPECT_EQ(0.5, result(1,1));
EXPECT_EQ(168, result(2,0));
EXPECT_EQ(4, result(2,1));
}
template<class Matrix>
void MatricesGTest::testBigMatrixMultiplication() {
Matrix mat = Matrix::adjacencyMatrix(graph);
Matrix result = mat * mat;
ASSERT_EQ(mat.numberOfRows(), result.numberOfRows());
ASSERT_EQ(mat.numberOfColumns(), result.numberOfColumns());
}
template<class Matrix>
void MatricesGTest::testAdjacencyMatrix() {
Graph G(6);
G.addEdge(0,0);
G.addEdge(0,1);
G.addEdge(0,4);
G.addEdge(1,2);
G.addEdge(1,4);
G.addEdge(2,3);
G.addEdge(3,4);
G.addEdge(3,5);
Matrix mat = Matrix::adjacencyMatrix(G);
// first row
EXPECT_EQ(1, mat(0,0));
EXPECT_EQ(1, mat(0,1));
EXPECT_EQ(0, mat(0,2));
EXPECT_EQ(0, mat(0,3));
EXPECT_EQ(1, mat(0,4));
EXPECT_EQ(0, mat(0,5));
// third row
EXPECT_EQ(0, mat(2,0));
EXPECT_EQ(1, mat(2,1));
EXPECT_EQ(0, mat(2,2));
EXPECT_EQ(1, mat(2,3));
EXPECT_EQ(0, mat(2,4));
EXPECT_EQ(0, mat(2,5));
// fifth row
EXPECT_EQ(1, mat(4,0));
EXPECT_EQ(1, mat(4,1));
EXPECT_EQ(0, mat(4,2));
EXPECT_EQ(1, mat(4,3));
EXPECT_EQ(0, mat(4,4));
EXPECT_EQ(0, mat(4,5));
// directed, weighted G
Graph dGraph(4, true, true);
dGraph.addEdge(0,1,2);
dGraph.addEdge(0,0, 42);
dGraph.addEdge(2,3,-3);
dGraph.addEdge(3,2,5);
mat = Matrix::adjacencyMatrix(dGraph);
ASSERT_EQ(dGraph.numberOfNodes(), mat.numberOfRows());
ASSERT_EQ(dGraph.numberOfNodes(), mat.numberOfColumns());
EXPECT_EQ(2, mat(0,1));
EXPECT_EQ(0, mat(1,0));
EXPECT_EQ(42, mat(0,0));
EXPECT_EQ(-3, mat(2,3));
EXPECT_EQ(5, mat(3,2));
// read lesmis G
METISGraphReader graphReader;
G = graphReader.read("input/lesmis.graph");
// create AdjacencyMatrix
mat = Matrix::adjacencyMatrix(G);
G.forNodes([&](node u) {
G.forNodes([&](node v) {
if (G.hasEdge(u,v)) {
EXPECT_EQ(G.weight(u,v), mat(u,v));
} else {
EXPECT_EQ(0.0, mat(u,v));
}
});
});
}
template<class Matrix>
void MatricesGTest::testDiagonalMatrix() {
Vector diagonal = {1,0,4,-1};
Matrix mat = Matrix::diagonalMatrix(diagonal);
EXPECT_EQ(4u, mat.numberOfRows());
EXPECT_EQ(4u, mat.numberOfColumns());
EXPECT_EQ(1, mat(0,0));
EXPECT_EQ(0, mat(1,1));
EXPECT_EQ(4, mat(2,2));
EXPECT_EQ(-1, mat(3,3));
for (index i = 0; i < mat.numberOfRows(); ++i) {
for (index j = 0; j < mat.numberOfColumns(); ++j) {
if (i != j) {
EXPECT_EQ(0, mat(i,j));
}
}
}
}
template<class Matrix>
void MatricesGTest::testIncidenceMatrix() {
Graph G = Graph(5, true);
G.addEdge(0,1, 4.0);
G.addEdge(0,2, 9.0);
G.addEdge(0,3, 16.0);
G.addEdge(2,3, 1.0);
G.addEdge(4,1, 25.0);
G.addEdge(4,4, 1.0);
G.indexEdges();
Matrix mat = Matrix::incidenceMatrix(G);
ASSERT_EQ(G.numberOfNodes(), mat.numberOfRows());
ASSERT_EQ(G.numberOfEdges(), mat.numberOfColumns());
EXPECT_EQ(sqrt(G.weight(0,1)), mat(0,0));
EXPECT_EQ(-sqrt(G.weight(0,1)), mat(1,0));
for (uint64_t i = 2; i < mat.numberOfRows(); ++i) {
EXPECT_EQ(0.0, mat(i, 0));
}
EXPECT_EQ(-sqrt(G.weight(0,2)), mat(2,1));
EXPECT_EQ(-sqrt(G.weight(0,3)), mat(3,2));
EXPECT_EQ(-sqrt(G.weight(2,3)), mat(3,3));
for (uint64_t i = 0; i < mat.numberOfRows(); ++i) {
EXPECT_EQ(0.0, mat(i, 5));
}
Vector row0 = mat.row(0);
ASSERT_EQ(row0.getDimension(), mat.numberOfColumns());
EXPECT_EQ(sqrt(G.weight(0,1)), row0[0]);
EXPECT_EQ(sqrt(G.weight(0,2)), row0[1]);
EXPECT_EQ(sqrt(G.weight(0,3)), row0[2]);
for (uint64_t j = 3; j < row0.getDimension(); ++j) {
EXPECT_EQ(0.0, row0[j]);
}
for (uint64_t j = 0; j < 5; ++j) {
Vector column = mat.column(j);
ASSERT_EQ(column.getDimension(), mat.numberOfRows());
double sum = 0.0;
for (uint64_t i = 0; i < column.getDimension(); ++i) {
sum += column[i];
}
EXPECT_EQ(0.0, sum);
}
Vector column5 = mat.column(5);
ASSERT_EQ(column5.getDimension(), mat.numberOfRows());
for (uint64_t i = 0; i < column5.getDimension(); ++i) {
EXPECT_EQ(0.0, column5[i]);
}
Vector v = {12, 3, 9, 28, 0, -1};
Vector result = mat * v;
ASSERT_EQ(result.getDimension(), mat.numberOfRows());
EXPECT_EQ(69, result[0]);
EXPECT_EQ(-24, result[1]);
EXPECT_EQ(19, result[2]);
EXPECT_EQ(-64, result[3]);
EXPECT_EQ(0, result[4]);
}
template<class Matrix>
void MatricesGTest::testLaplacianOfGraph() {
METISGraphReader graphReader;
Matrix mat = Matrix::laplacianMatrix(graph);
EXPECT_TRUE(MatrixTools::isLaplacian(mat));
mat = Matrix::laplacianMatrix(graphReader.read("input/power.graph"));
EXPECT_TRUE(MatrixTools::isLaplacian(mat));
}
TEST_F(MatricesGTest, testDimension) {
testDimension<DynamicMatrix>();
testDimension<CSRMatrix>();
testDimension<DenseMatrix>();
}
TEST_F(MatricesGTest, testNNZInRow) {
testNNZInRow<DynamicMatrix>();
testNNZInRow<CSRMatrix>();
testNNZInRow<DenseMatrix>();
}
TEST_F(MatricesGTest, testRowAndColumnAccess) {
testRowAndColumnAccess<DynamicMatrix>();
testRowAndColumnAccess<CSRMatrix>();
testRowAndColumnAccess<DenseMatrix>();
}
TEST_F(MatricesGTest, testDiagonalVector) {
testDiagonalVector<DynamicMatrix>();
testDiagonalVector<CSRMatrix>();
testDiagonalVector<DenseMatrix>();
}
TEST_F(MatricesGTest, testTranspose) {
testTranspose<DynamicMatrix>();
testTranspose<CSRMatrix>();
testTranspose<DenseMatrix>();
}
TEST_F(MatricesGTest, testExtract) {
testExtract<DynamicMatrix>();
testExtract<CSRMatrix>();
}
TEST_F(MatricesGTest, testAssign) {
testAssign<DynamicMatrix>();
testAssign<CSRMatrix>();
testAssign<DenseMatrix>();
}
TEST_F(MatricesGTest, testApply) {
testApply<DynamicMatrix>();
testApply<CSRMatrix>();
}
TEST_F(MatricesGTest, testMatrixAddition) {
testMatrixAddition<DynamicMatrix>();
testMatrixAddition<CSRMatrix>();
testMatrixAddition<DenseMatrix>();
}
TEST_F(MatricesGTest, testMatrixSubtraction) {
testMatrixSubtraction<DynamicMatrix>();
testMatrixSubtraction<CSRMatrix>();
testMatrixSubtraction<DenseMatrix>();
}
TEST_F(MatricesGTest, testScalarMultiplication) {
testScalarMultiplication<DynamicMatrix>();
testScalarMultiplication<CSRMatrix>();
testScalarMultiplication<DenseMatrix>();
}
TEST_F(MatricesGTest, testMatrixDivisionOperator) {
testMatrixDivisionOperator<DynamicMatrix>();
testMatrixDivisionOperator<CSRMatrix>();
testMatrixDivisionOperator<DenseMatrix>();
}
TEST_F(MatricesGTest, testMatrixVectorProduct) {
testMatrixVectorProduct<DynamicMatrix>();
testMatrixVectorProduct<CSRMatrix>();
testMatrixVectorProduct<DenseMatrix>();
}
TEST_F(MatricesGTest, testMatrixMultiplication) {
testMatrixMultiplication<DynamicMatrix>();
testMatrixMultiplication<CSRMatrix>();
testMatrixMultiplication<DenseMatrix>();
}
TEST_F(MatricesGTest, testBigMatrixMultiplcation) {
testBigMatrixMultiplication<DynamicMatrix>();
testBigMatrixMultiplication<CSRMatrix>();
}
TEST_F(MatricesGTest, testAdjacencyMatrixOfGraph) {
testAdjacencyMatrix<DynamicMatrix>();
testAdjacencyMatrix<CSRMatrix>();
}
TEST_F(MatricesGTest, testDiagonalMatrix) {
testDiagonalMatrix<DynamicMatrix>();
testDiagonalMatrix<CSRMatrix>();
}
TEST_F(MatricesGTest, testIncidenceMatrix) {
testIncidenceMatrix<DynamicMatrix>();
testIncidenceMatrix<CSRMatrix>();
}
TEST_F(MatricesGTest, testLaplacianMatrixOfGraph) {
testLaplacianOfGraph<DynamicMatrix>();
testLaplacianOfGraph<CSRMatrix>();
}
} /* namespace NetworKit */
| 24.253629 | 129 | 0.578818 | [
"vector"
] |
c8759dcf23cfd273d4e490f4b11c1f71e7815e32 | 28,386 | cpp | C++ | DearPyGui/src/core/PythonCommands/mvAppInterface.cpp | czhmisaka/DearPyGui | a10b6cb8446aa17d3b3255214ca6b535111ec835 | [
"MIT"
] | 1 | 2021-02-09T07:03:52.000Z | 2021-02-09T07:03:52.000Z | DearPyGui/src/core/PythonCommands/mvAppInterface.cpp | VinoXuanyu/DearPyGui | 4d45df347c9de67062c6d0e0db0b4e6e2864b184 | [
"MIT"
] | null | null | null | DearPyGui/src/core/PythonCommands/mvAppInterface.cpp | VinoXuanyu/DearPyGui | 4d45df347c9de67062c6d0e0db0b4e6e2864b184 | [
"MIT"
] | null | null | null | #include "mvAppInterface.h"
#include "mvAppItem.h"
#include "mvWindow.h"
#include "mvEvents.h"
#include <ImGuiFileDialog.h>
#include <iostream>
namespace Marvel {
void AddAppCommands(std::map<std::string, mvPythonParser>* parsers)
{
parsers->insert({ "add_texture", mvPythonParser({
{mvPythonDataType::String, "name"},
{mvPythonDataType::IntList, "data", "RGBA format"},
{mvPythonDataType::Integer, "width"},
{mvPythonDataType::Integer, "height"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::Integer, "format", "mvTEX_XXXX_XXXXX constants", "0"},
}, "Adds a texture.") });
parsers->insert({ "decrement_texture", mvPythonParser({
{mvPythonDataType::String, "name"},
}, "Decrements a texture.") });
parsers->insert({ "enable_docking", mvPythonParser({
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::Bool, "shift_only", "press shift for docking", "True"},
{mvPythonDataType::Bool, "dock_space", "add explicit dockspace over viewport", "False"},
}, "Decrements a texture.") });
parsers->insert({ "set_start_callback", mvPythonParser({
{mvPythonDataType::Object, "callback"},
}, "Callback to run when starting main window.") });
parsers->insert({ "set_exit_callback", mvPythonParser({
{mvPythonDataType::Object, "callback"},
}, "Callback to run when exiting main window.") });
parsers->insert({ "set_accelerator_callback", mvPythonParser({
{mvPythonDataType::Object, "callback"},
}, "Callback similar to keypress but used for accelerator keys.") });
parsers->insert({ "set_vsync", mvPythonParser({
{mvPythonDataType::Bool, "value"},
}, "Sets vsync on or off.") });
parsers->insert({ "is_dearpygui_running", mvPythonParser({
}, "Checks if dearpygui is still running", "bool") });
parsers->insert({ "set_main_window_title", mvPythonParser({
{mvPythonDataType::String, "title"}
}, "Sets the title of the main window.") });
parsers->insert({ "set_logger_window_title", mvPythonParser({
{mvPythonDataType::String, "title"}
}, "Sets the title of the logger window.") });
parsers->insert({ "set_main_window_resizable", mvPythonParser({
{mvPythonDataType::Bool, "resizable"}
}, "Sets the main window to be resizable.") });
parsers->insert({ "set_main_window_pos", mvPythonParser({
{mvPythonDataType::Integer, "x"},
{mvPythonDataType::Integer, "y"},
}, "Sets the main window position.") });
parsers->insert({ "add_character_remap", mvPythonParser({
{mvPythonDataType::Integer, "destination"},
{mvPythonDataType::Integer, "source"},
}, "Remaps characters.") });
parsers->insert({ "setup_dearpygui", mvPythonParser({
}, "Sets up DearPyGui for user controlled rendering. Only call once and you must call cleanup_deapygui when finished.") });
parsers->insert({ "render_dearpygui_frame", mvPythonParser({
}, "Renders a DearPyGui frame. Should be called within a user's event loop. Must first call setup_dearpygui outside of event loop.") });
parsers->insert({ "cleanup_dearpygui", mvPythonParser({
}, "Cleans up DearPyGui after calling setup_dearpygui.") });
parsers->insert({ "start_dearpygui", mvPythonParser({
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "primary_window", "Window that will expand into viewport.", "''"},
}, "Starts DearPyGui.") });
parsers->insert({ "stop_dearpygui", mvPythonParser({
}, "Stops DearPyGui.") });
parsers->insert({ "set_global_font_scale", mvPythonParser({
{mvPythonDataType::Float, "scale", "default is 1.0"}
}, "Changes the global font scale.") });
parsers->insert({ "get_global_font_scale", mvPythonParser({
}, "Returns the global font scale.", "float") });
parsers->insert({ "open_file_dialog", mvPythonParser({
{mvPythonDataType::Optional},
{mvPythonDataType::Callable, "callback", "function to call on completion", "None"},
{mvPythonDataType::String, "extensions", "filters items with extensions i.e '.*, .py'", "''"},
}, "Opens an 'open file' dialog.") });
parsers->insert({ "select_directory_dialog", mvPythonParser({
{mvPythonDataType::Optional},
{mvPythonDataType::Callable, "callback", "function to call on completion", "None"},
}, "Opens a select directory dialog.") });
parsers->insert({ "add_data", mvPythonParser({
{mvPythonDataType::String, "name"},
{mvPythonDataType::Object, "data"}
}, "Adds data for later retrieval.") });
parsers->insert({ "get_data", mvPythonParser({
{mvPythonDataType::String, "name"}
}, "Retrieves data from storage.", "object") });
parsers->insert({ "delete_data", mvPythonParser({
{mvPythonDataType::String, "name"}
}, "Deletes data from storage.") });
parsers->insert({ "get_total_time", mvPythonParser({
}, "Returns total time since app started.", "float") });
parsers->insert({ "get_delta_time", mvPythonParser({
}, "Returns time since last frame.", "float") });
parsers->insert({ "get_main_window_size", mvPythonParser({
}, "Returns the size of the main window.", "[int, int]") });
parsers->insert({ "get_active_window", mvPythonParser({
}, "Returns the active window name.", "str") });
parsers->insert({ "get_dearpygui_version", mvPythonParser({
}, "Returns the current version of Dear PyGui.", "str") });
parsers->insert({ "set_main_window_size", mvPythonParser({
{mvPythonDataType::Integer, "width"},
{mvPythonDataType::Integer, "height"}
}, "Sets the main window size.") });
parsers->insert({ "set_primary_window", mvPythonParser({
{mvPythonDataType::String, "window"},
{mvPythonDataType::Bool, "value"},
}, "Sets the primary window to fill the viewport.") });
}
void AddLogCommands(std::map<std::string, mvPythonParser>* parsers)
{
parsers->insert({ "get_log_level", mvPythonParser({
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Returns the log level.", "int", "Logging") });
parsers->insert({ "clear_log", mvPythonParser({
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Clears the logger.", "None", "Logging") });
parsers->insert({ "set_log_level", mvPythonParser({
{mvPythonDataType::Integer, "level"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Sets the log level.", "None", "Logging") });
parsers->insert({ "log", mvPythonParser({
{mvPythonDataType::Object, "message"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "level", "logger widget", "'TRACE'"},
{mvPythonDataType::String, "logger", "logger widget", "''"}
}, "Logs a trace level log.", "None", "Logging") });
parsers->insert({ "log_debug", mvPythonParser({
{mvPythonDataType::Object, "message"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Logs a debug level log.", "None", "Logging") });
parsers->insert({ "log_info", mvPythonParser({
{mvPythonDataType::Object, "message"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Logs a info level log.", "None", "Logging") });
parsers->insert({ "log_warning", mvPythonParser({
{mvPythonDataType::Object, "message"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Logs a warning level log.", "None", "Logging") });
parsers->insert({ "log_error", mvPythonParser({
{mvPythonDataType::Object, "message"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::String, "logger", "logger widget", "''"},
}, "Logs a error level log.", "None", "Logging") });
}
void AddStdWindowCommands(std::map<std::string, mvPythonParser>* parsers)
{
parsers->insert({ "show_logger", mvPythonParser({
}, "Shows the logging window. The Default log level is Trace", "None", "Standard Windows") });
parsers->insert({ "close_popup", mvPythonParser({
{mvPythonDataType::String, "item"},
}, "Closes a popup.") });
}
PyObject* add_texture(PyObject* self, PyObject* args, PyObject* kwargs)
{
// TO DO, FIX THIS MESS
const char* name;
PyObject* data;
int width;
int height;
int format = 0;
if (!(*mvApp::GetApp()->getParsers())["add_texture"].parse(args, kwargs, __FUNCTION__,
&name, &data, &width, &height, &format))
return GetPyNone();
mvTextureFormat tformat = (mvTextureFormat)format;
std::vector<float> fdata;
if (tformat == mvTextureFormat::RGBA_INT)
{
std::vector<int> mdata = ToIntVect(data);
for (auto& item : mdata)
fdata.push_back(item / 255.0f);
}
else if (tformat == mvTextureFormat::RGB_INT)
{
std::vector<int> mdata = ToIntVect(data);
for (int i = 0; i < mdata.size(); i = i + 3)
{
fdata.push_back(mdata[i] / 255.0f);
fdata.push_back(mdata[i + 1] / 255.0f);
fdata.push_back(mdata[i + 2] / 255.0f);
fdata.push_back(1.0f);
}
}
else if (tformat == mvTextureFormat::RGBA_FLOAT)
fdata = ToFloatVect(data);
else if (tformat == mvTextureFormat::RGB_FLOAT)
{
std::vector<float> mdata = ToFloatVect(data);
for (int i = 0; i < mdata.size(); i = i + 3)
{
fdata.push_back(mdata[i]);
fdata.push_back(mdata[i + 1]);
fdata.push_back(mdata[i + 2]);
fdata.push_back(1.0f);
}
}
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
if (mvApp::IsAppStarted())
mvApp::GetApp()->getTextureStorage().addTexture(name, fdata.data(), width, height, tformat);
else
mvApp::GetApp()->getTextureStorage().addDelayedTexture(name, fdata, width, height, tformat);
return GetPyNone();
}
PyObject* enable_docking(PyObject* self, PyObject* args, PyObject* kwargs)
{
int shift_only = true;
int dockspace = false;
if (!(*mvApp::GetApp()->getParsers())["enable_docking"].parse(args, kwargs, __FUNCTION__,
&shift_only, &dockspace))
return GetPyNone();
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->turnOnDocking(shift_only, dockspace);
});
return GetPyNone();
}
PyObject* decrement_texture(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
if (!(*mvApp::GetApp()->getParsers())["decrement_texture"].parse(args, kwargs, __FUNCTION__,
&name))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvEventBus::PublishEndFrame(mvEVT_CATEGORY_TEXTURE, mvEVT_DEC_TEXTURE, { CreateEventArgument("NAME", std::string(name)) });
return GetPyNone();
}
PyObject* is_dearpygui_running(PyObject* self, PyObject* args, PyObject* kwargs)
{
return ToPyBool(mvApp::IsAppStarted());
}
PyObject* set_main_window_title(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* title;
if (!(*mvApp::GetApp()->getParsers())["set_main_window_title"].parse(args, kwargs, __FUNCTION__,
&title))
return GetPyNone();
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->setTitle(title);
if (mvApp::IsAppStarted())
mvApp::GetApp()->getViewport()->setWindowText(title);
});
return GetPyNone();
}
PyObject* set_main_window_pos(PyObject* self, PyObject* args, PyObject* kwargs)
{
int x;
int y;
if (!(*mvApp::GetApp()->getParsers())["set_main_window_pos"].parse(args, kwargs, __FUNCTION__,
&x, &y))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvApp::GetApp()->setMainPos(x, y);
return GetPyNone();
}
PyObject* add_character_remap(PyObject* self, PyObject* args, PyObject* kwargs)
{
int destination;
int source;
if (!(*mvApp::GetApp()->getParsers())["add_character_remap"].parse(args, kwargs, __FUNCTION__,
&destination, &source))
return GetPyNone();
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->addRemapChar(destination, source);
});
return GetPyNone();
}
PyObject* set_main_window_resizable(PyObject* self, PyObject* args, PyObject* kwargs)
{
int resizable = true;
if (!(*mvApp::GetApp()->getParsers())["set_main_window_resizable"].parse(args, kwargs, __FUNCTION__,
&resizable))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvApp::GetApp()->setResizable(resizable);
return GetPyNone();
}
PyObject* set_vsync(PyObject* self, PyObject* args, PyObject* kwargs)
{
int value;
if (!(*mvApp::GetApp()->getParsers())["set_vsync"].parse(args, kwargs, __FUNCTION__,
&value))
return GetPyNone();
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->setVSync(value);
});
return GetPyNone();
}
PyObject* setup_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs)
{
Py_BEGIN_ALLOW_THREADS;
mvApp::SetAppStarted();
// create window
auto window = mvWindow::CreatemvWindow(mvApp::GetApp()->getActualWidth(), mvApp::GetApp()->getActualHeight(), false);
window->show();
mvApp::GetApp()->setViewport(window);
window->setup();
Py_END_ALLOW_THREADS;
return GetPyNone();
}
PyObject* render_dearpygui_frame(PyObject* self, PyObject* args, PyObject* kwargs)
{
Py_BEGIN_ALLOW_THREADS;
auto window = mvApp::GetApp()->getViewport();
window->renderFrame();
Py_END_ALLOW_THREADS;
return GetPyNone();
}
PyObject* cleanup_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs)
{
auto window = mvApp::GetApp()->getViewport();
delete window;
mvApp::GetApp()->setViewport(nullptr);
Py_BEGIN_ALLOW_THREADS;
mvApp::SetAppStopped();
mvApp::DeleteApp();
Py_END_ALLOW_THREADS;
return GetPyNone();
}
PyObject* start_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* primary_window = "";
if (!(*mvApp::GetApp()->getParsers())["start_dearpygui"].parse(args, kwargs, __FUNCTION__, &primary_window))
return GetPyNone();
if (mvApp::IsAppStarted())
{
ThrowPythonException("Cannot call \"start_dearpygui\" while a Dear PyGUI app is already running.");
return GetPyNone();
}
Py_BEGIN_ALLOW_THREADS;
mvApp::GetApp()->start(primary_window);
Py_END_ALLOW_THREADS;
mvApp::DeleteApp();
mvEventBus::Reset();
mvAppLog::Clear();
return GetPyNone();
}
PyObject* set_start_callback(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* callback;
if (!(*mvApp::GetApp()->getParsers())["set_start_callback"].parse(args, kwargs, __FUNCTION__, &callback))
return GetPyNone();
Py_XINCREF(callback);
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->getCallbackRegistry().setOnStartCallback(callback);
});
return GetPyNone();
}
PyObject* set_exit_callback(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* callback;
if (!(*mvApp::GetApp()->getParsers())["set_exit_callback"].parse(args, kwargs, __FUNCTION__, &callback))
return GetPyNone();
Py_XINCREF(callback);
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->getCallbackRegistry().setOnCloseCallback(callback);
});
return GetPyNone();
}
PyObject* set_accelerator_callback(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* callback;
if (!(*mvApp::GetApp()->getParsers())["set_accelerator_callback"].parse(args, kwargs, __FUNCTION__, &callback))
return GetPyNone();
Py_XINCREF(callback);
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
mvApp::GetApp()->getCallbackRegistry().setAcceleratorCallback(callback);
});
return GetPyNone();
}
PyObject* stop_dearpygui(PyObject* self, PyObject* args, PyObject* kwargs)
{
mvApp::StopApp();
auto viewport = mvApp::GetApp()->getViewport();
if (viewport)
viewport->stop();
return GetPyNone();
}
PyObject* select_directory_dialog(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* callback = nullptr;
if (!(*mvApp::GetApp()->getParsers())["select_directory_dialog"].parse(args, kwargs, __FUNCTION__, &callback))
return GetPyNone();
if (callback)
Py_XINCREF(callback);
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
igfd::ImGuiFileDialog::Instance()->OpenModal("ChooseFileDlgKey", "Choose Directory", 0, ".");
auto window = mvApp::GetApp()->getItemRegistry().getItem("filedialog");
auto dialog = static_cast<mvFileDialog*>(window.get());
dialog->setCallback(callback);
window->show();
});
return GetPyNone();
}
PyObject* open_file_dialog(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* callback = nullptr;
const char* extensions = ".*";
if (!(*mvApp::GetApp()->getParsers())["open_file_dialog"].parse(args, kwargs, __FUNCTION__,
&callback, &extensions))
return GetPyNone();
if (callback)
Py_XINCREF(callback);
mvApp::GetApp()->getCallbackRegistry().submit([=]()
{
igfd::ImGuiFileDialog::Instance()->OpenModal("ChooseFileDlgKey", "Choose File", extensions, ".");
auto window = mvApp::GetApp()->getItemRegistry().getItem("filedialog");
auto dialog = static_cast<mvFileDialog*>(window.get());
dialog->setCallback(callback);
window->show();
});
return GetPyNone();
}
PyObject* get_total_time(PyObject* self, PyObject* args, PyObject* kwargs)
{
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
return ToPyFloat((float)mvApp::GetApp()->getTotalTime());
}
PyObject* get_delta_time(PyObject* self, PyObject* args, PyObject* kwargs)
{
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
return ToPyFloat(mvApp::GetApp()->getDeltaTime());
}
PyObject* get_main_window_size(PyObject* self, PyObject* args, PyObject* kwargs)
{
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
return ToPyPairII(mvApp::GetApp()->getActualWidth(), mvApp::GetApp()->getActualHeight());
}
PyObject* get_active_window(PyObject* self, PyObject* args, PyObject* kwargs)
{
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
return ToPyString(mvApp::GetApp()->getItemRegistry().getActiveWindow());
}
PyObject* get_dearpygui_version(PyObject* self, PyObject* args, PyObject* kwargs)
{
return ToPyString(mvApp::GetApp()->GetVersion());
}
PyObject* add_data(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
PyObject* data;
if (!(*mvApp::GetApp()->getParsers())["add_data"].parse(args, kwargs, __FUNCTION__, &name, &data))
return GetPyNone();
Py_XINCREF(data);
mvDataStorage::AddData(name, data);
return GetPyNone();
}
PyObject* get_data(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
if (!(*mvApp::GetApp()->getParsers())["get_data"].parse(args, kwargs, __FUNCTION__, &name))
return GetPyNone();
return mvDataStorage::GetDataIncRef(name);
}
PyObject* delete_data(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
if (!(*mvApp::GetApp()->getParsers())["delete_data"].parse(args, kwargs, __FUNCTION__, &name))
return GetPyNone();
mvDataStorage::DeleteData(name);
return GetPyNone();
}
PyObject* set_main_window_size(PyObject* self, PyObject* args, PyObject* kwargs)
{
int width;
int height;
if (!(*mvApp::GetApp()->getParsers())["set_main_window_size"].parse(args, kwargs, __FUNCTION__, &width, &height))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvEventBus::Publish(mvEVT_CATEGORY_VIEWPORT, mvEVT_VIEWPORT_RESIZE, {
CreateEventArgument("actual_width", width),
CreateEventArgument("actual_height", height),
CreateEventArgument("client_width", width),
CreateEventArgument("client_height", height)
});
return GetPyNone();
}
PyObject* get_log_level(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["get_log_level"].parse(args, kwargs, __FUNCTION__, &logger))
return GetPyNone();
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return ToPyInt(-1);
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return ToPyInt(-1);
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
return ToPyInt(loggerwidget->getLogLevel());
}
else
return ToPyInt((int)mvAppLog::getLogLevel());
}
PyObject* set_log_level(PyObject* self, PyObject* args, PyObject* kwargs)
{
int level;
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["set_log_level"].parse(args, kwargs, __FUNCTION__,
&level, &logger))
return GetPyNone();
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->setLogLevel(level);
}
else
mvAppLog::setLogLevel(level);
return GetPyNone();
}
PyObject* log(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* message;
const char* level = "TRACE";
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["log"].parse(args, kwargs, __FUNCTION__, &message, &level, &logger))
return GetPyNone();
std::string cmessage = ToString(message);
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->Log(cmessage, std::string(level));
}
else
mvAppLog::Log(cmessage, std::string(level));
return GetPyNone();
}
PyObject* log_debug(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* message;
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["log_debug"].parse(args, kwargs, __FUNCTION__, &message, &logger))
return GetPyNone();
std::string cmessage = ToString(message);
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->LogDebug(cmessage);
}
else
mvAppLog::LogDebug(cmessage);
return GetPyNone();
}
PyObject* log_info(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* message;
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["log_info"].parse(args, kwargs, __FUNCTION__, &message, &logger))
return GetPyNone();
std::string cmessage = ToString(message);
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->LogInfo(cmessage);
}
else
mvAppLog::LogInfo(cmessage);
return GetPyNone();
}
PyObject* log_warning(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* message;
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["log_warning"].parse(args, kwargs, __FUNCTION__, &message, &logger))
return GetPyNone();
std::string cmessage = ToString(message);
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->LogWarning(cmessage);
}
else
mvAppLog::LogWarning(cmessage);
return GetPyNone();
}
PyObject* log_error(PyObject* self, PyObject* args, PyObject* kwargs)
{
PyObject* message;
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["log_error"].parse(args, kwargs, __FUNCTION__, &message, &logger))
return GetPyNone();
std::string cmessage = ToString(message);
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->LogError(cmessage);
}
else
mvAppLog::LogError(cmessage);
return GetPyNone();
}
PyObject* clear_log(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* logger = "";
if (!(*mvApp::GetApp()->getParsers())["clear_log"].parse(args, kwargs, __FUNCTION__, &logger))
return GetPyNone();
if (!std::string(logger).empty())
{
auto loggeritem = mvApp::GetApp()->getItemRegistry().getItem(logger);
if (loggeritem == nullptr)
{
ThrowPythonException(std::string(logger) + " logger does not exist.");
return GetPyNone();
}
if (loggeritem->getType() != mvAppItemType::Logger)
{
ThrowPythonException(std::string(logger) + " is not a logger.");
return GetPyNone();
}
auto loggerwidget = static_cast<mvLoggerItem*>(loggeritem.get());
loggerwidget->ClearLog();
}
else
mvAppLog::ClearLog();
return GetPyNone();
}
PyObject* show_logger(PyObject* self, PyObject* args)
{
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvAppLog::Show();
return GetPyNone();
}
PyObject* set_logger_window_title(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* title;
if (!(*mvApp::GetApp()->getParsers())["set_logger_window_title"].parse(args, kwargs, __FUNCTION__,
&title))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvAppLog::setTitle(title);
return GetPyNone();
}
PyObject* close_popup(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* popup;
if (!(*mvApp::GetApp()->getParsers())["close_popup"].parse(args, kwargs, __FUNCTION__, &popup))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
auto item = mvApp::GetApp()->getItemRegistry().getItem(popup);
if (item == nullptr)
{
std::string message = popup;
ThrowPythonException(message + " popup does not exist.");
return GetPyNone();
}
mvPopup* pop;
if (item->getType() == mvAppItemType::Popup)
pop = static_cast<mvPopup*>(item.get());
else
{
ThrowPythonException(std::string(popup) + " is not a popup.");
return GetPyNone();
}
pop->closePopup();
return GetPyNone();
}
PyObject* set_primary_window(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
int value;
if (!(*mvApp::GetApp()->getParsers())["set_primary_window"].parse(args, kwargs, __FUNCTION__, &item, &value))
return GetPyNone();
std::lock_guard<std::mutex> lk(mvApp::GetApp()->GetApp()->getMutex());
mvApp::GetApp()->getItemRegistry().setPrimaryWindow(item, value);
return GetPyNone();
}
}
| 28.847561 | 138 | 0.675016 | [
"object",
"vector"
] |
c877b7130c55c728a635a4170405447115551244 | 114,249 | cc | C++ | paddle/fluid/operators/mlu/mlu_baseop.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 2 | 2021-07-25T06:47:03.000Z | 2021-12-17T04:27:26.000Z | paddle/fluid/operators/mlu/mlu_baseop.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | null | null | null | paddle/fluid/operators/mlu/mlu_baseop.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 2 | 2021-03-10T08:05:40.000Z | 2021-03-11T14:30:14.000Z | /* Copyright (c) 2021 PaddlePaddle 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 "paddle/fluid/operators/mlu/mlu_baseop.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/framework.pb.h"
#include "paddle/fluid/framework/operator.h"
namespace paddle {
namespace operators {
class MLUCnnlTensorDescPool {
public:
cnnlTensorDescriptor_t Pop() {
cnnlTensorDescriptor_t raw_desc;
if (q_.try_dequeue(raw_desc)) {
return raw_desc;
} else {
cnnlCreateTensorDescriptor(&raw_desc);
return raw_desc;
}
}
void Recycle(cnnlTensorDescriptor_t desc) {
cnnlResetTensorDescriptor(desc);
q_.enqueue(desc);
}
~MLUCnnlTensorDescPool() {
auto size = q_.size_approx();
if (size > 0) {
std::vector<cnnlTensorDescriptor_t> vec(size);
q_.try_dequeue_bulk(vec.data(), size);
for (auto desc : vec) {
cnnlDestroyTensorDescriptor(desc);
}
}
}
private:
moodycamel::ConcurrentQueue<cnnlTensorDescriptor_t> q_;
};
static MLUCnnlTensorDescPool g_cnnl_tensor_desc_pool;
MLUCnnlTensorDesc& MLUCnnlTensorDesc::operator=(MLUCnnlTensorDesc&& rhs) {
if (raw_tensor_desc) {
g_cnnl_tensor_desc_pool.Recycle(raw_tensor_desc);
}
raw_tensor_desc = rhs.raw_tensor_desc;
rhs.raw_tensor_desc = nullptr;
return *this;
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const int tensor_dim,
const int dim_sizes[],
const cnnlDataType_t tensor_dtype) {
raw_tensor_desc = g_cnnl_tensor_desc_pool.Pop();
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptor(
raw_tensor_desc, CNNL_LAYOUT_ARRAY, tensor_dtype, tensor_dim, dim_sizes));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const int tensor_dim,
const int dim_sizes[],
const cnnlDataType_t tensor_dtype,
const cnnlTensorLayout_t layout) {
raw_tensor_desc = g_cnnl_tensor_desc_pool.Pop();
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptor(
raw_tensor_desc, layout, tensor_dtype, tensor_dim, dim_sizes));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const int tensor_dim,
const int dim_sizes[],
const cnnlDataType_t tensor_dtype,
int position)
: MLUCnnlTensorDesc(tensor_dim, dim_sizes, tensor_dtype) {
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorPosition(raw_tensor_desc, position));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const int tensor_dim,
const int64_t dim_sizes[],
const cnnlDataType_t tensor_dtype) {
std::vector<int> dim_sizes_int32(tensor_dim);
std::vector<int64_t>::const_iterator int64_cbegin(dim_sizes);
std::vector<int64_t>::const_iterator int64_cend(dim_sizes + tensor_dim);
std::transform(int64_cbegin, int64_cend, dim_sizes_int32.begin(),
&CheckedNarrowing<int64_t, int>);
raw_tensor_desc = g_cnnl_tensor_desc_pool.Pop();
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptor(raw_tensor_desc, CNNL_LAYOUT_ARRAY, tensor_dtype,
tensor_dim, dim_sizes_int32.data()));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const int tensor_dim,
const int64_t dim_sizes[],
const cnnlDataType_t tensor_dtype,
const cnnlTensorLayout_t layout) {
std::vector<int> dim_sizes_int32(tensor_dim);
std::vector<int64_t>::const_iterator int64_cbegin(dim_sizes);
std::vector<int64_t>::const_iterator int64_cend(dim_sizes + tensor_dim);
std::transform(int64_cbegin, int64_cend, dim_sizes_int32.begin(),
&CheckedNarrowing<int64_t, int>);
raw_tensor_desc = g_cnnl_tensor_desc_pool.Pop();
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptor(raw_tensor_desc, layout,
tensor_dtype, tensor_dim,
dim_sizes_int32.data()));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const int tensor_dim,
const int64_t dim_sizes[],
const cnnlDataType_t tensor_dtype,
int position) {
std::vector<int> dim_sizes_int32(tensor_dim);
std::vector<int64_t>::const_iterator int64_cbegin(dim_sizes);
std::vector<int64_t>::const_iterator int64_cend(dim_sizes + tensor_dim);
std::transform(int64_cbegin, int64_cend, dim_sizes_int32.begin(),
&CheckedNarrowing<int64_t, int>);
raw_tensor_desc = g_cnnl_tensor_desc_pool.Pop();
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptor(raw_tensor_desc, CNNL_LAYOUT_ARRAY, tensor_dtype,
tensor_dim, dim_sizes_int32.data()));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorPosition(raw_tensor_desc, position));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const Tensor& tensor,
const cnnlTensorLayout_t layout,
const cnnlDataType_t tensor_dtype) {
auto dims = framework::vectorize<int>(tensor.dims());
int tensor_dim = dims.size();
raw_tensor_desc = g_cnnl_tensor_desc_pool.Pop();
if (tensor_dim == 0) {
int scalar_dims[1] = {1};
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptor(
raw_tensor_desc, layout, tensor_dtype, 1, scalar_dims));
} else {
std::vector<int> tensor_dim_sizes_int(dims.begin(), dims.end());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptor(raw_tensor_desc, layout, tensor_dtype,
tensor_dim, tensor_dim_sizes_int.data()));
}
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const Tensor& tensor,
cnnlTensorLayout_t layout,
const cnnlDataType_t tensor_dtype,
int position)
: MLUCnnlTensorDesc(tensor, layout, tensor_dtype) {
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorPosition(raw_tensor_desc, position));
}
MLUCnnlTensorDesc::MLUCnnlTensorDesc(const Tensor& tensor,
cnnlTensorLayout_t layout,
const cnnlDataType_t tensor_dtype,
int position, float scale)
: MLUCnnlTensorDesc(tensor, layout, tensor_dtype) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptorPositionAndScale(
raw_tensor_desc, position, scale));
}
MLUCnnlTensorDesc::~MLUCnnlTensorDesc() {
if (raw_tensor_desc) {
g_cnnl_tensor_desc_pool.Recycle(raw_tensor_desc);
}
}
MLUCnnlActivationDesc::MLUCnnlActivationDesc(
const cnnlActivationMode_t act_mode, const float ceof) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateActivationDescriptor(&active_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetActivationDescriptor(
active_desc_, act_mode, CNNL_NOT_PROPAGATE_NAN, ceof));
}
const cnnlActivationDescriptor_t MLUCnnlActivationDesc::get() const {
return active_desc_;
}
MLUCnnlActivationDesc::~MLUCnnlActivationDesc() {
if (active_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyActivationDescriptor(active_desc_));
}
}
MLUCnnlPoolingDesc::MLUCnnlPoolingDesc(
const cnnlPoolingMode_t mode, const cnnlNanPropagation_t maxpooling_nan_opt,
int window_rows, int window_cols, int64_t pad_up, int64_t pad_down,
int64_t pad_left, int64_t pad_right, int row_stride, int col_stride) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreatePoolingDescriptor(&pooling_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetPooling2dDescriptor(
pooling_desc_, mode, maxpooling_nan_opt, window_rows, window_cols, pad_up,
pad_down, pad_left, pad_right, row_stride, col_stride));
}
MLUCnnlPoolingDesc::MLUCnnlPoolingDesc(
const cnnlPoolingMode_t mode, const cnnlNanPropagation_t maxpooling_nan_opt,
const int tensor_rank, const std::vector<int>& window,
const std::vector<int>& padding, const std::vector<int>& stride) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreatePoolingDescriptor(&pooling_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetPoolingNdDescriptor(
pooling_desc_, mode, maxpooling_nan_opt, tensor_rank, window.data(),
padding.data(), stride.data()));
}
const cnnlPoolingDescriptor_t MLUCnnlPoolingDesc::get() const {
return pooling_desc_;
}
MLUCnnlPoolingDesc::~MLUCnnlPoolingDesc() {
if (pooling_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyPoolingDescriptor(pooling_desc_));
}
}
MLUCnnlRandomGeneratorDesc::MLUCnnlRandomGeneratorDesc(const bool is_mlu200,
const int seed) {
if (is_mlu200) {
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlRandCreateGenerator(&mlu_generator, CNNL_RAND_RNG_FAST));
} else {
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlRandCreateGenerator(&mlu_generator, CNNL_RAND_RNG_MTGP32));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlRandSetPseudoRandomGeneratorSeed(mlu_generator, seed));
}
}
const cnnlRandGenerator_t MLUCnnlRandomGeneratorDesc::get() const {
return mlu_generator;
}
MLUCnnlRandomGeneratorDesc::~MLUCnnlRandomGeneratorDesc() {
if (mlu_generator) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlRandDestroyGenerator(mlu_generator));
}
}
MLUCnnlNMSDesc::MLUCnnlNMSDesc(const cnnlNmsOutputMode_t mode,
const float iou_threshold,
const int max_output_size,
const float confidence_threshold,
const int input_layout) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateNmsDescriptor(&nms_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetNmsDescriptor_v2(nms_desc_, mode, iou_threshold, max_output_size,
confidence_threshold, input_layout));
}
const cnnlNmsDescriptor_t MLUCnnlNMSDesc::get() const { return nms_desc_; }
MLUCnnlNMSDesc::~MLUCnnlNMSDesc() {
if (nms_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyNmsDescriptor(nms_desc_));
}
}
MLUCnnlReduceDesc::MLUCnnlReduceDesc(const std::vector<int>& axis_vec,
const cnnlReduceOp_t reduce_op,
const cnnlDataType_t data_type,
const cnnlNanPropagation_t nan_propagation,
const cnnlReduceIndices_t reduce_indices,
const cnnlIndicesType_t indices_type) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateReduceDescriptor(&reduction_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetReduceDescriptor(
reduction_desc_, const_cast<int*>(axis_vec.data()), axis_vec.size(),
reduce_op, data_type, nan_propagation, reduce_indices, indices_type));
}
const cnnlReduceDescriptor_t MLUCnnlReduceDesc::get() const {
return reduction_desc_;
}
MLUCnnlReduceDesc::~MLUCnnlReduceDesc() {
if (reduction_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyReduceDescriptor(reduction_desc_));
}
}
MLUCnnlOpTensorDesc::MLUCnnlOpTensorDesc(
cnnlOpTensorDesc_t op_tensor_op, cnnlDataType_t op_tensor_comp_type,
cnnlNanPropagation_t op_tensor_nan_opt) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateOpTensorDescriptor(&op_tensor_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetOpTensorDescriptor(
op_tensor_desc_, op_tensor_op, op_tensor_comp_type, op_tensor_nan_opt));
}
const cnnlOpTensorDescriptor_t MLUCnnlOpTensorDesc::get() const {
return op_tensor_desc_;
}
MLUCnnlOpTensorDesc::~MLUCnnlOpTensorDesc() {
if (op_tensor_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyOpTensorDescriptor(op_tensor_desc_));
}
}
MLUCnnlConvolutionDesc::MLUCnnlConvolutionDesc(
const int dims, const int pad[], const int stride[], const int dilation[],
const int group_count, const cnnlDataType_t tensor_dtype) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateConvolutionDescriptor(&conv_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetConvolutionDescriptor(
conv_desc_, dims, pad, stride, dilation, group_count, tensor_dtype));
}
MLUCnnlConvolutionDesc::MLUCnnlConvolutionDesc(
const int dims, const int64_t pad[], const int64_t stride[],
const int64_t dilation[], const int group_count,
const cnnlDataType_t tensor_dtype) {
const int spatial_dims = dims - 2;
const int pad_dims = spatial_dims * 2;
std::vector<int> pad_int32(pad_dims);
std::vector<int> stride_int32(spatial_dims);
std::vector<int> dilation_int32(spatial_dims);
std::vector<int64_t>::const_iterator int64_pad_cbegin(pad);
std::vector<int64_t>::const_iterator int64_pad_cend(pad + pad_dims);
std::vector<int64_t>::const_iterator int64_stride_cbegin(stride);
std::vector<int64_t>::const_iterator int64_stride_cend(stride + spatial_dims);
std::vector<int64_t>::const_iterator int64_dilation_cbegin(dilation);
std::vector<int64_t>::const_iterator int64_dilation_cend(dilation +
spatial_dims);
std::transform(int64_pad_cbegin, int64_pad_cend, pad_int32.begin(),
&CheckedNarrowing<int64_t, int>);
std::transform(int64_stride_cbegin, int64_stride_cend, stride_int32.begin(),
&CheckedNarrowing<int64_t, int>);
std::transform(int64_dilation_cbegin, int64_dilation_cend,
dilation_int32.begin(), &CheckedNarrowing<int64_t, int>);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateConvolutionDescriptor(&conv_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetConvolutionDescriptor(
conv_desc_, dims, pad_int32.data(), stride_int32.data(),
dilation_int32.data(), group_count, tensor_dtype));
}
const cnnlConvolutionDescriptor_t MLUCnnlConvolutionDesc::get() const {
return conv_desc_;
}
MLUCnnlConvolutionDesc::~MLUCnnlConvolutionDesc() {
if (conv_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyConvolutionDescriptor(conv_desc_));
}
}
MLUCnnlBatchSpaceDesc::MLUCnnlBatchSpaceDesc(uint32_t block_shape[],
uint32_t paddings[],
const uint32_t block_shape_size,
const uint32_t paddings_size) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateSpaceBatchNdDescriptor(&op_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetSpaceBatchNdDescriptor(
op_desc_, block_shape, block_shape_size, paddings, paddings_size));
}
void MLUCnnlBatchSpaceDesc::getSpace2batchNdextraInputSize(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetSpace2batchNdExtraInputSize(
handle, input_desc, op_desc_, &extra_input_size_));
}
void MLUCnnlBatchSpaceDesc::getBatch2spaceNdextraInputSize(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetBatch2spaceNdExtraInputSize(
handle, input_desc, op_desc_, &extra_input_size_));
}
void MLUCnnlBatchSpaceDesc::initSpace2batchNdExtraInput(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
void* extra_host_input) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlInitSpace2batchNdExtraInput(
handle, input_desc, op_desc_, extra_host_input));
}
void MLUCnnlBatchSpaceDesc::initBatch2spaceNdExtraInput(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
void* extra_host_input) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlInitBatch2spaceNdExtraInput(
handle, input_desc, op_desc_, extra_host_input));
}
const cnnlSpaceBatchNdDescriptor_t MLUCnnlBatchSpaceDesc::get() const {
return op_desc_;
}
size_t MLUCnnlBatchSpaceDesc::getExtraInputSize() const {
return extra_input_size_;
}
MLUCnnlBatchSpaceDesc::~MLUCnnlBatchSpaceDesc() {
if (op_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroySpaceBatchNdDescriptor(op_desc_));
}
}
MLUCnnlTrigonDesc::MLUCnnlTrigonDesc(
const cnnlTrigonFunctionMode_t trigon_function_mode) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateTrigonDescriptor(&trigon_desc_));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTrigonDescriptor(trigon_desc_, trigon_function_mode));
}
const cnnlTrigonDescriptor_t MLUCnnlTrigonDesc::get() const {
return trigon_desc_;
}
MLUCnnlTrigonDesc::~MLUCnnlTrigonDesc() {
if (trigon_desc_) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyTrigonDescriptor(trigon_desc_));
}
}
/* static */ void MLUCnnl::Active(const ExecutionContext& ctx,
cnnlActivationDescriptor_t active_desc,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlActivationForward(
handle, active_desc, NULL, input_desc, input, NULL, output_desc, output));
}
/* static */ void MLUCnnl::ActiveGrad(
const ExecutionContext& ctx, cnnlActivationDescriptor_t active_desc,
const void* alpha, const void* beta, const cnnlTensorDescriptor_t y_desc,
const void* y, const cnnlTensorDescriptor_t diff_y_desc, const void* diff_y,
const cnnlTensorDescriptor_t x_desc, const void* x,
const cnnlTensorDescriptor_t diff_x_desc, void* diff_x) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlActivationBackward(handle, active_desc, alpha, y_desc, y, diff_y_desc,
diff_y, x_desc, x, beta, diff_x_desc, diff_x));
}
/* static */ void MLUCnnl::Concat(const ExecutionContext& ctx,
const int pack_num, const int axis,
const cnnlTensorDescriptor_t inputs_desc[],
const void* const inputs[],
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetConcatWorkspaceSize(handle, pack_num, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlConcat(handle, pack_num, axis, inputs_desc,
inputs, workspace_ptr, workspace_size,
output_desc, output));
}
/* static */ void MLUCnnl::Div(
const ExecutionContext& ctx, cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t in0_desc, const void* in0,
const cnnlTensorDescriptor_t in1_desc, const void* in1,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetDivWorkspaceSize(
handle, in0_desc, in1_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDiv_v2(handle, prefer, in0_desc, in0, in1_desc,
in1, workspace_ptr, workspace_size,
output_desc, output));
}
/* static */ void MLUCnnl::Fill(const ExecutionContext& ctx, float value,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlFill(handle, value, output_desc, output));
}
/* static */ void MLUCnnl::QuantifyOffline(
const ExecutionContext& ctx, cnnlQuantizeMode_t mode,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlQuantizeV1(handle, mode, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::LRN(const ExecutionContext& ctx,
const int local_size, const double alpha,
const double beta, const double k,
const cnnlTensorDescriptor_t input_quant_desc,
const void* input_quant,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetLrnWorkspaceSize(
handle, input_quant_desc, output_desc, local_size, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
const cnnlLrnMode_t mode = CNNL_LRN_CROSS_CHANNEL;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlLrn(
handle, mode, local_size, alpha, beta, k, workspace_ptr, workspace_size,
input_quant_desc, const_cast<void*>(input_quant), output_desc, output));
}
/* static */ void MLUCnnl::QuantifyOnline(
const ExecutionContext& ctx, const int bitwidth,
const cnnlTensorDescriptor_t input_desc, const void* input,
const bool compute_scale, void* position, void* scale,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetQuantizeParamWorkspaceSize(handle, input_desc, &workspace_size));
// use ctx allocate interface for profiling purpose
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
const cnnlQuantizeMode_t mode =
compute_scale ? CNNL_QUANTIZE_POSITION_SCALE : CNNL_QUANTIZE_POSITION;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeParam(
handle, mode, input_desc, input, bitwidth, workspace_ptr, workspace_size,
position, scale, nullptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeV2(handle, mode, input_desc, input,
position, scale, nullptr,
output_desc, output));
}
/* static */ void MLUCnnl::Range(const ExecutionContext& ctx, const void* start,
const void* end, const void* step,
const cnnlDataType_t output_dtype,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlArange(handle, start, end, step, output_dtype, output));
}
/* static */ void MLUCnnl::Round(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlRound(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::SparseSoftmaxXentWithLogits(
const ExecutionContext& ctx, cnnlSoftmaxMode_t mode,
const cnnlTensorDescriptor_t x_desc, const void* input,
const cnnlTensorDescriptor_t label_desc, const void* label,
const cnnlTensorDescriptor_t y_desc, void* output,
const cnnlTensorDescriptor_t diff_y_desc, void* back_out) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSparseSoftmaxCrossEntropyWithLogits(
handle, mode, x_desc, input, label_desc, label, y_desc, output,
diff_y_desc, back_out));
}
/* static */ void MLUCnnl::Cumsum(const ExecutionContext& ctx, const int axis,
const bool exclusive, const bool reverse,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t ouput_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
// NAN propagation mode: Only support CNNL_NOT_PROPAGATE_NAN now.
cnnlNanPropagation_t mode = CNNL_NOT_PROPAGATE_NAN;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCumsum(handle, input_desc, input, axis,
exclusive, reverse, mode, ouput_desc,
output));
}
/* static */ void MLUCnnl::BroadcastTo(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlExpand(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::AssignAdd(const ExecutionContext& ctx,
const void* alpha, const void* beta,
const cnnlTensorDescriptor_t update_desc,
const void* update,
const cnnlTensorDescriptor_t param_desc,
void* param) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlAssignAdd(
handle, alpha, update_desc, update, nullptr, 0, beta, param_desc, param));
}
/* static */ void MLUCnnl::AssignSub(const ExecutionContext& ctx,
const void* alpha, const void* beta,
const cnnlTensorDescriptor_t update_desc,
const void* update,
const cnnlTensorDescriptor_t param_desc,
void* param) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlAssignSub(
handle, alpha, update_desc, update, nullptr, 0, beta, param_desc, param));
}
/* static */ void MLUCnnl::Assign(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t update_desc,
const void* update,
const cnnlTensorDescriptor_t param_desc,
void* param) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlCopy(handle, update_desc, update, param_desc, param));
}
/* static */ void MLUCnnl::SGD(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t grad_desc,
const void* grad, const void* lr,
const cnnlTensorDescriptor_t var_desc,
void* var) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGradientDescent(handle, grad_desc, grad, lr, var_desc, var));
}
/* static */ void MLUCnnl::ApplyAdaGrad(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t grad_desc,
const void* grad, const cnnlTensorDescriptor_t accum_desc, void* accum,
const cnnlTensorDescriptor_t var_desc, void* var, const void* lr,
const bool update_slots) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlApplyAdaGrad(handle, grad_desc, grad,
accum_desc, accum, var_desc, var,
lr, update_slots));
}
/* static */ void MLUCnnl::ApplyRMSProp(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t grad_desc,
const void* grad, const void* lr, const void* rho, const void* momentum,
const void* epsilon, const cnnlTensorDescriptor_t var_desc, void* var,
const cnnlTensorDescriptor_t ms_desc, void* ms,
const cnnlTensorDescriptor_t mom_desc, void* mom) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlRMSProp(handle, lr, rho, epsilon, momentum,
grad_desc, grad, var_desc, var,
ms_desc, ms, mom_desc, mom));
}
/* static */ void MLUCnnl::ApplyCenterRMSProp(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t grad_desc,
const void* grad, const void* lr, const void* rho, const void* momentum,
const void* epsilon, const cnnlTensorDescriptor_t var_desc, void* var,
const cnnlTensorDescriptor_t mg_desc, void* mg,
const cnnlTensorDescriptor_t ms_desc, void* ms,
const cnnlTensorDescriptor_t mom_desc, void* mom) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlApplyCenterRMSProp(
handle, var_desc, var, mg_desc, mg, ms_desc, ms, mom_desc, mom, grad_desc,
grad, lr, rho, momentum, epsilon));
}
/* static */ void MLUCnnl::ApplyAdam(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t grad_desc,
const void* grad, const void* lr, const void* beta1, const void* beta2,
const void* beta1_power, const void* beta2_power, const void* epsilon,
const bool use_nesterov, const cnnlTensorDescriptor_t var_desc, void* var,
const cnnlTensorDescriptor_t m_desc, void* m,
const cnnlTensorDescriptor_t v_desc, void* v) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlApplyAdam(
handle, grad_desc, var, grad_desc, m, grad_desc, v, grad_desc, grad, lr,
beta1, beta2, beta1_power, beta2_power, epsilon, use_nesterov));
}
/* static */ void MLUCnnl::ApplyAdaMax(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t grad_desc,
const cnnlTensorDescriptor_t var_desc, void* var,
const cnnlTensorDescriptor_t m_desc, void* m,
const cnnlTensorDescriptor_t v_desc, void* v, const void* diff,
const void* lr, const void* beta1, const void* beta2,
const void* beta1_power, const void* epsilon) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlApplyAdaMax(handle, var_desc, var, m_desc, m, v_desc, v, grad_desc,
diff, lr, beta1, beta2, beta1_power, epsilon));
}
/* static */ void MLUCnnl::ApplyMomentum(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t grad_desc,
const void* grad,
const bool use_nesterov,
const void* lr, const void* momentum,
void* var, void* accum) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlMomentum(handle, grad_desc, var, grad_desc,
accum, grad_desc, grad, lr, momentum,
use_nesterov));
}
/* static */ void MLUCnnl::ApplyKerasMomentum(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t grad_desc,
const void* grad, const bool use_nesterov, const void* lr,
const void* momentum, void* var, void* accum) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlKerasMomentum(handle, grad_desc, var, grad_desc, accum, grad_desc,
grad, lr, momentum, use_nesterov));
}
/* static */ void MLUCnnl::ApplyAdadelta(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t grad_desc,
const void* diff, const void* lr,
const void* rho, const void* epsilon,
void* var, void* accum,
void* accum_update) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlApplyAdadelta(handle, grad_desc, var, grad_desc, accum, grad_desc,
accum_update, grad_desc, diff, lr, rho, epsilon));
}
/* static */ void MLUCnnl::Scale(
const ExecutionContext& ctx, const int axis,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t alpha_desc, const void* alpha,
const cnnlTensorDescriptor_t beta_desc, const void* beta,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlScale(handle, axis, input_desc, input,
alpha_desc, alpha, beta_desc, beta,
output_desc, output));
}
/* static */ void MLUCnnl::AddN(const ExecutionContext& ctx, uint32_t input_num,
const cnnlTensorDescriptor_t inputs_desc[],
const void* inputs[],
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlAddN(handle, inputs_desc, inputs, input_num, output_desc, output));
}
/* static */ void MLUCnnl::Log(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlLogBase_t log_base = CNNL_LOG_E;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlLog_v2(handle, prefer, log_base, input_desc,
input, output_desc, output));
}
/* static */ void MLUCnnl::Matmul(
const ExecutionContext& ctx, const bool transpose_a, const bool transpose_b,
const cnnlTensorDescriptor_t in0_desc, const void* in0,
const cnnlTensorDescriptor_t in1_desc, const void* in1,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
float alpha = 1.0f;
float beta = 0.0f;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlMatMul(handle, transpose_a, transpose_b,
reinterpret_cast<void*>(&alpha), in0_desc, in0, in1_desc, in1,
reinterpret_cast<void*>(&beta), output_desc, output));
}
/* static */ void MLUCnnl::BatchMatmul(
const ExecutionContext& ctx, const bool transpose_a, const bool transpose_b,
const cnnlTensorDescriptor_t in0_desc, const void* in0,
const cnnlTensorDescriptor_t in1_desc, const void* in1,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetBatchMatMulBCastWorkspaceSize(
handle, in0_desc, in1_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulBCast(
handle, transpose_a, transpose_b, in0_desc, in0, in1_desc, in1,
workspace_ptr, workspace_size, output_desc, output));
}
/* static */ void MLUCnnl::OpTensor(
const ExecutionContext& ctx, const cnnlOpTensorDescriptor_t op_tensor_desc,
const cnnlTensorDescriptor_t a_desc, const void* a,
const cnnlTensorDescriptor_t b_desc, const void* b,
const cnnlTensorDescriptor_t output_desc, void* output,
const cnnlDataType_t dtype) {
static const int alpha1_int = 1, alpha2_int = 1, beta_int = 0;
static const float alpha1_float = 1.f, alpha2_float = 1.f, beta_float = 0.f;
const void* alpha1_ptr = static_cast<const void*>(&alpha1_float);
const void* alpha2_ptr = static_cast<const void*>(&alpha2_float);
const void* beta_ptr = static_cast<const void*>(&beta_float);
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
bool is_dt_float = (dtype == CNNL_DTYPE_FLOAT || dtype == CNNL_DTYPE_HALF);
// if datatype is not float, we set alpha and beta to be int
if (!is_dt_float) {
alpha1_ptr = static_cast<const void*>(&alpha1_int);
alpha2_ptr = static_cast<const void*>(&alpha2_int);
beta_ptr = static_cast<const void*>(&beta_int);
}
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetOpTensorWorkspaceSize_v2(
handle, op_tensor_desc, alpha1_ptr, a_desc, a, alpha2_ptr, b_desc, b,
beta_ptr, output_desc, output, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlOpTensor(
handle, op_tensor_desc, alpha1_ptr, a_desc, a, alpha2_ptr, b_desc, b,
workspace_ptr, workspace_size, beta_ptr, output_desc, output));
}
/* static */ void MLUCnnl::BiasAddGrad(
const ExecutionContext& ctx, const int axis,
const cnnlTensorDescriptor_t out_backprop_desc, const void* out_backprop,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBiasAddBackward(
handle, out_backprop_desc, out_backprop, axis, output_desc, output));
}
/* static */ void MLUCnnl::RandomUniform(
const ExecutionContext& ctx, const int num, const cnnlDataType_t data_type,
const cnnlRandGenerator_t mlu_generator, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlRandGenerateUniform(
handle, mlu_generator, data_type, nullptr, num, 0, 1, output));
}
/* static */ void MLUCnnl::TopK(
const ExecutionContext& ctx, const int k, const int dim, const bool largest,
const bool sorted, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t values_output_desc,
void* values_out, const cnnlTensorDescriptor_t indices_output_desc,
void* indices_out) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlTopKTensor(
handle, input_desc, input, k, dim, largest, sorted, values_output_desc,
values_out, indices_output_desc, indices_out));
}
/* static */ void MLUCnnl::StridedSlice(
const ExecutionContext& ctx, const int begin[], const int end[],
const int strides[], const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlStridedSlice(
handle, input_desc, input, begin, end, strides, output_desc, output));
}
/* static */ void MLUCnnl::Split(const ExecutionContext& ctx, int split_num,
int axis,
const cnnlTensorDescriptor_t input_desc,
const void* input_ptr,
const cnnlTensorDescriptor_t output_descs[],
void* output_ptrs[]) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetSplitWorkspaceSize(handle, split_num, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSplit(handle, split_num, axis, input_desc,
input_ptr, workspace_ptr, workspace_size,
output_descs, output_ptrs));
}
/* static */ void MLUCnnl::GatherFunctor(
const ExecutionContext& ctx, const int axis, const int batch_dims,
const cnnlTensorDescriptor_t params_desc, const void* params,
const cnnlTensorDescriptor_t indices_desc, const void* indices,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlBatchGatherV2(handle, axis, batch_dims, params_desc, params,
indices_desc, indices, output_desc, output));
}
/* static */ void MLUCnnl::ScatterFunctor(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t params_desc,
const void* params, const cnnlTensorDescriptor_t updates_desc,
const void* updates, const cnnlTensorDescriptor_t indices_desc,
const void* indices, const cnnlScatterRefMode_t mode) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlScatterRef(handle, params_desc, params,
indices_desc, indices, updates_desc,
updates, 0, mode));
}
/* static */ void MLUCnnl::StridedSliceGrad(
const ExecutionContext& ctx, const int begin[], const int end[],
const int strides[], const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlStridedSliceBackward(
handle, begin, end, strides, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Logic(
const ExecutionContext& ctx, const MLULogicMethod log_method,
const cnnlTensorDescriptor_t input1_desc, const void* input1,
const cnnlTensorDescriptor_t input2_desc, const void* input2,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetLogicOpWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlLogicOp(
handle, cnnlLogicOp_t(log_method), input1_desc, input1, input2_desc,
input2, workspace_ptr, workspace_size, output_desc, output));
}
/* static */ void MLUCnnl::Select(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t then_desc,
const void* p_then, const cnnlTensorDescriptor_t else_desc,
const void* p_else, const cnnlTensorDescriptor_t output_desc, void* output,
const bool* condition, const int condition_size) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSelect(handle, then_desc, p_then, else_desc,
p_else, output_desc, output, condition,
condition_size));
}
/*static */ void MLUCnnl::GatherNd(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t params_desc,
const void* params,
const cnnlTensorDescriptor_t indices_desc,
const void* indices,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGatherNd(
handle, params_desc, params, indices_desc, indices, output_desc, output));
}
/* static */ void MLUCnnl::BatchToSpace(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t output_desc, void* output,
const cnnlSpaceBatchParam_t param) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetBatch2spaceWorkspaceSize(
handle, input_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatch2space(handle, input_desc, input,
output_desc, output, param,
workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::BatchToSpaceNd(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
const void* input, cnnlSpaceBatchNdDescriptor_t param,
void* extra_device_input, size_t extra_input_size,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlBatch2spaceNd_v2(handle, input_desc, input, output_desc, output,
param, extra_device_input, extra_input_size));
}
/* static */ void MLUCnnl::SoftmaxForward(
const ExecutionContext& ctx, cnnlSoftmaxAlgorithm_t algorithm,
cnnlSoftmaxMode_t mode, const void* alpha,
const cnnlTensorDescriptor_t input_desc, const void* input,
const void* beta, const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSoftmaxForward(handle, algorithm, mode, alpha,
input_desc, input, beta,
output_desc, output));
}
/* static */ void MLUCnnl::Softplus(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t features_desc,
const void* features,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
const int beta = 1;
const int threshold = 20;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSoftplusForward(
handle, features_desc, features, output_desc, output, beta, threshold));
}
/* static */ void MLUCnnl::SoftplusGrad(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t gradients_desc,
const void* gradients, const cnnlTensorDescriptor_t features_desc,
const void* features, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
int beta = 1;
int threshold = 20;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSoftplusBackward(handle, features_desc, features, gradients_desc,
gradients, output_desc, output, beta, threshold));
}
/* static */ void MLUCnnl::PoolingForward(
const ExecutionContext& ctx, cnnlPoolingMode_t pool_mode,
const std::vector<int64_t>& output_shape,
const cnnlPoolingDescriptor_t pooling_desc, const void* alpha,
const cnnlTensorDescriptor_t input_desc, const void* input,
const void* beta, const void* extra_input_ptr,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetPoolingWorkspaceSize(
handle, pool_mode, output_shape[2], output_shape[1], &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlPoolingForward_v2(
handle, pooling_desc, alpha, input_desc, input, beta, extra_input_ptr,
output_desc, output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::Pool3D(
const ExecutionContext& ctx, cnnlPoolingMode_t pool_mode,
const std::vector<int64_t>& output_shape,
const cnnlPoolingDescriptor_t pooling_desc, const void* alpha,
const cnnlTensorDescriptor_t input_desc, const void* input,
const void* beta, const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetPoolingWorkspaceSize(
handle, pool_mode, output_shape[2], output_shape[1], &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlPoolingForward(handle, pooling_desc, alpha, input_desc, input, beta,
output_desc, output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::RsqrtGrad(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t data_desc,
const void* y, const void* diff_y,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlRsqrtBackward(handle, data_desc, y, diff_y, output));
}
/* static */ void MLUCnnl::SqrtGrad(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t data_desc,
const void* y, const void* diff_y,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSqrtBackward(handle, data_desc, y, diff_y, output));
}
/* static */ void MLUCnnl::UnsortedSegmentSum(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t data_desc,
const void* data, const cnnlTensorDescriptor_t ids_desc,
const int* segment_ids, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetUnsortedSegmentSumWorkspaceSize(
handle, data_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlUnsortedSegmentSum(
handle, data_desc, data, ids_desc, segment_ids, workspace_ptr,
workspace_size, output_desc, output));
}
/* static */ void MLUCnnl::Pad(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input, const void* paddings,
const void* padding_value,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlPad(handle, input_desc, input, paddings,
padding_value, output_desc, output));
}
/* static */ void MLUCnnl::OneHot(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t desc_indices,
const void* indices, const int depth,
const void* on_value, const void* off_value,
const int axis,
cnnlDataType_t output_data_type,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlOneHot(handle, desc_indices, indices, depth,
on_value, off_value, axis,
output_data_type, output));
}
/* static */ void MLUCnnl::ConvolutionForward(
const ExecutionContext& ctx, cnnlConvolutionDescriptor_t conv_desc,
const void* alpha, const void* beta, const cnnlTensorDescriptor_t bias_desc,
const void* bias_ptr, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t filtet_desc,
const void* filter, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
// cnnl: select best algorithm for convolution compution.
cnnlConvolutionForwardAlgo_t algo;
cnnlConvolutionFwdPreference_t preference = CNNL_CONVOLUTION_FWD_FASTEST;
cnnlGetConvolutionForwardAlgorithm(handle, conv_desc, input_desc, filtet_desc,
output_desc, preference, &algo);
// get workspace size
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionForwardWorkspaceSize(
handle, input_desc, filtet_desc, output_desc, bias_desc, conv_desc, algo,
&workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlConvolutionForward(
handle, conv_desc, algo, alpha, input_desc, input, filtet_desc, filter,
bias_desc, bias_ptr, workspace_ptr, workspace_size, beta, output_desc,
output));
}
/* static */ void MLUCnnl::Tile(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlTile(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::SoftmaxCrossEntropyWithLogits(
const ExecutionContext& ctx, cnnlSoftmaxMode_t mode,
cnnlComputationPreference_t prefer, const cnnlTensorDescriptor_t input_desc,
const void* logits_in, const cnnlTensorDescriptor_t label_desc,
const void* labels_in, const cnnlTensorDescriptor_t loss_out_desc,
void* loss_out, const cnnlTensorDescriptor_t back_out_desc,
void* back_out) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSoftmaxCrossEntropyWithLogits_v2(
handle, mode, prefer, input_desc, logits_in, label_desc, labels_in,
loss_out_desc, loss_out, back_out_desc, back_out));
}
/* static */ void MLUCnnl::Reduce(
const ExecutionContext& ctx, const bool need_workspace,
const cnnlReduceDescriptor_t reduction_desc, const void* alpha,
const cnnlTensorDescriptor_t input_desc, const void* input,
const size_t indices_size, void* indices, const void* beta,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
void* workspace_ptr = nullptr;
Tensor workspace;
if (need_workspace) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetReduceOpWorkspaceSize(
handle, input_desc, output_desc, reduction_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
workspace_ptr = workspace.mutable_data(ctx.GetPlace());
}
PADDLE_ENFORCE_MLU_SUCCESS(cnnlReduce(
handle, reduction_desc, workspace_ptr, workspace_size, alpha, input_desc,
input, indices_size, indices, beta, output_desc, output));
}
/* static */ void MLUCnnl::FloorDiv(
const ExecutionContext& ctx, cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input1_desc, const void* input1,
const cnnlTensorDescriptor_t input2_desc, const void* input2,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetFloorDivWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlFloorDiv_v2(handle, prefer, input1_desc, input1, input2_desc, input2,
output_desc, output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::FloorMod(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input1_desc,
const void* input1,
const cnnlTensorDescriptor_t input2_desc,
const void* input2,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetFloorModWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlFloorMod(handle, input1_desc, input1, input2_desc, input2,
output_desc, output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::Maximum(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input1_desc,
const void* input1,
const cnnlTensorDescriptor_t input2_desc,
const void* input2,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetMaximumWorkspaceSize(handle, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlMaximum(handle, input1_desc, input1, input2_desc, input2, output_desc,
output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::Minimum(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input1_desc,
const void* input1,
const cnnlTensorDescriptor_t input2_desc,
const void* input2,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetMinimumWorkspaceSize(handle, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlMinimum(handle, input1_desc, input1, input2_desc, input2, output_desc,
output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::PowR(
const ExecutionContext& ctx, cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input1_desc, const void* input1,
const cnnlTensorDescriptor_t input2_desc, const void* input2,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetPowRWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlPowR_v2(handle, prefer, input1_desc, input1,
input2_desc, input2, workspace_ptr,
workspace_size, output_desc, output));
}
/* static */ void MLUCnnl::DivNoNan(
const ExecutionContext& ctx, cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input1_desc, const void* input1,
const cnnlTensorDescriptor_t input2_desc, const void* input2,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetDivNoNanWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlDivNoNan_v2(handle, prefer, input1_desc, input1, input2_desc, input2,
workspace_ptr, workspace_size, output_desc, output));
}
/* static */ void MLUCnnl::SquaredDifference(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input1_desc,
const void* input1, const cnnlTensorDescriptor_t input2_desc,
const void* input2, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetSquaredDifferenceWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSquaredDifference(
handle, input1_desc, input1, input2_desc, input2, output_desc, output,
workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::L2Loss(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlL2Loss(handle, input_desc, input, output));
}
/* static */ void MLUCnnl::Abs(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlAbs(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Neg(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlNegTensor(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Floor(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlFloor(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Ceil(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlCeil(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::IsNan(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlIsNan(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Square(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSquare(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Sqrt(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSqrt_v2(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Rsqrt(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlRsqrt_v2(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Cos(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlCos_v2(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Sin(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSin_v2(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::TrigonForward(
const ExecutionContext& ctx, const cnnlTrigonDescriptor_t trigon_desc,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlTrigonForward(handle, trigon_desc, input_desc,
input, output_desc, output));
}
/* static */ void MLUCnnl::Exp(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlExp_v2(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Sign(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSign(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::IsFinite(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlIsFinite(handle, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::IsNanInf(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
// TODO(CTR-3849): output type should be void*, but now bool*.
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlNanInf(handle, input_desc, input, reinterpret_cast<bool*>(output)));
}
/* static */ void MLUCnnl::Erf(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlErf_v2(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Log1p(const ExecutionContext& ctx,
cnnlComputationPreference_t prefer,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlLog1p(handle, prefer, input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::LogicalNot(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlLogicOp(handle, CNNL_LOGIC_OP_NOT, input_desc,
input, input_desc, input, nullptr, 0,
output_desc, output));
}
/* static */ void MLUCnnl::DynamicStitch(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t* indices_desc,
const int** indices, const cnnlTensorDescriptor_t* data_desc,
const void** data, const int size, int* indices_dims,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetDynamicStitchWorkspaceSize(handle, size, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDynamicStitch(
handle, indices_desc, indices, data_desc, data, size, indices_dims,
workspace_ptr, workspace_size, output_desc, output));
}
/* static */ void MLUCnnl::CropAndResize(
const ExecutionContext& ctx, const std::string method_name,
const float extrapolation_value, const cnnlTensorDescriptor_t image_desc,
const void* image, const cnnlTensorDescriptor_t boxes_desc,
const void* boxes, const cnnlTensorDescriptor_t box_index_desc,
const void* box_index, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlCropAndResizeMode_t mode = CNNL_CROP_AND_RESIZE_BILINEAR;
if (method_name == "nearest") {
mode = CNNL_CROP_AND_RESIZE_NEAREST;
}
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCropAndResize(
handle, image_desc, image, boxes_desc, boxes, box_index_desc, box_index,
mode, extrapolation_value, output_desc, output));
}
/* static */ void MLUCnnl::CropAndResizeBackwardImage(
const ExecutionContext& ctx, const std::string method_name,
const cnnlTensorDescriptor_t grads_desc, const void* grads,
const cnnlTensorDescriptor_t boxes_desc, const void* boxes,
const cnnlTensorDescriptor_t box_idx_desc, const void* box_idx,
const cnnlTensorDescriptor_t grads_image_desc, void* grads_image) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlCropAndResizeMode_t mode = CNNL_CROP_AND_RESIZE_BILINEAR;
if (method_name == "nearest") {
mode = CNNL_CROP_AND_RESIZE_NEAREST;
}
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCropAndResizeBackwardImage(
handle, grads_desc, grads, boxes_desc, boxes, box_idx_desc, box_idx, mode,
grads_image_desc, grads_image));
}
/* static */ void MLUCnnl::CropAndResizeBackwardBoxes(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t image_desc,
const void* image, const cnnlTensorDescriptor_t boxes_desc,
const void* boxes, const cnnlTensorDescriptor_t box_idx_desc,
const void* box_idx, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlCropAndResizeMode_t mode = CNNL_CROP_AND_RESIZE_BILINEAR;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCropAndResizeBackwardBoxes(
handle, input_desc, input, image_desc, image, boxes_desc, boxes,
box_idx_desc, box_idx, output_desc, output, mode));
}
/* static */ void MLUCnnl::Interp(
const ExecutionContext& ctx, const cnnlInterpMode_t mode,
const bool align_corners, const bool half_pixel_centers,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlInterp_v2(handle, align_corners, half_pixel_centers, mode, NULL, true,
input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::InterpBackward(
const ExecutionContext& ctx, const cnnlInterpBackwardMode_t mode,
const bool align_corners, const bool half_pixel_centers,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlInterpBackward(handle, align_corners, half_pixel_centers, mode,
input_desc, input, output_desc, output));
}
/* static */ void MLUCnnl::Cast(const ExecutionContext& ctx,
cnnlCastDataType_t cast_type,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCastDataType(handle, input_desc, input,
cast_type, output_desc, output));
}
/* static */ void MLUCnnl::PoolingBackward(
const ExecutionContext& ctx, const cnnlPoolingDescriptor_t pooling_desc,
const void* alpha, const cnnlTensorDescriptor_t y_desc, const void* y,
const cnnlTensorDescriptor_t diff_y_desc, const void* diff_y,
const cnnlTensorDescriptor_t x_desc, const void* x, const void* beta,
const cnnlTensorDescriptor_t diff_x_desc, void* diff_x) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlPoolingBackward(
handle, const_cast<cnnlPoolingDescriptor_t>(pooling_desc), alpha, y_desc,
y, diff_y_desc, diff_y, x_desc, x, beta, diff_x_desc, diff_x));
}
/* static */ void MLUCnnl::NonMaxSuppression(
const ExecutionContext& ctx, const cnnlNmsDescriptor_t nms_desc,
const cnnlTensorDescriptor_t boxes_desc, const void* boxes,
const cnnlTensorDescriptor_t confidence_desc, const void* confidence,
const cnnlTensorDescriptor_t output_desc, void* output, void* output_size) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetNmsWorkspaceSize_v2(handle, confidence_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlNms_v2(
handle, nms_desc, boxes_desc, boxes, confidence_desc, confidence,
workspace_ptr, workspace_size, output_desc, output, output_size));
}
/* static */ void MLUCnnl::PoolingIndex(
const ExecutionContext& ctx, const cnnlPoolingDescriptor_t pooling_desc,
const cnnlTensorDescriptor_t x_desc, const void* x,
const cnnlTensorDescriptor_t y_desc, void* y) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlPoolingIndex(
handle, const_cast<cnnlPoolingDescriptor_t>(pooling_desc), x_desc, x,
y_desc, y));
}
/* static */ void MLUCnnl::SpaceToBatch(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t output_desc, void* output,
const int64_t block_shape[]) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetSpace2batchWorkspaceSize(
handle, input_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
cnnlSpaceBatchParam_t param = {static_cast<uint32_t>(block_shape[0]),
static_cast<uint32_t>(block_shape[1])};
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSpace2batch(handle, input_desc, input,
output_desc, output, param,
workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::SpaceToBatchNd(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t input_desc,
const void* input, cnnlSpaceBatchNdDescriptor_t param,
void* extra_device_input, size_t extra_host_input,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSpace2batchNd_v2(handle, input_desc, input, output_desc, output,
param, extra_device_input, extra_host_input));
}
/* static */ void MLUCnnl::FusedBatchNorm(
const ExecutionContext& ctx, const bool is_training,
const cnnlTensorDescriptor_t x_desc, const void* x,
const cnnlTensorDescriptor_t scale_desc, const void* scale,
const void* offset, const void* running_mean_input,
const void* running_variance_input, float epsilon, float momentum,
const cnnlTensorDescriptor_t output_desc, void* output,
void* running_mean_output, void* running_var_output,
void* saved_batch_mean_output, void* saved_batch_var_output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
if (is_training) {
/*
* If in Paddle, running_mean_output = momentum * runnning_mean_input +
* (1 - momentum) * batch_mean. However, In CNNL,
* running_mean_output = (1 - momentum) * running_mean_input +
* momentum * batch_mean. So we pass (1.0 - momentum) to momentum param.
*/
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchNormForwardTraining(
handle, NULL, NULL, x_desc, x, scale_desc, scale, offset,
running_mean_output, running_var_output, epsilon, 1.0 - momentum,
output_desc, output, saved_batch_mean_output, saved_batch_var_output));
} else {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchNormForwardInference(
handle, NULL, NULL, x_desc, x, scale_desc, scale, offset,
running_mean_input, running_variance_input, epsilon, output_desc,
output));
}
}
/* static */ void MLUCnnl::FusedBatchNormGrad(
const ExecutionContext& ctx, const bool is_training,
const cnnlTensorDescriptor_t y_backprop_desc, const void* y_backprop,
const cnnlTensorDescriptor_t x_desc, const void* x,
const cnnlTensorDescriptor_t scale_desc, const void* scale,
const void* saved_mean, const void* saved_var, float epsilon,
const cnnlTensorDescriptor_t x_backprop_desc, void* x_backprop,
void* scale_backprop, void* offset_backprop) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
if (is_training) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchNormBackward(
handle, NULL, NULL, NULL, NULL, x_desc, x, y_backprop_desc, y_backprop,
scale_desc, scale, saved_mean, saved_var, epsilon, x_backprop_desc,
x_backprop, scale_backprop, offset_backprop));
} else {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlFrozenBatchNormBackward(
handle, x_desc, x, y_backprop_desc, y_backprop, scale_desc, scale,
saved_mean, saved_var, epsilon, x_backprop_desc, x_backprop,
scale_backprop, offset_backprop));
}
}
/* static */ void MLUCnnl::QuantizeParam(
const ExecutionContext& ctx, const cnnlQuantizeMode_t mode,
const int bitwidth, const cnnlTensorDescriptor_t input_desc,
const void* input, void* position, void* scale, void* offset) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetQuantizeParamWorkspaceSize(handle, input_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeParam(
handle, mode, input_desc, input, bitwidth, workspace_ptr, workspace_size,
position, scale, offset));
}
/* static */ void MLUCnnl::Conv2D(
const ExecutionContext& ctx, const cnnlConvolutionDescriptor_t conv_desc,
const cnnlDataType_t tensor_dtype, const cnnlDataType_t dt_onchip,
const void* input_position, const void* input_scale,
const void* input_offset, const void* filter_position,
const void* filter_scale, const void* filter_offset,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t filter_desc, const void* filter,
const cnnlTensorDescriptor_t bias_desc, const void* bias,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(input_desc, dt_onchip));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(filter_desc, dt_onchip));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(output_desc, tensor_dtype));
cnnlConvolutionForwardAlgo_t algo;
const cnnlConvolutionFwdPreference_t preference =
CNNL_CONVOLUTION_FWD_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionForwardAlgorithm(
handle, conv_desc, input_desc, filter_desc, output_desc, preference,
&algo));
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionForwardWorkspaceSize(
handle, input_desc, filter_desc, output_desc, bias_desc, conv_desc, algo,
&workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeConvolutionForward(
handle, conv_desc, algo, nullptr /*alpha*/, input_desc, input,
input_position, input_scale, input_offset, filter_desc, filter,
filter_position, filter_scale, filter_offset, bias_desc, bias,
workspace_ptr, workspace_size, nullptr /*beta*/, output_desc, output));
}
/* static */ void MLUCnnl::FusedConvBNQuantify(
const ExecutionContext& ctx, cnnlConvolutionDescriptor_t conv_desc,
const void* epsilon_ptr, const int fused_ops_number,
const cnnlDataType_t tensor_dtype, const int input_position,
const float input_scale, const int filter_position,
const float filter_scale, const cnnlTensorDescriptor_t scale_desc,
const void* scale_ptr, const cnnlTensorDescriptor_t offset_desc,
const void* offset_ptr, const cnnlTensorDescriptor_t mean_desc,
const void* mean_ptr, const cnnlTensorDescriptor_t variance_desc,
const void* variance_ptr, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t filter_desc,
const void* filter, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(input_desc, CNNL_DTYPE_INT16));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(filter_desc, CNNL_DTYPE_INT16));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(output_desc, tensor_dtype));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptorPositionAndScale(
input_desc, input_position, input_scale));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptorPositionAndScale(
filter_desc, filter_position, filter_scale));
cnnlFusedOpsPlan_t fusion_plan = nullptr;
cnnlActivationDescriptor_t active_desc = nullptr;
cnnlFusedOpsConstParamPack_t cparam_pack = nullptr;
cnnlFusedOpsVariantParamPack_t vparam_pack = nullptr;
cnnlConvolutionForwardAlgo_t algo;
cnnlFusedOps_t fusion_type = CNNL_CONV_SCALE_BN_ACTIVATION;
cnnlConvolutionCastMode_t cast_mode = CNNL_OFFLINE_SYMMETRIC_QUANTIZE;
cnnlConvolutionFwdPreference_t preference = CNNL_CONVOLUTION_FWD_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionForwardAlgorithm(
handle, conv_desc, input_desc, filter_desc, output_desc, preference,
&algo));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateFusedOpsPlan(&fusion_plan, fusion_type));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlCreateFusedOpsConstParamPack(&cparam_pack, fusion_type));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlCreateFusedOpsVariantParamPack(&vparam_pack, fusion_type));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_XDESC, input_desc));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetFusedOpsVariantParamPackAttribute(vparam_pack, CNNL_PTR_X, input));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_WDESC, filter_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_W, filter));
if (fused_ops_number > 1) {
cnnlCreateActivationDescriptor(&active_desc);
cnnlNanPropagation_t nan_opt = CNNL_NOT_PROPAGATE_NAN;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetActivationDescriptor(
active_desc, CNNL_ACTIVATION_RELU, nan_opt, 0.0));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_ACTIVATION_DESC, active_desc));
}
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_BN_WEIGHT_BIAS_MEAN_VAR_DESC, scale_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_BN_WEIGHT, scale_ptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_BN_WEIGHT_BIAS_MEAN_VAR_DESC, offset_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_BN_BIAS, offset_ptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_BN_WEIGHT_BIAS_MEAN_VAR_DESC, mean_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_BN_MEAN, mean_ptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_BN_WEIGHT_BIAS_MEAN_VAR_DESC, variance_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_BN_VAR, variance_ptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_CONV_DESC, conv_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_SCALAR_CONV_FWD_ALGO, &algo));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_SCALAR_CONV_FWD_CAST_MODE, &cast_mode));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_SCALAR_BN_EPSILON, epsilon_ptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsConstParamPackAttribute(
cparam_pack, CNNL_YDESC, output_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_Y, output));
// get workspace size
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlMakeFusedOpsPlan(handle, fusion_plan, cparam_pack, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
if (workspace_size > 0) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_PTR_WORKSPACE, workspace_ptr));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetFusedOpsVariantParamPackAttribute(
vparam_pack, CNNL_SCALAR_WORKSPACE_SIZE, &workspace_size));
}
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlFusedOpsExecute(handle, fusion_plan, vparam_pack));
if (active_desc) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyActivationDescriptor(active_desc));
}
if (cparam_pack) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyFusedOpsConstParamPack(cparam_pack));
}
if (vparam_pack) {
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlDestroyFusedOpsVariantParamPack(vparam_pack));
}
if (fusion_plan) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyFusedOpsPlan(fusion_plan));
}
}
/* static */ void MLUCnnl::ConvBackpropInput(
const ExecutionContext& ctx, const cnnlConvolutionDescriptor_t conv_desc,
const cnnlTensorDescriptor_t filter_desc, const void* filter,
const cnnlTensorDescriptor_t out_backprop_desc, const void* out_backprop,
const cnnlTensorDescriptor_t in_backprop_desc, void* in_backprop) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlConvolutionBwdDataAlgo_t algo;
const cnnlConvolutionBwdDataPreference_t preference =
CNNL_CONVOLUTION_BWD_DATA_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardDataAlgorithm(
handle, filter_desc, out_backprop_desc, conv_desc, in_backprop_desc,
preference, &algo));
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardDataWorkspaceSize(
handle, filter_desc, out_backprop_desc, conv_desc, in_backprop_desc, algo,
&workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlConvolutionBackwardData(
handle, nullptr /*alpha*/, filter_desc, filter, out_backprop_desc,
out_backprop, conv_desc, algo, workspace_ptr, workspace_size,
nullptr /*beta*/, in_backprop_desc, in_backprop));
}
/* static */ void MLUCnnl::QuantizeConvBackpropInput(
const ExecutionContext& ctx, const cnnlConvolutionDescriptor_t conv_desc,
const cnnlDataType_t tensor_dtype, const cnnlDataType_t dt_onchip,
const void* filter_position, const void* filter_scale,
const void* filter_offset, const void* out_backprop_position,
const void* out_backprop_scale, const void* out_backprop_offset,
const cnnlTensorDescriptor_t filter_desc, const void* filter,
const cnnlTensorDescriptor_t out_backprop_desc, const void* out_backprop,
const cnnlTensorDescriptor_t in_backprop_desc, void* in_backprop) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(filter_desc, dt_onchip));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(out_backprop_desc, dt_onchip));
cnnlConvolutionBwdDataAlgo_t algo;
const cnnlConvolutionBwdDataPreference_t preference =
CNNL_CONVOLUTION_BWD_DATA_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardDataAlgorithm(
handle, filter_desc, out_backprop_desc, conv_desc, in_backprop_desc,
preference, &algo));
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardDataWorkspaceSize(
handle, filter_desc, out_backprop_desc, conv_desc, in_backprop_desc, algo,
&workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeConvolutionBackwardData(
handle, nullptr /*alpha*/, filter_desc, filter, filter_position,
filter_scale, filter_offset, out_backprop_desc, out_backprop,
out_backprop_position, out_backprop_scale, out_backprop_offset, conv_desc,
algo, workspace_ptr, workspace_size, nullptr /*beta*/, in_backprop_desc,
in_backprop));
}
/* static */ void MLUCnnl::ConvBackpropFilter(
const ExecutionContext& ctx, const cnnlConvolutionDescriptor_t conv_desc,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t out_backprop_desc, const void* out_backprop,
const cnnlTensorDescriptor_t filter_backprop_desc, void* filter_backprop) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlConvolutionBwdFilterAlgo_t algo;
const cnnlConvolutionBwdFilterPreference_t preference =
CNNL_CONVOLUTION_BWD_FILTER_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardFilterAlgorithm(
handle, conv_desc, input_desc, out_backprop_desc, filter_backprop_desc,
preference, &algo));
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardFilterWorkspaceSize(
handle, input_desc, out_backprop_desc, filter_backprop_desc, conv_desc,
algo, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlConvolutionBackwardFilter(
handle, nullptr /*alpha*/, input_desc, input, out_backprop_desc,
out_backprop, conv_desc, algo, workspace_ptr, workspace_size,
nullptr /*beta*/, filter_backprop_desc, filter_backprop));
}
/* static */ void MLUCnnl::QuantizeConvBackpropFilter(
const ExecutionContext& ctx, const cnnlConvolutionDescriptor_t conv_desc,
const cnnlDataType_t tensor_dtype, const cnnlDataType_t dt_onchip,
const void* input_position, const void* input_scale,
const void* input_offset, const void* out_backprop_position,
const void* out_backprop_scale, const void* out_backprop_offset,
const cnnlTensorDescriptor_t input_desc, const void* input,
const cnnlTensorDescriptor_t out_backprop_desc, const void* out_backprop,
const cnnlTensorDescriptor_t filter_backprop_desc, void* filter_backprop) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(input_desc, dt_onchip));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTensorDescriptorOnchipDataType(out_backprop_desc, dt_onchip));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetTensorDescriptorOnchipDataType(
filter_backprop_desc, tensor_dtype));
cnnlConvolutionBwdFilterAlgo_t algo;
const cnnlConvolutionBwdFilterPreference_t preference =
CNNL_CONVOLUTION_BWD_FILTER_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardFilterAlgorithm(
handle, conv_desc, input_desc, out_backprop_desc, filter_backprop_desc,
preference, &algo));
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetConvolutionBackwardFilterWorkspaceSize(
handle, input_desc, out_backprop_desc, filter_backprop_desc, conv_desc,
algo, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeConvolutionBackwardFilter(
handle, nullptr /*alpha*/, input_desc, input, input_position, input_scale,
input_offset, out_backprop_desc, out_backprop, out_backprop_position,
out_backprop_scale, out_backprop_offset, conv_desc, algo, workspace_ptr,
workspace_size, nullptr /*beta*/, filter_backprop_desc, filter_backprop));
}
/* static */ void MLUCnnl::QuantizeMatMul(
const ExecutionContext& ctx, const bool transpose_a, const bool transpose_b,
const cnnlTensorDescriptor_t a_desc, const void* a, const void* a_position,
const void* a_scale, const void* a_offset,
const cnnlTensorDescriptor_t b_desc, const void* b, const void* b_position,
const void* b_scale, const void* b_offset, const cnnlDataType_t quant_type,
const cnnlDataType_t data_type, const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
// Set onchip data type
cnnlSetTensorDescriptorOnchipDataType(a_desc, quant_type);
cnnlSetTensorDescriptorOnchipDataType(b_desc, quant_type);
cnnlSetTensorDescriptorOnchipDataType(output_desc, data_type);
// Create and set matmul descriptor
cnnlMatMulDescriptor_t matmul_desc;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlMatMulDescCreate(&matmul_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetMatMulDescAttr(
matmul_desc, CNNL_MATMUL_DESC_COMPUTE_TYPE, &data_type, sizeof(int)));
int transpose_a_int = static_cast<int>(transpose_a);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetMatMulDescAttr(
matmul_desc, CNNL_MATMUL_DESC_TRANSA, &(transpose_a_int), sizeof(int)));
int transpose_b_int = static_cast<int>(transpose_b);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetMatMulDescAttr(
matmul_desc, CNNL_MATMUL_DESC_TRANSB, &(transpose_b_int), sizeof(int)));
// Create and get matmul algorithim
cnnlMatMulAlgo_t algo;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlMatMulAlgoCreate(&algo));
const cnnlMatMulPreference_t preference = CNNL_MATMUL_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetQuantizeMatMulAlgorithm(
handle, matmul_desc, a_desc, b_desc, output_desc, preference, &algo));
// Get workspace
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetQuantizeMatMulWorkspaceSize(
handle, matmul_desc, a_desc, b_desc, output_desc, algo, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
// Compute
float alpha = 1.0;
float beta = 0.0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeMatMul(
handle, matmul_desc, reinterpret_cast<void*>(&alpha), a_desc, a,
a_position, a_scale, a_offset, b_desc, b, b_position, b_scale, b_offset,
reinterpret_cast<void*>(&beta), output_desc, output, algo, workspace_ptr,
workspace_size));
// Destroy matmul descriptor and algorithim
PADDLE_ENFORCE_MLU_SUCCESS(cnnlMatMulDescDestroy(matmul_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlMatMulAlgoDestroy(algo));
}
/* static */ void MLUCnnl::QuantizeBatchMatMul(
const ExecutionContext& ctx, const bool adj_x, const bool adj_y,
const cnnlTensorDescriptor_t in0_desc, const void* in0,
const void* in0_position, const void* in0_scale, const void* in0_offset,
const cnnlTensorDescriptor_t in1_desc, const void* in1,
const void* in1_position, const void* in1_scale, const void* in1_offset,
const cnnlDataType_t quant_type, const cnnlDataType_t data_type,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
// Set onchip data type
cnnlSetTensorDescriptorOnchipDataType(in0_desc, quant_type);
cnnlSetTensorDescriptorOnchipDataType(in1_desc, quant_type);
cnnlSetTensorDescriptorOnchipDataType(output_desc, data_type);
// Create and set batch matmul descriptor
cnnlBatchMatMulDescriptor_t bmm_desc;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulDescCreate(&bmm_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetBatchMatMulDescAttr(
bmm_desc, CNNL_BMM_DESC_COMPUTE_TYPE, &data_type, sizeof(int)));
int transpose_a_int = static_cast<int>(adj_x);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetBatchMatMulDescAttr(
bmm_desc, CNNL_BMM_DESC_TRANSA, &(transpose_a_int), sizeof(int)));
int transpose_b_int = static_cast<int>(adj_y);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetBatchMatMulDescAttr(
bmm_desc, CNNL_BMM_DESC_TRANSB, &(transpose_b_int), sizeof(int)));
// Create and get batch matmul algorithim
cnnlBatchMatMulAlgo_t algo;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulAlgoCreate(&algo));
const cnnlBatchMatMulPreference_t preference = CNNL_BMM_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetQuantizeBatchMatMulAlgorithm(
handle, bmm_desc, in0_desc, in1_desc, output_desc, preference, &algo));
// Get workspace
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetQuantizeBatchMatMulWorkspaceSize(
handle, bmm_desc, in0_desc, in1_desc, output_desc, algo,
&workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
// Compute
float alpha = 1.0;
float beta = 0.0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeBatchMatMul(
handle, bmm_desc, reinterpret_cast<void*>(&alpha), in0_desc, in0,
in0_position, in0_scale, in0_offset, in1_desc, in1, in1_position,
in1_scale, in1_offset, reinterpret_cast<void*>(&beta), output_desc,
output, algo, workspace_ptr, workspace_size));
// Destroy matmul descriptor and algorithim
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulDescDestroy(bmm_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulAlgoDestroy(algo));
}
/* static */ void MLUCnnl::QuantizeBatchMatMulBCast(
const ExecutionContext& ctx, const bool adj_x, const bool adj_y,
const cnnlTensorDescriptor_t in0_desc, const void* in0,
const void* in0_position, const void* in0_scale, const void* in0_offset,
const cnnlTensorDescriptor_t in1_desc, const void* in1,
const void* in1_position, const void* in1_scale, const void* in1_offset,
const cnnlDataType_t quant_type, const cnnlDataType_t data_type,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
// Set onchip data type
cnnlSetTensorDescriptorOnchipDataType(in0_desc, quant_type);
cnnlSetTensorDescriptorOnchipDataType(in1_desc, quant_type);
cnnlSetTensorDescriptorOnchipDataType(output_desc, data_type);
// Create and set batch matmul descriptor
cnnlBatchMatMulBCastDescriptor_t bmm_bcast_desc;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulBCastDescCreate(&bmm_bcast_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetBatchMatMulBCastDescAttr(
bmm_bcast_desc, CNNL_BMM_BCAST_DESC_COMPUTE_TYPE, &data_type,
sizeof(int)));
int transpose_a_int = static_cast<int>(adj_x);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetBatchMatMulBCastDescAttr(
bmm_bcast_desc, CNNL_BMM_BCAST_DESC_TRANSA, &(transpose_a_int),
sizeof(int)));
int transpose_b_int = static_cast<int>(adj_y);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlSetBatchMatMulBCastDescAttr(
bmm_bcast_desc, CNNL_BMM_BCAST_DESC_TRANSB, &(transpose_b_int),
sizeof(int)));
// Create and get batch matmul algorithim
cnnlBatchMatMulBCastAlgo_t algo;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulBCastAlgoCreate(&algo));
const cnnlBatchMatMulBCastPreference_t preference = CNNL_BMM_BCAST_FASTEST;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetQuantizeBatchMatMulBCastAlgorithm(
handle, bmm_bcast_desc, in0_desc, in1_desc, output_desc, preference,
&algo));
// Get workspace
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetQuantizeBatchMatMulBCastWorkspaceSize(
handle, bmm_bcast_desc, in0_desc, in1_desc, output_desc, algo,
&workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
// Compute
float alpha = 1.0;
float beta = 0.0;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQuantizeBatchMatMulBCast(
handle, bmm_bcast_desc, reinterpret_cast<void*>(&alpha), in0_desc, in0,
in0_position, in0_scale, in0_offset, in1_desc, in1, in1_position,
in1_scale, in1_offset, reinterpret_cast<void*>(&beta), output_desc,
output, algo, workspace_ptr, workspace_size));
// Destroy matmul descriptor and algorithim
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulBCastDescDestroy(bmm_bcast_desc));
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBatchMatMulBCastAlgoDestroy(algo));
}
/* static */ void MLUCnnl::Transpose(
const ExecutionContext& ctx, const std::vector<int> perm,
const int input_dim, const cnnlTensorDescriptor_t input_desc,
const void* input, const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
cnnlTransposeDescriptor_t perm_desc;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlCreateTransposeDescriptor(&perm_desc));
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlSetTransposeDescriptor(perm_desc, input_dim, perm.data()));
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetTransposeWorkspaceSize(
handle, input_desc, perm_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlTranspose_v2(handle, perm_desc, input_desc,
input, output_desc, output,
workspace_ptr, workspace_size));
if (perm_desc) {
PADDLE_ENFORCE_MLU_SUCCESS(cnnlDestroyTransposeDescriptor(perm_desc));
}
}
/* static */ void MLUCnnl::MatrixBandPart(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t data_desc,
const void* input, const int num_lower, const int num_upper, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlMatrixBandPart(handle, data_desc, input,
num_lower, num_upper, output));
}
/* static */ void MLUCnnl::NumTrue(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t x_desc,
const void* x, Tensor index,
uint32_t* num_true) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size = 0;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetNumTrueWorkspaceSize(handle, x_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
index = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* index_ptr = index.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlNumTrue(
handle, x_desc, x, static_cast<uint32_t*>(index_ptr), num_true));
}
/* static */ void MLUCnnl::Where(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t x_desc,
const void* x, const uint32_t* strides,
const uint32_t* index,
const cnnlTensorDescriptor_t y_desc, int* y,
const bool as_tuple) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlWhere(handle, x_desc, x, strides, index, y_desc, y, as_tuple));
}
/* static */ void MLUCnnl::InTopK(
const ExecutionContext& ctx, const cnnlTensorDescriptor_t predictions_desc,
const void* predictions, const cnnlTensorDescriptor_t targets_desc,
const void* targets, const cnnlTensorDescriptor_t k_desc, const void* k,
const int k_int, const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlInTopK(handle, predictions_desc, predictions,
targets_desc, targets, k_desc, k, k_int,
output_desc, output));
}
/* static */ void MLUCnnl::ScatterNd(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t indices_desc,
const void* indices,
const cnnlTensorDescriptor_t updates_desc,
const void* updates,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(cnnlScatterNd(handle, indices_desc, indices,
updates_desc, updates, output_desc,
output));
}
/* static */ void MLUCnnl::BitWise(
const ExecutionContext& ctx, const cnnlBitComputeOp_t optype,
const cnnlTensorDescriptor_t input1_desc, const void* input1,
const cnnlTensorDescriptor_t input2_desc, const void* input2,
const cnnlTensorDescriptor_t output_desc, void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(cnnlGetBitComputeWorkspaceSize(
handle, input1_desc, input2_desc, output_desc, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlBitCompute_v2(
handle, optype, input1_desc, input1, input2_desc, input2, output_desc,
output, workspace_ptr, workspace_size));
}
/* static */ void MLUCnnl::QR(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t a_desc,
const void* a,
const cnnlTensorDescriptor_t q_desc, void* q,
const cnnlTensorDescriptor_t r_desc, void* r,
const bool some) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
size_t workspace_size;
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlGetQRWorkspaceSize(handle, a_desc, some, &workspace_size));
auto& dev_ctx = GetDevCtxFromCTX(ctx);
Tensor workspace = ctx.AllocateTmpTensor<int8_t, MLUDeviceContext>(
{static_cast<int64_t>(workspace_size)}, dev_ctx);
void* workspace_ptr = workspace.mutable_data(ctx.GetPlace());
PADDLE_ENFORCE_MLU_SUCCESS(cnnlQR(handle, a_desc, a, q_desc, q, r_desc, r,
workspace_ptr, workspace_size, some));
}
/* static */ void MLUCnnl::Reciprocal(const ExecutionContext& ctx,
const cnnlTensorDescriptor_t input_desc,
const void* input,
const cnnlTensorDescriptor_t output_desc,
void* output) {
cnnlHandle_t handle = GetHandleFromCTX(ctx);
PADDLE_ENFORCE_MLU_SUCCESS(
cnnlReciprocal(handle, input_desc, input, output_desc, output));
}
} // namespace operators
} // namespace paddle
| 44.750881 | 80 | 0.700776 | [
"vector",
"transform"
] |
c88126e42447a5c724c2c27050dabc0b4c32cb28 | 3,579 | hpp | C++ | parallel_transport_frames.hpp | ddiakopoulos/sandbox | fd4aa4d0e1cd6e45459cdee44aa18d0087adb708 | [
"Unlicense"
] | 177 | 2015-09-19T19:51:57.000Z | 2021-11-08T11:25:55.000Z | parallel_transport_frames.hpp | ddiakopoulos/gfx_dev | fd4aa4d0e1cd6e45459cdee44aa18d0087adb708 | [
"Unlicense"
] | 1 | 2016-03-16T23:27:11.000Z | 2016-03-17T08:12:54.000Z | parallel_transport_frames.hpp | ddiakopoulos/gfx_dev | fd4aa4d0e1cd6e45459cdee44aa18d0087adb708 | [
"Unlicense"
] | 16 | 2016-03-16T13:06:55.000Z | 2020-06-20T04:57:04.000Z | #ifndef parallel_transport_frames_hpp
#define parallel_transport_frames_hpp
#include "util.hpp"
#include "math-common.hpp"
#include "splines.hpp"
// good ref: http://sunandblackcat.com/tipFullView.php?l=eng&topicid=4
// Compute a set of reference frames defined by their transformation matrix along a
// curve. It is designed so that the array of points and the array of matrices used
// to fetch these routines don't need to be ordered as the curve. e.g.
//
// m[0] = first_frame(p[0], p[1], p[2]);
// for(int i = 1; i < n - 1; i++)
// {
// m[i] = next_frame(m[i-1], p[i-1], p[i], t[i-1], t[i]);
// }
// m[n-1] = last_frame(m[n-2], p[n-2], p[n-1]);
//
// See Game Programming Gems 2, Section 2.5
inline std::vector<float4x4> make_parallel_transport_frame_bezier(const std::array<Pose, 4> controlPoints, const int segments)
{
BezierCurve curve(controlPoints[0].position, controlPoints[1].position, controlPoints[2].position, controlPoints[3].position);
std::vector<float3> points; // Points in spline
std::vector<float3> tangents; // Tangents in spline (fwd dir)
// Build the spline.
float dt = 1.0f / float(segments);
for (int i = 0; i < segments; ++i)
{
float t = float(i) * dt;
float3 P = curve.point(t);
points.push_back(P);
float3 T = normalize(curve.derivative(t));
tangents.push_back(T);
}
auto n = points.size();
std::vector<float4x4> frames(n); // Coordinate frame at each spline sample
// Require at least 3 points to start
if (n >= 3)
{
// First frame, expressed in a Y-up, right-handed coordinate system
const float3 B = normalize(points[1] - points[0]); // bitangent
const float3 T = normalize(cross({ 0, 1, 0 }, B)); // tangent
const float3 N = cross(B, N); // normal
frames[0] = { float4(-T, 0), float4(N, 0), float4(B, 0), float4(points[0], 1) };
// This sets the transformation matrix to the last reference frame defined by the previously computed
// transformation matrix and the last point along the curve.
for (int i = 1; i < n - 1; ++i)
{
float3 axis;
float r = 0.f;
if ((length2(tangents[i - 1]) != 0.0f) && (length2(tangents[i]) != 0.0f))
{
const float3 prevTangent = normalize(tangents[i - 1]);
const float3 curTangent = normalize(tangents[i]);
float dp = dot(prevTangent, curTangent);
if (dp > 1) dp = 1;
else if (dp < -1) dp = -1;
r = std::acos(dp);
axis = cross(prevTangent, curTangent);
}
if ((length(axis) != 0.0f) && (r != 0.0f))
{
float4x4 R = make_rotation_matrix(normalize(axis), r); // note the normalized axis
float4x4 Tj = make_translation_matrix(points[i]); // current point
float4x4 Ti = make_translation_matrix(-points[i - 1]); // previous point
frames[i] = mul(Tj, mul(R, mul(Ti, frames[i - 1])));
}
else
{
float4x4 t = make_translation_matrix(points[i] - points[i - 1]);
frames[i] = mul(t, frames[i - 1]);
}
}
// Last frame
frames[n - 1] = mul(make_translation_matrix(points[n - 1] - points[n - 2]), frames[n - 2]);
}
return frames;
}
#endif // end parallel_transport_frames_hpp | 37.28125 | 130 | 0.557698 | [
"vector"
] |
c8817f80d60f9b5e4a0db373dccc8b608046bcc2 | 12,660 | cpp | C++ | hyper/console/command.cpp | hyperlib/console | 045b36a3a1f0ad3493c7032409f1c4af156ad37a | [
"MIT"
] | null | null | null | hyper/console/command.cpp | hyperlib/console | 045b36a3a1f0ad3493c7032409f1c4af156ad37a | [
"MIT"
] | null | null | null | hyper/console/command.cpp | hyperlib/console | 045b36a3a1f0ad3493c7032409f1c4af156ad37a | [
"MIT"
] | null | null | null | // <hyper/console/command.cpp> -*- C++ -*-
/**
* Hyper
*
* (c) 2017 Axel Etcheverry
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include "command.hpp"
#include "option_value.hpp"
namespace hyper {
namespace console {
Command::Command(): m_parent(nullptr) {
}
Command::~Command() {
/*
for (std::map<std::string, Command*>::iterator itr = m_commands.begin(); itr != m_commands.end(); itr++) {
delete itr->second;
}
*/
for (std::size_t i = 0; i < m_options.size(); ++i) {
delete m_options[i];
}
}
Command& Command::setParent(const Command* command) {
m_parent = command;
return *this;
}
Command& Command::setName(const std::string& name) {
m_name = name;
return *this;
}
std::string Command::getName() const {
return m_name;
}
Command& Command::setDescription(const std::string& description) {
m_description = description;
return *this;
}
std::string Command::getDescription() const {
return m_description;
}
Command& Command::addOption(Option* option) {
for (std::size_t n = 0; n < m_options.size(); ++n) {
if ((option->getShortOption() != 0) && (option->getShortOption() == m_options[n]->getShortOption())) {
throw std::invalid_argument("dublicate short option '-" + std::string(1, option->getShortOption()) + "'");
}
if (!option->getLongOption().empty() && (option->getLongOption() == (m_options[n]->getLongOption()))) {
throw std::invalid_argument("dublicate long option '--" + option->getLongOption() + "'");
}
}
m_options.push_back(option);
return *this;
}
Command& Command::addCommand(Command* cmd) {
cmd->setParent(this);
cmd->configuration();
m_commands[cmd->getName()] = cmd;
return *this;
}
bool Command::hasCommand() const {
return m_commands.size() > 0;
}
Option* Command::getLongOpt(const std::string& opt) const {
for (std::size_t n = 0; n < m_options.size(); ++n) {
if (m_options[n]->getLongOption() == opt) {
return m_options[n];
}
}
return NULL;
}
Option* Command::getShortOpt(const char opt) const {
for (std::size_t n = 0; n < m_options.size(); ++n) {
if (m_options[n]->getShortOption() == opt) {
return m_options[n];
}
}
return NULL;
}
std::vector<std::string>& Command::getArguments() {
return m_args;
}
Command& Command::parse(int argc, char *argv[]) {
std::vector<std::string> arguments(argv + 0, argv + argc);
return parse(arguments);
}
Command& Command::parse(std::vector<std::string>& args) {
m_args.clear();
args.erase(args.begin());
m_argv = args;
for (std::size_t i = 0; i < args.size(); ++i) {
std::string arg = args[i];
if (arg == "--") {
///from here on only non opt args
for (std::size_t m = i + 1; m < args.size(); ++m) {
m_args.push_back(args[m]);
}
break;
} else if (arg.find("--") == 0) {
/// long option arg
std::string opt = arg.substr(2);
std::string optarg;
std::size_t equalIdx = opt.find('=');
if (equalIdx != std::string::npos) {
optarg = opt.substr(equalIdx + 1);
opt.resize(equalIdx);
}
Option* option = NULL;
if ((option = getLongOpt(opt)) != NULL) {
if (option->getType() == OptionValue::None) {
if (!optarg.empty()) {
option = NULL;
}
} else if (option->getType() == OptionValue::Required) {
if (optarg.empty() && i < args.size()-1) {
m_argv.erase(m_argv.begin() + i);
optarg = args[++i];
}
}
}
if (option != NULL) {
option->parse(opt, optarg);
m_argv.erase(m_argv.begin() + i);
} else if (m_commands.empty()) {
//@TODO throw error
//m_unknown_options.push_back(arg);
std::cerr << "Unknown options: " << arg << std::endl;
}
} else if (arg.find("-") == 0) {
/// short option arg
std::string opt = arg.substr(1);
bool unknown = false;
for (std::size_t m = 0; m < opt.size(); ++m) {
char c = opt[m];
Option* option = NULL;
std::string optarg;
if ((option = getShortOpt(c)) != NULL) {
if (option->getType() == OptionValue::Required) {
/// use the rest of the current argument as optarg
optarg = opt.substr(m + 1);
/// or the next arg
if (optarg.empty() && i < args.size()-1) {
m_argv.erase(m_argv.begin() + i);
optarg = args[++i];
}
m = opt.size();
} else if (option->getType() == OptionValue::Optional) {
/// use the rest of the current argument as optarg
optarg = opt.substr(m + 1);
m = opt.size();
}
// trim space or equal ex= -l=foo
// ^
if (!optarg.empty() && optarg[0] == '=') {
optarg = optarg.substr(1);
}
}
if (option != NULL) {
option->parse(std::string(1, c), optarg);
} else {
unknown = true;
}
}
if (unknown && m_commands.empty()) {
//@TODO throw error
std::cerr << "Unknown options: " << arg << std::endl;
//m_unknown_options.push_back(arg);
} else {
m_argv.erase(m_argv.begin() + i);
}
} else {
m_args.push_back(arg);
}
}
return *this;
}
Command& Command::setOptions(const std::vector<Option*>& options) {
m_options = options;
return *this;
}
int Command::exec() {
try {
return execute();
} catch (std::exception& ex) {
std::cerr << ex.what() << std::endl;
return EXIT_FAILURE;
}
}
int Command::run() {
// show usage message if program has no command arg
if (m_args.empty() && !m_parent) {
std::cout << help();
return EXIT_FAILURE;
}
// show usage message if command has subcommand
if (m_args.empty() && !m_commands.empty()) {
std::cout << help();
return EXIT_FAILURE;
}
/*
for (auto arg : m_args) {
std::cout << "--- arg: " << arg << std::endl;
}
*/
// get command
std::string command = m_args.front();
//@TODO: Added external command support with prefix, ex: hyperscale-*
// show usage message if command not found.
if (m_commands.count(command) == 0) {
std::cout << help();
return EXIT_FAILURE;
}
Command* cmd = m_commands[command];
// check if command has sub command
if (cmd->hasCommand()) {
// forward argc/argv to subcommand without this command arg.
// example: ./hyperscale debug lexer --log-level=debug --foo
// 1. parse debug lexer --log-level=debug --foo
// 2. call debug command
// 3. parse lexer --log-level=debug --foo
// 4. call lexer
// 5. parse --log-level=debug --foo
// 6. exec handle
cmd->setOptions(m_options);
cmd->parse(m_argv);
return cmd->run();
} else {
//@TODO optimize this
cmd->parse(m_argv);
// exec command handle
return cmd->exec();
}
}
std::string Command::getNameWithParent() const {
std::stringstream s;
if (m_parent != NULL) {
s << m_parent->getNameWithParent() << " ";
}
s << m_name;
return s.str();
}
std::string Command::help() const {
std::size_t optionRightMargin(20);
const std::size_t maxDescriptionLeftMargin(40);
// const std::size_t descriptionRightMargin(80);
for (std::size_t opt = 0; opt < m_options.size(); ++opt) {
optionRightMargin = std::max(optionRightMargin, m_options[opt]->optionToString().size() + 2);
}
optionRightMargin = std::min(maxDescriptionLeftMargin - 2, optionRightMargin);
std::stringstream s;
s << "Usage: " << getNameWithParent();
if (m_commands.empty() && m_options.size() > 0) {
s << " [OPTIONS]";
} else if (m_commands.size() > 0) {
s << " COMMAND";
}
s << std::endl;
s << std::endl;
if (!m_description.empty()) {
s << m_description << std::endl;
s << std::endl;
}
if (m_options.size() > 0) {
s << "Options:" << std::endl;
for (std::size_t opt = 0; opt < m_options.size(); ++opt) {
std::string optionStr = m_options[opt]->optionToString();
if (optionStr.size() < optionRightMargin) {
optionStr.resize(optionRightMargin, ' ');
} else {
optionStr += "\n" + std::string(optionRightMargin, ' ');
}
s << optionStr;
std::vector<std::string> lines = m_options[opt]->descriptionToString(20);
std::string empty(optionRightMargin, ' ');
for (std::size_t n = 0; n < lines.size(); ++n) {
if (n > 0) {
s << std::endl << empty;
}
s << lines[n];
}
s << std::endl;
}
}
if (!m_commands.empty()) {
std::size_t commandRightMargin(14);
s << "Commands:" << std::endl;
for (auto& item : m_commands) {
std::string commandStr = " " + item.second->getName();
if (commandStr.size() < commandRightMargin) {
commandStr.resize(commandRightMargin, ' ');
} else {
commandStr += "\n" + std::string(commandRightMargin, ' ');
}
s << commandStr;
std::vector<std::string> lines = item.second->descriptionToString(20);
std::string empty(commandRightMargin, ' ');
for (std::size_t n = 0; n < lines.size(); ++n) {
if (n > 0) {
s << std::endl << empty;
}
s << lines[n];
}
s << std::endl;
}
s << std::endl;
s << "Run '" << getNameWithParent() << " COMMAND --help' for more information on a command." << std::endl;
}
return s.str();
}
std::vector<std::string> Command::descriptionToString(std::size_t width) const {
std::vector<std::string> lines;
std::stringstream description(getDescription());
std::string line;
while (std::getline(description, line, '\n')) {
lines.push_back(line);
}
return lines;
}
} // end of console namespace
} // end of hyper namespace
| 29.44186 | 122 | 0.450237 | [
"vector"
] |
c881e9077309bfad4bed6ff9bf6abedbebc0de54 | 1,200 | cc | C++ | OnlineDB/CSCCondDB/test/stubs/CSCChamberMapHandler.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | OnlineDB/CSCCondDB/test/stubs/CSCChamberMapHandler.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | OnlineDB/CSCCondDB/test/stubs/CSCChamberMapHandler.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "OnlineDB/CSCCondDB/test/stubs/CSCChamberMapHandler.h"
#include "FWCore/ParameterSet/interface/ParameterSetfwd.h"
#include<iostream>
#include "CondFormats/CSCObjects/interface/CSCChamberMap.h"
#include "OnlineDB/CSCCondDB/interface/CSCChamberMapValues.h"
popcon::CSCChamberMapImpl::CSCChamberMapImpl(const edm::ParameterSet& pset): m_name(pset.getUntrackedParameter<std::string>("name","CSCChamberMapImpl"))
{}
popcon::CSCChamberMapImpl::~CSCChamberMapImpl()
{
}
void popcon::CSCChamberMapImpl::getNewObjects()
{
std::cout << "------- CSC src - > getNewObjects\n"<<m_name;
// fill object from file
CSCChamberMap * mycham_map = CSCChamberMapValues::fillChamberMap();
//check whats already inside of database
std::cerr<<"got offlineInfo"<<std::endl;
std::cerr << tagInfo().name << " , last object valid since "
<< tagInfo().lastInterval.first << std::endl;
unsigned int snc;
std::cout << "Source implementation test ::getNewObjects : enter since ? \n";
std::cin >> snc;
m_to_transfer.push_back(std::make_pair((CSCChamberMap*)mycham_map,snc));
std::cout << "------- " << m_name << "CSC src - > getNewObjects -----------\n"<< std::endl;
}
| 31.578947 | 152 | 0.7025 | [
"object"
] |
c885db6dfcc3433a2fa7a3ea3cb8cb2994242231 | 3,598 | cpp | C++ | P0/MyApp/main.cpp | daniOrtiz11/Graficos-Por-Computador | df655ee952f0516ec63b27508617a27b0fe51a99 | [
"MIT"
] | null | null | null | P0/MyApp/main.cpp | daniOrtiz11/Graficos-Por-Computador | df655ee952f0516ec63b27508617a27b0fe51a99 | [
"MIT"
] | null | null | null | P0/MyApp/main.cpp | daniOrtiz11/Graficos-Por-Computador | df655ee952f0516ec63b27508617a27b0fe51a99 | [
"MIT"
] | null | null | null | //#include <Windows.h>
//#include <gl/GL.h>
//#include <gl/GLU.h>
//#include <GL/glut.h>
#include <GL/freeglut.h>
#include "Camera.h"
#include "Scene.h"
#include <iostream>
using namespace std;
//---------- Global variables -------------------------------------------------------------
// Viewport position and size
Viewport viewPort(800, 600);
// Camera position, view volume and projection
Camera camera(&viewPort);
// Scene entities
Scene scene(&camera);
//----------- Callbacks ----------------------------------------------------
void display();
void resize(int newWidth, int newHeight);
void key(unsigned char key, int x, int y);
void specialKey(int key, int x, int y);
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
cout << "Starting console..." << '\n';
// Initialization
glutInit(&argc, argv);
glutInitContextVersion(3, 3);
glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
glutInitWindowSize(800, 600); // window size
//glutInitWindowPosition (140, 140);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); // | GLUT_STENCIL
int win = glutCreateWindow( "Freeglut-project" ); // window's identifier
// Callback registration
glutReshapeFunc(resize);
glutKeyboardFunc(key);
glutSpecialFunc(specialKey);
glutDisplayFunc(display);
cout << glGetString(GL_VERSION) << '\n';
cout << glGetString(GL_VENDOR) << '\n';
scene.init(); // after creating the context
glutMainLoop();
//cin.sync(); cin.get();
glutDestroyWindow(win); // Destroy the context
return 0;
}
//-------------------------------------------------------------------------
void display() // double buffer
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
scene.render();
glutSwapBuffers();
}
//-------------------------------------------------------------------------
void resize(int newWidth, int newHeight)
{
// Resize Viewport
viewPort.setSize(newWidth, newHeight);
// Resize Scene Visible Area
camera.setSize(viewPort.getW(), viewPort.getH()); // scale unchanged
}
//-------------------------------------------------------------------------
void key(unsigned char key, int x, int y)
{
bool need_redisplay = true;
switch (key) {
case 27: // Escape key
glutLeaveMainLoop(); // Freeglut's sentence for stopping glut's main loop
break;
case '+':
camera.scale(+0.01); // zoom in
break;
case '-':
camera.scale(-0.01); // zoom out
break;
case 'l':
camera.set3D();
break;
case 'o':
camera.setAZ();
break;
case 'a':
scene.aumentarRotacion();
scene.render();
break;
default:
need_redisplay = false;
break;
}//switch
if (need_redisplay)
glutPostRedisplay();
}
//-------------------------------------------------------------------------
void specialKey(int key, int x, int y)
{
bool need_redisplay = true;
switch (key) {
case GLUT_KEY_RIGHT:
camera.pitch(1); // rotate 1 on the X axis
break;
case GLUT_KEY_LEFT:
camera.yaw(1); // rotate 1 on the Y axis
break;
case GLUT_KEY_UP:
camera.roll(1); // rotate 1 on the Z axis
break;
case GLUT_KEY_DOWN:
camera.roll(-1); // rotate -1 on the Z axis
break;
default:
need_redisplay = false;
break;
}//switch
if (need_redisplay)
glutPostRedisplay();
}
//-------------------------------------------------------------------------
| 23.827815 | 91 | 0.546415 | [
"render"
] |
c886927e74a7ee12e79b8f2cbc2ae09173cfe351 | 2,886 | cpp | C++ | src/main.cpp | 22427/df | f6761259fce95856d4ebc895b6e621c85b5b34b6 | [
"Unlicense"
] | null | null | null | src/main.cpp | 22427/df | f6761259fce95856d4ebc895b6e621c85b5b34b6 | [
"Unlicense"
] | null | null | null | src/main.cpp | 22427/df | f6761259fce95856d4ebc895b6e621c85b5b34b6 | [
"Unlicense"
] | null | null | null | #define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/norm.hpp>
#include <glm/gtx/matrix_transform_2d.hpp>
#include <string>
#include <vector>
#include <stdint.h>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <stb_image.h>
#include <stb_image_write.h>
#include <sstream>
#include "bin_img.h"
#include "shape.h"
#include "image2d.h"
Image2D<float> sample_distance_field(const Glyphe& g,int width, int height, float belt_radius =5)
{
Image2D<float> df(width,height,1);
// belt_radius--;
int br = belt_radius;
belt_radius = belt_radius/std::min(width,height);
#pragma omp parallel for
for(int y = 0; y<height;y++)
for(int x = 0; x<width;x++)
{
const auto d = g.distance(df.in_relative(x,y),belt_radius*4);
df(x,y)[0] =d;
}
float max= std::numeric_limits<float>::lowest();
for(int y = 0; y<height;y++)
for(int x = 0; x<width;x++)
{
bool use = false;
if(df(x,y)[0] == std::numeric_limits<float>::lowest())
continue;
int y_s = std::max(0,y-br);
int x_s = std::max(0,x-br);
int y_e = std::max(height,y+br);
int x_e = std::max(width,x+br);
for(int yy = y_s; yy<=y_e;yy++)
for(int xx = x_s; xx<=x_e;xx++)
{
if(df(xx,yy)[0] * df(x,y)[0] <0)
{
use = true;
break;
}
}
if(use)
max = std::max(max,fabsf(df(x,y)[0]));
}
printf("normalizing with %f\n",max);
for(int i = 0 ; i< width * height ; i++)
{
df(i)[0] = ((df(i)[0]/max)+1.0f)*0.5f;
df(i)[0] = df(i)[0]<0? 0:df(i)[0];
df(i)[0] = df(i)[0]>1? 1:df(i)[0];
}
return df;
}
void save_image(const Image2D<uint8_t>& img,const std::string& path)
{
stbi_write_png(path.c_str(),img.width,img.height,img.channels,img(0),0);
}
Image2D<uint8_t> load_image(const std::string& path)
{
int w, h , c;
auto data = stbi_load(path.c_str(),&w,&h,&c,0);
Image2D<uint8_t> img;
img.set_data_ptr(data,true,w,h,c);
return img;
}
BinImg* to_binary(const Image2D<uint8_t>& img, uint c)
{
BinImg* res = new BinImg(img.width,img.height);
for(int i =0 ; i < img.num_pix();i++)
{
res->at(i)[0] = img.at(i)[c]>127?1:0;
}
return res;
}
#include "fstream"
int main(int argc, char** argv)
{
Glyphe g;
GParser gp;
for(int i = 1; i< argc-4;i++)
{
std::string arg = argv[i];
const auto ending = arg.substr(arg.find_last_of('.'));
if(ending == ".txt")
{
std::ifstream f(arg);
g.add_shape(gp.parse(f));
}
else
{
auto img = load_image(arg);
auto bin_img = to_binary(img,0);
g.add_shape(bin_img);
}
}
int w,h,b;
w = atoi(argv[argc-1-3]);
h = atoi(argv[argc-1-2]);
b = atoi(argv[argc-1-1]);
std::string path = argv[argc-1];
auto img = sample_distance_field(g,w,h,b);
img.scale(255);
auto r = img.cast<uint8_t>();
save_image(r,path);
}
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image.h>
#include <stb_image_write.h>
| 19.632653 | 97 | 0.619543 | [
"shape",
"vector"
] |
c8876b20a5c43bcc6e95236fbf0232ad36a0efdd | 17,404 | cpp | C++ | Tests/testXLRow.cpp | martbelko/OpenXLSX | 87d1c8c4c5f71aeb4ce0214b20babffaf3f17f4c | [
"BSD-3-Clause"
] | 1 | 2021-12-24T09:31:24.000Z | 2021-12-24T09:31:24.000Z | Tests/testXLRow.cpp | martbelko/OpenXLSX | 87d1c8c4c5f71aeb4ce0214b20babffaf3f17f4c | [
"BSD-3-Clause"
] | null | null | null | Tests/testXLRow.cpp | martbelko/OpenXLSX | 87d1c8c4c5f71aeb4ce0214b20babffaf3f17f4c | [
"BSD-3-Clause"
] | 1 | 2022-01-01T15:13:38.000Z | 2022-01-01T15:13:38.000Z | //
// Created by Kenneth Balslev on 27/08/2021.
//
#include <OpenXLSX.hpp>
#include <catch.hpp>
#include <fstream>
#include <vector>
#include <list>
#include <deque>
using namespace OpenXLSX;
TEST_CASE("XLRow Tests", "[XLRow]")
{
SECTION("XLRow")
{
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto row_3 = wks.row(3);
REQUIRE(row_3.rowNumber() == 3);
XLRow copy1 = row_3;
auto height = copy1.height();
REQUIRE(copy1.height() == height);
XLRow copy2 = std::move(copy1);
auto descent = copy2.descent();
REQUIRE(copy2.descent() == descent);
XLRow copy3;
copy3 = copy2;
copy3.setHeight(height * 3);
REQUIRE(copy3.height() == height * 3);
copy3.setHeight(height * 4);
REQUIRE(copy3.height() == height * 4);
XLRow copy4;
copy4 = std::move(copy3);
copy4.setDescent(descent * 2);
REQUIRE(copy4.descent() == descent * 2);
copy4.setDescent(descent * 3);
REQUIRE(copy4.descent() == descent * 3);
REQUIRE(copy4.isHidden() == false);
copy4.setHidden(true);
REQUIRE(copy4.isHidden() == true);
copy4.setHidden(false);
REQUIRE(copy4.isHidden() == false);
auto row1 = wks.row(11);
auto row2 = wks.row(12);
auto row3 = wks.row(13);
auto row4 = wks.row(13);
REQUIRE(row3 == row4);
REQUIRE(row4 >= row3);
REQUIRE(row3 <= row4);
REQUIRE(row3 >= row2);
REQUIRE(row2 <= row3);
REQUIRE(row1 != row2);
REQUIRE(row2 > row1);
REQUIRE(row1 < row2);
doc.save();
}
}
TEST_CASE("XLRowData Tests", "[XLRowData]")
{
SECTION("XLRowData (vector<int>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::vector<int> {1, 2, 3, 4, 5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::vector<int>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 15);
val1sum = 0;
const auto val1results2 = static_cast<std::vector<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<int>();
REQUIRE(val1sum == 15);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (vector<double>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::vector<double> {1.1, 2.2, 3.3, 4.4, 5.5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0.0;
const auto val1results1 = static_cast<std::vector<double>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 16.5);
val1sum = 0;
const auto val1results2 = static_cast<std::vector<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<double>();
REQUIRE(val1sum == 16.5);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (vector<bool>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::vector<bool> {true, false, true, false, true};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::vector<bool>>(row1c.values());
for (const auto v : val1results1)
if (v) val1sum += 1;
REQUIRE(val1sum == 3);
val1sum = 0;
const auto val1results2 = static_cast<std::vector<XLCellValue>>(row1c.values());
for (const auto v : val1results2)
if(v.get<bool>()) val1sum += 1;
REQUIRE(val1sum == 3);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (vector<std::string>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::vector<std::string> {"This", "is", "a", "test."};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::vector<std::string>>(row1c.values());
for (const auto v : val1results1) val1sum += v.size();
REQUIRE(val1sum == 12);
val1sum = 0;
const auto val1results2 = static_cast<std::vector<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<std::string>().size();
REQUIRE(val1sum == 12);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (vector<XLCellValue>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::vector<XLCellValue> {1, 2, 3, 4, 5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::vector<int>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 15);
val1sum = 0;
const auto val1results2 = static_cast<std::vector<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<int>();
REQUIRE(val1sum == 15);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (list<int>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::list<int> {1, 2, 3, 4, 5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::list<int>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 15);
val1sum = 0;
const auto val1results2 = static_cast<std::list<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<int>();
REQUIRE(val1sum == 15);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (list<bool>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::list<bool> {true, false, true, false, true};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::list<bool>>(row1c.values());
for (const auto v : val1results1)
if (v) val1sum += 1;
REQUIRE(val1sum == 3);
val1sum = 0;
const auto val1results2 = static_cast<std::list<XLCellValue>>(row1c.values());
for (const auto v : val1results2)
if (v.get<bool>()) val1sum += 1;
REQUIRE(val1sum == 3);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (list<double>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::list<double> {1.1, 2.2, 3.3, 4.4, 5.5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0.0;
const auto val1results1 = static_cast<std::list<double>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 16.5);
val1sum = 0;
const auto val1results2 = static_cast<std::list<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<double>();
REQUIRE(val1sum == 16.5);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (list<std::string>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::list<std::string> {"This", "is", "a", "test."};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::list<std::string>>(row1c.values());
for (const auto v : val1results1) val1sum += v.size();
REQUIRE(val1sum == 12);
val1sum = 0;
const auto val1results2 = static_cast<std::list<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<std::string>().size();
REQUIRE(val1sum == 12);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (list<XLCellValue>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::list<XLCellValue> {1, 2, 3, 4, 5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::list<int>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 15);
val1sum = 0;
const auto val1results2 = static_cast<std::list<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<int>();
REQUIRE(val1sum == 15);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (deque<int>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::deque<int> {1, 2, 3, 4, 5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::deque<int>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 15);
val1sum = 0;
const auto val1results2 = static_cast<std::deque<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<int>();
REQUIRE(val1sum == 15);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (deque<bool>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::deque<bool> {true, false, true, false, true};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::deque<bool>>(row1c.values());
for (const auto v : val1results1)
if (v) val1sum += 1;
REQUIRE(val1sum == 3);
val1sum = 0;
const auto val1results2 = static_cast<std::deque<XLCellValue>>(row1c.values());
for (const auto v : val1results2)
if (v.get<bool>()) val1sum += 1;
REQUIRE(val1sum == 3);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (deque<double>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::deque<double> {1.1, 2.2, 3.3, 4.4, 5.5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0.0;
const auto val1results1 = static_cast<std::deque<double>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 16.5);
val1sum = 0;
const auto val1results2 = static_cast<std::deque<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<double>();
REQUIRE(val1sum == 16.5);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (deque<std::string>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::deque<std::string> {"This", "is", "a", "test."};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::deque<std::string>>(row1c.values());
for (const auto v : val1results1) val1sum += v.size();
REQUIRE(val1sum == 12);
val1sum = 0;
const auto val1results2 = static_cast<std::deque<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<std::string>().size();
REQUIRE(val1sum == 12);
row1.values().clear();
doc.save();
}
SECTION("XLRowData (deque<XLCellValue>)") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto val1 = std::deque<XLCellValue> {1, 2, 3, 4, 5};
auto row1 = wks.row(1);
row1.values() = val1;
const auto row1c = row1;
auto val1sum = 0;
const auto val1results1 = static_cast<std::deque<int>>(row1c.values());
for (const auto v : val1results1) val1sum += v;
REQUIRE(val1sum == 15);
val1sum = 0;
const auto val1results2 = static_cast<std::deque<XLCellValue>>(row1c.values());
for (const auto v : val1results2) val1sum += v.get<int>();
REQUIRE(val1sum == 15);
row1.values().clear();
doc.save();
}
}
TEST_CASE("XLRowDataRange Tests", "[XLRowDataRange]")
{
SECTION("XLRowDataRange") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto row = wks.row(1);
auto range = row.cells();
for (auto& cell : range) cell.value() = 1;
auto sum = 0;
for (const auto& cell : range) sum += cell.value().get<int>();
REQUIRE(sum == 1);
REQUIRE(range.size() == 1);
auto range_copy = range;
sum = 0;
for (const auto& cell : range_copy) sum += cell.value().get<int>();
REQUIRE(sum == 1);
REQUIRE(range_copy.size() == 1);
auto range_move = std::move(range_copy);
sum = 0;
for (const auto& cell : range_move) sum += cell.value().get<int>();
REQUIRE(sum == 1);
REQUIRE(range_move.size() == 1);
auto range_copy2 = range_move;
range_copy2 = range;
sum = 0;
for (const auto& cell : range_copy2) sum += cell.value().get<int>();
REQUIRE(sum == 1);
REQUIRE(range_copy2.size() == 1);
auto range_move2 = range_move;
range_move2 = std::move(range_copy2);
sum = 0;
for (const auto& cell : range_move2) sum += cell.value().get<int>();
REQUIRE(sum == 1);
REQUIRE(range_move2.size() == 1);
auto row2 = wks.row(2);
auto range2 = row2.cells(8);
for (auto& cell : range2) cell.value() = 1;
sum = 0;
for (const auto& cell : row2.cells()) sum += cell.value().get<int>();
REQUIRE(sum == 8);
REQUIRE(range2.size() == 8);
auto row3 = wks.row(3);
auto range3 = row3.cells(3, 8);
for (auto& cell : range3) cell.value() = 1;
sum = 0;
for (const auto& cell : row3.cells())
if (cell.value().type() == XLValueType::Integer) sum += cell.value().get<int>();
REQUIRE(sum == 6);
REQUIRE(row3.cells().size() == 8);
doc.save();
}
SECTION("XLRowDataIterator") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto row = wks.row(1);
auto range = row.cells(2);
for (auto& cell : range) cell.value() = 1;
auto begin = range.begin();
auto end = range.end();
auto other = begin;
REQUIRE(begin == other);
REQUIRE_FALSE(begin == end);
REQUIRE(begin != end);
REQUIRE_FALSE(begin != other);
++other;
REQUIRE_FALSE(begin == other);
++other;
REQUIRE(other == end);
other = begin;
REQUIRE(begin == other);
other++;
other = std::move(begin);
begin = range.begin();
REQUIRE(begin == other);
}
}
TEST_CASE("XLRowIterator Tests", "[XLRowDataRange]")
{
SECTION("XLRowIterator") {
XLDocument doc;
doc.create("./testXLRow.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
auto range = wks.rows(1,3);
auto first = range.begin();
auto second = first;
second++;
auto third = range.end();
auto fourth = std::move(third);
third = second;
second = std::move(first);
first = range.begin();
REQUIRE(second == range.begin());
REQUIRE_FALSE(second == third);
REQUIRE_FALSE(second == fourth);
REQUIRE(range.rowCount() == 3);
REQUIRE(first->rowNumber() == 1);
}
} | 29.152429 | 92 | 0.545852 | [
"vector"
] |
c88a4d8e7ebdc56f30a68d680f378cd24b1160e2 | 34,128 | cxx | C++ | main/sd/source/ui/view/drviews2.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sd/source/ui/view/drviews2.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sd/source/ui/view/drviews2.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "DrawViewShell.hxx"
#include "ViewShellImplementation.hxx"
#include <vcl/waitobj.hxx>
#include <svx/svdograf.hxx>
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#include <svx/svdpagv.hxx>
#include <svx/svdundo.hxx>
#ifndef _ZOOMITEM_HXX
#include <svx/zoomitem.hxx>
#endif
#ifndef _EDITDATA_HXX
#include <editeng/editdata.hxx>
#endif
#include <basic/sberrors.hxx>
#include <vcl/msgbox.hxx>
#include <sfx2/request.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/xfillit0.hxx>
#include <svx/xflclit.hxx>
#include <svl/aeitem.hxx>
#include <editeng/eeitem.hxx>
#include <basic/sbstar.hxx>
#include <editeng/flditem.hxx>
#include <svx/xlineit0.hxx>
#include <svx/xfillit0.hxx>
#ifndef _SDOUTL_HXX //autogen
#include <svx/svdoutl.hxx>
#endif
#include <svx/xlnwtit.hxx>
#include <svx/svdoattr.hxx>
#include <svx/xlnstwit.hxx>
#include <svx/sdtmfitm.hxx>
#include <svx/sdtagitm.hxx>
#include <svx/xlnedwit.hxx>
#include <svx/fontworkbar.hxx>
#include <editeng/escpitem.hxx>
#include <editeng/kernitem.hxx>
#include <editeng/wghtitem.hxx>
#include <editeng/postitem.hxx>
#include <editeng/udlnitem.hxx>
#include <editeng/crsditem.hxx>
#include <editeng/cntritem.hxx>
#include <editeng/shdditem.hxx>
#include <svx/xtable.hxx>
#include <svx/svdobj.hxx>
#include <editeng/outlobj.hxx>
#include <editeng/flstitem.hxx>
#include <editeng/scripttypeitem.hxx>
#include <editeng/fontitem.hxx>
#include <editeng/fhgtitem.hxx>
#include <editeng/colritem.hxx>
#include <editeng/brshitem.hxx>
#include <svl/whiter.hxx>
#include <svx/svxdlg.hxx>
#include <svx/dialogs.hrc>
#include <sfx2/viewfrm.hxx>
#include "sdgrffilter.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "helpids.h"
#include "sdattr.hxx"
#include "drawview.hxx"
#include "Window.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#include "sdpage.hxx"
#include "fuscale.hxx"
#include "sdresid.hxx"
#include "GraphicViewShell.hxx"
#include "unmodpg.hxx"
#include "slideshow.hxx"
#include "fuvect.hxx"
#include "futext.hxx"
#include "stlpool.hxx"
// #90356#
#include "optsitem.hxx"
#include "sdabstdlg.hxx"
#include <com/sun/star/drawing/XMasterPagesSupplier.hpp>
#include <com/sun/star/drawing/XDrawPages.hpp>
#include <strings.hrc>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace sd {
/*************************************************************************
|*
|* SfxRequests fuer temporaere Funktionen
|*
\************************************************************************/
void DrawViewShell::FuTemporary(SfxRequest& rReq)
{
// Waehrend einer Native-Diashow wird nichts ausgefuehrt!
if(SlideShow::IsRunning( GetViewShellBase() ) && (rReq.GetSlot() != SID_NAVIGATOR))
return;
DBG_ASSERT( mpDrawView, "sd::DrawViewShell::FuTemporary(), no draw view!" );
if( !mpDrawView )
return;
CheckLineTo (rReq);
DeactivateCurrentFunction();
sal_uInt16 nSId = rReq.GetSlot();
// Slot wird gemapped (ToolboxImages/-Slots)
MapSlot( nSId );
switch ( nSId )
{
// Flaechen und Linien-Attribute:
// Sollten (wie StateMethode) eine eigene
// Execute-Methode besitzen
case SID_ATTR_FILL_STYLE:
case SID_ATTR_FILL_COLOR:
case SID_ATTR_FILL_GRADIENT:
case SID_ATTR_FILL_HATCH:
case SID_ATTR_FILL_BITMAP:
case SID_ATTR_FILL_SHADOW:
case SID_ATTR_FILL_TRANSPARENCE:
case SID_ATTR_FILL_FLOATTRANSPARENCE:
case SID_ATTR_LINE_STYLE:
case SID_ATTR_LINE_DASH:
case SID_ATTR_LINE_WIDTH:
case SID_ATTR_LINE_COLOR:
case SID_ATTR_LINEEND_STYLE:
case SID_ATTR_LINE_START:
case SID_ATTR_LINE_END:
case SID_ATTR_LINE_TRANSPARENCE:
case SID_ATTR_LINE_JOINT:
case SID_ATTR_LINE_CAP:
case SID_ATTR_TEXT_FITTOSIZE:
{
if( rReq.GetArgs() )
{
mpDrawView->SetAttributes(*rReq.GetArgs());
rReq.Done();
}
else
{
switch( rReq.GetSlot() )
{
case SID_ATTR_FILL_SHADOW:
case SID_ATTR_FILL_STYLE:
case SID_ATTR_FILL_COLOR:
case SID_ATTR_FILL_GRADIENT:
case SID_ATTR_FILL_HATCH:
case SID_ATTR_FILL_BITMAP:
case SID_ATTR_FILL_TRANSPARENCE:
case SID_ATTR_FILL_FLOATTRANSPARENCE:
GetViewFrame()->GetDispatcher()->Execute( SID_ATTRIBUTES_AREA, SFX_CALLMODE_ASYNCHRON );
break;
case SID_ATTR_LINE_STYLE:
case SID_ATTR_LINE_DASH:
case SID_ATTR_LINE_WIDTH:
case SID_ATTR_LINE_COLOR:
case SID_ATTR_LINE_TRANSPARENCE:
case SID_ATTR_LINE_JOINT:
case SID_ATTR_LINE_CAP:
GetViewFrame()->GetDispatcher()->Execute( SID_ATTRIBUTES_LINE, SFX_CALLMODE_ASYNCHRON );
break;
case SID_ATTR_TEXT_FITTOSIZE:
GetViewFrame()->GetDispatcher()->Execute( SID_TEXTATTR_DLG, SFX_CALLMODE_ASYNCHRON );
break;
}
}
Cancel();
}
break;
case SID_HYPHENATION:
{
// const SfxPoolItem* pItem = rReq.GetArg( SID_HYPHENATION );
// ^-- Soll so nicht benutzt werden (Defaults sind falsch) !
SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, SID_HYPHENATION, sal_False);
if( pItem )
{
SfxItemSet aSet( GetPool(), EE_PARA_HYPHENATE, EE_PARA_HYPHENATE );
sal_Bool bValue = ( (const SfxBoolItem*) pItem)->GetValue();
aSet.Put( SfxBoolItem( EE_PARA_HYPHENATE, bValue ) );
mpDrawView->SetAttributes( aSet );
}
else // nur zum Test
{
DBG_ERROR(" Kein Wert fuer Silbentrennung!");
SfxItemSet aSet( GetPool(), EE_PARA_HYPHENATE, EE_PARA_HYPHENATE );
sal_Bool bValue = sal_True;
aSet.Put( SfxBoolItem( EE_PARA_HYPHENATE, bValue ) );
mpDrawView->SetAttributes( aSet );
}
rReq.Done();
Cancel();
}
break;
case SID_INSERTPAGE:
case SID_INSERTPAGE_QUICK:
case SID_DUPLICATE_PAGE:
{
SdPage* pNewPage = CreateOrDuplicatePage (rReq, mePageKind, GetActualPage());
Cancel();
if(HasCurrentFunction(SID_BEZIER_EDIT) )
GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
if (pNewPage != NULL)
SwitchPage((pNewPage->GetPageNum()-1)/2);
rReq.Done ();
}
break;
case SID_INSERT_MASTER_PAGE:
{
// Use the API to create a new page.
Reference<drawing::XMasterPagesSupplier> xMasterPagesSupplier (
GetDoc()->getUnoModel(), UNO_QUERY);
if (xMasterPagesSupplier.is())
{
Reference<drawing::XDrawPages> xMasterPages (
xMasterPagesSupplier->getMasterPages());
if (xMasterPages.is())
{
sal_uInt16 nIndex = GetCurPageId();
xMasterPages->insertNewByIndex (nIndex);
// Create shapes for the default layout.
SdPage* pMasterPage = GetDoc()->GetMasterSdPage(
nIndex, PK_STANDARD);
pMasterPage->CreateTitleAndLayout (sal_True,sal_True);
}
}
Cancel();
if(HasCurrentFunction(SID_BEZIER_EDIT))
GetViewFrame()->GetDispatcher()->Execute(
SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
rReq.Done ();
}
break;
case SID_MODIFYPAGE:
{
if (mePageKind==PK_STANDARD || mePageKind==PK_NOTES ||
(mePageKind==PK_HANDOUT && meEditMode==EM_MASTERPAGE) )
{
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
}
sal_uInt16 nPage = maTabControl.GetCurPageId() - 1;
mpActualPage = GetDoc()->GetSdPage(nPage, mePageKind);
::sd::ViewShell::mpImpl->ProcessModifyPageSlot (
rReq,
mpActualPage,
mePageKind);
}
Cancel();
rReq.Done ();
}
break;
case SID_ASSIGN_LAYOUT:
{
if (mePageKind==PK_STANDARD || mePageKind==PK_NOTES || (mePageKind==PK_HANDOUT && meEditMode==EM_MASTERPAGE))
{
if ( mpDrawView->IsTextEdit() )
mpDrawView->SdrEndTextEdit();
::sd::ViewShell::mpImpl->AssignLayout(rReq, mePageKind);
}
Cancel();
rReq.Done ();
}
break;
case SID_RENAMEPAGE:
case SID_RENAME_MASTER_PAGE:
{
if (mePageKind==PK_STANDARD || mePageKind==PK_NOTES )
{
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
}
sal_uInt16 nPageId = maTabControl.GetCurPageId();
SdPage* pCurrentPage = ( GetEditMode() == EM_PAGE )
? GetDoc()->GetSdPage( nPageId - 1, GetPageKind() )
: GetDoc()->GetMasterSdPage( nPageId - 1, GetPageKind() );
String aTitle( SdResId( STR_TITLE_RENAMESLIDE ) );
String aDescr( SdResId( STR_DESC_RENAMESLIDE ) );
String aPageName = pCurrentPage->GetName();
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet fail!");
AbstractSvxNameDialog* aNameDlg = pFact->CreateSvxNameDialog( GetActiveWindow(), aPageName, aDescr );
DBG_ASSERT(aNameDlg, "Dialogdiet fail!");
aNameDlg->SetText( aTitle );
aNameDlg->SetCheckNameHdl( LINK( this, DrawViewShell, RenameSlideHdl ), true );
aNameDlg->SetEditHelpId( HID_SD_NAMEDIALOG_PAGE );
if( aNameDlg->Execute() == RET_OK )
{
String aNewName;
aNameDlg->GetName( aNewName );
if( ! aNewName.Equals( aPageName ) )
{
#ifdef DBG_UTIL
bool bResult =
#endif
RenameSlide( nPageId, aNewName );
DBG_ASSERT( bResult, "Couldn't rename slide" );
}
}
delete aNameDlg;
}
Cancel();
rReq.Ignore ();
}
break;
case SID_RENAMEPAGE_QUICK:
{
if (mePageKind==PK_STANDARD || mePageKind==PK_NOTES )
{
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
}
maTabControl.StartEditMode( maTabControl.GetCurPageId() );
}
Cancel();
rReq.Ignore ();
}
break;
case SID_PAGESIZE : // entweder dieses (kein menueeintrag o. ae. !!)
{
const SfxItemSet *pArgs = rReq.GetArgs ();
if (pArgs)
if (pArgs->Count () == 3)
{
SFX_REQUEST_ARG (rReq, pWidth, SfxUInt32Item, ID_VAL_PAGEWIDTH, sal_False);
SFX_REQUEST_ARG (rReq, pHeight, SfxUInt32Item, ID_VAL_PAGEHEIGHT, sal_False);
SFX_REQUEST_ARG (rReq, pScaleAll, SfxBoolItem, ID_VAL_SCALEOBJECTS, sal_False);
Size aSize (pWidth->GetValue (), pHeight->GetValue ());
SetupPage (aSize, 0, 0, 0, 0, sal_True, sal_False, pScaleAll->GetValue ());
rReq.Ignore ();
break;
}
StarBASIC::FatalError (SbERR_WRONG_ARGS);
rReq.Ignore ();
break;
}
case SID_PAGEMARGIN : // oder dieses (kein menueeintrag o. ae. !!)
{
const SfxItemSet *pArgs = rReq.GetArgs ();
if (pArgs)
if (pArgs->Count () == 5)
{
SFX_REQUEST_ARG (rReq, pLeft, SfxUInt32Item, ID_VAL_PAGELEFT, sal_False);
SFX_REQUEST_ARG (rReq, pRight, SfxUInt32Item, ID_VAL_PAGERIGHT, sal_False);
SFX_REQUEST_ARG (rReq, pUpper, SfxUInt32Item, ID_VAL_PAGETOP, sal_False);
SFX_REQUEST_ARG (rReq, pLower, SfxUInt32Item, ID_VAL_PAGEBOTTOM, sal_False);
SFX_REQUEST_ARG (rReq, pScaleAll, SfxBoolItem, ID_VAL_SCALEOBJECTS, sal_False);
Size aEmptySize (0, 0);
SetupPage (aEmptySize, pLeft->GetValue (), pRight->GetValue (),
pUpper->GetValue (), pLower->GetValue (),
sal_False, sal_True, pScaleAll->GetValue ());
rReq.Ignore ();
break;
}
StarBASIC::FatalError (SbERR_WRONG_ARGS);
rReq.Ignore ();
break;
}
case SID_ATTR_ZOOMSLIDER:
{
const SfxItemSet* pArgs = rReq.GetArgs();
if (pArgs && pArgs->Count () == 1 )
{
SFX_REQUEST_ARG (rReq, pScale, SfxUInt16Item, SID_ATTR_ZOOMSLIDER, sal_False);
if (CHECK_RANGE (5, pScale->GetValue (), 3000))
{
SetZoom (pScale->GetValue ());
SfxBindings& rBindings = GetViewFrame()->GetBindings();
rBindings.Invalidate( SID_ATTR_ZOOM );
rBindings.Invalidate( SID_ZOOM_IN );
rBindings.Invalidate( SID_ZOOM_OUT );
rBindings.Invalidate( SID_ATTR_ZOOMSLIDER );
}
}
Cancel();
rReq.Done ();
break;
}
case SID_ZOOMING : // kein Menueintrag, sondern aus dem Zoomdialog generiert
{
const SfxItemSet* pArgs = rReq.GetArgs();
if (pArgs)
if (pArgs->Count () == 1)
{
SFX_REQUEST_ARG (rReq, pScale, SfxUInt32Item, ID_VAL_ZOOM, sal_False);
if (CHECK_RANGE (10, pScale->GetValue (), 1000))
{
SetZoom (pScale->GetValue ());
SfxBindings& rBindings = GetViewFrame()->GetBindings();
rBindings.Invalidate( SID_ATTR_ZOOM );
rBindings.Invalidate( SID_ZOOM_IN );
rBindings.Invalidate( SID_ZOOM_OUT );
rBindings.Invalidate( SID_ATTR_ZOOMSLIDER );
}
else StarBASIC::FatalError (SbERR_BAD_PROP_VALUE);
rReq.Ignore ();
break;
}
StarBASIC::FatalError (SbERR_WRONG_ARGS);
rReq.Ignore ();
break;
}
case SID_ATTR_ZOOM:
{
const SfxItemSet* pArgs = rReq.GetArgs();
mbZoomOnPage = sal_False;
if ( pArgs )
{
SvxZoomType eZT = ( ( const SvxZoomItem& ) pArgs->
Get( SID_ATTR_ZOOM ) ).GetType();
switch( eZT )
{
case SVX_ZOOM_PERCENT:
SetZoom( (long) ( ( const SvxZoomItem& ) pArgs->
Get( SID_ATTR_ZOOM ) ).GetValue() );
break;
case SVX_ZOOM_OPTIMAL:
GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_ALL,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
break;
case SVX_ZOOM_PAGEWIDTH:
GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_PAGE_WIDTH,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
break;
case SVX_ZOOM_WHOLEPAGE:
GetViewFrame()->GetDispatcher()->Execute( SID_SIZE_PAGE,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
break;
case SVX_ZOOM_PAGEWIDTH_NOBORDER:
DBG_ERROR("sd::DrawViewShell::FuTemporary(), SVX_ZOOM_PAGEWIDTH_NOBORDER not handled!" );
break;
}
rReq.Ignore ();
}
else
{
// hier den Zoom-Dialog oeffnen
SetCurrentFunction( FuScale::Create( this, GetActiveWindow(), mpDrawView, GetDoc(), rReq ) );
}
Cancel();
}
break;
case SID_CHANGEBEZIER:
case SID_CHANGEPOLYGON:
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
}
if ( mpDrawView->IsPresObjSelected() )
{
::sd::Window* pWindow = GetActiveWindow();
InfoBox(pWindow, String(SdResId(STR_ACTION_NOTPOSSIBLE) ) ).Execute();
}
else
{
if( rReq.GetSlot() == SID_CHANGEBEZIER )
{
WaitObject aWait( (Window*)GetActiveWindow() );
mpDrawView->ConvertMarkedToPathObj(sal_False);
}
else
{
if( mpDrawView->IsVectorizeAllowed() )
{
SetCurrentFunction( FuVectorize::Create( this, GetActiveWindow(), mpDrawView, GetDoc(), rReq ) );
}
else
{
WaitObject aWait( (Window*)GetActiveWindow() );
mpDrawView->ConvertMarkedToPolyObj(sal_False);
}
}
Invalidate(SID_CHANGEBEZIER);
Invalidate(SID_CHANGEPOLYGON);
}
Cancel();
if( HasCurrentFunction(SID_BEZIER_EDIT) )
{ // ggf. die richtige Editfunktion aktivieren
GetViewFrame()->GetDispatcher()->Execute(SID_SWITCH_POINTEDIT,
SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}
rReq.Ignore ();
break;
case SID_CONVERT_TO_CONTOUR:
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
}
if ( mpDrawView->IsPresObjSelected() )
{
::sd::Window* pWindow = GetActiveWindow();
InfoBox(pWindow, String(SdResId(STR_ACTION_NOTPOSSIBLE) ) ).Execute();
}
else
{
WaitObject aWait( (Window*)GetActiveWindow() );
mpDrawView->ConvertMarkedToPathObj(sal_True);
Invalidate(SID_CONVERT_TO_CONTOUR);
}
Cancel();
rReq.Ignore ();
break;
case SID_CONVERT_TO_METAFILE:
case SID_CONVERT_TO_BITMAP:
{
// End text edit mode when it is active because the metafile or
// bitmap that will be created does not support it.
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
}
if ( mpDrawView->IsPresObjSelected(true,true,true) )
{
::sd::Window* pWindow = GetActiveWindow();
InfoBox(pWindow, String(SdResId(STR_ACTION_NOTPOSSIBLE) ) ).Execute();
}
else
{
WaitObject aWait( (Window*)GetActiveWindow() );
// switch on undo for the next operations
mpDrawView->BegUndo(
String(
SdResId (nSId==SID_CONVERT_TO_METAFILE ? STR_UNDO_CONVERT_TO_METAFILE : STR_UNDO_CONVERT_TO_BITMAP)));
// create SdrGrafObj from metafile/bitmap
Graphic aGraphic;
switch (nSId)
{
case SID_CONVERT_TO_METAFILE:
{
GDIMetaFile aMetaFile(mpDrawView->GetMarkedObjMetaFile());
aGraphic = Graphic(aMetaFile);
}
break;
case SID_CONVERT_TO_BITMAP:
{
bool bDone(false);
// I have to get the image here directly since GetMarkedObjBitmapEx works
// based on Bitmaps, but not on BitmapEx, thus throwing away the alpha
// channel. Argh! GetMarkedObjBitmapEx itself is too widely used to safely
// change that, e.g. in the exchange formats. For now I can only add this
// exception to get good results for Svgs. This is how the code gets more
// and more crowded, at last I made a remark for myself to change this
// as one of the next tasks.
if(1 == mpDrawView->GetMarkedObjectCount())
{
const SdrGrafObj* pSdrGrafObj = dynamic_cast< const SdrGrafObj* >(mpDrawView->GetMarkedObjectByIndex(0));
if(pSdrGrafObj && pSdrGrafObj->isEmbeddedSvg())
{
aGraphic = Graphic(pSdrGrafObj->GetGraphic().getSvgData()->getReplacement());
bDone = true;
}
}
if(!bDone)
{
aGraphic = Graphic(mpDrawView->GetMarkedObjBitmapEx());
}
}
break;
}
// create new object
SdrGrafObj* pGraphicObj = new SdrGrafObj (aGraphic);
// get some necessary info and ensure it
const SdrMarkList& rMarkList(mpDrawView->GetMarkedObjectList());
const sal_uInt32 nMarkCount(rMarkList.GetMarkCount());
SdrPageView* pPageView = mpDrawView->GetSdrPageView();
OSL_ENSURE(nMarkCount, "DrawViewShell::FuTemporary: SID_CONVERT_TO_BITMAP with empty selection (!)");
OSL_ENSURE(pPageView, "DrawViewShell::FuTemporary: SID_CONVERT_TO_BITMAP without SdrPageView (!)");
// fit rectangle of new graphic object to selection's mark rect
Rectangle aAllMarkedRect;
rMarkList.TakeBoundRect(pPageView, aAllMarkedRect);
pGraphicObj->SetLogicRect(aAllMarkedRect);
// #i71540# to keep the order, it is necessary to replace the lowest object
// of the selection with the new object. This also means that with multi
// selection, all other objects need to be deleted first
SdrMark* pFirstMark = rMarkList.GetMark(0L);
SdrObject* pReplacementCandidate = pFirstMark->GetMarkedSdrObj();
if(nMarkCount > 1L)
{
// take first object out of selection
mpDrawView->MarkObj(pReplacementCandidate, pPageView, true, true);
// clear remaining selection
mpDrawView->DeleteMarkedObj();
}
// #124816# copy layer from lowest object which gets replaced
pGraphicObj->SetLayer(pReplacementCandidate->GetLayer());
// now replace lowest object with new one
mpDrawView->ReplaceObjectAtView(pReplacementCandidate, *pPageView, pGraphicObj);
// switch off undo
mpDrawView->EndUndo();
}
}
Cancel();
rReq.Done ();
break;
case SID_SET_DEFAULT:
{
SfxItemSet* pSet = NULL;
if (mpDrawView->IsTextEdit())
{
::Outliner* pOutl = mpDrawView->GetTextEditOutliner();
if (pOutl)
{
pOutl->RemoveFields(sal_True, (TypeId) SvxURLField::StaticType());
}
pSet = new SfxItemSet( GetPool(), EE_ITEMS_START, EE_ITEMS_END );
mpDrawView->SetAttributes( *pSet, sal_True );
}
else
{
const SdrMarkList& rMarkList = mpDrawView->GetMarkedObjectList();
sal_uLong nCount = rMarkList.GetMarkCount();
// In diese Liste werden fuer jedes Praesentationsobjekt ein SfxItemSet
// der harten Attribute sowie der UserCall eingetragen, da diese beim nachfolgenden
// mpDrawView->SetAttributes( *pSet, sal_True ) verloren gehen und spaeter restauriert
// werden muessen
List* pAttrList = new List();
SdPage* pPresPage = (SdPage*) mpDrawView->GetSdrPageView()->GetPage();
sal_uLong i;
for ( i = 0; i < nCount; i++ )
{
SdrObject* pObj = rMarkList.GetMark(i)->GetMarkedSdrObj();
if( pPresPage->IsPresObj( pObj ) )
{
SfxItemSet* pNewSet = new SfxItemSet( GetDoc()->GetPool(), SDRATTR_TEXT_MINFRAMEHEIGHT, SDRATTR_TEXT_AUTOGROWHEIGHT, 0 );
pNewSet->Put(pObj->GetMergedItemSet());
pAttrList->Insert( pNewSet, LIST_APPEND );
pAttrList->Insert( pObj->GetUserCall(), LIST_APPEND );
}
}
pSet = new SfxItemSet( GetPool() );
mpDrawView->SetAttributes( *pSet, sal_True );
sal_uLong j = 0;
for ( i = 0; i < nCount; i++ )
{
SfxStyleSheet* pSheet = NULL;
SdrObject* pObj = rMarkList.GetMark(i)->GetMarkedSdrObj();
if (pObj->GetObjIdentifier() == OBJ_TITLETEXT)
{
pSheet = mpActualPage->GetStyleSheetForPresObj(PRESOBJ_TITLE);
if (pSheet)
pObj->SetStyleSheet(pSheet, sal_False);
}
else if(pObj->GetObjIdentifier() == OBJ_OUTLINETEXT)
{
for (sal_uInt16 nLevel = 1; nLevel < 10; nLevel++)
{
pSheet = mpActualPage->GetStyleSheetForPresObj( PRESOBJ_OUTLINE );
DBG_ASSERT(pSheet, "Vorlage fuer Gliederungsobjekt nicht gefunden");
if (pSheet)
{
pObj->StartListening(*pSheet);
if( nLevel == 1 )
// Textrahmen hoert auf StyleSheet der Ebene1
pObj->NbcSetStyleSheet(pSheet, sal_False);
}
}
}
if( pPresPage->IsPresObj( pObj ) )
{
SfxItemSet* pNewSet = (SfxItemSet*) pAttrList->GetObject(j++);
SdrObjUserCall* pUserCall = (SdrObjUserCall*) pAttrList->GetObject(j++);
if ( pNewSet && pNewSet->GetItemState( SDRATTR_TEXT_MINFRAMEHEIGHT ) == SFX_ITEM_ON )
{
pObj->SetMergedItem(pNewSet->Get(SDRATTR_TEXT_MINFRAMEHEIGHT));
}
if ( pNewSet && pNewSet->GetItemState( SDRATTR_TEXT_AUTOGROWHEIGHT ) == SFX_ITEM_ON )
{
pObj->SetMergedItem(pNewSet->Get(SDRATTR_TEXT_AUTOGROWHEIGHT));
}
if( pUserCall )
pObj->SetUserCall( pUserCall );
delete pNewSet;
}
}
delete pAttrList;
}
delete pSet;
Cancel();
}
break;
case SID_DELETE_SNAPITEM:
{
SdrPageView* pPV;
Point aMPos = GetActiveWindow()->PixelToLogic( maMousePos );
sal_uInt16 nHitLog = (sal_uInt16) GetActiveWindow()->PixelToLogic( Size(
FuPoor::HITPIX, 0 ) ).Width();
sal_uInt16 nHelpLine;
mbMousePosFreezed = sal_False;
if( mpDrawView->PickHelpLine( aMPos, nHitLog, *GetActiveWindow(), nHelpLine, pPV) )
{
pPV->DeleteHelpLine( nHelpLine );
}
Cancel();
rReq.Ignore ();
}
break;
case SID_DELETE_PAGE:
case SID_DELETE_MASTER_PAGE:
DeleteActualPage();
Cancel();
rReq.Ignore ();
break;
case SID_DELETE_LAYER:
DeleteActualLayer();
Cancel();
rReq.Ignore ();
break;
case SID_ORIGINAL_SIZE:
mpDrawView->SetMarkedOriginalSize();
Cancel();
rReq.Done();
break;
case SID_DRAW_FONTWORK:
case SID_DRAW_FONTWORK_VERTICAL:
{
svx::FontworkBar::execute( mpView, rReq, GetViewFrame()->GetBindings() ); // SJ: can be removed (I think)
Cancel();
rReq.Done();
}
break;
case SID_SAVEGRAPHIC:
{
const SdrMarkList& rMarkList = mpDrawView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrGrafObj *pGrafObj = dynamic_cast< SdrGrafObj* >( rMarkList.GetMark( 0 )->GetMarkedSdrObj() );
if(pGrafObj )
{
::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > xShape( pGrafObj->getUnoShape(), com::sun::star::uno::UNO_QUERY );
SdGRFFilter::SaveGraphic( xShape );
}
}
Cancel();
rReq.Ignore();
}
break;
default:
{
// switch Anweisung wegen CLOOKS aufgeteilt. Alle case-Anweisungen die
// eine Fu???? -Funktion aufrufen, sind in die Methode FuTemp01 (drviews8)
// gewandert.
FuTemp01(rReq);
}
break;
}
if(HasCurrentFunction())
{
GetCurrentFunction()->Activate();
}
}
void DrawViewShell::ExecChar( SfxRequest &rReq )
{
SdDrawDocument* pDoc = GetDoc();
if (!pDoc || !mpDrawView)
return;
SfxItemSet aEditAttr( pDoc->GetPool() );
mpDrawView->GetAttributes( aEditAttr );
//modified by wj for sym2_1580, if put old itemset into new set,
//when mpDrawView->SetAttributes(aNewAttr) it will invalidate all the item
// and use old attr to update all the attributes
// SfxItemSet aNewAttr( GetPool(),
// EE_ITEMS_START, EE_ITEMS_END );
// aNewAttr.Put( aEditAttr, sal_False );
SfxItemSet aNewAttr( pDoc->GetPool() );
//modified end
sal_uInt16 nSId = rReq.GetSlot();
MapSlot( nSId );
switch ( nSId )
{
case SID_ATTR_CHAR_FONT:
if( rReq.GetArgs() )
{
SFX_REQUEST_ARG( rReq, pItem, SvxFontItem, SID_ATTR_CHAR_FONT , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_FONTHEIGHT:
if( rReq.GetArgs() )
{
SFX_REQUEST_ARG( rReq, pItem, SvxFontHeightItem, SID_ATTR_CHAR_FONTHEIGHT , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_WEIGHT:
if( rReq.GetArgs() )
{
//const SvxWeightItem *pItem = (const SvxWeightItem*) rReq.GetArg( SID_ATTR_CHAR_WEIGHT, sal_False, TYPE(SvxWeightItem) );
SFX_REQUEST_ARG( rReq, pItem, SvxWeightItem, SID_ATTR_CHAR_WEIGHT , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_POSTURE:
if( rReq.GetArgs() )
{
//const SvxPostureItem *pItem = (const SvxPostureItem*) rReq.GetArg( SID_ATTR_CHAR_POSTURE, sal_False, TYPE(SvxPostureItem) );
SFX_REQUEST_ARG( rReq, pItem, SvxPostureItem, SID_ATTR_CHAR_POSTURE , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_UNDERLINE:
if( rReq.GetArgs() )
{
//<<modify by wj for sym2_1873
//SFX_REQUEST_ARG( rReq, pItem, SvxTextLineItem, SID_ATTR_CHAR_UNDERLINE , sal_False );
SFX_REQUEST_ARG( rReq, pItem, SvxUnderlineItem, SID_ATTR_CHAR_UNDERLINE , sal_False );
//end>>
if (pItem)
{
aNewAttr.Put(*pItem);
}
else
{
FontUnderline eFU = ( (const SvxUnderlineItem&) aEditAttr.Get( EE_CHAR_UNDERLINE ) ).GetLineStyle();
aNewAttr.Put( SvxUnderlineItem( eFU != UNDERLINE_NONE ?UNDERLINE_NONE : UNDERLINE_SINGLE, EE_CHAR_UNDERLINE ) );
}//aNewAttr.Put( (const SvxUnderlineItem&)aEditAttr.Get( EE_CHAR_UNDERLINE ) );
}
break;
case SID_ATTR_CHAR_SHADOWED:
if( rReq.GetArgs() )
{
SFX_REQUEST_ARG( rReq, pItem, SvxShadowedItem, SID_ATTR_CHAR_SHADOWED , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_STRIKEOUT:
if( rReq.GetArgs() )
{
SFX_REQUEST_ARG( rReq, pItem, SvxCrossedOutItem, SID_ATTR_CHAR_STRIKEOUT , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_COLOR:
if( rReq.GetArgs() )
{
SFX_REQUEST_ARG( rReq, pItem, SvxColorItem, SID_ATTR_CHAR_COLOR , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_ATTR_CHAR_KERNING:
if( rReq.GetArgs() )
{
SFX_REQUEST_ARG( rReq, pItem, SvxKerningItem, SID_ATTR_CHAR_KERNING , sal_False );
if (pItem)
{
aNewAttr.Put(*pItem);
}
}
break;
case SID_SET_SUB_SCRIPT:
if( rReq.GetArgs() )
{
SvxEscapementItem aItem( EE_CHAR_ESCAPEMENT );
SvxEscapement eEsc = (SvxEscapement ) ( (const SvxEscapementItem&)
aEditAttr.Get( EE_CHAR_ESCAPEMENT ) ).GetEnumValue();
if( eEsc == SVX_ESCAPEMENT_SUBSCRIPT )
aItem.SetEscapement( SVX_ESCAPEMENT_OFF );
else
aItem.SetEscapement( SVX_ESCAPEMENT_SUBSCRIPT );
aNewAttr.Put( aItem );
}
break;
case SID_SET_SUPER_SCRIPT:
if( rReq.GetArgs() )
{
SvxEscapementItem aItem( EE_CHAR_ESCAPEMENT );
SvxEscapement eEsc = (SvxEscapement ) ( (const SvxEscapementItem&)
aEditAttr.Get( EE_CHAR_ESCAPEMENT ) ).GetEnumValue();
if( eEsc == SVX_ESCAPEMENT_SUPERSCRIPT )
aItem.SetEscapement( SVX_ESCAPEMENT_OFF );
else
aItem.SetEscapement( SVX_ESCAPEMENT_SUPERSCRIPT );
aNewAttr.Put( aItem );
}
break;
case SID_SHRINK_FONT_SIZE:
case SID_GROW_FONT_SIZE:
//if (rReq.GetArgs())
{
const SvxFontListItem* pFonts = dynamic_cast<const SvxFontListItem*>(GetDocSh()->GetItem( SID_ATTR_CHAR_FONTLIST ) );
const FontList* pFontList = pFonts->GetFontList();
if( pFontList )
{
FuText::ChangeFontSize( nSId == SID_GROW_FONT_SIZE, NULL, pFontList, mpView );
GetViewFrame()->GetBindings().Invalidate( SID_ATTR_CHAR_FONTHEIGHT );
}
}
default:
;
}
mpDrawView->SetAttributes(aNewAttr);
rReq.Done();
Cancel();
}
/** This method consists basically of three parts:
1. Process the arguments of the SFX request.
2. Use the model to create a new page or duplicate an existing one.
3. Update the tab control and switch to the new page.
*/
SdPage* DrawViewShell::CreateOrDuplicatePage (
SfxRequest& rRequest,
PageKind ePageKind,
SdPage* pPage,
const sal_Int32 nInsertPosition)
{
SdPage* pNewPage = NULL;
if (ePageKind == PK_STANDARD && meEditMode != EM_MASTERPAGE)
{
if ( mpDrawView->IsTextEdit() )
{
mpDrawView->SdrEndTextEdit();
}
pNewPage = ViewShell::CreateOrDuplicatePage (rRequest, ePageKind, pPage, nInsertPosition);
}
return pNewPage;
}
void DrawViewShell::ExecutePropPanelAttr (SfxRequest& rReq)
{
if(SlideShow::IsRunning( GetViewShellBase() ))
return;
SdDrawDocument* pDoc = GetDoc();
if (!pDoc || !mpDrawView)
return;
sal_uInt16 nSId = rReq.GetSlot();
SfxItemSet aAttrs( pDoc->GetPool() );
switch ( nSId )
{
case SID_TABLE_VERT_NONE:
case SID_TABLE_VERT_CENTER:
case SID_TABLE_VERT_BOTTOM:
SdrTextVertAdjust eTVA = SDRTEXTVERTADJUST_TOP;
if (nSId == SID_TABLE_VERT_CENTER)
eTVA = SDRTEXTVERTADJUST_CENTER;
else if (nSId == SID_TABLE_VERT_BOTTOM)
eTVA = SDRTEXTVERTADJUST_BOTTOM;
aAttrs.Put( SdrTextVertAdjustItem(eTVA) );
mpDrawView->SetAttributes(aAttrs);
break;
}
}
void DrawViewShell::GetStatePropPanelAttr(SfxItemSet& rSet)
{
SfxWhichIter aIter( rSet );
sal_uInt16 nWhich = aIter.FirstWhich();
SdDrawDocument* pDoc = GetDoc();
if (!pDoc || !mpDrawView)
return;
SfxItemSet aAttrs( pDoc->GetPool() );
mpDrawView->GetAttributes( aAttrs );
while ( nWhich )
{
sal_uInt16 nSlotId = SfxItemPool::IsWhich(nWhich)
? GetPool().GetSlotId(nWhich)
: nWhich;
switch ( nSlotId )
{
case SID_TABLE_VERT_NONE:
case SID_TABLE_VERT_CENTER:
case SID_TABLE_VERT_BOTTOM:
sal_Bool bContour = sal_False;
SfxItemState eConState = aAttrs.GetItemState( SDRATTR_TEXT_CONTOURFRAME );
if( eConState != SFX_ITEM_DONTCARE )
{
bContour = ( ( const SdrTextContourFrameItem& )aAttrs.Get( SDRATTR_TEXT_CONTOURFRAME ) ).GetValue();
}
if (bContour) break;
SfxItemState eVState = aAttrs.GetItemState( SDRATTR_TEXT_VERTADJUST );
//SfxItemState eHState = aAttrs.GetItemState( SDRATTR_TEXT_HORZADJUST );
//if(SFX_ITEM_DONTCARE != eVState && SFX_ITEM_DONTCARE != eHState)
if(SFX_ITEM_DONTCARE != eVState)
{
SdrTextVertAdjust eTVA = (SdrTextVertAdjust)((const SdrTextVertAdjustItem&)aAttrs.Get(SDRATTR_TEXT_VERTADJUST)).GetValue();
sal_Bool bSet = nSlotId == SID_TABLE_VERT_NONE && eTVA == SDRTEXTVERTADJUST_TOP||
nSlotId == SID_TABLE_VERT_CENTER && eTVA == SDRTEXTVERTADJUST_CENTER ||
nSlotId == SID_TABLE_VERT_BOTTOM && eTVA == SDRTEXTVERTADJUST_BOTTOM;
rSet.Put(SfxBoolItem(nSlotId, bSet));
}
else
{
rSet.Put(SfxBoolItem(nSlotId, sal_False));
}
break;
}
nWhich = aIter.NextWhich();
}
}
} // end of namespace sd
| 29.069847 | 141 | 0.648324 | [
"object",
"model"
] |
c88b8085803c71133585eab9b9ca6e9a0772ad3f | 3,771 | cpp | C++ | 3rdparty/glslang/SPIRV/CInterface/spirv_c_interface.cpp | christiancoder/bgfx | b96deb1cecbd92b2ca46d7266499839069d6ba6a | [
"BSD-2-Clause"
] | 166 | 2019-06-19T19:51:45.000Z | 2022-03-24T13:03:29.000Z | 3rdparty/glslang/SPIRV/CInterface/spirv_c_interface.cpp | christiancoder/bgfx | b96deb1cecbd92b2ca46d7266499839069d6ba6a | [
"BSD-2-Clause"
] | 312 | 2019-06-13T19:39:25.000Z | 2022-03-02T18:37:22.000Z | 3rdparty/glslang/SPIRV/CInterface/spirv_c_interface.cpp | christiancoder/bgfx | b96deb1cecbd92b2ca46d7266499839069d6ba6a | [
"BSD-2-Clause"
] | 23 | 2019-10-04T11:02:21.000Z | 2021-12-24T16:34:52.000Z | /**
This code is based on the glslang_c_interface implementation by Viktor Latypov
**/
/**
BSD 2-Clause License
Copyright (c) 2019, Viktor Latypov
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.
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 HOLDER 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 "glslang/Include/glslang_c_interface.h"
#include "SPIRV/GlslangToSpv.h"
#include "SPIRV/Logger.h"
#include "SPIRV/SpvTools.h"
typedef struct glslang_program_s {
glslang::TProgram* program;
std::vector<unsigned int> spirv;
std::string loggerMessages;
} glslang_program_t;
static EShLanguage c_shader_stage(glslang_stage_t stage)
{
switch (stage) {
case GLSLANG_STAGE_VERTEX:
return EShLangVertex;
case GLSLANG_STAGE_TESSCONTROL:
return EShLangTessControl;
case GLSLANG_STAGE_TESSEVALUATION:
return EShLangTessEvaluation;
case GLSLANG_STAGE_GEOMETRY:
return EShLangGeometry;
case GLSLANG_STAGE_FRAGMENT:
return EShLangFragment;
case GLSLANG_STAGE_COMPUTE:
return EShLangCompute;
case GLSLANG_STAGE_RAYGEN_NV:
return EShLangRayGen;
case GLSLANG_STAGE_INTERSECT_NV:
return EShLangIntersect;
case GLSLANG_STAGE_ANYHIT_NV:
return EShLangAnyHit;
case GLSLANG_STAGE_CLOSESTHIT_NV:
return EShLangClosestHit;
case GLSLANG_STAGE_MISS_NV:
return EShLangMiss;
case GLSLANG_STAGE_CALLABLE_NV:
return EShLangCallable;
case GLSLANG_STAGE_TASK_NV:
return EShLangTaskNV;
case GLSLANG_STAGE_MESH_NV:
return EShLangMeshNV;
default:
break;
}
return EShLangCount;
}
void glslang_program_SPIRV_generate(glslang_program_t* program, glslang_stage_t stage)
{
spv::SpvBuildLogger logger;
glslang::SpvOptions spvOptions;
spvOptions.validate = true;
const glslang::TIntermediate* intermediate = program->program->getIntermediate(c_shader_stage(stage));
glslang::GlslangToSpv(*intermediate, program->spirv, &logger, &spvOptions);
program->loggerMessages = logger.getAllMessages();
}
size_t glslang_program_SPIRV_get_size(glslang_program_t* program) { return program->spirv.size(); }
void glslang_program_SPIRV_get(glslang_program_t* program, unsigned int* out)
{
memcpy(out, program->spirv.data(), program->spirv.size() * sizeof(unsigned int));
}
unsigned int* glslang_program_SPIRV_get_ptr(glslang_program_t* program)
{
return program->spirv.data();
}
const char* glslang_program_SPIRV_get_messages(glslang_program_t* program)
{
return program->loggerMessages.empty() ? nullptr : program->loggerMessages.c_str();
}
| 33.972973 | 106 | 0.765845 | [
"vector"
] |
c891edf78b288836a6b7110e8873fac51e1ef484 | 1,336 | cpp | C++ | logdevice/test/utils/nc.cpp | dmitris/LogDevice | 18336bb95262c51d9b1e8f2f9ae9ad0874b023cd | [
"BSD-3-Clause"
] | null | null | null | logdevice/test/utils/nc.cpp | dmitris/LogDevice | 18336bb95262c51d9b1e8f2f9ae9ad0874b023cd | [
"BSD-3-Clause"
] | null | null | null | logdevice/test/utils/nc.cpp | dmitris/LogDevice | 18336bb95262c51d9b1e8f2f9ae9ad0874b023cd | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/test/utils/nc.h"
#include "logdevice/common/debug.h"
#include "logdevice/ops/py_extensions/admin_command_client/AdminCommandClient.h"
namespace facebook { namespace logdevice { namespace test {
std::string nc(const std::shared_ptr<AdminCommandClient>& adminclient,
const folly::SocketAddress& addr,
const std::string& input,
std::string* out_error,
bool ssl,
std::chrono::milliseconds command_timeout,
std::chrono::milliseconds connect_timeout) {
std::vector<AdminCommandClient::Request> rr;
rr.emplace_back(addr,
input,
ssl ? AdminCommandClient::ConnectionType::ENCRYPTED
: AdminCommandClient::ConnectionType::PLAIN);
auto response = adminclient->send(rr, command_timeout, connect_timeout);
ld_check_eq(1, response.size());
if (out_error && !response[0].success) {
*out_error = response[0].failure_reason;
}
return response[0].success ? response[0].response : "";
}
}}} // namespace facebook::logdevice::test
| 34.25641 | 80 | 0.669162 | [
"vector"
] |
c894de8360eee1746236921c3af45dabdb73aec9 | 90,306 | cpp | C++ | src/mongo/db/query/index_bounds_builder_test.cpp | hgGeorg/mongo | b5bea92504b2612f433b55e7b901f9ae276d11ec | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/index_bounds_builder_test.cpp | hgGeorg/mongo | b5bea92504b2612f433b55e7b901f9ae276d11ec | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/index_bounds_builder_test.cpp | hgGeorg/mongo | b5bea92504b2612f433b55e7b901f9ae276d11ec | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/query/index_bounds_builder.h"
#include <limits>
#include <memory>
#include "mongo/db/json.h"
#include "mongo/db/matcher/expression_parser.h"
#include "mongo/db/matcher/extensions_callback_disallow_extensions.h"
#include "mongo/db/query/collation/collator_interface_mock.h"
#include "mongo/db/query/expression_index.h"
#include "mongo/unittest/unittest.h"
using namespace mongo;
namespace {
using std::unique_ptr;
using std::numeric_limits;
using std::string;
using std::vector;
double numberMin = -numeric_limits<double>::max();
double numberMax = numeric_limits<double>::max();
double negativeInfinity = -numeric_limits<double>::infinity();
double positiveInfinity = numeric_limits<double>::infinity();
double NaN = numeric_limits<double>::quiet_NaN();
/**
* Utility function to create MatchExpression
*/
MatchExpression* parseMatchExpression(const BSONObj& obj) {
const CollatorInterface* collator = nullptr;
StatusWithMatchExpression status =
MatchExpressionParser::parse(obj, ExtensionsCallbackDisallowExtensions(), collator);
ASSERT_TRUE(status.isOK());
MatchExpression* expr(status.getValue().release());
return expr;
}
/**
* Given a list of queries in 'toUnion', translate into index bounds and return
* the union of these bounds in the out-parameter 'oilOut'.
*/
void testTranslateAndUnion(const vector<BSONObj>& toUnion,
OrderedIntervalList* oilOut,
IndexBoundsBuilder::BoundsTightness* tightnessOut) {
IndexEntry testIndex = IndexEntry(BSONObj());
for (vector<BSONObj>::const_iterator it = toUnion.begin(); it != toUnion.end(); ++it) {
unique_ptr<MatchExpression> expr(parseMatchExpression(*it));
BSONElement elt = it->firstElement();
if (toUnion.begin() == it) {
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, oilOut, tightnessOut);
} else {
IndexBoundsBuilder::translateAndUnion(expr.get(), elt, testIndex, oilOut, tightnessOut);
}
}
}
/**
* Given a list of queries in 'toUnion', translate into index bounds and return
* the intersection of these bounds in the out-parameter 'oilOut'.
*/
void testTranslateAndIntersect(const vector<BSONObj>& toIntersect,
OrderedIntervalList* oilOut,
IndexBoundsBuilder::BoundsTightness* tightnessOut) {
IndexEntry testIndex = IndexEntry(BSONObj());
for (vector<BSONObj>::const_iterator it = toIntersect.begin(); it != toIntersect.end(); ++it) {
unique_ptr<MatchExpression> expr(parseMatchExpression(*it));
BSONElement elt = it->firstElement();
if (toIntersect.begin() == it) {
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, oilOut, tightnessOut);
} else {
IndexBoundsBuilder::translateAndIntersect(
expr.get(), elt, testIndex, oilOut, tightnessOut);
}
}
}
/**
* 'constraints' is a vector of BSONObj's representing match expressions, where
* each filter is paired with a boolean. If the boolean is true, then the filter's
* index bounds should be intersected with the other constraints; if false, then
* they should be unioned. The resulting bounds are returned in the
* out-parameter 'oilOut'.
*/
void testTranslate(const vector<std::pair<BSONObj, bool>>& constraints,
OrderedIntervalList* oilOut,
IndexBoundsBuilder::BoundsTightness* tightnessOut) {
IndexEntry testIndex = IndexEntry(BSONObj());
for (vector<std::pair<BSONObj, bool>>::const_iterator it = constraints.begin();
it != constraints.end();
++it) {
BSONObj obj = it->first;
bool isIntersect = it->second;
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
if (constraints.begin() == it) {
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, oilOut, tightnessOut);
} else if (isIntersect) {
IndexBoundsBuilder::translateAndIntersect(
expr.get(), elt, testIndex, oilOut, tightnessOut);
} else {
IndexBoundsBuilder::translateAndUnion(expr.get(), elt, testIndex, oilOut, tightnessOut);
}
}
}
/**
* run isSingleInterval and return the result to calling test.
*/
bool testSingleInterval(IndexBounds bounds) {
BSONObj startKey;
bool startKeyIn;
BSONObj endKey;
bool endKeyIn;
return IndexBoundsBuilder::isSingleInterval(bounds, &startKey, &startKeyIn, &endKey, &endKeyIn);
}
//
// $elemMatch value
// Example: {a: {$elemMatch: {$gt: 2}}}
//
TEST(IndexBoundsBuilderTest, TranslateElemMatchValue) {
IndexEntry testIndex = IndexEntry(BSONObj());
// Bounds generated should be the same as the embedded expression
// except for the tightness.
BSONObj obj = fromjson("{a: {$elemMatch: {$gt: 2}}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 2, '': Infinity}"), false, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_FETCH);
}
//
// Comparison operators ($lte, $lt, $gt, $gte, $eq)
//
TEST(IndexBoundsBuilderTest, TranslateLteNumber) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$lte: 1}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': 1}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLteNumberMin) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << BSON("$lte" << numberMin));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(BSON("" << negativeInfinity << "" << numberMin), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLteNegativeInfinity) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$lte: -Infinity}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': -Infinity}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLtNumber) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$lt: 1}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': 1}"), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLtNumberMin) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << BSON("$lt" << numberMin));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(BSON("" << negativeInfinity << "" << numberMin), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLtNegativeInfinity) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$lt: -Infinity}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 0U);
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLtDate) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << LT << Date_t::fromMillisSinceEpoch(5000));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(fromjson("{'': true, '': new Date(5000)}"), false, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtTimestamp) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << GT << Timestamp(2, 3));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
// Constant below is ~0U, or 2**32 - 1, but cannot be written that way in JS
oil.intervals[0].compare(Interval(
fromjson("{'': Timestamp(2, 3), '': Timestamp(4294967295, 4294967295)}"),
false,
true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, TranslateGtNumber) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gt: 1}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': Infinity}"), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtNumberMax) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << BSON("$gt" << numberMax));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(BSON("" << numberMax << "" << positiveInfinity), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtPositiveInfinity) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gt: Infinity}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 0U);
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGteNumber) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gte: 1}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': Infinity}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGteNumberMax) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << BSON("$gte" << numberMax));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(BSON("" << numberMax << "" << positiveInfinity), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtePositiveInfinity) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gte: Infinity}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': Infinity, '': Infinity}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtString) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gt: 'abc'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'abc', '': {}}"), false, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateEqualNan) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: NaN}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': NaN, '': NaN}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLtNan) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$lt: NaN}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 0U);
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLteNan) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$lte: NaN}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': NaN, '': NaN}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtNan) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gt: NaN}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 0U);
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGteNan) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$gte: NaN}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': NaN, '': NaN}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateEqual) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << 4);
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 4, '': 4}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateArrayEqualBasic) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: [1, 2, 3]}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': 1}"), true, true)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': [1, 2, 3], '': [1, 2, 3]}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, TranslateIn) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$in: [8, 44, -1, -3]}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 4U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -3, '': -3}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': -1, '': -1}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[2].compare(Interval(fromjson("{'': 8, '': 8}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[3].compare(Interval(fromjson("{'': 44, '': 44}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateInArray) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$in: [[1], 2]}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 3U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': 1}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': 2, '': 2}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[2].compare(Interval(fromjson("{'': [1], '': [1]}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, TranslateLteBinData) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson(
"{a: {$lte: {$binary: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAA',"
"$type: '00'}}}");
std::unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQ(oil.name, "a");
ASSERT_EQ(oil.intervals.size(), 1U);
ASSERT_EQ(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(fromjson("{'': {$binary: '', $type: '00'},"
"'': {$binary: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAA', $type: '00'}}"),
true,
true)));
ASSERT_EQ(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLtBinData) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson(
"{a: {$lt: {$binary: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAA',"
"$type: '00'}}}");
std::unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQ(oil.name, "a");
ASSERT_EQ(oil.intervals.size(), 1U);
ASSERT_EQ(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(fromjson("{'': {$binary: '', $type: '00'},"
"'': {$binary: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAA', $type: '00'}}"),
true,
false)));
ASSERT_EQ(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGtBinData) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson(
"{a: {$gt: {$binary: '////////////////////////////',"
"$type: '00'}}}");
std::unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQ(oil.name, "a");
ASSERT_EQ(oil.intervals.size(), 1U);
ASSERT_EQ(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(fromjson("{'': {$binary: '////////////////////////////', $type: '00'},"
"'': ObjectId('000000000000000000000000')}"),
false,
false)));
ASSERT_EQ(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGteBinData) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson(
"{a: {$gte: {$binary: '////////////////////////////',"
"$type: '00'}}}");
std::unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQ(oil.name, "a");
ASSERT_EQ(oil.intervals.size(), 1U);
ASSERT_EQ(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(
Interval(fromjson("{'': {$binary: '////////////////////////////', $type: '00'},"
"'': ObjectId('000000000000000000000000')}"),
true,
false)));
ASSERT_EQ(tightness, IndexBoundsBuilder::EXACT);
}
//
// $type
//
TEST(IndexBoundsBuilderTest, TypeNumber) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$type: 'number'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
// Build the expected interval.
BSONObjBuilder bob;
BSONType type = BSONType::NumberInt;
bob.appendMinForType("", type);
bob.appendMaxForType("", type);
BSONObj expectedInterval = bob.obj();
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(expectedInterval, true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
//
// $exists tests
//
TEST(IndexBoundsBuilderTest, ExistsTrue) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$exists: true}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, ExistsFalse) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$exists: false}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': null, '': null}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, ExistsTrueSparse) {
IndexEntry testIndex = IndexEntry(BSONObj(),
false, // multikey
true, // sparse
false, // unique
"exists_true_sparse",
nullptr, // filterExpr
BSONObj());
BSONObj obj = fromjson("{a: {$exists: true}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
//
// Union tests
//
TEST(IndexBoundsBuilderTest, UnionTwoLt) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toUnion;
toUnion.push_back(fromjson("{a: {$lt: 1}}"));
toUnion.push_back(fromjson("{a: {$lt: 5}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndUnion(toUnion, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': 5}"), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, UnionDupEq) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toUnion;
toUnion.push_back(fromjson("{a: 1}"));
toUnion.push_back(fromjson("{a: 5}"));
toUnion.push_back(fromjson("{a: 1}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndUnion(toUnion, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': 1}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': 5, '': 5}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, UnionGtLt) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toUnion;
toUnion.push_back(fromjson("{a: {$gt: 1}}"));
toUnion.push_back(fromjson("{a: {$lt: 3}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndUnion(toUnion, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': Infinity}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, UnionTwoEmptyRanges) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<std::pair<BSONObj, bool>> constraints;
constraints.push_back(std::make_pair(fromjson("{a: {$gt: 1}}"), true));
constraints.push_back(std::make_pair(fromjson("{a: {$lte: 0}}"), true));
constraints.push_back(std::make_pair(fromjson("{a: {$in:[]}}"), false));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslate(constraints, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 0U);
}
//
// Intersection tests
//
TEST(IndexBoundsBuilderTest, IntersectTwoLt) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: {$lt: 1}}"));
toIntersect.push_back(fromjson("{a: {$lt: 5}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': 1}"), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, IntersectEqGte) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: 1}}"));
toIntersect.push_back(fromjson("{a: {$gte: 1}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': 1}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, IntersectGtLte) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: {$gt: 0}}"));
toIntersect.push_back(fromjson("{a: {$lte: 10}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 0, '': 10}"), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, IntersectGtIn) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: {$gt: 4}}"));
toIntersect.push_back(fromjson("{a: {$in: [1,2,3,4,5,6]}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 5, '': 5}"), true, true)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': 6, '': 6}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, IntersectionIsPointInterval) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: {$gte: 1}}"));
toIntersect.push_back(fromjson("{a: {$lte: 1}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 1, '': 1}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, IntersectFullyContained) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: {$gt: 5}}"));
toIntersect.push_back(fromjson("{a: {$lt: 15}}"));
toIntersect.push_back(fromjson("{a: {$gte: 6}}"));
toIntersect.push_back(fromjson("{a: {$lte: 13}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 6, '': 13}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, EmptyIntersection) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: 1}}"));
toIntersect.push_back(fromjson("{a: {$gte: 2}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 0U);
}
//
// $mod
//
TEST(IndexBoundsBuilderTest, TranslateMod) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$mod: [2, 0]}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(BSON("" << NaN << "" << positiveInfinity), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
//
// Test simpleRegex
//
TEST(SimpleRegexTest, RootedLine) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^foo", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "foo");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedString) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("\\Afoo", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "foo");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedOptionalFirstChar) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^f?oo", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedOptionalSecondChar) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^fz?oo", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "f");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedMultiline) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^foo", "m", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedStringMultiline) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("\\Afoo", "m", testIndex, &tightness);
ASSERT_EQUALS(prefix, "foo");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedCaseInsensitiveMulti) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("\\Afoo", "mi", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedComplex) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex(
"\\Af \t\vo\n\ro \\ \\# #comment", "mx", testIndex, &tightness);
ASSERT_EQUALS(prefix, "foo #");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedLiteral) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^\\Qasdf\\E", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "asdf");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedLiteralWithExtra) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^\\Qasdf\\E.*", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "asdf");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedLiteralNoEnd) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^\\Qasdf", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "asdf");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedLiteralBackslash) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^\\Qasdf\\\\E", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "asdf\\");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedLiteralDotStar) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^\\Qas.*df\\E", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "as.*df");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedLiteralNestedEscape) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^\\Qas\\Q[df\\E", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "as\\Q[df");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(SimpleRegexTest, RootedLiteralNestedEscapeEnd) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix =
IndexBoundsBuilder::simpleRegex("^\\Qas\\E\\\\E\\Q$df\\E", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "as\\E$df");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
// A regular expression with the "|" character is not considered simple. See SERVER-15235.
TEST(SimpleRegexTest, PipeCharacterDisallowed) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^(a(a|$)|b", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, PipeCharacterDisallowed2) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^(a(a|$)|^b", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
// SERVER-9035
TEST(SimpleRegexTest, RootedSingleLineMode) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^foo", "s", testIndex, &tightness);
ASSERT_EQUALS(prefix, "foo");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
// SERVER-9035
TEST(SimpleRegexTest, NonRootedSingleLineMode) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("foo", "s", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
// SERVER-9035
TEST(SimpleRegexTest, RootedComplexSingleLineMode) {
IndexEntry testIndex = IndexEntry(BSONObj());
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex(
"\\Af \t\vo\n\ro \\ \\# #comment", "msx", testIndex, &tightness);
ASSERT_EQUALS(prefix, "foo #");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(SimpleRegexTest, RootedRegexCantBeIndexedTightlyIfIndexHasCollation) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
IndexBoundsBuilder::BoundsTightness tightness;
string prefix = IndexBoundsBuilder::simpleRegex("^foo", "", testIndex, &tightness);
ASSERT_EQUALS(prefix, "");
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
//
// Regex bounds
//
TEST(IndexBoundsBuilderTest, SimpleNonPrefixRegex) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: /foo/}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': {}}"), true, false)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': /foo/, '': /foo/}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(IndexBoundsBuilderTest, NonSimpleRegexWithPipe) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: /^foo.*|bar/}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': {}}"), true, false)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(
Interval(fromjson("{'': /^foo.*|bar/, '': /^foo.*|bar/}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_COVERED);
}
TEST(IndexBoundsBuilderTest, SimpleRegexSingleLineMode) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: /^foo/s}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'foo', '': 'fop'}"), true, false)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': /^foo/s, '': /^foo/s}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, SimplePrefixRegex) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: /^foo/}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'foo', '': 'fop'}"), true, false)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': /^foo/, '': /^foo/}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::EXACT);
}
//
// isSingleInterval
//
TEST(IndexBoundsBuilderTest, SingleFieldEqualityInterval) {
// Equality on a single field is a single interval.
OrderedIntervalList oil("a");
IndexBounds bounds;
oil.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
bounds.fields.push_back(oil);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, SingleIntervalSingleFieldInterval) {
// Single interval on a single field is a single interval.
OrderedIntervalList oil("a");
IndexBounds bounds;
oil.intervals.push_back(Interval(fromjson("{ '':5, '':Infinity }"), true, true));
bounds.fields.push_back(oil);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, MultipleIntervalsSingleFieldInterval) {
// Multiple intervals on a single field is not a single interval.
OrderedIntervalList oil("a");
IndexBounds bounds;
oil.intervals.push_back(Interval(fromjson("{ '':4, '':5 }"), true, true));
oil.intervals.push_back(Interval(fromjson("{ '':7, '':Infinity }"), true, true));
bounds.fields.push_back(oil);
ASSERT(!testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualityTwoFieldsInterval) {
// Equality on two fields is a compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(BSON("" << 6 << "" << 6), true, true));
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualityFirstFieldSingleIntervalSecondFieldInterval) {
// Equality on first field and single interval on second field
// is a compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(fromjson("{ '':6, '':Infinity }"), true, true));
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, SingleIntervalFirstAndSecondFieldsInterval) {
// Single interval on first field and single interval on second field is
// not a compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(fromjson("{ '':-Infinity, '':5 }"), true, true));
oil_b.intervals.push_back(Interval(fromjson("{ '':6, '':Infinity }"), true, true));
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
ASSERT(!testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, MultipleIntervalsTwoFieldsInterval) {
// Multiple intervals on two fields is not a compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 4 << "" << 4), true, true));
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(BSON("" << 7 << "" << 7), true, true));
oil_b.intervals.push_back(Interval(BSON("" << 8 << "" << 8), true, true));
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
ASSERT(!testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, MissingSecondFieldInterval) {
// when second field is not specified, still a compound single interval
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(IndexBoundsBuilder::allValues());
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualityTwoFieldsIntervalThirdInterval) {
// Equality on first two fields and single interval on third is a
// compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
OrderedIntervalList oil_c("c");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(BSON("" << 6 << "" << 6), true, true));
oil_c.intervals.push_back(Interval(fromjson("{ '':7, '':Infinity }"), true, true));
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
bounds.fields.push_back(oil_c);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualitySingleIntervalMissingInterval) {
// Equality, then Single Interval, then missing is a compound single interval
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
OrderedIntervalList oil_c("c");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(fromjson("{ '':7, '':Infinity }"), true, true));
oil_c.intervals.push_back(IndexBoundsBuilder::allValues());
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
bounds.fields.push_back(oil_c);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualitySingleMissingMissingInterval) {
// Equality, then single interval, then missing, then missing,
// is a compound single interval
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
OrderedIntervalList oil_c("c");
OrderedIntervalList oil_d("d");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(fromjson("{ '':7, '':Infinity }"), true, true));
oil_c.intervals.push_back(IndexBoundsBuilder::allValues());
oil_d.intervals.push_back(IndexBoundsBuilder::allValues());
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
bounds.fields.push_back(oil_c);
bounds.fields.push_back(oil_d);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualitySingleMissingMissingMixedInterval) {
// Equality, then single interval, then missing, then missing, with mixed order
// fields is a compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
OrderedIntervalList oil_c("c");
OrderedIntervalList oil_d("d");
IndexBounds bounds;
Interval allValues = IndexBoundsBuilder::allValues();
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(fromjson("{ '':7, '':Infinity }"), true, true));
oil_c.intervals.push_back(allValues);
IndexBoundsBuilder::reverseInterval(&allValues);
oil_d.intervals.push_back(allValues);
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
bounds.fields.push_back(oil_c);
bounds.fields.push_back(oil_d);
ASSERT(testSingleInterval(bounds));
}
TEST(IndexBoundsBuilderTest, EqualitySingleMissingSingleInterval) {
// Equality, then single interval, then missing, then single interval is not
// a compound single interval.
OrderedIntervalList oil_a("a");
OrderedIntervalList oil_b("b");
OrderedIntervalList oil_c("c");
OrderedIntervalList oil_d("d");
IndexBounds bounds;
oil_a.intervals.push_back(Interval(BSON("" << 5 << "" << 5), true, true));
oil_b.intervals.push_back(Interval(fromjson("{ '':7, '':Infinity }"), true, true));
oil_c.intervals.push_back(IndexBoundsBuilder::allValues());
oil_d.intervals.push_back(Interval(fromjson("{ '':1, '':Infinity }"), true, true));
bounds.fields.push_back(oil_a);
bounds.fields.push_back(oil_b);
bounds.fields.push_back(oil_c);
bounds.fields.push_back(oil_d);
ASSERT(!testSingleInterval(bounds));
}
//
// Complementing bounds for negations
//
/**
* Get a BSONObj which represents the interval from
* MinKey to 'end'.
*/
BSONObj minKeyIntObj(int end) {
BSONObjBuilder bob;
bob.appendMinKey("");
bob.appendNumber("", end);
return bob.obj();
}
/**
* Get a BSONObj which represents the interval from
* 'start' to MaxKey.
*/
BSONObj maxKeyIntObj(int start) {
BSONObjBuilder bob;
bob.appendNumber("", start);
bob.appendMaxKey("");
return bob.obj();
}
// Expected oil: [MinKey, 3), (3, MaxKey]
TEST(IndexBoundsBuilderTest, SimpleNE) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = BSON("a" << BSON("$ne" << 3));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(minKeyIntObj(3), true, false)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(maxKeyIntObj(3), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, IntersectWithNE) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toIntersect;
toIntersect.push_back(fromjson("{a: {$gt: 1}}"));
toIntersect.push_back(fromjson("{a: {$ne: 2}}}"));
toIntersect.push_back(fromjson("{a: {$lte: 6}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndIntersect(toIntersect, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(BSON("" << 1 << "" << 2), false, false)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(BSON("" << 2 << "" << 6), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, UnionizeWithNE) {
IndexEntry testIndex = IndexEntry(BSONObj());
vector<BSONObj> toUnionize;
toUnionize.push_back(fromjson("{a: {$ne: 3}}"));
toUnionize.push_back(fromjson("{a: {$ne: 4}}}"));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
testTranslateAndUnion(toUnionize, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
// Test $type bounds for Code BSON type.
TEST(IndexBoundsBuilderTest, CodeTypeBounds) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$type: 13}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
// Build the expected interval.
BSONObjBuilder bob;
bob.appendCode("", "");
bob.appendCodeWScope("", "", BSONObj());
BSONObj expectedInterval = bob.obj();
// Check the output of translate().
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(expectedInterval, true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_FETCH);
}
// Test $type bounds for Code With Scoped BSON type.
TEST(IndexBoundsBuilderTest, CodeWithScopeTypeBounds) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$type: 15}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
// Build the expected interval.
BSONObjBuilder bob;
bob.appendCodeWScope("", "", BSONObj());
bob.appendMaxKey("");
BSONObj expectedInterval = bob.obj();
// Check the output of translate().
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(expectedInterval, true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_FETCH);
}
// Test $type bounds for double BSON type.
TEST(IndexBoundsBuilderTest, DoubleTypeBounds) {
IndexEntry testIndex = IndexEntry(BSONObj());
BSONObj obj = fromjson("{a: {$type: 1}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
// Build the expected interval.
BSONObjBuilder bob;
bob.appendNumber("", NaN);
bob.appendNumber("", positiveInfinity);
BSONObj expectedInterval = bob.obj();
// Check the output of translate().
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(expectedInterval, true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_FETCH);
}
//
// Collation-related tests.
//
TEST(IndexBoundsBuilderTest, TranslateEqualityToStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = BSON("a"
<< "foo");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'oof', '': 'oof'}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateEqualityToNonStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = BSON("a" << 3);
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 3, '': 3}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateNotEqualToStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = BSON("a" << BSON("$ne"
<< "bar"));
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
// Bounds should be [MinKey, "rab"), ("rab", MaxKey].
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
{
BSONObjBuilder bob;
bob.appendMinKey("");
bob.append("", "rab");
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(bob.obj(), true, false)));
}
{
BSONObjBuilder bob;
bob.append("", "rab");
bob.appendMaxKey("");
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(bob.obj(), false, true)));
}
}
TEST(IndexBoundsBuilderTest, TranslateEqualToStringElemMatchValueWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$elemMatch: {$eq: 'baz'}}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'zab', '': 'zab'}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, TranslateLTEToStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$lte: 'foo'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': 'oof'}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLTEToNumberWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$lte: 3}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': 3}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLTStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$lt: 'foo'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': 'oof'}"), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateLTNumberWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$lt: 3}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': -Infinity, '': 3}"), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGTStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$gt: 'foo'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'oof', '': {}}"), false, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGTNumberWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$gt: 3}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 3, '': Infinity}"), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGTEToStringWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$gte: 'foo'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'oof', '': {}}"), true, false)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, TranslateGTEToNumberWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$gte: 3}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 3, '': Infinity}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, SimplePrefixRegexWithMockCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: /^foo/}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': {}}"), true, false)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': /^foo/, '': /^foo/}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, NotWithMockCollatorIsExact) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$ne: 3}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(minKeyIntObj(3), true, false)));
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(maxKeyIntObj(3), false, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, ExistsTrueWithMockCollatorAndSparseIsExact) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
testIndex.sparse = true;
BSONObj obj = fromjson("{a: {$exists: true}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, ExistsFalseWithMockCollatorIsInexactFetch) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$exists: false}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': null, '': null}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, TypeStringIsInexactFetch) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$type: 'string'}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': {}}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, InWithStringAndCollatorIsExact) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$in: ['foo']}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 'oof', '': 'oof'}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, InWithNumberAndStringAndCollatorIsExact) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$in: [2, 'foo']}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 2, '': 2}"), true, true)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': 'oof', '': 'oof'}"), true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, InWithRegexAndCollatorIsInexactFetch) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$in: [/^foo/]}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 2U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': '', '': {}}"), true, false)));
ASSERT_EQUALS(
Interval::INTERVAL_EQUALS,
oil.intervals[1].compare(Interval(fromjson("{'': /^foo/, '': /^foo/}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, InWithNumberAndCollatorIsExact) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$in: [2]}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(fromjson("{'': 2, '': 2}"), true, true)));
ASSERT(tightness == IndexBoundsBuilder::EXACT);
}
TEST(IndexBoundsBuilderTest, LTEMaxKeyWithCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$lte: {$maxKey: 1}}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, LTMaxKeyWithCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$lt: {$maxKey: 1}}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, GTEMinKeyWithCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$gte: {$minKey: 1}}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, GTMinKeyWithCollator) {
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(BSONObj());
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$gt: {$minKey: 1}}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
BSONElement elt = obj.firstElement();
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(IndexBoundsBuilder::allValues()));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, StringEqualityAgainstHashedIndexWithCollatorUsesHashOfCollationKey) {
BSONObj keyPattern = fromjson("{a: 'hashed'}");
BSONElement elt = keyPattern.firstElement();
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(keyPattern);
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: 'foo'}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
BSONObj expectedCollationKey = BSON(""
<< "oof");
BSONObj expectedHash = ExpressionMapping::hash(expectedCollationKey.firstElement());
BSONObjBuilder intervalBuilder;
intervalBuilder.append("", expectedHash.firstElement().numberLong());
intervalBuilder.append("", expectedHash.firstElement().numberLong());
BSONObj intervalObj = intervalBuilder.obj();
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(intervalObj, true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, EqualityToNumberAgainstHashedIndexWithCollatorUsesHash) {
BSONObj keyPattern = fromjson("{a: 'hashed'}");
BSONElement elt = keyPattern.firstElement();
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(keyPattern);
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: 3}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
BSONObj expectedHash = ExpressionMapping::hash(obj.firstElement());
BSONObjBuilder intervalBuilder;
intervalBuilder.append("", expectedHash.firstElement().numberLong());
intervalBuilder.append("", expectedHash.firstElement().numberLong());
BSONObj intervalObj = intervalBuilder.obj();
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(intervalObj, true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
TEST(IndexBoundsBuilderTest, InWithStringAgainstHashedIndexWithCollatorUsesHashOfCollationKey) {
BSONObj keyPattern = fromjson("{a: 'hashed'}");
BSONElement elt = keyPattern.firstElement();
CollatorInterfaceMock collator(CollatorInterfaceMock::MockType::kReverseString);
IndexEntry testIndex = IndexEntry(keyPattern);
testIndex.collator = &collator;
BSONObj obj = fromjson("{a: {$in: ['foo']}}");
unique_ptr<MatchExpression> expr(parseMatchExpression(obj));
OrderedIntervalList oil;
IndexBoundsBuilder::BoundsTightness tightness;
IndexBoundsBuilder::translate(expr.get(), elt, testIndex, &oil, &tightness);
BSONObj expectedCollationKey = BSON(""
<< "oof");
BSONObj expectedHash = ExpressionMapping::hash(expectedCollationKey.firstElement());
BSONObjBuilder intervalBuilder;
intervalBuilder.append("", expectedHash.firstElement().numberLong());
intervalBuilder.append("", expectedHash.firstElement().numberLong());
BSONObj intervalObj = intervalBuilder.obj();
ASSERT_EQUALS(oil.name, "a");
ASSERT_EQUALS(oil.intervals.size(), 1U);
ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
oil.intervals[0].compare(Interval(intervalObj, true, true)));
ASSERT_EQUALS(tightness, IndexBoundsBuilder::INEXACT_FETCH);
}
} // namespace
| 42.179355 | 100 | 0.695292 | [
"vector"
] |
c89815653498976e019f47a0db2a2e2e3842eb73 | 5,140 | hpp | C++ | src/vlCore/plugins/ioJPG.hpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | 1 | 2017-06-29T18:25:11.000Z | 2017-06-29T18:25:11.000Z | src/vlCore/plugins/ioJPG.hpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | null | null | null | src/vlCore/plugins/ioJPG.hpp | pasenau/VisualizationLibrary | 2fcf1808475aebd4862f40377754be62a7f77a52 | [
"BSD-2-Clause"
] | 1 | 2021-01-01T10:43:33.000Z | 2021-01-01T10:43:33.000Z | /**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2017, Michele Bosi */
/* 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. */
/* */
/* 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 HOLDER 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. */
/* */
/**************************************************************************************/
#if !defined(ioJPG_INCLUDE_ONCE)
#define ioJPG_INCLUDE_ONCE
#include <vlCore/Object.hpp>
#include <vlCore/ResourceLoadWriter.hpp>
#include <vlCore/ResourceDatabase.hpp>
#include <vlCore/Image.hpp>
namespace vl
{
class VirtualFile;
class String;
class Image;
VLCORE_EXPORT ref<Image> loadJPG(VirtualFile* file);
VLCORE_EXPORT ref<Image> loadJPG(const String& path);
VLCORE_EXPORT bool isJPG(VirtualFile* file);
VLCORE_EXPORT bool saveJPG(const Image* src, const String& path, int quality = 95);
VLCORE_EXPORT bool saveJPG(const Image* src, VirtualFile* file, int quality = 95);
//---------------------------------------------------------------------------
// LoadWriterJPG
//---------------------------------------------------------------------------
/**
* The LoadWriterJPG class is a ResourceLoadWriter capable of reading JPG files.
*/
class LoadWriterJPG: public ResourceLoadWriter
{
VL_INSTRUMENT_CLASS(vl::LoadWriterJPG, ResourceLoadWriter)
public:
LoadWriterJPG(): ResourceLoadWriter("|jpg|", "|jpg|"), mQuality(95)
{
VL_DEBUG_SET_OBJECT_NAME()
}
ref<ResourceDatabase> loadResource(const String& path) const
{
ref<ResourceDatabase> res_db = new ResourceDatabase;
ref<Image> img = loadJPG(path);
if (img)
res_db->resources().push_back(img);
return res_db;
}
ref<ResourceDatabase> loadResource(VirtualFile* file) const
{
ref<ResourceDatabase> res_db = new ResourceDatabase;
ref<Image> img = loadJPG(file);
if (img)
res_db->resources().push_back(img);
return res_db;
}
bool writeResource(const String& path, ResourceDatabase* resource) const
{
bool ok = true;
for(unsigned i=0; i<resource->count<Image>(); ++i)
ok &= saveJPG(resource->get<Image>(i), path, quality());
return ok;
}
bool writeResource(VirtualFile* file, ResourceDatabase* resource) const
{
bool ok = true;
for(unsigned i=0; i<resource->count<Image>(); ++i)
ok &= saveJPG(resource->get<Image>(i), file, quality());
return ok;
}
int quality() const { return mQuality; }
//! Sets the quality level used when saving a file. Must be between 0 and 100.
void setQuality(int quality) { mQuality = quality; }
protected:
int mQuality;
};
}
#endif
| 45.892857 | 89 | 0.502529 | [
"object"
] |
c898d06b51b8252fc21ef1a97ee9bfe89e10110e | 8,634 | cpp | C++ | mainwindow.cpp | PLLUG/CPPQT-2016-2-CafeMenuEditor | 7832561f2c347db8de49ea16b77c33032b5a43f8 | [
"MIT"
] | null | null | null | mainwindow.cpp | PLLUG/CPPQT-2016-2-CafeMenuEditor | 7832561f2c347db8de49ea16b77c33032b5a43f8 | [
"MIT"
] | null | null | null | mainwindow.cpp | PLLUG/CPPQT-2016-2-CafeMenuEditor | 7832561f2c347db8de49ea16b77c33032b5a43f8 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <utility>
#include <menu.h>
#include <menuitem.h>
#include <QJsonObject>
#include <string>
#include <queue>
#include <QJsonArray>
#include <QFileDialog>
#include <QDebug>
#include <QFile>
#include <QJsonDocument>
#include <QDir>
#include <map>
#include <tuple>
#include "texteditprintmenuvisitor.h"
#include "menuiterator.h"
#include "adddialog.h"
#include "ui_adddialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
resize(800, 600);
createMenu();
slotUpdateMenu();
connect(ui->menuComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(menuElementSelected()), Qt::UniqueConnection);
connect(ui->action_Add, SIGNAL(triggered(bool)),
this, SLOT(slotAddNewItem()), Qt::UniqueConnection);
connect(ui->savePushButton, SIGNAL(clicked(bool)),
this, SLOT(slotSaveEditedItem()), Qt::UniqueConnection);
connect(ui->menuEditorDelegate, SIGNAL(itemChanged()),
this, SLOT(slotItemChanged()), Qt::UniqueConnection);
//First task. Add new button '+'
connect(ui->addButton, SIGNAL(clicked(bool)),
this, SLOT(slotAddNewItem()), Qt::UniqueConnection);
connect(ui->action_Open, SIGNAL(triggered(bool)),
this, SLOT(slotOpenFile()), Qt::UniqueConnection);
connect(ui->buttonDelete, SIGNAL(clicked(bool)), this, SLOT(slotDeleteItem()), Qt::UniqueConnection);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slotPrintMenu()
{
ui->menuTextEdit->clear();
TextEditPrintMenuVisitor visitor(ui->menuTextEdit);
MenuIterator iterator(mRoot.get());
while(iterator.hasNext())
{
auto item = iterator.next();
item->apply(&visitor);
}
}
void MainWindow::menuElementSelected()
{
ui->savePushButton->setEnabled(false);
AbstractMenuItem * item = ui->menuComboBox->currentMenuItem();
AbstractVisitor *visitor = ui->menuEditorDelegate;
item->apply(visitor);
ui->buttonDelete->setEnabled(true);
}
void MainWindow::slotUpdateMenu()
{
int index = ui->menuComboBox->currentIndex();
ui->menuComboBox->setMenu(mRoot.get());
slotPrintMenu();
ui->menuComboBox->setCurrentIndex(index);
}
void MainWindow::slotAddNewItem()
{
AddDialog addDialog;
addDialog.setMenu(mRoot.get());
if (QDialog::Accepted == addDialog.exec())
{
slotUpdateMenu();
}
}
void MainWindow::slotItemChanged()
{
ui->savePushButton->setEnabled(true);
}
void MainWindow::slotSaveEditedItem()
{
if(ui->menuEditorDelegate->slotSave())
{
if(ui->menuComboBox->checkDublicate(ui->menuEditorDelegate->getTempTitle()))
{
ui->savePushButton->setEnabled(false);
slotUpdateMenu();
}
else
{
QMessageBox msgBox;
msgBox.setText("Menu item with the same name already exists.");
msgBox.exec();
}
}
}
void MainWindow::slotOpenFile()
{
QFileDialog openDialog(this, tr("Open File..."), QDir::currentPath(), tr("Json Files (*.json);;All Files (*.*)"));
openDialog.setAcceptMode(QFileDialog::AcceptOpen);
if(QDialog::Accepted == openDialog.exec())
{
auto filePath = openDialog.selectedFiles()[0];
QFile file(filePath);
file.open(QIODevice::ReadOnly);
QTextStream file_text(&file);
QString json_string;
json_string = file_text.readAll();
file.close();
QByteArray json_bytes = json_string.toLocal8Bit();
QJsonParseError parseErrorJson;
auto result = QJsonDocument::fromJson(json_bytes, &parseErrorJson);
if(parseErrorJson.error == QJsonParseError::NoError)
{
auto arrJson = result.object();
mRoot.reset();
auto root = std::make_unique<Menu>("MAIN MENU");
root->append(std::move(createMenuFromJson(arrJson)));
mRoot = std::move(root);
slotUpdateMenu();
}
else
{
QMessageBox info(QMessageBox::Warning, tr("Error"), QString("Error in reading json file: %1.").arg(parseErrorJson.errorString()));
info.exec();
}
}
}
void MainWindow::slotDeleteItem()
{
auto toDel = ui->menuComboBox->currentMenuItem();
ui->menuComboBox->clearData();
toDel->removeSubitem();
ui->menuComboBox->updateComboBox();
slotPrintMenu();
ui->menuComboBox->updateComboBox();
if(ui->menuComboBox->currentIndex() < 0)
{
ui->buttonDelete->setEnabled(false);
}
}
void MainWindow::createMenu()
{
auto root = std::make_unique<Menu>("MAIN MENU");
auto pizzaMenu = std::make_unique<Menu>("Pizza Menu");
pizzaMenu->append(std::make_unique<MenuItem>("hawaiian pizza", 2.4, "cheese and tomato base with toppings of ham and pineapple"));
pizzaMenu->append(std::make_unique<MenuItem>("vegetarian pizza", 4.2, "cheese and tomato ... "));
auto beveragesMenu = std::make_unique<Menu>("Beverages");
beveragesMenu->append(std::make_unique<MenuItem>("Coca-Cola", 2));
auto coffeMenu = std::make_unique<Menu>("Coffe");
coffeMenu->append(std::make_unique<MenuItem>("Late", 1, " "));
coffeMenu->append(std::make_unique<MenuItem>("Capucino", 2, " "));
beveragesMenu->append(std::move(coffeMenu));
beveragesMenu->append(std::make_unique<MenuItem>("Pepsi-Cola", 3));
auto mineralWatersMenu = std::make_unique<Menu>("Mineral waters");
mineralWatersMenu->append(std::make_unique<MenuItem>("Borjomi", 2.43, " nice thing "));
mineralWatersMenu->append(std::make_unique<MenuItem>("Morshynska", 1.4, " "));
beveragesMenu->append(std::move(mineralWatersMenu));
auto alcoDrinksMenu = std::make_unique<Menu>("Alco drinks");
auto winesMenu = std::make_unique<Menu>("Wines");
auto dryWines = std::make_unique<Menu>("Dry Wines");
dryWines->append(std::make_unique<MenuItem>("Bordeaux", 20));
winesMenu->append(std::move(dryWines));
winesMenu->append(std::make_unique<MenuItem>("Champagne", 16.5));
alcoDrinksMenu->append(std::move(winesMenu));
alcoDrinksMenu->append(std::make_unique<MenuItem>("Beer", 5));
beveragesMenu->append(std::move(alcoDrinksMenu));
root->append(std::move(beveragesMenu));
root->append(std::move(pizzaMenu));
mRoot = std::move(root);
}
std::unique_ptr<AbstractMenuItem> MainWindow::createMenuFromJson(QJsonObject sub)
{
auto keys = sub.keys();
int index = 0;
std::queue<QJsonArray> children;
std::map<std::string, std::string> valueStr;
std::map<std::string, double> valueDouble;
std::map<std::string, bool> valueBool;
enum typeData{Str, Dbl, Bool};
auto mixedData = make_tuple(valueStr, valueDouble, valueBool); //tuple of 3 kind of data value:str <-> key:{str, dbl, bool}.
for(auto i : sub)
{
if(i.isArray())
{
//foo(i.toArray(), deep+1);
children.push(i.toArray());
++index;
}
else
{
QString key = keys[index++];
if(i.isString())
{
std::get<typeData::Str>(mixedData)[key.toStdString()] = i.toString().toStdString();
}
if(i.isDouble())
{
std::get<typeData::Dbl>(mixedData)[key.toStdString()] = i.toDouble();
}
if(i.isBool())
{
std::get<typeData::Bool>(mixedData)[key.toStdString()] = i.toBool();
}
}
}
//create new menu or menuitem
std::unique_ptr<MenuItem> newMenuItem;
std::unique_ptr<Menu> newMenu;
if(std::get<typeData::Str>(mixedData)["type"] == std::string("Menu"))
{
newMenu = std::make_unique<Menu>(std::get<typeData::Str>(mixedData)["title"]/*valueStr["title"]*/);
while(!children.empty())
{
//append all children
auto currentItem = children.front();
children.pop();
for(auto j : currentItem)
{
newMenu->append(createMenuFromJson(j.toObject()));
}
}
return std::move(newMenu);
}
else
{
newMenuItem = std::make_unique<MenuItem>(std::get<typeData::Str>(mixedData)["title"],
std::get<typeData::Dbl>(mixedData)["price"],
std::get<typeData::Str>(mixedData)["description"]);
return std::move(newMenuItem);
}
}
| 31.396364 | 142 | 0.614895 | [
"object"
] |
c89b83b9b6b7e8f20e77f51277afe1bddf57331e | 19,136 | cpp | C++ | rtcp_payload/src/cpp_stl_98/rtcp_payload.cpp | kaitai-io/formats-kaitai-io.github.io | 2700514a2a8f67c5351fe93962c70abea02fd3d3 | [
"0BSD"
] | 4 | 2018-12-10T09:21:19.000Z | 2021-11-03T16:43:22.000Z | rtcp_payload/src/cpp_stl_98/rtcp_payload.cpp | kaitai-io/formats-kaitai-io.github.io | 2700514a2a8f67c5351fe93962c70abea02fd3d3 | [
"0BSD"
] | null | null | null | rtcp_payload/src/cpp_stl_98/rtcp_payload.cpp | kaitai-io/formats-kaitai-io.github.io | 2700514a2a8f67c5351fe93962c70abea02fd3d3 | [
"0BSD"
] | 3 | 2019-04-08T08:22:22.000Z | 2021-10-10T19:11:51.000Z | // This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
#include "rtcp_payload.h"
rtcp_payload_t::rtcp_payload_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = this;
m_rtcp_packets = 0;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::_read() {
m_rtcp_packets = new std::vector<rtcp_packet_t*>();
{
int i = 0;
while (!m__io->is_eof()) {
m_rtcp_packets->push_back(new rtcp_packet_t(m__io, this, m__root));
i++;
}
}
}
rtcp_payload_t::~rtcp_payload_t() {
_clean_up();
}
void rtcp_payload_t::_clean_up() {
if (m_rtcp_packets) {
for (std::vector<rtcp_packet_t*>::iterator it = m_rtcp_packets->begin(); it != m_rtcp_packets->end(); ++it) {
delete *it;
}
delete m_rtcp_packets; m_rtcp_packets = 0;
}
}
rtcp_payload_t::psfb_afb_remb_packet_t::psfb_afb_remb_packet_t(kaitai::kstream* p__io, rtcp_payload_t::psfb_afb_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m_ssrc_list = 0;
f_max_total_bitrate = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::psfb_afb_remb_packet_t::_read() {
m_num_ssrc = m__io->read_u1();
m_br_exp = m__io->read_bits_int_be(6);
m_br_mantissa = m__io->read_bits_int_be(18);
m__io->align_to_byte();
int l_ssrc_list = num_ssrc();
m_ssrc_list = new std::vector<uint32_t>();
m_ssrc_list->reserve(l_ssrc_list);
for (int i = 0; i < l_ssrc_list; i++) {
m_ssrc_list->push_back(m__io->read_u4be());
}
}
rtcp_payload_t::psfb_afb_remb_packet_t::~psfb_afb_remb_packet_t() {
_clean_up();
}
void rtcp_payload_t::psfb_afb_remb_packet_t::_clean_up() {
if (m_ssrc_list) {
delete m_ssrc_list; m_ssrc_list = 0;
}
}
int32_t rtcp_payload_t::psfb_afb_remb_packet_t::max_total_bitrate() {
if (f_max_total_bitrate)
return m_max_total_bitrate;
m_max_total_bitrate = (br_mantissa() * (1 << br_exp()));
f_max_total_bitrate = true;
return m_max_total_bitrate;
}
rtcp_payload_t::sr_packet_t::sr_packet_t(kaitai::kstream* p__io, rtcp_payload_t::rtcp_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m_report_block = 0;
f_ntp = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::sr_packet_t::_read() {
m_ssrc = m__io->read_u4be();
m_ntp_msw = m__io->read_u4be();
m_ntp_lsw = m__io->read_u4be();
m_rtp_timestamp = m__io->read_u4be();
m_sender_packet_count = m__io->read_u4be();
m_sender_octet_count = m__io->read_u4be();
int l_report_block = _parent()->subtype();
m_report_block = new std::vector<report_block_t*>();
m_report_block->reserve(l_report_block);
for (int i = 0; i < l_report_block; i++) {
m_report_block->push_back(new report_block_t(m__io, this, m__root));
}
}
rtcp_payload_t::sr_packet_t::~sr_packet_t() {
_clean_up();
}
void rtcp_payload_t::sr_packet_t::_clean_up() {
if (m_report_block) {
for (std::vector<report_block_t*>::iterator it = m_report_block->begin(); it != m_report_block->end(); ++it) {
delete *it;
}
delete m_report_block; m_report_block = 0;
}
}
int32_t rtcp_payload_t::sr_packet_t::ntp() {
if (f_ntp)
return m_ntp;
m_ntp = ((ntp_msw() << 32) & ntp_lsw());
f_ntp = true;
return m_ntp;
}
rtcp_payload_t::rr_packet_t::rr_packet_t(kaitai::kstream* p__io, rtcp_payload_t::rtcp_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m_report_block = 0;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::rr_packet_t::_read() {
m_ssrc = m__io->read_u4be();
int l_report_block = _parent()->subtype();
m_report_block = new std::vector<report_block_t*>();
m_report_block->reserve(l_report_block);
for (int i = 0; i < l_report_block; i++) {
m_report_block->push_back(new report_block_t(m__io, this, m__root));
}
}
rtcp_payload_t::rr_packet_t::~rr_packet_t() {
_clean_up();
}
void rtcp_payload_t::rr_packet_t::_clean_up() {
if (m_report_block) {
for (std::vector<report_block_t*>::iterator it = m_report_block->begin(); it != m_report_block->end(); ++it) {
delete *it;
}
delete m_report_block; m_report_block = 0;
}
}
rtcp_payload_t::rtcp_packet_t::rtcp_packet_t(kaitai::kstream* p__io, rtcp_payload_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m__io__raw_body = 0;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::rtcp_packet_t::_read() {
m_version = m__io->read_bits_int_be(2);
m_padding = m__io->read_bits_int_be(1);
m_subtype = m__io->read_bits_int_be(5);
m__io->align_to_byte();
m_payload_type = static_cast<rtcp_payload_t::payload_type_t>(m__io->read_u1());
m_length = m__io->read_u2be();
n_body = true;
switch (payload_type()) {
case rtcp_payload_t::PAYLOAD_TYPE_SR: {
n_body = false;
m__raw_body = m__io->read_bytes((4 * length()));
m__io__raw_body = new kaitai::kstream(m__raw_body);
m_body = new sr_packet_t(m__io__raw_body, this, m__root);
break;
}
case rtcp_payload_t::PAYLOAD_TYPE_PSFB: {
n_body = false;
m__raw_body = m__io->read_bytes((4 * length()));
m__io__raw_body = new kaitai::kstream(m__raw_body);
m_body = new psfb_packet_t(m__io__raw_body, this, m__root);
break;
}
case rtcp_payload_t::PAYLOAD_TYPE_RR: {
n_body = false;
m__raw_body = m__io->read_bytes((4 * length()));
m__io__raw_body = new kaitai::kstream(m__raw_body);
m_body = new rr_packet_t(m__io__raw_body, this, m__root);
break;
}
case rtcp_payload_t::PAYLOAD_TYPE_RTPFB: {
n_body = false;
m__raw_body = m__io->read_bytes((4 * length()));
m__io__raw_body = new kaitai::kstream(m__raw_body);
m_body = new rtpfb_packet_t(m__io__raw_body, this, m__root);
break;
}
case rtcp_payload_t::PAYLOAD_TYPE_SDES: {
n_body = false;
m__raw_body = m__io->read_bytes((4 * length()));
m__io__raw_body = new kaitai::kstream(m__raw_body);
m_body = new sdes_packet_t(m__io__raw_body, this, m__root);
break;
}
default: {
m__raw_body = m__io->read_bytes((4 * length()));
break;
}
}
}
rtcp_payload_t::rtcp_packet_t::~rtcp_packet_t() {
_clean_up();
}
void rtcp_payload_t::rtcp_packet_t::_clean_up() {
if (!n_body) {
if (m__io__raw_body) {
delete m__io__raw_body; m__io__raw_body = 0;
}
if (m_body) {
delete m_body; m_body = 0;
}
}
}
rtcp_payload_t::sdes_tlv_t::sdes_tlv_t(kaitai::kstream* p__io, rtcp_payload_t::source_chunk_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::sdes_tlv_t::_read() {
m_type = static_cast<rtcp_payload_t::sdes_subtype_t>(m__io->read_u1());
n_length = true;
if (type() != rtcp_payload_t::SDES_SUBTYPE_PAD) {
n_length = false;
m_length = m__io->read_u1();
}
n_value = true;
if (type() != rtcp_payload_t::SDES_SUBTYPE_PAD) {
n_value = false;
m_value = m__io->read_bytes(length());
}
}
rtcp_payload_t::sdes_tlv_t::~sdes_tlv_t() {
_clean_up();
}
void rtcp_payload_t::sdes_tlv_t::_clean_up() {
if (!n_length) {
}
if (!n_value) {
}
}
rtcp_payload_t::report_block_t::report_block_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
f_fraction_lost = false;
f_cumulative_packets_lost = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::report_block_t::_read() {
m_ssrc_source = m__io->read_u4be();
m_lost_val = m__io->read_u1();
m_highest_seq_num_received = m__io->read_u4be();
m_interarrival_jitter = m__io->read_u4be();
m_lsr = m__io->read_u4be();
m_dlsr = m__io->read_u4be();
}
rtcp_payload_t::report_block_t::~report_block_t() {
_clean_up();
}
void rtcp_payload_t::report_block_t::_clean_up() {
}
int32_t rtcp_payload_t::report_block_t::fraction_lost() {
if (f_fraction_lost)
return m_fraction_lost;
m_fraction_lost = (lost_val() >> 24);
f_fraction_lost = true;
return m_fraction_lost;
}
int32_t rtcp_payload_t::report_block_t::cumulative_packets_lost() {
if (f_cumulative_packets_lost)
return m_cumulative_packets_lost;
m_cumulative_packets_lost = (lost_val() & 16777215);
f_cumulative_packets_lost = true;
return m_cumulative_packets_lost;
}
rtcp_payload_t::rtpfb_transport_feedback_packet_t::rtpfb_transport_feedback_packet_t(kaitai::kstream* p__io, rtcp_payload_t::rtpfb_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
f_reference_time = false;
f_fb_pkt_count = false;
f_packet_status = false;
f_recv_delta = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::rtpfb_transport_feedback_packet_t::_read() {
m_base_sequence_number = m__io->read_u2be();
m_packet_status_count = m__io->read_u2be();
m_b4 = m__io->read_u4be();
m_remaining = m__io->read_bytes_full();
}
rtcp_payload_t::rtpfb_transport_feedback_packet_t::~rtpfb_transport_feedback_packet_t() {
_clean_up();
}
void rtcp_payload_t::rtpfb_transport_feedback_packet_t::_clean_up() {
if (f_packet_status) {
}
if (f_recv_delta) {
}
}
int32_t rtcp_payload_t::rtpfb_transport_feedback_packet_t::reference_time() {
if (f_reference_time)
return m_reference_time;
m_reference_time = (b4() >> 8);
f_reference_time = true;
return m_reference_time;
}
int32_t rtcp_payload_t::rtpfb_transport_feedback_packet_t::fb_pkt_count() {
if (f_fb_pkt_count)
return m_fb_pkt_count;
m_fb_pkt_count = (b4() & 255);
f_fb_pkt_count = true;
return m_fb_pkt_count;
}
std::string rtcp_payload_t::rtpfb_transport_feedback_packet_t::packet_status() {
if (f_packet_status)
return m_packet_status;
m_packet_status = m__io->read_bytes(0);
f_packet_status = true;
return m_packet_status;
}
std::string rtcp_payload_t::rtpfb_transport_feedback_packet_t::recv_delta() {
if (f_recv_delta)
return m_recv_delta;
m_recv_delta = m__io->read_bytes(0);
f_recv_delta = true;
return m_recv_delta;
}
rtcp_payload_t::psfb_packet_t::psfb_packet_t(kaitai::kstream* p__io, rtcp_payload_t::rtcp_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m__io__raw_fci_block = 0;
f_fmt = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::psfb_packet_t::_read() {
m_ssrc = m__io->read_u4be();
m_ssrc_media_source = m__io->read_u4be();
n_fci_block = true;
switch (fmt()) {
case rtcp_payload_t::PSFB_SUBTYPE_AFB: {
n_fci_block = false;
m__raw_fci_block = m__io->read_bytes_full();
m__io__raw_fci_block = new kaitai::kstream(m__raw_fci_block);
m_fci_block = new psfb_afb_packet_t(m__io__raw_fci_block, this, m__root);
break;
}
default: {
m__raw_fci_block = m__io->read_bytes_full();
break;
}
}
}
rtcp_payload_t::psfb_packet_t::~psfb_packet_t() {
_clean_up();
}
void rtcp_payload_t::psfb_packet_t::_clean_up() {
if (!n_fci_block) {
if (m__io__raw_fci_block) {
delete m__io__raw_fci_block; m__io__raw_fci_block = 0;
}
if (m_fci_block) {
delete m_fci_block; m_fci_block = 0;
}
}
}
rtcp_payload_t::psfb_subtype_t rtcp_payload_t::psfb_packet_t::fmt() {
if (f_fmt)
return m_fmt;
m_fmt = static_cast<rtcp_payload_t::psfb_subtype_t>(_parent()->subtype());
f_fmt = true;
return m_fmt;
}
rtcp_payload_t::source_chunk_t::source_chunk_t(kaitai::kstream* p__io, rtcp_payload_t::sdes_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m_sdes_tlv = 0;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::source_chunk_t::_read() {
m_ssrc = m__io->read_u4be();
m_sdes_tlv = new std::vector<sdes_tlv_t*>();
{
int i = 0;
while (!m__io->is_eof()) {
m_sdes_tlv->push_back(new sdes_tlv_t(m__io, this, m__root));
i++;
}
}
}
rtcp_payload_t::source_chunk_t::~source_chunk_t() {
_clean_up();
}
void rtcp_payload_t::source_chunk_t::_clean_up() {
if (m_sdes_tlv) {
for (std::vector<sdes_tlv_t*>::iterator it = m_sdes_tlv->begin(); it != m_sdes_tlv->end(); ++it) {
delete *it;
}
delete m_sdes_tlv; m_sdes_tlv = 0;
}
}
rtcp_payload_t::sdes_packet_t::sdes_packet_t(kaitai::kstream* p__io, rtcp_payload_t::rtcp_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m_source_chunk = 0;
f_source_count = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::sdes_packet_t::_read() {
int l_source_chunk = source_count();
m_source_chunk = new std::vector<source_chunk_t*>();
m_source_chunk->reserve(l_source_chunk);
for (int i = 0; i < l_source_chunk; i++) {
m_source_chunk->push_back(new source_chunk_t(m__io, this, m__root));
}
}
rtcp_payload_t::sdes_packet_t::~sdes_packet_t() {
_clean_up();
}
void rtcp_payload_t::sdes_packet_t::_clean_up() {
if (m_source_chunk) {
for (std::vector<source_chunk_t*>::iterator it = m_source_chunk->begin(); it != m_source_chunk->end(); ++it) {
delete *it;
}
delete m_source_chunk; m_source_chunk = 0;
}
}
uint64_t rtcp_payload_t::sdes_packet_t::source_count() {
if (f_source_count)
return m_source_count;
m_source_count = _parent()->subtype();
f_source_count = true;
return m_source_count;
}
rtcp_payload_t::rtpfb_packet_t::rtpfb_packet_t(kaitai::kstream* p__io, rtcp_payload_t::rtcp_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m__io__raw_fci_block = 0;
f_fmt = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::rtpfb_packet_t::_read() {
m_ssrc = m__io->read_u4be();
m_ssrc_media_source = m__io->read_u4be();
n_fci_block = true;
switch (fmt()) {
case rtcp_payload_t::RTPFB_SUBTYPE_TRANSPORT_FEEDBACK: {
n_fci_block = false;
m__raw_fci_block = m__io->read_bytes_full();
m__io__raw_fci_block = new kaitai::kstream(m__raw_fci_block);
m_fci_block = new rtpfb_transport_feedback_packet_t(m__io__raw_fci_block, this, m__root);
break;
}
default: {
m__raw_fci_block = m__io->read_bytes_full();
break;
}
}
}
rtcp_payload_t::rtpfb_packet_t::~rtpfb_packet_t() {
_clean_up();
}
void rtcp_payload_t::rtpfb_packet_t::_clean_up() {
if (!n_fci_block) {
if (m__io__raw_fci_block) {
delete m__io__raw_fci_block; m__io__raw_fci_block = 0;
}
if (m_fci_block) {
delete m_fci_block; m_fci_block = 0;
}
}
}
rtcp_payload_t::rtpfb_subtype_t rtcp_payload_t::rtpfb_packet_t::fmt() {
if (f_fmt)
return m_fmt;
m_fmt = static_cast<rtcp_payload_t::rtpfb_subtype_t>(_parent()->subtype());
f_fmt = true;
return m_fmt;
}
rtcp_payload_t::packet_status_chunk_t::packet_status_chunk_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
f_s = false;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::packet_status_chunk_t::_read() {
m_t = m__io->read_bits_int_be(1);
n_s2 = true;
if (((t()) ? 1 : 0) == 0) {
n_s2 = false;
m_s2 = m__io->read_bits_int_be(2);
}
n_s1 = true;
if (((t()) ? 1 : 0) == 1) {
n_s1 = false;
m_s1 = m__io->read_bits_int_be(1);
}
n_rle = true;
if (((t()) ? 1 : 0) == 0) {
n_rle = false;
m_rle = m__io->read_bits_int_be(13);
}
n_symbol_list = true;
if (((t()) ? 1 : 0) == 1) {
n_symbol_list = false;
m_symbol_list = m__io->read_bits_int_be(14);
}
}
rtcp_payload_t::packet_status_chunk_t::~packet_status_chunk_t() {
_clean_up();
}
void rtcp_payload_t::packet_status_chunk_t::_clean_up() {
if (!n_s2) {
}
if (!n_s1) {
}
if (!n_rle) {
}
if (!n_symbol_list) {
}
}
int32_t rtcp_payload_t::packet_status_chunk_t::s() {
if (f_s)
return m_s;
m_s = ((((t()) ? 1 : 0) == 0) ? (s2()) : (((((s1()) ? 1 : 0) == 0) ? (1) : (0))));
f_s = true;
return m_s;
}
rtcp_payload_t::psfb_afb_packet_t::psfb_afb_packet_t(kaitai::kstream* p__io, rtcp_payload_t::psfb_packet_t* p__parent, rtcp_payload_t* p__root) : kaitai::kstruct(p__io) {
m__parent = p__parent;
m__root = p__root;
m__io__raw_contents = 0;
try {
_read();
} catch(...) {
_clean_up();
throw;
}
}
void rtcp_payload_t::psfb_afb_packet_t::_read() {
m_uid = m__io->read_u4be();
n_contents = true;
switch (uid()) {
case 1380273474: {
n_contents = false;
m__raw_contents = m__io->read_bytes_full();
m__io__raw_contents = new kaitai::kstream(m__raw_contents);
m_contents = new psfb_afb_remb_packet_t(m__io__raw_contents, this, m__root);
break;
}
default: {
m__raw_contents = m__io->read_bytes_full();
break;
}
}
}
rtcp_payload_t::psfb_afb_packet_t::~psfb_afb_packet_t() {
_clean_up();
}
void rtcp_payload_t::psfb_afb_packet_t::_clean_up() {
if (!n_contents) {
if (m__io__raw_contents) {
delete m__io__raw_contents; m__io__raw_contents = 0;
}
if (m_contents) {
delete m_contents; m_contents = 0;
}
}
}
| 27.337143 | 203 | 0.637803 | [
"vector"
] |
c8a158c9f84965c85aa7ac957063c3889eb6d725 | 5,047 | hpp | C++ | include/GlobalNamespace/SimpleAudioPlayer.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/SimpleAudioPlayer.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/SimpleAudioPlayer.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: AudioPlayerBase
#include "GlobalNamespace/AudioPlayerBase.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: AudioClip
class AudioClip;
// Forward declaring type: AudioSource
class AudioSource;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x35
#pragma pack(push, 1)
// Autogenerated type: SimpleAudioPlayer
class SimpleAudioPlayer : public GlobalNamespace::AudioPlayerBase {
public:
// private UnityEngine.AudioClip _audioClip
// Size: 0x8
// Offset: 0x18
UnityEngine::AudioClip* audioClip;
// Field size check
static_assert(sizeof(UnityEngine::AudioClip*) == 0x8);
// private UnityEngine.AudioSource _audioSource
// Size: 0x8
// Offset: 0x20
UnityEngine::AudioSource* audioSource;
// Field size check
static_assert(sizeof(UnityEngine::AudioSource*) == 0x8);
// private System.Single _targetVolume
// Size: 0x4
// Offset: 0x28
float targetVolume;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _loop
// Size: 0x1
// Offset: 0x2C
bool loop;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: loop and: fadeSpeed
char __padding3[0x3] = {};
// private System.Single _fadeSpeed
// Size: 0x4
// Offset: 0x30
float fadeSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _fadingIn
// Size: 0x1
// Offset: 0x34
bool fadingIn;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: SimpleAudioPlayer
SimpleAudioPlayer(UnityEngine::AudioClip* audioClip_ = {}, UnityEngine::AudioSource* audioSource_ = {}, float targetVolume_ = {}, bool loop_ = {}, float fadeSpeed_ = {}, bool fadingIn_ = {}) noexcept : audioClip{audioClip_}, audioSource{audioSource_}, targetVolume{targetVolume_}, loop{loop_}, fadeSpeed{fadeSpeed_}, fadingIn{fadingIn_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// protected System.Void Start()
// Offset: 0x10ED730
void Start();
// protected System.Void Update()
// Offset: 0x10ED804
void Update();
// private System.Void FadeIn(System.Single duration)
// Offset: 0x10ED7BC
void FadeIn(float duration);
// public override UnityEngine.AudioClip get_activeAudioClip()
// Offset: 0x10ED728
// Implemented from: AudioPlayerBase
// Base method: UnityEngine.AudioClip AudioPlayerBase::get_activeAudioClip()
UnityEngine::AudioClip* get_activeAudioClip();
// public override System.Void FadeOut(System.Single duration)
// Offset: 0x10ED964
// Implemented from: AudioPlayerBase
// Base method: System.Void AudioPlayerBase::FadeOut(System.Single duration)
void FadeOut(float duration);
// public override System.Void PauseCurrentChannel()
// Offset: 0x10ED9A8
// Implemented from: AudioPlayerBase
// Base method: System.Void AudioPlayerBase::PauseCurrentChannel()
void PauseCurrentChannel();
// public override System.Void UnPauseCurrentChannel()
// Offset: 0x10ED9C4
// Implemented from: AudioPlayerBase
// Base method: System.Void AudioPlayerBase::UnPauseCurrentChannel()
void UnPauseCurrentChannel();
// public System.Void .ctor()
// Offset: 0x10ED9E0
// Implemented from: AudioPlayerBase
// Base method: System.Void AudioPlayerBase::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static SimpleAudioPlayer* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::SimpleAudioPlayer::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<SimpleAudioPlayer*, creationType>()));
}
}; // SimpleAudioPlayer
#pragma pack(pop)
static check_size<sizeof(SimpleAudioPlayer), 52 + sizeof(bool)> __GlobalNamespace_SimpleAudioPlayerSizeCheck;
static_assert(sizeof(SimpleAudioPlayer) == 0x35);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::SimpleAudioPlayer*, "", "SimpleAudioPlayer");
| 41.710744 | 343 | 0.705964 | [
"object"
] |
c8a54bb46eb33a59b3fad97e3b622833ff2d0317 | 144,546 | cpp | C++ | src/CppParser/Parser.cpp | ChristophBender/CppSharp | 59e766a394000e63bbb7fb7236b7cb9f83083e59 | [
"MIT"
] | 1 | 2022-01-05T10:34:27.000Z | 2022-01-05T10:34:27.000Z | src/CppParser/Parser.cpp | ChristophBender/CppSharp | 59e766a394000e63bbb7fb7236b7cb9f83083e59 | [
"MIT"
] | null | null | null | src/CppParser/Parser.cpp | ChristophBender/CppSharp | 59e766a394000e63bbb7fb7236b7cb9f83083e59 | [
"MIT"
] | 2 | 2021-12-07T10:53:27.000Z | 2021-12-22T06:50:43.000Z | /************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#ifdef DEBUG
#undef DEBUG // workaround DEBUG define messing with LLVM COFF headers
#endif
#include "Parser.h"
#include "ELFDumper.h"
#include "APValuePrinter.h"
#include <llvm/Support/Host.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Object/Archive.h>
#include <llvm/Object/COFF.h>
#include <llvm/Object/ObjectFile.h>
#include <llvm/Object/ELFObjectFile.h>
#include <llvm/Object/MachO.h>
#include <llvm/Option/ArgList.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/DataLayout.h>
#include <clang/Basic/Builtins.h>
#include <clang/Basic/Version.h>
#include <clang/Config/config.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/Comment.h>
#include <clang/AST/DeclFriend.h>
#include <clang/AST/ExprCXX.h>
#include <clang/Lex/DirectoryLookup.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/PreprocessorOptions.h>
#include <clang/Lex/PreprocessingRecord.h>
#include <clang/Parse/ParseAST.h>
#include <clang/Sema/Sema.h>
#include <clang/Sema/SemaConsumer.h>
#include <clang/Frontend/Utils.h>
#include <clang/Driver/Driver.h>
#include <clang/Driver/ToolChain.h>
#include <clang/Driver/Util.h>
#include <clang/Index/USRGeneration.h>
#include <CodeGen/TargetInfo.h>
#include <CodeGen/CGCall.h>
#include <CodeGen/CGCXXABI.h>
#include <Driver/ToolChains/Linux.h>
#include <Driver/ToolChains/MSVC.h>
#if defined(__APPLE__) || defined(__linux__)
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <dlfcn.h>
#define HAVE_DLFCN
#endif
using namespace CppSharp::CppParser;
// We use this as a placeholder for pointer values that should be ignored.
void* IgnorePtr = reinterpret_cast<void*>(0x1);
//-----------------------------------//
Parser::Parser(CppParserOptions* Opts) : opts(Opts), index(0)
{
for (const auto& SupportedStdType : Opts->SupportedStdTypes)
supportedStdTypes.insert(SupportedStdType);
supportedStdTypes.insert("allocator");
supportedStdTypes.insert("basic_string");
}
LayoutField Parser::WalkVTablePointer(Class* Class,
const clang::CharUnits& Offset, const std::string& prefix)
{
LayoutField LayoutField;
LayoutField.offset = Offset.getQuantity();
LayoutField.name = prefix + "_" + Class->name;
LayoutField.qualifiedType = GetQualifiedType(c->getASTContext().VoidPtrTy);
return LayoutField;
}
static CppAbi GetClassLayoutAbi(clang::TargetCXXABI::Kind abi)
{
switch (abi)
{
case clang::TargetCXXABI::Microsoft:
return CppAbi::Microsoft;
case clang::TargetCXXABI::GenericItanium:
return CppAbi::Itanium;
case clang::TargetCXXABI::GenericARM:
return CppAbi::ARM;
case clang::TargetCXXABI::iOS:
return CppAbi::iOS;
case clang::TargetCXXABI::AppleARM64:
return CppAbi::iOS64;
default:
llvm_unreachable("Unsupported C++ ABI kind");
}
}
void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD,
clang::CharUnits Offset, bool IncludeVirtualBases)
{
using namespace clang;
const auto &Layout = c->getASTContext().getASTRecordLayout(RD);
auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
auto Parent = static_cast<AST::Class*>(
WalkDeclaration(RD));
if (Class != Parent)
{
LayoutBase LayoutBase;
LayoutBase.offset = Offset.getQuantity();
LayoutBase._class = Parent;
Class->layout->Bases.push_back(LayoutBase);
}
// Dump bases.
if (CXXRD) {
const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
bool HasOwnVFPtr = Layout.hasOwnVFPtr();
bool HasOwnVBPtr = Layout.hasOwnVBPtr();
// Vtable pointer.
if (CXXRD->isDynamicClass() && !PrimaryBase &&
!c->getTarget().getCXXABI().isMicrosoft()) {
auto VPtr = WalkVTablePointer(Parent, Offset, "vptr");
Class->layout->Fields.push_back(VPtr);
}
else if (HasOwnVFPtr) {
auto VTPtr = WalkVTablePointer(Parent, Offset, "vfptr");
Class->layout->Fields.push_back(VTPtr);
}
// Collect nvbases.
SmallVector<const CXXRecordDecl *, 4> Bases;
for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
assert(!Base.getType()->isDependentType() &&
"Cannot layout class with dependent bases.");
if (!Base.isVirtual())
Bases.push_back(Base.getType()->getAsCXXRecordDecl());
}
// Sort nvbases by offset.
std::stable_sort(Bases.begin(), Bases.end(),
[&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
});
// Dump (non-virtual) bases
for (const CXXRecordDecl *Base : Bases) {
CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
ReadClassLayout(Class, Base, BaseOffset,
/*IncludeVirtualBases=*/false);
}
// vbptr (for Microsoft C++ ABI)
if (HasOwnVBPtr) {
auto VBPtr = WalkVTablePointer(Parent,
Offset + Layout.getVBPtrOffset(), "vbptr");
Class->layout->Fields.push_back(VBPtr);
}
}
// Dump fields.
uint64_t FieldNo = 0;
for (const clang::FieldDecl* Field : RD->fields()) {
uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo++);
CharUnits FieldOffset =
Offset + c->getASTContext().toCharUnitsFromBits(LocalFieldOffsetInBits);
auto F = WalkFieldCXX(Field, Parent);
LayoutField LayoutField;
LayoutField.offset = FieldOffset.getQuantity();
LayoutField.name = F->name;
LayoutField.qualifiedType = GetQualifiedType(Field->getType());
LayoutField.fieldPtr = (void*)Field;
Class->layout->Fields.push_back(LayoutField);
}
// Dump virtual bases.
if (CXXRD && IncludeVirtualBases) {
const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
Layout.getVBaseOffsetsMap();
for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
assert(Base.isVirtual() && "Found non-virtual class!");
const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
auto VtorDisp = WalkVTablePointer(Parent,
VBaseOffset - CharUnits::fromQuantity(4), "vtordisp");
Class->layout->Fields.push_back(VtorDisp);
}
ReadClassLayout(Class, VBase, VBaseOffset,
/*IncludeVirtualBases=*/false);
}
}
}
//-----------------------------------//
static clang::TargetCXXABI::Kind
ConvertToClangTargetCXXABI(CppSharp::CppParser::AST::CppAbi abi)
{
using namespace clang;
switch (abi)
{
case CppSharp::CppParser::AST::CppAbi::Itanium:
return TargetCXXABI::GenericItanium;
case CppSharp::CppParser::AST::CppAbi::Microsoft:
return TargetCXXABI::Microsoft;
case CppSharp::CppParser::AST::CppAbi::ARM:
return TargetCXXABI::GenericARM;
case CppSharp::CppParser::AST::CppAbi::iOS:
return TargetCXXABI::iOS;
case CppSharp::CppParser::AST::CppAbi::iOS64:
return TargetCXXABI::AppleARM64;
}
llvm_unreachable("Unsupported C++ ABI.");
}
void Parser::Setup()
{
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
using namespace clang;
std::vector<const char*> args;
args.push_back("-cc1");
for (unsigned I = 0, E = opts->Arguments.size(); I != E; ++I)
{
const auto& Arg = opts->Arguments[I];
args.push_back(Arg.c_str());
if (opts->verbose)
printf("Compiler argument: %s\n", Arg.c_str());
}
c.reset(new CompilerInstance());
c->createDiagnostics();
CompilerInvocation* Inv = new CompilerInvocation();
llvm::ArrayRef<const char*> arguments(args.data(), args.data() + args.size());
CompilerInvocation::CreateFromArgs(*Inv, arguments, c->getDiagnostics());
c->setInvocation(std::shared_ptr<CompilerInvocation>(Inv));
c->getLangOpts() = *Inv->LangOpts;
auto& TO = Inv->TargetOpts;
if (opts->targetTriple.empty())
opts->targetTriple = llvm::sys::getDefaultTargetTriple();
TO->Triple = llvm::Triple::normalize(opts->targetTriple);
if (opts->verbose)
printf("Target triple: %s\n", TO->Triple.c_str());
TargetInfo* TI = TargetInfo::CreateTargetInfo(c->getDiagnostics(), TO);
if (!TI)
{
// We might have no target info due to an invalid user-provided triple.
// Try again with the default triple.
opts->targetTriple = llvm::sys::getDefaultTargetTriple();
TO->Triple = llvm::Triple::normalize(opts->targetTriple);
TI = TargetInfo::CreateTargetInfo(c->getDiagnostics(), TO);
}
assert(TI && "Expected valid target info");
c->setTarget(TI);
c->createFileManager();
c->createSourceManager(c->getFileManager());
auto& HSOpts = c->getHeaderSearchOpts();
auto& PPOpts = c->getPreprocessorOpts();
auto& LangOpts = c->getLangOpts();
if (opts->noStandardIncludes)
{
HSOpts.UseStandardSystemIncludes = false;
HSOpts.UseStandardCXXIncludes = false;
}
if (opts->noBuiltinIncludes)
HSOpts.UseBuiltinIncludes = false;
if (opts->verbose)
HSOpts.Verbose = true;
for (unsigned I = 0, E = opts->IncludeDirs.size(); I != E; ++I)
{
const auto& s = opts->IncludeDirs[I];
HSOpts.AddPath(s, frontend::Angled, false, false);
}
for (unsigned I = 0, E = opts->SystemIncludeDirs.size(); I != E; ++I)
{
const auto& s = opts->SystemIncludeDirs[I];
HSOpts.AddPath(s, frontend::System, false, false);
}
for (unsigned I = 0, E = opts->Defines.size(); I != E; ++I)
{
const auto& define = opts->Defines[I];
PPOpts.addMacroDef(define);
}
for (unsigned I = 0, E = opts->Undefines.size(); I != E; ++I)
{
const auto& undefine = opts->Undefines[I];
PPOpts.addMacroUndef(undefine);
}
#ifdef _MSC_VER
if (opts->microsoftMode)
{
LangOpts.MSCompatibilityVersion = opts->toolSetToUse;
if (!LangOpts.MSCompatibilityVersion) LangOpts.MSCompatibilityVersion = 1700;
}
#endif
llvm::opt::InputArgList Args(0, 0);
clang::driver::Driver D("", TO->Triple, c->getDiagnostics());
clang::driver::ToolChain *TC = nullptr;
llvm::Triple Target(TO->Triple);
if (Target.getOS() == llvm::Triple::Linux)
TC = new clang::driver::toolchains::Linux(D, Target, Args);
else if (Target.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
TC = new clang::driver::toolchains::MSVCToolChain(D, Target, Args);
if (TC && !opts->noStandardIncludes) {
llvm::opt::ArgStringList Includes;
TC->AddClangSystemIncludeArgs(Args, Includes);
TC->AddClangCXXStdlibIncludeArgs(Args, Includes);
for (auto& Arg : Includes) {
if (strlen(Arg) > 0 && Arg[0] != '-')
HSOpts.AddPath(Arg, frontend::System, /*IsFramework=*/false,
/*IgnoreSysRoot=*/false);
}
}
if (TC)
delete TC;
// Enable preprocessing record.
PPOpts.DetailedRecord = true;
c->createPreprocessor(TU_Complete);
Preprocessor& PP = c->getPreprocessor();
PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
c->createASTContext();
}
//-----------------------------------//
std::string Parser::GetDeclMangledName(const clang::Decl* D)
{
using namespace clang;
if(!D || !isa<NamedDecl>(D))
return "";
bool CanMangle = isa<FunctionDecl>(D) || isa<VarDecl>(D)
|| isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D);
if (!CanMangle) return "";
auto ND = cast<NamedDecl>(D);
std::unique_ptr<MangleContext> MC;
auto& AST = c->getASTContext();
auto targetABI = c->getTarget().getCXXABI().getKind();
switch(targetABI)
{
default:
MC.reset(ItaniumMangleContext::create(AST, AST.getDiagnostics()));
break;
case TargetCXXABI::Microsoft:
MC.reset(MicrosoftMangleContext::create(AST, AST.getDiagnostics()));
break;
}
if (!MC)
llvm_unreachable("Unknown mangling ABI");
std::string Mangled;
llvm::raw_string_ostream Out(Mangled);
bool IsDependent = false;
if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND))
IsDependent |= VD->getType()->isDependentType();
if (!IsDependent)
IsDependent |= ND->getDeclContext()->isDependentContext();
if (!MC->shouldMangleDeclName(ND) || IsDependent)
return ND->getDeclName().getAsString();
GlobalDecl GD;
if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
GD = GlobalDecl(CD, Ctor_Base);
else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
GD = GlobalDecl(DD, Dtor_Base);
else
GD = GlobalDecl(ND);
MC->mangleName(GD, Out);
Out.flush();
// Strip away LLVM name marker.
if(!Mangled.empty() && Mangled[0] == '\01')
Mangled = Mangled.substr(1);
return Mangled;
}
//-----------------------------------//
static std::string GetDeclName(const clang::NamedDecl* D)
{
if (const clang::IdentifierInfo *II = D->getIdentifier())
return II->getName().str();
return D->getNameAsString();
}
static std::string GetTagDeclName(const clang::TagDecl* D)
{
using namespace clang;
if (auto Typedef = D->getTypedefNameForAnonDecl())
{
assert(Typedef->getIdentifier() && "Typedef without identifier?");
return GetDeclName(Typedef);
}
return GetDeclName(D);
}
static std::string GetDeclUSR(const clang::Decl* D)
{
using namespace clang;
SmallString<128> usr;
if (!index::generateUSRForDecl(D, usr))
return usr.str().str();
return "<invalid>";
}
static clang::Decl* GetPreviousDeclInContext(const clang::Decl* D)
{
assert(!D->getLexicalDeclContext()->decls_empty());
clang::Decl* prevDecl = nullptr;
for(auto it = D->getDeclContext()->decls_begin();
it != D->getDeclContext()->decls_end(); it++)
{
if((*it) == D)
return prevDecl;
prevDecl = (*it);
}
return nullptr;
}
bool IsExplicit(const clang::Decl* D)
{
using namespace clang;
auto CTS = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D);
return !CTS ||
CTS->getSpecializationKind() == TSK_ExplicitSpecialization ||
CTS->getSpecializationKind() == TSK_ExplicitInstantiationDeclaration ||
CTS->getSpecializationKind() == TSK_ExplicitInstantiationDefinition;
}
static clang::SourceLocation GetDeclStartLocation(clang::CompilerInstance* C,
const clang::Decl* D)
{
auto& SM = C->getSourceManager();
auto startLoc = SM.getExpansionLoc(D->getBeginLoc());
auto startOffset = SM.getFileOffset(startLoc);
if (clang::dyn_cast_or_null<clang::TranslationUnitDecl>(D) || !startLoc.isValid())
return startLoc;
auto lineNo = SM.getExpansionLineNumber(startLoc);
auto lineBeginLoc = SM.translateLineCol(SM.getFileID(startLoc), lineNo, 1);
auto lineBeginOffset = SM.getFileOffset(lineBeginLoc);
assert(lineBeginOffset <= startOffset);
if (D->getLexicalDeclContext()->decls_empty())
return lineBeginLoc;
auto prevDecl = GetPreviousDeclInContext(D);
if(!prevDecl || !IsExplicit(prevDecl))
return lineBeginLoc;
auto prevDeclEndLoc = SM.getExpansionLoc(prevDecl->getEndLoc());
auto prevDeclEndOffset = SM.getFileOffset(prevDeclEndLoc);
if(SM.getFileID(prevDeclEndLoc) != SM.getFileID(startLoc))
return lineBeginLoc;
// TODO: Figure out why this asserts
//assert(prevDeclEndOffset <= startOffset);
if(prevDeclEndOffset < lineBeginOffset)
return lineBeginLoc;
// Declarations don't share same macro expansion
if(SM.getExpansionLoc(prevDecl->getBeginLoc()) != startLoc)
return prevDeclEndLoc;
return GetDeclStartLocation(C, prevDecl);
}
std::string Parser::GetTypeName(const clang::Type* Type)
{
using namespace clang;
if(Type->isAnyPointerType() || Type->isReferenceType())
Type = Type->getPointeeType().getTypePtr();
if(Type->isEnumeralType() || Type->isRecordType())
{
const clang::TagType* Tag = Type->getAs<clang::TagType>();
return GetTagDeclName(Tag->getDecl());
}
PrintingPolicy pp(c->getLangOpts());
pp.SuppressTagKeyword = true;
std::string TypeName;
QualType::getAsStringInternal(Type, Qualifiers(), TypeName, pp);
return TypeName;
}
static TypeQualifiers GetTypeQualifiers(const clang::QualType& Type)
{
TypeQualifiers quals;
quals.isConst = Type.isLocalConstQualified();
quals.isRestrict = Type.isLocalRestrictQualified();
quals.isVolatile = Type.isVolatileQualified();
return quals;
}
QualifiedType Parser::GetQualifiedType(clang::QualType qual, const clang::TypeLoc* TL)
{
if (qual.isNull())
return QualifiedType();
QualifiedType qualType;
qualType.type = WalkType(qual, TL);
qualType.qualifiers = GetTypeQualifiers(qual);
return qualType;
}
//-----------------------------------//
static AccessSpecifier ConvertToAccess(clang::AccessSpecifier AS)
{
switch(AS)
{
case clang::AS_private:
return AccessSpecifier::Private;
case clang::AS_protected:
return AccessSpecifier::Protected;
case clang::AS_public:
return AccessSpecifier::Public;
case clang::AS_none:
return AccessSpecifier::Public;
}
llvm_unreachable("Unknown AccessSpecifier");
}
VTableComponent
Parser::WalkVTableComponent(const clang::VTableComponent& Component)
{
using namespace clang;
VTableComponent VTC;
switch(Component.getKind())
{
case clang::VTableComponent::CK_VCallOffset:
{
VTC.kind = VTableComponentKind::VBaseOffset;
VTC.offset = Component.getVCallOffset().getQuantity();
break;
}
case clang::VTableComponent::CK_VBaseOffset:
{
VTC.kind = VTableComponentKind::VBaseOffset;
VTC.offset = Component.getVBaseOffset().getQuantity();
break;
}
case clang::VTableComponent::CK_OffsetToTop:
{
VTC.kind = VTableComponentKind::OffsetToTop;
VTC.offset = Component.getOffsetToTop().getQuantity();
break;
}
case clang::VTableComponent::CK_RTTI:
{
VTC.kind = VTableComponentKind::RTTI;
auto RD = Component.getRTTIDecl();
VTC.declaration = WalkRecordCXX(RD);
break;
}
case clang::VTableComponent::CK_FunctionPointer:
{
VTC.kind = VTableComponentKind::FunctionPointer;
auto MD = Component.getFunctionDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
case clang::VTableComponent::CK_CompleteDtorPointer:
{
VTC.kind = VTableComponentKind::CompleteDtorPointer;
auto MD = Component.getDestructorDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
case clang::VTableComponent::CK_DeletingDtorPointer:
{
VTC.kind = VTableComponentKind::DeletingDtorPointer;
auto MD = Component.getDestructorDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
case clang::VTableComponent::CK_UnusedFunctionPointer:
{
VTC.kind = VTableComponentKind::UnusedFunctionPointer;
auto MD = Component.getUnusedFunctionDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
default:
llvm_unreachable("Unknown vtable component kind");
}
return VTC;
}
VTableLayout Parser::WalkVTableLayout(const clang::VTableLayout& VTLayout)
{
auto Layout = VTableLayout();
for (const auto& VTC : VTLayout.vtable_components())
{
auto VTComponent = WalkVTableComponent(VTC);
Layout.Components.push_back(VTComponent);
}
return Layout;
}
void Parser::WalkVTable(const clang::CXXRecordDecl* RD, Class* C)
{
using namespace clang;
assert(RD->isDynamicClass() && "Only dynamic classes have virtual tables");
if (!C->layout)
C->layout = new ClassLayout();
auto targetABI = c->getTarget().getCXXABI().getKind();
C->layout->ABI = GetClassLayoutAbi(targetABI);
auto& AST = c->getASTContext();
switch(targetABI)
{
case TargetCXXABI::Microsoft:
{
MicrosoftVTableContext VTContext(AST);
const auto& VFPtrs = VTContext.getVFPtrOffsets(RD);
for (const auto& VFPtrInfo : VFPtrs)
{
VFTableInfo Info;
Info.VFPtrOffset = VFPtrInfo->NonVirtualOffset.getQuantity();
Info.VFPtrFullOffset = VFPtrInfo->FullOffsetInMDC.getQuantity();
auto& VTLayout = VTContext.getVFTableLayout(RD, VFPtrInfo->FullOffsetInMDC);
Info.layout = WalkVTableLayout(VTLayout);
C->layout->VFTables.push_back(Info);
}
break;
}
case TargetCXXABI::GenericItanium:
{
ItaniumVTableContext VTContext(AST);
auto& VTLayout = VTContext.getVTableLayout(RD);
C->layout->layout = WalkVTableLayout(VTLayout);
break;
}
default:
llvm_unreachable("Unsupported C++ ABI kind");
}
}
void Parser::EnsureCompleteRecord(const clang::RecordDecl* Record,
DeclarationContext* NS, Class* RC)
{
using namespace clang;
if (!RC->isIncomplete || RC->completeDeclaration)
return;
Decl* Definition;
if (auto CXXRecord = dyn_cast<CXXRecordDecl>(Record))
Definition = CXXRecord->getDefinition();
else
Definition = Record->getDefinition();
if (!Definition)
return;
RC->completeDeclaration = WalkDeclaration(Definition);
}
Class* Parser::GetRecord(const clang::RecordDecl* Record, bool& Process)
{
using namespace clang;
Process = false;
auto NS = GetNamespace(Record);
assert(NS && "Expected a valid namespace");
bool isCompleteDefinition = Record->isCompleteDefinition();
Class* RC = nullptr;
auto Name = GetTagDeclName(Record);
auto HasEmptyName = Record->getDeclName().isEmpty();
if (HasEmptyName)
{
auto USR = GetDeclUSR(Record);
if (auto AR = NS->FindAnonymous(USR))
RC = static_cast<Class*>(AR);
}
else
{
RC = NS->FindClass(opts->unityBuild ? Record : 0, Name,
isCompleteDefinition, /*Create=*/false);
}
if (RC)
return RC;
RC = NS->FindClass(opts->unityBuild ? Record : 0, Name,
isCompleteDefinition, /*Create=*/true);
RC->isInjected = Record->isInjectedClassName();
HandleDeclaration(Record, RC);
EnsureCompleteRecord(Record, NS, RC);
for (auto Redecl : Record->redecls())
{
if (Redecl->isImplicit() || Redecl == Record)
continue;
RC->Redeclarations.push_back(WalkDeclaration(Redecl));
}
if (HasEmptyName)
{
auto USR = GetDeclUSR(Record);
NS->anonymous[USR] = RC;
}
if (!isCompleteDefinition)
return RC;
Process = true;
return RC;
}
Class* Parser::WalkRecord(const clang::RecordDecl* Record)
{
bool Process;
auto RC = GetRecord(Record, Process);
if (!RC || !Process)
return RC;
WalkRecord(Record, RC);
return RC;
}
Class* Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record)
{
bool Process;
auto RC = GetRecord(Record, Process);
if (!RC || !Process)
return RC;
WalkRecordCXX(Record, RC);
return RC;
}
static int I = 0;
static bool IsRecordValid(const clang::RecordDecl* RC,
std::unordered_set<const clang::RecordDecl*>& Visited)
{
using namespace clang;
if (Visited.find(RC) != Visited.end())
return true;
Visited.insert(RC);
if (RC->isInvalidDecl())
return false;
for (auto Field : RC->fields())
{
auto Type = Field->getType()->getUnqualifiedDesugaredType();
const auto* RD = const_cast<CXXRecordDecl*>(Type->getAsCXXRecordDecl());
if (!RD)
RD = Type->getPointeeCXXRecordDecl();
if (RD && !IsRecordValid(RD, Visited))
return false;
}
return true;
}
static bool IsRecordValid(const clang::RecordDecl* RC)
{
std::unordered_set<const clang::RecordDecl*> Visited;
return IsRecordValid(RC, Visited);
}
static clang::CXXRecordDecl* GetCXXRecordDeclFromBaseType(const clang::QualType& Ty) {
using namespace clang;
if (auto RT = Ty->getAs<clang::RecordType>())
return dyn_cast<clang::CXXRecordDecl>(RT->getDecl());
else if (auto TST = Ty->getAs<clang::TemplateSpecializationType>())
return dyn_cast<clang::CXXRecordDecl>(
TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl());
else if (auto Injected = Ty->getAs<clang::InjectedClassNameType>())
return Injected->getDecl();
assert("Could not get base CXX record from type");
return nullptr;
}
bool Parser::HasLayout(const clang::RecordDecl* Record)
{
if (opts->skipLayoutInfo)
return false;
if (Record->isDependentType() || !Record->getDefinition() ||
!IsRecordValid(Record))
return false;
if (auto CXXRecord = llvm::dyn_cast<clang::CXXRecordDecl>(Record))
for (const clang::CXXBaseSpecifier& Base : CXXRecord->bases())
{
auto CXXBase = GetCXXRecordDeclFromBaseType(Base.getType());
if (!CXXBase || !HasLayout(CXXBase))
return false;
}
return true;
}
bool Parser::IsSupported(const clang::NamedDecl* ND)
{
return !c->getSourceManager().isInSystemHeader(ND->getBeginLoc()) ||
(llvm::isa<clang::RecordDecl>(ND) &&
supportedStdTypes.find(ND->getName().str()) != supportedStdTypes.end());
}
bool Parser::IsSupported(const clang::CXXMethodDecl* MD)
{
using namespace clang;
return !c->getSourceManager().isInSystemHeader(MD->getBeginLoc()) ||
(isa<CXXConstructorDecl>(MD) && MD->getNumParams() == 0) ||
isa<CXXDestructorDecl>(MD) ||
(MD->getDeclName().isIdentifier() &&
((MD->getName() == "data" && MD->getNumParams() == 0 && MD->isConst()) ||
(MD->getName() == "assign" && MD->getNumParams() == 1 &&
MD->parameters()[0]->getType()->isPointerType())) &&
supportedStdTypes.find(MD->getParent()->getName().str()) !=
supportedStdTypes.end());
}
static RecordArgABI GetRecordArgABI(
clang::CodeGen::CGCXXABI::RecordArgABI argAbi)
{
using namespace clang::CodeGen;
switch (argAbi)
{
case CGCXXABI::RecordArgABI::RAA_DirectInMemory:
return RecordArgABI::DirectInMemory;
case CGCXXABI::RecordArgABI::RAA_Indirect:
return RecordArgABI::Indirect;
default:
return RecordArgABI::Default;
}
}
void Parser::WalkRecord(const clang::RecordDecl* Record, Class* RC)
{
using namespace clang;
if (Record->isImplicit())
return;
if (IsExplicit(Record))
{
auto headStartLoc = GetDeclStartLocation(c.get(), Record);
auto headEndLoc = Record->getLocation(); // identifier location
auto bodyEndLoc = Record->getEndLoc();
auto headRange = clang::SourceRange(headStartLoc, headEndLoc);
auto bodyRange = clang::SourceRange(headEndLoc, bodyEndLoc);
HandlePreprocessedEntities(RC, headRange, MacroLocation::ClassHead);
HandlePreprocessedEntities(RC, bodyRange, MacroLocation::ClassBody);
}
auto& Sema = c->getSema();
RC->isUnion = Record->isUnion();
RC->isDependent = Record->isDependentType();
RC->isExternCContext = Record->isExternCContext();
bool hasLayout = HasLayout(Record);
if (hasLayout)
{
if (!RC->layout)
RC->layout = new ClassLayout();
auto targetABI = c->getTarget().getCXXABI().getKind();
RC->layout->ABI = GetClassLayoutAbi(targetABI);
if (auto CXXRD = llvm::dyn_cast_or_null<clang::CXXRecordDecl>(Record))
{
auto& CXXABI = codeGenTypes->getCXXABI();
RC->layout->argABI = GetRecordArgABI(CXXABI.getRecordArgABI(CXXRD));
}
const auto& Layout = c->getASTContext().getASTRecordLayout(Record);
RC->layout->alignment = (int)Layout.getAlignment().getQuantity();
RC->layout->size = (int)Layout.getSize().getQuantity();
RC->layout->dataSize = (int)Layout.getDataSize().getQuantity();
ReadClassLayout(RC, Record, CharUnits(), true);
}
for (auto FD : Record->fields())
WalkFieldCXX(FD, RC);
if (c->getSourceManager().isInSystemHeader(Record->getBeginLoc()))
{
if (supportedStdTypes.find(Record->getName().str()) != supportedStdTypes.end())
{
for (auto D : Record->decls())
{
switch (D->getKind())
{
case Decl::CXXConstructor:
case Decl::CXXDestructor:
case Decl::CXXConversion:
case Decl::CXXMethod:
{
auto MD = cast<CXXMethodDecl>(D);
if (IsSupported(MD))
WalkDeclaration(MD);
break;
}
default:
break;
}
}
}
return;
}
if (opts->skipPrivateDeclarations &&
Record->getAccess() == clang::AccessSpecifier::AS_private)
return;
for (auto D : Record->decls())
{
switch (D->getKind())
{
case Decl::AccessSpec:
{
AccessSpecDecl* AS = cast<AccessSpecDecl>(D);
auto AccessDecl = new AccessSpecifierDecl();
HandleDeclaration(AS, AccessDecl);
AccessDecl->access = ConvertToAccess(AS->getAccess());
AccessDecl->_namespace = RC;
RC->Specifiers.push_back(AccessDecl);
break;
}
case Decl::Field: // fields already handled
case Decl::IndirectField: // FIXME: Handle indirect fields
break;
case Decl::CXXRecord:
// Handle implicit records inside the class.
if (D->isImplicit())
continue;
WalkDeclaration(D);
break;
case Decl::Friend:
{
FriendDecl* FD = cast<FriendDecl>(D);
auto decl = FD->getFriendDecl();
// Skip every friend declaration that isn't a function declaration
if (decl && !isa<FunctionDecl>(decl))
continue;
WalkDeclaration(D);
break;
}
case Decl::FriendTemplate:
{
// In this case always skip the declaration since, unlike Decl::Friend handled above,
// it never is a declaration of a friend function or method
break;
}
default:
{
WalkDeclaration(D);
break;
} }
}
}
void Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record, Class* RC)
{
using namespace clang;
if (Record->isImplicit())
return;
auto& Sema = c->getSema();
Sema.ForceDeclarationOfImplicitMembers(const_cast<clang::CXXRecordDecl*>(Record));
WalkRecord(Record, RC);
if (!Record->hasDefinition())
return;
RC->isPOD = Record->isPOD();
RC->isAbstract = Record->isAbstract();
RC->isDynamic = Record->isDynamicClass();
RC->isPolymorphic = Record->isPolymorphic();
RC->hasNonTrivialDefaultConstructor = Record->hasNonTrivialDefaultConstructor();
RC->hasNonTrivialCopyConstructor = Record->hasNonTrivialCopyConstructor();
RC->hasNonTrivialDestructor = Record->hasNonTrivialDestructor();
bool hasLayout = HasLayout(Record) &&
Record->getDeclName() != c->getSema().VAListTagName;
// Get the record layout information.
const ASTRecordLayout* Layout = 0;
if (hasLayout)
{
Layout = &c->getASTContext().getASTRecordLayout(Record);
assert (RC->layout && "Expected a valid AST layout");
RC->layout->hasOwnVFPtr = Layout->hasOwnVFPtr();
RC->layout->VBPtrOffset = Layout->getVBPtrOffset().getQuantity();
}
// Iterate through the record bases.
for (const CXXBaseSpecifier& BS : Record->bases())
{
BaseClassSpecifier* Base = new BaseClassSpecifier();
Base->access = ConvertToAccess(BS.getAccessSpecifier());
Base->isVirtual = BS.isVirtual();
auto BSTL = BS.getTypeSourceInfo()->getTypeLoc();
Base->type = WalkType(BS.getType(), &BSTL);
auto BaseDecl = GetCXXRecordDeclFromBaseType(BS.getType());
if (BaseDecl && Layout)
{
auto Offset = BS.isVirtual() ? Layout->getVBaseClassOffset(BaseDecl)
: Layout->getBaseClassOffset(BaseDecl);
Base->offset = Offset.getQuantity();
}
RC->Bases.push_back(Base);
}
// Process the vtables
if (hasLayout && Record->isDynamicClass())
WalkVTable(Record, RC);
}
//-----------------------------------//
static TemplateSpecializationKind
WalkTemplateSpecializationKind(clang::TemplateSpecializationKind Kind)
{
switch(Kind)
{
case clang::TSK_Undeclared:
return TemplateSpecializationKind::Undeclared;
case clang::TSK_ImplicitInstantiation:
return TemplateSpecializationKind::ImplicitInstantiation;
case clang::TSK_ExplicitSpecialization:
return TemplateSpecializationKind::ExplicitSpecialization;
case clang::TSK_ExplicitInstantiationDeclaration:
return TemplateSpecializationKind::ExplicitInstantiationDeclaration;
case clang::TSK_ExplicitInstantiationDefinition:
return TemplateSpecializationKind::ExplicitInstantiationDefinition;
}
llvm_unreachable("Unknown template specialization kind");
}
//-----------------------------------//
struct Diagnostic
{
clang::SourceLocation Location;
llvm::SmallString<100> Message;
clang::DiagnosticsEngine::Level Level = clang::DiagnosticsEngine::Level::Ignored;
};
struct DiagnosticConsumer : public clang::DiagnosticConsumer
{
virtual void HandleDiagnostic(clang::DiagnosticsEngine::Level Level,
const clang::Diagnostic& Info) override {
// Update the base type NumWarnings and NumErrors variables.
if (Level == clang::DiagnosticsEngine::Warning)
NumWarnings++;
if (Level == clang::DiagnosticsEngine::Error ||
Level == clang::DiagnosticsEngine::Fatal)
{
NumErrors++;
if (Decl)
{
Decl->setInvalidDecl();
Decl = 0;
}
}
auto Diag = Diagnostic();
Diag.Location = Info.getLocation();
Diag.Level = Level;
Info.FormatDiagnostic(Diag.Message);
Diagnostics.push_back(Diag);
}
std::vector<Diagnostic> Diagnostics;
clang::Decl* Decl = 0;
};
ClassTemplateSpecialization*
Parser::WalkClassTemplateSpecialization(const clang::ClassTemplateSpecializationDecl* CTS)
{
using namespace clang;
auto CT = WalkClassTemplate(CTS->getSpecializedTemplate());
auto USR = GetDeclUSR(CTS);
auto TS = CT->FindSpecialization(USR);
if (TS != nullptr)
return TS;
TS = new ClassTemplateSpecialization();
HandleDeclaration(CTS, TS);
auto NS = GetNamespace(CTS);
assert(NS && "Expected a valid namespace");
TS->_namespace = NS;
TS->name = CTS->getName().str();
TS->templatedDecl = CT;
TS->specializationKind = WalkTemplateSpecializationKind(CTS->getSpecializationKind());
CT->Specializations.push_back(TS);
auto& TAL = CTS->getTemplateArgs();
auto TSI = CTS->getTypeAsWritten();
if (TSI)
{
auto TL = TSI->getTypeLoc();
auto TSL = TL.getAs<TemplateSpecializationTypeLoc>();
TS->Arguments = WalkTemplateArgumentList(&TAL, &TSL);
}
else
{
TS->Arguments = WalkTemplateArgumentList(&TAL, (clang::TemplateSpecializationTypeLoc*) 0);
}
if (CTS->isCompleteDefinition())
{
WalkRecordCXX(CTS, TS);
}
else
{
TS->isIncomplete = true;
if (CTS->getDefinition())
{
auto Complete = WalkDeclarationDef(CTS->getDefinition());
if (!Complete->isIncomplete)
TS->completeDeclaration = Complete;
}
}
return TS;
}
//-----------------------------------//
ClassTemplatePartialSpecialization*
Parser::WalkClassTemplatePartialSpecialization(const clang::ClassTemplatePartialSpecializationDecl* CTS)
{
using namespace clang;
auto CT = WalkClassTemplate(CTS->getSpecializedTemplate());
auto USR = GetDeclUSR(CTS);
auto TS = CT->FindPartialSpecialization(USR);
if (TS != nullptr)
return TS;
TS = new ClassTemplatePartialSpecialization();
HandleDeclaration(CTS, TS);
auto NS = GetNamespace(CTS);
assert(NS && "Expected a valid namespace");
TS->_namespace = NS;
TS->name = CTS->getName().str();
TS->templatedDecl = CT;
TS->specializationKind = WalkTemplateSpecializationKind(CTS->getSpecializationKind());
CT->Specializations.push_back(TS);
auto& TAL = CTS->getTemplateArgs();
if (auto TSI = CTS->getTypeAsWritten())
{
auto TL = TSI->getTypeLoc();
auto TSL = TL.getAs<TemplateSpecializationTypeLoc>();
TS->Arguments = WalkTemplateArgumentList(&TAL, &TSL);
}
if (CTS->isCompleteDefinition())
{
WalkRecordCXX(CTS, TS);
}
else
{
TS->isIncomplete = true;
if (CTS->getDefinition())
{
auto Complete = WalkDeclarationDef(CTS->getDefinition());
if (!Complete->isIncomplete)
TS->completeDeclaration = Complete;
}
}
return TS;
}
//-----------------------------------//
std::vector<Declaration*> Parser::WalkTemplateParameterList(const clang::TemplateParameterList* TPL)
{
auto params = std::vector<CppSharp::CppParser::Declaration*>();
for (auto it = TPL->begin(); it != TPL->end(); ++it)
{
auto ND = *it;
auto TP = WalkDeclaration(ND);
params.push_back(TP);
}
return params;
}
//-----------------------------------//
ClassTemplate* Parser::WalkClassTemplate(const clang::ClassTemplateDecl* TD)
{
auto NS = GetNamespace(TD);
assert(NS && "Expected a valid namespace");
auto USR = GetDeclUSR(TD);
auto CT = NS->FindTemplate<ClassTemplate>(USR);
if (CT != nullptr)
return CT;
CT = new ClassTemplate();
HandleDeclaration(TD, CT);
CT->name = GetDeclName(TD);
CT->_namespace = NS;
NS->Templates.push_back(CT);
bool Process;
auto RC = GetRecord(TD->getTemplatedDecl(), Process);
CT->TemplatedDecl = RC;
if (Process)
WalkRecordCXX(TD->getTemplatedDecl(), RC);
CT->Parameters = WalkTemplateParameterList(TD->getTemplateParameters());
return CT;
}
//-----------------------------------//
TemplateTemplateParameter* Parser::WalkTemplateTemplateParameter(const clang::TemplateTemplateParmDecl* TTP)
{
auto TP = walkedTemplateTemplateParameters[TTP];
if (TP)
return TP;
TP = new TemplateTemplateParameter();
HandleDeclaration(TTP, TP);
TP->Parameters = WalkTemplateParameterList(TTP->getTemplateParameters());
TP->isParameterPack = TTP->isParameterPack();
TP->isPackExpansion = TTP->isPackExpansion();
TP->isExpandedParameterPack = TTP->isExpandedParameterPack();
if (TTP->getTemplatedDecl())
{
auto TD = WalkDeclaration(TTP->getTemplatedDecl());
TP->TemplatedDecl = TD;
}
walkedTemplateTemplateParameters[TTP] = TP;
return TP;
}
//-----------------------------------//
TypeTemplateParameter* Parser::WalkTypeTemplateParameter(const clang::TemplateTypeParmDecl* TTPD)
{
auto TP = walkedTypeTemplateParameters[TTPD];
if (TP)
return TP;
TP = new CppSharp::CppParser::TypeTemplateParameter();
TP->name = GetDeclName(TTPD);
HandleDeclaration(TTPD, TP);
if (TTPD->hasDefaultArgument())
TP->defaultArgument = GetQualifiedType(TTPD->getDefaultArgument());
TP->depth = TTPD->getDepth();
TP->index = TTPD->getIndex();
TP->isParameterPack = TTPD->isParameterPack();
walkedTypeTemplateParameters[TTPD] = TP;
return TP;
}
//-----------------------------------//
NonTypeTemplateParameter* Parser::WalkNonTypeTemplateParameter(const clang::NonTypeTemplateParmDecl* NTTPD)
{
auto NTP = walkedNonTypeTemplateParameters[NTTPD];
if (NTP)
return NTP;
NTP = new CppSharp::CppParser::NonTypeTemplateParameter();
NTP->name = GetDeclName(NTTPD);
HandleDeclaration(NTTPD, NTP);
if (NTTPD->hasDefaultArgument())
NTP->defaultArgument = WalkExpressionObsolete(NTTPD->getDefaultArgument());
NTP->depth = NTTPD->getDepth();
NTP->index = NTTPD->getIndex();
NTP->isParameterPack = NTTPD->isParameterPack();
walkedNonTypeTemplateParameters[NTTPD] = NTP;
return NTP;
}
//-----------------------------------//
UnresolvedUsingTypename* Parser::WalkUnresolvedUsingTypename(const clang::UnresolvedUsingTypenameDecl* UUTD)
{
auto UUT = new CppSharp::CppParser::UnresolvedUsingTypename();
HandleDeclaration(UUTD, UUT);
return UUT;
}
//-----------------------------------//
template<typename TypeLoc>
std::vector<CppSharp::CppParser::TemplateArgument>
Parser::WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL,
TypeLoc* TSTL)
{
using namespace clang;
auto LocValid = TSTL && !TSTL->isNull() && TSTL->getTypePtr();
auto params = std::vector<CppSharp::CppParser::TemplateArgument>();
auto typeLocNumArgs = LocValid ? TSTL->getNumArgs() : 0;
for (size_t i = 0, e = TAL->size(); i < e; i++)
{
const clang::TemplateArgument& TA = TAL->get(i);
TemplateArgumentLoc TArgLoc;
TemplateArgumentLoc *ArgLoc = 0;
if (i < typeLocNumArgs && e == typeLocNumArgs)
{
TArgLoc = TSTL->getArgLoc(i);
ArgLoc = &TArgLoc;
}
auto Arg = WalkTemplateArgument(TA, ArgLoc);
params.push_back(Arg);
}
return params;
}
//-----------------------------------//
std::vector<CppSharp::CppParser::TemplateArgument>
Parser::WalkTemplateArgumentList(const clang::TemplateArgumentList* TAL,
const clang::ASTTemplateArgumentListInfo* TALI)
{
using namespace clang;
auto params = std::vector<CppSharp::CppParser::TemplateArgument>();
for (size_t i = 0, e = TAL->size(); i < e; i++)
{
const clang::TemplateArgument& TA = TAL->get(i);
if (TALI)
{
auto ArgLoc = TALI->operator[](i);
auto TP = WalkTemplateArgument(TA, &ArgLoc);
params.push_back(TP);
}
else
{
auto TP = WalkTemplateArgument(TA, 0);
params.push_back(TP);
}
}
return params;
}
//-----------------------------------//
CppSharp::CppParser::TemplateArgument
Parser::WalkTemplateArgument(const clang::TemplateArgument& TA,
clang::TemplateArgumentLoc* ArgLoc)
{
auto Arg = CppSharp::CppParser::TemplateArgument();
switch (TA.getKind())
{
case clang::TemplateArgument::Type:
{
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::Type;
clang::TypeLoc ArgTL;
if (ArgLoc && ArgLoc->getTypeSourceInfo())
{
ArgTL = ArgLoc->getTypeSourceInfo()->getTypeLoc();
}
auto Type = TA.getAsType();
CompleteIfSpecializationType(Type);
Arg.type = GetQualifiedType(Type, &ArgTL);
break;
}
case clang::TemplateArgument::Declaration:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::Declaration;
Arg.declaration = WalkDeclaration(TA.getAsDecl());
break;
case clang::TemplateArgument::NullPtr:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::NullPtr;
break;
case clang::TemplateArgument::Integral:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::Integral;
//Arg.Type = WalkType(TA.getIntegralType(), 0);
Arg.integral = TA.getAsIntegral().getLimitedValue();
break;
case clang::TemplateArgument::Template:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::Template;
break;
case clang::TemplateArgument::TemplateExpansion:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::TemplateExpansion;
break;
case clang::TemplateArgument::Expression:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::Expression;
break;
case clang::TemplateArgument::Pack:
Arg.kind = CppSharp::CppParser::TemplateArgument::ArgumentKind::Pack;
break;
case clang::TemplateArgument::Null:
default:
llvm_unreachable("Unknown TemplateArgument");
}
return Arg;
}
//-----------------------------------//
TypeAliasTemplate* Parser::WalkTypeAliasTemplate(
const clang::TypeAliasTemplateDecl* TD)
{
using namespace clang;
auto NS = GetNamespace(TD);
assert(NS && "Expected a valid namespace");
auto USR = GetDeclUSR(TD);
auto TA = NS->FindTemplate<TypeAliasTemplate>(USR);
if (TA != nullptr)
return TA;
TA = new TypeAliasTemplate();
HandleDeclaration(TD, TA);
TA->name = GetDeclName(TD);
NS->Templates.push_back(TA);
TA->TemplatedDecl = WalkDeclaration(TD->getTemplatedDecl());
TA->Parameters = WalkTemplateParameterList(TD->getTemplateParameters());
return TA;
}
//-----------------------------------//
FunctionTemplate* Parser::WalkFunctionTemplate(const clang::FunctionTemplateDecl* TD)
{
if (opts->skipPrivateDeclarations &&
TD->getAccess() == clang::AccessSpecifier::AS_private)
return nullptr;
using namespace clang;
auto NS = GetNamespace(TD);
assert(NS && "Expected a valid namespace");
auto USR = GetDeclUSR(TD);
auto FT = NS->FindTemplate<FunctionTemplate>(USR);
if (FT != nullptr)
return FT;
CppSharp::CppParser::AST::Function* Function = nullptr;
auto TemplatedDecl = TD->getTemplatedDecl();
if (auto MD = dyn_cast<CXXMethodDecl>(TemplatedDecl))
Function = WalkMethodCXX(MD);
else
Function = WalkFunction(TemplatedDecl);
FT = new FunctionTemplate();
HandleDeclaration(TD, FT);
FT->name = GetDeclName(TD);
FT->_namespace = NS;
FT->TemplatedDecl = Function;
FT->Parameters = WalkTemplateParameterList(TD->getTemplateParameters());
NS->Templates.push_back(FT);
return FT;
}
//-----------------------------------//
CppSharp::CppParser::FunctionTemplateSpecialization*
Parser::WalkFunctionTemplateSpec(clang::FunctionTemplateSpecializationInfo* FTSI, CppSharp::CppParser::Function* Function)
{
using namespace clang;
auto FTS = new CppSharp::CppParser::FunctionTemplateSpecialization();
FTS->specializationKind = WalkTemplateSpecializationKind(FTSI->getTemplateSpecializationKind());
FTS->specializedFunction = Function;
FTS->_template = WalkFunctionTemplate(FTSI->getTemplate());
FTS->_template->Specializations.push_back(FTS);
if (auto TSA = FTSI->TemplateArguments)
{
if (auto TSAW = FTSI->TemplateArgumentsAsWritten)
{
if (TSA->size() == TSAW->NumTemplateArgs)
{
FTS->Arguments = WalkTemplateArgumentList(TSA, TSAW);
return FTS;
}
}
FTS->Arguments = WalkTemplateArgumentList(TSA,
(const clang::ASTTemplateArgumentListInfo*) 0);
}
return FTS;
}
//-----------------------------------//
VarTemplate* Parser::WalkVarTemplate(const clang::VarTemplateDecl* TD)
{
auto NS = GetNamespace(TD);
assert(NS && "Expected a valid namespace");
auto USR = GetDeclUSR(TD);
auto VT = NS->FindTemplate<VarTemplate>(USR);
if (VT != nullptr)
return VT;
VT = new VarTemplate();
HandleDeclaration(TD, VT);
VT->name = GetDeclName(TD);
VT->_namespace = NS;
NS->Templates.push_back(VT);
auto RC = WalkVariable(TD->getTemplatedDecl());
VT->TemplatedDecl = RC;
VT->Parameters = WalkTemplateParameterList(TD->getTemplateParameters());
return VT;
}
VarTemplateSpecialization*
Parser::WalkVarTemplateSpecialization(const clang::VarTemplateSpecializationDecl* VTS)
{
using namespace clang;
auto VT = WalkVarTemplate(VTS->getSpecializedTemplate());
auto USR = GetDeclUSR(VTS);
auto TS = VT->FindSpecialization(USR);
if (TS != nullptr)
return TS;
TS = new VarTemplateSpecialization();
HandleDeclaration(VTS, TS);
auto NS = GetNamespace(VTS);
assert(NS && "Expected a valid namespace");
TS->_namespace = NS;
TS->name = VTS->getName().str();
TS->templatedDecl = VT;
TS->specializationKind = WalkTemplateSpecializationKind(VTS->getSpecializationKind());
VT->Specializations.push_back(TS);
auto& TAL = VTS->getTemplateArgs();
auto TSI = VTS->getTypeAsWritten();
if (TSI)
{
auto TL = TSI->getTypeLoc();
auto TSL = TL.getAs<TemplateSpecializationTypeLoc>();
TS->Arguments = WalkTemplateArgumentList(&TAL, &TSL);
}
else
{
TS->Arguments = WalkTemplateArgumentList(&TAL, (clang::TemplateSpecializationTypeLoc*) 0);
}
WalkVariable(VTS, TS);
return TS;
}
VarTemplatePartialSpecialization*
Parser::WalkVarTemplatePartialSpecialization(const clang::VarTemplatePartialSpecializationDecl* VTS)
{
using namespace clang;
auto VT = WalkVarTemplate(VTS->getSpecializedTemplate());
auto USR = GetDeclUSR(VTS);
auto TS = VT->FindPartialSpecialization(USR);
if (TS != nullptr)
return TS;
TS = new VarTemplatePartialSpecialization();
HandleDeclaration(VTS, TS);
auto NS = GetNamespace(VTS);
assert(NS && "Expected a valid namespace");
TS->_namespace = NS;
TS->name = VTS->getName().str();
TS->templatedDecl = VT;
TS->specializationKind = WalkTemplateSpecializationKind(VTS->getSpecializationKind());
VT->Specializations.push_back(TS);
auto& TAL = VTS->getTemplateArgs();
if (auto TSI = VTS->getTypeAsWritten())
{
auto TL = TSI->getTypeLoc();
auto TSL = TL.getAs<TemplateSpecializationTypeLoc>();
TS->Arguments = WalkTemplateArgumentList(&TAL, &TSL);
}
WalkVariable(VTS, TS);
return TS;
}
//-----------------------------------//
static CXXMethodKind GetMethodKindFromDecl(clang::DeclarationName Name)
{
using namespace clang;
switch(Name.getNameKind())
{
case DeclarationName::Identifier:
case DeclarationName::CXXDeductionGuideName:
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCMultiArgSelector:
return CXXMethodKind::Normal;
case DeclarationName::CXXConstructorName:
return CXXMethodKind::Constructor;
case DeclarationName::CXXDestructorName:
return CXXMethodKind::Destructor;
case DeclarationName::CXXConversionFunctionName:
return CXXMethodKind::Conversion;
case DeclarationName::CXXOperatorName:
case DeclarationName::CXXLiteralOperatorName:
return CXXMethodKind::Operator;
case DeclarationName::CXXUsingDirective:
return CXXMethodKind::UsingDirective;
}
return CXXMethodKind::Normal;
}
static CXXOperatorKind GetOperatorKindFromDecl(clang::DeclarationName Name)
{
using namespace clang;
if (Name.getNameKind() != DeclarationName::CXXOperatorName)
return CXXOperatorKind::None;
switch(Name.getCXXOverloadedOperator())
{
case OO_None:
return CXXOperatorKind::None;
case NUM_OVERLOADED_OPERATORS:
break;
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
case OO_##Name: return CXXOperatorKind::Name;
#include "clang/Basic/OperatorKinds.def"
}
llvm_unreachable("Unknown OverloadedOperator");
}
Method* Parser::WalkMethodCXX(const clang::CXXMethodDecl* MD)
{
const clang::CXXConstructorDecl* Ctor;
if (opts->skipPrivateDeclarations &&
MD->getAccess() == clang::AccessSpecifier::AS_private &&
!MD->isVirtual() &&
!MD->isCopyAssignmentOperator() &&
!MD->isMoveAssignmentOperator() &&
(!(Ctor = llvm::dyn_cast<clang::CXXConstructorDecl>(MD)) ||
(!Ctor->isDefaultConstructor() && !Ctor->isCopyOrMoveConstructor())))
return nullptr;
using namespace clang;
// We could be in a redeclaration, so process the primary context.
if (MD->getPrimaryContext() != MD)
return WalkMethodCXX(cast<CXXMethodDecl>(MD->getPrimaryContext()));
auto RD = MD->getParent();
auto Decl = WalkDeclaration(RD);
auto Class = static_cast<CppSharp::CppParser::AST::Class*>(Decl);
// Check for an already existing method that came from the same declaration.
auto USR = GetDeclUSR(MD);
for (auto& M : Class->Methods)
{
if (M->USR == USR)
{
return M;
}
}
for (unsigned I = 0, E = Class->Templates.size(); I != E; ++I)
{
Template* Template = Class->Templates[I];
if (Template->TemplatedDecl->USR == USR)
return static_cast<Method*>(Template->TemplatedDecl);
}
auto Method = new CppSharp::CppParser::Method();
HandleDeclaration(MD, Method);
Method->access = ConvertToAccess(MD->getAccess());
Method->methodKind = GetMethodKindFromDecl(MD->getDeclName());
Method->isStatic = MD->isStatic();
Method->isVirtual = MD->isVirtual();
Method->isConst = MD->isConst();
for (auto OverriddenMethod : MD->overridden_methods())
{
auto OM = WalkMethodCXX(OverriddenMethod);
Method->OverriddenMethods.push_back(OM);
}
switch (MD->getRefQualifier())
{
case clang::RefQualifierKind::RQ_None:
Method->refQualifier = RefQualifierKind::None;
break;
case clang::RefQualifierKind::RQ_LValue:
Method->refQualifier = RefQualifierKind::LValue;
break;
case clang::RefQualifierKind::RQ_RValue:
Method->refQualifier = RefQualifierKind::RValue;
break;
}
Class->Methods.push_back(Method);
WalkFunction(MD, Method);
if (const CXXConstructorDecl* CD = dyn_cast<CXXConstructorDecl>(MD))
{
Method->isDefaultConstructor = CD->isDefaultConstructor();
Method->isCopyConstructor = CD->isCopyConstructor();
Method->isMoveConstructor = CD->isMoveConstructor();
Method->isExplicit = CD->isExplicit();
}
else if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
{
}
else if (const CXXConversionDecl* CD = dyn_cast<CXXConversionDecl>(MD))
{
auto TL = MD->getTypeSourceInfo()->getTypeLoc().castAs<FunctionTypeLoc>();
auto RTL = TL.getReturnLoc();
Method->conversionType = GetQualifiedType(CD->getConversionType(), &RTL);
}
return Method;
}
//-----------------------------------//
Field* Parser::WalkFieldCXX(const clang::FieldDecl* FD, Class* Class)
{
using namespace clang;
const auto& USR = GetDeclUSR(FD);
auto FoundField = std::find_if(Class->Fields.begin(), Class->Fields.end(),
[&](Field* Field) { return Field->USR == USR; });
if (FoundField != Class->Fields.end())
return *FoundField;
auto F = new Field();
HandleDeclaration(FD, F);
F->_namespace = Class;
F->name = FD->getName().str();
auto TL = FD->getTypeSourceInfo()->getTypeLoc();
F->qualifiedType = GetQualifiedType(FD->getType(), &TL);
F->access = ConvertToAccess(FD->getAccess());
F->_class = Class;
F->isBitField = FD->isBitField();
if (F->isBitField && !F->isDependent && !FD->getBitWidth()->isInstantiationDependent())
F->bitWidth = FD->getBitWidthValue(c->getASTContext());
if (auto alignedAttr = FD->getAttr<clang::AlignedAttr>())
F->alignAs = GetAlignAs(alignedAttr);
Class->Fields.push_back(F);
return F;
}
//-----------------------------------//
TranslationUnit* Parser::GetTranslationUnit(clang::SourceLocation Loc,
SourceLocationKind *Kind)
{
using namespace clang;
clang::SourceManager& SM = c->getSourceManager();
if (Loc.isMacroID())
Loc = SM.getExpansionLoc(Loc);
StringRef File;
auto LocKind = GetLocationKind(Loc);
switch(LocKind)
{
case SourceLocationKind::Invalid:
File = "<invalid>";
break;
case SourceLocationKind::Builtin:
File = "<built-in>";
break;
case SourceLocationKind::CommandLine:
File = "<command-line>";
break;
default:
File = SM.getFilename(Loc);
assert(!File.empty() && "Expected to find a valid file");
break;
}
if (Kind)
*Kind = LocKind;
auto Unit = opts->ASTContext->FindOrCreateModule(File.str());
Unit->originalPtr = (void*) Unit;
assert(Unit->originalPtr != nullptr);
if (LocKind != SourceLocationKind::Invalid)
Unit->isSystemHeader = SM.isInSystemHeader(Loc);
return Unit;
}
//-----------------------------------//
TranslationUnit* Parser::GetTranslationUnit(const clang::Decl* D)
{
clang::SourceLocation Loc = D->getLocation();
SourceLocationKind Kind;
TranslationUnit* Unit = GetTranslationUnit(Loc, &Kind);
return Unit;
}
DeclarationContext* Parser::GetNamespace(const clang::Decl* D,
const clang::DeclContext *Ctx)
{
using namespace clang;
auto Context = Ctx;
// If the declaration is at global scope, just early exit.
if (Context->isTranslationUnit())
return GetTranslationUnit(D);
TranslationUnit* Unit = GetTranslationUnit(cast<Decl>(Context));
// Else we need to do a more expensive check to get all the namespaces,
// and then perform a reverse iteration to get the namespaces in order.
typedef SmallVector<const DeclContext *, 8> ContextsTy;
ContextsTy Contexts;
for(; Context != nullptr; Context = Context->getParent())
Contexts.push_back(Context);
assert(Contexts.back()->isTranslationUnit());
Contexts.pop_back();
DeclarationContext* DC = Unit;
for (auto I = Contexts.rbegin(), E = Contexts.rend(); I != E; ++I)
{
const auto* Ctx = *I;
switch(Ctx->getDeclKind())
{
case Decl::Namespace:
{
auto ND = cast<NamespaceDecl>(Ctx);
if (ND->isAnonymousNamespace())
continue;
auto Name = ND->getName();
DC = DC->FindCreateNamespace(Name.str());
((Namespace*)DC)->isAnonymous = ND->isAnonymousNamespace();
((Namespace*)DC)->isInline = ND->isInline();
HandleDeclaration(ND, DC);
continue;
}
case Decl::LinkageSpec:
{
const LinkageSpecDecl* LD = cast<LinkageSpecDecl>(Ctx);
continue;
}
case Decl::CXXRecord:
{
auto RD = cast<CXXRecordDecl>(Ctx);
DC = WalkRecordCXX(RD);
continue;
}
default:
{
auto D = cast<Decl>(Ctx);
auto Decl = WalkDeclaration(D);
DC = static_cast<DeclarationContext*>(Decl);
} }
}
return DC;
}
DeclarationContext* Parser::GetNamespace(const clang::Decl *D)
{
return GetNamespace(D, D->getDeclContext());
}
static PrimitiveType WalkBuiltinType(const clang::BuiltinType* Builtin)
{
assert(Builtin && "Expected a builtin type");
switch(Builtin->getKind())
{
case clang::BuiltinType::Void: return PrimitiveType::Void;
case clang::BuiltinType::Bool: return PrimitiveType::Bool;
case clang::BuiltinType::SChar: return PrimitiveType::SChar;
case clang::BuiltinType::Char_S: return PrimitiveType::Char;
case clang::BuiltinType::UChar:
case clang::BuiltinType::Char_U: return PrimitiveType::UChar;
case clang::BuiltinType::WChar_S:
case clang::BuiltinType::WChar_U: return PrimitiveType::WideChar;
case clang::BuiltinType::Char16: return PrimitiveType::Char16;
case clang::BuiltinType::Char32: return PrimitiveType::Char32;
case clang::BuiltinType::Short: return PrimitiveType::Short;
case clang::BuiltinType::UShort: return PrimitiveType::UShort;
case clang::BuiltinType::Int: return PrimitiveType::Int;
case clang::BuiltinType::UInt: return PrimitiveType::UInt;
case clang::BuiltinType::Long: return PrimitiveType::Long;
case clang::BuiltinType::ULong: return PrimitiveType::ULong;
case clang::BuiltinType::LongLong: return PrimitiveType::LongLong;
case clang::BuiltinType::ULongLong: return PrimitiveType::ULongLong;
case clang::BuiltinType::Int128: return PrimitiveType::Int128;
case clang::BuiltinType::UInt128: return PrimitiveType::UInt128;
case clang::BuiltinType::Half: return PrimitiveType::Half;
case clang::BuiltinType::Float: return PrimitiveType::Float;
case clang::BuiltinType::Double: return PrimitiveType::Double;
case clang::BuiltinType::LongDouble: return PrimitiveType::LongDouble;
case clang::BuiltinType::Float128: return PrimitiveType::Float128;
case clang::BuiltinType::NullPtr: return PrimitiveType::Null;
default: break;
}
return PrimitiveType::Null;
}
//-----------------------------------//
clang::TypeLoc ResolveTypeLoc(clang::TypeLoc TL, clang::TypeLoc::TypeLocClass Class)
{
using namespace clang;
auto TypeLocClass = TL.getTypeLocClass();
if (TypeLocClass == Class)
{
return TL;
}
if (TypeLocClass == TypeLoc::Qualified)
{
auto UTL = TL.getUnqualifiedLoc();
TL = UTL;
}
else if (TypeLocClass == TypeLoc::Elaborated)
{
auto ETL = TL.getAs<ElaboratedTypeLoc>();
auto ITL = ETL.getNextTypeLoc();
TL = ITL;
}
else if (TypeLocClass == TypeLoc::Paren)
{
auto PTL = TL.getAs<ParenTypeLoc>();
TL = PTL.getNextTypeLoc();
}
assert(TL.getTypeLocClass() == Class);
return TL;
}
static FriendKind ConvertFriendKind(clang::Decl::FriendObjectKind FK)
{
using namespace clang;
switch (FK)
{
case Decl::FriendObjectKind::FOK_Declared:
return FriendKind::Declared;
case Decl::FriendObjectKind::FOK_Undeclared:
return FriendKind::Undeclared;
default:
return FriendKind::None;
}
}
static CallingConvention ConvertCallConv(clang::CallingConv CC)
{
using namespace clang;
switch(CC)
{
case CC_C:
return CallingConvention::C;
case CC_X86StdCall:
return CallingConvention::StdCall;
case CC_X86FastCall:
return CallingConvention::FastCall;
case CC_X86ThisCall:
return CallingConvention::ThisCall;
default:
return CallingConvention::Unknown;
}
}
static ExceptionSpecType ConvertExceptionType(clang::ExceptionSpecificationType EST)
{
using namespace clang;
switch (EST)
{
case ExceptionSpecificationType::EST_BasicNoexcept:
return ExceptionSpecType::BasicNoexcept;
case ExceptionSpecificationType::EST_DependentNoexcept:
return ExceptionSpecType::DependentNoexcept;
case ExceptionSpecificationType::EST_NoexceptFalse:
return ExceptionSpecType::NoexceptFalse;
case ExceptionSpecificationType::EST_NoexceptTrue:
return ExceptionSpecType::NoexceptTrue;
case ExceptionSpecificationType::EST_Dynamic:
return ExceptionSpecType::Dynamic;
case ExceptionSpecificationType::EST_DynamicNone:
return ExceptionSpecType::DynamicNone;
case ExceptionSpecificationType::EST_MSAny:
return ExceptionSpecType::MSAny;
case ExceptionSpecificationType::EST_Unevaluated:
return ExceptionSpecType::Unevaluated;
case ExceptionSpecificationType::EST_Uninstantiated:
return ExceptionSpecType::Uninstantiated;
case ExceptionSpecificationType::EST_Unparsed:
return ExceptionSpecType::Unparsed;
default:
return ExceptionSpecType::None;
}
}
static ParserIntType ConvertIntType(clang::TargetInfo::IntType IT)
{
switch (IT)
{
case clang::TargetInfo::IntType::NoInt:
return ParserIntType::NoInt;
case clang::TargetInfo::IntType::SignedChar:
return ParserIntType::SignedChar;
case clang::TargetInfo::IntType::UnsignedChar:
return ParserIntType::UnsignedChar;
case clang::TargetInfo::IntType::SignedShort:
return ParserIntType::SignedShort;
case clang::TargetInfo::IntType::UnsignedShort:
return ParserIntType::UnsignedShort;
case clang::TargetInfo::IntType::SignedInt:
return ParserIntType::SignedInt;
case clang::TargetInfo::IntType::UnsignedInt:
return ParserIntType::UnsignedInt;
case clang::TargetInfo::IntType::SignedLong:
return ParserIntType::SignedLong;
case clang::TargetInfo::IntType::UnsignedLong:
return ParserIntType::UnsignedLong;
case clang::TargetInfo::IntType::SignedLongLong:
return ParserIntType::SignedLongLong;
case clang::TargetInfo::IntType::UnsignedLongLong:
return ParserIntType::UnsignedLongLong;
}
llvm_unreachable("Unknown parser integer type");
}
static const clang::Type* GetFinalType(const clang::Type* Ty)
{
auto FinalType = Ty;
while (true)
{
FinalType = FinalType->getUnqualifiedDesugaredType();
if (FinalType->getPointeeType().isNull())
return FinalType;
FinalType = FinalType->getPointeeType().getTypePtr();
}
}
Type* Parser::WalkType(clang::QualType QualType, const clang::TypeLoc* TL,
bool DesugarType)
{
using namespace clang;
if (QualType.isNull())
return nullptr;
auto LocValid = TL && !TL->isNull();
const clang::Type* Type = QualType.getTypePtr();
auto& AST = c->getASTContext();
if (DesugarType)
{
clang::QualType Desugared = QualType.getDesugaredType(AST);
assert(!Desugared.isNull() && "Expected a valid desugared type");
Type = Desugared.getTypePtr();
}
CppSharp::CppParser::AST::Type* Ty = nullptr;
assert(Type && "Expected a valid type");
switch(Type->getTypeClass())
{
case clang::Type::Atomic:
{
auto Atomic = Type->getAs<clang::AtomicType>();
assert(Atomic && "Expected an atomic type");
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
Ty = WalkType(Atomic->getValueType(), &Next);
break;
}
case clang::Type::Attributed:
{
auto Attributed = Type->getAs<clang::AttributedType>();
assert(Attributed && "Expected an attributed type");
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto AT = new AttributedType();
auto Modified = Attributed->getModifiedType();
AT->modified = GetQualifiedType(Modified, &Next);
auto Equivalent = Attributed->getEquivalentType();
AT->equivalent = GetQualifiedType(Equivalent, &Next);
Ty = AT;
break;
}
case clang::Type::Builtin:
{
auto Builtin = Type->getAs<clang::BuiltinType>();
assert(Builtin && "Expected a builtin type");
auto BT = new BuiltinType();
BT->type = WalkBuiltinType(Builtin);
Ty = BT;
break;
}
case clang::Type::Enum:
{
auto ET = Type->getAs<clang::EnumType>();
EnumDecl* ED = ET->getDecl();
auto TT = new TagType();
TT->declaration = TT->declaration = WalkDeclaration(ED);
Ty = TT;
break;
}
case clang::Type::Pointer:
{
auto Pointer = Type->getAs<clang::PointerType>();
auto P = new PointerType();
P->modifier = PointerType::TypeModifier::Pointer;
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto Pointee = Pointer->getPointeeType();
P->qualifiedPointee = GetQualifiedType(Pointee, &Next);
Ty = P;
break;
}
case clang::Type::Typedef:
{
auto TT = Type->getAs<clang::TypedefType>();
auto TD = TT->getDecl();
auto TTL = TD->getTypeSourceInfo()->getTypeLoc();
auto TDD = static_cast<TypedefNameDecl*>(WalkDeclaration(TD));
auto Type = new TypedefType();
Type->declaration = TDD;
Ty = Type;
break;
}
case clang::Type::Decayed:
{
auto DT = Type->getAs<clang::DecayedType>();
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto Type = new DecayedType();
Type->decayed = GetQualifiedType(DT->getDecayedType(), &Next);
Type->original = GetQualifiedType(DT->getOriginalType(), &Next);
Type->pointee = GetQualifiedType(DT->getPointeeType(), &Next);
Ty = Type;
break;
}
case clang::Type::Elaborated:
{
auto ET = Type->getAs<clang::ElaboratedType>();
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
Ty = WalkType(ET->getNamedType(), &Next);
break;
}
case clang::Type::Record:
{
auto RT = Type->getAs<clang::RecordType>();
RecordDecl* RD = RT->getDecl();
auto TT = new TagType();
TT->declaration = WalkDeclaration(RD);
Ty = TT;
break;
}
case clang::Type::Paren:
{
auto PT = Type->getAs<clang::ParenType>();
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
Ty = WalkType(PT->getInnerType(), &Next);
break;
}
case clang::Type::ConstantArray:
{
auto AT = AST.getAsConstantArrayType(QualType);
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto A = new ArrayType();
auto ElemTy = AT->getElementType();
A->qualifiedType = GetQualifiedType(ElemTy, &Next);
A->sizeType = ArrayType::ArraySize::Constant;
A->size = AST.getConstantArrayElementCount(AT);
if (!ElemTy->isDependentType() && !opts->skipLayoutInfo)
A->elementSize = (long)AST.getTypeSize(ElemTy);
Ty = A;
break;
}
case clang::Type::IncompleteArray:
{
auto AT = AST.getAsIncompleteArrayType(QualType);
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto A = new ArrayType();
A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next);
A->sizeType = ArrayType::ArraySize::Incomplete;
Ty = A;
break;
}
case clang::Type::DependentSizedArray:
{
auto AT = AST.getAsDependentSizedArrayType(QualType);
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto A = new ArrayType();
A->qualifiedType = GetQualifiedType(AT->getElementType(), &Next);
A->sizeType = ArrayType::ArraySize::Dependent;
//A->Size = AT->getSizeExpr();
Ty = A;
break;
}
case clang::Type::UnresolvedUsing:
{
auto UT = Type->getAs<clang::UnresolvedUsingType>();
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto U = new UnresolvedUsingType();
U->declaration = static_cast<UnresolvedUsingTypename*>(
WalkDeclaration(UT->getDecl()));
Ty = U;
break;
}
case clang::Type::FunctionNoProto:
{
auto FP = Type->getAs<clang::FunctionNoProtoType>();
FunctionNoProtoTypeLoc FTL;
TypeLoc RL;
TypeLoc Next;
if (LocValid)
{
while (!TL->isNull() && TL->getTypeLocClass() != TypeLoc::FunctionNoProto)
{
Next = TL->getNextTypeLoc();
TL = &Next;
}
if (!TL->isNull() && TL->getTypeLocClass() == TypeLoc::FunctionNoProto)
{
FTL = TL->getAs<FunctionNoProtoTypeLoc>();
RL = FTL.getReturnLoc();
}
}
auto F = new FunctionType();
F->returnType = GetQualifiedType(FP->getReturnType(), &RL);
F->callingConvention = ConvertCallConv(FP->getCallConv());
Ty = F;
break;
}
case clang::Type::FunctionProto:
{
auto FP = Type->getAs<clang::FunctionProtoType>();
FunctionProtoTypeLoc FTL;
TypeLoc RL;
TypeLoc Next;
clang::SourceLocation ParamStartLoc;
if (LocValid)
{
while (!TL->isNull() && TL->getTypeLocClass() != TypeLoc::FunctionProto)
{
Next = TL->getNextTypeLoc();
TL = &Next;
}
if (!TL->isNull() && TL->getTypeLocClass() == TypeLoc::FunctionProto)
{
FTL = TL->getAs<FunctionProtoTypeLoc>();
RL = FTL.getReturnLoc();
ParamStartLoc = FTL.getLParenLoc();
}
}
auto F = new FunctionType();
F->returnType = GetQualifiedType(FP->getReturnType(), &RL);
F->callingConvention = ConvertCallConv(FP->getCallConv());
F->exceptionSpecType = ConvertExceptionType(FP->getExceptionSpecType());
for (unsigned i = 0; i < FP->getNumParams(); ++i)
{
if (FTL && FTL.getParam(i))
{
auto PVD = FTL.getParam(i);
auto FA = WalkParameter(PVD, ParamStartLoc);
F->Parameters.push_back(FA);
}
else
{
auto FA = new Parameter();
auto Arg = FP->getParamType(i);
FA->name = "";
FA->qualifiedType = GetQualifiedType(Arg);
// In this case we have no valid value to use as a pointer so
// use a special value known to the managed side to make sure
// it gets ignored.
FA->originalPtr = IgnorePtr;
F->Parameters.push_back(FA);
}
}
Ty = F;
break;
}
case clang::Type::TypeOf:
{
auto TO = Type->getAs<clang::TypeOfType>();
Ty = WalkType(TO->getUnderlyingType());
break;
}
case clang::Type::TypeOfExpr:
{
auto TO = Type->getAs<clang::TypeOfExprType>();
Ty = WalkType(TO->getUnderlyingExpr()->getType());
break;
}
case clang::Type::MemberPointer:
{
auto MP = Type->getAs<clang::MemberPointerType>();
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto MPT = new MemberPointerType();
MPT->pointee = GetQualifiedType(MP->getPointeeType(), &Next);
Ty = MPT;
break;
}
case clang::Type::TemplateSpecialization:
{
auto TS = Type->getAs<clang::TemplateSpecializationType>();
auto TST = new TemplateSpecializationType();
TemplateName Name = TS->getTemplateName();
TST->_template = static_cast<Template*>(WalkDeclaration(
Name.getAsTemplateDecl()));
if (TS->isSugared())
TST->desugared = GetQualifiedType(TS->getCanonicalTypeInternal(), TL);
TypeLoc UTL, ETL, ITL;
if (LocValid)
{
auto TypeLocClass = TL->getTypeLocClass();
if (TypeLocClass == TypeLoc::Qualified)
{
UTL = TL->getUnqualifiedLoc();
TL = &UTL;
}
else if (TypeLocClass == TypeLoc::Elaborated)
{
ETL = TL->getAs<ElaboratedTypeLoc>();
ITL = ETL.getNextTypeLoc();
TL = &ITL;
}
assert(TL->getTypeLocClass() == TypeLoc::TemplateSpecialization);
}
TemplateSpecializationTypeLoc TSpecTL;
TemplateSpecializationTypeLoc *TSTL = 0;
if (LocValid)
{
TSpecTL = TL->getAs<TemplateSpecializationTypeLoc>();
TSTL = &TSpecTL;
}
ArrayRef<clang::TemplateArgument> TSArgs(TS->getArgs(), TS->getNumArgs());
TemplateArgumentList TArgs(TemplateArgumentList::OnStack, TSArgs);
TST->Arguments = WalkTemplateArgumentList(&TArgs, TSTL);
Ty = TST;
break;
}
case clang::Type::DependentTemplateSpecialization:
{
auto TS = Type->getAs<clang::DependentTemplateSpecializationType>();
auto TST = new DependentTemplateSpecializationType();
if (TS->isSugared())
TST->desugared = GetQualifiedType(TS->getCanonicalTypeInternal(), TL);
TypeLoc UTL, ETL, ITL;
if (LocValid)
{
auto TypeLocClass = TL->getTypeLocClass();
if (TypeLocClass == TypeLoc::Qualified)
{
UTL = TL->getUnqualifiedLoc();
TL = &UTL;
}
else if (TypeLocClass == TypeLoc::Elaborated)
{
ETL = TL->getAs<ElaboratedTypeLoc>();
ITL = ETL.getNextTypeLoc();
TL = &ITL;
}
assert(TL->getTypeLocClass() == TypeLoc::DependentTemplateSpecialization);
}
DependentTemplateSpecializationTypeLoc TSpecTL;
DependentTemplateSpecializationTypeLoc *TSTL = 0;
if (LocValid)
{
TSpecTL = TL->getAs<DependentTemplateSpecializationTypeLoc>();
TSTL = &TSpecTL;
}
ArrayRef<clang::TemplateArgument> TSArgs(TS->getArgs(), TS->getNumArgs());
TemplateArgumentList TArgs(TemplateArgumentList::OnStack, TSArgs);
TST->Arguments = WalkTemplateArgumentList(&TArgs, TSTL);
Ty = TST;
break;
}
case clang::Type::TemplateTypeParm:
{
auto TP = Type->getAs<TemplateTypeParmType>();
auto TPT = new CppSharp::CppParser::TemplateParameterType();
if (auto Ident = TP->getIdentifier())
TPT->parameter->name = Ident->getName().str();
TypeLoc UTL, ETL, ITL, Next;
if (LocValid)
{
auto TypeLocClass = TL->getTypeLocClass();
if (TypeLocClass == TypeLoc::Qualified)
{
UTL = TL->getUnqualifiedLoc();
TL = &UTL;
}
else if (TypeLocClass == TypeLoc::Elaborated)
{
ETL = TL->getAs<ElaboratedTypeLoc>();
ITL = ETL.getNextTypeLoc();
TL = &ITL;
}
while (TL->getTypeLocClass() != TypeLoc::TemplateTypeParm)
{
Next = TL->getNextTypeLoc();
TL = &Next;
}
assert(TL->getTypeLocClass() == TypeLoc::TemplateTypeParm);
auto TTTL = TL->getAs<TemplateTypeParmTypeLoc>();
TPT->parameter = WalkTypeTemplateParameter(TTTL.getDecl());
}
else if (TP->getDecl())
TPT->parameter = WalkTypeTemplateParameter(TP->getDecl());
TPT->depth = TP->getDepth();
TPT->index = TP->getIndex();
TPT->isParameterPack = TP->isParameterPack();
Ty = TPT;
break;
}
case clang::Type::SubstTemplateTypeParm:
{
auto TP = Type->getAs<SubstTemplateTypeParmType>();
auto TPT = new TemplateParameterSubstitutionType();
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto RepTy = TP->getReplacementType();
TPT->replacement = GetQualifiedType(RepTy, &Next);
TPT->replacedParameter = (TemplateParameterType*)
WalkType(clang::QualType(TP->getReplacedParameter(), 0), 0);
TPT->replacedParameter->parameter = WalkTypeTemplateParameter(
TP->getReplacedParameter()->getDecl());
Ty = TPT;
break;
}
case clang::Type::InjectedClassName:
{
auto ICN = Type->getAs<clang::InjectedClassNameType>();
auto ICNT = new InjectedClassNameType();
ICNT->_class = static_cast<Class*>(WalkDeclaration(
ICN->getDecl()));
ICNT->injectedSpecializationType = GetQualifiedType(
ICN->getInjectedSpecializationType());
Ty = ICNT;
break;
}
case clang::Type::DependentName:
{
auto DN = Type->getAs<clang::DependentNameType>();
auto DNT = new DependentNameType();
switch (DN->getQualifier()->getKind())
{
case clang::NestedNameSpecifier::SpecifierKind::TypeSpec:
case clang::NestedNameSpecifier::SpecifierKind::TypeSpecWithTemplate:
{
const auto& Qualifier = clang::QualType(DN->getQualifier()->getAsType(), 0);
if (LocValid)
{
const auto& DNTL = TL->getAs<DependentNameTypeLoc>();
if (!DNTL.isNull())
{
const auto& QL = DNTL.getQualifierLoc();
const auto& NNSL = QL.getTypeLoc();
DNT->qualifier = GetQualifiedType(Qualifier, &NNSL);
}
else
{
DNT->qualifier = GetQualifiedType(Qualifier, 0);
}
}
else
{
DNT->qualifier = GetQualifiedType(Qualifier, 0);
}
break;
}
default: break;
}
DNT->identifier = DN->getIdentifier()->getName().str();
Ty = DNT;
break;
}
case clang::Type::LValueReference:
{
auto LR = Type->getAs<clang::LValueReferenceType>();
auto P = new PointerType();
P->modifier = PointerType::TypeModifier::LVReference;
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto Pointee = LR->getPointeeType();
P->qualifiedPointee = GetQualifiedType(Pointee, &Next);
Ty = P;
break;
}
case clang::Type::RValueReference:
{
auto LR = Type->getAs<clang::RValueReferenceType>();
auto P = new PointerType();
P->modifier = PointerType::TypeModifier::RVReference;
TypeLoc Next;
if (LocValid) Next = TL->getNextTypeLoc();
auto Pointee = LR->getPointeeType();
P->qualifiedPointee = GetQualifiedType(Pointee, &Next);
Ty = P;
break;
}
case clang::Type::UnaryTransform:
{
auto UT = Type->getAs<clang::UnaryTransformType>();
TypeLoc Loc;
if (LocValid)
{
clang::TypeSourceInfo* TSI = TL->getAs<UnaryTransformTypeLoc>().getUnderlyingTInfo();
Loc = TSI->getTypeLoc();
}
auto UTT = new UnaryTransformType();
UTT->desugared = GetQualifiedType(UT->isSugared() ? UT->getCanonicalTypeInternal() : UT->getBaseType(), &Loc);
UTT->baseType = GetQualifiedType(UT->getBaseType(), &Loc);
Ty = UTT;
break;
}
case clang::Type::Vector:
{
auto V = Type->getAs<clang::VectorType>();
auto VT = new VectorType();
VT->elementType = GetQualifiedType(V->getElementType());
VT->numElements = V->getNumElements();
Ty = VT;
break;
}
case clang::Type::PackExpansion:
{
// TODO: stubbed
Ty = new PackExpansionType();
break;
}
case clang::Type::Auto:
{
auto AT = Type->getAs<clang::AutoType>();
if (AT->isSugared())
Ty = WalkType(AT->getCanonicalTypeInternal());
else
return nullptr;
break;
}
case clang::Type::Decltype:
{
auto DT = Type->getAs<clang::DecltypeType>();
Ty = WalkType(DT->getUnderlyingType(), TL);
break;
}
case clang::Type::MacroQualified:
{
auto MT = Type->getAs<clang::MacroQualifiedType>();
Ty = WalkType(MT->getUnderlyingType(), TL);
break;
}
default:
{
Debug("Unhandled type class '%s'\n", Type->getTypeClassName());
return nullptr;
} }
Ty->isDependent = Type->isDependentType();
return Ty;
}
//-----------------------------------//
Enumeration* Parser::WalkEnum(const clang::EnumDecl* ED)
{
using namespace clang;
auto NS = GetNamespace(ED);
assert(NS && "Expected a valid namespace");
auto E = NS->FindEnum(ED->getCanonicalDecl());
if (E && !E->isIncomplete)
return E;
if (!E)
{
auto Name = GetTagDeclName(ED);
if (!Name.empty())
E = NS->FindEnum(Name, /*Create=*/false);
else
{
// Enum with no identifier - try to find existing enum through enum items
for (auto it = ED->enumerator_begin(); it != ED->enumerator_end(); ++it)
{
EnumConstantDecl* ECD = (*it);
auto EnumItemName = ECD->getNameAsString();
E = NS->FindEnumWithItem(EnumItemName);
break;
}
}
}
if (E && !E->isIncomplete)
return E;
if (!E)
{
auto Name = GetTagDeclName(ED);
if (!Name.empty())
E = NS->FindEnum(Name, /*Create=*/true);
else
{
E = new Enumeration();
E->name = Name;
E->_namespace = NS;
NS->Enums.push_back(E);
}
HandleDeclaration(ED, E);
}
if (ED->isScoped())
E->modifiers = (Enumeration::EnumModifiers)
((int)E->modifiers | (int)Enumeration::EnumModifiers::Scoped);
// Get the underlying integer backing the enum.
clang::QualType IntType = ED->getIntegerType();
E->type = WalkType(IntType, 0);
E->builtinType = static_cast<BuiltinType*>(WalkType(IntType, 0,
/*DesugarType=*/true));
if (!ED->isThisDeclarationADefinition())
{
E->isIncomplete = true;
return E;
}
E->isIncomplete = false;
for(auto it = ED->enumerator_begin(); it != ED->enumerator_end(); ++it)
{
E->Items.push_back(WalkEnumItem(*it));
}
return E;
}
Enumeration::Item* Parser::WalkEnumItem(clang::EnumConstantDecl* ECD)
{
auto EnumItem = new Enumeration::Item();
HandleDeclaration(ECD, EnumItem);
EnumItem->name = ECD->getNameAsString();
auto Value = ECD->getInitVal();
EnumItem->value = Value.isSigned() ? Value.getSExtValue()
: Value.getZExtValue();
EnumItem->_namespace = GetNamespace(ECD);
std::string Text;
if (GetDeclText(ECD->getSourceRange(), Text))
EnumItem->expression = Text;
return EnumItem;
}
//-----------------------------------//
static const clang::CodeGen::CGFunctionInfo& GetCodeGenFunctionInfo(
clang::CodeGen::CodeGenTypes* CodeGenTypes, const clang::FunctionDecl* FD)
{
auto FTy = FD->getType()->getCanonicalTypeUnqualified();
return CodeGenTypes->arrangeFreeFunctionType(
FTy.castAs<clang::FunctionProtoType>());
}
bool Parser::CanCheckCodeGenInfo(clang::Sema& S, const clang::Type* Ty)
{
auto FinalType = GetFinalType(Ty);
if (FinalType->isDependentType() ||
FinalType->isInstantiationDependentType() || FinalType->isUndeducedType())
return false;
if (FinalType->isFunctionType())
{
auto FTy = FinalType->getAs<clang::FunctionType>();
auto CanCheck = CanCheckCodeGenInfo(S, FTy->getReturnType().getTypePtr());
if (!CanCheck)
return false;
if (FinalType->isFunctionProtoType())
{
auto FPTy = FinalType->getAs<clang::FunctionProtoType>();
for (const auto& ParamType : FPTy->getParamTypes())
{
auto CanCheck = CanCheckCodeGenInfo(S, ParamType.getTypePtr());
if (!CanCheck)
return false;
}
}
}
if (auto RT = FinalType->getAs<clang::RecordType>())
if (!HasLayout(RT->getDecl()))
return false;
// Lock in the MS inheritance model if we have a member pointer to a class,
// else we get an assertion error inside Clang's codegen machinery.
if (c->getTarget().getCXXABI().isMicrosoft())
{
if (auto MPT = Ty->getAs<clang::MemberPointerType>())
if (!MPT->isDependentType())
S.RequireCompleteType(clang::SourceLocation(), clang::QualType(Ty, 0), 1);
}
return true;
}
static clang::TypeLoc DesugarTypeLoc(const clang::TypeLoc& Loc)
{
using namespace clang;
switch (Loc.getTypeLocClass())
{
case TypeLoc::TypeLocClass::Attributed:
{
auto ATL = Loc.getAs<AttributedTypeLoc>();
return ATL.getModifiedLoc();
}
case TypeLoc::TypeLocClass::Paren:
{
auto PTL = Loc.getAs<ParenTypeLoc>();
return PTL.getInnerLoc();
}
default:
break;
}
return Loc;
}
void Parser::CompleteIfSpecializationType(const clang::QualType& QualType)
{
using namespace clang;
auto Type = QualType->getUnqualifiedDesugaredType();
auto RD = Type->getAsCXXRecordDecl();
if (!RD)
RD = const_cast<CXXRecordDecl*>(Type->getPointeeCXXRecordDecl());
ClassTemplateSpecializationDecl* CTS;
if (!RD ||
!(CTS = llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) ||
CTS->isCompleteDefinition())
return;
auto existingClient = c->getSema().getDiagnostics().getClient();
std::unique_ptr<::DiagnosticConsumer> SemaDiagnostics(new ::DiagnosticConsumer());
SemaDiagnostics->Decl = CTS;
c->getSema().getDiagnostics().setClient(SemaDiagnostics.get(), false);
c->getSema().InstantiateClassTemplateSpecialization(CTS->getBeginLoc(),
CTS, TSK_ImplicitInstantiation, false);
c->getSema().getDiagnostics().setClient(existingClient, false);
auto CT = WalkClassTemplate(CTS->getSpecializedTemplate());
auto USR = GetDeclUSR(CTS);
auto TS = CT->FindSpecialization(USR);
if (TS != nullptr && TS->isIncomplete)
{
TS->isIncomplete = false;
TS->specializationKind = WalkTemplateSpecializationKind(CTS->getSpecializationKind());
WalkRecordCXX(CTS, TS);
}
}
Parameter* Parser::WalkParameter(const clang::ParmVarDecl* PVD,
const clang::SourceLocation& ParamStartLoc)
{
using namespace clang;
auto P = walkedParameters[PVD];
if (P)
return P;
P = new Parameter();
P->name = PVD->getNameAsString();
TypeLoc PTL;
if (auto TSI = PVD->getTypeSourceInfo())
PTL = TSI->getTypeLoc();
auto paramRange = PVD->getSourceRange();
paramRange.setBegin(ParamStartLoc);
HandlePreprocessedEntities(P, paramRange, MacroLocation::FunctionParameters);
const auto& Type = PVD->getOriginalType();
auto Function = PVD->getParentFunctionOrMethod();
if (Function && cast<NamedDecl>(Function)->isExternallyVisible())
CompleteIfSpecializationType(Type);
P->qualifiedType = GetQualifiedType(Type, &PTL);
P->hasDefaultValue = PVD->hasDefaultArg();
P->index = PVD->getFunctionScopeIndex();
if (PVD->hasDefaultArg() && !PVD->hasUnparsedDefaultArg())
{
if (PVD->hasUninstantiatedDefaultArg())
P->defaultArgument = WalkExpressionObsolete(PVD->getUninstantiatedDefaultArg());
else
P->defaultArgument = WalkExpressionObsolete(PVD->getDefaultArg());
}
HandleDeclaration(PVD, P);
walkedParameters[PVD] = P;
auto Context = cast<Decl>(PVD->getDeclContext());
P->_namespace = static_cast<DeclarationContext*>(WalkDeclaration(Context));
return P;
}
void Parser::SetBody(const clang::FunctionDecl* FD, Function* F)
{
F->body = GetFunctionBody(FD);
F->isInline = FD->isInlined();
if (!F->body.empty() && F->isInline)
return;
for (const auto& R : FD->redecls())
{
if (F->body.empty())
F->body = GetFunctionBody(R);
F->isInline |= R->isInlined();
if (!F->body.empty() && F->isInline)
break;
}
}
static bool IsInvalid(clang::Stmt* Body, std::unordered_set<clang::Stmt*>& Bodies)
{
using namespace clang;
if (Bodies.find(Body) != Bodies.end())
return false;
Bodies.insert(Body);
if (auto E = dyn_cast<clang::Expr>(Body))
if (E->containsErrors())
return true;
Decl* D = 0;
switch (Body->getStmtClass())
{
case clang::Stmt::StmtClass::DeclRefExprClass:
D = cast<clang::DeclRefExpr>(Body)->getDecl();
break;
case clang::Stmt::StmtClass::MemberExprClass:
D = cast<clang::MemberExpr>(Body)->getMemberDecl();
break;
default:
break;
}
if (D)
{
if (D->isInvalidDecl())
return true;
if (auto F = dyn_cast<FunctionDecl>(D))
if (IsInvalid(F->getBody(), Bodies))
return true;
}
for (auto C : Body->children())
if (IsInvalid(C, Bodies))
return true;
return false;
}
void Parser::MarkValidity(Function* F)
{
using namespace clang;
auto FD = static_cast<FunctionDecl*>(F->originalPtr);
if (!FD->getTemplateInstantiationPattern() || !FD->isExternallyVisible())
return;
auto existingClient = c->getSema().getDiagnostics().getClient();
std::unique_ptr<::DiagnosticConsumer> SemaDiagnostics(new ::DiagnosticConsumer());
SemaDiagnostics->Decl = FD;
c->getSema().getDiagnostics().setClient(SemaDiagnostics.get(), false);
c->getSema().InstantiateFunctionDefinition(FD->getBeginLoc(), FD,
/*Recursive*/true);
F->isInvalid = FD->isInvalidDecl();
if (!F->isInvalid)
{
std::unordered_set<clang::Stmt*> Bodies{ 0 };
F->isInvalid = IsInvalid(FD->getBody(), Bodies);
}
c->getSema().getDiagnostics().setClient(existingClient, false);
}
void Parser::WalkFunction(const clang::FunctionDecl* FD, Function* F)
{
using namespace clang;
assert(FD->getBuiltinID() == 0);
auto FT = FD->getType()->getAs<clang::FunctionType>();
auto NS = GetNamespace(FD);
assert(NS && "Expected a valid namespace");
F->name = FD->getNameAsString();
F->_namespace = NS;
F->isConstExpr = FD->isConstexpr();
F->isVariadic = FD->isVariadic();
F->isDependent = FD->isDependentContext();
F->isPure = FD->isPure();
F->isDeleted = FD->isDeleted();
F->isDefaulted = FD->isDefaulted();
SetBody(FD, F);
if (auto InstantiatedFrom = FD->getTemplateInstantiationPattern())
F->instantiatedFrom = static_cast<Function*>(WalkDeclaration(InstantiatedFrom));
auto FK = FD->getFriendObjectKind();
F->friendKind = ConvertFriendKind(FK);
auto CC = FT->getCallConv();
F->callingConvention = ConvertCallConv(CC);
F->operatorKind = GetOperatorKindFromDecl(FD->getDeclName());
TypeLoc RTL;
FunctionTypeLoc FTL;
if (auto TSI = FD->getTypeSourceInfo())
{
auto Loc = DesugarTypeLoc(TSI->getTypeLoc());
FTL = Loc.getAs<FunctionTypeLoc>();
if (FTL)
{
RTL = FTL.getReturnLoc();
auto& SM = c->getSourceManager();
auto headStartLoc = GetDeclStartLocation(c.get(), FD);
auto headEndLoc = SM.getExpansionLoc(FTL.getLParenLoc());
auto headRange = clang::SourceRange(headStartLoc, headEndLoc);
HandlePreprocessedEntities(F, headRange, MacroLocation::FunctionHead);
HandlePreprocessedEntities(F, FTL.getParensRange(), MacroLocation::FunctionParameters);
}
}
auto ReturnType = FD->getReturnType();
if (FD->isExternallyVisible())
CompleteIfSpecializationType(ReturnType);
F->returnType = GetQualifiedType(ReturnType, &RTL);
const auto& Mangled = GetDeclMangledName(FD);
F->mangled = Mangled;
const auto& Body = GetFunctionBody(FD);
F->body = Body;
clang::SourceLocation ParamStartLoc = FD->getBeginLoc();
clang::SourceLocation ResultLoc;
auto FTSI = FD->getTypeSourceInfo();
if (FTSI)
{
auto FTL = FTSI->getTypeLoc();
while (FTL && !FTL.getAs<FunctionTypeLoc>())
FTL = FTL.getNextTypeLoc();
if (FTL)
{
auto FTInfo = FTL.castAs<FunctionTypeLoc>();
assert(!FTInfo.isNull());
ParamStartLoc = FTInfo.getLParenLoc();
ResultLoc = FTInfo.getReturnLoc().getBeginLoc();
}
}
clang::SourceLocation BeginLoc = FD->getBeginLoc();
if (ResultLoc.isValid())
BeginLoc = ResultLoc;
clang::SourceRange Range(BeginLoc, FD->getEndLoc());
std::string Sig;
if (GetDeclText(Range, Sig))
F->signature = Sig;
for (auto VD : FD->parameters())
{
auto P = WalkParameter(VD, ParamStartLoc);
F->Parameters.push_back(P);
ParamStartLoc = VD->getEndLoc();
}
if (!opts->skipFunctionBodies)
{
if (FD->hasBody())
{
if (auto Body = FD->getBody())
F->bodyStmt = WalkStatement(Body);
}
}
auto& CXXABI = codeGenTypes->getCXXABI();
bool HasThisReturn = false;
if (auto CD = dyn_cast<CXXConstructorDecl>(FD))
HasThisReturn = CXXABI.HasThisReturn(GlobalDecl(CD, Ctor_Complete));
else if (auto DD = dyn_cast<CXXDestructorDecl>(FD))
HasThisReturn = CXXABI.HasThisReturn(GlobalDecl(DD, Dtor_Complete));
else
HasThisReturn = CXXABI.HasThisReturn(FD);
F->hasThisReturn = HasThisReturn;
if (auto FTSI = FD->getTemplateSpecializationInfo())
F->specializationInfo = WalkFunctionTemplateSpec(FTSI, F);
const CXXMethodDecl* MD;
if (FD->isDependentContext() ||
((MD = dyn_cast<CXXMethodDecl>(FD)) && !MD->isStatic() &&
!HasLayout(cast<CXXRecordDecl>(MD->getDeclContext()))) ||
!CanCheckCodeGenInfo(c->getSema(), FD->getReturnType().getTypePtr()) ||
std::any_of(FD->parameters().begin(), FD->parameters().end(),
[this](auto* P) { return !CanCheckCodeGenInfo(c->getSema(), P->getType().getTypePtr()); }))
{
F->qualifiedType = GetQualifiedType(FD->getType(), &FTL);
return;
}
auto& CGInfo = GetCodeGenFunctionInfo(codeGenTypes.get(), FD);
F->isReturnIndirect = CGInfo.getReturnInfo().isIndirect() ||
CGInfo.getReturnInfo().isInAlloca();
unsigned Index = 0;
for (const auto& Arg : CGInfo.arguments())
{
F->Parameters[Index++]->isIndirect =
Arg.info.isIndirect() && !Arg.info.getIndirectByVal();
}
MarkValidity(F);
F->qualifiedType = GetQualifiedType(FD->getType(), &FTL);
}
Function* Parser::WalkFunction(const clang::FunctionDecl* FD)
{
using namespace clang;
assert (FD->getBuiltinID() == 0);
auto NS = GetNamespace(FD);
assert(NS && "Expected a valid namespace");
auto USR = GetDeclUSR(FD);
auto F = NS->FindFunction(USR);
if (F != nullptr)
return F;
F = new Function();
HandleDeclaration(FD, F);
NS->Functions.push_back(F);
WalkFunction(FD, F);
return F;
}
//-----------------------------------//
SourceLocationKind Parser::GetLocationKind(const clang::SourceLocation& Loc)
{
using namespace clang;
clang::SourceManager& SM = c->getSourceManager();
clang::PresumedLoc PLoc = SM.getPresumedLoc(Loc);
if (PLoc.isInvalid())
return SourceLocationKind::Invalid;
const char *FileName = PLoc.getFilename();
if(strcmp(FileName, "<built-in>") == 0)
return SourceLocationKind::Builtin;
if(strcmp(FileName, "<command line>") == 0)
return SourceLocationKind::CommandLine;
if(SM.getFileCharacteristic(Loc) == clang::SrcMgr::C_User)
return SourceLocationKind::User;
return SourceLocationKind::System;
}
bool Parser::IsValidDeclaration(const clang::SourceLocation& Loc)
{
auto Kind = GetLocationKind(Loc);
return Kind == SourceLocationKind::User;
}
//-----------------------------------//
void Parser::WalkAST(clang::TranslationUnitDecl* TU)
{
for (auto D : TU->decls())
{
if (D->getBeginLoc().isValid() &&
!c->getSourceManager().isInSystemHeader(D->getBeginLoc()))
WalkDeclarationDef(D);
}
}
//-----------------------------------//
void Parser::WalkVariable(const clang::VarDecl* VD, Variable* Var)
{
HandleDeclaration(VD, Var);
Var->isConstExpr = VD->isConstexpr();
Var->name = VD->getName().str();
Var->access = ConvertToAccess(VD->getAccess());
auto Init = VD->getAnyInitializer();
Var->initializer = (Init && !Init->getType()->isDependentType()) ?
WalkVariableInitializerExpression(Init) : nullptr;
auto TL = VD->getTypeSourceInfo()->getTypeLoc();
Var->qualifiedType = GetQualifiedType(VD->getType(), &TL);
auto Mangled = GetDeclMangledName(VD);
Var->mangled = Mangled;
}
Variable* Parser::WalkVariable(const clang::VarDecl *VD)
{
using namespace clang;
auto NS = GetNamespace(VD);
assert(NS && "Expected a valid namespace");
auto USR = GetDeclUSR(VD);
if (auto Var = NS->FindVariable(USR))
return Var;
auto Var = new Variable();
Var->_namespace = NS;
WalkVariable(VD, Var);
NS->Variables.push_back(Var);
return Var;
}
//-----------------------------------//
Friend* Parser::WalkFriend(const clang::FriendDecl *FD)
{
using namespace clang;
auto NS = GetNamespace(FD);
assert(NS && "Expected a valid namespace");
auto FriendDecl = FD->getFriendDecl();
// Work around clangIndex's lack of USR handling for friends and pass the
// pointed to friend declaration instead.
auto USR = GetDeclUSR(FriendDecl ? ((Decl*)FriendDecl) : FD);
if (auto F = NS->FindFriend(USR))
return F;
auto F = new Friend();
HandleDeclaration(FD, F);
F->_namespace = NS;
if (FriendDecl)
{
F->declaration = GetDeclarationFromFriend(FriendDecl);
}
NS->Friends.push_back(F);
return F;
}
//-----------------------------------//
bool Parser::GetDeclText(clang::SourceRange SR, std::string& Text)
{
using namespace clang;
clang::SourceManager& SM = c->getSourceManager();
const LangOptions &LangOpts = c->getLangOpts();
auto Range = CharSourceRange::getTokenRange(SR);
bool Invalid;
Text = Lexer::getSourceText(Range, SM, LangOpts, &Invalid).str();
return !Invalid && !Text.empty();
}
PreprocessedEntity* Parser::WalkPreprocessedEntity(
Declaration* Decl, clang::PreprocessedEntity* PPEntity)
{
using namespace clang;
for (unsigned I = 0, E = Decl->PreprocessedEntities.size();
I != E; ++I)
{
auto Entity = Decl->PreprocessedEntities[I];
if (Entity->originalPtr == PPEntity)
return Entity;
}
auto& P = c->getPreprocessor();
PreprocessedEntity* Entity = 0;
switch(PPEntity->getKind())
{
case clang::PreprocessedEntity::MacroExpansionKind:
{
auto ME = cast<clang::MacroExpansion>(PPEntity);
auto Expansion = new MacroExpansion();
auto MD = ME->getDefinition();
if (MD && MD->getKind() != clang::PreprocessedEntity::InvalidKind)
Expansion->definition = (MacroDefinition*)
WalkPreprocessedEntity(Decl, ME->getDefinition());
Entity = Expansion;
std::string Text;
GetDeclText(PPEntity->getSourceRange(), Text);
static_cast<MacroExpansion*>(Entity)->text = Text;
break;
}
case clang::PreprocessedEntity::MacroDefinitionKind:
{
auto MD = cast<clang::MacroDefinitionRecord>(PPEntity);
if (!IsValidDeclaration(MD->getLocation()))
break;
const IdentifierInfo* II = MD->getName();
assert(II && "Expected valid identifier info");
MacroInfo* MI = P.getMacroInfo((IdentifierInfo*)II);
if (!MI || MI->isBuiltinMacro())
break;
clang::SourceManager& SM = c->getSourceManager();
const LangOptions &LangOpts = c->getLangOpts();
auto Loc = MI->getDefinitionLoc();
if (!IsValidDeclaration(Loc))
break;
clang::SourceLocation BeginExpr =
Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
auto Range = clang::CharSourceRange::getTokenRange(
BeginExpr, MI->getDefinitionEndLoc());
bool Invalid;
StringRef Expression = Lexer::getSourceText(Range, SM, LangOpts,
&Invalid);
if (Invalid || Expression.empty())
break;
auto Definition = new MacroDefinition();
Definition->lineNumberStart = SM.getExpansionLineNumber(MD->getLocation());
Definition->lineNumberEnd = SM.getExpansionLineNumber(MD->getLocation());
Entity = Definition;
Definition->name = II->getName().trim().str();
Definition->expression = Expression.trim().str();
}
case clang::PreprocessedEntity::InclusionDirectiveKind:
// nothing to be done for InclusionDirectiveKind
break;
default:
llvm_unreachable("Unknown PreprocessedEntity");
}
if (!Entity)
return nullptr;
Entity->originalPtr = PPEntity;
auto Namespace = GetTranslationUnit(PPEntity->getSourceRange().getBegin());
if (Decl->kind == CppSharp::CppParser::AST::DeclarationKind::TranslationUnit)
{
Namespace->PreprocessedEntities.push_back(Entity);
}
else
{
Decl->PreprocessedEntities.push_back(Entity);
}
return Entity;
}
void Parser::HandlePreprocessedEntities(Declaration* Decl)
{
using namespace clang;
auto PPRecord = c->getPreprocessor().getPreprocessingRecord();
for (auto it = PPRecord->begin(); it != PPRecord->end(); ++it)
{
clang::PreprocessedEntity* PPEntity = (*it);
auto Entity = WalkPreprocessedEntity(Decl, PPEntity);
}
}
AST::ExpressionObsolete* Parser::WalkExpressionObsolete(const clang::Expr* Expr)
{
using namespace clang;
switch (Expr->getStmtClass())
{
case clang::Stmt::BinaryOperatorClass:
{
auto BinaryOperator = cast<clang::BinaryOperator>(Expr);
return new AST::BinaryOperatorObsolete(GetStringFromStatement(Expr),
WalkExpressionObsolete(BinaryOperator->getLHS()), WalkExpressionObsolete(BinaryOperator->getRHS()),
BinaryOperator->getOpcodeStr().str());
}
case clang::Stmt::CallExprClass:
{
auto CallExpr = cast<clang::CallExpr>(Expr);
auto CallExpression = new AST::CallExprObsolete(GetStringFromStatement(Expr),
CallExpr->getCalleeDecl() ? WalkDeclaration(CallExpr->getCalleeDecl()) : 0);
for (auto arg : CallExpr->arguments())
{
CallExpression->Arguments.push_back(WalkExpressionObsolete(arg));
}
return CallExpression;
}
case clang::Stmt::DeclRefExprClass:
return new AST::ExpressionObsolete(GetStringFromStatement(Expr), StatementClassObsolete::DeclRefExprClass,
WalkDeclaration(cast<clang::DeclRefExpr>(Expr)->getDecl()));
case clang::Stmt::CStyleCastExprClass:
case clang::Stmt::CXXConstCastExprClass:
case clang::Stmt::CXXDynamicCastExprClass:
case clang::Stmt::CXXFunctionalCastExprClass:
case clang::Stmt::CXXReinterpretCastExprClass:
case clang::Stmt::CXXStaticCastExprClass:
case clang::Stmt::ImplicitCastExprClass:
return WalkExpressionObsolete(cast<clang::CastExpr>(Expr)->getSubExprAsWritten());
case clang::Stmt::CXXOperatorCallExprClass:
{
auto OperatorCallExpr = cast<clang::CXXOperatorCallExpr>(Expr);
return new AST::ExpressionObsolete(GetStringFromStatement(Expr), StatementClassObsolete::CXXOperatorCallExpr,
OperatorCallExpr->getCalleeDecl() ? WalkDeclaration(OperatorCallExpr->getCalleeDecl()) : 0);
}
case clang::Stmt::CXXConstructExprClass:
case clang::Stmt::CXXTemporaryObjectExprClass:
{
auto ConstructorExpr = cast<clang::CXXConstructExpr>(Expr);
if (ConstructorExpr->getNumArgs() == 1)
{
auto Arg = ConstructorExpr->getArg(0);
auto TemporaryExpr = dyn_cast<clang::MaterializeTemporaryExpr>(Arg);
if (TemporaryExpr)
{
auto SubTemporaryExpr = TemporaryExpr->getSubExpr();
auto Cast = dyn_cast<clang::CastExpr>(SubTemporaryExpr);
if (!Cast ||
(Cast->getSubExprAsWritten()->getStmtClass() != clang::Stmt::IntegerLiteralClass &&
Cast->getSubExprAsWritten()->getStmtClass() != clang::Stmt::CXXNullPtrLiteralExprClass))
return WalkExpressionObsolete(SubTemporaryExpr);
return new AST::CXXConstructExprObsolete(GetStringFromStatement(Expr),
WalkDeclaration(ConstructorExpr->getConstructor()));
}
}
auto ConstructorExpression = new AST::CXXConstructExprObsolete(GetStringFromStatement(Expr),
WalkDeclaration(ConstructorExpr->getConstructor()));
for (auto arg : ConstructorExpr->arguments())
{
ConstructorExpression->Arguments.push_back(WalkExpressionObsolete(arg));
}
return ConstructorExpression;
}
case clang::Stmt::CXXBindTemporaryExprClass:
return WalkExpressionObsolete(cast<clang::CXXBindTemporaryExpr>(Expr)->getSubExpr());
case clang::Stmt::CXXDefaultArgExprClass:
return WalkExpressionObsolete(cast<clang::CXXDefaultArgExpr>(Expr)->getExpr());
case clang::Stmt::MaterializeTemporaryExprClass:
return WalkExpressionObsolete(cast<clang::MaterializeTemporaryExpr>(Expr)->getSubExpr());
default:
break;
}
if (!Expr->isValueDependent())
{
clang::Expr::EvalResult integer;
if (Expr->getStmtClass() == clang::Stmt::CharacterLiteralClass)
{
auto result = GetStringFromStatement(Expr);
if (!result.empty() &&
result.front() != '\'' &&
Expr->EvaluateAsInt(integer, c->getASTContext()))
{
result = integer.Val.getInt().toString(10);
}
return new AST::ExpressionObsolete(result);
}
else if (Expr->getStmtClass() != clang::Stmt::CXXBoolLiteralExprClass &&
Expr->getStmtClass() != clang::Stmt::UnaryExprOrTypeTraitExprClass &&
Expr->EvaluateAsInt(integer, c->getASTContext())
)
{
return new AST::ExpressionObsolete(integer.Val.getInt().toString(10));
}
}
return new AST::ExpressionObsolete(GetStringFromStatement(Expr));
}
AST::ExpressionObsolete* Parser::WalkVariableInitializerExpression(const clang::Expr* Expr)
{
using namespace clang;
if (IsCastStmt(Expr->getStmtClass()))
return WalkVariableInitializerExpression(cast<clang::CastExpr>(Expr)->getSubExprAsWritten());
if (IsLiteralStmt(Expr->getStmtClass()))
return WalkExpressionObsolete(Expr);
clang::Expr::EvalResult result;
if (Expr->EvaluateAsConstantExpr(result, c->getASTContext()))
{
std::string s;
llvm::raw_string_ostream out(s);
APValuePrinter printer{c->getASTContext(), out};
if (printer.Print(result.Val, Expr->getType()))
return new AST::ExpressionObsolete(out.str());
}
return WalkExpressionObsolete(Expr);
}
bool Parser::IsCastStmt(clang::Stmt::StmtClass stmt)
{
switch (stmt)
{
case clang::Stmt::CStyleCastExprClass:
case clang::Stmt::CXXConstCastExprClass:
case clang::Stmt::CXXDynamicCastExprClass:
case clang::Stmt::CXXFunctionalCastExprClass:
case clang::Stmt::CXXReinterpretCastExprClass:
case clang::Stmt::CXXStaticCastExprClass:
case clang::Stmt::ImplicitCastExprClass:
return true;
default:
return false;
}
}
bool Parser::IsLiteralStmt(clang::Stmt::StmtClass stmt)
{
switch (stmt)
{
case clang::Stmt::CharacterLiteralClass:
case clang::Stmt::FixedPointLiteralClass:
case clang::Stmt::FloatingLiteralClass:
case clang::Stmt::IntegerLiteralClass:
case clang::Stmt::StringLiteralClass:
case clang::Stmt::ImaginaryLiteralClass:
case clang::Stmt::UserDefinedLiteralClass:
case clang::Stmt::CXXNullPtrLiteralExprClass:
case clang::Stmt::CXXBoolLiteralExprClass:
return true;
default:
return false;
}
}
std::string Parser::GetStringFromStatement(const clang::Stmt* Statement)
{
using namespace clang;
PrintingPolicy Policy(c->getLangOpts());
std::string s;
llvm::raw_string_ostream as(s);
Statement->printPretty(as, 0, Policy);
return as.str();
}
std::string Parser::GetFunctionBody(const clang::FunctionDecl* FD)
{
if (!FD->getBody())
return "";
clang::PrintingPolicy Policy(c->getLangOpts());
std::string s;
llvm::raw_string_ostream as(s);
FD->getBody()->printPretty(as, 0, Policy);
return as.str();
}
void Parser::HandlePreprocessedEntities(Declaration* Decl,
clang::SourceRange sourceRange,
MacroLocation macroLocation)
{
if (sourceRange.isInvalid()) return;
auto& SourceMgr = c->getSourceManager();
auto isBefore = SourceMgr.isBeforeInTranslationUnit(sourceRange.getEnd(),
sourceRange.getBegin());
if (isBefore) return;
assert(!SourceMgr.isBeforeInTranslationUnit(sourceRange.getEnd(),
sourceRange.getBegin()));
using namespace clang;
auto PPRecord = c->getPreprocessor().getPreprocessingRecord();
auto Range = PPRecord->getPreprocessedEntitiesInRange(sourceRange);
for (auto PPEntity : Range)
{
auto Entity = WalkPreprocessedEntity(Decl, PPEntity);
if (!Entity) continue;
if (Entity->macroLocation == MacroLocation::Unknown)
Entity->macroLocation = macroLocation;
}
}
void Parser::HandleOriginalText(const clang::Decl* D, Declaration* Decl)
{
auto& SM = c->getSourceManager();
auto& LangOpts = c->getLangOpts();
auto Range = clang::CharSourceRange::getTokenRange(D->getSourceRange());
bool Invalid;
auto DeclText = clang::Lexer::getSourceText(Range, SM, LangOpts, &Invalid);
if (!Invalid)
Decl->debugText = DeclText.str();
}
void Parser::HandleDeclaration(const clang::Decl* D, Declaration* Decl)
{
if (Decl->originalPtr != nullptr)
return;
Decl->originalPtr = (void*) D;
Decl->USR = GetDeclUSR(D);
Decl->isImplicit = D->isImplicit();
Decl->location = SourceLocation(D->getLocation().getRawEncoding());
auto IsDeclExplicit = IsExplicit(D);
if (IsDeclExplicit)
{
Decl->lineNumberStart = c->getSourceManager().getExpansionLineNumber(D->getBeginLoc());
Decl->lineNumberEnd = c->getSourceManager().getExpansionLineNumber(D->getEndLoc());
}
else
{
Decl->lineNumberStart = -1;
Decl->lineNumberEnd = -1;
}
if (Decl->PreprocessedEntities.empty() && !D->isImplicit())
{
if (clang::dyn_cast<clang::TranslationUnitDecl>(D))
{
HandlePreprocessedEntities(Decl);
}
else if (clang::dyn_cast<clang::ParmVarDecl>(D))
{
// Ignore function parameters as we already walk their preprocessed entities.
}
else if (IsDeclExplicit)
{
auto startLoc = GetDeclStartLocation(c.get(), D);
auto endLoc = D->getEndLoc();
auto range = clang::SourceRange(startLoc, endLoc);
HandlePreprocessedEntities(Decl, range);
}
}
if (IsDeclExplicit)
HandleOriginalText(D, Decl);
HandleComments(D, Decl);
if (const clang::ValueDecl *VD = clang::dyn_cast_or_null<clang::ValueDecl>(D))
Decl->isDependent = VD->getType()->isDependentType();
if (const clang::DeclContext *DC = clang::dyn_cast_or_null<clang::DeclContext>(D))
Decl->isDependent |= DC->isDependentContext();
Decl->access = ConvertToAccess(D->getAccess());
}
//-----------------------------------//
Declaration* Parser::WalkDeclarationDef(clang::Decl* D)
{
auto Decl = WalkDeclaration(D);
if (!Decl || Decl->definitionOrder > 0)
return Decl;
// We store a definition order index into the declarations.
// This is needed because declarations are added to their contexts as
// soon as they are referenced and we need to know the original order
// of the declarations.
clang::RecordDecl* RecordDecl;
if ((RecordDecl = llvm::dyn_cast<clang::RecordDecl>(D)) &&
RecordDecl->isCompleteDefinition())
Decl->definitionOrder = index++;
return Decl;
}
Declaration* Parser::WalkDeclaration(const clang::Decl* D)
{
using namespace clang;
if (D == nullptr)
return nullptr;
Declaration* Decl = nullptr;
auto Kind = D->getKind();
switch(D->getKind())
{
case Decl::Record:
{
auto RD = cast<RecordDecl>(D);
Decl = WalkRecord(RD);
break;
}
case Decl::CXXRecord:
{
auto RD = cast<CXXRecordDecl>(D);
Decl = WalkRecordCXX(RD);
break;
}
case Decl::ClassTemplate:
{
auto TD = cast<ClassTemplateDecl>(D);
auto Template = WalkClassTemplate(TD);
Decl = Template;
break;
}
case Decl::ClassTemplateSpecialization:
{
auto TS = cast<ClassTemplateSpecializationDecl>(D);
auto CT = WalkClassTemplateSpecialization(TS);
Decl = CT;
break;
}
case Decl::ClassTemplatePartialSpecialization:
{
auto TS = cast<ClassTemplatePartialSpecializationDecl>(D);
auto CT = WalkClassTemplatePartialSpecialization(TS);
Decl = CT;
break;
}
case Decl::FunctionTemplate:
{
auto TD = cast<FunctionTemplateDecl>(D);
auto FT = WalkFunctionTemplate(TD);
Decl = FT;
break;
}
case Decl::VarTemplate:
{
auto TD = cast<VarTemplateDecl>(D);
auto Template = WalkVarTemplate(TD);
Decl = Template;
break;
}
case Decl::VarTemplateSpecialization:
{
auto TS = cast<VarTemplateSpecializationDecl>(D);
auto CT = WalkVarTemplateSpecialization(TS);
Decl = CT;
break;
}
case Decl::VarTemplatePartialSpecialization:
{
auto TS = cast<VarTemplatePartialSpecializationDecl>(D);
auto CT = WalkVarTemplatePartialSpecialization(TS);
Decl = CT;
break;
}
case Decl::TypeAliasTemplate:
{
auto TD = cast<TypeAliasTemplateDecl>(D);
auto TA = WalkTypeAliasTemplate(TD);
Decl = TA;
break;
}
case Decl::Enum:
{
auto ED = cast<EnumDecl>(D);
Decl = WalkEnum(ED);
break;
}
case Decl::EnumConstant:
{
auto ED = cast<EnumConstantDecl>(D);
auto E = static_cast<Enumeration*>(GetNamespace(ED));
assert(E && "Expected a valid enumeration");
Decl = E->FindItemByName(ED->getNameAsString());
break;
}
case Decl::Function:
{
auto FD = cast<FunctionDecl>(D);
// Check for and ignore built-in functions.
if (FD->getBuiltinID() != 0)
break;
Decl = WalkFunction(FD);
break;
}
case Decl::LinkageSpec:
{
auto LS = cast<LinkageSpecDecl>(D);
for (auto it = LS->decls_begin(); it != LS->decls_end(); ++it)
{
clang::Decl* D = (*it);
Decl = WalkDeclarationDef(D);
}
break;
}
case Decl::Typedef:
{
auto TD = cast<clang::TypedefDecl>(D);
auto NS = GetNamespace(TD);
auto Name = GetDeclName(TD);
auto Typedef = NS->FindTypedef(Name, /*Create=*/false);
if (Typedef) return Typedef;
Typedef = NS->FindTypedef(Name, /*Create=*/true);
HandleDeclaration(TD, Typedef);
auto TTL = TD->getTypeSourceInfo()->getTypeLoc();
// resolve the typedef before adding it to the list otherwise it might be found and returned prematurely
// see "typedef _Aligned<16, char>::type type;" and the related classes in Common.h in the tests
Typedef->qualifiedType = GetQualifiedType(TD->getUnderlyingType(), &TTL);
AST::TypedefDecl* Existing;
// if the typedef was added along the way, the just created one is useless, delete it
if ((Existing = NS->FindTypedef(Name, /*Create=*/false)))
delete Typedef;
else
NS->Typedefs.push_back(Existing = Typedef);
Decl = Existing;
break;
}
case Decl::TypeAlias:
{
auto TD = cast<clang::TypeAliasDecl>(D);
auto NS = GetNamespace(TD);
auto Name = GetDeclName(TD);
auto TypeAlias = NS->FindTypeAlias(Name, /*Create=*/false);
if (TypeAlias) return TypeAlias;
TypeAlias = NS->FindTypeAlias(Name, /*Create=*/true);
HandleDeclaration(TD, TypeAlias);
auto TTL = TD->getTypeSourceInfo()->getTypeLoc();
// see above the case for "Typedef"
TypeAlias->qualifiedType = GetQualifiedType(TD->getUnderlyingType(), &TTL);
AST::TypeAlias* Existing;
if ((Existing = NS->FindTypeAlias(Name, /*Create=*/false)))
delete TypeAlias;
else
NS->TypeAliases.push_back(Existing = TypeAlias);
if (auto TAT = TD->getDescribedAliasTemplate())
TypeAlias->describedAliasTemplate = WalkTypeAliasTemplate(TAT);
Decl = Existing;
break;
}
case Decl::TranslationUnit:
{
Decl = GetTranslationUnit(D);
break;
}
case Decl::Namespace:
{
auto ND = cast<NamespaceDecl>(D);
for (auto D : ND->decls())
{
if (!isa<NamedDecl>(D) || IsSupported(cast<NamedDecl>(D)))
Decl = WalkDeclarationDef(D);
}
break;
}
case Decl::Var:
{
auto VD = cast<VarDecl>(D);
Decl = WalkVariable(VD);
break;
}
case Decl::CXXConstructor:
case Decl::CXXDestructor:
case Decl::CXXConversion:
case Decl::CXXMethod:
{
auto MD = cast<CXXMethodDecl>(D);
Decl = WalkMethodCXX(MD);
if (Decl == nullptr)
return Decl;
auto NS = GetNamespace(MD);
Decl->_namespace = NS;
break;
}
case Decl::Friend:
{
auto FD = cast<FriendDecl>(D);
Decl = WalkFriend(FD);
break;
}
case Decl::TemplateTemplateParm:
{
auto TTP = cast<TemplateTemplateParmDecl>(D);
Decl = WalkTemplateTemplateParameter(TTP);
break;
}
case Decl::TemplateTypeParm:
{
auto TTPD = cast<TemplateTypeParmDecl>(D);
Decl = WalkTypeTemplateParameter(TTPD);
break;
}
case Decl::NonTypeTemplateParm:
{
auto NTTPD = cast<NonTypeTemplateParmDecl>(D);
Decl = WalkNonTypeTemplateParameter(NTTPD);
break;
}
case Decl::UnresolvedUsingTypename:
{
auto UUTD = cast<UnresolvedUsingTypenameDecl>(D);
Decl = WalkUnresolvedUsingTypename(UUTD);
break;
}
case Decl::BuiltinTemplate:
case Decl::ClassScopeFunctionSpecialization:
case Decl::PragmaComment:
case Decl::PragmaDetectMismatch:
case Decl::Empty:
case Decl::AccessSpec:
case Decl::Using:
case Decl::UsingDirective:
case Decl::UsingShadow:
case Decl::ConstructorUsingShadow:
case Decl::UnresolvedUsingValue:
case Decl::IndirectField:
case Decl::StaticAssert:
case Decl::NamespaceAlias:
break;
default:
{
Debug("Unhandled declaration kind: %s\n", D->getDeclKindName());
auto& SM = c->getSourceManager();
auto Loc = D->getLocation();
auto FileName = SM.getFilename(Loc);
auto Offset = SM.getFileOffset(Loc);
auto LineNo = SM.getLineNumber(SM.getFileID(Loc), Offset);
Debug(" %s (line %u)\n", FileName.str().c_str(), LineNo);
break;
} };
if (Decl && D->hasAttrs())
{
for (auto it = D->attr_begin(); it != D->attr_end(); ++it)
{
Attr* Attr = (*it);
switch(Attr->getKind())
{
case clang::attr::Kind::MaxFieldAlignment:
{
auto MFA = cast<clang::MaxFieldAlignmentAttr>(Attr);
Decl->maxFieldAlignment = MFA->getAlignment() / 8; // bits to bytes.
break;
}
case clang::attr::Kind::Deprecated:
{
auto DA = cast<clang::DeprecatedAttr>(Attr);
Decl->isDeprecated = true;
break;
}
case clang::attr::Kind::Aligned:
Decl->alignAs = GetAlignAs(cast<clang::AlignedAttr>(Attr));
break;
default:
break;
}
}
}
return Decl;
}
int Parser::GetAlignAs(const clang::AlignedAttr* alignedAttr)
{
return alignedAttr->isAlignas() &&
!alignedAttr->isAlignmentErrorDependent() &&
!alignedAttr->isAlignmentDependent()
? alignedAttr->getAlignment(c->getASTContext())
: 0;
}
void Parser::HandleDiagnostics(ParserResult* res)
{
auto DiagClient = (DiagnosticConsumer&) c->getDiagnosticClient();
auto& Diags = DiagClient.Diagnostics;
// Convert the diagnostics to the managed types
for (unsigned I = 0, E = Diags.size(); I != E; ++I)
{
auto& Diag = DiagClient.Diagnostics[I];
auto& Source = c->getSourceManager();
auto FileName = Source.getFilename(Source.getFileLoc(Diag.Location));
auto PDiag = ParserDiagnostic();
PDiag.fileName = FileName.str();
PDiag.message = Diag.Message.str().str();
PDiag.lineNumber = 0;
PDiag.columnNumber = 0;
if( !Diag.Location.isInvalid() )
{
clang::PresumedLoc PLoc = Source.getPresumedLoc(Diag.Location);
if( PLoc.isValid() )
{
PDiag.lineNumber = PLoc.getLine();
PDiag.columnNumber = PLoc.getColumn();
}
}
switch( Diag.Level )
{
case clang::DiagnosticsEngine::Ignored:
PDiag.level = ParserDiagnosticLevel::Ignored;
break;
case clang::DiagnosticsEngine::Note:
PDiag.level = ParserDiagnosticLevel::Note;
break;
case clang::DiagnosticsEngine::Warning:
PDiag.level = ParserDiagnosticLevel::Warning;
break;
case clang::DiagnosticsEngine::Error:
PDiag.level = ParserDiagnosticLevel::Error;
break;
case clang::DiagnosticsEngine::Fatal:
PDiag.level = ParserDiagnosticLevel::Fatal;
break;
default:
assert(0);
}
res->Diagnostics.push_back(PDiag);
}
}
void Parser::SetupLLVMCodegen()
{
// Initialize enough Clang codegen machinery so we can get at ABI details.
LLVMModule.reset(new llvm::Module("", LLVMCtx));
LLVMModule->setTargetTriple(c->getTarget().getTriple().getTriple());
LLVMModule->setDataLayout(c->getTarget().getDataLayout());
CGM.reset(new clang::CodeGen::CodeGenModule(c->getASTContext(),
c->getHeaderSearchOpts(), c->getPreprocessorOpts(),
c->getCodeGenOpts(), *LLVMModule, c->getDiagnostics()));
codeGenTypes.reset(new clang::CodeGen::CodeGenTypes(*CGM.get()));
}
bool Parser::SetupSourceFiles(const std::vector<std::string>& SourceFiles,
std::vector<const clang::FileEntry*>& FileEntries)
{
// Check that the file is reachable.
const clang::DirectoryLookup *Dir;
llvm::SmallVector<
std::pair<const clang::FileEntry *, const clang::DirectoryEntry *>,
0> Includers;
for (const auto& SourceFile : SourceFiles)
{
auto FileEntry = c->getPreprocessor().getHeaderSearchInfo().LookupFile(SourceFile,
clang::SourceLocation(), /*isAngled*/true,
nullptr, Dir, Includers, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
if (!FileEntry)
return false;
FileEntries.push_back(&FileEntry.getPointer()->getFileEntry());
}
// Create a virtual file that includes the header. This gets rid of some
// Clang warnings about parsing an header file as the main file.
std::string source;
for (const auto& SourceFile : SourceFiles)
{
source += "#include \"" + SourceFile + "\"" + "\n";
}
source += "\0";
auto buffer = llvm::MemoryBuffer::getMemBufferCopy(source);
auto& SM = c->getSourceManager();
SM.setMainFileID(SM.createFileID(std::move(buffer)));
return true;
}
class SemaConsumer : public clang::SemaConsumer {
CppSharp::CppParser::Parser& Parser;
std::vector<const clang::FileEntry*>& FileEntries;
public:
SemaConsumer(CppSharp::CppParser::Parser& parser,
std::vector<const clang::FileEntry*>& entries)
: Parser(parser), FileEntries(entries) {}
virtual void HandleTranslationUnit(clang::ASTContext& Ctx) override;
};
void SemaConsumer::HandleTranslationUnit(clang::ASTContext& Ctx)
{
auto FileEntry = FileEntries[0];
auto FileName = FileEntry->getName();
auto Unit = Parser.opts->ASTContext->FindOrCreateModule(FileName.str());
auto TU = Ctx.getTranslationUnitDecl();
Parser.HandleDeclaration(TU, Unit);
if (Unit->originalPtr == nullptr)
Unit->originalPtr = (void*)FileEntry;
Parser.WalkAST(TU);
}
ParserResult* Parser::Parse(const std::vector<std::string>& SourceFiles)
{
assert(opts->ASTContext && "Expected a valid ASTContext");
auto res = new ParserResult();
if (SourceFiles.empty())
{
res->kind = ParserResultKind::FileNotFound;
return res;
}
Setup();
SetupLLVMCodegen();
std::vector<const clang::FileEntry*> FileEntries;
if (!SetupSourceFiles(SourceFiles, FileEntries))
{
res->kind = ParserResultKind::FileNotFound;
return res;
}
std::unique_ptr<SemaConsumer> SC(new SemaConsumer(*this, FileEntries));
c->setASTConsumer(std::move(SC));
c->createSema(clang::TU_Complete, 0);
std::unique_ptr<::DiagnosticConsumer> DiagClient(new ::DiagnosticConsumer());
c->getDiagnostics().setClient(DiagClient.get(), false);
DiagClient->BeginSourceFile(c->getLangOpts(), &c->getPreprocessor());
ParseAST(c->getSema());
DiagClient->EndSourceFile();
HandleDiagnostics(res);
if(DiagClient->getNumErrors() != 0)
{
res->kind = ParserResultKind::Error;
return res;
}
res->targetInfo = GetTargetInfo();
res->kind = ParserResultKind::Success;
return res;
}
ParserResultKind Parser::ParseArchive(const std::string& File,
llvm::object::Archive* Archive,
std::vector<CppSharp::CppParser::NativeLibrary*>& NativeLibs)
{
auto NativeLib = new NativeLibrary();
NativeLib->fileName = File;
for (const auto& Symbol : Archive->symbols())
{
llvm::StringRef SymRef = Symbol.getName();
NativeLib->Symbols.push_back(SymRef.str());
}
NativeLibs.push_back(NativeLib);
return ParserResultKind::Success;
}
static ArchType ConvertArchType(unsigned int archType)
{
switch (archType)
{
case llvm::Triple::ArchType::x86:
return ArchType::x86;
case llvm::Triple::ArchType::x86_64:
return ArchType::x86_64;
}
return ArchType::UnknownArch;
}
template<class ELFT>
static void ReadELFDependencies(const llvm::object::ELFFile<ELFT>& ELFFile, CppSharp::CppParser::NativeLibrary*& NativeLib)
{
ELFDumper<ELFT> ELFDumper(&ELFFile);
for (const auto& Dependency : ELFDumper.getNeededLibraries())
NativeLib->Dependencies.push_back(Dependency.str());
}
ParserResultKind Parser::ParseSharedLib(const std::string& File,
llvm::object::ObjectFile* ObjectFile,
std::vector<CppSharp::CppParser::NativeLibrary*>& NativeLibs)
{
auto NativeLib = new NativeLibrary();
NativeLib->fileName = File;
NativeLib->archType = ConvertArchType(ObjectFile->getArch());
NativeLibs.push_back(NativeLib);
if (ObjectFile->isELF())
{
auto IDyn = llvm::cast<llvm::object::ELFObjectFileBase>(ObjectFile)->getDynamicSymbolIterators();
for (auto it = IDyn.begin(); it != IDyn.end(); ++it)
{
std::string Sym;
llvm::raw_string_ostream SymStream(Sym);
if (it->printName(SymStream))
continue;
SymStream.flush();
if (!Sym.empty())
NativeLib->Symbols.push_back(Sym);
}
if (auto ELFObjectFile = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(ObjectFile))
{
ReadELFDependencies(ELFObjectFile->getELFFile(), NativeLib);
}
else if (auto ELFObjectFile = llvm::dyn_cast<llvm::object::ELF32BEObjectFile>(ObjectFile))
{
ReadELFDependencies(ELFObjectFile->getELFFile(), NativeLib);
}
else if (auto ELFObjectFile = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(ObjectFile))
{
ReadELFDependencies(ELFObjectFile->getELFFile(), NativeLib);
}
else if (auto ELFObjectFile = llvm::dyn_cast<llvm::object::ELF64BEObjectFile>(ObjectFile))
{
ReadELFDependencies(ELFObjectFile->getELFFile(), NativeLib);
}
return ParserResultKind::Success;
}
if (ObjectFile->isCOFF())
{
auto COFFObjectFile = static_cast<llvm::object::COFFObjectFile*>(ObjectFile);
for (const auto& ExportedSymbol : COFFObjectFile->export_directories())
{
llvm::StringRef Symbol;
if (!ExportedSymbol.getSymbolName(Symbol))
NativeLib->Symbols.push_back(Symbol.str());
}
for (const auto& ImportedSymbol : COFFObjectFile->import_directories())
{
llvm::StringRef Name;
if (!ImportedSymbol.getName(Name) && (Name.endswith(".dll") || Name.endswith(".DLL")))
NativeLib->Dependencies.push_back(Name.str());
}
return ParserResultKind::Success;
}
if (ObjectFile->isMachO())
{
auto MachOObjectFile = static_cast<llvm::object::MachOObjectFile*>(ObjectFile);
for (const auto& Load : MachOObjectFile->load_commands())
{
if (Load.C.cmd == llvm::MachO::LC_ID_DYLIB ||
Load.C.cmd == llvm::MachO::LC_LOAD_DYLIB ||
Load.C.cmd == llvm::MachO::LC_LOAD_WEAK_DYLIB ||
Load.C.cmd == llvm::MachO::LC_REEXPORT_DYLIB ||
Load.C.cmd == llvm::MachO::LC_LAZY_LOAD_DYLIB ||
Load.C.cmd == llvm::MachO::LC_LOAD_UPWARD_DYLIB)
{
auto dl = MachOObjectFile->getDylibIDLoadCommand(Load);
auto lib = llvm::sys::path::filename(Load.Ptr + dl.dylib.name);
NativeLib->Dependencies.push_back(lib.str());
}
}
// HACK: the correct way is with exported(Err) but it crashes with msvc 32
// see https://bugs.llvm.org/show_bug.cgi?id=44433
for (const auto& Symbol : MachOObjectFile->symbols())
{
if (Symbol.getName().takeError() || Symbol.getFlags().takeError())
return ParserResultKind::Error;
if ((Symbol.getFlags().get() & llvm::object::BasicSymbolRef::Flags::SF_Exported) &&
!(Symbol.getFlags().get() & llvm::object::BasicSymbolRef::Flags::SF_Undefined))
NativeLib->Symbols.push_back(Symbol.getName().get().str());
}
return ParserResultKind::Success;
}
return ParserResultKind::Error;
}
ParserResultKind Parser::ReadSymbols(llvm::StringRef File,
llvm::object::basic_symbol_iterator Begin,
llvm::object::basic_symbol_iterator End,
CppSharp::CppParser::NativeLibrary*& NativeLib)
{
auto LibName = File;
NativeLib = new NativeLibrary();
NativeLib->fileName = LibName.str();
for (auto it = Begin; it != End; ++it)
{
std::string Sym;
llvm::raw_string_ostream SymStream(Sym);
if (it->printName(SymStream))
continue;
SymStream.flush();
if (!Sym.empty())
NativeLib->Symbols.push_back(Sym);
}
return ParserResultKind::Success;
}
ParserResult* Parser::ParseLibrary(const LinkerOptions* Opts)
{
auto res = new ParserResult();
for (const auto& Lib : Opts->Libraries)
{
if (Lib.empty())
{
res->kind = ParserResultKind::FileNotFound;
return res;
}
std::string PrefixedLib = "lib" + Lib;
std::string FileName;
std::string FileEntry;
using namespace llvm::sys;
for (const auto& LibDir : Opts->LibraryDirs)
{
std::error_code ErrorCode;
fs::directory_iterator Dir(LibDir, ErrorCode);
for (const auto& File = Dir;
Dir != fs::directory_iterator() && !ErrorCode;
Dir = Dir.increment(ErrorCode))
{
FileName = path::filename(File->path()).str();
if (FileName == Lib ||
FileName == PrefixedLib ||
path::stem(FileName) == Lib ||
path::stem(FileName) == PrefixedLib ||
path::stem(path::stem(FileName)) == Lib ||
path::stem(path::stem(FileName)) == PrefixedLib)
{
FileEntry = File->path();
goto found;
}
}
}
if (FileEntry.empty())
{
res->kind = ParserResultKind::FileNotFound;
return res;
}
found:
auto BinaryOrErr = llvm::object::createBinary(FileEntry);
if (!BinaryOrErr)
{
auto Error = BinaryOrErr.takeError();
res->kind = ParserResultKind::Error;
return res;
}
auto OwningBinary = std::move(BinaryOrErr.get());
auto Bin = OwningBinary.getBinary();
if (auto Archive = llvm::dyn_cast<llvm::object::Archive>(Bin)) {
res->kind = ParseArchive(FileName, Archive, res->Libraries);
if (res->kind == ParserResultKind::Error)
return res;
}
if (auto ObjectFile = llvm::dyn_cast<llvm::object::ObjectFile>(Bin))
{
res->kind = ParseSharedLib(FileName, ObjectFile, res->Libraries);
if (res->kind == ParserResultKind::Error)
return res;
}
}
res->kind = ParserResultKind::Success;
return res;
}
ParserResult* ClangParser::ParseHeader(CppParserOptions* Opts)
{
if (!Opts)
return nullptr;
auto& Headers = Opts->SourceFiles;
if (Opts->unityBuild)
{
Parser parser(Opts);
return parser.Parse(Headers);
}
ParserResult* res = 0;
std::vector<Parser*> parsers;
for (size_t i = 0; i < Headers.size(); i++)
{
auto parser = new Parser(Opts);
parsers.push_back(parser);
std::vector<std::string> Header(&Headers[i], &Headers[i + 1]);
if (i < Headers.size() - 1)
delete parser->Parse(Header);
else
res = parser->Parse(Header);
}
for (auto parser : parsers)
delete parser;
return res;
}
ParserResult* ClangParser::ParseLibrary(LinkerOptions* Opts)
{
if (!Opts)
return nullptr;
return Parser::ParseLibrary(Opts);
}
ParserTargetInfo* Parser::GetTargetInfo()
{
auto parserTargetInfo = new ParserTargetInfo();
auto& TI = c->getTarget();
parserTargetInfo->ABI = TI.getABI().str();
parserTargetInfo->char16Type = ConvertIntType(TI.getChar16Type());
parserTargetInfo->char32Type = ConvertIntType(TI.getChar32Type());
parserTargetInfo->int64Type = ConvertIntType(TI.getInt64Type());
parserTargetInfo->intMaxType = ConvertIntType(TI.getIntMaxType());
parserTargetInfo->intPtrType = ConvertIntType(TI.getIntPtrType());
parserTargetInfo->sizeType = ConvertIntType(TI.getSizeType());
parserTargetInfo->uIntMaxType = ConvertIntType(TI.getUIntMaxType());
parserTargetInfo->wCharType = ConvertIntType(TI.getWCharType());
parserTargetInfo->wIntType = ConvertIntType(TI.getWIntType());
parserTargetInfo->boolAlign = TI.getBoolAlign();
parserTargetInfo->boolWidth = TI.getBoolWidth();
parserTargetInfo->charAlign = TI.getCharAlign();
parserTargetInfo->charWidth = TI.getCharWidth();
parserTargetInfo->char16Align = TI.getChar16Align();
parserTargetInfo->char16Width = TI.getChar16Width();
parserTargetInfo->char32Align = TI.getChar32Align();
parserTargetInfo->char32Width = TI.getChar32Width();
parserTargetInfo->halfAlign = TI.getHalfAlign();
parserTargetInfo->halfWidth = TI.getHalfWidth();
parserTargetInfo->floatAlign = TI.getFloatAlign();
parserTargetInfo->floatWidth = TI.getFloatWidth();
parserTargetInfo->doubleAlign = TI.getDoubleAlign();
parserTargetInfo->doubleWidth = TI.getDoubleWidth();
parserTargetInfo->shortAlign = TI.getShortAlign();
parserTargetInfo->shortWidth = TI.getShortWidth();
parserTargetInfo->intAlign = TI.getIntAlign();
parserTargetInfo->intWidth = TI.getIntWidth();
parserTargetInfo->intMaxTWidth = TI.getIntMaxTWidth();
parserTargetInfo->longAlign = TI.getLongAlign();
parserTargetInfo->longWidth = TI.getLongWidth();
parserTargetInfo->longDoubleAlign = TI.getLongDoubleAlign();
parserTargetInfo->longDoubleWidth = TI.getLongDoubleWidth();
parserTargetInfo->longLongAlign = TI.getLongLongAlign();
parserTargetInfo->longLongWidth = TI.getLongLongWidth();
parserTargetInfo->pointerAlign = TI.getPointerAlign(0);
parserTargetInfo->pointerWidth = TI.getPointerWidth(0);
parserTargetInfo->wCharAlign = TI.getWCharAlign();
parserTargetInfo->wCharWidth = TI.getWCharWidth();
parserTargetInfo->float128Align = TI.getFloat128Align();
parserTargetInfo->float128Width = TI.getFloat128Width();
return parserTargetInfo;
}
Declaration* Parser::GetDeclarationFromFriend(clang::NamedDecl* FriendDecl)
{
Declaration* Decl = WalkDeclarationDef(FriendDecl);
if (!Decl) return nullptr;
int MinLineNumberStart = std::numeric_limits<int>::max();
int MinLineNumberEnd = std::numeric_limits<int>::max();
auto& SM = c->getSourceManager();
for (auto it = FriendDecl->redecls_begin(); it != FriendDecl->redecls_end(); it++)
{
if (it->getLocation() != FriendDecl->getLocation())
{
auto DecomposedLocStart = SM.getDecomposedLoc(it->getLocation());
int NewLineNumberStart = SM.getLineNumber(DecomposedLocStart.first, DecomposedLocStart.second);
auto DecomposedLocEnd = SM.getDecomposedLoc(it->getEndLoc());
int NewLineNumberEnd = SM.getLineNumber(DecomposedLocEnd.first, DecomposedLocEnd.second);
if (NewLineNumberStart < MinLineNumberStart)
{
MinLineNumberStart = NewLineNumberStart;
MinLineNumberEnd = NewLineNumberEnd;
}
}
}
if (MinLineNumberStart < std::numeric_limits<int>::max())
{
Decl->lineNumberStart = MinLineNumberStart;
Decl->lineNumberEnd = MinLineNumberEnd;
}
return Decl;
} | 30.462803 | 123 | 0.616766 | [
"object",
"vector",
"model"
] |
c8a5e8cd567a92e7de13bafa452842a11ed613c5 | 17,071 | cpp | C++ | layers/render_pass_state.cpp | youkim02/Vulkan-ValidationLayers | 09227446c8d3a6bc1f7814adee401573cdcc8c0f | [
"Apache-2.0"
] | null | null | null | layers/render_pass_state.cpp | youkim02/Vulkan-ValidationLayers | 09227446c8d3a6bc1f7814adee401573cdcc8c0f | [
"Apache-2.0"
] | null | null | null | layers/render_pass_state.cpp | youkim02/Vulkan-ValidationLayers | 09227446c8d3a6bc1f7814adee401573cdcc8c0f | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2015-2022 The Khronos Group Inc.
* Copyright (c) 2015-2022 Valve Corporation
* Copyright (c) 2015-2022 LunarG, Inc.
* Copyright (C) 2015-2022 Google Inc.
* Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. 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.
*
* Author: Courtney Goeltzenleuchter <courtneygo@google.com>
* Author: Tobin Ehlis <tobine@google.com>
* Author: Chris Forbes <chrisf@ijw.co.nz>
* Author: Mark Lobodzinski <mark@lunarg.com>
* Author: Dave Houlton <daveh@lunarg.com>
* Author: John Zulauf <jzulauf@lunarg.com>
* Author: Tobias Hector <tobias.hector@amd.com>
* Author: Jeremy Gebben <jeremyg@lunarg.com>
*/
#include "render_pass_state.h"
#include "convert_to_renderpass2.h"
#include "image_state.h"
static const VkImageLayout kInvalidLayout = VK_IMAGE_LAYOUT_MAX_ENUM;
static VkSubpassDependency2 ImplicitDependencyFromExternal(uint32_t subpass) {
VkSubpassDependency2 from_external = {VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2,
nullptr,
VK_SUBPASS_EXTERNAL,
subpass,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
0,
VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
0,
0};
return from_external;
}
static VkSubpassDependency2 ImplicitDependencyToExternal(uint32_t subpass) {
VkSubpassDependency2 to_external = {VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2,
nullptr,
subpass,
VK_SUBPASS_EXTERNAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
0,
0,
0};
return to_external;
}
// NOTE: The functions below are only called from the RENDER_PASS_STATE constructor, and use const_cast<> to set up
// members that never change after construction is finished.
static void RecordRenderPassDAG(const VkRenderPassCreateInfo2 *pCreateInfo, RENDER_PASS_STATE *render_pass) {
auto &subpass_to_node = const_cast<RENDER_PASS_STATE::DAGNodeVec &>(render_pass->subpass_to_node);
subpass_to_node.resize(pCreateInfo->subpassCount);
auto &self_dependencies = const_cast<RENDER_PASS_STATE::SelfDepVec &>(render_pass->self_dependencies);
self_dependencies.resize(pCreateInfo->subpassCount);
auto &subpass_dependencies = const_cast<RENDER_PASS_STATE::SubpassGraphVec &>(render_pass->subpass_dependencies);
subpass_dependencies.resize(pCreateInfo->subpassCount);
for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) {
subpass_to_node[i].pass = i;
self_dependencies[i].clear();
subpass_dependencies[i].pass = i;
}
for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) {
const auto &dependency = pCreateInfo->pDependencies[i];
const auto src_subpass = dependency.srcSubpass;
const auto dst_subpass = dependency.dstSubpass;
if ((dependency.srcSubpass != VK_SUBPASS_EXTERNAL) && (dependency.dstSubpass != VK_SUBPASS_EXTERNAL)) {
if (dependency.srcSubpass == dependency.dstSubpass) {
self_dependencies[dependency.srcSubpass].push_back(i);
} else {
subpass_to_node[dependency.dstSubpass].prev.push_back(dependency.srcSubpass);
subpass_to_node[dependency.srcSubpass].next.push_back(dependency.dstSubpass);
}
}
if (src_subpass == VK_SUBPASS_EXTERNAL) {
assert(dst_subpass != VK_SUBPASS_EXTERNAL); // this is invalid per VUID-VkSubpassDependency-srcSubpass-00865
subpass_dependencies[dst_subpass].barrier_from_external.emplace_back(&dependency);
} else if (dst_subpass == VK_SUBPASS_EXTERNAL) {
subpass_dependencies[src_subpass].barrier_to_external.emplace_back(&dependency);
} else if (dependency.srcSubpass != dependency.dstSubpass) {
// ignore self dependencies in prev and next
subpass_dependencies[src_subpass].next[&subpass_dependencies[dst_subpass]].emplace_back(&dependency);
subpass_dependencies[dst_subpass].prev[&subpass_dependencies[src_subpass]].emplace_back(&dependency);
}
}
// If no barriers to external are provided for a given subpass, add them.
for (auto &subpass_dep : subpass_dependencies) {
const uint32_t pass = subpass_dep.pass;
if (subpass_dep.barrier_from_external.size() == 0) {
// Add implicit from barrier if they're aren't any
subpass_dep.implicit_barrier_from_external =
layer_data::make_unique<VkSubpassDependency2>(ImplicitDependencyFromExternal(pass));
subpass_dep.barrier_from_external.emplace_back(subpass_dep.implicit_barrier_from_external.get());
}
if (subpass_dep.barrier_to_external.size() == 0) {
// Add implicit to barrier if they're aren't any
subpass_dep.implicit_barrier_to_external =
layer_data::make_unique<VkSubpassDependency2>(ImplicitDependencyToExternal(pass));
subpass_dep.barrier_to_external.emplace_back(subpass_dep.implicit_barrier_to_external.get());
}
}
//
// Determine "asynchrononous" subpassess
// syncronization is only interested in asyncronous stages *earlier* that the current one... so we'll only look towards those.
// NOTE: This is O(N^3), which we could shrink to O(N^2logN) using sets instead of arrays, but given that N is likely to be
// small and the K for |= from the prev is must less than for set, we'll accept the brute force.
std::vector<std::vector<bool>> pass_depends(pCreateInfo->subpassCount);
for (uint32_t i = 1; i < pCreateInfo->subpassCount; ++i) {
auto &depends = pass_depends[i];
depends.resize(i);
auto &subpass_dep = subpass_dependencies[i];
for (const auto &prev : subpass_dep.prev) {
const auto prev_pass = prev.first->pass;
const auto &prev_depends = pass_depends[prev_pass];
for (uint32_t j = 0; j < prev_pass; j++) {
depends[j] = depends[j] || prev_depends[j];
}
depends[prev_pass] = true;
}
for (uint32_t pass = 0; pass < subpass_dep.pass; pass++) {
if (!depends[pass]) {
subpass_dep.async.push_back(pass);
}
}
}
}
struct AttachmentTracker { // This is really only of local interest, but a bit big for a lambda
RENDER_PASS_STATE *const rp;
RENDER_PASS_STATE::SubpassVec &first;
RENDER_PASS_STATE::FirstIsTransitionVec &first_is_transition;
RENDER_PASS_STATE::SubpassVec &last;
RENDER_PASS_STATE::TransitionVec &subpass_transitions;
RENDER_PASS_STATE::FirstReadMap &first_read;
const uint32_t attachment_count;
std::vector<VkImageLayout> attachment_layout;
std::vector<std::vector<VkImageLayout>> subpass_attachment_layout;
explicit AttachmentTracker(RENDER_PASS_STATE *render_pass)
: rp(render_pass),
first(const_cast<RENDER_PASS_STATE::SubpassVec &>(rp->attachment_first_subpass)),
first_is_transition(const_cast<RENDER_PASS_STATE::FirstIsTransitionVec &>(rp->attachment_first_is_transition)),
last(const_cast<RENDER_PASS_STATE::SubpassVec &>(rp->attachment_last_subpass)),
subpass_transitions(const_cast<RENDER_PASS_STATE::TransitionVec &>(rp->subpass_transitions)),
first_read(const_cast<RENDER_PASS_STATE::FirstReadMap &>(rp->attachment_first_read)),
attachment_count(rp->createInfo.attachmentCount),
attachment_layout(),
subpass_attachment_layout() {
first.resize(attachment_count, VK_SUBPASS_EXTERNAL);
first_is_transition.resize(attachment_count, false);
last.resize(attachment_count, VK_SUBPASS_EXTERNAL);
subpass_transitions.resize(rp->createInfo.subpassCount + 1); // Add an extra for EndRenderPass
attachment_layout.reserve(attachment_count);
subpass_attachment_layout.resize(rp->createInfo.subpassCount);
for (auto &subpass_layouts : subpass_attachment_layout) {
subpass_layouts.resize(attachment_count, kInvalidLayout);
}
for (uint32_t j = 0; j < attachment_count; j++) {
attachment_layout.push_back(rp->createInfo.pAttachments[j].initialLayout);
}
}
void Update(uint32_t subpass, const VkAttachmentReference2 *attach_ref, uint32_t count, bool is_read) {
if (nullptr == attach_ref) return;
for (uint32_t j = 0; j < count; ++j) {
const auto attachment = attach_ref[j].attachment;
if (attachment != VK_ATTACHMENT_UNUSED) {
const auto layout = attach_ref[j].layout;
// Take advantage of the fact that insert won't overwrite, so we'll only write the first time.
first_read.emplace(attachment, is_read);
if (first[attachment] == VK_SUBPASS_EXTERNAL) {
first[attachment] = subpass;
const auto initial_layout = rp->createInfo.pAttachments[attachment].initialLayout;
if (initial_layout != layout) {
subpass_transitions[subpass].emplace_back(VK_SUBPASS_EXTERNAL, attachment, initial_layout, layout);
first_is_transition[attachment] = true;
}
}
last[attachment] = subpass;
for (const auto &prev : rp->subpass_dependencies[subpass].prev) {
const auto prev_pass = prev.first->pass;
const auto prev_layout = subpass_attachment_layout[prev_pass][attachment];
if ((prev_layout != kInvalidLayout) && (prev_layout != layout)) {
subpass_transitions[subpass].emplace_back(prev_pass, attachment, prev_layout, layout);
}
}
attachment_layout[attachment] = layout;
}
}
}
void FinalTransitions() {
auto &final_transitions = subpass_transitions[rp->createInfo.subpassCount];
for (uint32_t attachment = 0; attachment < attachment_count; ++attachment) {
const auto final_layout = rp->createInfo.pAttachments[attachment].finalLayout;
// Add final transitions for attachments that were used and change layout.
if ((last[attachment] != VK_SUBPASS_EXTERNAL) && final_layout != attachment_layout[attachment]) {
final_transitions.emplace_back(last[attachment], attachment, attachment_layout[attachment], final_layout);
}
}
}
};
static void InitRenderPassState(RENDER_PASS_STATE *render_pass) {
auto create_info = render_pass->createInfo.ptr();
RecordRenderPassDAG(create_info, render_pass);
AttachmentTracker attachment_tracker(render_pass);
for (uint32_t subpass_index = 0; subpass_index < create_info->subpassCount; ++subpass_index) {
const VkSubpassDescription2 &subpass = create_info->pSubpasses[subpass_index];
attachment_tracker.Update(subpass_index, subpass.pColorAttachments, subpass.colorAttachmentCount, false);
attachment_tracker.Update(subpass_index, subpass.pResolveAttachments, subpass.colorAttachmentCount, false);
attachment_tracker.Update(subpass_index, subpass.pDepthStencilAttachment, 1, false);
attachment_tracker.Update(subpass_index, subpass.pInputAttachments, subpass.inputAttachmentCount, true);
}
attachment_tracker.FinalTransitions();
}
RENDER_PASS_STATE::RENDER_PASS_STATE(VkRenderPass rp, VkRenderPassCreateInfo2 const *pCreateInfo)
: BASE_NODE(rp, kVulkanObjectTypeRenderPass), use_dynamic_rendering(false), use_dynamic_rendering_inherited(false), createInfo(pCreateInfo) {
InitRenderPassState(this);
}
static safe_VkRenderPassCreateInfo2 ConvertCreateInfo(const VkRenderPassCreateInfo &create_info) {
safe_VkRenderPassCreateInfo2 create_info_2;
ConvertVkRenderPassCreateInfoToV2KHR(create_info, &create_info_2);
return create_info_2;
}
RENDER_PASS_STATE::RENDER_PASS_STATE(VkRenderPass rp, VkRenderPassCreateInfo const *pCreateInfo)
: BASE_NODE(rp, kVulkanObjectTypeRenderPass), use_dynamic_rendering(false), use_dynamic_rendering_inherited(false), createInfo(ConvertCreateInfo(*pCreateInfo)) {
InitRenderPassState(this);
}
const VkPipelineRenderingCreateInfo VkPipelineRenderingCreateInfo_default = {
VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
nullptr,
0,
0,
nullptr,
VK_FORMAT_UNDEFINED,
VK_FORMAT_UNDEFINED
};
RENDER_PASS_STATE::RENDER_PASS_STATE(VkPipelineRenderingCreateInfo const *pPipelineRenderingCreateInfo)
: BASE_NODE(static_cast<VkRenderPass>(VK_NULL_HANDLE), kVulkanObjectTypeRenderPass),
use_dynamic_rendering(true),
use_dynamic_rendering_inherited(false),
dynamic_rendering_pipeline_create_info(pPipelineRenderingCreateInfo ? pPipelineRenderingCreateInfo
: &VkPipelineRenderingCreateInfo_default) {}
bool RENDER_PASS_STATE::UsesColorAttachment(uint32_t subpass_num) const {
bool result = false;
if (subpass_num < createInfo.subpassCount) {
const auto &subpass = createInfo.pSubpasses[subpass_num];
for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
if (subpass.pColorAttachments[i].attachment != VK_ATTACHMENT_UNUSED) {
result = true;
break;
}
}
}
return result;
}
bool RENDER_PASS_STATE::UsesDepthStencilAttachment(uint32_t subpass_num) const {
bool result = false;
if (subpass_num < createInfo.subpassCount) {
const auto &subpass = createInfo.pSubpasses[subpass_num];
if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
result = true;
}
}
return result;
}
RENDER_PASS_STATE::RENDER_PASS_STATE(VkRenderingInfo const *pRenderingInfo)
: BASE_NODE(static_cast<VkRenderPass>(VK_NULL_HANDLE), kVulkanObjectTypeRenderPass),
use_dynamic_rendering(true),
use_dynamic_rendering_inherited(false),
dynamic_rendering_begin_rendering_info(pRenderingInfo) {}
RENDER_PASS_STATE::RENDER_PASS_STATE(VkCommandBufferInheritanceRenderingInfo const* pInheritanceRenderingInfo)
: BASE_NODE(static_cast<VkRenderPass>(VK_NULL_HANDLE), kVulkanObjectTypeRenderPass),
use_dynamic_rendering(false),
use_dynamic_rendering_inherited(true),
inheritance_rendering_info(pInheritanceRenderingInfo) {}
FRAMEBUFFER_STATE::FRAMEBUFFER_STATE(VkFramebuffer fb, const VkFramebufferCreateInfo *pCreateInfo,
std::shared_ptr<RENDER_PASS_STATE> &&rpstate,
std::vector<std::shared_ptr<IMAGE_VIEW_STATE>> &&attachments)
: BASE_NODE(fb, kVulkanObjectTypeFramebuffer),
createInfo(pCreateInfo),
rp_state(rpstate),
attachments_view_state(std::move(attachments)) {}
void FRAMEBUFFER_STATE::LinkChildNodes() {
// Connect child node(s), which cannot safely be done in the constructor.
for (auto &a : attachments_view_state) {
a->AddParent(this);
}
}
void FRAMEBUFFER_STATE::Destroy() {
for (auto &view : attachments_view_state) {
view->RemoveParent(this);
}
attachments_view_state.clear();
BASE_NODE::Destroy();
}
| 50.958209 | 165 | 0.675122 | [
"vector"
] |
c8a72562524b3f44d8cd6194f60f711792146c5f | 339,193 | cc | C++ | mysql-dst/mysql-cluster/sql/field.cc | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/sql/field.cc | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/sql/field.cc | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /*
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
@file
@brief
This file implements classes defined in field.h
*/
#include "field.h"
#include "filesort.h" // change_double_for_sort
#include "item_timefunc.h" // Item_func_now_local
#include "json_binary.h" // json_binary::serialize
#include "json_dom.h" // Json_dom, Json_wrapper
#include "item_json_func.h" // ensure_utf8mb4
#include "log_event.h" // class Table_map_log_event
#include "rpl_rli.h" // Relay_log_info
#include "rpl_slave.h" // rpl_master_has_bug
#include "sql_class.h" // THD
#include "sql_join_buffer.h" // CACHE_FIELD
#include "sql_time.h" // str_to_datetime_with_warn
#include "strfunc.h" // find_type2
#include "template_utils.h" // pointer_cast
#include "tztime.h" // Time_zone
#include "spatial.h" // Geometry
#include "sql_base.h" // is_equal
#include <algorithm>
#include <memory> // auto_ptr
using std::max;
using std::min;
#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")
// Maximum allowed exponent value for converting string to decimal
#define MAX_EXPONENT 1024
/**
Static variables
*/
uchar Field_null::null[1]={1};
const char field_separator=',';
#define DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE FLOATING_POINT_BUFFER
#define LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define BLOB_PACK_LENGTH_TO_MAX_LENGH(arg) \
((ulong) ((1LL << MY_MIN(arg, 4) * 8) - 1LL))
/*
Rules for merging different types of fields in UNION
NOTE: to avoid 256*256 table, gap in table types numeration is skiped
following #defines describe that gap and how to canculate number of fields
and index of field in thia array.
*/
#define FIELDTYPE_TEAR_FROM (MYSQL_TYPE_BIT + 1)
#define FIELDTYPE_TEAR_TO (MYSQL_TYPE_JSON - 1)
#define FIELDTYPE_NUM (FIELDTYPE_TEAR_FROM + (255 - FIELDTYPE_TEAR_TO))
inline int field_type2index (enum_field_types field_type)
{
field_type= real_type_to_type(field_type);
DBUG_ASSERT(field_type < FIELDTYPE_TEAR_FROM ||
field_type > FIELDTYPE_TEAR_TO);
return (field_type < FIELDTYPE_TEAR_FROM ?
field_type :
((int)FIELDTYPE_TEAR_FROM) + (field_type - FIELDTYPE_TEAR_TO) - 1);
}
static enum_field_types field_types_merge_rules [FIELDTYPE_NUM][FIELDTYPE_NUM]=
{
/* MYSQL_TYPE_DECIMAL -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_DECIMAL, MYSQL_TYPE_DECIMAL,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_TINY -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_TINY,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TINY, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_SHORT -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_SHORT,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_SHORT, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_SHORT,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_LONG -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_LONG,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_LONG, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONG, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_LONG,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_LONG,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_FLOAT -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_FLOAT,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_FLOAT, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_FLOAT, MYSQL_TYPE_FLOAT,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_FLOAT,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_DOUBLE -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_NULL -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_TINY,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_TIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_BIT,
//MYSQL_TYPE_JSON
MYSQL_TYPE_JSON,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_ENUM,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_SET, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_GEOMETRY
},
/* MYSQL_TYPE_TIMESTAMP -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_TIMESTAMP,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_LONGLONG -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_LONG,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_LONGLONG,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_INT24 -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_INT24,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_INT24, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_INT24, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_INT24,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_DATE -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_TIME -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME, MYSQL_TYPE_TIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_DATETIME -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_YEAR -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_YEAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONGLONG, MYSQL_TYPE_INT24,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_YEAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_NEWDATE -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_DATETIME,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_DATETIME, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_VARCHAR -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_BIT -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_BIT, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_BIT,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_JSON -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_JSON, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_JSON,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_NEWDECIMAL -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_DOUBLE, MYSQL_TYPE_DOUBLE,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_NEWDECIMAL,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_ENUM -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_ENUM, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_SET -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_SET, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_TINY_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_JSON
MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_TINY_BLOB
},
/* MYSQL_TYPE_MEDIUM_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_JSON
MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB
},
/* MYSQL_TYPE_LONG_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_JSON
MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_LONG_BLOB
},
/* MYSQL_TYPE_BLOB -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_BLOB,
//MYSQL_TYPE_JSON
MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_BLOB, MYSQL_TYPE_BLOB
},
/* MYSQL_TYPE_VAR_STRING -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR
},
/* MYSQL_TYPE_STRING -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_STRING, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_STRING,
//MYSQL_TYPE_JSON
MYSQL_TYPE_STRING,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_STRING, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_STRING
},
/* MYSQL_TYPE_GEOMETRY -> */
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
MYSQL_TYPE_GEOMETRY, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_BIT <16>-<244>
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_JSON
MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_TINY_BLOB,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
MYSQL_TYPE_BLOB, MYSQL_TYPE_VARCHAR,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
MYSQL_TYPE_STRING, MYSQL_TYPE_GEOMETRY
}
};
/**
Set field to temporary value NULL.
*/
void Field::set_tmp_null()
{
m_is_tmp_null= true;
m_count_cuted_fields_saved= table ? table->in_use->count_cuted_fields :
current_thd->count_cuted_fields;
}
/**
Return type of which can carry value of both given types in UNION result.
@param a type for merging
@param b type for merging
@return
type of field
*/
enum_field_types Field::field_type_merge(enum_field_types a,
enum_field_types b)
{
return field_types_merge_rules[field_type2index(a)]
[field_type2index(b)];
}
static Item_result field_types_result_type [FIELDTYPE_NUM]=
{
//MYSQL_TYPE_DECIMAL MYSQL_TYPE_TINY
DECIMAL_RESULT, INT_RESULT,
//MYSQL_TYPE_SHORT MYSQL_TYPE_LONG
INT_RESULT, INT_RESULT,
//MYSQL_TYPE_FLOAT MYSQL_TYPE_DOUBLE
REAL_RESULT, REAL_RESULT,
//MYSQL_TYPE_NULL MYSQL_TYPE_TIMESTAMP
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_LONGLONG MYSQL_TYPE_INT24
INT_RESULT, INT_RESULT,
//MYSQL_TYPE_DATE MYSQL_TYPE_TIME
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_DATETIME MYSQL_TYPE_YEAR
STRING_RESULT, INT_RESULT,
//MYSQL_TYPE_NEWDATE MYSQL_TYPE_VARCHAR
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_BIT <16>-<244>
STRING_RESULT,
//MYSQL_TYPE_JSON
STRING_RESULT,
//MYSQL_TYPE_NEWDECIMAL MYSQL_TYPE_ENUM
DECIMAL_RESULT, STRING_RESULT,
//MYSQL_TYPE_SET MYSQL_TYPE_TINY_BLOB
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_MEDIUM_BLOB MYSQL_TYPE_LONG_BLOB
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_BLOB MYSQL_TYPE_VAR_STRING
STRING_RESULT, STRING_RESULT,
//MYSQL_TYPE_STRING MYSQL_TYPE_GEOMETRY
STRING_RESULT, STRING_RESULT
};
/**
Convert Field::geometry_type to the corresponding Geometry::wkbType.
@param t The geometry_type to convert
@return The corresponding Geometry::wkbType, or
Geometry::wkb_invalid_type if there's not suitable type.
*/
static Geometry::wkbType geometry_type_to_wkb_type(Field::geometry_type t)
{
switch(t)
{
case Field::GEOM_GEOMETRY:
return Geometry::wkb_invalid_type;
case Field::GEOM_POINT:
return Geometry::wkb_point;
case Field::GEOM_LINESTRING:
return Geometry::wkb_linestring;
case Field::GEOM_POLYGON:
return Geometry::wkb_polygon;
case Field::GEOM_MULTIPOINT:
return Geometry::wkb_multipoint;
case Field::GEOM_MULTILINESTRING:
return Geometry::wkb_multilinestring;
case Field::GEOM_MULTIPOLYGON:
return Geometry::wkb_multipolygon;
case Field::GEOM_GEOMETRYCOLLECTION:
return Geometry::wkb_geometrycollection;
default:
DBUG_ASSERT(0);
return Geometry::wkb_invalid_type;
}
}
/*
Test if the given string contains important data:
not spaces for character string,
or any data for binary string.
SYNOPSIS
test_if_important_data()
cs Character set
str String to test
strend String end
RETURN
FALSE - If string does not have important data
TRUE - If string has some important data
*/
static bool
test_if_important_data(const CHARSET_INFO *cs, const char *str,
const char *strend)
{
if (cs != &my_charset_bin)
str+= cs->cset->scan(cs, str, strend, MY_SEQ_SPACES);
return (str < strend);
}
/**
Function to compare two unsigned integers for their relative order.
Used below. In an anonymous namespace to not clash with definitions
in other files.
*/
namespace {
int compare(unsigned int a, unsigned int b)
{
if (a < b)
return -1;
if (b < a)
return 1;
return 0;
}
} // namespace
/**
Detect Item_result by given field type of UNION merge result.
@param field_type given field type
@return
Item_result (type of internal MySQL expression result)
*/
Item_result Field::result_merge_type(enum_field_types field_type)
{
return field_types_result_type[field_type2index(field_type)];
}
/*****************************************************************************
Static help functions
*****************************************************************************/
/**
Output a warning for erroneous conversion of strings to numerical
values. For use with ER_TRUNCATED_WRONG_VALUE[_FOR_FIELD]
@param thd THD object
@param str pointer to string that failed to be converted
@param length length of string
@param cs charset for string
@param typestr string describing type converted to
@param error error value to output
@param field_name (for *_FOR_FIELD) name of field
@param row_num (for *_FOR_FIELD) row number
*/
static void push_numerical_conversion_warning(THD* thd, const char* str,
uint length,
const CHARSET_INFO* cs,
const char* typestr, int error,
const char* field_name="UNKNOWN",
ulong row_num=0)
{
char buf[MY_MAX(MY_MAX(DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE,
LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE),
DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE)];
String tmp(buf, sizeof(buf), cs);
tmp.copy(str, length, cs);
push_warning_printf(thd, Sql_condition::SL_WARNING,
error, ER(error), typestr, tmp.c_ptr(),
field_name, row_num);
}
/**
Emits a warning for the decimal conversion error. May modify
dec_value if there was conversion overflow or bad number.
@param dec_error decimal library return code
(E_DEC_* see include/decimal.h)
@param dec_value[in,out] Decimal value returned by convertion function.
@param from Value converted from
@param length Length of 'from'
@param charset_arg Charset of 'from'
*/
static void set_decimal_warning(Field_new_decimal *field,
int dec_error,
my_decimal *dec_value,
const char *from,
size_t length,
const CHARSET_INFO *charset_arg)
{
switch (dec_error) {
case E_DEC_TRUNCATED:
field->set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
break;
case E_DEC_OVERFLOW:
field->set_warning(Sql_condition::SL_WARNING,
ER_WARN_DATA_OUT_OF_RANGE, 1);
field->set_value_on_overflow(dec_value, dec_value->sign());
break;
case E_DEC_BAD_NUM:
ErrConvString errmsg(from, length, charset_arg);
const Diagnostics_area *da= field->table->in_use->get_stmt_da();
push_warning_printf(field->table->in_use, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"decimal", errmsg.ptr(), field->field_name,
da->current_row_for_condition());
my_decimal_set_zero(dec_value);
}
}
/**
Copy string with optional character set conversion.
This calls helper function well_formed_copy_nchars to copy string
with optional character set convertion. Specially, it checks if
the ASCII code point exceeds code range. If YES, it allows the
input but raises a warning.
@param to_cs Character set of "to" string
@param to Store result here
@param to_length Maxinum length of "to" string
@param from_cs From character set
@param from Copy from here
@param from_length Length of from string
@param nchars Copy not more that nchars characters
@param well_formed_error_pos Return position when "from" is not well
formed or NULL otherwise.
@param cannot_convert_error_pos Return position where a not convertable
character met, or NULL otherwise.
@param from_end_pos Return position where scanning of "from"
string stopped.
@retval length of bytes copied to 'to'
*/
size_t field_well_formed_copy_nchars(const CHARSET_INFO *to_cs,
char *to, size_t to_length,
const CHARSET_INFO *from_cs,
const char *from, size_t from_length,
size_t nchars,
const char **well_formed_error_pos,
const char **cannot_convert_error_pos,
const char **from_end_pos)
{
size_t res = well_formed_copy_nchars(to_cs, to, to_length, from_cs,
from, from_length, nchars,
well_formed_error_pos,
cannot_convert_error_pos,
from_end_pos);
/*
If the code point is out of ascii range, we only give user a warning
in 5.7. Need to change to give a ERROR in future version.
*/
if ((to_cs->state & MY_CS_PUREASCII) && *well_formed_error_pos != NULL)
{
char tmp[32];
*well_formed_error_pos = NULL;
convert_to_printable(tmp, sizeof(tmp), from, from_length, from_cs, 6);
push_warning_printf(current_thd, Sql_condition::SL_WARNING,
ER_INVALID_CHARACTER_STRING,
ER_THD(current_thd, ER_INVALID_CHARACTER_STRING),
"ascii", tmp);
}
return res;
}
/**
Check whether a field type can be partially indexed by a key.
This is a static method, rather than a virtual function, because we need
to check the type of a non-Field in mysql_alter_table().
@param type field type
@retval
TRUE Type can have a prefixed key
@retval
FALSE Type can not have a prefixed key
*/
bool Field::type_can_have_key_part(enum enum_field_types type)
{
switch (type) {
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_GEOMETRY:
return TRUE;
default:
return FALSE;
}
}
/**
Numeric fields base class constructor.
*/
Field_num::Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg, utype unireg_check_arg,
const char *field_name_arg,
uint8 dec_arg, bool zero_arg, bool unsigned_arg)
:Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg),
dec(dec_arg),zerofill(zero_arg),unsigned_flag(unsigned_arg)
{
if (zerofill)
flags|=ZEROFILL_FLAG;
if (unsigned_flag)
flags|=UNSIGNED_FLAG;
}
void Field_num::prepend_zeros(String *value)
{
int diff;
if ((diff= (int) (field_length - value->length())) > 0)
{
const bool error= value->mem_realloc(field_length);
if (!error)
{
memmove(const_cast<char*>(value->ptr()) + field_length - value->length(),
value->ptr(), value->length());
memset(const_cast<char*>(value->ptr()), '0', diff);
value->length(field_length);
}
}
}
/**
Test if given number is a int.
@todo
Make this multi-byte-character safe
@param str String to test
@param length Length of 'str'
@param int_end Pointer to char after last used digit
@param cs Character set
@note
This is called after one has called strntoull10rnd() function.
@return TYPE_OK, TYPE_ERR_BAD_VALUE or TYPE_WARN_TRUNCATED
*/
type_conversion_status
Field_num::check_int(const CHARSET_INFO *cs, const char *str, size_t length,
const char *int_end, int error)
{
/* Test if we get an empty string or wrong integer */
if (str == int_end || error == MY_ERRNO_EDOM)
{
ErrConvString err(str, length, cs);
push_warning_printf(table->in_use, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"integer", err.ptr(), field_name,
table->in_use->get_stmt_da()->
current_row_for_condition());
return TYPE_ERR_BAD_VALUE;
}
/* Test if we have garbage at the end of the given string. */
if (test_if_important_data(cs, int_end, str + length))
{
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
return TYPE_WARN_TRUNCATED;
}
return TYPE_OK;
}
/*
Conver a string to an integer then check bounds.
SYNOPSIS
Field_num::get_int
cs Character set
from String to convert
len Length of the string
rnd OUT longlong value
unsigned_max max unsigned value
signed_min min signed value
signed_max max signed value
DESCRIPTION
The function calls strntoull10rnd() to get an integer value then
check bounds and errors returned. In case of any error a warning
is raised.
@return TYPE_OK, TYPE_WARN_OUT_OF_RANGE, TYPE_ERR_BAD_VALUE or
TYPE_WARN_TRUNCATED
*/
type_conversion_status
Field_num::get_int(const CHARSET_INFO *cs, const char *from, size_t len,
longlong *rnd, ulonglong unsigned_max,
longlong signed_min, longlong signed_max)
{
char *end;
int error;
*rnd= (longlong) cs->cset->strntoull10rnd(cs, from, len,
unsigned_flag, &end,
&error);
if (unsigned_flag)
{
if ((((ulonglong) *rnd > unsigned_max) &&
(*rnd= (longlong) unsigned_max)) ||
error == MY_ERRNO_ERANGE)
goto out_of_range;
}
else
{
if (*rnd < signed_min)
{
*rnd= signed_min;
goto out_of_range;
}
else if (*rnd > signed_max)
{
*rnd= signed_max;
goto out_of_range;
}
}
if (table->in_use->count_cuted_fields != 0)
return check_int(cs, from, len, end, error);
return TYPE_OK;
out_of_range:
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return TYPE_WARN_OUT_OF_RANGE;
}
/*
This is a generic method which is executed only for
Field_short, Field_medium, Field_long, Field_longlong and Field_tiny.
The other field types that come from Field_num override this method:
Field_real (common parent for Field_decimal, Field_float, Field_double),
Field_new_decimal, Field_year.
*/
type_conversion_status
Field_num::store_time(MYSQL_TIME *ltime,
uint8 dec_arg MY_ATTRIBUTE((unused)))
{
longlong nr= TIME_to_ulonglong_round(ltime);
return store(ltime->neg ? -nr : nr, 0);
}
/**
Process decimal library return codes and issue warnings for overflow and
truncation.
@param op_result decimal library return code (E_DEC_* see include/decimal.h)
@retval 0 No error or some other errors except overflow
@retval 1 There was overflow
*/
bool Field::warn_if_overflow(int op_result)
{
if (op_result == E_DEC_OVERFLOW)
{
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return true;
}
if (op_result == E_DEC_TRUNCATED)
{
set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
/* We return 0 here as this is not a critical issue */
}
return false;
}
/**
Interpret field value as an integer but return the result as a string.
This is used for printing bit_fields as numbers while debugging.
*/
String *Field::val_int_as_str(String *val_buffer, my_bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_READ;
const CHARSET_INFO *cs= &my_charset_bin;
uint length;
longlong value= val_int();
if (val_buffer->alloc(MY_INT64_NUM_DECIMAL_DIGITS))
return 0;
length= (uint) (*cs->cset->longlong10_to_str)(cs, (char*) val_buffer->ptr(),
MY_INT64_NUM_DECIMAL_DIGITS,
unsigned_val ? 10 : -10,
value);
val_buffer->length(length);
return val_buffer;
}
/// This is used as a table name when the table structure is not set up
Field::Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
uchar null_bit_arg,
utype unireg_check_arg, const char *field_name_arg)
:ptr(ptr_arg),
m_null_ptr(null_ptr_arg),
m_is_tmp_nullable(false),
m_is_tmp_null(false),
table(0), orig_table(0), table_name(0),
field_name(field_name_arg),
unireg_check(unireg_check_arg),
field_length(length_arg), null_bit(null_bit_arg),
is_created_from_null_item(FALSE), m_indexed(false),
m_warnings_pushed(0),
gcol_info(0), stored_in_db(TRUE)
{
flags=real_maybe_null() ? 0: NOT_NULL_FLAG;
comment.str= (char*) "";
comment.length=0;
field_index= 0;
}
/**
Check NOT NULL constraint on the field after temporary nullability is
disabled.
@param warning_no Warning to report.
@return TYPE_OK if the value is Ok, or corresponding error code from
the type_conversion_status enum.
*/
type_conversion_status Field::check_constraints(int mysql_errno)
{
/*
Ensure that Field::check_constraints() is called only when temporary
nullability is disabled.
*/
DBUG_ASSERT(!is_tmp_nullable());
if (real_maybe_null())
return TYPE_OK; // If the field is nullable, we're Ok.
if (!m_is_tmp_null)
return TYPE_OK; // If the field was not NULL, we're Ok.
// The field has been set to NULL.
/*
If the field is of AUTO_INCREMENT, and the next number
has been assigned to it, we're Ok.
*/
if (this == table->next_number_field)
return TYPE_OK;
/*
If the field is of TIMESTAMP its default value is CURRENT_TIMESTAMP
and was set before calling this method. Therefore m_is_tmp_null == false
for such field and we leave check_constraints() before this
DBUG_ASSERT is fired.
*/
DBUG_ASSERT (type() != MYSQL_TYPE_TIMESTAMP);
switch (m_count_cuted_fields_saved) {
case CHECK_FIELD_WARN:
set_warning(Sql_condition::SL_WARNING, mysql_errno, 1);
/* fall through */
case CHECK_FIELD_IGNORE:
return TYPE_OK;
case CHECK_FIELD_ERROR_FOR_NULL:
if (!table->in_use->no_errors)
my_error(ER_BAD_NULL_ERROR, MYF(0), field_name);
return TYPE_ERR_NULL_CONSTRAINT_VIOLATION;
}
DBUG_ASSERT(0); // impossible
return TYPE_ERR_NULL_CONSTRAINT_VIOLATION;
}
/**
Set field to value NULL.
@param row_offset This is the offset between the row being updated
and table->record[0]
*/
void Field::set_null(my_ptrdiff_t row_offset)
{
if (real_maybe_null())
{
m_null_ptr[row_offset]|= null_bit;
}
else if (is_tmp_nullable())
{
set_tmp_null();
}
}
/**
Set field to value NOT NULL.
@param row_offset This is the offset between the row being updated
and table->record[0]
*/
void Field::set_notnull(my_ptrdiff_t row_offset)
{
if (real_maybe_null())
{
m_null_ptr[row_offset]&= (uchar) ~null_bit;
}
else if (is_tmp_nullable())
{
reset_tmp_null();
}
}
void Field::hash(ulong *nr, ulong *nr2)
{
if (is_null())
{
*nr^= (*nr << 1) | 1;
}
else
{
uint len= pack_length();
const CHARSET_INFO *cs= sort_charset();
cs->coll->hash_sort(cs, ptr, len, nr, nr2);
}
}
size_t Field::do_last_null_byte() const
{
DBUG_ASSERT(!real_maybe_null() || m_null_ptr >= table->record[0]);
return real_maybe_null() ? null_offset() + 1 : (size_t) LAST_NULL_BYTE_UNDEF;
}
void Field::copy_data(my_ptrdiff_t src_record_offset)
{
memcpy(ptr, ptr + src_record_offset, pack_length());
if (real_maybe_null())
{
// Set to NULL if the source record is NULL, otherwise set to NOT-NULL.
m_null_ptr[0]= (m_null_ptr[0] & ~null_bit) |
(m_null_ptr[src_record_offset] & null_bit);
} else if (is_tmp_nullable())
m_is_tmp_null= false;
}
bool Field::send_text(Protocol *protocol)
{
if (is_null())
return protocol->store_null();
char buff[MAX_FIELD_WIDTH];
String str(buff, sizeof(buff), &my_charset_bin);
#ifndef DBUG_OFF
my_bitmap_map *old_map= 0;
if (table->file)
old_map= dbug_tmp_use_all_columns(table, table->read_set);
#endif
String *res= val_str(&str);
#ifndef DBUG_OFF
if (old_map)
dbug_tmp_restore_column_map(table->read_set, old_map);
#endif
return res ? protocol->store(res) : protocol->store_null();
}
bool Field::send_binary(Protocol *protocol)
{
char buff[MAX_FIELD_WIDTH];
String tmp(buff,sizeof(buff),charset());
if (is_null())
return protocol->store_null();
String *res= val_str(&tmp);
return res ? protocol->store(res) : protocol->store_null();
}
/**
Check to see if field size is compatible with destination.
This method is used in row-based replication to verify that the
slave's field size is less than or equal to the master's field
size. The encoded field metadata (from the master or source) is
decoded and compared to the size of this field (the slave or
destination).
@note
The comparison is made so that if the source data (from the master)
is less than the target data (on the slave), -1 is returned in @c
<code>*order_var</code>. This implies that a conversion is
necessary, but that it is lossy and can result in truncation of the
value.
If the source data is strictly greater than the target data, 1 is
returned in <code>*order_var</code>. This implies that the source
type can is contained in the target type and that a conversion is
necessary but is non-lossy.
If no conversion is required to fit the source type in the target
type, 0 is returned in <code>*order_var</code>.
@param field_metadata Encoded size in field metadata
@param mflags Flags from the table map event for the table.
@param order_var Pointer to variable where the order
between the source field and this field
will be returned.
@return @c true if this field's size is compatible with the
master's field size, @c false otherwise.
*/
bool Field::compatible_field_size(uint field_metadata,
Relay_log_info *rli_arg MY_ATTRIBUTE((unused)),
uint16 mflags MY_ATTRIBUTE((unused)),
int *order_var)
{
uint const source_size= pack_length_from_metadata(field_metadata);
uint const destination_size= row_pack_length();
DBUG_PRINT("debug", ("real_type: %d, source_size: %u, destination_size: %u",
real_type(), source_size, destination_size));
*order_var = compare(source_size, destination_size);
return true;
}
type_conversion_status
Field::store(const char *to, size_t length, const CHARSET_INFO *cs,
enum_check_fields check_level)
{
enum_check_fields old_check_level= table->in_use->count_cuted_fields;
table->in_use->count_cuted_fields= check_level;
const type_conversion_status res= store(to, length, cs);
table->in_use->count_cuted_fields= old_check_level;
return res;
}
/**
Pack the field into a format suitable for storage and transfer.
To implement packing functionality, only the virtual function
should be overridden. The other functions are just convenience
functions and hence should not be overridden.
The value of <code>low_byte_first</code> is dependent on how the
packed data is going to be used: for local use, e.g., temporary
store on disk or in memory, use the native format since that is
faster. For data that is going to be transfered to other machines
(e.g., when writing data to the binary log), data should always be
stored in little-endian format.
@note The default method for packing fields just copy the raw bytes
of the record into the destination, but never more than
<code>max_length</code> characters.
@param to
Pointer to memory area where representation of field should be put.
@param from
Pointer to memory area where record representation of field is
stored.
@param max_length
Maximum length of the field, as given in the column definition. For
example, for <code>CHAR(1000)</code>, the <code>max_length</code>
is 1000. This information is sometimes needed to decide how to pack
the data.
@param low_byte_first
@c TRUE if integers should be stored little-endian, @c FALSE if
native format should be used. Note that for little-endian machines,
the value of this flag is a moot point since the native format is
little-endian.
*/
uchar *
Field::pack(uchar *to, const uchar *from, uint max_length,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
uint32 length= pack_length();
set_if_smaller(length, max_length);
memcpy(to, from, length);
return to+length;
}
/**
Unpack a field from row data.
This method is used to unpack a field from a master whose size of
the field is less than that of the slave.
The <code>param_data</code> parameter is a two-byte integer (stored
in the least significant 16 bits of the unsigned integer) usually
consisting of two parts: the real type in the most significant byte
and a original pack length in the least significant byte.
The exact layout of the <code>param_data</code> field is given by
the <code>Table_map_log_event::save_field_metadata()</code>.
This is the default method for unpacking a field. It just copies
the memory block in byte order (of original pack length bytes or
length of field, whichever is smaller).
@param to Destination of the data
@param from Source of the data
@param param_data Real type and original pack length of the field
data
@param low_byte_first
If this flag is @c true, all composite entities (e.g., lengths)
should be unpacked in little-endian format; otherwise, the entities
are unpacked in native order.
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field::unpack(uchar* to, const uchar *from, uint param_data,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
uint length=pack_length();
int from_type= 0;
/*
If from length is > 255, it has encoded data in the upper bits. Need
to mask it out.
*/
if (param_data > 255)
{
from_type= (param_data & 0xff00) >> 8U; // real_type.
param_data= param_data & 0x00ff; // length.
}
if ((param_data == 0) ||
(length == param_data) ||
(from_type != real_type()))
{
memcpy(to, from, length);
return from+length;
}
uint len= (param_data && (param_data < length)) ?
param_data : length;
memcpy(to, from, param_data > length ? length : len);
return from+len;
}
void Field_num::add_zerofill_and_unsigned(String &res) const
{
if (unsigned_flag)
res.append(STRING_WITH_LEN(" unsigned"));
if (zerofill)
res.append(STRING_WITH_LEN(" zerofill"));
}
void Field::make_field(Send_field *field)
{
if (orig_table && orig_table->s->db.str && *orig_table->s->db.str)
{
field->db_name= orig_table->s->db.str;
if (orig_table->pos_in_table_list &&
orig_table->pos_in_table_list->schema_table)
field->org_table_name= (orig_table->pos_in_table_list->
schema_table->table_name);
else
field->org_table_name= orig_table->s->table_name.str;
}
else
field->org_table_name= field->db_name= "";
if (orig_table && orig_table->alias)
{
field->table_name= orig_table->alias;
field->org_col_name= field_name;
}
else
{
field->table_name= "";
field->org_col_name= "";
}
field->col_name= field_name;
field->charsetnr= charset()->number;
field->length=field_length;
field->type=type();
field->flags=table->is_nullable() ? (flags & ~NOT_NULL_FLAG) : flags;
field->decimals= decimals();
field->field= false;
}
/**
Conversion from decimal to longlong. Checks overflow and returns
correct value (min/max) in case of overflow.
@param val value to be converted
@param unsigned_flag type of integer to which we convert val
@param has_overflow true if there is overflow
@return
value converted from val
*/
longlong Field::convert_decimal2longlong(const my_decimal *val,
bool unsigned_flag,
bool *has_overflow)
{
if (unsigned_flag && val->sign())
{
// Converting a signed decimal to unsigned int
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
*has_overflow= true;
return 0;
}
longlong val_ll;
int conversion_error= my_decimal2int(E_DEC_ERROR & ~E_DEC_OVERFLOW
& ~E_DEC_TRUNCATED,
val, unsigned_flag, &val_ll);
if (warn_if_overflow(conversion_error))
{
*has_overflow= true;
if (unsigned_flag)
return ULLONG_MAX;
return (val->sign() ? LLONG_MIN : LLONG_MAX);
}
return val_ll;
}
/**
Storing decimal in integer fields.
@param val value for storing
@note
This method is used by all integer fields, real/decimal redefine it
@retval TYPE_OK Storage of value went fine without warnings or errors
@retval !TYPE_OK Warning/error as indicated by type_conversion_status enum
value
*/
type_conversion_status Field_num::store_decimal(const my_decimal *val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
bool has_overflow= false;
longlong i= convert_decimal2longlong(val, unsigned_flag, &has_overflow);
const type_conversion_status res= store(i, unsigned_flag);
return has_overflow ? TYPE_WARN_OUT_OF_RANGE : res;
}
/**
Return decimal value of integer field.
@param decimal_value buffer for storing decimal value
@note
This method is used by all integer fields, real/decimal redefine it.
All longlong values fit in our decimal buffer which cal store 8*9=72
digits of integer number
@return
pointer to decimal buffer with value of field
*/
my_decimal* Field_num::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(result_type() == INT_RESULT);
longlong nr= val_int();
int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
return decimal_value;
}
bool Field_num::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
DBUG_ASSERT(result_type() == INT_RESULT);
return my_longlong_to_datetime_with_warn(val_int(), ltime, fuzzydate);
}
bool Field_num::get_time(MYSQL_TIME *ltime)
{
DBUG_ASSERT(result_type() == INT_RESULT);
return my_longlong_to_time_with_warn(val_int(), ltime);
}
Field_str::Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg, utype unireg_check_arg,
const char *field_name_arg,
const CHARSET_INFO *charset_arg)
:Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg)
{
field_charset= charset_arg;
if (charset_arg->state & MY_CS_BINSORT)
flags|=BINARY_FLAG;
field_derivation= DERIVATION_IMPLICIT;
}
void Field_str::make_field(Send_field *field)
{
Field::make_field(field);
field->decimals= 0;
}
/**
Decimal representation of Field_str.
@param d value for storing
@note
Field_str is the base class for fields implemeting
[VAR]CHAR, VAR[BINARY], BLOB/TEXT, GEOMETRY, JSON.
String value should be converted to floating point value according
our rules, so we use double to store value of decimal in string.
@todo
use decimal2string?
@retval
0 OK
@retval
!=0 error
*/
type_conversion_status Field_str::store_decimal(const my_decimal *d)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
double val;
/* TODO: use decimal2string? */
int err= my_decimal2double(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, d, &val);
warn_if_overflow(err);
const type_conversion_status res= store(val);
return (err != E_DEC_OK) ? decimal_err_to_type_conv_status(err) : res;
}
uint Field::fill_cache_field(CACHE_FIELD *copy)
{
uint store_length;
copy->str= ptr;
copy->length= pack_length();
copy->field= this;
if (flags & BLOB_FLAG)
{
copy->type= CACHE_BLOB;
copy->length-= portable_sizeof_char_ptr;
return copy->length;
}
else if (!zero_pack() &&
(type() == MYSQL_TYPE_STRING && copy->length >= 4 &&
copy->length < 256))
{
copy->type= CACHE_STRIPPED; /* Remove end space */
store_length= 2;
}
else if (type() == MYSQL_TYPE_VARCHAR)
{
copy->type= pack_length()-row_pack_length() == 1 ? CACHE_VARSTR1:
CACHE_VARSTR2;
store_length= 0;
}
else
{
copy->type= 0;
store_length= 0;
}
return copy->length + store_length;
}
bool Field::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
char buff[MAX_DATE_STRING_REP_LENGTH];
String tmp(buff,sizeof(buff),&my_charset_bin),*res;
return !(res= val_str(&tmp)) ||
str_to_datetime_with_warn(res, ltime, fuzzydate);
}
bool Field::get_time(MYSQL_TIME *ltime)
{
char buff[MAX_DATE_STRING_REP_LENGTH];
String tmp(buff,sizeof(buff),&my_charset_bin),*res;
return !(res= val_str(&tmp)) || str_to_time_with_warn(res, ltime);
}
bool Field::get_timestamp(struct timeval *tm, int *warnings)
{
MYSQL_TIME ltime;
DBUG_ASSERT(!is_null());
return get_date(<ime, TIME_FUZZY_DATE) ||
datetime_to_timeval(current_thd, <ime, tm, warnings);
}
/**
This is called when storing a date in a string.
@note
Needs to be changed if/when we want to support different time formats.
*/
type_conversion_status Field::store_time(MYSQL_TIME *ltime, uint8 dec_arg)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[MAX_DATE_STRING_REP_LENGTH];
uint length= (uint) my_TIME_to_str(ltime, buff,
MY_MIN(dec_arg, DATETIME_MAX_DECIMALS));
/* Avoid conversion when field character set is ASCII compatible */
return store(buff, length, (charset()->state & MY_CS_NONASCII) ?
&my_charset_latin1 : charset());
}
bool Field::optimize_range(uint idx, uint part)
{
return MY_TEST(table->file->index_flags(idx, part, 1) & HA_READ_RANGE);
}
Field *Field::new_field(MEM_ROOT *root, TABLE *new_table,
bool keep_type MY_ATTRIBUTE((unused)))
{
Field *tmp= clone(root);
if (tmp == NULL)
return 0;
if (tmp->table->is_nullable())
tmp->flags&= ~NOT_NULL_FLAG;
tmp->table= new_table;
tmp->key_start.init(0);
tmp->part_of_key.init(0);
tmp->part_of_sortkey.init(0);
tmp->m_indexed= false;
/*
todo: We should never alter unireg_check after an object is constructed,
and the member should be made const. But a lot of code depends upon this
hack, and the different utype values are completely unrelated so we can
never be quite sure which parts of the server will break.
*/
tmp->unireg_check= Field::NONE;
tmp->flags&= (NOT_NULL_FLAG | BLOB_FLAG | UNSIGNED_FLAG |
ZEROFILL_FLAG | BINARY_FLAG | ENUM_FLAG | SET_FLAG);
tmp->reset_fields();
return tmp;
}
Field *Field::new_key_field(MEM_ROOT *root, TABLE *new_table,
uchar *new_ptr, uchar *new_null_ptr,
uint new_null_bit)
{
Field *tmp;
if ((tmp= new_field(root, new_table, table == new_table)))
{
tmp->ptr= new_ptr;
tmp->m_null_ptr= new_null_ptr;
tmp->null_bit= new_null_bit;
}
return tmp;
}
void Field::evaluate_insert_default_function()
{
if (has_insert_default_function())
Item_func_now_local::store_in(this);
}
void Field::evaluate_update_default_function()
{
if (has_update_default_function())
Item_func_now_local::store_in(this);
}
/****************************************************************************
Field_null, a field that always return NULL
****************************************************************************/
void Field_null::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("null"));
}
/****************************************************************************
Functions for the Field_decimal class
This is an number stored as a pre-space (or pre-zero) string
****************************************************************************/
type_conversion_status Field_decimal::reset(void)
{
Field_decimal::store(STRING_WITH_LEN("0"),&my_charset_bin);
return TYPE_OK;
}
void Field_decimal::overflow(bool negative)
{
uint len=field_length;
uchar *to=ptr, filler= '9';
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
if (negative)
{
if (!unsigned_flag)
{
/* Put - sign as a first digit so we'll have -999..999 or 999..999 */
*to++ = '-';
len--;
}
else
{
filler= '0'; // Fill up with 0
if (!zerofill)
{
/*
Handle unsigned integer without zerofill, in which case
the number should be of format ' 0' or ' 0.000'
*/
uint whole_part=field_length- (dec ? dec+2 : 1);
// Fill with spaces up to the first digit
memset(to, ' ', whole_part);
to+= whole_part;
len-= whole_part;
// The main code will also handle the 0 before the decimal point
}
}
}
memset(to, filler, len);
if (dec)
ptr[field_length-dec-1]='.';
return;
}
type_conversion_status Field_decimal::store(const char *from_arg, size_t len,
const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmp(buff,sizeof(buff), &my_charset_bin);
const uchar *from= (uchar*) from_arg;
/* Convert character set if the old one is multi uchar */
if (cs->mbmaxlen > 1)
{
uint dummy_errors;
tmp.copy((char*) from, len, cs, &my_charset_bin, &dummy_errors);
from= (uchar*) tmp.ptr();
len= tmp.length();
}
const uchar *end= from+len;
/* The pointer where the field value starts (i.e., "where to write") */
uchar *to= ptr;
uint tmp_dec, tmp_uint;
/*
The sign of the number : will be 0 (means positive but sign not
specified), '+' or '-'
*/
uchar sign_char=0;
/* The pointers where prezeros start and stop */
const uchar *pre_zeros_from, *pre_zeros_end;
/* The pointers where digits at the left of '.' start and stop */
const uchar *int_digits_from, *int_digits_end;
/* The pointers where digits at the right of '.' start and stop */
const uchar *frac_digits_from, *frac_digits_end;
/* The sign of the exponent : will be 0 (means no exponent), '+' or '-' */
char expo_sign_char=0;
uint exponent=0; // value of the exponent
/*
Pointers used when digits move from the left of the '.' to the
right of the '.' (explained below)
*/
const uchar *int_digits_tail_from= NULL;
/* Number of 0 that need to be added at the left of the '.' (1E3: 3 zeros) */
uint int_digits_added_zeros= 0;
/*
Pointer used when digits move from the right of the '.' to the left
of the '.'
*/
const uchar *frac_digits_head_end= NULL;
/* Number of 0 that need to be added at the right of the '.' (for 1E-3) */
uint frac_digits_added_zeros= 0;
uchar *pos,*tmp_left_pos,*tmp_right_pos;
/* Pointers that are used as limits (begin and end of the field buffer) */
uchar *left_wall,*right_wall;
uchar tmp_char;
/*
To remember if table->in_use->cuted_fields has already been incremented,
to do that only once
*/
bool is_cuted_fields_incr=0;
/*
There are three steps in this function :
- parse the input string
- modify the position of digits around the decimal dot '.'
according to the exponent value (if specified)
- write the formatted number
*/
if ((tmp_dec=dec))
tmp_dec++;
/* skip pre-space */
while (from != end && my_isspace(&my_charset_bin,*from))
from++;
if (from == end)
{
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
is_cuted_fields_incr=1;
}
else if (*from == '+' || *from == '-') // Found some sign ?
{
sign_char= *from++;
/*
We allow "+" for unsigned decimal unless defined different
Both options allowed as one may wish not to have "+" for unsigned numbers
because of data processing issues
*/
if (unsigned_flag)
{
if (sign_char=='-')
{
Field_decimal::overflow(1);
return TYPE_WARN_OUT_OF_RANGE;
}
}
}
pre_zeros_from= from;
for (; from!=end && *from == '0'; from++) ; // Read prezeros
pre_zeros_end=int_digits_from=from;
/* Read non zero digits at the left of '.'*/
for (; from != end && my_isdigit(&my_charset_bin, *from) ; from++) ;
int_digits_end=from;
if (from!=end && *from == '.') // Some '.' ?
from++;
frac_digits_from= from;
/* Read digits at the right of '.' */
for (;from!=end && my_isdigit(&my_charset_bin, *from); from++) ;
frac_digits_end=from;
// Some exponentiation symbol ?
if (from != end && (*from == 'e' || *from == 'E'))
{
from++;
if (from != end && (*from == '+' || *from == '-')) // Some exponent sign ?
expo_sign_char= *from++;
else
expo_sign_char= '+';
/*
Read digits of the exponent and compute its value. We must care about
'exponent' overflow, because as unsigned arithmetic is "modulo", big
exponents will become small (e.g. 1e4294967296 will become 1e0, and the
field will finally contain 1 instead of its max possible value).
*/
for (;from!=end && my_isdigit(&my_charset_bin, *from); from++)
{
exponent=10*exponent+(*from-'0');
if (exponent>MAX_EXPONENT)
break;
}
}
/*
We only have to generate warnings if count_cuted_fields is set.
This is to avoid extra checks of the number when they are not needed.
Even if this flag is not set, it's OK to increment warnings, if
it makes the code easer to read.
*/
if (table->in_use->count_cuted_fields)
{
// Skip end spaces
for (;from != end && my_isspace(&my_charset_bin, *from); from++) ;
if (from != end) // If still something left, warn
{
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
is_cuted_fields_incr=1;
}
}
/*
Now "move" digits around the decimal dot according to the exponent value,
and add necessary zeros.
Examples :
- 1E+3 : needs 3 more zeros at the left of '.' (int_digits_added_zeros=3)
- 1E-3 : '1' moves at the right of '.', and 2 more zeros are needed
between '.' and '1'
- 1234.5E-3 : '234' moves at the right of '.'
These moves are implemented with pointers which point at the begin
and end of each moved segment. Examples :
- 1234.5E-3 : before the code below is executed, the int_digits part is
from '1' to '4' and the frac_digits part from '5' to '5'. After the code
below, the int_digits part is from '1' to '1', the frac_digits_head
part is from '2' to '4', and the frac_digits part from '5' to '5'.
- 1234.5E3 : before the code below is executed, the int_digits part is
from '1' to '4' and the frac_digits part from '5' to '5'. After the code
below, the int_digits part is from '1' to '4', the int_digits_tail
part is from '5' to '5', the frac_digits part is empty, and
int_digits_added_zeros=2 (to make 1234500).
*/
/*
Below tmp_uint cannot overflow with small enough MAX_EXPONENT setting,
as int_digits_added_zeros<=exponent<4G and
(int_digits_end-int_digits_from)<=max_allowed_packet<=2G and
(frac_digits_from-int_digits_tail_from)<=max_allowed_packet<=2G
*/
if (!expo_sign_char)
tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
else if (expo_sign_char == '-')
{
tmp_uint=min(exponent,(uint)(int_digits_end-int_digits_from));
frac_digits_added_zeros=exponent-tmp_uint;
int_digits_end -= tmp_uint;
frac_digits_head_end=int_digits_end+tmp_uint;
tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
}
else // (expo_sign_char=='+')
{
tmp_uint=min(exponent,(uint)(frac_digits_end-frac_digits_from));
int_digits_added_zeros=exponent-tmp_uint;
int_digits_tail_from=frac_digits_from;
frac_digits_from=frac_digits_from+tmp_uint;
/*
We "eat" the heading zeros of the
int_digits.int_digits_tail.int_digits_added_zeros concatenation
(for example 0.003e3 must become 3 and not 0003)
*/
if (int_digits_from == int_digits_end)
{
/*
There was nothing in the int_digits part, so continue
eating int_digits_tail zeros
*/
for (; int_digits_tail_from != frac_digits_from &&
*int_digits_tail_from == '0'; int_digits_tail_from++) ;
if (int_digits_tail_from == frac_digits_from)
{
// there were only zeros in int_digits_tail too
int_digits_added_zeros=0;
}
}
tmp_uint= (uint) (tmp_dec+(int_digits_end-int_digits_from)+
(uint)(frac_digits_from-int_digits_tail_from)+
int_digits_added_zeros);
}
/*
Now write the formated number
First the digits of the int_% parts.
Do we have enough room to write these digits ?
If the sign is defined and '-', we need one position for it
*/
if (field_length < tmp_uint + (int) (sign_char == '-'))
{
// too big number, change to max or min number
Field_decimal::overflow(sign_char == '-');
return TYPE_WARN_OUT_OF_RANGE;
}
/*
Tmp_left_pos is the position where the leftmost digit of
the int_% parts will be written
*/
tmp_left_pos=pos=to+(uint)(field_length-tmp_uint);
// Write all digits of the int_% parts
while (int_digits_from != int_digits_end)
*pos++ = *int_digits_from++ ;
if (expo_sign_char == '+')
{
while (int_digits_tail_from != frac_digits_from)
*pos++= *int_digits_tail_from++;
while (int_digits_added_zeros-- >0)
*pos++= '0';
}
/*
Note the position where the rightmost digit of the int_% parts has been
written (this is to later check if the int_% parts contained nothing,
meaning an extra 0 is needed).
*/
tmp_right_pos=pos;
/*
Step back to the position of the leftmost digit of the int_% parts,
to write sign and fill with zeros or blanks or prezeros.
*/
pos=tmp_left_pos-1;
if (zerofill)
{
left_wall=to-1;
while (pos > left_wall) // Fill with zeros
*pos--='0';
}
else
{
left_wall=to+(sign_char != 0)-1;
if (!expo_sign_char) // If exponent was specified, ignore prezeros
{
for (;pos > left_wall && pre_zeros_from !=pre_zeros_end;
pre_zeros_from++)
*pos--= '0';
}
if (pos == tmp_right_pos-1)
*pos--= '0'; // no 0 has ever been written, so write one
left_wall= to-1;
if (sign_char && pos != left_wall)
{
/* Write sign if possible (it is if sign is '-') */
*pos--= sign_char;
}
while (pos != left_wall)
*pos--=' '; //fill with blanks
}
/*
Write digits of the frac_% parts ;
Depending on table->in_use->count_cutted_fields, we may also want
to know if some non-zero tail of these parts will
be truncated (for example, 0.002->0.00 will generate a warning,
while 0.000->0.00 will not)
(and 0E1000000000 will not, while 1E-1000000000 will)
*/
pos=to+(uint)(field_length-tmp_dec); // Calculate post to '.'
right_wall=to+field_length;
if (pos != right_wall)
*pos++='.';
if (expo_sign_char == '-')
{
while (frac_digits_added_zeros-- > 0)
{
if (pos == right_wall)
{
if (table->in_use->count_cuted_fields && !is_cuted_fields_incr)
break; // Go on below to see if we lose non zero digits
return TYPE_OK;
}
*pos++='0';
}
while (int_digits_end != frac_digits_head_end)
{
tmp_char= *int_digits_end++;
if (pos == right_wall)
{
if (tmp_char != '0') // Losing a non zero digit ?
{
if (!is_cuted_fields_incr)
set_warning(Sql_condition::SL_WARNING,
WARN_DATA_TRUNCATED, 1);
return TYPE_OK;
}
continue;
}
*pos++= tmp_char;
}
}
for (;frac_digits_from!=frac_digits_end;)
{
tmp_char= *frac_digits_from++;
if (pos == right_wall)
{
if (tmp_char != '0') // Losing a non zero digit ?
{
if (!is_cuted_fields_incr)
{
/*
This is a note, not a warning, as we don't want to abort
when we cut decimals in strict mode
*/
set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
}
return TYPE_OK;
}
continue;
}
*pos++= tmp_char;
}
while (pos != right_wall)
*pos++='0'; // Fill with zeros at right of '.'
return TYPE_OK;
}
type_conversion_status Field_decimal::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (unsigned_flag && nr < 0)
{
overflow(1);
return TYPE_WARN_OUT_OF_RANGE;
}
if (!my_isfinite(nr)) // Handle infinity as special case
{
overflow(nr < 0.0);
return TYPE_WARN_OUT_OF_RANGE;
}
size_t i;
size_t length;
uchar fyllchar,*to;
char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
fyllchar = zerofill ? '0' : ' ';
length= my_fcvt(nr, dec, buff, NULL);
if (length > field_length)
{
overflow(nr < 0.0);
return TYPE_WARN_OUT_OF_RANGE;
}
else
{
to=ptr;
for (i=field_length-length ; i-- > 0 ;)
*to++ = fyllchar;
memcpy(to,buff,length);
return TYPE_OK;
}
}
type_conversion_status Field_decimal::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[22];
uint length, int_part;
char fyllchar;
uchar *to;
if (nr < 0 && unsigned_flag && !unsigned_val)
{
overflow(1);
return TYPE_WARN_OUT_OF_RANGE;
}
length= (uint) (longlong10_to_str(nr,buff,unsigned_val ? 10 : -10) - buff);
int_part= field_length- (dec ? dec+1 : 0);
if (length > int_part)
{
overflow(!unsigned_val && nr < 0L); /* purecov: inspected */
return TYPE_WARN_OUT_OF_RANGE;
}
fyllchar = zerofill ? '0' : ' ';
to= ptr;
for (uint i=int_part-length ; i-- > 0 ;)
*to++ = fyllchar;
memcpy(to,buff,length);
if (dec)
{
to[length]='.';
memset(to + length + 1, '0', dec);
}
return TYPE_OK;
}
double Field_decimal::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *end_not_used;
return my_strntod(&my_charset_bin, (char*) ptr, field_length, &end_not_used,
¬_used);
}
longlong Field_decimal::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
if (unsigned_flag)
return my_strntoull(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
¬_used);
return my_strntoll(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
¬_used);
}
String *Field_decimal::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uchar *str;
size_t tmp_length;
for (str=ptr ; *str == ' ' ; str++) ;
val_ptr->set_charset(&my_charset_numeric);
tmp_length= (size_t) (str-ptr);
if (field_length < tmp_length) // Error in data
val_ptr->length(0);
else
val_ptr->set_ascii((const char*) str, field_length-tmp_length);
return val_ptr;
}
/**
Should be able to handle at least the following fixed decimal formats:
5.00 , -1.0, 05, -05, +5 with optional pre/end space
*/
int Field_decimal::cmp(const uchar *a_ptr,const uchar *b_ptr)
{
const uchar *end;
int swap=0;
/* First remove prefixes '0', ' ', and '-' */
for (end=a_ptr+field_length;
a_ptr != end &&
(*a_ptr == *b_ptr ||
((my_isspace(&my_charset_bin,*a_ptr) || *a_ptr == '+' ||
*a_ptr == '0') &&
(my_isspace(&my_charset_bin,*b_ptr) || *b_ptr == '+' ||
*b_ptr == '0')));
a_ptr++,b_ptr++)
{
if (*a_ptr == '-') // If both numbers are negative
swap= -1 ^ 1; // Swap result
}
if (a_ptr == end)
return 0;
if (*a_ptr == '-')
return -1;
if (*b_ptr == '-')
return 1;
while (a_ptr != end)
{
if (*a_ptr++ != *b_ptr++)
return swap ^ (a_ptr[-1] < b_ptr[-1] ? -1 : 1); // compare digits
}
return 0;
}
void Field_decimal::make_sort_key(uchar *to, size_t length)
{
uchar *str,*end;
for (str=ptr,end=ptr+length;
str != end &&
((my_isspace(&my_charset_bin,*str) || *str == '+' ||
*str == '0')) ;
str++)
*to++=' ';
if (str == end)
return; /* purecov: inspected */
if (*str == '-')
{
*to++=1; // Smaller than any number
str++;
while (str != end)
if (my_isdigit(&my_charset_bin,*str))
*to++= (char) ('9' - *str++);
else
*to++= *str++;
}
else memcpy(to,str,(uint) (end-str));
}
void Field_decimal::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
uint tmp=field_length;
if (!unsigned_flag)
tmp--;
if (dec)
tmp--;
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"decimal(%d,%d)",tmp,dec));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
** Field_new_decimal
****************************************************************************/
Field_new_decimal::Field_new_decimal(uchar *ptr_arg,
uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg,
uint8 dec_arg,bool zero_arg,
bool unsigned_arg)
:Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg)
{
precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
set_if_smaller(precision, DECIMAL_MAX_PRECISION);
DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
(dec <= DECIMAL_MAX_SCALE));
bin_size= my_decimal_get_binary_size(precision, dec);
}
Field_new_decimal::Field_new_decimal(uint32 len_arg,
bool maybe_null_arg,
const char *name,
uint8 dec_arg,
bool unsigned_arg)
:Field_num((uchar*) 0, len_arg,
maybe_null_arg ? (uchar*) "": 0, 0,
NONE, name, dec_arg, 0, unsigned_arg)
{
precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
set_if_smaller(precision, DECIMAL_MAX_PRECISION);
DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
(dec <= DECIMAL_MAX_SCALE));
bin_size= my_decimal_get_binary_size(precision, dec);
}
Field *Field_new_decimal::create_from_item (Item *item)
{
uint8 dec= item->decimals;
uint8 intg= item->decimal_precision() - dec;
uint32 len= item->max_char_length();
DBUG_ASSERT (item->result_type() == DECIMAL_RESULT);
/*
Trying to put too many digits overall in a DECIMAL(prec,dec)
will always throw a warning. We must limit dec to
DECIMAL_MAX_SCALE however to prevent an assert() later.
*/
if (dec > 0)
{
signed int overflow;
dec= min<int>(dec, DECIMAL_MAX_SCALE);
/*
If the value still overflows the field with the corrected dec,
we'll throw out decimals rather than integers. This is still
bad and of course throws a truncation warning.
+1: for decimal point
*/
const int required_length=
my_decimal_precision_to_length(intg + dec, dec,
item->unsigned_flag);
overflow= required_length - len;
if (overflow > 0)
dec= max(0, dec - overflow); // too long, discard fract
else
/* Corrected value fits. */
len= required_length;
}
return new Field_new_decimal(len, item->maybe_null, item->item_name.ptr(),
dec, item->unsigned_flag);
}
type_conversion_status Field_new_decimal::reset(void)
{
store_value(&decimal_zero);
return TYPE_OK;
}
/**
Generate max/min decimal value in case of overflow.
@param decimal_value buffer for value
@param sign sign of value which caused overflow
*/
void Field_new_decimal::set_value_on_overflow(my_decimal *decimal_value,
bool sign)
{
DBUG_ENTER("Field_new_decimal::set_value_on_overflow");
max_my_decimal(decimal_value, precision, decimals());
if (sign)
{
if (unsigned_flag)
my_decimal_set_zero(decimal_value);
else
decimal_value->sign(TRUE);
}
DBUG_VOID_RETURN;
}
/**
Store decimal value in the binary buffer.
Checks if decimal_value fits into field size.
If it does, stores the decimal in the buffer using binary format.
Otherwise sets maximal number that can be stored in the field.
@param decimal_value my_decimal
@retval
0 ok
@retval
1 error
*/
type_conversion_status
Field_new_decimal::store_value(const my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
DBUG_ENTER("Field_new_decimal::store_value");
#ifndef DBUG_OFF
{
char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
}
#endif
/* check that we do not try to write negative value in unsigned field */
if (unsigned_flag && decimal_value->sign())
{
DBUG_PRINT("info", ("unsigned overflow"));
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
decimal_value= &decimal_zero;
}
#ifndef DBUG_OFF
{
char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("info", ("saving with precision %d scale: %d value %s",
(int)precision, (int)dec,
dbug_decimal_as_string(dbug_buff, decimal_value)));
}
#endif
int err= my_decimal2binary(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
decimal_value, ptr, precision, dec);
if (warn_if_overflow(err))
{
my_decimal buff;
DBUG_PRINT("info", ("overflow"));
set_value_on_overflow(&buff, decimal_value->sign());
my_decimal2binary(E_DEC_FATAL_ERROR, &buff, ptr, precision, dec);
}
DBUG_EXECUTE("info", print_decimal_buff(decimal_value, ptr,
bin_size););
DBUG_RETURN((err != E_DEC_OK) ? decimal_err_to_type_conv_status(err)
: error);
}
type_conversion_status
Field_new_decimal::store(const char *from, size_t length,
const CHARSET_INFO *charset_arg)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
my_decimal decimal_value;
DBUG_ENTER("Field_new_decimal::store(char*)");
int err= str2my_decimal(E_DEC_FATAL_ERROR &
~(E_DEC_OVERFLOW | E_DEC_BAD_NUM),
from, length, charset_arg,
&decimal_value);
if (err != 0 && !table->in_use->lex->is_ignore()
&& table->in_use->is_strict_mode())
{
ErrConvString errmsg(from, length, charset_arg);
const Diagnostics_area *da= table->in_use->get_stmt_da();
push_warning_printf(table->in_use, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"decimal", errmsg.ptr(), field_name,
da->current_row_for_condition());
DBUG_RETURN(decimal_err_to_type_conv_status(err));
}
if (err != 0)
set_decimal_warning(this, err, &decimal_value, from, length, charset_arg);
#ifndef DBUG_OFF
char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("enter", ("value: %s",
dbug_decimal_as_string(dbug_buff, &decimal_value)));
#endif
type_conversion_status store_stat= store_value(&decimal_value);
DBUG_RETURN(err != 0 ? decimal_err_to_type_conv_status(err) : store_stat);
}
type_conversion_status
store_internal_with_error_check(Field_new_decimal *field,
int err, my_decimal *value)
{
type_conversion_status stat= TYPE_OK;
if (err != 0)
{
if (field->check_overflow(err))
{
field->set_value_on_overflow(value, value->sign());
stat= TYPE_WARN_OUT_OF_RANGE;
}
else if (field->check_truncated(err))
stat= TYPE_NOTE_TRUNCATED;
/* Only issue a warning if store_value doesn't issue an warning */
field->table->in_use->got_warning= 0;
}
type_conversion_status store_stat= field->store_value(value);
if (store_stat != TYPE_OK)
return store_stat;
else if (err != 0 && !field->table->in_use->got_warning)
field->warn_if_overflow(err);
return stat;
}
/**
@todo
Fix following when double2my_decimal when double2decimal
will return E_DEC_TRUNCATED always correctly
*/
type_conversion_status Field_new_decimal::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
DBUG_ENTER("Field_new_decimal::store(double)");
my_decimal decimal_value;
int conv_err= double2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, nr,
&decimal_value);
DBUG_RETURN(store_internal_with_error_check(this, conv_err, &decimal_value));
}
type_conversion_status
Field_new_decimal::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
DBUG_ENTER("Field_new_decimal::store(double, unsigned_val)");
my_decimal decimal_value;
int conv_err= int2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
nr, unsigned_val, &decimal_value);
DBUG_RETURN(store_internal_with_error_check(this, conv_err, &decimal_value));
}
type_conversion_status
Field_new_decimal::store_decimal(const my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
return store_value(decimal_value);
}
type_conversion_status
Field_new_decimal::store_time(MYSQL_TIME *ltime,
uint8 dec_arg MY_ATTRIBUTE((unused)))
{
my_decimal decimal_value;
return store_value(date2my_decimal(ltime, &decimal_value));
}
double Field_new_decimal::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double dbl;
my_decimal decimal_value;
my_decimal2double(E_DEC_FATAL_ERROR, val_decimal(&decimal_value), &dbl);
return dbl;
}
longlong Field_new_decimal::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong i;
my_decimal decimal_value;
my_decimal2int(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
unsigned_flag, &i);
return i;
}
my_decimal* Field_new_decimal::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ENTER("Field_new_decimal::val_decimal");
binary2my_decimal(E_DEC_FATAL_ERROR, ptr, decimal_value,
precision, dec);
DBUG_EXECUTE("info", print_decimal_buff(decimal_value, ptr,
bin_size););
DBUG_RETURN(decimal_value);
}
String *Field_new_decimal::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
my_decimal decimal_value;
uint fixed_precision= zerofill ? precision : 0;
my_decimal2string(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
fixed_precision, dec, '0', val_buffer);
val_buffer->set_charset(&my_charset_numeric);
return val_buffer;
}
bool Field_new_decimal::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
my_decimal buf, *decimal_value= val_decimal(&buf);
if (!decimal_value)
{
set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
return true;
}
return my_decimal_to_datetime_with_warn(decimal_value, ltime, fuzzydate);
}
bool Field_new_decimal::get_time(MYSQL_TIME *ltime)
{
my_decimal buf, *decimal_value= val_decimal(&buf);
if (!decimal_value)
{
set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
return true;
}
return my_decimal_to_time_with_warn(decimal_value, ltime);
}
int Field_new_decimal::cmp(const uchar *a,const uchar*b)
{
return memcmp(a, b, bin_size);
}
void Field_new_decimal::make_sort_key(uchar *buff, size_t length)
{
memcpy(buff, ptr, min(length, static_cast<size_t>(bin_size)));
}
void Field_new_decimal::sql_type(String &str) const
{
const CHARSET_INFO *cs= str.charset();
str.length(cs->cset->snprintf(cs, (char*) str.ptr(), str.alloced_length(),
"decimal(%d,%d)", precision, (int)dec));
add_zerofill_and_unsigned(str);
}
/**
Save the field metadata for new decimal fields.
Saves the precision in the first byte and decimals() in the second
byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_new_decimal::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= precision;
*(metadata_ptr + 1)= decimals();
return 2;
}
/**
Returns the number of bytes field uses in row-based replication
row packed size.
This method is used in row-based replication to determine the number
of bytes that the field consumes in the row record format. This is
used to skip fields in the master that do not exist on the slave.
@param field_metadata Encoded size in field metadata
@returns The size of the field based on the field metadata.
*/
uint Field_new_decimal::pack_length_from_metadata(uint field_metadata)
{
uint const source_precision= (field_metadata >> 8U) & 0x00ff;
uint const source_decimal= field_metadata & 0x00ff;
uint const source_size= my_decimal_get_binary_size(source_precision,
source_decimal);
return (source_size);
}
/**
Check to see if field size is compatible with destination.
This method is used in row-based replication to verify that the slave's
field size is less than or equal to the master's field size. The
encoded field metadata (from the master or source) is decoded and compared
to the size of this field (the slave or destination).
@param field_metadata Encoded size in field metadata
@param order_var Pointer to variable where the order
between the source field and this field
will be returned.
@return @c true
*/
bool Field_new_decimal::compatible_field_size(uint field_metadata,
Relay_log_info * MY_ATTRIBUTE((unused)),
uint16 mflags MY_ATTRIBUTE((unused)),
int *order_var)
{
uint const source_precision= (field_metadata >> 8U) & 0x00ff;
uint const source_decimal= field_metadata & 0x00ff;
int order= compare(source_precision, precision);
*order_var= order != 0 ? order : compare(source_decimal, dec);
return true;
}
uint Field_new_decimal::is_equal(Create_field *new_field)
{
return ((new_field->sql_type == real_type()) &&
((new_field->flags & UNSIGNED_FLAG) ==
(uint) (flags & UNSIGNED_FLAG)) &&
((new_field->flags & AUTO_INCREMENT_FLAG) ==
(uint) (flags & AUTO_INCREMENT_FLAG)) &&
(new_field->length == max_display_length()) &&
(new_field->decimals == dec));
}
/**
Unpack a decimal field from row data.
This method is used to unpack a decimal or numeric field from a master
whose size of the field is less than that of the slave.
@param to Destination of the data
@param from Source of the data
@param param_data Precision (upper) and decimal (lower) values
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_new_decimal::unpack(uchar* to,
const uchar *from,
uint param_data,
bool low_byte_first)
{
if (param_data == 0)
return Field::unpack(to, from, param_data, low_byte_first);
uint from_precision= (param_data & 0xff00) >> 8U;
uint from_decimal= param_data & 0x00ff;
uint length=pack_length();
uint from_pack_len= my_decimal_get_binary_size(from_precision, from_decimal);
uint len= (param_data && (from_pack_len < length)) ?
from_pack_len : length;
if ((from_pack_len && (from_pack_len < length)) ||
(from_precision < precision) ||
(from_decimal < decimals()))
{
/*
If the master's data is smaller than the slave, we need to convert
the binary to decimal then resize the decimal converting it back to
a decimal and write that to the raw data buffer.
*/
decimal_digit_t dec_buf[DECIMAL_MAX_PRECISION];
decimal_t dec_val;
dec_val.len= from_precision;
dec_val.buf= dec_buf;
/*
Note: bin2decimal does not change the length of the field. So it is
just the first step the resizing operation. The second step does the
resizing using the precision and decimals from the slave.
*/
bin2decimal((uchar *)from, &dec_val, from_precision, from_decimal);
decimal2bin(&dec_val, to, precision, decimals());
}
else
memcpy(to, from, len); // Sizes are the same, just copy the data.
return from+len;
}
bool Field_new_decimal::send_binary(Protocol *protocol)
{
my_decimal dec_value;
if (is_null())
return protocol->store_null();
return protocol->store_decimal(val_decimal(&dec_value),
zerofill ? precision : 0, dec);
}
/****************************************************************************
** tiny int
****************************************************************************/
type_conversion_status
Field_tiny::store(const char *from, size_t len, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
longlong rnd;
const type_conversion_status error= get_int(cs, from, len, &rnd,
255, -128, 127);
ptr[0]= unsigned_flag ? (char) (ulonglong) rnd : (char) rnd;
return error;
}
type_conversion_status Field_tiny::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0.0)
{
*ptr=0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > 255.0)
{
*ptr=(char) 255;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
*ptr=(char) nr;
}
else
{
if (nr < -128.0)
{
*ptr= (char) -128;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > 127.0)
{
*ptr=127;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
*ptr=(char) (int) nr;
}
return error;
}
type_conversion_status Field_tiny::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
if (unsigned_flag)
{
if (nr < 0 && !unsigned_val)
{
*ptr= 0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if ((ulonglong) nr > (ulonglong) 255)
{
*ptr= (char) 255;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
*ptr=(char) nr;
}
else
{
if (nr < 0 && unsigned_val)
nr= 256; // Generate overflow
if (nr < -128)
{
*ptr= (char) -128;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > 127)
{
*ptr=127;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
*ptr=(char) nr;
}
return error;
}
double Field_tiny::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int tmp= unsigned_flag ? (int) ptr[0] :
(int) ((signed char*) ptr)[0];
return (double) tmp;
}
longlong Field_tiny::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int tmp= unsigned_flag ? (int) ptr[0] :
(int) ((signed char*) ptr)[0];
return (longlong) tmp;
}
String *Field_tiny::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
const CHARSET_INFO *cs= &my_charset_numeric;
uint length;
uint mlength=max(field_length+1,5*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
if (unsigned_flag)
length= (uint) cs->cset->long10_to_str(cs,to,mlength, 10,
(long) *ptr);
else
length= (uint) cs->cset->long10_to_str(cs,to,mlength,-10,
(long) *((signed char*) ptr));
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
val_buffer->set_charset(cs);
return val_buffer;
}
bool Field_tiny::send_binary(Protocol *protocol)
{
if (is_null())
return protocol->store_null();
return protocol->store_tiny((longlong) unsigned_flag? (uint8) ptr[0]:
(int8) ptr[0]);
}
int Field_tiny::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
signed char a,b;
a=(signed char) a_ptr[0]; b= (signed char) b_ptr[0];
if (unsigned_flag)
return ((uchar) a < (uchar) b) ? -1 : ((uchar) a > (uchar) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_tiny::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 1);
if (unsigned_flag)
*to= *ptr;
else
to[0] = (char) (ptr[0] ^ (uchar) 128); /* Revers signbit */
}
void Field_tiny::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"tinyint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
Field type short int (2 byte)
****************************************************************************/
type_conversion_status
Field_short::store(const char *from, size_t len, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int store_tmp;
longlong rnd;
const type_conversion_status error=
get_int(cs, from, len, &rnd, UINT_MAX16, INT_MIN16, INT_MAX16);
store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr, store_tmp);
}
else
#endif
shortstore(ptr, (short) store_tmp);
return error;
}
type_conversion_status Field_short::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
int16 res;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
res=0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (double) UINT_MAX16)
{
res=(int16) UINT_MAX16;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int16) (uint16) nr;
}
else
{
if (nr < (double) INT_MIN16)
{
res=INT_MIN16;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (double) INT_MAX16)
{
res=INT_MAX16;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int16) (int) nr;
}
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr,res);
}
else
#endif
shortstore(ptr,res);
return error;
}
type_conversion_status Field_short::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
int16 res;
if (unsigned_flag)
{
if (nr < 0L && !unsigned_val)
{
res=0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if ((ulonglong) nr > (ulonglong) UINT_MAX16)
{
res=(int16) UINT_MAX16;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int16) (uint16) nr;
}
else
{
if (nr < 0 && unsigned_val)
nr= UINT_MAX16+1; // Generate overflow
if (nr < INT_MIN16)
{
res=INT_MIN16;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (longlong) INT_MAX16)
{
res=INT_MAX16;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int16) nr;
}
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr,res);
}
else
#endif
shortstore(ptr,res);
return error;
}
double Field_short::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
short j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint2korr(ptr);
else
#endif
shortget(&j, ptr);
return unsigned_flag ? (double) (unsigned short) j : (double) j;
}
longlong Field_short::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
short j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint2korr(ptr);
else
#endif
shortget(&j, ptr);
return unsigned_flag ? (longlong) (unsigned short) j : (longlong) j;
}
String *Field_short::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
const CHARSET_INFO *cs= &my_charset_numeric;
uint length;
uint mlength=max(field_length+1,7*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
short j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint2korr(ptr);
else
#endif
shortget(&j, ptr);
if (unsigned_flag)
length=(uint) cs->cset->long10_to_str(cs, to, mlength, 10,
(long) (uint16) j);
else
length=(uint) cs->cset->long10_to_str(cs, to, mlength,-10, (long) j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
val_buffer->set_charset(cs);
return val_buffer;
}
bool Field_short::send_binary(Protocol *protocol)
{
if (is_null())
return protocol->store_null();
return protocol->store_short(Field_short::val_int());
}
int Field_short::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
short a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
a=sint2korr(a_ptr);
b=sint2korr(b_ptr);
}
else
#endif
{
shortget(&a, a_ptr);
shortget(&b, b_ptr);
}
if (unsigned_flag)
return ((unsigned short) a < (unsigned short) b) ? -1 :
((unsigned short) a > (unsigned short) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_short::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 2);
#ifdef WORDS_BIGENDIAN
if (!table->s->db_low_byte_first)
{
if (unsigned_flag)
to[0] = ptr[0];
else
to[0] = (char) (ptr[0] ^ 128); /* Revers signbit */
to[1] = ptr[1];
}
else
#endif
{
if (unsigned_flag)
to[0] = ptr[1];
else
to[0] = (char) (ptr[1] ^ 128); /* Revers signbit */
to[1] = ptr[0];
}
}
void Field_short::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"smallint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
Field type medium int (3 byte)
****************************************************************************/
type_conversion_status Field_medium::store(const char *from, size_t len,
const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int store_tmp;
longlong rnd;
const type_conversion_status error=
get_int(cs, from, len, &rnd, UINT_MAX24, INT_MIN24, INT_MAX24);
store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
int3store(ptr, store_tmp);
return error;
}
type_conversion_status Field_medium::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
int3store(ptr,0);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr >= (double) (long) (1L << 24))
{
uint32 tmp=(uint32) (1L << 24)-1L;
int3store(ptr,tmp);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
int3store(ptr,(uint32) nr);
}
else
{
if (nr < (double) INT_MIN24)
{
long tmp=(long) INT_MIN24;
int3store(ptr,tmp);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (double) INT_MAX24)
{
long tmp=(long) INT_MAX24;
int3store(ptr,tmp);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
int3store(ptr,(long) nr);
}
return error;
}
type_conversion_status Field_medium::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
if (unsigned_flag)
{
if (nr < 0 && !unsigned_val)
{
int3store(ptr,0);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if ((ulonglong) nr >= (ulonglong) (long) (1L << 24))
{
long tmp= (long) (1L << 24)-1L;
int3store(ptr,tmp);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
int3store(ptr,(uint32) nr);
}
else
{
if (nr < 0 && unsigned_val)
nr= (ulonglong) (long) (1L << 24); // Generate overflow
if (nr < (longlong) INT_MIN24)
{
long tmp= (long) INT_MIN24;
int3store(ptr,tmp);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (longlong) INT_MAX24)
{
long tmp=(long) INT_MAX24;
int3store(ptr,tmp);
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
int3store(ptr,(long) nr);
}
return error;
}
double Field_medium::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
return (double) j;
}
longlong Field_medium::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
return (longlong) j;
}
String *Field_medium::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
const CHARSET_INFO *cs= &my_charset_numeric;
uint length;
uint mlength=max(field_length+1,10*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
length=(uint) cs->cset->long10_to_str(cs,to,mlength,-10,j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer); /* purecov: inspected */
val_buffer->set_charset(cs);
return val_buffer;
}
bool Field_medium::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
if (is_null())
return protocol->store_null();
return protocol->store_long(Field_medium::val_int());
}
int Field_medium::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
long a,b;
if (unsigned_flag)
{
a=uint3korr(a_ptr);
b=uint3korr(b_ptr);
}
else
{
a=sint3korr(a_ptr);
b=sint3korr(b_ptr);
}
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_medium::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 3);
if (unsigned_flag)
to[0] = ptr[2];
else
to[0] = (uchar) (ptr[2] ^ 128); /* Revers signbit */
to[1] = ptr[1];
to[2] = ptr[0];
}
void Field_medium::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"mediumint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
** long int
****************************************************************************/
type_conversion_status Field_long::store(const char *from, size_t len,
const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
long store_tmp;
longlong rnd;
const type_conversion_status error=
get_int(cs, from, len, &rnd, UINT_MAX32, INT_MIN32, INT_MAX32);
store_tmp= unsigned_flag ? (long) (ulonglong) rnd : (long) rnd;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr, store_tmp);
}
else
#endif
longstore(ptr, store_tmp);
return error;
}
type_conversion_status Field_long::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
int32 res;
nr=rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
res=0;
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (double) UINT_MAX32)
{
res= UINT_MAX32;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int32) (ulong) nr;
}
else
{
if (nr < (double) INT_MIN32)
{
res=(int32) INT_MIN32;
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (double) INT_MAX32)
{
res=(int32) INT_MAX32;
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int32) (longlong) nr;
}
if (error)
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr,res);
}
else
#endif
longstore(ptr,res);
return error;
}
/**
Store a longlong in the field
@param nr the value to store
@param unsigned_val whether or not 'nr' should be interpreted as
signed or unsigned. E.g., if 'nr' has all bits
set it is interpreted as -1 if unsigned_val is
false and ULLONG_MAX if unsigned_val is true.
*/
type_conversion_status Field_long::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
int32 res;
if (unsigned_flag)
{
if (nr < 0 && !unsigned_val)
{
res=0;
error= TYPE_WARN_OUT_OF_RANGE;
}
else if ((ulonglong) nr >= (1LL << 32))
{
res=(int32) (uint32) ~0L;
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int32) (uint32) nr;
}
else
{
if (nr < 0 && unsigned_val)
{
nr= ((longlong) INT_MAX32) + 1; // Generate overflow
error= TYPE_WARN_OUT_OF_RANGE;
}
if (nr < (longlong) INT_MIN32)
{
res=(int32) INT_MIN32;
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr > (longlong) INT_MAX32)
{
res=(int32) INT_MAX32;
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(int32) nr;
}
if (error)
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr,res);
}
else
#endif
longstore(ptr,res);
return error;
}
double Field_long::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int32 j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(&j, ptr);
return unsigned_flag ? (double) (uint32) j : (double) j;
}
longlong Field_long::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int32 j;
/* See the comment in Field_long::store(long long) */
DBUG_ASSERT(table->in_use == current_thd);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(&j, ptr);
return unsigned_flag ? (longlong) (uint32) j : (longlong) j;
}
String *Field_long::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
const CHARSET_INFO *cs= &my_charset_numeric;
size_t length;
uint mlength=max(field_length+1,12*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
int32 j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint4korr(ptr);
else
#endif
longget(&j, ptr);
if (unsigned_flag)
length=cs->cset->long10_to_str(cs,to,mlength, 10,(long) (uint32)j);
else
length=cs->cset->long10_to_str(cs,to,mlength,-10,(long) j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
val_buffer->set_charset(cs);
return val_buffer;
}
bool Field_long::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
if (is_null())
return protocol->store_null();
return protocol->store_long(Field_long::val_int());
}
int Field_long::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
a=sint4korr(a_ptr);
b=sint4korr(b_ptr);
}
else
#endif
{
longget(&a, a_ptr);
longget(&b, b_ptr);
}
if (unsigned_flag)
return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_long::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 4);
#ifdef WORDS_BIGENDIAN
if (!table->s->db_low_byte_first)
{
if (unsigned_flag)
to[0] = ptr[0];
else
to[0] = (char) (ptr[0] ^ 128); /* Revers signbit */
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
}
else
#endif
{
if (unsigned_flag)
to[0] = ptr[3];
else
to[0] = (char) (ptr[3] ^ 128); /* Revers signbit */
to[1] = ptr[2];
to[2] = ptr[1];
to[3] = ptr[0];
}
}
void Field_long::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"int(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/****************************************************************************
Field type longlong int (8 bytes)
****************************************************************************/
type_conversion_status
Field_longlong::store(const char *from, size_t len, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int conv_err= 0;
type_conversion_status error= TYPE_OK;
char *end;
ulonglong tmp;
tmp= cs->cset->strntoull10rnd(cs,from,len,unsigned_flag,&end,&conv_err);
if (conv_err == MY_ERRNO_ERANGE)
{
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (table->in_use->count_cuted_fields &&
check_int(cs, from, len, end, conv_err))
error= TYPE_WARN_OUT_OF_RANGE;
else
error= TYPE_OK;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,tmp);
}
else
#endif
longlongstore(ptr,tmp);
return error;
}
type_conversion_status Field_longlong::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
longlong res;
nr= rint(nr);
if (unsigned_flag)
{
if (nr < 0)
{
res=0;
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr >= (double) ULLONG_MAX)
{
res= ~(longlong) 0;
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(longlong) double2ulonglong(nr);
}
else
{
if (nr <= (double) LLONG_MIN)
{
res= LLONG_MIN;
if (nr < (double) LLONG_MIN)
error= TYPE_WARN_OUT_OF_RANGE;
}
else if (nr >= (double) (ulonglong) LLONG_MAX)
{
res= LLONG_MAX;
if (nr > (double) LLONG_MAX)
error= TYPE_WARN_OUT_OF_RANGE;
}
else
res=(longlong) nr;
}
if (error)
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,res);
}
else
#endif
longlongstore(ptr,res);
return error;
}
type_conversion_status Field_longlong::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
if (nr < 0) // Only possible error
{
/*
if field is unsigned and value is signed (< 0) or
if field is signed and value is unsigned we have an overflow
*/
if (unsigned_flag != unsigned_val)
{
nr= unsigned_flag ? (ulonglong) 0 : (ulonglong) LLONG_MAX;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
error= TYPE_WARN_OUT_OF_RANGE;
}
}
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,nr);
}
else
#endif
longlongstore(ptr,nr);
return error;
}
double Field_longlong::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
j=sint8korr(ptr);
}
else
#endif
longlongget(&j, ptr);
/* The following is open coded to avoid a bug in gcc 3.3 */
if (unsigned_flag)
{
ulonglong tmp= (ulonglong) j;
return ulonglong2double(tmp);
}
return (double) j;
}
longlong Field_longlong::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
longlong j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint8korr(ptr);
else
#endif
longlongget(&j, ptr);
return j;
}
String *Field_longlong::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
const CHARSET_INFO *cs= &my_charset_numeric;
uint length;
uint mlength=max(field_length+1,22*cs->mbmaxlen);
val_buffer->alloc(mlength);
char *to=(char*) val_buffer->ptr();
longlong j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
j=sint8korr(ptr);
else
#endif
longlongget(&j, ptr);
length=(uint) (cs->cset->longlong10_to_str)(cs,to,mlength,
unsigned_flag ? 10 : -10, j);
val_buffer->length(length);
if (zerofill)
prepend_zeros(val_buffer);
val_buffer->set_charset(cs);
return val_buffer;
}
bool Field_longlong::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
if (is_null())
return protocol->store_null();
return protocol->store_longlong(Field_longlong::val_int(), unsigned_flag);
}
int Field_longlong::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
longlong a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
a=sint8korr(a_ptr);
b=sint8korr(b_ptr);
}
else
#endif
{
longlongget(&a, a_ptr);
longlongget(&b, b_ptr);
}
if (unsigned_flag)
return ((ulonglong) a < (ulonglong) b) ? -1 :
((ulonglong) a > (ulonglong) b) ? 1 : 0;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_longlong::make_sort_key(uchar *to, size_t length)
{
const size_t from_length= PACK_LENGTH;
const size_t to_length= min(from_length, length);
#ifdef WORDS_BIGENDIAN
if (table == NULL || !table->s->db_low_byte_first)
copy_integer<true>(to, to_length, ptr, from_length, unsigned_flag);
else
#endif
copy_integer<false>(to, to_length, ptr, from_length, unsigned_flag);
}
void Field_longlong::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"bigint(%d)",(int) field_length));
add_zerofill_and_unsigned(res);
}
/*
Floating-point numbers
*/
uchar *
Field_real::pack(uchar *to, const uchar *from,
uint max_length, bool low_byte_first)
{
DBUG_ENTER("Field_real::pack");
DBUG_ASSERT(max_length >= pack_length());
#ifdef WORDS_BIGENDIAN
if (low_byte_first != table->s->db_low_byte_first)
{
const uchar *dptr= from + pack_length();
while (dptr-- > from)
*to++ = *dptr;
DBUG_RETURN(to);
}
else
#endif
DBUG_RETURN(Field::pack(to, from, max_length, low_byte_first));
}
const uchar *
Field_real::unpack(uchar *to, const uchar *from,
uint param_data, bool low_byte_first)
{
DBUG_ENTER("Field_real::unpack");
#ifdef WORDS_BIGENDIAN
if (low_byte_first != table->s->db_low_byte_first)
{
const uchar *dptr= from + pack_length();
while (dptr-- > from)
*to++ = *dptr;
DBUG_RETURN(from + pack_length());
}
else
#endif
DBUG_RETURN(Field::unpack(to, from, param_data, low_byte_first));
}
type_conversion_status
Field_real::store_time(MYSQL_TIME *ltime,
uint8 dec_arg MY_ATTRIBUTE((unused)))
{
double nr= TIME_to_double(ltime);
return store(ltime->neg ? -nr : nr);
}
/****************************************************************************
single precision float
****************************************************************************/
type_conversion_status
Field_float::store(const char *from, size_t len, const CHARSET_INFO *cs)
{
int conv_error;
type_conversion_status err= TYPE_OK;
char *end;
double nr= my_strntod(cs,(char*) from,len,&end,&conv_error);
if (conv_error || (!len || ((uint) (end-from) != len &&
table->in_use->count_cuted_fields)))
{
set_warning(Sql_condition::SL_WARNING,
(conv_error ? ER_WARN_DATA_OUT_OF_RANGE
: WARN_DATA_TRUNCATED),
1);
err= conv_error ? TYPE_WARN_OUT_OF_RANGE : TYPE_WARN_TRUNCATED;
}
Field_float::store(nr);
return err;
}
type_conversion_status Field_float::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
const type_conversion_status error=
truncate(&nr, FLT_MAX) ? TYPE_WARN_OUT_OF_RANGE : TYPE_OK;
float j= (float)nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4store(ptr,j);
}
else
#endif
memcpy(ptr, &j, sizeof(j));
return error;
}
type_conversion_status Field_float::store(longlong nr, bool unsigned_val)
{
return Field_float::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
(double) nr);
}
double Field_float::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
float j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(&j,ptr);
}
else
#endif
memcpy(&j, ptr, sizeof(j));
return ((double) j);
}
longlong Field_float::val_int(void)
{
float j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(&j,ptr);
}
else
#endif
memcpy(&j, ptr, sizeof(j));
return (longlong) rint(j);
}
String *Field_float::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
float nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(&nr,ptr);
}
else
#endif
memcpy(&nr, ptr, sizeof(nr));
uint to_length= 70;
if (val_buffer->alloc(to_length))
{
my_error(ER_OUT_OF_RESOURCES, MYF(0));
return val_buffer;
}
char *to=(char*) val_buffer->ptr();
size_t len;
if (dec >= NOT_FIXED_DEC)
len= my_gcvt(nr, MY_GCVT_ARG_FLOAT, to_length - 1, to, NULL);
else
{
/*
We are safe here because the buffer length is 70, and
fabs(float) < 10^39, dec < NOT_FIXED_DEC. So the resulting string
will be not longer than 69 chars + terminating '\0'.
*/
len= my_fcvt(nr, dec, to, NULL);
}
val_buffer->length((uint) len);
if (zerofill)
prepend_zeros(val_buffer);
val_buffer->set_charset(&my_charset_numeric);
return val_buffer;
}
int Field_float::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
float a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(&a,a_ptr);
float4get(&b,b_ptr);
}
else
#endif
{
memcpy(&a, a_ptr, sizeof(float));
memcpy(&b, b_ptr, sizeof(float));
}
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
#define FLT_EXP_DIG (sizeof(float)*8-FLT_MANT_DIG)
void Field_float::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 4);
float nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float4get(&nr,ptr);
}
else
#endif
memcpy(&nr, ptr, min(length, sizeof(float)));
uchar *tmp= to;
if (nr == (float) 0.0)
{ /* Change to zero string */
tmp[0]=(uchar) 128;
memset(tmp + 1, 0, min(length, sizeof(nr) - 1));
}
else
{
#ifdef WORDS_BIGENDIAN
memcpy(tmp, &nr, sizeof(nr));
#else
tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
#endif
if (tmp[0] & 128) /* Negative */
{ /* make complement */
uint i;
for (i=0 ; i < sizeof(nr); i++)
tmp[i]= (uchar) (tmp[i] ^ (uchar) 255);
}
else
{
ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
(ushort) 32768);
exp_part+= (ushort) 1 << (16-1-FLT_EXP_DIG);
tmp[0]= (uchar) (exp_part >> 8);
tmp[1]= (uchar) exp_part;
}
}
}
bool Field_float::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
if (is_null())
return protocol->store_null();
return protocol->store((float) Field_float::val_real(), dec, (String*) 0);
}
/**
Save the field metadata for float fields.
Saves the pack length in the first byte.
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_float::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= pack_length();
return 1;
}
void Field_float::sql_type(String &res) const
{
if (dec == NOT_FIXED_DEC)
{
res.set_ascii(STRING_WITH_LEN("float"));
}
else
{
const CHARSET_INFO *cs= res.charset();
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"float(%d,%d)",(int) field_length,dec));
}
add_zerofill_and_unsigned(res);
}
/****************************************************************************
double precision floating point numbers
****************************************************************************/
type_conversion_status
Field_double::store(const char *from, size_t len, const CHARSET_INFO *cs)
{
int conv_error;
type_conversion_status error= TYPE_OK;
char *end;
double nr= my_strntod(cs,(char*) from, len, &end, &conv_error);
if ((conv_error != 0) || (!len || ((uint) (end-from) != len &&
table->in_use->count_cuted_fields)))
{
set_warning(Sql_condition::SL_WARNING,
(conv_error ? ER_WARN_DATA_OUT_OF_RANGE
: WARN_DATA_TRUNCATED),
1);
error= conv_error ? TYPE_WARN_OUT_OF_RANGE : TYPE_WARN_TRUNCATED;
}
Field_double::store(nr);
return error;
}
type_conversion_status Field_double::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
const type_conversion_status error=
truncate(&nr, DBL_MAX) ? TYPE_WARN_OUT_OF_RANGE : TYPE_OK;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8store(ptr,nr);
}
else
#endif
doublestore(ptr,nr);
return error;
}
type_conversion_status Field_double::store(longlong nr, bool unsigned_val)
{
return Field_double::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
(double) nr);
}
/*
If a field has fixed length, truncate the double argument pointed to by 'nr'
appropriately.
Also ensure that the argument is within [-max_value; max_value] range.
*/
bool Field_real::truncate(double *nr, double max_value)
{
if (my_isnan(*nr))
{
*nr= 0;
set_null();
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return true;
}
else if (unsigned_flag && *nr < 0)
{
*nr= 0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return true;
}
if (!not_fixed)
{
uint order= field_length - dec;
uint step= array_elements(log_10) - 1;
max_value= 1.0;
for (; order > step; order-= step)
max_value*= log_10[step];
max_value*= log_10[order];
max_value-= 1.0 / log_10[dec];
/* Check for infinity so we don't get NaN in calculations */
if (!my_isinf(*nr))
{
double tmp= rint((*nr - floor(*nr)) * log_10[dec]) / log_10[dec];
*nr= floor(*nr) + tmp;
}
}
if (*nr < -max_value)
{
*nr= -max_value;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return true;
}
else if (*nr > max_value)
{
*nr= max_value;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return true;
}
return false;
}
type_conversion_status Field_real::store_decimal(const my_decimal *dm)
{
double dbl;
my_decimal2double(E_DEC_FATAL_ERROR, dm, &dbl);
return store(dbl);
}
double Field_double::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double j;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(&j,ptr);
}
else
#endif
doubleget(&j,ptr);
return j;
}
longlong Field_double::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double j;
longlong res;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(&j,ptr);
}
else
#endif
doubleget(&j,ptr);
/* Check whether we fit into longlong range */
if (j <= (double) LLONG_MIN)
{
res= (longlong) LLONG_MIN;
goto warn;
}
if (j >= (double) (ulonglong) LLONG_MAX)
{
res= (longlong) LLONG_MAX;
goto warn;
}
return (longlong) rint(j);
warn:
{
char buf[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
String tmp(buf, sizeof(buf), &my_charset_latin1), *str;
str= val_str(&tmp, 0);
ErrConvString err(str);
push_warning_printf(current_thd, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
err.ptr());
}
return res;
}
my_decimal *Field_real::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
double2my_decimal(E_DEC_FATAL_ERROR, val_real(), decimal_value);
return decimal_value;
}
bool Field_real::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
return my_double_to_datetime_with_warn(val_real(), ltime, fuzzydate);
}
bool Field_real::get_time(MYSQL_TIME *ltime)
{
return my_double_to_time_with_warn(val_real(), ltime);
}
String *Field_double::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
double nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(&nr,ptr);
}
else
#endif
doubleget(&nr,ptr);
uint to_length= DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE;
if (val_buffer->alloc(to_length))
{
my_error(ER_OUT_OF_RESOURCES, MYF(0));
return val_buffer;
}
char *to=(char*) val_buffer->ptr();
size_t len;
if (dec >= NOT_FIXED_DEC)
len= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, to_length - 1, to, NULL);
else
len= my_fcvt(nr, dec, to, NULL);
val_buffer->length((uint) len);
if (zerofill)
prepend_zeros(val_buffer);
val_buffer->set_charset(&my_charset_numeric);
return val_buffer;
}
bool Field_double::send_binary(Protocol *protocol)
{
if (is_null())
return protocol->store_null();
String buf;
return protocol->store(Field_double::val_real(), dec, &buf);
}
int Field_double::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
double a,b;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(&a,a_ptr);
float8get(&b,b_ptr);
}
else
#endif
{
doubleget(&a, a_ptr);
doubleget(&b, b_ptr);
}
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)
/* The following should work for IEEE */
void Field_double::make_sort_key(uchar *to, size_t length)
{
double nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
float8get(&nr, ptr);
}
else
#endif
doubleget(&nr, ptr);
if (length < 8)
{
uchar buff[8];
change_double_for_sort(nr, buff);
memcpy(to, buff, length);
}
else
change_double_for_sort(nr, to);
}
/**
Save the field metadata for double fields.
Saves the pack length in the first byte of the field metadata array
at index of *metadata_ptr.
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_double::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= pack_length();
return 1;
}
void Field_double::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
if (dec == NOT_FIXED_DEC)
{
res.set_ascii(STRING_WITH_LEN("double"));
}
else
{
res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
"double(%d,%d)",(int) field_length,dec));
}
add_zerofill_and_unsigned(res);
}
/****************************************************************************
** Common code for all temporal data types: DATE, DATETIME, TIMESTAMP, TIME
*****************************************************************************/
uint Field_temporal::is_equal(Create_field *new_field)
{
return new_field->sql_type == real_type() &&
new_field->decimals == decimals();
}
my_decimal *Field_temporal::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(decimals() == 0);
int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 0, decimal_value);
return decimal_value;
}
/**
Set warnings from a warning vector.
Note, multiple warnings can be set at the same time.
@param str Value.
@param warnings Warning vector.
*/
void
Field_temporal::set_warnings(ErrConvString str, int warnings)
{
int cut_incremented= 0;
timestamp_type ts_type= field_type_to_timestamp_type(type());
if (warnings & MYSQL_TIME_WARN_TRUNCATED)
{
set_datetime_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED,
str, ts_type, !cut_incremented);
cut_incremented= 1;
}
if (warnings & (MYSQL_TIME_WARN_OUT_OF_RANGE | MYSQL_TIME_WARN_ZERO_DATE |
MYSQL_TIME_WARN_ZERO_IN_DATE))
{
set_datetime_warning(Sql_condition::SL_WARNING,
ER_WARN_DATA_OUT_OF_RANGE,
str, ts_type, !cut_incremented);
cut_incremented= 1;
}
if (warnings & MYSQL_TIME_WARN_INVALID_TIMESTAMP)
{
set_datetime_warning(Sql_condition::SL_WARNING,
ER_WARN_INVALID_TIMESTAMP,
str, ts_type, !cut_incremented);
cut_incremented= 1;
}
if ((warnings & MYSQL_TIME_NOTE_TRUNCATED) &&
!(warnings & MYSQL_TIME_WARN_TRUNCATED))
{
set_datetime_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED,
str, ts_type, !cut_incremented);
}
}
type_conversion_status Field_temporal::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int warnings= 0;
MYSQL_TIME ltime;
type_conversion_status error= convert_number_to_TIME(nr, unsigned_val, 0,
<ime, &warnings);
if (error == TYPE_OK || error == TYPE_NOTE_TRUNCATED)
error= store_internal(<ime, &warnings);
else
{
DBUG_ASSERT(warnings != 0); // Must be set by convert_number_to_TIME
if (warnings & (MYSQL_TIME_WARN_ZERO_DATE |
MYSQL_TIME_WARN_ZERO_IN_DATE) &&
!current_thd->is_strict_mode())
error= TYPE_NOTE_TIME_TRUNCATED;
}
if (warnings)
set_warnings(ErrConvString(nr, unsigned_val), warnings);
return error;
}
type_conversion_status
Field_temporal::store_lldiv_t(const lldiv_t *lld, int *warnings)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error;
MYSQL_TIME ltime;
error= convert_number_to_TIME(lld->quot, 0, static_cast<int>(lld->rem),
<ime, warnings);
if (error == TYPE_OK || error == TYPE_NOTE_TRUNCATED)
error= store_internal_with_round(<ime, warnings);
else if (!*warnings)
{
DBUG_ASSERT(warnings != 0); // Must be set by convert_number_to_TIME
if (((*warnings & MYSQL_TIME_WARN_ZERO_DATE) != 0 ||
(*warnings & MYSQL_TIME_WARN_ZERO_IN_DATE) != 0) &&
!current_thd->is_strict_mode())
error= TYPE_NOTE_TIME_TRUNCATED;
}
return error;
}
type_conversion_status Field_temporal::store_decimal(const my_decimal *decimal)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
lldiv_t lld;
int warnings= 0;
/* Pass 0 in the first argument, not to produce warnings automatically */
my_decimal2lldiv_t(0, decimal, &lld);
const type_conversion_status error= store_lldiv_t(&lld, &warnings);
if (warnings)
set_warnings(ErrConvString(decimal), warnings);
return error;
}
type_conversion_status Field_temporal::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int warnings= 0;
lldiv_t lld;
double2lldiv_t(nr, &lld);
const type_conversion_status error= store_lldiv_t(&lld, &warnings);
if (warnings)
set_warnings(ErrConvString(nr), warnings);
return error;
}
/**
Store string into a date/time/datetime field.
@param from Date/time string
@param len Length of the string
@param cs Character set of the string
@retval TYPE_OK Storage of value went fine without warnings or errors
@retval !TYPE_OK Warning/error as indicated by type_conversion_status enum
value
*/
type_conversion_status
Field_temporal::store(const char *str, size_t len, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
MYSQL_TIME ltime;
MYSQL_TIME_STATUS status;
if (convert_str_to_TIME(str, len, cs, <ime, &status))
{
/*
When convert_str_to_TIME() returns error, ltime has been set to
0 so there's nothing to store in the field.
*/
reset();
if (status.warnings & (MYSQL_TIME_WARN_ZERO_DATE |
MYSQL_TIME_WARN_ZERO_IN_DATE) &&
!current_thd->is_strict_mode())
error= TYPE_NOTE_TIME_TRUNCATED;
else
error= TYPE_ERR_BAD_VALUE;
}
else
{
error= time_warning_to_type_conversion_status(status.warnings);
const type_conversion_status tmp_error= store_internal_with_round(<ime,
&status.warnings);
// Return the most serious error of the two, see type_conversion_status
if (tmp_error > error)
error= tmp_error;
}
if (status.warnings)
set_warnings(ErrConvString(str, len, cs), status.warnings);
return error;
}
/**
@retval -1 Timestamp with wrong values
@retval anything else DATETIME as integer in YYYYMMDDHHMMSS format
*/
longlong
Field_temporal::convert_number_to_datetime(longlong nr, bool unsigned_val,
MYSQL_TIME *ltime, int *warnings)
{
/*
Note, number_to_datetime can return a result different from nr:
e.g. 111111 -> 20111111000000
*/
longlong tmp= number_to_datetime(nr, ltime, date_flags(), warnings);
if (tmp == -1LL)
reset();
return tmp;
}
/****************************************************************************
** Common code for temporal data types with date: DATE, DATETIME, TIMESTAMP
*****************************************************************************/
bool
Field_temporal_with_date::get_internal_check_zero(MYSQL_TIME *ltime,
my_time_flags_t fuzzydate)
{
if (get_date_internal(ltime)) /* '0000-00-00' */
{
DBUG_ASSERT(type() == MYSQL_TYPE_TIMESTAMP);
if (fuzzydate & TIME_NO_ZERO_DATE)
return true;
set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
}
return false;
}
longlong Field_temporal_with_date::val_date_temporal()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_date_internal(<ime) ?
0 : TIME_to_longlong_datetime_packed(<ime);
}
longlong Field_temporal_with_date::val_time_temporal()
{
/*
There are currently no tests covering this method,
as DATETIME seems to always superseed over TIME in comparison.
*/
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_date_internal(<ime) ? 0 : TIME_to_longlong_time_packed(<ime);
}
/**
Convert a number in format YYMMDDhhmmss to string.
Straight coded to avoid problem with slow longlong arithmetic and sprintf.
@param[out] pos pointer to convert to.
@param tmp number with datetime value.
*/
static inline int
my_datetime_number_to_str(char *pos, longlong tmp)
{
long part1= (long) (tmp / 1000000LL);
long part2= (long) (tmp - (ulonglong) part1 * 1000000LL);
int part3;
pos+= MAX_DATETIME_WIDTH; /* Start from the end */
*pos--= 0;
*pos--= (char) ('0' + (char) (part2 % 10)); /* Seconds */
part2 /= 10;
*pos--= (char) ('0' + (char) (part2 % 10));
part3= (int) (part2 / 10);
*pos--= ':';
*pos--= (char) ('0' + (char) (part3 % 10)); /* Minutes */
part3 /= 10;
*pos--= (char) ('0' + (char) (part3 % 10));
part3 /= 10;
*pos--= ':';
*pos--= (char) ('0' + (char) (part3 % 10)); /* Hours */
part3 /= 10;
*pos--= (char) ('0' + (char) part3);
*pos--= ' ';
*pos--= (char) ('0' + (char) (part1 % 10)); /* Day */
part1 /= 10;
*pos--= (char) ('0' + (char) (part1 % 10));
part1 /= 10;
*pos--= '-';
*pos--= (char) ('0' + (char) (part1 % 10)); /* Month */
part1 /= 10;
*pos--= (char) ('0' + (char) (part1 % 10));
part3= (int) (part1 / 10);
*pos--= '-';
*pos--= (char) ('0' + (char) (part3 % 10)); /* Year */
part3 /= 10;
*pos--= (char) ('0' + (char) (part3 % 10));
part3 /= 10;
*pos--= (char) ('0' + (char) (part3 % 10));
part3 /= 10;
*pos= (char) ('0'+ (char) part3);
return MAX_DATETIME_WIDTH;
}
String *Field_temporal_with_date::val_str(String *val_buffer, String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
val_buffer->alloc(field_length + 1);
val_buffer->set_charset(&my_charset_numeric);
if (get_date_internal(<ime))
{
val_buffer->set_ascii(my_zero_datetime6, field_length);
return val_buffer;
}
make_datetime((Date_time_format *) 0, <ime, val_buffer, dec);
return val_buffer;
}
type_conversion_status
Field_temporal_with_date::convert_number_to_TIME(longlong nr,
bool unsigned_val,
int nanoseconds,
MYSQL_TIME *ltime,
int *warnings)
{
if (nr < 0 || nanoseconds < 0)
{
reset();
*warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE;
return TYPE_WARN_OUT_OF_RANGE;
}
if (convert_number_to_datetime(nr, unsigned_val, ltime, warnings) == -1LL)
return TYPE_ERR_BAD_VALUE;
if (ltime->time_type == MYSQL_TIMESTAMP_DATE && nanoseconds)
{
*warnings|= MYSQL_TIME_WARN_TRUNCATED;
return TYPE_NOTE_TRUNCATED;
}
ltime->second_part= 0;
if (datetime_add_nanoseconds_with_round(ltime, nanoseconds, warnings))
{
reset();
return TYPE_WARN_OUT_OF_RANGE;
}
return TYPE_OK;
}
type_conversion_status
Field_temporal_with_date::store_time(MYSQL_TIME *ltime,
uint8 dec_arg MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error;
int warnings= 0;
switch (ltime->time_type) // TS-TODO: split into separate methods?
{
case MYSQL_TIMESTAMP_DATETIME:
case MYSQL_TIMESTAMP_DATE:
if (check_date(ltime, non_zero_date(ltime), date_flags(), &warnings))
{
DBUG_ASSERT(warnings &
(MYSQL_TIME_WARN_OUT_OF_RANGE |
MYSQL_TIME_WARN_ZERO_DATE |
MYSQL_TIME_WARN_ZERO_IN_DATE));
error= time_warning_to_type_conversion_status(warnings);
reset();
}
else
error= store_internal_with_round(ltime, &warnings);
break;
case MYSQL_TIMESTAMP_TIME:
{
/* Convert TIME to DATETIME */
THD *thd= table ? table->in_use : current_thd;
MYSQL_TIME ltime2;
time_to_datetime(thd, ltime, <ime2);
error= store_internal_with_round(<ime2, &warnings);
break;
}
case MYSQL_TIMESTAMP_NONE:
case MYSQL_TIMESTAMP_ERROR:
default:
warnings|= MYSQL_TIME_WARN_TRUNCATED;
reset();
error= TYPE_WARN_TRUNCATED;
}
if (warnings)
set_warnings(ErrConvString(ltime, decimals()), warnings);
return error;
}
bool
Field_temporal_with_date::convert_str_to_TIME(const char *str, size_t len,
const CHARSET_INFO *cs,
MYSQL_TIME *ltime,
MYSQL_TIME_STATUS *status)
{
return str_to_datetime(cs, str, len, ltime, date_flags(), status);
}
bool Field_temporal_with_date::send_binary(Protocol *protocol)
{
MYSQL_TIME ltime;
if (is_null())
return protocol->store_null();
if (get_date_internal(<ime))
{
// Only MYSQL_TYPE_TIMESTAMP can return an error in get_date_internal()
DBUG_ASSERT(type() == MYSQL_TYPE_TIMESTAMP);
set_zero_time(<ime, MYSQL_TIMESTAMP_DATETIME);
}
return protocol->store(<ime, 0);
}
type_conversion_status
Field_temporal_with_date::store_internal_with_round(MYSQL_TIME *ltime,
int *warnings)
{
if (my_datetime_round(ltime, dec, warnings))
{
reset();
return time_warning_to_type_conversion_status(*warnings);
}
else
return store_internal(ltime, warnings);
}
/**
Validate date value stored in the field.
Now we check whether date value is zero or has zero in date or not and sets
warning/error message appropriately(depending on the sql_mode).
*/
type_conversion_status Field_temporal_with_date::validate_stored_val(THD *thd)
{
MYSQL_TIME ltime;
type_conversion_status error= TYPE_OK;
int warnings= 0;
if (is_real_null())
return error;
memset(<ime, 0, sizeof(MYSQL_TIME));
get_date_internal(<ime);
if (check_date(<ime, non_zero_date(<ime), date_flags(), &warnings))
error= time_warning_to_type_conversion_status(warnings);
if (warnings)
{
ltime.time_type = field_type_to_timestamp_type(type());
set_warnings(ErrConvString(<ime, dec), warnings);
}
return error;
}
/****************************************************************************
** Common code for data types with date and time: DATETIME, TIMESTAMP
*****************************************************************************/
void Field_temporal_with_date_and_time::store_timestamp(const struct timeval *tm)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (!my_time_fraction_remainder(tm->tv_usec, decimals()))
{
store_timestamp_internal(tm);
return;
}
struct timeval tm2= *tm;
my_timeval_round(&tm2, decimals());
store_timestamp_internal(&tm2);
}
bool
Field_temporal_with_date_and_time::convert_TIME_to_timestamp(THD *thd,
const MYSQL_TIME *ltime,
struct timeval *tm,
int *warnings)
{
/*
No need to do check_date(TIME_NO_ZERO_IN_DATE),
because it has been done earlier in
store_time(), number_to_datetime() or str_to_datetime().
*/
if (datetime_with_no_zero_in_date_to_timeval(thd, ltime, tm, warnings))
{
tm->tv_sec= tm->tv_usec= 0;
return true;
}
return false;
}
void Field_temporal_with_date_and_time::init_timestamp_flags()
{
if (unireg_check != NONE)
{
/*
This TIMESTAMP column is hereby quietly assumed to have an insert or
update default function.
*/
flags|= TIMESTAMP_FLAG;
if (unireg_check != TIMESTAMP_DN_FIELD)
flags|= ON_UPDATE_NOW_FLAG;
}
}
/****************************************************************************
** Common code for DATETIME(N) and TIMESTAMP(N)
*****************************************************************************/
double Field_temporal_with_date_and_timef::val_real()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_date_internal(<ime) ? 0 : TIME_to_double_datetime(<ime);
}
longlong Field_temporal_with_date_and_timef::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_date_internal(<ime) ?
0 : TIME_to_ulonglong_datetime_round(<ime);
}
my_decimal *Field_temporal_with_date_and_timef::val_decimal(my_decimal *dec_arg)
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
if (get_date_internal(<ime))
{
// Only MYSQL_TYPE_TIMESTAMP can return an error in get_date_internal()
DBUG_ASSERT(type() == MYSQL_TYPE_TIMESTAMP);
set_zero_time(<ime, MYSQL_TIMESTAMP_DATETIME);
}
return date2my_decimal(<ime, dec_arg);
}
/**
TIMESTAMP type columns hold date and time values in the range 1970-01-01
00:00:01 UTC to 2038-01-01 00:00:00 UTC, stored as number of seconds since
the start of the Unix Epoch (1970-01-01 00:00:01 UTC.)
TIMESTAMP columns can be automatically set on row updates to and/or have
CURRENT_TIMESTAMP as default value for inserts.
The implementation of function defaults is heavily entangled with the binary
.frm file format. The @c utype @c enum is part of the file format
specification but is declared a member of the Field class. This constructor
accepts a unireg_check value to initialize the column default expression.
Five distinct unireg_check values are used for TIMESTAMP columns to
distinguish various cases of DEFAULT or ON UPDATE values. These values are:
- TIMESTAMP_OLD_FIELD - old timestamp, this has no significance when
creating a the Field_timestamp.
- TIMESTAMP_DN_FIELD - means TIMESTAMP DEFAULT CURRENT_TIMESTAMP.
- TIMESTAMP_UN_FIELD - means TIMESTAMP DEFAULT <default value> ON UPDATE
CURRENT_TIMESTAMP, where <default value> is an implicit or explicit
expression other than CURRENT_TIMESTAMP or any synonym thereof
(e.g. NOW().)
- TIMESTAMP_DNUN_FIELD - means DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP.
- NONE - means that the column has neither DEFAULT CURRENT_TIMESTAMP, nor ON
UPDATE CURRENT_TIMESTAMP
Note that columns with TIMESTAMP_OLD_FIELD are no longer created explicitly,
the value is meant to preserve the ability to read tables from old
databases. Such columns are replaced with their newer counterparts by CREATE
TABLE and SHOW CREATE TABLE. This is because we want to prefer NONE
unireg_check over TIMESTAMP_OLD_FIELD for "TIMESTAMP DEFAULT 'Const'"
field. (Old TIMESTAMP columns allowed such definitions as well but ignored
the default value for first the TIMESTAMP column. This is, of course,
non-standard.) In most cases a user won't notice any change, only exception
being different behavior of old/new TIMESTAMPS columns during ALTER TABLE.
*/
Field_timestamp::Field_timestamp(uchar *ptr_arg, uint32 len_arg,
uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg)
:Field_temporal_with_date_and_time(ptr_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg, 0)
{
init_timestamp_flags();
/* For 4.0 MYD and 4.0 InnoDB compatibility */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
}
Field_timestamp::Field_timestamp(bool maybe_null_arg,
const char *field_name_arg)
:Field_temporal_with_date_and_time((uchar *) 0,
maybe_null_arg ? (uchar *) "" : 0, 0,
NONE, field_name_arg, 0)
{
init_timestamp_flags();
/* For 4.0 MYD and 4.0 InnoDB compatibility */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
}
my_time_flags_t Field_timestamp::date_flags(const THD *thd)
{
/* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
my_time_flags_t date_flags= TIME_NO_ZERO_IN_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
date_flags|= TIME_NO_ZERO_DATE;
return date_flags;
}
type_conversion_status
Field_timestamp::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
THD *thd= table ? table->in_use : current_thd;
struct timeval tm;
convert_TIME_to_timestamp(thd, ltime, &tm, warnings);
const type_conversion_status error=
time_warning_to_type_conversion_status(*warnings);
store_timestamp_internal(&tm);
return error;
}
/**
Get a value from record, without checking fuzzy date flags.
@retval true - if timestamp is 0, ltime is not touched in this case.
@retval false - if timestamp is non-zero.
*/
bool Field_timestamp::get_date_internal(MYSQL_TIME *ltime)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint32 temp;
THD *thd= table ? table->in_use : current_thd;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
temp= uint4korr(ptr);
else
#endif
ulongget(&temp, ptr);
if (!temp)
return true;
thd->time_zone()->gmt_sec_to_TIME(ltime, (my_time_t) temp);
return false;
}
/**
Get TIMESTAMP field value as seconds since begging of Unix Epoch
*/
bool Field_timestamp::get_timestamp(struct timeval *tm, int *warnings)
{
if (is_null())
return true;
tm->tv_usec= 0;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
tm->tv_sec= sint4korr(ptr);
return false;
}
#endif
int32 tmp;
longget(&tmp, ptr);
tm->tv_sec= tmp;
return false;
}
void Field_timestamp::store_timestamp_internal(const struct timeval *tm)
{
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int4store(ptr, tm->tv_sec);
}
else
#endif
longstore(ptr, (uint32) tm->tv_sec);
}
type_conversion_status Field_timestamp::store_packed(longlong nr)
{
/* Make sure the stored value was previously properly rounded or truncated */
DBUG_ASSERT((MY_PACKED_TIME_GET_FRAC_PART(nr) %
(int) log_10_int[DATETIME_MAX_DECIMALS - decimals()]) == 0);
MYSQL_TIME ltime;
TIME_from_longlong_datetime_packed(<ime, nr);
return Field_timestamp::store_time(<ime, 0);
}
longlong Field_timestamp::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_date_internal(<ime) ? 0 : TIME_to_ulonglong_datetime(<ime);
}
bool Field_timestamp::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
/* Don't do check_fuzzy_date() as month and year are never 0 for timestamp */
return get_internal_check_zero(ltime, fuzzydate);
}
int Field_timestamp::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
a=sint4korr(a_ptr);
b=sint4korr(b_ptr);
}
else
#endif
{
longget(&a, a_ptr);
longget(&b, b_ptr);
}
return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}
void Field_timestamp::make_sort_key(uchar *to, size_t length MY_ATTRIBUTE((unused)))
{
#ifdef WORDS_BIGENDIAN
if (!table || !table->s->db_low_byte_first)
{
to[0] = ptr[0];
to[1] = ptr[1];
to[2] = ptr[2];
to[3] = ptr[3];
}
else
#endif
{
to[0] = ptr[3];
to[1] = ptr[2];
to[2] = ptr[1];
to[3] = ptr[0];
}
}
void Field_timestamp::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("timestamp"));
}
type_conversion_status Field_timestamp::validate_stored_val(THD *thd)
{
/*
While deprecating "TIMESTAMP with implicit DEFAULT value", we can
remove this function implementation and depend directly on
"Field_temporal_with_date::validate_stored_val"
*/
if (!thd->variables.explicit_defaults_for_timestamp)
return TYPE_OK;
return (Field_temporal_with_date::validate_stored_val(thd));
}
/****************************************************************************
** timestamp(N) type
** In string context: YYYY-MM-DD HH:MM:SS.FFFFFF
** In number context: YYYYMMDDHHMMSS.FFFFFF
** Stored as a 7 byte value
****************************************************************************/
Field_timestampf::Field_timestampf(uchar *ptr_arg,
uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg,
uint8 dec_arg)
:Field_temporal_with_date_and_timef(ptr_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg,
dec_arg)
{
init_timestamp_flags();
}
Field_timestampf::Field_timestampf(bool maybe_null_arg,
const char *field_name_arg,
uint8 dec_arg)
:Field_temporal_with_date_and_timef((uchar*) 0,
maybe_null_arg ? (uchar*) "": 0, 0,
NONE, field_name_arg, dec_arg)
{
if (unireg_check != TIMESTAMP_DN_FIELD)
flags|= ON_UPDATE_NOW_FLAG;
}
my_time_flags_t Field_timestampf::date_flags(const THD *thd)
{
/* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
my_time_flags_t date_flags= TIME_NO_ZERO_IN_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
date_flags|= TIME_NO_ZERO_DATE;
return date_flags;
}
type_conversion_status Field_timestampf::reset()
{
memset(ptr, 0, pack_length());
return TYPE_OK;
}
void Field_timestampf::store_timestamp_internal(const struct timeval *tm)
{
my_timestamp_to_binary(tm, ptr, dec);
}
type_conversion_status
Field_timestampf::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
THD *thd= table ? table->in_use : current_thd;
struct timeval tm;
convert_TIME_to_timestamp(thd, ltime, &tm, warnings);
const type_conversion_status error=
time_warning_to_type_conversion_status(*warnings);
store_timestamp_internal(&tm);
return error;
}
type_conversion_status Field_timestampf::store_packed(longlong nr)
{
MYSQL_TIME ltime;
TIME_from_longlong_datetime_packed(<ime, nr);
return Field_timestampf::store_time(<ime, dec);
}
bool Field_timestampf::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
/* Don't do check_fuzzy_date() as month and year are never 0 for timestamp */
return get_internal_check_zero(ltime, fuzzydate);
}
void Field_timestampf::sql_type(String &res) const
{
if (dec == 0)
{
res.set_ascii(STRING_WITH_LEN("timestamp"));
return;
}
const CHARSET_INFO *cs= res.charset();
res.length(cs->cset->snprintf(cs, (char *) res.ptr(), res.alloced_length(),
"timestamp(%d)", dec));
}
bool
Field_timestampf::get_date_internal(MYSQL_TIME *ltime)
{
THD *thd= table ? table->in_use : current_thd;
struct timeval tm;
my_timestamp_from_binary(&tm, ptr, dec);
if (tm.tv_sec == 0)
return true;
thd->time_zone()->gmt_sec_to_TIME(ltime, tm);
return false;
}
bool Field_timestampf::get_timestamp(struct timeval *tm, int *warnings)
{
THD *thd= table ? table->in_use : current_thd;
thd->time_zone_used= 1;
DBUG_ASSERT(!is_null());
my_timestamp_from_binary(tm, ptr, dec);
return false;
}
type_conversion_status Field_timestampf::validate_stored_val(THD *thd)
{
/*
While deprecating "TIMESTAMP with implicit DEFAULT value", we can
remove this function implementation and depend directly on
"Field_temporal_with_date::validate_stored_val"
*/
if (!thd->variables.explicit_defaults_for_timestamp)
return TYPE_OK;
return (Field_temporal_with_date::validate_stored_val(thd));
}
/****************************************************************************
** TIME and TIME(N) common methods
****************************************************************************/
bool
Field_time_common::convert_str_to_TIME(const char *str, size_t len,
const CHARSET_INFO *cs,
MYSQL_TIME *ltime,
MYSQL_TIME_STATUS *status)
{
return str_to_time(cs, str, len, ltime, 0, status);
}
type_conversion_status
Field_time_common::convert_number_to_TIME(longlong nr, bool unsigned_val,
int nanoseconds,
MYSQL_TIME *ltime, int *warnings)
{
if (unsigned_val && nr < 0)
{
*warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE;
set_max_time(ltime, 0);
store_internal(ltime, warnings);
return TYPE_WARN_OUT_OF_RANGE;
}
if (number_to_time(nr, ltime, warnings))
{
store_internal(ltime, warnings);
return TYPE_WARN_OUT_OF_RANGE;
}
/*
Both number_to_time() call and negative nanoseconds value
affect ltime->neg, hence "|=" to combine them:
*/
if ((ltime->neg|= (nanoseconds < 0)))
nanoseconds= -nanoseconds;
ltime->second_part= 0;
bool round_error= time_add_nanoseconds_with_round(ltime, nanoseconds,
warnings);
return round_error ? time_warning_to_type_conversion_status(*warnings)
: TYPE_OK;
}
type_conversion_status
Field_time_common::store_time(MYSQL_TIME *ltime,
uint8 dec_arg MY_ATTRIBUTE((unused)))
{
/* Check if seconds or minutes are out of range */
if (ltime->second >= 60 || ltime->minute >= 60)
{
set_warnings(ErrConvString(ltime, decimals()),
MYSQL_TIME_WARN_OUT_OF_RANGE);
reset();
return TYPE_WARN_OUT_OF_RANGE;
}
int warnings= 0;
return store_internal_with_round(ltime, &warnings);
}
type_conversion_status
Field_time_common::store_internal_with_round(MYSQL_TIME *ltime, int *warnings)
{
if (my_time_round(ltime, dec))
return TYPE_WARN_OUT_OF_RANGE;
return store_internal(ltime, warnings);
}
String *Field_time_common::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
val_buffer->alloc(MAX_DATE_STRING_REP_LENGTH);
val_buffer->set_charset(&my_charset_numeric);
if (get_time(<ime))
{
DBUG_ASSERT(0);
set_zero_time(<ime, MYSQL_TIMESTAMP_TIME);
}
make_time((Date_time_format *) 0, <ime, val_buffer, dec);
return val_buffer;
}
/**
For a column for TIME type, get_date() takes the time
value of the field, adds current date to it and returns
the result as a DATETIME value.
*/
bool Field_time_common::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME tm;
if (get_time(&tm))
{
DBUG_ASSERT(0);
set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
}
time_to_datetime(table ? table->in_use : current_thd, &tm, ltime);
return false;
}
longlong Field_time_common::val_date_temporal()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME time, datetime;
if (get_time(&time))
{
DBUG_ASSERT(0); // Field_time*::get_time should not fail
return 0;
}
time_to_datetime(table ? table->in_use : current_thd, &time, &datetime);
return TIME_to_longlong_datetime_packed(&datetime);
}
bool Field_time_common::send_binary(Protocol *protocol)
{
MYSQL_TIME ltime;
if (is_null())
return protocol->store_null();
if (get_time(<ime))
{
DBUG_ASSERT(0);
set_zero_time(<ime, MYSQL_TIMESTAMP_TIME);
}
ltime.day= ltime.hour / 24; // Move hours to days
ltime.hour-= ltime.day * 24;
return protocol->store_time(<ime, 0);
}
/****************************************************************************
** time type
** In string context: HH:MM:SS
** In number context: HHMMSS
** Stored as a 3 byte unsigned int
****************************************************************************/
type_conversion_status
Field_time::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
long tmp= ((ltime->month ? 0 : ltime->day * 24L) + ltime->hour) * 10000L +
(ltime->minute * 100 + ltime->second);
if (ltime->neg)
tmp= -tmp;
int3store(ptr, tmp);
return TYPE_OK;
}
type_conversion_status Field_time::store_packed(longlong nr)
{
MYSQL_TIME ltime;
TIME_from_longlong_time_packed(<ime, nr);
return Field_time::store_time(<ime, 0);
}
longlong Field_time::val_time_temporal()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_time(<ime) ? 0 : TIME_to_longlong_time_packed(<ime);
}
longlong Field_time::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
return (longlong) sint3korr(ptr);
}
bool Field_time::get_time(MYSQL_TIME *ltime)
{
long tmp=(long) sint3korr(ptr);
if ((ltime->neg= tmp < 0))
tmp= -tmp;
ltime->year= ltime->month= ltime->day= 0;
TIME_set_hhmmss(ltime, tmp);
ltime->second_part=0;
ltime->time_type= MYSQL_TIMESTAMP_TIME;
return false;
}
int Field_time::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
int32 a,b;
a= sint3korr(a_ptr);
b= sint3korr(b_ptr);
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_time::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 3);
to[0] = (uchar) (ptr[2] ^ 128);
to[1] = ptr[1];
to[2] = ptr[0];
}
void Field_time::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("time"));
}
/****************************************************************************
** time type with fsp
** In string context: HH:MM:SS.FFFFFF
** In number context: HHMMSS.FFFFFF
****************************************************************************/
longlong Field_timef::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
if (get_time(<ime))
{
DBUG_ASSERT(0);
set_zero_time(<ime, MYSQL_TIMESTAMP_TIME);
}
longlong tmp= (longlong) TIME_to_ulonglong_time_round(<ime);
return ltime.neg ? -tmp : tmp;
}
my_decimal *Field_timef::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
if (get_time(<ime))
{
DBUG_ASSERT(0);
set_zero_time(<ime, MYSQL_TIMESTAMP_TIME);
}
return time2my_decimal(<ime, decimal_value);
}
double Field_timef::val_real()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
if (get_time(<ime))
{
DBUG_ASSERT(0);
return 0;
}
double tmp= TIME_to_double_time(<ime);
return ltime.neg ? -tmp : tmp;
}
void Field_timef::sql_type(String &res) const
{
if (dec == 0)
{
res.set_ascii(STRING_WITH_LEN("time"));
return;
}
const CHARSET_INFO *cs= res.charset();
res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
"time(%d)", dec));
}
type_conversion_status Field_timef::reset()
{
return store_packed(0);
}
type_conversion_status Field_timef::store_packed(longlong nr)
{
my_time_packed_to_binary(nr, ptr, dec);
return TYPE_OK;
}
longlong Field_timef::val_time_temporal()
{
ASSERT_COLUMN_MARKED_FOR_READ;
return my_time_packed_from_binary(ptr, dec);
}
type_conversion_status
Field_timef::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
type_conversion_status rc= store_packed(TIME_to_longlong_time_packed(ltime));
if (rc == TYPE_OK && non_zero_date(ltime))
{
/*
The DATE part got lost; we warn, like in Field_newdate::store_internal,
and trigger some code in get_mm_leaf()
(see err==TYPE_NOTE_TIME_TRUNCATED there).
*/
*warnings|= MYSQL_TIME_NOTE_TRUNCATED;
rc= TYPE_NOTE_TIME_TRUNCATED;
}
return rc;
}
bool Field_timef::get_time(MYSQL_TIME *ltime)
{
longlong tmp= val_time_temporal();
TIME_from_longlong_time_packed(ltime, tmp);
return false;
}
/****************************************************************************
** year type
** Save in a byte the year 0, 1901->2155
** Can handle 2 byte or 4 byte years!
****************************************************************************/
type_conversion_status
Field_year::store(const char *from, size_t len,const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char *end;
int conv_error;
type_conversion_status ret= TYPE_OK;
longlong nr= cs->cset->strntoull10rnd(cs, from, len, 0, &end, &conv_error);
if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155 ||
conv_error == MY_ERRNO_ERANGE)
{
*ptr=0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return TYPE_WARN_OUT_OF_RANGE;
}
if (conv_error)
ret= TYPE_ERR_BAD_VALUE;
if (table->in_use->count_cuted_fields)
ret= check_int(cs, from, len, end, conv_error);
if (ret != TYPE_OK)
{
if (ret == TYPE_ERR_BAD_VALUE) /* empty or incorrect string */
{
*ptr= 0; // Invalid date
return ret;
}
ret= TYPE_WARN_OUT_OF_RANGE;
}
if (nr != 0 || len != 4)
{
if (nr < YY_PART_YEAR)
nr+=100; // 2000 - 2069
else if (nr > 1900)
nr-= 1900;
}
*ptr= (char) (uchar) nr;
return ret;
}
type_conversion_status Field_year::store(double nr)
{
if (nr < 0.0 || nr > 2155.0)
{
(void) Field_year::store((longlong) -1, FALSE);
return TYPE_WARN_OUT_OF_RANGE;
}
return Field_year::store((longlong) nr, FALSE);
}
type_conversion_status
Field_year::store_time(MYSQL_TIME *ltime,
uint8 dec_arg MY_ATTRIBUTE((unused)))
{
if (ltime->time_type != MYSQL_TIMESTAMP_DATETIME &&
ltime->time_type != MYSQL_TIMESTAMP_DATE)
{
/* Convert time to datetime, then store year of the result */
THD *thd= table ? table->in_use : current_thd;
MYSQL_TIME ltime2;
time_to_datetime(thd, ltime, <ime2);
return store(ltime2.year, 0);
}
return store(ltime->year, 0);
}
type_conversion_status Field_year::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155)
{
*ptr= 0;
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return TYPE_WARN_OUT_OF_RANGE;
}
if (nr != 0 || field_length != 4) // 0000 -> 0; 00 -> 2000
{
if (nr < YY_PART_YEAR)
nr+=100; // 2000 - 2069
else if (nr > 1900)
nr-= 1900;
}
*ptr= (char) (uchar) nr;
return TYPE_OK;
}
bool Field_year::send_binary(Protocol *protocol)
{
ASSERT_COLUMN_MARKED_FOR_READ;
if (is_null())
return protocol->store_null();
ulonglong tmp= Field_year::val_int();
return protocol->store_short(tmp);
}
double Field_year::val_real(void)
{
return (double) Field_year::val_int();
}
longlong Field_year::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(field_length == 2 || field_length == 4);
int tmp= (int) ptr[0];
if (field_length != 4)
tmp%=100; // Return last 2 char
else if (tmp)
tmp+=1900;
return (longlong) tmp;
}
String *Field_year::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
DBUG_ASSERT(field_length < 5);
val_buffer->alloc(5);
val_buffer->length(field_length);
char *to=(char*) val_buffer->ptr();
sprintf(to,field_length == 2 ? "%02d" : "%04d",(int) Field_year::val_int());
val_buffer->set_charset(&my_charset_numeric);
return val_buffer;
}
void Field_year::sql_type(String &res) const
{
const CHARSET_INFO *cs=res.charset();
res.length(cs->cset->snprintf(cs,(char*)res.ptr(),res.alloced_length(),
"year(%d)",(int) field_length));
}
/****************************************************************************
** The new date type
** Stored as 3 bytes
** In number context: YYYYMMDD
****************************************************************************/
my_time_flags_t Field_newdate::date_flags(const THD *thd)
{
my_time_flags_t date_flags= TIME_FUZZY_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
date_flags|= TIME_NO_ZERO_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
date_flags|= TIME_NO_ZERO_IN_DATE;
if (thd->variables.sql_mode & MODE_INVALID_DATES)
date_flags|= TIME_INVALID_DATES;
return date_flags;
}
type_conversion_status
Field_newdate::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
long tmp= ltime->day + ltime->month * 32 + ltime->year * 16 * 32;
int3store(ptr, tmp);
if (non_zero_time(ltime))
{
*warnings|= MYSQL_TIME_NOTE_TRUNCATED;
return TYPE_NOTE_TIME_TRUNCATED;
}
return TYPE_OK;
}
bool Field_newdate::get_date_internal(MYSQL_TIME *ltime)
{
uint32 tmp= uint3korr(ptr);
ltime->day= tmp & 31;
ltime->month= (tmp >> 5) & 15;
ltime->year= (tmp >> 9);
ltime->time_type= MYSQL_TIMESTAMP_DATE;
ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
return false;
}
type_conversion_status Field_newdate::store_packed(longlong nr)
{
int warnings= 0;
MYSQL_TIME ltime;
TIME_from_longlong_date_packed(<ime, nr);
return store_internal(<ime, &warnings);
}
bool Field_newdate::send_binary(Protocol *protocol)
{
MYSQL_TIME ltime;
if (is_null())
return protocol->store_null();
get_date(<ime, 0);
return protocol->store_date(<ime);
}
longlong Field_newdate::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
ulong j= uint3korr(ptr);
j= (j % 32L)+(j / 32L % 16L)*100L + (j/(16L*32L))*10000L;
return (longlong) j;
}
longlong Field_newdate::val_date_temporal()
{
ASSERT_COLUMN_MARKED_FOR_READ;
MYSQL_TIME ltime;
return get_date_internal(<ime) ? 0 : TIME_to_longlong_date_packed(<ime);
}
longlong Field_newdate::val_time_temporal()
{
ASSERT_COLUMN_MARKED_FOR_READ;
return 0;
}
String *Field_newdate::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
val_buffer->alloc(field_length);
val_buffer->length(field_length);
uint32 tmp= uint3korr(ptr);
int part;
char *pos=(char*) val_buffer->ptr()+10;
/* Open coded to get more speed */
*pos--=0; // End NULL
part=(int) (tmp & 31);
*pos--= (char) ('0'+part%10);
*pos--= (char) ('0'+part/10);
*pos--= '-';
part=(int) (tmp >> 5 & 15);
*pos--= (char) ('0'+part%10);
*pos--= (char) ('0'+part/10);
*pos--= '-';
part=(int) (tmp >> 9);
*pos--= (char) ('0'+part%10); part/=10;
*pos--= (char) ('0'+part%10); part/=10;
*pos--= (char) ('0'+part%10); part/=10;
*pos= (char) ('0'+part);
val_buffer->set_charset(&my_charset_numeric);
return val_buffer;
}
bool Field_newdate::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
return get_internal_check_zero(ltime, fuzzydate) ||
check_fuzzy_date(ltime, fuzzydate);
}
int Field_newdate::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
uint32 a,b;
a= uint3korr(a_ptr);
b= uint3korr(b_ptr);
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_newdate::make_sort_key(uchar *to, size_t length)
{
DBUG_ASSERT(length >= 3);
to[0] = ptr[2];
to[1] = ptr[1];
to[2] = ptr[0];
}
void Field_newdate::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("date"));
}
/****************************************************************************
** datetime type
** In string context: YYYY-MM-DD HH:MM:DD
** In number context: YYYYMMDDHHMMDD
** Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte int.
****************************************************************************/
my_time_flags_t Field_datetime::date_flags(const THD *thd)
{
my_time_flags_t date_flags= TIME_FUZZY_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
date_flags|= TIME_NO_ZERO_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
date_flags|= TIME_NO_ZERO_IN_DATE;
if (thd->variables.sql_mode & MODE_INVALID_DATES)
date_flags|= TIME_INVALID_DATES;
return date_flags;
}
void Field_datetime::store_timestamp_internal(const timeval *tm)
{
MYSQL_TIME mysql_time;
THD *thd= current_thd;
thd->variables.time_zone->gmt_sec_to_TIME(&mysql_time, *tm);
thd->time_zone_used= true;
int error= 0;
store_internal(&mysql_time, &error);
}
/**
Store a DATETIME in a 8-byte integer to record.
@param table Table
@param tmp The number, in YYYYMMDDhhmmss format
@param ptr Where to store to
*/
static inline type_conversion_status
datetime_store_internal(TABLE *table, ulonglong tmp, uchar *ptr)
{
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
int8store(ptr, tmp);
}
else
#endif
longlongstore(ptr, tmp);
return TYPE_OK;
}
/**
Read a DATETIME from record to a 8-byte integer
@param table Table
@param ptr Where to read from
@retval An integer in format YYYYMMDDhhmmss
*/
static inline longlong
datetime_get_internal(TABLE *table, uchar *ptr)
{
longlong tmp;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
tmp= sint8korr(ptr);
else
#endif
longlongget(&tmp, ptr);
return tmp;
}
bool Field_datetime::get_date_internal(MYSQL_TIME *ltime)
{
longlong tmp= datetime_get_internal(table, ptr);
ltime->time_type= MYSQL_TIMESTAMP_DATETIME;
ltime->neg= 0;
ltime->second_part= 0;
TIME_set_yymmdd(ltime, (uint) (tmp / 1000000LL));
TIME_set_hhmmss(ltime, (uint) (tmp % 1000000LL));
return false;
}
type_conversion_status
Field_datetime::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
ulonglong tmp= TIME_to_ulonglong_datetime(ltime);
return datetime_store_internal(table, tmp, ptr);
}
type_conversion_status Field_datetime::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
MYSQL_TIME ltime;
int warnings;
type_conversion_status error= TYPE_OK;
longlong tmp= convert_number_to_datetime(nr, unsigned_val,
<ime, &warnings);
if (tmp == -1LL)
error= TYPE_ERR_BAD_VALUE;
else
{
error= time_warning_to_type_conversion_status(warnings);
datetime_store_internal(table, tmp, ptr);
}
if (warnings)
set_warnings(ErrConvString(nr, unsigned_val), warnings);
return error;
}
type_conversion_status Field_datetime::store_packed(longlong nr)
{
MYSQL_TIME ltime;
TIME_from_longlong_datetime_packed(<ime, nr);
return Field_datetime::store_time(<ime, 0);
}
longlong Field_datetime::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
return datetime_get_internal(table, ptr);
}
/*
We don't reuse the parent method for performance purposes,
to avoid convertion from number to MYSQL_TIME.
Using my_datetime_number_to_str() instead of my_datetime_to_str().
*/
String *Field_datetime::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
val_buffer->alloc(field_length + 1);
val_buffer->set_charset(&my_charset_numeric);
val_buffer->length(MAX_DATETIME_WIDTH);
longlong tmp= datetime_get_internal(table, ptr);
val_buffer->length(my_datetime_number_to_str((char *) val_buffer->ptr(),
tmp));
return val_buffer;
}
bool Field_datetime::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
return get_internal_check_zero(ltime, fuzzydate) ||
check_fuzzy_date(ltime, fuzzydate);
}
int Field_datetime::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
longlong a,b;
#ifdef WORDS_BIGENDIAN
if (table && table->s->db_low_byte_first)
{
a=sint8korr(a_ptr);
b=sint8korr(b_ptr);
}
else
#endif
{
longlongget(&a, a_ptr);
longlongget(&b, b_ptr);
}
return ((ulonglong) a < (ulonglong) b) ? -1 :
((ulonglong) a > (ulonglong) b) ? 1 : 0;
}
void Field_datetime::make_sort_key(uchar *to, size_t length)
{
const size_t pack_length= PACK_LENGTH;
const size_t to_length= min(pack_length, length);
#ifdef WORDS_BIGENDIAN
if (!table || !table->s->db_low_byte_first)
copy_integer<true>(to, to_length, ptr, pack_length, true);
else
#endif
copy_integer<false>(to, to_length, ptr, pack_length, true);
}
void Field_datetime::sql_type(String &res) const
{
res.set_ascii(STRING_WITH_LEN("datetime"));
}
/****************************************************************************
** datetimef type
** In string context: YYYY-MM-DD HH:MM:DD.FFFFFF
** In number context: YYYYMMDDHHMMDD.FFFFFF
** Stored as a 8 byte value.
****************************************************************************/
my_time_flags_t Field_datetimef::date_flags(const THD *thd)
{
my_time_flags_t date_flags= TIME_FUZZY_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
date_flags|= TIME_NO_ZERO_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
date_flags|= TIME_NO_ZERO_IN_DATE;
if (thd->variables.sql_mode & MODE_INVALID_DATES)
date_flags|= TIME_INVALID_DATES;
return date_flags;
}
void Field_datetimef::store_timestamp_internal(const timeval *tm)
{
MYSQL_TIME mysql_time;
THD *thd= current_thd;
thd->variables.time_zone->gmt_sec_to_TIME(&mysql_time, *tm);
thd->time_zone_used= true;
int warnings= 0;
store_internal(&mysql_time, &warnings);
}
bool Field_datetimef::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
return get_internal_check_zero(ltime, fuzzydate) ||
check_fuzzy_date(ltime, fuzzydate);
}
void Field_datetimef::sql_type(String &res) const
{
if (dec == 0)
{
res.set_ascii(STRING_WITH_LEN("datetime"));
return;
}
const CHARSET_INFO *cs= res.charset();
res.length(cs->cset->snprintf(cs, (char *) res.ptr(), res.alloced_length(),
"datetime(%d)", dec));
}
bool Field_datetimef::get_date_internal(MYSQL_TIME *ltime)
{
TIME_from_longlong_datetime_packed(ltime, val_date_temporal());
return false;
}
type_conversion_status
Field_datetimef::store_internal(const MYSQL_TIME *ltime, int *warnings)
{
store_packed(TIME_to_longlong_datetime_packed(ltime));
return TYPE_OK;
}
type_conversion_status Field_datetimef::reset()
{
store_packed(0);
return TYPE_OK;
}
longlong Field_datetimef::val_date_temporal()
{
return my_datetime_packed_from_binary(ptr, dec);
}
type_conversion_status Field_datetimef::store_packed(longlong nr)
{
my_datetime_packed_to_binary(nr, ptr, dec);
return TYPE_OK;
}
/****************************************************************************
** string type
** A string may be varchar or binary
****************************************************************************/
/**
Report "not well formed" or "cannot convert" error
after storing a character string info a field.
As of version 5.0 both cases return the same error:
"Invalid string value: 'xxx' for column 't' at row 1"
Future versions will possibly introduce a new error message:
"Cannot convert character string: 'xxx' for column 't' at row 1"
@param original_string this is is the original string that was
supposed to be copied. Helps in keeping
track of whether a value has been
completely truncated.
@param well_formed_error_pos position of the first non-wellformed
character in the source string
@param cannot_convert_error_pos position of the first non-convertable
character in the source string
@param from_end_pos position where conversion stopped in
the source string
@param end end of the source string
@param count_spaces treat trailing spaces as important data
@param cs character set of the string
@return TYPE_OK, TYPE_NOTE_TRUNCATED, TYPE_WARN_TRUNCATED,
TYPE_WARN_INVALID_STRING
*/
type_conversion_status
Field_longstr::check_string_copy_error(const char *original_string,
const char *well_formed_error_pos,
const char *cannot_convert_error_pos,
const char *from_end_pos,
const char *end,
bool count_spaces,
const CHARSET_INFO *cs)
{
const char *pos;
char tmp[32];
THD *thd= table->in_use;
if (!(pos= well_formed_error_pos) &&
!(pos= cannot_convert_error_pos))
return report_if_important_data(from_end_pos, end, count_spaces);
convert_to_printable(tmp, sizeof(tmp), pos, (end - pos), cs, 6);
push_warning_printf(thd,
Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"string", tmp, field_name,
thd->get_stmt_da()->current_row_for_condition());
if (well_formed_error_pos != NULL)
return TYPE_WARN_INVALID_STRING;
return TYPE_WARN_TRUNCATED;
}
/*
Check if we lost any important data and send a truncation error/warning
SYNOPSIS
Field_longstr::report_if_important_data()
pstr - Truncated rest of string
end - End of truncated string
count_spaces - Treat traling spaces as important data
RETURN VALUES
TYPE_OK - None was truncated
!= TYPE_OK - Some bytes were truncated
NOTE
Check if we lost any important data (anything in a binary string,
or any non-space in others). If only trailing spaces was lost,
send a truncation note, otherwise send a truncation error.
Silently ignore traling spaces if the count_space parameter is FALSE.
*/
type_conversion_status
Field_longstr::report_if_important_data(const char *pstr, const char *end,
bool count_spaces)
{
if (pstr < end) // String is truncated
{
if (test_if_important_data(field_charset, pstr, end))
{
// Warning should only be written when count_cuted_fields is set
if (table->in_use->count_cuted_fields)
{
if (!table->in_use->lex->is_ignore() && table->in_use->is_strict_mode())
set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
else
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
}
return TYPE_WARN_TRUNCATED;
}
else if (count_spaces)
{ /* If we lost only spaces then produce a NOTE, not a WARNING */
if (table->in_use->count_cuted_fields)
{
set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
}
return TYPE_NOTE_TRUNCATED;
}
}
return TYPE_OK;
}
/* Copy a string and fill with space */
type_conversion_status
Field_string::store(const char *from, size_t length,const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
size_t copy_length;
const char *well_formed_error_pos;
const char *cannot_convert_error_pos;
const char *from_end_pos;
/* See the comment for Field_long::store(long long) */
DBUG_ASSERT(table->in_use == current_thd);
copy_length= field_well_formed_copy_nchars(field_charset,
(char*) ptr, field_length,
cs, from, length,
field_length / field_charset->mbmaxlen,
&well_formed_error_pos,
&cannot_convert_error_pos,
&from_end_pos);
/* Append spaces if the string was shorter than the field. */
if (copy_length < field_length)
field_charset->cset->fill(field_charset,(char*) ptr+copy_length,
field_length-copy_length,
field_charset->pad_char);
return check_string_copy_error(from, well_formed_error_pos,
cannot_convert_error_pos, from_end_pos,
from + length, false, cs);
}
/**
Store double value in Field_string or Field_varstring.
Pretty prints double number into field_length characters buffer.
@param nr number
*/
type_conversion_status Field_str::store(double nr)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
uint local_char_length= field_length / charset()->mbmaxlen;
size_t length= 0;
my_bool error= (local_char_length == 0);
// my_gcvt() requires width > 0, and we may have a CHAR(0) column.
if (!error)
length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, local_char_length, buff, &error);
if (error)
{
if (!table->in_use->lex->is_ignore() && table->in_use->is_strict_mode())
set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
else
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
}
return store(buff, length, &my_charset_numeric);
}
/**
Check whether generated columns' expressions are the same.
@param field An existing field to compare against
@return true means the same, otherwise not.
*/
bool Field::gcol_expr_is_equal(const Field *field) const
{
DBUG_ASSERT(is_gcol() && field->is_gcol());
return gcol_info->expr_item->eq(field->gcol_info->expr_item, true);
}
/**
Check whether generated columns' expressions are the same.
@param field A new field to compare against
@return true means the same, otherwise not.
*/
bool Field::gcol_expr_is_equal(const Create_field *field) const
{
DBUG_ASSERT(is_gcol() && field->is_gcol());
return ::is_equal(&gcol_info->expr_str, &field->gcol_info->expr_str);
}
uint Field::is_equal(Create_field *new_field)
{
return (new_field->sql_type == real_type());
}
uint Field_str::is_equal(Create_field *new_field)
{
return ((new_field->sql_type == real_type()) &&
new_field->charset == field_charset &&
new_field->length == max_display_length());
}
type_conversion_status Field_string::store(longlong nr, bool unsigned_val)
{
char buff[64];
size_t l;
const CHARSET_INFO *cs=charset();
l= (cs->cset->longlong10_to_str)(cs,buff,sizeof(buff),
unsigned_val ? 10 : -10, nr);
return Field_string::store(buff, l, cs);
}
type_conversion_status Field_longstr::store_decimal(const my_decimal *d)
{
char buff[DECIMAL_MAX_STR_LENGTH+1];
String str(buff, sizeof(buff), &my_charset_numeric);
my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
return store(str.ptr(), str.length(), str.charset());
}
uint32 Field_longstr::max_data_length() const
{
return field_length + (field_length > 255 ? 2 : 1);
}
double Field_string::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int error;
char *end;
const CHARSET_INFO *cs= charset();
double result;
result= my_strntod(cs,(char*) ptr,field_length,&end,&error);
if (!table->in_use->no_errors &&
(error || (field_length != (uint32)(end - (char*) ptr) &&
!check_if_only_end_space(cs, end,
(char*) ptr + field_length))))
{
ErrConvString err((char*) ptr, field_length, cs);
push_warning_printf(current_thd, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
err.ptr());
}
return result;
}
longlong Field_string::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int error;
char *end;
const CHARSET_INFO *cs= charset();
longlong result;
result= my_strntoll(cs, (char*) ptr,field_length,10,&end,&error);
if (!table->in_use->no_errors &&
(error || (field_length != (uint32)(end - (char*) ptr) &&
!check_if_only_end_space(cs, end,
(char*) ptr + field_length))))
{
ErrConvString err((char*) ptr, field_length, cs);
push_warning_printf(current_thd, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE),
"INTEGER", err.ptr());
}
return result;
}
String *Field_string::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
/* See the comment for Field_long::store(long long) */
DBUG_ASSERT(table->in_use == current_thd);
size_t length;
if (table->in_use->variables.sql_mode &
MODE_PAD_CHAR_TO_FULL_LENGTH)
length= my_charpos(field_charset, ptr, ptr + field_length,
field_length / field_charset->mbmaxlen);
else
length= field_charset->cset->lengthsp(field_charset, (const char*) ptr,
field_length);
val_ptr->set((const char*) ptr, length, field_charset);
return val_ptr;
}
my_decimal *Field_string::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int err= str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr, field_length,
charset(), decimal_value);
if (!table->in_use->no_errors && err)
{
ErrConvString errmsg((char*) ptr, field_length, charset());
push_warning_printf(current_thd, Sql_condition::SL_WARNING,
ER_TRUNCATED_WRONG_VALUE,
ER(ER_TRUNCATED_WRONG_VALUE),
"DECIMAL", errmsg.ptr());
}
return decimal_value;
}
struct Check_field_param {
Field *field;
};
#ifdef HAVE_REPLICATION
static bool
check_field_for_37426(const void *param_arg)
{
Check_field_param *param= (Check_field_param*) param_arg;
DBUG_ASSERT(param->field->real_type() == MYSQL_TYPE_STRING);
DBUG_PRINT("debug", ("Field %s - type: %d, size: %d",
param->field->field_name,
param->field->real_type(),
param->field->row_pack_length()));
return param->field->row_pack_length() > 255;
}
#endif
bool
Field_string::compatible_field_size(uint field_metadata,
Relay_log_info *rli_arg,
uint16 mflags MY_ATTRIBUTE((unused)),
int *order_var)
{
#ifdef HAVE_REPLICATION
const Check_field_param check_param = { this };
if (!is_mts_worker(rli_arg->info_thd) && rpl_master_has_bug(rli_arg, 37426, TRUE,
check_field_for_37426, &check_param))
return FALSE; // Not compatible field sizes
#endif
return Field::compatible_field_size(field_metadata, rli_arg, mflags, order_var);
}
int Field_string::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
size_t a_len, b_len;
if (field_charset->mbmaxlen != 1)
{
uint char_len= field_length/field_charset->mbmaxlen;
a_len= my_charpos(field_charset, a_ptr, a_ptr + field_length, char_len);
b_len= my_charpos(field_charset, b_ptr, b_ptr + field_length, char_len);
}
else
a_len= b_len= field_length;
/*
We have to remove end space to be able to compare multi-byte-characters
like in latin_de 'ae' and 0xe4
*/
return field_charset->coll->strnncollsp(field_charset,
a_ptr, a_len,
b_ptr, b_len,
0);
}
void Field_string::make_sort_key(uchar *to, size_t length)
{
size_t tmp MY_ATTRIBUTE((unused))=
field_charset->coll->strnxfrm(field_charset,
to, length, char_length(),
ptr, field_length,
MY_STRXFRM_PAD_WITH_SPACE |
MY_STRXFRM_PAD_TO_MAXLEN);
DBUG_ASSERT(tmp == length);
}
void Field_string::sql_type(String &res) const
{
THD *thd= table->in_use;
const CHARSET_INFO *cs=res.charset();
size_t length;
length= cs->cset->snprintf(cs,(char*) res.ptr(),
res.alloced_length(), "%s(%d)",
((type() == MYSQL_TYPE_VAR_STRING &&
!thd->variables.new_mode) ?
(has_charset() ? "varchar" : "varbinary") :
(has_charset() ? "char" : "binary")),
(int) field_length / charset()->mbmaxlen);
res.length(length);
if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
has_charset() && (charset()->state & MY_CS_BINSORT))
res.append(STRING_WITH_LEN(" binary"));
}
uchar *Field_string::pack(uchar *to, const uchar *from,
uint max_length,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
uint length= min(field_length,max_length);
uint local_char_length= max_length/field_charset->mbmaxlen;
DBUG_PRINT("debug", ("Packing field '%s' - length: %u ", field_name, length));
if (length > local_char_length)
local_char_length= my_charpos(field_charset, from, from+length,
local_char_length);
set_if_smaller(length, local_char_length);
/*
TODO: change charset interface to add a new function that does
the following or add a flag to lengthsp to do it itself
(this is for not packing padding adding bytes in BINARY
fields).
*/
if (field_charset->mbmaxlen == 1)
{
while (length && from[length-1] == field_charset->pad_char)
length --;
}
else
length= field_charset->cset->lengthsp(field_charset, (const char*) from, length);
// Length always stored little-endian
*to++= (uchar) length;
if (field_length > 255)
*to++= (uchar) (length >> 8);
// Store the actual bytes of the string
memcpy(to, from, length);
return to+length;
}
/**
Unpack a string field from row data.
This method is used to unpack a string field from a master whose size
of the field is less than that of the slave. Note that there can be a
variety of field types represented with this class. Certain types like
ENUM or SET are processed differently. Hence, the upper byte of the
@c param_data argument contains the result of field->real_type() from
the master.
@note For information about how the length is packed, see @c
Field_string::do_save_field_metadata
@param to Destination of the data
@param from Source of the data
@param param_data Real type (upper) and length (lower) values
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_string::unpack(uchar *to,
const uchar *from,
uint param_data,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
uint from_length, length;
/*
Compute the declared length of the field on the master. This is
used to decide if one or two bytes should be read as length.
*/
if (param_data)
from_length= (((param_data >> 4) & 0x300) ^ 0x300) + (param_data & 0x00ff);
else
from_length= field_length;
DBUG_PRINT("debug",
("param_data: 0x%x, field_length: %u, from_length: %u",
param_data, field_length, from_length));
/*
Compute the actual length of the data by reading one or two bits
(depending on the declared field length on the master).
*/
if (from_length > 255)
{
length= uint2korr(from);
from+= 2;
}
else
length= (uint) *from++;
memcpy(to, from, length);
// Pad the string with the pad character of the fields charset
field_charset->cset->fill(field_charset, (char*) to + length, field_length - length, field_charset->pad_char);
return from+length;
}
/**
Save the field metadata for string fields.
Saves the real type in the first byte and the field length in the
second byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@note In order to be able to handle lengths exceeding 255 and be
backwards-compatible with pre-5.1.26 servers, an extra two bits of
the length has been added to the metadata in such a way that if
they are set, a new unrecognized type is generated. This will
cause pre-5.1-26 servers to stop due to a field type mismatch,
while new servers will be able to extract the extra bits. If the
length is <256, there will be no difference and both a new and an
old server will be able to handle it.
@note The extra two bits are added to bits 13 and 14 of the
parameter data (with 1 being the least siginficant bit and 16 the
most significant bit of the word) by xoring the extra length bits
with the real type. Since all allowable types have 0xF as most
significant bits of the metadata word, lengths <256 will not affect
the real type at all, while all other values will result in a
non-existant type in the range 17-244.
@see Field_string::unpack
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_string::do_save_field_metadata(uchar *metadata_ptr)
{
DBUG_ASSERT(field_length < 1024);
DBUG_ASSERT((real_type() & 0xF0) == 0xF0);
DBUG_PRINT("debug", ("field_length: %u, real_type: %u",
field_length, real_type()));
*metadata_ptr= (real_type() ^ ((field_length & 0x300) >> 4));
*(metadata_ptr + 1)= field_length & 0xFF;
return 2;
}
uint Field_string::packed_col_length(const uchar *data_ptr, uint length)
{
if (length > 255)
return uint2korr(data_ptr)+2;
return (uint) *data_ptr + 1;
}
uint Field_string::max_packed_col_length()
{
const uint max_length= pack_length();
return (max_length > 255 ? 2 : 1) + max_length;
}
size_t Field_string::get_key_image(uchar *buff, size_t length, imagetype type_arg)
{
size_t bytes = my_charpos(field_charset, (char*) ptr,
(char*) ptr + field_length,
length / field_charset->mbmaxlen);
memcpy(buff, ptr, bytes);
if (bytes < length)
field_charset->cset->fill(field_charset, (char*) buff + bytes,
length - bytes, field_charset->pad_char);
return bytes;
}
Field *Field_string::new_field(MEM_ROOT *root, TABLE *new_table,
bool keep_type)
{
Field *field;
if (type() != MYSQL_TYPE_VAR_STRING || keep_type)
field= Field::new_field(root, new_table, keep_type);
else if ((field= new Field_varstring(field_length, maybe_null(), field_name,
new_table->s, charset())))
{
/*
Old VARCHAR field which should be modified to a VARCHAR on copy
This is done to ensure that ALTER TABLE will convert old VARCHAR fields
to now VARCHAR fields.
*/
field->init(new_table);
/*
Normally orig_table is different from table only if field was created
via ::new_field. Here we alter the type of field, so ::new_field is
not applicable. But we still need to preserve the original field
metadata for the client-server protocol.
*/
field->orig_table= orig_table;
}
return field;
}
/****************************************************************************
VARCHAR type
Data in field->ptr is stored as:
1 or 2 bytes length-prefix-header (from Field_varstring::length_bytes)
data
NOTE:
When VARCHAR is stored in a key (for handler::index_read() etc) it's always
stored with a 2 byte prefix. (Just like blob keys).
Normally length_bytes is calculated as (field_length < 256 : 1 ? 2)
The exception is if there is a prefix key field that is part of a long
VARCHAR, in which case field_length for this may be 1 but the length_bytes
is 2.
****************************************************************************/
const uint Field_varstring::MAX_SIZE= UINT_MAX16;
/**
Save the field metadata for varstring fields.
Saves the field length in the first byte. Note: may consume
2 bytes. Caller must ensure second byte is contiguous with
first byte (e.g. array index 0,1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_varstring::do_save_field_metadata(uchar *metadata_ptr)
{
DBUG_ASSERT(field_length <= 65535);
int2store((char*)metadata_ptr, field_length);
return 2;
}
type_conversion_status Field_varstring::store(const char *from, size_t length,
const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
size_t copy_length;
const char *well_formed_error_pos;
const char *cannot_convert_error_pos;
const char *from_end_pos;
copy_length= field_well_formed_copy_nchars(field_charset,
(char*) ptr + length_bytes,
field_length,
cs, from, length,
field_length / field_charset->mbmaxlen,
&well_formed_error_pos,
&cannot_convert_error_pos,
&from_end_pos);
if (length_bytes == 1)
*ptr= (uchar) copy_length;
else
int2store(ptr, static_cast<uint16>(copy_length));
return check_string_copy_error(from, well_formed_error_pos,
cannot_convert_error_pos, from_end_pos,
from + length, true, cs);
}
type_conversion_status Field_varstring::store(longlong nr, bool unsigned_val)
{
char buff[64];
uint length;
length= (uint) (field_charset->cset->longlong10_to_str)(field_charset,
buff,
sizeof(buff),
(unsigned_val ? 10:
-10),
nr);
return Field_varstring::store(buff, length, field_charset);
}
double Field_varstring::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int error;
char *end;
double result;
const CHARSET_INFO* cs= charset();
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
result= my_strntod(cs, (char*)ptr+length_bytes, length, &end, &error);
if (!table->in_use->no_errors &&
(error || (length != (uint)(end - (char*)ptr+length_bytes) &&
!check_if_only_end_space(cs, end, (char*)ptr+length_bytes+length))))
{
push_numerical_conversion_warning(current_thd, (char*)ptr+length_bytes,
length, cs,"DOUBLE",
ER_TRUNCATED_WRONG_VALUE);
}
return result;
}
longlong Field_varstring::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int error;
char *end;
const CHARSET_INFO *cs= charset();
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
longlong result= my_strntoll(cs, (char*) ptr+length_bytes, length, 10,
&end, &error);
if (!table->in_use->no_errors &&
(error || (length != (uint)(end - (char*)ptr+length_bytes) &&
!check_if_only_end_space(cs, end, (char*)ptr+length_bytes+length))))
{
push_numerical_conversion_warning(current_thd, (char*)ptr+length_bytes,
length, cs, "INTEGER",
ER_TRUNCATED_WRONG_VALUE);
}
return result;
}
String *Field_varstring::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
val_ptr->set((const char*) ptr+length_bytes, length, field_charset);
return val_ptr;
}
my_decimal *Field_varstring::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
const CHARSET_INFO *cs= charset();
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
int error= str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr+length_bytes, length,
cs, decimal_value);
if (!table->in_use->no_errors && error)
{
push_numerical_conversion_warning(current_thd, (char*)ptr+length_bytes,
length, cs, "DECIMAL",
ER_TRUNCATED_WRONG_VALUE);
}
return decimal_value;
}
int Field_varstring::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
uint max_len)
{
uint a_length, b_length;
int diff;
if (length_bytes == 1)
{
a_length= (uint) *a_ptr;
b_length= (uint) *b_ptr;
}
else
{
a_length= uint2korr(a_ptr);
b_length= uint2korr(b_ptr);
}
set_if_smaller(a_length, max_len);
set_if_smaller(b_length, max_len);
diff= field_charset->coll->strnncollsp(field_charset,
a_ptr+
length_bytes,
a_length,
b_ptr+
length_bytes,
b_length,0);
return diff;
}
/**
@note
varstring and blob keys are ALWAYS stored with a 2 byte length prefix
*/
int Field_varstring::key_cmp(const uchar *key_ptr, uint max_key_length)
{
uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
uint local_char_length= max_key_length / field_charset->mbmaxlen;
local_char_length= my_charpos(field_charset, ptr + length_bytes,
ptr + length_bytes + length, local_char_length);
set_if_smaller(length, local_char_length);
return field_charset->coll->strnncollsp(field_charset,
ptr + length_bytes,
length,
key_ptr+
HA_KEY_BLOB_LENGTH,
uint2korr(key_ptr), 0);
}
/**
Compare to key segments (always 2 byte length prefix).
@note
This is used only to compare key segments created for index_read().
(keys are created and compared in key.cc)
*/
int Field_varstring::key_cmp(const uchar *a,const uchar *b)
{
return field_charset->coll->strnncollsp(field_charset,
a + HA_KEY_BLOB_LENGTH,
uint2korr(a),
b + HA_KEY_BLOB_LENGTH,
uint2korr(b),
0);
}
void Field_varstring::make_sort_key(uchar *to, size_t length)
{
size_t tot_length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
if (field_charset == &my_charset_bin)
{
/* Store length last in high-byte order to sort longer strings first */
if (length_bytes == 1)
to[length-1]= tot_length;
else
mi_int2store(to+length-2, tot_length);
length-= length_bytes;
}
tot_length= field_charset->coll->strnxfrm(field_charset,
to, length, char_length(),
ptr + length_bytes, tot_length,
MY_STRXFRM_PAD_WITH_SPACE |
MY_STRXFRM_PAD_TO_MAXLEN);
DBUG_ASSERT(tot_length == length);
}
enum ha_base_keytype Field_varstring::key_type() const
{
enum ha_base_keytype res;
if (binary())
res= length_bytes == 1 ? HA_KEYTYPE_VARBINARY1 : HA_KEYTYPE_VARBINARY2;
else
res= length_bytes == 1 ? HA_KEYTYPE_VARTEXT1 : HA_KEYTYPE_VARTEXT2;
return res;
}
void Field_varstring::sql_type(String &res) const
{
THD *thd= table->in_use;
const CHARSET_INFO *cs=res.charset();
size_t length;
length= cs->cset->snprintf(cs,(char*) res.ptr(),
res.alloced_length(), "%s(%d)",
(has_charset() ? "varchar" : "varbinary"),
(int) field_length / charset()->mbmaxlen);
res.length(length);
if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
has_charset() && (charset()->state & MY_CS_BINSORT))
res.append(STRING_WITH_LEN(" binary"));
}
uint32 Field_varstring::data_length(uint row_offset)
{
return length_bytes == 1 ?
(uint32) *(ptr + row_offset) : uint2korr(ptr + row_offset);
}
/*
Functions to create a packed row.
Here the number of length bytes are depending on the given max_length
*/
uchar *Field_varstring::pack(uchar *to, const uchar *from,
uint max_length,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
uint length= length_bytes == 1 ? (uint) *from : uint2korr(from);
set_if_smaller(max_length, field_length);
if (length > max_length)
length=max_length;
/* Length always stored little-endian */
*to++= length & 0xFF;
if (max_length > 255)
*to++= (length >> 8) & 0xFF;
/* Store bytes of string */
if (length > 0)
memcpy(to, from+length_bytes, length);
return to+length;
}
/**
Unpack a varstring field from row data.
This method is used to unpack a varstring field from a master
whose size of the field is less than that of the slave.
@note
The string length is always packed little-endian.
@param to Destination of the data
@param from Source of the data
@param param_data Length bytes from the master's field data
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_varstring::unpack(uchar *to, const uchar *from,
uint param_data,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
uint length;
uint l_bytes= (param_data && (param_data < field_length)) ?
(param_data <= 255) ? 1 : 2 : length_bytes;
if (l_bytes == 1)
{
to[0]= *from++;
length= to[0];
if (length_bytes == 2)
to[1]= 0;
}
else /* l_bytes == 2 */
{
length= uint2korr(from);
to[0]= *from++;
to[1]= *from++;
}
if (length)
memcpy(to+ length_bytes, from, length);
return from+length;
}
uint Field_varstring::packed_col_length(const uchar *data_ptr, uint length)
{
if (length > 255)
return uint2korr(data_ptr)+2;
return (uint) *data_ptr + 1;
}
size_t Field_varstring::get_key_image(uchar *buff, size_t length, imagetype type)
{
/*
If NULL, data bytes may have been left random by the storage engine, so
don't try to read them.
*/
uint f_length= is_null() ? 0 :
(length_bytes == 1 ? (uint) *ptr : uint2korr(ptr));
uint local_char_length= length / field_charset->mbmaxlen;
uchar *pos= ptr+length_bytes;
local_char_length= my_charpos(field_charset, pos, pos + f_length,
local_char_length);
set_if_smaller(f_length, local_char_length);
/* Key is always stored with 2 bytes */
int2store(buff,f_length);
memcpy(buff+HA_KEY_BLOB_LENGTH, pos, f_length);
if (f_length < length)
{
/*
Must clear this as we do a memcmp in opt_range.cc to detect
identical keys
*/
memset(buff+HA_KEY_BLOB_LENGTH+f_length, 0, (length-f_length));
}
return HA_KEY_BLOB_LENGTH+f_length;
}
void Field_varstring::set_key_image(const uchar *buff, size_t length)
{
length= uint2korr(buff); // Real length is here
(void) Field_varstring::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
field_charset);
}
int Field_varstring::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
uint32 max_length)
{
uint32 a_length,b_length;
if (length_bytes == 1)
{
a_length= (uint) *a_ptr;
b_length= (uint) *b_ptr;
}
else
{
a_length= uint2korr(a_ptr);
b_length= uint2korr(b_ptr);
}
set_if_smaller(a_length, max_length);
set_if_smaller(b_length, max_length);
if (a_length != b_length)
return 1;
return memcmp(a_ptr+length_bytes, b_ptr+length_bytes, a_length);
}
Field *Field_varstring::new_field(MEM_ROOT *root, TABLE *new_table,
bool keep_type)
{
Field_varstring *res= (Field_varstring*) Field::new_field(root, new_table,
keep_type);
if (res)
res->length_bytes= length_bytes;
return res;
}
Field *Field_varstring::new_key_field(MEM_ROOT *root,
TABLE *new_table,
uchar *new_ptr, uchar *new_null_ptr,
uint new_null_bit)
{
Field_varstring *res;
if ((res= (Field_varstring*) Field::new_key_field(root,
new_table,
new_ptr,
new_null_ptr,
new_null_bit)))
{
/* Keys length prefixes are always packed with 2 bytes */
res->length_bytes= 2;
}
return res;
}
uint Field_varstring::is_equal(Create_field *new_field)
{
if (new_field->sql_type == real_type() &&
new_field->charset == field_charset)
{
if (new_field->length == max_display_length())
return IS_EQUAL_YES;
DBUG_ASSERT(0 == (new_field->length % field_charset->mbmaxlen));
DBUG_ASSERT(0 == (max_display_length() % field_charset->mbmaxlen));
if (new_field->length > max_display_length() &&
((new_field->length <= 255 && max_display_length() <= 255) ||
(new_field->length > 255 && max_display_length() > 255)))
return IS_EQUAL_PACK_LENGTH; // VARCHAR, longer variable length
}
return IS_EQUAL_NO;
}
void Field_varstring::hash(ulong *nr, ulong *nr2)
{
if (is_null())
{
*nr^= (*nr << 1) | 1;
}
else
{
uint len= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
const CHARSET_INFO *cs= charset();
cs->coll->hash_sort(cs, ptr + length_bytes, len, nr, nr2);
}
}
/****************************************************************************
** blob type
** A blob is saved as a length and a pointer. The length is stored in the
** packlength slot and may be from 1-4.
****************************************************************************/
Field_blob::Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg, const char *field_name_arg,
TABLE_SHARE *share, uint blob_pack_length,
const CHARSET_INFO *cs)
:Field_longstr(ptr_arg, BLOB_PACK_LENGTH_TO_MAX_LENGH(blob_pack_length),
null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg,
cs),
packlength(blob_pack_length), m_keep_old_value(false)
{
DBUG_ASSERT(blob_pack_length <= 4); // Only pack lengths 1-4 supported currently
flags|= BLOB_FLAG;
share->blob_fields++;
/* TODO: why do not fill table->s->blob_field array here? */
}
void Field_blob::store_length(uchar *i_ptr,
uint i_packlength,
uint32 i_number,
bool low_byte_first)
{
switch (i_packlength) {
case 1:
i_ptr[0]= (uchar) i_number;
break;
case 2:
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
{
int2store(i_ptr,(unsigned short) i_number);
}
else
#endif
shortstore(i_ptr,(unsigned short) i_number);
break;
case 3:
int3store(i_ptr,i_number);
break;
case 4:
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
{
int4store(i_ptr,i_number);
}
else
#endif
longstore(i_ptr,i_number);
}
}
uint32 Field_blob::get_length(const uchar *pos, uint packlength_arg, bool low_byte_first)
{
switch (packlength_arg) {
case 1:
return (uint32) pos[0];
case 2:
{
uint16 tmp;
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
tmp=sint2korr(pos);
else
#endif
ushortget(&tmp, pos);
return (uint32) tmp;
}
case 3:
return uint3korr(pos);
case 4:
{
uint32 tmp;
#ifdef WORDS_BIGENDIAN
if (low_byte_first)
tmp=uint4korr(pos);
else
#endif
ulongget(&tmp, pos);
return tmp;
}
}
/* When expanding this, see also MAX_FIELD_BLOBLENGTH. */
return 0; // Impossible
}
/**
Put a blob length field into a record buffer.
Depending on the maximum length of a blob, its length field is
put into 1 to 4 bytes. This is a property of the blob object,
described by 'packlength'.
@param pos Pointer into the record buffer.
@param length The length value to put.
*/
void Field_blob::put_length(uchar *pos, uint32 length)
{
switch (packlength) {
case 1:
*pos= (char) length;
break;
case 2:
int2store(pos, length);
break;
case 3:
int3store(pos, length);
break;
case 4:
int4store(pos, length);
break;
}
}
/**
Store a blob value to memory storage.
@param from the string value to store.
@param length length of the string value.
@param cs character set of the string value.
@param max_length Cut at this length safely (multibyte aware).
@param[out] blob_storage Memory storage to put value to.
*/
type_conversion_status
Field_blob::store_to_mem(const char *from, size_t length,
const CHARSET_INFO *cs,
size_t max_length,
Blob_mem_storage *blob_storage)
{
/*
We don't need to support escaping or character set conversions here,
because store_to_mem() is currently called only when we process
queries having GROUP_CONCAT with ORDER BY or DISTINCT,
hence some assersions:
*/
DBUG_ASSERT(field_charset == cs);
DBUG_ASSERT(length <= max_data_length());
if (length > max_length)
{
int well_formed_error;
length= cs->cset->well_formed_len(cs, from, from + max_length,
length, &well_formed_error);
table->blob_storage->set_truncated_value(true);
}
char *tmp;
if (!(tmp= table->blob_storage->store(from, length)))
{
memset(ptr, 0, Field_blob::pack_length());
return TYPE_ERR_OOM;
}
store_ptr_and_length(tmp, length);
return TYPE_OK;
}
type_conversion_status
Field_blob::store_internal(const char *from, size_t length,
const CHARSET_INFO *cs)
{
size_t new_length;
char buff[STRING_BUFFER_USUAL_SIZE], *tmp;
String tmpstr(buff,sizeof(buff), &my_charset_bin);
/*
If the 'from' address is in the range of the temporary 'value'-
object we need to copy the content to a different location or it will be
invalidated when the 'value'-object is reallocated to make room for
the new character set.
*/
if (from >= value.ptr() && from <= value.ptr()+value.length())
{
/*
If content of the 'from'-address is cached in the 'value'-object
it is possible that the content needs a character conversion.
*/
if (!String::needs_conversion_on_storage(length, cs, field_charset))
{
store_ptr_and_length(from, length);
return TYPE_OK;
}
if (tmpstr.copy(from, length, cs))
goto oom_error;
from= tmpstr.ptr();
}
new_length= min<size_t>(max_data_length(), field_charset->mbmaxlen * length);
if (value.alloc(new_length))
goto oom_error;
tmp= const_cast<char*>(value.ptr());
{
const char *well_formed_error_pos;
const char *cannot_convert_error_pos;
const char *from_end_pos;
/*
"length" is OK as "nchars" argument to well_formed_copy_nchars as this
is never used to limit the length of the data. The cut of long data
is done with the new_length value.
*/
size_t copy_length= field_well_formed_copy_nchars(field_charset,
tmp, new_length,
cs, from, length,
length,
&well_formed_error_pos,
&cannot_convert_error_pos,
&from_end_pos);
store_ptr_and_length(tmp, copy_length);
return check_string_copy_error(from, well_formed_error_pos,
cannot_convert_error_pos, from_end_pos,
from + length, true, cs);
}
oom_error:
/* Fatal OOM error */
memset(ptr, 0, Field_blob::pack_length());
return TYPE_ERR_OOM;
}
type_conversion_status
Field_blob::store(const char *from, size_t length, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (table->blob_storage) // GROUP_CONCAT with ORDER BY | DISTINCT
return store_to_mem(from, length, cs,
table->in_use->variables.group_concat_max_len,
table->blob_storage);
return store_internal(from, length, cs);
}
type_conversion_status Field_blob::store(double nr)
{
const CHARSET_INFO *cs=charset();
value.set_real(nr, NOT_FIXED_DEC, cs);
return Field_blob::store(value.ptr(), value.length(), cs);
}
type_conversion_status Field_blob::store(longlong nr, bool unsigned_val)
{
const CHARSET_INFO *cs=charset();
value.set_int(nr, unsigned_val, cs);
return Field_blob::store(value.ptr(), value.length(), cs);
}
double Field_blob::val_real(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *end_not_used, *blob;
uint32 length;
const CHARSET_INFO *cs;
memcpy(&blob, ptr+packlength, sizeof(char*));
if (!blob)
return 0.0;
length= get_length(ptr);
cs= charset();
return my_strntod(cs, blob, length, &end_not_used, ¬_used);
}
longlong Field_blob::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int not_used;
char *blob;
memcpy(&blob, ptr+packlength, sizeof(char*));
if (!blob)
return 0;
uint32 length=get_length(ptr);
return my_strntoll(charset(),blob,length,10,NULL,¬_used);
}
String *Field_blob::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
String *val_ptr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
char *blob;
memcpy(&blob, ptr+packlength, sizeof(char*));
if (!blob)
val_ptr->set("",0,charset()); // A bit safer than ->length(0)
else
val_ptr->set((const char*) blob,get_length(ptr),charset());
return val_ptr;
}
my_decimal *Field_blob::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
const char *blob;
size_t length;
memcpy(&blob, ptr+packlength, sizeof(const uchar*));
if (!blob)
{
blob= "";
length= 0;
}
else
length= get_length(ptr);
str2my_decimal(E_DEC_FATAL_ERROR, blob, length, charset(),
decimal_value);
return decimal_value;
}
int Field_blob::cmp(const uchar *a,uint32 a_length, const uchar *b,
uint32 b_length)
{
return field_charset->coll->strnncollsp(field_charset,
a, a_length, b, b_length,
0);
}
int Field_blob::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
uint max_length)
{
uchar *blob1,*blob2;
memcpy(&blob1, a_ptr+packlength, sizeof(char*));
memcpy(&blob2, b_ptr+packlength, sizeof(char*));
uint a_len= get_length(a_ptr), b_len= get_length(b_ptr);
set_if_smaller(a_len, max_length);
set_if_smaller(b_len, max_length);
return Field_blob::cmp(blob1,a_len,blob2,b_len);
}
int Field_blob::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
uint32 max_length)
{
char *a,*b;
uint diff;
uint32 a_length,b_length;
memcpy(&a, a_ptr+packlength, sizeof(char*));
memcpy(&b, b_ptr+packlength, sizeof(char*));
a_length=get_length(a_ptr);
if (a_length > max_length)
a_length=max_length;
b_length=get_length(b_ptr);
if (b_length > max_length)
b_length=max_length;
diff=memcmp(a,b,min(a_length,b_length));
return diff ? diff : (int) (a_length - b_length);
}
/* The following is used only when comparing a key */
size_t Field_blob::get_key_image(uchar *buff, size_t length, imagetype type_arg)
{
uint32 blob_length= get_length(ptr);
uchar *blob;
if (type_arg == itMBR)
{
MBR mbr;
Geometry_buffer buffer;
Geometry *gobj;
const uint image_length= SIZEOF_STORED_DOUBLE*4;
if (blob_length < SRID_SIZE)
{
memset(buff, 0, image_length);
return image_length;
}
get_ptr(&blob);
gobj= Geometry::construct(&buffer, (char*) blob, blob_length);
if (!gobj || gobj->get_mbr(&mbr))
memset(buff, 0, image_length);
else
{
float8store(buff, mbr.xmin);
float8store(buff+8, mbr.xmax);
float8store(buff+16, mbr.ymin);
float8store(buff+24, mbr.ymax);
}
return image_length;
}
get_ptr(&blob);
uint local_char_length= length / field_charset->mbmaxlen;
local_char_length= my_charpos(field_charset, blob, blob + blob_length,
local_char_length);
set_if_smaller(blob_length, local_char_length);
if ((uint32) length > blob_length)
{
/*
Must clear this as we do a memcmp in opt_range.cc to detect
identical keys
*/
memset(buff+HA_KEY_BLOB_LENGTH+blob_length, 0, (length-blob_length));
length=(uint) blob_length;
}
int2store(buff, static_cast<uint16>(length));
memcpy(buff+HA_KEY_BLOB_LENGTH, blob, length);
return HA_KEY_BLOB_LENGTH+length;
}
void Field_blob::set_key_image(const uchar *buff, size_t length)
{
length= uint2korr(buff);
(void) Field_blob::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
field_charset);
}
int Field_blob::key_cmp(const uchar *key_ptr, uint max_key_length)
{
uchar *blob1;
uint blob_length=get_length(ptr);
memcpy(&blob1, ptr+packlength, sizeof(char*));
const CHARSET_INFO *cs= charset();
uint local_char_length= max_key_length / cs->mbmaxlen;
local_char_length= my_charpos(cs, blob1, blob1+blob_length,
local_char_length);
set_if_smaller(blob_length, local_char_length);
return Field_blob::cmp(blob1, blob_length,
key_ptr+HA_KEY_BLOB_LENGTH,
uint2korr(key_ptr));
}
int Field_blob::key_cmp(const uchar *a,const uchar *b)
{
return Field_blob::cmp(a+HA_KEY_BLOB_LENGTH, uint2korr(a),
b+HA_KEY_BLOB_LENGTH, uint2korr(b));
}
/**
Save the field metadata for blob fields.
Saves the pack length in the first byte of the field metadata array
at index of *metadata_ptr.
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_blob::do_save_field_metadata(uchar *metadata_ptr)
{
DBUG_ENTER("Field_blob::do_save_field_metadata");
*metadata_ptr= pack_length_no_ptr();
DBUG_PRINT("debug", ("metadata: %u (pack_length_no_ptr)", *metadata_ptr));
DBUG_RETURN(1);
}
uint32 Field_blob::sort_length() const
{
return (uint32) (current_thd->variables.max_sort_length +
(field_charset == &my_charset_bin ? 0 : packlength));
}
void Field_blob::make_sort_key(uchar *to, size_t length)
{
uchar *blob;
size_t blob_length=get_length();
if (!blob_length)
memset(to, 0, length);
else
{
if (field_charset == &my_charset_bin)
{
uchar *pos;
/*
Store length of blob last in blob to shorter blobs before longer blobs
*/
length-= packlength;
pos= to+length;
switch (packlength) {
case 1:
*pos= (char) blob_length;
break;
case 2:
mi_int2store(pos, blob_length);
break;
case 3:
mi_int3store(pos, blob_length);
break;
case 4:
mi_int4store(pos, blob_length);
break;
}
}
memcpy(&blob, ptr+packlength, sizeof(char*));
blob_length= field_charset->coll->strnxfrm(field_charset,
to, length, length,
blob, blob_length,
MY_STRXFRM_PAD_WITH_SPACE |
MY_STRXFRM_PAD_TO_MAXLEN);
DBUG_ASSERT(blob_length == length);
}
}
void Field_blob::sql_type(String &res) const
{
const char *str;
uint length;
switch (packlength) {
default: str="tiny"; length=4; break;
case 2: str=""; length=0; break;
case 3: str="medium"; length= 6; break;
case 4: str="long"; length=4; break;
}
res.set_ascii(str,length);
if (charset() == &my_charset_bin)
res.append(STRING_WITH_LEN("blob"));
else
{
res.append(STRING_WITH_LEN("text"));
}
}
uchar *Field_blob::pack(uchar *to, const uchar *from,
uint max_length, bool low_byte_first)
{
uchar *save= ptr;
ptr= (uchar*) from;
uint32 length=get_length(); // Length of from string
/*
Store max length, which will occupy packlength bytes. If the max
length given is smaller than the actual length of the blob, we
just store the initial bytes of the blob.
*/
store_length(to, packlength, min(length, max_length), low_byte_first);
/*
Store the actual blob data, which will occupy 'length' bytes.
*/
if (length > 0)
{
get_ptr((uchar**) &from);
memcpy(to+packlength, from,length);
}
ptr=save; // Restore org row pointer
return to+packlength+length;
}
/**
Unpack a blob field from row data.
This method is used to unpack a blob field from a master whose size of
the field is less than that of the slave. Note: This method is included
to satisfy inheritance rules, but is not needed for blob fields. It
simply is used as a pass-through to the original unpack() method for
blob fields.
@param to Destination of the data
@param from Source of the data
@param param_data @c TRUE if base types should be stored in little-
endian format, @c FALSE if native format should
be used.
@return New pointer into memory based on from + length of the data
*/
const uchar *Field_blob::unpack(uchar *to,
const uchar *from,
uint param_data,
bool low_byte_first)
{
DBUG_ENTER("Field_blob::unpack");
DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
" param_data: %u; low_byte_first: %d",
(ulong) to, (ulong) from, param_data, low_byte_first));
uint const master_packlength=
param_data > 0 ? param_data & 0xFF : packlength;
uint32 const length= get_length(from, master_packlength, low_byte_first);
DBUG_DUMP("packed", from, length + master_packlength);
bitmap_set_bit(table->write_set, field_index);
Field_blob::store(pointer_cast<const char*>(from) + master_packlength,
length, field_charset);
#ifndef DBUG_OFF
uchar *vptr;
get_ptr(&vptr);
DBUG_DUMP("field", ptr, pack_length() /* len bytes + ptr bytes */);
DBUG_DUMP("value", vptr, length /* the blob value length */);
#endif
DBUG_RETURN(from + master_packlength + length);
}
uint Field_blob::packed_col_length(const uchar *data_ptr, uint length)
{
if (length > 255)
return uint2korr(data_ptr)+2;
return (uint) *data_ptr + 1;
}
uint Field_blob::max_packed_col_length()
{
// We do not use addon fields for blobs.
DBUG_ASSERT(false);
const uint max_length= pack_length();
return (max_length > 255 ? 2 : 1) + max_length;
}
uint Field_blob::is_equal(Create_field *new_field)
{
return ((new_field->sql_type == get_blob_type_from_length(max_data_length()))
&& new_field->charset == field_charset &&
new_field->pack_length == pack_length());
}
void Field_geom::sql_type(String &res) const
{
const CHARSET_INFO *cs= &my_charset_latin1;
switch (geom_type)
{
case GEOM_POINT:
res.set(STRING_WITH_LEN("point"), cs);
break;
case GEOM_LINESTRING:
res.set(STRING_WITH_LEN("linestring"), cs);
break;
case GEOM_POLYGON:
res.set(STRING_WITH_LEN("polygon"), cs);
break;
case GEOM_MULTIPOINT:
res.set(STRING_WITH_LEN("multipoint"), cs);
break;
case GEOM_MULTILINESTRING:
res.set(STRING_WITH_LEN("multilinestring"), cs);
break;
case GEOM_MULTIPOLYGON:
res.set(STRING_WITH_LEN("multipolygon"), cs);
break;
case GEOM_GEOMETRYCOLLECTION:
res.set(STRING_WITH_LEN("geometrycollection"), cs);
break;
default:
res.set(STRING_WITH_LEN("geometry"), cs);
}
}
type_conversion_status Field_geom::store(double nr)
{
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return TYPE_ERR_BAD_VALUE;
}
type_conversion_status Field_geom::store(longlong nr, bool unsigned_val)
{
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return TYPE_ERR_BAD_VALUE;
}
type_conversion_status Field_geom::store_decimal(const my_decimal *)
{
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return TYPE_ERR_BAD_VALUE;
}
type_conversion_status Field_geom::store(const char *from, size_t length,
const CHARSET_INFO *cs)
{
if (length < SRID_SIZE + WKB_HEADER_SIZE + sizeof(uint32))
{
memset(ptr, 0, Field_blob::pack_length());
my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, MYF(0));
return TYPE_ERR_BAD_VALUE;
}
return Field_blob::store(from, length, cs);
}
type_conversion_status
Field_geom::store_internal(const char *from, size_t length,
const CHARSET_INFO *cs)
{
// Check that the given WKB
// 1. is at least 13 bytes long (length of GEOMETRYCOLLECTION EMPTY)
// 2. isn't marked as bad geometry data
// 3. isn't shorter than empty geometrycollection
// 4. is a valid geometry type
// 5. is well formed
if (length < 13 || // 1
from == Geometry::bad_geometry_data.ptr() || // 2
length < SRID_SIZE + WKB_HEADER_SIZE + sizeof(uint32) || // 3
!Geometry::is_valid_geotype(uint4korr(from + SRID_SIZE + 1)) || // 4
!Geometry::is_well_formed(from, length, // 5
geometry_type_to_wkb_type(geom_type),
Geometry::wkb_ndr))
{
memset(ptr, 0, Field_blob::pack_length());
my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
return TYPE_ERR_BAD_VALUE;
}
if (table->copy_blobs || length <= MAX_FIELD_WIDTH)
{ // Must make a copy
value.copy(from, length, cs);
from= value.ptr();
}
store_ptr_and_length(from, length);
return TYPE_OK;
}
uint Field_geom::is_equal(Create_field *new_field)
{
return new_field->sql_type == real_type() &&
new_field->geom_type == get_geometry_type() &&
new_field->charset == field_charset &&
new_field->pack_length == pack_length();
}
/**
Get the type of this field (json).
@param str the string that receives the type
*/
void Field_json::sql_type(String &str) const
{
str.set_ascii(STRING_WITH_LEN("json"));
}
/// Create a shallow clone of this field in the specified MEM_ROOT.
Field_json *Field_json::clone(MEM_ROOT *mem_root) const
{
DBUG_ASSERT(type() == MYSQL_TYPE_JSON);
return new (mem_root) Field_json(*this);
}
/// Create a shallow clone of this field.
Field_json *Field_json::clone() const
{
DBUG_ASSERT(type() == MYSQL_TYPE_JSON);
return new Field_json(*this);
}
/**
Check if a new field is compatible with this one.
@param new_field the new field
@return true if new_field is compatible with this field, false otherwise
*/
uint Field_json::is_equal(Create_field *new_field)
{
// All JSON fields are compatible with each other.
return (new_field->sql_type == real_type());
}
/**
Store data in this JSON field.
JSON data is usually stored using store(Field_json*) or store_json(), so this
function will only be called if non-JSON data is attempted stored in a JSON
field. This results in an error in most cases.
It will attempt to parse the string (unless it's binary) as JSON text, and
store a binary representation of JSON document if the string could be parsed.
Note that we override store() and not store_internal() because
Field_blob::store() contains logic that bypasses store_internal() in
some cases we care about. In particular:
- When supplied an empty string, we want to raise a JSON syntax
error instead of silently inserting an empty byte string.
- When called from GROUP_CONCAT with ORDER BY or DISTINCT, we want
to do the same data conversion as usual, whereas
Field_blob::store() jumps directly to Field_blob::store_to_mem()
with the unprocessed input data.
@param from the start of the data to be stored
@param length the length of the data
@param cs the character set of the data
@return zero on success, non-zero on failure
*/
type_conversion_status
Field_json::store(const char *from, size_t length, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
/*
First clear the field so that it doesn't contain garbage if we
return with an error. Some callers continue for a while even after
an error has been raised, and they could get into trouble if the
field contains garbage.
*/
reset();
const char *s;
size_t ss;
String v(from, length, cs);
if (ensure_utf8mb4(&v, &value, &s, &ss, true))
{
return TYPE_ERR_BAD_VALUE;
}
const char *parse_err;
size_t err_offset;
std::auto_ptr<Json_dom> dom(Json_dom::parse(s, ss, &parse_err, &err_offset));
if (dom.get() == NULL)
{
if (parse_err != NULL)
{
// Syntax error.
invalid_text(parse_err, err_offset);
}
return TYPE_ERR_BAD_VALUE;
}
if (json_binary::serialize(dom.get(), &value))
return TYPE_ERR_BAD_VALUE;
return store_binary(value.ptr(), value.length());
}
/**
Helper function for raising an error when trying to store a value
into a JSON column, and that value needs to be cast to JSON before
it can be stored.
*/
type_conversion_status Field_json::unsupported_conversion()
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
invalid_text("not a JSON text, may need CAST", 0);
return TYPE_ERR_BAD_VALUE;
}
/**
Store the provided JSON binary data in this field.
@param[in] ptr pointer to JSON binary data
@param[in] length the length of the binary data
@return zero on success, non-zero on failure
*/
type_conversion_status Field_json::store_binary(const char *ptr, size_t length)
{
/*
We expect that a valid binary representation of a JSON document is
passed to us.
We make an exception for the case of an empty binary string. Even
though an empty binary string is not a valid representation of a
JSON document, we might be served one as a result of inserting
NULL or DEFAULT into a not nullable JSON column using INSERT
IGNORE, or inserting DEFAULT into a not nullable JSON column in
non-strict SQL mode.
We accept an empty binary string in those cases. Such values will
be converted to the JSON null literal when they are read with
Field_json::val_json().
*/
DBUG_ASSERT(length == 0 || json_binary::parse_binary(ptr, length).is_valid());
if (value.length() > UINT_MAX32)
{
/* purecov: begin inspected */
my_error(ER_JSON_VALUE_TOO_BIG, MYF(0));
return TYPE_ERR_BAD_VALUE;
/* purecov: end */
}
return Field_blob::store(ptr, length, field_charset);
}
/// Store a double in a JSON field. Will raise an error for now.
type_conversion_status Field_json::store(double nr)
{
return unsupported_conversion();
}
/// Store an integer in a JSON field. Will raise an error for now.
type_conversion_status Field_json::store(longlong nr, bool unsigned_val)
{
return unsupported_conversion();
}
/// Store a decimal in a JSON field. Will raise an error for now.
type_conversion_status Field_json::store_decimal(const my_decimal *)
{
return unsupported_conversion();
}
/// Store a TIME value in a JSON field. Will raise an error for now.
type_conversion_status Field_json::store_time(MYSQL_TIME *ltime, uint8 dec_arg)
{
return unsupported_conversion();
}
/**
Store a JSON value as binary.
@param json the JSON value to store
@return zero on success, non-zero otherwise
*/
type_conversion_status Field_json::store_json(Json_wrapper *json)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
if (json->to_binary(&value))
return TYPE_ERR_BAD_VALUE;
return store_binary(value.ptr(), value.length());
}
/**
Copy the contents of a non-null JSON field into this field.
@param[in] field the field to copy data from
@return zero on success, non-zero on failure
*/
type_conversion_status Field_json::store(Field_json *field)
{
/*
The callers of this function have already checked for null, so we
don't need to handle it here for now. Assert that field is not
null.
*/
DBUG_ASSERT(!field->is_null());
String tmp;
String *s= field->Field_blob::val_str(&tmp, &tmp);
return store_binary(s->ptr(), s->length());
}
bool Field_json::val_json(Json_wrapper *wr)
{
ASSERT_COLUMN_MARKED_FOR_READ;
DBUG_ASSERT(!is_null());
String tmp;
String *s= Field_blob::val_str(&tmp, &tmp);
/*
The empty string is not a valid JSON binary representation, so we
should have returned an error. However, sometimes an empty
Field_json object is created in order to retrieve meta-data.
Return a dummy value instead of raising an error. Bug#21104470.
The field could also contain an empty string after forcing NULL or
DEFAULT into a not nullable JSON column using lax error checking
(such as INSERT IGNORE or non-strict SQL mode). The JSON null
literal is used to represent the empty value in this case.
Bug#21437989.
*/
if (s->length() == 0)
{
Json_wrapper w(new (std::nothrow) Json_null());
wr->steal(&w);
return false;
}
json_binary::Value v(json_binary::parse_binary(s->ptr(), s->length()));
if (v.type() == json_binary::Value::ERROR)
{
/* purecov: begin inspected */
my_error(ER_INVALID_JSON_BINARY_DATA, MYF(0));
return true;
/* purecov: end */
}
Json_wrapper w(v);
wr->steal(&w);
return false;
}
longlong Field_json::val_int()
{
ASSERT_COLUMN_MARKED_FOR_READ;
Json_wrapper wr;
if (is_null() || val_json(&wr))
return 0; /* purecov: inspected */
return wr.coerce_int(field_name);
}
double Field_json::val_real()
{
ASSERT_COLUMN_MARKED_FOR_READ;
Json_wrapper wr;
if (is_null() || val_json(&wr))
return 0.0; /* purecov: inspected */
return wr.coerce_real(field_name);
}
String *Field_json::val_str(String *buf1, String *buf2 MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
/*
Per contract of Field::val_str(String*,String*), buf1 should be
used if the value needs to be converted to string, and buf2 should
be used if the string value is already known. We need to convert,
so use buf1.
*/
buf1->length(0);
Json_wrapper wr;
if (is_null() || val_json(&wr) || wr.to_string(buf1, true, field_name))
buf1->length(0);
return buf1;
}
my_decimal *Field_json::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
Json_wrapper wr;
if (is_null() || val_json(&wr))
{
/* purecov: begin inspected */
my_decimal_set_zero(decimal_value);
return decimal_value;
/* purecov: end */
}
return wr.coerce_decimal(decimal_value, field_name);
}
bool Field_json::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
{
bool result= get_time(ltime);
if (!result && ltime->time_type == MYSQL_TIMESTAMP_TIME)
{
MYSQL_TIME tmp= *ltime;
time_to_datetime(current_thd, &tmp, ltime);
}
return result;
}
bool Field_json::get_time(MYSQL_TIME *ltime)
{
ASSERT_COLUMN_MARKED_FOR_READ;
Json_wrapper wr;
bool result= is_null() || val_json(&wr) || wr.coerce_time(ltime, field_name);
if (result)
set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME); /* purecov: inspected */
return result;
}
void Field_json::make_sort_key(uchar *to, size_t length)
{
Json_wrapper wr;
if (val_json(&wr))
{
/* purecov: begin inspected */
memset(to, 0, length);
return;
/* purecov: end */
}
wr.make_sort_key(to, length);
}
ulonglong Field_json::make_hash_key(ulonglong *hash_val)
{
Json_wrapper wr;
if (val_json(&wr))
return *hash_val; /* purecov: inspected */
return wr.make_hash_key(hash_val);
}
/****************************************************************************
** enum type.
** This is a string which only can have a selection of different values.
** If one uses this string in a number context one gets the type number.
****************************************************************************/
enum ha_base_keytype Field_enum::key_type() const
{
switch (packlength) {
default: return HA_KEYTYPE_BINARY;
case 2: return HA_KEYTYPE_USHORT_INT;
case 3: return HA_KEYTYPE_UINT24;
case 4: return HA_KEYTYPE_ULONG_INT;
case 8: return HA_KEYTYPE_ULONGLONG;
}
}
void Field_enum::store_type(ulonglong value)
{
switch (packlength) {
case 1: ptr[0]= (uchar) value;
break;
case 2:
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int2store(ptr,(unsigned short) value);
}
else
{
shortstore(ptr,(unsigned short) value);
}
#else
shortstore(ptr,(unsigned short) value);
#endif
break;
case 3: int3store(ptr,(long) value);
break;
case 4:
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int4store(ptr,value);
}
else
{
longstore(ptr,(long) value);
}
#else
longstore(ptr,(long) value);
#endif
break;
case 8:
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
{
int8store(ptr,value);
}
else
{
longlongstore(ptr,value);
}
#else
longlongstore(ptr,value);
#endif
break;
}
}
/**
@note
Storing a empty string in a enum field gives a warning
(if there isn't a empty value in the enum)
*/
type_conversion_status
Field_enum::store(const char *from, size_t length,const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int err= 0;
type_conversion_status ret= TYPE_OK;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmpstr(buff,sizeof(buff), &my_charset_bin);
/* Convert character set if necessary */
if (String::needs_conversion_on_storage(length, cs, field_charset))
{
uint dummy_errors;
tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
from= tmpstr.ptr();
length= tmpstr.length();
}
/* Remove end space */
length= field_charset->cset->lengthsp(field_charset, from, length);
uint tmp=find_type2(typelib, from, length, field_charset);
if (!tmp)
{
if (length < 6) // Can't be more than 99999 enums
{
/* This is for reading numbers with LOAD DATA INFILE */
char *end;
tmp=(uint) my_strntoul(cs,from,length,10,&end,&err);
if (err || end != from+length || tmp > typelib->count)
{
tmp=0;
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
ret= TYPE_WARN_TRUNCATED;
}
if (!table->in_use->count_cuted_fields)
ret= TYPE_OK;
}
else
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
}
store_type((ulonglong) tmp);
return ret;
}
type_conversion_status Field_enum::store(double nr)
{
return Field_enum::store((longlong) nr, FALSE);
}
type_conversion_status Field_enum::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
if ((ulonglong) nr > typelib->count || nr == 0)
{
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
if (nr != 0 || table->in_use->count_cuted_fields)
{
nr= 0;
error= TYPE_WARN_TRUNCATED;
}
}
store_type((ulonglong) (uint) nr);
return error;
}
double Field_enum::val_real(void)
{
return (double) Field_enum::val_int();
}
my_decimal *Field_enum::val_decimal(my_decimal *decimal_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 0, decimal_value);
return decimal_value;
}
longlong Field_enum::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
switch (packlength) {
case 1:
return (longlong) ptr[0];
case 2:
{
uint16 tmp;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
tmp=sint2korr(ptr);
else
#endif
ushortget(&tmp, ptr);
return (longlong) tmp;
}
case 3:
return (longlong) uint3korr(ptr);
case 4:
{
uint32 tmp;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
tmp=uint4korr(ptr);
else
#endif
ulongget(&tmp, ptr);
return (longlong) tmp;
}
case 8:
{
longlong tmp;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
tmp=sint8korr(ptr);
else
#endif
longlongget(&tmp, ptr);
return tmp;
}
}
return 0; // impossible
}
/**
Save the field metadata for enum fields.
Saves the real type in the first byte and the pack length in the
second byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_enum::do_save_field_metadata(uchar *metadata_ptr)
{
*metadata_ptr= real_type();
*(metadata_ptr + 1)= pack_length();
return 2;
}
String *Field_enum::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
String *val_ptr)
{
uint tmp=(uint) Field_enum::val_int();
if (!tmp || tmp > typelib->count)
val_ptr->set("", 0, field_charset);
else
val_ptr->set(typelib->type_names[tmp-1],
typelib->type_lengths[tmp-1],
field_charset);
return val_ptr;
}
int Field_enum::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
uchar *old= ptr;
ptr= (uchar*) a_ptr;
ulonglong a=Field_enum::val_int();
ptr= (uchar*) b_ptr;
ulonglong b=Field_enum::val_int();
ptr= old;
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
void Field_enum::make_sort_key(uchar *to, size_t length)
{
#ifdef WORDS_BIGENDIAN
if (!table->s->db_low_byte_first)
copy_integer<true>(to, length, ptr, packlength, true);
else
#endif
copy_integer<false>(to, length, ptr, packlength, true);
}
void Field_enum::sql_type(String &res) const
{
char buffer[255];
String enum_item(buffer, sizeof(buffer), res.charset());
res.length(0);
res.append(STRING_WITH_LEN("enum("));
bool flag=0;
uint *len= typelib->type_lengths;
for (const char **pos= typelib->type_names; *pos; pos++, len++)
{
uint dummy_errors;
if (flag)
res.append(',');
/* convert to res.charset() == utf8, then quote */
enum_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
append_unescaped(&res, enum_item.ptr(), enum_item.length());
flag= 1;
}
res.append(')');
}
Field *Field_enum::new_field(MEM_ROOT *root, TABLE *new_table,
bool keep_type)
{
Field_enum *res= (Field_enum*) Field::new_field(root, new_table, keep_type);
if (res)
res->typelib= copy_typelib(root, typelib);
return res;
}
/*
set type.
This is a string which can have a collection of different values.
Each string value is separated with a ','.
For example "One,two,five"
If one uses this string in a number context one gets the bits as a longlong
number.
*/
type_conversion_status
Field_set::store(const char *from, size_t length,const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
bool got_warning= 0;
int err= 0;
type_conversion_status ret= TYPE_OK;
char *not_used;
uint not_used2;
char buff[STRING_BUFFER_USUAL_SIZE];
String tmpstr(buff,sizeof(buff), &my_charset_bin);
/* Convert character set if necessary */
if (String::needs_conversion_on_storage(length, cs, field_charset))
{
uint dummy_errors;
tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
from= tmpstr.ptr();
length= tmpstr.length();
}
ulonglong tmp= find_set(typelib, from, length, field_charset,
¬_used, ¬_used2, &got_warning);
if (!tmp && length && length < 22)
{
/* This is for reading numbers with LOAD DATA INFILE */
char *end;
tmp=my_strntoull(cs,from,length,10,&end,&err);
if (err ||
end != from+length ||
(typelib->count < 64 && tmp >= (1ULL << typelib->count)))
{
tmp=0;
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
ret= TYPE_WARN_TRUNCATED;
}
}
else if (got_warning)
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
store_type(tmp);
return ret;
}
type_conversion_status Field_set::store(longlong nr, bool unsigned_val)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
type_conversion_status error= TYPE_OK;
ulonglong max_nr;
if (sizeof(ulonglong)*8 <= typelib->count)
max_nr= ULLONG_MAX;
else
max_nr= (1ULL << typelib->count) - 1;
if ((ulonglong) nr > max_nr)
{
nr&= max_nr;
set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
error= TYPE_WARN_TRUNCATED;
}
store_type((ulonglong) nr);
return error;
}
String *Field_set::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ulonglong tmp=(ulonglong) Field_enum::val_int();
uint bitnr=0;
/*
Some callers expect *val_buffer to contain the result,
so we assign to it, rather than doing 'return &empty_set_string.
*/
*val_buffer= empty_set_string;
if (tmp == 0)
{
return val_buffer;
}
val_buffer->set_charset(field_charset);
val_buffer->length(0);
while (tmp && bitnr < typelib->count)
{
if (tmp & 1)
{
if (val_buffer->length())
val_buffer->append(&field_separator, 1, &my_charset_latin1);
String str(typelib->type_names[bitnr],
typelib->type_lengths[bitnr],
field_charset);
val_buffer->append(str);
}
tmp>>=1;
bitnr++;
}
return val_buffer;
}
void Field_set::sql_type(String &res) const
{
char buffer[255];
String set_item(buffer, sizeof(buffer), res.charset());
res.length(0);
res.append(STRING_WITH_LEN("set("));
bool flag=0;
uint *len= typelib->type_lengths;
for (const char **pos= typelib->type_names; *pos; pos++, len++)
{
uint dummy_errors;
if (flag)
res.append(',');
/* convert to res.charset() == utf8, then quote */
set_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
append_unescaped(&res, set_item.ptr(), set_item.length());
flag= 1;
}
res.append(')');
}
/**
@retval
1 if the fields are equally defined
@retval
0 if the fields are unequally defined
*/
bool Field::eq_def(Field *field)
{
if (real_type() != field->real_type() || charset() != field->charset() ||
pack_length() != field->pack_length())
return 0;
return 1;
}
/**
Compare the first t1::count type names.
@return TRUE if the type names of t1 match those of t2. FALSE otherwise.
*/
static bool compare_type_names(const CHARSET_INFO *charset,
TYPELIB *t1, TYPELIB *t2)
{
for (uint i= 0; i < t1->count; i++)
if (my_strnncoll(charset,
(const uchar*) t1->type_names[i],
t1->type_lengths[i],
(const uchar*) t2->type_names[i],
t2->type_lengths[i]))
return FALSE;
return TRUE;
}
/**
@return
returns 1 if the fields are equally defined
*/
bool Field_enum::eq_def(Field *field)
{
TYPELIB *values;
if (!Field::eq_def(field))
return FALSE;
values= ((Field_enum*) field)->typelib;
/* Definition must be strictly equal. */
if (typelib->count != values->count)
return FALSE;
return compare_type_names(field_charset, typelib, values);
}
/**
Check whether two fields can be considered 'equal' for table
alteration purposes. Fields are equal if they retain the same
pack length and if new members are added to the end of the list.
@return IS_EQUAL_YES if fields are compatible.
IS_EQUAL_NO otherwise.
*/
uint Field_enum::is_equal(Create_field *new_field)
{
TYPELIB *values= new_field->interval;
/*
The fields are compatible if they have the same flags,
type, charset and have the same underlying length.
*/
if (new_field->sql_type != real_type() ||
new_field->charset != field_charset ||
new_field->pack_length != pack_length())
return IS_EQUAL_NO;
/*
Changing the definition of an ENUM or SET column by adding a new
enumeration or set members to the end of the list of valid member
values only alters table metadata and not table data.
*/
if (typelib->count > values->count)
return IS_EQUAL_NO;
/* Check whether there are modification before the end. */
if (! compare_type_names(field_charset, typelib, new_field->interval))
return IS_EQUAL_NO;
return IS_EQUAL_YES;
}
uchar *Field_enum::pack(uchar *to, const uchar *from,
uint max_length, bool low_byte_first)
{
DBUG_ENTER("Field_enum::pack");
DBUG_PRINT("debug", ("packlength: %d", packlength));
DBUG_DUMP("from", from, packlength);
switch (packlength)
{
case 1:
*to = *from;
DBUG_RETURN(to + 1);
case 2: DBUG_RETURN(pack_int16(to, from, low_byte_first));
case 3: DBUG_RETURN(pack_int24(to, from, low_byte_first));
case 4: DBUG_RETURN(pack_int32(to, from, low_byte_first));
case 8: DBUG_RETURN(pack_int64(to, from, low_byte_first));
default:
DBUG_ASSERT(0);
}
MY_ASSERT_UNREACHABLE();
DBUG_RETURN(NULL);
}
const uchar *Field_enum::unpack(uchar *to, const uchar *from,
uint param_data, bool low_byte_first)
{
DBUG_ENTER("Field_enum::unpack");
DBUG_PRINT("debug", ("packlength: %d", packlength));
DBUG_DUMP("from", from, packlength);
switch (packlength)
{
case 1:
*to = *from;
DBUG_RETURN(from + 1);
case 2: DBUG_RETURN(unpack_int16(to, from, low_byte_first));
case 3: DBUG_RETURN(unpack_int24(to, from, low_byte_first));
case 4: DBUG_RETURN(unpack_int32(to, from, low_byte_first));
case 8: DBUG_RETURN(unpack_int64(to, from, low_byte_first));
default:
DBUG_ASSERT(0);
}
MY_ASSERT_UNREACHABLE();
DBUG_RETURN(NULL);
}
/**
@return
returns 1 if the fields are equally defined
*/
bool Field_num::eq_def(Field *field)
{
if (!Field::eq_def(field))
return 0;
Field_num *from_num= (Field_num*) field;
if (unsigned_flag != from_num->unsigned_flag ||
(zerofill && !from_num->zerofill && !zero_pack()) ||
dec != from_num->dec)
return 0;
return 1;
}
/**
Check whether two numeric fields can be considered 'equal' for table
alteration purposes. Fields are equal if they are of the same type
and retain the same pack length.
*/
uint Field_num::is_equal(Create_field *new_field)
{
return ((new_field->sql_type == real_type()) &&
((new_field->flags & UNSIGNED_FLAG) ==
(uint) (flags & UNSIGNED_FLAG)) &&
((new_field->flags & AUTO_INCREMENT_FLAG) ==
(uint) (flags & AUTO_INCREMENT_FLAG)) &&
(new_field->pack_length == pack_length()));
}
/*
Bit field.
We store the first 0 - 6 uneven bits among the null bits
at the start of the record. The rest bytes are stored in
the record itself.
For example:
CREATE TABLE t1 (a int, b bit(17), c bit(21) not null, d bit(8));
We would store data as follows in the record:
Byte Bit
1 7 - reserve for delete
6 - null bit for 'a'
5 - null bit for 'b'
4 - first (high) bit of 'b'
3 - first (high) bit of 'c'
2 - second bit of 'c'
1 - third bit of 'c'
0 - forth bit of 'c'
2 7 - firth bit of 'c'
6 - null bit for 'd'
3 - 6 four bytes for 'a'
7 - 8 two bytes for 'b'
9 - 10 two bytes for 'c'
11 one byte for 'd'
*/
Field_bit::Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
enum utype unireg_check_arg, const char *field_name_arg)
: Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unireg_check_arg, field_name_arg),
bit_ptr(bit_ptr_arg), bit_ofs(bit_ofs_arg), bit_len(len_arg & 7),
bytes_in_rec(len_arg / 8)
{
DBUG_ENTER("Field_bit::Field_bit");
DBUG_PRINT("enter", ("ptr_arg: %p, null_ptr_arg: %p, len_arg: %u, bit_len: %u, bytes_in_rec: %u",
ptr_arg, null_ptr_arg, len_arg, bit_len, bytes_in_rec));
flags|= UNSIGNED_FLAG;
/*
Ensure that Field::eq() can distinguish between two different bit fields.
(two bit fields that are not null, may have same ptr and m_null_ptr)
*/
if (!null_ptr_arg)
null_bit= bit_ofs_arg;
DBUG_VOID_RETURN;
}
void Field_bit::hash(ulong *nr, ulong *nr2)
{
if (is_null())
{
*nr^= (*nr << 1) | 1;
}
else
{
const CHARSET_INFO *cs= &my_charset_bin;
longlong value= Field_bit::val_int();
uchar tmp[8];
mi_int8store(tmp,value);
cs->coll->hash_sort(cs, tmp, 8, nr, nr2);
}
}
size_t
Field_bit::do_last_null_byte() const
{
/*
Code elsewhere is assuming that bytes are 8 bits, so I'm using
that value instead of the correct one: CHAR_BIT.
REFACTOR SUGGESTION (Matz): Change to use the correct number of
bits. On systems with CHAR_BIT > 8 (not very common), the storage
will lose the extra bits.
*/
DBUG_PRINT("test", ("bit_ofs: %d, bit_len: %d bit_ptr: 0x%lx",
bit_ofs, bit_len, (long) bit_ptr));
const uchar *result;
if (bit_len == 0)
result= get_null_ptr();
else if (bit_ofs + bit_len > 8)
result= bit_ptr + 1;
else
result= bit_ptr;
if (result)
return (size_t) (result - table->record[0]) + 1;
return LAST_NULL_BYTE_UNDEF;
}
Field *Field_bit::new_key_field(MEM_ROOT *root,
TABLE *new_table,
uchar *new_ptr, uchar *new_null_ptr,
uint new_null_bit)
{
Field_bit *res;
if ((res= (Field_bit*) Field::new_key_field(root, new_table,
new_ptr, new_null_ptr,
new_null_bit)))
{
/* Move bits normally stored in null_pointer to new_ptr */
res->bit_ptr= new_ptr;
res->bit_ofs= 0;
if (bit_len)
res->ptr++; // Store rest of data here
}
return res;
}
uint Field_bit::is_equal(Create_field *new_field)
{
return (new_field->sql_type == real_type() &&
new_field->length == max_display_length());
}
type_conversion_status
Field_bit::store(const char *from, size_t length, const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int delta;
for (; length && !*from; from++, length--) ; // skip left 0's
delta= bytes_in_rec - static_cast<int>(length);
/*
*from should probably be treated like uint here see BUG#13727586
*/
if (delta < -1 ||
(delta == -1 && (uchar) *from > ((1 << bit_len) - 1)) ||
(!bit_len && delta < 0))
{
set_rec_bits((1 << bit_len) - 1, bit_ptr, bit_ofs, bit_len);
memset(ptr, 0xff, bytes_in_rec);
if (table->in_use->is_strict_mode())
set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
else
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return TYPE_WARN_OUT_OF_RANGE;
}
/* delta is >= -1 here */
if (delta > 0)
{
if (bit_len)
clr_rec_bits(bit_ptr, bit_ofs, bit_len);
memset(ptr, 0, delta);
memcpy(ptr + delta, from, length);
}
else if (delta == 0)
{
if (bit_len)
clr_rec_bits(bit_ptr, bit_ofs, bit_len);
memcpy(ptr, from, length);
}
else
{
if (bit_len)
{
set_rec_bits((uchar) *from, bit_ptr, bit_ofs, bit_len);
from++;
}
memcpy(ptr, from, bytes_in_rec);
}
return TYPE_OK;
}
type_conversion_status Field_bit::store(double nr)
{
return Field_bit::store((longlong) nr, FALSE);
}
type_conversion_status Field_bit::store(longlong nr, bool unsigned_val)
{
char buf[8];
mi_int8store(buf, nr);
return store(buf, 8, NULL);
}
type_conversion_status Field_bit::store_decimal(const my_decimal *val)
{
bool has_overflow= false;
longlong i= convert_decimal2longlong(val, 1, &has_overflow);
type_conversion_status res= store(i, TRUE);
return has_overflow ? TYPE_WARN_OUT_OF_RANGE : res;
}
double Field_bit::val_real(void)
{
return (double) Field_bit::val_int();
}
longlong Field_bit::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
ulonglong bits= 0;
if (bit_len)
{
bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
bits<<= (bytes_in_rec * 8);
}
switch (bytes_in_rec) {
case 0: return bits;
case 1: return bits | (ulonglong) ptr[0];
case 2: return bits | mi_uint2korr(ptr);
case 3: return bits | mi_uint3korr(ptr);
case 4: return bits | mi_uint4korr(ptr);
case 5: return bits | mi_uint5korr(ptr);
case 6: return bits | mi_uint6korr(ptr);
case 7: return bits | mi_uint7korr(ptr);
default: return mi_uint8korr(ptr + bytes_in_rec - sizeof(longlong));
}
}
String *Field_bit::val_str(String *val_buffer,
String *val_ptr MY_ATTRIBUTE((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
char buff[sizeof(longlong)];
uint length= min<uint>(pack_length(), sizeof(longlong));
ulonglong bits= val_int();
mi_int8store(buff,bits);
val_buffer->alloc(length);
memcpy((char *) val_buffer->ptr(), buff+8-length, length);
val_buffer->length(length);
val_buffer->set_charset(&my_charset_bin);
return val_buffer;
}
my_decimal *Field_bit::val_decimal(my_decimal *deciaml_value)
{
ASSERT_COLUMN_MARKED_FOR_READ;
int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 1, deciaml_value);
return deciaml_value;
}
/*
Compare two bit fields using pointers within the record.
SYNOPSIS
cmp_max()
a Pointer to field->ptr in first record
b Pointer to field->ptr in second record
max_len Maximum length used in index
DESCRIPTION
This method is used from key_rec_cmp used by merge sorts used
by partitioned index read and later other similar places.
The a and b pointer must be pointers to the field in a record
(not the table->record[0] necessarily)
*/
int Field_bit::cmp_max(const uchar *a, const uchar *b, uint max_len)
{
my_ptrdiff_t a_diff= a - ptr;
my_ptrdiff_t b_diff= b - ptr;
if (bit_len)
{
int flag;
uchar bits_a= get_rec_bits(bit_ptr+a_diff, bit_ofs, bit_len);
uchar bits_b= get_rec_bits(bit_ptr+b_diff, bit_ofs, bit_len);
if ((flag= (int) (bits_a - bits_b)))
return flag;
}
return memcmp(a, b, pack_length());
}
int Field_bit::key_cmp(const uchar *str, uint length)
{
if (bit_len)
{
int flag;
uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
if ((flag= (int) (bits - *str)))
return flag;
str++;
length--;
}
return memcmp(ptr, str, length);
}
int Field_bit::cmp_offset(uint row_offset)
{
if (bit_len)
{
int flag;
uchar bits_a= get_rec_bits(bit_ptr, bit_ofs, bit_len);
uchar bits_b= get_rec_bits(bit_ptr + row_offset, bit_ofs, bit_len);
if ((flag= (int) (bits_a - bits_b)))
return flag;
}
return memcmp(ptr, ptr + row_offset, bytes_in_rec);
}
size_t Field_bit::get_key_image(uchar *buff, size_t length, imagetype type_arg)
{
if (bit_len)
{
uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
*buff++= bits;
length--;
}
size_t data_length = min(length, static_cast<size_t>(bytes_in_rec));
memcpy(buff, ptr, data_length);
return data_length + 1;
}
/**
Save the field metadata for bit fields.
Saves the bit length in the first byte and bytes in record in the
second byte of the field metadata array at index of *metadata_ptr and
*(metadata_ptr + 1).
@param metadata_ptr First byte of field metadata
@returns number of bytes written to metadata_ptr
*/
int Field_bit::do_save_field_metadata(uchar *metadata_ptr)
{
DBUG_ENTER("Field_bit::do_save_field_metadata");
DBUG_PRINT("debug", ("bit_len: %d, bytes_in_rec: %d",
bit_len, bytes_in_rec));
/*
Since this class and Field_bit_as_char have different ideas of
what should be stored here, we compute the values of the metadata
explicitly using the field_length.
*/
metadata_ptr[0]= field_length % 8;
metadata_ptr[1]= field_length / 8;
DBUG_RETURN(2);
}
/**
Returns the number of bytes field uses in row-based replication
row packed size.
This method is used in row-based replication to determine the number
of bytes that the field consumes in the row record format. This is
used to skip fields in the master that do not exist on the slave.
@param field_metadata Encoded size in field metadata
@returns The size of the field based on the field metadata.
*/
uint Field_bit::pack_length_from_metadata(uint field_metadata)
{
uint const from_len= (field_metadata >> 8U) & 0x00ff;
uint const from_bit_len= field_metadata & 0x00ff;
uint const source_size= from_len + ((from_bit_len > 0) ? 1 : 0);
return (source_size);
}
/**
Check to see if field size is compatible with destination.
This method is used in row-based replication to verify that the slave's
field size is less than or equal to the master's field size. The
encoded field metadata (from the master or source) is decoded and compared
to the size of this field (the slave or destination).
@param field_metadata Encoded size in field metadata
@param order_var Pointer to variable where the order
between the source field and this field
will be returned.
@return @c true
*/
bool
Field_bit::compatible_field_size(uint field_metadata,
Relay_log_info * MY_ATTRIBUTE((unused)),
uint16 mflags,
int *order_var)
{
DBUG_ENTER("Field_bit::compatible_field_size");
DBUG_ASSERT((field_metadata >> 16) == 0);
uint from_bit_len= 8 * (field_metadata >> 8) + (field_metadata & 0xff);
uint to_bit_len= max_display_length();
DBUG_PRINT("debug", ("from_bit_len: %u, to_bit_len: %u",
from_bit_len, to_bit_len));
/*
If the bit length exact flag is clear, we are dealing with an old
master, so we allow some less strict behaviour if replicating by
moving both bit lengths to an even multiple of 8.
We do this by computing the number of bytes to store the field
instead, and then compare the result.
*/
if (!(mflags & Table_map_log_event::TM_BIT_LEN_EXACT_F)) {
from_bit_len= (from_bit_len + 7) / 8;
to_bit_len= (to_bit_len + 7) / 8;
}
*order_var= compare(from_bit_len, to_bit_len);
DBUG_RETURN(TRUE);
}
void Field_bit::sql_type(String &res) const
{
const CHARSET_INFO *cs= res.charset();
size_t length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
"bit(%d)", (int) field_length);
res.length(length);
}
uchar *
Field_bit::pack(uchar *to, const uchar *from, uint max_length,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
DBUG_ASSERT(max_length > 0);
uint length;
if (bit_len > 0)
{
/*
We have the following:
ptr Points into a field in record R1
from Points to a field in a record R2
bit_ptr Points to the byte (in the null bytes) that holds the
odd bits of R1
from_bitp Points to the byte that holds the odd bits of R2
We have the following:
ptr - bit_ptr = from - from_bitp
We want to isolate 'from_bitp', so this gives:
ptr - bit_ptr - from = - from_bitp
- ptr + bit_ptr + from = from_bitp
bit_ptr + from - ptr = from_bitp
*/
uchar bits= get_rec_bits(bit_ptr + (from - ptr), bit_ofs, bit_len);
*to++= bits;
}
length= min(bytes_in_rec, max_length - (bit_len > 0));
memcpy(to, from, length);
return to + length;
}
/**
Unpack a bit field from row data.
This method is used to unpack a bit field from a master whose size
of the field is less than that of the slave.
@param to Destination of the data
@param from Source of the data
@param param_data Bit length (upper) and length (lower) values
@return New pointer into memory based on from + length of the data
*/
const uchar *
Field_bit::unpack(uchar *to, const uchar *from, uint param_data,
bool low_byte_first MY_ATTRIBUTE((unused)))
{
DBUG_ENTER("Field_bit::unpack");
DBUG_PRINT("enter", ("to: %p, from: %p, param_data: 0x%x",
to, from, param_data));
DBUG_PRINT("debug", ("bit_ptr: %p, bit_len: %u, bit_ofs: %u",
bit_ptr, bit_len, bit_ofs));
uint const from_len= (param_data >> 8U) & 0x00ff;
uint const from_bit_len= param_data & 0x00ff;
DBUG_PRINT("debug", ("from_len: %u, from_bit_len: %u",
from_len, from_bit_len));
/*
If the parameter data is zero (i.e., undefined), or if the master
and slave have the same sizes, then use the old unpack() method.
*/
if (param_data == 0 ||
((from_bit_len == bit_len) && (from_len == bytes_in_rec)))
{
if (bit_len > 0)
{
/*
set_rec_bits is a macro, don't put the post-increment in the
argument since that might cause strange side-effects.
For the choice of the second argument, see the explanation for
Field_bit::pack().
*/
set_rec_bits(*from, bit_ptr + (to - ptr), bit_ofs, bit_len);
from++;
}
memcpy(to, from, bytes_in_rec);
DBUG_RETURN(from + bytes_in_rec);
}
/*
We are converting a smaller bit field to a larger one here.
To do that, we first need to construct a raw value for the original
bit value stored in the from buffer. Then that needs to be converted
to the larger field then sent to store() for writing to the field.
Lastly the odd bits need to be masked out if the bytes_in_rec > 0.
Otherwise stray bits can cause spurious values.
*/
uint new_len= (field_length + 7) / 8;
char *value= (char *)my_alloca(new_len);
memset(value, 0, new_len);
uint len= from_len + ((from_bit_len > 0) ? 1 : 0);
memcpy(value + (new_len - len), from, len);
/*
Mask out the unused bits in the partial byte.
TODO: Add code to the master to always mask these bits and remove
the following.
*/
if ((from_bit_len > 0) && (from_len > 0))
value[new_len - len]= value[new_len - len] & ((1U << from_bit_len) - 1);
bitmap_set_bit(table->write_set,field_index);
store(value, new_len, system_charset_info);
DBUG_RETURN(from + len);
}
void Field_bit::set_default()
{
if (bit_len > 0)
{
my_ptrdiff_t offset= table->default_values_offset();
uchar bits= get_rec_bits(bit_ptr + offset, bit_ofs, bit_len);
set_rec_bits(bits, bit_ptr, bit_ofs, bit_len);
}
Field::set_default();
}
/*
Bit field support for non-MyISAM tables.
*/
Field_bit_as_char::Field_bit_as_char(uchar *ptr_arg, uint32 len_arg,
uchar *null_ptr_arg, uchar null_bit_arg,
enum utype unireg_check_arg,
const char *field_name_arg)
:Field_bit(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, 0, 0,
unireg_check_arg, field_name_arg)
{
flags|= UNSIGNED_FLAG;
bit_len= 0;
bytes_in_rec= (len_arg + 7) / 8;
}
type_conversion_status Field_bit_as_char::store(const char *from, size_t length,
const CHARSET_INFO *cs)
{
ASSERT_COLUMN_MARKED_FOR_WRITE;
int delta;
uchar bits= (uchar) (field_length & 7);
for (; length && !*from; from++, length--) ; // skip left 0's
delta= bytes_in_rec - static_cast<int>(length);
if (delta < 0 ||
(delta == 0 && bits && (uint) (uchar) *from >= (uint) (1 << bits)))
{
memset(ptr, 0xff, bytes_in_rec);
if (bits)
*ptr&= ((1 << bits) - 1); /* set first uchar */
if (table->in_use->is_strict_mode())
set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
else
set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
return TYPE_WARN_OUT_OF_RANGE;
}
memset(ptr, 0, delta);
memcpy(ptr + delta, from, length);
return TYPE_OK;
}
void Field_bit_as_char::sql_type(String &res) const
{
const CHARSET_INFO *cs= res.charset();
size_t length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
"bit(%d)", (int) field_length);
res.length(length);
}
/*****************************************************************************
Handling of field and Create_field
*****************************************************************************/
/**
Convert create_field::length from number of characters to number of bytes.
*/
void Create_field::create_length_to_internal_length(void)
{
switch (sql_type) {
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_JSON:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VARCHAR:
length*= charset->mbmaxlen;
key_length= length;
pack_length= calc_pack_length(sql_type, length);
break;
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
/* Pack_length already calculated in sql_parse.cc */
length*= charset->mbmaxlen;
key_length= pack_length;
break;
case MYSQL_TYPE_BIT:
if (f_bit_as_char(pack_flag))
{
key_length= pack_length= ((length + 7) & ~7) / 8;
}
else
{
pack_length= length / 8;
/* We need one extra byte to store the bits we save among the null bits */
key_length= pack_length + MY_TEST(length & 7);
}
break;
case MYSQL_TYPE_NEWDECIMAL:
key_length= pack_length=
my_decimal_get_binary_size(my_decimal_length_to_precision(length,
decimals,
flags &
UNSIGNED_FLAG),
decimals);
break;
default:
key_length= pack_length= calc_pack_length(sql_type, length);
break;
}
}
/**
Init for a tmp table field. To be extended if need be.
*/
void Create_field::init_for_tmp_table(enum_field_types sql_type_arg,
uint32 length_arg, uint32 decimals_arg,
bool maybe_null, bool is_unsigned,
uint pack_length_arg)
{
DBUG_ENTER("Create_field::init_for_tmp_table");
field_name= "";
sql_type= sql_type_arg;
char_length= length= length_arg;;
unireg_check= Field::NONE;
interval= 0;
charset= &my_charset_bin;
geom_type= Field::GEOM_GEOMETRY;
DBUG_PRINT("enter", ("sql_type: %d, length: %u, pack_length: %u",
sql_type_arg, length_arg, pack_length_arg));
/*
These pack flags are crafted to get it correctly through the
branches of make_field().
*/
switch (sql_type_arg)
{
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_SET:
pack_flag= 0;
break;
case MYSQL_TYPE_GEOMETRY:
pack_flag= FIELDFLAG_GEOM;
break;
case MYSQL_TYPE_JSON:
pack_flag= FIELDFLAG_JSON;
break;
case MYSQL_TYPE_ENUM:
pack_flag= FIELDFLAG_INTERVAL;
break;
case MYSQL_TYPE_NEWDECIMAL:
DBUG_ASSERT(decimals_arg <= DECIMAL_MAX_SCALE);
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE:
pack_flag= FIELDFLAG_NUMBER |
(decimals_arg & FIELDFLAG_MAX_DEC) << FIELDFLAG_DEC_SHIFT;
break;
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
pack_flag= FIELDFLAG_BLOB;
break;
case MYSQL_TYPE_BIT:
pack_flag= FIELDFLAG_NUMBER | FIELDFLAG_TREAT_BIT_AS_CHAR;
break;
default:
pack_flag= FIELDFLAG_NUMBER;
break;
}
/*
Set the pack flag correctly for the blob-like types. This sets the
packtype to something that make_field can use. If the pack type is
not set correctly, the packlength will be reeeeally wierd (like
129 or so).
*/
switch (sql_type_arg)
{
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_JSON:
/*
If you are going to use the above types, you have to pass a
pack_length as parameter. Assert that is really done.
*/
DBUG_ASSERT(pack_length_arg != ~0U);
pack_flag|= pack_length_to_packflag(pack_length_arg);
break;
default:
/* Nothing */
break;
}
pack_flag|=
(maybe_null ? FIELDFLAG_MAYBE_NULL : 0) |
(is_unsigned ? 0 : FIELDFLAG_DECIMAL);
gcol_info= 0;
stored_in_db= TRUE;
DBUG_PRINT("debug", ("pack_flag: %s%s%s%s%s%s%s, pack_type: %d",
FLAGSTR(pack_flag, FIELDFLAG_BINARY),
FLAGSTR(pack_flag, FIELDFLAG_NUMBER),
FLAGSTR(pack_flag, FIELDFLAG_INTERVAL),
FLAGSTR(pack_flag, FIELDFLAG_GEOM),
FLAGSTR(pack_flag, FIELDFLAG_BLOB),
FLAGSTR(pack_flag, FIELDFLAG_DECIMAL),
FLAGSTR(pack_flag, FIELDFLAG_JSON),
f_packtype(pack_flag)));
DBUG_VOID_RETURN;
}
/**
Initialize a column definition object. Column definition objects can be used
to construct Field objects.
@param thd Session/Thread handle.
@param fld_name Column name.
@param fld_type Column type.
@param fld_length Column length.
@param fld_decimals Number of digits to the right of the decimal
point (if any.)
@param fld_type_modifier Additional type information.
@param fld_default_value Column default expression (if any.)
@param fld_on_update_value The expression in the ON UPDATE clause.
@param fld_comment Column comment.
@param fld_change Column change.
@param fld_interval_list Interval list (if any.)
@param fld_charset Column charset.
@param fld_geom_type Column geometry type (if any.)
@param fld_gcol_info Generated column data
@retval
FALSE on success.
@retval
TRUE on error.
*/
bool Create_field::init(THD *thd, const char *fld_name,
enum_field_types fld_type, const char *fld_length,
const char *fld_decimals, uint fld_type_modifier,
Item *fld_default_value, Item *fld_on_update_value,
LEX_STRING *fld_comment, const char *fld_change,
List<String> *fld_interval_list,
const CHARSET_INFO *fld_charset, uint fld_geom_type,
Generated_column *fld_gcol_info)
{
uint sign_len, allowed_type_modifier= 0;
ulong max_field_charlength= MAX_FIELD_CHARLENGTH;
DBUG_ENTER("Create_field::init()");
field= 0;
field_name= fld_name;
flags= fld_type_modifier;
charset= fld_charset;
const bool on_update_is_function=
(fld_on_update_value != NULL &&
fld_on_update_value->type() == Item::FUNC_ITEM);
if (fld_default_value != NULL && fld_default_value->type() == Item::FUNC_ITEM)
{
// We have a function default for insertions.
def= NULL;
unireg_check= on_update_is_function ?
Field::TIMESTAMP_DNUN_FIELD : // for insertions and for updates.
Field::TIMESTAMP_DN_FIELD; // only for insertions.
}
else
{
// No function default for insertions. Either NULL or a constant.
def= fld_default_value;
if (on_update_is_function)
// We have a function default for updates only.
unireg_check= Field::TIMESTAMP_UN_FIELD;
else
// No function defaults.
unireg_check= (fld_type_modifier & AUTO_INCREMENT_FLAG) != 0 ?
Field::NEXT_NUMBER : // Automatic increment.
Field::NONE;
}
decimals= fld_decimals ? (uint)atoi(fld_decimals) : 0;
if (is_temporal_real_type(fld_type))
{
flags|= BINARY_FLAG;
charset= &my_charset_numeric;
if (decimals > DATETIME_MAX_DECIMALS)
{
my_error(ER_TOO_BIG_PRECISION, MYF(0),
decimals, fld_name, DATETIME_MAX_DECIMALS);
DBUG_RETURN(TRUE);
}
}
else if (decimals >= NOT_FIXED_DEC)
{
my_error(ER_TOO_BIG_SCALE, MYF(0), decimals, fld_name,
static_cast<ulong>(NOT_FIXED_DEC - 1));
DBUG_RETURN(TRUE);
}
sql_type= fld_type;
length= 0;
change= fld_change;
interval= 0;
pack_length= key_length= 0;
geom_type= (Field::geometry_type) fld_geom_type;
interval_list.empty();
comment= *fld_comment;
gcol_info= fld_gcol_info;
stored_in_db= TRUE;
/* Initialize data for a virtual field */
if (gcol_info)
{
DBUG_ASSERT(gcol_info->expr_item);
stored_in_db= gcol_info->get_field_stored();
/*
Perform per item-type checks to determine if the expression is
allowed for a generated column.
Note that validation of the specific function is done later in
procedures open_table_from_share and fix_fields_gcol_func
*/
switch (gcol_info->expr_item->type()) {
case Item::FUNC_ITEM:
if (((Item_func *)gcol_info->expr_item)->functype() ==
Item_func::FUNC_SP)
{
my_error(ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0),
field_name);
DBUG_RETURN(TRUE);
}
break;
case Item::COPY_STR_ITEM:
case Item::FIELD_AVG_ITEM:
case Item::PROC_ITEM:
case Item::REF_ITEM:
case Item::FIELD_STD_ITEM:
case Item::FIELD_VARIANCE_ITEM:
case Item::INSERT_VALUE_ITEM:
case Item::SUBSELECT_ITEM:
case Item::CACHE_ITEM:
case Item::TYPE_HOLDER:
case Item::PARAM_ITEM:
case Item::TRIGGER_FIELD_ITEM:
case Item::XPATH_NODESET:
case Item::XPATH_NODESET_CMP:
case Item::VIEW_FIXER_ITEM:
my_error(ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0),
field_name);
DBUG_RETURN(TRUE);
break;
default:
// Continue with the field creation
break;
}
/*
Make a field created for the real type.
Note that "real" and generated fields differ from each other
only by Field::gcol_info, which is always 0 for normal columns.
gcol_info is updated for fields later in procedure open_binary_frm.
*/
sql_type= fld_type= gcol_info->get_real_type();
}
/*
Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and
it is NOT NULL and not an AUTO_INCREMENT field.
*/
if (!fld_default_value &&
(fld_type_modifier & NOT_NULL_FLAG) &&
!(fld_type_modifier & AUTO_INCREMENT_FLAG))
{
/*
TIMESTAMP columns get implicit DEFAULT value when
explicit_defaults_for_timestamp is not set.
*/
if (thd->variables.explicit_defaults_for_timestamp ||
!is_timestamp_type(fld_type))
{
flags|= NO_DEFAULT_VALUE_FLAG;
}
}
if (fld_length != NULL)
{
errno= 0;
length= strtoul(fld_length, NULL, 10);
if ((errno != 0) || (length > MAX_FIELD_BLOBLENGTH))
{
my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name, MAX_FIELD_BLOBLENGTH);
DBUG_RETURN(TRUE);
}
if (length == 0)
fld_length= NULL; /* purecov: inspected */
}
sign_len= fld_type_modifier & UNSIGNED_FLAG ? 0 : 1;
switch (fld_type) {
case MYSQL_TYPE_TINY:
if (!fld_length)
length= MAX_TINYINT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_SHORT:
if (!fld_length)
length= MAX_SMALLINT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_INT24:
if (!fld_length)
length= MAX_MEDIUMINT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_LONG:
if (!fld_length)
length= MAX_INT_WIDTH+sign_len;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_LONGLONG:
if (!fld_length)
length= MAX_BIGINT_WIDTH;
allowed_type_modifier= AUTO_INCREMENT_FLAG;
break;
case MYSQL_TYPE_NULL:
break;
case MYSQL_TYPE_NEWDECIMAL:
{
ulong precision= static_cast<ulong>(length);
my_decimal_trim(&precision, &decimals);
length= precision;
}
if (length > DECIMAL_MAX_PRECISION)
{
my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<int>(length),
fld_name, static_cast<ulong>(DECIMAL_MAX_PRECISION));
DBUG_RETURN(TRUE);
}
if (length < decimals)
{
my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
length=
my_decimal_precision_to_length(length, decimals,
fld_type_modifier & UNSIGNED_FLAG);
pack_length=
my_decimal_get_binary_size(length, decimals);
break;
case MYSQL_TYPE_VARCHAR:
/*
Long VARCHAR's are automaticly converted to blobs in mysql_prepare_table
if they don't have a default value
*/
max_field_charlength= MAX_FIELD_VARCHARLENGTH;
break;
case MYSQL_TYPE_STRING:
break;
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_JSON:
if (fld_default_value)
{
/* Allow empty as default value. */
String str,*res;
res= fld_default_value->val_str(&str);
/*
A default other than '' is always an error, and any non-NULL
specified default is an error in strict mode.
*/
if (res->length() || thd->is_strict_mode())
{
my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0),
fld_name); /* purecov: inspected */
DBUG_RETURN(TRUE);
}
else
{
/*
Otherwise a default of '' is just a warning.
*/
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_BLOB_CANT_HAVE_DEFAULT,
ER(ER_BLOB_CANT_HAVE_DEFAULT),
fld_name);
}
def= 0;
}
flags|= BLOB_FLAG;
break;
case MYSQL_TYPE_YEAR:
if (!fld_length || length != 4)
length= 4; /* Default length */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
break;
case MYSQL_TYPE_FLOAT:
/* change FLOAT(precision) to FLOAT or DOUBLE */
allowed_type_modifier= AUTO_INCREMENT_FLAG;
if (fld_length && !fld_decimals)
{
size_t tmp_length= length;
if (tmp_length > PRECISION_FOR_DOUBLE)
{
my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
else if (tmp_length > PRECISION_FOR_FLOAT)
{
sql_type= MYSQL_TYPE_DOUBLE;
length= MAX_DOUBLE_STR_LENGTH;
}
else
length= MAX_FLOAT_STR_LENGTH;
decimals= NOT_FIXED_DEC;
break;
}
if (!fld_length && !fld_decimals)
{
length= MAX_FLOAT_STR_LENGTH;
decimals= NOT_FIXED_DEC;
}
if (length < decimals &&
decimals != NOT_FIXED_DEC)
{
my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
break;
case MYSQL_TYPE_DOUBLE:
allowed_type_modifier= AUTO_INCREMENT_FLAG;
if (!fld_length && !fld_decimals)
{
length= DBL_DIG+7;
decimals= NOT_FIXED_DEC;
}
if (length < decimals &&
decimals != NOT_FIXED_DEC)
{
my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
break;
case MYSQL_TYPE_TIMESTAMP:
/* Add flags for TIMESTAMP for 4.0 MYD and 4.0 InnoDB compatibility */
flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
/* Fall through */
case MYSQL_TYPE_TIMESTAMP2:
if (fld_length == NULL)
{
length= MAX_DATETIME_WIDTH + (decimals ? (1 + decimals) : 0);
}
else if (length != MAX_DATETIME_WIDTH)
{
/*
We support only even TIMESTAMP lengths less or equal than 14
and 19 as length of 4.1 compatible representation. Silently
shrink it to MAX_DATETIME_COMPRESSED_WIDTH.
*/
DBUG_ASSERT(MAX_DATETIME_COMPRESSED_WIDTH < UINT_MAX);
if (length != UINT_MAX) /* avoid overflow; is safe because of min() */
length= ((length+1)/2)*2;
length= min<size_t>(length, MAX_DATETIME_COMPRESSED_WIDTH);
}
/*
Since we silently rewrite down to MAX_DATETIME_COMPRESSED_WIDTH bytes,
the parser should not raise errors unless bizzarely large.
*/
max_field_charlength= UINT_MAX;
break;
case MYSQL_TYPE_DATE:
/* Old date type. */
sql_type= MYSQL_TYPE_NEWDATE;
/* fall through */
case MYSQL_TYPE_NEWDATE:
length= MAX_DATE_WIDTH;
break;
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_TIME2:
length= MAX_TIME_WIDTH + (decimals ? (1 + decimals) : 0);
break;
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_DATETIME2:
length= MAX_DATETIME_WIDTH + (decimals ? (1 + decimals) : 0);
break;
case MYSQL_TYPE_SET:
{
pack_length= get_set_pack_length(fld_interval_list->elements);
List_iterator<String> it(*fld_interval_list);
String *tmp;
while ((tmp= it++))
interval_list.push_back(tmp);
/*
Set fake length to 1 to pass the below conditions.
Real length will be set in mysql_prepare_table()
when we know the character set of the column
*/
length= 1;
break;
}
case MYSQL_TYPE_ENUM:
{
/* Should be safe. */
pack_length= get_enum_pack_length(fld_interval_list->elements);
List_iterator<String> it(*fld_interval_list);
String *tmp;
while ((tmp= it++))
interval_list.push_back(tmp);
length= 1; /* See comment for MYSQL_TYPE_SET above. */
break;
}
case MYSQL_TYPE_VAR_STRING:
DBUG_ASSERT(0); /* Impossible. */
break;
case MYSQL_TYPE_BIT:
{
if (!fld_length)
{
my_error(ER_INVALID_FIELD_SIZE, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
if (length > MAX_BIT_FIELD_LENGTH)
{
my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name,
static_cast<ulong>(MAX_BIT_FIELD_LENGTH));
DBUG_RETURN(TRUE);
}
pack_length= (length + 7) / 8;
break;
}
case MYSQL_TYPE_DECIMAL:
DBUG_ASSERT(0); /* Was obsolete */
}
/* Remember the value of length */
char_length= length;
if (!(flags & BLOB_FLAG) &&
((length > max_field_charlength && fld_type != MYSQL_TYPE_SET &&
fld_type != MYSQL_TYPE_ENUM &&
(fld_type != MYSQL_TYPE_VARCHAR || fld_default_value)) ||
((length == 0) &&
fld_type != MYSQL_TYPE_STRING &&
fld_type != MYSQL_TYPE_VARCHAR && fld_type != MYSQL_TYPE_GEOMETRY)))
{
my_error((fld_type == MYSQL_TYPE_VAR_STRING ||
fld_type == MYSQL_TYPE_VARCHAR ||
fld_type == MYSQL_TYPE_STRING) ? ER_TOO_BIG_FIELDLENGTH :
ER_TOO_BIG_DISPLAYWIDTH,
MYF(0),
fld_name, max_field_charlength); /* purecov: inspected */
DBUG_RETURN(TRUE);
}
fld_type_modifier&= AUTO_INCREMENT_FLAG;
if ((~allowed_type_modifier) & fld_type_modifier)
{
my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
DBUG_RETURN(TRUE);
}
DBUG_RETURN(FALSE); /* success */
}
enum_field_types get_blob_type_from_length(ulong length)
{
enum_field_types type;
if (length < 256)
type= MYSQL_TYPE_TINY_BLOB;
else if (length < 65536)
type= MYSQL_TYPE_BLOB;
else if (length < 256L*256L*256L)
type= MYSQL_TYPE_MEDIUM_BLOB;
else
type= MYSQL_TYPE_LONG_BLOB;
return type;
}
/*
Make a field from the .frm file info
*/
size_t calc_pack_length(enum_field_types type, size_t length)
{
switch (type) {
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_DECIMAL: return (length);
case MYSQL_TYPE_VARCHAR: return (length + (length < 256 ? 1: 2));
case MYSQL_TYPE_YEAR:
case MYSQL_TYPE_TINY : return 1;
case MYSQL_TYPE_SHORT : return 2;
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_NEWDATE: return 3;
case MYSQL_TYPE_TIME: return 3;
case MYSQL_TYPE_TIME2:
return length > MAX_TIME_WIDTH ?
my_time_binary_length(length - MAX_TIME_WIDTH - 1) : 3;
case MYSQL_TYPE_TIMESTAMP: return 4;
case MYSQL_TYPE_TIMESTAMP2:
return length > MAX_DATETIME_WIDTH ?
my_timestamp_binary_length(length - MAX_DATETIME_WIDTH - 1) : 4;
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_LONG : return 4;
case MYSQL_TYPE_FLOAT : return sizeof(float);
case MYSQL_TYPE_DOUBLE: return sizeof(double);
case MYSQL_TYPE_DATETIME: return 8;
case MYSQL_TYPE_DATETIME2:
return length > MAX_DATETIME_WIDTH ?
my_datetime_binary_length(length - MAX_DATETIME_WIDTH - 1) : 5;
case MYSQL_TYPE_LONGLONG: return 8; /* Don't crash if no longlong */
case MYSQL_TYPE_NULL : return 0;
case MYSQL_TYPE_TINY_BLOB: return 1+portable_sizeof_char_ptr;
case MYSQL_TYPE_BLOB: return 2+portable_sizeof_char_ptr;
case MYSQL_TYPE_MEDIUM_BLOB: return 3+portable_sizeof_char_ptr;
case MYSQL_TYPE_LONG_BLOB: return 4+portable_sizeof_char_ptr;
case MYSQL_TYPE_GEOMETRY: return 4+portable_sizeof_char_ptr;
case MYSQL_TYPE_JSON: return 4+portable_sizeof_char_ptr;
case MYSQL_TYPE_SET:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_NEWDECIMAL:
abort(); return 0; // This shouldn't happen
case MYSQL_TYPE_BIT: return length / 8;
default:
return 0;
}
}
uint pack_length_to_packflag(uint type)
{
switch (type) {
case 1: return f_settype((uint) MYSQL_TYPE_TINY);
case 2: return f_settype((uint) MYSQL_TYPE_SHORT);
case 3: return f_settype((uint) MYSQL_TYPE_INT24);
case 4: return f_settype((uint) MYSQL_TYPE_LONG);
case 8: return f_settype((uint) MYSQL_TYPE_LONGLONG);
}
return 0; // This shouldn't happen
}
Field *make_field(TABLE_SHARE *share, uchar *ptr, size_t field_length,
uchar *null_pos, uchar null_bit,
uint pack_flag,
enum_field_types field_type,
const CHARSET_INFO *field_charset,
Field::geometry_type geom_type,
Field::utype unireg_check,
TYPELIB *interval,
const char *field_name)
{
uchar *bit_ptr= NULL;
uchar bit_offset= 0;
if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
{
bit_ptr= null_pos;
bit_offset= null_bit;
if (f_maybe_null(pack_flag)) // if null field
{
bit_ptr+= (null_bit == 7); // shift bit_ptr and bit_offset
bit_offset= (bit_offset + 1) & 7;
}
}
if (!f_maybe_null(pack_flag))
{
null_pos=0;
null_bit=0;
}
else
{
null_bit= ((uchar) 1) << null_bit;
}
if (is_temporal_real_type(field_type))
field_charset= &my_charset_numeric;
DBUG_PRINT("debug", ("field_type: %d, field_length: %zu, "
"interval: %p, pack_flag: %s%s%s%s%s",
field_type, field_length, interval,
FLAGSTR(pack_flag, FIELDFLAG_BINARY),
FLAGSTR(pack_flag, FIELDFLAG_INTERVAL),
FLAGSTR(pack_flag, FIELDFLAG_NUMBER),
FLAGSTR(pack_flag, FIELDFLAG_PACK),
FLAGSTR(pack_flag, FIELDFLAG_BLOB)));
if (f_is_alpha(pack_flag))
{
if (!f_is_packed(pack_flag))
{
if (field_type == MYSQL_TYPE_STRING ||
field_type == MYSQL_TYPE_DECIMAL || // 3.23 or 4.0 string
field_type == MYSQL_TYPE_VAR_STRING)
return new Field_string(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
field_charset);
if (field_type == MYSQL_TYPE_VARCHAR)
return new Field_varstring(ptr,field_length,
HA_VARCHAR_PACKLENGTH(field_length),
null_pos,null_bit,
unireg_check, field_name,
share,
field_charset);
return 0; // Error
}
uint pack_length=calc_pack_length((enum_field_types)
f_packtype(pack_flag),
field_length);
if (f_is_geom(pack_flag))
return new Field_geom(ptr,null_pos,null_bit,
unireg_check, field_name, share,
pack_length, geom_type);
if (f_is_json(pack_flag))
return new Field_json(ptr, null_pos, null_bit,
unireg_check, field_name, share,
pack_length);
if (f_is_blob(pack_flag))
return new Field_blob(ptr,null_pos,null_bit,
unireg_check, field_name, share,
pack_length, field_charset);
if (interval)
{
if (f_is_enum(pack_flag))
return new Field_enum(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
pack_length, interval, field_charset);
else
return new Field_set(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
pack_length, interval, field_charset);
}
}
switch (field_type) {
case MYSQL_TYPE_DECIMAL:
return new Field_decimal(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_NEWDECIMAL:
return new Field_new_decimal(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_FLOAT:
return new Field_float(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag)== 0);
case MYSQL_TYPE_DOUBLE:
return new Field_double(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_decimals(pack_flag),
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag)== 0);
case MYSQL_TYPE_TINY:
return new Field_tiny(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_SHORT:
return new Field_short(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_INT24:
return new Field_medium(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_LONG:
return new Field_long(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_LONGLONG:
return new Field_longlong(ptr,field_length,null_pos,null_bit,
unireg_check, field_name,
f_is_zerofill(pack_flag) != 0,
f_is_dec(pack_flag) == 0);
case MYSQL_TYPE_TIMESTAMP:
return new Field_timestamp(ptr, field_length, null_pos, null_bit,
unireg_check, field_name);
case MYSQL_TYPE_TIMESTAMP2:
return new Field_timestampf(ptr, null_pos, null_bit,
unireg_check, field_name,
field_length > MAX_DATETIME_WIDTH ?
field_length - 1 - MAX_DATETIME_WIDTH : 0);
case MYSQL_TYPE_YEAR:
return new Field_year(ptr,field_length,null_pos,null_bit,
unireg_check, field_name);
case MYSQL_TYPE_NEWDATE:
return new Field_newdate(ptr, null_pos, null_bit, unireg_check, field_name);
case MYSQL_TYPE_TIME:
return new Field_time(ptr, null_pos, null_bit,
unireg_check, field_name);
case MYSQL_TYPE_TIME2:
return new Field_timef(ptr, null_pos, null_bit,
unireg_check, field_name,
(field_length > MAX_TIME_WIDTH) ?
field_length - 1 - MAX_TIME_WIDTH : 0);
case MYSQL_TYPE_DATETIME:
return new Field_datetime(ptr, null_pos, null_bit,
unireg_check, field_name);
case MYSQL_TYPE_DATETIME2:
return new Field_datetimef(ptr, null_pos, null_bit,
unireg_check, field_name,
(field_length > MAX_DATETIME_WIDTH) ?
field_length - 1 - MAX_DATETIME_WIDTH : 0);
case MYSQL_TYPE_NULL:
return new Field_null(ptr, field_length, unireg_check, field_name,
field_charset);
case MYSQL_TYPE_BIT:
return f_bit_as_char(pack_flag) ?
new Field_bit_as_char(ptr, field_length, null_pos, null_bit,
unireg_check, field_name) :
new Field_bit(ptr, field_length, null_pos, null_bit, bit_ptr,
bit_offset, unireg_check, field_name);
default: // Impossible (Wrong version)
break;
}
return 0;
}
/**
Constructs a column definition from an actual column object. This is a
reverse-engineering procedure that creates a column definition object as
produced by the parser (Create_field) from a resolved column object
(Field).
@param old_field The column object from which the column definition is
constructed.
@param orig_field Used for copying default values. This parameter may be
NULL, but if present it is used for copying default
values.
Default values are copied into an Item_string unless:
@li The default value is a function.
@li There is no default value.
@li old_field is a BLOB column.
@li old_field has its data pointer improperly initialized.
*/
Create_field::Create_field(Field *old_field,Field *orig_field) :
field_name(old_field->field_name),
change(NULL),
comment(old_field->comment),
sql_type(old_field->real_type()),
length(old_field->field_length),
decimals(old_field->decimals()),
flags(old_field->flags),
pack_length(old_field->pack_length()),
key_length(old_field->key_length()),
unireg_check(old_field->unireg_check),
charset(old_field->charset()), // May be NULL ptr
field(old_field),
gcol_info(old_field->gcol_info),
stored_in_db(old_field->stored_in_db)
{
switch (sql_type) {
case MYSQL_TYPE_BLOB:
switch (pack_length - portable_sizeof_char_ptr) {
case 1: sql_type= MYSQL_TYPE_TINY_BLOB; break;
case 2: sql_type= MYSQL_TYPE_BLOB; break;
case 3: sql_type= MYSQL_TYPE_MEDIUM_BLOB; break;
default: sql_type= MYSQL_TYPE_LONG_BLOB; break;
}
length/= charset->mbmaxlen;
key_length/= charset->mbmaxlen;
break;
case MYSQL_TYPE_STRING:
/* Change CHAR -> VARCHAR if dynamic record length */
if (old_field->type() == MYSQL_TYPE_VAR_STRING)
sql_type= MYSQL_TYPE_VARCHAR;
/* fall through */
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
/* This is corrected in create_length_to_internal_length */
length= (length+charset->mbmaxlen-1) / charset->mbmaxlen;
break;
case MYSQL_TYPE_GEOMETRY:
geom_type= ((Field_geom*)old_field)->geom_type;
break;
case MYSQL_TYPE_YEAR:
if (length != 4)
length= 4; //set default value
break;
default:
break;
}
if (flags & (ENUM_FLAG | SET_FLAG))
interval= ((Field_enum*) old_field)->typelib;
else
interval=0;
def=0;
char_length= length;
/*
Copy the default (constant/function) from the column object orig_field, if
supplied. We do this if all these conditions are met:
- The column allows a default.
- The column type is not a BLOB type.
- The original column (old_field) was properly initialized with a record
buffer pointer.
*/
if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) &&
old_field->ptr != NULL &&
orig_field != NULL)
{
bool default_now= false;
if (real_type_with_now_as_default(sql_type))
{
// The SQL type of the new field allows a function default:
default_now= orig_field->has_insert_default_function();
bool update_now= orig_field->has_update_default_function();
if (default_now && update_now)
unireg_check= Field::TIMESTAMP_DNUN_FIELD;
else if (default_now)
unireg_check= Field::TIMESTAMP_DN_FIELD;
else if (update_now)
unireg_check= Field::TIMESTAMP_UN_FIELD;
}
if (!default_now) // Give a constant default
{
char buff[MAX_FIELD_WIDTH];
String tmp(buff,sizeof(buff), charset);
/* Get the value from default_values */
my_ptrdiff_t diff= orig_field->table->default_values_offset();
orig_field->move_field_offset(diff); // Points now at default_values
if (!orig_field->is_real_null())
{
char buff[MAX_FIELD_WIDTH], *pos;
String tmp(buff, sizeof(buff), charset), *res;
res= orig_field->val_str(&tmp);
pos= sql_strmake(res->ptr(), res->length());
def= new Item_string(pos, res->length(), charset);
}
orig_field->move_field_offset(-diff); // Back to record[0]
}
}
}
/**
maximum possible character length for blob.
This method is used in Item_field::set_field to calculate
max_length for Item.
For example:
CREATE TABLE t2 SELECT CONCAT(tinyblob_utf8_column) FROM t1;
must create a "VARCHAR(255) CHARACTER SET utf8" column.
@return
length
*/
uint32 Field_blob::char_length()
{
switch (packlength)
{
case 1:
return 255;
case 2:
return 65535;
case 3:
return 16777215;
case 4:
return (uint32) 4294967295U;
default:
DBUG_ASSERT(0); // we should never go here
return 0;
}
}
/**
This function creates a separate copy of blob value.
@param [in] mem_root
mem_root that is used to allocate memory for 'copy_of_value'.
@return - Can fail if we are out of memory.
@retval false Success
@retval true Failure
*/
bool Field_blob::copy_blob_value(MEM_ROOT *mem_root)
{
DBUG_ENTER("copy_blob_value");
// Testing memory allocation failure
DBUG_EXECUTE_IF("simulate_blob_memory_allocation_fail",
DBUG_SET("+d,simulate_out_of_memory"););
// Allocate new memory location
size_t ulen= get_length(ptr);
char *blob_value= (char *) alloc_root(mem_root, ulen);
if (!blob_value)
DBUG_RETURN(true);
// Copy Data
uchar *temp_ptr;
get_ptr(&temp_ptr);
memcpy(blob_value, temp_ptr, ulen);
// Set ptr of Field for duplicated data
store_ptr_and_length(blob_value, ulen);
// Set 'value' with the duplicated data
value.set(blob_value, ulen, value.charset());
DBUG_RETURN(false);
}
/**
maximum possible display length for blob.
@return
length
*/
uint32 Field_blob::max_display_length()
{
switch (packlength)
{
case 1:
return 255 * field_charset->mbmaxlen;
case 2:
return 65535 * field_charset->mbmaxlen;
case 3:
return 16777215 * field_charset->mbmaxlen;
case 4:
return (uint32) 4294967295U;
default:
DBUG_ASSERT(0); // we should never go here
return 0;
}
}
/*****************************************************************************
Warning handling
*****************************************************************************/
/**
Produce warning or note about data saved into field.
@param level - level of message (Note/Warning/Error)
@param code - error code of message to be produced
@param cut_increment - whenever we should increase cut fields count
@param view_db_name - if set this is the database name for view
that causes the warning
@param view_name - if set this is the name of view that causes
the warning
@note
This function won't produce warning and increase cut fields counter
if count_cuted_fields == CHECK_FIELD_IGNORE for current thread.
if count_cuted_fields == CHECK_FIELD_IGNORE then we ignore notes.
This allows us to avoid notes in optimisation, like convert_constant_item().
In case of execution statements INSERT/INSERT SELECT/REPLACE/REPLACE SELECT
the method emits only one warning message for the following
types of warning: ER_BAD_NULL_ERROR, ER_WARN_NULL_TO_NOTNULL,
ER_NO_DEFAULT_FOR_FIELD.
@retval
1 if count_cuted_fields == CHECK_FIELD_IGNORE and error level is not NOTE
@retval
0 otherwise
*/
bool Field::set_warning(Sql_condition::enum_severity_level level,
uint code,
int cut_increment,
const char *view_db_name,
const char *view_name)
{
/*
If this field was created only for type conversion purposes it
will have table == NULL.
*/
THD *thd= table ? table->in_use : current_thd;
if (!thd->count_cuted_fields)
return level >= Sql_condition::SL_WARNING;
thd->cuted_fields+= cut_increment;
if (thd->lex->sql_command != SQLCOM_INSERT &&
thd->lex->sql_command != SQLCOM_INSERT_SELECT &&
thd->lex->sql_command != SQLCOM_REPLACE &&
thd->lex->sql_command != SQLCOM_REPLACE_SELECT)
{
// We aggregate warnings from only INSERT and REPLACE statements.
push_warning_printf(thd, level, code, ER(code), field_name,
thd->get_stmt_da()->current_row_for_condition());
return 0;
}
unsigned int current_warning_mask= 0;
if (code == ER_BAD_NULL_ERROR)
current_warning_mask= BAD_NULL_ERROR_PUSHED;
else if (code == ER_NO_DEFAULT_FOR_FIELD)
current_warning_mask= NO_DEFAULT_FOR_FIELD_PUSHED;
if (current_warning_mask)
{
if (!(m_warnings_pushed & current_warning_mask))
{
push_warning_printf(thd, level, code, ER(code), field_name,
thd->get_stmt_da()->current_row_for_condition());
m_warnings_pushed|= current_warning_mask;
}
}
else if (code == ER_NO_DEFAULT_FOR_VIEW_FIELD)
{
if (!(m_warnings_pushed & NO_DEFAULT_FOR_VIEW_FIELD_PUSHED))
{
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_NO_DEFAULT_FOR_VIEW_FIELD,
ER(ER_NO_DEFAULT_FOR_VIEW_FIELD),
view_db_name,
view_name);
m_warnings_pushed|= NO_DEFAULT_FOR_VIEW_FIELD_PUSHED;
}
}
else
{
push_warning_printf(thd, level, code, ER(code), field_name,
thd->get_stmt_da()->current_row_for_condition());
}
return 0;
}
/**
Produce warning or note about double datetime data saved into field.
@param level level of message (Note/Warning/Error)
@param code error code of message to be produced
@param val error parameter (the value)
@param ts_type type of datetime value (datetime/date/time)
@param cut_increment whenever we should increase cut fields count
@note
This function will always produce some warning but won't increase cut
fields counter if count_cuted_fields == FIELD_CHECK_IGNORE for current
thread.
*/
void
Field_temporal::set_datetime_warning(Sql_condition::enum_severity_level level,
uint code,
ErrConvString val,
timestamp_type ts_type,
int cut_increment)
{
THD *thd= table ? table->in_use : current_thd;
if ((!thd->lex->is_ignore() &&
((thd->variables.sql_mode & MODE_STRICT_ALL_TABLES) ||
(thd->variables.sql_mode & MODE_STRICT_TRANS_TABLES &&
!thd->get_transaction()->cannot_safely_rollback(Transaction_ctx::STMT)))) ||
set_warning(level, code, cut_increment))
make_truncated_value_warning(thd, level, val, ts_type, field_name);
}
bool Field::is_part_of_actual_key(THD *thd, uint cur_index, KEY *cur_index_info)
{
return
thd->optimizer_switch_flag(OPTIMIZER_SWITCH_USE_INDEX_EXTENSIONS) &&
!(cur_index_info->flags & HA_NOSAME) ?
part_of_key.is_set(cur_index) :
part_of_key_not_extended.is_set(cur_index);
}
| 29.180403 | 112 | 0.653967 | [
"geometry",
"object",
"vector"
] |
c8a9d8cd1e0ed41a2562e1548bbd725084121d37 | 4,491 | cpp | C++ | solved/o-q/opening-doors/doors.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/o-q/opening-doors/doors.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/o-q/opening-doors/doors.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define MAXLEN 101
#define crFor(t,v,c) \
for(t::const_reverse_iterator v=c.rbegin(); v != c.rend(); ++v)
typedef vector<int> IV;
typedef IV::iterator IVi;
//
// Big Integer
//
#define BIBAS 1000
#define BIDIG 3
#define BIFMT "%03d"
struct Bigint {
IV d; bool sgn;
Bigint(int n=0) {
if (n < 0) sgn = true, n = -n; else sgn = false;
if (n < BIBAS) d.push_back(n);
else while (n != 0) { d.push_back(n % BIBAS); n /= BIBAS; }
}
Bigint(const char *s) {
if (*s == '-') sgn = true, s++; else sgn = false;
for (int end = strlen(s), i = max(0, end-BIDIG); true;) {
int n = 0; for (int j=i; j != end; j++) n = n*10 + s[j] - '0';
d.push_back(n); if (i == 0) break;
end = i, i = max(0, i-BIDIG);
} clean();
}
size_t len() const { return d.size(); }
bool is_zero() const { return len() == 1 && d[0] == 0; }
void flip() { sgn = !sgn; }
Bigint neg() const { Bigint x = *this; x.flip(); return x; }
bool operator==(const Bigint &b) const {
return sgn == b.sgn && d == b.d;
}
bool operator<(const Bigint &b) const {
if (sgn != b.sgn) return sgn;
if (len() != b.len()) return sgn ^ (len() < b.len());
for (int i = len() - 1; i >= 0; --i)
if (d[i] != b.d[i]) return sgn ^ (d[i] < b.d[i]);
return false;
}
bool operator<=(const Bigint &x) const { return *this == x || *this < x; }
bool operator>(const Bigint &x) const { return !(*this <= x); }
Bigint &operator+=(const Bigint &b) {
if (sgn != b.sgn) { (*this) -= b.neg(); return *this; }
int s1 = len(), s2 = b.len(), s3 = max(s1, s2) + 1;
IV res(s3); int c = 0;
for (int i = 0; i < s3; ++i) {
int sum = c;
sum += i < s1 ? d[i] : 0;
sum += i < s2 ? b.d[i] : 0;
if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0;
res[i] = sum;
}
d = res; clean();
return *this;
}
Bigint &operator-=(const Bigint &b) {
if (sgn != b.sgn) { (*this) += b.neg(); return *this; }
if (*this < b) { Bigint x = b; x -= *this; return *this = x.neg(); }
int s1 = len(), s2 = b.len(), s3 = s1;
IV res(s3); int c = 0;
for (int i = 0; i < s3; ++i) {
int sum = d[i] - (i < s2 ? b.d[i] : 0) - c;
if (sum < 0) { sum += BIBAS; c = 1; } else c = 0;
res[i] = sum;
}
d = res; clean();
return *this;
}
Bigint &operator*=(const Bigint &b) {
int s1 = len(), s2 = b.len(), s3 = s1+s2;
IV res(s3); int c = 0;
for (int k=0; k < s3; ++k) {
int sum = c;
for (int i=max(0,k-s2+1), I=min(k+1, s1), j=k-i; i < I; ++i, --j)
sum += d[i] * b.d[j];
if (sum >= BIBAS) { c = sum / BIBAS; sum %= BIBAS; } else c = 0;
res[k] = sum;
}
d = res; sgn ^= b.sgn; clean();
return *this;
}
Bigint &short_div(int b) {
for (int r = 0, i = len() - 1; i >= 0; --i)
r = r*BIBAS + d[i], d[i] = r / b, r %= b;
clean(); return *this;
}
void clean() {
IVi i; for (i=d.end()-1; *i == 0 && i != d.begin(); i--);
d.erase(i+1, d.end());
if (sgn && d.size() == 1 && d[0] == 0) sgn = false;
}
void println() {
if (sgn) putchar('-');
bool flg = true;
crFor (IV, i, d) {
if (flg) { printf("%d", *i); flg=false; }
else printf(BIFMT, *i);
} putchar('\n');
}
};
Bigint ans;
Bigint N;
Bigint One(1);
char numstr[MAXLEN + 1];
void solve()
{
Bigint lo = One;
Bigint hi = N;
while (true) {
Bigint mid = lo;
mid += hi;
mid.short_div(2);
Bigint mid2 = mid;
mid2 *= mid;
Bigint suc = mid2; // (mid + 1)^2
suc += mid;
suc += mid;
suc += One;
if (mid2 <= N && suc > N) {
ans = mid2;
return;
}
if (mid2 < N) {
lo = mid;
lo += One;
}
else {
hi = mid;
hi -= One;
}
}
}
int main()
{
while (true) {
scanf("%s", numstr);
N = Bigint(numstr);
if (N.is_zero()) break;
solve();
ans.println();
}
return 0;
}
| 26.417647 | 78 | 0.421732 | [
"vector"
] |
c8ac76275e8536a37d5211337664164948f14788 | 1,353 | cpp | C++ | Game/player.cpp | benbancroft/2DEngine | 56aa3ecd388bac3ad3e036a750749b2399d2ed12 | [
"MIT"
] | null | null | null | Game/player.cpp | benbancroft/2DEngine | 56aa3ecd388bac3ad3e036a750749b2399d2ed12 | [
"MIT"
] | null | null | null | Game/player.cpp | benbancroft/2DEngine | 56aa3ecd388bac3ad3e036a750749b2399d2ed12 | [
"MIT"
] | null | null | null | #include "player.h"
void Player::Loaded(Core::Engine* engine){
Entity::Loaded(engine);
Maths::Vector2<int> res = engine->GetResolution();
x = res.GetX()/2;
y = res.GetY()/2;
speed = 0;
//SetAlarm(0, 150);
}
void Player::Tick(Core::Engine *engine){
Entity::Tick(engine);
if (hasTarget){
double distance = Maths::distanceBetweenPoints(Maths::Vector2<double>(x, y), target);
if (distance <= speed){
speed = 0;
x = target.GetX();
y = target.GetY();
hasTarget = false;
}
}
}
void Player::Render(Core::Render *render){
Entity::Render(render);
}
void Player::Alarm(int index){
if (index == 0){
DEBUG_LOG_WRITE_V("Alarm", "Alarm Entity");
SetAlarm(0, 150);
}
}
void Player::OnTouchPress(double x, double y){
speed = 0.5;
target = Maths::Vector2<double>(x, y);
hasTarget = true;
this->DirectTowards(target);
//this->x = target.GetX();
//this->y = target.GetY();
DEBUG_LOG_WRITE_V("Tick", "Press again");
DEBUG_LOG_PRINT_V("Engine", "press X: %f Y: %f current X: %f Y: %f angle: %f", x, y, this->x, this->y, this->direction);
}
void Player::OnTouchDrag(double x, double y){
DEBUG_LOG_WRITE_V("Tick", "Drag again");
DEBUG_LOG_PRINT_V("Engine", "drag X: %f Y: %f", x, y);
}
| 22.55 | 124 | 0.577236 | [
"render"
] |
c8adefea03905797a7f14eab167e77ab69a281ae | 1,308 | cpp | C++ | impl/src/gui_fltk.cpp | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null | impl/src/gui_fltk.cpp | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null | impl/src/gui_fltk.cpp | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null |
#include "gui_fltk.h"
#include "fltk_wrapper.h"
#include <stdlib.h>
#include <memory>
Gui_FLTK::Gui_FLTK(int _argc, char *_argv[], Model &md):ControllerInterface{_argc, _argv, md}{
}
Gui_FLTK::~Gui_FLTK(){
}
bool Gui_FLTK::run() {
std::unique_ptr<Fl_Double_Window> window = std::make_unique<Fl_Double_Window>(400,320,argv[0]);
std::unique_ptr<Fl_Box> box = std::make_unique<Fl_Box>(FL_ENGRAVED_FRAME,10,10,300,300,
"MINIMUM UPDATE TEST\n"
"\n"
"The slider on the right purposely\n"
"draws outside it's boundaries.\n"
"Moving it should leave old copies\n"
"of the label. These copies should\n"
"*not* be erased by any actions\n"
"other than hiding and showing\n"
"of that portion of the window\n"
"or changing the button that\n"
"intesects them.");
window->resizable(box.get());
std::unique_ptr<Fl_Slider> slider = std::make_unique<Fl_Slider>(320,10,20,300,"Too_Big_Label");
slider->align(0);
std::unique_ptr<Fl_Button> btn1 = std::make_unique<Fl_Button>(20,270,100,30,"Button");
std::unique_ptr<Fl_Return_Button> btn2 = std::make_unique<Fl_Return_Button>(200,270,100,30,"Button");
window->show(argc, argv);
int finish = Fl::run();
(void)finish;
return false;
}
| 27.829787 | 105 | 0.655963 | [
"model"
] |
c8b1dad8f0abd80c5f03e13238bf15f2d4d40364 | 21,852 | cc | C++ | DQM/Phase2OuterTracker/plugins/OuterTrackerMonitorTTStub.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DQM/Phase2OuterTracker/plugins/OuterTrackerMonitorTTStub.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DQM/Phase2OuterTracker/plugins/OuterTrackerMonitorTTStub.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | // -*- C++ -*-
//
// Package: Phase2OuterTracker
// Class: Phase2OuterTracker
//
/**\class Phase2OuterTracker OuterTrackerMonitorTTStub.cc DQM/Phase2OuterTracker/plugins/OuterTrackerMonitorTTStub.cc
Description: [one line class summary]
Implementation:
[Notes on implementation]
*/
//
// Original Author: Isis Marina Van Parijs
// Created: Fri, 24 Oct 2014 12:31:31 GMT
// $Id$
//
//
// system include files
#include <memory>
#include <vector>
#include <numeric>
#include <iostream>
#include <fstream>
// user include files
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "DQM/Phase2OuterTracker/interface/OuterTrackerMonitorTTStub.h"
#include "DataFormats/L1TrackTrigger/interface/TTStub.h"
#include "DataFormats/SiStripDetId/interface/StripSubdetector.h"
#include "DataFormats/TrackerCommon/interface/TrackerTopology.h"
#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
#include "Geometry/CommonDetUnit/interface/GeomDet.h"
#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
#include "Geometry/TrackerGeometryBuilder/interface/StripGeomDetUnit.h"
//
// constructors and destructor
//
OuterTrackerMonitorTTStub::OuterTrackerMonitorTTStub(const edm::ParameterSet& iConfig)
: dqmStore_(edm::Service<DQMStore>().operator->()), conf_(iConfig)
{
//now do what ever initialization is needed
topFolderName_ = conf_.getParameter<std::string>("TopFolderName");
tagTTStubsToken_ = consumes<edmNew::DetSetVector< TTStub< Ref_Phase2TrackerDigi_ > > > (conf_.getParameter<edm::InputTag>("TTStubs") );
}
OuterTrackerMonitorTTStub::~OuterTrackerMonitorTTStub()
{
// do anything here that needs to be done at desctruction time
// (e.g. close files, deallocate resources etc.)
}
//
// member functions
//
// ------------ method called for each event ------------
void
OuterTrackerMonitorTTStub::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
{
/// Track Trigger Stubs
edm::Handle< edmNew::DetSetVector< TTStub< Ref_Phase2TrackerDigi_ > > > Phase2TrackerDigiTTStubHandle;
iEvent.getByToken( tagTTStubsToken_, Phase2TrackerDigiTTStubHandle );
/// Geometry
edm::ESHandle<TrackerTopology> tTopoHandle;
const TrackerTopology* tTopo;
iSetup.get< TrackerTopologyRcd >().get(tTopoHandle);
tTopo = tTopoHandle.product();
edm::ESHandle< TrackerGeometry > tGeometryHandle;
const TrackerGeometry* theTrackerGeometry;
iSetup.get< TrackerDigiGeometryRecord >().get( tGeometryHandle );
theTrackerGeometry = tGeometryHandle.product();
/// Loop over input Stubs
typename edmNew::DetSetVector< TTStub< Ref_Phase2TrackerDigi_ > >::const_iterator inputIter;
typename edmNew::DetSet< TTStub< Ref_Phase2TrackerDigi_ > >::const_iterator contentIter;
//Adding protection
if ( !Phase2TrackerDigiTTStubHandle.isValid() ) return;
for ( inputIter = Phase2TrackerDigiTTStubHandle->begin();
inputIter != Phase2TrackerDigiTTStubHandle->end();
++inputIter )
{
for ( contentIter = inputIter->begin(); contentIter != inputIter->end(); ++contentIter )
{
/// Make reference stub
edm::Ref< edmNew::DetSetVector< TTStub< Ref_Phase2TrackerDigi_ > >, TTStub< Ref_Phase2TrackerDigi_ > > tempStubRef = edmNew::makeRefTo( Phase2TrackerDigiTTStubHandle, contentIter );
/// Get det ID (place of the stub)
// tempStubRef->getDetId() gives the stackDetId, not rawId
DetId detIdStub = theTrackerGeometry->idToDet( (tempStubRef->getClusterRef(0))->getDetId() )->geographicalId();
/// Get trigger displacement/offset
double displStub = tempStubRef->getTriggerDisplacement();
double offsetStub = tempStubRef->getTriggerOffset();
/// Define position stub by position inner cluster
MeasurementPoint mp = (tempStubRef->getClusterRef(0))->findAverageLocalCoordinates();
const GeomDet* theGeomDet = theTrackerGeometry->idToDet(detIdStub);
Global3DPoint posStub = theGeomDet->surface().toGlobal( theGeomDet->topology().localPosition(mp) );
double eta = posStub.eta();
Stub_Eta->Fill(eta);
Stub_RZ->Fill( posStub.z(), posStub.perp() );
if ( detIdStub.subdetId() == static_cast<int>(StripSubdetector::TOB) ) // Phase 2 Outer Tracker Barrel
{
Stub_Barrel->Fill(tTopo->layer(detIdStub));
Stub_Barrel_XY->Fill( posStub.x(), posStub.y() );
Stub_Barrel_XY_Zoom->Fill( posStub.x(), posStub.y() );
Stub_Barrel_W->Fill(tTopo->layer(detIdStub), displStub - offsetStub);
Stub_Barrel_O->Fill(tTopo->layer(detIdStub), offsetStub);
}
else if ( detIdStub.subdetId() == static_cast<int>(StripSubdetector::TID) ) // Phase 2 Outer Tracker Endcap
{
int disc = tTopo->layer(detIdStub); // returns wheel
int ring = tTopo->tidRing(detIdStub);
Stub_Endcap_Disc->Fill(disc);
Stub_Endcap_Ring->Fill(ring);
Stub_Endcap_Disc_W->Fill(disc, displStub - offsetStub);
Stub_Endcap_Ring_W->Fill(ring, displStub - offsetStub);
Stub_Endcap_Disc_O->Fill(disc, offsetStub);
Stub_Endcap_Ring_O->Fill(ring, offsetStub);
if ( posStub.z() > 0 )
{
Stub_Endcap_Fw_XY->Fill( posStub.x(), posStub.y() );
Stub_Endcap_Fw_RZ_Zoom->Fill( posStub.z(), posStub.perp() );
Stub_Endcap_Disc_Fw->Fill(disc);
Stub_Endcap_Ring_Fw[disc-1]->Fill(ring);
Stub_Endcap_Ring_W_Fw[disc-1]->Fill(ring, displStub - offsetStub);
Stub_Endcap_Ring_O_Fw[disc-1]->Fill(ring, offsetStub);
}
else
{
Stub_Endcap_Bw_XY->Fill( posStub.x(), posStub.y() );
Stub_Endcap_Bw_RZ_Zoom->Fill( posStub.z(), posStub.perp() );
Stub_Endcap_Disc_Bw->Fill(disc);
Stub_Endcap_Ring_Bw[disc-1]->Fill(ring);
Stub_Endcap_Ring_W_Bw[disc-1]->Fill(ring, displStub - offsetStub);
Stub_Endcap_Ring_O_Bw[disc-1]->Fill(ring, offsetStub);
}
}
}
}
} // end of method
// ------------ method called when starting to processes a run ------------
void
OuterTrackerMonitorTTStub::beginRun(edm::Run const&, edm::EventSetup const&)
{
std::string HistoName;
dqmStore_->setCurrentFolder(topFolderName_+"/Stubs/Position");
////////////////////////////////////////
///// GLOBAL POSITION OF THE STUB //////
////////////////////////////////////////
edm::ParameterSet psTTStub_Barrel_XY = conf_.getParameter<edm::ParameterSet>("TH2TTStub_Position");
HistoName = "Stub_Barrel_XY";
Stub_Barrel_XY = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Barrel_XY.getParameter<int32_t>("Nbinsx"),
psTTStub_Barrel_XY.getParameter<double>("xmin"),
psTTStub_Barrel_XY.getParameter<double>("xmax"),
psTTStub_Barrel_XY.getParameter<int32_t>("Nbinsy"),
psTTStub_Barrel_XY.getParameter<double>("ymin"),
psTTStub_Barrel_XY.getParameter<double>("ymax"));
Stub_Barrel_XY->setAxisTitle("L1 Stub Barrel position x [cm]", 1);
Stub_Barrel_XY->setAxisTitle("L1 Stub Barrel position y [cm]", 2);
edm::ParameterSet psTTStub_Barrel_XY_Zoom = conf_.getParameter<edm::ParameterSet>("TH2TTStub_Barrel_XY_Zoom");
HistoName = "Stub_Barrel_XY_Zoom";
Stub_Barrel_XY_Zoom = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Barrel_XY_Zoom.getParameter<int32_t>("Nbinsx"),
psTTStub_Barrel_XY_Zoom.getParameter<double>("xmin"),
psTTStub_Barrel_XY_Zoom.getParameter<double>("xmax"),
psTTStub_Barrel_XY_Zoom.getParameter<int32_t>("Nbinsy"),
psTTStub_Barrel_XY_Zoom.getParameter<double>("ymin"),
psTTStub_Barrel_XY_Zoom.getParameter<double>("ymax"));
Stub_Barrel_XY_Zoom->setAxisTitle("L1 Stub Barrel position x [cm]", 1);
Stub_Barrel_XY_Zoom->setAxisTitle("L1 Stub Barrel position y [cm]", 2);
edm::ParameterSet psTTStub_Endcap_Fw_XY = conf_.getParameter<edm::ParameterSet>("TH2TTStub_Position");
HistoName = "Stub_Endcap_Fw_XY";
Stub_Endcap_Fw_XY = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Endcap_Fw_XY.getParameter<int32_t>("Nbinsx"),
psTTStub_Endcap_Fw_XY.getParameter<double>("xmin"),
psTTStub_Endcap_Fw_XY.getParameter<double>("xmax"),
psTTStub_Endcap_Fw_XY.getParameter<int32_t>("Nbinsy"),
psTTStub_Endcap_Fw_XY.getParameter<double>("ymin"),
psTTStub_Endcap_Fw_XY.getParameter<double>("ymax"));
Stub_Endcap_Fw_XY->setAxisTitle("L1 Stub Endcap position x [cm]", 1);
Stub_Endcap_Fw_XY->setAxisTitle("L1 Stub Endcap position y [cm]", 2);
edm::ParameterSet psTTStub_Endcap_Bw_XY = conf_.getParameter<edm::ParameterSet>("TH2TTStub_Position");
HistoName = "Stub_Endcap_Bw_XY";
Stub_Endcap_Bw_XY = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Endcap_Bw_XY.getParameter<int32_t>("Nbinsx"),
psTTStub_Endcap_Bw_XY.getParameter<double>("xmin"),
psTTStub_Endcap_Bw_XY.getParameter<double>("xmax"),
psTTStub_Endcap_Bw_XY.getParameter<int32_t>("Nbinsy"),
psTTStub_Endcap_Bw_XY.getParameter<double>("ymin"),
psTTStub_Endcap_Bw_XY.getParameter<double>("ymax"));
Stub_Endcap_Bw_XY->setAxisTitle("L1 Stub Endcap position x [cm]", 1);
Stub_Endcap_Bw_XY->setAxisTitle("L1 Stub Endcap position y [cm]", 2);
//TTStub #rho vs. z
edm::ParameterSet psTTStub_RZ = conf_.getParameter<edm::ParameterSet>("TH2TTStub_RZ");
HistoName = "Stub_RZ";
Stub_RZ = dqmStore_->book2D(HistoName, HistoName,
psTTStub_RZ.getParameter<int32_t>("Nbinsx"),
psTTStub_RZ.getParameter<double>("xmin"),
psTTStub_RZ.getParameter<double>("xmax"),
psTTStub_RZ.getParameter<int32_t>("Nbinsy"),
psTTStub_RZ.getParameter<double>("ymin"),
psTTStub_RZ.getParameter<double>("ymax"));
Stub_RZ->setAxisTitle("L1 Stub position z [cm]", 1);
Stub_RZ->setAxisTitle("L1 Stub position #rho [cm]", 2);
//TTStub Forward Endcap #rho vs. z
edm::ParameterSet psTTStub_Endcap_Fw_RZ_Zoom = conf_.getParameter<edm::ParameterSet>("TH2TTStub_Endcap_Fw_RZ_Zoom");
HistoName = "Stub_Endcap_Fw_RZ_Zoom";
Stub_Endcap_Fw_RZ_Zoom = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Endcap_Fw_RZ_Zoom.getParameter<int32_t>("Nbinsx"),
psTTStub_Endcap_Fw_RZ_Zoom.getParameter<double>("xmin"),
psTTStub_Endcap_Fw_RZ_Zoom.getParameter<double>("xmax"),
psTTStub_Endcap_Fw_RZ_Zoom.getParameter<int32_t>("Nbinsy"),
psTTStub_Endcap_Fw_RZ_Zoom.getParameter<double>("ymin"),
psTTStub_Endcap_Fw_RZ_Zoom.getParameter<double>("ymax"));
Stub_Endcap_Fw_RZ_Zoom->setAxisTitle("L1 Stub Endcap position z [cm]", 1);
Stub_Endcap_Fw_RZ_Zoom->setAxisTitle("L1 Stub Endcap position #rho [cm]", 2);
//TTStub Backward Endcap #rho vs. z
edm::ParameterSet psTTStub_Endcap_Bw_RZ_Zoom = conf_.getParameter<edm::ParameterSet>("TH2TTStub_Endcap_Bw_RZ_Zoom");
HistoName = "Stub_Endcap_Bw_RZ_Zoom";
Stub_Endcap_Bw_RZ_Zoom = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Endcap_Bw_RZ_Zoom.getParameter<int32_t>("Nbinsx"),
psTTStub_Endcap_Bw_RZ_Zoom.getParameter<double>("xmin"),
psTTStub_Endcap_Bw_RZ_Zoom.getParameter<double>("xmax"),
psTTStub_Endcap_Bw_RZ_Zoom.getParameter<int32_t>("Nbinsy"),
psTTStub_Endcap_Bw_RZ_Zoom.getParameter<double>("ymin"),
psTTStub_Endcap_Bw_RZ_Zoom.getParameter<double>("ymax"));
Stub_Endcap_Bw_RZ_Zoom->setAxisTitle("L1 Stub Endcap position z [cm]", 1);
Stub_Endcap_Bw_RZ_Zoom->setAxisTitle("L1 Stub Endcap position #rho [cm]", 2);
dqmStore_->setCurrentFolder(topFolderName_+"/Stubs");
//TTStub eta
edm::ParameterSet psTTStub_Eta = conf_.getParameter<edm::ParameterSet>("TH1TTStub_Eta");
HistoName = "Stub_Eta";
Stub_Eta = dqmStore_ ->book1D(HistoName,HistoName,
psTTStub_Eta.getParameter<int32_t>("Nbinsx"),
psTTStub_Eta.getParameter<double>("xmin"),
psTTStub_Eta.getParameter<double>("xmax"));
Stub_Eta->setAxisTitle("#eta",1);
Stub_Eta->setAxisTitle("# L1 Stubs ",2);
dqmStore_->setCurrentFolder(topFolderName_+"/Stubs/NStubs");
//TTStub barrel stack
edm::ParameterSet psTTStub_Barrel = conf_.getParameter<edm::ParameterSet>("TH1TTStub_Layers");
HistoName = "NStubs_Barrel";
Stub_Barrel = dqmStore_ ->book1D(HistoName,HistoName,
psTTStub_Barrel.getParameter<int32_t>("Nbinsx"),
psTTStub_Barrel.getParameter<double>("xmin"),
psTTStub_Barrel.getParameter<double>("xmax"));
Stub_Barrel->setAxisTitle("Barrel Layer",1);
Stub_Barrel->setAxisTitle("# L1 Stubs ",2);
//TTStub Endcap stack
edm::ParameterSet psTTStub_ECDisc = conf_.getParameter<edm::ParameterSet>("TH1TTStub_Discs");
HistoName = "NStubs_Endcap_Disc";
Stub_Endcap_Disc = dqmStore_ ->book1D(HistoName,HistoName,
psTTStub_ECDisc.getParameter<int32_t>("Nbinsx"),
psTTStub_ECDisc.getParameter<double>("xmin"),
psTTStub_ECDisc.getParameter<double>("xmax"));
Stub_Endcap_Disc->setAxisTitle("Endcap Disc",1);
Stub_Endcap_Disc->setAxisTitle("# L1 Stubs ",2);
//TTStub Endcap stack
HistoName = "NStubs_Endcap_Disc_Fw";
Stub_Endcap_Disc_Fw = dqmStore_ ->book1D(HistoName,HistoName,
psTTStub_ECDisc.getParameter<int32_t>("Nbinsx"),
psTTStub_ECDisc.getParameter<double>("xmin"),
psTTStub_ECDisc.getParameter<double>("xmax"));
Stub_Endcap_Disc_Fw->setAxisTitle("Forward Endcap Disc",1);
Stub_Endcap_Disc_Fw->setAxisTitle("# L1 Stubs ",2);
//TTStub Endcap stack
HistoName = "NStubs_Endcap_Disc_Bw";
Stub_Endcap_Disc_Bw = dqmStore_ ->book1D(HistoName,HistoName,
psTTStub_ECDisc.getParameter<int32_t>("Nbinsx"),
psTTStub_ECDisc.getParameter<double>("xmin"),
psTTStub_ECDisc.getParameter<double>("xmax"));
Stub_Endcap_Disc_Bw->setAxisTitle("Backward Endcap Disc",1);
Stub_Endcap_Disc_Bw->setAxisTitle("# L1 Stubs ",2);
edm::ParameterSet psTTStub_ECRing = conf_.getParameter<edm::ParameterSet>("TH1TTStub_Rings");
HistoName = "NStubs_Endcap_Ring";
Stub_Endcap_Ring = dqmStore_ ->book1D(HistoName,HistoName,
psTTStub_ECRing.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing.getParameter<double>("xmin"),
psTTStub_ECRing.getParameter<double>("xmax"));
Stub_Endcap_Ring->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring->setAxisTitle("# L1 Stubs ",2);
for (int i = 0; i < 5; i++)
{
HistoName = "NStubs_Disc+"+std::to_string(i+1);
//TTStub Endcap stack
Stub_Endcap_Ring_Fw[i] = dqmStore_ ->book1D(HistoName, HistoName,
psTTStub_ECRing.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing.getParameter<double>("xmin"),
psTTStub_ECRing.getParameter<double>("xmax"));
Stub_Endcap_Ring_Fw[i]->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_Fw[i]->setAxisTitle("# L1 Stubs ",2);
}
for (int i = 0; i < 5; i++)
{
HistoName = "NStubs_Disc-"+std::to_string(i+1);
//TTStub Endcap stack
Stub_Endcap_Ring_Bw[i] = dqmStore_ ->book1D(HistoName, HistoName,
psTTStub_ECRing.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing.getParameter<double>("xmin"),
psTTStub_ECRing.getParameter<double>("xmax"));
Stub_Endcap_Ring_Bw[i]->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_Bw[i]->setAxisTitle("# L1 Stubs ",2);
}
//TTStub displ/offset
edm::ParameterSet psTTStub_Barrel_2D = conf_.getParameter<edm::ParameterSet>("TH2TTStub_DisOf_Layer");
edm::ParameterSet psTTStub_ECDisc_2D = conf_.getParameter<edm::ParameterSet>("TH2TTStub_DisOf_Disc");
edm::ParameterSet psTTStub_ECRing_2D = conf_.getParameter<edm::ParameterSet>("TH2TTStub_DisOf_Ring");
dqmStore_->setCurrentFolder(topFolderName_+"/Stubs/Width");
HistoName = "Stub_Width_Barrel";
Stub_Barrel_W = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Barrel_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_Barrel_2D.getParameter<double>("xmin"),
psTTStub_Barrel_2D.getParameter<double>("xmax"),
psTTStub_Barrel_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_Barrel_2D.getParameter<double>("ymin"),
psTTStub_Barrel_2D.getParameter<double>("ymax"));
Stub_Barrel_W->setAxisTitle("Barrel Layer",1);
Stub_Barrel_W->setAxisTitle("Displacement - Offset",2);
HistoName = "Stub_Width_Endcap_Disc";
Stub_Endcap_Disc_W = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECDisc_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECDisc_2D.getParameter<double>("xmin"),
psTTStub_ECDisc_2D.getParameter<double>("xmax"),
psTTStub_ECDisc_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECDisc_2D.getParameter<double>("ymin"),
psTTStub_ECDisc_2D.getParameter<double>("ymax"));
Stub_Endcap_Disc_W->setAxisTitle("Endcap Disc",1);
Stub_Endcap_Disc_W->setAxisTitle("Displacement - Offset",2);
HistoName = "Stub_Width_Endcap_Ring";
Stub_Endcap_Ring_W = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing_2D.getParameter<double>("xmin"),
psTTStub_ECRing_2D.getParameter<double>("xmax"),
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECRing_2D.getParameter<double>("ymin"),
psTTStub_ECRing_2D.getParameter<double>("ymax"));
Stub_Endcap_Ring_W->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_W->setAxisTitle("Trigger Offset",2);
for (int i = 0; i < 5; i++)
{
HistoName = "Stub_Width_Disc+"+std::to_string(i+1);
Stub_Endcap_Ring_W_Fw[i] = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing_2D.getParameter<double>("xmin"),
psTTStub_ECRing_2D.getParameter<double>("xmax"),
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECRing_2D.getParameter<double>("ymin"),
psTTStub_ECRing_2D.getParameter<double>("ymax"));
Stub_Endcap_Ring_W_Fw[i]->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_W_Fw[i]->setAxisTitle("Displacement - Offset",2);
}
for (int i = 0; i < 5; i++)
{
HistoName = "Stub_Width_Disc-"+std::to_string(i+1);
Stub_Endcap_Ring_W_Bw[i] = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing_2D.getParameter<double>("xmin"),
psTTStub_ECRing_2D.getParameter<double>("xmax"),
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECRing_2D.getParameter<double>("ymin"),
psTTStub_ECRing_2D.getParameter<double>("ymax"));
Stub_Endcap_Ring_W_Bw[i]->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_W_Bw[i]->setAxisTitle("Displacement - Offset",2);
}
dqmStore_->setCurrentFolder(topFolderName_+"/Stubs/Offset");
HistoName = "Stub_Offset_Barrel";
Stub_Barrel_O = dqmStore_->book2D(HistoName, HistoName,
psTTStub_Barrel_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_Barrel_2D.getParameter<double>("xmin"),
psTTStub_Barrel_2D.getParameter<double>("xmax"),
psTTStub_Barrel_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_Barrel_2D.getParameter<double>("ymin"),
psTTStub_Barrel_2D.getParameter<double>("ymax"));
Stub_Barrel_O->setAxisTitle("Barrel Layer",1);
Stub_Barrel_O->setAxisTitle("Trigger Offset",2);
HistoName = "Stub_Offset_Endcap_Disc";
Stub_Endcap_Disc_O = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECDisc_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECDisc_2D.getParameter<double>("xmin"),
psTTStub_ECDisc_2D.getParameter<double>("xmax"),
psTTStub_ECDisc_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECDisc_2D.getParameter<double>("ymin"),
psTTStub_ECDisc_2D.getParameter<double>("ymax"));
Stub_Endcap_Disc_O->setAxisTitle("Endcap Disc",1);
Stub_Endcap_Disc_O->setAxisTitle("Trigger Offset",2);
HistoName = "Stub_Offset_Endcap_Ring";
Stub_Endcap_Ring_O = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing_2D.getParameter<double>("xmin"),
psTTStub_ECRing_2D.getParameter<double>("xmax"),
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECRing_2D.getParameter<double>("ymin"),
psTTStub_ECRing_2D.getParameter<double>("ymax"));
Stub_Endcap_Ring_O->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_O->setAxisTitle("Trigger Offset",2);
for (int i = 0; i < 5; i++)
{
HistoName = "Stub_Offset_Disc+"+std::to_string(i+1);
Stub_Endcap_Ring_O_Fw[i] = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing_2D.getParameter<double>("xmin"),
psTTStub_ECRing_2D.getParameter<double>("xmax"),
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECRing_2D.getParameter<double>("ymin"),
psTTStub_ECRing_2D.getParameter<double>("ymax"));
Stub_Endcap_Ring_O_Fw[i]->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_O_Fw[i]->setAxisTitle("Trigger Offset",2);
}
for (int i = 0; i < 5; i++)
{
HistoName = "Stub_Offset_Disc-"+std::to_string(i+1);
Stub_Endcap_Ring_O_Bw[i] = dqmStore_->book2D(HistoName, HistoName,
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsx"),
psTTStub_ECRing_2D.getParameter<double>("xmin"),
psTTStub_ECRing_2D.getParameter<double>("xmax"),
psTTStub_ECRing_2D.getParameter<int32_t>("Nbinsy"),
psTTStub_ECRing_2D.getParameter<double>("ymin"),
psTTStub_ECRing_2D.getParameter<double>("ymax"));
Stub_Endcap_Ring_O_Bw[i]->setAxisTitle("Endcap Ring",1);
Stub_Endcap_Ring_O_Bw[i]->setAxisTitle("Trigger Offset",2);
}
}
// ------------ method called once each job just after ending the event loop ------------
void
OuterTrackerMonitorTTStub::endJob()
{
}
//define this as a plug-in
DEFINE_FWK_MODULE(OuterTrackerMonitorTTStub);
| 44.324544 | 187 | 0.716639 | [
"geometry",
"vector"
] |
c8b2ed24e435474162b38c4dbe5e7a27a2cd888f | 1,369 | cpp | C++ | 数学/同余/crt.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | 3 | 2020-11-16T08:58:30.000Z | 2020-11-16T08:58:33.000Z | 数学/同余/crt.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | 数学/同余/crt.cpp | tempure/algorithm-advance | 38c4504f64cd3fd15fc32cf20a541ad5ba2ad82b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int)(x).size())
typedef vector<int> vi;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
mt19937 mrand(random_device{}());
const ll mod = 1000000007;
int rnd(int x) { return mrand() % x;}
ll mulmod(ll a, ll b) {ll res = 0; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = (res + a) % mod; a = 2 * a % mod;} return res;}
ll powmod(ll a, ll b) {ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = res * a % mod; a = a * a % mod;} return res;}
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;}
//snippet-head
//中国剩余定理模板
const int N = 11;
int n;
int A[N], B[N];
void exgcd(ll a, ll b, ll &x, ll & y) {
if (!b)
x = 1, y = 0;
else {
exgcd(b, a % b, y, x);
y -= a / b * x;
}
}
int main() {
scanf("%d", &n);
ll M = 1;
//方程组为 x 同余 B[i] mod (A[i])
for (int i = 0; i < n; i++) {
scanf("%d%d", &A[i], &B[i]);
M *= A[i];
}
ll res = 0;
for (int i = 0; i < n; i++) {
ll Mi = M / A[i];
//求Mi*ti 同余 1(mod mi) 的ti
ll ti, x;
exgcd(Mi, A[i], ti, x);
res += (B[i] * Mi * ti);
}
//中国剩余定理给出的通解是 x + k * M 对M取模即可得到最小正整数解
cout << (res % M + M ) % M << endl;
}
| 23.603448 | 144 | 0.472608 | [
"vector"
] |
c8b4bab55a93c0210c11abf8f7140bc925d04801 | 9,648 | cpp | C++ | modules/props_2d/material_cache/prop_2d_material_cache.cpp | Relintai/pandemonium_engine | 3de05db75a396b497f145411f71eb363572b38ae | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | modules/props_2d/material_cache/prop_2d_material_cache.cpp | Relintai/pandemonium_engine | 3de05db75a396b497f145411f71eb363572b38ae | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | modules/props_2d/material_cache/prop_2d_material_cache.cpp | Relintai/pandemonium_engine | 3de05db75a396b497f145411f71eb363572b38ae | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | /*
Copyright (c) 2019-2022 Péter Magyar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "prop_2d_material_cache.h"
#include "../props/prop_2d_data.h"
#include "../props/prop_2d_data_prop.h"
#include "../props/prop_2d_data_tiled_wall_2d.h"
#include "../singleton/prop_2d_cache.h"
#include "../tiled_wall/tiled_wall_2d_data.h"
#if MESH_DATA_RESOURCE_PRESENT
//define PROPS_PRESENT, so things compile. That module's scsub will define this too while compiling,
//but not when included from here.
#define PROPS_2D_PRESENT 1
#include "../../mesh_data_resource/props_2d/prop_2d_data_mesh_data.h"
#endif
#define VARIANT_ARRAY_GET(arr) \
Vector<Variant> r; \
for (int i = 0; i < arr.size(); i++) { \
r.push_back(arr[i].get_ref_ptr()); \
} \
return r;
bool Prop2DMaterialCache::get_initialized() {
return _initialized;
}
void Prop2DMaterialCache::set_initialized(const bool value) {
_initialized = value;
}
bool Prop2DMaterialCache::mutex_locked() {
return _locked;
}
void Prop2DMaterialCache::mutex_lock() {
_mutex.lock();
}
void Prop2DMaterialCache::mutex_unlock() {
_mutex.unlock();
}
int Prop2DMaterialCache::get_ref_count() {
return _ref_count;
}
void Prop2DMaterialCache::set_ref_count(const int value) {
_ref_count = value;
}
void Prop2DMaterialCache::inc_ref_count() {
_ref_count += 1;
}
void Prop2DMaterialCache::dec_ref_count() {
_ref_count -= 1;
}
//Materials
Ref<Material> Prop2DMaterialCache::material_get() {
return _material;
}
void Prop2DMaterialCache::material_set(const Ref<Material> &value) {
_material = value;
}
void Prop2DMaterialCache::texture_add(const Ref<Texture> &texture) {
_textures.push_back(texture);
}
void Prop2DMaterialCache::texture_remove(const Ref<Texture> &texture) {
for (int i = 0; i < _textures.size(); ++i) {
if (_textures[i] == texture) {
_textures.remove(i);
return;
}
}
}
void Prop2DMaterialCache::texture_remove_index(const int index) {
ERR_FAIL_INDEX(index, _textures.size());
_textures.remove(index);
}
void Prop2DMaterialCache::textures_clear() {
_textures.clear();
}
int Prop2DMaterialCache::texture_count() {
return _textures.size();
}
Ref<Texture> Prop2DMaterialCache::texture_get(const int index) {
ERR_FAIL_INDEX_V(index, _textures.size(), Ref<Texture>());
return _textures[index];
}
Ref<AtlasTexture> Prop2DMaterialCache::texture_get_atlas(const int index) {
ERR_FAIL_INDEX_V(index, _textures.size(), Ref<AtlasTexture>());
return texture_get_atlas_tex(_textures[index]);
}
Ref<AtlasTexture> Prop2DMaterialCache::texture_get_atlas_tex(const Ref<Texture> &texture) {
return Ref<AtlasTexture>();
}
Rect2 Prop2DMaterialCache::texture_get_rect(const Ref<Texture> &texture) {
Ref<AtlasTexture> at = texture_get_atlas_tex(texture);
if (!at.is_valid()) {
return Rect2();
}
return at->get_region();
}
Rect2 Prop2DMaterialCache::texture_get_uv_rect(const Ref<Texture> &texture) {
return Rect2(0, 0, 1, 1);
}
Ref<Texture> Prop2DMaterialCache::texture_get_merged() {
return Ref<Texture>();
}
void Prop2DMaterialCache::prop_add_textures(const Ref<Prop2DData> &prop) {
if (!prop.is_valid()) {
return;
}
for (int i = 0; i < prop->get_prop_count(); ++i) {
#if MESH_DATA_RESOURCE_PRESENT
Ref<Prop2DDataMeshData> pdm = prop->get_prop(i);
if (pdm.is_valid()) {
Ref<Texture> tex = pdm->get_texture();
if (!tex.is_valid())
continue;
texture_add(tex);
continue;
}
#endif
Ref<Prop2DDataTiledWall2D> pdtw = prop->get_prop(i);
if (pdtw.is_valid()) {
Ref<TiledWall2DData> twd = pdtw->get_data();
if (!twd.is_valid())
continue;
twd->setup_cache(Ref<Prop2DMaterialCache>(this));
continue;
}
Ref<Prop2DDataProp2D> pdp = prop->get_prop(i);
if (pdp.is_valid()) {
prop_add_textures(pdp->get_prop());
}
}
}
void Prop2DMaterialCache::prop_remove_textures(const Ref<Prop2DData> &prop) {
if (!prop.is_valid()) {
return;
}
for (int i = 0; i < prop->get_prop_count(); ++i) {
#if MESH_DATA_RESOURCE_PRESENT
Ref<Prop2DDataMeshData> pdm = prop->get_prop(i);
if (pdm.is_valid()) {
Ref<Texture> tex = pdm->get_texture();
if (!tex.is_valid())
continue;
texture_remove(tex);
}
#endif
Ref<Prop2DDataTiledWall2D> pdtw = prop->get_prop(i);
if (pdtw.is_valid()) {
Ref<TiledWall2DData> twd = pdtw->get_data();
if (!twd.is_valid())
continue;
for (int j = 0; j < twd->get_texture_count(); ++j) {
const Ref<Texture> &tex = twd->get_texture(j);
if (tex.is_valid()) {
texture_remove(tex);
}
}
for (int j = 0; j < twd->get_flavour_texture_count(); ++j) {
const Ref<Texture> &tex = twd->get_flavour_texture(j);
if (tex.is_valid()) {
texture_remove(tex);
}
}
continue;
}
Ref<Prop2DDataProp2D> pdp = prop->get_prop(i);
if (pdp.is_valid()) {
prop_remove_textures(pdp);
}
}
}
void Prop2DMaterialCache::refresh_rects() {
_initialized = true;
}
void Prop2DMaterialCache::initial_setup_default() {
//Note: call only on the main thread! Shader->duplicate() can crash if done from an another thread!
//Also shader duplication is synchronized with the main thread. So you can cause daedlocks if you hold up the main thread
//Somwhere else.
Prop2DCache *pc = Prop2DCache::get_singleton();
pc->ensure_material_loaded();
Ref<Material> m = pc->material_get();
if (m.is_valid()) {
Ref<Material> md = m->duplicate();
_material = md;
}
}
void Prop2DMaterialCache::setup_material_albedo(Ref<Texture> texture) {
if (has_method("_setup_material_albedo"))
call("_setup_material_albedo", texture);
}
Prop2DMaterialCache::Prop2DMaterialCache() {
_ref_count = 0;
_initialized = false;
_locked = false;
}
Prop2DMaterialCache::~Prop2DMaterialCache() {
}
void Prop2DMaterialCache::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_initialized"), &Prop2DMaterialCache::get_initialized);
ClassDB::bind_method(D_METHOD("set_initialized", "value"), &Prop2DMaterialCache::set_initialized);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "initialized"), "set_initialized", "get_initialized");
ClassDB::bind_method(D_METHOD("mutex_locked"), &Prop2DMaterialCache::mutex_locked);
ClassDB::bind_method(D_METHOD("mutex_lock"), &Prop2DMaterialCache::mutex_lock);
ClassDB::bind_method(D_METHOD("mutex_unlock"), &Prop2DMaterialCache::mutex_unlock);
ClassDB::bind_method(D_METHOD("get_ref_count"), &Prop2DMaterialCache::get_ref_count);
ClassDB::bind_method(D_METHOD("set_ref_count", "value"), &Prop2DMaterialCache::set_ref_count);
ADD_PROPERTY(PropertyInfo(Variant::INT, "mat_ref_count"), "set_ref_count", "get_ref_count");
ClassDB::bind_method(D_METHOD("inc_ref_count"), &Prop2DMaterialCache::inc_ref_count);
ClassDB::bind_method(D_METHOD("dec_ref_count"), &Prop2DMaterialCache::dec_ref_count);
BIND_VMETHOD(MethodInfo("_setup_material_albedo", PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture")));
ClassDB::bind_method(D_METHOD("material_get"), &Prop2DMaterialCache::material_get);
ClassDB::bind_method(D_METHOD("material_set", "value"), &Prop2DMaterialCache::material_set);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "Material"), "material_set", "material_get");
ClassDB::bind_method(D_METHOD("texture_add", "texture"), &Prop2DMaterialCache::texture_add);
ClassDB::bind_method(D_METHOD("texture_remove", "texture"), &Prop2DMaterialCache::texture_remove);
ClassDB::bind_method(D_METHOD("texture_remove_index", "index"), &Prop2DMaterialCache::texture_remove_index);
ClassDB::bind_method(D_METHOD("textures_clear"), &Prop2DMaterialCache::textures_clear);
ClassDB::bind_method(D_METHOD("texture_count"), &Prop2DMaterialCache::texture_count);
ClassDB::bind_method(D_METHOD("texture_get", "index"), &Prop2DMaterialCache::texture_get);
ClassDB::bind_method(D_METHOD("texture_get_atlas", "index"), &Prop2DMaterialCache::texture_get_atlas);
ClassDB::bind_method(D_METHOD("texture_get_atlas_tex", "index"), &Prop2DMaterialCache::texture_get_atlas_tex);
ClassDB::bind_method(D_METHOD("texture_get_uv_rect", "texture"), &Prop2DMaterialCache::texture_get_uv_rect);
ClassDB::bind_method(D_METHOD("texture_get_merged"), &Prop2DMaterialCache::texture_get_merged);
ClassDB::bind_method(D_METHOD("prop_add_textures", "prop"), &Prop2DMaterialCache::prop_add_textures);
ClassDB::bind_method(D_METHOD("prop_remove_textures", "prop"), &Prop2DMaterialCache::prop_remove_textures);
ClassDB::bind_method(D_METHOD("refresh_rects"), &Prop2DMaterialCache::refresh_rects);
ClassDB::bind_method(D_METHOD("setup_material_albedo", "texture"), &Prop2DMaterialCache::setup_material_albedo);
}
| 31.529412 | 134 | 0.743677 | [
"object",
"vector"
] |
c8ba3105ab0b2d964b29712143235434de6b1f5f | 5,801 | cc | C++ | src/featbin/apply-vad-merged.cc | supreet21/kaldi-1 | 996d9241eaea0f71d41eb3d064dba8907dcafa31 | [
"Apache-2.0"
] | null | null | null | src/featbin/apply-vad-merged.cc | supreet21/kaldi-1 | 996d9241eaea0f71d41eb3d064dba8907dcafa31 | [
"Apache-2.0"
] | null | null | null | src/featbin/apply-vad-merged.cc | supreet21/kaldi-1 | 996d9241eaea0f71d41eb3d064dba8907dcafa31 | [
"Apache-2.0"
] | null | null | null | // featbin/apply-vad.cc
// Copyright 2014 University of Southern California (author: Maarten Van Segbroeck)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "matrix/kaldi-matrix.h"
#include "transform/featxtra-functions.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
const char *usage =
"Apply voice activity detection processing on a frame sequence of speech/non-speech probabilities \n"
"Usage: apply-vad-merged [options] in-rspecifier out-wspecifier\n";
ParseOptions po(usage);
std::string spk2utt_rspecifier;
int32 prb_pow = 2;
int32 ctx_win = 40;
BaseFloat vad_thr = 0.4;
bool prb_str = false;
po.Register("prb-pow", &prb_pow, "Power of probability stream prior "
"to median filtering.");
po.Register("ctx-win", &ctx_win, "Number of frames of median filtering.");
po.Register("vad-thr", &vad_thr, "VAD threshold.");
po.Register("prb-str", &prb_str, "Median filtered probability stream.");
po.Register("spk2utt", &spk2utt_rspecifier, "rspecifier for speaker to "
"utterance-list map");
po.Read(argc, argv);
if (po.NumArgs() != 2) {
po.PrintUsage();
exit(1);
}
int32 num_done = 0, num_err = 0;
std::string rspecifier = po.GetArg(1);
std::string wspecifier = po.GetArg(2);
KALDI_ASSERT(vad_thr > 0 || ctx_win > 0);
BaseFloatMatrixWriter kaldi_writer(wspecifier);
SequentialBaseFloatMatrixReader kaldi_reader(rspecifier);
if (spk2utt_rspecifier != "") {
SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier);
RandomAccessBaseFloatMatrixReader kaldi_reader(rspecifier);
for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) {
std::string spk = spk2utt_reader.Key();
const std::vector<std::string> &uttlist = spk2utt_reader.Value();
Matrix<BaseFloat> spkfeats;
for (size_t i = 0; i < uttlist.size(); i++) {
std::string utt = uttlist[i];
if (!kaldi_reader.HasKey(utt)) {
KALDI_WARN << "Did not find features for utterance " << utt;
num_err++;
continue;
}
const Matrix<BaseFloat> &uttfeats = kaldi_reader.Value(utt);
spkfeats.Resize(spkfeats.NumRows() + uttfeats.NumRows(),
1, kCopyData);
if (utt.find("_NT") == std::string::npos) {
spkfeats.Range(spkfeats.NumRows() - uttfeats.NumRows(),
uttfeats.NumRows(), 0, 1).CopyFromMat(uttfeats);
}
num_done++;
}
if (spkfeats.NumRows() == 0) {
KALDI_WARN << "No stats accumulated for speaker " << spk;
} else {
int32 nb_frames=spkfeats.NumRows();
KALDI_ASSERT(ctx_win < nb_frames);
Vector<BaseFloat> vad_out;
// Mean of the probability streams
ApplyColMean(spkfeats, &vad_out);
// Take square of the probability streams
vad_out.ApplyPow(prb_pow);
// Median filtering of the resulting VAD probability stream
ApplyMedianfiltering(ctx_win, &vad_out);
Matrix<BaseFloat> to_write;
if (!prb_str) {
to_write.Resize(nb_frames, 1);
to_write.CopyColFromVec(vad_out, 0);
// Apply thresholding
to_write.Add(-vad_thr);
to_write.ApplyHeaviside();
} else {
to_write.Resize(nb_frames, 2);
to_write.CopyColFromVec(vad_out, 0);
Vector<BaseFloat> prob_stream = vad_out;
// Apply thresholding
to_write.Add(-vad_thr);
to_write.ApplyHeaviside();
// concatenation of the probability stream
to_write.Resize(nb_frames, 2, kCopyData);
to_write.Range(0, nb_frames, 1, 1).CopyColFromVec(prob_stream, 0);
}
// Write
kaldi_writer.Write(spk, to_write);
KALDI_LOG << "Done accumulating vad labels for speaker " << spk
<< " for " << num_done << " segments; "
<< num_err << " had errors; "
<< nb_frames << " frames.";
}
}
}
//int32 k = 0;
//for (; !kaldi_reader.Done() ; kaldi_reader.Next(), k++) {
// std::string utt = kaldi_reader.Key();
// const Matrix<BaseFloat> &feats = kaldi_reader.Value();
// KALDI_ASSERT(ctx_win < feats.NumRows());
// Vector<BaseFloat> vad_out;
// // Mean of the probability streams
// ApplyColMean(feats, &vad_out);
// // Median filtering of the resulting VAD probability stream
// ApplyMedianfiltering(ctx_win, &vad_out);
// Matrix<BaseFloat> to_write(feats.NumRows(), 1);
// to_write.CopyColFromVec(vad_out, 0);
// // Apply thresholding
// to_write.Add(-vad_thr);
// to_write.ApplyHeaviside();
// kaldi_writer.Write(utt, to_write);
//}
//return 0;
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 36.031056 | 109 | 0.607309 | [
"vector",
"transform"
] |
c8bd5c1136fb7f5efd45a336c1f540c2784f61ed | 55,344 | cpp | C++ | src/luxcore/pyluxcoreforblender.cpp | OmidGhotbi/LuxCore | e83fb6bf2e2c0254e3c769ffc8e5546eb71f576a | [
"Apache-2.0"
] | 826 | 2017-12-12T15:38:16.000Z | 2022-03-28T07:12:40.000Z | src/luxcore/pyluxcoreforblender.cpp | OmidGhotbi/LuxCore | e83fb6bf2e2c0254e3c769ffc8e5546eb71f576a | [
"Apache-2.0"
] | 531 | 2017-12-03T17:21:06.000Z | 2022-03-20T19:22:11.000Z | src/luxcore/pyluxcoreforblender.cpp | OmidGhotbi/LuxCore | e83fb6bf2e2c0254e3c769ffc8e5546eb71f576a | [
"Apache-2.0"
] | 133 | 2017-12-13T18:46:10.000Z | 2022-03-27T16:21:00.000Z | /***************************************************************************
* Copyright 1998-2020 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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. *
***************************************************************************/
#ifdef WIN32
// Windows seems to require this #define otherwise VisualC++ looks for
// Boost Python DLL symbols.
// Do not use for Unix(s), it makes some symbol local.
#define BOOST_PYTHON_STATIC_LIB
#define BOOST_NUMPY_STATIC_LIB
// Python 3.8 and older define snprintf as a macro even for VS 2015 and newer,
// where this causes an error - See https://bugs.python.org/issue36020
#if defined(_MSC_VER) && _MSC_VER >= 1900
#define HAVE_SNPRINTF
#endif
#endif
#include <memory>
#include <vector>
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/format.hpp>
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <OpenImageIO/imagebufalgo.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/dassert.h>
#include <openvdb/openvdb.h>
#include <openvdb/io/File.h>
#include <Python.h>
#include "luxcore/luxcore.h"
#include "luxcore/luxcoreimpl.h"
#include "luxcore/pyluxcore/pyluxcoreforblender.h"
#include "luxcore/pyluxcore/blender_types.h"
#include "luxrays/utils/utils.h"
using namespace std;
using namespace luxrays;
using namespace luxcore;
using namespace boost::python;
namespace np = boost::python::numpy;
OIIO_NAMESPACE_USING
namespace luxcore {
namespace blender {
//------------------------------------------------------------------------------
// Blender struct access functions
//------------------------------------------------------------------------------
template<typename CustomData>
static int CustomData_get_active_layer_index(const CustomData *data, int type)
{
const int layer_index = data->typemap[type];
return (layer_index != -1) ? layer_index + data->layers[layer_index].active : -1;
}
template<typename CustomData>
static void *CustomData_get_layer(const CustomData *data, int type)
{
/* get the layer index of the active layer of type */
int layer_index = CustomData_get_active_layer_index(data, type);
if (layer_index == -1) {
return nullptr;
}
return data->layers[layer_index].data;
}
//------------------------------------------------------------------------------
// Utility functions
//------------------------------------------------------------------------------
template<class T>
T FindMaxValue(const T* buffer, const u_int buffersize) {
T maxValue = 0;
for (u_int i = 0; i < buffersize; ++i) {
const T value = buffer[i];
if (value > maxValue) {
maxValue = value;
}
}
return maxValue;
}
template<>
float FindMaxValue<float>(const float *buffer, const u_int buffersize) {
float maxValue = 0;
for (u_int i = 0; i < buffersize; ++i) {
const float value = buffer[i];
if (!isinf(value) && !isnan(value) && (value > maxValue)) {
maxValue = value;
}
}
return maxValue;
}
template<class T>
void GetOutput(boost::python::object &filmObj, const Film::FilmOutputType outputType,
const u_int outputIndex, T *pixels, const bool executeImagePipeline) {
// Convert boost::python::object to C++ class
luxcore::detail::FilmImpl &filmImpl = extract<luxcore::detail::FilmImpl &>(filmObj);
Film &film = reinterpret_cast<Film &>(filmImpl);
film.GetOutput<T>(outputType, pixels, outputIndex, executeImagePipeline);
}
// Safety check
void ThrowIfSizeMismatch(const RenderPass *renderPass, const u_int width, const u_int height) {
if ((u_int)renderPass->rectx != width || (u_int)renderPass->recty != height) {
const string rectSize = luxrays::ToString(renderPass->rectx) + "x" + luxrays::ToString(renderPass->recty);
const string outputSize = luxrays::ToString(width) + "x" + luxrays::ToString(height);
throw runtime_error("Size mismatch. RenderPass->rect size: " + rectSize + ", passed width x height: " + outputSize);
}
}
static Transform ExtractTransformation(const boost::python::object &transformation) {
if (transformation.is_none()) {
return Transform();
}
extract<boost::python::list> getTransformationList(transformation);
if (getTransformationList.check()) {
const boost::python::list &lst = getTransformationList();
const boost::python::ssize_t size = len(lst);
if (size != 16) {
const string objType = extract<string>((transformation.attr("__class__")).attr("__name__"));
throw runtime_error("Wrong number of elements for the list of transformation values: " + objType);
}
luxrays::Matrix4x4 mat;
boost::python::ssize_t index = 0;
for (u_int j = 0; j < 4; ++j)
for (u_int i = 0; i < 4; ++i)
mat.m[i][j] = extract<float>(lst[index++]);
return Transform(mat);
}
else {
const string objType = extract<string>((transformation.attr("__class__")).attr("__name__"));
throw runtime_error("Wrong data type for the list of transformation values: " + objType);
}
}
//------------------------------------------------------------------------------
// Film output conversion functions
//------------------------------------------------------------------------------
// For channels like DEPTH
void ConvertFilmChannelOutput_1xFloat_To_1xFloatList(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 1;
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// srcBufferDepth is equal, write directly to the renderPass
GetOutput(filmObj, outputType, outputIndex, renderPass->rect, executeImagePipeline);
if (normalize) {
const float maxValue = FindMaxValue(renderPass->rect, width * height * srcBufferDepth);
const float k = (maxValue == 0.f) ? 0.f : (1.f / maxValue);
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
for (u_int x = 0; x < width; ++x) {
renderPass->rect[srcIndex++] *= k;
}
}
}
}
// For the UV channel.
// We need to pad the UV pass to 3 elements (Blender can't handle 2 elements).
// The third channel is a mask that is 1 where a UV map exists and 0 otherwise.
void ConvertFilmChannelOutput_UV_to_Blender_UV(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 2;
const u_int dstBufferDepth = 3;
unique_ptr<float[]> src(new float[width * height * srcBufferDepth]);
GetOutput(filmObj, outputType, outputIndex, src.get(), executeImagePipeline);
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// Here we can't simply copy the values
float k = 1.f;
if (normalize) {
const float maxValue = FindMaxValue(src.get(), width * height);
k = (maxValue == 0.f) ? 0.f : (1.f / maxValue);
}
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
u_int dstIndex = y * width * dstBufferDepth;
for (u_int x = 0; x < width; ++x) {
const float u = src[srcIndex] * k;
const float v = src[srcIndex + 1] * k;
renderPass->rect[dstIndex] = u;
renderPass->rect[dstIndex + 1] = v;
// The third channel is a mask that is 1 where a UV map exists and 0 otherwise.
renderPass->rect[dstIndex + 2] = (u || v) ? 1.f : 0.f;
srcIndex += srcBufferDepth;
dstIndex += dstBufferDepth;
}
}
}
void ConvertFilmChannelOutput_1xFloat_To_4xFloatList(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 1;
const u_int dstBufferDepth = 4;
unique_ptr<float[]> src(new float[width * height * srcBufferDepth]);
GetOutput(filmObj, outputType, outputIndex, src.get(), executeImagePipeline);
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// Here we can't simply copy the values
float k = 1.f;
if (normalize) {
const float maxValue = FindMaxValue(src.get(), width * height);
k = (maxValue == 0.f) ? 0.f : (1.f / maxValue);
}
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
u_int dstIndex = y * width * dstBufferDepth;
for (u_int x = 0; x < width; ++x) {
const float val = src[srcIndex] * k;
renderPass->rect[dstIndex] = val;
renderPass->rect[dstIndex + 1] = val;
renderPass->rect[dstIndex + 2] = val;
renderPass->rect[dstIndex + 3] = 1.f; // Alpha
srcIndex += srcBufferDepth;
dstIndex += dstBufferDepth;
}
}
}
void ConvertFilmChannelOutput_3xFloat_To_3xFloatList(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 3;
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// srcBufferDepth is equal, write directly to the renderPass
GetOutput(filmObj, outputType, outputIndex, renderPass->rect, executeImagePipeline);
if (normalize) {
const float maxValue = FindMaxValue(renderPass->rect, width * height);
const float k = (maxValue == 0.f) ? 0.f : (1.f / maxValue);
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
for (u_int x = 0; x < width; ++x) {
renderPass->rect[srcIndex] *= k;
renderPass->rect[srcIndex + 1] *= k;
renderPass->rect[srcIndex + 2] *= k;
srcIndex += srcBufferDepth;
}
}
}
}
void ConvertFilmChannelOutput_3xFloat_To_4xFloatList(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 3;
const u_int dstBufferDepth = 4;
unique_ptr<float[]> src(new float[width * height * srcBufferDepth]);
GetOutput(filmObj, outputType, outputIndex, src.get(), executeImagePipeline);
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// Here we can't simply copy the values
float k = 1.f;
if (normalize) {
const float maxValue = FindMaxValue(src.get(), width * height);
k = (maxValue == 0.f) ? 0.f : (1.f / maxValue);
}
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
u_int dstIndex = y * width * dstBufferDepth;
for (u_int x = 0; x < width; ++x) {
renderPass->rect[dstIndex] = src[srcIndex] * k;
renderPass->rect[dstIndex + 1] = src[srcIndex + 1] * k;
renderPass->rect[dstIndex + 2] = src[srcIndex + 2] * k;
renderPass->rect[dstIndex + 3] = 1.f; // Alpha
srcIndex += srcBufferDepth;
dstIndex += dstBufferDepth;
}
}
}
void ConvertFilmChannelOutput_4xFloat_To_4xFloatList(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 4;
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// srcBufferDepth is equal, write directly to the renderPass
GetOutput(filmObj, outputType, outputIndex, renderPass->rect, executeImagePipeline);
if (normalize) {
// Look for the max. in source buffer (only among RGB values, not Alpha)
float maxValue = 0.f;
for (u_int i = 0; i < width * height * 4; ++i) {
const float value = renderPass->rect[i];
// Leave out every multiple of 4 (alpha values)
if ((i % 4 != 0) && !isinf(value) && !isnan(value) && (value > maxValue))
maxValue = value;
}
const float k = (maxValue == 0.f) ? 0.f : (1.f / maxValue);
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
for (u_int x = 0; x < width; ++x) {
renderPass->rect[srcIndex] *= k;
renderPass->rect[srcIndex + 1] *= k;
renderPass->rect[srcIndex + 2] *= k;
// Note: we do not normalize the alpha channel
srcIndex += srcBufferDepth;
}
}
}
}
// This function is for channels like the material index, object index or samplecount
void ConvertFilmChannelOutput_1xUInt_To_1xFloatList(boost::python::object &filmObj,
const Film::FilmOutputType outputType, const u_int outputIndex, const u_int width, const u_int height,
const size_t renderPassPtr, const bool normalize, const bool executeImagePipeline) {
const u_int srcBufferDepth = 1;
// Note that objSrc is unsigned int here
unique_ptr<u_int[]> src(new u_int[width * height * srcBufferDepth]);
GetOutput(filmObj, outputType, outputIndex, src.get(), executeImagePipeline);
RenderPass *renderPass = reinterpret_cast<RenderPass *>(renderPassPtr);
ThrowIfSizeMismatch(renderPass, width, height);
// Here we can't simply copy the values
float k = 1.f;
if (normalize) {
u_int maxValue = FindMaxValue(src.get(), width * height);
k = (maxValue == 0) ? 0.f : (1.f / maxValue);
}
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = y * width * srcBufferDepth;
for (u_int x = 0; x < width; ++x) {
// u_int is converted to float here
renderPass->rect[srcIndex] = src[srcIndex] * k;
srcIndex += srcBufferDepth;
}
}
}
// Note: This method is used by pyluxcoredemo.py, do not remove.
void ConvertFilmChannelOutput_3xFloat_To_4xUChar(const u_int width, const u_int height,
boost::python::object &objSrc, boost::python::object &objDst, const bool normalize) {
if (!PyObject_CheckBuffer(objSrc.ptr())) {
const string objType = extract<string>((objSrc.attr("__class__")).attr("__name__"));
throw runtime_error("Unsupported data type in source object of ConvertFilmChannelOutput_3xFloat_To_4xUChar(): " + objType);
}
if (!PyObject_CheckBuffer(objDst.ptr())) {
const string objType = extract<string>((objDst.attr("__class__")).attr("__name__"));
throw runtime_error("Unsupported data type in destination object of ConvertFilmChannelOutput_3xFloat_To_4xUChar(): " + objType);
}
Py_buffer srcView;
if (PyObject_GetBuffer(objSrc.ptr(), &srcView, PyBUF_SIMPLE)) {
const string objType = extract<string>((objSrc.attr("__class__")).attr("__name__"));
throw runtime_error("Unable to get a source data view in ConvertFilmChannelOutput_3xFloat_To_4xUChar(): " + objType);
}
Py_buffer dstView;
if (PyObject_GetBuffer(objDst.ptr(), &dstView, PyBUF_SIMPLE)) {
PyBuffer_Release(&srcView);
const string objType = extract<string>((objSrc.attr("__class__")).attr("__name__"));
throw runtime_error("Unable to get a source data view in ConvertFilmChannelOutput_3xFloat_To_4xUChar(): " + objType);
}
if (srcView.len / (3 * 4) != dstView.len / 4) {
PyBuffer_Release(&srcView);
PyBuffer_Release(&dstView);
throw runtime_error("Wrong buffer size in ConvertFilmChannelOutput_3xFloat_To_4xUChar()");
}
const float *src = (float *)srcView.buf;
u_char *dst = (u_char *)dstView.buf;
if (normalize) {
const float maxValue = FindMaxValue(src, width * height * 3);
const float k = (maxValue == 0.f) ? 0.f : (255.f / maxValue);
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = (height - y - 1) * width * 3;
u_int dstIndex = y * width * 4;
for (u_int x = 0; x < width; ++x) {
dst[dstIndex++] = (u_char)floor((src[srcIndex + 2] * k + .5f));
dst[dstIndex++] = (u_char)floor((src[srcIndex + 1] * k + .5f));
dst[dstIndex++] = (u_char)floor((src[srcIndex] * k + .5f));
dst[dstIndex++] = 0xff;
srcIndex += 3;
}
}
} else {
for (u_int y = 0; y < height; ++y) {
u_int srcIndex = (height - y - 1) * width * 3;
u_int dstIndex = y * width * 4;
for (u_int x = 0; x < width; ++x) {
dst[dstIndex++] = (u_char)floor((src[srcIndex + 2] * 255.f + .5f));
dst[dstIndex++] = (u_char)floor((src[srcIndex + 1] * 255.f + .5f));
dst[dstIndex++] = (u_char)floor((src[srcIndex] * 255.f + .5f));
dst[dstIndex++] = 0xff;
srcIndex += 3;
}
}
}
PyBuffer_Release(&srcView);
PyBuffer_Release(&dstView);
}
//------------------------------------------------------------------------------
// General utility functions for the Blender addon
//------------------------------------------------------------------------------
// No safety checks to gain speed, this function is called for each particle,
// potentially millions of times.
boost::python::list BlenderMatrix4x4ToList(boost::python::object &blenderMatrix) {
const PyObject *pyObj = blenderMatrix.ptr();
const MatrixObject *blenderMatrixObj = (MatrixObject *)pyObj;
boost::python::list result;
for (int i = 0; i < 16; ++i) {
result.append(blenderMatrixObj->matrix[i]);
}
// Make invertible if necessary
Matrix4x4 matrix(blenderMatrixObj->matrix);
if (matrix.Determinant() == 0.f) {
const float epsilon = 1e-8f;
result[0] += epsilon; // [0][0]
result[5] += epsilon; // [1][1]
result[10] += epsilon; // [2][2]
result[15] += epsilon; // [3][3]
}
return result;
}
//------------------------------------------------------------------------------
// OpenVDB helper functions
//------------------------------------------------------------------------------
boost::python::list GetOpenVDBGridNames(const string &filePathStr) {
boost::python::list gridNames;
openvdb::io::File file(filePathStr);
file.open();
for (auto i = file.beginName(); i != file.endName(); ++i)
gridNames.append(*i);
file.close();
return gridNames;
}
boost::python::tuple GetOpenVDBGridInfo(const string &filePathStr, const string &gridName) {
boost::python::list bBox;
boost::python::list bBox_w;
boost::python::list trans_matrix;
boost::python::list BlenderMetadata;
openvdb::io::File file(filePathStr);
file.open();
openvdb::MetaMap::Ptr ovdbMetaMap = file.getMetadata();
string creator = "";
try {
creator = ovdbMetaMap->metaValue<string>("creator");
} catch (openvdb::LookupError &e) {
cout << "No creator file meta data found in OpenVDB file " + filePathStr << endl;
};
openvdb::GridBase::Ptr ovdbGrid = file.readGridMetadata(gridName);
//const openvdb::Vec3i bbox_min = ovdbGrid->metaValue<openvdb::Vec3i>("file_bbox_min");
//const openvdb::Vec3i bbox_max = ovdbGrid->metaValue<openvdb::Vec3i>("file_bbox_max");
const openvdb::math::Transform &transform = ovdbGrid->transform();
openvdb::math::Mat4f matrix = transform.baseMap()->getAffineMap()->getMat4();
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
trans_matrix.append(matrix(col, row));
}
}
// Read the grid from the file
ovdbGrid = file.readGrid(gridName);
openvdb::CoordBBox coordbbox;
ovdbGrid->baseTree().evalLeafBoundingBox(coordbbox);
openvdb::BBoxd bbox_world = ovdbGrid->transform().indexToWorld(coordbbox);
bBox.append(coordbbox.min()[0]);
bBox.append(coordbbox.min()[1]);
bBox.append(coordbbox.min()[2]);
bBox.append(coordbbox.max()[0]);
bBox.append(coordbbox.max()[1]);
bBox.append(coordbbox.max()[2]);
bBox_w.append(bbox_world.min().x());
bBox_w.append(bbox_world.min().y());
bBox_w.append(bbox_world.min().z());
bBox_w.append(bbox_world.max().x());
bBox_w.append(bbox_world.max().y());
bBox_w.append(bbox_world.max().z());
if (creator == "Blender/Smoke") {
boost::python::list min_bbox_list;
boost::python::list max_bbox_list;
boost::python::list res_list;
boost::python::list minres_list;
boost::python::list maxres_list;
boost::python::list baseres_list;
boost::python::list obmat_list;
boost::python::list obj_shift_f_list;
openvdb::Vec3s min_bbox = ovdbMetaMap->metaValue<openvdb::Vec3s>("blender/smoke/min_bbox");
openvdb::Vec3s max_bbox = ovdbMetaMap->metaValue<openvdb::Vec3s>("blender/smoke/max_bbox");
openvdb::Vec3i res = ovdbMetaMap->metaValue<openvdb::Vec3i>("blender/smoke/resolution");
//adaptive domain settings
openvdb::Vec3i minres = ovdbMetaMap->metaValue<openvdb::Vec3i>("blender/smoke/min_resolution");
openvdb::Vec3i maxres = ovdbMetaMap->metaValue<openvdb::Vec3i>("blender/smoke/max_resolution");
openvdb::Vec3i base_res = ovdbMetaMap->metaValue<openvdb::Vec3i>("blender/smoke/base_resolution");
openvdb::Mat4s obmat = ovdbMetaMap->metaValue<openvdb::Mat4s>("blender/smoke/obmat");
openvdb::Vec3s obj_shift_f = ovdbMetaMap->metaValue<openvdb::Vec3s>("blender/smoke/obj_shift_f");
min_bbox_list.append(min_bbox[0]);
min_bbox_list.append(min_bbox[1]);
min_bbox_list.append(min_bbox[2]);
max_bbox_list.append(max_bbox[0]);
max_bbox_list.append(max_bbox[1]);
max_bbox_list.append(max_bbox[2]);
res_list.append(res[0]);
res_list.append(res[1]);
res_list.append(res[2]);
minres_list.append(minres[0]);
minres_list.append(minres[1]);
minres_list.append(minres[2]);
maxres_list.append(maxres[0]);
maxres_list.append(maxres[1]);
maxres_list.append(maxres[2]);
baseres_list.append(base_res[0]);
baseres_list.append(base_res[1]);
baseres_list.append(base_res[2]);
obmat_list.append(obmat[0][0]);
obmat_list.append(obmat[0][1]);
obmat_list.append(obmat[0][2]);
obmat_list.append(obmat[0][3]);
obmat_list.append(obmat[1][0]);
obmat_list.append(obmat[1][1]);
obmat_list.append(obmat[1][2]);
obmat_list.append(obmat[1][3]);
obmat_list.append(obmat[2][0]);
obmat_list.append(obmat[2][1]);
obmat_list.append(obmat[2][2]);
obmat_list.append(obmat[2][3]);
obmat_list.append(obmat[3][0]);
obmat_list.append(obmat[3][1]);
obmat_list.append(obmat[3][2]);
obmat_list.append(obmat[3][3]);
obj_shift_f_list.append(obj_shift_f[0]);
obj_shift_f_list.append(obj_shift_f[1]);
obj_shift_f_list.append(obj_shift_f[2]);
BlenderMetadata.append(min_bbox_list);
BlenderMetadata.append(max_bbox_list);
BlenderMetadata.append(res_list);
BlenderMetadata.append(minres_list);
BlenderMetadata.append(maxres_list);
BlenderMetadata.append(baseres_list);
BlenderMetadata.append(obmat_list);
BlenderMetadata.append(obj_shift_f_list);
};
file.close();
return boost::python::make_tuple(creator, bBox, bBox_w, trans_matrix, ovdbGrid->valueType(), BlenderMetadata);
}
//------------------------------------------------------------------------------
// Mesh conversion functions
//------------------------------------------------------------------------------
static bool Scene_DefineBlenderMesh(luxcore::detail::SceneImpl *scene, const string &name,
const size_t loopTriCount, const size_t loopTriPtr,
const size_t loopPtr,
const size_t vertPtr,
const size_t polyPtr,
const boost::python::object &loopUVsPtrList,
const boost::python::object &loopColsPtrList,
const size_t meshPtr,
const short matIndex,
const luxrays::Transform *trans,
const boost::python::tuple &blenderVersion,
const boost::python::object &loopTriCustomNormals) {
const MLoopTri *loopTris = reinterpret_cast<const MLoopTri *>(loopTriPtr);
const MLoop *loops = reinterpret_cast<const MLoop *>(loopPtr);
const MVert *verts = reinterpret_cast<const MVert *>(vertPtr);
const MPoly *polygons = reinterpret_cast<const MPoly *>(polyPtr);
extract<boost::python::list> getUVPtrList(loopUVsPtrList);
extract<boost::python::list> getColPtrList(loopColsPtrList);
// Check UVs
if (!getUVPtrList.check()) {
const string objType = extract<string>((loopUVsPtrList.attr("__class__")).attr("__name__"));
throw runtime_error("Wrong data type for the list of UV maps of method Scene.DefineMesh(): " + objType);
}
const boost::python::list &UVsList = getUVPtrList();
const boost::python::ssize_t loopUVsCount = len(UVsList);
if (loopUVsCount > EXTMESH_MAX_DATA_COUNT) {
throw runtime_error("Too many UV Maps in list for method Scene.DefineMesh()");
}
// Check vertex colors
if (!getColPtrList.check()) {
const string objType = extract<string>((loopColsPtrList.attr("__class__")).attr("__name__"));
throw runtime_error("Wrong data type for the list of Vertex Color maps of method Scene.DefineMesh(): " + objType);
}
const boost::python::list &ColsList = getColPtrList();
const boost::python::ssize_t loopColsCount = len(ColsList);
if (loopColsCount > EXTMESH_MAX_DATA_COUNT) {
throw runtime_error("Too many Vertex Color Maps in list for method Scene.DefineMesh()");
}
vector<Normal> customNormals;
bool hasCustomNormals = false;
{
const float(*loopNormals)[3] = nullptr;
u_int loopCount = 0;
if (len(blenderVersion) != 3) {
throw runtime_error("Blender version tuple needs to have exactly 3 elements for Scene.DefineMesh()");
}
const int blenderVersionMajor = extract<int>(blenderVersion[0]);
const int blenderVersionMinor = extract<int>(blenderVersion[1]);
const int blenderVersionSub = extract<int>(blenderVersion[2]);
if (blenderVersionMajor == 2 && blenderVersionMinor == 82 && blenderVersionSub == 7) {
const blender_2_82::Mesh *mesh = reinterpret_cast<const blender_2_82::Mesh*>(meshPtr);
loopNormals = static_cast<const float(*)[3]>(CustomData_get_layer(&mesh->ldata, blender_2_82::CD_NORMAL));
loopCount = mesh->totloop;
} else if (blenderVersionMajor == 2 && blenderVersionMinor == 83) {
// Not checking the sub version here, for now we assume that these data structures stay the same across sub releases
const blender_2_83::Mesh *mesh = reinterpret_cast<const blender_2_83::Mesh*>(meshPtr);
loopNormals = static_cast<const float(*)[3]>(CustomData_get_layer(&mesh->ldata, blender_2_83::CD_NORMAL));
loopCount = mesh->totloop;
}
if (loopNormals) {
hasCustomNormals = true;
for (u_int i = 0; i < loopCount; ++i) {
customNormals.emplace_back(Normal(loopNormals[i][0], loopNormals[i][1], loopNormals[i][2]));
}
} else {
// Fallback to Python-converted custom normals if we don't have support for the mesh layout of this Blender version
hasCustomNormals = !loopTriCustomNormals.is_none();
if (hasCustomNormals) {
extract<boost::python::list> getCustomNormalsList(loopTriCustomNormals);
if (!getCustomNormalsList.check()) {
const string objType = extract<string>((loopUVsPtrList.attr("__class__")).attr("__name__"));
throw runtime_error("Wrong data type for the list of custom normals of method Scene.DefineMesh(): " + objType);
}
const boost::python::list &loopTriCustomNormalsList = getCustomNormalsList();
const boost::python::ssize_t loopCustomNormalsCount = len(loopTriCustomNormalsList);
for (int i = 0; i < loopCustomNormalsCount; i += 3) {
const float x = extract<float>(loopTriCustomNormalsList[i]);
const float y = extract<float>(loopTriCustomNormalsList[i + 1]);
const float z = extract<float>(loopTriCustomNormalsList[i + 2]);
customNormals.emplace_back(Normal(x, y, z));
}
}
}
}
vector<const MLoopUV *> loopUVsList;
vector<const MLoopCol *> loopColsList;
vector<Point> tmpMeshVerts;
vector<Normal> tmpMeshNorms;
vector<vector<UV>> tmpMeshUVs;
vector<vector<Spectrum>> tmpMeshCols;
vector<Triangle> tmpMeshTris;
for (u_int i = 0; i < loopUVsCount; ++i) {
const size_t UVListPtr = extract<size_t>(UVsList[i]);
loopUVsList.push_back(reinterpret_cast<const MLoopUV *>(UVListPtr));
vector<UV> temp;
tmpMeshUVs.push_back(temp);
}
for (u_int i = 0; i < loopColsCount; ++i) {
const size_t ColListPtr = extract<size_t>(ColsList[i]);
loopColsList.push_back(reinterpret_cast<const MLoopCol *>(ColListPtr));
vector<Spectrum> temp;
tmpMeshCols.push_back(temp);
}
u_int vertFreeIndex = 0;
boost::unordered_map<u_int, u_int> vertexMap;
const float normalScale = 1.f / 32767.f;
const float rgbScale = 1.f / 255.f;
for (u_int loopTriIndex = 0; loopTriIndex < loopTriCount; ++loopTriIndex) {
const MLoopTri &loopTri = loopTris[loopTriIndex];
const MPoly &poly = polygons[loopTri.poly];
if (poly.mat_nr != matIndex)
continue;
u_int vertIndices[3];
if ((poly.flag & ME_SMOOTH) || hasCustomNormals) {
// Smooth shaded, use the Blender vertex normal
for (u_int i = 0; i < 3; ++i) {
const u_int tri = loopTri.tri[i];
const u_int index = loops[tri].v;
// Check if it has been already defined
bool alreadyDefined = (vertexMap.find(index) != vertexMap.end());
if (alreadyDefined) {
const u_int mappedIndex = vertexMap[index];
if (hasCustomNormals && (customNormals[tri] != tmpMeshNorms[mappedIndex]))
alreadyDefined = false;
for (u_int uvLayerIndex = 0; uvLayerIndex < loopUVsList.size() && alreadyDefined; ++uvLayerIndex) {
const MLoopUV *loopUVs = loopUVsList[uvLayerIndex];
if (loopUVs) {
const MLoopUV &loopUV = loopUVs[tri];
// Check if the already defined vertex has the right UV coordinates
if ((loopUV.uv[0] != tmpMeshUVs[uvLayerIndex][mappedIndex].u) ||
(loopUV.uv[1] != tmpMeshUVs[uvLayerIndex][mappedIndex].v)) {
// I have to create a new vertex
alreadyDefined = false;
}
}
}
for (u_int colLayerIndex = 0; colLayerIndex < loopColsList.size() && alreadyDefined; ++colLayerIndex) {
const MLoopCol *loopCols = loopColsList[colLayerIndex];
if (loopCols) {
const MLoopCol &loopCol = loopCols[tri];
// Check if the already defined vertex has the right color
if (((loopCol.r * rgbScale) != tmpMeshCols[colLayerIndex][mappedIndex].c[0]) ||
((loopCol.g * rgbScale) != tmpMeshCols[colLayerIndex][mappedIndex].c[1]) ||
((loopCol.b * rgbScale) != tmpMeshCols[colLayerIndex][mappedIndex].c[2])) {
// I have to create a new vertex
alreadyDefined = false;
}
}
}
}
if (alreadyDefined)
vertIndices[i] = vertexMap[index];
else {
const MVert &vertex = verts[index];
// Add the vertex
tmpMeshVerts.emplace_back(Point(vertex.co));
// Add the normal
if (hasCustomNormals) {
tmpMeshNorms.push_back(customNormals[tri]);
} else {
tmpMeshNorms.push_back(Normalize(Normal(
vertex.no[0] * normalScale,
vertex.no[1] * normalScale,
vertex.no[2] * normalScale)));
}
// Add the UV
for (u_int uvLayerIndex = 0; uvLayerIndex < loopUVsList.size(); ++uvLayerIndex) {
const MLoopUV *loopUVs = loopUVsList[uvLayerIndex];
if (loopUVs) {
const MLoopUV &loopUV = loopUVs[tri];
tmpMeshUVs[uvLayerIndex].push_back(UV(loopUV.uv));
}
}
// Add the color
for (u_int colLayerIndex = 0; colLayerIndex < loopColsList.size(); ++colLayerIndex) {
const MLoopCol *loopCols = loopColsList[colLayerIndex];
if (loopCols) {
const MLoopCol &loopCol = loopCols[tri];
tmpMeshCols[colLayerIndex].push_back(Spectrum(
loopCol.r * rgbScale,
loopCol.g * rgbScale,
loopCol.b * rgbScale));
}
}
// Add the vertex mapping
const u_int vertIndex = vertFreeIndex++;
vertexMap[index] = vertIndex;
vertIndices[i] = vertIndex;
}
}
} else {
// Flat shaded, use the Blender face normal
const MVert &v0 = verts[loops[loopTri.tri[0]].v];
const MVert &v1 = verts[loops[loopTri.tri[1]].v];
const MVert &v2 = verts[loops[loopTri.tri[2]].v];
const Point p0(v0.co);
const Point p1(v1.co);
const Point p2(v2.co);
const Vector e1 = p1 - p0;
const Vector e2 = p2 - p0;
Normal faceNormal(Cross(e1, e2));
if ((faceNormal.x != 0.f) || (faceNormal.y != 0.f) || (faceNormal.z != 0.f))
faceNormal /= faceNormal.Length();
for (u_int i = 0; i < 3; ++i) {
const u_int tri = loopTri.tri[i];
const u_int index = loops[tri].v;
// Check if it has been already defined
bool alreadyDefined = (vertexMap.find(index) != vertexMap.end());
if (alreadyDefined) {
const u_int mappedIndex = vertexMap[index];
// In order to have flat shading, we need to duplicate vertices with differing normals
if (faceNormal != tmpMeshNorms[mappedIndex])
alreadyDefined = false;
for (u_int uvLayerIndex = 0; uvLayerIndex < loopUVsList.size() && alreadyDefined; ++uvLayerIndex) {
const MLoopUV * loopUVs = loopUVsList[uvLayerIndex];
if (loopUVs) {
const MLoopUV &loopUV = loopUVs[tri];
// Check if the already defined vertex has the right UV coordinates
if ((loopUV.uv[0] != tmpMeshUVs[uvLayerIndex][mappedIndex].u) ||
(loopUV.uv[1] != tmpMeshUVs[uvLayerIndex][mappedIndex].v)) {
// I have to create a new vertex
alreadyDefined = false;
}
}
}
for (u_int colLayerIndex = 0; colLayerIndex < loopColsList.size() && alreadyDefined; ++colLayerIndex) {
const MLoopCol * loopCols = loopColsList[colLayerIndex];
if (loopCols) {
const MLoopCol &loopCol = loopCols[tri];
// Check if the already defined vertex has the right color
if (((loopCol.r * rgbScale) != tmpMeshCols[colLayerIndex][mappedIndex].c[0]) ||
((loopCol.g * rgbScale) != tmpMeshCols[colLayerIndex][mappedIndex].c[1]) ||
((loopCol.b * rgbScale) != tmpMeshCols[colLayerIndex][mappedIndex].c[2])) {
// I have to create a new vertex
alreadyDefined = false;
}
}
}
}
if (alreadyDefined)
vertIndices[i] = vertexMap[index];
else {
const MVert &vertex = verts[index];
// Add the vertex
tmpMeshVerts.emplace_back(Point(vertex.co));
// Add the normal (same for all vertices of this face, to have flat shading)
tmpMeshNorms.push_back(faceNormal);
// Add the UV
for (u_int uvLayerIndex = 0; uvLayerIndex < loopUVsList.size(); ++uvLayerIndex) {
const MLoopUV * loopUVs = loopUVsList[uvLayerIndex];
if (loopUVs) {
const MLoopUV &loopUV = loopUVs[tri];
tmpMeshUVs[uvLayerIndex].push_back(UV(loopUV.uv));
}
}
// Add the color
for (u_int colLayerIndex = 0; colLayerIndex < loopColsList.size(); ++colLayerIndex) {
const MLoopCol * loopCols = loopColsList[colLayerIndex];
if (loopCols) {
const MLoopCol &loopCol = loopCols[tri];
tmpMeshCols[colLayerIndex].push_back(Spectrum(
loopCol.r * rgbScale,
loopCol.g * rgbScale,
loopCol.b * rgbScale));
}
}
// Add the vertex mapping
const u_int vertIndex = vertFreeIndex++;
vertexMap[index] = vertIndex;
vertIndices[i] = vertIndex;
}
}
}
tmpMeshTris.emplace_back(Triangle(vertIndices[0], vertIndices[1], vertIndices[2]));
}
// Check if there wasn't any triangles with matIndex
if (tmpMeshTris.size() == 0)
return false;
// Allocate memory for LuxCore mesh data
Triangle *meshTris = TriangleMesh::AllocTrianglesBuffer(tmpMeshTris.size());
copy(tmpMeshTris.begin(), tmpMeshTris.end(), meshTris);
Point *meshVerts = TriangleMesh::AllocVerticesBuffer(tmpMeshVerts.size());
copy(tmpMeshVerts.begin(), tmpMeshVerts.end(), meshVerts);
Normal *meshNorms = new Normal[tmpMeshVerts.size()];
copy(tmpMeshNorms.begin(), tmpMeshNorms.end(), meshNorms);
array<UV *, EXTMESH_MAX_DATA_COUNT> meshUVs;
array<Spectrum *, EXTMESH_MAX_DATA_COUNT> meshCols;
fill(meshUVs.begin(), meshUVs.end(), nullptr);
fill(meshCols.begin(), meshCols.end(), nullptr);
for (u_int i = 0; i < loopUVsList.size(); ++i) {
const MLoopUV * loopUVs = loopUVsList[i];
if (loopUVs) {
meshUVs[i] = new UV[tmpMeshVerts.size()];
copy(tmpMeshUVs[i].begin(), tmpMeshUVs[i].end(), meshUVs[i]);
}
}
for (u_int i = 0; i < loopColsList.size(); ++i) {
const MLoopCol * loopCols = loopColsList[i];
if (loopCols) {
meshCols[i] = new Spectrum[tmpMeshVerts.size()];
copy(tmpMeshCols[i].begin(), tmpMeshCols[i].end(), meshCols[i]);
}
}
luxrays::ExtTriangleMesh *mesh = new luxrays::ExtTriangleMesh(tmpMeshVerts.size(),
tmpMeshTris.size(), meshVerts, meshTris,
meshNorms, &meshUVs, &meshCols, NULL);
// Apply the transformation if required
if (trans)
mesh->ApplyTransform(*trans);
mesh->SetName(name);
scene->DefineMesh(mesh);
return true;
}
boost::python::list Scene_DefineBlenderMesh1(luxcore::detail::SceneImpl *scene, const string &name,
const size_t loopTriCount, const size_t loopTriPtr,
const size_t loopPtr,
const size_t vertPtr,
const size_t polyPtr,
const boost::python::object &loopUVsPtrList,
const boost::python::object &loopColsPtrList,
const size_t meshPtr,
const u_int materialCount,
const boost::python::object &transformation,
const boost::python::tuple &blenderVersion,
const boost::python::object &loopTriCustomNormals) {
// Get the transformation if required
bool hasTransformation = false;
Transform trans;
if (!transformation.is_none()) {
trans = ExtractTransformation(transformation);
hasTransformation = true;
}
boost::python::list result;
for (u_int matIndex = 0; matIndex < materialCount; ++matIndex) {
const string meshName = (boost::format(name + "%03d") % matIndex).str();
if (Scene_DefineBlenderMesh(scene, meshName, loopTriCount, loopTriPtr,
loopPtr, vertPtr, polyPtr,
loopUVsPtrList, loopColsPtrList,
meshPtr,
matIndex,
hasTransformation ? &trans : NULL,
blenderVersion,
loopTriCustomNormals)) {
boost::python::list meshInfo;
meshInfo.append(meshName);
meshInfo.append(matIndex);
result.append(meshInfo);
}
}
return result;
}
boost::python::list Scene_DefineBlenderMesh2(luxcore::detail::SceneImpl *scene, const string &name,
const size_t loopTriCount, const size_t loopTriPtr,
const size_t loopPtr,
const size_t vertPtr,
const size_t polyPtr,
const boost::python::object &loopUVsPtrList,
const boost::python::object &loopColsPtrList,
const size_t meshPtr,
const u_int materialCount,
const boost::python::tuple &blenderVersion,
const boost::python::object &loopTriCustomNormals) {
return Scene_DefineBlenderMesh1(scene, name, loopTriCount, loopTriPtr,
loopPtr, vertPtr, polyPtr, loopUVsPtrList, loopColsPtrList,
meshPtr, materialCount, boost::python::object(), blenderVersion,
loopTriCustomNormals);
}
//------------------------------------------------------------------------------
// Hair/strands conversion functions
//------------------------------------------------------------------------------
bool nearlyEqual(const float a, const float b, const float epsilon) {
return fabs(a - b) < epsilon;
}
Spectrum getColorFromImage(const vector<float> &imageData, const float gamma,
const u_int width, const u_int height, const u_int channelCount,
const float u, const float v) {
assert (width > 0);
assert (height > 0);
const u_int x = u * (width - 1);
// The pixels coming from OIIO are flipped in y direction, so we flip v
const u_int y = (1.f - v) * (height - 1);
assert (x >= 0);
assert (x < width);
assert (y >= 0);
assert (y < height);
const u_int index = (width * y + x) * channelCount;
if (channelCount == 1) {
return Spectrum(powf(imageData[index], gamma));
} else {
// In case of channelCount == 4, we just ignore the alpha channel
return Spectrum(powf(imageData[index], gamma),
powf(imageData[index + 1], gamma),
powf(imageData[index + 2], gamma));
}
}
// Returns true if the shape could be defined successfully, false otherwise.
// root_width, tip_width and width_offset are percentages (range 0..1).
bool Scene_DefineBlenderStrands(luxcore::detail::SceneImpl *scene,
const string &shapeName,
const u_int pointsPerStrand,
const boost::python::object &points,
const boost::python::object &colors,
const boost::python::object &uvs,
const string &imageFilename,
const float imageGamma,
const bool copyUVs,
const boost::python::object &transformation,
const float strandDiameter,
const float rootWidth,
const float tipWidth,
const float widthOffset,
const string &tessellationTypeStr,
const u_int adaptiveMaxDepth, const float adaptiveError,
const u_int solidSideCount, const bool solidCapBottom, const bool solidCapTop,
const boost::python::list &rootColor,
const boost::python::list &tipColor) {
//--------------------------------------------------------------------------
// Extract arguments (e.g. numpy arrays)
//--------------------------------------------------------------------------
if (pointsPerStrand == 0)
throw runtime_error("pointsPerStrand needs to be greater than 0");
// Points
extract<np::ndarray> getPointsArray(points);
if (!getPointsArray.check())
throw runtime_error("Points: not a numpy ndarray");
const np::ndarray &arrPoints = getPointsArray();
if (arrPoints.get_dtype() != np::dtype::get_builtin<float>())
throw runtime_error("Points: Wrong ndarray dtype (required: float32)");
if (arrPoints.get_nd() != 1)
throw runtime_error("Points: Wrong number of dimensions (required: 1)");
const float * const pointsStartPtr = reinterpret_cast<const float*>(arrPoints.get_data());
const int pointArraySize = arrPoints.shape(0);
const int pointStride = 3;
const size_t inputPointCount = pointArraySize / pointStride;
// Colors
extract<np::ndarray> getColorsArray(colors);
if (!getColorsArray.check())
throw runtime_error("Colors: not a numpy ndarray");
const np::ndarray &arrColors = getColorsArray();
if (arrColors.get_dtype() != np::dtype::get_builtin<float>())
throw runtime_error("Colors: Wrong ndarray dtype (required: float32)");
if (arrColors.get_nd() != 1)
throw runtime_error("Colors: Wrong number of dimensions (required: 1)");
const float * const colorsStartPtr = reinterpret_cast<const float*>(arrColors.get_data());
const int colorArraySize = arrColors.shape(0);
const int colorStride = 3;
// const size_t inputColorCount = colorArraySize / colorStride;
const bool useVertexCols = colorArraySize > 0;
// Root/tip colors
if (len(rootColor) != 3)
throw runtime_error("rootColor list has wrong length (required: 3)");
if (len(tipColor) != 3)
throw runtime_error("tipColor list has wrong length (required: 3)");
const float rootColorR = extract<float>(rootColor[0]);
const float rootColorG = extract<float>(rootColor[1]);
const float rootColorB = extract<float>(rootColor[2]);
const float tipColorR = extract<float>(tipColor[0]);
const float tipColorG = extract<float>(tipColor[1]);
const float tipColorB = extract<float>(tipColor[2]);
const Spectrum rootCol(rootColorR, rootColorG, rootColorB);
const Spectrum tipCol(tipColorR, tipColorG, tipColorB);
const Spectrum white(1.f);
// Since root and tip colors are multipliers, we don't need them if both are white
const bool useRootTipColors = rootCol != white || tipCol != white;
// UVs
extract<np::ndarray> getUVsArray(uvs);
if (!getUVsArray.check())
throw runtime_error("UVs: not a numpy ndarray");
const np::ndarray &arrUVs = getUVsArray();
if (arrUVs.get_dtype() != np::dtype::get_builtin<float>())
throw runtime_error("UVs: Wrong ndarray dtype (required: float32)");
if (arrUVs.get_nd() != 1)
throw runtime_error("UVs: Wrong number of dimensions (required: 1)");
const float * const uvsStartPtr = reinterpret_cast<const float*>(arrUVs.get_data());
const int uvArraySize = arrUVs.shape(0);
const int uvStride = 2;
// If UVs are used, we expect one UV coord per strand (not per point)
const int inputUVCount = uvArraySize / uvStride;
const int inputStrandCount = inputPointCount / pointsPerStrand;
if (uvArraySize > 0 && inputUVCount != inputStrandCount)
throw runtime_error("UV array size is " + to_string(inputUVCount)
+ " (expected: " + to_string(inputStrandCount) + ")");
if (copyUVs && uvArraySize == 0)
throw runtime_error("Can not copy UVs without UV array");
// Tessellation type
Scene::StrandsTessellationType tessellationType;
if (tessellationTypeStr == "ribbon")
tessellationType = Scene::TESSEL_RIBBON;
else if (tessellationTypeStr == "ribbonadaptive")
tessellationType = Scene::TESSEL_RIBBON_ADAPTIVE;
else if (tessellationTypeStr == "solid")
tessellationType = Scene::TESSEL_SOLID;
else if (tessellationTypeStr == "solidadaptive")
tessellationType = Scene::TESSEL_SOLID_ADAPTIVE;
else
throw runtime_error("Unknown tessellation type: " + tessellationTypeStr);
// Transformation
bool hasTransformation = false;
Transform trans;
if (!transformation.is_none()) {
trans = ExtractTransformation(transformation);
hasTransformation = true;
}
//--------------------------------------------------------------------------
// Load image if required
//--------------------------------------------------------------------------
vector<float> imageData;
u_int width = 0;
u_int height = 0;
u_int channelCount = 0;
if (uvArraySize > 0 && !imageFilename.empty()) {
ImageSpec config;
config.attribute ("oiio:UnassociatedAlpha", 1);
unique_ptr<ImageInput> in(ImageInput::open(imageFilename, &config));
if (!in.get()) {
throw runtime_error("Error opening image file : " + imageFilename +
"\n" + geterror());
}
const ImageSpec &spec = in->spec();
width = spec.width;
height = spec.height;
channelCount = spec.nchannels;
if (channelCount != 1 && channelCount != 3 && channelCount != 4) {
throw runtime_error("Unsupported number of channels (" + to_string(channelCount)
+ ") in image file: " + imageFilename
+ " (supported: 1, 3, or 4 channels)");
}
imageData.resize(width * height * channelCount);
in->read_image(TypeDesc::FLOAT, &imageData[0]);
in->close();
in.reset();
}
if (!imageFilename.empty() && uvArraySize == 0)
throw runtime_error("Image provided, but no UV data");
const bool colorsFromImage = uvArraySize > 0 && !imageFilename.empty();
if (useVertexCols && colorsFromImage)
throw runtime_error("Can't copy colors from both image and color array");
//--------------------------------------------------------------------------
// Remove invalid points, create other arrays (segments, thickness etc.)
//--------------------------------------------------------------------------
// There can be invalid points, so we have to filter them
const float epsilon = 0.000000001f;
const Point invalidPoint(0.f, 0.f, 0.f);
vector<u_short> segments;
segments.reserve(inputPointCount / pointsPerStrand);
// We save the filtered points as raw floats so we can easily move later
vector<float> filteredPoints;
filteredPoints.reserve(pointArraySize);
// We only need the thickness array if rootWidth and tipWidth are not equal.
// Also, if the widthOffset is 1, there is no thickness variation.
const bool useThicknessArray = !nearlyEqual(rootWidth, tipWidth, epsilon)
&& !nearlyEqual(widthOffset, 1.f, epsilon);
vector<float> thickness;
if (useThicknessArray) {
thickness.reserve(inputPointCount);
} else {
thickness.push_back(strandDiameter * rootWidth);
}
const bool useColorsArray = colorsFromImage || useVertexCols || useRootTipColors;
vector<float> filteredColors;
if (useColorsArray) {
filteredColors.reserve(inputPointCount * colorStride);
}
const bool useUVsArray = inputUVCount > 0 && copyUVs;
vector<float> filteredUVs;
if (useUVsArray) {
filteredUVs.reserve(inputPointCount * uvStride);
}
const float *pointPtr = pointsStartPtr;
const float *uvPtr = uvsStartPtr;
const float *colorPtr = colorsStartPtr;
while (pointPtr < (pointsStartPtr + pointArraySize)) {
u_short validPointCount = 0;
// We only have uv and color information for the first point of each strand
float u = 0.f, v = 0.f, r = 1.f, g = 1.f, b = 1.f;
if (useUVsArray || colorsFromImage) {
u = *uvPtr++;
v = *uvPtr++;
// Bring u and v into range 0..1
u -= floor(u);
v -= floor(v);
}
if (useVertexCols) {
r = *colorPtr++;
g = *colorPtr++;
b = *colorPtr++;
}
Point currPoint = Point(pointPtr);
if (hasTransformation)
currPoint *= trans;
pointPtr += pointStride;
Point lastPoint;
// Iterate over the strand. We can skip step == 0.
for (u_int step = 1; step < pointsPerStrand; ++step) {
lastPoint = currPoint;
currPoint = Point(pointPtr);
if (hasTransformation)
currPoint *= trans;
pointPtr += pointStride;
if (lastPoint == invalidPoint || currPoint == invalidPoint) {
// Blender sometimes creates points that are all zeros, e.g. if
// hair length is textured and an area is black (length == 0)
continue;
}
const float segmentLengthSqr = DistanceSquared(currPoint, lastPoint);
if (segmentLengthSqr < epsilon) {
continue;
}
if (step == 1) {
filteredPoints.push_back(lastPoint.x);
filteredPoints.push_back(lastPoint.y);
filteredPoints.push_back(lastPoint.z);
validPointCount++;
// The root point of a strand always uses the rootWidth
if (useThicknessArray) {
thickness.push_back(rootWidth * strandDiameter);
}
if (useUVsArray) {
filteredUVs.push_back(u);
filteredUVs.push_back(v);
}
Spectrum colPoint(1.f);
if (colorsFromImage) {
colPoint = getColorFromImage(imageData, imageGamma,
width, height,
channelCount, u, v);
}
if (useVertexCols) {
colPoint = Spectrum(r, g, b);
}
if (useColorsArray) {
if (useRootTipColors) {
// We are in the root, no need to interpolate
colPoint *= rootCol;
}
filteredColors.push_back(colPoint.c[0]);
filteredColors.push_back(colPoint.c[1]);
filteredColors.push_back(colPoint.c[2]);
}
}
filteredPoints.push_back(currPoint.x);
filteredPoints.push_back(currPoint.y);
filteredPoints.push_back(currPoint.z);
validPointCount++;
if (useThicknessArray) {
const float widthOffsetSteps = widthOffset * (pointsPerStrand - 1);
if (step < widthOffsetSteps) {
// We are still in the root part
thickness.push_back(rootWidth * strandDiameter);
} else {
// We are above the root, interpolate thickness
const float normalizedPosition = ((float)step - widthOffsetSteps)
/ (pointsPerStrand - 1 - widthOffsetSteps);
const float relativeThick = Lerp(normalizedPosition, rootWidth, tipWidth);
thickness.push_back(relativeThick * strandDiameter);
}
}
if (useUVsArray) {
filteredUVs.push_back(u);
filteredUVs.push_back(v);
}
Spectrum colPoint(1.f);
if (colorsFromImage) {
colPoint = getColorFromImage(imageData, imageGamma,
width, height,
channelCount, u, v);
}
if (useVertexCols) {
colPoint = Spectrum(r, g, b);
}
if (useColorsArray) {
if (useRootTipColors) {
if (step == pointsPerStrand - 1) {
// We are in the root, no need to interpolate
colPoint *= tipCol;
} else {
const float normalizedPosition = (float)step / (pointsPerStrand - 1);
colPoint *= Lerp(normalizedPosition, rootCol, tipCol);
}
}
filteredColors.push_back(colPoint.c[0]);
filteredColors.push_back(colPoint.c[1]);
filteredColors.push_back(colPoint.c[2]);
}
}
if (validPointCount == 1) {
// Can't make a segment with only one point, rollback
for (int i = 0; i < pointStride; ++i)
filteredPoints.pop_back();
if (useThicknessArray)
thickness.pop_back();
if (useColorsArray) {
for (int i = 0; i < colorStride; ++i)
filteredColors.pop_back();
}
if (useUVsArray) {
for (int i = 0; i < uvStride; ++i)
filteredUVs.pop_back();
}
} else if (validPointCount > 1) {
segments.push_back(validPointCount - 1);
}
}
if (segments.empty()) {
SLG_LOG("Aborting strand definition: Could not find valid segments!");
return false;
}
const size_t pointCount = filteredPoints.size() / pointStride;
if (pointCount != inputPointCount) {
SLG_LOG("Removed " << (inputPointCount - pointCount) << " invalid points");
}
const bool allSegmentsEqual = std::adjacent_find(segments.begin(), segments.end(),
std::not_equal_to<u_short>()) == segments.end();
//--------------------------------------------------------------------------
// Create hair file header
//--------------------------------------------------------------------------
luxrays::cyHairFile strands;
strands.SetHairCount(segments.size());
strands.SetPointCount(pointCount);
int flags = CY_HAIR_FILE_POINTS_BIT;
if (allSegmentsEqual) {
strands.SetDefaultSegmentCount(segments.at(0));
}
else {
flags |= CY_HAIR_FILE_SEGMENTS_BIT;
}
if (useThicknessArray)
flags |= CY_HAIR_FILE_THICKNESS_BIT;
else
strands.SetDefaultThickness(thickness.at(0));
// We don't need/support vertex alpha at the moment
strands.SetDefaultTransparency(0.f);
if (useColorsArray)
flags |= CY_HAIR_FILE_COLORS_BIT;
else
strands.SetDefaultColor(1.f, 1.f, 1.f);
if (useUVsArray)
flags |= CY_HAIR_FILE_UVS_BIT;
strands.SetArrays(flags);
//--------------------------------------------------------------------------
// Copy/move data into hair file
//--------------------------------------------------------------------------
if (!allSegmentsEqual) {
move(segments.begin(), segments.end(), strands.GetSegmentsArray());
}
if (useThicknessArray) {
move(thickness.begin(), thickness.end(), strands.GetThicknessArray());
}
if (useColorsArray) {
move(filteredColors.begin(), filteredColors.end(), strands.GetColorsArray());
}
if (useUVsArray) {
move(filteredUVs.begin(), filteredUVs.end(), strands.GetUVsArray());
}
move(filteredPoints.begin(), filteredPoints.end(), strands.GetPointsArray());
const bool useCameraPosition = true;
scene->DefineStrands(shapeName, strands,
tessellationType, adaptiveMaxDepth, adaptiveError,
solidSideCount, solidCapBottom, solidCapTop,
useCameraPosition);
return true;
}
} // namespace blender
} // namespace luxcore
| 35.005693 | 130 | 0.661047 | [
"mesh",
"object",
"shape",
"vector",
"transform",
"solid"
] |
c8bd74b2ac3481a49b32664d5c8c9c867e56f706 | 1,309 | hpp | C++ | libraries/chain/include/mos/chain/protocol_feature_activation.hpp | moschain/moschain-master | 418531f281a8a1fb58621bb7f38ad3202edce46f | [
"MIT"
] | null | null | null | libraries/chain/include/mos/chain/protocol_feature_activation.hpp | moschain/moschain-master | 418531f281a8a1fb58621bb7f38ad3202edce46f | [
"MIT"
] | null | null | null | libraries/chain/include/mos/chain/protocol_feature_activation.hpp | moschain/moschain-master | 418531f281a8a1fb58621bb7f38ad3202edce46f | [
"MIT"
] | null | null | null | #pragma once
#include <mos/chain/types.hpp>
namespace mos { namespace chain {
struct protocol_feature_activation : fc::reflect_init {
static constexpr uint16_t extension_id() { return 0; }
static constexpr bool enforce_unique() { return true; }
protocol_feature_activation() = default;
protocol_feature_activation( const vector<digest_type>& pf )
:protocol_features( pf )
{}
protocol_feature_activation( vector<digest_type>&& pf )
:protocol_features( std::move(pf) )
{}
void reflector_init();
vector<digest_type> protocol_features;
};
struct protocol_feature_activation_set;
using protocol_feature_activation_set_ptr = std::shared_ptr<protocol_feature_activation_set>;
struct protocol_feature_activation_set {
flat_set<digest_type> protocol_features;
protocol_feature_activation_set() = default;
protocol_feature_activation_set( const protocol_feature_activation_set& orig_pfa_set,
vector<digest_type> additional_features,
bool enforce_disjoint = true
);
};
} } // namespace mos::chain
FC_REFLECT(mos::chain::protocol_feature_activation, (protocol_features))
FC_REFLECT(mos::chain::protocol_feature_activation_set, (protocol_features))
| 28.456522 | 93 | 0.714286 | [
"vector"
] |
c8bf07cf76318a1a3b801675c9283423ce4d855d | 59,821 | cc | C++ | test/cpp/end2end/xds/xds_ring_hash_end2end_test.cc | PJB2TY/grpc | 1630efd8ab3d2ff4b006f1288fde1be5c29dc651 | [
"Apache-2.0"
] | null | null | null | test/cpp/end2end/xds/xds_ring_hash_end2end_test.cc | PJB2TY/grpc | 1630efd8ab3d2ff4b006f1288fde1be5c29dc651 | [
"Apache-2.0"
] | null | null | null | test/cpp/end2end/xds/xds_ring_hash_end2end_test.cc | PJB2TY/grpc | 1630efd8ab3d2ff4b006f1288fde1be5c29dc651 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
#include "src/core/lib/address_utils/sockaddr_utils.h"
#include "src/core/lib/gpr/env.h"
#include "src/proto/grpc/testing/xds/v3/aggregate_cluster.grpc.pb.h"
#include "src/proto/grpc/testing/xds/v3/cluster.grpc.pb.h"
#include "test/cpp/end2end/connection_delay_injector.h"
#include "test/cpp/end2end/xds/xds_end2end_test_lib.h"
namespace grpc {
namespace testing {
namespace {
using ::envoy::config::cluster::v3::CustomClusterType;
using ::envoy::config::endpoint::v3::HealthStatus;
using ::envoy::extensions::clusters::aggregate::v3::ClusterConfig;
class RingHashTest : public XdsEnd2endTest {
protected:
void SetUp() override {
logical_dns_cluster_resolver_response_generator_ =
grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
InitClient();
ChannelArguments args;
args.SetPointerWithVtable(
GRPC_ARG_XDS_LOGICAL_DNS_CLUSTER_FAKE_RESOLVER_RESPONSE_GENERATOR,
logical_dns_cluster_resolver_response_generator_.get(),
&grpc_core::FakeResolverResponseGenerator::kChannelArgPointerVtable);
ResetStub(/*failover_timeout_ms=*/0, &args);
}
grpc_core::ServerAddressList CreateAddressListFromPortList(
const std::vector<int>& ports) {
grpc_core::ServerAddressList addresses;
for (int port : ports) {
absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(
absl::StrCat(ipv6_only_ ? "ipv6:[::1]:" : "ipv4:127.0.0.1:", port));
GPR_ASSERT(lb_uri.ok());
grpc_resolved_address address;
GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
addresses.emplace_back(address.addr, address.len, nullptr);
}
return addresses;
}
std::string CreateMetadataValueThatHashesToBackendPort(int port) {
return absl::StrCat(ipv6_only_ ? "[::1]" : "127.0.0.1", ":", port, "_0");
}
std::string CreateMetadataValueThatHashesToBackend(int index) {
return CreateMetadataValueThatHashesToBackendPort(backends_[index]->port());
}
grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
logical_dns_cluster_resolver_response_generator_;
};
// Run both with and without load reporting, just for test coverage.
INSTANTIATE_TEST_SUITE_P(
XdsTest, RingHashTest,
::testing::Values(XdsTestType(), XdsTestType().set_enable_load_reporting()),
&XdsTestType::Name);
TEST_P(RingHashTest, AggregateClusterFallBackFromRingHashAtStartup) {
CreateAndStartBackends(2);
const char* kNewCluster1Name = "new_cluster_1";
const char* kNewEdsService1Name = "new_eds_service_name_1";
const char* kNewCluster2Name = "new_cluster_2";
const char* kNewEdsService2Name = "new_eds_service_name_2";
// Populate new EDS resources.
EdsResourceArgs args1({
{"locality0", {MakeNonExistantEndpoint(), MakeNonExistantEndpoint()}},
});
EdsResourceArgs args2({
{"locality0", CreateEndpointsForBackends()},
});
balancer_->ads_service()->SetEdsResource(
BuildEdsResource(args1, kNewEdsService1Name));
balancer_->ads_service()->SetEdsResource(
BuildEdsResource(args2, kNewEdsService2Name));
// Populate new CDS resources.
Cluster new_cluster1 = default_cluster_;
new_cluster1.set_name(kNewCluster1Name);
new_cluster1.mutable_eds_cluster_config()->set_service_name(
kNewEdsService1Name);
balancer_->ads_service()->SetCdsResource(new_cluster1);
Cluster new_cluster2 = default_cluster_;
new_cluster2.set_name(kNewCluster2Name);
new_cluster2.mutable_eds_cluster_config()->set_service_name(
kNewEdsService2Name);
balancer_->ads_service()->SetCdsResource(new_cluster2);
// Create Aggregate Cluster
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kNewCluster1Name);
cluster_config.add_clusters(kNewCluster2Name);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancer_->ads_service()->SetCdsResource(cluster);
// Set up route with channel id hashing
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
// Verifying that we are using ring hash as only 1 endpoint is receiving all
// the traffic.
CheckRpcSendOk(DEBUG_LOCATION, 100);
bool found = false;
for (size_t i = 0; i < backends_.size(); ++i) {
if (backends_[i]->backend_service()->request_count() > 0) {
EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
<< "backend " << i;
EXPECT_FALSE(found) << "backend " << i;
found = true;
}
}
EXPECT_TRUE(found);
}
TEST_P(RingHashTest,
AggregateClusterFallBackFromRingHashToLogicalDnsAtStartup) {
CreateAndStartBackends(1);
const char* kEdsClusterName = "eds_cluster";
const char* kLogicalDNSClusterName = "logical_dns_cluster";
// Populate EDS resource.
EdsResourceArgs args({
{"locality0",
{MakeNonExistantEndpoint(), MakeNonExistantEndpoint()},
kDefaultLocalityWeight,
0},
{"locality1",
{MakeNonExistantEndpoint(), MakeNonExistantEndpoint()},
kDefaultLocalityWeight,
1},
});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// Populate new CDS resources.
Cluster eds_cluster = default_cluster_;
eds_cluster.set_name(kEdsClusterName);
balancer_->ads_service()->SetCdsResource(eds_cluster);
// Populate LOGICAL_DNS cluster.
auto logical_dns_cluster = default_cluster_;
logical_dns_cluster.set_name(kLogicalDNSClusterName);
logical_dns_cluster.set_type(Cluster::LOGICAL_DNS);
auto* address = logical_dns_cluster.mutable_load_assignment()
->add_endpoints()
->add_lb_endpoints()
->mutable_endpoint()
->mutable_address()
->mutable_socket_address();
address->set_address(kServerName);
address->set_port_value(443);
balancer_->ads_service()->SetCdsResource(logical_dns_cluster);
// Create Aggregate Cluster
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
CustomClusterType* custom_cluster = cluster.mutable_cluster_type();
custom_cluster->set_name("envoy.clusters.aggregate");
ClusterConfig cluster_config;
cluster_config.add_clusters(kEdsClusterName);
cluster_config.add_clusters(kLogicalDNSClusterName);
custom_cluster->mutable_typed_config()->PackFrom(cluster_config);
balancer_->ads_service()->SetCdsResource(cluster);
// Set up route with channel id hashing
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
// Set Logical DNS result
{
grpc_core::ExecCtx exec_ctx;
grpc_core::Resolver::Result result;
result.addresses = CreateAddressListFromPortList(GetBackendPorts());
logical_dns_cluster_resolver_response_generator_->SetResponse(
std::move(result));
}
// Inject connection delay to make this act more realistically.
ConnectionDelayInjector delay_injector(
grpc_core::Duration::Milliseconds(500) * grpc_test_slowdown_factor());
delay_injector.Start();
// Send RPC. Need the timeout to be long enough to account for the
// subchannel connection delays.
CheckRpcSendOk(DEBUG_LOCATION, 1, RpcOptions().set_timeout_ms(5000));
}
// Tests that ring hash policy that hashes using channel id ensures all RPCs
// to go 1 particular backend.
TEST_P(RingHashTest, ChannelIdHashing) {
CreateAndStartBackends(4);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
CheckRpcSendOk(DEBUG_LOCATION, 100);
bool found = false;
for (size_t i = 0; i < backends_.size(); ++i) {
if (backends_[i]->backend_service()->request_count() > 0) {
EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
<< "backend " << i;
EXPECT_FALSE(found) << "backend " << i;
found = true;
}
}
EXPECT_TRUE(found);
}
// Tests that ring hash policy that hashes using a header value can spread
// RPCs across all the backends.
TEST_P(RingHashTest, HeaderHashing) {
CreateAndStartBackends(4);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// Note each type of RPC will contains a header value that will always be
// hashed to a specific backend as the header value matches the value used
// to create the entry in the ring.
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
std::vector<std::pair<std::string, std::string>> metadata1 = {
{"address_hash", CreateMetadataValueThatHashesToBackend(1)}};
std::vector<std::pair<std::string, std::string>> metadata2 = {
{"address_hash", CreateMetadataValueThatHashesToBackend(2)}};
std::vector<std::pair<std::string, std::string>> metadata3 = {
{"address_hash", CreateMetadataValueThatHashesToBackend(3)}};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
const auto rpc_options1 = RpcOptions().set_metadata(std::move(metadata1));
const auto rpc_options2 = RpcOptions().set_metadata(std::move(metadata2));
const auto rpc_options3 = RpcOptions().set_metadata(std::move(metadata3));
WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
WaitForBackend(DEBUG_LOCATION, 1, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options1);
WaitForBackend(DEBUG_LOCATION, 2, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options2);
WaitForBackend(DEBUG_LOCATION, 3, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options3);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options1);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options2);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options3);
for (size_t i = 0; i < backends_.size(); ++i) {
EXPECT_EQ(100, backends_[i]->backend_service()->request_count());
}
}
// Tests that ring hash policy that hashes using a header value and regex
// rewrite to aggregate RPCs to 1 backend.
TEST_P(RingHashTest, HeaderHashingWithRegexRewrite) {
CreateAndStartBackends(4);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
hash_policy->mutable_header()
->mutable_regex_rewrite()
->mutable_pattern()
->set_regex("[0-9]+");
hash_policy->mutable_header()->mutable_regex_rewrite()->set_substitution(
"foo");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
std::vector<std::pair<std::string, std::string>> metadata1 = {
{"address_hash", CreateMetadataValueThatHashesToBackend(1)}};
std::vector<std::pair<std::string, std::string>> metadata2 = {
{"address_hash", CreateMetadataValueThatHashesToBackend(2)}};
std::vector<std::pair<std::string, std::string>> metadata3 = {
{"address_hash", CreateMetadataValueThatHashesToBackend(3)}};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
const auto rpc_options1 = RpcOptions().set_metadata(std::move(metadata1));
const auto rpc_options2 = RpcOptions().set_metadata(std::move(metadata2));
const auto rpc_options3 = RpcOptions().set_metadata(std::move(metadata3));
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options1);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options2);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options3);
bool found = false;
for (size_t i = 0; i < backends_.size(); ++i) {
if (backends_[i]->backend_service()->request_count() > 0) {
EXPECT_EQ(backends_[i]->backend_service()->request_count(), 400)
<< "backend " << i;
EXPECT_FALSE(found) << "backend " << i;
found = true;
}
}
EXPECT_TRUE(found);
}
// Tests that ring hash policy that hashes using a random value.
TEST_P(RingHashTest, NoHashPolicy) {
CreateAndStartBackends(2);
const double kDistribution50Percent = 0.5;
const double kErrorTolerance = 0.05;
const uint32_t kRpcTimeoutMs = 10000;
const size_t kNumRpcs =
ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
auto cluster = default_cluster_;
// Increasing min ring size for random distribution.
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
100000);
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// TODO(donnadionne): remove extended timeout after ring creation
// optimization.
WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
WaitForBackendOptions(),
RpcOptions().set_timeout_ms(kRpcTimeoutMs));
CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
const int request_count_1 = backends_[0]->backend_service()->request_count();
const int request_count_2 = backends_[1]->backend_service()->request_count();
EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
}
// Test that ring hash policy evaluation will continue past the terminal
// policy if no results are produced yet.
TEST_P(RingHashTest, ContinuesPastTerminalPolicyThatDoesNotProduceResult) {
CreateAndStartBackends(2);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("header_not_present");
hash_policy->set_terminal(true);
auto* hash_policy2 = route->mutable_route()->add_hash_policy();
hash_policy2->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
EXPECT_EQ(backends_[0]->backend_service()->request_count(), 100);
EXPECT_EQ(backends_[1]->backend_service()->request_count(), 0);
}
// Test random hash is used when header hashing specified a header field that
// the RPC did not have.
TEST_P(RingHashTest, HashOnHeaderThatIsNotPresent) {
CreateAndStartBackends(2);
const double kDistribution50Percent = 0.5;
const double kErrorTolerance = 0.05;
const uint32_t kRpcTimeoutMs = 10000;
const size_t kNumRpcs =
ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
auto cluster = default_cluster_;
// Increasing min ring size for random distribution.
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
100000);
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("header_not_present");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"unmatched_header", absl::StrFormat("%" PRIu32, rand())},
};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
// TODO(donnadionne): remove extended timeout after ring creation
// optimization.
WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
WaitForBackendOptions(),
RpcOptions().set_timeout_ms(kRpcTimeoutMs));
CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs, rpc_options);
const int request_count_1 = backends_[0]->backend_service()->request_count();
const int request_count_2 = backends_[1]->backend_service()->request_count();
EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
}
// Test random hash is used when only unsupported hash policies are
// configured.
TEST_P(RingHashTest, UnsupportedHashPolicyDefaultToRandomHashing) {
CreateAndStartBackends(2);
const double kDistribution50Percent = 0.5;
const double kErrorTolerance = 0.05;
const uint32_t kRpcTimeoutMs = 10000;
const size_t kNumRpcs =
ComputeIdealNumRpcs(kDistribution50Percent, kErrorTolerance);
auto cluster = default_cluster_;
// Increasing min ring size for random distribution.
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
100000);
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy_unsupported_1 = route->mutable_route()->add_hash_policy();
hash_policy_unsupported_1->mutable_cookie()->set_name("cookie");
auto* hash_policy_unsupported_2 = route->mutable_route()->add_hash_policy();
hash_policy_unsupported_2->mutable_connection_properties()->set_source_ip(
true);
auto* hash_policy_unsupported_3 = route->mutable_route()->add_hash_policy();
hash_policy_unsupported_3->mutable_query_parameter()->set_name(
"query_parameter");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// TODO(donnadionne): remove extended timeout after ring creation
// optimization.
WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
WaitForBackendOptions(),
RpcOptions().set_timeout_ms(kRpcTimeoutMs));
CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
const int request_count_1 = backends_[0]->backend_service()->request_count();
const int request_count_2 = backends_[1]->backend_service()->request_count();
EXPECT_THAT(static_cast<double>(request_count_1) / kNumRpcs,
::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
EXPECT_THAT(static_cast<double>(request_count_2) / kNumRpcs,
::testing::DoubleNear(kDistribution50Percent, kErrorTolerance));
}
// Tests that ring hash policy that hashes using a random value can spread
// RPCs across all the backends according to locality weight.
TEST_P(RingHashTest, RandomHashingDistributionAccordingToEndpointWeight) {
CreateAndStartBackends(2);
const size_t kWeight1 = 1;
const size_t kWeight2 = 2;
const size_t kWeightTotal = kWeight1 + kWeight2;
const double kWeight33Percent = static_cast<double>(kWeight1) / kWeightTotal;
const double kWeight66Percent = static_cast<double>(kWeight2) / kWeightTotal;
const double kErrorTolerance = 0.05;
const uint32_t kRpcTimeoutMs = 10000;
const size_t kNumRpcs =
ComputeIdealNumRpcs(kWeight33Percent, kErrorTolerance);
auto cluster = default_cluster_;
// Increasing min ring size for random distribution.
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
100000);
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
EdsResourceArgs args({{"locality0",
{CreateEndpoint(0, HealthStatus::UNKNOWN, 1),
CreateEndpoint(1, HealthStatus::UNKNOWN, 2)}}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// TODO(donnadionne): remove extended timeout after ring creation
// optimization.
WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
WaitForBackendOptions(),
RpcOptions().set_timeout_ms(kRpcTimeoutMs));
CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
const int weight_33_request_count =
backends_[0]->backend_service()->request_count();
const int weight_66_request_count =
backends_[1]->backend_service()->request_count();
EXPECT_THAT(static_cast<double>(weight_33_request_count) / kNumRpcs,
::testing::DoubleNear(kWeight33Percent, kErrorTolerance));
EXPECT_THAT(static_cast<double>(weight_66_request_count) / kNumRpcs,
::testing::DoubleNear(kWeight66Percent, kErrorTolerance));
}
// Tests that ring hash policy that hashes using a random value can spread
// RPCs across all the backends according to locality weight.
TEST_P(RingHashTest,
RandomHashingDistributionAccordingToLocalityAndEndpointWeight) {
CreateAndStartBackends(2);
const size_t kWeight1 = 1 * 1;
const size_t kWeight2 = 2 * 2;
const size_t kWeightTotal = kWeight1 + kWeight2;
const double kWeight20Percent = static_cast<double>(kWeight1) / kWeightTotal;
const double kWeight80Percent = static_cast<double>(kWeight2) / kWeightTotal;
const double kErrorTolerance = 0.05;
const uint32_t kRpcTimeoutMs = 10000;
const size_t kNumRpcs =
ComputeIdealNumRpcs(kWeight20Percent, kErrorTolerance);
auto cluster = default_cluster_;
// Increasing min ring size for random distribution.
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
100000);
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
EdsResourceArgs args(
{{"locality0", {CreateEndpoint(0, HealthStatus::UNKNOWN, 1)}, 1},
{"locality1", {CreateEndpoint(1, HealthStatus::UNKNOWN, 2)}, 2}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// TODO(donnadionne): remove extended timeout after ring creation
// optimization.
WaitForAllBackends(DEBUG_LOCATION, 0, 2, /*check_status=*/nullptr,
WaitForBackendOptions(),
RpcOptions().set_timeout_ms(kRpcTimeoutMs));
CheckRpcSendOk(DEBUG_LOCATION, kNumRpcs);
const int weight_20_request_count =
backends_[0]->backend_service()->request_count();
const int weight_80_request_count =
backends_[1]->backend_service()->request_count();
EXPECT_THAT(static_cast<double>(weight_20_request_count) / kNumRpcs,
::testing::DoubleNear(kWeight20Percent, kErrorTolerance));
EXPECT_THAT(static_cast<double>(weight_80_request_count) / kNumRpcs,
::testing::DoubleNear(kWeight80Percent, kErrorTolerance));
}
// Tests that ring hash policy that hashes using a fixed string ensures all
// RPCs to go 1 particular backend; and that subsequent hashing policies are
// ignored due to the setting of terminal.
TEST_P(RingHashTest, FixedHashingTerminalPolicy) {
CreateAndStartBackends(2);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("fixed_string");
hash_policy->set_terminal(true);
auto* hash_policy_to_be_ignored = route->mutable_route()->add_hash_policy();
hash_policy_to_be_ignored->mutable_header()->set_header_name("random_string");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"fixed_string", "fixed_value"},
{"random_string", absl::StrFormat("%" PRIu32, rand())},
};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
bool found = false;
for (size_t i = 0; i < backends_.size(); ++i) {
if (backends_[i]->backend_service()->request_count() > 0) {
EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
<< "backend " << i;
EXPECT_FALSE(found) << "backend " << i;
found = true;
}
}
EXPECT_TRUE(found);
}
// Test that the channel will go from idle to ready via connecting;
// (tho it is not possible to catch the connecting state before moving to
// ready)
TEST_P(RingHashTest, IdleToReady) {
CreateAndStartBackends(1);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
CheckRpcSendOk(DEBUG_LOCATION);
EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
}
// Test that the channel will transition to READY once it starts
// connecting even if there are no RPCs being sent to the picker.
TEST_P(RingHashTest, ContinuesConnectingWithoutPicks) {
// Create EDS resource.
CreateAndStartBackends(1);
auto non_existant_endpoint = MakeNonExistantEndpoint();
EdsResourceArgs args(
{{"locality0", {non_existant_endpoint, CreateEndpoint(0)}}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// Change CDS resource to use RING_HASH.
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
// Add hash policy to RDS resource.
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
// A connection injector that cancels the RPC after seeing the
// connection attempt for the non-existant endpoint.
class ConnectionInjector : public ConnectionAttemptInjector {
public:
explicit ConnectionInjector(int port) : port_(port) {}
void HandleConnection(grpc_closure* closure, grpc_endpoint** ep,
grpc_pollset_set* interested_parties,
const grpc_channel_args* channel_args,
const grpc_resolved_address* addr,
grpc_core::Timestamp deadline) override {
{
grpc_core::MutexLock lock(&mu_);
const int port = grpc_sockaddr_get_port(addr);
gpr_log(GPR_INFO, "==> HandleConnection(): seen_port_=%d, port=%d",
seen_port_, port);
if (!seen_port_ && port == port_) {
gpr_log(GPR_INFO, "*** SEEN P0 CONNECTION ATTEMPT");
queued_p0_attempt_ = absl::make_unique<QueuedAttempt>(
closure, ep, interested_parties, channel_args, addr, deadline);
seen_port_ = true;
cond_.Signal();
return;
}
}
AttemptConnection(closure, ep, interested_parties, channel_args, addr,
deadline);
}
void WaitForP0ConnectionAttempt() {
grpc_core::MutexLock lock(&mu_);
while (!seen_port_) {
cond_.Wait(&mu_);
}
}
// Invoked by the test when the RPC has been cancelled and it's ready
// to allow the connection attempt to proceed.
void CompleteP0ConnectionAttempt() {
grpc_core::ExecCtx exec_ctx;
std::unique_ptr<QueuedAttempt> attempt;
{
grpc_core::MutexLock lock(&mu_);
attempt = std::move(queued_p0_attempt_);
}
attempt->Resume();
}
private:
const int port_;
grpc_core::Mutex mu_;
grpc_core::CondVar cond_;
bool seen_port_ ABSL_GUARDED_BY(mu_) = false;
std::unique_ptr<QueuedAttempt> queued_p0_attempt_ ABSL_GUARDED_BY(mu_);
};
ConnectionInjector connection_injector(non_existant_endpoint.port);
connection_injector.Start();
// A long-running RPC, just used to send the RPC in another thread.
LongRunningRpc rpc;
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash",
CreateMetadataValueThatHashesToBackendPort(non_existant_endpoint.port)}};
rpc.StartRpc(stub_.get(), RpcOptions().set_timeout_ms(0).set_metadata(
std::move(metadata)));
// Wait for the RPC to trigger the P0 connection attempt, then cancel it,
// and then allow the connection attempt to complete.
connection_injector.WaitForP0ConnectionAttempt();
rpc.CancelRpc();
EXPECT_EQ(StatusCode::CANCELLED, rpc.GetStatus().error_code());
connection_injector.CompleteP0ConnectionAttempt();
// Wait for channel to become connected without any pending RPC.
EXPECT_TRUE(channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(5)));
// Make sure the backend did not get any requests.
EXPECT_EQ(0UL, backends_[0]->backend_service()->request_count());
}
// Tests that when we trigger internal connection attempts without
// picks, we do so for only one subchannel at a time.
TEST_P(RingHashTest, ContinuesConnectingWithoutPicksOneSubchannelAtATime) {
// Create EDS resource.
CreateAndStartBackends(1);
auto non_existant_endpoint0 = MakeNonExistantEndpoint();
auto non_existant_endpoint1 = MakeNonExistantEndpoint();
auto non_existant_endpoint2 = MakeNonExistantEndpoint();
EdsResourceArgs args({{"locality0",
{non_existant_endpoint0, non_existant_endpoint1,
non_existant_endpoint2, CreateEndpoint(0)}}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// Change CDS resource to use RING_HASH.
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
// Add hash policy to RDS resource.
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
// A connection injector that ensures that only one subchannel is
// connecting at a time.
class ConnectionInjector : public ConnectionAttemptInjector {
public:
ConnectionInjector(int port0, int port1, int port2, int good_port)
: port0_(port0), port1_(port1), port2_(port2), good_port_(good_port) {}
void HandleConnection(grpc_closure* closure, grpc_endpoint** ep,
grpc_pollset_set* interested_parties,
const grpc_channel_args* channel_args,
const grpc_resolved_address* addr,
grpc_core::Timestamp deadline) override {
{
grpc_core::MutexLock lock(&mu_);
const int port = grpc_sockaddr_get_port(addr);
gpr_log(GPR_INFO, "==> HandleConnection(): state_=%d, port=%d", state_,
port);
switch (state_) {
case kInit:
EXPECT_NE(port, port1_);
EXPECT_NE(port, port2_);
EXPECT_NE(port, good_port_);
if (port == port0_) {
gpr_log(GPR_INFO, "*** DELAYING ENDPOINT 0");
new DelayedAttempt(this, closure, ep, interested_parties,
channel_args, addr, deadline);
state_ = kDelayedEndpoint0;
cond_.Signal();
return;
}
break;
case kResumedEndpoint0:
EXPECT_NE(port, port0_);
EXPECT_NE(port, port2_);
EXPECT_NE(port, good_port_);
if (port == port1_) {
gpr_log(GPR_INFO, "*** DELAYING ENDPOINT 1");
new DelayedAttempt(this, closure, ep, interested_parties,
channel_args, addr, deadline);
state_ = kDelayedEndpoint1;
return;
} else {
gpr_log(GPR_INFO, "*** UNEXPECTED PORT");
}
break;
case kResumedEndpoint1:
EXPECT_NE(port, port0_);
EXPECT_NE(port, port1_);
EXPECT_NE(port, good_port_);
if (port == port2_) {
gpr_log(GPR_INFO, "*** DELAYING ENDPOINT 2");
new DelayedAttempt(this, closure, ep, interested_parties,
channel_args, addr, deadline);
state_ = kDelayedEndpoint2;
return;
} else {
gpr_log(GPR_INFO, "*** UNEXPECTED PORT");
}
break;
case kResumedEndpoint2:
EXPECT_NE(port, port0_);
EXPECT_NE(port, port1_);
EXPECT_NE(port, port2_);
if (port == good_port_) {
gpr_log(GPR_INFO, "*** DONE WITH ALL UNREACHABLE ENDPOINTS");
state_ = kDone;
}
break;
case kDelayedEndpoint0:
case kDelayedEndpoint1:
case kDelayedEndpoint2:
ASSERT_THAT(port, ::testing::AllOf(::testing::Ne(port0_),
::testing::Ne(port1_),
::testing::Ne(port2_),
::testing::Ne(good_port_)))
<< "started second connection attempt in parallel";
break;
case kDone:
break;
}
}
AttemptConnection(closure, ep, interested_parties, channel_args, addr,
deadline);
}
void WaitForFirstPortSeen() {
grpc_core::MutexLock lock(&mu_);
while (state_ == kInit) {
cond_.Wait(&mu_);
}
}
private:
class DelayedAttempt : public InjectedDelay {
public:
DelayedAttempt(ConnectionInjector* parent, grpc_closure* closure,
grpc_endpoint** ep, grpc_pollset_set* interested_parties,
const grpc_channel_args* channel_args,
const grpc_resolved_address* addr,
grpc_core::Timestamp deadline)
: InjectedDelay(
grpc_core::Duration::Seconds(1 * grpc_test_slowdown_factor()),
closure, ep, interested_parties, channel_args, addr, deadline),
parent_(parent) {}
private:
void BeforeResumingAction() override {
grpc_core::MutexLock lock(&parent_->mu_);
if (parent_->state_ == kDelayedEndpoint0) {
gpr_log(GPR_INFO, "*** RESUMING ENDPOINT 0");
parent_->state_ = kResumedEndpoint0;
} else if (parent_->state_ == kDelayedEndpoint1) {
gpr_log(GPR_INFO, "*** RESUMING ENDPOINT 1");
parent_->state_ = kResumedEndpoint1;
} else if (parent_->state_ == kDelayedEndpoint2) {
gpr_log(GPR_INFO, "*** RESUMING ENDPOINT 2");
parent_->state_ = kResumedEndpoint2;
}
}
ConnectionInjector* parent_;
};
const int port0_;
const int port1_;
const int port2_;
const int good_port_;
grpc_core::Mutex mu_;
grpc_core::CondVar cond_;
enum {
kInit,
kDelayedEndpoint0,
kResumedEndpoint0,
kDelayedEndpoint1,
kResumedEndpoint1,
kDelayedEndpoint2,
kResumedEndpoint2,
kDone,
} state_ ABSL_GUARDED_BY(mu_) = kInit;
};
ConnectionInjector connection_injector(
non_existant_endpoint0.port, non_existant_endpoint1.port,
non_existant_endpoint2.port, backends_[0]->port());
connection_injector.Start();
// A long-running RPC, just used to send the RPC in another thread.
LongRunningRpc rpc;
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackendPort(
non_existant_endpoint0.port)}};
rpc.StartRpc(stub_.get(), RpcOptions().set_timeout_ms(0).set_metadata(
std::move(metadata)));
// Wait for the RPC to trigger the first connection attempt, then cancel it.
connection_injector.WaitForFirstPortSeen();
rpc.CancelRpc();
// Wait for channel to become connected without any pending RPC.
EXPECT_TRUE(channel_->WaitForConnected(grpc_timeout_seconds_to_deadline(10)));
// RPC should have been cancelled.
EXPECT_EQ(StatusCode::CANCELLED, rpc.GetStatus().error_code());
// Make sure the backend did not get any requests.
EXPECT_EQ(0UL, backends_[0]->backend_service()->request_count());
}
// Test that when the first pick is down leading to a transient failure, we
// will move on to the next ring hash entry.
TEST_P(RingHashTest, TransientFailureCheckNextOne) {
CreateAndStartBackends(1);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
std::vector<EdsResourceArgs::Endpoint> endpoints;
const int unused_port = grpc_pick_unused_port_or_die();
endpoints.emplace_back(unused_port);
endpoints.emplace_back(backends_[0]->port());
EdsResourceArgs args({{"locality0", std::move(endpoints)}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash",
CreateMetadataValueThatHashesToBackendPort(unused_port)}};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
}
// Test that when a backend goes down, we will move on to the next subchannel
// (with a lower priority). When the backend comes back up, traffic will move
// back.
TEST_P(RingHashTest, SwitchToLowerPrioirtyAndThenBack) {
CreateAndStartBackends(2);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({
{"locality0", CreateEndpointsForBackends(0, 1), kDefaultLocalityWeight,
0},
{"locality1", CreateEndpointsForBackends(1, 2), kDefaultLocalityWeight,
1},
});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
const auto rpc_options = RpcOptions().set_metadata(std::move(metadata));
WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
backends_[0]->StopListeningAndSendGoaways();
WaitForBackend(DEBUG_LOCATION, 1, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
ShutdownBackend(0);
StartBackend(0);
WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
CheckRpcSendOk(DEBUG_LOCATION, 100, rpc_options);
EXPECT_EQ(100, backends_[0]->backend_service()->request_count());
EXPECT_EQ(0, backends_[1]->backend_service()->request_count());
}
// Test that when all backends are down, we will keep reattempting.
TEST_P(RingHashTest, ReattemptWhenAllEndpointsUnreachable) {
CreateAndStartBackends(1);
const uint32_t kConnectionTimeoutMilliseconds = 5000;
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args(
{{"locality0", {MakeNonExistantEndpoint(), CreateEndpoint(0)}}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
ShutdownBackend(0);
CheckRpcSendFailure(
DEBUG_LOCATION, StatusCode::UNAVAILABLE,
"ring hash cannot find a connected subchannel; first failure: "
"(UNKNOWN: Failed to connect to remote host: Connection refused|"
"UNAVAILABLE: Failed to connect to remote host: FD shutdown)",
RpcOptions().set_metadata(std::move(metadata)));
StartBackend(0);
// Ensure we are actively connecting without any traffic.
EXPECT_TRUE(channel_->WaitForConnected(
grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
}
// Test that when all backends are down and then up, we may pick a TF backend
// and we will then jump to ready backend.
TEST_P(RingHashTest, TransientFailureSkipToAvailableReady) {
CreateBackends(2);
const uint32_t kConnectionTimeoutMilliseconds = 5000;
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_header()->set_header_name("address_hash");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
// Make sure we include some unused ports to fill the ring.
EdsResourceArgs args({
{"locality0",
{CreateEndpoint(0), CreateEndpoint(1), MakeNonExistantEndpoint(),
MakeNonExistantEndpoint()}},
});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
std::vector<std::pair<std::string, std::string>> metadata = {
{"address_hash", CreateMetadataValueThatHashesToBackend(0)}};
const auto rpc_options = RpcOptions()
.set_metadata(std::move(metadata))
.set_timeout_ms(kConnectionTimeoutMilliseconds);
EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
gpr_log(GPR_INFO, "=== SENDING FIRST RPC ===");
CheckRpcSendFailure(
DEBUG_LOCATION, StatusCode::UNAVAILABLE,
"ring hash cannot find a connected subchannel; first failure: "
"(UNKNOWN: Failed to connect to remote host: Connection refused|"
"UNAVAILABLE: Failed to connect to remote host: FD shutdown)",
rpc_options);
gpr_log(GPR_INFO, "=== DONE WITH FIRST RPC ===");
EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
// Bring up backend 0. The channel should become connected without
// any picks, because in TF, we are always trying to connect to at
// least one backend at all times.
gpr_log(GPR_INFO, "=== STARTING BACKEND 0 ===");
StartBackend(0);
gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL TO BECOME READY ===");
EXPECT_TRUE(channel_->WaitForConnected(
grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
// RPCs should go to backend 0.
gpr_log(GPR_INFO, "=== WAITING FOR BACKEND 0 ===");
WaitForBackend(DEBUG_LOCATION, 0, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
// Bring down backend 0 and bring up backend 1.
// Note the RPC contains a header value that will always be hashed to
// backend 0. So by purposely bringing down backend 0 and bringing up another
// backend, this will ensure Picker's first choice of backend 0 will fail
// and it will go through the remaining subchannels to find one in READY.
// Since the the entries in the ring are pretty distributed and we have
// unused ports to fill the ring, it is almost guaranteed that the Picker
// will go through some non-READY entries and skip them as per design.
gpr_log(GPR_INFO, "=== SHUTTING DOWN BACKEND 0 ===");
ShutdownBackend(0);
gpr_log(GPR_INFO, "=== WAITING FOR STATE CHANGE ===");
EXPECT_TRUE(channel_->WaitForStateChange(
GRPC_CHANNEL_READY,
grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
gpr_log(GPR_INFO, "=== SENDING SECOND RPC ===");
CheckRpcSendFailure(
DEBUG_LOCATION, StatusCode::UNAVAILABLE,
"ring hash cannot find a connected subchannel; first failure: "
"(UNKNOWN: Failed to connect to remote host: Connection refused|"
"UNAVAILABLE: Failed to connect to remote host: FD shutdown)",
rpc_options);
gpr_log(GPR_INFO, "=== STARTING BACKEND 1 ===");
StartBackend(1);
gpr_log(GPR_INFO, "=== WAITING FOR CHANNEL TO BECOME READY ===");
EXPECT_TRUE(channel_->WaitForConnected(
grpc_timeout_milliseconds_to_deadline(kConnectionTimeoutMilliseconds)));
gpr_log(GPR_INFO, "=== WAITING FOR BACKEND 1 ===");
WaitForBackend(DEBUG_LOCATION, 1, /*check_status=*/nullptr,
WaitForBackendOptions(), rpc_options);
gpr_log(GPR_INFO, "=== DONE ===");
}
// This tests a bug seen in the wild where ring_hash started with no
// endpoints and reported TRANSIENT_FAILURE, then got an update with
// endpoints and reported IDLE, but the picker update was squelched, so
// it failed to ever get reconnected.
TEST_P(RingHashTest, ReattemptWhenGoingFromTransientFailureToIdle) {
CreateAndStartBackends(1);
const uint32_t kConnectionTimeoutMilliseconds = 5000;
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
// Send empty EDS update.
EdsResourceArgs args(
{{"locality0", std::vector<EdsResourceArgs::Endpoint>()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
EXPECT_EQ(GRPC_CHANNEL_IDLE, channel_->GetState(false));
// Channel should fail RPCs and go into TRANSIENT_FAILURE.
CheckRpcSendFailure(
DEBUG_LOCATION, StatusCode::UNAVAILABLE,
// TODO(roth): As part of https://github.com/grpc/grpc/issues/22883,
// figure out how to get a useful resolution note plumbed down to
// improve this message.
"empty address list: ",
RpcOptions().set_timeout_ms(kConnectionTimeoutMilliseconds));
EXPECT_EQ(GRPC_CHANNEL_TRANSIENT_FAILURE, channel_->GetState(false));
// Send EDS update with 1 backend.
args = EdsResourceArgs({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
// A wait_for_ready RPC should succeed, and the channel should report READY.
CheckRpcSendOk(DEBUG_LOCATION, 1,
RpcOptions()
.set_timeout_ms(kConnectionTimeoutMilliseconds)
.set_wait_for_ready(true));
EXPECT_EQ(GRPC_CHANNEL_READY, channel_->GetState(false));
}
// Test unspported hash policy types are all ignored before a supported
// policy.
TEST_P(RingHashTest, UnsupportedHashPolicyUntilChannelIdHashing) {
CreateAndStartBackends(2);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy_unsupported_1 = route->mutable_route()->add_hash_policy();
hash_policy_unsupported_1->mutable_cookie()->set_name("cookie");
auto* hash_policy_unsupported_2 = route->mutable_route()->add_hash_policy();
hash_policy_unsupported_2->mutable_connection_properties()->set_source_ip(
true);
auto* hash_policy_unsupported_3 = route->mutable_route()->add_hash_policy();
hash_policy_unsupported_3->mutable_query_parameter()->set_name(
"query_parameter");
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
CheckRpcSendOk(DEBUG_LOCATION, 100);
bool found = false;
for (size_t i = 0; i < backends_.size(); ++i) {
if (backends_[i]->backend_service()->request_count() > 0) {
EXPECT_EQ(backends_[i]->backend_service()->request_count(), 100)
<< "backend " << i;
EXPECT_FALSE(found) << "backend " << i;
found = true;
}
}
EXPECT_TRUE(found);
}
// Test we nack when ring hash policy has invalid hash function (something
// other than XX_HASH.
TEST_P(RingHashTest, InvalidHashFunction) {
CreateAndStartBackends(1);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
cluster.mutable_ring_hash_lb_config()->set_hash_function(
Cluster::RingHashLbConfig::MURMUR_HASH_2);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
const auto response_state = WaitForCdsNack(DEBUG_LOCATION);
ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
EXPECT_THAT(
response_state->error_message,
::testing::HasSubstr("ring hash lb config has invalid hash function."));
}
// Test we nack when ring hash policy has invalid ring size.
TEST_P(RingHashTest, InvalidMinimumRingSize) {
CreateAndStartBackends(1);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
0);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
const auto response_state = WaitForCdsNack(DEBUG_LOCATION);
ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
EXPECT_THAT(response_state->error_message,
::testing::HasSubstr(
"min_ring_size is not in the range of 1 to 8388608."));
}
// Test we nack when ring hash policy has invalid ring size.
TEST_P(RingHashTest, InvalidMaxmumRingSize) {
CreateAndStartBackends(1);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
cluster.mutable_ring_hash_lb_config()->mutable_maximum_ring_size()->set_value(
8388609);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
const auto response_state = WaitForCdsNack(DEBUG_LOCATION);
ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
EXPECT_THAT(response_state->error_message,
::testing::HasSubstr(
"max_ring_size is not in the range of 1 to 8388608."));
}
// Test we nack when ring hash policy has invalid ring size.
TEST_P(RingHashTest, InvalidRingSizeMinGreaterThanMax) {
CreateAndStartBackends(1);
auto cluster = default_cluster_;
cluster.set_lb_policy(Cluster::RING_HASH);
cluster.mutable_ring_hash_lb_config()->mutable_maximum_ring_size()->set_value(
5000);
cluster.mutable_ring_hash_lb_config()->mutable_minimum_ring_size()->set_value(
5001);
balancer_->ads_service()->SetCdsResource(cluster);
auto new_route_config = default_route_config_;
auto* route = new_route_config.mutable_virtual_hosts(0)->mutable_routes(0);
auto* hash_policy = route->mutable_route()->add_hash_policy();
hash_policy->mutable_filter_state()->set_key("io.grpc.channel_id");
SetListenerAndRouteConfiguration(balancer_.get(), default_listener_,
new_route_config);
EdsResourceArgs args({{"locality0", CreateEndpointsForBackends()}});
balancer_->ads_service()->SetEdsResource(BuildEdsResource(args));
const auto response_state = WaitForCdsNack(DEBUG_LOCATION);
ASSERT_TRUE(response_state.has_value()) << "timed out waiting for NACK";
EXPECT_THAT(response_state->error_message,
::testing::HasSubstr(
"min_ring_size cannot be greater than max_ring_size."));
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(&argc, argv);
::testing::InitGoogleTest(&argc, argv);
// Make the backup poller poll very frequently in order to pick up
// updates from all the subchannels's FDs.
GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
#if TARGET_OS_IPHONE
// Workaround Apple CFStream bug
gpr_setenv("grpc_cfstream", "0");
#endif
grpc_init();
grpc::testing::ConnectionAttemptInjector::Init();
const auto result = RUN_ALL_TESTS();
grpc_shutdown();
return result;
}
| 47.10315 | 80 | 0.715334 | [
"vector"
] |
c8bf97a6a2152fd029fe065ef39326aaa1fc9e2f | 54,264 | cpp | C++ | deps/icu/repo/source/test/intltest/dcfmapts.cpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | hihope_neptune-oh_hid/00_src/v0.3/third_party/icu/icu4c/source/test/intltest/dcfmapts.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 2 | 2015-01-05T10:41:27.000Z | 2015-01-06T20:46:11.000Z | hihope_neptune-oh_hid/00_src/v0.3/third_party/icu/icu4c/source/test/intltest/dcfmapts.cpp | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 5 | 2016-08-02T11:13:57.000Z | 2018-10-26T11:19:27.000Z | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2015, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "dcfmapts.h"
#include "unicode/currpinf.h"
#include "unicode/dcfmtsym.h"
#include "unicode/decimfmt.h"
#include "unicode/fmtable.h"
#include "unicode/localpointer.h"
#include "unicode/parseerr.h"
#include "unicode/stringpiece.h"
#include "putilimp.h"
#include "plurrule_impl.h"
#include "number_decimalquantity.h"
#include <stdio.h>
// This is an API test, not a unit test. It doesn't test very many cases, and doesn't
// try to test the full functionality. It just calls each function in the class and
// verifies that it works on a basic level.
void IntlTestDecimalFormatAPI::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
{
if (exec) logln((UnicodeString)"TestSuite DecimalFormatAPI");
switch (index) {
case 0: name = "DecimalFormat API test";
if (exec) {
logln((UnicodeString)"DecimalFormat API test---"); logln((UnicodeString)"");
UErrorCode status = U_ZERO_ERROR;
Locale saveLocale;
Locale::setDefault(Locale::getEnglish(), status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: Could not set default locale, test may not give correct results");
}
testAPI(/*par*/);
Locale::setDefault(saveLocale, status);
}
break;
case 1: name = "Rounding test";
if(exec) {
logln((UnicodeString)"DecimalFormat Rounding test---");
testRounding(/*par*/);
}
break;
case 2: name = "Test6354";
if(exec) {
logln((UnicodeString)"DecimalFormat Rounding Increment test---");
testRoundingInc(/*par*/);
}
break;
case 3: name = "TestCurrencyPluralInfo";
if(exec) {
logln((UnicodeString)"CurrencyPluralInfo API test---");
TestCurrencyPluralInfo();
}
break;
case 4: name = "TestScale";
if(exec) {
logln((UnicodeString)"Scale test---");
TestScale();
}
break;
case 5: name = "TestFixedDecimal";
if(exec) {
logln((UnicodeString)"TestFixedDecimal ---");
TestFixedDecimal();
}
break;
case 6: name = "TestBadFastpath";
if(exec) {
logln((UnicodeString)"TestBadFastpath ---");
TestBadFastpath();
}
break;
case 7: name = "TestRequiredDecimalPoint";
if(exec) {
logln((UnicodeString)"TestRequiredDecimalPoint ---");
TestRequiredDecimalPoint();
}
break;
case 8: name = "testErrorCode";
if(exec) {
logln((UnicodeString)"testErrorCode ---");
testErrorCode();
}
break;
case 9: name = "testInvalidObject";
if(exec) {
logln((UnicodeString) "testInvalidObject ---");
testInvalidObject();
}
break;
default: name = ""; break;
}
}
/**
* This test checks various generic API methods in DecimalFormat to achieve 100%
* API coverage.
*/
void IntlTestDecimalFormatAPI::testAPI(/*char *par*/)
{
UErrorCode status = U_ZERO_ERROR;
// ======= Test constructors
logln((UnicodeString)"Testing DecimalFormat constructors");
DecimalFormat def(status);
if(U_FAILURE(status)) {
errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status));
return;
}
// bug 10864
status = U_ZERO_ERROR;
DecimalFormat noGrouping("###0.##", status);
assertEquals("Grouping size should be 0 for no grouping.", 0, noGrouping.getGroupingSize());
noGrouping.setGroupingUsed(TRUE);
assertEquals("Grouping size should still be 0.", 0, noGrouping.getGroupingSize());
// end bug 10864
// bug 13442 comment 14
status = U_ZERO_ERROR;
{
DecimalFormat df("0", {"en", status}, status);
UnicodeString result;
assertEquals("pat 0: ", 0, df.getGroupingSize());
assertEquals("pat 0: ", (UBool) FALSE, (UBool) df.isGroupingUsed());
df.setGroupingUsed(false);
assertEquals("pat 0 then disabled: ", 0, df.getGroupingSize());
assertEquals("pat 0 then disabled: ", u"1111", df.format(1111, result.remove()));
df.setGroupingUsed(true);
assertEquals("pat 0 then enabled: ", 0, df.getGroupingSize());
assertEquals("pat 0 then enabled: ", u"1111", df.format(1111, result.remove()));
}
{
DecimalFormat df("#,##0", {"en", status}, status);
UnicodeString result;
assertEquals("pat #,##0: ", 3, df.getGroupingSize());
assertEquals("pat #,##0: ", (UBool) TRUE, (UBool) df.isGroupingUsed());
df.setGroupingUsed(false);
assertEquals("pat #,##0 then disabled: ", 3, df.getGroupingSize());
assertEquals("pat #,##0 then disabled: ", u"1111", df.format(1111, result.remove()));
df.setGroupingUsed(true);
assertEquals("pat #,##0 then enabled: ", 3, df.getGroupingSize());
assertEquals("pat #,##0 then enabled: ", u"1,111", df.format(1111, result.remove()));
}
// end bug 13442 comment 14
status = U_ZERO_ERROR;
const UnicodeString pattern("#,##0.# FF");
DecimalFormat pat(pattern, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern)");
return;
}
status = U_ZERO_ERROR;
DecimalFormatSymbols *symbols = new DecimalFormatSymbols(Locale::getFrench(), status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (French)");
return;
}
status = U_ZERO_ERROR;
DecimalFormat cust1(pattern, symbols, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)");
}
status = U_ZERO_ERROR;
DecimalFormat cust2(pattern, *symbols, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols)");
}
DecimalFormat copy(pat);
// ======= Test clone(), assignment, and equality
logln((UnicodeString)"Testing clone(), assignment and equality operators");
if( ! (copy == pat) || copy != pat) {
errln((UnicodeString)"ERROR: Copy constructor or == failed");
}
copy = cust1;
if(copy != cust1) {
errln((UnicodeString)"ERROR: Assignment (or !=) failed");
}
Format *clone = def.clone();
if( ! (*clone == def) ) {
errln((UnicodeString)"ERROR: Clone() failed");
}
delete clone;
// ======= Test various format() methods
logln((UnicodeString)"Testing various format() methods");
double d = -10456.0037;
int32_t l = 100000000;
Formattable fD(d);
Formattable fL(l);
UnicodeString res1, res2, res3, res4;
FieldPosition pos1(FieldPosition::DONT_CARE), pos2(FieldPosition::DONT_CARE), pos3(FieldPosition::DONT_CARE), pos4(FieldPosition::DONT_CARE);
res1 = def.format(d, res1, pos1);
logln( (UnicodeString) "" + (int32_t) d + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln((UnicodeString) "" + (int32_t) l + " formatted to " + res2);
status = U_ZERO_ERROR;
res3 = cust1.format(fD, res3, pos3, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: format(Formattable [double]) failed");
}
logln((UnicodeString) "" + (int32_t) fD.getDouble() + " formatted to " + res3);
status = U_ZERO_ERROR;
res4 = cust2.format(fL, res4, pos4, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: format(Formattable [long]) failed");
}
logln((UnicodeString) "" + fL.getLong() + " formatted to " + res4);
// ======= Test parse()
logln((UnicodeString)"Testing parse()");
UnicodeString text("-10,456.0037");
Formattable result1, result2;
ParsePosition pos(0);
UnicodeString patt("#,##0.#");
status = U_ZERO_ERROR;
pat.applyPattern(patt, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: applyPattern() failed");
}
pat.parse(text, result1, pos);
if(result1.getType() != Formattable::kDouble && result1.getDouble() != d) {
errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + (int32_t) result1.getDouble());
status = U_ZERO_ERROR;
pat.parse(text, result2, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: parse() failed");
}
if(result2.getType() != Formattable::kDouble && result2.getDouble() != d) {
errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + (int32_t) result2.getDouble());
// ======= Test getters and setters
logln((UnicodeString)"Testing getters and setters");
const DecimalFormatSymbols *syms = pat.getDecimalFormatSymbols();
DecimalFormatSymbols *newSyms = new DecimalFormatSymbols(*syms);
def.setDecimalFormatSymbols(*newSyms);
def.adoptDecimalFormatSymbols(newSyms); // don't use newSyms after this
if( *(pat.getDecimalFormatSymbols()) != *(def.getDecimalFormatSymbols())) {
errln((UnicodeString)"ERROR: adopt or set DecimalFormatSymbols() failed");
}
UnicodeString posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix(posPrefix);
logln((UnicodeString)"Positive prefix (should be +): " + posPrefix);
if(posPrefix != "+") {
errln((UnicodeString)"ERROR: setPositivePrefix() failed");
}
UnicodeString negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix(negPrefix);
logln((UnicodeString)"Negative prefix (should be -): " + negPrefix);
if(negPrefix != "-") {
errln((UnicodeString)"ERROR: setNegativePrefix() failed");
}
UnicodeString posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix(posSuffix);
logln((UnicodeString)"Positive suffix (should be _): " + posSuffix);
if(posSuffix != "_") {
errln((UnicodeString)"ERROR: setPositiveSuffix() failed");
}
UnicodeString negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix(negSuffix);
logln((UnicodeString)"Negative suffix (should be ~): " + negSuffix);
if(negSuffix != "~") {
errln((UnicodeString)"ERROR: setNegativeSuffix() failed");
}
int32_t multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln((UnicodeString)"Multiplier (should be 8): " + multiplier);
if(multiplier != 8) {
errln((UnicodeString)"ERROR: setMultiplier() failed");
}
int32_t groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln((UnicodeString)"Grouping size (should be 2): " + (int32_t) groupingSize);
if(groupingSize != 2) {
errln((UnicodeString)"ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(TRUE);
UBool tf = pat.isDecimalSeparatorAlwaysShown();
logln((UnicodeString)"DecimalSeparatorIsAlwaysShown (should be TRUE) is " + (UnicodeString) (tf ? "TRUE" : "FALSE"));
if(tf != TRUE) {
errln((UnicodeString)"ERROR: setDecimalSeparatorAlwaysShown() failed");
}
// Added by Ken Liu testing set/isExponentSignAlwaysShown
pat.setExponentSignAlwaysShown(TRUE);
UBool esas = pat.isExponentSignAlwaysShown();
logln((UnicodeString)"ExponentSignAlwaysShown (should be TRUE) is " + (UnicodeString) (esas ? "TRUE" : "FALSE"));
if(esas != TRUE) {
errln((UnicodeString)"ERROR: ExponentSignAlwaysShown() failed");
}
// Added by Ken Liu testing set/isScientificNotation
pat.setScientificNotation(TRUE);
UBool sn = pat.isScientificNotation();
logln((UnicodeString)"isScientificNotation (should be TRUE) is " + (UnicodeString) (sn ? "TRUE" : "FALSE"));
if(sn != TRUE) {
errln((UnicodeString)"ERROR: setScientificNotation() failed");
}
// Added by Ken Liu testing set/getMinimumExponentDigits
int8_t MinimumExponentDigits = 0;
pat.setMinimumExponentDigits(2);
MinimumExponentDigits = pat.getMinimumExponentDigits();
logln((UnicodeString)"MinimumExponentDigits (should be 2) is " + (int8_t) MinimumExponentDigits);
if(MinimumExponentDigits != 2) {
errln((UnicodeString)"ERROR: setMinimumExponentDigits() failed");
}
// Added by Ken Liu testing set/getRoundingIncrement
double RoundingIncrement = 0.0;
pat.setRoundingIncrement(2.0);
RoundingIncrement = pat.getRoundingIncrement();
logln((UnicodeString)"RoundingIncrement (should be 2.0) is " + (double) RoundingIncrement);
if(RoundingIncrement != 2.0) {
errln((UnicodeString)"ERROR: setRoundingIncrement() failed");
}
//end of Ken's Adding
UnicodeString funkyPat;
funkyPat = pat.toPattern(funkyPat);
logln((UnicodeString)"Pattern is " + funkyPat);
UnicodeString locPat;
locPat = pat.toLocalizedPattern(locPat);
logln((UnicodeString)"Localized pattern is " + locPat);
// ======= Test applyPattern()
logln((UnicodeString)"Testing applyPattern()");
pat = DecimalFormat(status); // reset
UnicodeString p1("#,##0.0#;(#,##0.0#)");
logln((UnicodeString)"Applying pattern " + p1);
status = U_ZERO_ERROR;
pat.applyPattern(p1, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status);
}
UnicodeString s2;
s2 = pat.toPattern(s2);
logln((UnicodeString)"Extracted pattern is " + s2);
assertEquals("toPattern() result did not match pattern applied", p1, s2);
if(pat.getSecondaryGroupingSize() != 0) {
errln("FAIL: Secondary Grouping Size should be 0, not %d\n", pat.getSecondaryGroupingSize());
}
if(pat.getGroupingSize() != 3) {
errln("FAIL: Primary Grouping Size should be 3, not %d\n", pat.getGroupingSize());
}
UnicodeString p2("#,##,##0.0# FF;(#,##,##0.0# FF)");
logln((UnicodeString)"Applying pattern " + p2);
status = U_ZERO_ERROR;
pat.applyLocalizedPattern(p2, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status);
}
UnicodeString s3;
s3 = pat.toLocalizedPattern(s3);
logln((UnicodeString)"Extracted pattern is " + s3);
assertEquals("toLocalizedPattern() result did not match pattern applied", p2, s3);
status = U_ZERO_ERROR;
UParseError pe;
pat.applyLocalizedPattern(p2, pe, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: applyPattern((with ParseError)) failed with " + (int32_t) status);
}
UnicodeString s4;
s4 = pat.toLocalizedPattern(s3);
logln((UnicodeString)"Extracted pattern is " + s4);
assertEquals("toLocalizedPattern(with ParseErr) result did not match pattern applied", p2, s4);
if(pat.getSecondaryGroupingSize() != 2) {
errln("FAIL: Secondary Grouping Size should be 2, not %d\n", pat.getSecondaryGroupingSize());
}
if(pat.getGroupingSize() != 3) {
errln("FAIL: Primary Grouping Size should be 3, not %d\n", pat.getGroupingSize());
}
// ======= Test getStaticClassID()
logln((UnicodeString)"Testing getStaticClassID()");
status = U_ZERO_ERROR;
NumberFormat *test = new DecimalFormat(status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: Couldn't create a DecimalFormat");
}
if(test->getDynamicClassID() != DecimalFormat::getStaticClassID()) {
errln((UnicodeString)"ERROR: getDynamicClassID() didn't return the expected value");
}
delete test;
}
void IntlTestDecimalFormatAPI::TestCurrencyPluralInfo(){
UErrorCode status = U_ZERO_ERROR;
LocalPointer<CurrencyPluralInfo>cpi(new CurrencyPluralInfo(status), status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: CurrencyPluralInfo(UErrorCode) could not be created");
return;
}
CurrencyPluralInfo cpi1 = *cpi;
if(cpi->getDynamicClassID() != CurrencyPluralInfo::getStaticClassID()){
errln((UnicodeString)"ERROR: CurrencyPluralInfo::getDynamicClassID() didn't return the expected value");
}
cpi->setCurrencyPluralPattern("","",status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: CurrencyPluralInfo::setCurrencyPluralPattern");
}
cpi->setLocale(Locale::getCanada(), status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: CurrencyPluralInfo::setLocale");
}
cpi->setPluralRules("",status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: CurrencyPluralInfo::setPluralRules");
}
LocalPointer<DecimalFormat>df(new DecimalFormat(status));
if(U_FAILURE(status)) {
errcheckln(status, "ERROR: Could not create DecimalFormat - %s", u_errorName(status));
return;
}
df->adoptCurrencyPluralInfo(cpi.orphan());
df->getCurrencyPluralInfo();
df->setCurrencyPluralInfo(cpi1);
}
void IntlTestDecimalFormatAPI::testRounding(/*char *par*/)
{
UErrorCode status = U_ZERO_ERROR;
double Roundingnumber = 2.55;
double Roundingnumber1 = -2.55;
//+2.55 results -2.55 results
double result[]={ 3.0, -2.0, // kRoundCeiling 0,
2.0, -3.0, // kRoundFloor 1,
2.0, -2.0, // kRoundDown 2,
3.0, -3.0, // kRoundUp 3,
3.0, -3.0, // kRoundHalfEven 4,
3.0, -3.0, // kRoundHalfDown 5,
3.0, -3.0 // kRoundHalfUp 6
};
DecimalFormat pat(status);
if(U_FAILURE(status)) {
errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status));
return;
}
uint16_t mode;
uint16_t i=0;
UnicodeString message;
UnicodeString resultStr;
for(mode=0;mode < 7;mode++){
pat.setRoundingMode((DecimalFormat::ERoundingMode)mode);
if(pat.getRoundingMode() != (DecimalFormat::ERoundingMode)mode){
errln((UnicodeString)"SetRoundingMode or GetRoundingMode failed for mode=" + mode);
}
//for +2.55 with RoundingIncrement=1.0
pat.setRoundingIncrement(1.0);
pat.format(Roundingnumber, resultStr);
message= (UnicodeString)"round(" + (double)Roundingnumber + UnicodeString(",") + mode + UnicodeString(",FALSE) with RoundingIncrement=1.0==>");
verify(message, resultStr, result[i++]);
message.remove();
resultStr.remove();
//for -2.55 with RoundingIncrement=1.0
pat.format(Roundingnumber1, resultStr);
message= (UnicodeString)"round(" + (double)Roundingnumber1 + UnicodeString(",") + mode + UnicodeString(",FALSE) with RoundingIncrement=1.0==>");
verify(message, resultStr, result[i++]);
message.remove();
resultStr.remove();
}
}
void IntlTestDecimalFormatAPI::verify(const UnicodeString& message, const UnicodeString& got, double expected){
logln((UnicodeString)message + got + (UnicodeString)" Expected : " + expected);
UnicodeString expectedStr("");
expectedStr=expectedStr + expected;
if(got != expectedStr ) {
errln((UnicodeString)"ERROR: " + message + got + (UnicodeString)" Expected : " + expectedStr);
}
}
void IntlTestDecimalFormatAPI::verifyString(const UnicodeString& message, const UnicodeString& got, UnicodeString& expected){
logln((UnicodeString)message + got + (UnicodeString)" Expected : " + expected);
if(got != expected ) {
errln((UnicodeString)"ERROR: " + message + got + (UnicodeString)" Expected : " + expected);
}
}
void IntlTestDecimalFormatAPI::testRoundingInc(/*char *par*/)
{
UErrorCode status = U_ZERO_ERROR;
DecimalFormat pat(UnicodeString("#,##0.00"),status);
if(U_FAILURE(status)) {
errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status));
return;
}
// get default rounding increment
double roundingInc = pat.getRoundingIncrement();
if (roundingInc != 0.0) {
errln((UnicodeString)"ERROR: Rounding increment not zero");
return;
}
// With rounding now being handled by decNumber, we no longer
// set a rounding increment to enable non-default mode rounding,
// checking of which was the original point of this test.
// set rounding mode with zero increment. Rounding
// increment should not be set by this operation
pat.setRoundingMode((DecimalFormat::ERoundingMode)0);
roundingInc = pat.getRoundingIncrement();
if (roundingInc != 0.0) {
errln((UnicodeString)"ERROR: Rounding increment not zero after setRoundingMode");
return;
}
}
void IntlTestDecimalFormatAPI::TestScale()
{
typedef struct TestData {
double inputValue;
int inputScale;
const char *expectedOutput;
} TestData;
static TestData testData[] = {
{ 100.0, 3, "100,000" },
{ 10034.0, -2, "100.34" },
{ 0.86, -3, "0.0009" },
{ -0.000455, 1, "-0%" },
{ -0.000555, 1, "-1%" },
{ 0.000455, 1, "0%" },
{ 0.000555, 1, "1%" },
};
UErrorCode status = U_ZERO_ERROR;
DecimalFormat pat(status);
if(U_FAILURE(status)) {
errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status));
return;
}
UnicodeString message;
UnicodeString resultStr;
UnicodeString exp;
UnicodeString percentPattern("#,##0%");
pat.setMaximumFractionDigits(4);
for(int32_t i=0; i < UPRV_LENGTHOF(testData); i++) {
if ( i > 2 ) {
pat.applyPattern(percentPattern,status);
}
// Test both the attribute and the setter
if (i % 2 == 0) {
pat.setAttribute(UNUM_SCALE, testData[i].inputScale,status);
assertEquals("", testData[i].inputScale, pat.getMultiplierScale());
} else {
pat.setMultiplierScale(testData[i].inputScale);
assertEquals("", testData[i].inputScale, pat.getAttribute(UNUM_SCALE, status));
}
pat.format(testData[i].inputValue, resultStr);
message = UnicodeString("Unexpected output for ") + testData[i].inputValue + UnicodeString(" and scale ") +
testData[i].inputScale + UnicodeString(". Got: ");
exp = testData[i].expectedOutput;
verifyString(message, resultStr, exp);
message.remove();
resultStr.remove();
exp.remove();
}
}
#define ASSERT_EQUAL(expect, actual) UPRV_BLOCK_MACRO_BEGIN { \
/* ICU-20080: Use temporary variables to avoid strange compiler behaviour \
(with the nice side-effect of avoiding repeated function calls too). */ \
auto lhs = (expect); \
auto rhs = (actual); \
char tmp[200]; \
sprintf(tmp, "(%g==%g)", (double)lhs, (double)rhs); \
assertTrue(tmp, (lhs==rhs), FALSE, TRUE, __FILE__, __LINE__); \
} UPRV_BLOCK_MACRO_END
#if defined(_MSC_VER)
// Ignore the noisy warning 4805 (comparisons between int and bool) in the function below as we use the ICU TRUE/FALSE macros
// which are int values, whereas some of the DecimalQuantity methods return C++ bools.
#pragma warning(push)
#pragma warning(disable: 4805)
#endif
void IntlTestDecimalFormatAPI::TestFixedDecimal() {
UErrorCode status = U_ZERO_ERROR;
LocalPointer<DecimalFormat> df(new DecimalFormat("###", status), status);
assertSuccess(WHERE, status);
if (status == U_MISSING_RESOURCE_ERROR) {
return;
}
number::impl::DecimalQuantity fd;
df->formatToDecimalQuantity(44, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(44, fd.getPluralOperand(PLURAL_OPERAND_N));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(FALSE, fd.isNegative());
df->formatToDecimalQuantity(-44, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(44, fd.getPluralOperand(PLURAL_OPERAND_N));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(TRUE, fd.isNegative());
df.adoptInsteadAndCheckErrorCode(new DecimalFormat("###.00##", status), status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(3, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(123.456, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df->formatToDecimalQuantity(-123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(3, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(123.456, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(TRUE, fd.isNegative());
// test max int digits
df->setMaximumIntegerDigits(2);
df->formatToDecimalQuantity(123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(3, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(23, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(23.456, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df->formatToDecimalQuantity(-123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(3, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(456, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(23, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(23.456, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(TRUE, fd.isNegative());
// test max fraction digits
df->setMaximumIntegerDigits(2000000000);
df->setMaximumFractionDigits(2);
df->formatToDecimalQuantity(123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(46, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(46, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(123.46, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df->formatToDecimalQuantity(-123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(46, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(46, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(123.46, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(TRUE, fd.isNegative());
// test esoteric rounding
df->setMaximumFractionDigits(6);
df->setRoundingIncrement(7.3);
df->formatToDecimalQuantity(30.0, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(20, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(29, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(29.2, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df->formatToDecimalQuantity(-30.0, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V)); // v
ASSERT_EQUAL(20, fd.getPluralOperand(PLURAL_OPERAND_F)); // f
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_T)); // t
ASSERT_EQUAL(29, fd.getPluralOperand(PLURAL_OPERAND_I)); // i
ASSERT_EQUAL(29.2, fd.getPluralOperand(PLURAL_OPERAND_N)); // n
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(TRUE, fd.isNegative());
df.adoptInsteadAndCheckErrorCode(new DecimalFormat("###", status), status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(123.456, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df.adoptInsteadAndCheckErrorCode(new DecimalFormat("###.0", status), status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(123.01, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df.adoptInsteadAndCheckErrorCode(new DecimalFormat("###.0", status), status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(123.06, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df.adoptInsteadAndCheckErrorCode(new DecimalFormat("@@@@@", status), status); // Significant Digits
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(123, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(123, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df.adoptInsteadAndCheckErrorCode(new DecimalFormat("@@@@@", status), status); // Significant Digits
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(1.23, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(4, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(2300, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(23, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
df->formatToDecimalQuantity(uprv_getInfinity(), fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(TRUE, fd.isNaN() || fd.isInfinite());
df->formatToDecimalQuantity(0.0, fd, status);
ASSERT_EQUAL(FALSE, fd.isNaN() || fd.isInfinite());
df->formatToDecimalQuantity(uprv_getNaN(), fd, status);
ASSERT_EQUAL(TRUE, fd.isNaN() || fd.isInfinite());
assertSuccess(WHERE, status);
// Test Big Decimal input.
// 22 digits before and after decimal, will exceed the precision of a double
// and force DecimalFormat::getFixedDecimal() to work with a digit list.
df.adoptInsteadAndCheckErrorCode(
new DecimalFormat("#####################0.00####################", status), status);
assertSuccess(WHERE, status);
Formattable fable("12.34", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(34, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(34, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(12, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
fable.setDecimalNumber("12.3456789012345678900123456789", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(22, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(3456789012345678900LL, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(34567890123456789LL, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(12, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
// On field overflow, Integer part is truncated on the left, fraction part on the right.
fable.setDecimalNumber("123456789012345678901234567890.123456789012345678901234567890", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(22, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(1234567890123456789LL, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(1234567890123456789LL, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(345678901234567890LL, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
// Digits way to the right of the decimal but within the format's precision aren't truncated
fable.setDecimalNumber("1.0000000000000000000012", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(22, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(12, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(12, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
// Digits beyond the precision of the format are rounded away
fable.setDecimalNumber("1.000000000000000000000012", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
// Negative numbers come through
fable.setDecimalNumber("-1.0000000000000000000012", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(22, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(12, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(12, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(1, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(TRUE, fd.isNegative());
// MinFractionDigits from format larger than from number.
fable.setDecimalNumber("1000000000000000000000.3", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(30, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(3, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
fable.setDecimalNumber("1000000000000000050000.3", status);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(30, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(3, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(50000LL, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(FALSE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
// Test some int64_t values that are out of the range of a double
fable.setInt64(4503599627370496LL);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(4503599627370496LL, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
fable.setInt64(4503599627370497LL);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
ASSERT_EQUAL(4503599627370497LL, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
fable.setInt64(9223372036854775807LL);
assertSuccess(WHERE, status);
df->formatToDecimalQuantity(fable, fd, status);
assertSuccess(WHERE, status);
ASSERT_EQUAL(2, fd.getPluralOperand(PLURAL_OPERAND_V));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_F));
ASSERT_EQUAL(0, fd.getPluralOperand(PLURAL_OPERAND_T));
// note: going through DigitList path to FixedDecimal, which is trimming
// int64_t fields to 18 digits. See ticket Ticket #10374
ASSERT_EQUAL(223372036854775807LL, fd.getPluralOperand(PLURAL_OPERAND_I));
ASSERT_EQUAL(TRUE, fd.hasIntegerValue());
ASSERT_EQUAL(FALSE, fd.isNegative());
}
#if defined(_MSC_VER)
// Re-enable 4805 warnings (comparisons between int and bool).
#pragma warning(pop)
#endif
void IntlTestDecimalFormatAPI::TestBadFastpath() {
UErrorCode status = U_ZERO_ERROR;
LocalPointer<DecimalFormat> df(new DecimalFormat("###", status), status);
if (U_FAILURE(status)) {
dataerrln("Error creating new DecimalFormat - %s", u_errorName(status));
return;
}
UnicodeString fmt;
fmt.remove();
assertEquals("Format 1234", "1234", df->format((int32_t)1234, fmt));
df->setGroupingUsed(FALSE);
fmt.remove();
assertEquals("Format 1234", "1234", df->format((int32_t)1234, fmt));
df->setGroupingUsed(TRUE);
df->setGroupingSize(3);
fmt.remove();
assertEquals("Format 1234 w/ grouping", "1,234", df->format((int32_t)1234, fmt));
}
void IntlTestDecimalFormatAPI::TestRequiredDecimalPoint() {
UErrorCode status = U_ZERO_ERROR;
UnicodeString text("99");
Formattable result1;
UnicodeString pat1("##.0000");
UnicodeString pat2("00.0");
LocalPointer<DecimalFormat> df(new DecimalFormat(pat1, status), status);
if (U_FAILURE(status)) {
dataerrln("Error creating new DecimalFormat - %s", u_errorName(status));
return;
}
status = U_ZERO_ERROR;
df->applyPattern(pat1, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: applyPattern() failed");
}
df->parse(text, result1, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: parse() failed");
}
df->setDecimalPatternMatchRequired(TRUE);
df->parse(text, result1, status);
if(U_SUCCESS(status)) {
errln((UnicodeString)"ERROR: unexpected parse()");
}
status = U_ZERO_ERROR;
df->applyPattern(pat2, status);
df->setDecimalPatternMatchRequired(FALSE);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: applyPattern(2) failed");
}
df->parse(text, result1, status);
if(U_FAILURE(status)) {
errln((UnicodeString)"ERROR: parse(2) failed - " + u_errorName(status));
}
df->setDecimalPatternMatchRequired(TRUE);
df->parse(text, result1, status);
if(U_SUCCESS(status)) {
errln((UnicodeString)"ERROR: unexpected parse(2)");
}
}
void IntlTestDecimalFormatAPI::testErrorCode() {
// Try each DecimalFormat constructor with an errorCode set on input,
// Verify no crashes or leaks, and that the errorCode is not altered.
UErrorCode status = U_ZERO_ERROR;
const UnicodeString pattern(u"0.###E0");
UParseError pe;
DecimalFormatSymbols symbols(Locale::getUS(), status);
assertSuccess(WHERE, status);
{
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat df(status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
{
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat df(pattern, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
{
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat df(pattern, new DecimalFormatSymbols(symbols), status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
{
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat df(pattern, new DecimalFormatSymbols(symbols), UNUM_DECIMAL_COMPACT_LONG, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
{
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat df(pattern, new DecimalFormatSymbols(symbols), pe, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
{
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat df(pattern, symbols ,status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
// Try each DecimalFormat method with an error code parameter, verifying that
// an input error is not altered, and that no segmentation faults occur.
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus(status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_ZERO_ERROR;
DecimalFormat dfGood(pattern, new DecimalFormatSymbols(symbols), status);
assertSuccess(WHERE, status);
for (DecimalFormat *df: {&dfBogus, &dfGood}) {
status = U_INTERNAL_PROGRAM_ERROR;
df->setAttribute(UNUM_PARSE_INT_ONLY, 0, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->getAttribute(UNUM_MAX_FRACTION_DIGITS, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
UnicodeString dest;
FieldPosition fp;
df->format(1.2, dest, fp, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->format(1.2, dest, nullptr, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->format((int32_t)666, dest, nullptr, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->format((int64_t)666, dest, nullptr, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->format(StringPiece("3.1415926535897932384626"), dest, nullptr, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->applyPattern(pattern, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->applyLocalizedPattern(pattern, pe, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->applyLocalizedPattern(pattern, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->setCurrency(u"USD", status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
df->setCurrencyUsage(UCURR_USAGE_CASH, &status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
}
}
void IntlTestDecimalFormatAPI::testInvalidObject() {
{
UErrorCode status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus(status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_ZERO_ERROR;
DecimalFormat dfGood(status);
assertSuccess(WHERE, status);
// An invalid object should not be equal to a valid object.
// This also tests that no segmentation fault occurs in the comparison operator due
// to any dangling/nullptr pointers. (ICU-20381).
assertTrue(WHERE, dfGood != dfBogus);
status = U_MEMORY_ALLOCATION_ERROR;
DecimalFormat dfBogus2(status);
assertEquals(WHERE, U_MEMORY_ALLOCATION_ERROR, status);
// Two invalid objects should not be equal.
// (Also verify that nullptr isn't t dereferenced in the comparision operator.)
assertTrue(WHERE, dfBogus != dfBogus2);
// Verify the comparison operator works for two valid objects.
status = U_ZERO_ERROR;
DecimalFormat dfGood2(status);
assertSuccess(WHERE, status);
assertTrue(WHERE, dfGood == dfGood2);
// Verify that the assignment operator sets the object to an invalid state, and
// that no segmentation fault occurs due to any dangling/nullptr pointers.
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfAssignmentBogus = DecimalFormat(status);
// Verify comparison for the assigned object.
assertTrue(WHERE, dfAssignmentBogus != dfGood);
assertTrue(WHERE, dfAssignmentBogus != dfGood2);
assertTrue(WHERE, dfAssignmentBogus != dfBogus);
// Verify that cloning our original invalid object gives nullptr.
auto dfBogusClone = dfBogus.clone();
assertTrue(WHERE, dfBogusClone == nullptr);
// Verify that cloning our assigned invalid object gives nullptr.
auto dfBogusClone2 = dfAssignmentBogus.clone();
assertTrue(WHERE, dfBogusClone2 == nullptr);
// Verify copy constructing from an invalid object is also invalid.
DecimalFormat dfCopy(dfBogus);
assertTrue(WHERE, dfCopy != dfGood);
assertTrue(WHERE, dfCopy != dfGood2);
assertTrue(WHERE, dfCopy != dfBogus);
DecimalFormat dfCopyAssign = dfBogus;
assertTrue(WHERE, dfCopyAssign != dfGood);
assertTrue(WHERE, dfCopyAssign != dfGood2);
assertTrue(WHERE, dfCopyAssign != dfBogus);
auto dfBogusCopyClone1 = dfCopy.clone();
auto dfBogusCopyClone2 = dfCopyAssign.clone();
assertTrue(WHERE, dfBogusCopyClone1 == nullptr);
assertTrue(WHERE, dfBogusCopyClone2 == nullptr);
}
{
// Try each DecimalFormat class method that lacks an error code parameter, verifying
// we don't crash (segmentation fault) on invalid objects.
UErrorCode status = U_ZERO_ERROR;
const UnicodeString pattern(u"0.###E0");
UParseError pe;
DecimalFormatSymbols symbols(Locale::getUS(), status);
assertSuccess(WHERE, status);
CurrencyPluralInfo currencyPI(status);
assertSuccess(WHERE, status);
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus1(status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus2(pattern, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus3(pattern, new DecimalFormatSymbols(symbols), status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus4(pattern, new DecimalFormatSymbols(symbols), UNumberFormatStyle::UNUM_CURRENCY, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
status = U_INTERNAL_PROGRAM_ERROR;
DecimalFormat dfBogus5(pattern, new DecimalFormatSymbols(symbols), pe, status);
assertEquals(WHERE, U_INTERNAL_PROGRAM_ERROR, status);
for (DecimalFormat *df : {&dfBogus1, &dfBogus2, &dfBogus3, &dfBogus4, &dfBogus5})
{
df->setGroupingUsed(true);
df->setParseIntegerOnly(false);
df->setLenient(true);
auto dfClone = df->clone();
assertTrue(WHERE, dfClone == nullptr);
UnicodeString dest;
FieldPosition fp;
df->format(1.2, dest, fp);
df->format(static_cast<int32_t>(1234), dest, fp);
df->format(static_cast<int64_t>(1234), dest, fp);
UnicodeString text("-1,234.00");
Formattable result;
ParsePosition pos(0);
df->parse(text, result, pos);
CurrencyAmount* ca = df->parseCurrency(text, pos);
assertTrue(WHERE, ca == nullptr);
const DecimalFormatSymbols* dfs = df->getDecimalFormatSymbols();
assertTrue(WHERE, dfs == nullptr);
df->adoptDecimalFormatSymbols(nullptr);
df->setDecimalFormatSymbols(symbols);
const CurrencyPluralInfo* cpi = df->getCurrencyPluralInfo();
assertTrue(WHERE, cpi == nullptr);
df->adoptCurrencyPluralInfo(nullptr);
df->setCurrencyPluralInfo(currencyPI);
UnicodeString prefix("-123");
df->getPositivePrefix(dest);
df->setPositivePrefix(prefix);
df->getNegativePrefix(dest);
df->setNegativePrefix(prefix);
df->getPositiveSuffix(dest);
df->setPositiveSuffix(prefix);
df->getNegativeSuffix(dest);
df->setNegativeSuffix(prefix);
df->isSignAlwaysShown();
df->setSignAlwaysShown(true);
df->getMultiplier();
df->setMultiplier(10);
df->getMultiplierScale();
df->setMultiplierScale(2);
df->getRoundingIncrement();
df->setRoundingIncrement(1.2);
df->getRoundingMode();
df->setRoundingMode(DecimalFormat::ERoundingMode::kRoundDown);
df->getFormatWidth();
df->setFormatWidth(0);
UnicodeString pad(" ");
df->getPadCharacterString();
df->setPadCharacter(pad);
df->getPadPosition();
df->setPadPosition(DecimalFormat::EPadPosition::kPadBeforePrefix);
df->isScientificNotation();
df->setScientificNotation(false);
df->getMinimumExponentDigits();
df->setMinimumExponentDigits(1);
df->isExponentSignAlwaysShown();
df->setExponentSignAlwaysShown(true);
df->getGroupingSize();
df->setGroupingSize(3);
df->getSecondaryGroupingSize();
df->setSecondaryGroupingSize(-1);
df->getMinimumGroupingDigits();
df->setMinimumGroupingDigits(-1);
df->isDecimalSeparatorAlwaysShown();
df->setDecimalSeparatorAlwaysShown(true);
df->isDecimalPatternMatchRequired();
df->setDecimalPatternMatchRequired(false);
df->isParseNoExponent();
df->setParseNoExponent(true);
df->isParseCaseSensitive();
df->setParseCaseSensitive(false);
df->isFormatFailIfMoreThanMaxDigits();
df->setFormatFailIfMoreThanMaxDigits(true);
df->toPattern(dest);
df->toLocalizedPattern(dest);
df->setMaximumIntegerDigits(10);
df->setMinimumIntegerDigits(0);
df->setMaximumFractionDigits(2);
df->setMinimumFractionDigits(0);
df->getMinimumSignificantDigits();
df->setMinimumSignificantDigits(0);
df->getMaximumSignificantDigits();
df->setMaximumSignificantDigits(5);
df->areSignificantDigitsUsed();
df->setSignificantDigitsUsed(true);
df->setCurrency(u"USD");
df->getCurrencyUsage();
const number::LocalizedNumberFormatter* lnf = df->toNumberFormatter(status);
assertEquals("toNumberFormatter should return nullptr",
(int64_t) nullptr, (int64_t) lnf);
// Should not crash when chaining to error code enabled methods on the LNF
lnf->formatInt(1, status);
lnf->formatDouble(1.0, status);
lnf->formatDecimal("1", status);
lnf->toFormat(status);
lnf->toSkeleton(status);
lnf->copyErrorTo(status);
}
}
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| 39.066955 | 152 | 0.66182 | [
"object"
] |
c8c139d3ba850e564bd51b4fed500f78f7ee051d | 398 | cpp | C++ | Sabertooth/main.cpp | AugustoChies/OtimizacaoGB | 21b5aeb2f5b6ce097f953f5ccdd157d7dc9dfe8b | [
"MIT"
] | null | null | null | Sabertooth/main.cpp | AugustoChies/OtimizacaoGB | 21b5aeb2f5b6ce097f953f5ccdd157d7dc9dfe8b | [
"MIT"
] | null | null | null | Sabertooth/main.cpp | AugustoChies/OtimizacaoGB | 21b5aeb2f5b6ce097f953f5ccdd157d7dc9dfe8b | [
"MIT"
] | null | null | null | #include "System.h"
#define EXIT_FAILURE -1
#define EXIT_SUCCESS 0
Object cubo;
int main() {
cubo.readobj("uvmappedcow.obj");
//cubo.setupMesh();
System system;
if ( system.GLFWInit() != 0 ){
return EXIT_FAILURE;
}
if ( system.OpenGLSetup() != 0 ){
return EXIT_FAILURE;
}
if ( system.SystemSetup() != 0 ){
return EXIT_FAILURE;
}
system.Run();
system.Finish();
return 0;
} | 13.266667 | 34 | 0.648241 | [
"object"
] |
c8c25c30bc1f4bde8569b2b91982cc339df99bc9 | 6,029 | hpp | C++ | library/include/rocwmma/internal/io_config.hpp | mkarunan/rocWMMA | 390a2e793699a1e17c18e46d7fe51e245907f012 | [
"MIT"
] | null | null | null | library/include/rocwmma/internal/io_config.hpp | mkarunan/rocWMMA | 390a2e793699a1e17c18e46d7fe51e245907f012 | [
"MIT"
] | null | null | null | library/include/rocwmma/internal/io_config.hpp | mkarunan/rocWMMA | 390a2e793699a1e17c18e46d7fe51e245907f012 | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* MIT License
*
* Copyright 2021-2022 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef ROCWMMA_IO_CONFIG_HPP
#define ROCWMMA_IO_CONFIG_HPP
#include "broadcast.hpp"
#include "coop_load.hpp"
#include "coop_store.hpp"
#include "io_shape.hpp"
#include "opaque_load.hpp"
#include "opaque_store.hpp"
#include "pack.hpp"
#include "types.hpp"
#include "unpack.hpp"
namespace rocwmma
{
/**
* \ingroup rocwmma
* \defgroup ROCWMMA IOConfig
*
* @brief ROCWMMA fragment input and output configurations leveraging amdgcn architecture
*/
/**
* \ingroup ROCWMMA IOConfig
* @{
*/
/*! \struct IOConfig
* \brief Definition of ROCWMMA fragment input / output configurations
* in specific matrix context.
*
* @tparam Matrix fragment context
* @tparam BlockM/N/K block dimensions
* @tparam DataT data type
* @tparam DataLayout in-memory layout as col_major or row_major
* @param BlockDim leading block dimension (row / col size)
* @param KDim minor block dimension (row / col count)
* @param MaxVectorWidth maximum allowable vector width
* @param VectorWidth currently used vector width
* @param CoopIndex shared wave index (0 = row, 1 = col)
* @param IOTraits Input/output traits specific to AMDGCN architecture
* @param Packer Packs raw fragment data into register
* @param Unpacker Unpacks registers to raw fragment data
* @param Broadcaster Sets all fragment data to a desired value
* @param MatrixLayout Maps GPU threads to matrix shape or geometry
* @param Loader Issues load instructions for raw fragment data
* @param Storer Issues store instructions for raw fragment data
* @param CoopLoader Issues cooperative load instructions for raw fragment data
* @param CoopStorer Issues cooperative store instructions for raw fragment data
*/
template <typename MatrixT,
uint32_t BlockM,
uint32_t BlockN,
uint32_t BlockK,
typename DataT,
typename DataLayoutT>
struct IOConfig
{
using IOShape = IOShape<MatrixT, BlockM, BlockN, BlockK, DataT, DataLayoutT>;
using IOTraits = IOTraits<IOShape::BlockDim, IOShape::KDim, DataT, IOShape::VectorWidth>;
using Packer = Pack<DataT, IOTraits::UnpackedSize>;
using Unpacker = Unpack<DataT, IOTraits::PackedSize>;
using Broadcaster = Broadcast<DataT, IOTraits::UnpackedSize>;
using MappingUtil
= MappingUtil<IOShape::BlockHeight, IOShape::BlockWidth, DataT, DataLayoutT>;
using Loader = OpaqueLoad<IOShape::BlockDim,
IOShape::KDim,
DataT,
typename IOShape::DataLayout,
typename IOShape::MatrixLayout,
IOShape::VectorWidth>;
using Storer = OpaqueStore<IOShape::BlockDim,
IOShape::KDim,
DataT,
typename IOShape::DataLayout,
typename IOShape::MatrixLayout,
IOShape::VectorWidth>;
using CoopLoader = CooperativeLoad<IOShape::BlockDim,
IOShape::KDim,
DataT,
typename IOShape::DataLayout,
typename IOShape::MatrixLayout,
IOShape::VectorWidth>;
using CoopStorer = CooperativeStore<IOShape::BlockDim,
IOShape::KDim,
DataT,
typename IOShape::DataLayout,
typename IOShape::MatrixLayout,
IOShape::VectorWidth>;
};
/************************************************
* Matrix C/D (accumulator) with undetermined DataLayout
*
* Fewer specific indications for matrix data geometry I/O, however
* general IOTraits, Pack/Unpack, Broadcast still available.
*
* */
template <uint32_t BlockM, uint32_t BlockN, uint32_t BlockK, typename DataT>
struct IOConfig<accumulator, BlockM, BlockN, BlockK, DataT, void>
{
using IOShape = IOShape<accumulator, BlockM, BlockN, BlockK, DataT, void>;
using IOTraits = IOTraits<IOShape::BlockDim, IOShape::KDim, DataT>;
using Packer = Pack<DataT, IOTraits::UnpackedSize>;
using Unpacker = Unpack<DataT, IOTraits::PackedSize>;
using Broadcaster = Broadcast<DataT, IOTraits::UnpackedSize>;
};
} // namespace rocwmma
#endif // ROCWMMA_IO_CONFIG_HPP
| 41.868056 | 100 | 0.607563 | [
"geometry",
"shape",
"vector"
] |
c8c361f88037bd89769e063b04c59062b381cf3d | 5,926 | cpp | C++ | src/rpccrypto.cpp | durgeshkmr/SlimCoin-upgrade | efcc261711e7abeb22bb14fb7ab73f48a709b4e2 | [
"MIT"
] | 29 | 2017-03-16T19:01:36.000Z | 2022-03-03T03:36:55.000Z | src/rpccrypto.cpp | durgeshkmr/SlimCoin-upgrade | efcc261711e7abeb22bb14fb7ab73f48a709b4e2 | [
"MIT"
] | 17 | 2015-08-19T23:36:11.000Z | 2020-11-20T17:51:48.000Z | src/rpccrypto.cpp | durgeshkmr/SlimCoin-upgrade | efcc261711e7abeb22bb14fb7ab73f48a709b4e2 | [
"MIT"
] | 28 | 2016-06-15T18:39:22.000Z | 2021-11-21T10:31:05.000Z | /*
* Copyright (c) 2018 John Doering <ghostlander@slimcoin.org>
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "bitcoinrpc.h"
#include "init.h"
#include "util.h"
#include "base58.h"
using namespace json_spirit;
using namespace std;
extern Object JSONRPCError(int code, const string& message);
Value encryptmessage(const Array ¶ms, bool fHelp) {
if(fHelp || (params.size() != 2))
throw(runtime_error(
"encryptmessage <public key> <message>\n"
"Encrypts an arbitrary message with the public key provided;\n"
"if an address is provided instead, the respective key is picked from the wallet.\n"));
CPubKey pubKey;
if(IsHex(params[0].get_str())) {
pubKey = ParseHex(params[0].get_str());
} else {
CBitcoinAddress addr(params[0].get_str());
if(addr.IsValid()) {
CKeyID keyID;
addr.GetKeyID(keyID);
if(!pwalletMain->GetPubKey(keyID, pubKey))
throw(JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Public key not found for this address"));
}
}
vector<unsigned char> vchEncrypted;
string strData = params[1].get_str();
pubKey.EncryptData(vector<unsigned char>(strData.begin(), strData.end()), vchEncrypted);
return(EncodeBase58Check(vchEncrypted));
}
Value decryptmessage(const Array ¶ms, bool fHelp) {
if(fHelp || (params.size() != 2))
throw(runtime_error(
"decryptmessage <private key> <message>\n"
"Decrypts an arbitrary message with the private key provided;\n"
"if an address is provided instead, the respective key is picked from the wallet.\n"));
EnsureWalletIsUnlocked();
CKey key;
CBitcoinAddress addr(params[0].get_str());
if(addr.IsValid()) {
CKeyID keyID;
addr.GetKeyID(keyID);
if(!pwalletMain->GetKey(keyID, key))
throw(JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key not found for this address"));
} else {
CBitcoinSecret vchSecret;
if(!vchSecret.SetString(params[0].get_str()))
throw(JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"));
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
}
vector<unsigned char> vchEncrypted;
if(!DecodeBase58Check(params[1].get_str(), vchEncrypted))
throw(JSONRPCError(RPC_INVALID_PARAMETER, "Invalid message string"));
vector<unsigned char> vchDecrypted;
key.DecryptData(vchEncrypted, vchDecrypted);
return(std::string((const char *) &vchDecrypted[0], vchDecrypted.size()));
}
Value encryptdata(const Array ¶ms, bool fHelp) {
if(fHelp || (params.size() != 2))
throw(runtime_error(
"encryptdata <public key> <hex data>\n"
"Encrypts arbitrary data with the public key provided;\n"
"if an address is provided instead, the respective key is picked from the wallet.\n"));
CPubKey pubKey;
if(IsHex(params[0].get_str())) {
pubKey = ParseHex(params[0].get_str());
} else {
CBitcoinAddress addr(params[0].get_str());
if(addr.IsValid()) {
CKeyID keyID;
addr.GetKeyID(keyID);
if(!pwalletMain->GetPubKey(keyID, pubKey))
throw(JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Public key not found for this address"));
}
}
vector<unsigned char> vchEncrypted;
pubKey.EncryptData(ParseHex(params[1].get_str()), vchEncrypted);
return(HexStr(vchEncrypted));
}
Value decryptdata(const Array ¶ms, bool fHelp) {
if(fHelp || (params.size() != 2))
throw(runtime_error(
"decryptdata <private key> <hex data>\n"
"Decrypts arbitrary data with the private key provided;\n"
"if an address is provided instead, the respective key is picked from the wallet.\n"));
EnsureWalletIsUnlocked();
CKey key;
CBitcoinAddress addr(params[0].get_str());
if(addr.IsValid()) {
CKeyID keyID;
addr.GetKeyID(keyID);
if(!pwalletMain->GetKey(keyID, key))
throw(JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key not found for this address"));
} else {
CBitcoinSecret vchSecret;
if(!vchSecret.SetString(params[0].get_str()))
throw(JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"));
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
}
vector<unsigned char> vchDecrypted;
key.DecryptData(ParseHex(params[1].get_str()), vchDecrypted);
return(HexStr(vchDecrypted));
}
| 36.355828 | 103 | 0.681404 | [
"object",
"vector"
] |
c8c53be447292b60fbfa93aa34541a8b4e9e7799 | 14,112 | cpp | C++ | src/utils/MRMPairFinder.cpp | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/utils/MRMPairFinder.cpp | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/utils/MRMPairFinder.cpp | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/FeatureFinderAlgorithmIsotopeWavelet.h>
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/FeatureFinder_impl.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
//Doxygen docu
//-------------------------------------------------------------
/**
@page UTILS_MRMPairFinder MRMPairFinder
@brief Util which can be used to evaluate pairs of MRM experiments
@experimental This software is experimental and might contain bugs!
<B>The command line parameters of this tool are:</B>
@verbinclude UTILS_MRMPairFinder.cli
<B>INI file documentation of this tool:</B>
@htmlinclude UTILS_MRMPairFinder.html
*/
// We do not want this class to show up in the docu:
/// @cond TOPPCLASSES
// simple helper struct which stores
// a SILAC pair, with m/z value rt
struct SILAC_pair
{
double mz_light;
double mz_heavy;
double rt;
};
// helper struct which stores the
// SILAC_pair which it is matched to
struct MatchedFeature
{
MatchedFeature(const Feature & feature, Size index) :
f(feature),
idx(index)
{
}
Feature f;
Size idx;
};
// This struct store quantitation for one scan
// for fast access to defined pair
struct SILACQuantitation
{
SILACQuantitation(double l_intensity, double h_intensity, Size index) :
light_intensity(l_intensity),
heavy_intensity(h_intensity),
idx(index)
{
}
double light_intensity;
double heavy_intensity;
Size idx;
};
class TOPPMRMPairFinder :
public TOPPBase
{
public:
TOPPMRMPairFinder() :
TOPPBase("MRMPairFinder", "Util which can be used to evaluate labeled pair ratios on MRM features.", false)
{
}
protected:
void registerOptionsAndFlags_()
{
registerInputFile_("in", "<file>", "", "Input featureXML file containing the features of the MRM experiment spectra.");
setValidFormats_("in", ListUtils::create<String>("featureXML"));
registerInputFile_("pair_in", "<file>", "", "Pair-file in the format: prec-m/z-light prec-m/z-heavy frag-m/z-light frag-m/z-heavy rt");
setValidFormats_("pair_in", ListUtils::create<String>("csv"));
registerOutputFile_("out", "<file>", "", "Output consensusXML file were the pairs of the features will be written to.");
setValidFormats_("out", ListUtils::create<String>("consensusXML"));
registerOutputFile_("feature_out", "<file>", "", "Output featureXML file, only written if given, skipped otherwise.", false);
setValidFormats_("feature_out", ListUtils::create<String>("featureXML"));
registerDoubleOption_("mass_tolerance", "<tolerance>", 0.01, "Precursor mass tolerance which is used for the pair finding and the matching of the given pair m/z values to the features.", false, true);
setMinFloat_("mass_tolerance", 0.0);
registerDoubleOption_("RT_tolerance", "<tolerance>", 200, "Maximal deviation in RT dimension in seconds a feature can have when comparing to the RT values given in the pair file.", false, true);
setMinFloat_("RT_tolerance", 0.0);
registerDoubleOption_("RT_pair_tolerance", "<tolerance>", 5, "Maximal deviation in RT dimension in seconds the two partners of a pair is allowed to have.", false, true);
setMinFloat_("RT_pair_tolerance", 0.0);
}
ExitCodes main_(int, const char **)
{
//-------------------------------------------------------------
// parsing parameters
//-------------------------------------------------------------
String in(getStringOption_("in"));
String out(getStringOption_("out"));
String feature_out(getStringOption_("feature_out"));
String pair_in(getStringOption_("pair_in"));
double mass_tolerance(getDoubleOption_("mass_tolerance"));
double RT_tolerance(getDoubleOption_("RT_tolerance"));
double RT_pair_tolerance(getDoubleOption_("RT_pair_tolerance"));
//-------------------------------------------------------------
// reading input
//-------------------------------------------------------------
FeatureMap<> all_mrm_features;
FeatureXMLFile().load(in, all_mrm_features);
// read pair file
ifstream is(pair_in.c_str());
String line;
Map<double, Map<double, vector<SILAC_pair> > > pairs;
while (getline(is, line))
{
line.trim();
if (line.empty() || line[0] == '#')
{
continue;
}
vector<String> split;
line.split(' ', split);
if (split.empty())
{
line.split('\t', split);
}
if (split.size() != 5)
{
cerr << "missformated line ('" << line << "') should be (space separated) 'prec-m/z-light prec-m/z-heavy frag-m/z-light frag-m/z-heavy rt'" << endl;
continue;
}
SILAC_pair p;
double prec_mz_light = split[0].toDouble();
double prec_mz_heavy = split[1].toDouble();
p.mz_light = split[2].toDouble();
p.mz_heavy = split[3].toDouble();
p.rt = split[4].toDouble();
pairs[prec_mz_light][prec_mz_heavy].push_back(p);
}
is.close();
//-------------------------------------------------------------
// calculations
//-------------------------------------------------------------
ConsensusMap results_map;
results_map.getFileDescriptions()[0].label = "light";
results_map.getFileDescriptions()[0].filename = in;
results_map.getFileDescriptions()[1].label = "heavy";
results_map.getFileDescriptions()[1].filename = in;
// collect the different MRM XIC pairs for each SILAC pair as quantlets
// then calculate the ratio over the quanlets and calculate some statistics
FeatureMap<> all_features;
for (Map<double, Map<double, vector<SILAC_pair> > >::ConstIterator it1 = pairs.begin(); it1 != pairs.end(); ++it1)
{
for (Map<double, vector<SILAC_pair> >::ConstIterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
{
vector<SILACQuantitation> quantlets;
writeDebug_("Analyzing SILAC pair: " + String(it1->first) + " <-> " + String(it2->first), 3);
Size idx = 0;
for (vector<SILAC_pair>::const_iterator pit = it2->second.begin(); pit != it2->second.end(); ++pit, ++idx)
{
FeatureMap<> feature_map_light, feature_map_heavy;
for (FeatureMap<>::const_iterator it = all_mrm_features.begin(); it != all_mrm_features.end(); ++it)
{
if (fabs((double)it->getMetaValue("MZ") - it1->first) < mass_tolerance &&
fabs(it->getMZ() - pit->mz_light) < mass_tolerance &&
fabs(it->getRT() - pit->rt) < RT_tolerance)
{
feature_map_light.push_back(*it);
}
if (fabs((double)it->getMetaValue("MZ") - it2->first) < mass_tolerance &&
fabs(it->getMZ() - pit->mz_heavy) < mass_tolerance &&
fabs(it->getRT() - pit->rt) < RT_tolerance)
{
feature_map_heavy.push_back(*it);
}
}
// search if feature maps to m/z value of pair
vector<MatchedFeature> light, heavy;
for (FeatureMap<>::const_iterator fit = feature_map_light.begin(); fit != feature_map_light.end(); ++fit)
{
all_features.push_back(*fit);
light.push_back(MatchedFeature(*fit, idx));
}
for (FeatureMap<>::const_iterator fit = feature_map_heavy.begin(); fit != feature_map_heavy.end(); ++fit)
{
all_features.push_back(*fit);
heavy.push_back(MatchedFeature(*fit, idx));
}
if (!heavy.empty() && !light.empty())
{
writeDebug_("Finding best feature pair out of " + String(light.size()) + " light and " + String(heavy.size()) + " heavy matching features.", 1);
// now find "good" matches, means the pair with the smallest m/z deviation
Feature best_light, best_heavy;
double best_deviation(numeric_limits<double>::max());
Size best_idx(it2->second.size());
for (vector<MatchedFeature>::const_iterator fit1 = light.begin(); fit1 != light.end(); ++fit1)
{
for (vector<MatchedFeature>::const_iterator fit2 = heavy.begin(); fit2 != heavy.end(); ++fit2)
{
if (fit1->idx != fit2->idx || fabs(fit1->f.getRT() - fit2->f.getRT()) > RT_pair_tolerance)
{
continue;
}
double deviation(0);
deviation = fabs(fit1->f.getMZ() - it2->second[fit1->idx].mz_light) +
fabs(fit2->f.getMZ() - it2->second[fit2->idx].mz_heavy);
if (deviation < best_deviation && deviation < mass_tolerance)
{
best_light = fit1->f;
best_heavy = fit2->f;
best_idx = fit1->idx;
}
}
}
if (best_idx == it2->second.size())
{
continue;
}
ConsensusFeature SILAC_feature;
SILAC_feature.setMZ((best_light.getMZ() + best_heavy.getMZ()) / 2.0);
SILAC_feature.setRT((best_light.getRT() + best_heavy.getRT()) / 2.0);
SILAC_feature.insert(0, best_light);
SILAC_feature.insert(1, best_heavy);
results_map.push_back(SILAC_feature);
quantlets.push_back(SILACQuantitation(best_light.getIntensity(), best_heavy.getIntensity(), best_idx));
writeDebug_("Ratio of XIC: " + String(best_heavy.getIntensity() / best_light.getIntensity()) + " " + String(best_light.getMZ()) + " <-> " + String(best_heavy.getMZ()) + " @" + String(SILAC_feature.getRT()) + " RT-heavy=" + String(best_heavy.getRT()) + ", RT-light=" + String(best_light.getRT()) + ", RT-diff=" + String(best_heavy.getRT() - best_light.getRT()) +
" avg. int " + String((best_heavy.getIntensity() + best_light.getIntensity()) / 2.0), 1);
}
}
writeDebug_("Quantitation of pair " + String(it1->first) + " <-> " + String(it2->first) + " (#XIC pairs for quantation=" + String(quantlets.size()) + ")", 1);
if (quantlets.empty())
{
continue;
}
// simply add up all intensities and calculate the final ratio
double light_sum(0), heavy_sum(0);
vector<double> light_ints, heavy_ints, ratios;
for (vector<SILACQuantitation>::const_iterator qit1 = quantlets.begin(); qit1 != quantlets.end(); ++qit1)
{
light_sum += qit1->light_intensity;
light_ints.push_back(qit1->light_intensity);
heavy_sum += qit1->heavy_intensity;
heavy_ints.push_back(qit1->heavy_intensity);
ratios.push_back(qit1->heavy_intensity / qit1->light_intensity * (qit1->heavy_intensity + qit1->light_intensity));
}
double absdev_ratios = Math::absdev(ratios.begin(), ratios.begin() + (ratios.size()) / (light_sum + heavy_sum));
cout << "Ratio: " << it1->first << " <-> " << it2->first << " @ " << it2->second.begin()->rt << " s, ratio(h/l) " << heavy_sum / light_sum << " +/- " << absdev_ratios << " " << "(#XIC-pairs for quantation: " + String(ratios.size()) + " )" << endl;
}
}
//-------------------------------------------------------------
// writing output
//-------------------------------------------------------------
if (feature_out != "")
{
FeatureXMLFile().store(feature_out, all_features);
}
writeDebug_("Writing output", 1);
ConsensusXMLFile().store(out, results_map);
return EXECUTION_OK;
}
};
int main(int argc, const char ** argv)
{
TOPPMRMPairFinder tool;
return tool.main(argc, argv);
}
/// @endcond
| 41.505882 | 373 | 0.592971 | [
"vector"
] |
c8c671d74f91ea5bbaaacf33e9c91b64a53a011d | 48,026 | cpp | C++ | src/mod/pop/wave_extensions.cpp | rafradek/sigsegv-mvm | e36f347ff5c89fcfc9ceff7ddde22ec2d1499edd | [
"BSD-2-Clause"
] | 7 | 2021-03-02T02:27:18.000Z | 2022-02-18T00:56:28.000Z | src/mod/pop/wave_extensions.cpp | rafradek/sigsegv-mvm | e36f347ff5c89fcfc9ceff7ddde22ec2d1499edd | [
"BSD-2-Clause"
] | 3 | 2021-11-29T15:53:02.000Z | 2022-02-21T13:09:22.000Z | src/mod/pop/wave_extensions.cpp | rafradek/sigsegv-mvm | e36f347ff5c89fcfc9ceff7ddde22ec2d1499edd | [
"BSD-2-Clause"
] | 5 | 2021-03-04T20:26:11.000Z | 2021-11-26T07:09:24.000Z | #include "mod.h"
#include "stub/populators.h"
#include "mod/pop/kv_conditional.h"
#include "stub/usermessages_sv.h"
#include "stub/entities.h"
#include "stub/nextbot_cc_behavior.h"
#include "stub/objects.h"
#include "stub/gamerules.h"
#include "stub/tf_objective_resource.h"
#include "stub/tfplayer.h"
#include "stub/team.h"
#include "util/scope.h"
#include "util/iterate.h"
#include "stub/strings.h"
#include "stub/misc.h"
#include "mod/pop/pointtemplate.h"
#include "mod/pop/common.h"
namespace Mod::Pop::Wave_Extensions
{
struct SentryGunInfo
{
~SentryGunInfo()
{
if (sentry != nullptr) {
sentry->DetonateObject();
}
}
bool use_hint = true;
std::vector<CHandle<CTFBotHintSentrygun>> hints;
Vector origin;
QAngle angles;
int teamnum = TF_TEAM_BLUE;
float delay = 0.0f;
int level = 0;
bool is_mini = false;
int health = -1;
bool spawned = false;
int skin = 0;
int bodygroup = 0;
CHandle<CObjectSentrygun> sentry;
};
struct BossInfo
{
~BossInfo()
{
if (boss != nullptr) {
boss->Remove();
}
}
Vector origin;
CHalloweenBaseBoss::HalloweenBossType type = CHalloweenBaseBoss::INVALID;
int teamnum = TF_TEAM_HALLOWEEN_BOSS;
int health = -1;
float delay = 0.0f;
float lifetime = FLT_MAX;
bool spawned = false;
CHandle<CHalloweenBaseBoss> boss;
};
struct WaveData
{
std::vector<std::string> explanation;
std::vector<SentryGunInfo> sentryguns;
std::vector<BossInfo> bosses;
std::map<std::string,float> sound_loops;
std::vector<PointTemplateInfo> templ;
std::vector<std::shared_ptr<PointTemplateInstance>> templ_inst;
std::vector<ETFCond> addconds;
std::vector<ETFCond> addconds_class[11] = {};
std::vector<ItemAttributes> item_attributes;
ForceItems force_items;
bool red_team_wipe_causes_wave_loss = false;
bool blue_team_wipe_causes_wave_loss = false;
bool finishing_wave_causes_wave_loss = false;
bool finishing_wave_and_player_wipe_causes_wave_loss = false;
bool defined_class_attributes = false;
std::map<std::string,float> player_attributes_class[11] = {};
std::map<std::string,float> player_attributes;
int custom_wave_number = INT_MIN;
int custom_max_wave_number = INT_MIN;
float sound_time_end = 0.f;
IntervalTimer t_wavestart;
IntervalTimer t_waveinit;
CBaseEntity *explanation_text;
};
std::map<CWave *, WaveData> waves;
std::vector<CWave *> waves_vec;
void WaveCleanup(CWave *wave){
auto &data = waves[wave];
for (auto inst : data.templ_inst) {
if (inst != nullptr)
inst->OnKilledParent(false);
}
ForEachTFPlayer([&](CTFPlayer *player) {
if (player->IsBot()) return;
bool respawn = false;
ForEachTFPlayerEconEntity(player, [&](CEconEntity *entity) {
CEconItemView *item_view = entity->GetItem();
if (item_view == nullptr) return;
bool found = false;
const char *classname = item_view->GetItemDefinition()->GetItemClass();
std::map<CEconItemAttributeDefinition *, std::string> *attribs;
for (auto& item_attributes : data.item_attributes) {
if (item_attributes.entry->Matches(classname, item_view)) {
attribs = &(item_attributes.attributes);
found = true;
break;
}
}
if (found && attribs != nullptr) {
CEconItemView *view = item_view;
for (auto& entry : *attribs) {
view->GetAttributeList().RemoveAttribute(entry.first);
}
}
int forced = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER(entity, forced, is_forced_item);
if (forced != 0) {
respawn = true;
}
});
if (respawn) {
player->ForceRegenerateAndRespawn();
}
});
data.templ_inst.clear();
}
WaveData *GetWaveData(CWave *wave)
{
if (!TFGameRules()->IsMannVsMachineMode())
return nullptr;
if (wave == nullptr)
return nullptr;
auto it = waves.find(wave);
if (it != waves.end()) {
return &(it->second);
}
return nullptr;
}
WaveData *GetCurrentWaveData()
{
if (!TFGameRules()->IsMannVsMachineMode())
return nullptr;
CWave *wave = g_pPopulationManager->GetCurrentWave();
if (wave == nullptr)
return nullptr;
auto it = waves.find(wave);
if (it != waves.end()) {
return &(it->second);
}
return nullptr;
}
DETOUR_DECL_MEMBER(void, CWave_dtor0)
{
auto wave = reinterpret_cast<CWave *>(this);
// DevMsg("CWave %08x: dtor0\n", (uintptr_t)wave);
WaveCleanup(wave);
waves.erase(wave);
DETOUR_MEMBER_CALL(CWave_dtor0)();
}
DETOUR_DECL_MEMBER(void, CWave_dtor2)
{
auto wave = reinterpret_cast<CWave *>(this);
WaveCleanup(wave);
// DevMsg("CWave %08x: dtor2\n", (uintptr_t)wave);
waves.erase(wave);
DETOUR_MEMBER_CALL(CWave_dtor2)();
}
bool FindSentryHint(const char *name, std::vector<CHandle<CTFBotHintSentrygun>>& hints)
{
ForEachEntityByClassname("bot_hint_sentrygun", [&](CBaseEntity *ent){
if (FStrEq(STRING(ent->GetEntityName()), name)) {
auto hint = rtti_cast<CTFBotHintSentrygun *>(ent);
if (hint != nullptr) {
hints.emplace_back(hint);
}
}
});
return !hints.empty();
}
void Parse_Explanation(CWave *wave, KeyValues *kv)
{
waves[wave].explanation.clear();
FOR_EACH_SUBKEY(kv, subkey) {
waves[wave].explanation.emplace_back(subkey->GetString());
}
}
void Parse_SentryGun(CWave *wave, KeyValues *kv)
{
SentryGunInfo info;
FOR_EACH_SUBKEY(kv, subkey) {
const char *name = subkey->GetName();
if (FStrEq(name, "HintName")) {
if (!FindSentryHint(subkey->GetString(), info.hints)) {
Warning("Could not find a bot_hint_sentrygun entity named \"%s\".\n", subkey->GetString());
return;
}
} else if (FStrEq(name, "TeamNum")) {
info.teamnum = Clamp(subkey->GetInt(), (int)TF_TEAM_RED, (int)TF_TEAM_BLUE);
// DevMsg("TeamNum \"%s\" --> %d\n", subkey->GetString(), info.teamnum);
} else if (FStrEq(name, "Delay")) {
info.delay = Max(0.0f, subkey->GetFloat());
// DevMsg("Delay \"%s\" --> %.1f\n", subkey->GetString(), info.delay);
} else if (FStrEq(name, "Level")) {
info.level = Clamp(subkey->GetInt(), 1, 3);
// DevMsg("Level \"%s\" --> %d\n", subkey->GetString(), info.level);
} else if (FStrEq(name, "IsMini")) {
info.is_mini = subkey->GetBool();
// DevMsg("Level \"%s\" --> %d\n", subkey->GetString(), info.level);
} else if (FStrEq(name, "Health")) {
info.health = subkey->GetInt();
// DevMsg("Level \"%s\" --> %d\n", subkey->GetString(), info.level);
} else if (FStrEq(name, "Bodygroup")) {
info.bodygroup = subkey->GetInt();
// DevMsg("Level \"%s\" --> %d\n", subkey->GetString(), info.level);
} else if (FStrEq(name, "Skin")) {
info.skin = subkey->GetInt();
// DevMsg("Level \"%s\" --> %d\n", subkey->GetString(), info.level);
} else if (FStrEq(name, "Position")) {
FOR_EACH_SUBKEY(subkey, subsub) {
const char *name = subsub->GetName();
float value = subsub->GetFloat();
if (FStrEq(name, "X")) {
info.origin.x = value;
} else if (FStrEq(name, "Y")) {
info.origin.y = value;
} else if (FStrEq(name, "Z")) {
info.origin.z = value;
} else if (FStrEq(name, "Pitch")) {
info.angles.x = value;
} else if (FStrEq(name, "Yaw")) {
info.angles.y = value;
} else if (FStrEq(name, "Roll")) {
info.angles.z = value;
} else {
Warning("Unknown key \'%s\' in SentryGun Position sub-block.\n", name);
}
}
info.use_hint = false;
} else {
Warning("Unknown key \'%s\' in SentryGun block.\n", name);
}
}
bool fail = false;
if (info.use_hint && info.hints.empty()) {
Warning("Missing HintName key or Position block in SentryGun block.\n");
fail = true;
}
if (info.level == -1) {
Warning("Missing Level key in SentryGun block.\n");
fail = true;
}
if (fail) return;
DevMsg("Wave %08x: add SentryGun\n", (uintptr_t)wave);
waves[wave].sentryguns.push_back(info);
}
void Parse_HalloweenBoss(CWave *wave, KeyValues *kv)
{
BossInfo info;
FOR_EACH_SUBKEY(kv, subkey) {
const char *name = subkey->GetName();
if (FStrEq(name, "BossType")) {
if (FStrEq(subkey->GetString(), "HHH")) {
info.type = CHalloweenBaseBoss::HEADLESS_HATMAN;
} else if (FStrEq(subkey->GetString(), "MONOCULUS")) {
info.type = CHalloweenBaseBoss::EYEBALL_BOSS;
} else if (FStrEq(subkey->GetString(), "Merasmus")) {
info.type = CHalloweenBaseBoss::MERASMUS;
} else {
Warning("Invalid value \'%s\' for BossType key in HalloweenBoss block.\n", subkey->GetString());
}
// DevMsg("BossType \"%s\" --> %d\n", subkey->GetString(), info.type);
} else if (FStrEq(name, "TeamNum")) {
info.teamnum = subkey->GetInt();
// DevMsg("TeamNum \"%s\" --> %d\n", subkey->GetString(), info.teamnum);
} else if (FStrEq(name, "Health")) {
info.health = Max(1, subkey->GetInt());
// DevMsg("Health \"%s\" --> %d\n", subkey->GetString(), info.health);
} else if (FStrEq(name, "Delay")) {
info.delay = Max(0.0f, subkey->GetFloat());
// DevMsg("Delay \"%s\" --> %.1f\n", subkey->GetString(), info.delay);
} else if (FStrEq(name, "Lifetime")) {
info.lifetime = Max(0.0f, subkey->GetFloat());
// DevMsg("Delay \"%s\" --> %.1f\n", subkey->GetString(), info.delay);
} else if (FStrEq(name, "Position")) {
FOR_EACH_SUBKEY(subkey, subsub) {
const char *name = subsub->GetName();
float value = subsub->GetFloat();
if (FStrEq(name, "X")) {
info.origin.x = value;
} else if (FStrEq(name, "Y")) {
info.origin.y = value;
} else if (FStrEq(name, "Z")) {
info.origin.z = value;
} else {
Warning("Unknown key \'%s\' in HalloweenBoss Position sub-block.\n", name);
}
}
} else {
Warning("Unknown key \'%s\' in HalloweenBoss block.\n", name);
}
}
bool fail = false;
if (info.type == CHalloweenBaseBoss::INVALID) {
Warning("Missing BossType key in HalloweenBoss block.\n");
fail = true;
}
if (info.teamnum != TF_TEAM_HALLOWEEN_BOSS) {
if (info.type == CHalloweenBaseBoss::EYEBALL_BOSS) {
if (info.teamnum != TF_TEAM_RED && info.teamnum != TF_TEAM_BLUE) {
Warning("Invalid value for TeamNum key in HalloweenBoss block: MONOCULUS must be team 5 or 2 or 3.\n");
fail = true;
}
} else {
Warning("Invalid value for TeamNum key in HalloweenBoss block: HHH and Merasmus must be team 5.\n");
fail = true;
}
}
if (fail) return;
DevMsg("Wave %08x: add HalloweenBoss\n", (uintptr_t)wave);
waves[wave].bosses.push_back(info);
}
void Parse_SoundLoop(CWave *wave, KeyValues *kv)
{
if (!waves[wave].sound_loops.empty()) {
Warning("Multiple \'SoundLoop\' blocks found in the same Wave!\n");
return;
}
FOR_EACH_SUBKEY(kv, subkey) {
const char *name = subkey->GetName();
if (FStrEq(name, "SoundFile")) {
waves[wave].sound_loops[subkey->GetString()]=0;
} else {
waves[wave].sound_loops[name]=subkey->GetFloat();
}
}
}
void Parse_PlayerAttributes(CWave *wave, KeyValues *kv)
{
FOR_EACH_SUBKEY(kv, subkey) {
int classname = 0;
for(int i=1; i < 11; i++){
if(FStrEq(g_aRawPlayerClassNames[i],subkey->GetName())){
classname=i;
break;
}
}
if (classname == 0) {
if (GetItemSchema()->GetAttributeDefinitionByName(subkey->GetName()) != nullptr) {
waves[wave].player_attributes[subkey->GetName()] = subkey->GetFloat();
DevMsg("Parsed attribute %s %f\n", subkey->GetName(),subkey->GetFloat());
}
}
else {
waves[wave].defined_class_attributes = true;
FOR_EACH_SUBKEY(subkey, subkey2) {
if (GetItemSchema()->GetAttributeDefinitionByName(subkey2->GetName()) != nullptr) {
waves[wave].player_attributes_class[classname][subkey2->GetName()] = subkey2->GetFloat();
DevMsg("Parsed attribute %s %f\n", subkey2->GetName(),subkey2->GetFloat());
}
}
}
}
DevMsg("Parsed attributes\n");
}
void Parse_PlayerAddCond(CWave *wave, KeyValues *kv)
{
FOR_EACH_SUBKEY(kv, subkey) {
int classname = 0;
for(int i=1; i < 11; i++){
if(FStrEq(g_aRawPlayerClassNames[i],subkey->GetName())){
classname=i;
break;
}
}
if (classname == 0) {
const char *name = subkey->GetName();
ETFCond cond = (ETFCond)-1;
if (FStrEq(name, "Index"))
cond = (ETFCond)subkey->GetInt();
else if (FStrEq(name, "Name"))
cond = GetTFConditionFromName(subkey->GetString());
if (cond == -1)
Warning("Unrecognized condition name \"%s\" in AddCond block.\n", subkey->GetString());
else
waves[wave].addconds.push_back(cond);
}
else {
waves[wave].defined_class_attributes = true;
FOR_EACH_SUBKEY(subkey, subkey2) {
const char *name = subkey2->GetName();
ETFCond cond = (ETFCond)-1;
if (FStrEq(name, "Index"))
cond = (ETFCond)subkey2->GetInt();
else if (FStrEq(name, "Name"))
cond = GetTFConditionFromName(subkey2->GetString());
if (cond == -1)
Warning("Unrecognized condition name \"%s\" in AddCond block.\n", subkey2->GetString());
else
waves[wave].addconds_class[classname].push_back(cond);
}
}
}
DevMsg("Parsed addcond\n");
}
DETOUR_DECL_MEMBER(bool, CPopulationManager_Parse)
{
waves_vec.clear();
return DETOUR_MEMBER_CALL(CPopulationManager_Parse)();
}
DETOUR_DECL_MEMBER(bool, CWave_Parse, KeyValues *kv)
{
auto wave = reinterpret_cast<CWave *>(this);
// DevMsg("CWave::Parse\n");
waves_vec.push_back(wave);
std::vector<KeyValues *> del_kv;
FOR_EACH_SUBKEY(kv, subkey) {
const char *name = subkey->GetName();
bool del = true;
if (FStrEq(name, "Explanation")) {
Parse_Explanation(wave, subkey);
} else if (FStrEq(name, "SentryGun")) {
Parse_SentryGun(wave, subkey);
} else if (FStrEq(name, "HalloweenBoss")) {
Parse_HalloweenBoss(wave, subkey);
} else if (FStrEq(name, "SoundLoop")) {
Parse_SoundLoop(wave, subkey);
} else if (FStrEq(name, "PlayerAttributes")) {
Parse_PlayerAttributes(wave, subkey);
} else if (FStrEq(name, "ItemAttributes")) {
Parse_ItemAttributes(subkey, waves[wave].item_attributes);
} else if (FStrEq(name, "ForceItem")) {
Parse_ForceItem(subkey, waves[wave].force_items, false);
} else if (FStrEq(name, "ForceItemNoRemove")) {
Parse_ForceItem(subkey, waves[wave].force_items, true);
} else if (FStrEq(name, "RedTeamWipeCausesWaveLoss")) {
waves[wave].red_team_wipe_causes_wave_loss = subkey->GetBool();
} else if (FStrEq(name, "BlueTeamWipeCausesWaveLoss")) {
waves[wave].blue_team_wipe_causes_wave_loss = subkey->GetBool();
} else if (FStrEq(name, "FinishingWaveCausesWaveLoss")) {
waves[wave].finishing_wave_causes_wave_loss = subkey->GetBool();
} else if (FStrEq(name, "FinishingWaveAndPlayerWipeCausesWaveLoss")) {
waves[wave].finishing_wave_and_player_wipe_causes_wave_loss = subkey->GetBool();
} else if (FStrEq(name, "CustomWaveNumber")) {
waves[wave].custom_wave_number = subkey->GetInt();
} else if (FStrEq(name, "CustomMaxWaveNumber")) {
waves[wave].custom_max_wave_number = subkey->GetInt();
} else if (FStrEq(name, "SpawnTemplate")) {
PointTemplateInfo info =Parse_SpawnTemplate(subkey);
if (info.templ != nullptr)
waves[wave].templ.push_back(info);
} else if (FStrEq(name, "PlayerAddCond")) {
Parse_PlayerAddCond(wave, subkey);
} else {
del = false;
}
if (del) {
// DevMsg("Key \"%s\": processed, will delete\n", name);
del_kv.push_back(subkey);
} else {
// DevMsg("Key \"%s\": passthru\n", name);
}
}
for (auto subkey : del_kv) {
// DevMsg("Deleting key \"%s\"\n", subkey->GetName());
kv->RemoveSubKey(subkey);
subkey->deleteThis();
}
auto ret = DETOUR_MEMBER_CALL(CWave_Parse)(kv);
int waveSpawnCount = wave->m_WaveSpawns.Count();
for (int i = 0; i < waveSpawnCount; i++) {
auto wavespawn = wave->m_WaveSpawns[i];
if (wavespawn == nullptr) continue;
wavespawn->extra = new CWaveSpawnExtra();
if (!wavespawn->m_waitForAllSpawned.IsEmpty()) {
char *name = wavespawn->m_waitForAllSpawned.GetForModify();
for (int j = 0; j < waveSpawnCount; j++) {
auto wavespawnwait = wave->m_WaveSpawns[j];
if (wavespawnwait && !Q_stricmp(wavespawnwait->m_name.Get(), name)) {
wavespawn->extra->m_waitForAllSpawnedList.AddToHead(wavespawnwait);
}
}
wavespawn->m_waitForAllSpawned = "";
}
if (!wavespawn->m_waitForAllDead.IsEmpty()) {
char *name = wavespawn->m_waitForAllDead.GetForModify();
for (int j = 0; j < waveSpawnCount; j++) {
auto wavespawnwait = wave->m_WaveSpawns[j];
if (wavespawnwait && !Q_stricmp(wavespawnwait->m_name.Get(), name)) {
wavespawn->extra->m_waitForAllDeadList.AddToHead(wavespawnwait);
}
}
wavespawn->m_waitForAllDead = "";
}
}
return ret;
}
std::vector<std::string> *GetWaveExplanation(int wave)
{
if (waves_vec.empty())
return nullptr;
WaveData *data = GetWaveData(waves_vec[wave]);
if (data != nullptr) {
return &data->explanation;
}
return nullptr;
}
ConVar sig_text_print_speed("sig_text_print_speed", "4");
void ParseColorsAndPrint(const char *line, float gameTextDelay, int &linenum, CTFPlayer* player = nullptr)
{
std::vector<char> output;
std::vector<char> output_nocolor;
int color = 0xFFFFFF;
char num[7];
int colorcode_idx=0;
bool hasText = false;
/* always start with reset so that colors will work properly */
output.push_back('\x01');
bool in_braces = false;
int brace_idx = 0;
int i = 0;
char c;
while ((c = line[i]) != '\0') {
hasText |= isalnum(c);
if (in_braces) {
if (c == '}') {
const char *brace_str = line + brace_idx;
int brace_len = i - brace_idx;
if (V_strnicmp(brace_str, "Reset", brace_len) == 0) {
output.push_back('\x01');
} else if (V_strnicmp(brace_str, "Blue", brace_len) == 0) {
output.insert(output.end(), {'\x07', '9', '9', 'c', 'c', 'f', 'f'});
color = 0x99ccff;
} else if (V_strnicmp(brace_str, "Red", brace_len) == 0) {
output.insert(output.end(), {'\x07', 'f', 'f', '3', 'f', '3', 'f'});
color = 0xff3f3f;
} else if (V_strnicmp(brace_str, "Green", brace_len) == 0) {
output.insert(output.end(), {'\x07', '9', '9', 'f', 'f', '9', '9'});
color = 0x99ff99;
} else if (V_strnicmp(brace_str, "DarkGreen", brace_len) == 0) {
output.insert(output.end(), {'\x07', '4', '0', 'f', 'f', '4', '0'});
color = 0x40ff40;
} else if (V_strnicmp(brace_str, "Yellow", brace_len) == 0) {
output.insert(output.end(), {'\x07', 'f', 'f', 'b', '2', '0', '0'});
color = 0xffb200;
} else if (V_strnicmp(brace_str, "Grey", brace_len) == 0) {
output.insert(output.end(), {'\x07', 'c', 'c', 'c', 'c', 'c', 'c'});
color = 0xcccccc;
} else {
/* RGB hex code */
if (brace_len >= 6) {
output.push_back('\x07');
output.push_back(brace_str[0]);
output.push_back(brace_str[1]);
output.push_back(brace_str[2]);
output.push_back(brace_str[3]);
output.push_back(brace_str[4]);
output.push_back(brace_str[5]);
memcpy(num, brace_str,6);
color = strtol(num, nullptr, 16);
}
}
in_braces = false;
}
} else {
if (c == '{') {
in_braces = true;
brace_idx = i + 1;
} else {
output.push_back(c);
if (c == '\x07')
colorcode_idx = i+1;
if (colorcode_idx != 0) {
if (i >= colorcode_idx) {
if (i - colorcode_idx < 6) {
num[i - colorcode_idx] = c;
}
else {
color = strtol(num, nullptr, 16);
colorcode_idx = 0;
}
}
}
else
output_nocolor.push_back(c);
}
}
++i;
}
/* append an extra space at the end to make empty lines show up */
output.push_back(' ');
output.push_back('\n');
output.push_back('\0');
output_nocolor.push_back('\0');
if (hasText && sig_text_print_speed.GetFloat() > 0.0f) {
// The first line is always drawn before others so it makes sense to only then create a new game_text entity if its missing
if (linenum == 0 && servertools->FindEntityByName(nullptr, "wave_explanation_text") == nullptr) {
CBaseEntity *textent = CreateEntityByName("game_text");
servertools->SetKeyValue(textent, "targetname", "wave_explanation_text");
servertools->SetKeyValue(textent, "channel", "0");
servertools->SetKeyValue(textent, "effect", "2");
servertools->SetKeyValue(textent, "fadeout", "0.5");
servertools->SetKeyValue(textent, "fxtime", "0.5");
servertools->SetKeyValue(textent, "holdtime", "2.5");
servertools->SetKeyValue(textent, "x", "-1");
servertools->SetKeyValue(textent, "y", "0.25");
servertools->SetKeyValue(textent, "spawnflags", "0");
textent->Spawn();
textent->Activate();
}
//textent->AcceptInput("Display",player,player,variant,-1);
CEventQueue &que = g_EventQueue;
variant_t variant;
//servertools->SetKeyValue(textent, "color", CFmtStr("%d %d %d", ((color >> 16) & 255), ((color >> 8) & 255), (color & 255)));
//servertools->SetKeyValue(textent, "color2", CFmtStr("%d %d %d", ((color >> 16) & 255), ((color >> 8) & 255), (color & 255)));
bool hasPlayer = player != nullptr;
float delay = gameTextDelay + linenum * sig_text_print_speed.GetFloat() + (hasPlayer ? 0.5f : 0.0f);
variant.SetString(AllocPooledString(CFmtStr("color %d %d %d", ((color >> 16) & 255), ((color >> 8) & 255), (color & 255))));
que.AddEvent("wave_explanation_text","addoutput",variant,delay, player,player,-1);
variant.SetString(AllocPooledString(CFmtStr("color2 %d %d %d", ((color >> 16) & 255), ((color >> 8) & 255), (color & 255))));
que.AddEvent("wave_explanation_text","addoutput",variant,delay, player,player,-1);
variant.SetString(AllocPooledString(CFmtStr("message %s", output_nocolor.data())));
que.AddEvent("wave_explanation_text","addoutput",variant,delay, player,player,-1);
variant.SetString(AllocPooledString(CFmtStr("fadein %f", 1.0f/output_nocolor.size() * sig_text_print_speed.GetFloat() * 0.25f)));
que.AddEvent("wave_explanation_text","addoutput",variant,delay, player,player,-1);
variant.SetString(AllocPooledString(CFmtStr("holdtime %f", 0.75f * sig_text_print_speed.GetFloat() - 0.5f )));
que.AddEvent("wave_explanation_text","addoutput",variant,delay, player,player,-1);
if (!hasPlayer)
for (int i = 1; i <= gpGlobals->maxClients; ++i) {
CBasePlayer *baseplayer = UTIL_PlayerByIndex(i);
que.AddEvent("wave_explanation_text","display",variant,delay + 0.01f, baseplayer,baseplayer,-1);
}
que.AddEvent("wave_explanation_text","display",variant,delay + 0.01f, player,player,-1);
linenum++;
}
if (!player)
PrintToChatAll(output.data());
else
PrintToChat(output.data(), player);
}
float last_explanation_time = 0.0f;
std::set<CHandle<CTFPlayer>> saw_explanation;
void ShowWaveExplanation(bool success, CTFPlayer *player = nullptr)
{
CWave *wave = g_pPopulationManager->GetCurrentWave();
if (wave == nullptr) return;
if (player == nullptr) {
if (gpGlobals->curtime - last_explanation_time < 0.5f )
return;
else
last_explanation_time = gpGlobals->curtime;
saw_explanation.clear();
ForEachTFPlayer([&](CTFPlayer *playerl){
if (!playerl->IsFakeClient()) {
saw_explanation.insert(playerl);
}
});
}
/* wave will be null after game is won and in other corner cases */
if (player != nullptr && saw_explanation.find(player) != saw_explanation.end()) return;
if (player != nullptr) {
saw_explanation.insert(player);
}
auto data = GetWaveData(wave);
if (data == nullptr) return;
const auto& explanation = data->explanation;
if (explanation.size() > 0) {
int linenum = 0;
for (const auto& line : explanation) {
ParseColorsAndPrint(line.c_str(), success ? 15.0f : 1.0f, linenum, player);
}
}
}
THINK_FUNC_DECL(DelayExplaination)
{
ShowWaveExplanation(false, reinterpret_cast<CTFPlayer *>(this));
}
THINK_FUNC_DECL(DelayExplainationAll)
{
ShowWaveExplanation(false);
}
THINK_FUNC_DECL(DelayExplainationAllSuccess)
{
ShowWaveExplanation(true);
}
DETOUR_DECL_MEMBER(void, CTFPlayer_HandleCommand_JoinClass, const char *pClassName, bool b1)
{
auto player = reinterpret_cast<CTFPlayer *>(this);
bool show_wave_expl = !player->IsBot() && player->GetPlayerClass()->GetClassIndex() == TF_CLASS_UNDEFINED;
DETOUR_MEMBER_CALL(CTFPlayer_HandleCommand_JoinClass)(pClassName, b1);
if (show_wave_expl && TFGameRules()->IsMannVsMachineMode())
THINK_FUNC_SET(player, DelayExplaination, gpGlobals->curtime + 2.0f);
}
void OnWaveBegin(bool success) {
if (success) {
THINK_FUNC_SET(g_pPopulationManager, DelayExplainationAllSuccess, gpGlobals->curtime + 2.0f);
}
else {
THINK_FUNC_SET(g_pPopulationManager, DelayExplainationAll, gpGlobals->curtime + 2.0f);
}
auto data = GetCurrentWaveData();
if (data != nullptr && !data->t_waveinit.HasStarted()) {
data->t_waveinit.Start();
}
if (data != nullptr) {
ForEachTFPlayer([&](CTFPlayer *player) {
if (player->IsBot()) return;
ForEachTFPlayerEconEntity(player, [&](CEconEntity *entity) {
CEconItemView *item_view = entity->GetItem();
if (item_view == nullptr) return;
ApplyItemAttributes(item_view, player, data->item_attributes);
});
ApplyForceItems(data->force_items, player, true, false);
});
}
// Remove old force items
/*ForEachTFPlayer([&](CTFPlayer *player) {
if (player->IsBot() || !player->IsAlive())
return;
player->
}*/
}
int rc_JumpToWave = 0;
DETOUR_DECL_MEMBER(void, CPopulationManager_JumpToWave, unsigned int wave, float f1)
{
DevMsg("[%8.3f] JumpToWave\n", gpGlobals->curtime);
rc_JumpToWave++;
DETOUR_MEMBER_CALL(CPopulationManager_JumpToWave)(wave, f1);
rc_JumpToWave--;
OnWaveBegin(false);
}
DETOUR_DECL_MEMBER(void, CPopulationManager_WaveEnd, bool b1)
{
//DevMsg("[%8.3f] WaveEnd\n", gpGlobals->curtime);
CWave *wave = g_pPopulationManager->GetCurrentWave();
if (wave != nullptr)
WaveCleanup(wave);
DETOUR_MEMBER_CALL(CPopulationManager_WaveEnd)(b1);
OnWaveBegin(true);
}
DETOUR_DECL_MEMBER(void, CMannVsMachineStats_RoundEvent_WaveEnd, bool success)
{
DETOUR_MEMBER_CALL(CMannVsMachineStats_RoundEvent_WaveEnd)(success);
if (!success && rc_JumpToWave == 0) {
//DevMsg("[%8.3f] RoundEvent_WaveEnd\n", gpGlobals->curtime);
OnWaveBegin(false);
}
}
CObjectSentrygun *SpawnSentryGun(const Vector& origin, const QAngle& angles, int teamnum, int level, bool is_mini, int health, int skin, int bodygroup)
{
auto sentry = rtti_cast<CObjectSentrygun *>(CreateEntityByName("obj_sentrygun"));
if (sentry == nullptr) {
Warning("SpawnSentryGun: CreateEntityByName(\"obj_sentrygun\") failed\n");
return nullptr;
}
// DevMsg("[%8.3f] SpawnSentryGun: [hint #%d \"%s\"] [teamnum %d] [level %d]\n",
// gpGlobals->curtime, ENTINDEX(sg_info.hint), STRING(sg_info.hint->GetEntityName()), sg_info.teamnum, sg_info.level);
sentry->SetAbsOrigin(origin);
sentry->SetAbsAngles(angles);
sentry->Spawn();
sentry->ChangeTeam(teamnum);
sentry->m_nDefaultUpgradeLevel = level - 1;
if (is_mini) {
sentry->SetModelScale(0.75f);
sentry->m_bMiniBuilding = true;
sentry->m_nSkin += 2;
}
sentry->InitializeMapPlacedObject();
sentry->m_nBody = bodygroup;
sentry->m_nSkin = skin;
if (health != -1) {
sentry->SetMaxHealth(health);
sentry->SetHealth((float)health);
}
DevMsg("SpawnSentryGun: #%d, %08x, level %d, health %d, maxhealth %d\n",
ENTINDEX(sentry), (uintptr_t)sentry, level, sentry->GetHealth(), sentry->GetMaxHealth());
return sentry;
}
void SpawnSentryGuns(SentryGunInfo& info)
{
info.spawned = true;
if (info.use_hint && info.hints.empty()) {
Warning("SpawnSentryGuns: info.hints.empty()\n");
return;
}
if (info.use_hint) {
for (const auto& hint : info.hints) {
info.sentry = SpawnSentryGun(hint->GetAbsOrigin(), hint->GetAbsAngles(), info.teamnum, info.level, info.is_mini, info.health, info.skin, info.bodygroup);
}
} else {
info.sentry = SpawnSentryGun(info.origin, info.angles, info.teamnum, info.level, info.is_mini, info.health, info.skin, info.bodygroup);
}
}
void SpawnBoss(BossInfo& info)
{
info.spawned = true;
static ConVarRef tf_merasmus_lifetime("tf_merasmus_lifetime");
static ConVarRef tf_eyeball_boss_lifetime("tf_eyeball_boss_lifetime");
float tf_merasmus_lifetime_old = tf_merasmus_lifetime.GetFloat();
float tf_eyeball_boss_lifetime_old = tf_eyeball_boss_lifetime.GetFloat();
tf_merasmus_lifetime.SetValue(info.lifetime);
tf_eyeball_boss_lifetime.SetValue(info.lifetime);
DevMsg("lifetime %f\n", tf_merasmus_lifetime.GetFloat());
CHalloweenBaseBoss *boss = CHalloweenBaseBoss::SpawnBossAtPos(info.type, info.origin, info.teamnum, nullptr);
if (boss == nullptr) {
Warning("SpawnBoss: CHalloweenBaseBoss::SpawnBossAtPos(type %d, teamnum %d) failed\n", info.type, info.teamnum);
return;
}
tf_merasmus_lifetime.SetValue(tf_merasmus_lifetime_old);
tf_eyeball_boss_lifetime.SetValue(tf_eyeball_boss_lifetime_old);
if (info.health > 0) {
boss->SetMaxHealth(info.health);
boss->SetHealth (info.health);
}
info.boss = boss;
}
std::string soundloop_active;
void StopSoundLoop()
{
ConColorMsg(Color(0xff, 0x00, 0x00, 0xff), "[SoundLoop] StopSoundLoop \"%s\"\n", soundloop_active.c_str());
if (TFGameRules() != nullptr) {
TFGameRules()->BroadcastSound(SOUND_FROM_LOCAL_PLAYER, soundloop_active.c_str(), SND_STOP);
}
soundloop_active.clear();
}
void StartSoundLoop(const std::string& filename)
{
if (!soundloop_active.empty()) {
StopSoundLoop();
}
ConColorMsg(Color(0x00, 0xff, 0x00, 0xff), "[SoundLoop] StartSoundLoop \"%s\"\n", filename.c_str());
/* if filename is explicitly "", then don't play anything */
if (TFGameRules() != nullptr && filename != "") {
TFGameRules()->BroadcastSound(SOUND_FROM_LOCAL_PLAYER, filename.c_str(), SND_NOFLAGS);
soundloop_active = filename;
}
}
void SelectLoopSound(WaveData &data) {
if (!data.sound_loops.empty()) {
auto sound_loop = select_random(data.sound_loops.begin(),data.sound_loops.end());
StartSoundLoop(sound_loop->first);
if (sound_loop->second > 0.0f)
data.sound_time_end = data.t_wavestart.GetElapsedTime() + sound_loop->second;
else
data.sound_time_end = data.t_wavestart.GetElapsedTime() + 99999;
}
}
DETOUR_DECL_MEMBER(void, CWave_ActiveWaveUpdate)
{
auto wave = reinterpret_cast<CWave *>(this);
auto it = waves.find(wave);
if (it == waves.end()) {
DETOUR_MEMBER_CALL(CWave_ActiveWaveUpdate)();
return;
}
WaveData& data = (*it).second;
if (!data.t_wavestart.HasStarted()) {
data.t_wavestart.Start();
}
/* since we are pre-detour and ActiveWaveUpdate only happens in RND_RUNNING, we are safe to skip the check */
if (data.red_team_wipe_causes_wave_loss/* && TFGameRules()->State_Get() == GR_STATE_RND_RUNNING*/) {
CTFTeam *team_red = TFTeamMgr()->GetTeam(TF_TEAM_RED);
if (team_red != nullptr && team_red->GetNumPlayers() != 0) {
int num_red_humans = 0;
int num_red_humans_alive = 0;
ForEachTFPlayerOnTeam(TFTeamMgr()->GetTeam(TF_TEAM_RED), [&](CTFPlayer *player){
if (player->IsBot()) return;
++num_red_humans;
if (player->IsAlive()) {
++num_red_humans_alive;
}
});
/* if red team actually contains zero humans, then don't do anything */
if (num_red_humans > 0 && num_red_humans_alive == 0) {
/* not entirely sure what effect the win reason parameter has (if it even has an effect at all) */
TFGameRules()->SetWinningTeam(TF_TEAM_BLUE, WINREASON_OPPONENTS_DEAD, true, false);
}
}
}
if (data.blue_team_wipe_causes_wave_loss/* && TFGameRules()->State_Get() == GR_STATE_RND_RUNNING*/) {
CTFTeam *team_blue = TFTeamMgr()->GetTeam(TF_TEAM_BLUE);
if (team_blue != nullptr && team_blue->GetNumPlayers() != 0) {
int num_blue_humans = 0;
int num_blue_humans_alive = 0;
ForEachTFPlayerOnTeam(TFTeamMgr()->GetTeam(TF_TEAM_BLUE), [&](CTFPlayer *player){
if (player->IsBot()) return;
++num_blue_humans;
if (player->IsAlive()) {
++num_blue_humans_alive;
}
});
/* if red team actually contains zero humans, then don't do anything */
if (num_blue_humans > 0 && num_blue_humans_alive == 0) {
/* not entirely sure what effect the win reason parameter has (if it even has an effect at all) */
TFGameRules()->SetWinningTeam(TF_TEAM_RED, WINREASON_OPPONENTS_DEAD, true, false);
}
}
}
if (data.defined_class_attributes || data.player_attributes.size() > 0 || data.addconds.size() > 0)
ForEachTFPlayer([&](CTFPlayer *player){
if (player->IsBot()) return;
if (!player->IsAlive()) return;
for(auto it = data.player_attributes.begin(); it != data.player_attributes.end(); ++it){
player->AddCustomAttribute(it->first.c_str(),it->second, 1.0f);
}
int classname = player->GetPlayerClass()->GetClassIndex();
for(auto it = data.player_attributes_class[classname].begin(); it != data.player_attributes_class[classname].end(); ++it){
player->AddCustomAttribute(it->first.c_str(),it->second, 7200.0f);
}
for(auto cond : data.addconds){
if (!player->m_Shared->InCond(cond)){
player->m_Shared->AddCond(cond,-1.0f);
}
}
for(auto cond : data.addconds_class[classname]){
if (!player->m_Shared->InCond(cond)){
player->m_Shared->AddCond(cond,-1.0f);
}
}
});
// ^^^^ PRE-DETOUR ===================================================
DETOUR_MEMBER_CALL(CWave_ActiveWaveUpdate)();
// vvvv POST-DETOUR ===================================================
for (auto& info : data.sentryguns) {
if (!info.spawned && !data.t_wavestart.IsLessThen(info.delay)) {
SpawnSentryGuns(info);
}
}
for (auto& info : data.bosses) {
if (!info.spawned && !data.t_wavestart.IsLessThen(info.delay)) {
SpawnBoss(info);
}
}
for (auto it1 = data.templ.begin(); it1 != data.templ.end(); ++it1) {
if(!data.t_wavestart.IsLessThen(it1->delay)){
auto templ_inst = it1->SpawnTemplate(nullptr);
if (templ_inst != nullptr) {
templ_inst->is_wave_spawned = true;
data.templ_inst.push_back(templ_inst);
}
data.templ.erase(it1);
it1--;
}
}
if (!data.t_wavestart.IsLessThen(data.sound_time_end)) {
SelectLoopSound(data);
}
}
DETOUR_DECL_MEMBER(bool, CWave_IsDoneWithNonSupportWaves)
{
bool done = DETOUR_MEMBER_CALL(CWave_IsDoneWithNonSupportWaves)();
auto wave = reinterpret_cast<CWave *>(this);
auto it = waves.find(wave);
if (it != waves.end()) {
WaveData& data = (*it).second;
for (auto& info : data.bosses) {
if (info.spawned && info.boss != nullptr && info.boss->IsAlive()) {
return false;
}
}
if (done && (data.finishing_wave_causes_wave_loss || data.finishing_wave_and_player_wipe_causes_wave_loss)) {
if (!data.finishing_wave_causes_wave_loss) {
int playercount = 0;
int aliveplayercount = 0;
ForEachTFPlayer([&](CTFPlayer *playerl){
if (!playerl->IsFakeClient() && playerl->GetTeamNumber() > 1) {
playercount +=1;
if (playerl->IsAlive())
aliveplayercount +=1;
}
});
if (playercount > 0 && aliveplayercount == 0) {
TFGameRules()->SetWinningTeam(TF_TEAM_RED, WINREASON_OPPONENTS_DEAD, true, false);
done = false;
}
}
else{
TFGameRules()->SetWinningTeam(TF_TEAM_RED, WINREASON_OPPONENTS_DEAD, true, false);
done = false;
}
}
}
return done;
}
CWave *last_wave;
DETOUR_DECL_MEMBER(void, CTeamplayRoundBasedRules_State_Enter, gamerules_roundstate_t newState)
{
auto oldState = TeamplayRoundBasedRules()->State_Get();
ConColorMsg(Color(0xff, 0x00, 0xff, 0xff),
"[SoundLoop] CTeamplayRoundBasedRules: %s -> %s\n",
GetRoundStateName(oldState), GetRoundStateName(newState));
if (oldState != GR_STATE_RND_RUNNING && newState == GR_STATE_RND_RUNNING) {
if (TFGameRules()->IsMannVsMachineMode()) {
last_wave = g_pPopulationManager->GetCurrentWave();
WaveData *data = GetWaveData(last_wave);
if (data != nullptr)
SelectLoopSound(*data);
}
} else if (oldState == GR_STATE_RND_RUNNING && newState != GR_STATE_RND_RUNNING) {
if (last_wave != nullptr) {
WaveData *data = GetWaveData(last_wave);
if (data != nullptr) {
if (data->defined_class_attributes || data->player_attributes.size() > 0 || data->addconds.size() > 0) {
ForEachTFPlayer([&](CTFPlayer *player){
if (player->IsBot()) return;
for(auto it = data->player_attributes.begin(); it != data->player_attributes.end(); ++it){
player->RemoveCustomAttribute(it->first.c_str());
}
int classname = player->GetPlayerClass()->GetClassIndex();
for(auto it = data->player_attributes_class[classname].begin(); it != data->player_attributes_class[classname].end(); ++it){
player->RemoveCustomAttribute(it->first.c_str());
}
for(auto cond : data->addconds){
if (player->m_Shared->InCond(cond)){
player->m_Shared->RemoveCond(cond);
}
}
for(auto cond : data->addconds_class[classname]){
if (player->m_Shared->InCond(cond)){
player->m_Shared->RemoveCond(cond);
}
}
});
}
}
}
StopSoundLoop();
}
DETOUR_MEMBER_CALL(CTeamplayRoundBasedRules_State_Enter)(newState);
}
BossInfo *GetBossInfo(CBaseEntity *entity)
{
WaveData *data = GetCurrentWaveData();
if (data == nullptr) return nullptr;
for (auto &bossinfo : data->bosses) {
if (bossinfo.boss == entity)
return &bossinfo;
}
return nullptr;
}
/* block attempts by MONOCULUS to switch to CEyeballBossTeleport */
DETOUR_DECL_MEMBER(ActionResult<CEyeballBoss>, CEyeballBossIdle_Update, CEyeballBoss *actor, float dt)
{
auto result = DETOUR_MEMBER_CALL(CEyeballBossIdle_Update)(actor, dt);
if (result.transition == ActionTransition::CHANGE_TO && strcmp(result.reason, "Moving...") == 0) {
if (TFGameRules()->IsMannVsMachineMode() && GetBossInfo(actor) != nullptr) {
delete result.action;
result.transition = ActionTransition::CONTINUE;
result.action = nullptr;
result.reason = nullptr;
}
}
return result;
}
RefCount rc_CEyeballBossDead_Update__and_is_from_spawner;
DETOUR_DECL_MEMBER(ActionResult<CEyeballBoss>, CEyeballBossDead_Update, CEyeballBoss *actor, float dt)
{
SCOPED_INCREMENT_IF(rc_CEyeballBossDead_Update__and_is_from_spawner,
(TFGameRules()->IsMannVsMachineMode() && GetBossInfo(actor) != nullptr));
return DETOUR_MEMBER_CALL(CEyeballBossDead_Update)(actor, dt);
}
/* prevent MONOCULUS's death from spawning a teleport vortex */
DETOUR_DECL_STATIC(CBaseEntity *, CBaseEntity_Create, const char *szName, const Vector& vecOrigin, const QAngle& vecAngles, CBaseEntity *pOwner)
{
if (rc_CEyeballBossDead_Update__and_is_from_spawner > 0 && strcmp(szName, "teleport_vortex") == 0) {
return nullptr;
}
return DETOUR_STATIC_CALL(CBaseEntity_Create)(szName, vecOrigin, vecAngles, pOwner);
}
/* set MONOCULUS's lifetime from the spawner parameter instead of from the global convars */
DETOUR_DECL_MEMBER(ActionResult<CEyeballBoss>, CEyeballBossIdle_OnStart, CEyeballBoss *actor, Action<CEyeballBoss> *action)
{
auto me = reinterpret_cast<CEyeballBossIdle *>(this);
auto result = DETOUR_MEMBER_CALL(CEyeballBossIdle_OnStart)(actor, action);
if (TFGameRules()->IsMannVsMachineMode()) {
auto *info = GetBossInfo(actor);
if (info != nullptr) {
me->m_ctLifetime.Start(info->lifetime);
}
}
return result;
}
DETOUR_DECL_MEMBER(void, CUpgrades_GrantOrRemoveAllUpgrades, CTFPlayer * player, bool remove, bool refund)
{
DETOUR_MEMBER_CALL(CUpgrades_GrantOrRemoveAllUpgrades)(player, remove, refund);
WaveData *data = GetCurrentWaveData();
if (data == nullptr) return;
if (remove && !data->item_attributes.empty()) {
ForEachTFPlayerEconEntity(player, [&](CEconEntity *entity) {
CEconItemView *item_view = entity->GetItem();
if (item_view == nullptr) return;
ApplyItemAttributes(item_view, player, data->item_attributes);
});
}
}
DETOUR_DECL_MEMBER(void, CTFPlayer_ReapplyItemUpgrades, CEconItemView *item_view)
{
auto player = reinterpret_cast<CTFPlayer *>(this);
if (TFGameRules()->IsMannVsMachineMode() && !player->IsBot()) {
WaveData *data = GetCurrentWaveData();
if (data != nullptr) {
if (!data->item_attributes.empty()) {
ApplyItemAttributes(item_view, player, data->item_attributes);
}
}
}
DETOUR_MEMBER_CALL(CTFPlayer_ReapplyItemUpgrades)(item_view);
}
DETOUR_DECL_STATIC(void, SV_ComputeClientPacks, int clientCount, void **clients, void *snapshot)
{
int wave_number = INT_MIN;
int max_wave_number = INT_MIN;
WaveData *data = GetCurrentWaveData();
if (data != nullptr && TFObjectiveResource() != nullptr) {
if (data->custom_wave_number != INT_MIN) {
wave_number = TFObjectiveResource()->m_nMannVsMachineWaveCount;
TFObjectiveResource()->m_nMannVsMachineWaveCount = data->custom_wave_number;
}
if (data->custom_max_wave_number != INT_MIN) {
max_wave_number = TFObjectiveResource()->m_nMannVsMachineMaxWaveCount;
TFObjectiveResource()->m_nMannVsMachineMaxWaveCount = data->custom_max_wave_number;
}
}
DETOUR_STATIC_CALL(SV_ComputeClientPacks)(clientCount, clients, snapshot);
if (wave_number != INT_MIN) {
TFObjectiveResource()->m_nMannVsMachineWaveCount = wave_number;
}
if (max_wave_number != INT_MIN) {
TFObjectiveResource()->m_nMannVsMachineMaxWaveCount = max_wave_number;
}
}
class PlayerLoadoutUpdatedListener : public IBitBufUserMessageListener
{
public:
CTFPlayer *player = nullptr;
virtual void OnUserMessage(int msg_id, bf_write *bf, IRecipientFilter *pFilter)
{
if (pFilter->GetRecipientCount() > 0) {
int id = pFilter->GetRecipientIndex(0);
player = ToTFPlayer(UTIL_PlayerByIndex(id));
}
}
virtual void OnPostUserMessage(int msg_id, bool sent)
{
if (sent && player != nullptr) {
auto data = GetCurrentWaveData();
if (data != nullptr && !player->IsBot())
ApplyForceItems(data->force_items, player, false, false);
}
}
};
class CMod : public IMod, public IModCallbackListener
{
public:
CMod() : IMod("Pop:Wave_Extensions")
{
MOD_ADD_DETOUR_MEMBER(CWave_dtor0, "CWave::~CWave [D0]");
MOD_ADD_DETOUR_MEMBER(CWave_dtor2, "CWave::~CWave [D2]");
MOD_ADD_DETOUR_MEMBER(CPopulationManager_Parse, "CPopulationManager::Parse");
MOD_ADD_DETOUR_MEMBER(CWave_Parse, "CWave::Parse");
MOD_ADD_DETOUR_MEMBER(CPopulationManager_JumpToWave, "CPopulationManager::JumpToWave");
MOD_ADD_DETOUR_MEMBER(CPopulationManager_WaveEnd, "CPopulationManager::WaveEnd");
MOD_ADD_DETOUR_MEMBER(CMannVsMachineStats_RoundEvent_WaveEnd, "CMannVsMachineStats::RoundEvent_WaveEnd");
MOD_ADD_DETOUR_MEMBER(CWave_ActiveWaveUpdate, "CWave::ActiveWaveUpdate");
MOD_ADD_DETOUR_MEMBER(CWave_IsDoneWithNonSupportWaves, "CWave::IsDoneWithNonSupportWaves");
MOD_ADD_DETOUR_MEMBER(CTeamplayRoundBasedRules_State_Enter, "CTeamplayRoundBasedRules::State_Enter");
MOD_ADD_DETOUR_MEMBER(CTFPlayer_HandleCommand_JoinClass, "CTFPlayer::HandleCommand_JoinClass");
MOD_ADD_DETOUR_MEMBER(CEyeballBossIdle_Update, "CEyeballBossIdle::Update");
MOD_ADD_DETOUR_MEMBER(CEyeballBossDead_Update, "CEyeballBossDead::Update");
MOD_ADD_DETOUR_STATIC(CBaseEntity_Create, "CBaseEntity::Create");
MOD_ADD_DETOUR_MEMBER(CEyeballBossIdle_OnStart, "CEyeballBossIdle::OnStart");
MOD_ADD_DETOUR_MEMBER(CUpgrades_GrantOrRemoveAllUpgrades, "CUpgrades::GrantOrRemoveAllUpgrades");
MOD_ADD_DETOUR_MEMBER(CTFPlayer_ReapplyItemUpgrades, "CTFPlayer::ReapplyItemUpgrades");
MOD_ADD_DETOUR_STATIC(SV_ComputeClientPacks, "SV_ComputeClientPacks");
}
virtual void OnUnload() override
{
waves.clear();
StopSoundLoop();
}
virtual void OnEnable() override
{
usermsgs->HookUserMessage2(usermsgs->GetMessageIndex("PlayerLoadoutUpdated"), &player_loadout_updated_listener);
}
virtual void OnDisable() override
{
usermsgs->UnhookUserMessage2(usermsgs->GetMessageIndex("PlayerLoadoutUpdated"), &player_loadout_updated_listener);
waves.clear();
StopSoundLoop();
}
virtual bool ShouldReceiveCallbacks() const override { return this->IsEnabled(); }
virtual void LevelInitPreEntity() override
{
waves.clear();
StopSoundLoop();
last_explanation_time = 0.0f;
}
virtual void LevelShutdownPostEntity() override
{
waves.clear();
StopSoundLoop();
}
/*virtual void FrameUpdatePostEntityThink() override
{
if(g_pPopulationManager != nullptr) {
CWave *wave = g_pPopulationManager->GetCurrentWave();
if (wave != nullptr) {
for (int i = 0; i < 32; i++) {
CBasePlayer *player = UTIL_PlayerByIndex(i);
if (player == nullptr) continue;
if (player->IsBot()) continue;
float &progress = waves[wave].player_explanation_progress[i];
if (progress > 0) {
}
}
}
}
}*/
private:
PlayerLoadoutUpdatedListener player_loadout_updated_listener;
};
CMod s_Mod;
ConVar cvar_enable("sig_pop_wave_extensions", "0", FCVAR_NOTIFY,
"Mod: enable extended KV in CWave::Parse",
[](IConVar *pConVar, const char *pOldValue, float flOldValue){
s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool());
});
class CKVCond_Wave : public IKVCond
{
public:
virtual bool operator()() override
{
return s_Mod.IsEnabled();
}
};
CKVCond_Wave cond;
}
/* wave explanation TODO:
each time a wave starts, reset some tracking info
- keep track of which steam IDs have seen the explanation and which haven't
if a new player connects, and the wave has an explanation, and they haven't seen it,
then show it *just* to them, a few seconds after they pick a class
*/
| 32.038692 | 158 | 0.64159 | [
"vector"
] |
c8ccb90df0b33d7952ebe23ce2770e79baf16e38 | 63,431 | cpp | C++ | handlers/token_collector/xasm/generated/xasm_singleParser.cpp | amirebrahimi/qcor | 1345cc04e7871105e1a251a1714dd9ce19a5f646 | [
"BSD-3-Clause"
] | null | null | null | handlers/token_collector/xasm/generated/xasm_singleParser.cpp | amirebrahimi/qcor | 1345cc04e7871105e1a251a1714dd9ce19a5f646 | [
"BSD-3-Clause"
] | null | null | null | handlers/token_collector/xasm/generated/xasm_singleParser.cpp | amirebrahimi/qcor | 1345cc04e7871105e1a251a1714dd9ce19a5f646 | [
"BSD-3-Clause"
] | 1 | 2021-03-14T09:13:06.000Z | 2021-03-14T09:13:06.000Z |
// Generated from xasm_single.g4 by ANTLR 4.8
#include "xasm_singleListener.h"
#include "xasm_singleVisitor.h"
#include "xasm_singleParser.h"
using namespace antlrcpp;
using namespace xasm;
using namespace antlr4;
xasm_singleParser::xasm_singleParser(TokenStream *input) : Parser(input) {
_interpreter = new atn::ParserATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache);
}
xasm_singleParser::~xasm_singleParser() {
delete _interpreter;
}
std::string xasm_singleParser::getGrammarFileName() const {
return "xasm_single.g4";
}
const std::vector<std::string>& xasm_singleParser::getRuleNames() const {
return _ruleNames;
}
dfa::Vocabulary& xasm_singleParser::getVocabulary() const {
return _vocabulary;
}
//----------------- LineContext ------------------------------------------------------------------
xasm_singleParser::LineContext::LineContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
xasm_singleParser::StatementContext* xasm_singleParser::LineContext::statement() {
return getRuleContext<xasm_singleParser::StatementContext>(0);
}
xasm_singleParser::CommentContext* xasm_singleParser::LineContext::comment() {
return getRuleContext<xasm_singleParser::CommentContext>(0);
}
size_t xasm_singleParser::LineContext::getRuleIndex() const {
return xasm_singleParser::RuleLine;
}
void xasm_singleParser::LineContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterLine(this);
}
void xasm_singleParser::LineContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitLine(this);
}
antlrcpp::Any xasm_singleParser::LineContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitLine(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::LineContext* xasm_singleParser::line() {
LineContext *_localctx = _tracker.createInstance<LineContext>(_ctx, getState());
enterRule(_localctx, 0, xasm_singleParser::RuleLine);
auto onExit = finally([=] {
exitRule();
});
try {
setState(28);
_errHandler->sync(this);
switch (_input->LA(1)) {
case xasm_singleParser::T__0:
case xasm_singleParser::T__3:
case xasm_singleParser::T__7:
case xasm_singleParser::T__9:
case xasm_singleParser::T__10:
case xasm_singleParser::T__11:
case xasm_singleParser::T__15:
case xasm_singleParser::T__16:
case xasm_singleParser::T__17:
case xasm_singleParser::T__26:
case xasm_singleParser::T__34:
case xasm_singleParser::T__37:
case xasm_singleParser::T__38:
case xasm_singleParser::T__39:
case xasm_singleParser::T__40:
case xasm_singleParser::T__41:
case xasm_singleParser::T__42:
case xasm_singleParser::T__43:
case xasm_singleParser::ID:
case xasm_singleParser::REAL:
case xasm_singleParser::INT:
case xasm_singleParser::STRING: {
enterOuterAlt(_localctx, 1);
setState(26);
statement();
break;
}
case xasm_singleParser::COMMENT: {
enterOuterAlt(_localctx, 2);
setState(27);
comment();
break;
}
default:
throw NoViableAltException(this);
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- StatementContext ------------------------------------------------------------------
xasm_singleParser::StatementContext::StatementContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
xasm_singleParser::QinstContext* xasm_singleParser::StatementContext::qinst() {
return getRuleContext<xasm_singleParser::QinstContext>(0);
}
xasm_singleParser::CinstContext* xasm_singleParser::StatementContext::cinst() {
return getRuleContext<xasm_singleParser::CinstContext>(0);
}
size_t xasm_singleParser::StatementContext::getRuleIndex() const {
return xasm_singleParser::RuleStatement;
}
void xasm_singleParser::StatementContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterStatement(this);
}
void xasm_singleParser::StatementContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitStatement(this);
}
antlrcpp::Any xasm_singleParser::StatementContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitStatement(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::StatementContext* xasm_singleParser::statement() {
StatementContext *_localctx = _tracker.createInstance<StatementContext>(_ctx, getState());
enterRule(_localctx, 2, xasm_singleParser::RuleStatement);
auto onExit = finally([=] {
exitRule();
});
try {
setState(32);
_errHandler->sync(this);
switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 1, _ctx)) {
case 1: {
enterOuterAlt(_localctx, 1);
setState(30);
qinst();
break;
}
case 2: {
enterOuterAlt(_localctx, 2);
setState(31);
cinst();
break;
}
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- CommentContext ------------------------------------------------------------------
xasm_singleParser::CommentContext::CommentContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
tree::TerminalNode* xasm_singleParser::CommentContext::COMMENT() {
return getToken(xasm_singleParser::COMMENT, 0);
}
size_t xasm_singleParser::CommentContext::getRuleIndex() const {
return xasm_singleParser::RuleComment;
}
void xasm_singleParser::CommentContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterComment(this);
}
void xasm_singleParser::CommentContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitComment(this);
}
antlrcpp::Any xasm_singleParser::CommentContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitComment(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::CommentContext* xasm_singleParser::comment() {
CommentContext *_localctx = _tracker.createInstance<CommentContext>(_ctx, getState());
enterRule(_localctx, 4, xasm_singleParser::RuleComment);
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(34);
match(xasm_singleParser::COMMENT);
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- QinstContext ------------------------------------------------------------------
xasm_singleParser::QinstContext::QinstContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
xasm_singleParser::ExplistContext* xasm_singleParser::QinstContext::explist() {
return getRuleContext<xasm_singleParser::ExplistContext>(0);
}
xasm_singleParser::IdContext* xasm_singleParser::QinstContext::id() {
return getRuleContext<xasm_singleParser::IdContext>(0);
}
size_t xasm_singleParser::QinstContext::getRuleIndex() const {
return xasm_singleParser::RuleQinst;
}
void xasm_singleParser::QinstContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterQinst(this);
}
void xasm_singleParser::QinstContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitQinst(this);
}
antlrcpp::Any xasm_singleParser::QinstContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitQinst(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::QinstContext* xasm_singleParser::qinst() {
QinstContext *_localctx = _tracker.createInstance<QinstContext>(_ctx, getState());
enterRule(_localctx, 6, xasm_singleParser::RuleQinst);
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(36);
dynamic_cast<QinstContext *>(_localctx)->inst_name = id();
setState(37);
match(xasm_singleParser::T__0);
setState(38);
explist();
setState(39);
match(xasm_singleParser::T__1);
setState(40);
match(xasm_singleParser::T__2);
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- CinstContext ------------------------------------------------------------------
xasm_singleParser::CinstContext::CinstContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
xasm_singleParser::Cpp_typeContext* xasm_singleParser::CinstContext::cpp_type() {
return getRuleContext<xasm_singleParser::Cpp_typeContext>(0);
}
std::vector<xasm_singleParser::ExpContext *> xasm_singleParser::CinstContext::exp() {
return getRuleContexts<xasm_singleParser::ExpContext>();
}
xasm_singleParser::ExpContext* xasm_singleParser::CinstContext::exp(size_t i) {
return getRuleContext<xasm_singleParser::ExpContext>(i);
}
xasm_singleParser::CompareContext* xasm_singleParser::CinstContext::compare() {
return getRuleContext<xasm_singleParser::CompareContext>(0);
}
xasm_singleParser::ExplistContext* xasm_singleParser::CinstContext::explist() {
return getRuleContext<xasm_singleParser::ExplistContext>(0);
}
size_t xasm_singleParser::CinstContext::getRuleIndex() const {
return xasm_singleParser::RuleCinst;
}
void xasm_singleParser::CinstContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterCinst(this);
}
void xasm_singleParser::CinstContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitCinst(this);
}
antlrcpp::Any xasm_singleParser::CinstContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitCinst(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::CinstContext* xasm_singleParser::cinst() {
CinstContext *_localctx = _tracker.createInstance<CinstContext>(_ctx, getState());
enterRule(_localctx, 8, xasm_singleParser::RuleCinst);
size_t _la = 0;
auto onExit = finally([=] {
exitRule();
});
try {
setState(135);
_errHandler->sync(this);
switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 11, _ctx)) {
case 1: {
enterOuterAlt(_localctx, 1);
setState(43);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__3) {
setState(42);
match(xasm_singleParser::T__3);
}
setState(45);
dynamic_cast<CinstContext *>(_localctx)->type_name = cpp_type();
setState(46);
dynamic_cast<CinstContext *>(_localctx)->var_name = exp(0);
setState(49);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__4) {
setState(47);
match(xasm_singleParser::T__4);
setState(48);
dynamic_cast<CinstContext *>(_localctx)->var_value = exp(0);
}
setState(51);
match(xasm_singleParser::T__2);
break;
}
case 2: {
enterOuterAlt(_localctx, 2);
setState(53);
exp(0);
setState(54);
match(xasm_singleParser::T__5);
setState(55);
match(xasm_singleParser::T__2);
break;
}
case 3: {
enterOuterAlt(_localctx, 3);
setState(57);
exp(0);
setState(58);
match(xasm_singleParser::T__6);
setState(59);
match(xasm_singleParser::T__2);
break;
}
case 4: {
enterOuterAlt(_localctx, 4);
setState(61);
match(xasm_singleParser::T__7);
setState(62);
match(xasm_singleParser::T__0);
setState(63);
cpp_type();
setState(64);
exp(0);
setState(65);
match(xasm_singleParser::T__4);
setState(66);
exp(0);
setState(67);
match(xasm_singleParser::T__2);
setState(72);
_errHandler->sync(this);
_la = _input->LA(1);
if ((((_la & ~ 0x3fULL) == 0) &&
((1ULL << _la) & ((1ULL << xasm_singleParser::T__0)
| (1ULL << xasm_singleParser::T__26)
| (1ULL << xasm_singleParser::T__34)
| (1ULL << xasm_singleParser::T__37)
| (1ULL << xasm_singleParser::T__38)
| (1ULL << xasm_singleParser::T__39)
| (1ULL << xasm_singleParser::T__40)
| (1ULL << xasm_singleParser::T__41)
| (1ULL << xasm_singleParser::T__42)
| (1ULL << xasm_singleParser::T__43)
| (1ULL << xasm_singleParser::ID)
| (1ULL << xasm_singleParser::REAL)
| (1ULL << xasm_singleParser::INT)
| (1ULL << xasm_singleParser::STRING))) != 0)) {
setState(68);
exp(0);
setState(69);
compare();
setState(70);
exp(0);
}
setState(74);
match(xasm_singleParser::T__2);
setState(80);
_errHandler->sync(this);
switch (_input->LA(1)) {
case xasm_singleParser::T__0:
case xasm_singleParser::T__26:
case xasm_singleParser::T__34:
case xasm_singleParser::T__37:
case xasm_singleParser::T__38:
case xasm_singleParser::T__39:
case xasm_singleParser::T__40:
case xasm_singleParser::T__41:
case xasm_singleParser::T__42:
case xasm_singleParser::T__43:
case xasm_singleParser::ID:
case xasm_singleParser::REAL:
case xasm_singleParser::INT:
case xasm_singleParser::STRING: {
setState(75);
exp(0);
setState(76);
_la = _input->LA(1);
if (!(_la == xasm_singleParser::T__5
|| _la == xasm_singleParser::T__6)) {
_errHandler->recoverInline(this);
}
else {
_errHandler->reportMatch(this);
consume();
}
break;
}
case xasm_singleParser::T__5:
case xasm_singleParser::T__6: {
setState(78);
_la = _input->LA(1);
if (!(_la == xasm_singleParser::T__5
|| _la == xasm_singleParser::T__6)) {
_errHandler->recoverInline(this);
}
else {
_errHandler->reportMatch(this);
consume();
}
setState(79);
exp(0);
break;
}
case xasm_singleParser::T__1: {
break;
}
default:
break;
}
setState(82);
match(xasm_singleParser::T__1);
setState(84);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__8) {
setState(83);
match(xasm_singleParser::T__8);
}
break;
}
case 5: {
enterOuterAlt(_localctx, 5);
setState(86);
match(xasm_singleParser::T__9);
break;
}
case 6: {
enterOuterAlt(_localctx, 6);
setState(87);
exp(0);
setState(88);
match(xasm_singleParser::T__0);
setState(90);
_errHandler->sync(this);
_la = _input->LA(1);
if ((((_la & ~ 0x3fULL) == 0) &&
((1ULL << _la) & ((1ULL << xasm_singleParser::T__0)
| (1ULL << xasm_singleParser::T__26)
| (1ULL << xasm_singleParser::T__34)
| (1ULL << xasm_singleParser::T__37)
| (1ULL << xasm_singleParser::T__38)
| (1ULL << xasm_singleParser::T__39)
| (1ULL << xasm_singleParser::T__40)
| (1ULL << xasm_singleParser::T__41)
| (1ULL << xasm_singleParser::T__42)
| (1ULL << xasm_singleParser::T__43)
| (1ULL << xasm_singleParser::ID)
| (1ULL << xasm_singleParser::REAL)
| (1ULL << xasm_singleParser::INT)
| (1ULL << xasm_singleParser::STRING))) != 0)) {
setState(89);
explist();
}
setState(92);
match(xasm_singleParser::T__1);
setState(93);
match(xasm_singleParser::T__2);
break;
}
case 7: {
enterOuterAlt(_localctx, 7);
setState(95);
match(xasm_singleParser::T__10);
setState(96);
match(xasm_singleParser::T__0);
setState(97);
explist();
setState(98);
match(xasm_singleParser::T__1);
setState(100);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__8) {
setState(99);
match(xasm_singleParser::T__8);
}
break;
}
case 8: {
enterOuterAlt(_localctx, 8);
setState(102);
match(xasm_singleParser::T__11);
setState(103);
match(xasm_singleParser::T__0);
setState(104);
explist();
setState(105);
match(xasm_singleParser::T__1);
setState(107);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__8) {
setState(106);
match(xasm_singleParser::T__8);
}
break;
}
case 9: {
enterOuterAlt(_localctx, 9);
setState(110);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__3) {
setState(109);
match(xasm_singleParser::T__3);
}
setState(112);
dynamic_cast<CinstContext *>(_localctx)->type_name = cpp_type();
setState(113);
dynamic_cast<CinstContext *>(_localctx)->var_name = exp(0);
setState(114);
match(xasm_singleParser::T__4);
setState(115);
match(xasm_singleParser::T__0);
setState(116);
exp(0);
setState(117);
match(xasm_singleParser::T__12);
setState(118);
exp(0);
setState(119);
match(xasm_singleParser::T__1);
setState(120);
match(xasm_singleParser::T__13);
setState(121);
exp(0);
setState(122);
match(xasm_singleParser::T__14);
setState(123);
exp(0);
setState(124);
match(xasm_singleParser::T__2);
break;
}
case 10: {
enterOuterAlt(_localctx, 10);
setState(126);
match(xasm_singleParser::T__15);
setState(127);
match(xasm_singleParser::T__2);
break;
}
case 11: {
enterOuterAlt(_localctx, 11);
setState(128);
match(xasm_singleParser::T__16);
setState(129);
match(xasm_singleParser::T__2);
break;
}
case 12: {
enterOuterAlt(_localctx, 12);
setState(130);
exp(0);
setState(131);
match(xasm_singleParser::T__4);
setState(132);
exp(0);
setState(133);
match(xasm_singleParser::T__2);
break;
}
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- Cpp_typeContext ------------------------------------------------------------------
xasm_singleParser::Cpp_typeContext::Cpp_typeContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
xasm_singleParser::ExpContext* xasm_singleParser::Cpp_typeContext::exp() {
return getRuleContext<xasm_singleParser::ExpContext>(0);
}
size_t xasm_singleParser::Cpp_typeContext::getRuleIndex() const {
return xasm_singleParser::RuleCpp_type;
}
void xasm_singleParser::Cpp_typeContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterCpp_type(this);
}
void xasm_singleParser::Cpp_typeContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitCpp_type(this);
}
antlrcpp::Any xasm_singleParser::Cpp_typeContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitCpp_type(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::Cpp_typeContext* xasm_singleParser::cpp_type() {
Cpp_typeContext *_localctx = _tracker.createInstance<Cpp_typeContext>(_ctx, getState());
enterRule(_localctx, 10, xasm_singleParser::RuleCpp_type);
size_t _la = 0;
auto onExit = finally([=] {
exitRule();
});
try {
setState(142);
_errHandler->sync(this);
switch (_input->LA(1)) {
case xasm_singleParser::T__17: {
enterOuterAlt(_localctx, 1);
setState(137);
match(xasm_singleParser::T__17);
setState(139);
_errHandler->sync(this);
_la = _input->LA(1);
if (_la == xasm_singleParser::T__18
|| _la == xasm_singleParser::T__19) {
setState(138);
_la = _input->LA(1);
if (!(_la == xasm_singleParser::T__18
|| _la == xasm_singleParser::T__19)) {
_errHandler->recoverInline(this);
}
else {
_errHandler->reportMatch(this);
consume();
}
}
break;
}
case xasm_singleParser::T__0:
case xasm_singleParser::T__26:
case xasm_singleParser::T__34:
case xasm_singleParser::T__37:
case xasm_singleParser::T__38:
case xasm_singleParser::T__39:
case xasm_singleParser::T__40:
case xasm_singleParser::T__41:
case xasm_singleParser::T__42:
case xasm_singleParser::T__43:
case xasm_singleParser::ID:
case xasm_singleParser::REAL:
case xasm_singleParser::INT:
case xasm_singleParser::STRING: {
enterOuterAlt(_localctx, 2);
setState(141);
exp(0);
break;
}
default:
throw NoViableAltException(this);
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- CompareContext ------------------------------------------------------------------
xasm_singleParser::CompareContext::CompareContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
size_t xasm_singleParser::CompareContext::getRuleIndex() const {
return xasm_singleParser::RuleCompare;
}
void xasm_singleParser::CompareContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterCompare(this);
}
void xasm_singleParser::CompareContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitCompare(this);
}
antlrcpp::Any xasm_singleParser::CompareContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitCompare(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::CompareContext* xasm_singleParser::compare() {
CompareContext *_localctx = _tracker.createInstance<CompareContext>(_ctx, getState());
enterRule(_localctx, 12, xasm_singleParser::RuleCompare);
size_t _la = 0;
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(144);
_la = _input->LA(1);
if (!((((_la & ~ 0x3fULL) == 0) &&
((1ULL << _la) & ((1ULL << xasm_singleParser::T__20)
| (1ULL << xasm_singleParser::T__21)
| (1ULL << xasm_singleParser::T__22)
| (1ULL << xasm_singleParser::T__23))) != 0))) {
_errHandler->recoverInline(this);
}
else {
_errHandler->reportMatch(this);
consume();
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- ExplistContext ------------------------------------------------------------------
xasm_singleParser::ExplistContext::ExplistContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
std::vector<xasm_singleParser::ExpContext *> xasm_singleParser::ExplistContext::exp() {
return getRuleContexts<xasm_singleParser::ExpContext>();
}
xasm_singleParser::ExpContext* xasm_singleParser::ExplistContext::exp(size_t i) {
return getRuleContext<xasm_singleParser::ExpContext>(i);
}
size_t xasm_singleParser::ExplistContext::getRuleIndex() const {
return xasm_singleParser::RuleExplist;
}
void xasm_singleParser::ExplistContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterExplist(this);
}
void xasm_singleParser::ExplistContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitExplist(this);
}
antlrcpp::Any xasm_singleParser::ExplistContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitExplist(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::ExplistContext* xasm_singleParser::explist() {
ExplistContext *_localctx = _tracker.createInstance<ExplistContext>(_ctx, getState());
enterRule(_localctx, 14, xasm_singleParser::RuleExplist);
size_t _la = 0;
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(146);
exp(0);
setState(151);
_errHandler->sync(this);
_la = _input->LA(1);
while (_la == xasm_singleParser::T__24) {
setState(147);
match(xasm_singleParser::T__24);
setState(148);
exp(0);
setState(153);
_errHandler->sync(this);
_la = _input->LA(1);
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- ExpContext ------------------------------------------------------------------
xasm_singleParser::ExpContext::ExpContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
xasm_singleParser::IdContext* xasm_singleParser::ExpContext::id() {
return getRuleContext<xasm_singleParser::IdContext>(0);
}
std::vector<xasm_singleParser::ExpContext *> xasm_singleParser::ExpContext::exp() {
return getRuleContexts<xasm_singleParser::ExpContext>();
}
xasm_singleParser::ExpContext* xasm_singleParser::ExpContext::exp(size_t i) {
return getRuleContext<xasm_singleParser::ExpContext>(i);
}
xasm_singleParser::UnaryopContext* xasm_singleParser::ExpContext::unaryop() {
return getRuleContext<xasm_singleParser::UnaryopContext>(0);
}
xasm_singleParser::StringContext* xasm_singleParser::ExpContext::string() {
return getRuleContext<xasm_singleParser::StringContext>(0);
}
xasm_singleParser::RealContext* xasm_singleParser::ExpContext::real() {
return getRuleContext<xasm_singleParser::RealContext>(0);
}
tree::TerminalNode* xasm_singleParser::ExpContext::INT() {
return getToken(xasm_singleParser::INT, 0);
}
xasm_singleParser::ExplistContext* xasm_singleParser::ExpContext::explist() {
return getRuleContext<xasm_singleParser::ExplistContext>(0);
}
size_t xasm_singleParser::ExpContext::getRuleIndex() const {
return xasm_singleParser::RuleExp;
}
void xasm_singleParser::ExpContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterExp(this);
}
void xasm_singleParser::ExpContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitExp(this);
}
antlrcpp::Any xasm_singleParser::ExpContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitExp(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::ExpContext* xasm_singleParser::exp() {
return exp(0);
}
xasm_singleParser::ExpContext* xasm_singleParser::exp(int precedence) {
ParserRuleContext *parentContext = _ctx;
size_t parentState = getState();
xasm_singleParser::ExpContext *_localctx = _tracker.createInstance<ExpContext>(_ctx, parentState);
xasm_singleParser::ExpContext *previousContext = _localctx;
(void)previousContext; // Silence compiler, in case the context is not used by generated code.
size_t startState = 16;
enterRecursionRule(_localctx, 16, xasm_singleParser::RuleExp, precedence);
auto onExit = finally([=] {
unrollRecursionContexts(parentContext);
});
try {
size_t alt;
enterOuterAlt(_localctx, 1);
setState(173);
_errHandler->sync(this);
switch (_input->LA(1)) {
case xasm_singleParser::ID: {
setState(155);
id();
break;
}
case xasm_singleParser::T__26: {
setState(156);
match(xasm_singleParser::T__26);
setState(157);
exp(12);
break;
}
case xasm_singleParser::T__0: {
setState(158);
match(xasm_singleParser::T__0);
setState(159);
exp(0);
setState(160);
match(xasm_singleParser::T__1);
break;
}
case xasm_singleParser::T__38:
case xasm_singleParser::T__39:
case xasm_singleParser::T__40:
case xasm_singleParser::T__41:
case xasm_singleParser::T__42:
case xasm_singleParser::T__43: {
setState(162);
unaryop();
setState(163);
match(xasm_singleParser::T__0);
setState(164);
exp(0);
setState(165);
match(xasm_singleParser::T__1);
break;
}
case xasm_singleParser::STRING: {
setState(167);
string();
break;
}
case xasm_singleParser::REAL: {
setState(168);
real();
break;
}
case xasm_singleParser::INT: {
setState(169);
match(xasm_singleParser::INT);
break;
}
case xasm_singleParser::T__34: {
setState(170);
match(xasm_singleParser::T__34);
break;
}
case xasm_singleParser::T__37: {
setState(171);
match(xasm_singleParser::T__37);
setState(172);
exp(1);
break;
}
default:
throw NoViableAltException(this);
}
_ctx->stop = _input->LT(-1);
setState(234);
_errHandler->sync(this);
alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 17, _ctx);
while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) {
if (alt == 1) {
if (!_parseListeners.empty())
triggerExitRuleEvent();
previousContext = _localctx;
setState(232);
_errHandler->sync(this);
switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 16, _ctx)) {
case 1: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(175);
if (!(precpred(_ctx, 22))) throw FailedPredicateException(this, "precpred(_ctx, 22)");
setState(176);
match(xasm_singleParser::T__25);
setState(177);
exp(23);
break;
}
case 2: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(178);
if (!(precpred(_ctx, 21))) throw FailedPredicateException(this, "precpred(_ctx, 21)");
setState(179);
match(xasm_singleParser::T__26);
setState(180);
exp(22);
break;
}
case 3: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(181);
if (!(precpred(_ctx, 20))) throw FailedPredicateException(this, "precpred(_ctx, 20)");
setState(182);
match(xasm_singleParser::T__19);
setState(183);
exp(21);
break;
}
case 4: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(184);
if (!(precpred(_ctx, 19))) throw FailedPredicateException(this, "precpred(_ctx, 19)");
setState(185);
match(xasm_singleParser::T__27);
setState(186);
exp(20);
break;
}
case 5: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(187);
if (!(precpred(_ctx, 18))) throw FailedPredicateException(this, "precpred(_ctx, 18)");
setState(188);
match(xasm_singleParser::T__28);
setState(189);
exp(19);
break;
}
case 6: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(190);
if (!(precpred(_ctx, 17))) throw FailedPredicateException(this, "precpred(_ctx, 17)");
setState(191);
match(xasm_singleParser::T__29);
setState(192);
exp(18);
break;
}
case 7: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(193);
if (!(precpred(_ctx, 11))) throw FailedPredicateException(this, "precpred(_ctx, 11)");
setState(194);
match(xasm_singleParser::T__31);
setState(195);
exp(12);
break;
}
case 8: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(196);
if (!(precpred(_ctx, 3))) throw FailedPredicateException(this, "precpred(_ctx, 3)");
setState(197);
match(xasm_singleParser::T__35);
setState(198);
exp(4);
break;
}
case 9: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(199);
if (!(precpred(_ctx, 2))) throw FailedPredicateException(this, "precpred(_ctx, 2)");
setState(200);
match(xasm_singleParser::T__36);
setState(201);
exp(3);
break;
}
case 10: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(202);
if (!(precpred(_ctx, 16))) throw FailedPredicateException(this, "precpred(_ctx, 16)");
setState(203);
match(xasm_singleParser::T__21);
setState(204);
exp(0);
setState(205);
match(xasm_singleParser::T__20);
break;
}
case 11: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(207);
if (!(precpred(_ctx, 15))) throw FailedPredicateException(this, "precpred(_ctx, 15)");
setState(208);
match(xasm_singleParser::T__28);
setState(209);
exp(0);
setState(210);
match(xasm_singleParser::T__0);
setState(211);
explist();
setState(212);
match(xasm_singleParser::T__1);
break;
}
case 12: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(214);
if (!(precpred(_ctx, 14))) throw FailedPredicateException(this, "precpred(_ctx, 14)");
setState(215);
match(xasm_singleParser::T__30);
setState(216);
exp(0);
setState(217);
match(xasm_singleParser::T__0);
setState(218);
match(xasm_singleParser::T__1);
break;
}
case 13: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(220);
if (!(precpred(_ctx, 13))) throw FailedPredicateException(this, "precpred(_ctx, 13)");
setState(221);
match(xasm_singleParser::T__30);
setState(222);
exp(0);
setState(223);
match(xasm_singleParser::T__0);
setState(224);
explist();
setState(225);
match(xasm_singleParser::T__1);
break;
}
case 14: {
_localctx = _tracker.createInstance<ExpContext>(parentContext, parentState);
pushNewRecursionContext(_localctx, startState, RuleExp);
setState(227);
if (!(precpred(_ctx, 8))) throw FailedPredicateException(this, "precpred(_ctx, 8)");
setState(228);
match(xasm_singleParser::T__32);
setState(229);
exp(0);
setState(230);
match(xasm_singleParser::T__33);
break;
}
}
}
setState(236);
_errHandler->sync(this);
alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 17, _ctx);
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- UnaryopContext ------------------------------------------------------------------
xasm_singleParser::UnaryopContext::UnaryopContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
size_t xasm_singleParser::UnaryopContext::getRuleIndex() const {
return xasm_singleParser::RuleUnaryop;
}
void xasm_singleParser::UnaryopContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterUnaryop(this);
}
void xasm_singleParser::UnaryopContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitUnaryop(this);
}
antlrcpp::Any xasm_singleParser::UnaryopContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitUnaryop(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::UnaryopContext* xasm_singleParser::unaryop() {
UnaryopContext *_localctx = _tracker.createInstance<UnaryopContext>(_ctx, getState());
enterRule(_localctx, 18, xasm_singleParser::RuleUnaryop);
size_t _la = 0;
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(237);
_la = _input->LA(1);
if (!((((_la & ~ 0x3fULL) == 0) &&
((1ULL << _la) & ((1ULL << xasm_singleParser::T__38)
| (1ULL << xasm_singleParser::T__39)
| (1ULL << xasm_singleParser::T__40)
| (1ULL << xasm_singleParser::T__41)
| (1ULL << xasm_singleParser::T__42)
| (1ULL << xasm_singleParser::T__43))) != 0))) {
_errHandler->recoverInline(this);
}
else {
_errHandler->reportMatch(this);
consume();
}
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- IdContext ------------------------------------------------------------------
xasm_singleParser::IdContext::IdContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
tree::TerminalNode* xasm_singleParser::IdContext::ID() {
return getToken(xasm_singleParser::ID, 0);
}
size_t xasm_singleParser::IdContext::getRuleIndex() const {
return xasm_singleParser::RuleId;
}
void xasm_singleParser::IdContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterId(this);
}
void xasm_singleParser::IdContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitId(this);
}
antlrcpp::Any xasm_singleParser::IdContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitId(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::IdContext* xasm_singleParser::id() {
IdContext *_localctx = _tracker.createInstance<IdContext>(_ctx, getState());
enterRule(_localctx, 20, xasm_singleParser::RuleId);
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(239);
match(xasm_singleParser::ID);
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- RealContext ------------------------------------------------------------------
xasm_singleParser::RealContext::RealContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
tree::TerminalNode* xasm_singleParser::RealContext::REAL() {
return getToken(xasm_singleParser::REAL, 0);
}
size_t xasm_singleParser::RealContext::getRuleIndex() const {
return xasm_singleParser::RuleReal;
}
void xasm_singleParser::RealContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterReal(this);
}
void xasm_singleParser::RealContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitReal(this);
}
antlrcpp::Any xasm_singleParser::RealContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitReal(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::RealContext* xasm_singleParser::real() {
RealContext *_localctx = _tracker.createInstance<RealContext>(_ctx, getState());
enterRule(_localctx, 22, xasm_singleParser::RuleReal);
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(241);
match(xasm_singleParser::REAL);
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
//----------------- StringContext ------------------------------------------------------------------
xasm_singleParser::StringContext::StringContext(ParserRuleContext *parent, size_t invokingState)
: ParserRuleContext(parent, invokingState) {
}
tree::TerminalNode* xasm_singleParser::StringContext::STRING() {
return getToken(xasm_singleParser::STRING, 0);
}
size_t xasm_singleParser::StringContext::getRuleIndex() const {
return xasm_singleParser::RuleString;
}
void xasm_singleParser::StringContext::enterRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->enterString(this);
}
void xasm_singleParser::StringContext::exitRule(tree::ParseTreeListener *listener) {
auto parserListener = dynamic_cast<xasm_singleListener *>(listener);
if (parserListener != nullptr)
parserListener->exitString(this);
}
antlrcpp::Any xasm_singleParser::StringContext::accept(tree::ParseTreeVisitor *visitor) {
if (auto parserVisitor = dynamic_cast<xasm_singleVisitor*>(visitor))
return parserVisitor->visitString(this);
else
return visitor->visitChildren(this);
}
xasm_singleParser::StringContext* xasm_singleParser::string() {
StringContext *_localctx = _tracker.createInstance<StringContext>(_ctx, getState());
enterRule(_localctx, 24, xasm_singleParser::RuleString);
auto onExit = finally([=] {
exitRule();
});
try {
enterOuterAlt(_localctx, 1);
setState(243);
match(xasm_singleParser::STRING);
}
catch (RecognitionException &e) {
_errHandler->reportError(this, e);
_localctx->exception = std::current_exception();
_errHandler->recover(this, _localctx->exception);
}
return _localctx;
}
bool xasm_singleParser::sempred(RuleContext *context, size_t ruleIndex, size_t predicateIndex) {
switch (ruleIndex) {
case 8: return expSempred(dynamic_cast<ExpContext *>(context), predicateIndex);
default:
break;
}
return true;
}
bool xasm_singleParser::expSempred(ExpContext *_localctx, size_t predicateIndex) {
switch (predicateIndex) {
case 0: return precpred(_ctx, 22);
case 1: return precpred(_ctx, 21);
case 2: return precpred(_ctx, 20);
case 3: return precpred(_ctx, 19);
case 4: return precpred(_ctx, 18);
case 5: return precpred(_ctx, 17);
case 6: return precpred(_ctx, 11);
case 7: return precpred(_ctx, 3);
case 8: return precpred(_ctx, 2);
case 9: return precpred(_ctx, 16);
case 10: return precpred(_ctx, 15);
case 11: return precpred(_ctx, 14);
case 12: return precpred(_ctx, 13);
case 13: return precpred(_ctx, 8);
default:
break;
}
return true;
}
// Static vars and initialization.
std::vector<dfa::DFA> xasm_singleParser::_decisionToDFA;
atn::PredictionContextCache xasm_singleParser::_sharedContextCache;
// We own the ATN which in turn owns the ATN states.
atn::ATN xasm_singleParser::_atn;
std::vector<uint16_t> xasm_singleParser::_serializedATN;
std::vector<std::string> xasm_singleParser::_ruleNames = {
"line", "statement", "comment", "qinst", "cinst", "cpp_type", "compare",
"explist", "exp", "unaryop", "id", "real", "string"
};
std::vector<std::string> xasm_singleParser::_literalNames = {
"", "'('", "')'", "';'", "'const'", "'='", "'++'", "'--'", "'for'", "'{'",
"'}'", "'if'", "'else'", "'=='", "'?'", "':'", "'break'", "'return'",
"'auto'", "'&'", "'*'", "'>'", "'<'", "'>='", "'<='", "','", "'+'", "'-'",
"'/'", "'::'", "'<<'", "'.'", "'^'", "'['", "']'", "'pi'", "'&&'", "'||'",
"'!'", "'sin'", "'cos'", "'tan'", "'exp'", "'ln'", "'sqrt'"
};
std::vector<std::string> xasm_singleParser::_symbolicNames = {
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "COMMENT", "ID", "REAL", "INT", "STRING",
"WS", "EOL"
};
dfa::Vocabulary xasm_singleParser::_vocabulary(_literalNames, _symbolicNames);
std::vector<std::string> xasm_singleParser::_tokenNames;
xasm_singleParser::Initializer::Initializer() {
for (size_t i = 0; i < _symbolicNames.size(); ++i) {
std::string name = _vocabulary.getLiteralName(i);
if (name.empty()) {
name = _vocabulary.getSymbolicName(i);
}
if (name.empty()) {
_tokenNames.push_back("<INVALID>");
} else {
_tokenNames.push_back(name);
}
}
_serializedATN = {
0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964,
0x3, 0x35, 0xf8, 0x4, 0x2, 0x9, 0x2, 0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9,
0x4, 0x4, 0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7, 0x9, 0x7, 0x4,
0x8, 0x9, 0x8, 0x4, 0x9, 0x9, 0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9,
0xb, 0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x4, 0xe, 0x9, 0xe, 0x3,
0x2, 0x3, 0x2, 0x5, 0x2, 0x1f, 0xa, 0x2, 0x3, 0x3, 0x3, 0x3, 0x5, 0x3,
0x23, 0xa, 0x3, 0x3, 0x4, 0x3, 0x4, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3,
0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x6, 0x5, 0x6, 0x2e, 0xa, 0x6, 0x3, 0x6,
0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x5, 0x6, 0x34, 0xa, 0x6, 0x3, 0x6, 0x3,
0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3,
0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3,
0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x5, 0x6, 0x4b,
0xa, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6,
0x5, 0x6, 0x53, 0xa, 0x6, 0x3, 0x6, 0x3, 0x6, 0x5, 0x6, 0x57, 0xa, 0x6,
0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x5, 0x6, 0x5d, 0xa, 0x6, 0x3,
0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3,
0x6, 0x5, 0x6, 0x67, 0xa, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6,
0x3, 0x6, 0x5, 0x6, 0x6e, 0xa, 0x6, 0x3, 0x6, 0x5, 0x6, 0x71, 0xa, 0x6,
0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6,
0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6,
0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6,
0x3, 0x6, 0x3, 0x6, 0x5, 0x6, 0x8a, 0xa, 0x6, 0x3, 0x7, 0x3, 0x7, 0x5,
0x7, 0x8e, 0xa, 0x7, 0x3, 0x7, 0x5, 0x7, 0x91, 0xa, 0x7, 0x3, 0x8, 0x3,
0x8, 0x3, 0x9, 0x3, 0x9, 0x3, 0x9, 0x7, 0x9, 0x98, 0xa, 0x9, 0xc, 0x9,
0xe, 0x9, 0x9b, 0xb, 0x9, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3,
0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3,
0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3,
0xa, 0x5, 0xa, 0xb0, 0xa, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa,
0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x7, 0xa, 0xeb, 0xa, 0xa, 0xc,
0xa, 0xe, 0xa, 0xee, 0xb, 0xa, 0x3, 0xb, 0x3, 0xb, 0x3, 0xc, 0x3, 0xc,
0x3, 0xd, 0x3, 0xd, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x2, 0x3, 0x12, 0xf,
0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a,
0x2, 0x6, 0x3, 0x2, 0x8, 0x9, 0x3, 0x2, 0x15, 0x16, 0x3, 0x2, 0x17,
0x1a, 0x3, 0x2, 0x29, 0x2e, 0x2, 0x11a, 0x2, 0x1e, 0x3, 0x2, 0x2, 0x2,
0x4, 0x22, 0x3, 0x2, 0x2, 0x2, 0x6, 0x24, 0x3, 0x2, 0x2, 0x2, 0x8, 0x26,
0x3, 0x2, 0x2, 0x2, 0xa, 0x89, 0x3, 0x2, 0x2, 0x2, 0xc, 0x90, 0x3, 0x2,
0x2, 0x2, 0xe, 0x92, 0x3, 0x2, 0x2, 0x2, 0x10, 0x94, 0x3, 0x2, 0x2,
0x2, 0x12, 0xaf, 0x3, 0x2, 0x2, 0x2, 0x14, 0xef, 0x3, 0x2, 0x2, 0x2,
0x16, 0xf1, 0x3, 0x2, 0x2, 0x2, 0x18, 0xf3, 0x3, 0x2, 0x2, 0x2, 0x1a,
0xf5, 0x3, 0x2, 0x2, 0x2, 0x1c, 0x1f, 0x5, 0x4, 0x3, 0x2, 0x1d, 0x1f,
0x5, 0x6, 0x4, 0x2, 0x1e, 0x1c, 0x3, 0x2, 0x2, 0x2, 0x1e, 0x1d, 0x3,
0x2, 0x2, 0x2, 0x1f, 0x3, 0x3, 0x2, 0x2, 0x2, 0x20, 0x23, 0x5, 0x8,
0x5, 0x2, 0x21, 0x23, 0x5, 0xa, 0x6, 0x2, 0x22, 0x20, 0x3, 0x2, 0x2,
0x2, 0x22, 0x21, 0x3, 0x2, 0x2, 0x2, 0x23, 0x5, 0x3, 0x2, 0x2, 0x2,
0x24, 0x25, 0x7, 0x2f, 0x2, 0x2, 0x25, 0x7, 0x3, 0x2, 0x2, 0x2, 0x26,
0x27, 0x5, 0x16, 0xc, 0x2, 0x27, 0x28, 0x7, 0x3, 0x2, 0x2, 0x28, 0x29,
0x5, 0x10, 0x9, 0x2, 0x29, 0x2a, 0x7, 0x4, 0x2, 0x2, 0x2a, 0x2b, 0x7,
0x5, 0x2, 0x2, 0x2b, 0x9, 0x3, 0x2, 0x2, 0x2, 0x2c, 0x2e, 0x7, 0x6,
0x2, 0x2, 0x2d, 0x2c, 0x3, 0x2, 0x2, 0x2, 0x2d, 0x2e, 0x3, 0x2, 0x2,
0x2, 0x2e, 0x2f, 0x3, 0x2, 0x2, 0x2, 0x2f, 0x30, 0x5, 0xc, 0x7, 0x2,
0x30, 0x33, 0x5, 0x12, 0xa, 0x2, 0x31, 0x32, 0x7, 0x7, 0x2, 0x2, 0x32,
0x34, 0x5, 0x12, 0xa, 0x2, 0x33, 0x31, 0x3, 0x2, 0x2, 0x2, 0x33, 0x34,
0x3, 0x2, 0x2, 0x2, 0x34, 0x35, 0x3, 0x2, 0x2, 0x2, 0x35, 0x36, 0x7,
0x5, 0x2, 0x2, 0x36, 0x8a, 0x3, 0x2, 0x2, 0x2, 0x37, 0x38, 0x5, 0x12,
0xa, 0x2, 0x38, 0x39, 0x7, 0x8, 0x2, 0x2, 0x39, 0x3a, 0x7, 0x5, 0x2,
0x2, 0x3a, 0x8a, 0x3, 0x2, 0x2, 0x2, 0x3b, 0x3c, 0x5, 0x12, 0xa, 0x2,
0x3c, 0x3d, 0x7, 0x9, 0x2, 0x2, 0x3d, 0x3e, 0x7, 0x5, 0x2, 0x2, 0x3e,
0x8a, 0x3, 0x2, 0x2, 0x2, 0x3f, 0x40, 0x7, 0xa, 0x2, 0x2, 0x40, 0x41,
0x7, 0x3, 0x2, 0x2, 0x41, 0x42, 0x5, 0xc, 0x7, 0x2, 0x42, 0x43, 0x5,
0x12, 0xa, 0x2, 0x43, 0x44, 0x7, 0x7, 0x2, 0x2, 0x44, 0x45, 0x5, 0x12,
0xa, 0x2, 0x45, 0x4a, 0x7, 0x5, 0x2, 0x2, 0x46, 0x47, 0x5, 0x12, 0xa,
0x2, 0x47, 0x48, 0x5, 0xe, 0x8, 0x2, 0x48, 0x49, 0x5, 0x12, 0xa, 0x2,
0x49, 0x4b, 0x3, 0x2, 0x2, 0x2, 0x4a, 0x46, 0x3, 0x2, 0x2, 0x2, 0x4a,
0x4b, 0x3, 0x2, 0x2, 0x2, 0x4b, 0x4c, 0x3, 0x2, 0x2, 0x2, 0x4c, 0x52,
0x7, 0x5, 0x2, 0x2, 0x4d, 0x4e, 0x5, 0x12, 0xa, 0x2, 0x4e, 0x4f, 0x9,
0x2, 0x2, 0x2, 0x4f, 0x53, 0x3, 0x2, 0x2, 0x2, 0x50, 0x51, 0x9, 0x2,
0x2, 0x2, 0x51, 0x53, 0x5, 0x12, 0xa, 0x2, 0x52, 0x4d, 0x3, 0x2, 0x2,
0x2, 0x52, 0x50, 0x3, 0x2, 0x2, 0x2, 0x52, 0x53, 0x3, 0x2, 0x2, 0x2,
0x53, 0x54, 0x3, 0x2, 0x2, 0x2, 0x54, 0x56, 0x7, 0x4, 0x2, 0x2, 0x55,
0x57, 0x7, 0xb, 0x2, 0x2, 0x56, 0x55, 0x3, 0x2, 0x2, 0x2, 0x56, 0x57,
0x3, 0x2, 0x2, 0x2, 0x57, 0x8a, 0x3, 0x2, 0x2, 0x2, 0x58, 0x8a, 0x7,
0xc, 0x2, 0x2, 0x59, 0x5a, 0x5, 0x12, 0xa, 0x2, 0x5a, 0x5c, 0x7, 0x3,
0x2, 0x2, 0x5b, 0x5d, 0x5, 0x10, 0x9, 0x2, 0x5c, 0x5b, 0x3, 0x2, 0x2,
0x2, 0x5c, 0x5d, 0x3, 0x2, 0x2, 0x2, 0x5d, 0x5e, 0x3, 0x2, 0x2, 0x2,
0x5e, 0x5f, 0x7, 0x4, 0x2, 0x2, 0x5f, 0x60, 0x7, 0x5, 0x2, 0x2, 0x60,
0x8a, 0x3, 0x2, 0x2, 0x2, 0x61, 0x62, 0x7, 0xd, 0x2, 0x2, 0x62, 0x63,
0x7, 0x3, 0x2, 0x2, 0x63, 0x64, 0x5, 0x10, 0x9, 0x2, 0x64, 0x66, 0x7,
0x4, 0x2, 0x2, 0x65, 0x67, 0x7, 0xb, 0x2, 0x2, 0x66, 0x65, 0x3, 0x2,
0x2, 0x2, 0x66, 0x67, 0x3, 0x2, 0x2, 0x2, 0x67, 0x8a, 0x3, 0x2, 0x2,
0x2, 0x68, 0x69, 0x7, 0xe, 0x2, 0x2, 0x69, 0x6a, 0x7, 0x3, 0x2, 0x2,
0x6a, 0x6b, 0x5, 0x10, 0x9, 0x2, 0x6b, 0x6d, 0x7, 0x4, 0x2, 0x2, 0x6c,
0x6e, 0x7, 0xb, 0x2, 0x2, 0x6d, 0x6c, 0x3, 0x2, 0x2, 0x2, 0x6d, 0x6e,
0x3, 0x2, 0x2, 0x2, 0x6e, 0x8a, 0x3, 0x2, 0x2, 0x2, 0x6f, 0x71, 0x7,
0x6, 0x2, 0x2, 0x70, 0x6f, 0x3, 0x2, 0x2, 0x2, 0x70, 0x71, 0x3, 0x2,
0x2, 0x2, 0x71, 0x72, 0x3, 0x2, 0x2, 0x2, 0x72, 0x73, 0x5, 0xc, 0x7,
0x2, 0x73, 0x74, 0x5, 0x12, 0xa, 0x2, 0x74, 0x75, 0x7, 0x7, 0x2, 0x2,
0x75, 0x76, 0x7, 0x3, 0x2, 0x2, 0x76, 0x77, 0x5, 0x12, 0xa, 0x2, 0x77,
0x78, 0x7, 0xf, 0x2, 0x2, 0x78, 0x79, 0x5, 0x12, 0xa, 0x2, 0x79, 0x7a,
0x7, 0x4, 0x2, 0x2, 0x7a, 0x7b, 0x7, 0x10, 0x2, 0x2, 0x7b, 0x7c, 0x5,
0x12, 0xa, 0x2, 0x7c, 0x7d, 0x7, 0x11, 0x2, 0x2, 0x7d, 0x7e, 0x5, 0x12,
0xa, 0x2, 0x7e, 0x7f, 0x7, 0x5, 0x2, 0x2, 0x7f, 0x8a, 0x3, 0x2, 0x2,
0x2, 0x80, 0x81, 0x7, 0x12, 0x2, 0x2, 0x81, 0x8a, 0x7, 0x5, 0x2, 0x2,
0x82, 0x83, 0x7, 0x13, 0x2, 0x2, 0x83, 0x8a, 0x7, 0x5, 0x2, 0x2, 0x84,
0x85, 0x5, 0x12, 0xa, 0x2, 0x85, 0x86, 0x7, 0x7, 0x2, 0x2, 0x86, 0x87,
0x5, 0x12, 0xa, 0x2, 0x87, 0x88, 0x7, 0x5, 0x2, 0x2, 0x88, 0x8a, 0x3,
0x2, 0x2, 0x2, 0x89, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x89, 0x37, 0x3, 0x2,
0x2, 0x2, 0x89, 0x3b, 0x3, 0x2, 0x2, 0x2, 0x89, 0x3f, 0x3, 0x2, 0x2,
0x2, 0x89, 0x58, 0x3, 0x2, 0x2, 0x2, 0x89, 0x59, 0x3, 0x2, 0x2, 0x2,
0x89, 0x61, 0x3, 0x2, 0x2, 0x2, 0x89, 0x68, 0x3, 0x2, 0x2, 0x2, 0x89,
0x70, 0x3, 0x2, 0x2, 0x2, 0x89, 0x80, 0x3, 0x2, 0x2, 0x2, 0x89, 0x82,
0x3, 0x2, 0x2, 0x2, 0x89, 0x84, 0x3, 0x2, 0x2, 0x2, 0x8a, 0xb, 0x3,
0x2, 0x2, 0x2, 0x8b, 0x8d, 0x7, 0x14, 0x2, 0x2, 0x8c, 0x8e, 0x9, 0x3,
0x2, 0x2, 0x8d, 0x8c, 0x3, 0x2, 0x2, 0x2, 0x8d, 0x8e, 0x3, 0x2, 0x2,
0x2, 0x8e, 0x91, 0x3, 0x2, 0x2, 0x2, 0x8f, 0x91, 0x5, 0x12, 0xa, 0x2,
0x90, 0x8b, 0x3, 0x2, 0x2, 0x2, 0x90, 0x8f, 0x3, 0x2, 0x2, 0x2, 0x91,
0xd, 0x3, 0x2, 0x2, 0x2, 0x92, 0x93, 0x9, 0x4, 0x2, 0x2, 0x93, 0xf,
0x3, 0x2, 0x2, 0x2, 0x94, 0x99, 0x5, 0x12, 0xa, 0x2, 0x95, 0x96, 0x7,
0x1b, 0x2, 0x2, 0x96, 0x98, 0x5, 0x12, 0xa, 0x2, 0x97, 0x95, 0x3, 0x2,
0x2, 0x2, 0x98, 0x9b, 0x3, 0x2, 0x2, 0x2, 0x99, 0x97, 0x3, 0x2, 0x2,
0x2, 0x99, 0x9a, 0x3, 0x2, 0x2, 0x2, 0x9a, 0x11, 0x3, 0x2, 0x2, 0x2,
0x9b, 0x99, 0x3, 0x2, 0x2, 0x2, 0x9c, 0x9d, 0x8, 0xa, 0x1, 0x2, 0x9d,
0xb0, 0x5, 0x16, 0xc, 0x2, 0x9e, 0x9f, 0x7, 0x1d, 0x2, 0x2, 0x9f, 0xb0,
0x5, 0x12, 0xa, 0xe, 0xa0, 0xa1, 0x7, 0x3, 0x2, 0x2, 0xa1, 0xa2, 0x5,
0x12, 0xa, 0x2, 0xa2, 0xa3, 0x7, 0x4, 0x2, 0x2, 0xa3, 0xb0, 0x3, 0x2,
0x2, 0x2, 0xa4, 0xa5, 0x5, 0x14, 0xb, 0x2, 0xa5, 0xa6, 0x7, 0x3, 0x2,
0x2, 0xa6, 0xa7, 0x5, 0x12, 0xa, 0x2, 0xa7, 0xa8, 0x7, 0x4, 0x2, 0x2,
0xa8, 0xb0, 0x3, 0x2, 0x2, 0x2, 0xa9, 0xb0, 0x5, 0x1a, 0xe, 0x2, 0xaa,
0xb0, 0x5, 0x18, 0xd, 0x2, 0xab, 0xb0, 0x7, 0x32, 0x2, 0x2, 0xac, 0xb0,
0x7, 0x25, 0x2, 0x2, 0xad, 0xae, 0x7, 0x28, 0x2, 0x2, 0xae, 0xb0, 0x5,
0x12, 0xa, 0x3, 0xaf, 0x9c, 0x3, 0x2, 0x2, 0x2, 0xaf, 0x9e, 0x3, 0x2,
0x2, 0x2, 0xaf, 0xa0, 0x3, 0x2, 0x2, 0x2, 0xaf, 0xa4, 0x3, 0x2, 0x2,
0x2, 0xaf, 0xa9, 0x3, 0x2, 0x2, 0x2, 0xaf, 0xaa, 0x3, 0x2, 0x2, 0x2,
0xaf, 0xab, 0x3, 0x2, 0x2, 0x2, 0xaf, 0xac, 0x3, 0x2, 0x2, 0x2, 0xaf,
0xad, 0x3, 0x2, 0x2, 0x2, 0xb0, 0xec, 0x3, 0x2, 0x2, 0x2, 0xb1, 0xb2,
0xc, 0x18, 0x2, 0x2, 0xb2, 0xb3, 0x7, 0x1c, 0x2, 0x2, 0xb3, 0xeb, 0x5,
0x12, 0xa, 0x19, 0xb4, 0xb5, 0xc, 0x17, 0x2, 0x2, 0xb5, 0xb6, 0x7, 0x1d,
0x2, 0x2, 0xb6, 0xeb, 0x5, 0x12, 0xa, 0x18, 0xb7, 0xb8, 0xc, 0x16, 0x2,
0x2, 0xb8, 0xb9, 0x7, 0x16, 0x2, 0x2, 0xb9, 0xeb, 0x5, 0x12, 0xa, 0x17,
0xba, 0xbb, 0xc, 0x15, 0x2, 0x2, 0xbb, 0xbc, 0x7, 0x1e, 0x2, 0x2, 0xbc,
0xeb, 0x5, 0x12, 0xa, 0x16, 0xbd, 0xbe, 0xc, 0x14, 0x2, 0x2, 0xbe, 0xbf,
0x7, 0x1f, 0x2, 0x2, 0xbf, 0xeb, 0x5, 0x12, 0xa, 0x15, 0xc0, 0xc1, 0xc,
0x13, 0x2, 0x2, 0xc1, 0xc2, 0x7, 0x20, 0x2, 0x2, 0xc2, 0xeb, 0x5, 0x12,
0xa, 0x14, 0xc3, 0xc4, 0xc, 0xd, 0x2, 0x2, 0xc4, 0xc5, 0x7, 0x22, 0x2,
0x2, 0xc5, 0xeb, 0x5, 0x12, 0xa, 0xe, 0xc6, 0xc7, 0xc, 0x5, 0x2, 0x2,
0xc7, 0xc8, 0x7, 0x26, 0x2, 0x2, 0xc8, 0xeb, 0x5, 0x12, 0xa, 0x6, 0xc9,
0xca, 0xc, 0x4, 0x2, 0x2, 0xca, 0xcb, 0x7, 0x27, 0x2, 0x2, 0xcb, 0xeb,
0x5, 0x12, 0xa, 0x5, 0xcc, 0xcd, 0xc, 0x12, 0x2, 0x2, 0xcd, 0xce, 0x7,
0x18, 0x2, 0x2, 0xce, 0xcf, 0x5, 0x12, 0xa, 0x2, 0xcf, 0xd0, 0x7, 0x17,
0x2, 0x2, 0xd0, 0xeb, 0x3, 0x2, 0x2, 0x2, 0xd1, 0xd2, 0xc, 0x11, 0x2,
0x2, 0xd2, 0xd3, 0x7, 0x1f, 0x2, 0x2, 0xd3, 0xd4, 0x5, 0x12, 0xa, 0x2,
0xd4, 0xd5, 0x7, 0x3, 0x2, 0x2, 0xd5, 0xd6, 0x5, 0x10, 0x9, 0x2, 0xd6,
0xd7, 0x7, 0x4, 0x2, 0x2, 0xd7, 0xeb, 0x3, 0x2, 0x2, 0x2, 0xd8, 0xd9,
0xc, 0x10, 0x2, 0x2, 0xd9, 0xda, 0x7, 0x21, 0x2, 0x2, 0xda, 0xdb, 0x5,
0x12, 0xa, 0x2, 0xdb, 0xdc, 0x7, 0x3, 0x2, 0x2, 0xdc, 0xdd, 0x7, 0x4,
0x2, 0x2, 0xdd, 0xeb, 0x3, 0x2, 0x2, 0x2, 0xde, 0xdf, 0xc, 0xf, 0x2,
0x2, 0xdf, 0xe0, 0x7, 0x21, 0x2, 0x2, 0xe0, 0xe1, 0x5, 0x12, 0xa, 0x2,
0xe1, 0xe2, 0x7, 0x3, 0x2, 0x2, 0xe2, 0xe3, 0x5, 0x10, 0x9, 0x2, 0xe3,
0xe4, 0x7, 0x4, 0x2, 0x2, 0xe4, 0xeb, 0x3, 0x2, 0x2, 0x2, 0xe5, 0xe6,
0xc, 0xa, 0x2, 0x2, 0xe6, 0xe7, 0x7, 0x23, 0x2, 0x2, 0xe7, 0xe8, 0x5,
0x12, 0xa, 0x2, 0xe8, 0xe9, 0x7, 0x24, 0x2, 0x2, 0xe9, 0xeb, 0x3, 0x2,
0x2, 0x2, 0xea, 0xb1, 0x3, 0x2, 0x2, 0x2, 0xea, 0xb4, 0x3, 0x2, 0x2,
0x2, 0xea, 0xb7, 0x3, 0x2, 0x2, 0x2, 0xea, 0xba, 0x3, 0x2, 0x2, 0x2,
0xea, 0xbd, 0x3, 0x2, 0x2, 0x2, 0xea, 0xc0, 0x3, 0x2, 0x2, 0x2, 0xea,
0xc3, 0x3, 0x2, 0x2, 0x2, 0xea, 0xc6, 0x3, 0x2, 0x2, 0x2, 0xea, 0xc9,
0x3, 0x2, 0x2, 0x2, 0xea, 0xcc, 0x3, 0x2, 0x2, 0x2, 0xea, 0xd1, 0x3,
0x2, 0x2, 0x2, 0xea, 0xd8, 0x3, 0x2, 0x2, 0x2, 0xea, 0xde, 0x3, 0x2,
0x2, 0x2, 0xea, 0xe5, 0x3, 0x2, 0x2, 0x2, 0xeb, 0xee, 0x3, 0x2, 0x2,
0x2, 0xec, 0xea, 0x3, 0x2, 0x2, 0x2, 0xec, 0xed, 0x3, 0x2, 0x2, 0x2,
0xed, 0x13, 0x3, 0x2, 0x2, 0x2, 0xee, 0xec, 0x3, 0x2, 0x2, 0x2, 0xef,
0xf0, 0x9, 0x5, 0x2, 0x2, 0xf0, 0x15, 0x3, 0x2, 0x2, 0x2, 0xf1, 0xf2,
0x7, 0x30, 0x2, 0x2, 0xf2, 0x17, 0x3, 0x2, 0x2, 0x2, 0xf3, 0xf4, 0x7,
0x31, 0x2, 0x2, 0xf4, 0x19, 0x3, 0x2, 0x2, 0x2, 0xf5, 0xf6, 0x7, 0x33,
0x2, 0x2, 0xf6, 0x1b, 0x3, 0x2, 0x2, 0x2, 0x14, 0x1e, 0x22, 0x2d, 0x33,
0x4a, 0x52, 0x56, 0x5c, 0x66, 0x6d, 0x70, 0x89, 0x8d, 0x90, 0x99, 0xaf,
0xea, 0xec,
};
atn::ATNDeserializer deserializer;
_atn = deserializer.deserialize(_serializedATN);
size_t count = _atn.getNumberOfDecisions();
_decisionToDFA.reserve(count);
for (size_t i = 0; i < count; i++) {
_decisionToDFA.emplace_back(_atn.getDecisionState(i), i);
}
}
xasm_singleParser::Initializer xasm_singleParser::_init;
| 33.847919 | 103 | 0.63532 | [
"vector"
] |
c8d12b13db2422b0e97b3ac5bdc01db71fd68260 | 35,867 | cc | C++ | src/Perf.cc | IMCG/RamCloud | dad96cf34d330608acb43b009d12949ed2d938f4 | [
"0BSD"
] | 1 | 2021-12-06T01:24:22.000Z | 2021-12-06T01:24:22.000Z | src/Perf.cc | behnamm/cs244b_project | 957e8b3979e4ca24814edd73254cc4c69ea14126 | [
"0BSD"
] | null | null | null | src/Perf.cc | behnamm/cs244b_project | 957e8b3979e4ca24814edd73254cc4c69ea14126 | [
"0BSD"
] | 1 | 2021-12-06T01:24:22.000Z | 2021-12-06T01:24:22.000Z | /* Copyright (c) 2011-2014 Stanford University
* Copyright (c) 2011 Facebook
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// This program contains a collection of low-level performance measurements
// for RAMCloud, which can be run either individually or altogether. These
// tests measure performance in a single stand-alone process, not in a cluster
// with multiple servers. Invoke the program like this:
//
// Perf test1 test2 ...
//
// test1 and test2 are the names of individual performance measurements to
// run. If no test names are provided then all of the performance tests
// are run.
//
// To add a new test:
// * Write a function that implements the test. Use existing test functions
// as a guideline, and be sure to generate output in the same form as
// other tests.
// * Create a new entry for the test in the #tests table.
#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 5
#include <atomic>
#else
#include <cstdatomic>
#endif
#include <vector>
#include "Common.h"
#include "Atomic.h"
#include "Cycles.h"
#include "CycleCounter.h"
#include "Dispatch.h"
#include "Fence.h"
#include "Memory.h"
#include "MurmurHash3.h"
#include "Object.h"
#include "ObjectPool.h"
#include "Segment.h"
#include "SegmentIterator.h"
#include "SpinLock.h"
#include "ClientException.h"
#include "PerfHelper.h"
using namespace RAMCloud;
/**
* Ask the operating system to pin the current thread to a given CPU.
*
* \param cpu
* Indicates the desired CPU and hyperthread; low order 2 bits
* specify CPU, next bit specifies hyperthread.
*/
void bindThreadToCpu(int cpu)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
sched_setaffinity((pid_t)syscall(SYS_gettid), sizeof(set), &set);
}
/*
* This function just discards its argument. It's used to make it
* appear that data is used, so that the compiler won't optimize
* away the code we're trying to measure.
*
* \param value
* Pointer to arbitrary value; it's discarded.
*/
void discard(void* value) {
int x = *reinterpret_cast<int*>(value);
if (x == 0x43924776) {
printf("Value was 0x%x\n", x);
}
}
//----------------------------------------------------------------------
// Test functions start here
//----------------------------------------------------------------------
// Measure the cost of Atomic<int>::compareExchange.
double atomicIntCmpX()
{
int count = 1000000;
Atomic<int> value(11);
int test = 11;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
value.compareExchange(test, test+2);
test += 2;
}
uint64_t stop = Cycles::rdtsc();
// printf("Final value: %d\n", value.load());
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of Atomic<int>::inc.
double atomicIntInc()
{
int count = 1000000;
Atomic<int> value(11);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
value.inc();
}
uint64_t stop = Cycles::rdtsc();
// printf("Final value: %d\n", value.load());
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of reading an Atomic<int>.
double atomicIntLoad()
{
int count = 1000000;
Atomic<int> value(11);
int total = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
total += value.load();
}
uint64_t stop = Cycles::rdtsc();
// printf("Total: %d\n", total);
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of Atomic<int>::exchange.
double atomicIntXchg()
{
int count = 1000000;
Atomic<int> value(11);
int total = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
total += value.exchange(i);
}
uint64_t stop = Cycles::rdtsc();
// printf("Total: %d\n", total);
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of storing a new value in a Atomic<int>.
double atomicIntStore()
{
int count = 1000000;
Atomic<int> value(11);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
value.store(88);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of acquiring and releasing a std mutex in the
// fast case where the mutex is free.
double bMutexNoBlock()
{
int count = 1000000;
std::mutex m;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
m.lock();
m.unlock();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of allocating and deallocating a buffer, plus
// appending (virtually) one block.
double bufferBasic()
{
int count = 1000000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Buffer b;
b.appendExternal("abcdefg", 5);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
struct dummyBlock {
int a, b, c, d;
};
// Measure the cost of allocating and deallocating a buffer, plus
// allocating space for one chunk.
double bufferBasicAlloc()
{
int count = 1000000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Buffer b;
b.emplaceAppend<dummyBlock>();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of allocating and deallocating a buffer, plus
// copying in a small block.
double bufferBasicCopy()
{
int count = 1000000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Buffer b;
b.appendCopy("abcdefg", 6);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of making a copy of parts of two chunks.
double bufferCopy()
{
int count = 1000000;
Buffer b;
b.appendExternal("abcde", 5);
b.appendExternal("01234", 5);
char copy[10];
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
b.copy(2, 6, copy);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of allocating new space by extending the
// last chunk.
double bufferExtendChunk()
{
int count = 100000;
uint64_t total = 0;
for (int i = 0; i < count; i++) {
Buffer b;
b.emplaceAppend<dummyBlock>();
uint64_t start = Cycles::rdtsc();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
b.emplaceAppend<dummyBlock>();
total += Cycles::rdtsc() - start;
b.reset();
}
return Cycles::toSeconds(total)/(count*10);
}
// Measure the cost of retrieving an object from the beginning of a buffer.
double bufferGetStart()
{
int count = 1000000;
int value = 11;
Buffer b;
b.appendCopy(&value);
int sum = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
sum += *b.getStart<int>();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of creating an iterator and iterating over 10
// chunks in a buffer.
double bufferIterator()
{
Buffer b;
const char* p = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 5; i++) {
b.appendExternal(p+i, 5);
}
int count = 100000;
int sum = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Buffer::Iterator it(&b);
while (!it.isDone()) {
sum += (static_cast<const char*>(it.getData()))[it.getLength()-1];
it.next();
}
}
uint64_t stop = Cycles::rdtsc();
discard(&sum);
return Cycles::toSeconds(stop - start)/count;
}
// Implements the condPingPong test.
class CondPingPong {
public:
CondPingPong()
: mutex()
, cond()
, prod(0)
, cons(0)
, count(10000)
{
}
double run() {
std::thread thread(&CondPingPong::consumer, this);
uint64_t start = Cycles::rdtsc();
producer();
uint64_t stop = Cycles::rdtsc();
thread.join();
return Cycles::toSeconds(stop - start)/count;
}
void producer() {
std::unique_lock<std::mutex> lockGuard(mutex);
while (cons < count) {
while (cons < prod)
cond.wait(lockGuard);
++prod;
cond.notify_all();
}
}
void consumer() {
std::unique_lock<std::mutex> lockGuard(mutex);
while (cons < count) {
while (cons == prod)
cond.wait(lockGuard);
++cons;
cond.notify_all();
}
}
private:
std::mutex mutex;
std::condition_variable cond;
int prod;
int cons;
const int count;
DISALLOW_COPY_AND_ASSIGN(CondPingPong);
};
// Measure the cost of coordinating between threads using a condition variable.
double condPingPong()
{
return CondPingPong().run();
}
// Measure the cost of the exchange method on a C++ atomic_int.
double cppAtomicExchange()
{
int count = 100000;
std::atomic_int value(11);
int other = 22;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
other = value.exchange(other);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of the load method on a C++ atomic_int (seems to have
// 2 mfence operations!).
double cppAtomicLoad()
{
int count = 100000;
std::atomic_int value(11);
int total = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
total += value.load();
}
uint64_t stop = Cycles::rdtsc();
// printf("Total: %d\n", total);
return Cycles::toSeconds(stop - start)/count;
}
// Measure the minimum cost of Dispatch::poll, when there are no
// Pollers and no Timers.
double dispatchPoll()
{
int count = 1000000;
Dispatch dispatch(false);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
dispatch.poll();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of a 32-bit divide. Divides don't take a constant
// number of cycles. Values were chosen here semi-randomly to depict a
// fairly expensive scenario. Someone with fancy ALU knowledge could
// probably pick worse values.
double div32()
{
int count = 1000000;
Dispatch dispatch(false);
uint64_t start = Cycles::rdtsc();
// NB: Expect an x86 processor exception is there's overflow.
uint32_t numeratorHi = 0xa5a5a5a5U;
uint32_t numeratorLo = 0x55aa55aaU;
uint32_t divisor = 0xaa55aa55U;
uint32_t quotient;
uint32_t remainder;
for (int i = 0; i < count; i++) {
__asm__ __volatile__("div %4" :
"=a"(quotient), "=d"(remainder) :
"a"(numeratorLo), "d"(numeratorHi), "r"(divisor) :
"cc");
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of a 64-bit divide. Divides don't take a constant
// number of cycles. Values were chosen here semi-randomly to depict a
// fairly expensive scenario. Someone with fancy ALU knowledge could
// probably pick worse values.
double div64()
{
int count = 1000000;
Dispatch dispatch(false);
// NB: Expect an x86 processor exception is there's overflow.
uint64_t start = Cycles::rdtsc();
uint64_t numeratorHi = 0x5a5a5a5a5a5UL;
uint64_t numeratorLo = 0x55aa55aa55aa55aaUL;
uint64_t divisor = 0xaa55aa55aa55aa55UL;
uint64_t quotient;
uint64_t remainder;
for (int i = 0; i < count; i++) {
__asm__ __volatile__("divq %4" :
"=a"(quotient), "=d"(remainder) :
"a"(numeratorLo), "d"(numeratorHi), "r"(divisor) :
"cc");
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of calling a non-inlined function.
double functionCall()
{
int count = 1000000;
uint64_t x = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
x = PerfHelper::plusOne(x);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of calling ThreadId::get.
double getThreadId()
{
int count = 1000000;
int64_t result = 0;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
result += ThreadId::get();
}
uint64_t stop = Cycles::rdtsc();
// printf("Result: %d\n", downCast<int>(result));
return Cycles::toSeconds(stop - start)/count;
}
// Measure hash table lookup performance. Prefetching can
// be enabled to measure its effect. This test is a lot
// slower than the others (takes several seconds) due to the
// set up cost, but we really need a large hash table to
// avoid caching.
template<int prefetchBucketAhead = 0>
double hashTableLookup()
{
uint64_t numBuckets = 16777216; // 16M * 64 = 1GB
uint32_t numLookups = 1000000;
HashTable hashTable(numBuckets);
HashTable::Candidates candidates;
// fill with some objects to look up (enough to blow caches)
for (uint64_t i = 0; i < numLookups; i++) {
uint64_t* object = new uint64_t(i);
uint64_t reference = reinterpret_cast<uint64_t>(object);
Key key(0, object, downCast<uint16_t>(sizeof(*object)));
hashTable.insert(key.getHash(), reference);
}
PerfHelper::flushCache();
// now look up the objects again
uint64_t start = Cycles::rdtsc();
for (uint64_t i = 0; i < numLookups; i++) {
if (prefetchBucketAhead) {
if (i + prefetchBucketAhead < numLookups) {
uint64_t object = i + prefetchBucketAhead;
Key key(0, &object, downCast<uint16_t>(sizeof(object)));
hashTable.prefetchBucket(key.getHash());
}
}
Key key(0, &i, downCast<uint16_t>(sizeof(i)));
hashTable.lookup(key.getHash(), candidates);
while (!candidates.isDone()) {
if (*reinterpret_cast<uint64_t*>(candidates.getReference()) == i)
break;
candidates.next();
}
}
uint64_t stop = Cycles::rdtsc();
// clean up
for (uint64_t i = 0; i < numLookups; i++) {
Key key(0, &i, downCast<uint16_t>(sizeof(i)));
hashTable.lookup(key.getHash(), candidates);
while (!candidates.isDone()) {
if (*reinterpret_cast<uint64_t*>(candidates.getReference()) == i) {
delete reinterpret_cast<uint64_t*>(candidates.getReference());
candidates.remove();
break;
}
}
}
return Cycles::toSeconds((stop - start) / numLookups);
}
// Measure the cost of an lfence instruction.
double lfence()
{
int count = 1000000;
Dispatch dispatch(false);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Fence::lfence();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of creating and deleting a Dispatch::Lock from within
// the dispatch thread.
double lockInDispThrd()
{
int count = 1000000;
Dispatch dispatch(false);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Dispatch::Lock lock(&dispatch);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of creating and deleting a Dispatch::Lock from a thread
// other than the dispatch thread (best case: the dispatch thread has no
// pollers).
void dispatchThread(Dispatch **d, volatile int* flag)
{
bindThreadToCpu(2);
Dispatch dispatch(true);
*d = &dispatch;
dispatch.poll();
*flag = 1;
while (*flag == 1)
dispatch.poll();
}
double lockNonDispThrd()
{
int count = 100000;
volatile int flag = 0;
// Start a new thread and wait for it to create a dispatcher.
Dispatch* dispatch;
std::thread thread(dispatchThread, &dispatch, &flag);
while (flag == 0) {
usleep(100);
}
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Dispatch::Lock lock(dispatch);
}
uint64_t stop = Cycles::rdtsc();
flag = 0;
thread.join();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of copying a given number of bytes with memcpy.
double memcpyShared(size_t size)
{
int count = 1000000;
char src[size], dst[size];
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
memcpy(dst, src, size);
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
double memcpy100()
{
return memcpyShared(100);
}
double memcpy1000()
{
return memcpyShared(1000);
}
double memcpy10000()
{
return memcpyShared(10000);
}
// Benchmark MurmurHash3 hashing performance on cached data.
// Uses the version generating 128-bit hashes with code
// optimised for 64-bit processors.
template <int keyLength>
double murmur3()
{
int count = 100000;
char buf[keyLength];
uint32_t seed = 11051955;
uint64_t out[2];
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++)
MurmurHash3_x64_128(buf, sizeof(buf), seed, &out);
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Starting with a new ObjectPool, measure the cost of Object
// allocations. The pool may optionally be primed first to
// measure the best-case performance.
template <typename T, bool primeFirst>
double objectPoolAlloc()
{
int count = 100000;
T* toDestroy[count];
ObjectPool<T> pool;
if (primeFirst) {
for (int i = 0; i < count; i++) {
toDestroy[i] = pool.construct();
}
for (int i = 0; i < count; i++) {
pool.destroy(toDestroy[i]);
}
}
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
toDestroy[i] = pool.construct();
}
uint64_t stop = Cycles::rdtsc();
// clean up
for (int i = 0; i < count; i++) {
pool.destroy(toDestroy[i]);
}
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of the Cylcles::toNanoseconds method.
double perfCyclesToNanoseconds()
{
int count = 1000000;
std::atomic_int value(11);
uint64_t total = 0;
uint64_t cycles = 994261;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
total += Cycles::toNanoseconds(cycles);
}
uint64_t stop = Cycles::rdtsc();
// printf("Result: %lu\n", total/count);
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of the Cycles::toSeconds method.
double perfCyclesToSeconds()
{
int count = 1000000;
std::atomic_int value(11);
double total = 0;
uint64_t cycles = 994261;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
total += Cycles::toSeconds(cycles);
}
uint64_t stop = Cycles::rdtsc();
// printf("Result: %.4f\n", total/count);
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of the prefetch instruction.
double prefetch()
{
uint64_t totalTicks = 0;
int count = 10;
char buf[16 * 64];
for (int i = 0; i < count; i++) {
PerfHelper::flushCache();
CycleCounter<uint64_t> ticks(&totalTicks);
prefetch(&buf[576], 64);
prefetch(&buf[0], 64);
prefetch(&buf[512], 64);
prefetch(&buf[960], 64);
prefetch(&buf[640], 64);
prefetch(&buf[896], 64);
prefetch(&buf[256], 64);
prefetch(&buf[704], 64);
prefetch(&buf[320], 64);
prefetch(&buf[384], 64);
prefetch(&buf[128], 64);
prefetch(&buf[448], 64);
prefetch(&buf[768], 64);
prefetch(&buf[832], 64);
prefetch(&buf[64], 64);
prefetch(&buf[192], 64);
}
return Cycles::toSeconds(totalTicks) / count / 16;
}
// Measure the cost of reading the fine-grain cycle counter.
double rdtscTest()
{
int count = 1000000;
uint64_t start = Cycles::rdtsc();
uint64_t total = 0;
for (int i = 0; i < count; i++) {
total += Cycles::rdtsc();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Sorting functor for #segmentEntrySort.
struct SegmentEntryLessThan {
public:
bool
operator()(const std::pair<uint64_t, uint32_t> a,
const std::pair<uint64_t, uint32_t> b)
{
return a.second < b.second;
}
};
// Measure the time it takes to walk a Segment full of small objects,
// populate a vector with their entries, and sort it by age.
double segmentEntrySort()
{
Segment s;
const int avgObjectSize = 100;
char data[2 * avgObjectSize];
vector<std::pair<uint64_t, uint32_t>> entries;
int count;
for (count = 0; ; count++) {
uint32_t timestamp = static_cast<uint32_t>(generateRandom());
uint32_t size = timestamp % (2 * avgObjectSize);
Key key(0, &count, sizeof(count));
Buffer dataBuffer;
Object object(key, data, size, 0, timestamp, dataBuffer);
Buffer buffer;
object.assembleForLog(buffer);
if (!s.append(LOG_ENTRY_TYPE_OBJ, buffer))
break;
}
// doesn't appear to help
entries.reserve(count);
uint64_t start = Cycles::rdtsc();
// appears to take about 1/8th the time
for (SegmentIterator i(s); !i.isDone(); i.next()) {
if (i.getType() == LOG_ENTRY_TYPE_OBJ) {
uint64_t handle = 0; // fake pointer to object
Buffer buffer;
i.appendToBuffer(buffer);
Object object(buffer);
uint32_t timestamp = object.getTimestamp();
entries.push_back(std::pair<uint64_t, uint32_t>(handle, timestamp));
}
}
// the rest is, unsurprisingly, here
std::sort(entries.begin(), entries.end(), SegmentEntryLessThan());
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start);
}
// Measure the time it takes to iterate over the entries in
// a single Segment.
template<uint32_t minObjectBytes, uint32_t maxObjectBytes>
double segmentIterator()
{
uint64_t numObjects = 0;
uint64_t nextKeyVal = 0;
// build a segment
Segment segment;
while (1) {
uint32_t size = minObjectBytes;
if (minObjectBytes != maxObjectBytes) {
uint64_t rnd = generateRandom();
size += downCast<uint32_t>(rnd % (maxObjectBytes - minObjectBytes));
}
string stringKey = format("%lu", nextKeyVal++);
Key key(0, stringKey.c_str(), downCast<uint16_t>(stringKey.length()));
char data[size];
Buffer dataBuffer;
Object object(key, data, size, 0, 0, dataBuffer);
Buffer buffer;
object.assembleForLog(buffer);
if (!segment.append(LOG_ENTRY_TYPE_OBJ, buffer))
break;
numObjects++;
}
segment.close();
// scan through the segment
uint64_t totalBytes = 0;
uint64_t totalObjects = 0;
CycleCounter<uint64_t> counter;
SegmentIterator si(segment);
while (!si.isDone()) {
totalBytes += si.getLength();
totalObjects++;
si.next();
}
double time = Cycles::toSeconds(counter.stop());
return time;
}
// Measure the cost of incrementing and decrementing the reference count in
// a SessionRef.
double sessionRefCount()
{
int count = 1000000;
Transport::Session session;
Transport::SessionRef ref1(&session);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Transport::SessionRef ref2 = ref1;
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of an sfence instruction.
double sfence()
{
int count = 1000000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
Fence::sfence();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of acquiring and releasing a SpinLock (assuming the
// lock is initially free).
double spinLock()
{
int count = 1000000;
SpinLock lock;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
lock.lock();
lock.unlock();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Helper for spawnThread. This is the main function that the thread executes
// (intentionally empty).
void spawnThreadHelper()
{
}
// Measure the cost of start and joining with a thread.
double spawnThread()
{
int count = 10000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
std::thread thread(&spawnThreadHelper);
thread.join();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of starting and stopping a Dispatch::Timer.
double startStopTimer()
{
int count = 1000000;
Dispatch dispatch(false);
Dispatch::Timer timer(&dispatch);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
timer.start(12345U);
timer.stop();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of throwing and catching an int. This uses an integer as
// the value thrown, which is presumably as fast as possible.
double throwInt()
{
int count = 10000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
try {
throw 0;
} catch (int) { // NOLINT
// pass
}
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of throwing and catching an int from a function call.
double throwIntNL()
{
int count = 10000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
try {
PerfHelper::throwInt();
} catch (int) { // NOLINT
// pass
}
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of throwing and catching an Exception. This uses an actual
// exception as the value thrown, which may be slower than throwInt.
double throwException()
{
int count = 10000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
try {
throw ObjectDoesntExistException(HERE);
} catch (const ObjectDoesntExistException&) {
// pass
}
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of throwing and catching an Exception from a function call.
double throwExceptionNL()
{
int count = 10000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
try {
PerfHelper::throwObjectDoesntExistException();
} catch (const ObjectDoesntExistException&) {
// pass
}
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of throwing and catching an Exception using
// ClientException::throwException.
double throwSwitch()
{
int count = 10000;
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
try {
ClientException::throwException(HERE, STATUS_OBJECT_DOESNT_EXIST);
} catch (const ObjectDoesntExistException&) {
// pass
}
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/count;
}
// Measure the cost of pushing a new element on a std::vector, copying
// from the end to an internal element, and popping the end element.
double vectorPushPop()
{
int count = 100000;
std::vector<int> vector;
vector.push_back(1);
vector.push_back(2);
vector.push_back(3);
uint64_t start = Cycles::rdtsc();
for (int i = 0; i < count; i++) {
vector.push_back(i);
vector.push_back(i+1);
vector.push_back(i+2);
vector[2] = vector.back();
vector.pop_back();
vector[0] = vector.back();
vector.pop_back();
vector[1] = vector.back();
vector.pop_back();
}
uint64_t stop = Cycles::rdtsc();
return Cycles::toSeconds(stop - start)/(count*3);
}
// The following struct and table define each performance test in terms of
// a string name and a function that implements the test.
struct TestInfo {
const char* name; // Name of the performance test; this is
// what gets typed on the command line to
// run the test.
double (*func)(); // Function that implements the test;
// returns the time (in seconds) for each
// iteration of that test.
const char *description; // Short description of this test (not more
// than about 40 characters, so the entire
// test output fits on a single line).
};
TestInfo tests[] = {
{"atomicIntCmpX", atomicIntCmpX,
"Atomic<int>::compareExchange"},
{"atomicIntInc", atomicIntInc,
"Atomic<int>::inc"},
{"atomicIntLoad", atomicIntLoad,
"Atomic<int>::load"},
{"atomicIntStore", atomicIntStore,
"Atomic<int>::store"},
{"atomicIntXchg", atomicIntXchg,
"Atomic<int>::exchange"},
{"bMutexNoBlock", bMutexNoBlock,
"std::mutex lock/unlock (no blocking)"},
{"bufferBasic", bufferBasic,
"buffer create, add one chunk, delete"},
{"bufferBasicAlloc", bufferBasicAlloc,
"buffer create, alloc block in chunk, delete"},
{"bufferBasicCopy", bufferBasicCopy,
"buffer create, copy small block, delete"},
{"bufferCopy", bufferCopy,
"copy out 2 small chunks from buffer"},
{"bufferExtendChunk", bufferExtendChunk,
"buffer add onto existing chunk"},
{"bufferGetStart", bufferGetStart,
"Buffer::getStart"},
{"bufferIterator", bufferIterator,
"iterate over buffer with 5 chunks"},
{"condPingPong", condPingPong,
"std::condition_variable round-trip"},
{"cppAtomicExchg", cppAtomicExchange,
"Exchange method on a C++ atomic_int"},
{"cppAtomicLoad", cppAtomicLoad,
"Read a C++ atomic_int"},
{"cyclesToSeconds", perfCyclesToSeconds,
"Convert a rdtsc result to (double) seconds"},
{"cyclesToNanos", perfCyclesToNanoseconds,
"Convert a rdtsc result to (uint64_t) nanoseconds"},
{"dispatchPoll", dispatchPoll,
"Dispatch::poll (no timers or pollers)"},
{"div32", div32,
"32-bit integer division instruction"},
{"div64", div64,
"64-bit integer division instruction"},
{"functionCall", functionCall,
"Call a function that has not been inlined"},
{"getThreadId", getThreadId,
"Retrieve thread id via ThreadId::get"},
{"hashTableLookup", hashTableLookup,
"Key lookup in a 1GB HashTable"},
{"hashTableLookupPf", hashTableLookup<20>,
"Key lookup in a 1GB HashTable with prefetching"},
{"lfence", lfence,
"Lfence instruction"},
{"lockInDispThrd", lockInDispThrd,
"Acquire/release Dispatch::Lock (in dispatch thread)"},
{"lockNonDispThrd", lockNonDispThrd,
"Acquire/release Dispatch::Lock (non-dispatch thread)"},
{"memcpy100", memcpy100,
"Copy 100 bytes with memcpy"},
{"memcpy1000", memcpy1000,
"Copy 1000 bytes with memcpy"},
{"memcpy10000", memcpy10000,
"Copy 10000 bytes with memcpy"},
{"murmur3", murmur3<1>,
"128-bit MurmurHash3 (64-bit optimised) on 1 byte of data"},
{"murmur3", murmur3<256>,
"128-bit MurmurHash3 hash (64-bit optimised) on 256 bytes of data"},
{"objectPoolAlloc", objectPoolAlloc<int, false>,
"Cost of new allocations from an ObjectPool (no destroys)"},
{"objectPoolRealloc", objectPoolAlloc<int, true>,
"Cost of ObjectPool allocation after destroying an object"},
{"prefetch", prefetch,
"Prefetch instruction"},
{"rdtsc", rdtscTest,
"Read the fine-grain cycle counter"},
{"segmentEntrySort", segmentEntrySort,
"Sort a Segment full of avg. 100-byte Objects by age"},
{"segmentIterator", segmentIterator<50, 150>,
"Iterate a Segment full of avg. 100-byte Objects"},
#if 0 // Causes a double free.
{"sessionRefCount", sessionRefCount,
"Create/delete SessionRef"},
#endif
{"sfence", sfence,
"Sfence instruction"},
{"spinLock", spinLock,
"Acquire/release SpinLock"},
{"startStopTimer", startStopTimer,
"Start and stop a Dispatch::Timer"},
{"spawnThread", spawnThread,
"Start and stop a thread"},
{"throwInt", throwInt,
"Throw an int"},
{"throwIntNL", throwIntNL,
"Throw an int in a function call"},
{"throwException", throwException,
"Throw an Exception"},
{"throwExceptionNL", throwExceptionNL,
"Throw an Exception in a function call"},
{"throwSwitch", throwSwitch,
"Throw an Exception using ClientException::throwException"},
{"vectorPushPop", vectorPushPop,
"Push and pop a std::vector"},
};
/**
* Runs a particular test and prints a one-line result message.
*
* \param info
* Describes the test to run.
*/
void runTest(TestInfo& info)
{
double secs = info.func();
int width = printf("%-18s ", info.name);
if (secs < 1.0e-06) {
width += printf("%8.2fns", 1e09*secs);
} else if (secs < 1.0e-03) {
width += printf("%8.2fus", 1e06*secs);
} else if (secs < 1.0) {
width += printf("%8.2fms", 1e03*secs);
} else {
width += printf("%8.2fs", secs);
}
printf("%*s %s\n", 26-width, "", info.description);
}
int
main(int argc, char *argv[])
{
bindThreadToCpu(3);
if (argc == 1) {
// No test names specified; run all tests.
foreach (TestInfo& info, tests) {
runTest(info);
}
} else {
// Run only the tests that were specified on the command line.
for (int i = 1; i < argc; i++) {
bool foundTest = false;
foreach (TestInfo& info, tests) {
if (strcmp(argv[i], info.name) == 0) {
foundTest = true;
runTest(info);
break;
}
}
if (!foundTest) {
int width = printf("%-18s ??", argv[i]);
printf("%*s No such test\n", 26-width, "");
}
}
}
}
| 29.351064 | 80 | 0.608637 | [
"object",
"vector"
] |
c8d1837358f4e3489529e58c27e899e2e70ad3f5 | 19,884 | cpp | C++ | sample/so_5/news_board/main.cpp | sigman78/sobjectizer | d81c20a1264582e427a9a35d212361425fc34277 | [
"BSD-3-Clause"
] | 2 | 2018-04-14T16:16:47.000Z | 2019-04-15T06:47:58.000Z | sample/so_5/news_board/main.cpp | sigman78/sobjectizer | d81c20a1264582e427a9a35d212361425fc34277 | [
"BSD-3-Clause"
] | null | null | null | sample/so_5/news_board/main.cpp | sigman78/sobjectizer | d81c20a1264582e427a9a35d212361425fc34277 | [
"BSD-3-Clause"
] | null | null | null | /*
* An example for imitation of news board which handles requests from
* different types of clients: news-writers and news-readers.
*/
#if defined( _MSC_VER )
#if defined( __clang__ )
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <algorithm>
#include <chrono>
#include <ctime>
#include <iostream>
#include <iterator>
#include <list>
#include <random>
#include <tuple>
#include <so_5/all.hpp>
//
// Auxilary tools.
//
// Helper function to generate a random integer in the specified range.
unsigned int random_value( unsigned int left, unsigned int right )
{
std::random_device rd;
std::mt19937 gen{ rd() };
return std::uniform_int_distribution< unsigned int >{left, right}(gen);
}
// Imitation of some hard-working.
// Blocks the current thread for random amount of time.
void imitate_hard_work()
{
std::this_thread::sleep_for(
std::chrono::milliseconds{ random_value( 25, 125 ) } );
}
// Type of clock to work with time values.
using clock_type = std::chrono::system_clock;
// A helper function to calculate difference between to time points.
// The result is converted to string.
std::string ms_from_time( const clock_type::time_point & previous_point )
{
using namespace std::chrono;
const auto t = clock_type::now();
if( t > previous_point )
return std::to_string( duration_cast< milliseconds >(
clock_type::now() - previous_point ).count() ) + "ms";
else
return "0ms";
}
// A message for logging something.
struct msg_log
{
std::string m_who;
std::string m_what;
};
// A helper for logging simplification.
void log(
const so_5::mbox_t & logger_mbox,
std::string who,
std::string what )
{
so_5::send< msg_log >( logger_mbox, std::move(who), std::move(what) );
}
// Builder of logger agent.
so_5::mbox_t create_logger_coop( so_5::environment_t & env )
{
so_5::mbox_t result;
env.introduce_coop( [&]( so_5::coop_t & coop )
{
// Logger agent.
auto a = coop.define_agent();
// Reacts to just one message.
a.event( a, []( const msg_log & evt ) {
// String representation for date/time.
char local_time_sz[ 32 ];
auto t = clock_type::to_time_t( clock_type::now() );
std::strftime( local_time_sz, sizeof local_time_sz,
"%Y.%m.%d %H:%M:%S", std::localtime( &t ) );
// Simplest form of logging.
std::cout << "[" << local_time_sz << "] {" << evt.m_who
<< "}: " << evt.m_what << std::endl;
} );
// Direct mbox of logger agent will be returned.
result = a.direct_mbox();
} );
return result;
}
//
// Messages for interaction with news board.
//
// Type of story ID.
using story_id_type = unsigned long;
// Base class for all messages. It stores timestamp.
struct news_board_message_base : public so_5::message_t
{
// Time at which an operation was started.
// This time will be used for calculation of operation duration.
const clock_type::time_point m_timestamp;
news_board_message_base( clock_type::time_point timestamp )
: m_timestamp( std::move(timestamp) )
{}
};
// Base class for all request messages. It stores reply_to value.
struct news_board_request_base : public news_board_message_base
{
// Mbox of request initiator.
// Response will be sent to that mbox.
const so_5::mbox_t m_reply_to;
news_board_request_base(
clock_type::time_point timestamp,
so_5::mbox_t reply_to )
: news_board_message_base( std::move(timestamp) )
, m_reply_to( std::move(reply_to) )
{}
};
// Request for publishing new story.
struct msg_publish_story_req : public news_board_request_base
{
const std::string m_title;
const std::string m_content;
msg_publish_story_req(
clock_type::time_point timestamp,
so_5::mbox_t reply_to,
std::string title,
std::string content )
: news_board_request_base(
std::move(timestamp), std::move(reply_to) )
, m_title( std::move(title) )
, m_content( std::move(content) )
{}
};
// Reply for publishing new story.
struct msg_publish_story_resp : public news_board_message_base
{
story_id_type m_id;
msg_publish_story_resp(
clock_type::time_point timestamp,
story_id_type id )
: news_board_message_base( std::move(timestamp) )
, m_id( id )
{}
};
// Request for updates from news board.
struct msg_updates_req : public news_board_request_base
{
// Last known story ID.
story_id_type m_last_id;
msg_updates_req(
clock_type::time_point timestamp,
so_5::mbox_t reply_to,
story_id_type last_id )
: news_board_request_base(
std::move(timestamp), std::move(reply_to) )
, m_last_id( last_id )
{}
};
// Reply for request for updates.
struct msg_updates_resp : public news_board_message_base
{
// Type of new stories list.
using story_list = std::list< std::tuple< story_id_type, std::string > >;
// List of short info about new storis.
const story_list m_updates;
msg_updates_resp(
clock_type::time_point timestamp,
story_list updates )
: news_board_message_base( std::move(timestamp) )
, m_updates( std::move(updates) )
{}
};
// Request for content of the story.
struct msg_story_content_req : public news_board_request_base
{
// Story ID.
const story_id_type m_id;
msg_story_content_req(
clock_type::time_point timestamp,
so_5::mbox_t reply_to,
story_id_type id )
: news_board_request_base(
std::move(timestamp), std::move(reply_to) )
, m_id( id )
{}
};
// Positive response to a request for story content.
struct msg_story_content_resp_ack : public news_board_message_base
{
// Story content.
const std::string m_content;
msg_story_content_resp_ack(
clock_type::time_point timestamp,
std::string content )
: news_board_message_base( std::move(timestamp) )
, m_content( std::move(content) )
{}
};
// Negative response to a request for story content.
// This message is used when story was removed from the board.
struct msg_story_content_resp_nack : public news_board_message_base
{
msg_story_content_resp_nack(
clock_type::time_point timestamp )
: news_board_message_base( std::move(timestamp) )
{}
};
//
// News board data.
//
struct news_board_data
{
// Information about one story.
struct story_info
{
std::string m_title;
std::string m_content;
};
// Type of map from story ID to story data.
using story_map = std::map< story_id_type, story_info >;
// Published stories.
story_map m_stories;
// ID counter.
story_id_type m_last_id = 0;
};
//
// Agents to work with news board data.
//
// Agent for receiving and storing new stories to news board.
void define_news_receiver_agent(
so_5::coop_t & coop,
news_board_data & board_data,
const so_5::mbox_t & board_mbox,
const so_5::mbox_t & logger_mbox )
{
coop.define_agent(
// This agent should have lowest priority among
// board-related agents.
coop.make_agent_context() + so_5::prio::p1 )
// It handles just one message.
.event( board_mbox,
[&board_data, logger_mbox]( const msg_publish_story_req & evt )
{
// Store new story to board.
auto story_id = ++(board_data.m_last_id);
board_data.m_stories.emplace( story_id,
news_board_data::story_info{ evt.m_title, evt.m_content } );
// Log this fact.
log( logger_mbox,
"board.receiver",
"new story published, id=" + std::to_string( story_id ) +
", title=" + evt.m_title );
// Take some time for processing.
imitate_hard_work();
// Send reply to story-sender.
so_5::send< msg_publish_story_resp >(
evt.m_reply_to,
evt.m_timestamp,
story_id );
// Remove oldest story if there are too much stories.
if( 40 < board_data.m_stories.size() )
{
auto removed_id = board_data.m_stories.begin()->first;
board_data.m_stories.erase( board_data.m_stories.begin() );
log( logger_mbox,
"board.receiver",
"old story removed, id=" + std::to_string( removed_id ) );
}
} );
}
// Agent for handling requests about updates on news board.
void define_news_directory_agent(
so_5::coop_t & coop,
news_board_data & board_data,
const so_5::mbox_t & board_mbox,
const so_5::mbox_t & logger_mbox )
{
coop.define_agent(
// This agent should have priority higher than news_receiver.
coop.make_agent_context() + so_5::prio::p2 )
// It handles just one message.
.event( board_mbox,
[&board_data, logger_mbox]( const msg_updates_req & req )
{
log( logger_mbox,
"board.directory",
"request for updates received, last_id=" +
std::to_string( req.m_last_id ) );
// Take some time for processing.
imitate_hard_work();
// Searching for new stories for that request
// and building result list.
msg_updates_resp::story_list new_stories;
std::transform(
board_data.m_stories.upper_bound( req.m_last_id ),
std::end( board_data.m_stories ),
std::back_inserter( new_stories ),
[]( const news_board_data::story_map::value_type & v ) {
return std::make_tuple( v.first, v.second.m_title );
} );
log( logger_mbox,
"board.directory",
std::to_string( new_stories.size() ) + " new stories found" );
// Sending response.
so_5::send< msg_updates_resp >(
req.m_reply_to,
req.m_timestamp,
std::move(new_stories) );
} );
}
// Agent for handling requests for story content.
void define_story_extractor_agent(
so_5::coop_t & coop,
news_board_data & board_data,
const so_5::mbox_t & board_mbox,
const so_5::mbox_t & logger_mbox )
{
coop.define_agent(
// This agent should have priority higher that news_directory.
coop.make_agent_context() + so_5::prio::p3 )
// It handles just one message.
.event( board_mbox,
[&board_data, logger_mbox]( const msg_story_content_req & req )
{
log( logger_mbox,
"board.extractor",
"request for story content received, id=" +
std::to_string( req.m_id ) );
// Take some time for processing.
imitate_hard_work();
auto it = board_data.m_stories.find( req.m_id );
if( it != board_data.m_stories.end() )
{
log( logger_mbox,
"board.extractor",
"story {" + std::to_string( req.m_id ) + "} found" );
so_5::send< msg_story_content_resp_ack >(
req.m_reply_to,
req.m_timestamp,
it->second.m_content );
}
else
{
log( logger_mbox,
"board.extractor",
"story {" + std::to_string( req.m_id ) + "} NOT found" );
so_5::send< msg_story_content_resp_nack >(
req.m_reply_to,
req.m_timestamp );
}
} );
}
so_5::mbox_t create_board_coop(
so_5::environment_t & env,
const so_5::mbox_t & logger_mbox )
{
auto board_mbox = env.create_mbox();
using namespace so_5::disp::prio_one_thread::quoted_round_robin;
using namespace so_5::prio;
// Board cooperation will use quoted_round_robin dispatcher
// with different quotes for agents.
env.introduce_coop(
create_private_disp( env,
quotes_t{ 1 }
.set( p1, 10 ) // 10 events for news_receiver.
.set( p2, 20 ) // 20 events for news_directory.
.set( p3, 30 ) // 30 events for story_extractor.
)->binder(),
[&]( so_5::coop_t & coop )
{
// Lifetime of news board data will be controlled by cooperation.
auto board_data = coop.take_under_control( new news_board_data() );
define_news_receiver_agent(
coop, *board_data, board_mbox, logger_mbox );
define_news_directory_agent(
coop, *board_data, board_mbox, logger_mbox );
define_story_extractor_agent(
coop, *board_data, board_mbox, logger_mbox );
} );
return board_mbox;
}
//
// Story publishers.
//
class story_publisher : public so_5::agent_t
{
struct msg_time_for_new_story : public so_5::signal_t {};
public :
story_publisher(
context_t ctx,
std::string publisher_name,
so_5::mbox_t board_mbox,
so_5::mbox_t logger_mbox )
: so_5::agent_t( ctx )
, m_name( std::move(publisher_name) )
, m_board_mbox( std::move(board_mbox) )
, m_logger_mbox( std::move(logger_mbox) )
{}
virtual void so_define_agent() override
{
this >>= st_await_new_story;
st_await_new_story.event< msg_time_for_new_story >(
&story_publisher::evt_time_for_new_story );
st_await_publish_response.event(
&story_publisher::evt_publish_response );
}
virtual void so_evt_start() override
{
initiate_time_for_new_story_signal();
}
private :
// The agent will wait 'msg_time_for_new_story' signal in this state.
const state_t st_await_new_story{ this };
// The agent will wait a response to publising request in this state.
const state_t st_await_publish_response{ this };
const std::string m_name;
const so_5::mbox_t m_board_mbox;
const so_5::mbox_t m_logger_mbox;
// This counter will be used in store generation procedure.
unsigned int m_stories_counter = 0;
void initiate_time_for_new_story_signal()
{
so_5::send_delayed< msg_time_for_new_story >(
*this,
std::chrono::milliseconds{ random_value( 100, 1500 ) } );
}
void evt_time_for_new_story()
{
// Create new story.
auto story_number = ++m_stories_counter;
std::string title = "A story from " + m_name + " #" +
std::to_string( story_number );
std::string content = "This is a content from a story '" +
title + "' provided by " + m_name;
log( m_logger_mbox, m_name, "Publish new story: " + title );
// Publishing the story.
so_5::send< msg_publish_story_req >( m_board_mbox,
clock_type::now(),
so_direct_mbox(),
std::move(title),
std::move(content) );
// Waiting a response.
this >>= st_await_publish_response;
}
void evt_publish_response( const msg_publish_story_resp & resp )
{
log( m_logger_mbox, m_name, "Publish finished, id=" +
std::to_string( resp.m_id ) + ", publish took " +
ms_from_time( resp.m_timestamp ) );
// Waiting for a time for next story.
this >>= st_await_new_story;
initiate_time_for_new_story_signal();
}
};
void create_publisher_coop(
so_5::environment_t & env,
const so_5::mbox_t & board_mbox,
const so_5::mbox_t & logger_mbox )
{
// All publishers will work on the same working thread.
env.introduce_coop(
so_5::disp::one_thread::create_private_disp( env )->binder(),
[&]( so_5::coop_t & coop )
{
for( int i = 0; i != 5; ++i )
coop.make_agent< story_publisher >(
"publisher" + std::to_string(i+1),
board_mbox,
logger_mbox );
} );
}
//
// News readers.
//
class news_reader : public so_5::agent_t
{
struct msg_time_for_updates : public so_5::signal_t {};
public :
news_reader(
context_t ctx,
std::string reader_name,
so_5::mbox_t board_mbox,
so_5::mbox_t logger_mbox )
: so_5::agent_t( ctx )
, m_name( std::move(reader_name) )
, m_board_mbox( std::move(board_mbox) )
, m_logger_mbox( std::move(logger_mbox) )
{}
virtual void so_define_agent() override
{
this >>= st_sleeping;
st_sleeping.event< msg_time_for_updates >(
&news_reader::evt_time_for_updates );
st_await_updates.event(
&news_reader::evt_updates_received );
st_await_story_content.event(
&news_reader::evt_story_content );
st_await_story_content.event(
&news_reader::evt_story_not_found );
}
virtual void so_evt_start() override
{
initiate_time_for_updates_signal();
}
private :
// The agent will wait 'msg_time_for_updates' signal in this state.
const state_t st_sleeping{ this };
// The agent will wait updates from news board in this state.
const state_t st_await_updates{ this };
// The agent will wait story content in this state.
const state_t st_await_story_content{ this };
const std::string m_name;
const so_5::mbox_t m_board_mbox;
const so_5::mbox_t m_logger_mbox;
// ID of last received story from news board.
story_id_type m_last_id = 0;
// List a stories to be requested from news board.
msg_updates_resp::story_list m_stories_to_read;
void initiate_time_for_updates_signal()
{
so_5::send_delayed< msg_time_for_updates >(
*this,
std::chrono::milliseconds{ random_value( 500, 2500 ) } );
}
void evt_time_for_updates()
{
request_updates();
}
void evt_updates_received( const msg_updates_resp & resp )
{
log( m_logger_mbox,
m_name,
std::to_string( resp.m_updates.size() ) +
" updates received, took " +
ms_from_time( resp.m_timestamp ) );
if( resp.m_updates.empty() )
{
// Nothing new. We should sleep.
this >>= st_sleeping;
initiate_time_for_updates_signal();
}
else
{
this >>= st_await_story_content;
// Read no more than 3 latest stories.
unsigned int c = 0;
for( auto it = resp.m_updates.rbegin();
it != resp.m_updates.rend() && c != 3; ++it, ++c )
m_stories_to_read.push_front( *it );
request_story_content();
}
}
void evt_story_content( const msg_story_content_resp_ack & resp )
{
const auto & id = std::get<0>( *std::begin(m_stories_to_read) );
const auto & title = std::get<1>( *std::begin(m_stories_to_read) );
log( m_logger_mbox,
m_name,
"read story {" + std::to_string( id ) + "} '" +
title + "': \"" + resp.m_content + "\", took " +
ms_from_time( resp.m_timestamp ) );
remove_current_story_and_read_next();
}
void evt_story_not_found( const msg_story_content_resp_nack & resp )
{
const auto & id = std::get<0>( *std::begin(m_stories_to_read) );
const auto & title = std::get<1>( *std::begin(m_stories_to_read) );
log( m_logger_mbox,
m_name,
"unable to read story {" + std::to_string( id ) + "} '" +
title + "', took " + ms_from_time( resp.m_timestamp ) );
remove_current_story_and_read_next();
}
void request_updates()
{
log( m_logger_mbox,
m_name,
"requesting updates, last_id=" + std::to_string( m_last_id ) );
so_5::send< msg_updates_req >( m_board_mbox,
clock_type::now(),
so_direct_mbox(),
m_last_id );
this >>= st_await_updates;
}
void request_story_content()
{
auto id = std::get<0>( *std::begin(m_stories_to_read) );
log( m_logger_mbox,
m_name,
"requesting story {" + std::to_string( id ) + "}" );
so_5::send< msg_story_content_req >(
m_board_mbox,
clock_type::now(),
so_direct_mbox(),
id );
}
void remove_current_story_and_read_next()
{
m_last_id = std::get<0>( *std::begin(m_stories_to_read) );
m_stories_to_read.pop_front();
if( !m_stories_to_read.empty() )
request_story_content();
else
request_updates();
}
};
void create_reader_coop(
so_5::environment_t & env,
const so_5::mbox_t & board_mbox,
const so_5::mbox_t & logger_mbox )
{
// All readers will work on the same working thread.
env.introduce_coop(
so_5::disp::one_thread::create_private_disp( env )->binder(),
[&]( so_5::coop_t & coop )
{
for( int i = 0; i != 50; ++i )
coop.make_agent< news_reader >(
"reader" + std::to_string(i+1),
board_mbox,
logger_mbox );
} );
}
void init( so_5::environment_t & env )
{
auto logger_mbox = create_logger_coop( env );
auto board_mbox = create_board_coop( env, logger_mbox );
create_publisher_coop( env, board_mbox, logger_mbox );
create_reader_coop( env, board_mbox, logger_mbox );
}
int main()
{
try
{
so_5::launch( init );
return 0;
}
catch( const std::exception & x )
{
std::cerr << "Exception: " << x.what() << std::endl;
}
return 2;
}
| 25.992157 | 75 | 0.664253 | [
"transform"
] |
c8d31fd7211a6c8ef24915fd352a93299c34f460 | 1,038 | hpp | C++ | src/MultiLayerOptics/src/MultiPaneSampleData.hpp | bakonyidani/Windows-CalcEngine | afa4c4a9f88199c6206af8bc994a073931fc8b91 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/MultiLayerOptics/src/MultiPaneSampleData.hpp | bakonyidani/Windows-CalcEngine | afa4c4a9f88199c6206af8bc994a073931fc8b91 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/MultiLayerOptics/src/MultiPaneSampleData.hpp | bakonyidani/Windows-CalcEngine | afa4c4a9f88199c6206af8bc994a073931fc8b91 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #ifndef MultiLayerOpticsMEASUREDDATA_H
#define MultiLayerOpticsMEASUREDDATA_H
#include "WCESpectralAveraging.hpp"
namespace FenestrationCommon {
class CSeries;
}
namespace MultiLayerOptics {
// Contain multiple spectral data samples. It also calculates MultiLayerOptics properties (Transmittance,
// Front reflectance and back reflectance)
class CMultiPaneSampleData : public SpectralAveraging::CSpectralSampleData {
public:
CMultiPaneSampleData();
void addSample( const std::shared_ptr< CSpectralSampleData >& t_Sample );
std::shared_ptr< FenestrationCommon::CSeries > getLayerAbsorptances( size_t const Index );
std::vector< double > getWavelengths() const;
size_t numberOfLayers() const;
private:
void calculateProperties();
void interpolate( const std::vector< double >& t_Wavelengths );
void calculateEquivalentProperties();
std::vector< std::shared_ptr< CSpectralSampleData > > m_MeasuredSamples;
std::vector< std::shared_ptr< FenestrationCommon::CSeries > > m_LayerAbsorptances;
};
}
#endif
| 26.615385 | 106 | 0.783237 | [
"vector"
] |
c8d3f47e377f551d94f2bb93829646d2496c7aa4 | 6,529 | cxx | C++ | src/Cxx/Meshes/ClipFrustum.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Meshes/ClipFrustum.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Meshes/ClipFrustum.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | #include <vtkSmartPointer.h>
#include <vtkFrustumSource.h>
#include <vtkClipPolyData.h>
#include <vtkPlanes.h>
#include <vtkNamedColors.h>
#include <vtkPolyDataNormals.h>
#include <vtkBYUReader.h>
#include <vtkOBJReader.h>
#include <vtkPLYReader.h>
#include <vtkPolyDataReader.h>
#include <vtkSTLReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkSphereSource.h>
#include <vtksys/SystemTools.hxx>
#include <vtkProperty.h>
#include <vtkCamera.h>
#include <vtkMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkPolyDataMapper.h>
#include <vtkCamera.h>
namespace
{
vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fileName);
void PositionCamera(vtkSmartPointer<vtkRenderer> &renderer,
double *viewUp,
double *position);
}
int main (int argc, char *argv[])
{
vtkSmartPointer<vtkPolyData> polyData = ReadPolyData(argc > 1 ? argv[1] : "");;
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// a renderer and render window
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
// an interactor
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(polyData);
mapper->ScalarVisibilityOff();
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetDiffuseColor(colors->GetColor3d("Crimson").GetData());
actor->GetProperty()->SetSpecular(.6);
actor->GetProperty()->SetSpecularPower(30);
renderer->AddActor(actor);
vtkSmartPointer<vtkPolyDataMapper> outMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
outMapper->SetInputData(polyData);
outMapper->ScalarVisibilityOff();
vtkSmartPointer<vtkActor> outActor =
vtkSmartPointer<vtkActor>::New();
outActor->SetMapper(outMapper);
outActor->GetProperty()->SetDiffuseColor(colors->GetColor3d("Gold").GetData());
outActor->GetProperty()->SetSpecular(.6);
outActor->GetProperty()->SetSpecularPower(30);
// Position the camera so that we can see the frustum
double viewUp[3] = {0.0,1.0,0.0};
double position[3] = {1.0,0.0,0.0};
PositionCamera(renderer, viewUp, position);
renderer->GetActiveCamera()->Elevation(30);
renderer->GetActiveCamera()->SetViewAngle(10.0);
double planesArray[24];
renderer->GetActiveCamera()->GetFrustumPlanes(1.0, planesArray);
vtkSmartPointer<vtkPlanes> planes =
vtkSmartPointer<vtkPlanes>::New();
planes->SetFrustumPlanes(planesArray);
vtkSmartPointer<vtkFrustumSource> frustumSource =
vtkSmartPointer<vtkFrustumSource>::New();
frustumSource->ShowLinesOff();
frustumSource->SetPlanes(planes);
frustumSource->Update();
vtkSmartPointer<vtkPolyDataMapper> frustumMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
frustumMapper->SetInputConnection(frustumSource->GetOutputPort());
vtkSmartPointer<vtkActor> frustumActor =
vtkSmartPointer<vtkActor>::New();
frustumActor->SetMapper(frustumMapper);
frustumActor->GetProperty()->EdgeVisibilityOn();
frustumActor->GetProperty()->SetOpacity(.5);
frustumActor->GetProperty()->SetColor(colors->GetColor3d("Banana").GetData());
vtkSmartPointer<vtkClipPolyData> clip =
vtkSmartPointer<vtkClipPolyData>::New();
clip->SetInputData(polyData);
clip->SetClipFunction(planes);
clip->InsideOutOn();
clip->GenerateClippedOutputOn();
clip->Update();
mapper->SetInputConnection(clip->GetOutputPort());
outMapper->SetInputData(clip->GetClippedOutput());
renderer->SetBackground(colors->GetColor3d("Silver").GetData());
renderer->AddActor(frustumActor);
renderer->AddActor(outActor);
renderer->ResetCamera();
renderer->GetActiveCamera()->Azimuth(30);
renderer->GetActiveCamera()->Elevation(30);
renderer->GetActiveCamera()->Dolly(1.5);
renderer->ResetCameraClippingRange();
renderWindow->SetSize(640, 480);
renderWindow->Render();
// begin mouse interaction
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
// Snippets
namespace
{
vtkSmartPointer<vtkPolyData> ReadPolyData(const char *fileName)
{
vtkSmartPointer<vtkPolyData> polyData;
std::string extension = vtksys::SystemTools::GetFilenameExtension(std::string(fileName));
if (extension == ".ply")
{
vtkSmartPointer<vtkPLYReader> reader =
vtkSmartPointer<vtkPLYReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".vtp")
{
vtkSmartPointer<vtkXMLPolyDataReader> reader =
vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".obj")
{
vtkSmartPointer<vtkOBJReader> reader =
vtkSmartPointer<vtkOBJReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".stl")
{
vtkSmartPointer<vtkSTLReader> reader =
vtkSmartPointer<vtkSTLReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".vtk")
{
vtkSmartPointer<vtkPolyDataReader> reader =
vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else if (extension == ".g")
{
vtkSmartPointer<vtkBYUReader> reader =
vtkSmartPointer<vtkBYUReader>::New();
reader->SetGeometryFileName (fileName);
reader->Update();
polyData = reader->GetOutput();
}
else
{
vtkSmartPointer<vtkSphereSource> source =
vtkSmartPointer<vtkSphereSource>::New();
source->Update();
polyData = source->GetOutput();
}
return polyData;
}
void PositionCamera(vtkSmartPointer<vtkRenderer> &renderer,
double *viewUp,
double *position)
{
renderer->GetActiveCamera()->SetFocalPoint(0.0, 0.0, 0.0);
renderer->GetActiveCamera()->SetViewUp(viewUp);
renderer->GetActiveCamera()->SetPosition(position);
renderer->ResetCamera();
return;
}
}
| 30.087558 | 91 | 0.721244 | [
"render"
] |
c8d57c41a0fd1bb57e05a4e83ab96a5dedc7604b | 2,540 | cpp | C++ | data_structures/disjoint_set.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | data_structures/disjoint_set.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | data_structures/disjoint_set.cpp | dvijaymanohar/C-Plus-Plus | c987381c25858f08d0fe9301712ab6c1a10b433f | [
"MIT"
] | null | null | null | /**
*
* \file
* \brief [Disjoint Sets Data Structure
* (Disjoint Sets)](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)
*
* \author [leoyang429](https://github.com/leoyang429)
*
* \details
* A disjoint set data structure (also called union find or merge find set)
* is a data structure that tracks a set of elements partitioned into a number
* of disjoint (non-overlapping) subsets.
* Some situations where disjoint sets can be used are-
* to find connected components of a graph, kruskal's algorithm for finding
* Minimum Spanning Tree etc.
* There are two operation which we perform on disjoint sets -
* 1) Union
* 2) Find
*
*/
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
vector<int> root, rank;
/**
*
* Function to create a set
* @param n number of element
*
*/
void CreateSet(int n)
{
root = vector<int>(n + 1);
rank = vector<int>(n + 1, 1);
for (int i = 1; i <= n; ++i)
{
root[i] = i;
}
}
/**
*
* Find operation takes a number x and returns the set to which this number
* belongs to.
* @param x element of some set
* @return set to which x belongs to
*
*/
int Find(int x)
{
if (root[x] == x)
{
return x;
}
return root[x] = Find(root[x]);
}
/**
*
* A utility function to check if x and y are from same set or not
* @param x element of some set
* @param y element of some set
*
*/
bool InSameUnion(int x, int y) { return Find(x) == Find(y); }
/**
*
* Union operation combines two disjoint sets to make a single set
* in this union function we pass two elements and check if they are
* from different sets then combine those sets
* @param x element of some set
* @param y element of some set
*
*/
void Union(int x, int y)
{
int a = Find(x), b = Find(y);
if (a != b)
{
if (rank[a] < rank[b])
{
root[a] = b;
}
else if (rank[a] > rank[b])
{
root[b] = a;
}
else
{
root[a] = b;
++rank[b];
}
}
}
/** Main function */
int main()
{
// tests CreateSet & Find
int n = 100;
CreateSet(n);
for (int i = 1; i <= 100; ++i)
{
if (root[i] != i)
{
cout << "Fail" << endl;
break;
}
}
// tests InSameUnion & Union
cout << "1 and 2 are initially not in the same subset" << endl;
if (InSameUnion(1, 2))
{
cout << "Fail" << endl;
}
Union(1, 2);
cout << "1 and 2 are now in the same subset" << endl;
if (!InSameUnion(1, 2))
{
cout << "Fail" << endl;
}
return 0;
}
| 18.142857 | 78 | 0.588976 | [
"vector"
] |
c8d8bbe77166a7a2750eafd1e6bac97d916b2278 | 29,805 | cc | C++ | tests/unittests/unittests.cc | kacprzak/KTX-Software | ebc4b205e32090665d375bd9bee8559a85294b33 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-1-Clause",
"BSD-3-Clause"
] | null | null | null | tests/unittests/unittests.cc | kacprzak/KTX-Software | ebc4b205e32090665d375bd9bee8559a85294b33 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-1-Clause",
"BSD-3-Clause"
] | null | null | null | tests/unittests/unittests.cc | kacprzak/KTX-Software | ebc4b205e32090665d375bd9bee8559a85294b33 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-1-Clause",
"BSD-3-Clause"
] | null | null | null | /* -*- tab-width: 4; -*- */
/* vi: set sw=2 ts=4 expandtab: */
/*
* Copyright 2010-2020 Mark Callow.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @internal
* @file unittests.cc
* @~English
*
* @brief Tests of internal API functions.
*
* @author Mark Callow, Edgewise Consulting
*/
#if defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS
#if _MSC_VER < 1900
#define snprintf _snprintf
#endif
#endif
#include <string.h>
#include "GL/glcorearb.h"
#include "gl_format.h"
#include "ktx.h"
extern "C" {
#include "ktxint.h"
#include "filestream.h"
#include "memstream.h"
}
#include "gtest/gtest.h"
#include "wthelper.h"
#include "ltexceptions.h"
// These are so we can test swizzle_to_rgba. Do not put inside "namespace {"
// as there is no "namespace {" in basis_encode.cpp where the function is
// defined.
enum swizzle_e {
R = 1,
G = 2,
B = 3,
A = 4,
ZERO = 5,
ONE = 6,
};
extern void
swizzle_to_rgba(uint8_t* rgbadst, uint8_t* rgbasrc, uint32_t src_len,
ktx_size_t image_size, swizzle_e swizzle[4]);
namespace {
///////////////////////////////////////////////////////////
// Test fixtures
///////////////////////////////////////////////////////////
//--------------------------------------------
// Fixture for CheckHeaderTest
//--------------------------------------------
class CheckHeader1Test : public ::testing::Test {
protected:
CheckHeader1Test() {
// Done this way rather than by using an initializer here
// so it will compile on VS 2008.
memcpy(testHeader.identifier, ktxId, sizeof(ktxId));
testHeader.endianness = 0x04030201;
testHeader.glType = GL_UNSIGNED_BYTE;
testHeader.glTypeSize = 1;
testHeader.glFormat = GL_RGBA;
testHeader.glInternalformat = GL_RGBA8;
testHeader.glBaseInternalformat = GL_RGBA8;
testHeader.pixelWidth = 16;
testHeader.pixelHeight = 16;
testHeader.pixelDepth = 16;
testHeader.numberOfArrayElements = 0;
testHeader.numberOfFaces = 1;
testHeader.numberOfMipLevels = 5;
testHeader.bytesOfKeyValueData = 0;
}
KTX_header testHeader;
public:
static ktx_uint8_t ktxId[12];
};
ktx_uint8_t CheckHeader1Test::ktxId[12] = {
0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
};
//--------------------------------------------
// Base fixture for WriterTestHelper tests.
//--------------------------------------------
template<typename component_type, ktx_uint32_t num_components,
GLenum internalformat>
class WriterTestHelperTestBase : public ::testing::Test {
public:
WriterTestHelperTestBase() { }
WriterTestHelper<component_type, num_components, internalformat> helper;
ktx_uint32_t numComponents() { return num_components; }
};
class WriterTestHelperRGBA8Test : public WriterTestHelperTestBase<GLubyte, 4, GL_RGBA8> { };
class WriterTestHelperRGB8Test : public WriterTestHelperTestBase<GLubyte, 3, GL_RGB8> { };
typedef WriterTestHelper<GLubyte, 4, GL_RGBA8>::createFlagBits createFlagBits;
//////////////////////////////
// CheckHeaderTest
//////////////////////////////
#if defined(DEBUG)
TEST_F(CheckHeader1Test, AssertsOnNullArguments) {
ASSERT_DEATH_IF_SUPPORTED(ktxCheckHeader1_(0, 0), "Assert*");
}
#endif
TEST_F(CheckHeader1Test, ValidatesIdentifier) {
KTX_supplemental_info suppInfo;
EXPECT_EQ(ktxCheckHeader1_(&testHeader, &suppInfo), KTX_SUCCESS);
testHeader.identifier[9] = 0;
EXPECT_EQ(ktxCheckHeader1_(&testHeader, &suppInfo), KTX_UNKNOWN_FILE_FORMAT);
}
TEST_F(CheckHeader1Test, DisallowsInvalidEndianness) {
KTX_supplemental_info suppInfo;
testHeader.endianness = 0;
EXPECT_EQ(ktxCheckHeader1_(&testHeader, &suppInfo), KTX_FILE_DATA_ERROR);
}
//////////////////////////////
// MemStreamTest
//////////////////////////////
TEST(MemStreamTest, Read) {
ktxStream stream;
const ktx_uint8_t* data = (ktx_uint8_t*)"28 bytes of rubbish to read.";
const size_t size = 28;
char readBuf[size];
ktxMemStream_construct_ro(&stream, data, size);
stream.read(&stream, readBuf, size);
EXPECT_EQ(memcmp(data, readBuf, size), 0);
ktxMemStream_destruct(&stream);
}
TEST(MemStreamTest, Write) {
ktxStream stream;
const ktx_uint8_t* data = (ktx_uint8_t*)"29 bytes of rubbish to write.";
const size_t count = 29;
size_t returnedCount;
ktx_uint8_t* returnedData;
ktxMemStream_construct(&stream, KTX_TRUE);
stream.write(&stream, data, 1, count);
stream.getsize(&stream, &returnedCount);
ktxMemStream_getdata(&stream, &returnedData);
EXPECT_EQ(returnedCount, count);
EXPECT_EQ(memcmp(data, returnedData, count), 0);
ktxMemStream_destruct(&stream);
}
TEST(MemStreamTest, WriteExpand) {
ktxStream stream;
const ktx_uint8_t* data = (ktx_uint8_t*)"29 bytes of rubbish to write.";
const ktx_uint8_t* data2 = (ktx_uint8_t*)" 26 more bytes of rubbish.";
const size_t count = 29;
const size_t count2 = 26;
size_t returnedCount;
ktx_uint8_t* returnedData;
ktxMemStream_construct(&stream, KTX_TRUE);
stream.write(&stream, data, 1, count);
stream.write(&stream, data2, 1, count2);
stream.getsize(&stream, &returnedCount);
EXPECT_EQ(returnedCount, count + count2);
ktxMemStream_getdata(&stream, &returnedData);
EXPECT_EQ(memcmp(data, returnedData, count), 0);
EXPECT_EQ(memcmp(data2, &returnedData[count], count2), 0);
ktxMemStream_destruct(&stream);
}
//////////////////////////////
// WriterTestHelper tests.
//////////////////////////////
TEST_F(WriterTestHelperRGB8Test, Construct2D) {
helper.resize(createFlagBits::eNone, 1, 1, 2, 32, 32, 1);
EXPECT_EQ(helper.images.size(), 1U);
EXPECT_EQ(helper.images[0].size(), 1U);
EXPECT_EQ(helper.images[0][0].size(), 1U);
EXPECT_EQ(helper.images[0][0][0].size(), 32 * 32 * 3U);
EXPECT_EQ(numComponents(), 3U);
}
TEST_F(WriterTestHelperRGB8Test, Construct3D) {
helper.resize(createFlagBits::eNone, 1, 1, 3, 32, 32, 32);
EXPECT_EQ(helper.images.size(), 1U);
EXPECT_EQ(helper.images[0].size(), 1U);
EXPECT_EQ(helper.images[0][0].size(), 32U);
EXPECT_EQ(helper.images[0][0][0].size(), (size_t)(32 * 32 * 3));
EXPECT_EQ(numComponents(), 3U);
}
/////////////////////////////////////
// Base fixture for createDFD tests.
/////////////////////////////////////
#include <KHR/khr_df.h>
#define LIBKTX // To make dfd.h not include vulkan/vulkan_core.h.
#include "dfdutils/dfd.h"
// Template for single plane formats.
template<ktx_uint32_t numComponents, ktx_uint32_t bytesPlane>
class createDFDTestBase : public ::testing::Test {
public:
struct sampleType {
uint32_t bitOffset: 16;
uint32_t bitLength: 8;
uint32_t channelType: 8; // Includes qualifiers
uint32_t samplePosition0: 8;
uint32_t samplePosition1: 8;
uint32_t samplePosition2: 8;
uint32_t samplePosition3: 8;
uint32_t lower;
uint32_t upper;
};
createDFDTestBase() {
expected.vendorId = KHR_DF_VENDORID_KHRONOS;
expected.descriptorType = KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT;
expected.versionNumber = KHR_DF_VERSIONNUMBER_1_3;
// sizeof is after template instantiation so BDFD already includes
// numComponents samples.
expected.descriptorBlockSize = sizeof(BDFD);
expected.bytesPlane0 = bytesPlane;
expected.bytesPlane1 = 0;
expected.bytesPlane2 = 0;
expected.bytesPlane3 = 0;
expected.bytesPlane4 = 0;
expected.bytesPlane5 = 0;
expected.bytesPlane6 = 0;
expected.bytesPlane7 = 0;
}
protected:
struct BDFD {
uint32_t vendorId: 17;
uint32_t descriptorType: 15;
uint32_t versionNumber: 16;
uint32_t descriptorBlockSize: 16;
uint32_t model: 8;
uint32_t primaries: 8;
uint32_t transfer: 8;
uint32_t flags: 8;
uint32_t texelBlockDimension0: 8;
uint32_t texelBlockDimension1: 8;
uint32_t texelBlockDimension2: 8;
uint32_t texelBlockDimension3: 8;
uint32_t bytesPlane0: 8;
uint32_t bytesPlane1: 8;
uint32_t bytesPlane2: 8;
uint32_t bytesPlane3: 8;
uint32_t bytesPlane4: 8;
uint32_t bytesPlane5: 8;
uint32_t bytesPlane6: 8;
uint32_t bytesPlane7: 8;
sampleType samples[numComponents];
} expected;
};
template<ktx_uint32_t numComponents, ktx_uint32_t bytesPlane>
class createDFDTestBaseUncomp : public createDFDTestBase<numComponents, bytesPlane> {
using typename createDFDTestBase<numComponents, bytesPlane>::sampleType;
public:
createDFDTestBaseUncomp() : createDFDTestBase<numComponents, bytesPlane>() {
expected.texelBlockDimension0 = 0;
expected.texelBlockDimension1 = 0;
expected.texelBlockDimension2 = 0;
expected.texelBlockDimension3 = 0;
}
void customize(ktx_uint8_t model,
ktx_uint8_t primaries, ktx_uint8_t transfer,
ktx_uint8_t flags,
std::initializer_list<sampleType> samples) {
expected.model = model;
expected.primaries = primaries;
expected.transfer = transfer;
expected.flags = flags;
uint32_t i = 0; // There's got to be some syntax for declaring this in the for
for (auto sample : samples ) {
expected.samples[i] = sample;
if (++i == numComponents)
break;
}
}
protected:
using createDFDTestBase<numComponents, bytesPlane>::expected;
};
template<ktx_uint32_t numComponents, ktx_uint32_t bytesPlane>
class createDFDTestBaseComp : public createDFDTestBase<numComponents, bytesPlane> {
using typename createDFDTestBase<numComponents, bytesPlane>::sampleType;
public:
createDFDTestBaseComp() : createDFDTestBase<numComponents, bytesPlane>() {
expected.texelBlockDimension3 = 0;
}
void customize(ktx_uint8_t model,
ktx_uint8_t primaries, ktx_uint8_t transfer,
ktx_uint8_t flags,
ktx_uint32_t dim0, ktx_uint32_t dim1, ktx_uint32_t dim2,
std::initializer_list<sampleType> samples) {
expected.model = model;
expected.primaries = primaries;
expected.transfer = transfer;
expected.flags = flags;
expected.texelBlockDimension0 = dim0;
expected.texelBlockDimension1 = dim1;
expected.texelBlockDimension2 = dim2;
uint32_t i = 0; // There's got to be some syntax for declaring this in the for
for (auto sample : samples ) {
expected.samples[i] = sample;
if (++i == numComponents)
break;
}
}
void customize(ktx_uint8_t model,
ktx_uint8_t primaries, ktx_uint8_t transfer,
ktx_uint8_t flags, ktx_uint32_t dim0, ktx_uint32_t dim1,
std::initializer_list<sampleType> samples) {
customize(model, primaries, transfer, flags, dim0, dim1, 0, samples);
}
protected:
using createDFDTestBase<numComponents, bytesPlane>::expected;
};
class createDFDUnpackedTest4 : public createDFDTestBaseUncomp<4, 4> { };
class createDFDUnpackedTest3 : public createDFDTestBaseUncomp<3, 3> { };
class createDFDPackedTest3 : public createDFDTestBaseUncomp<3, 2> { };
class createDFDCompressedTest1 : public createDFDTestBaseComp<1, 8> { };
class createDFDCompressedTest2 : public createDFDTestBaseComp<2, 16> { };
class createDFDCompressedTest1x16 : public createDFDTestBaseComp<1, 16> { };
//////////////////////////////
// createDFD tests.
//////////////////////////////
TEST_F(createDFDUnpackedTest4, FormatSRGBA8) {
customize(KHR_DF_MODEL_RGBSDA, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
{
{0, 7, KHR_DF_CHANNEL_RGBSDA_RED, 0, 0, 0, 0, 0, 255},
{8, 7, KHR_DF_CHANNEL_RGBSDA_GREEN, 0, 0, 0, 0, 0, 255},
{16, 7, KHR_DF_CHANNEL_RGBSDA_BLUE, 0, 0, 0, 0, 0, 255},
{24, 7, KHR_DF_CHANNEL_RGBSDA_ALPHA | KHR_DF_SAMPLE_DATATYPE_LINEAR,
0, 0, 0, 0, 0, 255}
}
);
uint32_t* dfd = createDFDUnpacked(KTX_FALSE, 4, 1, KTX_FALSE, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDUnpackedTest4, FormatSBGRA8) {
customize(KHR_DF_MODEL_RGBSDA, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
{
{0, 7, KHR_DF_CHANNEL_RGBSDA_BLUE, 0, 0, 0, 0, 0, 255},
{8, 7, KHR_DF_CHANNEL_RGBSDA_GREEN, 0, 0, 0, 0, 0, 255},
{16, 7, KHR_DF_CHANNEL_RGBSDA_RED, 0, 0, 0, 0, 0, 255},
{24, 7, KHR_DF_CHANNEL_RGBSDA_ALPHA | KHR_DF_SAMPLE_DATATYPE_LINEAR,
0, 0, 0, 0, 0, 255}
}
);
uint32_t* dfd = createDFDUnpacked(KTX_FALSE, 4, 1, KTX_TRUE, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDUnpackedTest4, FormatRGBA8) {
customize(KHR_DF_MODEL_RGBSDA, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
{
{0, 7, KHR_DF_CHANNEL_RGBSDA_RED, 0, 0, 0, 0, 0, 255},
{8, 7, KHR_DF_CHANNEL_RGBSDA_GREEN, 0, 0, 0, 0, 0, 255},
{16, 7, KHR_DF_CHANNEL_RGBSDA_BLUE, 0, 0, 0, 0, 0, 255},
{24, 7, KHR_DF_CHANNEL_RGBSDA_ALPHA, 0, 0, 0, 0, 0, 255}
}
);
uint32_t* dfd = createDFDUnpacked(KTX_FALSE, 4, 1, KTX_FALSE, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDUnpackedTest3, FormatSRGB8) {
customize(KHR_DF_MODEL_RGBSDA, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
{
{0, 7, KHR_DF_CHANNEL_RGBSDA_RED, 0, 0, 0, 0, 0, 255},
{8, 7, KHR_DF_CHANNEL_RGBSDA_GREEN, 0, 0, 0, 0, 0, 255},
{16, 7, KHR_DF_CHANNEL_RGBSDA_BLUE, 0, 0, 0, 0, 0, 255},
}
);
uint32_t* dfd = createDFDUnpacked(KTX_FALSE, 3, 1, KTX_FALSE, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDPackedTest3, FormatRGB565) {
customize(KHR_DF_MODEL_RGBSDA, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
{
{0, 4, KHR_DF_CHANNEL_RGBSDA_BLUE, 0, 0, 0, 0, 0, 31},
{5, 5, KHR_DF_CHANNEL_RGBSDA_GREEN, 0, 0, 0, 0, 0, 63},
{11, 4, KHR_DF_CHANNEL_RGBSDA_RED, 0, 0, 0, 0, 0, 31},
}
);
// In order from LSB.
int bits[] = {5, 6, 5, 0};
int channels[] = {
KHR_DF_CHANNEL_RGBSDA_BLUE,
KHR_DF_CHANNEL_RGBSDA_GREEN,
KHR_DF_CHANNEL_RGBSDA_RED,
0
};
uint32_t* dfd = createDFDPacked(KTX_FALSE, 3, bits, channels, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1, FormatETC1S_R8B8G8) {
customize(KHR_DF_MODEL_ETC1S, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_ETC1S_RGB , 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ETC1S, 4, 4, 1, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1, FormatETC1S_SR8B8G8) {
customize(KHR_DF_MODEL_ETC1S, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_ETC1S_RGB, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ETC1S, 4, 4, 1, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1, FormatETC2_R8B8G8) {
customize(KHR_DF_MODEL_ETC2, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_ETC2_COLOR, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ETC2_R8G8B8, 4, 4, 1, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest2, FormatETC2_R8G8B8A8) {
customize(KHR_DF_MODEL_ETC2, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_ETC2_ALPHA, 0, 0, 0, 0, 0, 0xFFFFFFFF},
{64, 63, KHR_DF_CHANNEL_ETC2_COLOR, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ETC2_R8G8B8A8, 4, 4, 1, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1, FormatETC2_SR8B8G8) {
customize(KHR_DF_MODEL_ETC2, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_ETC2_COLOR, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ETC2_R8G8B8, 4, 4, 1, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest2, FormatETC2_SR8G8B8A8) {
customize(KHR_DF_MODEL_ETC2, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_ETC2_ALPHA | KHR_DF_SAMPLE_DATATYPE_LINEAR,
0, 0, 0, 0, 0, 0xFFFFFFFF},
{64, 63, KHR_DF_CHANNEL_ETC2_COLOR, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ETC2_R8G8B8A8, 4, 4, 1, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1x16, FormatASTC_12x12_SRGB) {
customize(KHR_DF_MODEL_ASTC, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
11, 11,
{
{0, 127, KHR_DF_CHANNEL_ASTC_DATA, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ASTC, 12, 12, 1, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1x16, FormatASTC_10x5_SRGB) {
customize(KHR_DF_MODEL_ASTC, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_SRGB, KHR_DF_FLAG_ALPHA_STRAIGHT,
9, 4,
{
{0, 127, KHR_DF_CHANNEL_ASTC_DATA, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ASTC, 10, 5, 1, s_SRGB);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1x16, FormatASTC_5x4) {
customize(KHR_DF_MODEL_ASTC, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
4, 3,
{
{0, 127, KHR_DF_CHANNEL_ASTC_DATA, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ASTC, 5, 4, 1, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1x16, FormatASTC_10x8) {
customize(KHR_DF_MODEL_ASTC, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
9, 7,
{
{0, 127, KHR_DF_CHANNEL_ASTC_DATA, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ASTC, 10, 8, 1, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1x16, FormatASTC_3x3x3) {
customize(KHR_DF_MODEL_ASTC, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
2, 2, 2,
{
{0, 127, KHR_DF_CHANNEL_ASTC_DATA, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_ASTC, 3, 3, 3, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
TEST_F(createDFDCompressedTest1, FormatBC1) {
customize(KHR_DF_MODEL_BC1A, KHR_DF_PRIMARIES_BT709,
KHR_DF_TRANSFER_LINEAR, KHR_DF_FLAG_ALPHA_STRAIGHT,
3, 3,
{
{0, 63, KHR_DF_CHANNEL_BC1A_COLOR, 0, 0, 0, 0, 0, 0xFFFFFFFF},
}
);
uint32_t* dfd = createDFDCompressed(c_BC1_RGB, 4, 4, 1, s_UNORM);
EXPECT_EQ(*dfd, sizeof(expected) + 4U);
EXPECT_EQ(memcmp(&expected, dfd+1, sizeof(expected)), 0);
free(dfd);
}
//////////////////////////////
// HashListTest Fixture
//////////////////////////////
class HashListTest : public ::testing::Test {
protected:
HashListTest() : writerVal("HashListTest"), orientationVal("ruo") { }
void constructList(bool sort) {
KTX_error_code result;
ktxHashList_Construct(&head);
result = ktxHashList_AddKVPair(&head, KTX_WRITER_KEY,
(ktx_uint32_t)writerVal.length() + 1,
writerVal.c_str());
EXPECT_EQ(result, KTX_SUCCESS);
result = ktxHashList_AddKVPair(&head, KTX_ORIENTATION_KEY,
(ktx_uint32_t)orientationVal.length() + 1,
orientationVal.c_str());
EXPECT_EQ(result, KTX_SUCCESS);
if (sort) {
ktxHashList_Sort(&head);
sorted = true;
}
}
void checkList() {
compareList(head, sorted);
}
void compareList(ktxHashList list, bool isSorted) {
ktxHashListEntry* entry = list;
ktx_uint32_t entryCount = 0;
for (; entry != NULL; entry = ktxHashList_Next(entry)) {
char* key;
ktx_uint8_t* value;
ktx_uint32_t keyLen, valueLen;
entryCount++;
ktxHashListEntry_GetKey(entry, &keyLen, &key);
ktxHashListEntry_GetValue(entry, &valueLen, (void**)&value);
if (isSorted) {
switch (entryCount) {
case 1:
EXPECT_STREQ(key, KTX_ORIENTATION_KEY);
break;
case 2:
EXPECT_STREQ(key, KTX_WRITER_KEY);
break;
default:
break;
}
}
if (strcmp(key, KTX_ORIENTATION_KEY) == 0)
EXPECT_EQ(orientationVal.compare((char*)value), 0);
else if (strcmp(key, KTX_WRITER_KEY) == 0)
EXPECT_EQ(writerVal.compare((char*)value), 0);
else
EXPECT_TRUE(false);
}
EXPECT_EQ(entryCount, 2U);
}
ktxHashList head;
std::string writerVal;
std::string orientationVal;
bool sorted;
};
//////////////////////////////
// HashListTests
//////////////////////////////
TEST_F(HashListTest, ConstructSorted) {
constructList(true);
checkList();
}
TEST_F(HashListTest, ConstructCopy) {
ktxHashList copyHead;
constructList(true);
ktxHashList_ConstructCopy(©Head, head);
compareList(copyHead, true);
}
///////////////////////
// Swizzle test fixture
///////////////////////
template<ktx_uint32_t num_components, GLenum internalformat>
class SwizzleTestBase : public ::testing::Test {
public:
SwizzleTestBase() {
std::vector<GLubyte> color;
// Use swizzle enumerator values for easy checking of result.
std::vector<GLubyte> defaultColor = { R, G, B, A };
color.resize(num_components);
for (uint32_t i = 0; i < num_components; i++) {
color[i] = defaultColor[i];
}
helper.resize(createFlagBits::eNone, 1, 1, 2, width, height, 1, &color);
}
void runTest(swizzle_e swizzle[4]) {
ktxTexture2* texture;
ktx_error_code_e result;
helper.texinfo.vkFormat
= vkGetFormatFromOpenGLInternalFormat(helper.texinfo.glInternalformat);
result = ktxTexture2_Create(&helper.texinfo,
KTX_TEXTURE_CREATE_ALLOC_STORAGE,
&texture);
ASSERT_TRUE(result == KTX_SUCCESS);
ASSERT_TRUE(texture != NULL) << "ktxTexture_CreateFromMemory failed: "
<< ktxErrorString(result);
ASSERT_TRUE(texture->pData != NULL) << "Image stoage not allocated";
result = helper.copyImagesToTexture(ktxTexture(texture));
ASSERT_TRUE(result == KTX_SUCCESS);
size_t destByteLen = width * height * 4 * sizeof(GLubyte);
size_t srcByteLen = width * height * num_components * sizeof(GLubyte);
typedef GLubyte color[4];
color* dest = (color*)malloc(destByteLen);
memset(dest, 0x7f, destByteLen);
swizzle_to_rgba((uint8_t*)dest,
texture->pData,
num_components,
srcByteLen,
swizzle);
for (uint32_t i = 0; i < width * height; i++) {
for (uint32_t c = 0; c < 4; c++) {
if (swizzle[c] == ZERO)
EXPECT_EQ(dest[i][c], 0);
else if (swizzle[c] == ONE)
EXPECT_EQ(dest[i][c], 255);
else
EXPECT_EQ(swizzle[c], dest[i][c]) << "c = " << c << ", i = " << i;
}
}
}
protected:
WriterTestHelper<GLubyte, num_components, internalformat> helper;
const unsigned int width = 16;
const unsigned int height = 16;
};
class SwizzleToRGBATestR8 : public SwizzleTestBase<1, GL_R8> { };
class SwizzleToRGBATestRG8 : public SwizzleTestBase<2, GL_RG8> { };
class SwizzleToRGBATestRGB8 : public SwizzleTestBase<3, GL_RGB8> { };
class SwizzleToRGBATestRGBA8 : public SwizzleTestBase<4, GL_RGBA8> { };
////////////////////////
// swizzle_to_rgba tests
////////////////////////
TEST_F(SwizzleToRGBATestR8, RRRONE) {
swizzle_e r_to_rgba_mapping[4] = { R, R, R, ONE };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRG8, RRRG) {
swizzle_e r_to_rgba_mapping[4] = { R, R, R, G };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGB8, RGBONE) {
swizzle_e r_to_rgba_mapping[4] = { R, G, B, ONE };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGB8, RRRG) {
swizzle_e r_to_rgba_mapping[4] = { R, R, R, G };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGBA8, RGBA) {
swizzle_e r_to_rgba_mapping[4] = { R, G, B, A };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGBA8, RRRG) {
swizzle_e r_to_rgba_mapping[4] = { R, R, R, G };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGBA8, BGRA) {
swizzle_e r_to_rgba_mapping[4] = { B, G, R, A };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGBA8, BGRZERO) {
swizzle_e r_to_rgba_mapping[4] = { B, G, R, ZERO };
runTest(r_to_rgba_mapping);
}
TEST_F(SwizzleToRGBATestRGBA8, ARGB) {
swizzle_e r_to_rgba_mapping[4] = { A, R, G, B };
runTest(r_to_rgba_mapping);
}
//////////////////////////////
// LoadTest exceptions tests
//////////////////////////////
#define OUT_OF_HOST_MEMORY -1
#define OUT_OF_DEVICE_MEMORY -2
#define FRAGMENTED_POOL -12
#define OUT_OF_POOL_MEMORY -1000069000
TEST(BadVulkanAllocExceptionTest, NoDeviceMemory) {
try {
throw bad_vulkan_alloc(OUT_OF_DEVICE_MEMORY, "no device memory test");
} catch (bad_vulkan_alloc& e) {
EXPECT_EQ(strcmp(e.what(), "Out of device memory for no device memory test."), 0);
}
}
TEST(BadVulkanAllocExceptionTest, NoHostMemory) {
try {
throw bad_vulkan_alloc(OUT_OF_HOST_MEMORY, "no host memory test");
} catch (bad_vulkan_alloc& e) {
EXPECT_EQ(strcmp(e.what(), "Out of host memory for no host memory test."), 0);
}
}
TEST(BadVulkanAllocExceptionTest, NoPoolMemory) {
try {
throw bad_vulkan_alloc(OUT_OF_POOL_MEMORY, "no pool memory test");
} catch (bad_vulkan_alloc& e) {
EXPECT_EQ(strcmp(e.what(), "Out of pool memory for no pool memory test."), 0);
}
}
TEST(BadVulkanAllocExceptionTest, PoolFragmented) {
try {
throw bad_vulkan_alloc(FRAGMENTED_POOL, "fragmented pool memory test");
} catch (bad_vulkan_alloc& e) {
EXPECT_EQ(strcmp(e.what(), "Pool fragmented when allocating for fragmented pool memory test."), 0);
}
}
} // namespace
| 31.979614 | 107 | 0.610837 | [
"vector",
"model"
] |
c8d98dff3742176e38a02742eabdb57afc7cb51b | 9,314 | cpp | C++ | examples/transformation.cpp | abhilashraju/GLplus | ae61c6e615ace5495bb6e7cddab84c159eb019be | [
"MIT"
] | null | null | null | examples/transformation.cpp | abhilashraju/GLplus | ae61c6e615ace5495bb6e7cddab84c159eb019be | [
"MIT"
] | null | null | null | examples/transformation.cpp | abhilashraju/GLplus | ae61c6e615ace5495bb6e7cddab84c159eb019be | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2021 abhilashraju
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "camwindow.h"
#include <fstream>
#include "glm/glm.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
using namespace gl;
int main(int argc, char* argv[])
{
CamWindow win(SCR_WIDTH, SCR_HEIGHT);
const char* vsource = R"(#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 acolor;
layout (location = 2) in vec2 texCord;
out vec3 fcolor;
out vec2 atextcord;
uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
void main()
{
gl_Position = projection* view * model * vec4(aPos.x, aPos.y, aPos.z, 1.0);
fcolor=acolor;
atextcord=texCord;
}
)";
const char* fsource = R"(#version 330 core
out vec4 FragColor;
uniform vec4 acolor;
uniform sampler2D texture1;
uniform sampler2D texture2;
in vec2 atextcord;
void main()
{
FragColor = mix(texture(texture1,atextcord),texture(texture2,atextcord),0.5);
}
)";
const char* fsource2 = R"(#version 330 core
out vec4 FragColor;
in vec3 fcolor;
void main()
{
FragColor = vec4(fcolor,1.0f);
}
)";
auto on_failure = [](const std::error_code& code,auto log) {
std::cout << code.message() << log << std::endl;
};
auto shaderProgram = make_programme(make_shader(vsource, GL_VERTEX_SHADER), make_shader(fsource, GL_FRAGMENT_SHADER))(on_failure);
auto shaderProgram2 = make_programme(make_shader(vsource, GL_VERTEX_SHADER), make_shader(fsource2, GL_FRAGMENT_SHADER))(on_failure);
std::array<float,288> vertices = {
-0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.f,0.f,0.f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.f,0.f,0.f, 0.0f, 1.0f
};
std::array<GLuint, 3> indices = { // note that we start from 0!
0, 1, 3, // first triangle
};
std::array<GLuint, 3> indices2 = { // note that we start from 0!
1, 2, 3 // second triangle
};
VBOS<2> vbo(GL_ARRAY_BUFFER);
VBOS<2> ebo(GL_ELEMENT_ARRAY_BUFFER);
VAOS<2> vao;
VTOS<2> vto(GL_TEXTURE_2D);
{
auto v = vao.bind(0);
auto b = vbo.bind(0);
auto t = vto.bind(0);
t.glTexParameteri( GL_TEXTURE_WRAP_S, GL_REPEAT);
t.glTexParameteri( GL_TEXTURE_WRAP_T, GL_REPEAT);
t.glTexParameteri( GL_TEXTURE_MIN_FILTER, GL_LINEAR);
t.glTexParameteri( GL_TEXTURE_MAG_FILTER, GL_LINEAR);
t.glTexImage2D(0, GL_RGB,GL_RGB, GL_UNSIGNED_BYTE,"./hand.jpg");
auto t2 = vto.bind(1);
t2.glTexParameteri(GL_TEXTURE_WRAP_S, GL_REPEAT);
t2.glTexParameteri(GL_TEXTURE_WRAP_T, GL_REPEAT);
t2.glTexParameteri(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
t2.glTexParameteri(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
t2.glTexImage2D(0, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, "./nature.jpg");
b.glBufferData(vertices, GL_STATIC_DRAW);
auto e = ebo.bind(0);
e.glBufferData(indices, GL_STATIC_DRAW);
v.glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 , 0);
v.glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8, 6);
}
win.setRenderCallback([&]() {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
std::array<glm::vec3, 5> cubes = {
glm::vec3{1,0,0},
glm::vec3{1,0,-2},
glm::vec3{2,-2,-3},
glm::vec3{-2,-4,-10},
glm::vec3{-1,-4,-7},
};
vao.bind(0).execute([&](auto&) {
glActiveTexture(GL_TEXTURE0);
auto t = vto.bind(0);
glActiveTexture(GL_TEXTURE1);
auto t2 = vto.bind(1);
shaderProgram.use();
shaderProgram.setUniform("acolor", 1.f, .1f,1.f,0.6f);
shaderProgram.setUniform("texture1", 0);
shaderProgram.setUniform("texture2", 1);
const float radius = 10.f;
float camX = sin(glfwGetTime()) * radius;
float camZ = cos(glfwGetTime()) * radius;
glm::mat4 view= win.cam.GetViewMatrix();
shaderProgram.setUniformMatrix4("view", 1, GL_FALSE, glm::value_ptr(view));
glm::mat4 projection;
projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
shaderProgram.setUniformMatrix4("projection", 1, GL_FALSE, glm::value_ptr(projection));
for (auto& v : cubes) {
auto model = glm::mat4(1.0f);
//model = glm::rotate(model, (float)glfwGetTime() * glm::radians(50.0f), glm::vec3(0.f, 1.f, 1.f));
model = glm::translate(model, v);
shaderProgram.setUniformMatrix4("model", 1, GL_FALSE, glm::value_ptr(model));
//glEnable(GL_DEPTH_TEST);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
});
});
win.exec();
glfwTerminate();
return 0;
}
| 41.580357 | 136 | 0.494632 | [
"model"
] |
c8de82ab8d5cb20e0f187c34cf0f6f3360af139d | 5,377 | cpp | C++ | bbp/src/uwsr/FEM/CompositeResponse.cpp | alborzgh/bbp | bc0cce2378aa071a5537d25c1a738e58ef610561 | [
"Apache-2.0"
] | null | null | null | bbp/src/uwsr/FEM/CompositeResponse.cpp | alborzgh/bbp | bc0cce2378aa071a5537d25c1a738e58ef610561 | [
"Apache-2.0"
] | null | null | null | bbp/src/uwsr/FEM/CompositeResponse.cpp | alborzgh/bbp | bc0cce2378aa071a5537d25c1a738e58ef610561 | [
"Apache-2.0"
] | 1 | 2018-11-12T23:10:02.000Z | 2018-11-12T23:10:02.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** Developed by: **
** Frank McKenna (fmckenna@ce.berkeley.edu) **
** Gregory L. Fenves (fenves@ce.berkeley.edu) **
** Filip C. Filippou (filippou@ce.berkeley.edu) **
** **
** ****************************************************************** */
// $Revision: 1.1 $
// $Date: 2010-05-13 00:15:36 $
// $Source: /usr/local/cvs/OpenSees/SRC/recorder/response/CompositeResponse.cpp,v $
// Written: fmk
// Created: 05/10
//
// Description: This file contains the CompositeResponse class interface.
// A CompositeResponse is a container holding a number of response objects.
#include <CompositeResponse.h>
#include <Vector.h>
#include <ID.h>
CompositeResponse::CompositeResponse(void)
:Response(), theResponses(0), numResponses(0)
{
}
CompositeResponse::~CompositeResponse()
{
for (int i=0; i<numResponses; i++)
delete theResponses[i];
delete [] theResponses;
}
int
CompositeResponse::addResponse(Response *nextResponse)
{
if (nextResponse == 0)
return 0;
//
// check valid type double, Vector, int, ID only
// resize theType accordiingly (vector or ID)
//
Information&otherType = nextResponse->getInformation();
if (otherType.theType == DoubleType ||
otherType.theType == VectorType) {
if (myInfo.theType == UnknownType) {
myInfo.theType = VectorType;
myInfo.theVector = new Vector();
}
if (myInfo.theType != VectorType) {
opserr << "WARNING: CompositeResponse::addResponse() - mismatching type, no responses will be addeed\n";
return -1;
}
int curSize = myInfo.theVector->Size();
if (otherType.theType == DoubleType)
curSize++;
else
curSize += otherType.theVector->Size();
myInfo.theVector->resize(curSize);
} else if (otherType.theType == IntType ||
otherType.theType == IdType) {
if (myInfo.theType == UnknownType) {
myInfo.theID = new ID();
myInfo.theType = IdType;
}
if (myInfo.theType != IdType) {
opserr << "WARNING: CompositeResponse::addResponse() - mismatching type, no responses will be addeed\n";
return -1;
}
int curSize = myInfo.theID->Size();
if (otherType.theType == IntType)
curSize++;
else
curSize += otherType.theID->Size();
myInfo.theID->resize(curSize);
}
//
// now add the response to the array
//
Response **theNextResponses = new Response *[numResponses+1];
if (theNextResponses == 0) {
opserr << "WARNING: CompositeResponse::addResponse() - out of memory, no responses will be added\n";
return -1;
}
for (int i=0; i<numResponses; i++)
theNextResponses[i] = theResponses[i];
if (theResponses != 0)
delete [] theResponses;
theResponses = theNextResponses;
theResponses[numResponses] = nextResponse;
numResponses++;
return numResponses;
}
int
CompositeResponse::getResponse(void)
{
int res = 0;
//
// invoke getResponse on all responses & add the data to myInfo
//
int currentLoc = 0;
for (int i=0; i<numResponses; i++) {
Response *theResponse = theResponses[i];
res += theResponse->getResponse();
Information&otherType = theResponse->getInformation();
if (otherType.theType == DoubleType || otherType.theType == VectorType) {
if (otherType.theType == DoubleType)
(*myInfo.theVector)(currentLoc++) = otherType.theDouble;
else {
int otherSize = otherType.theVector->Size();
for (int i=0; i<otherSize; i++, currentLoc++)
(*myInfo.theVector)(currentLoc) = (*otherType.theVector)(i);
}
} else if (otherType.theType == IntType || otherType.theType == IdType) {
if (otherType.theType == IntType) {
(*myInfo.theID)(currentLoc++) = otherType.theInt;
}
else {
int otherSize = otherType.theID->Size();
for (int i=0; i<otherSize; i++, currentLoc++)
(*myInfo.theID)(currentLoc) = (*otherType.theID)(i);
}
}
}
return res;
}
| 31.444444 | 111 | 0.530593 | [
"vector"
] |
c8e1ae4798ce577974ed453e291dd70f540b3234 | 1,574 | hpp | C++ | src/transpile/circuitopt.hpp | bytesalad/qiskit-aer | 63420bde7eccbd8181e12e0cc287e5a93090972b | [
"Apache-2.0"
] | null | null | null | src/transpile/circuitopt.hpp | bytesalad/qiskit-aer | 63420bde7eccbd8181e12e0cc287e5a93090972b | [
"Apache-2.0"
] | null | null | null | src/transpile/circuitopt.hpp | bytesalad/qiskit-aer | 63420bde7eccbd8181e12e0cc287e5a93090972b | [
"Apache-2.0"
] | null | null | null | /**
* This code is part of Qiskit.
*
* (C) Copyright IBM 2018, 2019.
*
* This code is licensed under the Apache License, Version 2.0. You may
* obtain a copy of this license in the LICENSE.txt file in the root directory
* of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
*
* Any modifications or derivative works of this code must retain this
* copyright notice, and modified files need to carry a notice indicating
* that they have been altered from the originals.
*/
#ifndef _aer_circuit_optimization_hpp_
#define _aer_circuit_optimization_hpp_
#include <chrono>
#include <cstdint>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include "framework/operations.hpp"
#include "noise/noise_model.hpp"
namespace AER {
namespace Transpile {
class CircuitOptimization {
public:
CircuitOptimization() = default;
virtual ~CircuitOptimization() = default;
virtual void optimize_circuit(Circuit& circ,
Noise::NoiseModel& noise,
const Operations::OpSet &opset,
ExperimentData &data) const = 0;
virtual void set_config(const json_t &config);
protected:
json_t config_;
};
void CircuitOptimization::set_config(const json_t& config) {
config_ = config;
}
//-------------------------------------------------------------------------
} // end namespace Transpile
} // end namespace AER
//-------------------------------------------------------------------------
#endif
| 26.233333 | 78 | 0.631512 | [
"vector"
] |
c8e2acbcbcf58f22e5fee0d5c7a13ea0e4d82c19 | 853 | cpp | C++ | src/omp_flush.cpp | ggrbill/omp-tutorial | 4518d3f442f68a1a9b97b9df6e519be97ea7ed62 | [
"MIT"
] | null | null | null | src/omp_flush.cpp | ggrbill/omp-tutorial | 4518d3f442f68a1a9b97b9df6e519be97ea7ed62 | [
"MIT"
] | null | null | null | src/omp_flush.cpp | ggrbill/omp-tutorial | 4518d3f442f68a1a9b97b9df6e519be97ea7ed62 | [
"MIT"
] | null | null | null | #include <iostream>
#include <omp.h>
#include <unistd.h> // usleep function
#include <vector>
int main()
{
int n_threads, thread_id;
int size = omp_get_max_threads();
std::vector<double> v(size), w(size), k(size);
std::fill(v.begin(), v.end(), 1.0);
std::fill(w.begin(), w.end(), 1.0);
std::fill(k.begin(), k.end(), 0.0);
double value{10.0};
// Fork a team of threads
#pragma omp parallel private(n_threads, thread_id) shared(v, w, k, value)
{
thread_id = omp_get_thread_num();
v[thread_id] += value;
w[thread_id] += value;
#pragma omp flush
#pragma omp for
for (int i = 0; i < size; i++)
{
k[i] = v[i] + w[i];
}
}
for (int i = 0; i < v.size(); i++)
std::cout << "k[" << i << "] = " << k[i] << std::endl;
} | 24.371429 | 77 | 0.506448 | [
"vector"
] |
c8e3600e7f8c48df175e78b86d86cb2096b845ac | 630 | cpp | C++ | 78.subsets.161111266.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 78.subsets.161111266.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 78.subsets.161111266.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
void util(vector<vector<int>> &ans,vector<int> temp,int index, vector<int> nums)
{
ans.push_back(temp);
if(index==nums.size())
{
return;
}
for(int i=index;i<nums.size();i++)
{
// util(ans,temp,i+1,nums);
temp.push_back(nums[i]);
util(ans,temp,i+1,nums);
temp.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> temp;
util(ans,temp,0,nums);
return ans;
}
};
| 22.5 | 84 | 0.465079 | [
"vector"
] |
c8e4c00a992bc120042386eaeb26b859bc2f4322 | 45,108 | cpp | C++ | server/api/src/rsDataObjRepl.cpp | Darleev/irods | 961555581469ba1d3e7da99c0bff7c15898b37e9 | [
"BSD-3-Clause"
] | null | null | null | server/api/src/rsDataObjRepl.cpp | Darleev/irods | 961555581469ba1d3e7da99c0bff7c15898b37e9 | [
"BSD-3-Clause"
] | null | null | null | server/api/src/rsDataObjRepl.cpp | Darleev/irods | 961555581469ba1d3e7da99c0bff7c15898b37e9 | [
"BSD-3-Clause"
] | null | null | null | #include "apiNumber.h"
#include "dataObjClose.h"
#include "dataObjCreate.h"
#include "dataObjGet.h"
#include "dataObjLock.h"
#include "dataObjOpen.h"
#include "dataObjOpr.hpp"
#include "dataObjPut.h"
#include "dataObjRepl.h"
#include "dataObjTrim.h"
#include "fileStageToCache.h"
#include "fileSyncToArch.h"
#include "getRemoteZoneResc.h"
#include "getRescQuota.h"
#include "icatDefines.h"
#include "l3FileGetSingleBuf.h"
#include "l3FilePutSingleBuf.h"
#include "miscServerFunct.hpp"
#include "objMetaOpr.hpp"
#include "physPath.hpp"
#include "resource.hpp"
#include "rodsLog.h"
#include "rsDataCopy.hpp"
#include "rsDataObjClose.hpp"
#include "rsDataObjCreate.hpp"
#include "rsDataObjGet.hpp"
#include "rsDataObjOpen.hpp"
#include "rsDataObjPut.hpp"
#include "rsDataObjRead.hpp"
#include "rsDataObjRepl.hpp"
#include "rsDataObjUnlink.hpp"
#include "rsDataObjWrite.hpp"
#include "rsFileStageToCache.hpp"
#include "rsFileSyncToArch.hpp"
#include "rsGetRescQuota.hpp"
#include "rsL3FileGetSingleBuf.hpp"
#include "rsL3FilePutSingleBuf.hpp"
#include "rsUnbunAndRegPhyBunfile.hpp"
#include "rsUnregDataObj.hpp"
#include "rs_replica_close.hpp"
#include "specColl.hpp"
#include "unbunAndRegPhyBunfile.h"
#include "finalize_utilities.hpp"
#include "irods_at_scope_exit.hpp"
#include "irods_log.hpp"
#include "irods_logger.hpp"
#include "irods_random.hpp"
#include "irods_resource_backport.hpp"
#include "irods_resource_redirect.hpp"
#include "irods_server_api_call.hpp"
#include "irods_server_properties.hpp"
#include "irods_stacktrace.hpp"
#include "irods_string_tokenize.hpp"
#include "json_serialization.hpp"
#include "key_value_proxy.hpp"
#include "replica_access_table.hpp"
#include "replication_utilities.hpp"
#include "voting.hpp"
#define IRODS_REPLICA_ENABLE_SERVER_SIDE_API
#include "data_object_proxy.hpp"
#include "replica_proxy.hpp"
#include "replica_state_table.hpp"
#include <algorithm>
#include <string_view>
#include <vector>
#include "fmt/format.h"
#include <boost/make_shared.hpp>
namespace
{
namespace ir = irods::experimental::replica;
namespace irv = irods::experimental::resource::voting;
namespace rst = irods::replica_state_table;
auto apply_static_peps(RsComm& _comm, l1desc& _l1desc, const int _operation_status) -> void
{
if (_l1desc.openType == CREATE_TYPE) {
irods::apply_static_post_pep(_comm, _l1desc, _operation_status, "acPostProcForCreate");
}
else if (_l1desc.openType == OPEN_FOR_WRITE_TYPE) {
irods::apply_static_post_pep(_comm, _l1desc, _operation_status, "acPostProcForOpen");
}
// Calling acPostProcForPut after replication is legacy behavior.
// Keep this here even though it is wrong.
irods::apply_static_post_pep(_comm, _l1desc, _operation_status, "acPostProcForPut");
} // apply_static_peps
auto finalize_source_replica(RsComm& _comm, l1desc& _l1desc, ir::replica_proxy_t& _info) -> int
{
if (_l1desc.purgeCacheFlag) {
irods::purge_cache(_comm, *_info.get());
}
irods::apply_metadata_from_cond_input(_comm, *_l1desc.dataObjInp);
irods::apply_acl_from_cond_input(_comm, *_l1desc.dataObjInp);
rst::erase(_info.data_id());
return 0;
} // finalize_source_replica
auto calculate_checksum(
RsComm& _comm,
l1desc& _l1desc,
ir::replica_proxy_t& _source_replica,
ir::replica_proxy_t& _destination_replica) -> std::string
{
if (!_destination_replica.checksum().empty()) {
_l1desc.chksumFlag = REG_CHKSUM;
}
char* checksum_string = nullptr;
irods::at_scope_exit free_checksum_string{[&checksum_string] { free(checksum_string); }};
if (_source_replica.checksum().length() > 0 && STALE_REPLICA != _source_replica.replica_status()) {
_destination_replica.cond_input()[ORIG_CHKSUM_KW] = _source_replica.checksum();
irods::log(LOG_DEBUG, fmt::format(
"[{}:{}] - verifying checksum for [{}],source:[{}]",
__FUNCTION__, __LINE__, _destination_replica.logical_path(), _source_replica.checksum()));
if (const int ec = _dataObjChksum(&_comm, _destination_replica.get(), &checksum_string); ec < 0) {
_destination_replica.checksum("");
if (DIRECT_ARCHIVE_ACCESS == ec) {
_destination_replica.checksum(_source_replica.checksum());
return _source_replica.checksum().data();
}
THROW(ec, fmt::format(
"{}: _dataObjChksum error for {}, status = {}",
__FUNCTION__, _destination_replica.logical_path(), ec));
}
if (!checksum_string) {
THROW(SYS_INTERNAL_NULL_INPUT_ERR, "checksum_string is NULL");
}
_destination_replica.checksum(checksum_string);
if (_source_replica.checksum() != checksum_string) {
THROW(USER_CHKSUM_MISMATCH, fmt::format(
"{}: chksum mismatch for {} src [{}] new [{}]",
__FUNCTION__, _destination_replica.logical_path(), _source_replica.checksum(), checksum_string));
}
return _destination_replica.checksum().data();
}
if (!_l1desc.chksumFlag) {
if (_destination_replica.checksum().empty()) {
return {};
}
_l1desc.chksumFlag = VERIFY_CHKSUM;
}
if (VERIFY_CHKSUM == _l1desc.chksumFlag) {
if (!std::string_view{_l1desc.chksum}.empty()) {
return irods::verify_checksum(_comm, *_destination_replica.get(), _l1desc.chksum);
}
if (!_destination_replica.checksum().empty()) {
_destination_replica.cond_input()[ORIG_CHKSUM_KW] = _destination_replica.checksum();
}
if (const int ec = _dataObjChksum(&_comm, _destination_replica.get(), &checksum_string); ec < 0) {
THROW(ec, "failed in _dataObjChksum");
}
if (!checksum_string) {
THROW(SYS_INTERNAL_NULL_INPUT_ERR, "checksum_string is NULL");
}
if (!_destination_replica.checksum().empty()) {
_destination_replica.cond_input().erase(ORIG_CHKSUM_KW);
/* for replication, the chksum in dataObjInfo was duplicated */
if (_destination_replica.checksum() != checksum_string) {
THROW(USER_CHKSUM_MISMATCH, fmt::format(
"{}:mismach chksum for {}.Rcat={},comp {}",
__FUNCTION__, _destination_replica.logical_path(), _destination_replica.checksum(), checksum_string));
}
}
return {checksum_string};
}
return irods::register_new_checksum(_comm, *_destination_replica.get(), _l1desc.chksum);
} // calculate_checksum
auto finalize_destination_replica(
RsComm& _comm,
l1desc& _l1desc,
ir::replica_proxy_t& _source_replica,
ir::replica_proxy_t& _destination_replica) -> int
{
auto cond_input = irods::experimental::make_key_value_proxy(_l1desc.dataObjInp->condInput);
try {
constexpr bool verify_size = true;
_destination_replica.size(irods::get_size_in_vault(_comm, *_destination_replica.get(), verify_size, _l1desc.dataSize));
if (!_destination_replica.checksum().empty()) {
const auto checksum = calculate_checksum(_comm, _l1desc, _source_replica, _destination_replica);
if (!checksum.empty()) {
cond_input[CHKSUM_KW] = checksum;
}
}
}
catch (const irods::exception& e) {
if (const int ec = irods::stale_replica(_comm, _l1desc, *_destination_replica.get()); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"{} - failed to stale replica [{}]",
__FUNCTION__, ec));
}
throw;
}
cond_input[OPEN_TYPE_KW] = std::to_string(_l1desc.openType);
_destination_replica.replica_status(_source_replica.replica_status());
_destination_replica.mtime(SET_TIME_TO_NOW_KW);
// This allows fileModified to trigger, but the resource plugins need to make sure the
// appropriate PDMO hierarchies are being checked to prevent infinite loops (e.g. replication
// resource triggering replication while performing a PDMO replication).
cond_input.erase(IN_REPL_KW);
// Write it out to the catalog
rst::update(_destination_replica.data_id(), _destination_replica);
const int ec = rst::publish_to_catalog(_comm,
_destination_replica.data_id(),
_destination_replica.replica_number(),
irods::to_json(cond_input.get()));
if (CREATE_TYPE == _l1desc.openType) {
updatequotaOverrun(_destination_replica.hierarchy().data(), _destination_replica.size(), ALL_QUOTA);
}
if (ec < 0) {
_l1desc.oprStatus = ec;
if (CATALOG_ALREADY_HAS_ITEM_BY_THAT_NAME != ec) {
l3Unlink(&_comm, _destination_replica.get());
}
irods::log(LOG_NOTICE, fmt::format(
"{}: RegReplica/ModDataObjMeta {} err. stat = {}",
__FUNCTION__, _destination_replica.logical_path(), ec));
}
if (rst::contains(_destination_replica.data_id())) {
rst::erase(_destination_replica.data_id());
}
return ec;
} // finalize_destination_replica
auto finalize_destination_replica_on_failure(RsComm& _comm, l1desc& _l1desc, ir::replica_proxy_t& _destination_replica) -> int
{
const rodsLong_t vault_size = getSizeInVault(&_comm, _destination_replica.get());
if (vault_size < 0) {
irods::log(LOG_ERROR, fmt::format(
"{} - getSizeInVault failed [{}]",
__FUNCTION__, vault_size));
return vault_size;
}
_destination_replica.replica_status(STALE_REPLICA);
_destination_replica.mtime(SET_TIME_TO_NOW_KW);
_destination_replica.size(vault_size);
// Write it out to the catalog
rst::update(_destination_replica.data_id(), _destination_replica);
const int ec = rst::publish_to_catalog(_comm,
_destination_replica.data_id(),
_destination_replica.replica_number(),
nlohmann::json{});
if (ec < 0) {
irods::log(LOG_ERROR, fmt::format("failed to publish to catalog:[{}]", ec));
}
return ec;
} // finalize_destination_replica_on_failure
auto get_replica_with_hierarchy(
RsComm& _comm,
irods::file_object_ptr _object,
const std::string_view _hierarchy,
const irods::replication::log_errors _log_errors) -> irods::physical_object&
{
auto maybe_replica = _object->get_replica(_hierarchy);
if (!maybe_replica) {
const std::string msg = fmt::format("no replica found with hierarchy [{}]", _hierarchy);
if (irods::replication::log_errors::yes == _log_errors) {
addRErrorMsg(&_comm.rError, SYS_REPLICA_DOES_NOT_EXIST, msg.data());
}
THROW(SYS_REPLICA_DOES_NOT_EXIST, fmt::format("[{}:{}] - [{}]", __FUNCTION__, __LINE__, msg));
}
return maybe_replica->get();
} // get_replica_with_hierarchy
auto resolve_hierarchy_and_get_data_object_info(
RsComm& _comm,
DataObjInp& _inp,
const std::string_view _operation) -> irods::file_object_ptr
{
auto cond_input = irods::experimental::make_key_value_proxy(_inp.condInput);
// Open for read operation is for source replica, so use RESC_HIER_STR_KW
// if that is the passed-in operation.
const std::string_view keyword = irods::OPEN_OPERATION == _operation ? RESC_HIER_STR_KW : DEST_RESC_HIER_STR_KW;
if (irods::experimental::keyword_has_a_value(_inp.condInput, keyword)) {
irods::file_object_ptr obj{new irods::file_object()};
if (irods::error err = irods::file_object_factory(&_comm, &_inp, obj); !err.ok()) {
THROW(err.code(), err.result());
}
if (irods::OPEN_OPERATION != _operation) {
cond_input[RESC_HIER_STR_KW] = cond_input.at(DEST_RESC_HIER_STR_KW);
}
return obj;
}
auto [obj, hier] = irods::resolve_resource_hierarchy(_operation.data(), &_comm, _inp);
cond_input[RESC_HIER_STR_KW] = hier;
if (irods::OPEN_OPERATION != _operation) {
cond_input[DEST_RESC_HIER_STR_KW] = cond_input.at(RESC_HIER_STR_KW);
}
return obj;
} // resolve_hierarchy_and_get_data_object_info
DataObjInp init_source_replica_input(RsComm& _comm, const DataObjInp& _inp)
{
DataObjInp source_data_obj_inp = _inp;
replKeyVal(&_inp.condInput, &source_data_obj_inp.condInput);
auto cond_input = irods::experimental::make_key_value_proxy(source_data_obj_inp.condInput);
// these keywords are used for destination resource, so remove them
cond_input.erase(DEST_RESC_NAME_KW);
cond_input.erase(DEST_RESC_HIER_STR_KW);
if (irods::experimental::keyword_has_a_value(_inp.condInput, RESC_NAME_KW) &&
irods::hierarchy_parser{cond_input.at(RESC_NAME_KW).value().data()}.num_levels() > 1) {
THROW(DIRECT_CHILD_ACCESS, fmt::format(
"specified resource [{}] is not a root resource",
cond_input.at(RESC_NAME_KW).value()));
}
return source_data_obj_inp;
} // init_source_replica_input
int open_source_replica(RsComm& _comm, DataObjInp& _inp)
{
_inp.oprType = REPLICATE_SRC;
_inp.openFlags = O_RDONLY;
return rsDataObjOpen(&_comm, &_inp);
} // open_source_replica
DataObjInp init_destination_replica_input(RsComm& _comm, const DataObjInp& _inp)
{
DataObjInp destination_inp = _inp;
replKeyVal(&_inp.condInput, &destination_inp.condInput);
auto cond_input = irods::experimental::make_key_value_proxy(destination_inp.condInput);
// these keywords are used for source resource, so remove them
cond_input.erase(RESC_NAME_KW);
cond_input.erase(RESC_HIER_STR_KW);
cond_input.erase(REPL_NUM_KW);
if (!irods::experimental::keyword_has_a_value(_inp.condInput, DEST_RESC_HIER_STR_KW) &&
!irods::experimental::keyword_has_a_value(_inp.condInput, DEST_RESC_NAME_KW) &&
irods::experimental::keyword_has_a_value(_inp.condInput, DEF_RESC_NAME_KW)) {
cond_input[DEST_RESC_NAME_KW] = cond_input.at(DEF_RESC_NAME_KW).value();
}
if (irods::experimental::keyword_has_a_value(_inp.condInput, DEST_RESC_NAME_KW) &&
irods::hierarchy_parser{cond_input.at(DEST_RESC_NAME_KW).value().data()}.num_levels() > 1) {
THROW(DIRECT_CHILD_ACCESS, fmt::format(
"specified resource [{}] is not a root resource",
cond_input.at(DEST_RESC_NAME_KW).value()));
}
return destination_inp;
} // init_destination_replica_input
int open_destination_replica(RsComm& _comm, DataObjInp& _inp, const int _source_fd)
{
auto cond_input = irods::experimental::make_key_value_proxy(_inp.condInput);
cond_input[REG_REPL_KW] = "";
cond_input[DATA_ID_KW] = std::to_string(L1desc[_source_fd].dataObjInfo->dataId);
cond_input.erase(PURGE_CACHE_KW);
_inp.oprType = REPLICATE_DEST;
_inp.openFlags = O_CREAT | O_WRONLY | O_TRUNC;
return rsDataObjOpen(&_comm, &_inp);
} // open_destination_replica
int replicate_data(RsComm& _comm, DataObjInp& _source_inp, DataObjInp& _destination_inp)
{
// Open source replica
int source_l1descInx = open_source_replica(_comm, _source_inp);
if (source_l1descInx < 0) {
return source_l1descInx;
}
auto& source_data_obj_info = *L1desc[source_l1descInx].dataObjInfo;
irods::log(LOG_DEBUG8, fmt::format(
"[{}:{}] - source:[{}]",
__FUNCTION__, __LINE__, source_data_obj_info.rescHier));
// Open destination replica
int destination_l1descInx = open_destination_replica(_comm, _destination_inp, source_l1descInx);
if (destination_l1descInx < 0) {
if (const int ec = irods::close_replica_without_catalog_update(_comm, source_l1descInx); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - failed to close source replica:[{}]",
__FUNCTION__, __LINE__, ec));
}
return destination_l1descInx;
}
auto& destination_data_obj_info = *L1desc[destination_l1descInx].dataObjInfo;
irods::log(LOG_DEBUG8, fmt::format(
"[{}:{}] - destination:[{}]",
__FUNCTION__, __LINE__, destination_data_obj_info.rescHier));
L1desc[destination_l1descInx].srcL1descInx = source_l1descInx;
L1desc[destination_l1descInx].dataSize = source_data_obj_info.dataSize;
// Copy data from source to destination
int status = dataObjCopy(&_comm, destination_l1descInx);
if (status < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - dataObjCopy failed for [{}], src:[{}], dest:[{}]; ec:[{}]",
__FUNCTION__, __LINE__,
_destination_inp.objPath,
source_data_obj_info.rescHier,
destination_data_obj_info.rescHier,
status));
L1desc[destination_l1descInx].bytesWritten = status;
}
else {
L1desc[destination_l1descInx].bytesWritten = destination_data_obj_info.dataSize;
}
// Save the token for the replica access table so that it can be removed
// in the event of a failure in close. On failure, the entry is restored,
// but this will prevent retries of the operation as the token information
// is lost by the time we have returned to the caller.
const auto token = L1desc[destination_l1descInx].replica_token;
auto source_fd = irods::duplicate_l1_descriptor(L1desc[source_l1descInx]);
auto destination_fd = irods::duplicate_l1_descriptor(L1desc[destination_l1descInx]);
irods::at_scope_exit free_fd{[&source_fd, &destination_fd]
{
freeL1desc_struct(source_fd);
freeL1desc_struct(destination_fd);
}
};
auto [source_replica, source_replica_lm] = ir::duplicate_replica(source_data_obj_info);
auto [destination_replica, destination_replica_lm] = ir::duplicate_replica(destination_data_obj_info);
// Close source replica
if (const int ec = irods::close_replica_without_catalog_update(_comm, source_l1descInx); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - closing source replica [{}] failed with [{}]",
__FUNCTION__, __LINE__, _source_inp.objPath, ec));
if (status >= 0) {
status = ec;
}
}
// Close destination replica
if (const int ec = irods::close_replica_without_catalog_update(_comm, destination_l1descInx); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - closing destination replica [{}] failed with [{}]",
__FUNCTION__, __LINE__, _destination_inp.objPath, ec));
if (status >= 0) {
status = ec;
}
irods::experimental::replica_access_table::erase_pid(token, getpid());
}
// finalize source replica
try {
if (const int ec = finalize_source_replica(_comm, source_fd, source_replica); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - closing source replica [{}] failed with [{}]",
__FUNCTION__, __LINE__, source_replica.logical_path(), ec));
if (status >= 0) {
status = ec;
}
}
}
catch (const irods::exception& e) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - error finalizing replica; [{}], ec:[{}]",
__FUNCTION__, __LINE__, e.what(), e.code()));
if (status >= 0) {
status = e.code();
}
}
if (destination_fd.bytesWritten < 0) {
if (const auto ec = finalize_destination_replica_on_failure(_comm, destination_fd, destination_replica); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}] - failed while finalizing object [{}]; ec:[{}]",
__FUNCTION__, destination_replica.logical_path(), ec));
}
return destination_fd.bytesWritten;
}
// finalize destination replica
try {
if (const int ec = finalize_destination_replica(_comm, destination_fd, source_replica, destination_replica); ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - closing destination replica [{}] failed with [{}]",
__FUNCTION__, __LINE__, destination_replica.logical_path(), ec));
if (status >= 0) {
status = ec;
}
}
}
catch (const irods::exception& e) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - error finalizing replica; [{}], ec:[{}]",
__FUNCTION__, __LINE__, e.what(), e.code()));
if (status >= 0) {
status = e.code();
}
}
// break here for lib
if (destination_fd.purgeCacheFlag > 0) {
irods::purge_cache(_comm, *destination_replica.get());
}
if (status >= 0) {
apply_static_peps(_comm, destination_fd, status);
}
return status;
} // replicate_data
int replicate_data_object(RsComm& _comm, const DataObjInp& _inp)
{
const auto cond_input = irods::experimental::make_key_value_proxy(_inp.condInput);
// get information about source replica
auto source_inp = init_source_replica_input(_comm, _inp);
const irods::at_scope_exit free_source_cond_input{[&source_inp]() { clearKeyVal(&source_inp.condInput); }};
auto source_cond_input = irods::experimental::make_key_value_proxy(source_inp.condInput);
auto source_obj = resolve_hierarchy_and_get_data_object_info(_comm, source_inp, irods::OPEN_OPERATION);
auto& source_replica = get_replica_with_hierarchy(
_comm, source_obj, source_cond_input.at(RESC_HIER_STR_KW).value(),
irods::replication::log_errors::yes);
// If the resolved resource hierarchy does not contain the specified
// resource name or replica number, that means the vote for that resource
// returned as 0.0. Either the replica is inaccessible or it does not exist.
if (irods::experimental::keyword_has_a_value(_inp.condInput, RESC_NAME_KW)) {
const auto resolved_hierarchy = source_cond_input.at(RESC_HIER_STR_KW).value();
const auto resource_name = source_cond_input.at(RESC_NAME_KW).value();
if (!irods::hierarchy_parser{resolved_hierarchy.data()}.resc_in_hier(resource_name.data())) {
THROW(SYS_REPLICA_INACCESSIBLE, fmt::format(
"hierarchy descending from specified source resource name [{}] "
"does not have a replica or the replica is inaccessible at this time",
resource_name));
}
}
else if (irods::experimental::keyword_has_a_value(_inp.condInput, REPL_NUM_KW)) {
if (const auto replica_number = std::stoi(source_cond_input.at(REPL_NUM_KW).value().data());
replica_number != source_replica.repl_num()) {
THROW(SYS_REPLICA_INACCESSIBLE, fmt::format(
"specified source replica number [{}] does not exist "
"or the replica is inaccessible at this time",
replica_number));
}
}
// get information about destination replica
auto destination_inp = init_destination_replica_input(_comm, _inp);
const irods::at_scope_exit free_destination_cond_input{[&destination_inp]() { clearKeyVal(&destination_inp.condInput); }};
auto destination_cond_input = irods::experimental::make_key_value_proxy(destination_inp.condInput);
auto destination_obj = resolve_hierarchy_and_get_data_object_info(_comm, destination_inp, irods::CREATE_OPERATION);
try {
if (irods::experimental::keyword_has_a_value(destination_inp.condInput, DEST_RESC_NAME_KW)) {
const auto resolved_hierarchy = destination_cond_input.at(DEST_RESC_HIER_STR_KW).value();
const auto resource_name = destination_cond_input.at(DEST_RESC_NAME_KW).value();
if (!irods::hierarchy_parser{resolved_hierarchy.data()}.resc_in_hier(resource_name.data())) {
THROW(SYS_REPLICA_INACCESSIBLE, fmt::format(
"hierarchy descending from specified destination resource name [{}] "
"does not have a replica or the replica is inaccessible at this time; "
"resolved hierarchy:[{}]",
resource_name, resolved_hierarchy.data()));
}
}
const auto& destination_replica = get_replica_with_hierarchy(
_comm, destination_obj, destination_cond_input.at(DEST_RESC_HIER_STR_KW).value(),
irods::replication::log_errors::no);
const auto log_errors = cond_input.contains(RECURSIVE_OPR__KW) ? irods::replication::log_errors::no : irods::replication::log_errors::yes;
if (!irods::replication::is_allowed(_comm, source_replica, destination_replica, log_errors)) {
return SYS_NOT_ALLOWED;
}
}
catch (const irods::exception& e) {
// If the destination replica doesn't exist, replication is always allowed.
if (SYS_REPLICA_DOES_NOT_EXIST != e.code()) {
throw;
}
}
irods::log(LOG_DEBUG8, fmt::format(
"[{}:{}] - source:[{}],destination:[{}]",
__FUNCTION__, __LINE__,
source_cond_input.at(RESC_HIER_STR_KW).value(),
destination_cond_input.at(RESC_HIER_STR_KW).value()));
// replicate!
const int ec = replicate_data(_comm, source_inp, destination_inp);
if (ec < 0) {
irods::log(LOG_ERROR, fmt::format(
"[{}:{}] - failed to replicate [{}]",
__FUNCTION__, __LINE__, _inp.objPath));
}
return ec;
} // replicate_data_object
int update_all_existing_replicas(RsComm& _comm, const dataObjInp_t& _inp)
{
// get information about source replica
auto source_inp = init_source_replica_input(_comm, _inp);
const irods::at_scope_exit free_source_cond_input{[&source_inp]() { clearKeyVal(&source_inp.condInput); }};
auto source_cond_input = irods::experimental::make_key_value_proxy(source_inp.condInput);
auto source_obj = resolve_hierarchy_and_get_data_object_info(_comm, source_inp, irods::OPEN_OPERATION);
auto& source_replica = get_replica_with_hierarchy(
_comm, source_obj, source_cond_input.at(RESC_HIER_STR_KW).value(),
irods::replication::log_errors::yes);
// If the resolved resource hierarchy does not contain the specified
// resource name or replica number, that means the vote for that resource
// returned as 0.0. Either the replica is inaccessible or it does not exist.
if (irods::experimental::keyword_has_a_value(_inp.condInput, RESC_NAME_KW)) {
const auto resolved_hierarchy = source_cond_input.at(RESC_HIER_STR_KW).value();
const auto resource_name = source_cond_input.at(RESC_NAME_KW).value();
if (!irods::hierarchy_parser{resolved_hierarchy.data()}.resc_in_hier(resource_name.data())) {
THROW(SYS_REPLICA_INACCESSIBLE, fmt::format(
"hierarchy descending from specified source resource name [{}] "
"does not have a replica or the replica is inaccessible at this time",
resource_name));
}
}
else if (irods::experimental::keyword_has_a_value(_inp.condInput, REPL_NUM_KW)) {
if (const auto replica_number = std::stoi(source_cond_input.at(REPL_NUM_KW).value().data());
replica_number != source_replica.repl_num()) {
THROW(SYS_REPLICA_INACCESSIBLE, fmt::format(
"specified source replica number [{}] does not exist "
"or the replica is inaccessible at this time",
replica_number));
}
}
// only good replica can be used as a source to update all other replicas
if (GOOD_REPLICA != source_replica.replica_status()) {
THROW(SYS_NOT_ALLOWED, fmt::format(
"source replica on [{}] has status [{}]; cannot be used to update other replicas.",
source_replica.resc_hier(), source_replica.replica_status()));
}
// get information about existing replicas (destination replicas)
auto destination_inp = init_destination_replica_input(_comm, _inp);
const irods::at_scope_exit free_destination_cond_input{[&destination_inp]() { clearKeyVal(&destination_inp.condInput); }};
auto destination_cond_input = irods::experimental::make_key_value_proxy(destination_inp.condInput);
auto destination_obj = resolve_hierarchy_and_get_data_object_info(_comm, destination_inp, irods::WRITE_OPERATION);
// replicate!
int status = 0;
for (const auto& destination_replica : destination_obj->replicas()) {
irods::log(LOG_DEBUG8, fmt::format(
"[{}:{}] - obj:[{}], source:[{}], destination:[{}], vote:[{}]",
__FUNCTION__, __LINE__,
destination_obj->logical_path(),
source_replica.resc_hier(),
destination_replica.resc_hier(),
destination_replica.vote()));
if (irods::replication::is_allowed(_comm, source_replica, destination_replica, irods::replication::log_errors::no) &&
destination_replica.vote() > irv::vote::zero) {
destination_cond_input[RESC_HIER_STR_KW] = destination_replica.resc_hier();
destination_cond_input[DEST_RESC_HIER_STR_KW] = destination_replica.resc_hier();
if (const int ec = replicate_data(_comm, source_inp, destination_inp);
ec < 0 && status >= 0) {
status = ec;
}
}
}
return status;
} // update_all_existing_replicas
int singleL1Copy(rsComm_t *rsComm, dataCopyInp_t& dataCopyInp)
{
int trans_buff_size;
try {
trans_buff_size = irods::get_advanced_setting<const int>(irods::CFG_TRANS_BUFFER_SIZE_FOR_PARA_TRANS) * 1024 * 1024;
} catch ( const irods::exception& e ) {
irods::log(e);
return e.code();
}
dataOprInp_t* dataOprInp = &dataCopyInp.dataOprInp;
int destL1descInx = dataCopyInp.portalOprOut.l1descInx;
int srcL1descInx = L1desc[destL1descInx].srcL1descInx;
openedDataObjInp_t dataObjReadInp{};
dataObjReadInp.l1descInx = srcL1descInx;
dataObjReadInp.len = trans_buff_size;
bytesBuf_t dataObjReadInpBBuf{};
dataObjReadInpBBuf.buf = malloc(dataObjReadInp.len);
dataObjReadInpBBuf.len = dataObjReadInp.len;
const irods::at_scope_exit free_data_obj_read_inp_bbuf{[&dataObjReadInpBBuf]() {
free(dataObjReadInpBBuf.buf);
}};
openedDataObjInp_t dataObjWriteInp{};
dataObjWriteInp.l1descInx = destL1descInx;
bytesBuf_t dataObjWriteInpBBuf{};
dataObjWriteInpBBuf.buf = dataObjReadInpBBuf.buf;
dataObjWriteInpBBuf.len = 0;
int bytesRead{};
rodsLong_t totalWritten = 0;
while ((bytesRead = rsDataObjRead(rsComm, &dataObjReadInp, &dataObjReadInpBBuf)) > 0) {
dataObjWriteInp.len = bytesRead;
dataObjWriteInpBBuf.len = bytesRead;
int bytesWritten = rsDataObjWrite(rsComm, &dataObjWriteInp, &dataObjWriteInpBBuf);
if (bytesWritten != bytesRead) {
rodsLog(LOG_ERROR,
"%s: Read %d bytes, Wrote %d bytes.\n ",
__FUNCTION__, bytesRead, bytesWritten );
return SYS_COPY_LEN_ERR;
}
totalWritten += bytesWritten;
}
if (dataOprInp->dataSize > 0 &&
!getValByKey(&dataOprInp->condInput, NO_CHK_COPY_LEN_KW) &&
totalWritten != dataOprInp->dataSize) {
rodsLog(LOG_ERROR,
"%s: totalWritten %lld dataSize %lld mismatch",
__FUNCTION__, totalWritten, dataOprInp->dataSize);
return SYS_COPY_LEN_ERR;
}
return 0;
} // singleL1Copy
} // anonymous namespace
int rsDataObjRepl( rsComm_t *rsComm, dataObjInp_t *dataObjInp, transferStat_t **transStat)
{
if (!rsComm || !dataObjInp) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
auto cond_input = irods::experimental::make_key_value_proxy(dataObjInp->condInput);
// -R and -a are not compatible
if (cond_input.contains(DEST_RESC_NAME_KW) && cond_input.contains(ALL_KW)) {
return USER_INCOMPATIBLE_PARAMS;
}
// -S and -n are not compatible
if (cond_input.contains(RESC_NAME_KW) && cond_input.contains(REPL_NUM_KW)) {
return USER_INCOMPATIBLE_PARAMS;
}
// Must be a privileged user to invoke SU
if (cond_input.contains(SU_CLIENT_USER_KW) &&
rsComm->proxyUser.authInfo.authFlag < REMOTE_PRIV_USER_AUTH) {
return CAT_INSUFFICIENT_PRIVILEGE_LEVEL;
}
// Resolve path in linked collection if applicable
dataObjInfo_t *dataObjInfo{};
const irods::at_scope_exit free_data_obj_info{[dataObjInfo]() {
freeAllDataObjInfo(dataObjInfo);
}};
int status = resolvePathInSpecColl( rsComm, dataObjInp->objPath,
READ_COLL_PERM, 0, &dataObjInfo );
if (status == DATA_OBJ_T && dataObjInfo && dataObjInfo->specColl) {
if (dataObjInfo->specColl->collClass != LINKED_COLL) {
return SYS_REG_OBJ_IN_SPEC_COLL;
}
rstrcpy(dataObjInp->objPath, dataObjInfo->objPath, MAX_NAME_LEN);
}
rodsServerHost_t *rodsServerHost{};
const int remoteFlag = getAndConnRemoteZone(rsComm, dataObjInp, &rodsServerHost, REMOTE_OPEN);
if ( remoteFlag < 0 ) {
return remoteFlag;
}
else if (remoteFlag == REMOTE_HOST) {
*transStat = (transferStat_t*)malloc(sizeof(transferStat_t));
memset(*transStat, 0, sizeof(transferStat_t));
status = _rcDataObjRepl(rodsServerHost->conn, dataObjInp, transStat);
return status;
}
try {
cond_input[IN_REPL_KW] = "";
const irods::at_scope_exit remove_in_repl{[&cond_input] { cond_input.erase(IN_REPL_KW); }};
if (cond_input.contains(ALL_KW)) {
status = update_all_existing_replicas(*rsComm, *dataObjInp);
}
else {
status = replicate_data_object(*rsComm, *dataObjInp);
}
}
catch (const irods::exception& e) {
irods::log(e);
addRErrorMsg(&rsComm->rError, e.code(), e.client_display_what());
status = e.code();
}
catch (const std::exception& e) {
irods::log(LOG_ERROR, fmt::format("[{}:{}] - [{}]", __FUNCTION__, __LINE__, e.what()));
status = SYS_INTERNAL_ERR;
}
catch (...) {
irods::log(LOG_ERROR, fmt::format("[{}:{}] - unknown error occurred", __FUNCTION__, __LINE__));
status = SYS_UNKNOWN_ERROR;
}
if (status < 0 && status != DIRECT_ARCHIVE_ACCESS) {
rodsLog(LOG_NOTICE, "%s - Failed to replicate data object. status:[%d]",
__FUNCTION__, status);
}
return (status == DIRECT_ARCHIVE_ACCESS) ? 0 : status;
} // rsDataObjRepl
int dataObjCopy(rsComm_t* rsComm, int _destination_l1descInx)
{
int source_l1descInx = L1desc[_destination_l1descInx].srcL1descInx;
if (source_l1descInx < 3) {
irods::log(LOG_ERROR, fmt::format(
"[{}] - source l1 descriptor out of range:[{}]",
__FUNCTION__, source_l1descInx));
return SYS_FILE_DESC_OUT_OF_RANGE;
}
int srcRemoteFlag{};
int srcL3descInx = L1desc[source_l1descInx].l3descInx;
if (L1desc[source_l1descInx].remoteZoneHost) {
srcRemoteFlag = REMOTE_ZONE_HOST;
}
else {
srcRemoteFlag = FileDesc[srcL3descInx].rodsServerHost->localFlag;
}
int destRemoteFlag{};
int destL3descInx = L1desc[_destination_l1descInx].l3descInx;
if (L1desc[_destination_l1descInx].remoteZoneHost) {
destRemoteFlag = REMOTE_ZONE_HOST;
}
else {
destRemoteFlag = FileDesc[destL3descInx].rodsServerHost->localFlag;
}
dataCopyInp_t dataCopyInp{};
const irods::at_scope_exit clear_cond_input{[&dataCopyInp]() {
clearKeyVal(&dataCopyInp.dataOprInp.condInput);
}};
portalOprOut_t* portalOprOut{};
if (srcRemoteFlag == REMOTE_ZONE_HOST &&
destRemoteFlag == REMOTE_ZONE_HOST) {
// Destination: remote zone
// Source: remote zone
initDataOprInp(&dataCopyInp.dataOprInp, _destination_l1descInx, COPY_TO_REM_OPR);
L1desc[_destination_l1descInx].dataObjInp->numThreads = 0;
dataCopyInp.portalOprOut.l1descInx = _destination_l1descInx;
return singleL1Copy(rsComm, dataCopyInp);
}
if (srcRemoteFlag != REMOTE_ZONE_HOST &&
destRemoteFlag != REMOTE_ZONE_HOST &&
FileDesc[srcL3descInx].rodsServerHost == FileDesc[destL3descInx].rodsServerHost) {
// Destination: local zone
// Source: local zone
// Source and destination host are the same
initDataOprInp( &dataCopyInp.dataOprInp, _destination_l1descInx, SAME_HOST_COPY_OPR );
dataCopyInp.portalOprOut.numThreads = dataCopyInp.dataOprInp.numThreads;
if ( srcRemoteFlag == LOCAL_HOST ) {
addKeyVal(&dataCopyInp.dataOprInp.condInput, EXEC_LOCALLY_KW, "");
}
}
else if (destRemoteFlag == REMOTE_ZONE_HOST ||
(srcRemoteFlag == LOCAL_HOST && destRemoteFlag != LOCAL_HOST)) {
// Destination: remote zone OR different host in local zone
// Source: local zone
initDataOprInp( &dataCopyInp.dataOprInp, _destination_l1descInx, COPY_TO_REM_OPR );
if ( L1desc[_destination_l1descInx].dataObjInp->numThreads > 0 ) {
int status = preProcParaPut( rsComm, _destination_l1descInx, &portalOprOut );
if (status < 0 || !portalOprOut) {
rodsLog(LOG_NOTICE,
"%s: preProcParaPut error for %s",
__FUNCTION__,
L1desc[source_l1descInx].dataObjInfo->objPath );
free( portalOprOut );
return status;
}
dataCopyInp.portalOprOut = *portalOprOut;
}
else {
dataCopyInp.portalOprOut.l1descInx = _destination_l1descInx;
}
if ( srcRemoteFlag == LOCAL_HOST ) {
addKeyVal( &dataCopyInp.dataOprInp.condInput, EXEC_LOCALLY_KW, "" );
}
}
else if (srcRemoteFlag == REMOTE_ZONE_HOST ||
(srcRemoteFlag != LOCAL_HOST && destRemoteFlag == LOCAL_HOST)) {
// Destination: local zone
// Source: remote zone OR different host in local zone
initDataOprInp( &dataCopyInp.dataOprInp, _destination_l1descInx, COPY_TO_LOCAL_OPR );
if ( L1desc[_destination_l1descInx].dataObjInp->numThreads > 0 ) {
int status = preProcParaGet( rsComm, source_l1descInx, &portalOprOut );
if (status < 0 || !portalOprOut) {
rodsLog(LOG_NOTICE,
"%s: preProcParaGet error for %s",
__FUNCTION__,
L1desc[source_l1descInx].dataObjInfo->objPath );
free( portalOprOut );
return status;
}
dataCopyInp.portalOprOut = *portalOprOut;
}
else {
dataCopyInp.portalOprOut.l1descInx = source_l1descInx;
}
if ( destRemoteFlag == LOCAL_HOST ) {
addKeyVal( &dataCopyInp.dataOprInp.condInput, EXEC_LOCALLY_KW, "" );
}
}
else {
/* remote to remote */
initDataOprInp( &dataCopyInp.dataOprInp, _destination_l1descInx, COPY_TO_LOCAL_OPR );
if (L1desc[_destination_l1descInx].dataObjInp->numThreads > 0) {
int status = preProcParaGet(rsComm, source_l1descInx, &portalOprOut);
if (status < 0 || !portalOprOut) {
rodsLog(LOG_NOTICE,
"%s: preProcParaGet error for %s",
__FUNCTION__,
L1desc[source_l1descInx].dataObjInfo->objPath );
free( portalOprOut );
return status;
}
dataCopyInp.portalOprOut = *portalOprOut;
}
else {
dataCopyInp.portalOprOut.l1descInx = source_l1descInx;
}
}
if (getValByKey(&L1desc[_destination_l1descInx].dataObjInp->condInput, NO_CHK_COPY_LEN_KW)) {
addKeyVal(&dataCopyInp.dataOprInp.condInput, NO_CHK_COPY_LEN_KW, "");
if (L1desc[_destination_l1descInx].dataObjInp->numThreads > 1) {
L1desc[_destination_l1descInx].dataObjInp->numThreads = 1;
L1desc[source_l1descInx].dataObjInp->numThreads = 1;
dataCopyInp.portalOprOut.numThreads = 1;
}
}
int status = rsDataCopy(rsComm, &dataCopyInp);
if (status >= 0 && portalOprOut && L1desc[_destination_l1descInx].dataObjInp) {
/* update numThreads since it could be changed by remote server */
L1desc[_destination_l1descInx].dataObjInp->numThreads = portalOprOut->numThreads;
}
free(portalOprOut);
return status;
} // dataObjCopy
int unbunAndStageBunfileObj(rsComm_t* rsComm, const char* bunfileObjPath, char** outCacheRescName) {
/* query the bundle dataObj */
dataObjInp_t dataObjInp{};
rstrcpy( dataObjInp.objPath, bunfileObjPath, MAX_NAME_LEN );
dataObjInfo_t *bunfileObjInfoHead{};
int status = getDataObjInfo( rsComm, &dataObjInp, &bunfileObjInfoHead, NULL, 1 );
if ( status < 0 ) {
rodsLog( LOG_ERROR,
"unbunAndStageBunfileObj: getDataObjInfo of bunfile %s failed.stat=%d",
dataObjInp.objPath, status );
return status;
}
status = _unbunAndStageBunfileObj( rsComm, &bunfileObjInfoHead, &dataObjInp.condInput,
outCacheRescName, 0 );
freeAllDataObjInfo( bunfileObjInfoHead );
return status;
} // unbunAndStageBunfileObj
int _unbunAndStageBunfileObj(
rsComm_t* rsComm,
dataObjInfo_t** bunfileObjInfoHead,
keyValPair_t * condInput,
char** outCacheRescName,
const int rmBunCopyFlag) {
dataObjInp_t dataObjInp{};
bzero( &dataObjInp.condInput, sizeof( dataObjInp.condInput ) );
rstrcpy( dataObjInp.objPath, ( *bunfileObjInfoHead )->objPath, MAX_NAME_LEN );
int status = sortObjInfoForOpen( bunfileObjInfoHead, condInput, 0 );
addKeyVal( &dataObjInp.condInput, RESC_HIER_STR_KW, ( *bunfileObjInfoHead )->rescHier );
if ( status < 0 ) {
return status;
}
if (outCacheRescName) {
*outCacheRescName = ( *bunfileObjInfoHead )->rescName;
}
addKeyVal(&dataObjInp.condInput, BUN_FILE_PATH_KW, (*bunfileObjInfoHead)->filePath);
if ( rmBunCopyFlag > 0 ) {
addKeyVal( &dataObjInp.condInput, RM_BUN_COPY_KW, "" );
}
if (!std::string_view{(*bunfileObjInfoHead)->dataType}.empty()) {
addKeyVal(&dataObjInp.condInput, DATA_TYPE_KW, (*bunfileObjInfoHead)->dataType);
}
status = _rsUnbunAndRegPhyBunfile(rsComm, &dataObjInp, (*bunfileObjInfoHead)->rescName);
return status;
} // _unbunAndStageBunfileObj
| 41.921933 | 150 | 0.627294 | [
"object",
"vector"
] |
c8e8c07a4fcecdd8a0b22edb3ba76b1d465c3971 | 39,995 | cpp | C++ | src/wasm/wasm-debug.cpp | sbc100/binaryen | 224d1a113f4d7f112314a8d3f62b830d698d00b2 | [
"Apache-2.0"
] | null | null | null | src/wasm/wasm-debug.cpp | sbc100/binaryen | 224d1a113f4d7f112314a8d3f62b830d698d00b2 | [
"Apache-2.0"
] | 2 | 2020-09-04T03:05:50.000Z | 2021-08-02T17:33:59.000Z | src/wasm/wasm-debug.cpp | sbc100/binaryen | 224d1a113f4d7f112314a8d3f62b830d698d00b2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 WebAssembly Community Group participants
*
* 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 "wasm-debug.h"
#include "wasm.h"
#ifdef BUILD_LLVM_DWARF
#include "llvm/ObjectYAML/DWARFEmitter.h"
#include "llvm/ObjectYAML/DWARFYAML.h"
#include "llvm/include/llvm/DebugInfo/DWARFContext.h"
std::error_code dwarf2yaml(llvm::DWARFContext& DCtx, llvm::DWARFYAML::Data& Y);
#endif
#include "wasm-binary.h"
#include "wasm-debug.h"
#include "wasm.h"
namespace wasm {
namespace Debug {
bool isDWARFSection(Name name) { return name.startsWith(".debug_"); }
bool hasDWARFSections(const Module& wasm) {
for (auto& section : wasm.userSections) {
if (isDWARFSection(section.name)) {
return true;
}
}
return false;
}
#ifdef BUILD_LLVM_DWARF
// In wasm32 the address size is 32 bits.
static const size_t AddressSize = 4;
struct BinaryenDWARFInfo {
llvm::StringMap<std::unique_ptr<llvm::MemoryBuffer>> sections;
std::unique_ptr<llvm::DWARFContext> context;
BinaryenDWARFInfo(const Module& wasm) {
// Get debug sections from the wasm.
for (auto& section : wasm.userSections) {
if (Name(section.name).startsWith(".debug_") && section.data.data()) {
// TODO: efficiency
sections[section.name.substr(1)] = llvm::MemoryBuffer::getMemBufferCopy(
llvm::StringRef(section.data.data(), section.data.size()));
}
}
// Parse debug sections.
uint8_t addrSize = AddressSize;
bool isLittleEndian = true;
context = llvm::DWARFContext::create(sections, addrSize, isLittleEndian);
}
};
void dumpDWARF(const Module& wasm) {
BinaryenDWARFInfo info(wasm);
std::cout << "DWARF debug info\n";
std::cout << "================\n\n";
for (auto& section : wasm.userSections) {
if (Name(section.name).startsWith(".debug_")) {
std::cout << "Contains section " << section.name << " ("
<< section.data.size() << " bytes)\n";
}
}
llvm::DIDumpOptions options;
options.DumpType = llvm::DIDT_All;
options.ShowChildren = true;
options.Verbose = true;
info.context->dump(llvm::outs(), options);
}
//
// Big picture: We use a DWARFContext to read data, then DWARFYAML support
// code to write it. That is not the main LLVM Dwarf code used for writing
// object files, but it avoids us create a "fake" MC layer, and provides a
// simple way to write out the debug info. Likely the level of info represented
// in the DWARFYAML::Data object is sufficient for Binaryen's needs, but if not,
// we may need a different approach.
//
// In more detail:
//
// 1. Binary sections => DWARFContext:
//
// llvm::DWARFContext::create(sections..)
//
// 2. DWARFContext => DWARFYAML::Data
//
// std::error_code dwarf2yaml(DWARFContext &DCtx, DWARFYAML::Data &Y) {
//
// 3. DWARFYAML::Data => binary sections
//
// StringMap<std::unique_ptr<MemoryBuffer>>
// EmitDebugSections(llvm::DWARFYAML::Data &DI, bool ApplyFixups);
//
// Represents the state when parsing a line table.
struct LineState {
uint32_t addr = 0;
// TODO sectionIndex?
uint32_t line = 1;
uint32_t col = 0;
uint32_t file = 1;
uint32_t isa = 0;
uint32_t discriminator = 0;
bool isStmt;
bool basicBlock = false;
bool prologueEnd = false;
bool epilogueBegin = false;
// Each instruction is part of a sequence, all of which get the same ID. The
// order within a sequence may change if binaryen reorders things, which means
// that we can't track the end_sequence location and assume it is at the end -
// we must track sequences and then emit an end for each one.
// -1 is an invalid marker value (note that this assumes we can fit all ids
// into just under 32 bits).
uint32_t sequenceId = -1;
LineState(const LineState& other) = default;
LineState(const llvm::DWARFYAML::LineTable& table, uint32_t sequenceId)
: isStmt(table.DefaultIsStmt), sequenceId(sequenceId) {}
LineState& operator=(const LineState& other) = default;
// Updates the state, and returns whether a new row is ready to be emitted.
bool update(llvm::DWARFYAML::LineTableOpcode& opcode,
const llvm::DWARFYAML::LineTable& table) {
switch (opcode.Opcode) {
case 0: {
// Extended opcodes
switch (opcode.SubOpcode) {
case llvm::dwarf::DW_LNE_set_address: {
addr = opcode.Data;
break;
}
case llvm::dwarf::DW_LNE_end_sequence: {
return true;
}
case llvm::dwarf::DW_LNE_set_discriminator: {
discriminator = opcode.Data;
break;
}
case llvm::dwarf::DW_LNE_define_file: {
Fatal() << "TODO: DW_LNE_define_file";
}
default: {
// An unknown opcode, ignore.
std::cerr << "warning: unknown subopcopde " << opcode.SubOpcode
<< '\n';
}
}
break;
}
case llvm::dwarf::DW_LNS_set_column: {
col = opcode.Data;
break;
}
case llvm::dwarf::DW_LNS_set_prologue_end: {
prologueEnd = true;
break;
}
case llvm::dwarf::DW_LNS_copy: {
return true;
}
case llvm::dwarf::DW_LNS_advance_pc: {
assert(table.MinInstLength == 1);
addr += opcode.Data;
break;
}
case llvm::dwarf::DW_LNS_advance_line: {
line += opcode.SData;
break;
}
case llvm::dwarf::DW_LNS_set_file: {
file = opcode.Data;
break;
}
case llvm::dwarf::DW_LNS_negate_stmt: {
isStmt = !isStmt;
break;
}
case llvm::dwarf::DW_LNS_set_basic_block: {
basicBlock = true;
break;
}
case llvm::dwarf::DW_LNS_const_add_pc: {
uint8_t AdjustOpcode = 255 - table.OpcodeBase;
uint64_t AddrOffset =
(AdjustOpcode / table.LineRange) * table.MinInstLength;
addr += AddrOffset;
break;
}
case llvm::dwarf::DW_LNS_fixed_advance_pc: {
addr += opcode.Data;
break;
}
case llvm::dwarf::DW_LNS_set_isa: {
isa = opcode.Data;
break;
}
default: {
if (opcode.Opcode >= table.OpcodeBase) {
// Special opcode: adjust line and addr, using some math.
uint8_t AdjustOpcode =
opcode.Opcode - table.OpcodeBase; // 20 - 13 = 7
uint64_t AddrOffset = (AdjustOpcode / table.LineRange) *
table.MinInstLength; // (7 / 14) * 1 = 0
int32_t LineOffset =
table.LineBase +
(AdjustOpcode % table.LineRange); // -5 + (7 % 14) = 2
line += LineOffset;
addr += AddrOffset;
return true;
} else {
Fatal() << "unknown debug line opcode: " << std::hex << opcode.Opcode;
}
}
}
return false;
}
// Checks if this starts a new range of addresses. Each range is a set of
// related addresses, where in particular, if the first has been zeroed out
// by the linker, we must omit the entire range. (If we do not, then the
// initial range is 0 and the others are offsets relative to it, which will
// look like random addresses, perhaps into the middle of instructions, and
// perhaps that happen to collide with real ones.)
bool startsNewRange(llvm::DWARFYAML::LineTableOpcode& opcode) {
return opcode.Opcode == 0 &&
opcode.SubOpcode == llvm::dwarf::DW_LNE_set_address;
}
bool needToEmit() {
// Zero values imply we can ignore this line.
// https://github.com/WebAssembly/debugging/issues/9#issuecomment-567720872
return line != 0 && addr != 0;
}
// Given an old state, emit the diff from it to this state into a new line
// table entry (that will be emitted in the updated DWARF debug line section).
void emitDiff(const LineState& old,
std::vector<llvm::DWARFYAML::LineTableOpcode>& newOpcodes,
const llvm::DWARFYAML::LineTable& table,
bool endSequence) const {
bool useSpecial = false;
if (addr != old.addr || line != old.line) {
// Try to use a special opcode TODO
}
if (addr != old.addr && !useSpecial) {
// len = 1 (subopcode) + 4 (wasm32 address)
// FIXME: look at AddrSize on the Unit.
auto item = makeItem(llvm::dwarf::DW_LNE_set_address, 5);
item.Data = addr;
newOpcodes.push_back(item);
}
if (line != old.line && !useSpecial) {
auto item = makeItem(llvm::dwarf::DW_LNS_advance_line);
// In wasm32 we have 32-bit addresses, and the delta here might be
// negative (note that SData is 64-bit, as LLVM supports 64-bit
// addresses too).
item.SData = int32_t(line - old.line);
newOpcodes.push_back(item);
}
if (col != old.col) {
auto item = makeItem(llvm::dwarf::DW_LNS_set_column);
item.Data = col;
newOpcodes.push_back(item);
}
if (file != old.file) {
auto item = makeItem(llvm::dwarf::DW_LNS_set_file);
item.Data = file;
newOpcodes.push_back(item);
}
if (isa != old.isa) {
auto item = makeItem(llvm::dwarf::DW_LNS_set_isa);
item.Data = isa;
newOpcodes.push_back(item);
}
if (discriminator != old.discriminator) {
// len = 1 (subopcode) + 4 (wasm32 address)
auto item = makeItem(llvm::dwarf::DW_LNE_set_discriminator, 5);
item.Data = discriminator;
newOpcodes.push_back(item);
}
if (isStmt != old.isStmt) {
newOpcodes.push_back(makeItem(llvm::dwarf::DW_LNS_negate_stmt));
}
if (basicBlock != old.basicBlock) {
assert(basicBlock);
newOpcodes.push_back(makeItem(llvm::dwarf::DW_LNS_set_basic_block));
}
if (prologueEnd) {
newOpcodes.push_back(makeItem(llvm::dwarf::DW_LNS_set_prologue_end));
}
if (epilogueBegin != old.epilogueBegin) {
Fatal() << "eb";
}
if (useSpecial) {
// Emit a special, which emits a line automatically.
// TODO
} else {
// Emit the line manually.
if (endSequence) {
// len = 1 (subopcode)
newOpcodes.push_back(makeItem(llvm::dwarf::DW_LNE_end_sequence, 1));
} else {
newOpcodes.push_back(makeItem(llvm::dwarf::DW_LNS_copy));
}
}
}
// Some flags are automatically reset after each debug line.
void resetAfterLine() { prologueEnd = false; }
private:
llvm::DWARFYAML::LineTableOpcode
makeItem(llvm::dwarf::LineNumberOps opcode) const {
llvm::DWARFYAML::LineTableOpcode item = {};
item.Opcode = opcode;
return item;
}
llvm::DWARFYAML::LineTableOpcode
makeItem(llvm::dwarf::LineNumberExtendedOps opcode, uint64_t len) const {
auto item = makeItem(llvm::dwarf::LineNumberOps(0));
// All the length after the len field itself, including the subopcode
// (1 byte).
item.ExtLen = len;
item.SubOpcode = opcode;
return item;
}
};
// Represents a mapping of addresses to expressions. We track beginnings and
// endings of expressions separately, since the end of one (which is one past
// the end in DWARF notation) overlaps with the beginning of the next, and also
// to let us use contextual information (we may know we are looking up the end
// of an instruction).
struct AddrExprMap {
std::unordered_map<BinaryLocation, Expression*> startMap;
std::unordered_map<BinaryLocation, Expression*> endMap;
// Some instructions have delimiter binary locations, like the else and end in
// and if. Track those separately, including their expression and their id
// ("else", "end", etc.), as they are rare, and we don't want to
// bloat the common case which is represented in the earlier maps.
struct DelimiterInfo {
Expression* expr;
BinaryLocations::DelimiterId id;
};
std::unordered_map<BinaryLocation, DelimiterInfo> delimiterMap;
// Construct the map from the binaryLocations loaded from the wasm.
AddrExprMap(const Module& wasm) {
for (auto& func : wasm.functions) {
for (auto pair : func->expressionLocations) {
add(pair.first, pair.second);
}
for (auto pair : func->delimiterLocations) {
add(pair.first, pair.second);
}
}
}
Expression* getStart(BinaryLocation addr) const {
auto iter = startMap.find(addr);
if (iter != startMap.end()) {
return iter->second;
}
return nullptr;
}
Expression* getEnd(BinaryLocation addr) const {
auto iter = endMap.find(addr);
if (iter != endMap.end()) {
return iter->second;
}
return nullptr;
}
DelimiterInfo getDelimiter(BinaryLocation addr) const {
auto iter = delimiterMap.find(addr);
if (iter != delimiterMap.end()) {
return iter->second;
}
return DelimiterInfo{nullptr, BinaryLocations::Invalid};
}
private:
void add(Expression* expr, const BinaryLocations::Span span) {
assert(startMap.count(span.start) == 0);
startMap[span.start] = expr;
assert(endMap.count(span.end) == 0);
endMap[span.end] = expr;
}
void add(Expression* expr,
const BinaryLocations::DelimiterLocations& delimiter) {
for (Index i = 0; i < delimiter.size(); i++) {
if (delimiter[i] != 0) {
assert(delimiterMap.count(delimiter[i]) == 0);
delimiterMap[delimiter[i]] =
DelimiterInfo{expr, BinaryLocations::DelimiterId(i)};
}
}
}
};
// Represents a mapping of addresses to expressions. As with expressions, we
// track both start and end; here, however, "start" means the "start" and
// "declarations" fields in FunctionLocations, and "end" means the two locations
// of one past the end, and one before it which is the "end" opcode that is
// emitted.
struct FuncAddrMap {
std::unordered_map<BinaryLocation, Function*> startMap, endMap;
// Construct the map from the binaryLocations loaded from the wasm.
FuncAddrMap(const Module& wasm) {
for (auto& func : wasm.functions) {
startMap[func->funcLocation.start] = func.get();
startMap[func->funcLocation.declarations] = func.get();
endMap[func->funcLocation.end - 1] = func.get();
endMap[func->funcLocation.end] = func.get();
}
}
Function* getStart(BinaryLocation addr) const {
auto iter = startMap.find(addr);
if (iter != startMap.end()) {
return iter->second;
}
return nullptr;
}
Function* getEnd(BinaryLocation addr) const {
auto iter = endMap.find(addr);
if (iter != endMap.end()) {
return iter->second;
}
return nullptr;
}
};
// Track locations from the original binary and the new one we wrote, so that
// we can update debug positions.
// We track expressions and functions separately, instead of having a single
// big map of (oldAddr) => (newAddr) because of the potentially ambiguous case
// of the final expression in a function: it's end might be identical in offset
// to the end of the function. So we have two different things that map to the
// same offset. However, if the context is "the end of the function" then the
// updated address is the new end of the function, even if the function ends
// with a different instruction now, as the old last instruction might have
// moved or been optimized out.
struct LocationUpdater {
Module& wasm;
const BinaryLocations& newLocations;
AddrExprMap oldExprAddrMap;
FuncAddrMap oldFuncAddrMap;
// Map offsets of location list entries in the debug_loc section to the index
// of their compile unit.
std::unordered_map<BinaryLocation, size_t> locToUnitMap;
// Map start of line tables in the debug_line section to their new locations.
std::unordered_map<BinaryLocation, BinaryLocation> debugLineMap;
typedef std::pair<BinaryLocation, BinaryLocation> OldToNew;
// Map of compile unit index => old and new base offsets (i.e., in the
// original binary and in the new one).
std::unordered_map<size_t, OldToNew> compileUnitBases;
// TODO: for memory efficiency, we may want to do this in a streaming manner,
// binary to binary, without YAML IR.
LocationUpdater(Module& wasm, const BinaryLocations& newLocations)
: wasm(wasm), newLocations(newLocations), oldExprAddrMap(wasm),
oldFuncAddrMap(wasm) {}
// Updates an expression's address. If there was never an instruction at that
// address, or if there was but if that instruction no longer exists, return
// 0. Otherwise, return the new updated location.
BinaryLocation getNewExprStart(BinaryLocation oldAddr) const {
if (auto* expr = oldExprAddrMap.getStart(oldAddr)) {
auto iter = newLocations.expressions.find(expr);
if (iter != newLocations.expressions.end()) {
BinaryLocation newAddr = iter->second.start;
return newAddr;
}
}
return 0;
}
bool hasOldExprStart(BinaryLocation oldAddr) const {
return oldExprAddrMap.getStart(oldAddr);
}
BinaryLocation getNewExprEnd(BinaryLocation oldAddr) const {
if (auto* expr = oldExprAddrMap.getEnd(oldAddr)) {
auto iter = newLocations.expressions.find(expr);
if (iter != newLocations.expressions.end()) {
return iter->second.end;
}
}
return 0;
}
bool hasOldExprEnd(BinaryLocation oldAddr) const {
return oldExprAddrMap.getEnd(oldAddr);
}
BinaryLocation getNewFuncStart(BinaryLocation oldAddr) const {
if (auto* func = oldFuncAddrMap.getStart(oldAddr)) {
// The function might have been optimized away, check.
auto iter = newLocations.functions.find(func);
if (iter != newLocations.functions.end()) {
auto oldLocations = func->funcLocation;
auto newLocations = iter->second;
if (oldAddr == oldLocations.start) {
return newLocations.start;
} else if (oldAddr == oldLocations.declarations) {
return newLocations.declarations;
} else {
WASM_UNREACHABLE("invalid func start");
}
}
}
return 0;
}
bool hasOldFuncStart(BinaryLocation oldAddr) const {
return oldFuncAddrMap.getStart(oldAddr);
}
BinaryLocation getNewFuncEnd(BinaryLocation oldAddr) const {
if (auto* func = oldFuncAddrMap.getEnd(oldAddr)) {
// The function might have been optimized away, check.
auto iter = newLocations.functions.find(func);
if (iter != newLocations.functions.end()) {
auto oldLocations = func->funcLocation;
auto newLocations = iter->second;
if (oldAddr == oldLocations.end) {
return newLocations.end;
} else if (oldAddr == oldLocations.end - 1) {
return newLocations.end - 1;
} else {
WASM_UNREACHABLE("invalid func end");
}
}
}
return 0;
}
// Check for either the end opcode, or one past the end.
bool hasOldFuncEnd(BinaryLocation oldAddr) const {
return oldFuncAddrMap.getEnd(oldAddr);
}
// Check specifically for the end opcode.
bool hasOldFuncEndOpcode(BinaryLocation oldAddr) const {
if (auto* func = oldFuncAddrMap.getEnd(oldAddr)) {
return oldAddr == func->funcLocation.end - 1;
}
return false;
}
BinaryLocation getNewDelimiter(BinaryLocation oldAddr) const {
auto info = oldExprAddrMap.getDelimiter(oldAddr);
if (info.expr) {
auto iter = newLocations.delimiters.find(info.expr);
if (iter != newLocations.delimiters.end()) {
return iter->second[info.id];
}
}
return 0;
}
bool hasOldDelimiter(BinaryLocation oldAddr) const {
return oldExprAddrMap.getDelimiter(oldAddr).expr;
}
// getNewStart|EndAddr utilities.
// TODO: should we track the start and end of delimiters, even though they
// are just one byte?
BinaryLocation getNewStart(BinaryLocation oldStart) const {
if (hasOldExprStart(oldStart)) {
return getNewExprStart(oldStart);
} else if (hasOldFuncStart(oldStart)) {
return getNewFuncStart(oldStart);
} else if (hasOldDelimiter(oldStart)) {
return getNewDelimiter(oldStart);
}
return 0;
}
BinaryLocation getNewEnd(BinaryLocation oldEnd) const {
if (hasOldExprEnd(oldEnd)) {
return getNewExprEnd(oldEnd);
} else if (hasOldFuncEnd(oldEnd)) {
return getNewFuncEnd(oldEnd);
} else if (hasOldDelimiter(oldEnd)) {
return getNewDelimiter(oldEnd);
}
return 0;
}
BinaryLocation getNewDebugLineLocation(BinaryLocation old) const {
return debugLineMap.at(old);
}
// Given an offset in .debug_loc, get the old and new compile unit bases.
OldToNew getCompileUnitBasesForLoc(size_t offset) const {
auto index = locToUnitMap.at(offset);
auto iter = compileUnitBases.find(index);
if (iter != compileUnitBases.end()) {
return iter->second;
}
return OldToNew{0, 0};
}
};
// Update debug lines, and update the locationUpdater with debug line offset
// changes so we can update offsets into the debug line section.
static void updateDebugLines(llvm::DWARFYAML::Data& data,
LocationUpdater& locationUpdater) {
for (auto& table : data.DebugLines) {
uint32_t sequenceId = 0;
// Parse the original opcodes and emit new ones.
LineState state(table, sequenceId);
// All the addresses we need to write out.
std::vector<BinaryLocation> newAddrs;
std::unordered_map<BinaryLocation, LineState> newAddrInfo;
// If the address was zeroed out, we must omit the entire range (we could
// also leave it unchanged, so that the debugger ignores it based on the
// initial zero; but it's easier and better to just not emit it at all).
bool omittingRange = false;
for (auto& opcode : table.Opcodes) {
// Update the state, and check if we have a new row to emit.
if (state.startsNewRange(opcode)) {
omittingRange = false;
}
if (state.update(opcode, table)) {
if (state.addr == 0) {
omittingRange = true;
}
if (omittingRange) {
state = LineState(table, sequenceId);
continue;
}
// An expression may not exist for this line table item, if we optimized
// it away.
BinaryLocation oldAddr = state.addr;
BinaryLocation newAddr = 0;
if (locationUpdater.hasOldExprStart(oldAddr)) {
newAddr = locationUpdater.getNewExprStart(oldAddr);
}
// Test for a function's end address first, as LLVM output appears to
// use 1-past-the-end-of-the-function as a location in that function,
// and not the next (but the first byte of the next function, which is
// ambiguously identical to that value, is used at least in low_pc).
else if (locationUpdater.hasOldFuncEnd(oldAddr)) {
newAddr = locationUpdater.getNewFuncEnd(oldAddr);
} else if (locationUpdater.hasOldFuncStart(oldAddr)) {
newAddr = locationUpdater.getNewFuncStart(oldAddr);
} else if (locationUpdater.hasOldDelimiter(oldAddr)) {
newAddr = locationUpdater.getNewDelimiter(oldAddr);
}
if (newAddr && state.needToEmit()) {
// LLVM sometimes emits the same address more than once. We should
// probably investigate that.
if (newAddrInfo.count(newAddr)) {
continue;
}
newAddrs.push_back(newAddr);
newAddrInfo.emplace(newAddr, state);
auto& updatedState = newAddrInfo.at(newAddr);
// The only difference is the address TODO other stuff?
updatedState.addr = newAddr;
// Reset relevant state.
state.resetAfterLine();
}
if (opcode.Opcode == 0 &&
opcode.SubOpcode == llvm::dwarf::DW_LNE_end_sequence) {
sequenceId++;
// We assume the number of sequences can fit in 32 bits, and -1 is
// an invalid value.
assert(sequenceId != uint32_t(-1));
state = LineState(table, sequenceId);
}
}
}
// Sort the new addresses (which may be substantially different from the
// original layout after optimization).
std::sort(newAddrs.begin(), newAddrs.end());
// Emit a new line table.
{
std::vector<llvm::DWARFYAML::LineTableOpcode> newOpcodes;
for (size_t i = 0; i < newAddrs.size(); i++) {
LineState state = newAddrInfo.at(newAddrs[i]);
assert(state.needToEmit());
LineState lastState(table, -1);
if (i != 0) {
lastState = newAddrInfo.at(newAddrs[i - 1]);
// If the last line is in another sequence, clear the old state, as
// there is nothing to diff to.
if (lastState.sequenceId != state.sequenceId) {
lastState = LineState(table, -1);
}
}
// This line ends a sequence if there is no next line after it, or if
// the next line is in a different sequence.
bool endSequence =
i + 1 == newAddrs.size() ||
newAddrInfo.at(newAddrs[i + 1]).sequenceId != state.sequenceId;
state.emitDiff(lastState, newOpcodes, table, endSequence);
}
table.Opcodes.swap(newOpcodes);
}
}
// After updating the contents, run the emitter in order to update the
// lengths of each section. We will use that to update offsets into the
// debug_line section.
std::vector<size_t> computedLengths;
llvm::DWARFYAML::ComputeDebugLine(data, computedLengths);
BinaryLocation oldLocation = 0, newLocation = 0;
for (size_t i = 0; i < data.DebugLines.size(); i++) {
auto& table = data.DebugLines[i];
locationUpdater.debugLineMap[oldLocation] = newLocation;
oldLocation += table.Length.getLength() + AddressSize;
newLocation += computedLengths[i] + AddressSize;
table.Length.setLength(computedLengths[i]);
}
}
// Iterate in parallel over a DwarfContext representation element and a
// YAML element, which parallel each other.
template<typename T, typename U, typename W>
static void iterContextAndYAML(const T& contextList, U& yamlList, W func) {
auto yamlValue = yamlList.begin();
for (const auto& contextValue : contextList) {
assert(yamlValue != yamlList.end());
func(contextValue, *yamlValue);
yamlValue++;
}
assert(yamlValue == yamlList.end());
}
// Updates a YAML entry from a DWARF DIE. Also updates LocationUpdater
// associating each .debug_loc entry with the base address of its corresponding
// compilation unit.
static void updateDIE(const llvm::DWARFDebugInfoEntry& DIE,
llvm::DWARFYAML::Entry& yamlEntry,
const llvm::DWARFAbbreviationDeclaration* abbrevDecl,
LocationUpdater& locationUpdater,
size_t compileUnitIndex) {
auto tag = DIE.getTag();
// Pairs of low/high_pc require some special handling, as the high
// may be an offset relative to the low. First, process everything but
// the high pcs, so we see the low pcs first.
BinaryLocation oldLowPC = 0, newLowPC = 0;
iterContextAndYAML(
abbrevDecl->attributes(),
yamlEntry.Values,
[&](const llvm::DWARFAbbreviationDeclaration::AttributeSpec& attrSpec,
llvm::DWARFYAML::FormValue& yamlValue) {
auto attr = attrSpec.Attr;
if (attr == llvm::dwarf::DW_AT_low_pc) {
// This is an address.
BinaryLocation oldValue = yamlValue.Value, newValue = 0;
if (tag == llvm::dwarf::DW_TAG_GNU_call_site ||
tag == llvm::dwarf::DW_TAG_inlined_subroutine ||
tag == llvm::dwarf::DW_TAG_lexical_block ||
tag == llvm::dwarf::DW_TAG_label) {
newValue = locationUpdater.getNewExprStart(oldValue);
} else if (tag == llvm::dwarf::DW_TAG_compile_unit) {
newValue = locationUpdater.getNewFuncStart(oldValue);
// Per the DWARF spec, "The base address of a compile unit is
// defined as the value of the DW_AT_low_pc attribute, if present."
locationUpdater.compileUnitBases[compileUnitIndex] =
LocationUpdater::OldToNew{oldValue, newValue};
} else if (tag == llvm::dwarf::DW_TAG_subprogram) {
newValue = locationUpdater.getNewFuncStart(oldValue);
} else {
Fatal() << "unknown tag with low_pc "
<< llvm::dwarf::TagString(tag).str();
}
oldLowPC = oldValue;
newLowPC = newValue;
yamlValue.Value = newValue;
} else if (attr == llvm::dwarf::DW_AT_stmt_list) {
// This is an offset into the debug line section.
yamlValue.Value =
locationUpdater.getNewDebugLineLocation(yamlValue.Value);
} else if (attr == llvm::dwarf::DW_AT_location &&
attrSpec.Form == llvm::dwarf::DW_FORM_sec_offset) {
BinaryLocation locOffset = yamlValue.Value;
locationUpdater.locToUnitMap[locOffset] = compileUnitIndex;
}
});
// Next, process the high_pcs.
// TODO: do this more efficiently, without a second traversal (but that's a
// little tricky given the special double-traversal we have).
iterContextAndYAML(
abbrevDecl->attributes(),
yamlEntry.Values,
[&](const llvm::DWARFAbbreviationDeclaration::AttributeSpec& attrSpec,
llvm::DWARFYAML::FormValue& yamlValue) {
auto attr = attrSpec.Attr;
if (attr != llvm::dwarf::DW_AT_high_pc) {
return;
}
BinaryLocation oldValue = yamlValue.Value, newValue = 0;
bool isRelative = attrSpec.Form == llvm::dwarf::DW_FORM_data4;
if (isRelative) {
oldValue += oldLowPC;
}
if (tag == llvm::dwarf::DW_TAG_GNU_call_site ||
tag == llvm::dwarf::DW_TAG_inlined_subroutine ||
tag == llvm::dwarf::DW_TAG_lexical_block ||
tag == llvm::dwarf::DW_TAG_label) {
newValue = locationUpdater.getNewExprEnd(oldValue);
} else if (tag == llvm::dwarf::DW_TAG_compile_unit ||
tag == llvm::dwarf::DW_TAG_subprogram) {
newValue = locationUpdater.getNewFuncEnd(oldValue);
} else {
Fatal() << "unknown tag with low_pc "
<< llvm::dwarf::TagString(tag).str();
}
if (isRelative) {
newValue -= newLowPC;
}
yamlValue.Value = newValue;
});
}
static void updateCompileUnits(const BinaryenDWARFInfo& info,
llvm::DWARFYAML::Data& yaml,
LocationUpdater& locationUpdater) {
// The context has the high-level information we need, and the YAML is where
// we write changes. First, iterate over the compile units.
size_t compileUnitIndex = 0;
iterContextAndYAML(
info.context->compile_units(),
yaml.CompileUnits,
[&](const std::unique_ptr<llvm::DWARFUnit>& CU,
llvm::DWARFYAML::Unit& yamlUnit) {
// Process the DIEs in each compile unit.
iterContextAndYAML(
CU->dies(),
yamlUnit.Entries,
[&](const llvm::DWARFDebugInfoEntry& DIE,
llvm::DWARFYAML::Entry& yamlEntry) {
// Process the entries in each relevant DIE, looking for attributes to
// change.
auto abbrevDecl = DIE.getAbbreviationDeclarationPtr();
if (abbrevDecl) {
// This is relevant; look for things to update.
updateDIE(
DIE, yamlEntry, abbrevDecl, locationUpdater, compileUnitIndex);
}
});
compileUnitIndex++;
});
}
static void updateRanges(llvm::DWARFYAML::Data& yaml,
const LocationUpdater& locationUpdater) {
// In each range section, try to update the start and end. If we no longer
// have something to map them to, we must skip that part.
size_t skip = 0;
for (size_t i = 0; i < yaml.Ranges.size(); i++) {
auto& range = yaml.Ranges[i];
BinaryLocation oldStart = range.Start, oldEnd = range.End, newStart = 0,
newEnd = 0;
// If this is an end marker (0, 0), or an invalid range (0, x) or (x, 0)
// then just emit it as it is - either to mark the end, or to mark an
// invalid entry.
if (oldStart == 0 || oldEnd == 0) {
newStart = oldStart;
newEnd = oldEnd;
} else {
// This was a valid entry; update it.
newStart = locationUpdater.getNewStart(oldStart);
newEnd = locationUpdater.getNewEnd(oldEnd);
if (newStart == 0 || newEnd == 0) {
// This part of the range no longer has a mapping, so we must skip it.
// Don't use (0, 0) as that would be an end marker; emit something
// invalid for the debugger to ignore.
newStart = 0;
newEnd = 1;
}
// TODO even if range start and end markers have been preserved,
// instructions in the middle may have moved around, making the range no
// longer contiguous. We should check that, and possibly split/merge
// the range. Or, we may need to have tracking in the IR for this.
}
auto& writtenRange = yaml.Ranges[i - skip];
writtenRange.Start = newStart;
writtenRange.End = newEnd;
}
}
// A location that is ignoreable, i.e., not a special value like 0 or -1 (which
// would indicate an end or a base in .debug_loc).
static const BinaryLocation IGNOREABLE_LOCATION = 1;
static bool isNewBaseLoc(const llvm::DWARFYAML::Loc& loc) {
return loc.Start == BinaryLocation(-1);
}
static bool isEndMarkerLoc(const llvm::DWARFYAML::Loc& loc) {
return loc.Start == 0 && loc.End == 0;
}
// Update the .debug_loc section.
static void updateLoc(llvm::DWARFYAML::Data& yaml,
const LocationUpdater& locationUpdater) {
// Similar to ranges, try to update the start and end. Note that here we
// can't skip since the location description is a variable number of bytes,
// so we mark no longer valid addresses as empty.
bool atStart = true;
// We need to keep positions in the .debug_loc section identical to before
// (or else we'd need to update their positions too) and so we need to keep
// base entries around (a base entry is added to every entry after it in the
// list). However, we may change the base's value as after moving instructions
// around the old base may not be smaller than all the values relative to it.
BinaryLocation oldBase, newBase;
auto& locs = yaml.Locs;
for (size_t i = 0; i < locs.size(); i++) {
auto& loc = locs[i];
if (atStart) {
std::tie(oldBase, newBase) =
locationUpdater.getCompileUnitBasesForLoc(loc.CompileUnitOffset);
atStart = false;
}
// By default we copy values over, unless we modify them below.
BinaryLocation newStart = loc.Start, newEnd = loc.End;
if (isNewBaseLoc(loc)) {
// This is a new base.
// Note that the base is not the address of an instruction, necessarily -
// it's just a number (seems like it could always be an instruction, but
// that's not what LLVM emits).
// We must look forward at everything relative to this base, so that we
// can emit a new proper base (as mentioned earlier, the original base may
// not be valid if instructions moved to a position before it - they must
// be positive offsets from it).
oldBase = newBase = newEnd;
BinaryLocation smallest = -1;
for (size_t j = i + 1; j < locs.size(); j++) {
auto& futureLoc = locs[j];
if (isNewBaseLoc(futureLoc) || isEndMarkerLoc(futureLoc)) {
break;
}
auto updatedStart =
locationUpdater.getNewStart(futureLoc.Start + oldBase);
// If we found a valid mapping, this is a relevant value for us. If the
// optimizer removed it, it's a 0, and we can ignore it here - we will
// emit IGNOREABLE_LOCATION for it later anyhow.
if (updatedStart != 0) {
smallest = std::min(smallest, updatedStart);
}
}
// If we found no valid values that will be relativized here, just use 0
// as the new (never-to-be-used) base, which is less confusing (otherwise
// the value looks like it means something).
if (smallest == BinaryLocation(-1)) {
smallest = 0;
}
newBase = newEnd = smallest;
} else if (isEndMarkerLoc(loc)) {
// This is an end marker, this list is done; reset the base.
atStart = true;
} else {
// This is a normal entry, try to find what it should be updated to. First
// de-relativize it to the base to get the absolute address, then look for
// a new address for it.
newStart = locationUpdater.getNewStart(loc.Start + oldBase);
newEnd = locationUpdater.getNewEnd(loc.End + oldBase);
if (newStart == 0 || newEnd == 0 || newStart > newEnd) {
// This part of the loc no longer has a mapping, or after the mapping
// it is no longer a proper span, so we must ignore it.
newStart = newEnd = IGNOREABLE_LOCATION;
} else {
// We picked a new base that ensures it is smaller than the values we
// will relativize to it.
assert(newStart >= newBase && newEnd >= newBase);
newStart -= newBase;
newEnd -= newBase;
if (newStart == 0 && newEnd == 0) {
// After mapping to the new positions, and after relativizing to the
// base, if we end up with (0, 0) then we must emit something else, as
// that would be interpreted as the end of a list. As it is an empty
// span, the actual value doesn't matter, it just has to be != 0.
// This can happen if the very first span in a compile unit is an
// empty span, in which case relative to the base of the compile unit
// we would have (0, 0).
newStart = newEnd = IGNOREABLE_LOCATION;
}
}
// The loc start and end markers have been preserved. However, TODO
// instructions in the middle may have moved around, making the loc no
// longer contiguous, we should check that, and possibly split/merge
// the loc. Or, we may need to have tracking in the IR for this.
}
loc.Start = newStart;
loc.End = newEnd;
// Note how the ".Location" field is unchanged.
}
}
void writeDWARFSections(Module& wasm, const BinaryLocations& newLocations) {
BinaryenDWARFInfo info(wasm);
// Convert to Data representation, which YAML can use to write.
llvm::DWARFYAML::Data data;
if (dwarf2yaml(*info.context, data)) {
Fatal() << "Failed to parse DWARF to YAML";
}
LocationUpdater locationUpdater(wasm, newLocations);
updateDebugLines(data, locationUpdater);
updateCompileUnits(info, data, locationUpdater);
updateRanges(data, locationUpdater);
updateLoc(data, locationUpdater);
// Convert to binary sections.
auto newSections =
EmitDebugSections(data, false /* EmitFixups for debug_info */);
// Update the custom sections in the wasm.
// TODO: efficiency
for (auto& section : wasm.userSections) {
if (Name(section.name).startsWith(".debug_")) {
auto llvmName = section.name.substr(1);
if (newSections.count(llvmName)) {
auto llvmData = newSections[llvmName]->getBuffer();
section.data.resize(llvmData.size());
std::copy(llvmData.begin(), llvmData.end(), section.data.data());
}
}
}
}
#else // BUILD_LLVM_DWARF
void dumpDWARF(const Module& wasm) {
std::cerr << "warning: no DWARF dumping support present\n";
}
void writeDWARFSections(Module& wasm, const BinaryLocations& newLocations) {
std::cerr << "warning: no DWARF updating support present\n";
}
#endif // BUILD_LLVM_DWARF
} // namespace Debug
} // namespace wasm
| 37.066728 | 80 | 0.647356 | [
"object",
"vector"
] |
c8e97d5c8565556f4833545308cbf46838ffa768 | 17,331 | cxx | C++ | main/framework/source/services/modulemanager.cxx | jimjag/openoffice | 74746a22d8cc22b031b00fcd106f4496bf936c77 | [
"Apache-2.0"
] | 1 | 2019-12-27T19:25:34.000Z | 2019-12-27T19:25:34.000Z | main/framework/source/services/modulemanager.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 1 | 2019-11-25T04:29:25.000Z | 2019-11-25T04:29:25.000Z | main/framework/source/services/modulemanager.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 6 | 2019-11-19T00:28:25.000Z | 2019-11-22T06:48:49.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
#include "services/modulemanager.hxx"
#include "services/frame.hxx"
//_______________________________________________
// own includes
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
#include <services.h>
//_______________________________________________
// interface includes
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/XModule.hpp>
#include <comphelper/configurationhelper.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <comphelper/sequenceasvector.hxx>
#include <comphelper/enumhelper.hxx>
//_______________________________________________
// other includes
#include <rtl/logfile.hxx>
namespace framework
{
static const ::rtl::OUString CFGPATH_FACTORIES = ::rtl::OUString::createFromAscii("/org.openoffice.Setup/Office/Factories");
static const ::rtl::OUString MODULEPROP_IDENTIFIER = ::rtl::OUString::createFromAscii("ooSetupFactoryModuleIdentifier" );
/*-----------------------------------------------
04.12.2003 09:32
-----------------------------------------------*/
DEFINE_XINTERFACE_7(ModuleManager ,
OWeakObject ,
DIRECT_INTERFACE(css::lang::XTypeProvider ),
DIRECT_INTERFACE(css::lang::XServiceInfo ),
DIRECT_INTERFACE(css::container::XNameReplace ),
DIRECT_INTERFACE(css::container::XNameAccess ),
DIRECT_INTERFACE(css::container::XElementAccess ),
DIRECT_INTERFACE(css::container::XContainerQuery),
DIRECT_INTERFACE(css::frame::XModuleManager ))
/*-----------------------------------------------
04.12.2003 09:32
-----------------------------------------------*/
DEFINE_XTYPEPROVIDER_7(ModuleManager ,
css::lang::XTypeProvider ,
css::lang::XServiceInfo ,
css::container::XNameReplace ,
css::container::XNameAccess ,
css::container::XElementAccess ,
css::container::XContainerQuery,
css::frame::XModuleManager )
/*-----------------------------------------------
04.12.2003 09:35
-----------------------------------------------*/
DEFINE_XSERVICEINFO_ONEINSTANCESERVICE(ModuleManager ,
::cppu::OWeakObject ,
SERVICENAME_MODULEMANAGER ,
IMPLEMENTATIONNAME_MODULEMANAGER)
/*-----------------------------------------------
04.12.2003 09:35
-----------------------------------------------*/
DEFINE_INIT_SERVICE(
ModuleManager,
{
/*Attention
I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()
to create a new instance of this class by our own supported service factory.
see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations!
*/
}
)
/*-----------------------------------------------
04.12.2003 09:30
-----------------------------------------------*/
ModuleManager::ModuleManager(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR)
: ThreadHelpBase( )
, m_xSMGR (xSMGR)
{
}
/*-----------------------------------------------
10.12.2003 11:59
-----------------------------------------------*/
ModuleManager::~ModuleManager()
{
if (m_xCFG.is())
m_xCFG.clear();
}
/*-----------------------------------------------
10.12.2003 11:02
-----------------------------------------------*/
::rtl::OUString SAL_CALL ModuleManager::identify(const css::uno::Reference< css::uno::XInterface >& xModule)
throw(css::lang::IllegalArgumentException,
css::frame::UnknownModuleException,
css::uno::RuntimeException )
{
// valid parameter?
css::uno::Reference< css::frame::XFrame > xFrame (xModule, css::uno::UNO_QUERY);
css::uno::Reference< css::awt::XWindow > xWindow (xModule, css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XController > xController(xModule, css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XModel > xModel (xModule, css::uno::UNO_QUERY);
if (
(!xFrame.is() ) &&
(!xWindow.is() ) &&
(!xController.is()) &&
(!xModel.is() )
)
{
throw css::lang::IllegalArgumentException(
::rtl::OUString::createFromAscii("Given module is not a frame nor a window, controller or model."),
static_cast< ::cppu::OWeakObject* >(this),
1);
}
if (xFrame.is())
{
xController = xFrame->getController();
xWindow = xFrame->getComponentWindow();
}
if (xController.is())
xModel = xController->getModel();
// modules are implemented by the deepest component in hierarchy ...
// Means: model -> controller -> window
// No fallbacks to higher components are allowed !
// Note : A frame provides access to module components only ... but it's not a module by himself.
::rtl::OUString sModule;
if (xModel.is())
sModule = implts_identify(xModel);
else
if (xController.is())
sModule = implts_identify(xController);
else
if (xWindow.is())
sModule = implts_identify(xWindow);
if (sModule.getLength() < 1)
throw css::frame::UnknownModuleException(
::rtl::OUString::createFromAscii("Can't find suitable module for the given component."),
static_cast< ::cppu::OWeakObject* >(this));
return sModule;
}
/*-----------------------------------------------
08.03.2007 09:55
-----------------------------------------------*/
void SAL_CALL ModuleManager::replaceByName(const ::rtl::OUString& sName ,
const css::uno::Any& aValue)
throw (css::lang::IllegalArgumentException ,
css::container::NoSuchElementException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
::comphelper::SequenceAsHashMap lProps(aValue);
if (lProps.empty() )
{
throw css::lang::IllegalArgumentException(
::rtl::OUString::createFromAscii("No properties given to replace part of module."),
static_cast< css::container::XNameAccess* >(this),
2);
}
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
aReadLock.unlock();
// <- SAFE ----------------------------------
// get access to the element
// Note: Dont use impl_getConfig() method here. Because it creates a readonly access only, further
// it cache it as a member of this module manager instance. If we change some props there ... but dont
// flush changes (because an error occurred) we will read them later. If we use a different config access
// we can close it without a flush ... and our read data wont be affected .-)
css::uno::Reference< css::uno::XInterface > xCfg = ::comphelper::ConfigurationHelper::openConfig(
xSMGR,
CFGPATH_FACTORIES,
::comphelper::ConfigurationHelper::E_STANDARD);
css::uno::Reference< css::container::XNameAccess > xModules (xCfg, css::uno::UNO_QUERY_THROW);
css::uno::Reference< css::container::XNameReplace > xModule ;
xModules->getByName(sName) >>= xModule;
if (!xModule.is())
{
throw css::uno::RuntimeException(
::rtl::OUString::createFromAscii("Was not able to get write access to the requested module entry inside configuration."),
static_cast< css::container::XNameAccess* >(this));
}
::comphelper::SequenceAsHashMap::const_iterator pProp;
for ( pProp = lProps.begin();
pProp != lProps.end() ;
++pProp )
{
const ::rtl::OUString& sPropName = pProp->first;
const css::uno::Any& aPropValue = pProp->second;
// let "NoSuchElementException" out ! We support the same API ...
// and without a flush() at the end all changed data before will be ignored !
xModule->replaceByName(sPropName, aPropValue);
}
::comphelper::ConfigurationHelper::flush(xCfg);
}
/*-----------------------------------------------
10.12.2003 12:05
-----------------------------------------------*/
css::uno::Any SAL_CALL ModuleManager::getByName(const ::rtl::OUString& sName)
throw(css::container::NoSuchElementException,
css::lang::WrappedTargetException ,
css::uno::RuntimeException )
{
// get access to the element
css::uno::Reference< css::container::XNameAccess > xCFG = implts_getConfig();
css::uno::Reference< css::container::XNameAccess > xModule;
xCFG->getByName(sName) >>= xModule;
if (!xModule.is())
{
throw css::uno::RuntimeException(
::rtl::OUString::createFromAscii("Was not able to get write access to the requested module entry inside configuration."),
static_cast< css::container::XNameAccess* >(this));
}
// convert it to seq< PropertyValue >
const css::uno::Sequence< ::rtl::OUString > lPropNames = xModule->getElementNames();
::comphelper::SequenceAsHashMap lProps ;
sal_Int32 c = lPropNames.getLength();
sal_Int32 i = 0;
lProps[MODULEPROP_IDENTIFIER] <<= sName;
for (i=0; i<c; ++i)
{
const ::rtl::OUString& sPropName = lPropNames[i];
lProps[sPropName] = xModule->getByName(sPropName);
}
return css::uno::makeAny(lProps.getAsConstPropertyValueList());
}
/*-----------------------------------------------
10.12.2003 11:58
-----------------------------------------------*/
css::uno::Sequence< ::rtl::OUString > SAL_CALL ModuleManager::getElementNames()
throw(css::uno::RuntimeException)
{
css::uno::Reference< css::container::XNameAccess > xCFG = implts_getConfig();
return xCFG->getElementNames();
}
/*-----------------------------------------------
10.12.2003 11:57
-----------------------------------------------*/
sal_Bool SAL_CALL ModuleManager::hasByName(const ::rtl::OUString& sName)
throw(css::uno::RuntimeException)
{
css::uno::Reference< css::container::XNameAccess > xCFG = implts_getConfig();
return xCFG->hasByName(sName);
}
/*-----------------------------------------------
10.12.2003 11:35
-----------------------------------------------*/
css::uno::Type SAL_CALL ModuleManager::getElementType()
throw(css::uno::RuntimeException)
{
return ::getCppuType((const css::uno::Sequence< css::beans::PropertyValue >*)0);
}
/*-----------------------------------------------
10.12.2003 11:56
-----------------------------------------------*/
sal_Bool SAL_CALL ModuleManager::hasElements()
throw(css::uno::RuntimeException)
{
css::uno::Reference< css::container::XNameAccess > xCFG = implts_getConfig();
return xCFG->hasElements();
}
/*-----------------------------------------------
07.03.2007 12:55
-----------------------------------------------*/
css::uno::Reference< css::container::XEnumeration > SAL_CALL ModuleManager::createSubSetEnumerationByQuery(const ::rtl::OUString&)
throw(css::uno::RuntimeException)
{
return css::uno::Reference< css::container::XEnumeration >();
}
/*-----------------------------------------------
07.03.2007 12:55
-----------------------------------------------*/
css::uno::Reference< css::container::XEnumeration > SAL_CALL ModuleManager::createSubSetEnumerationByProperties(const css::uno::Sequence< css::beans::NamedValue >& lProperties)
throw(css::uno::RuntimeException)
{
::comphelper::SequenceAsHashMap lSearchProps (lProperties);
css::uno::Sequence< ::rtl::OUString > lModules = getElementNames();
sal_Int32 c = lModules.getLength();
sal_Int32 i = 0;
::comphelper::SequenceAsVector< css::uno::Any > lResult ;
for (i=0; i<c; ++i)
{
try
{
const ::rtl::OUString& sModule = lModules[i];
::comphelper::SequenceAsHashMap lModuleProps = getByName(sModule);
if (lModuleProps.match(lSearchProps))
lResult.push_back(css::uno::makeAny(lModuleProps.getAsConstPropertyValueList()));
}
catch(const css::uno::Exception&)
{}
}
::comphelper::OAnyEnumeration* pEnum = new ::comphelper::OAnyEnumeration(lResult.getAsConstList());
css::uno::Reference< css::container::XEnumeration > xEnum(static_cast< css::container::XEnumeration* >(pEnum), css::uno::UNO_QUERY_THROW);
return xEnum;
}
/*-----------------------------------------------
14.12.2003 09:45
-----------------------------------------------*/
css::uno::Reference< css::container::XNameAccess > ModuleManager::implts_getConfig()
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
if (m_xCFG.is())
return m_xCFG;
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
aReadLock.unlock();
// <- SAFE ----------------------------------
css::uno::Reference< css::uno::XInterface > xCfg;
try
{
xCfg = ::comphelper::ConfigurationHelper::openConfig(
xSMGR,
CFGPATH_FACTORIES,
::comphelper::ConfigurationHelper::E_READONLY);
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ xCfg.clear(); }
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_xCFG = css::uno::Reference< css::container::XNameAccess >(xCfg, css::uno::UNO_QUERY_THROW);
return m_xCFG;
// <- SAFE ----------------------------------
}
/*-----------------------------------------------
30.01.2004 07:54
-----------------------------------------------*/
::rtl::OUString ModuleManager::implts_identify(const css::uno::Reference< css::uno::XInterface >& xComponent)
{
// Search for an optional (!) interface XModule first.
// Its used to overrule an existing service name. Used e.g. by our database form designer
// which uses a writer module internaly.
css::uno::Reference< css::frame::XModule > xModule(xComponent, css::uno::UNO_QUERY);
if (xModule.is())
return xModule->getIdentifier();
// detect modules in a generic way ...
// comparing service names with configured entries ...
css::uno::Reference< css::lang::XServiceInfo > xInfo(xComponent, css::uno::UNO_QUERY);
if (!xInfo.is())
return ::rtl::OUString();
const css::uno::Sequence< ::rtl::OUString > lKnownModules = getElementNames();
const ::rtl::OUString* pKnownModules = lKnownModules.getConstArray();
sal_Int32 c = lKnownModules.getLength();
sal_Int32 i = 0;
for (i=0; i<c; ++i)
{
if (xInfo->supportsService(pKnownModules[i]))
return pKnownModules[i];
}
return ::rtl::OUString();
}
} // namespace framework
| 41.06872 | 176 | 0.533264 | [
"model"
] |
c8e982aa410e897b0900e217af650e3a35dd9bd0 | 22,224 | cc | C++ | third_party/gloo/gloo/transport/tcp/pair.cc | Hosseinabady/caffe2_fpga | d7a31107332d9288a672e8dadda7774cffb78561 | [
"MIT"
] | 6 | 2016-09-28T18:51:21.000Z | 2019-04-01T04:42:08.000Z | third_party/gloo/gloo/transport/tcp/pair.cc | axbaretto/torch | 80b25960ef1ef510c8f1cf77680593db2fb4e7c4 | [
"Apache-2.0"
] | null | null | null | third_party/gloo/gloo/transport/tcp/pair.cc | axbaretto/torch | 80b25960ef1ef510c8f1cf77680593db2fb4e7c4 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "gloo/transport/tcp/pair.h"
#include <sstream>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "gloo/common/error.h"
#include "gloo/common/logging.h"
#include "gloo/transport/tcp/buffer.h"
#define FD_INVALID (-1)
namespace gloo {
namespace transport {
namespace tcp {
Pair::Pair(
const std::shared_ptr<Device>& dev,
std::chrono::milliseconds timeout)
: dev_(dev),
state_(INITIALIZING),
sync_(false),
timeout_(timeout),
busyPoll_(false),
fd_(FD_INVALID),
sendBufferSize_(0),
ex_(nullptr) {
memset(&rx_, 0, sizeof(rx_));
memset(&tx_, 0, sizeof(tx_));
listen();
}
Pair::~Pair() {
this->close();
}
void Pair::close() {
// Needs lock so that this doesn't race with read/write of the
// underlying file descriptor on the device thread.
std::lock_guard<std::mutex> lock(m_);
if (state_ != CLOSED) {
changeState(CLOSED);
}
}
const Address& Pair::address() const {
return self_;
}
void Pair::connect(const std::vector<char>& bytes) {
auto peer = Address(bytes);
connect(peer);
}
static void setSocketBlocking(int fd, bool enable) {
auto rv = fcntl(fd, F_GETFL);
GLOO_ENFORCE_NE(rv, -1);
if (enable) {
rv &= ~O_NONBLOCK;
} else {
rv |= O_NONBLOCK;
}
rv = fcntl(fd, F_SETFL, rv);
GLOO_ENFORCE_NE(rv, -1);
}
void Pair::setSync(bool sync, bool busyPoll) {
std::unique_lock<std::mutex> lock(m_);
if (!sync) {
GLOO_THROW_INVALID_OPERATION_EXCEPTION("Can only switch to sync mode");
}
// Wait for pair to be connected. No need to wait for timeout here. If
// necessary, the connect path will timeout and signal this thread.
waitUntilConnected(lock, false);
if (state_ == CLOSED) {
signalIoFailure(
GLOO_ERROR_MSG("Socket unexpectedly closed ", peer_.str()));
}
if (!sync_) {
// If async, unregister from loop and switch socket to blocking mode
dev_->unregisterDescriptor(fd_);
setSocketBlocking(fd_, true);
// If the pair was still flushing a write, finish it.
if (tx_.buf_ != nullptr) {
auto rv = write(tx_);
GLOO_ENFORCE(rv, "Write must always succeed in sync mode");
tx_.buf_->handleSendCompletion();
memset(&tx_, 0, sizeof(tx_));
}
}
sync_ = true;
busyPoll_ = busyPoll;
}
void Pair::listen() {
std::lock_guard<std::mutex> lock(m_);
int rv;
const auto& attr = dev_->attr_;
auto fd = socket(attr.ai_family, attr.ai_socktype, attr.ai_protocol);
if (fd == -1) {
signalIoFailure(GLOO_ERROR_MSG("socket: ", strerror(errno)));
}
// Set SO_REUSEADDR to signal that reuse of the listening port is OK.
int on = 1;
rv = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (rv == -1) {
::close(fd);
signalIoFailure(GLOO_ERROR_MSG("setsockopt: ", strerror(errno)));
}
rv = bind(fd, (const sockaddr*)&attr.ai_addr, attr.ai_addrlen);
if (rv == -1) {
::close(fd);
signalIoFailure(GLOO_ERROR_MSG("bind: ", strerror(errno)));
}
// listen(2) on socket
fd_ = fd;
rv = ::listen(fd_, 1);
if (rv == -1) {
::close(fd_);
fd_ = FD_INVALID;
signalIoFailure(GLOO_ERROR_MSG("listen: ", strerror(errno)));
}
// Keep copy of address
self_ = Address::fromSockName(fd);
// Register with device so we're called when peer connects
changeState(LISTENING);
dev_->registerDescriptor(fd_, EPOLLIN, this);
return;
}
void Pair::connect(const Address& peer) {
std::unique_lock<std::mutex> lock(m_);
int rv;
socklen_t addrlen;
checkErrorState();
peer_ = peer;
// Addresses have to have same family
if (self_.ss_.ss_family != peer_.ss_.ss_family) {
GLOO_THROW_INVALID_OPERATION_EXCEPTION("address family mismatch");
}
if (self_.ss_.ss_family == AF_INET) {
struct sockaddr_in* sa = (struct sockaddr_in*)&self_.ss_;
struct sockaddr_in* sb = (struct sockaddr_in*)&peer_.ss_;
addrlen = sizeof(struct sockaddr_in);
rv = memcmp(&sa->sin_addr, &sb->sin_addr, sizeof(struct in_addr));
if (rv == 0) {
rv = sa->sin_port - sb->sin_port;
}
} else if (peer_.ss_.ss_family == AF_INET6) {
struct sockaddr_in6* sa = (struct sockaddr_in6*)&self_.ss_;
struct sockaddr_in6* sb = (struct sockaddr_in6*)&peer_.ss_;
addrlen = sizeof(struct sockaddr_in6);
rv = memcmp(&sa->sin6_addr, &sb->sin6_addr, sizeof(struct in6_addr));
if (rv == 0) {
rv = sa->sin6_port - sb->sin6_port;
}
} else {
GLOO_THROW_INVALID_OPERATION_EXCEPTION("unknown sa_family");
}
if (rv == 0) {
GLOO_THROW_INVALID_OPERATION_EXCEPTION("cannot connect to self");
}
// self_ < peer_; we are listening side.
if (rv < 0) {
waitUntilConnected(lock, true);
return;
}
// self_ > peer_; we are connecting side.
// First destroy listening socket.
dev_->unregisterDescriptor(fd_);
::close(fd_);
// Create new socket to connect to peer.
fd_ = socket(peer_.ss_.ss_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (fd_ == -1) {
signalIoFailure(GLOO_ERROR_MSG("socket: ", strerror(errno)));
}
// Set SO_REUSEADDR to signal that reuse of the source port is OK.
int on = 1;
rv = setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (rv == -1) {
::close(fd_);
fd_ = FD_INVALID;
signalIoFailure(GLOO_ERROR_MSG("setsockopt: ", strerror(errno)));
}
// Connect to peer
rv = ::connect(fd_, (struct sockaddr*)&peer_.ss_, addrlen);
if (rv == -1 && errno != EINPROGRESS) {
::close(fd_);
fd_ = FD_INVALID;
signalIoFailure(GLOO_ERROR_MSG("connect: ", strerror(errno)));
}
// Register with device so we're called when connection completes.
changeState(CONNECTING);
dev_->registerDescriptor(fd_, EPOLLIN | EPOLLOUT, this);
// Wait for connection to complete
waitUntilConnected(lock, true);
}
// write is called from:
// 1) the device thread (the handleEvents function)
// 2) a user thread (the send function)
//
// In either case, the lock is held and the write function
// below inherits it.
//
bool Pair::write(Op& op) {
std::array<struct iovec, 2> iov;
int ioc;
int nbytes;
int rv;
verifyConnected();
for (;;) {
ioc = 0;
nbytes = 0;
// Include preamble if necessary
if (op.nwritten_ < sizeof(op.preamble_)) {
iov[ioc].iov_base = ((char*)&op.preamble_) + op.nwritten_;
iov[ioc].iov_len = sizeof(op.preamble_) - op.nwritten_;
nbytes += iov[ioc].iov_len;
ioc++;
}
// Include remaining piece of buffer
int offset = op.preamble_.offset_;
int length = op.preamble_.length_;
if (op.nwritten_ > sizeof(op.preamble_)) {
offset += op.nwritten_ - sizeof(op.preamble_);
length -= op.nwritten_ - sizeof(op.preamble_);
}
iov[ioc].iov_base = ((char*)op.buf_->ptr_) + offset;
iov[ioc].iov_len = length;
nbytes += iov[ioc].iov_len;
ioc++;
// Write
rv = writev(fd_, iov.data(), ioc);
if (rv == -1) {
if (errno == EAGAIN) {
if (sync_) {
// Blocking call returning with EAGAIN indicates timeout
signalIoFailure(GLOO_ERROR_MSG("Write timeout ", peer_.str()));
} else {
// Async. This write is done.
return false;
}
}
// Retry on EINTR
if (errno == EINTR) {
continue;
}
// Unexpected error
signalIoFailure(
GLOO_ERROR_MSG("writev ", peer_.str(), ": ", strerror(errno)));
}
// From write(2) man page (NOTES section):
//
// If a write() is interrupted by a signal handler before any
// bytes are written, then the call fails with the error EINTR;
// if it is interrupted after at least one byte has been written,
// the call succeeds, and returns the number of bytes written.
//
// If rv < nbytes we ALWAYS retry, regardless of sync/async mode,
// since an EINTR may or may not have happened. If this was not
// the case, and the kernel buffer is full, the next call to
// write(2) will return EAGAIN, which is handled appropriately.
op.nwritten_ += rv;
if (rv < nbytes) {
continue;
}
GLOO_ENFORCE_EQ(rv, nbytes);
break;
}
return true;
}
// read is called from:
// 1) the device thread (the handleEvents function).
// 2) a user thread (the recv function) IFF the pair is in sync mode.
//
// In either case, the lock is held and the read function
// below inherits it.
//
bool Pair::read(Op& op) {
verifyConnected();
auto start = std::chrono::steady_clock::now();
for (;;) {
struct iovec iov;
if (op.nread_ < sizeof(op.preamble_)) {
// Read preamble
iov.iov_base = ((char*)&op.preamble_) + op.nread_;
iov.iov_len = sizeof(op.preamble_) - op.nread_;
} else {
// Read payload
if (op.buf_ == nullptr) {
op.buf_ = getBuffer(op.preamble_.slot_);
// Buffer not (yet) registered, leave it for next loop iteration
if (op.buf_ == nullptr) {
return false;
}
}
auto offset = op.nread_ - sizeof(op.preamble_);
iov.iov_base = ((char*)op.buf_->ptr_) + offset + op.preamble_.roffset_;
iov.iov_len = op.preamble_.length_ - offset;
// There must always be a non-zero number of bytes to read
GLOO_ENFORCE_GT(iov.iov_len, 0);
// Bytes read must be in bounds for target buffer
GLOO_ENFORCE_LE(
op.preamble_.roffset_ + op.preamble_.length_,
op.buf_->size_);
}
// If busy-poll has been requested AND sync mode has been enabled for pair
// we'll keep spinning calling recv() on socket by supplying MSG_DONTWAIT
// flag. This is more efficient in terms of latency than allowing the kernel
// to de-schedule this thread waiting for IO event to happen. The tradeoff
// is stealing the CPU core just for busy polling.
int rv = 0;
for (;;) {
// Alas, readv does not support flags, so we need to use recv
rv = ::recv(fd_, iov.iov_base, iov.iov_len, busyPoll_ ? MSG_DONTWAIT : 0);
if (rv == -1) {
// EAGAIN happens when (1) non-blocking and there are no more bytes left
// to read or (2) blocking and timeout occurs.
if (errno == EAGAIN) {
if (sync_) {
auto hasTimedOut = [&]{
return (timeout_ != kNoTimeout) &&
((std::chrono::steady_clock::now() - start) >= timeout_);
};
if (busyPoll_ && !hasTimedOut()) {
// Keep looping on EAGAIN if busy-poll flag has been set and the
// timeout (if set) hasn't been reached
continue;
} else {
// Either timeout on poll or blocking call returning with EAGAIN
// indicates timeout
signalIoFailure(
GLOO_ERROR_MSG("Read timeout ", peer_.str()));
}
} else {
// Async. This read is done.
return false;
}
}
// Retry on EINTR
if (errno == EINTR) {
continue;
}
// ECONNRESET happens when the remote peer unexpectedly terminates
if (errno == ECONNRESET) {
changeState(CLOSED);
}
// Unexpected error
signalIoFailure(GLOO_ERROR_MSG(
"Read error ", peer_.str(), ": ", strerror(errno)));
}
break;
}
// Transition to CLOSED on EOF
if (rv == 0) {
changeState(CLOSED);
if (sync_) {
signalIoFailure(GLOO_ERROR_MSG(
"Remote socket closed during sync read ", peer_.str()));
} else {
return false;
}
}
op.nread_ += rv;
// Verify the payload is non-empty after reading preamble
if (op.nread_ == sizeof(op.preamble_)) {
GLOO_ENFORCE_NE(op.preamble_.length_, 0);
}
// Return if op is complete
if (op.nread_ == sizeof(op.preamble_) + op.preamble_.length_) {
return true;
}
}
}
void Pair::handleEvents(int events) {
// Try to acquire the pair's lock so the device thread (the thread
// that ends up calling handleEvents) can mutate the tx and rx op
// fields of this instance. If the lock cannot be acquired that
// means some other thread is trying to mutate this pair's state,
// which in turn might require calling into (and locking) the
// underlying device (for example, when the pair transitions to the
// CLOSED state). To avoid deadlocks, attempt to lock the pair and
// skip handling the events until the next tick if the lock cannot
// be acquired.
std::unique_lock<std::mutex> lock(m_, std::try_to_lock);
if (!lock) {
return;
}
try {
checkErrorState();
if (state_ == CONNECTED) {
if (events & EPOLLOUT) {
GLOO_ENFORCE(
tx_.buf_ != nullptr,
"tx_.buf_ cannot be NULL because EPOLLOUT happened");
if (write(tx_)) {
tx_.buf_->handleSendCompletion();
memset(&tx_, 0, sizeof(tx_));
dev_->registerDescriptor(fd_, EPOLLIN, this);
cv_.notify_all();
} else {
// Write didn't complete, wait for epoll again
}
}
if (events & EPOLLIN) {
while (read(rx_)) {
rx_.buf_->handleRecvCompletion();
memset(&rx_, 0, sizeof(rx_));
}
}
return;
}
if (state_ == LISTENING) {
handleListening();
return;
}
if (state_ == CONNECTING) {
handleConnecting();
return;
}
GLOO_ENFORCE(false, "Unexpected state: ", state_);
} catch (const ::gloo::IoException&) {
// Catch IO exceptions on the event handling thread. The exception has
// already been saved and user threads signaled.
}
}
void Pair::handleListening() {
struct sockaddr_storage addr;
socklen_t addrlen = sizeof(addr);
int rv;
rv = accept(fd_, (struct sockaddr*)&addr, &addrlen);
// Close the listening file descriptor whether we've successfully connected
// or run into an error and will throw an exception.
dev_->unregisterDescriptor(fd_);
::close(fd_);
fd_ = FD_INVALID;
if (rv == -1) {
signalIoFailure(GLOO_ERROR_MSG("accept: ", strerror(errno)));
}
// Connected, replace file descriptor
fd_ = rv;
// Common connection-made code
handleConnected();
}
void Pair::handleConnecting() {
int optval;
socklen_t optlen = sizeof(optval);
int rv;
// Verify that connecting was successful
rv = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &optval, &optlen);
GLOO_ENFORCE_NE(rv, -1);
if (optval != 0) {
signalIoFailure(
GLOO_ERROR_MSG("connect ", peer_.str(), ": ", strerror(optval)));
}
// Common connection-made code
handleConnected();
}
void Pair::handleConnected() {
int rv;
// Reset addresses
self_ = Address::fromSockName(fd_);
peer_ = Address::fromPeerName(fd_);
// Make sure socket is non-blocking
setSocketBlocking(fd_, false);
int flag = 1;
socklen_t optlen = sizeof(flag);
rv = setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, optlen);
GLOO_ENFORCE_NE(rv, -1);
// Set timeout
struct timeval tv = {};
tv.tv_sec = timeout_.count() / 1000;
tv.tv_usec = (timeout_.count() % 1000) * 1000;
rv = setsockopt(fd_, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
GLOO_ENFORCE_NE(rv, -1);
rv = setsockopt(fd_, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
GLOO_ENFORCE_NE(rv, -1);
dev_->registerDescriptor(fd_, EPOLLIN, this);
changeState(CONNECTED);
}
// getBuffer must only be called when holding lock.
Buffer* Pair::getBuffer(int slot) {
for (;;) {
auto it = buffers_.find(slot);
if (it == buffers_.end()) {
// The remote peer already sent some bytes destined for the
// buffer at this slot, but this side of the pair hasn't
// registed it yet.
//
// The current strategy is to return and let the the device loop
// repeatedly call us again until the buffer has been
// registered. This essentially means busy waiting while
// yielding to other pairs. This is not a problem as this only
// happens at initialization time.
//
return nullptr;
}
return it->second;
}
}
void Pair::registerBuffer(Buffer* buf) {
std::lock_guard<std::mutex> lock(m_);
GLOO_ENFORCE(
buffers_.find(buf->slot_) == buffers_.end(),
"duplicate buffer for slot ",
buf->slot_);
buffers_[buf->slot_] = buf;
cv_.notify_all();
}
void Pair::unregisterBuffer(Buffer* buf) {
std::lock_guard<std::mutex> lock(m_);
buffers_.erase(buf->slot_);
}
// changeState must only be called when holding lock.
void Pair::changeState(state nextState) {
// Ignore nops
if (nextState == state_) {
return;
}
// State can only move forward
GLOO_ENFORCE_GT(nextState, state_);
// Clean up file descriptor when transitioning to CLOSED.
if (nextState == CLOSED) {
if (state_ == CONNECTED) {
if (!sync_) {
dev_->unregisterDescriptor(fd_);
}
::close(fd_);
fd_ = FD_INVALID;
} else if (state_ == LISTENING) {
// The pair may be in the LISTENING state when it is destructed.
if (fd_ != FD_INVALID) {
dev_->unregisterDescriptor(fd_);
::close(fd_);
fd_ = FD_INVALID;
}
} else if (state_ == CONNECTING) {
// The pair may be in the CONNECTING state when it is destructed.
if (fd_ != FD_INVALID) {
dev_->unregisterDescriptor(fd_);
::close(fd_);
fd_ = FD_INVALID;
}
} else {
GLOO_ENFORCE(false, "Invalid state: ", state_);
}
}
state_ = nextState;
cv_.notify_all();
}
void Pair::waitUntilConnected(
std::unique_lock<std::mutex>& lock,
bool useTimeout) {
auto pred = [&] {
checkErrorState();
return state_ >= CONNECTED;
};
auto timeoutSet = timeout_ != kNoTimeout;
if (useTimeout && timeoutSet) {
// Use a longer timeout when waiting for initial connect
auto done = cv_.wait_for(lock, timeout_ * 5, pred);
if (!done) {
signalIoFailure(GLOO_ERROR_MSG("Connect timeout ", peer_.str()));
}
} else {
cv_.wait(lock, pred);
}
}
void Pair::verifyConnected() {
// This code path should only be called after reaching the connected state
GLOO_ENFORCE_GE(
state_,
CONNECTED,
"Pair is not connected (",
self_.str(),
" <--> ",
peer_.str(),
")");
// Check if the socket has been closed. We were unable to tell if this was an
// error or normal tear down, but now throw since we are trying to do IO.
if (state_ == CLOSED) {
signalIoFailure(GLOO_ERROR_MSG("Socket closed ", peer_.str()));
}
}
void Pair::send(Op& op) {
std::unique_lock<std::mutex> lock(m_);
checkErrorState();
// The connect function already wait for the pair to become
// connected (both in listening and connecting mode).
// No need to wait again here.
verifyConnected();
// Try to size the send buffer such that the write below completes
// synchronously and we don't need to finish the write later.
auto size = 2 * (sizeof(op.preamble_) + op.preamble_.length_);
if (sendBufferSize_ < size) {
int rv;
int optval = size;
socklen_t optlen = sizeof(optval);
rv = setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &optval, optlen);
GLOO_ENFORCE_NE(rv, -1);
rv = getsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &optval, &optlen);
GLOO_ENFORCE_NE(rv, -1);
sendBufferSize_ = optval;
}
// Wait until event loop has finished current write. No need to wait for
// timeout here. If necessary, the ongoing write op will timeout and signal
// this thread.
if (!sync_ && tx_.buf_ != nullptr) {
cv_.wait(lock, [&]{
checkErrorState();
return tx_.buf_ == nullptr;
});
}
// Write to socket
if (sync_) {
auto rv = write(op);
GLOO_ENFORCE(rv, "Write must always succeed in sync mode");
op.buf_->handleSendCompletion();
} else {
// Write immediately without checking socket for writeability.
if (write(op)) {
op.buf_->handleSendCompletion();
return;
}
// Write didn't complete; pass to event loop
tx_ = op;
dev_->registerDescriptor(fd_, EPOLLIN | EPOLLOUT, this);
}
}
void Pair::recv() {
std::unique_lock<std::mutex> lock(m_);
checkErrorState();
auto rv = read(rx_);
GLOO_ENFORCE(rv, "Read must always succeed in sync mode");
rx_.buf_->handleRecvCompletion();
memset(&rx_, 0, sizeof(rx_));
}
std::unique_ptr<::gloo::transport::Buffer>
Pair::createSendBuffer(int slot, void* ptr, size_t size) {
auto buffer = new Buffer(this, slot, ptr, size);
return std::unique_ptr<::gloo::transport::Buffer>(buffer);
}
std::unique_ptr<::gloo::transport::Buffer>
Pair::createRecvBuffer(int slot, void* ptr, size_t size) {
auto buffer = new Buffer(this, slot, ptr, size);
registerBuffer(buffer);
return std::unique_ptr<::gloo::transport::Buffer>(buffer);
}
void Pair::signalIoFailureExternal(const std::string& msg) {
std::unique_lock<std::mutex> lock(m_);
signalIoFailure(msg);
};
void Pair::signalIoFailure(const std::string& msg) {
auto ex = ::gloo::IoException(msg);
if (ex_ == nullptr) {
// If we haven't seen an error yet, store the exception to throw on future
// calling threads.
ex_ = std::make_exception_ptr(ex);
// Loop through the buffers and signal that an error has occurred.
for (auto it = buffers_.begin(); it != buffers_.end(); it++) {
it->second->signalError(ex_);
}
// Signal any threads in the async path
cv_.notify_all();
}
// Finally, throw the exception on this thread.
throw ex;
};
void Pair::checkErrorState() {
// If we previously encountered an error, rethrow here.
if (ex_ != nullptr) {
std::rethrow_exception(ex_);
}
}
} // namespace tcp
} // namespace transport
} // namespace gloo
| 28.096081 | 80 | 0.631075 | [
"vector"
] |
c8ea69933414ebf146c598c5a3576fa0f413ea50 | 6,462 | cpp | C++ | Source/ThirdParty/TurboBadger/tb_select_item.cpp | elix22/AtomicGameEngine | 83bc2c12f1451aea0b5de691b512810f00d5ee06 | [
"Apache-2.0",
"MIT"
] | 3,170 | 2015-02-13T12:35:00.000Z | 2022-03-31T15:32:42.000Z | Source/ThirdParty/TurboBadger/tb_select_item.cpp | elix22/AtomicGameEngine | 83bc2c12f1451aea0b5de691b512810f00d5ee06 | [
"Apache-2.0",
"MIT"
] | 1,314 | 2015-02-13T12:30:08.000Z | 2021-11-22T14:10:02.000Z | Source/ThirdParty/TurboBadger/tb_select_item.cpp | elix22/AtomicGameEngine | 83bc2c12f1451aea0b5de691b512810f00d5ee06 | [
"Apache-2.0",
"MIT"
] | 683 | 2015-02-13T12:35:06.000Z | 2022-03-31T16:13:54.000Z | // ================================================================================
// == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
// == See tb_core.h for more information. ==
// ================================================================================
#include "tb_select.h"
#include "tb_menu_window.h"
#include "tb_widgets_listener.h"
#include "tb_language.h"
#include <assert.h>
#include <stdlib.h>
namespace tb {
/** TBSimpleLayoutItemWidget is a item containing a layout with the following:
-TBSkinImage showing the item image.
-TBTextField showing the item string.
-TBSkinImage showing the arrow for items with a submenu.
It also handles submenu events. */
class TBSimpleLayoutItemWidget : public TBLayout, private TBWidgetListener
{
public:
TBSimpleLayoutItemWidget(TBID image, TBSelectItemSource *source, const char *str);
~TBSimpleLayoutItemWidget();
virtual bool OnEvent(const TBWidgetEvent &ev);
private:
TBSelectItemSource *m_source;
TBTextField m_textfield;
TBSkinImage m_image;
TBSkinImage m_image_arrow;
TBMenuWindow *m_menu; ///< Points to the submenu window if opened
virtual void OnWidgetDelete(TBWidget *widget);
void OpenSubMenu();
void CloseSubMenu();
};
// == TBSimpleLayoutItemWidget ==============================================================================
TBSimpleLayoutItemWidget::TBSimpleLayoutItemWidget(TBID image, TBSelectItemSource *source, const char *str)
: m_source(source)
, m_menu(nullptr)
{
SetSkinBg(TBIDC("TBSelectItem"));
SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
SetPaintOverflowFadeout(false);
if (image)
{
m_image.SetSkinBg(image);
m_image.SetIgnoreInput(true);
AddChild(&m_image);
}
m_textfield.SetText(str);
m_textfield.SetTextAlign(TB_TEXT_ALIGN_LEFT);
m_textfield.SetIgnoreInput(true);
AddChild(&m_textfield);
if (source)
{
m_image_arrow.SetSkinBg(TBIDC("arrow.right"));
m_image_arrow.SetIgnoreInput(true);
AddChild(&m_image_arrow);
}
}
TBSimpleLayoutItemWidget::~TBSimpleLayoutItemWidget()
{
if (m_image_arrow.GetParent())
RemoveChild(&m_image_arrow);
RemoveChild(&m_textfield);
if (m_image.GetParent())
RemoveChild(&m_image);
CloseSubMenu();
}
bool TBSimpleLayoutItemWidget::OnEvent(const TBWidgetEvent &ev)
{
if (m_source && ev.type == EVENT_TYPE_CLICK && ev.target == this)
{
OpenSubMenu();
return true;
}
return false;
}
void TBSimpleLayoutItemWidget::OnWidgetDelete(TBWidget *widget)
{
assert(widget == m_menu);
CloseSubMenu();
}
void TBSimpleLayoutItemWidget::OpenSubMenu()
{
if (m_menu)
return;
// Open a new menu window for the submenu with this widget as target
m_menu = new TBMenuWindow(this, TBIDC("submenu"));
if (m_menu)
{
SetState(WIDGET_STATE_SELECTED, true);
m_menu->AddListener(this);
m_menu->Show(m_source, TBPopupAlignment(TB_ALIGN_RIGHT), -1);
}
}
void TBSimpleLayoutItemWidget::CloseSubMenu()
{
if (!m_menu)
return;
SetState(WIDGET_STATE_SELECTED, false);
m_menu->RemoveListener(this);
if (!m_menu->GetIsDying())
m_menu->Close();
m_menu = nullptr;
}
// == TBSelectItemViewer ==============================================================================
void TBSelectItemViewer::SetSource(TBSelectItemSource *source)
{
if (m_source == source)
return;
if (m_source)
m_source->m_viewers.Remove(this);
m_source = source;
if (m_source)
m_source->m_viewers.AddLast(this);
OnSourceChanged();
}
// == TBSelectItemSource ====================================================================================
TBSelectItemSource::~TBSelectItemSource()
{
TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
while (TBSelectItemViewer *viewer = iter.GetAndStep())
{
viewer->SetSource(nullptr);
}
m_viewers.RemoveAll();
// If this assert trig, you are deleting a model that's still set on some
// TBSelect widget. That might be dangerous.
assert(!m_viewers.HasLinks());
}
bool TBSelectItemSource::Filter(int index, const char *filter)
{
const char *str = GetItemString(index);
if (str && stristr(str, filter))
return true;
return false;
}
TBWidget *TBSelectItemSource::CreateItemWidget(int index, TBSelectItemViewer *viewer)
{
const char *string = GetItemString(index);
TBSelectItemSource *sub_source = GetItemSubSource(index);
TBID image = GetItemImage(index);
if (sub_source || image)
{
if (TBSimpleLayoutItemWidget *itemwidget = new TBSimpleLayoutItemWidget(image, sub_source, string))
return itemwidget;
}
else if (string && *string == '-')
{
if (TBSeparator *separator = new TBSeparator)
{
separator->SetGravity(WIDGET_GRAVITY_ALL);
separator->SetSkinBg(TBIDC("TBSelectItem.separator"));
return separator;
}
}
else if (TBTextField *textfield = new TBTextField)
{
textfield->SetSkinBg("TBSelectItem");
textfield->SetText(string);
textfield->SetTextAlign(TB_TEXT_ALIGN_LEFT);
return textfield;
}
return nullptr;
}
void TBSelectItemSource::InvokeItemChanged(int index, TBSelectItemViewer *exclude_viewer)
{
TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
while (TBSelectItemViewer *viewer = iter.GetAndStep())
if (viewer != exclude_viewer)
viewer->OnItemChanged(index);
}
void TBSelectItemSource::InvokeItemAdded(int index)
{
TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
while (TBSelectItemViewer *viewer = iter.GetAndStep())
viewer->OnItemAdded(index);
}
void TBSelectItemSource::InvokeItemRemoved(int index)
{
TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
while (TBSelectItemViewer *viewer = iter.GetAndStep())
viewer->OnItemRemoved(index);
}
void TBSelectItemSource::InvokeAllItemsRemoved()
{
TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
while (TBSelectItemViewer *viewer = iter.GetAndStep())
viewer->OnAllItemsRemoved();
}
}; // namespace tb
| 29.239819 | 109 | 0.641907 | [
"model"
] |
c8ec1cec00f9986509311edd6bf67d69f4cc9052 | 4,336 | cpp | C++ | libs/intrusive/example/doc_external_value_traits.cpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 2 | 2015-01-02T14:24:56.000Z | 2015-01-02T14:25:17.000Z | libs/intrusive/example/doc_external_value_traits.cpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 2 | 2019-01-13T23:45:51.000Z | 2019-02-03T08:13:26.000Z | libs/intrusive/example/doc_external_value_traits.cpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 4 | 2018-04-17T15:37:11.000Z | 2018-06-10T14:06:31.000Z | /////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2007-2013
//
// 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)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
//[doc_external_value_traits
#include <boost/intrusive/list.hpp>
#include <vector>
using namespace boost::intrusive;
//This type is not modifiable so we can't store hooks or custom nodes
typedef int identifier_t;
//This value traits will associate elements from an array of identifiers with
//elements of an array of nodes. The element i of the value array will use the
//node i of the node array:
class external_traits
{
//Non-copyable
external_traits(const external_traits &);
external_traits& operator=(const external_traits &);
public:
typedef list_node_traits<void*> node_traits;
typedef node_traits::node node;
typedef node * node_ptr;
typedef const node * const_node_ptr;
typedef identifier_t value_type;
typedef identifier_t * pointer;
typedef const identifier_t * const_pointer;
static const link_mode_type link_mode = normal_link;
external_traits(pointer ids, std::size_t NumElements)
: ids_(ids), nodes_(NumElements)
{}
///Note: non static functions!
node_ptr to_node_ptr (value_type &value)
{ return &this->nodes_[0] + (&value - this->ids_); }
const_node_ptr to_node_ptr (const value_type &value) const
{ return &this->nodes_[0] + (&value - this->ids_); }
pointer to_value_ptr(node_ptr n)
{ return this->ids_ + (n - &this->nodes_[0]); }
const_pointer to_value_ptr(const_node_ptr n) const
{ return this->ids_ + (n - &this->nodes_[0]); }
private:
pointer ids_;
//This is an array of nodes that is necessary to form the linked list
std::vector<list_node_traits<void*>::node> nodes_;
};
//This is the value traits class that will be stored in the container
//and that will lead to the external traits using the address
//of the container.
struct internal_traits
{
static const bool external_value_traits = true;
typedef external_traits value_traits;
template<class Container>
value_traits &get_value_traits(Container &cont);
template<class Container>
const value_traits &get_value_traits(const Container &cont) const;
};
//The intrusive list that will use external value traits
typedef list<identifier_t, value_traits<internal_traits> > List;
class data_holder
: public List
{
public:
data_holder(identifier_t *ids, std::size_t NumElements)
: List()
, external_traits_(ids, NumElements)
{}
external_traits external_traits_;
};
template<class Container>
internal_traits::value_traits &internal_traits::get_value_traits(Container &cont)
{ return static_cast<data_holder&>(cont).external_traits_; }
template<class Container>
const internal_traits::value_traits &internal_traits::get_value_traits(const Container &cont) const
{ return static_cast<const data_holder&>(cont).external_traits_; }
int main()
{
const int NumElements = 100;
//This is an array of ids that we want to "store"
identifier_t ids [NumElements];
//Initialize id objects, each one with a different number
for(int i = 0; i != NumElements; ++i) ids[i] = i;
//The data holding the list and the external traits
data_holder data(ids, NumElements);
//This list will store ids without modifying identifier_t instances
//Stateful value traits must be explicitly passed in the constructor.
List &my_list = data;
//Insert ids in reverse order in the list
for(identifier_t * it(&ids[0]), *itend(&ids[NumElements]); it != itend; ++it)
my_list.push_front(*it);
//Now test lists
List::const_iterator list_it (my_list.cbegin());
identifier_t *it_val(&ids[NumElements]-1), *it_rbeg_val(&ids[0] -1);
//Test the objects inserted in the base hook list
for(; it_val != it_rbeg_val; --it_val, ++list_it){
if(&*list_it != &*it_val) return 1;
}
return 0;
}
//]
| 33.353846 | 99 | 0.669742 | [
"vector"
] |
c8ed40428baa6bf6e826f765d8d1eee5251040a2 | 8,559 | cc | C++ | dali/operators/detection/box_encoder.cc | truthiswill/DALI | 1c96cb62018138585b616888d4616646135cedad | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-12-25T01:36:32.000Z | 2019-12-25T01:36:32.000Z | dali/operators/detection/box_encoder.cc | CZZLEGEND/DALI | efd1f39b32b893c320ad580e7e84557df8f73983 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/detection/box_encoder.cc | CZZLEGEND/DALI | efd1f39b32b893c320ad580e7e84557df8f73983 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2017-2018, NVIDIA 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.
#include <algorithm>
#include <cmath>
#include "dali/operators/detection/box_encoder.h"
namespace dali {
void BoxEncoder<CPUBackend>::CalculateIousForBox(float *ious, const BoundingBox &box) const {
ious[0] = box.IntersectionOverUnion(anchors_[0]);
unsigned best_idx = 0;
float best_iou = ious[0];
for (unsigned anchor_idx = 1; anchor_idx < anchors_.size(); ++anchor_idx) {
ious[anchor_idx] = box.IntersectionOverUnion(anchors_[anchor_idx]);
if (ious[anchor_idx] >= best_iou) {
best_iou = ious[anchor_idx];
best_idx = anchor_idx;
}
}
// For best default box matched with current object let iou = 2, to make sure there is a match,
// as this object will be the best (highest IOU), for this default box
ious[best_idx] = 2.;
}
vector<float> BoxEncoder<CPUBackend>::CalculateIous(const vector<BoundingBox> &boxes) const {
vector<float> ious(boxes.size() * anchors_.size());
for (unsigned bbox_idx = 0; bbox_idx < boxes.size(); ++bbox_idx) {
auto ious_row = ious.data() + bbox_idx * anchors_.size();
CalculateIousForBox(ious_row, boxes[bbox_idx]);
}
return ious;
}
unsigned BoxEncoder<CPUBackend>::FindBestBoxForAnchor(
unsigned anchor_idx, const vector<float> &ious, unsigned num_boxes) const {
unsigned best_idx = 0;
float best_iou = ious[anchor_idx];
for (unsigned bbox_idx = 1; bbox_idx < num_boxes; ++bbox_idx) {
if (ious[bbox_idx * anchors_.size() + anchor_idx] >= best_iou) {
best_iou = ious[bbox_idx * anchors_.size() + anchor_idx];
best_idx = bbox_idx;
}
}
return best_idx;
}
vector<std::pair<unsigned, unsigned>> BoxEncoder<CPUBackend>::MatchBoxesWithAnchors(
const vector<BoundingBox> &boxes) const {
const auto ious = CalculateIous(boxes);
vector<std::pair<unsigned, unsigned>> matches;
for (unsigned anchor_idx = 0; anchor_idx < anchors_.size(); ++anchor_idx) {
const auto best_idx = FindBestBoxForAnchor(anchor_idx, ious, boxes.size());
// Filter matches by criteria
if (ious[best_idx * anchors_.size() + anchor_idx] > criteria_) {
matches.push_back({best_idx, anchor_idx});
}
}
return matches;
}
vector<BoundingBox> BoxEncoder<CPUBackend>::ReadBoxesFromInput(
const float *in_boxes, unsigned num_boxes) const {
vector<BoundingBox> boxes;
boxes.reserve(num_boxes);
auto in_box_data = in_boxes;
for (unsigned idx = 0; idx < num_boxes; ++idx) {
boxes.push_back(BoundingBox::FromLtrb(in_box_data, BoundingBox::NoBounds()));
in_box_data += BoundingBox::kSize;
}
return boxes;
}
void BoxEncoder<CPUBackend>::WriteBoxToOutput(const std::array<float, BoundingBox::kSize> &box,
float *out_box_data) const {
for (unsigned idx = 0; idx < BoundingBox::kSize; ++idx)
out_box_data[idx] = box[idx];
}
void BoxEncoder<CPUBackend>::WriteAnchorsToOutput(float *out_boxes, int *out_labels) const {
if (offset_) {
std::memset(out_boxes, 0,
sizeof(std::remove_pointer<decltype(out_boxes)>::type)*BoundingBox::kSize*anchors_.size());
std::memset(out_labels, 0,
sizeof(std::remove_pointer<decltype(out_labels)>::type)*anchors_.size());
} else {
for (unsigned idx = 0; idx < anchors_.size(); ++idx) {
const auto box = anchors_[idx].AsCenterWh();
WriteBoxToOutput(box, out_boxes + idx * BoundingBox::kSize);
out_labels[idx] = 0;
}
}
}
// Calculate offset from CenterWH ref box and anchor
// based on eq (2) in https://arxiv.org/abs/1512.02325 with extra normalization
std::array<float, BoundingBox::kSize>
GetOffsets(std::array<float, BoundingBox::kSize> box,
std::array<float, BoundingBox::kSize> anchor,
const std::vector<float>& means,
const std::vector<float>& stds,
float scale) {
for (std::size_t i = 0; i < BoundingBox::kSize; ++i) {
box[i] *= scale;
anchor[i] *= scale;
}
return {((box[0] - anchor[0]) / anchor[2] - means[0]) / stds[0],
((box[1] - anchor[1]) / anchor[3] - means[1]) / stds[1],
(std::log(box[2] / anchor[2]) - means[2]) / stds[2],
(std::log(box[3] / anchor[3]) - means[3]) / stds[3]};
}
void BoxEncoder<CPUBackend>::WriteMatchesToOutput(
const vector<std::pair<unsigned, unsigned>> matches, const vector<BoundingBox> &boxes,
const int *labels, float *out_boxes, int *out_labels) const {
if (offset_) {
for (const auto &match : matches) {
const auto box = boxes[match.first].AsCenterWh();
const auto anchor = anchors_[match.second].AsCenterWh();
WriteBoxToOutput(GetOffsets(box, anchor, means_, stds_, scale_),
out_boxes + match.second * BoundingBox::kSize);
out_labels[match.second] = labels[match.first];
}
} else {
for (const auto &match : matches) {
const auto box = boxes[match.first].AsCenterWh();
WriteBoxToOutput(box, out_boxes + match.second * BoundingBox::kSize);
out_labels[match.second] = labels[match.first];
}
}
}
void BoxEncoder<CPUBackend>::RunImpl(SampleWorkspace &ws) {
const auto &bboxes_input = ws.Input<CPUBackend>(kBoxesInId);
const auto &labels_input = ws.Input<CPUBackend>(kLabelsInId);
const auto num_boxes = bboxes_input.dim(0);
const auto labels = labels_input.data<int>();
const auto boxes = ReadBoxesFromInput(bboxes_input.data<float>(), num_boxes);
// Create output
auto &bboxes_output = ws.Output<CPUBackend>(kBoxesOutId);
bboxes_output.set_type(bboxes_input.type());
bboxes_output.Resize({static_cast<int>(anchors_.size()), static_cast<int>(BoundingBox::kSize)});
auto out_boxes = bboxes_output.mutable_data<float>();
auto &labels_output = ws.Output<CPUBackend>(kLabelsOutId);
labels_output.set_type(labels_input.type());
labels_output.Resize({static_cast<int>(anchors_.size())});
auto out_labels = labels_output.mutable_data<int>();
WriteAnchorsToOutput(out_boxes, out_labels);
if (num_boxes == 0)
return;
const auto matches = MatchBoxesWithAnchors(boxes);
WriteMatchesToOutput(matches, boxes, labels, out_boxes, out_labels);
}
DALI_REGISTER_OPERATOR(BoxEncoder, BoxEncoder<CPUBackend>, CPU);
DALI_SCHEMA(BoxEncoder)
.DocStr(
R"code(Encodes input bounding boxes and labels using set of default boxes (anchors) passed
during op construction. Follows algorithm described in https://arxiv.org/abs/1512.02325 and
implemented in https://github.com/mlperf/training/tree/master/single_stage_detector/ssd
Inputs must be supplied as two Tensors: `BBoxes` containing bounding boxes represented as
`[l,t,r,b]`, and `Labels` containing the corresponding label for each bounding box.
Results are two tensors: `EncodedBBoxes` containing M encoded bounding boxes as `[l,t,r,b]`,
where M is number of anchors and `EncodedLabels` containing the corresponding label for each
encoded box.)code")
.NumInput(2)
.NumOutput(2)
.AddArg("anchors",
R"code(Anchors to be used for encoding. List of floats in ltrb format.)code",
DALI_FLOAT_VEC)
.AddOptionalArg(
"criteria",
R"code(Threshold IOU for matching bounding boxes with anchors. Value between 0 and 1.)code",
0.5f, false)
.AddOptionalArg(
"offset",
R"code(Returns normalized offsets `((encoded_bboxes*scale - anchors*scale) - mean) / stds`
in `EncodedBBoxes` using `std`, `mean` and `scale` arguments (default values are transparent).)code",
false)
.AddOptionalArg("scale",
R"code(Rescale the box and anchors values before offset calculation (e.g. to get back to absolute values).)code",
1.0f)
.AddOptionalArg("means",
R"code([x y w h] means for offset normalization.)code",
std::vector<float>{0.f, 0.f, 0.f, 0.f})
.AddOptionalArg("stds",
R"code([x y w h] standard deviations for offset normalization.)code",
std::vector<float>{1.f, 1.f, 1.f, 1.f});
} // namespace dali
| 38.728507 | 125 | 0.68723 | [
"object",
"vector"
] |
c8ee2a6b275b047991f7a5a76f5af8f7a2366cd1 | 1,542 | cpp | C++ | src/statefunctions/declaration.cpp | realliance/sWar | d5c502ad0d8c719194a0f7d4fed662daceeb2cfb | [
"BSL-1.0"
] | null | null | null | src/statefunctions/declaration.cpp | realliance/sWar | d5c502ad0d8c719194a0f7d4fed662daceeb2cfb | [
"BSL-1.0"
] | null | null | null | src/statefunctions/declaration.cpp | realliance/sWar | d5c502ad0d8c719194a0f7d4fed662daceeb2cfb | [
"BSL-1.0"
] | null | null | null | #include <algorithm>
#include <memory>
#include <vector>
#include "card.h"
#include "event.h"
#include "gamestate.h"
#include "playercontroller.h"
#include "statefunctions.h"
auto sWar::Declaration(GameState& state) -> GameState& {
for (const auto& victor : state.victors) {
if (state.hands.at(victor).empty()) {
state.casualties.push_back(victor);
continue;
}
if (state.decks.at(victor).size() <= 3) {
state.table.insert(
state.table.begin(),
state.decks.at(victor).begin(),
state.decks.at(victor).end());
state.decks.at(victor).clear();
continue;
}
state.table.insert(
state.table.begin(),
state.decks.at(victor).begin(),
state.decks.at(victor).begin() + 3);
state.decks.at(victor).erase(
state.decks.at(victor).begin(),
state.decks.at(victor).begin() + 3);
}
for (const auto& casuality : state.casualties) {
state.victors.erase(
std::find(state.victors.begin(), state.victors.end(), casuality));
}
for (int i = 0; i < state.playerCnt; i++) {
state.players.at(i)->ReceiveEvent(
Event{
/*type: */ Event::DeclarationOfWar,
/*playerCnt: */ static_cast<int>(state.victors.size()),
/*cardCnt: */ 0,
/*players: */ state.victors,
/*cards: */ {},
/*remainingCards: */ static_cast<int>(state.decks.at(i).size())});
}
if (!state.casualties.empty()) {
state.nextState = Surrender;
return state;
}
state.nextState = Regroup;
return state;
}
| 26.135593 | 74 | 0.603113 | [
"vector"
] |
c8ef70dd6e994a4537877a0c711ac36b02156b05 | 2,088 | cpp | C++ | project/src/VideoStream.cpp | CheerfulMushroom/PokeRanch | 490ce1587a2c062ed8ef88f2302666cc3f910f0a | [
"CC-BY-3.0"
] | null | null | null | project/src/VideoStream.cpp | CheerfulMushroom/PokeRanch | 490ce1587a2c062ed8ef88f2302666cc3f910f0a | [
"CC-BY-3.0"
] | null | null | null | project/src/VideoStream.cpp | CheerfulMushroom/PokeRanch | 490ce1587a2c062ed8ef88f2302666cc3f910f0a | [
"CC-BY-3.0"
] | 1 | 2021-05-25T20:56:51.000Z | 2021-05-25T20:56:51.000Z | #include <iostream>
#include <opencv2/opencv.hpp>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "VideoStream.h"
#include "Utils.h"
VideoStream::VideoStream(int cam_index) {
cam = cv::VideoCapture(cam_index);
glGenTextures(1, &texture);
glGenBuffers(1, &VBO);
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &EBO);
configure_VAO();
}
bool VideoStream::configure_VAO() {
GLfloat vertices[] = {
1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
GLuint indices[] = {
0, 1, 3,
1, 2, 3
};
shader = ShaderProgram("project/shaders/v_shader.txt", "project/shaders/f_shader.txt");
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void *) (0 * sizeof(GLfloat)));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void *) (3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(shader.get_program(), "ourTexture1"), 0);
glBindVertexArray(0);
glfwSwapInterval(1);
}
VideoStream::~VideoStream() {
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
}
void VideoStream::render() {
mat_to_texture(texture, frame, false);
shader.use();
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
void VideoStream::update() {
cam.read(frame);
}
cv::Mat VideoStream::get_frame() {
return frame;
} | 22.945055 | 105 | 0.655172 | [
"render"
] |
c8f062c5747a6a38825e31c987737801f910e251 | 106,170 | cpp | C++ | openstudiocore/src/model/ThermalZone.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | 1 | 2017-10-13T09:23:04.000Z | 2017-10-13T09:23:04.000Z | openstudiocore/src/model/ThermalZone.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | null | null | null | openstudiocore/src/model/ThermalZone.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | 1 | 2022-03-20T13:19:42.000Z | 2022-03-20T13:19:42.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. 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 copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* 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 HOLDER, THE UNITED STATES GOVERNMENT, OR ANY 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 "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include "AirLoopHVACSupplyPlenum.hpp"
#include "AirLoopHVACSupplyPlenum_Impl.hpp"
#include "AirTerminalSingleDuctParallelPIUReheat.hpp"
#include "AirTerminalSingleDuctParallelPIUReheat_Impl.hpp"
#include "AirLoopHVACReturnPlenum.hpp"
#include "AirLoopHVACReturnPlenum_Impl.hpp"
#include "ZoneHVACEquipmentList.hpp"
#include "ZoneHVACEquipmentList_Impl.hpp"
#include "Model.hpp"
#include "Model_Impl.hpp"
#include "Building.hpp"
#include "Building_Impl.hpp"
#include "SizingZone.hpp"
#include "SizingZone_Impl.hpp"
#include "BuildingStory.hpp"
#include "BuildingStory_Impl.hpp"
#include "SpaceType.hpp"
#include "SpaceType_Impl.hpp"
#include "DefaultConstructionSet.hpp"
#include "DefaultConstructionSet_Impl.hpp"
#include "DefaultScheduleSet.hpp"
#include "DefaultScheduleSet_Impl.hpp"
#include "Space.hpp"
#include "Space_Impl.hpp"
#include "SpaceLoad.hpp"
#include "SpaceLoad_Impl.hpp"
#include "Surface.hpp"
#include "Surface_Impl.hpp"
#include "InteriorPartitionSurfaceGroup.hpp"
#include "InteriorPartitionSurfaceGroup_Impl.hpp"
#include "InteriorPartitionSurface.hpp"
#include "InteriorPartitionSurface_Impl.hpp"
#include "ConstructionBase.hpp"
#include "ConstructionBase_Impl.hpp"
#include "DaylightingControl.hpp"
#include "DaylightingControl_Impl.hpp"
#include "IlluminanceMap.hpp"
#include "IlluminanceMap_Impl.hpp"
#include "RenderingColor.hpp"
#include "RenderingColor_Impl.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include "PortList.hpp"
#include "PortList_Impl.hpp"
#include "AirLoopHVAC.hpp"
#include "AirLoopHVAC_Impl.hpp"
#include "Thermostat.hpp"
#include "Thermostat_Impl.hpp"
#include "ThermostatSetpointDualSetpoint.hpp"
#include "ThermostatSetpointDualSetpoint_Impl.hpp"
#include "ZoneControlContaminantController.hpp"
#include "ZoneControlContaminantController_Impl.hpp"
#include "ZoneControlHumidistat.hpp"
#include "ZoneControlHumidistat_Impl.hpp"
#include "DesignSpecificationOutdoorAir.hpp"
#include "DesignSpecificationOutdoorAir_Impl.hpp"
#include "Schedule.hpp"
#include "Schedule_Impl.hpp"
#include "AirLoopHVACZoneSplitter.hpp"
#include "AirLoopHVACZoneSplitter_Impl.hpp"
#include "AirLoopHVACZoneMixer.hpp"
#include "AirLoopHVACZoneMixer_Impl.hpp"
#include "LifeCycleCost.hpp"
#include "LifeCycleCost_Impl.hpp"
#include "SetpointManagerSingleZoneReheat.hpp"
#include "SetpointManagerSingleZoneReheat_Impl.hpp"
#include "SetpointManagerSingleZoneCooling.hpp"
#include "SetpointManagerSingleZoneCooling_Impl.hpp"
#include "SetpointManagerSingleZoneHeating.hpp"
#include "SetpointManagerSingleZoneHeating_Impl.hpp"
#include "ZoneMixing.hpp"
#include "ZoneMixing_Impl.hpp"
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/OS_ThermalZone_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include "../utilities/geometry/Transformation.hpp"
#include "../utilities/geometry/Geometry.hpp"
#include "../utilities/geometry/Point3d.hpp"
#include "../utilities/geometry/Vector3d.hpp"
#include "../utilities/units/Unit.hpp"
#include "../utilities/units/QuantityConverter.hpp"
#include "../utilities/math/FloatCompare.hpp"
#include "../utilities/core/Assert.hpp"
#include "../utilities/sql/SqlFile.hpp"
#include <QCoreApplication>
//NOTE:MAY BE USE QCoreApplication::processEvents(); later in for loop when slow
namespace openstudio {
namespace model {
namespace detail {
ThermalZone_Impl::ThermalZone_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle)
: HVACComponent_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == ThermalZone::iddObjectType());
}
ThermalZone_Impl::ThermalZone_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: HVACComponent_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == ThermalZone::iddObjectType());
}
ThermalZone_Impl::ThermalZone_Impl(const ThermalZone_Impl& other,
Model_Impl* model,
bool keepHandle)
: HVACComponent_Impl(other,model,keepHandle)
{}
boost::optional<ParentObject> ThermalZone_Impl::parent() const
{
return boost::optional<ParentObject>(this->model().building());
}
std::vector<ModelObject> ThermalZone_Impl::children() const
{
std::vector<ModelObject> result;
// Sizing Zone object
SizingZone sizingZone = this->sizingZone();
result.push_back(sizingZone);
// DLM: temporarily add supplyZoneMixing as children so we can see them in IG
// remove once we have gridview for these
for (const auto& mixing : supplyZoneMixing()){
result.push_back(mixing);
}
return result;
}
bool ThermalZone_Impl::setParent(ParentObject& newParent)
{
bool result = false;
if (newParent.optionalCast<Building>()){
result = (this->model() == newParent.model());
}
return result;
}
std::vector<IddObjectType> ThermalZone_Impl::allowableChildTypes() const
{
std::vector<IddObjectType> result;
// DLM: this does not seem to agree with implementation of children()
result.push_back(IddObjectType::OS_ThermostatSetpoint_DualSetpoint);
result.push_back(IddObjectType::OS_ZoneControl_Thermostat_StagedDualSetpoint);
return result;
}
const std::vector<std::string>& ThermalZone_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
result.push_back("Zone Outdoor Air Drybulb Temperature");
result.push_back("Zone Outdoor Air Wetbulb Temperature");
result.push_back("Zone Outdoor Air Wind Speed");
result.push_back("Zone Total Internal Radiant Heating Energy");
result.push_back("Zone Total Internal Visible Radiation Heating Energy");
result.push_back("Zone Total Internal Convective Heating Energy");
result.push_back("Zone Total Internal Latent Gain Energy");
result.push_back("Zone Total Internal Total Heating Energy");
result.push_back("Zone People Occupant Count");
result.push_back("Zone People Radiant Heating Energy");
result.push_back("Zone People Convective Heating Energy");
result.push_back("Zone People Sensible Heating Energy");
result.push_back("Zone People Latent Gain Energy");
result.push_back("Zone People Total Heating Energy");
result.push_back("Zone Lights Electric Power");
result.push_back("Zone Lights Radiant Heating Energy");
result.push_back("Zone Lights Visible Radiation Heating Energy");
result.push_back("Zone Lights Convective Heating Energy");
result.push_back("Zone Lights Return Air Heating Energy");
result.push_back("Zone Lights Total Heating Energy");
result.push_back("Zone Lights Electric Energy");
result.push_back("Zone Electric Equipment Radiant Heating Energy");
result.push_back("Zone Electric Equipment Convective Heating Energy");
result.push_back("Zone Electric Equipment Latent Gain Energy");
result.push_back("Zone Electric Equipment Lost Heat Energy");
result.push_back("Zone Electric Equipment Total Heating Energy");
result.push_back("Zone Electric Equipment Electric Energy");
result.push_back("Zone Electric Equipment Electric Power");
result.push_back("Zone Electric Equipment Radiant Heating Energy");
result.push_back("Zone Electric Equipment Latent Gain Energy");
result.push_back("Zone Electric Equipment Lost Heat Energy");
result.push_back("Zone Electric Equipment Total Heating Energy");
result.push_back("Zone Electric Equipment Electric Energy");
result.push_back("Zone Windows Total Transmitted Solar Radiation Rate");
result.push_back("Zone Exterior Windows Total Transmitted Beam Solar Radiation Rate");
result.push_back("Zone Interior Windows Total Transmitted Beam Solar Radiation Rate");
result.push_back("Zone Exterior Windows Total Transmitted Diffuse Solar Radiation Rate");
result.push_back("Zone Interior Windows Total Transmitted Diffuse Solar Radiation Rate");
result.push_back("Zone Windows Total Heat Gain Rate");
result.push_back("Zone Windows Total Heat Loss Rate");
result.push_back("Zone Windows Total Transmitted Solar Radiation Energy");
result.push_back("Zone Exterior Windows Total Transmitted Beam Solar Radiation Energy");
result.push_back("Zone Interior Windows Total Transmitted Beam Solar Radiation Energy");
result.push_back("Zone Exterior Windows Total Transmitted Diffuse Solar Radiation Rate");
result.push_back("Zone Interior Windows Total Transmitted Diffuse Solar Radiation Rate");
result.push_back("Zone Windows Total Heat Gain Energy");
result.push_back("Zone Windows Total Heat Loss Energy");
result.push_back("Zone Mean Radiant Temperature");
result.push_back("Zone Mean Air Temperature");
result.push_back("Zone Operative Temperature");
result.push_back("Zone Mean Air Humidity Ratio");
result.push_back("Zone Air Heat Balance Internal Convective Heat Gain Rate");
result.push_back("Zone Air Heat Balance Surface Convection Rate");
result.push_back("Zone Air Heat Balance Interzone Air Transfer Rate");
result.push_back("Zone Air Heat Balance Outdoor Air Transfer Rate");
result.push_back("Zone Air Heat Balance System Air Transfer Rate");
result.push_back("Zone Air Heat Balance Air Energy Storage Rate");
result.push_back("Zone Infiltration Sensible Heat Loss Energy");
result.push_back("Zone Infiltration Sensible Heat Gain Energy");
result.push_back("Zone Infiltration Sensible Heat Gain Energy");
result.push_back("Zone Infiltration Latent Heat Gain Energy");
result.push_back("Zone Infiltration Total Heat Loss Energy");
result.push_back("Zone Infiltration Total Heat Gain Energy");
result.push_back("Zone Infiltration Current Density Volume Flow Rate");
result.push_back("Zone Infiltration Standard Density Volume Flow Rate");
result.push_back("Zone Infiltration Current Density Volume");
result.push_back("Zone Infiltration Standard Density Volume");
result.push_back("Zone Infiltration Mass");
result.push_back("Zone Infiltration Air Change Rate");
result.push_back("Zone Air System Sensible Heating Energy");
result.push_back("Zone Air System Sensible Cooling Energy");
result.push_back("Zone Air System Sensible Heating Rate");
result.push_back("Zone Air System Sensible Cooling Rate");
result.push_back("Zone Air Temperature");
result.push_back("Zone Thermostat Air Temperature");
result.push_back("Zone Air Humidity Ratio");
result.push_back("Zone Air Relative Humidity");
result.push_back("Zone Predicted Sensible Load to Setpoint Heat Transfer Rate");
result.push_back("Zone Predicted Sensible Load to Heating Setpoint Heat Transfer Rate");
result.push_back("Zone Predicted Sensible Load to Cooling Setpoint Heat Transfer Rate");
result.push_back("Zone Predicted Moisture Load Moisture Transfer Rate");
result.push_back("Zone Predicted Moisture Load to Humidifying Setpoint Moisture Transfer Rate");
result.push_back("Zone Predicted Moisture Load to Dehumidifying Setpoint Moisture Transfer Rate");
result.push_back("Zone Thermostat Heating Setpoint Temperature");
result.push_back("Zone Thermostat Cooling Setpoint Temperature");
result.push_back("Zone Mechanical Ventilation No Load Heat Removal Energy");
result.push_back("Zone Mechanical Ventilation Cooling Load Increase Energy");
result.push_back("Zone Mechanical Ventilation Cooling Load Increase Energy Due to Overheating Energy");
result.push_back("Zone Mechanical Ventilation Cooling Load Decrease Energy");
result.push_back("Zone Mechanical Ventilation No Load Heat Addition Energy");
result.push_back("Zone Mechanical Ventilation No Load Heat Removal Energy");
result.push_back("Zone Mechanical Ventilation Cooling Load Increase Energy");
result.push_back("Zone Mechanical Ventilation Cooling Load Increase Energy Due to Overheating Energy");
result.push_back("Zone Mechanical Ventilation Cooling Load Decrease Energy");
result.push_back("Zone Mechanical Ventilation No Load Heat Addition Energy");
result.push_back("Zone Mechanical Ventilation Heating Load Increase Energy");
result.push_back("Zone Mechanical Ventilation Heating Load Increase Energy Due to Overcooling Energy");
result.push_back("Zone Mechanical Ventilation Heating Load Decrease Energy");
result.push_back("Zone Mechanical Ventilation Mass Flow Rate");
result.push_back("Zone Mechanical Ventilation Mass");
result.push_back("Zone Mechanical Ventilation Standard Density Volume Flow Rate");
result.push_back("Zone Mechanical Ventilation Standard Density Volume");
result.push_back("Zone Mechanical Ventilation Current Density Volume Flow Rate");
result.push_back("Zone Mechanical Ventilation Current Density Volume");
result.push_back("Zone Mechanical Ventilation Air Changes per Hour");
result.push_back("Zone Thermostat Control Type");
}
return result;
}
IddObjectType ThermalZone_Impl::iddObjectType() const {
return ThermalZone::iddObjectType();
}
std::vector<HVACComponent> ThermalZone_Impl::edges(const boost::optional<HVACComponent> & prev)
{
std::vector<HVACComponent> edges;
if( auto edgeModelObject = this->returnAirModelObject() ) {
if( auto edgeObject = edgeModelObject->optionalCast<HVACComponent>() ) {
edges.push_back(*edgeObject);
}
}
return edges;
}
int ThermalZone_Impl::multiplier() const {
boost::optional<int> value = getInt(OS_ThermalZoneFields::Multiplier,true);
OS_ASSERT(value);
return value.get();
}
bool ThermalZone_Impl::isMultiplierDefaulted() const {
return isEmpty(OS_ThermalZoneFields::Multiplier);
}
boost::optional<double> ThermalZone_Impl::ceilingHeight() const {
return getDouble(OS_ThermalZoneFields::CeilingHeight,true);
}
OSOptionalQuantity ThermalZone_Impl::getCeilingHeight(bool returnIP) const {
OSOptionalQuantity value = getQuantity(OS_ThermalZoneFields::CeilingHeight,true,returnIP);
return value;
}
bool ThermalZone_Impl::isCeilingHeightDefaulted() const {
return isEmpty(OS_ThermalZoneFields::CeilingHeight);
}
bool ThermalZone_Impl::isCeilingHeightAutocalculated() const {
bool result = false;
boost::optional<std::string> value = getString(OS_ThermalZoneFields::CeilingHeight, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autocalculate");
}
return result;
}
boost::optional<double> ThermalZone_Impl::volume() const {
return getDouble(OS_ThermalZoneFields::Volume,true);
}
OSOptionalQuantity ThermalZone_Impl::getVolume(bool returnIP) const {
OSOptionalQuantity value = getQuantity(OS_ThermalZoneFields::Volume,true,returnIP);
return value;
}
bool ThermalZone_Impl::isVolumeDefaulted() const {
return isEmpty(OS_ThermalZoneFields::Volume);
}
bool ThermalZone_Impl::isVolumeAutocalculated() const {
bool result = false;
boost::optional<std::string> value = getString(OS_ThermalZoneFields::Volume, true);
if (value) {
result = openstudio::istringEqual(value.get(), "autocalculate");
}
return result;
}
boost::optional<std::string> ThermalZone_Impl::zoneInsideConvectionAlgorithm() const {
return getString(OS_ThermalZoneFields::ZoneInsideConvectionAlgorithm,true);
}
boost::optional<std::string> ThermalZone_Impl::zoneOutsideConvectionAlgorithm() const {
return getString(OS_ThermalZoneFields::ZoneOutsideConvectionAlgorithm,true);
}
std::string ThermalZone_Impl::zoneConditioningEquipmentListName() const {
boost::optional<std::string> value = getString(OS_ThermalZoneFields::ZoneConditioningEquipmentListName,true);
OS_ASSERT(value);
return value.get();
}
double ThermalZone_Impl::fractionofZoneControlledbyPrimaryDaylightingControl() const {
boost::optional<double> value = getDouble(OS_ThermalZoneFields::FractionofZoneControlledbyPrimaryDaylightingControl,true);
OS_ASSERT(value);
return value.get();
}
Quantity ThermalZone_Impl::getFractionofZoneControlledbyPrimaryDaylightingControl(bool returnIP) const {
OSOptionalQuantity value = getQuantity(OS_ThermalZoneFields::FractionofZoneControlledbyPrimaryDaylightingControl,true,returnIP);
OS_ASSERT(value.isSet());
return value.get();
}
bool ThermalZone_Impl::isFractionofZoneControlledbyPrimaryDaylightingControlDefaulted() const {
return isEmpty(OS_ThermalZoneFields::FractionofZoneControlledbyPrimaryDaylightingControl);
}
double ThermalZone_Impl::fractionofZoneControlledbySecondaryDaylightingControl() const {
boost::optional<double> value = getDouble(OS_ThermalZoneFields::FractionofZoneControlledbySecondaryDaylightingControl,true);
OS_ASSERT(value);
return value.get();
}
Quantity ThermalZone_Impl::getFractionofZoneControlledbySecondaryDaylightingControl(bool returnIP) const {
OSOptionalQuantity value = getQuantity(OS_ThermalZoneFields::FractionofZoneControlledbySecondaryDaylightingControl,true,returnIP);
OS_ASSERT(value.isSet());
return value.get();
}
bool ThermalZone_Impl::isFractionofZoneControlledbySecondaryDaylightingControlDefaulted() const {
return isEmpty(OS_ThermalZoneFields::FractionofZoneControlledbySecondaryDaylightingControl);
}
bool ThermalZone_Impl::setMultiplier(int multiplier) {
bool result = setInt(OS_ThermalZoneFields::Multiplier, multiplier);
return result;
}
void ThermalZone_Impl::resetMultiplier() {
bool result = setString(OS_ThermalZoneFields::Multiplier, "");
OS_ASSERT(result);
}
void ThermalZone_Impl::setCeilingHeight(boost::optional<double> ceilingHeight) {
bool result = false;
if (ceilingHeight) {
result = setDouble(OS_ThermalZoneFields::CeilingHeight, ceilingHeight.get());
} else {
result = setString(OS_ThermalZoneFields::CeilingHeight, "");
}
OS_ASSERT(result);
}
void ThermalZone_Impl::setCeilingHeight(double ceilingHeight) {
bool result = setDouble(OS_ThermalZoneFields::CeilingHeight, ceilingHeight);
OS_ASSERT(result);
}
bool ThermalZone_Impl::setCeilingHeight(const OSOptionalQuantity& ceilingHeight) {
bool result;
if (ceilingHeight.isSet()) {
result = setQuantity(OS_ThermalZoneFields::CeilingHeight,ceilingHeight.get());
} else {
result = setString(OS_ThermalZoneFields::CeilingHeight, "");
}
return result;
}
void ThermalZone_Impl::resetCeilingHeight() {
bool result = setString(OS_ThermalZoneFields::CeilingHeight, "");
OS_ASSERT(result);
}
void ThermalZone_Impl::autocalculateCeilingHeight() {
bool result = setString(OS_ThermalZoneFields::CeilingHeight, "autocalculate");
OS_ASSERT(result);
}
void ThermalZone_Impl::setVolume(boost::optional<double> volume) {
bool result = false;
if (volume) {
result = setDouble(OS_ThermalZoneFields::Volume, volume.get());
} else {
result = setString(OS_ThermalZoneFields::Volume, "");
}
OS_ASSERT(result);
}
void ThermalZone_Impl::setVolume(double volume) {
bool result = setDouble(OS_ThermalZoneFields::Volume, volume);
OS_ASSERT(result);
}
bool ThermalZone_Impl::setVolume(const OSOptionalQuantity& volume) {
bool result;
if (volume.isSet()) {
result = setQuantity(OS_ThermalZoneFields::Volume,volume.get());
} else {
result = setString(OS_ThermalZoneFields::Volume, "");
}
return result;
}
void ThermalZone_Impl::resetVolume() {
bool result = setString(OS_ThermalZoneFields::Volume, "");
OS_ASSERT(result);
}
void ThermalZone_Impl::autocalculateVolume() {
bool result = setString(OS_ThermalZoneFields::Volume, "autocalculate");
OS_ASSERT(result);
}
bool ThermalZone_Impl::setZoneInsideConvectionAlgorithm(boost::optional<std::string> zoneInsideConvectionAlgorithm) {
bool result = false;
if (zoneInsideConvectionAlgorithm) {
result = setString(OS_ThermalZoneFields::ZoneInsideConvectionAlgorithm, zoneInsideConvectionAlgorithm.get());
} else {
result = setString(OS_ThermalZoneFields::ZoneInsideConvectionAlgorithm, "");
}
return result;
}
bool ThermalZone_Impl::setZoneInsideConvectionAlgorithm(std::string zoneInsideConvectionAlgorithm) {
bool result = setString(OS_ThermalZoneFields::ZoneInsideConvectionAlgorithm, zoneInsideConvectionAlgorithm);
return result;
}
void ThermalZone_Impl::resetZoneInsideConvectionAlgorithm() {
bool result = setString(OS_ThermalZoneFields::ZoneInsideConvectionAlgorithm, "");
OS_ASSERT(result);
}
bool ThermalZone_Impl::setZoneOutsideConvectionAlgorithm(boost::optional<std::string> zoneOutsideConvectionAlgorithm) {
bool result = false;
if (zoneOutsideConvectionAlgorithm) {
result = setString(OS_ThermalZoneFields::ZoneOutsideConvectionAlgorithm, zoneOutsideConvectionAlgorithm.get());
} else {
result = setString(OS_ThermalZoneFields::ZoneOutsideConvectionAlgorithm, "");
}
return result;
}
bool ThermalZone_Impl::setZoneOutsideConvectionAlgorithm(std::string zoneOutsideConvectionAlgorithm) {
bool result = setString(OS_ThermalZoneFields::ZoneOutsideConvectionAlgorithm, zoneOutsideConvectionAlgorithm);
return result;
}
void ThermalZone_Impl::resetZoneOutsideConvectionAlgorithm() {
bool result = setString(OS_ThermalZoneFields::ZoneOutsideConvectionAlgorithm, "");
OS_ASSERT(result);
}
void ThermalZone_Impl::setZoneConditioningEquipmentListName(std::string zoneConditioningEquipmentListName) {
bool result = setString(OS_ThermalZoneFields::ZoneConditioningEquipmentListName, zoneConditioningEquipmentListName);
OS_ASSERT(result);
}
bool ThermalZone_Impl::setFractionofZoneControlledbyPrimaryDaylightingControl(double fractionofZoneControlledbyPrimaryDaylightingControl) {
bool result = setDouble(OS_ThermalZoneFields::FractionofZoneControlledbyPrimaryDaylightingControl, fractionofZoneControlledbyPrimaryDaylightingControl);
return result;
}
bool ThermalZone_Impl::setFractionofZoneControlledbyPrimaryDaylightingControl(const Quantity& fractionofZoneControlledbyPrimaryDaylightingControl) {
return setQuantity(OS_ThermalZoneFields::FractionofZoneControlledbyPrimaryDaylightingControl,fractionofZoneControlledbyPrimaryDaylightingControl);
}
void ThermalZone_Impl::resetFractionofZoneControlledbyPrimaryDaylightingControl() {
bool result = setString(OS_ThermalZoneFields::FractionofZoneControlledbyPrimaryDaylightingControl, "");
OS_ASSERT(result);
}
bool ThermalZone_Impl::setFractionofZoneControlledbySecondaryDaylightingControl(double fractionofZoneControlledbySecondaryDaylightingControl) {
bool result = setDouble(OS_ThermalZoneFields::FractionofZoneControlledbySecondaryDaylightingControl, fractionofZoneControlledbySecondaryDaylightingControl);
return result;
}
bool ThermalZone_Impl::setFractionofZoneControlledbySecondaryDaylightingControl(const Quantity& fractionofZoneControlledbySecondaryDaylightingControl) {
return setQuantity(OS_ThermalZoneFields::FractionofZoneControlledbySecondaryDaylightingControl,fractionofZoneControlledbySecondaryDaylightingControl);
}
void ThermalZone_Impl::resetFractionofZoneControlledbySecondaryDaylightingControl() {
bool result = setString(OS_ThermalZoneFields::FractionofZoneControlledbySecondaryDaylightingControl, "");
OS_ASSERT(result);
}
unsigned ThermalZone_Impl::returnAirPort()
{
return OS_ThermalZoneFields::ZoneReturnAirNodeName;
}
unsigned ThermalZone_Impl::zoneAirPort()
{
return OS_ThermalZoneFields::ZoneAirNodeName;
}
OptionalModelObject ThermalZone_Impl::returnAirModelObject()
{
return this->connectedObject(this->returnAirPort());
}
Node ThermalZone_Impl::zoneAirNode()
{
return this->connectedObject(this->zoneAirPort())->cast<Node>();
}
boost::optional<DaylightingControl> ThermalZone_Impl::primaryDaylightingControl() const
{
return getObject<ModelObject>().getModelObjectTarget<DaylightingControl>(OS_ThermalZoneFields::PrimaryDaylightingControlName);
}
bool ThermalZone_Impl::setPrimaryDaylightingControl(const DaylightingControl& daylightingControl)
{
return setDaylightingControlsAndIlluminanceMaps(daylightingControl, this->secondaryDaylightingControl(), this->illuminanceMap());
}
void ThermalZone_Impl::resetPrimaryDaylightingControl()
{
bool test = setString(OS_ThermalZoneFields::PrimaryDaylightingControlName, "");
OS_ASSERT(test);
resetSecondaryDaylightingControl();
}
boost::optional<DaylightingControl> ThermalZone_Impl::secondaryDaylightingControl() const
{
return getObject<ModelObject>().getModelObjectTarget<DaylightingControl>(OS_ThermalZoneFields::SecondaryDaylightingControlName);
}
bool ThermalZone_Impl::setSecondaryDaylightingControl(const DaylightingControl& daylightingControl)
{
return setDaylightingControlsAndIlluminanceMaps(this->primaryDaylightingControl(), daylightingControl, this->illuminanceMap());
}
void ThermalZone_Impl::resetSecondaryDaylightingControl()
{
bool test = setString(OS_ThermalZoneFields::SecondaryDaylightingControlName, "");
OS_ASSERT(test);
}
boost::optional<IlluminanceMap> ThermalZone_Impl::illuminanceMap() const
{
return getObject<ModelObject>().getModelObjectTarget<IlluminanceMap>(OS_ThermalZoneFields::IlluminanceMapName);
}
bool ThermalZone_Impl::setIlluminanceMap(const IlluminanceMap& illuminanceMap)
{
return setDaylightingControlsAndIlluminanceMaps(this->primaryDaylightingControl(), this->secondaryDaylightingControl(), illuminanceMap);
}
void ThermalZone_Impl::resetIlluminanceMap()
{
bool test = setString(OS_ThermalZoneFields::IlluminanceMapName, "");
OS_ASSERT(test);
}
bool ThermalZone_Impl::setDaylightingControlsAndIlluminanceMaps(const boost::optional<DaylightingControl>& primaryDaylightingControl,
const boost::optional<DaylightingControl>& secondaryDaylightingControl,
const boost::optional<IlluminanceMap>& illuminanceMap)
{
resetPrimaryDaylightingControl();
resetSecondaryDaylightingControl();
resetIlluminanceMap();
bool result = true;
if (primaryDaylightingControl){
result = setPointer(OS_ThermalZoneFields::PrimaryDaylightingControlName, primaryDaylightingControl->handle());
}
if (secondaryDaylightingControl){
if (isEmpty(OS_ThermalZoneFields::PrimaryDaylightingControlName)){
result = false;
}else{
result = result && setPointer(OS_ThermalZoneFields::SecondaryDaylightingControlName, secondaryDaylightingControl->handle());
}
}
if (illuminanceMap){
boost::optional<Space> space = illuminanceMap->space();
if (space && (space->thermalZone()) && (space->thermalZone()->handle() == this->handle())){
result = result && setPointer(OS_ThermalZoneFields::IlluminanceMapName, illuminanceMap->handle());
}
}
return result;
}
void ThermalZone_Impl::checkDaylightingControlsAndIlluminanceMaps()
{
setDaylightingControlsAndIlluminanceMaps(this->primaryDaylightingControl(), this->secondaryDaylightingControl(), this->illuminanceMap());
}
boost::optional<RenderingColor> ThermalZone_Impl::renderingColor() const
{
return getObject<ModelObject>().getModelObjectTarget<RenderingColor>(OS_ThermalZoneFields::GroupRenderingName);
}
bool ThermalZone_Impl::setRenderingColor(const RenderingColor& renderingColor)
{
return setPointer(OS_ThermalZoneFields::GroupRenderingName, renderingColor.handle());
}
void ThermalZone_Impl::resetRenderingColor()
{
bool test = setString(OS_ThermalZoneFields::GroupRenderingName, "");
OS_ASSERT(test);
}
std::vector<Space> ThermalZone_Impl::spaces() const
{
return getObject<ModelObject>().getModelObjectSources<Space>(
Space::iddObjectType());
}
double ThermalZone_Impl::floorArea() const {
double result(0.0);
for (const Space& space : spaces()) {
result += space.floorArea();
}
return result;
}
double ThermalZone_Impl::exteriorSurfaceArea() const {
double result(0.0);
for (const Space& space : spaces()) {
result += space.exteriorArea();
}
return result;
}
double ThermalZone_Impl::exteriorWallArea() const {
double result(0.0);
for (const Space& space : spaces()) {
result += space.exteriorWallArea();
}
return result;
}
double ThermalZone_Impl::airVolume() const {
double result(0.0);
for (const Space& space : spaces()) {
result += space.volume();
}
return result;
}
double ThermalZone_Impl::numberOfPeople() const {
double result(0.0);
for (const Space& space : spaces()) {
result += space.numberOfPeople();
}
return result;
}
double ThermalZone_Impl::peoplePerFloorArea() const {
double area = floorArea();
double np = numberOfPeople();
if (equal(area,0.0)) {
if (equal(np,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].peoplePerFloorArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return np / area;
}
double ThermalZone_Impl::floorAreaPerPerson() const {
double area = floorArea();
double np = numberOfPeople();
if (equal(np,0.0)) {
if (spaces().size() == 1u) {
return spaces()[0].floorAreaPerPerson();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return area / np;
}
double ThermalZone_Impl::lightingPower() const {
double result(0.0);
for (const Space& space : spaces()){
result += space.lightingPower();
}
return result;
}
double ThermalZone_Impl::lightingPowerPerFloorArea() const {
double area = floorArea();
double lp = lightingPower();
if (equal(area,0.0)) {
if (equal(lp,0.0)) {
return 0.0;
}
else if (spaces().size() == 1u) {
return spaces()[0].lightingPowerPerFloorArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return lp / area;
}
double ThermalZone_Impl::lightingPowerPerPerson() const {
double np = numberOfPeople();
double lp = lightingPower();
if (equal(np,0.0)) {
if (equal(lp,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].lightingPowerPerPerson();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return lp / np;
}
double ThermalZone_Impl::electricEquipmentPower() const {
double result(0.0);
for (const Space& space : spaces()){
result += space.electricEquipmentPower();
}
return result;
}
double ThermalZone_Impl::electricEquipmentPowerPerFloorArea() const {
double area = floorArea();
double ep = electricEquipmentPower();
if (equal(area,0.0)) {
if (equal(ep,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].electricEquipmentPowerPerFloorArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return ep / area;
}
double ThermalZone_Impl::electricEquipmentPowerPerPerson() const {
double np = numberOfPeople();
double ep = electricEquipmentPower();
if (equal(np,0.0)) {
if (equal(ep,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].electricEquipmentPowerPerPerson();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return ep / np;
}
double ThermalZone_Impl::gasEquipmentPower() const {
double result(0.0);
for (const Space& space : spaces()){
result += space.gasEquipmentPower();
}
return result;
}
double ThermalZone_Impl::gasEquipmentPowerPerFloorArea() const {
double area = floorArea();
double ep = gasEquipmentPower();
if (equal(area,0.0)) {
if (equal(ep,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].gasEquipmentPowerPerFloorArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return ep / area;
}
double ThermalZone_Impl::gasEquipmentPowerPerPerson() const {
double np = numberOfPeople();
double ep = gasEquipmentPower();
if (equal(np,0.0)) {
if (equal(ep,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].gasEquipmentPowerPerPerson();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return ep / np;
}
double ThermalZone_Impl::infiltrationDesignFlowRate() const {
double result(0.0);
for (const Space& space : spaces()) {
result += space.infiltrationDesignFlowRate();
}
return result;
}
double ThermalZone_Impl::infiltrationDesignFlowPerSpaceFloorArea() const {
double area = floorArea();
double idfr = infiltrationDesignFlowRate();
if (equal(area,0.0)) {
if (equal(idfr,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].infiltrationDesignFlowPerSpaceFloorArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return idfr/area;
}
double ThermalZone_Impl::infiltrationDesignFlowPerExteriorSurfaceArea() const {
double area = exteriorSurfaceArea();
double idfr = infiltrationDesignFlowRate();
if (equal(area,0.0)) {
if (equal(idfr,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].infiltrationDesignFlowPerExteriorSurfaceArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return idfr/area;
}
double ThermalZone_Impl::infiltrationDesignFlowPerExteriorWallArea() const {
double area = exteriorWallArea();
double idfr = infiltrationDesignFlowRate();
if (equal(area,0.0)) {
if (equal(idfr,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].infiltrationDesignFlowPerExteriorWallArea();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return idfr/area;
}
double ThermalZone_Impl::infiltrationDesignAirChangesPerHour() const {
double volume = airVolume();
double idfr = infiltrationDesignFlowRate();
if (equal(volume,0.0)) {
if (equal(idfr,0.0)) {
return 0.0;
}
if (spaces().size() == 1u) {
return spaces()[0].infiltrationDesignAirChangesPerHour();
}
LOG_AND_THROW("Calculation would require division by 0.");
}
return convert(idfr/volume,"1/s","1/h").get();
}
boost::optional<std::string> ThermalZone_Impl::isConditioned() const {
boost::optional<std::string> result;
OptionalSqlFile mySqlFile = model().sqlFile();
// TODO: this should not require sql file
if (mySqlFile) {
// now use sql query to check if conditioned
std::string zoneName = boost::to_upper_copy(name(true).get());
result = mySqlFile->execAndReturnFirstString("SELECT Value from tabulardatawithstrings where (reportname = 'InputVerificationandResultsSummary') and (ReportForString = 'Entire Facility') and (TableName = 'Zone Summary' ) and (ColumnName ='Conditioned (Y/N)') and (RowName = '" + zoneName + "')");
if (!result){
LOG(Error, "Query for " << briefDescription() << " isConditioned failed.");
}
}
return result;
}
bool ThermalZone_Impl::isRemovable() const
{
//if( airLoopHVAC() )
//{
// return false;
//}
//else
//{
// return true;
//}
return true;
}
boost::optional<ThermostatSetpointDualSetpoint> ThermalZone_Impl::thermostatSetpointDualSetpoint() const
{
return getObject<ModelObject>().getModelObjectTarget<ThermostatSetpointDualSetpoint>(OS_ThermalZoneFields::ThermostatName);
}
bool ThermalZone_Impl::setThermostatSetpointDualSetpoint(const ThermostatSetpointDualSetpoint & thermostat)
{
return setThermostat(thermostat);
}
void ThermalZone_Impl::resetThermostatSetpointDualSetpoint()
{
// This will reset other thermostat types, but I think that is ok
resetThermostat();
}
boost::optional<Thermostat> ThermalZone_Impl::thermostat() const
{
return getObject<ModelObject>().getModelObjectTarget<Thermostat>(OS_ThermalZoneFields::ThermostatName);
}
bool ThermalZone_Impl::setThermostat(const Thermostat & thermostat)
{
auto t_model = model();
if( t_model != thermostat.model() ) {
return false;
}
if( auto currentZone = thermostat.thermalZone() ) {
if( currentZone->handle() == handle() ) {
// or should it be false?
// I think this is similar to what you would see in
// Lights::setSpace() under similar conditions
return true;
} else {
auto thermostatClone = thermostat.clone(t_model).cast<Thermostat>();
resetThermostat();
return setPointer(OS_ThermalZoneFields::ThermostatName, thermostatClone.handle());
}
} else {
resetThermostat();
return setPointer(OS_ThermalZoneFields::ThermostatName, thermostat.handle());
}
}
void ThermalZone_Impl::resetThermostat()
{
if( boost::optional<Thermostat> thermostat = this->thermostat() ) {
thermostat->remove();
}
setString(OS_ThermalZoneFields::ThermostatName, "");
}
boost::optional<ZoneControlHumidistat> ThermalZone_Impl::zoneControlHumidistat() const
{
return getObject<ModelObject>().getModelObjectTarget<ZoneControlHumidistat>(OS_ThermalZoneFields::HumidistatName);
}
bool ThermalZone_Impl::setZoneControlHumidistat(const ZoneControlHumidistat & humidistat)
{
auto t_model = model();
if( t_model != humidistat.model() ) {
return false;
}
if( auto currentZone = humidistat.controlledZone() ) {
if( currentZone->handle() == handle() ) {
return true;
} else {
auto humidistatClone = humidistat.clone(t_model).cast<ZoneControlHumidistat>();
resetZoneControlHumidistat();
return setPointer(OS_ThermalZoneFields::HumidistatName, humidistatClone.handle());
}
} else {
resetZoneControlHumidistat();
return setPointer(OS_ThermalZoneFields::HumidistatName, humidistat.handle());
}
}
void ThermalZone_Impl::resetZoneControlHumidistat()
{
if( boost::optional<ZoneControlHumidistat> humidistat = this->zoneControlHumidistat() ) {
humidistat->remove();
}
setString(OS_ThermalZoneFields::HumidistatName, "");
}
/// Combines all spaces referencing this zone into a single space referencing this zone.
/// If this zone has no spaces referencing it, then an uninitialized optional space is returned.
/// If this zone has one space referencing it, then that space is returned.
/// If this zone is referenced by more than one space, then geometry from all spaces is added to a single zone.
/// The space origin is at the minimum x, y, z coordinate of all space origins, direction of relative north is preserved if same for all spaces.
/// If all spaces reference the same building story then that is preserved, otherwise it is cleared.
/// If all spaces reference the same space type then that is preserved, otherwise space loads from the space type are applied to the new space directly.
/// Direct child space loads are converted to absolute levels.
/// Constructions and schedules are hard applied to all child surfaces and loads.
/// Surfaces referencing other surfaces within the space are converted to interior partitions.
boost::optional<Space> ThermalZone_Impl::combineSpaces()
{
std::vector<Space> spaces = this->spaces();
if (spaces.empty()){
return boost::none;
}else if (spaces.size() == 1){
return spaces[0];
}
// sort by space name
std::sort(spaces.begin(), spaces.end(), WorkspaceObjectNameLess());
// if these variables are set, then they are not defaulted and are common to all spaces
boost::optional<BuildingStory> buildingStory = spaces[0].buildingStory();
boost::optional<SpaceType> spaceType = spaces[0].spaceType();
boost::optional<double> directionofRelativeNorth;
if (!spaces[0].isDirectionofRelativeNorthDefaulted()){
directionofRelativeNorth = spaces[0].directionofRelativeNorth();
}
double xOrigin = spaces[0].xOrigin();
double yOrigin = spaces[0].yOrigin();
double zOrigin = spaces[0].zOrigin();
double sumFloorArea = 0.0;
double sumNumberOfPeople = 0.0;
double sumVolume = 0.0;
double totalFloorArea = 0.0; // only area included in total floor area
bool needToSetFloorArea = false;
bool anyNotPartofTotalFloorArea = false;
bool partofTotalFloorArea = spaces[0].partofTotalFloorArea();
// variables for merging outdoor area
boost::optional<DesignSpecificationOutdoorAir> designSpecificationOutdoorAir = spaces[0].designSpecificationOutdoorAir();
bool allDesignSpecificationOutdoorAirDefaulted = spaces[0].isDesignSpecificationOutdoorAirDefaulted();
bool anyDesignSpecificationOutdoorAirSchedules = false;
bool anyMaxOutdoorAirMethod = false;
bool anySumOutdoorAirMethod = false;
double sumOutdoorAirForPeople = 0.0;
double sumOutdoorAirForFloorArea = 0.0;
double sumOutdoorAirRate = 0.0;
double sumOutdoorAirForVolume = 0.0;
// Quick check to see what kind of ventilation methods are used
for (Space space : spaces){
if (boost::optional<DesignSpecificationOutdoorAir> designSpecificationOutdoorAir = space.designSpecificationOutdoorAir()) {
if (istringEqual("Maximum", designSpecificationOutdoorAir->outdoorAirMethod())){
anyMaxOutdoorAirMethod = true;
} else if(istringEqual("Sum", designSpecificationOutdoorAir->outdoorAirMethod())) {
anySumOutdoorAirMethod = true;
}
}
QCoreApplication::processEvents();
}
// find common variables for the new space
for (Space space : spaces){
// if all spaces are on the same building story use that, otherwise clear it
if (space.buildingStory()){
if (buildingStory && (buildingStory->handle() == space.buildingStory()->handle())){
// no-op
}else{
buildingStory.reset();
}
}else{
buildingStory.reset();
}
// if all spaces have the same space type use that, otherwise clear it
if (space.spaceType()){
if (spaceType && (spaceType->handle() == space.spaceType()->handle())){
// no-op
}else{
spaceType.reset();
}
}else{
spaceType.reset();
}
// if all spaces have same directionOfRelativeNorth use that, otherwise clear it
if (!space.isDirectionofRelativeNorthDefaulted()){
if (directionofRelativeNorth && (*directionofRelativeNorth == space.directionofRelativeNorth())){
// no-op
}else{
directionofRelativeNorth.reset();
}
}
// pick the lower left corner if specified
xOrigin = std::min(xOrigin, space.xOrigin());
yOrigin = std::min(yOrigin, space.yOrigin());
zOrigin = std::min(zOrigin, space.zOrigin());
double floorArea = space.floorArea();
sumFloorArea += floorArea;
double numberOfPeople = space.numberOfPeople();
sumNumberOfPeople += numberOfPeople;
double volume = space.volume();
sumVolume += volume;
// check if we have to explicitly set floor area and hard size loads
for (const Surface& surface : space.surfaces()) {
if (istringEqual(surface.surfaceType(), "Floor")){
// air wall floors do not count in floor area
if (surface.isAirWall()){
needToSetFloorArea = true;
break;
}
auto adjacentSurface = surface.adjacentSurface();
if (adjacentSurface){
auto adjacentSpace = adjacentSurface->space();
if (adjacentSpace){
auto adjacentThermalZone = adjacentSpace->thermalZone();
if (adjacentThermalZone){
if (adjacentThermalZone->handle() == this->handle())
{
// this surface is completely inside the zone, need to set floor area since this surface will be removed
needToSetFloorArea = true;
break;
}
}
}
}
}
QCoreApplication::processEvents();
}
// space floor area is counted if any space is part of floor area
if (space.partofTotalFloorArea()){
partofTotalFloorArea = true;
totalFloorArea += floorArea;
if (anyNotPartofTotalFloorArea){
needToSetFloorArea = true;
}
}else{
anyNotPartofTotalFloorArea = true;
if(partofTotalFloorArea){
needToSetFloorArea = true;
}
}
// if all spaces have the same outdoor air specification use that, otherwise clear it
boost::optional<DesignSpecificationOutdoorAir> thisDesignSpecificationOutdoorAir = space.designSpecificationOutdoorAir();
if (thisDesignSpecificationOutdoorAir){
if (designSpecificationOutdoorAir && (designSpecificationOutdoorAir->handle() == thisDesignSpecificationOutdoorAir->handle())){
// no-op
}else{
designSpecificationOutdoorAir.reset();
}
if (!space.isDesignSpecificationOutdoorAirDefaulted()){
allDesignSpecificationOutdoorAirDefaulted = false;
}
if (thisDesignSpecificationOutdoorAir->outdoorAirFlowRateFractionSchedule()){
anyDesignSpecificationOutdoorAirSchedules = true;
}
// compute outdoor air rates in case we need them
double outdoorAirForPeople = numberOfPeople*thisDesignSpecificationOutdoorAir->outdoorAirFlowperPerson();
double outdoorAirForFloorArea = floorArea*thisDesignSpecificationOutdoorAir->outdoorAirFlowperFloorArea();
double outdoorAirRate = thisDesignSpecificationOutdoorAir->outdoorAirFlowRate();
double outdoorAirForVolume = volume*thisDesignSpecificationOutdoorAir->outdoorAirFlowAirChangesperHour();
// First check if this space uses the Maximum method and other spaces do not
if (istringEqual("Maximum", thisDesignSpecificationOutdoorAir->outdoorAirMethod()) && anySumOutdoorAirMethod ){
sumOutdoorAirRate += std::max(outdoorAirForPeople,
std::max(outdoorAirForFloorArea,
std::max(outdoorAirRate,
outdoorAirForVolume)));
}else{
sumOutdoorAirForPeople += outdoorAirForPeople;
sumOutdoorAirForFloorArea += outdoorAirForFloorArea;
sumOutdoorAirRate += outdoorAirRate;
sumOutdoorAirForVolume += outdoorAirForVolume;
}
}else{
designSpecificationOutdoorAir.reset();
allDesignSpecificationOutdoorAirDefaulted = false;
}
QCoreApplication::processEvents();
}
// if all spaces share a common space type, ensure that there are no absolute loads
if (spaceType){
for (const auto& child : spaceType->children()){
if (child.optionalCast<SpaceLoad>()){
if (child.cast<SpaceLoad>().isAbsolute()){
LOG(Warn, "SpaceType '" << spaceType->name() << "' contains absolute loads, cannot be shared by combined spaces.")
spaceType.reset();
break;
}
}
QCoreApplication::processEvents();
}
}
// set E+ floor area here if needed, this is only used for reporting total building area
// loads are hard sized according to OpenStudio space floor area
if (needToSetFloorArea){
// do not allow per area loads in the space type since we are overriding floor area
spaceType.reset();
// don't override if user provided zone floor area
if (isEmpty(OS_ThermalZoneFields::FloorArea)){
this->setDouble(OS_ThermalZoneFields::FloorArea, totalFloorArea);
}
}
// make the new space
Model model = this->model();
Space newSpace(model);
ThermalZone thermalZone = this->getObject<ThermalZone>();
newSpace.setThermalZone(thermalZone);
newSpace.setXOrigin(xOrigin);
newSpace.setYOrigin(yOrigin);
newSpace.setZOrigin(zOrigin);
newSpace.setPartofTotalFloorArea(partofTotalFloorArea);
if (directionofRelativeNorth){
newSpace.setDirectionofRelativeNorth(*directionofRelativeNorth);
}
if (buildingStory){
newSpace.setBuildingStory(*buildingStory);
}
if (spaceType){
newSpace.setSpaceType(*spaceType);
}else{
// create a new space type
SpaceType newSpaceType(model);
// set space type to prevent picking up building level space type
newSpace.setSpaceType(newSpaceType);
}
// new space transformation
Transformation newTransformation = newSpace.transformation();
// set common variables for the new space
for (Space space : spaces){
// shift the geometry
space.changeTransformation(newTransformation);
// apply the space type
if (!spaceType){
space.hardApplySpaceType(true);
}
space.hardApplyConstructions();
// get the children
std::vector<ModelObject> children = space.children();
// first hard size any space loads, do this before removing surfaces as
// hard sizing may require space geometry
for (ModelObject child : children){
if (child.optionalCast<SpaceLoad>()){
child.cast<SpaceLoad>().hardSize();
child.cast<SpaceLoad>().hardApplySchedules();
}
QCoreApplication::processEvents();
}
// now move costs over to the new space
for (LifeCycleCost cost : space.lifeCycleCosts()){
// new costs are in absolute units as space area is changing in the merge
LifeCycleCost newCost(newSpace);
newCost.setName(cost.name().get());
newCost.setCategory(cost.category());
newCost.setCost(cost.totalCost());
newCost.setCostUnits("CostPerEach");
if (!cost.isYearsFromStartDefaulted()){
newCost.setYearsFromStart(cost.yearsFromStart());
}
if (!cost.isMonthsFromStartDefaulted()){
newCost.setMonthsFromStart(cost.monthsFromStart());
}
if (!cost.isRepeatPeriodYearsDefaulted()){
newCost.setRepeatPeriodYears(cost.repeatPeriodYears());
}
if (!cost.isRepeatPeriodMonthsDefaulted()){
newCost.setRepeatPeriodMonths(cost.repeatPeriodMonths());
}
QCoreApplication::processEvents();
}
// now move everything over to the new space
for (ModelObject child : children){
child.setParent(newSpace);
}
// remove the old space
space.remove();
}
// merge surfaces
boost::optional<InteriorPartitionSurfaceGroup> interiorPartitionSurfaceGroup;
std::set<Surface> mergedSurfaces;
// sort by surface name
std::vector<Surface> surfaces = newSpace.surfaces();
std::sort(surfaces.begin(), surfaces.end(), WorkspaceObjectNameLess());
for (Surface surface : surfaces){
auto it = mergedSurfaces.find(surface);
if (it != mergedSurfaces.end()){
continue;
}
boost::optional<Surface> adjacentSurface = surface.adjacentSurface();
if (adjacentSurface){
boost::optional<Space> adjacentSpace = adjacentSurface->space();
if (adjacentSpace && (newSpace.handle() == adjacentSpace->handle())){
// handling both the surface and the adjacentSurface
mergedSurfaces.insert(surface);
mergedSurfaces.insert(*adjacentSurface);
// don't make interior partitions for interior air walls
bool isAirWall = surface.isAirWall();
bool isAdjacentAirWall = adjacentSurface->isAirWall();
if (isAirWall && isAdjacentAirWall){
continue;
} else if (isAirWall){
LOG(Warn, "Interior surface '" << surface.name() << "' is an air wall but adjacent surface '" << adjacentSurface->name() << "' is not, ignoring internal mass.")
continue;
} else if (isAdjacentAirWall){
LOG(Warn, "Interior surface '" << adjacentSurface->name() << "' is an air wall but adjacent surface '" << surface.name() << "' is not, ignoring internal mass.")
continue;
}
if (!interiorPartitionSurfaceGroup){
interiorPartitionSurfaceGroup = InteriorPartitionSurfaceGroup(model);
interiorPartitionSurfaceGroup->setSpace(newSpace);
}
// DLM: is there a better way to pick which vertices to keep based on outward normal?
InteriorPartitionSurface interiorPartitionSurface(surface.vertices(), model);
interiorPartitionSurface.setName("Merged " + surface.name().get() + " - " + adjacentSurface->name().get());
interiorPartitionSurface.setInteriorPartitionSurfaceGroup(*interiorPartitionSurfaceGroup);
boost::optional<ConstructionBase> construction = surface.construction();
if (construction){
interiorPartitionSurface.setConstruction(*construction);
}
}
}
QCoreApplication::processEvents();
}
for (Surface mergedSurface : mergedSurfaces){
mergedSurface.remove();
}
// if there is a common designSpecificationOutdoorAir
if (designSpecificationOutdoorAir){
// allow new space to inherit from space type
bool useSpaceTypeOutdoorAir = false;
if (allDesignSpecificationOutdoorAirDefaulted){
if (spaceType){
if (spaceType->designSpecificationOutdoorAir()){
if (designSpecificationOutdoorAir->handle() == spaceType->designSpecificationOutdoorAir()->handle()){
useSpaceTypeOutdoorAir = true;
}
}
}
}
// set common designSpecificationOutdoorAir for the new space
if (!useSpaceTypeOutdoorAir){
newSpace.setDesignSpecificationOutdoorAir(*designSpecificationOutdoorAir);
}
}else{
double outdoorAirForPeople = 0.0;
if (sumOutdoorAirForPeople > 0 && sumNumberOfPeople > 0){
outdoorAirForPeople = sumOutdoorAirForPeople / sumNumberOfPeople;
}
double outdoorAirForFloorArea = 0.0;
if (sumOutdoorAirForFloorArea > 0 && sumFloorArea > 0){
outdoorAirForFloorArea = sumOutdoorAirForFloorArea / sumFloorArea;
}
double outdoorAirForVolume = 0.0;
if (sumOutdoorAirForVolume > 0 && sumVolume > 0){
outdoorAirForVolume = sumOutdoorAirForVolume / sumVolume;
}
// make a new designSpecificationOutdoorAir
designSpecificationOutdoorAir = DesignSpecificationOutdoorAir(model);
if( anySumOutdoorAirMethod && anyMaxOutdoorAirMethod ) {
designSpecificationOutdoorAir->setOutdoorAirMethod("Sum");
}else if( anyMaxOutdoorAirMethod ) {
designSpecificationOutdoorAir->setOutdoorAirMethod("Maximum");
}else{
designSpecificationOutdoorAir->setOutdoorAirMethod("Sum");
}
designSpecificationOutdoorAir->setOutdoorAirFlowperPerson(outdoorAirForPeople);
designSpecificationOutdoorAir->setOutdoorAirFlowperFloorArea(outdoorAirForFloorArea);
designSpecificationOutdoorAir->setOutdoorAirFlowRate(sumOutdoorAirRate);
designSpecificationOutdoorAir->setOutdoorAirFlowAirChangesperHour(outdoorAirForVolume);
if (anyDesignSpecificationOutdoorAirSchedules){
LOG(Warn, "DesignSpecificationOutdoorAir objects merged for ThermalZone '" << this->name() << "', could not preserve outdoor air flow rate fraction schedules");
}
newSpace.setDesignSpecificationOutdoorAir(*designSpecificationOutdoorAir);
}
return newSpace;
}
std::vector<IdfObject> ThermalZone_Impl::remove()
{
// this->blockSignals(true);
Model m = model();
// m.getImpl<QObject>()->blockSignals(true);
ThermalZone thermalZone = this->getObject<ThermalZone>();
if( boost::optional<AirLoopHVAC> airLoopHVAC = this->airLoopHVAC() )
{
airLoopHVAC->removeBranchForZone(thermalZone);
}
std::vector<ModelObject> comps = this->equipment();
for( auto & comp : comps )
{
comp.remove();
}
QCoreApplication::processEvents();
//detach it from the zone air node
Node airNode = this->zoneAirNode();
airNode.disconnect();
airNode.remove();
// remove port lists
inletPortList().remove();
exhaustPortList().remove();
// remove ZoneHVACEquipmentList
zoneHVACEquipmentList().remove();
// remove ZoneMixing objects
// DLM: these removed objects are not being returned in the result
for (auto mixing : this->zoneMixing()){
mixing.remove();
//std::vector<IdfObject> temp = mixing.remove();
//result.insert(result.end(), temp.begin(), temp.end());
}
QCoreApplication::processEvents();
//turn the object back on and proceed
// this->blockSignals(false);
// m.getImpl<QObject>()->blockSignals(false);
return HVACComponent_Impl::remove();
}
void ThermalZone_Impl::disconnect()
{
PortList pl = inletPortList();
unsigned plPort = pl.airLoopHVACPort();
ModelObject mo = this->getObject<ModelObject>();
Model _model = this->model();
_model.disconnect(pl,plPort);
_model.disconnect(mo,returnAirPort());
}
bool ThermalZone_Impl::useIdealAirLoads() const
{
boost::optional<std::string> value = getString(OS_ThermalZoneFields::UseIdealAirLoads);
OS_ASSERT(value);
return openstudio::istringEqual(value.get(), "Yes");
}
void ThermalZone_Impl::setUseIdealAirLoads(bool useIdealAirLoads)
{
if (useIdealAirLoads)
{
setString(OS_ThermalZoneFields::UseIdealAirLoads, "Yes");
std::vector<ModelObject> comps = this->equipment();
for( auto & comp : comps )
{
comp.remove();
}
QCoreApplication::processEvents();
if( boost::optional<AirLoopHVAC> airLoop = this->airLoopHVAC() )
{
ThermalZone thisObject = this->getObject<ThermalZone>();
airLoop->removeBranchForZone(thisObject);
}
}
else
{
setString(OS_ThermalZoneFields::UseIdealAirLoads, "No");
}
}
openstudio::OSOptionalQuantity ThermalZone_Impl::ceilingHeight_SI() const {
return getCeilingHeight(false);
}
openstudio::OSOptionalQuantity ThermalZone_Impl::ceilingHeight_IP() const {
return getCeilingHeight(true);
}
openstudio::OSOptionalQuantity ThermalZone_Impl::volume_SI() const {
return getVolume(false);
}
openstudio::OSOptionalQuantity ThermalZone_Impl::volume_IP() const {
return getVolume(true);
}
openstudio::Quantity ThermalZone_Impl::fractionofZoneControlledbyPrimaryDaylightingControl_SI() const {
return getFractionofZoneControlledbyPrimaryDaylightingControl(false);
}
openstudio::Quantity ThermalZone_Impl::fractionofZoneControlledbyPrimaryDaylightingControl_IP() const {
return getFractionofZoneControlledbyPrimaryDaylightingControl(true);
}
openstudio::Quantity ThermalZone_Impl::fractionofZoneControlledbySecondaryDaylightingControl_SI() const {
return getFractionofZoneControlledbySecondaryDaylightingControl(false);
}
openstudio::Quantity ThermalZone_Impl::fractionofZoneControlledbySecondaryDaylightingControl_IP() const {
return getFractionofZoneControlledbySecondaryDaylightingControl(true);
}
boost::optional<ModelObject> ThermalZone_Impl::thermostatSetpointDualSetpointAsModelObject() const {
OptionalModelObject result;
OptionalThermostatSetpointDualSetpoint intermediate = thermostatSetpointDualSetpoint();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> ThermalZone_Impl::zoneControlHumidistatAsModelObject() const {
OptionalModelObject result;
OptionalZoneControlHumidistat intermediate = zoneControlHumidistat();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> ThermalZone_Impl::primaryDaylightingControlAsModelObject() const {
OptionalModelObject result;
OptionalDaylightingControl intermediate = primaryDaylightingControl();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> ThermalZone_Impl::secondaryDaylightingControlAsModelObject() const {
OptionalModelObject result;
OptionalDaylightingControl intermediate = secondaryDaylightingControl();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> ThermalZone_Impl::illuminanceMapAsModelObject() const {
OptionalModelObject result;
OptionalIlluminanceMap intermediate = illuminanceMap();
if (intermediate) {
result = *intermediate;
}
return result;
}
boost::optional<ModelObject> ThermalZone_Impl::renderingColorAsModelObject() const {
OptionalModelObject result;
OptionalRenderingColor intermediate = renderingColor();
if (intermediate) {
result = *intermediate;
}
return result;
}
std::vector<ModelObject> ThermalZone_Impl::equipmentAsModelObjects() {
ModelObjectVector result = castVector<ModelObject>(equipment());
return result;
}
std::vector<ModelObject> ThermalZone_Impl::spacesAsModelObjects() const {
ModelObjectVector result = castVector<ModelObject>(spaces());
return result;
}
bool ThermalZone_Impl::setThermostatSetpointDualSetpointAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalThermostatSetpointDualSetpoint intermediate = modelObject->optionalCast<ThermostatSetpointDualSetpoint>();
if (intermediate) {
return setThermostatSetpointDualSetpoint(*intermediate);
}
else {
return false;
}
}
else {
resetThermostatSetpointDualSetpoint();
}
return true;
}
bool ThermalZone_Impl::setZoneControlHumidistatAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalZoneControlHumidistat intermediate = modelObject->optionalCast<ZoneControlHumidistat>();
if (intermediate) {
return setZoneControlHumidistat(*intermediate);
}
else {
return false;
}
}
else {
resetZoneControlHumidistat();
}
return true;
}
bool ThermalZone_Impl::setPrimaryDaylightingControlAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalDaylightingControl intermediate = modelObject->optionalCast<DaylightingControl>();
if (intermediate) {
return setPrimaryDaylightingControl(*intermediate);
}
else {
return false;
}
}
else {
resetPrimaryDaylightingControl();
}
return true;
}
bool ThermalZone_Impl::setSecondaryDaylightingControlAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalDaylightingControl intermediate = modelObject->optionalCast<DaylightingControl>();
if (intermediate) {
return setSecondaryDaylightingControl(*intermediate);
}
else {
return false;
}
}
else {
resetSecondaryDaylightingControl();
}
return true;
}
bool ThermalZone_Impl::setIlluminanceMapAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalIlluminanceMap intermediate = modelObject->optionalCast<IlluminanceMap>();
if (intermediate) {
return setIlluminanceMap(*intermediate);
}
else {
return false;
}
}
else {
resetIlluminanceMap();
}
return true;
}
bool ThermalZone_Impl::setRenderingColorAsModelObject(const boost::optional<ModelObject>& modelObject) {
if (modelObject) {
OptionalRenderingColor intermediate = modelObject->optionalCast<RenderingColor>();
if (intermediate) {
return setRenderingColor(*intermediate);
}
else {
return false;
}
}
else {
resetRenderingColor();
}
return true;
}
SizingZone ThermalZone_Impl::sizingZone() const
{
boost::optional<SizingZone> sizingZone;
std::vector<SizingZone> sizingObjects;
//sizingObjects = model().getConcreteModelObjects<SizingZone>();
sizingObjects = getObject<ModelObject>().getModelObjectSources<SizingZone>(SizingZone::iddObjectType());
for( const auto & sizingObject : sizingObjects )
{
if( sizingObject.thermalZone().handle() == this->handle() )
{
sizingZone = sizingObject;
}
}
if( sizingZone )
{
return sizingZone.get();
}
else
{
LOG_AND_THROW("ThermalZone missing Sizing:Zone object");
}
}
bool ThermalZone_Impl::addToNode(Node & node)
{
Model _model = model();
ThermalZone thisObject = getObject<ThermalZone>();
if( node.model() != _model )
{
return false;
}
if( isPlenum() )
{
return false;
}
boost::optional<AirLoopHVAC> airLoop = node.airLoopHVAC();
if( airLoop )
{
if( boost::optional<AirLoopHVAC> currentAirLoopHVAC = airLoopHVAC() )
{
if( currentAirLoopHVAC->handle() == airLoop->handle() )
{
return false;
}
currentAirLoopHVAC->removeBranchForZone(thisObject);
}
boost::optional<ModelObject> inletObj = node.inletModelObject();
boost::optional<ModelObject> outletObj = node.outletModelObject();
if( inletObj && outletObj )
{
if( (! inletObj->optionalCast<ThermalZone>()) && outletObj->optionalCast<Mixer>() )
{
Node newNode(_model);
ThermalZone thisobj = getObject<ThermalZone>();
PortList inletPortList = this->inletPortList();
unsigned oldMixerPort = node.connectedObjectPort( node.outletPort() ).get();
_model.connect( node, node.outletPort(),
inletPortList, inletPortList.nextPort() );
_model.connect( thisobj, returnAirPort(),
newNode, newNode.inletPort() );
_model.connect( newNode, newNode.outletPort(),
outletObj.get(), oldMixerPort );
// Add the terminal to equipment list
if( (! inletObj->optionalCast<Splitter>()) && (! inletObj->optionalCast<Node>()) )
{
addEquipment(inletObj.get());
if( boost::optional<AirTerminalSingleDuctParallelPIUReheat> terminal = inletObj->optionalCast<AirTerminalSingleDuctParallelPIUReheat>() )
{
Node secondaryInletNode(_model);
PortList t_exhaustPortList = exhaustPortList();
_model.connect( t_exhaustPortList,
t_exhaustPortList.nextPort(),
secondaryInletNode,
secondaryInletNode.inletPort() );
_model.connect( secondaryInletNode,
secondaryInletNode.outletPort(),
terminal.get(),
terminal->secondaryAirInletPort() );
}
}
setUseIdealAirLoads(false);
// If there is a single zone reheat spm, see if the control zone is set.
// If not set, then set it to this zone.
std::vector<ModelObject> supplyNodes = airLoop->supplyComponents(Node::iddObjectType());
for( const auto & supplyNode : supplyNodes )
{
{
std::vector<SetpointManagerSingleZoneReheat> setpointManagers = subsetCastVector<SetpointManagerSingleZoneReheat>(supplyNode.cast<Node>().setpointManagers());
if( ! setpointManagers.empty() ) {
SetpointManagerSingleZoneReheat spm = setpointManagers.front();
if( ! spm.controlZone() )
{
spm.setControlZone(thisobj);
}
}
}
{
std::vector<SetpointManagerSingleZoneCooling> setpointManagers = subsetCastVector<SetpointManagerSingleZoneCooling>(supplyNode.cast<Node>().setpointManagers());
if( ! setpointManagers.empty() ) {
SetpointManagerSingleZoneCooling spm = setpointManagers.front();
if( ! spm.controlZone() )
{
spm.setControlZone(thisobj);
}
}
}
{
std::vector<SetpointManagerSingleZoneHeating> setpointManagers = subsetCastVector<SetpointManagerSingleZoneHeating>(supplyNode.cast<Node>().setpointManagers());
if( ! setpointManagers.empty() ) {
SetpointManagerSingleZoneHeating spm = setpointManagers.front();
if( ! spm.controlZone() )
{
spm.setControlZone(thisobj);
}
}
}
QCoreApplication::processEvents();
}
return true;
}
}
}
return false;
}
PortList ThermalZone_Impl::inletPortList() const
{
boost::optional<PortList> pl = getObject<ModelObject>().getModelObjectTarget<PortList>(OS_ThermalZoneFields::ZoneAirInletPortList);
OS_ASSERT(pl);
return pl.get();
}
PortList ThermalZone_Impl::exhaustPortList() const
{
boost::optional<PortList> pl = getObject<ModelObject>().getModelObjectTarget<PortList>(OS_ThermalZoneFields::ZoneAirExhaustPortList);
OS_ASSERT(pl);
return pl.get();
}
ZoneHVACEquipmentList ThermalZone_Impl::zoneHVACEquipmentList() const
{
boost::optional<ZoneHVACEquipmentList> result;
std::vector<ZoneHVACEquipmentList> list = getObject<ModelObject>().getModelObjectSources<ZoneHVACEquipmentList>(ZoneHVACEquipmentList::iddObjectType());
//std::vector<ZoneHVACEquipmentList> list = model().getConcreteModelObjects<ZoneHVACEquipmentList>();
for( const auto & elem : list )
{
if( elem.thermalZone().handle() == handle() )
{
result = elem;
}
}
if (result)
{
return result.get();
} else
{
LOG_AND_THROW("ThermalZone missing ZoneHVAC:EquipmentList object");
}
}
void ThermalZone_Impl::addEquipment(const ModelObject & equipment)
{
zoneHVACEquipmentList().addEquipment(equipment);
}
void ThermalZone_Impl::removeEquipment(const ModelObject & equipment)
{
zoneHVACEquipmentList().removeEquipment(equipment);
}
void ThermalZone_Impl::setCoolingPriority(const ModelObject & equipment, unsigned priority)
{
zoneHVACEquipmentList().setCoolingPriority(equipment,priority);
}
void ThermalZone_Impl::setHeatingPriority(const ModelObject & equipment, unsigned priority)
{
zoneHVACEquipmentList().setHeatingPriority(equipment,priority);
}
std::vector<ModelObject> ThermalZone_Impl::equipment() const
{
return zoneHVACEquipmentList().equipment();
}
std::vector<ModelObject> ThermalZone_Impl::equipmentInHeatingOrder()
{
return zoneHVACEquipmentList().equipmentInHeatingOrder();
}
std::vector<ModelObject> ThermalZone_Impl::equipmentInCoolingOrder()
{
return zoneHVACEquipmentList().equipmentInCoolingOrder();
}
ModelObject ThermalZone_Impl::clone(Model model) const
{
ThermalZone tz = HVACComponent_Impl::clone(model).cast<ThermalZone>();
// We need this because "connect" is first going to try to disconnect from anything
// currently attached. At this point tz is left pointing (through a connection) to the old zone air node,
// (because of ModelObject::clone behavior) so connecting to the new node will remove the connection joining
// the original zone and the original node.
tz.setString(OS_ThermalZoneFields::ZoneAirNodeName,"");
tz.setString(OS_ThermalZoneFields::ThermostatName,"");
tz.setString(OS_ThermalZoneFields::HumidistatName,"");
Node node(model);
model.connect(tz,tz.zoneAirPort(),node,node.inletPort());
PortList inletPortList(tz);
tz.setPointer(OS_ThermalZoneFields::ZoneAirInletPortList,inletPortList.handle());
PortList exhaustPortList(tz);
tz.setPointer(OS_ThermalZoneFields::ZoneAirExhaustPortList,exhaustPortList.handle());
auto sizingZoneClone = sizingZone().clone(model).cast<SizingZone>();
sizingZoneClone.getImpl<detail::SizingZone_Impl>()->setThermalZone(tz);
ZoneHVACEquipmentList equipmentList(tz);
if( auto t_thermostat = thermostat() ) {
auto thermostatClone = t_thermostat->clone(model).cast<Thermostat>();
tz.setThermostat(thermostatClone);
}
if( auto t_humidistat = zoneControlHumidistat() ) {
auto humidistatClone = t_humidistat->clone(model).cast<ZoneControlHumidistat>();
tz.setZoneControlHumidistat(humidistatClone);
}
if( auto t_controller = zoneControlContaminantController() ) {
auto controllerClone = t_controller->clone(model).cast<ZoneControlContaminantController>();
tz.setZoneControlContaminantController(controllerClone);
}
// DLM: do not clone zone mixing objects
return tz;
}
boost::optional<AirLoopHVACSupplyPlenum> ThermalZone_Impl::airLoopHVACSupplyPlenum() const
{
boost::optional<AirLoopHVACSupplyPlenum> result;
std::vector<AirLoopHVACSupplyPlenum> plenums = model().getConcreteModelObjects<AirLoopHVACSupplyPlenum>();
for(const auto & plenum : plenums)
{
if( boost::optional<ThermalZone> tz = plenum.thermalZone() )
{
if( tz->handle() == handle() )
{
return plenum;
}
}
}
return result;
}
boost::optional<AirLoopHVACReturnPlenum> ThermalZone_Impl::airLoopHVACReturnPlenum() const
{
boost::optional<AirLoopHVACReturnPlenum> result;
std::vector<AirLoopHVACReturnPlenum> plenums = model().getConcreteModelObjects<AirLoopHVACReturnPlenum>();
for(const auto & plenum : plenums)
{
if( boost::optional<ThermalZone> tz = plenum.thermalZone() )
{
if( tz->handle() == handle() )
{
return plenum;
}
}
}
return result;
}
bool ThermalZone_Impl::isPlenum() const
{
bool result = false;
if( airLoopHVACReturnPlenum() || airLoopHVACSupplyPlenum() )
{
result = true;
}
return result;
}
bool ThermalZone_Impl::canBePlenum() const
{
bool result = true;
if( airLoopHVAC() || (! equipment().empty()) )
{
result = false;
}
return result;
}
bool ThermalZone_Impl::setSupplyPlenum(const ThermalZone & plenumZone, unsigned branchIndex)
{
bool result = true;
if( ! plenumZone.canBePlenum() )
{
result = false;
}
boost::optional<AirLoopHVAC> t_airLoopHVAC = airLoopHVAC();
if( ! t_airLoopHVAC )
{
result = false;
}
boost::optional<AirLoopHVACSupplyPlenum> plenum;
if( result )
{
plenum = plenumZone.getImpl<ThermalZone_Impl>()->airLoopHVACSupplyPlenum();
boost::optional<AirLoopHVAC> plenumAirLoop;
if( plenum )
{
plenumAirLoop = plenum->airLoopHVAC();
}
if( plenumAirLoop )
{
if( plenumAirLoop.get() != t_airLoopHVAC.get() )
{
result = false;
}
}
}
Model t_model = model();
if( result )
{
if( ! plenum )
{
plenum = AirLoopHVACSupplyPlenum(t_model);
plenum->setThermalZone(plenumZone);
}
}
boost::optional<AirLoopHVACZoneSplitter> zoneSplitter;
if( result ) {
auto zoneSplitters = t_airLoopHVAC->zoneSplitters();
if( branchIndex < zoneSplitters.size() ) {
zoneSplitter = zoneSplitters[branchIndex];
}
}
if( ! zoneSplitter ) result = false;
if( result )
{
removeSupplyPlenum();
model::ModelObject mo = t_airLoopHVAC->demandComponents(zoneSplitter.get(),getObject<ThermalZone>(),Node::iddObjectType()).front();
Node node = mo.cast<Node>();
OS_ASSERT(plenum);
result = plenum->addToNode(node);
}
return result;
}
bool ThermalZone_Impl::setSupplyPlenum(const ThermalZone & plenumZone)
{
return setSupplyPlenum(plenumZone,0u);
}
void ThermalZone_Impl::removeSupplyPlenum(unsigned branchIndex)
{
Model t_model = model();
boost::optional<AirLoopHVAC> t_airLoopHVAC = airLoopHVAC();
if( t_airLoopHVAC )
{
boost::optional<AirLoopHVACZoneSplitter> zoneSplitter;
auto zoneSplitters = t_airLoopHVAC->zoneSplitters();
if( branchIndex < zoneSplitters.size() ) {
zoneSplitter = zoneSplitters[branchIndex];
}
if( zoneSplitter ) {
std::vector<ModelObject> modelObjects = t_airLoopHVAC->demandComponents(zoneSplitter.get(),getObject<ThermalZone>());
std::vector<AirLoopHVACSupplyPlenum> plenums = subsetCastVector<AirLoopHVACSupplyPlenum>(modelObjects);
boost::optional<AirLoopHVACSupplyPlenum> plenum;
if( ! plenums.empty() )
{
plenum = plenums.front();
}
if( plenum )
{
if( plenum->outletModelObjects().size() == 1u )
{
plenum->remove();
}
else
{
auto it = std::find(modelObjects.begin(),modelObjects.end(),plenum.get());
ModelObject plenumOutletModelObject = *(it + 1);
unsigned branchIndex = plenum->branchIndexForOutletModelObject(plenumOutletModelObject);
unsigned port = plenum->connectedObjectPort(plenum->outletPort(branchIndex)).get();
plenum->removePortForBranch(branchIndex);
t_model.connect(zoneSplitter.get(),zoneSplitter->nextOutletPort(),plenumOutletModelObject,port);
}
}
}
}
}
void ThermalZone_Impl::removeSupplyPlenum()
{
return removeSupplyPlenum(0u);
}
bool ThermalZone_Impl::setReturnPlenum(const ThermalZone & plenumZone)
{
bool result = true;
if( ! plenumZone.canBePlenum() )
{
result = false;
}
boost::optional<AirLoopHVAC> t_airLoopHVAC = airLoopHVAC();
if( ! t_airLoopHVAC )
{
result = false;
}
boost::optional<AirLoopHVACReturnPlenum> plenum;
if( result )
{
plenum = plenumZone.getImpl<ThermalZone_Impl>()->airLoopHVACReturnPlenum();
boost::optional<AirLoopHVAC> plenumAirLoop;
if( plenum )
{
plenumAirLoop = plenum->airLoopHVAC();
}
if( plenumAirLoop )
{
if( plenumAirLoop.get() != t_airLoopHVAC.get() )
{
result = false;
}
}
}
Model t_model = model();
if( result )
{
if( ! plenum )
{
plenum = AirLoopHVACReturnPlenum(t_model);
plenum->setThermalZone(plenumZone);
}
}
if( result )
{
removeReturnPlenum();
model::ModelObject mo = t_airLoopHVAC->demandComponents(getObject<ThermalZone>(),t_airLoopHVAC->zoneMixer(),Node::iddObjectType()).front();
Node node = mo.cast<Node>();
OS_ASSERT(plenum);
result = plenum->addToNode(node);
}
return result;
}
void ThermalZone_Impl::removeReturnPlenum()
{
Model t_model = model();
boost::optional<AirLoopHVAC> t_airLoopHVAC = airLoopHVAC();
if( t_airLoopHVAC )
{
AirLoopHVACZoneMixer zoneMixer = t_airLoopHVAC->zoneMixer();
std::vector<ModelObject> modelObjects = t_airLoopHVAC->demandComponents(getObject<ThermalZone>(),zoneMixer);
std::vector<AirLoopHVACReturnPlenum> plenums = subsetCastVector<AirLoopHVACReturnPlenum>(modelObjects);
boost::optional<AirLoopHVACReturnPlenum> plenum;
if( ! plenums.empty() )
{
plenum = plenums.front();
}
if( plenum )
{
if( plenum->inletModelObjects().size() == 1u )
{
plenum->remove();
}
else
{
auto it = std::find(modelObjects.begin(),modelObjects.end(),plenum.get());
ModelObject plenumInletModelObject = *(it - 1);
unsigned branchIndex = plenum->branchIndexForInletModelObject(plenumInletModelObject);
unsigned port = plenum->connectedObjectPort(plenum->inletPort(branchIndex)).get();
plenum->removePortForBranch(branchIndex);
t_model.connect(plenumInletModelObject,port,zoneMixer,zoneMixer.nextInletPort());
}
}
}
}
std::vector<ZoneMixing> ThermalZone_Impl::zoneMixing() const
{
return getObject<ModelObject>().getModelObjectSources<ZoneMixing>();
}
std::vector<ZoneMixing> ThermalZone_Impl::supplyZoneMixing() const
{
std::vector<ZoneMixing> result = this->zoneMixing();
Handle handle = this->handle();
auto new_end = std::remove_if(result.begin(), result.end(),
[&](const ZoneMixing& mixing){ return (mixing.zone().handle() != handle); });
result.erase(new_end, result.end());
return result;
}
std::vector<ZoneMixing> ThermalZone_Impl::exhaustZoneMixing() const
{
std::vector<ZoneMixing> result = this->zoneMixing();
Handle handle = this->handle();
auto new_end = std::remove_if(result.begin(), result.end(),
[&](const ZoneMixing& mixing){ return (!mixing.sourceZone() || (mixing.sourceZone()->handle() != handle)); });
result.erase(new_end, result.end());
return result;
}
boost::optional<HVACComponent> ThermalZone_Impl::airLoopHVACTerminal() const
{
if( auto mo = inletPortList().airLoopHVACModelObject() ) {
if( auto node = mo->optionalCast<Node>() ) {
if( auto nodeInlet = node->inletModelObject() ) {
if( ! nodeInlet->optionalCast<Splitter>() ) {
return nodeInlet->optionalCast<HVACComponent>();
}
}
}
}
return boost::none;
}
boost::optional<ZoneControlContaminantController> ThermalZone_Impl::zoneControlContaminantController() const
{
auto h = handle();
auto controllers = model().getConcreteModelObjects<ZoneControlContaminantController>();
for( const auto & controller : controllers ) {
if( auto zone = controller.getImpl<detail::ZoneControlContaminantController_Impl>()->controlledZone() ) {
if( zone->handle() == h ) {
return controller;
}
}
}
return boost::none;
}
bool ThermalZone_Impl::setZoneControlContaminantController(const ZoneControlContaminantController & contaminantController)
{
auto t_model = model();
if( t_model != contaminantController.model() ) {
return false;
}
if( auto currentZone = contaminantController.controlledZone() ) {
if( currentZone->handle() == handle() ) {
return true;
} else {
auto controllerClone = contaminantController.clone(t_model).cast<ZoneControlContaminantController>();
auto tz = getObject<ThermalZone>();
return controllerClone.getImpl<detail::ZoneControlContaminantController_Impl>()->setControlledZone(tz);
}
} else {
resetZoneControlContaminantController();
auto tz = getObject<ThermalZone>();
return contaminantController.getImpl<detail::ZoneControlContaminantController_Impl>()->setControlledZone(tz);
}
}
void ThermalZone_Impl::resetZoneControlContaminantController()
{
if( auto controller = zoneControlContaminantController() ) {
controller->remove();
}
}
} // detail
ThermalZone::ThermalZone(const Model& model)
: HVACComponent(ThermalZone::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::ThermalZone_Impl>());
Node node(model);
model.connect(*this,this->zoneAirPort(),node,node.inletPort());
PortList inletPortList(*this);
setPointer(OS_ThermalZoneFields::ZoneAirInletPortList,inletPortList.handle());
PortList exhaustPortList(*this);
setPointer(OS_ThermalZoneFields::ZoneAirExhaustPortList,exhaustPortList.handle());
SizingZone sizingZone(model,*this);
ZoneHVACEquipmentList equipmentList(*this);
setUseIdealAirLoads(false);
}
IddObjectType ThermalZone::iddObjectType() {
IddObjectType result(IddObjectType::OS_ThermalZone);
return result;
}
std::vector<std::string> ThermalZone::validZoneInsideConvectionAlgorithmValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_ThermalZoneFields::ZoneInsideConvectionAlgorithm);
}
std::vector<std::string> ThermalZone::validZoneOutsideConvectionAlgorithmValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_ThermalZoneFields::ZoneOutsideConvectionAlgorithm);
}
int ThermalZone::multiplier() const {
return getImpl<detail::ThermalZone_Impl>()->multiplier();
}
bool ThermalZone::isMultiplierDefaulted() const {
return getImpl<detail::ThermalZone_Impl>()->isMultiplierDefaulted();
}
boost::optional<double> ThermalZone::ceilingHeight() const {
return getImpl<detail::ThermalZone_Impl>()->ceilingHeight();
}
OSOptionalQuantity ThermalZone::getCeilingHeight(bool returnIP) const {
return getImpl<detail::ThermalZone_Impl>()->getCeilingHeight(returnIP);
}
bool ThermalZone::isCeilingHeightDefaulted() const {
return getImpl<detail::ThermalZone_Impl>()->isCeilingHeightDefaulted();
}
bool ThermalZone::isCeilingHeightAutocalculated() const {
return getImpl<detail::ThermalZone_Impl>()->isCeilingHeightAutocalculated();
}
boost::optional<double> ThermalZone::volume() const {
return getImpl<detail::ThermalZone_Impl>()->volume();
}
OSOptionalQuantity ThermalZone::getVolume(bool returnIP) const {
return getImpl<detail::ThermalZone_Impl>()->getVolume(returnIP);
}
bool ThermalZone::isVolumeDefaulted() const {
return getImpl<detail::ThermalZone_Impl>()->isVolumeDefaulted();
}
bool ThermalZone::isVolumeAutocalculated() const {
return getImpl<detail::ThermalZone_Impl>()->isVolumeAutocalculated();
}
boost::optional<std::string> ThermalZone::zoneInsideConvectionAlgorithm() const {
return getImpl<detail::ThermalZone_Impl>()->zoneInsideConvectionAlgorithm();
}
boost::optional<std::string> ThermalZone::zoneOutsideConvectionAlgorithm() const {
return getImpl<detail::ThermalZone_Impl>()->zoneOutsideConvectionAlgorithm();
}
std::string ThermalZone::zoneConditioningEquipmentListName() const {
return getImpl<detail::ThermalZone_Impl>()->zoneConditioningEquipmentListName();
}
double ThermalZone::fractionofZoneControlledbyPrimaryDaylightingControl() const {
return getImpl<detail::ThermalZone_Impl>()->fractionofZoneControlledbyPrimaryDaylightingControl();
}
Quantity ThermalZone::getFractionofZoneControlledbyPrimaryDaylightingControl(bool returnIP) const {
return getImpl<detail::ThermalZone_Impl>()->getFractionofZoneControlledbyPrimaryDaylightingControl(returnIP);
}
bool ThermalZone::isFractionofZoneControlledbyPrimaryDaylightingControlDefaulted() const {
return getImpl<detail::ThermalZone_Impl>()->isFractionofZoneControlledbyPrimaryDaylightingControlDefaulted();
}
double ThermalZone::fractionofZoneControlledbySecondaryDaylightingControl() const {
return getImpl<detail::ThermalZone_Impl>()->fractionofZoneControlledbySecondaryDaylightingControl();
}
Quantity ThermalZone::getFractionofZoneControlledbySecondaryDaylightingControl(bool returnIP) const {
return getImpl<detail::ThermalZone_Impl>()->getFractionofZoneControlledbySecondaryDaylightingControl(returnIP);
}
bool ThermalZone::isFractionofZoneControlledbySecondaryDaylightingControlDefaulted() const {
return getImpl<detail::ThermalZone_Impl>()->isFractionofZoneControlledbySecondaryDaylightingControlDefaulted();
}
bool ThermalZone::setMultiplier(int multiplier) {
return getImpl<detail::ThermalZone_Impl>()->setMultiplier(multiplier);
}
void ThermalZone::resetMultiplier() {
getImpl<detail::ThermalZone_Impl>()->resetMultiplier();
}
void ThermalZone::setCeilingHeight(boost::optional<double> ceilingHeight) {
getImpl<detail::ThermalZone_Impl>()->setCeilingHeight(ceilingHeight);
}
void ThermalZone::setCeilingHeight(double ceilingHeight) {
getImpl<detail::ThermalZone_Impl>()->setCeilingHeight(ceilingHeight);
}
bool ThermalZone::setCeilingHeight(const Quantity& ceilingHeight) {
return getImpl<detail::ThermalZone_Impl>()->setCeilingHeight(ceilingHeight);
}
void ThermalZone::resetCeilingHeight() {
getImpl<detail::ThermalZone_Impl>()->resetCeilingHeight();
}
void ThermalZone::autocalculateCeilingHeight() {
getImpl<detail::ThermalZone_Impl>()->autocalculateCeilingHeight();
}
void ThermalZone::setVolume(boost::optional<double> volume) {
getImpl<detail::ThermalZone_Impl>()->setVolume(volume);
}
void ThermalZone::setVolume(double volume) {
getImpl<detail::ThermalZone_Impl>()->setVolume(volume);
}
bool ThermalZone::setVolume(const Quantity& volume) {
return getImpl<detail::ThermalZone_Impl>()->setVolume(volume);
}
void ThermalZone::resetVolume() {
getImpl<detail::ThermalZone_Impl>()->resetVolume();
}
void ThermalZone::autocalculateVolume() {
getImpl<detail::ThermalZone_Impl>()->autocalculateVolume();
}
bool ThermalZone::setZoneInsideConvectionAlgorithm(boost::optional<std::string> zoneInsideConvectionAlgorithm) {
return getImpl<detail::ThermalZone_Impl>()->setZoneInsideConvectionAlgorithm(zoneInsideConvectionAlgorithm);
}
bool ThermalZone::setZoneInsideConvectionAlgorithm(std::string zoneInsideConvectionAlgorithm) {
return getImpl<detail::ThermalZone_Impl>()->setZoneInsideConvectionAlgorithm(zoneInsideConvectionAlgorithm);
}
void ThermalZone::resetZoneInsideConvectionAlgorithm() {
getImpl<detail::ThermalZone_Impl>()->resetZoneInsideConvectionAlgorithm();
}
bool ThermalZone::setZoneOutsideConvectionAlgorithm(boost::optional<std::string> zoneOutsideConvectionAlgorithm) {
return getImpl<detail::ThermalZone_Impl>()->setZoneOutsideConvectionAlgorithm(zoneOutsideConvectionAlgorithm);
}
bool ThermalZone::setZoneOutsideConvectionAlgorithm(std::string zoneOutsideConvectionAlgorithm) {
return getImpl<detail::ThermalZone_Impl>()->setZoneOutsideConvectionAlgorithm(zoneOutsideConvectionAlgorithm);
}
void ThermalZone::resetZoneOutsideConvectionAlgorithm() {
getImpl<detail::ThermalZone_Impl>()->resetZoneOutsideConvectionAlgorithm();
}
void ThermalZone::setZoneConditioningEquipmentListName(std::string zoneConditioningEquipmentListName) {
getImpl<detail::ThermalZone_Impl>()->setZoneConditioningEquipmentListName(zoneConditioningEquipmentListName);
}
bool ThermalZone::setFractionofZoneControlledbyPrimaryDaylightingControl(double fractionofZoneControlledbyPrimaryDaylightingControl) {
return getImpl<detail::ThermalZone_Impl>()->setFractionofZoneControlledbyPrimaryDaylightingControl(fractionofZoneControlledbyPrimaryDaylightingControl);
}
bool ThermalZone::setFractionofZoneControlledbyPrimaryDaylightingControl(const Quantity& fractionofZoneControlledbyPrimaryDaylightingControl) {
return getImpl<detail::ThermalZone_Impl>()->setFractionofZoneControlledbyPrimaryDaylightingControl(fractionofZoneControlledbyPrimaryDaylightingControl);
}
void ThermalZone::resetFractionofZoneControlledbyPrimaryDaylightingControl() {
getImpl<detail::ThermalZone_Impl>()->resetFractionofZoneControlledbyPrimaryDaylightingControl();
}
bool ThermalZone::setFractionofZoneControlledbySecondaryDaylightingControl(double fractionofZoneControlledbySecondaryDaylightingControl) {
return getImpl<detail::ThermalZone_Impl>()->setFractionofZoneControlledbySecondaryDaylightingControl(fractionofZoneControlledbySecondaryDaylightingControl);
}
bool ThermalZone::setFractionofZoneControlledbySecondaryDaylightingControl(const Quantity& fractionofZoneControlledbySecondaryDaylightingControl) {
return getImpl<detail::ThermalZone_Impl>()->setFractionofZoneControlledbySecondaryDaylightingControl(fractionofZoneControlledbySecondaryDaylightingControl);
}
void ThermalZone::resetFractionofZoneControlledbySecondaryDaylightingControl() {
getImpl<detail::ThermalZone_Impl>()->resetFractionofZoneControlledbySecondaryDaylightingControl();
}
unsigned ThermalZone::returnAirPort()
{
return getImpl<detail::ThermalZone_Impl>()->returnAirPort();
}
unsigned ThermalZone::zoneAirPort()
{
return getImpl<detail::ThermalZone_Impl>()->zoneAirPort();
}
OptionalModelObject ThermalZone::returnAirModelObject()
{
return getImpl<detail::ThermalZone_Impl>()->returnAirModelObject();
}
Node ThermalZone::zoneAirNode()
{
return getImpl<detail::ThermalZone_Impl>()->zoneAirNode();
}
boost::optional<DaylightingControl> ThermalZone::primaryDaylightingControl() const
{
return getImpl<detail::ThermalZone_Impl>()->primaryDaylightingControl();
}
bool ThermalZone::setPrimaryDaylightingControl(const DaylightingControl& daylightingControl)
{
return getImpl<detail::ThermalZone_Impl>()->setPrimaryDaylightingControl(daylightingControl);
}
void ThermalZone::resetPrimaryDaylightingControl()
{
getImpl<detail::ThermalZone_Impl>()->resetPrimaryDaylightingControl();
}
boost::optional<DaylightingControl> ThermalZone::secondaryDaylightingControl() const
{
return getImpl<detail::ThermalZone_Impl>()->secondaryDaylightingControl();
}
bool ThermalZone::setSecondaryDaylightingControl(const DaylightingControl& daylightingControl)
{
return getImpl<detail::ThermalZone_Impl>()->setSecondaryDaylightingControl(daylightingControl);
}
void ThermalZone::resetSecondaryDaylightingControl()
{
getImpl<detail::ThermalZone_Impl>()->resetSecondaryDaylightingControl();
}
boost::optional<IlluminanceMap> ThermalZone::illuminanceMap() const
{
return getImpl<detail::ThermalZone_Impl>()->illuminanceMap();
}
bool ThermalZone::setIlluminanceMap(const IlluminanceMap& illuminanceMap)
{
return getImpl<detail::ThermalZone_Impl>()->setIlluminanceMap(illuminanceMap);
}
void ThermalZone::resetIlluminanceMap()
{
getImpl<detail::ThermalZone_Impl>()->resetIlluminanceMap();
}
void ThermalZone::checkDaylightingControlsAndIlluminanceMaps()
{
getImpl<detail::ThermalZone_Impl>()->checkDaylightingControlsAndIlluminanceMaps();
}
boost::optional<RenderingColor> ThermalZone::renderingColor() const
{
return getImpl<detail::ThermalZone_Impl>()->renderingColor();
}
bool ThermalZone::setRenderingColor(const RenderingColor& renderingColor)
{
return getImpl<detail::ThermalZone_Impl>()->setRenderingColor(renderingColor);
}
void ThermalZone::resetRenderingColor()
{
getImpl<detail::ThermalZone_Impl>()->resetRenderingColor();
}
std::vector<Space> ThermalZone::spaces() const {
return getImpl<detail::ThermalZone_Impl>()->spaces();
}
double ThermalZone::floorArea() const {
return getImpl<detail::ThermalZone_Impl>()->floorArea();
}
double ThermalZone::exteriorSurfaceArea() const {
return getImpl<detail::ThermalZone_Impl>()->exteriorSurfaceArea();
}
double ThermalZone::exteriorWallArea() const {
return getImpl<detail::ThermalZone_Impl>()->exteriorWallArea();
}
double ThermalZone::airVolume() const {
return getImpl<detail::ThermalZone_Impl>()->airVolume();
}
double ThermalZone::numberOfPeople() const {
return getImpl<detail::ThermalZone_Impl>()->numberOfPeople();
}
double ThermalZone::peoplePerFloorArea() const {
return getImpl<detail::ThermalZone_Impl>()->peoplePerFloorArea();
}
double ThermalZone::floorAreaPerPerson() const {
return getImpl<detail::ThermalZone_Impl>()->floorAreaPerPerson();
}
double ThermalZone::lightingPower() const {
return getImpl<detail::ThermalZone_Impl>()->lightingPower();
}
double ThermalZone::lightingPowerPerFloorArea() const {
return getImpl<detail::ThermalZone_Impl>()->lightingPowerPerFloorArea();
}
double ThermalZone::lightingPowerPerPerson() const {
return getImpl<detail::ThermalZone_Impl>()->lightingPowerPerPerson();
}
double ThermalZone::electricEquipmentPower() const {
return getImpl<detail::ThermalZone_Impl>()->electricEquipmentPower();
}
double ThermalZone::electricEquipmentPowerPerFloorArea() const {
return getImpl<detail::ThermalZone_Impl>()->electricEquipmentPowerPerFloorArea();
}
double ThermalZone::electricEquipmentPowerPerPerson() const {
return getImpl<detail::ThermalZone_Impl>()->electricEquipmentPowerPerPerson();
}
double ThermalZone::gasEquipmentPower() const {
return getImpl<detail::ThermalZone_Impl>()->gasEquipmentPower();
}
double ThermalZone::gasEquipmentPowerPerFloorArea() const {
return getImpl<detail::ThermalZone_Impl>()->gasEquipmentPowerPerFloorArea();
}
double ThermalZone::gasEquipmentPowerPerPerson() const {
return getImpl<detail::ThermalZone_Impl>()->gasEquipmentPowerPerPerson();
}
double ThermalZone::infiltrationDesignFlowRate() const {
return getImpl<detail::ThermalZone_Impl>()->infiltrationDesignFlowRate();
}
double ThermalZone::infiltrationDesignFlowPerSpaceFloorArea() const {
return getImpl<detail::ThermalZone_Impl>()->infiltrationDesignFlowPerSpaceFloorArea();
}
double ThermalZone::infiltrationDesignFlowPerExteriorSurfaceArea() const {
return getImpl<detail::ThermalZone_Impl>()->infiltrationDesignFlowPerExteriorSurfaceArea();
}
double ThermalZone::infiltrationDesignFlowPerExteriorWallArea() const {
return getImpl<detail::ThermalZone_Impl>()->infiltrationDesignFlowPerExteriorWallArea();
}
double ThermalZone::infiltrationDesignAirChangesPerHour() const {
return getImpl<detail::ThermalZone_Impl>()->infiltrationDesignAirChangesPerHour();
}
boost::optional<std::string> ThermalZone::isConditioned() const {
return getImpl<detail::ThermalZone_Impl>()->isConditioned();
}
boost::optional<ThermostatSetpointDualSetpoint> ThermalZone::thermostatSetpointDualSetpoint() const
{
return getImpl<detail::ThermalZone_Impl>()->thermostatSetpointDualSetpoint();
}
bool ThermalZone::setThermostatSetpointDualSetpoint(const ThermostatSetpointDualSetpoint & thermostat)
{
return getImpl<detail::ThermalZone_Impl>()->setThermostatSetpointDualSetpoint(thermostat);
}
void ThermalZone::resetThermostatSetpointDualSetpoint()
{
getImpl<detail::ThermalZone_Impl>()->resetThermostatSetpointDualSetpoint();
}
boost::optional<Thermostat> ThermalZone::thermostat() const
{
return getImpl<detail::ThermalZone_Impl>()->thermostat();
}
bool ThermalZone::setThermostat(const Thermostat & thermostat)
{
return getImpl<detail::ThermalZone_Impl>()->setThermostat(thermostat);
}
void ThermalZone::resetThermostat()
{
getImpl<detail::ThermalZone_Impl>()->resetThermostat();
}
boost::optional<ZoneControlHumidistat> ThermalZone::zoneControlHumidistat() const
{
return getImpl<detail::ThermalZone_Impl>()->zoneControlHumidistat();
}
bool ThermalZone::setZoneControlHumidistat(const ZoneControlHumidistat & humidistat)
{
return getImpl<detail::ThermalZone_Impl>()->setZoneControlHumidistat(humidistat);
}
void ThermalZone::resetZoneControlHumidistat()
{
getImpl<detail::ThermalZone_Impl>()->resetZoneControlHumidistat();
}
void ThermalZone::disconnect()
{
getImpl<detail::ThermalZone_Impl>()->disconnect();
}
boost::optional<Space> ThermalZone::combineSpaces()
{
return getImpl<detail::ThermalZone_Impl>()->combineSpaces();
}
bool ThermalZone::isRemovable() const
{
return getImpl<detail::ThermalZone_Impl>()->isRemovable();
}
bool ThermalZone::useIdealAirLoads() const
{
return getImpl<detail::ThermalZone_Impl>()->useIdealAirLoads();
}
void ThermalZone::setUseIdealAirLoads(bool useIdealAirLoads)
{
getImpl<detail::ThermalZone_Impl>()->setUseIdealAirLoads(useIdealAirLoads);
}
SizingZone ThermalZone::sizingZone() const
{
return getImpl<detail::ThermalZone_Impl>()->sizingZone();
}
bool ThermalZone::addToNode(Node & node)
{
return getImpl<detail::ThermalZone_Impl>()->addToNode(node);
}
PortList ThermalZone::inletPortList() const
{
return getImpl<detail::ThermalZone_Impl>()->inletPortList();
}
PortList ThermalZone::exhaustPortList() const
{
return getImpl<detail::ThermalZone_Impl>()->exhaustPortList();
}
void ThermalZone::addEquipment(const ModelObject & equipment)
{
getImpl<detail::ThermalZone_Impl>()->addEquipment(equipment);
}
void ThermalZone::setCoolingPriority(const ModelObject & equipment, unsigned priority)
{
getImpl<detail::ThermalZone_Impl>()->setCoolingPriority(equipment,priority);
}
void ThermalZone::setHeatingPriority(const ModelObject & equipment, unsigned priority)
{
getImpl<detail::ThermalZone_Impl>()->setHeatingPriority(equipment,priority);
}
std::vector<ModelObject> ThermalZone::equipment() const
{
return getImpl<detail::ThermalZone_Impl>()->equipment();
}
std::vector<ModelObject> ThermalZone::equipmentInHeatingOrder()
{
return getImpl<detail::ThermalZone_Impl>()->equipmentInHeatingOrder();
}
std::vector<ModelObject> ThermalZone::equipmentInCoolingOrder()
{
return getImpl<detail::ThermalZone_Impl>()->equipmentInCoolingOrder();
}
void ThermalZone::removeEquipment(const ModelObject & equipment)
{
getImpl<detail::ThermalZone_Impl>()->removeEquipment(equipment);
}
bool ThermalZone::isPlenum() const
{
return getImpl<detail::ThermalZone_Impl>()->isPlenum();
}
bool ThermalZone::canBePlenum() const
{
return getImpl<detail::ThermalZone_Impl>()->canBePlenum();
}
bool ThermalZone::setSupplyPlenum(const ThermalZone & plenumZone)
{
return getImpl<detail::ThermalZone_Impl>()->setSupplyPlenum(plenumZone);
}
bool ThermalZone::setSupplyPlenum(const ThermalZone & plenumZone, unsigned branchIndex)
{
return getImpl<detail::ThermalZone_Impl>()->setSupplyPlenum(plenumZone,branchIndex);
}
void ThermalZone::removeSupplyPlenum()
{
getImpl<detail::ThermalZone_Impl>()->removeSupplyPlenum();
}
void ThermalZone::removeSupplyPlenum(unsigned branchIndex)
{
getImpl<detail::ThermalZone_Impl>()->removeSupplyPlenum(branchIndex);
}
bool ThermalZone::setReturnPlenum(const ThermalZone & plenumZone)
{
return getImpl<detail::ThermalZone_Impl>()->setReturnPlenum(plenumZone);
}
void ThermalZone::removeReturnPlenum()
{
getImpl<detail::ThermalZone_Impl>()->removeReturnPlenum();
}
std::vector<ZoneMixing> ThermalZone::zoneMixing() const
{
return getImpl<detail::ThermalZone_Impl>()->zoneMixing();
}
std::vector<ZoneMixing> ThermalZone::supplyZoneMixing() const
{
return getImpl<detail::ThermalZone_Impl>()->supplyZoneMixing();
}
std::vector<ZoneMixing> ThermalZone::exhaustZoneMixing() const
{
return getImpl<detail::ThermalZone_Impl>()->exhaustZoneMixing();
}
boost::optional<HVACComponent> ThermalZone::airLoopHVACTerminal() const
{
return getImpl<detail::ThermalZone_Impl>()->airLoopHVACTerminal();
}
boost::optional<ZoneControlContaminantController> ThermalZone::zoneControlContaminantController() const
{
return getImpl<detail::ThermalZone_Impl>()->zoneControlContaminantController();
}
bool ThermalZone::setZoneControlContaminantController(const ZoneControlContaminantController & contaminantController)
{
return getImpl<detail::ThermalZone_Impl>()->setZoneControlContaminantController(contaminantController);
}
void ThermalZone::resetZoneControlContaminantController()
{
getImpl<detail::ThermalZone_Impl>()->resetZoneControlContaminantController();
}
/// @cond
ThermalZone::ThermalZone(std::shared_ptr<detail::ThermalZone_Impl> impl)
: HVACComponent(impl)
{}
/// @endcond
} // model
} // openstudio
| 34.673416 | 303 | 0.711595 | [
"geometry",
"object",
"vector",
"model"
] |
c8f4d601beb86fb5acdc2aaa2eeae2a814123d86 | 2,539 | cc | C++ | src/AndroidApiWrapper.cc | meesokim/openmsx-0.13.0 | 287033a3fcade297e008a544b715eb3906da3848 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5 | 2015-02-27T21:42:28.000Z | 2021-10-10T23:36:08.000Z | src/AndroidApiWrapper.cc | meesokim/openmsx-0.13.0 | 287033a3fcade297e008a544b715eb3906da3848 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/AndroidApiWrapper.cc | meesokim/openmsx-0.13.0 | 287033a3fcade297e008a544b715eb3906da3848 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2015-06-15T09:57:56.000Z | 2017-05-14T01:11:48.000Z | /*
* Android API wrapper
*
* It makes a few Android functions available for the android flavour of openMSX
*
*/
#include "build-info.hh"
#include "AndroidApiWrapper.hh"
#if PLATFORM_ANDROID
#include "openmsx.hh"
#include <stdlib.h>
#include <string.h>
#include <jni.h>
// The jniVM parameter gets set by the JNI mechanism directly after loading the
// shared lib containing openMSX by invoking a method with following
// signature if it exists in the shared lib:
// JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
// This method is defined at the end of this source file and must be able to
// initialize this jniVM parameter, hence it must exist outside the openmsx
// namespace
static JavaVM *jniVM = NULL;
namespace openmsx {
std::string AndroidApiWrapper::getStorageDirectory()
{
JNIEnv * jniEnv = NULL;
jclass cls;
jmethodID mid;
jobject storageDirectory;
jstring storageDirectoryName;
jniVM->AttachCurrentThread(&jniEnv, NULL);
if( !jniEnv ) {
throw JniException("Java VM AttachCurrentThread() failed");
}
cls = jniEnv->FindClass("android/os/Environment");
if (cls == 0) {
throw JniException("Cant find class android/os/Environment");
}
mid = jniEnv->GetStaticMethodID(cls, "getExternalStorageDirectory", "()Ljava/io/File;");
if (mid == 0) {
throw JniException("Cant find getExternalStorageDirectory method");
}
storageDirectory = jniEnv->CallStaticObjectMethod(cls, mid);
if (storageDirectory == 0) {
throw JniException("Cant get storageDirectory");
}
cls = jniEnv->GetObjectClass(storageDirectory);
if (cls == 0) {
throw JniException("Cant find class for storageDirectory object");
}
mid = jniEnv->GetMethodID(cls, "getAbsolutePath", "()Ljava/lang/String;");
if (mid == 0) {
throw JniException("Cant find getAbsolutePath method");
}
storageDirectoryName = (jstring)jniEnv->CallObjectMethod(storageDirectory, mid);
if (storageDirectoryName == 0) {
throw JniException("Cant get storageDirectoryName");
}
const char *str = jniEnv->GetStringUTFChars(storageDirectoryName, NULL);
if (str == NULL) {
throw JniException("Cant convert storageDirectoryName to C format");
}
std::string rslt(str);
jniEnv->ReleaseStringUTFChars(storageDirectoryName, str);
return rslt;
}
} // namespace openmsx
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
// Store the reference to the JVM so that the JNI calls can use it
jniVM = vm;
return JNI_VERSION_1_2;
};
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
{
// Nothing to do
};
#endif
| 28.52809 | 89 | 0.738874 | [
"object"
] |
c8f59ce22b35b07f47388c2a3c089a6efbaf87bd | 35,398 | cpp | C++ | drivers/gles2/shader_compiler_gles2.cpp | mikica1986vee/Godot_android_tegra_fallback | 61df6d40282ea5a4ff48d60885cf83c94f804433 | [
"CC-BY-3.0",
"MIT"
] | null | null | null | drivers/gles2/shader_compiler_gles2.cpp | mikica1986vee/Godot_android_tegra_fallback | 61df6d40282ea5a4ff48d60885cf83c94f804433 | [
"CC-BY-3.0",
"MIT"
] | null | null | null | drivers/gles2/shader_compiler_gles2.cpp | mikica1986vee/Godot_android_tegra_fallback | 61df6d40282ea5a4ff48d60885cf83c94f804433 | [
"CC-BY-3.0",
"MIT"
] | null | null | null | /*************************************************************************/
/* shader_compiler_gles2.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "shader_compiler_gles2.h"
#include "print_string.h"
#include "stdio.h"
//#define DEBUG_SHADER_ENABLED
typedef ShaderLanguage SL;
struct CodeGLSL2 {
String code;
};
static String _mktab(int p_level) {
String tb;
for(int i=0;i<p_level;i++) {
tb+="\t";
}
return tb;
}
static String _typestr(SL::DataType p_type) {
switch(p_type) {
case SL::TYPE_VOID: return "void";
case SL::TYPE_BOOL: return "bool";
case SL::TYPE_FLOAT: return "float";
case SL::TYPE_VEC2: return "vec2";
case SL::TYPE_VEC3: return "vec3";
case SL::TYPE_VEC4: return "vec4";
case SL::TYPE_MAT2: return "mat2";
case SL::TYPE_MAT3: return "mat3";
case SL::TYPE_MAT4: return "mat4";
case SL::TYPE_TEXTURE: return "sampler2D";
case SL::TYPE_CUBEMAP: return "samplerCube";
}
return "";
}
static String _mknum(float p_num) {
return String::num_real(p_num);
}
static String _opstr(SL::Operator p_op) {
switch(p_op) {
case SL::OP_ASSIGN: return "=";
case SL::OP_ADD: return "+";
case SL::OP_SUB: return "-";
case SL::OP_MUL: return "*";
case SL::OP_DIV: return "/";
case SL::OP_ASSIGN_ADD: return "+=";
case SL::OP_ASSIGN_SUB: return "-=";
case SL::OP_ASSIGN_MUL: return "*=";
case SL::OP_ASSIGN_DIV: return "/=";
case SL::OP_NEG: return "-";
case SL::OP_NOT: return "!";
case SL::OP_CMP_EQ: return "==";
case SL::OP_CMP_NEQ: return "!=";
case SL::OP_CMP_LEQ: return "<=";
case SL::OP_CMP_GEQ: return ">=";
case SL::OP_CMP_LESS: return "<";
case SL::OP_CMP_GREATER: return ">";
case SL::OP_CMP_OR: return "||";
case SL::OP_CMP_AND: return "&&";
default: return "";
}
return "";
}
//#ifdef DEBUG_SHADER_ENABLED
#if 1
#define ENDL "\n"
#else
#define ENDL ""
#endif
String ShaderCompilerGLES2::dump_node_code(SL::Node *p_node,int p_level,bool p_assign_left) {
String code;
switch(p_node->type) {
case SL::Node::TYPE_PROGRAM: {
SL::ProgramNode *pnode=(SL::ProgramNode*)p_node;
code+=dump_node_code(pnode->body,p_level);
} break;
case SL::Node::TYPE_FUNCTION: {
} break;
case SL::Node::TYPE_BLOCK: {
SL::BlockNode *bnode=(SL::BlockNode*)p_node;
//variables
code+="{" ENDL;
for(Map<StringName,SL::DataType>::Element *E=bnode->variables.front();E;E=E->next()) {
code+=_mktab(p_level)+_typestr(E->value())+" "+replace_string(E->key())+";" ENDL;
}
for(int i=0;i<bnode->statements.size();i++) {
code+=_mktab(p_level)+dump_node_code(bnode->statements[i],p_level)+";" ENDL;
}
code+="}" ENDL;
} break;
case SL::Node::TYPE_VARIABLE: {
SL::VariableNode *vnode=(SL::VariableNode*)p_node;
if (type==ShaderLanguage::SHADER_MATERIAL_VERTEX) {
if (vnode->name==vname_vertex && p_assign_left) {
vertex_code_writes_vertex=true;
}
if (vnode->name == vname_position && p_assign_left) {
vertex_code_writes_position = true;
}
if (vnode->name==vname_color_interp) {
flags->use_color_interp=true;
}
if (vnode->name==vname_uv_interp) {
flags->use_uv_interp=true;
}
if (vnode->name==vname_uv2_interp) {
flags->use_uv2_interp=true;
}
if (vnode->name==vname_var1_interp) {
flags->use_var1_interp=true;
}
if (vnode->name==vname_var2_interp) {
flags->use_var2_interp=true;
}
if (vnode->name==vname_tangent_interp || vnode->name==vname_binormal_interp) {
flags->use_tangent_interp=true;
}
}
if (type==ShaderLanguage::SHADER_MATERIAL_FRAGMENT) {
if (vnode->name==vname_discard) {
uses_discard=true;
}
if (vnode->name==vname_normalmap) {
uses_normalmap=true;
}
if (vnode->name==vname_screen_uv) {
uses_screen_uv=true;
}
if (vnode->name==vname_diffuse_alpha && p_assign_left) {
uses_alpha=true;
}
if (vnode->name==vname_color_interp) {
flags->use_color_interp=true;
}
if (vnode->name==vname_uv_interp) {
flags->use_uv_interp=true;
}
if (vnode->name==vname_uv2_interp) {
flags->use_uv2_interp=true;
}
if (vnode->name==vname_var1_interp) {
flags->use_var1_interp=true;
}
if (vnode->name==vname_var2_interp) {
flags->use_var2_interp=true;
}
if (vnode->name==vname_tangent_interp || vnode->name==vname_binormal_interp) {
flags->use_tangent_interp=true;
}
}
if (type==ShaderLanguage::SHADER_MATERIAL_LIGHT) {
if (vnode->name==vname_light) {
uses_light=true;
}
}
if (type==ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX) {
if (vnode->name==vname_var1_interp) {
flags->use_var1_interp=true;
}
if (vnode->name==vname_var2_interp) {
flags->use_var2_interp=true;
}
if (vnode->name==vname_world_vec) {
uses_worldvec=true;
}
}
if (type==ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT) {
if (vnode->name==vname_texpixel_size) {
uses_texpixel_size=true;
}
if (vnode->name==vname_normal) {
uses_normal=true;
}
if (vnode->name==vname_normalmap || vnode->name==vname_normalmap_depth) {
uses_normalmap=true;
uses_normal=true;
}
if (vnode->name==vname_screen_uv) {
uses_screen_uv=true;
}
if (vnode->name==vname_var1_interp) {
flags->use_var1_interp=true;
}
if (vnode->name==vname_var2_interp) {
flags->use_var2_interp=true;
}
}
if (type==ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT) {
if (vnode->name==vname_light) {
uses_light=true;
}
if (vnode->name==vname_normal) {
uses_normal=true;
}
if (vnode->name==vname_shadow) {
uses_shadow_color=true;
}
}
if (vnode->name==vname_time) {
uses_time=true;
}
code=replace_string(vnode->name);
} break;
case SL::Node::TYPE_CONSTANT: {
SL::ConstantNode *cnode=(SL::ConstantNode*)p_node;
switch(cnode->datatype) {
case SL::TYPE_BOOL: code=cnode->value.operator bool()?"true":"false"; break;
case SL::TYPE_FLOAT: code=_mknum(cnode->value); break; //force zeros, so GLSL doesn't confuse with integer.
case SL::TYPE_VEC2: { Vector2 v = cnode->value; code="vec2("+_mknum(v.x)+", "+_mknum(v.y)+")"; } break;
case SL::TYPE_VEC3: { Vector3 v = cnode->value; code="vec3("+_mknum(v.x)+", "+_mknum(v.y)+", "+_mknum(v.z)+")"; } break;
case SL::TYPE_VEC4: { Plane v = cnode->value; code="vec4("+_mknum(v.normal.x)+", "+_mknum(v.normal.y)+", "+_mknum(v.normal.z)+", "+_mknum(v.d)+")"; } break;
case SL::TYPE_MAT2: { Matrix32 x = cnode->value; code="mat2( vec2("+_mknum(x[0][0])+", "+_mknum(x[0][1])+"), vec2("+_mknum(x[1][0])+", "+_mknum(x[1][1])+"))"; } break;
case SL::TYPE_MAT3: { Matrix3 x = cnode->value; code="mat3( vec3("+_mknum(x.get_axis(0).x)+", "+_mknum(x.get_axis(0).y)+", "+_mknum(x.get_axis(0).z)+"), vec3("+_mknum(x.get_axis(1).x)+", "+_mknum(x.get_axis(1).y)+", "+_mknum(x.get_axis(1).z)+"), vec3("+_mknum(x.get_axis(2).x)+", "+_mknum(x.get_axis(2).y)+", "+_mknum(x.get_axis(2).z)+"))"; } break;
case SL::TYPE_MAT4: { Transform x = cnode->value; code="mat4( vec4("+_mknum(x.basis.get_axis(0).x)+", "+_mknum(x.basis.get_axis(0).y)+", "+_mknum(x.basis.get_axis(0).z)+",0.0), vec4("+_mknum(x.basis.get_axis(1).x)+", "+_mknum(x.basis.get_axis(1).y)+", "+_mknum(x.basis.get_axis(1).z)+",0.0), vec4("+_mknum(x.basis.get_axis(2).x)+", "+_mknum(x.basis.get_axis(2).y)+", "+_mknum(x.basis.get_axis(2).z)+",0.0), vec4("+_mknum(x.origin.x)+", "+_mknum(x.origin.y)+", "+_mknum(x.origin.z)+",1.0))"; } break;
default: code="<error: "+Variant::get_type_name(cnode->value.get_type())+" ("+itos(cnode->datatype)+">";
}
} break;
case SL::Node::TYPE_OPERATOR: {
SL::OperatorNode *onode=(SL::OperatorNode*)p_node;
switch(onode->op) {
case SL::OP_ASSIGN_MUL: {
if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC3 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
String mul_l=dump_node_code(onode->arguments[0],p_level,true);
String mul_r=dump_node_code(onode->arguments[1],p_level);
code=mul_l+"=(vec4("+mul_l+",1.0)*("+mul_r+")).xyz";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC3) {
String mul_l=dump_node_code(onode->arguments[0],p_level,true);
String mul_r=dump_node_code(onode->arguments[1],p_level);
code=mul_l+"=(("+mul_l+")*vec4("+mul_r+",1.0)).xyz";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
String mul_l=dump_node_code(onode->arguments[0],p_level,true);
String mul_r=dump_node_code(onode->arguments[1],p_level);
code=mul_l+"=(vec4("+mul_l+",0.0,1.0)*("+mul_r+")).xy";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC2) {
String mul_l=dump_node_code(onode->arguments[0],p_level,true);
String mul_r=dump_node_code(onode->arguments[1],p_level);
code=mul_l+"=(("+mul_l+")*vec4("+mul_r+",0.0,1.0)).xy";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT3) {
String mul_l=dump_node_code(onode->arguments[0],p_level,true);
String mul_r=dump_node_code(onode->arguments[1],p_level);
code=mul_l+"=(("+mul_l+")*vec3("+mul_r+",1.0)).xy";
break;
}
};
case SL::OP_ASSIGN:
case SL::OP_ASSIGN_ADD:
case SL::OP_ASSIGN_SUB:
case SL::OP_ASSIGN_DIV:
code="("+dump_node_code(onode->arguments[0],p_level,true)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level)+")";
break;
case SL::OP_MUL:
if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC3) {
code="("+dump_node_code(onode->arguments[0],p_level)+"*vec4("+dump_node_code(onode->arguments[1],p_level)+",1.0)).xyz";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC3 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
code="(vec4("+dump_node_code(onode->arguments[0],p_level)+",1.0)*"+dump_node_code(onode->arguments[1],p_level)+").xyz";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC2) {
code="("+dump_node_code(onode->arguments[0],p_level)+"*vec4("+dump_node_code(onode->arguments[1],p_level)+",0.0,1.0)).xy";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
code="(vec4("+dump_node_code(onode->arguments[0],p_level)+",0.0,1.0)*"+dump_node_code(onode->arguments[1],p_level)+").xy";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT3 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC2) {
code="("+dump_node_code(onode->arguments[0],p_level)+"*vec3("+dump_node_code(onode->arguments[1],p_level)+",1.0)).xy";
break;
} else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT3) {
code="(vec3("+dump_node_code(onode->arguments[0],p_level)+",1.0)*"+dump_node_code(onode->arguments[1],p_level)+").xy";
break;
}
case SL::OP_ADD:
case SL::OP_SUB:
case SL::OP_DIV:
case SL::OP_CMP_EQ:
case SL::OP_CMP_NEQ:
case SL::OP_CMP_LEQ:
case SL::OP_CMP_GEQ:
case SL::OP_CMP_LESS:
case SL::OP_CMP_GREATER:
case SL::OP_CMP_OR:
case SL::OP_CMP_AND:
//handle binary
code="("+dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level)+")";
break;
case SL::OP_NEG:
case SL::OP_NOT:
//handle unary
code=_opstr(onode->op)+dump_node_code(onode->arguments[0],p_level);
break;
case SL::OP_CONSTRUCT:
case SL::OP_CALL: {
String callfunc=dump_node_code(onode->arguments[0],p_level);
code=callfunc+"(";
/*if (callfunc=="mat4") {
//fix constructor for mat4
for(int i=1;i<onode->arguments.size();i++) {
if (i>1)
code+=", ";
//transform
code+="vec4( "+dump_node_code(onode->arguments[i],p_level)+(i==4?",1.0)":",0.0)");
}
} else*/ if (callfunc=="tex") {
code="texture2D( "+dump_node_code(onode->arguments[1],p_level)+","+dump_node_code(onode->arguments[2],p_level)+")";
break;
} else if (callfunc=="texcube") {
code="(textureCube( "+dump_node_code(onode->arguments[1],p_level)+",("+dump_node_code(onode->arguments[2],p_level)+")).xyz";
break;
} else if (callfunc=="texscreen") {
//create the call to sample the screen, and clamp it
uses_texscreen=true;
code="(texture2D( texscreen_tex, clamp(("+dump_node_code(onode->arguments[1],p_level)+").xy*texscreen_screen_mult,texscreen_screen_clamp.xy,texscreen_screen_clamp.zw))).rgb";
//code="(texture2D( screen_texture, ("+dump_node_code(onode->arguments[1],p_level)+").xy).rgb";
break;
} else if (callfunc=="texpos") {
//create the call to sample the screen, and clamp it
uses_texpos=true;
code="get_texpos("+dump_node_code(onode->arguments[1],p_level)+"";
// code="get_texpos(gl_ProjectionMatrixInverse * texture2D( depth_texture, clamp(("+dump_node_code(onode->arguments[1],p_level)+").xy,vec2(0.0),vec2(1.0))*gl_LightSource[5].specular.zw+gl_LightSource[5].specular.xy)";
//code="(texture2D( screen_texture, ("+dump_node_code(onode->arguments[1],p_level)+").xy).rgb";
break;
} else if (custom_h && callfunc=="cosh_custom") {
if (!cosh_used) {
global_code= "float cosh_custom(float val)\n"\
"{\n"\
" float tmp = exp(val);\n"\
" float cosH = (tmp + 1.0 / tmp) / 2.0;\n"\
" return cosH;\n"\
"}\n"+global_code;
cosh_used=true;
}
code="cosh_custom("+dump_node_code(onode->arguments[1],p_level)+"";
} else if (custom_h && callfunc=="sinh_custom") {
if (!sinh_used) {
global_code= "float sinh_custom(float val)\n"\
"{\n"\
" float tmp = exp(val);\n"\
" float sinH = (tmp - 1.0 / tmp) / 2.0;\n"\
" return sinH;\n"\
"}\n"+global_code;
sinh_used=true;
}
code="sinh_custom("+dump_node_code(onode->arguments[1],p_level)+"";
} else if (custom_h && callfunc=="tanh_custom") {
if (!tanh_used) {
global_code= "float tanh_custom(float val)\n"\
"{\n"\
" float tmp = exp(val);\n"\
" float tanH = (tmp - 1.0 / tmp) / (tmp + 1.0 / tmp);\n"\
" return tanH;\n"\
"}\n"+global_code;
tanh_used=true;
}
code="tanh_custom("+dump_node_code(onode->arguments[1],p_level)+"";
} else {
for(int i=1;i<onode->arguments.size();i++) {
if (i>1)
code+=", ";
//transform
code+=dump_node_code(onode->arguments[i],p_level);
}
}
code+=")";
break;
} break;
default: {}
}
} break;
case SL::Node::TYPE_CONTROL_FLOW: {
SL::ControlFlowNode *cfnode=(SL::ControlFlowNode*)p_node;
if (cfnode->flow_op==SL::FLOW_OP_IF) {
code+="if ("+dump_node_code(cfnode->statements[0],p_level)+") {" ENDL;
code+=dump_node_code(cfnode->statements[1],p_level+1);
if (cfnode->statements.size()==3) {
code+="} else {" ENDL;
code+=dump_node_code(cfnode->statements[2],p_level+1);
}
code+="}" ENDL;
} else if (cfnode->flow_op==SL::FLOW_OP_RETURN) {
if (cfnode->statements.size()) {
code="return "+dump_node_code(cfnode->statements[0],p_level);
} else {
code="return";
}
}
} break;
case SL::Node::TYPE_MEMBER: {
SL::MemberNode *mnode=(SL::MemberNode*)p_node;
String m;
if (mnode->basetype==SL::TYPE_MAT4) {
if (mnode->name=="x")
m="[0]";
else if (mnode->name=="y")
m="[1]";
else if (mnode->name=="z")
m="[2]";
else if (mnode->name=="w")
m="[3]";
} else if (mnode->basetype==SL::TYPE_MAT2) {
if (mnode->name=="x")
m="[0]";
else if (mnode->name=="y")
m="[1]";
} else if (mnode->basetype==SL::TYPE_MAT3) {
if (mnode->name=="x")
m="[0]";
else if (mnode->name=="y")
m="[1]";
else if (mnode->name=="z")
m="[2]";
} else {
m="."+mnode->name;
}
code=dump_node_code(mnode->owner,p_level)+m;
} break;
}
return code;
}
Error ShaderCompilerGLES2::compile_node(SL::ProgramNode *p_program) {
// feed the local replace table and global code
global_code="";
// uniforms first!
int ubase=0;
if (uniforms)
ubase=uniforms->size();
for(Map<StringName,SL::Uniform>::Element *E=p_program->uniforms.front();E;E=E->next()) {
String uline="uniform "+_typestr(E->get().type)+" _"+E->key().operator String()+";" ENDL;
global_code+=uline;
if (uniforms) {
//if (uniforms->has(E->key())) {
// //repeated uniform, error
// ERR_EXPLAIN("Uniform already exists from other shader: "+String(E->key()));
// ERR_FAIL_COND_V(uniforms->has(E->key()),ERR_ALREADY_EXISTS);
//
// }
SL::Uniform u = E->get();
u.order+=ubase;
uniforms->insert(E->key(),u);
}
}
for(int i=0;i<p_program->functions.size();i++) {
SL::FunctionNode *fnode=p_program->functions[i].function;
StringName funcname=fnode->name;
String newfuncname=replace_string(funcname);
String header;
header=_typestr(fnode->return_type)+" "+newfuncname+"(";
for(int i=0;i<fnode->arguments.size();i++) {
if (i>0)
header+=", ";
header+=_typestr(fnode->arguments[i].type)+" "+replace_string(fnode->arguments[i].name);
}
header+=") {" ENDL;
String fcode=header;
fcode+=dump_node_code(fnode->body,1);
fcode+="}" ENDL;
global_code+=fcode;
}
/* for(Map<StringName,SL::DataType>::Element *E=p_program->preexisting_variables.front();E;E=E->next()) {
StringName varname=E->key();
String newvarname=replace_string(varname);
global_code+="uniform "+_typestr(E->get())+" "+newvarname+";" ENDL;
}*/
code=dump_node_code(p_program,0);
#ifdef DEBUG_SHADER_ENABLED
print_line("GLOBAL CODE:\n\n");
print_line(global_code);
global_code=global_code.replace("\n","");
print_line("CODE:\n\n");
print_line(code);
code=code.replace("\n","");
#endif
return OK;
}
Error ShaderCompilerGLES2::create_glsl_120_code(void *p_str,SL::ProgramNode *p_program) {
ShaderCompilerGLES2 *compiler=(ShaderCompilerGLES2*)p_str;
return compiler->compile_node(p_program);
}
String ShaderCompilerGLES2::replace_string(const StringName& p_string) {
Map<StringName,StringName>::Element *E=NULL;
E=replace_table.find(p_string);
if (E)
return E->get();
E=mode_replace_table[type].find(p_string);
if (E)
return E->get();
return "_"+p_string.operator String();
}
Error ShaderCompilerGLES2::compile(const String& p_code, ShaderLanguage::ShaderType p_type, String& r_code_line, String& r_globals_line, Flags& r_flags, Map<StringName,ShaderLanguage::Uniform> *r_uniforms) {
uses_texscreen=false;
uses_texpos=false;
uses_alpha=false;
uses_discard=false;
uses_screen_uv=false;
uses_light=false;
uses_time=false;
uses_normalmap=false;
uses_normal=false;
uses_texpixel_size=false;
uses_worldvec=false;
vertex_code_writes_vertex=false;
vertex_code_writes_position = false;
uses_shadow_color=false;
uniforms=r_uniforms;
flags=&r_flags;
r_flags.use_color_interp=false;
r_flags.use_uv_interp=false;
r_flags.use_uv2_interp=false;
r_flags.use_tangent_interp=false;
r_flags.use_var1_interp=false;
r_flags.use_var2_interp=false;
r_flags.uses_normalmap=false;
r_flags.uses_normal=false;
sinh_used=false;
tanh_used=false;
cosh_used=false;
String error;
int errline,errcol;
type=p_type;
Error err = SL::compile(p_code,p_type,create_glsl_120_code,this,&error,&errline,&errcol);
if (err) {
print_line("***Error precompiling shader: "+error);
print_line("error "+itos(errline)+":"+itos(errcol));
return err;
}
r_flags.uses_alpha=uses_alpha;
r_flags.uses_texscreen=uses_texscreen;
r_flags.uses_texpos=uses_texpos;
r_flags.vertex_code_writes_vertex=vertex_code_writes_vertex;
r_flags.vertex_code_writes_position=vertex_code_writes_position;
r_flags.uses_discard=uses_discard;
r_flags.uses_screen_uv=uses_screen_uv;
r_flags.uses_light=uses_light;
r_flags.uses_time=uses_time;
r_flags.uses_normalmap=uses_normalmap;
r_flags.uses_normal=uses_normal;
r_flags.uses_texpixel_size=uses_texpixel_size;
r_flags.uses_worldvec=uses_worldvec;
r_flags.uses_shadow_color=uses_shadow_color;
r_code_line=code;
r_globals_line=global_code;
return OK;
}
ShaderCompilerGLES2::ShaderCompilerGLES2() {
#ifdef GLEW_ENABLED
//use custom functions because they are not supported in GLSL120
custom_h=true;
#else
custom_h=false;
#endif
replace_table["bool"]= "bool";
replace_table["float" ]= "float";
replace_table["vec2" ]= "vec2";
replace_table["vec3" ]= "vec3";
replace_table["vec4" ]= "vec4";
replace_table["mat2" ]= "mat2";
replace_table["mat3" ]= "mat3";
replace_table["mat4" ]= "mat4";
replace_table["texture" ]= "sampler2D";
replace_table["cubemap" ]= "samplerCube";
replace_table["sin"]= "sin";
replace_table["cos" ]= "cos";
replace_table["tan" ]= "tan";
replace_table["asin" ]= "asin";
replace_table["acos" ]= "acos";
replace_table["atan" ]= "atan";
replace_table["atan2"]= "atan";
if (custom_h) {
replace_table["sinh" ]= "sinh_custom";
replace_table["cosh" ]= "cosh_custom";
replace_table["tanh" ]= "tanh_custom";
} else {
replace_table["sinh" ]= "sinh";
replace_table["cosh" ]= "cosh";
replace_table["tanh" ]= "tanh";
}
replace_table["pow" ]= "pow";
replace_table["exp" ]= "exp";
replace_table["log" ]= "log";
replace_table["sqrt"]= "sqrt";
replace_table["abs" ]= "abs";
replace_table["sign"]= "sign";
replace_table["floor"]= "floor";
replace_table["trunc"]= "trunc";
#ifdef GLEW_ENABLED
replace_table["round"]= "roundfix";
#else
replace_table["round"]= "round";
#endif
replace_table["ceil" ]= "ceil";
replace_table["fract"]= "fract";
replace_table["mod" ]= "mod";
replace_table["min" ]= "min";
replace_table["max"]= "max";
replace_table["clamp"]= "clamp";
replace_table["mix" ]= "mix";
replace_table["step" ]= "step";
replace_table["smoothstep" ]= "smoothstep";
replace_table["length"]= "length";
replace_table["distance"]= "distance";
replace_table["dot" ]= "dot";
replace_table["cross" ]="cross";
replace_table["normalize"]= "normalize";
replace_table["reflect"]= "reflect";
replace_table["refract"]= "refract";
replace_table["tex"]= "tex";
replace_table["texa"]= "texa";
replace_table["tex2"]= "tex2";
replace_table["texcube"]= "textureCube";
replace_table["texscreen"]= "texscreen";
replace_table["texpos"]= "texpos";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["POSITION"] = "gl_Position";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_VERTEX"] = "vertex_in.xyz";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_NORMAL"] = "normal_in";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_TANGENT"]="tangent_in";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_BINORMALF"]="binormalf";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VERTEX"]="vertex_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["NORMAL"]="normal_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["TANGENT"]="tangent_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["BINORMAL"]="binormal_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["UV"]="uv_interp.xy";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["UV2"]="uv_interp.zw";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["COLOR"]="color_interp";
//@TODO convert to glsl stuff
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SPEC_EXP"]="vertex_specular_exp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["WORLD_MATRIX"]="world_transform";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["INV_CAMERA_MATRIX"]="camera_inverse_transform";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["PROJECTION_MATRIX"]="projection_transform";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["MODELVIEW_MATRIX"]="modelview";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["POINT_SIZE"]="gl_PointSize";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VAR1"]="var1_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VAR2"]="var2_interp";
// mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SCREEN_POS"]="SCREEN_POS";
// mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SCREEN_SIZE"]="SCREEN_SIZE";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["INSTANCE_ID"]="instance_id";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["TIME"]="time";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VERTEX"]="vertex";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POSITION"]="IN_POSITION";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMAL"]="normal";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["TANGENT"]="tangent";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POSITION"]="gl_Position";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["BINORMAL"]="binormal";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMALMAP"]="normalmap";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMALMAP_DEPTH"]="normaldepth";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR1"]="var1_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR2"]="var2_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["UV"]="uv";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["UV2"]="uv2";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_UV"]="screen_uv";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR1"]="var1_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR2"]="var2_interp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["COLOR"]="color";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DIFFUSE"]="diffuse.rgb";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DIFFUSE_ALPHA"]="diffuse";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SPECULAR"]="specular";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["EMISSION"]="emission";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SHADE_PARAM"]="shade_param";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SPEC_EXP"]="specular_exp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["GLOW"]="glow";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DISCARD"]="discard_";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POINT_COORD"]="gl_PointCoord";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["INV_CAMERA_MATRIX"]="camera_inverse_transform";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_POS"]="SCREEN_POS";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_TEXEL_SIZE"]="SCREEN_TEXEL_SIZE";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["TIME"]="time";
//////////////
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["NORMAL"]="normal";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["POSITION"]="IN_POSITION";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_DIR"]="light_dir";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_DIFFUSE"]="light_diffuse";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_SPECULAR"]="light_specular";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["EYE_VEC"]="eye_vec";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["DIFFUSE"]="mdiffuse";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SPECULAR"]="specular";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SPECULAR_EXP"]="specular_exp";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SHADE_PARAM"]="shade_param";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT"]="light";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["POINT_COORD"]="gl_PointCoord";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["TIME"]="time";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["SRC_VERTEX"]="src_vtx";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VERTEX"]="outvec.xy";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["WORLD_VERTEX"]="outvec.xy";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["UV"]="uv_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["COLOR"]="color_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VAR1"]="var1_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VAR2"]="var2_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["POINT_SIZE"]="gl_PointSize";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["WORLD_MATRIX"]="modelview_matrix";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["PROJECTION_MATRIX"]="projection_matrix";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["EXTRA_MATRIX"]="extra_matrix";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["TIME"]="time";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["POSITION"]="gl_Position";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMAL"]="normal";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMALMAP"]="normal_map";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMALMAP_DEPTH"]="normal_depth";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["UV"]="uv_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["SRC_COLOR"]="color_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["COLOR"]="color";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TEXTURE"]="texture";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TEXTURE_PIXEL_SIZE"]="texpixel_size";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["VAR1"]="var1_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["VAR2"]="var2_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["SCREEN_UV"]="screen_uv";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["POINT_COORD"]="gl_PointCoord";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TIME"]="time";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["POSITION"]="gl_Position";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["NORMAL"]="normal";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["UV"]="uv_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["COLOR"]="color";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TEXTURE"]="texture";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TEXTURE_PIXEL_SIZE"]="texpixel_size";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["VAR1"]="var1_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["VAR2"]="var2_interp";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_VEC"]="light_vec";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_HEIGHT"]="light_height";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_COLOR"]="light";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_UV"]="light_uv";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT"]="light_out";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["SHADOW"]="shadow_color";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["SCREEN_UV"]="screen_uv";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["POINT_COORD"]="gl_PointCoord";
mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TIME"]="time";
//mode_replace_table[2]["SCREEN_POS"]="SCREEN_POS";
//mode_replace_table[2]["SCREEN_TEXEL_SIZE"]="SCREEN_TEXEL_SIZE";
out_vertex_name="VERTEX";
vname_discard="DISCARD";
vname_screen_uv="SCREEN_UV";
vname_diffuse_alpha="DIFFUSE_ALPHA";
vname_color_interp="COLOR";
vname_uv_interp="UV";
vname_uv2_interp="UV2";
vname_tangent_interp="TANGENT";
vname_binormal_interp="BINORMAL";
vname_var1_interp="VAR1";
vname_var2_interp="VAR2";
vname_vertex="VERTEX";
vname_position = "POSITION";
vname_light="LIGHT";
vname_time="TIME";
vname_normalmap="NORMALMAP";
vname_normalmap_depth="NORMALMAP_DEPTH";
vname_normal="NORMAL";
vname_texpixel_size="TEXTURE_PIXEL_SIZE";
vname_world_vec="WORLD_VERTEX";
vname_shadow="SHADOW";
}
| 37.73774 | 503 | 0.685406 | [
"transform"
] |
c8f656de0fa5d189a3b9256fc7a662cb49940196 | 1,820 | cpp | C++ | src/PAT/P1095.cpp | TDYe123/Algorithm | 9c7cc2b2b79db7245846affc5b263049fd866c87 | [
"MIT"
] | 1 | 2019-05-04T15:44:41.000Z | 2019-05-04T15:44:41.000Z | src/PAT/P1095.cpp | TDYe123/Algorithm | 9c7cc2b2b79db7245846affc5b263049fd866c87 | [
"MIT"
] | null | null | null | src/PAT/P1095.cpp | TDYe123/Algorithm | 9c7cc2b2b79db7245846affc5b263049fd866c87 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
struct node {
char id[10];
int time, flag = 0; //flag = 1->进入;flag = -1->离开
};
bool cmp1(node a, node b) {
if(strcmp(a.id, b.id) != 0)
return strcmp(a.id, b.id) < 0;
else
return a.time < b.time;
}
bool cmp2(node a, node b) {
return a.time < b.time;
}
int main() {
int n, k, maxtime, tempindex = 0;
scanf("%d%d\n", &n, &k);
vector<node> record(n), car;
for(int i=0; i<n; i++) {
char temp[5];
int h, m, s;
scanf("%s %d:%d:%d %s\n", record[i].id, &h, &m, &s, temp);
int temptime = h*3600 + m*60 + s;
record[i].time = temptime;
record[i].flag = strcmp(temp, "in") == 0 ? 1 : -1;
}
sort(record.begin(), record.end(), cmp1);
map<string, int> mp;
for(int i=0; i<n-1; i++) {
if(strcmp(record[i].id, record[i+1].id) == 0 && record[i].flag == 1 && record[i+1].flag == -1) {
car.push_back(record[i]);
car.push_back(record[i+1]);
mp[record[i].id] += (record[i+1].time - record[i].time);
if(maxtime < mp[record[i].id])
maxtime = mp[record[i].id];
}
}
sort(car.begin(), car.end(), cmp2);
vector<int> cnt(n);
for(int i=0; i<car.size(); i++) {
if(i == 0)
cnt[i] += car[i].flag;
else
cnt[i] = cnt[i-1] + car[i].flag; //这个flag有点好用
}
for(int i=0; i<k; i++) {
int h, m, s;
scanf("%d:%d:%d", &h, &m, &s);
int temptime = h*3600 + m*60 + s;
int j;
for(j = tempindex; j<car.size(); j++) {
if(car[j].time > temptime) {
printf("%d\n", cnt[j-1]);
break;
} else if(j == car.size()-1) {
printf("%d\n", cnt[j]); //查询时间靠最后
}
tempindex = j;
}
}
for(auto it:mp) { //map本来就按照字典序排列
if(it.second == maxtime)
printf("%s ", it.first.c_str());
}
printf("%02d:%02d:%02d", maxtime/3600, (maxtime%3600)/60, maxtime%60);
return 0;
} | 25.633803 | 99 | 0.51978 | [
"vector"
] |
c8f697e045d437fc380639fc763603038d9897b3 | 2,405 | cpp | C++ | dlgsquar.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 12 | 2019-06-07T10:06:41.000Z | 2021-03-22T22:13:59.000Z | dlgsquar.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 1 | 2019-05-09T07:38:12.000Z | 2019-07-10T04:20:55.000Z | dlgsquar.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 3 | 2020-09-08T08:27:33.000Z | 2021-05-13T09:25:43.000Z | // dlgsquar.cpp : implementation file
//
#include "stdafx.h"
#include "audtest.h"
#include "zFormEdt.h"
#include "dlgsquar.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgSquare property page
IMPLEMENT_DYNCREATE(CDlgSquare, CPropertyPage)
CDlgSquare::CDlgSquare() : CPropertyPage(CDlgSquare::IDD), m_cDutyCycle(), m_cFreq()
{
EnableAutomation();
//{{AFX_DATA_INIT(CDlgSquare)
//}}AFX_DATA_INIT
}
CDlgSquare::~CDlgSquare()
{
}
void CDlgSquare::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. This implementation deletes the
// object. Add additional cleanup required for your object before
// deleting it from memory.
delete this;
}
void CDlgSquare::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
m_cDutyCycle.DDX_Value( pDX, m_fDutyCycle);
m_cFreq.DDX_Value( pDX, m_fFreq);
//{{AFX_DATA_MAP(CDlgSquare)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgSquare, CPropertyPage)
//{{AFX_MSG_MAP(CDlgSquare)
ON_NOTIFY(UDN_DELTAPOS, IDC_SCRL1, OnDeltaposScrl1)
ON_NOTIFY(UDN_DELTAPOS, IDC_SCRL2, OnDeltaposScrl2)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CDlgSquare, CDialog)
//{{AFX_DISPATCH_MAP(CDlgSquare)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgSquare message handlers
BOOL CDlgSquare::OnInitDialog()
{
m_cFreq.Subclass( this, IDC_FREQ, IDC_SCRL1);
m_cFreq.SetLimits( 1.0f, 20000.0f);
m_cDutyCycle.Subclass( this, IDC_DUTYCYCLE, IDC_SCRL2);
m_cDutyCycle.SetLimits( 0.0f, 100.0f);
CPropertyPage::OnInitDialog();
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDlgSquare::OnDeltaposScrl1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
m_cFreq.ProcessDelta( pNMUpDown->iDelta); // that's it....
*pResult = 0;
}
void CDlgSquare::OnDeltaposScrl2(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
m_cDutyCycle.ProcessDelta( pNMUpDown->iDelta); // that's it....
*pResult = 0;
}
| 23.811881 | 84 | 0.695634 | [
"object"
] |
c8f771601266aa57a2ec6a46d8f345b623fa2038 | 1,672 | cpp | C++ | inference-engine/src/cldnn_engine/ops/lrn.cpp | YUNEEC/openvino | a73a9a37124ca44445683e003f53f41ce8e1dee6 | [
"Apache-2.0"
] | null | null | null | inference-engine/src/cldnn_engine/ops/lrn.cpp | YUNEEC/openvino | a73a9a37124ca44445683e003f53f41ce8e1dee6 | [
"Apache-2.0"
] | null | null | null | inference-engine/src/cldnn_engine/ops/lrn.cpp | YUNEEC/openvino | a73a9a37124ca44445683e003f53f41ce8e1dee6 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "cldnn_program.h"
#include "cldnn_common_utils.h"
#include "ngraph/op/lrn.hpp"
#include "ngraph/op/constant.hpp"
#include "api/lrn.hpp"
namespace CLDNNPlugin {
static cldnn::lrn_norm_region GetNormRegion(std::vector<int64_t> axis_value) {
if (axis_value.size() == 1 && axis_value[0] == 1) {
return cldnn::lrn_norm_region_across_channel;
} else {
return cldnn::lrn_norm_region_within_channel;
}
}
void CreateLRNOp(Program& p, const std::shared_ptr<ngraph::op::v0::LRN>& op) {
p.ValidateInputs(op, {2});
auto inputPrimitives = p.GetInputPrimitiveIDs(op);
std::string layerName = layer_type_name_ID(op);
auto axis_const = std::dynamic_pointer_cast<ngraph::op::v0::Constant>(op->get_input_node_shared_ptr(1));
if (!axis_const) {
IE_THROW() << "Unsupported axes node type in " << op->get_friendly_name() << " (" << op->get_type_name() << ")";
}
auto axis_value = axis_const->cast_vector<int64_t>();
auto localSize = op->get_nsize();
auto lrnPrim = cldnn::lrn(layerName,
inputPrimitives[0],
localSize,
static_cast<float>(op->get_bias()),
static_cast<float>(op->get_alpha()),
static_cast<float>(op->get_beta()),
GetNormRegion(axis_value),
op->get_friendly_name());
p.AddPrimitive(lrnPrim);
p.AddPrimitiveToProfiler(op);
}
REGISTER_FACTORY_IMPL(v0, LRN);
} // namespace CLDNNPlugin
| 32.784314 | 120 | 0.610048 | [
"vector"
] |
7402aea62b4b40691f19f1ef195ee769fd83689d | 13,923 | cpp | C++ | src/System/Player.cpp | asifmallik/SCALE-MAMBA | 80db831818b55b7675dd549920b5fb096db4321f | [
"BSD-2-Clause"
] | null | null | null | src/System/Player.cpp | asifmallik/SCALE-MAMBA | 80db831818b55b7675dd549920b5fb096db4321f | [
"BSD-2-Clause"
] | null | null | null | src/System/Player.cpp | asifmallik/SCALE-MAMBA | 80db831818b55b7675dd549920b5fb096db4321f | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
Copyright (c) 2020, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
All rights reserved
*/
#include <errno.h>
#if !defined(__MACH__)
#include <malloc.h>
#else
#include <stdlib.h>
#endif
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <resolv.h>
#include <arpa/inet.h>
#include "openssl/err.h"
#include "openssl/ssl.h"
#include <fstream>
#include <mutex>
using namespace std;
#include "Exceptions/Exceptions.h"
#include "Networking.h"
#include "Player.h"
SSL_CTX *InitCTX(void)
{
const SSL_METHOD *method;
SSL_CTX *ctx;
method= TLS_method(); /* create new server-method instance */
ctx= SSL_CTX_new(method); /* create new context from method */
if (ctx == NULL)
{
ERR_print_errors_fp(stdout);
throw SSL_error("InitCTX");
}
SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
return ctx;
}
void LoadCertificates(SSL_CTX *ctx, const char *CertFile, const char *KeyFile)
{
/* set the local certificate from CertFile */
if (SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stdout);
throw SSL_error("LoadCertificates 1");
}
/* set the private key from KeyFile (may be the same as CertFile) */
if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stdout);
throw SSL_error("LoadCertificates 2");
}
/* verify private key */
if (!SSL_CTX_check_private_key(ctx))
{
throw SSL_error("Private key does not match the public certificate");
}
}
void ShowCerts(SSL *ssl, const string CommonName, int verbose)
{
X509 *cert;
char *line;
cert= SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
if (cert != NULL)
{
if (verbose > 0)
{
printf("Server certificates:\n");
line= X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line= X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
}
char buffer[256];
X509_NAME_get_text_by_NID(X509_get_subject_name(cert), NID_commonName,
buffer, 256);
string name(buffer);
if (verbose > 0)
{
printf("Subject Comman Name: %s\n", buffer);
}
if (name.compare(CommonName) != 0)
{
throw SSL_error("Common name does not match what I was expecting");
}
X509_free(cert);
}
else
printf("No certificates.\n");
}
void Init_SSL_CTX(SSL_CTX *&ctx, unsigned int me, const SystemData &SD, const string &rootDirectory)
{
// Initialize the SSL library
OPENSSL_init_ssl(
OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
ctx= InitCTX();
// Load in my certificates
string str_crt= rootDirectory + "Cert-Store/" + SD.PlayerCRT[me];
std::cout << "sm::" << me << ":: loading certificate from " + str_crt
<< std::endl;
string str_key= str_crt.substr(0, str_crt.length() - 3) + "key";
LoadCertificates(ctx, str_crt.c_str(), str_key.c_str());
// Turn on client auth via cert
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
NULL);
// Load in root CA
string str= rootDirectory + "Cert-Store/" + SD.RootCRT;
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(str.c_str()));
SSL_CTX_load_verify_locations(ctx, str.c_str(), NULL);
}
Player::Player(int mynumber, const SystemData &SD, int thread, SSL_CTX *ctx,
vector<vector<int>> &csockets, const vector<gfp> &MacK, int verbose)
{
unsigned int nbChannels= csockets[0].size();
clocks.resize(10);
G.ReSeed(thread);
sha256.resize(nbChannels);
for (unsigned int i= 0; i < nbChannels; i++)
{
SHA256_Init(&sha256[i]);
}
me= mynumber;
ssl.resize(SD.n);
#ifdef BENCH_NETDATA
br_messages_sent= 0;
pp_messages_sent= 0;
data_sent= 0;
data_received= 0;
#endif
// When communicating with player i, player me acts as server when i<me
for (unsigned int i= 0; i < SD.n; i++)
{
ssl[i].resize(nbChannels);
for (unsigned int j= 0; j < nbChannels; j++)
{
if (i != me)
{
ssl[i][j]= SSL_new(ctx); /* get new SSL state with context */
if (i < me)
{ /* set connection socket to SSL state */
int ret= SSL_set_fd(ssl[i][j], csockets[i][j]);
if (ret == 0)
{
printf("S: Player %d failed to SSL_set_fd with player %d on connection %d in thread %d\n",
mynumber, i, j, thread);
throw SSL_error("SSL_set_fd");
}
if (verbose > 0)
{
printf("S: Player %d going SSL with player %d on connction %d at %s in thread %d\n",
mynumber, i, j, SD.IP[i].c_str(), thread);
}
/* do SSL-protocol accept */
ret= SSL_accept(ssl[i][j]);
if (ret <= 0)
{
printf("S: Error in player %d accepting to player %d on connection %d at address %s "
"in thread %d\n",
mynumber, i, j, SD.IP[i].c_str(), thread);
ERR_print_errors_fp(stdout);
throw SSL_error("SSL_accept");
}
if (verbose > 0)
{
printf("S: Player %d connected to player %d on connection %d in thread %d with %s "
"encryption\n",
mynumber, i, j, thread, SSL_get_cipher(ssl[i][j]));
}
}
else
{ // Now client side stuff
int ret= SSL_set_fd(ssl[i][j], csockets[i][j]);
if (ret == 0)
{
printf("C: Player %d failed to SSL_set_fd with player %d on connection% d in thread %d\n",
mynumber, i, j, thread);
throw SSL_error("SSL_set_fd");
}
if (verbose > 0)
{
printf("C: Player %d going SSL with player %d on connection %d at %s in thread %d\n",
mynumber, i, j, SD.IP[i].c_str(), thread);
}
/* do SSL-protocol connect */
ret= SSL_connect(ssl[i][j]);
if (ret <= 0)
{
printf("C: Error player %d connecting to player %d on connection %d at address %s in "
"thread %d\n",
mynumber, i, j, SD.IP[i].c_str(), thread);
ERR_print_errors_fp(stdout);
throw SSL_error("SSL_connect");
}
if (verbose > 0)
{
printf("C: Player %d connected to player %d on connection %d in thread %d with %s "
"encryption\n",
mynumber, i, j, thread, SSL_get_cipher(ssl[i][j]));
}
}
ShowCerts(ssl[i][j], SD.PlayerCN[i], verbose - 1); /* get cert and test common name */
}
}
}
mac_keys= MacK;
}
Player::~Player()
{
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i != me)
{
SSL_free(ssl[i][0]);
SSL_free(ssl[i][1]);
SSL_free(ssl[i][2]);
}
}
}
void Player::send_all(const string &o, int connection, bool verbose) const
{
uint8_t buff[4];
#ifdef BENCH_NETDATA
br_messages_sent++;
int len_buff= 4;
#endif
encode_length(buff, o.length());
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i != me)
{
if (SSL_write(ssl[i][connection], buff, 4) != 4)
{
throw sending_error();
}
if (SSL_write(ssl[i][connection], o.c_str(), o.length()) != (int) o.length())
{
throw sending_error();
}
#ifdef BENCH_NETDATA
data_sent+= len_buff + o.length();
#endif
if (verbose)
{
printf("Sent to player %d : ", i);
for (unsigned int j= 0; j < 4; j++)
{
printf("%.2X", (uint8_t) buff[j]);
}
printf(" : ");
for (unsigned int j= 0; j < o.size(); j++)
{
printf("%.2X", (uint8_t) o.c_str()[j]);
}
printf("\n");
}
}
}
}
void Player::send_to_player(int player, const string &o, int connection) const
{
uint8_t buff[4];
int len_buff= 4;
encode_length(buff, o.length());
if (SSL_write(ssl[player][connection], buff, len_buff) != len_buff)
{
throw sending_error();
}
if (SSL_write(ssl[player][connection], o.c_str(), o.length()) != (int) o.length())
{
throw sending_error();
}
#ifdef BENCH_NETDATA
pp_messages_sent++;
data_sent+= len_buff + o.length();
#endif
}
void receive(SSL *ssl, uint8_t *data, int len)
{
int i= 0, j;
while (len - i > 0)
{
j= SSL_read(ssl, data + i, len - i);
if (j <= 0)
{
/*
int e0=SSL_get_error(ssl,j);
int e1=ERR_get_error();
printf("SSL_READ error : %d : %d % d : Was trying to read % d bytes out
of % d bytes \n",j,e0,e1,len-i,len);
perror("Some Error" );
*/
throw receiving_error();
}
i= i + j;
}
if (len - i != 0)
{
throw receiving_error();
}
}
void Player::receive_from_player(int i, string &o, int connection, bool verbose) const
{
uint8_t buff[4];
unsigned int len_buff= 4;
receive(ssl[i][connection], buff, len_buff);
int nlen= decode_length(buff);
uint8_t *sbuff= new uint8_t[nlen];
receive(ssl[i][connection], sbuff, nlen);
o.assign((char *) sbuff, nlen);
#ifdef BENCH_NETDATA
data_received+= len_buff + nlen;
#endif
if (verbose)
{
printf("Received from player %d : ", i);
for (unsigned int j= 0; j < len_buff; j++)
{
printf("%.2X", (uint8_t) buff[j]);
}
printf(" : ");
for (unsigned int j= 0; j < o.size(); j++)
{
printf("%.2X", (uint8_t) o.c_str()[j]);
}
printf("\n");
for (int j= 0; j < nlen; j++)
{
printf("%.2X", (uint8_t) sbuff[j]);
}
printf("\n");
}
delete[] sbuff;
}
/* This is deliberately weird to avoid problems with OS max buffer
* size getting in the way
*/
void Player::Broadcast_Receive(vector<string> &o, bool check, int connection)
{
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i > me)
{
send_to_player(i, o[me], connection);
}
else if (i < me)
{
receive_from_player(i, o[i], connection);
}
}
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i < me)
{
send_to_player(i, o[me], connection);
}
else if (i > me)
{
receive_from_player(i, o[i], connection);
}
}
if (check)
{
for (unsigned int i= 0; i < ssl.size(); i++)
{
SHA256_Update(&sha256[connection], o[i].c_str(), o[i].size());
}
}
}
void Player::Check_Broadcast(int connection)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_Final(hash, &sha256[connection]);
string ss((char *) hash, SHA256_DIGEST_LENGTH);
send_all(ss, connection);
for (unsigned int i= 0; i < nplayers(); i++)
{
if (i != whoami())
{
string is;
receive_from_player(i, is, connection);
if (is != ss)
{
throw hash_fail();
}
}
}
SHA256_Init(&sha256[connection]);
}
/* Again this is deliberately weird to avoid problems with OS max buffer
* size getting in the way
*/
void Player::Send_Distinct_And_Receive(vector<string> &o, int connection) const
{
vector<string> rec(ssl.size());
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i > me)
{
send_to_player(i, o[i], connection);
}
else if (i < me)
{
receive_from_player(i, rec[i], connection);
}
}
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i < me)
{
send_to_player(i, o[i], connection);
}
else if (i > me)
{
receive_from_player(i, rec[i], connection);
}
}
for (unsigned int i= 0; i < ssl.size(); i++)
{
if (i != me)
{
o[i]= move(rec[i]);
}
}
}
#ifdef BENCH_NETDATA
void Player::print_network_data(int thread_num)
{
printf(BENCH_TEXT_BOLD BENCH_COLOR_BLUE BENCH_MAGIC_START
"{\"player\":%u,\n"
" \"thread\":%d,\n"
" \"netdata\":{\n"
" \"sent\":{\"bytes\":%ld,\"MB\":%.2f},\n"
" \"received\":{\"bytes\":%ld,\"MB\":%.2f}\n"
" }\n"
" \"roundsdata\":{\n"
" \"broadcast\":%ld\n"
" \"p-to-p\":%ld\n"
" }\n"
"}\n" BENCH_MAGIC_END BENCH_ATTR_RESET,
me, thread_num, data_sent, ((double) data_sent / 1000000), data_received, ((double) data_received / 1000000), br_messages_sent, pp_messages_sent);
}
#endif
| 28.530738 | 155 | 0.519572 | [
"vector"
] |
740508e27876f531bf73b7633d84148f62172cb2 | 3,892 | cpp | C++ | src/standard/2d/sprite/sprite_system.cpp | jamjarlabs/JamJarNative | ed8aea9cbd3f1eed3eb49c7da0df50eea87e880e | [
"MIT"
] | 1 | 2022-03-28T02:26:23.000Z | 2022-03-28T02:26:23.000Z | src/standard/2d/sprite/sprite_system.cpp | jamjarlabs/JamJarNative | ed8aea9cbd3f1eed3eb49c7da0df50eea87e880e | [
"MIT"
] | 103 | 2020-02-24T23:52:58.000Z | 2021-04-18T21:00:50.000Z | src/standard/2d/sprite/sprite_system.cpp | jamjarlabs/JamJarNative | ed8aea9cbd3f1eed3eb49c7da0df50eea87e880e | [
"MIT"
] | 1 | 2021-05-20T22:29:44.000Z | 2021-05-20T22:29:44.000Z | #include "standard/2d/sprite/sprite_system.hpp"
#include "game.hpp"
#include "message/message_payload.hpp"
#include "standard/2d/render/render_system.hpp"
#include "standard/2d/render/renderable.hpp"
#include "standard/2d/sprite/sprite.hpp"
#include "standard/2d/transform/transform.hpp"
#include <array>
#include <memory>
const std::string JamJar::Standard::_2D::SpriteSystem::DEFAULT_SPRITE_VERTEX_SHADER_NAME =
"jamjar_default_sprite_vertex";
const std::string JamJar::Standard::_2D::SpriteSystem::DEFAULT_SPRITE_FRAGMENT_SHADER_NAME =
"jamjar_default_sprite_fragment";
JamJar::Standard::_2D::SpriteSystem::SpriteSystem(MessageBus *messageBus)
: VectorSystem(messageBus, JamJar::Standard::_2D::SpriteSystem::evaluator) {
this->messageBus->Subscribe(this, JamJar::Game::MESSAGE_PRE_RENDER);
#ifdef __EMSCRIPTEN__
this->loadWebgl2Shaders();
#endif
}
#ifdef __EMSCRIPTEN__
#include "standard/2d/sprite/webgl2_default_sprite_shaders.hpp"
#include "standard/2d/webgl2/webgl2_system.hpp"
void JamJar::Standard::_2D::SpriteSystem::loadWebgl2Shaders() {
// Load WebGL2 fragment shader
auto fragShader =
std::make_unique<WebGL2DefaultSpriteFragmentShader>(JamJar::Standard::_2D::WebGL2DefaultSpriteFragmentShader());
this->messageBus->Publish(
std::make_unique<JamJar::MessagePayload<std::unique_ptr<WebGL2DefaultSpriteFragmentShader>>>(
JamJar::Standard::_2D::WebGL2System::MESSAGE_LOAD_SHADER, std::move(fragShader)));
// Load WebGL2 vertex shader
auto vertShader =
std::make_unique<WebGL2DefaultSpriteVertexShader>(JamJar::Standard::_2D::WebGL2DefaultSpriteVertexShader());
this->messageBus->Publish(
std::make_unique<JamJar::MessagePayload<std::unique_ptr<WebGL2DefaultSpriteVertexShader>>>(
JamJar::Standard::_2D::WebGL2System::MESSAGE_LOAD_SHADER, std::move(vertShader)));
}
#endif
const std::vector<float> QUAD_POINTS = {0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5};
bool JamJar::Standard::_2D::SpriteSystem::evaluator(Entity *entity,
const std::vector<JamJar::Component *> &components) {
bool hasSprite = false;
bool hasTransform = false;
for (const auto &component : components) {
if (component->key == JamJar::Standard::_2D::Sprite::KEY) {
hasSprite = true;
}
if (component->key == JamJar::Standard::_2D::Transform::KEY) {
hasTransform = true;
}
if (hasSprite && hasTransform) {
return true;
}
}
return false;
}
void JamJar::Standard::_2D::SpriteSystem::OnMessage(JamJar::Message *message) {
VectorSystem::OnMessage(message);
switch (message->type) {
case JamJar::Game::MESSAGE_PRE_RENDER: {
auto *renderMessage = static_cast<JamJar::MessagePayload<float> *>(message);
this->preRender(renderMessage->payload);
break;
}
}
}
void JamJar::Standard::_2D::SpriteSystem::preRender(float alpha) {
std::vector<Renderable> renderables;
for (auto &entity : this->entities) {
auto transform = entity.Get<JamJar::Standard::_2D::Transform>();
auto sprite = entity.Get<JamJar::Standard::_2D::Sprite>();
auto quad = AABB(Vector2D(1, 1));
quad.dimensions += transform->scale;
quad.center += transform->position;
renderables.push_back({.vertices = QUAD_POINTS,
.modelMatrix = transform->InterpolatedMatrix4D(alpha),
.material = sprite->material,
.drawMode = JamJar::Standard::_2D::DrawMode::TRIANGLES});
}
auto msg = std::make_unique<JamJar::MessagePayload<std::vector<Renderable>>>(
JamJar::Standard::_2D::RenderSystem::MESSAGE_LOAD_RENDERABLES, renderables);
this->messageBus->Publish(std::move(msg));
}
| 41.849462 | 120 | 0.677544 | [
"render",
"vector",
"transform"
] |
740582125998d3dd86a5a8a341f5748246ba09ac | 45,167 | cpp | C++ | mlir/lib/Target/SPIRV/Serialization/Serializer.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Target/SPIRV/Serialization/Serializer.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Target/SPIRV/Serialization/Serializer.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | null | null | null | //===- Serializer.cpp - MLIR SPIR-V Serializer ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the MLIR SPIR-V module to SPIR-V binary serializer.
//
//===----------------------------------------------------------------------===//
#include "Serializer.h"
#include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
#include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
#include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Target/SPIRV/SPIRVBinaryUtils.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/ADT/bit.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "spirv-serialization"
using namespace mlir;
/// Returns the merge block if the given `op` is a structured control flow op.
/// Otherwise returns nullptr.
static Block *getStructuredControlFlowOpMergeBlock(Operation *op) {
if (auto selectionOp = dyn_cast<spirv::SelectionOp>(op))
return selectionOp.getMergeBlock();
if (auto loopOp = dyn_cast<spirv::LoopOp>(op))
return loopOp.getMergeBlock();
return nullptr;
}
/// Given a predecessor `block` for a block with arguments, returns the block
/// that should be used as the parent block for SPIR-V OpPhi instructions
/// corresponding to the block arguments.
static Block *getPhiIncomingBlock(Block *block) {
// If the predecessor block in question is the entry block for a
// spv.mlir.loop, we jump to this spv.mlir.loop from its enclosing block.
if (block->isEntryBlock()) {
if (auto loopOp = dyn_cast<spirv::LoopOp>(block->getParentOp())) {
// Then the incoming parent block for OpPhi should be the merge block of
// the structured control flow op before this loop.
Operation *op = loopOp.getOperation();
while ((op = op->getPrevNode()) != nullptr)
if (Block *incomingBlock = getStructuredControlFlowOpMergeBlock(op))
return incomingBlock;
// Or the enclosing block itself if no structured control flow ops
// exists before this loop.
return loopOp->getBlock();
}
}
// Otherwise, we jump from the given predecessor block. Try to see if there is
// a structured control flow op inside it.
for (Operation &op : llvm::reverse(block->getOperations())) {
if (Block *incomingBlock = getStructuredControlFlowOpMergeBlock(&op))
return incomingBlock;
}
return block;
}
namespace mlir {
namespace spirv {
/// Encodes an SPIR-V instruction with the given `opcode` and `operands` into
/// the given `binary` vector.
void encodeInstructionInto(SmallVectorImpl<uint32_t> &binary, spirv::Opcode op,
ArrayRef<uint32_t> operands) {
uint32_t wordCount = 1 + operands.size();
binary.push_back(spirv::getPrefixedOpcode(wordCount, op));
binary.append(operands.begin(), operands.end());
}
Serializer::Serializer(spirv::ModuleOp module,
const SerializationOptions &options)
: module(module), mlirBuilder(module.getContext()), options(options) {}
LogicalResult Serializer::serialize() {
LLVM_DEBUG(llvm::dbgs() << "+++ starting serialization +++\n");
if (failed(module.verifyInvariants()))
return failure();
// TODO: handle the other sections
processCapability();
processExtension();
processMemoryModel();
processDebugInfo();
// Iterate over the module body to serialize it. Assumptions are that there is
// only one basic block in the moduleOp
for (auto &op : *module.getBody()) {
if (failed(processOperation(&op))) {
return failure();
}
}
LLVM_DEBUG(llvm::dbgs() << "+++ completed serialization +++\n");
return success();
}
void Serializer::collect(SmallVectorImpl<uint32_t> &binary) {
auto moduleSize = spirv::kHeaderWordCount + capabilities.size() +
extensions.size() + extendedSets.size() +
memoryModel.size() + entryPoints.size() +
executionModes.size() + decorations.size() +
typesGlobalValues.size() + functions.size();
binary.clear();
binary.reserve(moduleSize);
spirv::appendModuleHeader(binary, module.vce_triple()->getVersion(), nextID);
binary.append(capabilities.begin(), capabilities.end());
binary.append(extensions.begin(), extensions.end());
binary.append(extendedSets.begin(), extendedSets.end());
binary.append(memoryModel.begin(), memoryModel.end());
binary.append(entryPoints.begin(), entryPoints.end());
binary.append(executionModes.begin(), executionModes.end());
binary.append(debug.begin(), debug.end());
binary.append(names.begin(), names.end());
binary.append(decorations.begin(), decorations.end());
binary.append(typesGlobalValues.begin(), typesGlobalValues.end());
binary.append(functions.begin(), functions.end());
}
#ifndef NDEBUG
void Serializer::printValueIDMap(raw_ostream &os) {
os << "\n= Value <id> Map =\n\n";
for (auto valueIDPair : valueIDMap) {
Value val = valueIDPair.first;
os << " " << val << " "
<< "id = " << valueIDPair.second << ' ';
if (auto *op = val.getDefiningOp()) {
os << "from op '" << op->getName() << "'";
} else if (auto arg = val.dyn_cast<BlockArgument>()) {
Block *block = arg.getOwner();
os << "from argument of block " << block << ' ';
os << " in op '" << block->getParentOp()->getName() << "'";
}
os << '\n';
}
}
#endif
//===----------------------------------------------------------------------===//
// Module structure
//===----------------------------------------------------------------------===//
uint32_t Serializer::getOrCreateFunctionID(StringRef fnName) {
auto funcID = funcIDMap.lookup(fnName);
if (!funcID) {
funcID = getNextID();
funcIDMap[fnName] = funcID;
}
return funcID;
}
void Serializer::processCapability() {
for (auto cap : module.vce_triple()->getCapabilities())
encodeInstructionInto(capabilities, spirv::Opcode::OpCapability,
{static_cast<uint32_t>(cap)});
}
void Serializer::processDebugInfo() {
if (!options.emitDebugInfo)
return;
auto fileLoc = module.getLoc().dyn_cast<FileLineColLoc>();
auto fileName = fileLoc ? fileLoc.getFilename().strref() : "<unknown>";
fileID = getNextID();
SmallVector<uint32_t, 16> operands;
operands.push_back(fileID);
spirv::encodeStringLiteralInto(operands, fileName);
encodeInstructionInto(debug, spirv::Opcode::OpString, operands);
// TODO: Encode more debug instructions.
}
void Serializer::processExtension() {
llvm::SmallVector<uint32_t, 16> extName;
for (spirv::Extension ext : module.vce_triple()->getExtensions()) {
extName.clear();
spirv::encodeStringLiteralInto(extName, spirv::stringifyExtension(ext));
encodeInstructionInto(extensions, spirv::Opcode::OpExtension, extName);
}
}
void Serializer::processMemoryModel() {
uint32_t mm = module->getAttrOfType<IntegerAttr>("memory_model").getInt();
uint32_t am = module->getAttrOfType<IntegerAttr>("addressing_model").getInt();
encodeInstructionInto(memoryModel, spirv::Opcode::OpMemoryModel, {am, mm});
}
LogicalResult Serializer::processDecoration(Location loc, uint32_t resultID,
NamedAttribute attr) {
auto attrName = attr.getName().strref();
auto decorationName = llvm::convertToCamelFromSnakeCase(attrName, true);
auto decoration = spirv::symbolizeDecoration(decorationName);
if (!decoration) {
return emitError(
loc, "non-argument attributes expected to have snake-case-ified "
"decoration name, unhandled attribute with name : ")
<< attrName;
}
SmallVector<uint32_t, 1> args;
switch (decoration.getValue()) {
case spirv::Decoration::Binding:
case spirv::Decoration::DescriptorSet:
case spirv::Decoration::Location:
if (auto intAttr = attr.getValue().dyn_cast<IntegerAttr>()) {
args.push_back(intAttr.getValue().getZExtValue());
break;
}
return emitError(loc, "expected integer attribute for ") << attrName;
case spirv::Decoration::BuiltIn:
if (auto strAttr = attr.getValue().dyn_cast<StringAttr>()) {
auto enumVal = spirv::symbolizeBuiltIn(strAttr.getValue());
if (enumVal) {
args.push_back(static_cast<uint32_t>(enumVal.getValue()));
break;
}
return emitError(loc, "invalid ")
<< attrName << " attribute " << strAttr.getValue();
}
return emitError(loc, "expected string attribute for ") << attrName;
case spirv::Decoration::Aliased:
case spirv::Decoration::Flat:
case spirv::Decoration::NonReadable:
case spirv::Decoration::NonWritable:
case spirv::Decoration::NoPerspective:
case spirv::Decoration::Restrict:
case spirv::Decoration::RelaxedPrecision:
// For unit attributes, the args list has no values so we do nothing
if (auto unitAttr = attr.getValue().dyn_cast<UnitAttr>())
break;
return emitError(loc, "expected unit attribute for ") << attrName;
default:
return emitError(loc, "unhandled decoration ") << decorationName;
}
return emitDecoration(resultID, decoration.getValue(), args);
}
LogicalResult Serializer::processName(uint32_t resultID, StringRef name) {
assert(!name.empty() && "unexpected empty string for OpName");
if (!options.emitSymbolName)
return success();
SmallVector<uint32_t, 4> nameOperands;
nameOperands.push_back(resultID);
spirv::encodeStringLiteralInto(nameOperands, name);
encodeInstructionInto(names, spirv::Opcode::OpName, nameOperands);
return success();
}
template <>
LogicalResult Serializer::processTypeDecoration<spirv::ArrayType>(
Location loc, spirv::ArrayType type, uint32_t resultID) {
if (unsigned stride = type.getArrayStride()) {
// OpDecorate %arrayTypeSSA ArrayStride strideLiteral
return emitDecoration(resultID, spirv::Decoration::ArrayStride, {stride});
}
return success();
}
template <>
LogicalResult Serializer::processTypeDecoration<spirv::RuntimeArrayType>(
Location loc, spirv::RuntimeArrayType type, uint32_t resultID) {
if (unsigned stride = type.getArrayStride()) {
// OpDecorate %arrayTypeSSA ArrayStride strideLiteral
return emitDecoration(resultID, spirv::Decoration::ArrayStride, {stride});
}
return success();
}
LogicalResult Serializer::processMemberDecoration(
uint32_t structID,
const spirv::StructType::MemberDecorationInfo &memberDecoration) {
SmallVector<uint32_t, 4> args(
{structID, memberDecoration.memberIndex,
static_cast<uint32_t>(memberDecoration.decoration)});
if (memberDecoration.hasValue) {
args.push_back(memberDecoration.decorationValue);
}
encodeInstructionInto(decorations, spirv::Opcode::OpMemberDecorate, args);
return success();
}
//===----------------------------------------------------------------------===//
// Type
//===----------------------------------------------------------------------===//
// According to the SPIR-V spec "Validation Rules for Shader Capabilities":
// "Composite objects in the StorageBuffer, PhysicalStorageBuffer, Uniform, and
// PushConstant Storage Classes must be explicitly laid out."
bool Serializer::isInterfaceStructPtrType(Type type) const {
if (auto ptrType = type.dyn_cast<spirv::PointerType>()) {
switch (ptrType.getStorageClass()) {
case spirv::StorageClass::PhysicalStorageBuffer:
case spirv::StorageClass::PushConstant:
case spirv::StorageClass::StorageBuffer:
case spirv::StorageClass::Uniform:
return ptrType.getPointeeType().isa<spirv::StructType>();
default:
break;
}
}
return false;
}
LogicalResult Serializer::processType(Location loc, Type type,
uint32_t &typeID) {
// Maintains a set of names for nested identified struct types. This is used
// to properly serialize recursive references.
SetVector<StringRef> serializationCtx;
return processTypeImpl(loc, type, typeID, serializationCtx);
}
LogicalResult
Serializer::processTypeImpl(Location loc, Type type, uint32_t &typeID,
SetVector<StringRef> &serializationCtx) {
typeID = getTypeID(type);
if (typeID)
return success();
typeID = getNextID();
SmallVector<uint32_t, 4> operands;
operands.push_back(typeID);
auto typeEnum = spirv::Opcode::OpTypeVoid;
bool deferSerialization = false;
if ((type.isa<FunctionType>() &&
succeeded(prepareFunctionType(loc, type.cast<FunctionType>(), typeEnum,
operands))) ||
succeeded(prepareBasicType(loc, type, typeID, typeEnum, operands,
deferSerialization, serializationCtx))) {
if (deferSerialization)
return success();
typeIDMap[type] = typeID;
encodeInstructionInto(typesGlobalValues, typeEnum, operands);
if (recursiveStructInfos.count(type) != 0) {
// This recursive struct type is emitted already, now the OpTypePointer
// instructions referring to recursive references are emitted as well.
for (auto &ptrInfo : recursiveStructInfos[type]) {
// TODO: This might not work if more than 1 recursive reference is
// present in the struct.
SmallVector<uint32_t, 4> ptrOperands;
ptrOperands.push_back(ptrInfo.pointerTypeID);
ptrOperands.push_back(static_cast<uint32_t>(ptrInfo.storageClass));
ptrOperands.push_back(typeIDMap[type]);
encodeInstructionInto(typesGlobalValues, spirv::Opcode::OpTypePointer,
ptrOperands);
}
recursiveStructInfos[type].clear();
}
return success();
}
return failure();
}
LogicalResult Serializer::prepareBasicType(
Location loc, Type type, uint32_t resultID, spirv::Opcode &typeEnum,
SmallVectorImpl<uint32_t> &operands, bool &deferSerialization,
SetVector<StringRef> &serializationCtx) {
deferSerialization = false;
if (isVoidType(type)) {
typeEnum = spirv::Opcode::OpTypeVoid;
return success();
}
if (auto intType = type.dyn_cast<IntegerType>()) {
if (intType.getWidth() == 1) {
typeEnum = spirv::Opcode::OpTypeBool;
return success();
}
typeEnum = spirv::Opcode::OpTypeInt;
operands.push_back(intType.getWidth());
// SPIR-V OpTypeInt "Signedness specifies whether there are signed semantics
// to preserve or validate.
// 0 indicates unsigned, or no signedness semantics
// 1 indicates signed semantics."
operands.push_back(intType.isSigned() ? 1 : 0);
return success();
}
if (auto floatType = type.dyn_cast<FloatType>()) {
typeEnum = spirv::Opcode::OpTypeFloat;
operands.push_back(floatType.getWidth());
return success();
}
if (auto vectorType = type.dyn_cast<VectorType>()) {
uint32_t elementTypeID = 0;
if (failed(processTypeImpl(loc, vectorType.getElementType(), elementTypeID,
serializationCtx))) {
return failure();
}
typeEnum = spirv::Opcode::OpTypeVector;
operands.push_back(elementTypeID);
operands.push_back(vectorType.getNumElements());
return success();
}
if (auto imageType = type.dyn_cast<spirv::ImageType>()) {
typeEnum = spirv::Opcode::OpTypeImage;
uint32_t sampledTypeID = 0;
if (failed(processType(loc, imageType.getElementType(), sampledTypeID)))
return failure();
operands.push_back(sampledTypeID);
operands.push_back(static_cast<uint32_t>(imageType.getDim()));
operands.push_back(static_cast<uint32_t>(imageType.getDepthInfo()));
operands.push_back(static_cast<uint32_t>(imageType.getArrayedInfo()));
operands.push_back(static_cast<uint32_t>(imageType.getSamplingInfo()));
operands.push_back(static_cast<uint32_t>(imageType.getSamplerUseInfo()));
operands.push_back(static_cast<uint32_t>(imageType.getImageFormat()));
return success();
}
if (auto arrayType = type.dyn_cast<spirv::ArrayType>()) {
typeEnum = spirv::Opcode::OpTypeArray;
uint32_t elementTypeID = 0;
if (failed(processTypeImpl(loc, arrayType.getElementType(), elementTypeID,
serializationCtx))) {
return failure();
}
operands.push_back(elementTypeID);
if (auto elementCountID = prepareConstantInt(
loc, mlirBuilder.getI32IntegerAttr(arrayType.getNumElements()))) {
operands.push_back(elementCountID);
}
return processTypeDecoration(loc, arrayType, resultID);
}
if (auto ptrType = type.dyn_cast<spirv::PointerType>()) {
uint32_t pointeeTypeID = 0;
spirv::StructType pointeeStruct =
ptrType.getPointeeType().dyn_cast<spirv::StructType>();
if (pointeeStruct && pointeeStruct.isIdentified() &&
serializationCtx.count(pointeeStruct.getIdentifier()) != 0) {
// A recursive reference to an enclosing struct is found.
//
// 1. Prepare an OpTypeForwardPointer with resultID and the ptr storage
// class as operands.
SmallVector<uint32_t, 2> forwardPtrOperands;
forwardPtrOperands.push_back(resultID);
forwardPtrOperands.push_back(
static_cast<uint32_t>(ptrType.getStorageClass()));
encodeInstructionInto(typesGlobalValues,
spirv::Opcode::OpTypeForwardPointer,
forwardPtrOperands);
// 2. Find the pointee (enclosing) struct.
auto structType = spirv::StructType::getIdentified(
module.getContext(), pointeeStruct.getIdentifier());
if (!structType)
return failure();
// 3. Mark the OpTypePointer that is supposed to be emitted by this call
// as deferred.
deferSerialization = true;
// 4. Record the info needed to emit the deferred OpTypePointer
// instruction when the enclosing struct is completely serialized.
recursiveStructInfos[structType].push_back(
{resultID, ptrType.getStorageClass()});
} else {
if (failed(processTypeImpl(loc, ptrType.getPointeeType(), pointeeTypeID,
serializationCtx)))
return failure();
}
typeEnum = spirv::Opcode::OpTypePointer;
operands.push_back(static_cast<uint32_t>(ptrType.getStorageClass()));
operands.push_back(pointeeTypeID);
if (isInterfaceStructPtrType(ptrType)) {
if (failed(emitDecoration(getTypeID(pointeeStruct),
spirv::Decoration::Block)))
return emitError(loc, "cannot decorate ")
<< pointeeStruct << " with Block decoration";
}
return success();
}
if (auto runtimeArrayType = type.dyn_cast<spirv::RuntimeArrayType>()) {
uint32_t elementTypeID = 0;
if (failed(processTypeImpl(loc, runtimeArrayType.getElementType(),
elementTypeID, serializationCtx))) {
return failure();
}
typeEnum = spirv::Opcode::OpTypeRuntimeArray;
operands.push_back(elementTypeID);
return processTypeDecoration(loc, runtimeArrayType, resultID);
}
if (auto sampledImageType = type.dyn_cast<spirv::SampledImageType>()) {
typeEnum = spirv::Opcode::OpTypeSampledImage;
uint32_t imageTypeID = 0;
if (failed(
processType(loc, sampledImageType.getImageType(), imageTypeID))) {
return failure();
}
operands.push_back(imageTypeID);
return success();
}
if (auto structType = type.dyn_cast<spirv::StructType>()) {
if (structType.isIdentified()) {
if (failed(processName(resultID, structType.getIdentifier())))
return failure();
serializationCtx.insert(structType.getIdentifier());
}
bool hasOffset = structType.hasOffset();
for (auto elementIndex :
llvm::seq<uint32_t>(0, structType.getNumElements())) {
uint32_t elementTypeID = 0;
if (failed(processTypeImpl(loc, structType.getElementType(elementIndex),
elementTypeID, serializationCtx))) {
return failure();
}
operands.push_back(elementTypeID);
if (hasOffset) {
// Decorate each struct member with an offset
spirv::StructType::MemberDecorationInfo offsetDecoration{
elementIndex, /*hasValue=*/1, spirv::Decoration::Offset,
static_cast<uint32_t>(structType.getMemberOffset(elementIndex))};
if (failed(processMemberDecoration(resultID, offsetDecoration))) {
return emitError(loc, "cannot decorate ")
<< elementIndex << "-th member of " << structType
<< " with its offset";
}
}
}
SmallVector<spirv::StructType::MemberDecorationInfo, 4> memberDecorations;
structType.getMemberDecorations(memberDecorations);
for (auto &memberDecoration : memberDecorations) {
if (failed(processMemberDecoration(resultID, memberDecoration))) {
return emitError(loc, "cannot decorate ")
<< static_cast<uint32_t>(memberDecoration.memberIndex)
<< "-th member of " << structType << " with "
<< stringifyDecoration(memberDecoration.decoration);
}
}
typeEnum = spirv::Opcode::OpTypeStruct;
if (structType.isIdentified())
serializationCtx.remove(structType.getIdentifier());
return success();
}
if (auto cooperativeMatrixType =
type.dyn_cast<spirv::CooperativeMatrixNVType>()) {
uint32_t elementTypeID = 0;
if (failed(processTypeImpl(loc, cooperativeMatrixType.getElementType(),
elementTypeID, serializationCtx))) {
return failure();
}
typeEnum = spirv::Opcode::OpTypeCooperativeMatrixNV;
auto getConstantOp = [&](uint32_t id) {
auto attr = IntegerAttr::get(IntegerType::get(type.getContext(), 32), id);
return prepareConstantInt(loc, attr);
};
operands.push_back(elementTypeID);
operands.push_back(
getConstantOp(static_cast<uint32_t>(cooperativeMatrixType.getScope())));
operands.push_back(getConstantOp(cooperativeMatrixType.getRows()));
operands.push_back(getConstantOp(cooperativeMatrixType.getColumns()));
return success();
}
if (auto matrixType = type.dyn_cast<spirv::MatrixType>()) {
uint32_t elementTypeID = 0;
if (failed(processTypeImpl(loc, matrixType.getColumnType(), elementTypeID,
serializationCtx))) {
return failure();
}
typeEnum = spirv::Opcode::OpTypeMatrix;
operands.push_back(elementTypeID);
operands.push_back(matrixType.getNumColumns());
return success();
}
// TODO: Handle other types.
return emitError(loc, "unhandled type in serialization: ") << type;
}
LogicalResult
Serializer::prepareFunctionType(Location loc, FunctionType type,
spirv::Opcode &typeEnum,
SmallVectorImpl<uint32_t> &operands) {
typeEnum = spirv::Opcode::OpTypeFunction;
assert(type.getNumResults() <= 1 &&
"serialization supports only a single return value");
uint32_t resultID = 0;
if (failed(processType(
loc, type.getNumResults() == 1 ? type.getResult(0) : getVoidType(),
resultID))) {
return failure();
}
operands.push_back(resultID);
for (auto &res : type.getInputs()) {
uint32_t argTypeID = 0;
if (failed(processType(loc, res, argTypeID))) {
return failure();
}
operands.push_back(argTypeID);
}
return success();
}
//===----------------------------------------------------------------------===//
// Constant
//===----------------------------------------------------------------------===//
uint32_t Serializer::prepareConstant(Location loc, Type constType,
Attribute valueAttr) {
if (auto id = prepareConstantScalar(loc, valueAttr)) {
return id;
}
// This is a composite literal. We need to handle each component separately
// and then emit an OpConstantComposite for the whole.
if (auto id = getConstantID(valueAttr)) {
return id;
}
uint32_t typeID = 0;
if (failed(processType(loc, constType, typeID))) {
return 0;
}
uint32_t resultID = 0;
if (auto attr = valueAttr.dyn_cast<DenseElementsAttr>()) {
int rank = attr.getType().dyn_cast<ShapedType>().getRank();
SmallVector<uint64_t, 4> index(rank);
resultID = prepareDenseElementsConstant(loc, constType, attr,
/*dim=*/0, index);
} else if (auto arrayAttr = valueAttr.dyn_cast<ArrayAttr>()) {
resultID = prepareArrayConstant(loc, constType, arrayAttr);
}
if (resultID == 0) {
emitError(loc, "cannot serialize attribute: ") << valueAttr;
return 0;
}
constIDMap[valueAttr] = resultID;
return resultID;
}
uint32_t Serializer::prepareArrayConstant(Location loc, Type constType,
ArrayAttr attr) {
uint32_t typeID = 0;
if (failed(processType(loc, constType, typeID))) {
return 0;
}
uint32_t resultID = getNextID();
SmallVector<uint32_t, 4> operands = {typeID, resultID};
operands.reserve(attr.size() + 2);
auto elementType = constType.cast<spirv::ArrayType>().getElementType();
for (Attribute elementAttr : attr) {
if (auto elementID = prepareConstant(loc, elementType, elementAttr)) {
operands.push_back(elementID);
} else {
return 0;
}
}
spirv::Opcode opcode = spirv::Opcode::OpConstantComposite;
encodeInstructionInto(typesGlobalValues, opcode, operands);
return resultID;
}
// TODO: Turn the below function into iterative function, instead of
// recursive function.
uint32_t
Serializer::prepareDenseElementsConstant(Location loc, Type constType,
DenseElementsAttr valueAttr, int dim,
MutableArrayRef<uint64_t> index) {
auto shapedType = valueAttr.getType().dyn_cast<ShapedType>();
assert(dim <= shapedType.getRank());
if (shapedType.getRank() == dim) {
if (auto attr = valueAttr.dyn_cast<DenseIntElementsAttr>()) {
return attr.getType().getElementType().isInteger(1)
? prepareConstantBool(loc, attr.getValues<BoolAttr>()[index])
: prepareConstantInt(loc,
attr.getValues<IntegerAttr>()[index]);
}
if (auto attr = valueAttr.dyn_cast<DenseFPElementsAttr>()) {
return prepareConstantFp(loc, attr.getValues<FloatAttr>()[index]);
}
return 0;
}
uint32_t typeID = 0;
if (failed(processType(loc, constType, typeID))) {
return 0;
}
uint32_t resultID = getNextID();
SmallVector<uint32_t, 4> operands = {typeID, resultID};
operands.reserve(shapedType.getDimSize(dim) + 2);
auto elementType = constType.cast<spirv::CompositeType>().getElementType(0);
for (int i = 0; i < shapedType.getDimSize(dim); ++i) {
index[dim] = i;
if (auto elementID = prepareDenseElementsConstant(
loc, elementType, valueAttr, dim + 1, index)) {
operands.push_back(elementID);
} else {
return 0;
}
}
spirv::Opcode opcode = spirv::Opcode::OpConstantComposite;
encodeInstructionInto(typesGlobalValues, opcode, operands);
return resultID;
}
uint32_t Serializer::prepareConstantScalar(Location loc, Attribute valueAttr,
bool isSpec) {
if (auto floatAttr = valueAttr.dyn_cast<FloatAttr>()) {
return prepareConstantFp(loc, floatAttr, isSpec);
}
if (auto boolAttr = valueAttr.dyn_cast<BoolAttr>()) {
return prepareConstantBool(loc, boolAttr, isSpec);
}
if (auto intAttr = valueAttr.dyn_cast<IntegerAttr>()) {
return prepareConstantInt(loc, intAttr, isSpec);
}
return 0;
}
uint32_t Serializer::prepareConstantBool(Location loc, BoolAttr boolAttr,
bool isSpec) {
if (!isSpec) {
// We can de-duplicate normal constants, but not specialization constants.
if (auto id = getConstantID(boolAttr)) {
return id;
}
}
// Process the type for this bool literal
uint32_t typeID = 0;
if (failed(processType(loc, boolAttr.getType(), typeID))) {
return 0;
}
auto resultID = getNextID();
auto opcode = boolAttr.getValue()
? (isSpec ? spirv::Opcode::OpSpecConstantTrue
: spirv::Opcode::OpConstantTrue)
: (isSpec ? spirv::Opcode::OpSpecConstantFalse
: spirv::Opcode::OpConstantFalse);
encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID});
if (!isSpec) {
constIDMap[boolAttr] = resultID;
}
return resultID;
}
uint32_t Serializer::prepareConstantInt(Location loc, IntegerAttr intAttr,
bool isSpec) {
if (!isSpec) {
// We can de-duplicate normal constants, but not specialization constants.
if (auto id = getConstantID(intAttr)) {
return id;
}
}
// Process the type for this integer literal
uint32_t typeID = 0;
if (failed(processType(loc, intAttr.getType(), typeID))) {
return 0;
}
auto resultID = getNextID();
APInt value = intAttr.getValue();
unsigned bitwidth = value.getBitWidth();
bool isSigned = value.isSignedIntN(bitwidth);
auto opcode =
isSpec ? spirv::Opcode::OpSpecConstant : spirv::Opcode::OpConstant;
switch (bitwidth) {
// According to SPIR-V spec, "When the type's bit width is less than
// 32-bits, the literal's value appears in the low-order bits of the word,
// and the high-order bits must be 0 for a floating-point type, or 0 for an
// integer type with Signedness of 0, or sign extended when Signedness
// is 1."
case 32:
case 16:
case 8: {
uint32_t word = 0;
if (isSigned) {
word = static_cast<int32_t>(value.getSExtValue());
} else {
word = static_cast<uint32_t>(value.getZExtValue());
}
encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID, word});
} break;
// According to SPIR-V spec: "When the type's bit width is larger than one
// word, the literal’s low-order words appear first."
case 64: {
struct DoubleWord {
uint32_t word1;
uint32_t word2;
} words;
if (isSigned) {
words = llvm::bit_cast<DoubleWord>(value.getSExtValue());
} else {
words = llvm::bit_cast<DoubleWord>(value.getZExtValue());
}
encodeInstructionInto(typesGlobalValues, opcode,
{typeID, resultID, words.word1, words.word2});
} break;
default: {
std::string valueStr;
llvm::raw_string_ostream rss(valueStr);
value.print(rss, /*isSigned=*/false);
emitError(loc, "cannot serialize ")
<< bitwidth << "-bit integer literal: " << rss.str();
return 0;
}
}
if (!isSpec) {
constIDMap[intAttr] = resultID;
}
return resultID;
}
uint32_t Serializer::prepareConstantFp(Location loc, FloatAttr floatAttr,
bool isSpec) {
if (!isSpec) {
// We can de-duplicate normal constants, but not specialization constants.
if (auto id = getConstantID(floatAttr)) {
return id;
}
}
// Process the type for this float literal
uint32_t typeID = 0;
if (failed(processType(loc, floatAttr.getType(), typeID))) {
return 0;
}
auto resultID = getNextID();
APFloat value = floatAttr.getValue();
APInt intValue = value.bitcastToAPInt();
auto opcode =
isSpec ? spirv::Opcode::OpSpecConstant : spirv::Opcode::OpConstant;
if (&value.getSemantics() == &APFloat::IEEEsingle()) {
uint32_t word = llvm::bit_cast<uint32_t>(value.convertToFloat());
encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID, word});
} else if (&value.getSemantics() == &APFloat::IEEEdouble()) {
struct DoubleWord {
uint32_t word1;
uint32_t word2;
} words = llvm::bit_cast<DoubleWord>(value.convertToDouble());
encodeInstructionInto(typesGlobalValues, opcode,
{typeID, resultID, words.word1, words.word2});
} else if (&value.getSemantics() == &APFloat::IEEEhalf()) {
uint32_t word =
static_cast<uint32_t>(value.bitcastToAPInt().getZExtValue());
encodeInstructionInto(typesGlobalValues, opcode, {typeID, resultID, word});
} else {
std::string valueStr;
llvm::raw_string_ostream rss(valueStr);
value.print(rss);
emitError(loc, "cannot serialize ")
<< floatAttr.getType() << "-typed float literal: " << rss.str();
return 0;
}
if (!isSpec) {
constIDMap[floatAttr] = resultID;
}
return resultID;
}
//===----------------------------------------------------------------------===//
// Control flow
//===----------------------------------------------------------------------===//
uint32_t Serializer::getOrCreateBlockID(Block *block) {
if (uint32_t id = getBlockID(block))
return id;
return blockIDMap[block] = getNextID();
}
#ifndef NDEBUG
void Serializer::printBlock(Block *block, raw_ostream &os) {
os << "block " << block << " (id = ";
if (uint32_t id = getBlockID(block))
os << id;
else
os << "unknown";
os << ")\n";
}
#endif
LogicalResult
Serializer::processBlock(Block *block, bool omitLabel,
function_ref<LogicalResult()> emitMerge) {
LLVM_DEBUG(llvm::dbgs() << "processing block " << block << ":\n");
LLVM_DEBUG(block->print(llvm::dbgs()));
LLVM_DEBUG(llvm::dbgs() << '\n');
if (!omitLabel) {
uint32_t blockID = getOrCreateBlockID(block);
LLVM_DEBUG(printBlock(block, llvm::dbgs()));
// Emit OpLabel for this block.
encodeInstructionInto(functionBody, spirv::Opcode::OpLabel, {blockID});
}
// Emit OpPhi instructions for block arguments, if any.
if (failed(emitPhiForBlockArguments(block)))
return failure();
// If we need to emit merge instructions, it must happen in this block. Check
// whether we have other structured control flow ops, which will be expanded
// into multiple basic blocks. If that's the case, we need to emit the merge
// right now and then create new blocks for further serialization of the ops
// in this block.
if (emitMerge && llvm::any_of(block->getOperations(), [](Operation &op) {
return isa<spirv::LoopOp, spirv::SelectionOp>(op);
})) {
if (failed(emitMerge()))
return failure();
emitMerge = nullptr;
// Start a new block for further serialization.
uint32_t blockID = getNextID();
encodeInstructionInto(functionBody, spirv::Opcode::OpBranch, {blockID});
encodeInstructionInto(functionBody, spirv::Opcode::OpLabel, {blockID});
}
// Process each op in this block except the terminator.
for (auto &op : llvm::make_range(block->begin(), std::prev(block->end()))) {
if (failed(processOperation(&op)))
return failure();
}
// Process the terminator.
if (emitMerge)
if (failed(emitMerge()))
return failure();
if (failed(processOperation(&block->back())))
return failure();
return success();
}
LogicalResult Serializer::emitPhiForBlockArguments(Block *block) {
// Nothing to do if this block has no arguments or it's the entry block, which
// always has the same arguments as the function signature.
if (block->args_empty() || block->isEntryBlock())
return success();
LLVM_DEBUG(llvm::dbgs() << "emitting phi instructions..\n");
// If the block has arguments, we need to create SPIR-V OpPhi instructions.
// A SPIR-V OpPhi instruction is of the syntax:
// OpPhi | result type | result <id> | (value <id>, parent block <id>) pair
// So we need to collect all predecessor blocks and the arguments they send
// to this block.
SmallVector<std::pair<Block *, OperandRange>, 4> predecessors;
for (Block *mlirPredecessor : block->getPredecessors()) {
auto *terminator = mlirPredecessor->getTerminator();
LLVM_DEBUG(llvm::dbgs() << " mlir predecessor ");
LLVM_DEBUG(printBlock(mlirPredecessor, llvm::dbgs()));
LLVM_DEBUG(llvm::dbgs() << " terminator: " << *terminator << "\n");
// The predecessor here is the immediate one according to MLIR's IR
// structure. It does not directly map to the incoming parent block for the
// OpPhi instructions at SPIR-V binary level. This is because structured
// control flow ops are serialized to multiple SPIR-V blocks. If there is a
// spv.mlir.selection/spv.mlir.loop op in the MLIR predecessor block, the
// branch op jumping to the OpPhi's block then resides in the previous
// structured control flow op's merge block.
Block *spirvPredecessor = getPhiIncomingBlock(mlirPredecessor);
LLVM_DEBUG(llvm::dbgs() << " spirv predecessor ");
LLVM_DEBUG(printBlock(spirvPredecessor, llvm::dbgs()));
if (auto branchOp = dyn_cast<spirv::BranchOp>(terminator)) {
predecessors.emplace_back(spirvPredecessor, branchOp.getOperands());
} else if (auto branchCondOp =
dyn_cast<spirv::BranchConditionalOp>(terminator)) {
Optional<OperandRange> blockOperands;
if (branchCondOp.trueTarget() == block) {
blockOperands = branchCondOp.trueTargetOperands();
} else {
assert(branchCondOp.falseTarget() == block);
blockOperands = branchCondOp.falseTargetOperands();
}
assert(!blockOperands->empty() &&
"expected non-empty block operand range");
predecessors.emplace_back(spirvPredecessor, *blockOperands);
} else {
return terminator->emitError("unimplemented terminator for Phi creation");
}
LLVM_DEBUG({
llvm::dbgs() << " block arguments:\n";
for (Value v : predecessors.back().second)
llvm::dbgs() << " " << v << "\n";
});
}
// Then create OpPhi instruction for each of the block argument.
for (auto argIndex : llvm::seq<unsigned>(0, block->getNumArguments())) {
BlockArgument arg = block->getArgument(argIndex);
// Get the type <id> and result <id> for this OpPhi instruction.
uint32_t phiTypeID = 0;
if (failed(processType(arg.getLoc(), arg.getType(), phiTypeID)))
return failure();
uint32_t phiID = getNextID();
LLVM_DEBUG(llvm::dbgs() << "[phi] for block argument #" << argIndex << ' '
<< arg << " (id = " << phiID << ")\n");
// Prepare the (value <id>, parent block <id>) pairs.
SmallVector<uint32_t, 8> phiArgs;
phiArgs.push_back(phiTypeID);
phiArgs.push_back(phiID);
for (auto predIndex : llvm::seq<unsigned>(0, predecessors.size())) {
Value value = predecessors[predIndex].second[argIndex];
uint32_t predBlockId = getOrCreateBlockID(predecessors[predIndex].first);
LLVM_DEBUG(llvm::dbgs() << "[phi] use predecessor (id = " << predBlockId
<< ") value " << value << ' ');
// Each pair is a value <id> ...
uint32_t valueId = getValueID(value);
if (valueId == 0) {
// The op generating this value hasn't been visited yet so we don't have
// an <id> assigned yet. Record this to fix up later.
LLVM_DEBUG(llvm::dbgs() << "(need to fix)\n");
deferredPhiValues[value].push_back(functionBody.size() + 1 +
phiArgs.size());
} else {
LLVM_DEBUG(llvm::dbgs() << "(id = " << valueId << ")\n");
}
phiArgs.push_back(valueId);
// ... and a parent block <id>.
phiArgs.push_back(predBlockId);
}
encodeInstructionInto(functionBody, spirv::Opcode::OpPhi, phiArgs);
valueIDMap[arg] = phiID;
}
return success();
}
//===----------------------------------------------------------------------===//
// Operation
//===----------------------------------------------------------------------===//
LogicalResult Serializer::encodeExtensionInstruction(
Operation *op, StringRef extensionSetName, uint32_t extensionOpcode,
ArrayRef<uint32_t> operands) {
// Check if the extension has been imported.
auto &setID = extendedInstSetIDMap[extensionSetName];
if (!setID) {
setID = getNextID();
SmallVector<uint32_t, 16> importOperands;
importOperands.push_back(setID);
spirv::encodeStringLiteralInto(importOperands, extensionSetName);
encodeInstructionInto(extendedSets, spirv::Opcode::OpExtInstImport,
importOperands);
}
// The first two operands are the result type <id> and result <id>. The set
// <id> and the opcode need to be insert after this.
if (operands.size() < 2) {
return op->emitError("extended instructions must have a result encoding");
}
SmallVector<uint32_t, 8> extInstOperands;
extInstOperands.reserve(operands.size() + 2);
extInstOperands.append(operands.begin(), std::next(operands.begin(), 2));
extInstOperands.push_back(setID);
extInstOperands.push_back(extensionOpcode);
extInstOperands.append(std::next(operands.begin(), 2), operands.end());
encodeInstructionInto(functionBody, spirv::Opcode::OpExtInst,
extInstOperands);
return success();
}
LogicalResult Serializer::processOperation(Operation *opInst) {
LLVM_DEBUG(llvm::dbgs() << "[op] '" << opInst->getName() << "'\n");
// First dispatch the ops that do not directly mirror an instruction from
// the SPIR-V spec.
return TypeSwitch<Operation *, LogicalResult>(opInst)
.Case([&](spirv::AddressOfOp op) { return processAddressOfOp(op); })
.Case([&](spirv::BranchOp op) { return processBranchOp(op); })
.Case([&](spirv::BranchConditionalOp op) {
return processBranchConditionalOp(op);
})
.Case([&](spirv::ConstantOp op) { return processConstantOp(op); })
.Case([&](spirv::FuncOp op) { return processFuncOp(op); })
.Case([&](spirv::GlobalVariableOp op) {
return processGlobalVariableOp(op);
})
.Case([&](spirv::LoopOp op) { return processLoopOp(op); })
.Case([&](spirv::ReferenceOfOp op) { return processReferenceOfOp(op); })
.Case([&](spirv::SelectionOp op) { return processSelectionOp(op); })
.Case([&](spirv::SpecConstantOp op) { return processSpecConstantOp(op); })
.Case([&](spirv::SpecConstantCompositeOp op) {
return processSpecConstantCompositeOp(op);
})
.Case([&](spirv::SpecConstantOperationOp op) {
return processSpecConstantOperationOp(op);
})
.Case([&](spirv::UndefOp op) { return processUndefOp(op); })
.Case([&](spirv::VariableOp op) { return processVariableOp(op); })
// Then handle all the ops that directly mirror SPIR-V instructions with
// auto-generated methods.
.Default(
[&](Operation *op) { return dispatchToAutogenSerialization(op); });
}
LogicalResult Serializer::processOpWithoutGrammarAttr(Operation *op,
StringRef extInstSet,
uint32_t opcode) {
SmallVector<uint32_t, 4> operands;
Location loc = op->getLoc();
uint32_t resultID = 0;
if (op->getNumResults() != 0) {
uint32_t resultTypeID = 0;
if (failed(processType(loc, op->getResult(0).getType(), resultTypeID)))
return failure();
operands.push_back(resultTypeID);
resultID = getNextID();
operands.push_back(resultID);
valueIDMap[op->getResult(0)] = resultID;
};
for (Value operand : op->getOperands())
operands.push_back(getValueID(operand));
if (failed(emitDebugLine(functionBody, loc)))
return failure();
if (extInstSet.empty()) {
encodeInstructionInto(functionBody, static_cast<spirv::Opcode>(opcode),
operands);
} else {
if (failed(encodeExtensionInstruction(op, extInstSet, opcode, operands)))
return failure();
}
if (op->getNumResults() != 0) {
for (auto attr : op->getAttrs()) {
if (failed(processDecoration(loc, resultID, attr)))
return failure();
}
}
return success();
}
LogicalResult Serializer::emitDecoration(uint32_t target,
spirv::Decoration decoration,
ArrayRef<uint32_t> params) {
uint32_t wordCount = 3 + params.size();
decorations.push_back(
spirv::getPrefixedOpcode(wordCount, spirv::Opcode::OpDecorate));
decorations.push_back(target);
decorations.push_back(static_cast<uint32_t>(decoration));
decorations.append(params.begin(), params.end());
return success();
}
LogicalResult Serializer::emitDebugLine(SmallVectorImpl<uint32_t> &binary,
Location loc) {
if (!options.emitDebugInfo)
return success();
if (lastProcessedWasMergeInst) {
lastProcessedWasMergeInst = false;
return success();
}
auto fileLoc = loc.dyn_cast<FileLineColLoc>();
if (fileLoc)
encodeInstructionInto(binary, spirv::Opcode::OpLine,
{fileID, fileLoc.getLine(), fileLoc.getColumn()});
return success();
}
} // namespace spirv
} // namespace mlir
| 36.780945 | 80 | 0.648394 | [
"vector"
] |
740d74fb47b32cf11a46224e78f5db59c60e88bf | 2,197 | cpp | C++ | test/unit/api/authentication_check_test.cpp | alexgunkel/shoppinglist-server | af9f96c34588f15b477a08e5a9d490d148dae4ce | [
"Apache-2.0"
] | null | null | null | test/unit/api/authentication_check_test.cpp | alexgunkel/shoppinglist-server | af9f96c34588f15b477a08e5a9d490d148dae4ce | [
"Apache-2.0"
] | null | null | null | test/unit/api/authentication_check_test.cpp | alexgunkel/shoppinglist-server | af9f96c34588f15b477a08e5a9d490d148dae4ce | [
"Apache-2.0"
] | null | null | null | #include "api/authentication_check.h"
#include <gtest/gtest.h>
#include <cpprest/asyncrt_utils.h>
TEST(AuthenticationRepositoryTest, testAuthentication) {
AuthenticationRepository repo{std::make_unique<HashingAlgorithm>()};
repo.addUser(User{"foo"}, Password{"bar"});
EXPECT_TRUE(repo.checkUser(User{"foo"}, Password{"bar"}));
EXPECT_FALSE(repo.checkUser(User{"foo"}, Password{"foo"}));
}
TEST(AuthenticationCheck, testCheck) {
auto repo = std::make_unique<AuthenticationRepository>(std::make_unique<HashingAlgorithm>());
repo->addUser(User{"foo"}, Password{"bar"});
AuthenticationCheck check{std::move(repo)};
std::vector<unsigned char > valid = {'f', 'o', 'o', ':', 'b', 'a', 'r'};
std::vector<unsigned char > inValid = {'b', 'a', 'r', ':', 'f', 'o', 'o'};
EXPECT_TRUE(check.check(Base64(utility::conversions::to_base64(valid))));
EXPECT_FALSE(check.check(Base64(utility::conversions::to_base64(inValid))));
}
TEST(AuthenticationRepository, testReadfile) {
auto file = std::tmpnam(nullptr);
std::ofstream filePtr;
filePtr.open(file);
filePtr << "foo:F27AB877EE002BAD7353436334E41AE847BE8B6F31F30CCF678BC7F1A4B9AD72\n"
<< "donald:B1E1ABA067B3AFC362AE553CB36E2DD9F7B50F0E62A21A18406B4E8C6EAD78C5\n" << std::endl;
AuthenticationRepository repository{std::make_unique<HashingAlgorithm>()};
repository.readFile(std::string(file));
filePtr.close();
EXPECT_TRUE(repository.checkUser(User{"foo"}, Password{"bar"}));
EXPECT_TRUE(repository.checkUser(User{"donald"}, Password{"duck"}));
EXPECT_FALSE(repository.checkUser(User{"foo"}, Password{"duck"}));
EXPECT_FALSE(repository.checkUser(User{"donald"}, Password{"bar"}));
}
TEST(AuthenticationRepository, testReadFileFailure) {
auto file = std::tmpnam(nullptr);
AuthenticationRepository repository{std::make_unique<HashingAlgorithm>()};
EXPECT_ANY_THROW(repository.readFile(std::string{file}));
}
TEST(HashingAlgorithmTest, testSha) {
HashingAlgorithm algorithm;
const auto result = algorithm.hashPassword(Password{"foo"});
EXPECT_EQ("282B8395083D4E56DEC421843252560A7BC01376DFB7C1FF16C61016CDD259E3", result.get());
}
| 37.87931 | 100 | 0.720983 | [
"vector"
] |
740d7ae86b30b83bc1f280338a0cf3b3dc756edd | 2,731 | cc | C++ | mindspore/lite/src/delegate/npu/op/argmax_npu.cc | Vincent34/mindspore | a39a60878a46e7e9cb02db788c0bca478f2fa6e5 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/delegate/npu/op/argmax_npu.cc | Vincent34/mindspore | a39a60878a46e7e9cb02db788c0bca478f2fa6e5 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/delegate/npu/op/argmax_npu.cc | Vincent34/mindspore | a39a60878a46e7e9cb02db788c0bca478f2fa6e5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 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/delegate/npu/op/argmax_npu.h"
#include <memory>
#include "src/delegate/npu/npu_converter_utils.h"
namespace mindspore {
int ArgmaxNPUOp::Init(const schema::Primitive *primitive, const std::vector<tensor::MSTensor *> &in_tensors,
const std::vector<tensor::MSTensor *> &out_tensors) {
argmax_ = new (std::nothrow) hiai::op::ArgMaxExt2(name_);
if (argmax_ == nullptr) {
MS_LOG(ERROR) << "New argmax npu operator for " << name_ << " failed.";
return RET_ERROR;
}
auto argmax_prim = primitive->value_as_ArgMaxFusion();
if (argmax_prim == nullptr) {
MS_LOG(ERROR) << "Get null primitive value for op ." << name_;
return RET_ERROR;
}
auto axis_const_ = new (std::nothrow) hiai::op::Const(name_ + "_axis");
if (axis_const_ == nullptr) {
MS_LOG(ERROR) << "New weight const failed.";
return RET_ERROR;
}
std::vector<int> axis = {static_cast<int>(argmax_prim->axis())};
ge::TensorDesc tensor_desc(ge::Shape({1}), ge::FORMAT_NCHW, ge::DT_INT32);
std::shared_ptr<ge::Tensor> ge_tensor =
std::make_shared<ge::Tensor>(tensor_desc, reinterpret_cast<const uint8_t *>(axis.data()), sizeof(int));
if (ge_tensor == nullptr) {
MS_LOG(ERROR) << "new ge_tensor failed.";
return RET_ERROR;
}
axis_const_->set_attr_value(ge_tensor);
argmax_->set_input_axis(*axis_const_);
argmax_->set_attr_keep_dims(argmax_prim->keep_dims());
argmax_->set_attr_outmaxval(argmax_prim->out_max_value());
argmax_->set_attr_topk(argmax_prim->top_k());
return RET_OK;
}
int ArgmaxNPUOp::SetNPUInputs(const std::vector<tensor::MSTensor *> &in_tensors,
const std::vector<tensor::MSTensor *> &out_tensors,
const std::vector<ge::Operator *> &npu_inputs) {
argmax_->set_input_x(*npu_inputs[0]);
return RET_OK;
}
ge::Operator *ArgmaxNPUOp::GetNPUOp() { return argmax_; }
ArgmaxNPUOp::~ArgmaxNPUOp() {
if (argmax_ != nullptr) {
delete argmax_;
argmax_ = nullptr;
}
if (axis_const_ != nullptr) {
delete axis_const_;
axis_const_ = nullptr;
}
}
} // namespace mindspore
| 35.467532 | 108 | 0.685097 | [
"shape",
"vector"
] |
74162d2efe74e3db0cbcc5d14197b6a4459de219 | 92,131 | cpp | C++ | source/slang/slang-compiler.cpp | lucy96chen/slang | fc84455d0d1cb6b9396ba869a17d6f8d4b65ecc6 | [
"MIT"
] | null | null | null | source/slang/slang-compiler.cpp | lucy96chen/slang | fc84455d0d1cb6b9396ba869a17d6f8d4b65ecc6 | [
"MIT"
] | null | null | null | source/slang/slang-compiler.cpp | lucy96chen/slang | fc84455d0d1cb6b9396ba869a17d6f8d4b65ecc6 | [
"MIT"
] | null | null | null | // Compiler.cpp : Defines the entry point for the console application.
//
#include "../core/slang-basic.h"
#include "../core/slang-platform.h"
#include "../core/slang-io.h"
#include "../core/slang-string-util.h"
#include "../core/slang-hex-dump-util.h"
#include "../core/slang-riff.h"
#include "../core/slang-type-text-util.h"
#include "../core/slang-type-convert-util.h"
#include "slang-check.h"
#include "slang-compiler.h"
#include "../compiler-core/slang-lexer.h"
#include "slang-lower-to-ir.h"
#include "slang-mangle.h"
#include "slang-parameter-binding.h"
#include "slang-parser.h"
#include "slang-preprocessor.h"
#include "slang-type-layout.h"
#include "slang-glsl-extension-tracker.h"
#include "slang-emit-cuda.h"
#include "slang-serialize-container.h"
//
// Includes to allow us to control console
// output when writing assembly dumps.
#include <fcntl.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX
#endif
#ifdef _MSC_VER
#pragma warning(disable: 4996)
#endif
namespace Slang
{
// !!!!!!!!!!!!!!!!!!!!!! free functions for DiagnosicSink !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
bool isHeterogeneousTarget(CodeGenTarget target)
{
switch (target)
{
case CodeGenTarget::HostCPPSource:
case CodeGenTarget::HostExecutable:
return true;
default:
return false;
}
}
void printDiagnosticArg(StringBuilder& sb, CodeGenTarget val)
{
switch (val)
{
default:
sb << "<unknown>";
break;
#define CASE(TAG, STR) case CodeGenTarget::TAG: sb << STR; break
CASE(GLSL, "glsl");
CASE(HLSL, "hlsl");
CASE(SPIRV, "spirv");
CASE(SPIRVAssembly, "spriv-assembly");
CASE(DXBytecode, "dxbc");
CASE(DXBytecodeAssembly, "dxbc-assembly");
CASE(DXIL, "dxil");
CASE(DXILAssembly, "dxil-assembly");
#undef CASE
}
}
void printDiagnosticArg(StringBuilder& sb, PassThroughMode val)
{
sb << TypeTextUtil::getPassThroughName(SlangPassThrough(val));
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!! CompileResult !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
SlangResult CompileResult::getSharedLibrary(ComPtr<ISlangSharedLibrary>& outSharedLibrary)
{
if (downstreamResult)
{
return downstreamResult->getHostCallableSharedLibrary(outSharedLibrary);
}
return SLANG_FAIL;
}
SlangResult CompileResult::getBlob(ComPtr<ISlangBlob>& outBlob) const
{
if(!blob)
{
switch(format)
{
default:
case ResultFormat::None:
{
// If no blob is returned, it's an error
return SLANG_FAIL;
}
case ResultFormat::Text:
{
blob = StringUtil::createStringBlob(outputString);
break;
}
case ResultFormat::Binary:
{
if (downstreamResult)
{
// TODO(JS):
// This seems a little questionable. As it stands downstreamResult, if it doesn't have a blob
// can try and read a file. How this currently works is that every getBlob will potentially try to read that file.
// Setting result to None would stop this, but is that reasonable as the state.
// Perhaps downstreamResult should hold some state that the read failed.
// For now we don't worry though.
SLANG_RETURN_ON_FAIL(downstreamResult->getBinary(blob));
}
break;
}
}
}
outBlob = blob;
return SLANG_OK;
}
SlangResult CompileResult::isParameterLocationUsed(SlangParameterCategory category, UInt spaceIndex, UInt registerIndex, bool& outUsed)
{
if (!postEmitMetadata)
return SLANG_E_NOT_AVAILABLE;
if (!ShaderBindingRange::isUsageTracked((slang::ParameterCategory)category))
return SLANG_E_NOT_AVAILABLE;
// TODO: optimize this with a binary search through a sorted list
for (const auto& range : postEmitMetadata->usedBindings)
{
if (range.containsBinding((slang::ParameterCategory)category, spaceIndex, registerIndex))
{
outUsed = true;
return SLANG_OK;
}
}
outUsed = false;
return SLANG_OK;
}
//
// FrontEndEntryPointRequest
//
FrontEndEntryPointRequest::FrontEndEntryPointRequest(
FrontEndCompileRequest* compileRequest,
int translationUnitIndex,
Name* name,
Profile profile)
: m_compileRequest(compileRequest)
, m_translationUnitIndex(translationUnitIndex)
, m_name(name)
, m_profile(profile)
{}
TranslationUnitRequest* FrontEndEntryPointRequest::getTranslationUnit()
{
return getCompileRequest()->translationUnits[m_translationUnitIndex];
}
//
// EntryPoint
//
ISlangUnknown* EntryPoint::getInterface(const Guid& guid)
{
if(guid == slang::IEntryPoint::getTypeGuid())
return static_cast<slang::IEntryPoint*>(this);
return Super::getInterface(guid);
}
RefPtr<EntryPoint> EntryPoint::create(
Linkage* linkage,
DeclRef<FuncDecl> funcDeclRef,
Profile profile)
{
RefPtr<EntryPoint> entryPoint = new EntryPoint(
linkage,
funcDeclRef.getName(),
profile,
funcDeclRef);
entryPoint->m_mangledName = getMangledName(linkage->getASTBuilder(), funcDeclRef);
return entryPoint;
}
RefPtr<EntryPoint> EntryPoint::createDummyForPassThrough(
Linkage* linkage,
Name* name,
Profile profile)
{
RefPtr<EntryPoint> entryPoint = new EntryPoint(
linkage,
name,
profile,
DeclRef<FuncDecl>());
return entryPoint;
}
RefPtr<EntryPoint> EntryPoint::createDummyForDeserialize(
Linkage* linkage,
Name* name,
Profile profile,
String mangledName)
{
RefPtr<EntryPoint> entryPoint = new EntryPoint(
linkage,
name,
profile,
DeclRef<FuncDecl>());
entryPoint->m_mangledName = mangledName;
return entryPoint;
}
EntryPoint::EntryPoint(
Linkage* linkage,
Name* name,
Profile profile,
DeclRef<FuncDecl> funcDeclRef)
: ComponentType(linkage)
, m_name(name)
, m_profile(profile)
, m_funcDeclRef(funcDeclRef)
{
// Collect any specialization parameters used by the entry point
//
_collectShaderParams();
}
Module* EntryPoint::getModule()
{
return Slang::getModule(getFuncDecl());
}
Index EntryPoint::getSpecializationParamCount()
{
return m_genericSpecializationParams.getCount() + m_existentialSpecializationParams.getCount();
}
SpecializationParam const& EntryPoint::getSpecializationParam(Index index)
{
auto genericParamCount = m_genericSpecializationParams.getCount();
if(index < genericParamCount)
{
return m_genericSpecializationParams[index];
}
else
{
return m_existentialSpecializationParams[index - genericParamCount];
}
}
Index EntryPoint::getRequirementCount()
{
// The only requirement of an entry point is the module that contains it.
//
// TODO: We will eventually want to support the case of an entry
// point nested in a `struct` type, in which case there should be
// a single requirement representing that outer type (so that multiple
// entry points nested under the same type can share the storage
// for parameters at that scope).
// Note: the defensive coding is here because the
// "dummy" entry points we create for pass-through
// compilation will not have an associated module.
//
if( auto module = getModule() )
{
return 1;
}
return 0;
}
RefPtr<ComponentType> EntryPoint::getRequirement(Index index)
{
SLANG_UNUSED(index);
SLANG_ASSERT(index == 0);
SLANG_ASSERT(getModule());
return getModule();
}
String EntryPoint::getEntryPointMangledName(Index index)
{
SLANG_UNUSED(index);
SLANG_ASSERT(index == 0);
return m_mangledName;
}
String EntryPoint::getEntryPointNameOverride(Index index)
{
SLANG_UNUSED(index);
SLANG_ASSERT(index == 0);
return m_name ? m_name->text : "";
}
void EntryPoint::acceptVisitor(ComponentTypeVisitor* visitor, SpecializationInfo* specializationInfo)
{
visitor->visitEntryPoint(this, as<EntryPointSpecializationInfo>(specializationInfo));
}
List<Module*> const& EntryPoint::getModuleDependencies()
{
if(auto module = getModule())
return module->getModuleDependencies();
static List<Module*> empty;
return empty;
}
List<String> const& EntryPoint::getFilePathDependencies()
{
if(auto module = getModule())
return getModule()->getFilePathDependencies();
static List<String> empty;
return empty;
}
TypeConformance::TypeConformance(
Linkage* linkage,
SubtypeWitness* witness,
Int confomrmanceIdOverride,
DiagnosticSink* sink)
: ComponentType(linkage)
, m_subtypeWitness(witness)
, m_conformanceIdOverride(confomrmanceIdOverride)
{
addDepedencyFromWitness(witness);
m_irModule = generateIRForTypeConformance(this, m_conformanceIdOverride, sink);
}
void TypeConformance::addDepedencyFromWitness(SubtypeWitness* witness)
{
if (auto declaredWitness = as<DeclaredSubtypeWitness>(witness))
{
auto declModule = getModule(declaredWitness->declRef.getDecl());
m_moduleDependency.addDependency(declModule);
m_pathDependency.addDependency(declModule);
if (m_requirementSet.Add(declModule))
{
m_requirements.add(declModule);
}
// TODO: handle the specialization arguments in declaredWitness->declRef.substitutions.
}
else if (auto transitiveWitness = as<TransitiveSubtypeWitness>(witness))
{
addDepedencyFromWitness(transitiveWitness->midToSup);
addDepedencyFromWitness(transitiveWitness->subToMid);
}
else if (auto conjunctionWitness = as<ConjunctionSubtypeWitness>(witness))
{
auto left = as<SubtypeWitness>(conjunctionWitness->leftWitness);
if (left)
addDepedencyFromWitness(left);
auto right = as<SubtypeWitness>(conjunctionWitness->rightWitness);
if (right)
addDepedencyFromWitness(right);
}
}
ISlangUnknown* TypeConformance::getInterface(const Guid& guid)
{
if (guid == slang::ITypeConformance::getTypeGuid())
return static_cast<slang::ITypeConformance*>(this);
return Super::getInterface(guid);
}
List<Module*> const& TypeConformance::getModuleDependencies()
{
return m_moduleDependency.getModuleList();
}
List<String> const& TypeConformance::getFilePathDependencies()
{
return m_pathDependency.getFilePathList();
}
Index TypeConformance::getRequirementCount() { return m_requirements.getCount(); }
RefPtr<ComponentType> TypeConformance::getRequirement(Index index)
{
return m_requirements[index];
}
void TypeConformance::acceptVisitor(
ComponentTypeVisitor* visitor,
ComponentType::SpecializationInfo* specializationInfo)
{
SLANG_UNUSED(specializationInfo);
visitor->visitTypeConformance(this);
}
RefPtr<ComponentType::SpecializationInfo> TypeConformance::_validateSpecializationArgsImpl(
SpecializationArg const* args,
Index argCount,
DiagnosticSink* sink)
{
SLANG_UNUSED(args);
SLANG_UNUSED(argCount);
SLANG_UNUSED(sink);
return nullptr;
}
//
Profile Profile::lookUp(UnownedStringSlice const& name)
{
#define PROFILE(TAG, NAME, STAGE, VERSION) if(name == UnownedTerminatedStringSlice(#NAME)) return Profile::TAG;
#define PROFILE_ALIAS(TAG, DEF, NAME) if(name == UnownedTerminatedStringSlice(#NAME)) return Profile::TAG;
#include "slang-profile-defs.h"
return Profile::Unknown;
}
Profile Profile::lookUp(char const* name)
{
return lookUp(UnownedTerminatedStringSlice(name));
}
char const* Profile::getName()
{
switch( raw )
{
default:
return "unknown";
#define PROFILE(TAG, NAME, STAGE, VERSION) case Profile::TAG: return #NAME;
#define PROFILE_ALIAS(TAG, DEF, NAME) /* empty */
#include "slang-profile-defs.h"
}
}
static const struct
{
char const* name;
Stage stage;
} kStages[] =
{
#define PROFILE_STAGE(ID, NAME, ENUM) \
{ #NAME, Stage::ID },
#define PROFILE_STAGE_ALIAS(ID, NAME, VAL) \
{ #NAME, Stage::ID },
#include "slang-profile-defs.h"
};
Stage findStageByName(String const& name)
{
for(auto entry : kStages)
{
if(name == entry.name)
{
return entry.stage;
}
}
return Stage::Unknown;
}
UnownedStringSlice getStageText(Stage stage)
{
for (auto entry : kStages)
{
if (stage == entry.stage)
{
return UnownedStringSlice(entry.name);
}
}
return UnownedStringSlice();
}
SlangResult checkExternalCompilerSupport(Session* session, PassThroughMode passThrough)
{
// Check if the type is supported on this compile
if (passThrough == PassThroughMode::None)
{
// If no pass through -> that will always work!
return SLANG_OK;
}
return session->getOrLoadDownstreamCompiler(passThrough, nullptr) ? SLANG_OK: SLANG_E_NOT_FOUND;
}
SourceLanguage getDefaultSourceLanguageForDownstreamCompiler(PassThroughMode compiler)
{
switch (compiler)
{
case PassThroughMode::None:
{
return SourceLanguage::Unknown;
}
case PassThroughMode::Fxc:
case PassThroughMode::Dxc:
{
return SourceLanguage::HLSL;
}
case PassThroughMode::Glslang:
{
return SourceLanguage::GLSL;
}
case PassThroughMode::LLVM:
case PassThroughMode::Clang:
case PassThroughMode::VisualStudio:
case PassThroughMode::Gcc:
case PassThroughMode::GenericCCpp:
{
// These could ingest C, but we only have this function to work out a
// 'default' language to ingest.
return SourceLanguage::CPP;
}
case PassThroughMode::NVRTC:
{
return SourceLanguage::CUDA;
}
default: break;
}
SLANG_ASSERT(!"Unknown compiler");
return SourceLanguage::Unknown;
}
PassThroughMode getDownstreamCompilerRequiredForTarget(CodeGenTarget target)
{
switch (target)
{
// Don't *require* a downstream compiler for source output
case CodeGenTarget::GLSL:
case CodeGenTarget::HLSL:
case CodeGenTarget::CUDASource:
case CodeGenTarget::CPPSource:
case CodeGenTarget::HostCPPSource:
case CodeGenTarget::CSource:
{
return PassThroughMode::None;
}
case CodeGenTarget::None:
{
return PassThroughMode::None;
}
case CodeGenTarget::SPIRVAssembly:
case CodeGenTarget::SPIRV:
{
return PassThroughMode::Glslang;
}
case CodeGenTarget::DXBytecode:
case CodeGenTarget::DXBytecodeAssembly:
{
return PassThroughMode::Fxc;
}
case CodeGenTarget::DXIL:
case CodeGenTarget::DXILAssembly:
{
return PassThroughMode::Dxc;
}
case CodeGenTarget::GLSL_Vulkan:
case CodeGenTarget::GLSL_Vulkan_OneDesc:
{
return PassThroughMode::Glslang;
}
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary:
case CodeGenTarget::HostExecutable:
{
// We need some C/C++ compiler
return PassThroughMode::GenericCCpp;
}
case CodeGenTarget::PTX:
{
return PassThroughMode::NVRTC;
}
default: break;
}
SLANG_ASSERT(!"Unhandled target");
return PassThroughMode::None;
}
EndToEndCompileRequest* CodeGenContext::isPassThroughEnabled()
{
auto endToEndReq = isEndToEndCompile();
// If there isn't an end-to-end compile going on,
// there can be no pass-through.
//
if (!endToEndReq)
return nullptr;
// And if pass-through isn't set on that end-to-end compile,
// then we clearly areb't doing a pass-through compile.
//
if(endToEndReq->m_passThrough == PassThroughMode::None)
return nullptr;
// If we have confirmed that pass-through compilation is going on,
// we return the end-to-end request, because it has all the
// relevant state that we need to implement pass-through mode.
//
return endToEndReq;
}
/// If there is a pass-through compile going on, find the translation unit for the given entry point.
/// Assumes isPassThroughEnabled has already been called
TranslationUnitRequest* getPassThroughTranslationUnit(
EndToEndCompileRequest* endToEndReq,
Int entryPointIndex)
{
SLANG_ASSERT(endToEndReq);
SLANG_ASSERT(endToEndReq->m_passThrough != PassThroughMode::None);
auto frontEndReq = endToEndReq->getFrontEndReq();
auto entryPointReq = frontEndReq->getEntryPointReq(entryPointIndex);
auto translationUnit = entryPointReq->getTranslationUnit();
return translationUnit;
}
TranslationUnitRequest* CodeGenContext::findPassThroughTranslationUnit(
Int entryPointIndex)
{
if (auto endToEndReq = isPassThroughEnabled())
return getPassThroughTranslationUnit(endToEndReq, entryPointIndex);
return nullptr;
}
static void _appendCodeWithPath(const UnownedStringSlice& filePath, const UnownedStringSlice& fileContent, StringBuilder& outCodeBuilder)
{
outCodeBuilder << "#line 1 \"";
auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
handler->appendEscaped(filePath, outCodeBuilder);
outCodeBuilder << "\"\n";
outCodeBuilder << fileContent << "\n";
}
void trackGLSLTargetCaps(
GLSLExtensionTracker* extensionTracker,
CapabilitySet const& caps)
{
for( auto atom : caps.getExpandedAtoms() )
{
switch( atom )
{
default:
break;
case CapabilityAtom::SPIRV_1_0: extensionTracker->requireSPIRVVersion(SemanticVersion(1, 0)); break;
case CapabilityAtom::SPIRV_1_1: extensionTracker->requireSPIRVVersion(SemanticVersion(1, 1)); break;
case CapabilityAtom::SPIRV_1_2: extensionTracker->requireSPIRVVersion(SemanticVersion(1, 2)); break;
case CapabilityAtom::SPIRV_1_3: extensionTracker->requireSPIRVVersion(SemanticVersion(1, 3)); break;
case CapabilityAtom::SPIRV_1_4: extensionTracker->requireSPIRVVersion(SemanticVersion(1, 4)); break;
case CapabilityAtom::SPIRV_1_5: extensionTracker->requireSPIRVVersion(SemanticVersion(1, 5)); break;
}
}
}
SlangResult CodeGenContext::emitEntryPointsSource(
String& outSource,
RefPtr<PostEmitMetadata>& outMetadata)
{
outSource = String();
if(auto endToEndReq = isPassThroughEnabled())
{
for (auto entryPointIndex : getEntryPointIndices())
{
auto translationUnit = getPassThroughTranslationUnit(endToEndReq, entryPointIndex);
SLANG_ASSERT(translationUnit);
// Generate a string that includes the content of
// the source file(s), along with a line directive
// to ensure that we get reasonable messages
// from the downstream compiler when in pass-through
// mode.
StringBuilder codeBuilder;
if (getTargetFormat() == CodeGenTarget::GLSL)
{
// Special case GLSL
int translationUnitCounter = 0;
for (auto sourceFile : translationUnit->getSourceFiles())
{
int translationUnitIndex = translationUnitCounter++;
// We want to output `#line` directives, but we need
// to skip this for the first file, since otherwise
// some GLSL implementations will get tripped up by
// not having the `#version` directive be the first
// thing in the file.
if (translationUnitIndex != 0)
{
codeBuilder << "#line 1 " << translationUnitIndex << "\n";
}
codeBuilder << sourceFile->getContent() << "\n";
}
}
else
{
for (auto sourceFile : translationUnit->getSourceFiles())
{
_appendCodeWithPath(sourceFile->getPathInfo().foundPath.getUnownedSlice(), sourceFile->getContent(), codeBuilder);
}
}
outSource = codeBuilder.ProduceString();
}
return SLANG_OK;
}
else
{
return emitEntryPointsSourceFromIR(
outSource, outMetadata);
}
}
String GetHLSLProfileName(Profile profile)
{
switch( profile.getFamily() )
{
case ProfileFamily::DX:
// Profile version is a DX one, so stick with it.
break;
default:
// Profile is a non-DX profile family, so we need to try
// to clobber it with something to get a default.
//
// TODO: This is a huge hack...
profile.setVersion(ProfileVersion::DX_5_0);
break;
}
char const* stagePrefix = nullptr;
switch( profile.getStage() )
{
// Note: All of the raytracing-related stages require
// compiling for a `lib_*` profile, even when only a
// single entry point is present.
//
// We also go ahead and use this target in any case
// where we don't know the actual stage to compiel for,
// as a fallback option.
//
// TODO: We also want to use this option when compiling
// multiple entry points to a DXIL library.
//
default:
stagePrefix = "lib";
break;
// The traditional rasterization pipeline and compute
// shaders all have custom profile names that identify
// both the stage and shader model, which need to be
// used when compiling a single entry point.
//
#define CASE(NAME, PREFIX) case Stage::NAME: stagePrefix = #PREFIX; break
CASE(Vertex, vs);
CASE(Hull, hs);
CASE(Domain, ds);
CASE(Geometry, gs);
CASE(Fragment, ps);
CASE(Compute, cs);
CASE(Amplification, as);
CASE(Mesh, ms);
#undef CASE
}
char const* versionSuffix = nullptr;
switch(profile.getVersion())
{
#define CASE(TAG, SUFFIX) case ProfileVersion::TAG: versionSuffix = #SUFFIX; break
CASE(DX_4_0, _4_0);
CASE(DX_4_0_Level_9_0, _4_0_level_9_0);
CASE(DX_4_0_Level_9_1, _4_0_level_9_1);
CASE(DX_4_0_Level_9_3, _4_0_level_9_3);
CASE(DX_4_1, _4_1);
CASE(DX_5_0, _5_0);
CASE(DX_5_1, _5_1);
CASE(DX_6_0, _6_0);
CASE(DX_6_1, _6_1);
CASE(DX_6_2, _6_2);
CASE(DX_6_3, _6_3);
CASE(DX_6_4, _6_4);
CASE(DX_6_5, _6_5);
CASE(DX_6_6, _6_6);
#undef CASE
default:
return "unknown";
}
String result;
result.append(stagePrefix);
result.append(versionSuffix);
return result;
}
void reportExternalCompileError(const char* compilerName, Severity severity, SlangResult res, const UnownedStringSlice& diagnostic, DiagnosticSink* sink)
{
StringBuilder builder;
if (compilerName)
{
builder << compilerName << ": ";
}
if (SLANG_FAILED(res) && res != SLANG_FAIL)
{
{
char tmp[17];
sprintf_s(tmp, SLANG_COUNT_OF(tmp), "0x%08x", uint32_t(res));
builder << "Result(" << tmp << ") ";
}
PlatformUtil::appendResult(res, builder);
}
if (diagnostic.getLength() > 0)
{
builder.Append(diagnostic);
if (!diagnostic.endsWith("\n"))
{
builder.Append("\n");
}
}
sink->diagnoseRaw(severity, builder.getUnownedSlice());
}
void reportExternalCompileError(const char* compilerName, SlangResult res, const UnownedStringSlice& diagnostic, DiagnosticSink* sink)
{
// TODO(tfoley): need a better policy for how we translate diagnostics
// back into the Slang world (although we should always try to generate
// HLSL that doesn't produce any diagnostics...)
reportExternalCompileError(compilerName, SLANG_FAILED(res) ? Severity::Error : Severity::Warning, res, diagnostic, sink);
}
static String _getDisplayPath(DiagnosticSink* sink, SourceFile* sourceFile)
{
if (sink->isFlagSet(DiagnosticSink::Flag::VerbosePath))
{
return sourceFile->calcVerbosePath();
}
else
{
return sourceFile->getPathInfo().foundPath;
}
}
String CodeGenContext::calcSourcePathForEntryPoints()
{
String failureMode = "slang-generated";
if (getEntryPointCount() != 1)
return failureMode;
auto entryPointIndex = getSingleEntryPointIndex();
auto translationUnitRequest = findPassThroughTranslationUnit(entryPointIndex);
if (!translationUnitRequest)
return failureMode;
const auto& sourceFiles = translationUnitRequest->getSourceFiles();
auto sink = getSink();
const Index numSourceFiles = sourceFiles.getCount();
switch (numSourceFiles)
{
case 0: return "unknown";
case 1: return _getDisplayPath(sink, sourceFiles[0]);
default:
{
StringBuilder builder;
builder << _getDisplayPath(sink, sourceFiles[0]);
for (int i = 1; i < numSourceFiles; ++i)
{
builder << ";" << _getDisplayPath(sink, sourceFiles[i]);
}
return builder;
}
}
}
// Helper function for cases where we can assume a single entry point
Int assertSingleEntryPoint(List<Int> const& entryPointIndices) {
SLANG_ASSERT(entryPointIndices.getCount() == 1);
return *entryPointIndices.begin();
}
// True if it's best to use 'emitted' source for complication. For a downstream compiler
// that is not file based, this is always ok.
///
/// If the downstream compiler is file system based, we may want to just use the file that was passed to be compiled.
/// That the downstream compiler can determine if it will then save the file or not based on if it's a match -
/// and generally there will not be a match with emitted source.
///
/// This test is only used for pass through mode.
static bool _useEmittedSource(DownstreamCompiler* compiler, TranslationUnitRequest* translationUnit)
{
// We only bother if it's a file based compiler.
if (compiler->isFileBased())
{
// It can only have *one* source file as otherwise we have to combine to make a new source file anyway
const auto& sourceFiles = translationUnit->getSourceFiles();
// The *assumption* here is that if it's file based that assuming it can find the file with the same contents
// it can compile directly without having to save off as a file
if (sourceFiles.getCount() == 1)
{
const SourceFile* sourceFile = sourceFiles[0];
// We need the path to be found and set
//
// NOTE! That the downstream compiler can determine if the path and contents match such that it can be used
// without writing file
const PathInfo& pathInfo = sourceFile->getPathInfo();
if ((pathInfo.type == PathInfo::Type::FoundPath || pathInfo.type == PathInfo::Type::Normal) && pathInfo.foundPath.getLength())
{
return false;
}
}
}
return true;
}
static Severity _getDiagnosticSeverity(DownstreamDiagnostic::Severity severity)
{
typedef DownstreamDiagnostic::Severity DownstreamSeverity;
switch (severity)
{
case DownstreamSeverity::Warning: return Severity::Warning;
case DownstreamSeverity::Info: return Severity::Note;
default: return Severity::Error;
}
}
static RefPtr<ExtensionTracker> _newExtensionTracker(CodeGenTarget target)
{
switch (target)
{
case CodeGenTarget::PTX:
case CodeGenTarget::CUDASource:
{
return new CUDAExtensionTracker;
}
case CodeGenTarget::SPIRV:
case CodeGenTarget::GLSL:
{
return new GLSLExtensionTracker;
}
default: return nullptr;
}
}
static CodeGenTarget _getDefaultSourceForTarget(CodeGenTarget target)
{
switch (target)
{
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary:
return CodeGenTarget::CPPSource;
case CodeGenTarget::HostExecutable:
return CodeGenTarget::HostCPPSource;
case CodeGenTarget::PTX: return CodeGenTarget::CUDASource;
case CodeGenTarget::DXBytecode: return CodeGenTarget::HLSL;
case CodeGenTarget::DXIL: return CodeGenTarget::HLSL;
case CodeGenTarget::SPIRV: return CodeGenTarget::GLSL;
default: break;
}
return CodeGenTarget::Unknown;
}
static bool _isCPUHostTarget(CodeGenTarget target)
{
switch (target)
{
case CodeGenTarget::HostCPPSource:
case CodeGenTarget::HostExecutable:
return true;
default:
return false;
}
}
SlangResult CodeGenContext::emitWithDownstreamForEntryPoints(
RefPtr<DownstreamCompileResult>& outResult,
RefPtr<PostEmitMetadata>& outMetadata)
{
outResult.setNull();
auto sink = getSink();
auto session = getSession();
CodeGenTarget sourceTarget = CodeGenTarget::None;
SourceLanguage sourceLanguage = SourceLanguage::Unknown;
auto target = getTargetFormat();
RefPtr<ExtensionTracker> extensionTracker = _newExtensionTracker(target);
PassThroughMode compilerType;
if (auto endToEndReq = isPassThroughEnabled())
{
compilerType = endToEndReq->m_passThrough;
}
else
{
// If we are not in pass through, lookup the default compiler for the emitted source type
// Get the default source codegen type for a given target
sourceTarget = _getDefaultSourceForTarget(target);
compilerType = (PassThroughMode)session->getDownstreamCompilerForTransition((SlangCompileTarget)sourceTarget, (SlangCompileTarget)target);
// We should have a downstream compiler set at this point
if (compilerType == PassThroughMode::None)
{
auto sourceName = TypeTextUtil::getCompileTargetName(SlangCompileTarget(sourceTarget));
auto targetName = TypeTextUtil::getCompileTargetName(SlangCompileTarget(target));
sink->diagnose(SourceLoc(), Diagnostics::compilerNotDefinedForTransition, sourceName, targetName);
return SLANG_FAIL;
}
}
SLANG_ASSERT(compilerType != PassThroughMode::None);
// Get the required downstream compiler
DownstreamCompiler* compiler = session->getOrLoadDownstreamCompiler(compilerType, sink);
if (!compiler)
{
auto compilerName = TypeTextUtil::getPassThroughAsHumanText((SlangPassThrough)compilerType);
sink->diagnose(SourceLoc(), Diagnostics::passThroughCompilerNotFound, compilerName);
return SLANG_FAIL;
}
Dictionary<String, String> preprocessorDefinitions;
List<String> includePaths;
typedef DownstreamCompiler::CompileOptions CompileOptions;
CompileOptions options;
// Set compiler specific args
{
auto linkage = getLinkage();
auto name = TypeTextUtil::getPassThroughName((SlangPassThrough)compilerType);
const Index nameIndex = linkage->m_downstreamArgs.findName(name);
if (nameIndex >= 0)
{
auto& args = linkage->m_downstreamArgs.getArgsAt(nameIndex);
for (const auto& arg : args.m_args)
{
options.compilerSpecificArguments.add(arg.value);
}
}
}
/* This is more convoluted than the other scenarios, because when we invoke C/C++ compiler we would ideally like
to use the original file. We want to do this because we want includes relative to the source file to work, and
for that to work most easily we want to use the original file, if there is one */
if (auto endToEndReq = isPassThroughEnabled())
{
// If we are pass through, we may need to set extension tracker state.
if (GLSLExtensionTracker* glslTracker = as<GLSLExtensionTracker>(extensionTracker))
{
trackGLSLTargetCaps(glslTracker, getTargetCaps());
}
auto translationUnit = getPassThroughTranslationUnit(endToEndReq, getSingleEntryPointIndex());
// We are just passing thru, so it's whatever it originally was
sourceLanguage = translationUnit->sourceLanguage;
// TODO(JS): This seems like a bit of a hack
// That if a pass-through is being performed and the source language is Slang
// no downstream compiler knows how to deal with that, so probably means 'HLSL'
sourceLanguage = (sourceLanguage == SourceLanguage::Slang) ? SourceLanguage::HLSL : sourceLanguage;
sourceTarget = CodeGenTarget(TypeConvertUtil::getCompileTargetFromSourceLanguage((SlangSourceLanguage)sourceLanguage));
// If it's pass through we accumulate the preprocessor definitions.
for (auto& define : translationUnit->compileRequest->preprocessorDefinitions)
{
preprocessorDefinitions.Add(define.Key, define.Value);
}
for (auto& define : translationUnit->preprocessorDefinitions)
{
preprocessorDefinitions.Add(define.Key, define.Value);
}
{
auto linkage = getLinkage();
for (auto& define : linkage->preprocessorDefinitions)
{
preprocessorDefinitions.Add(define.Key, define.Value);
}
}
{
/* TODO(JS): Not totally clear what options should be set here. If we are using the pass through - then using say the defines/includes
all makes total sense. If we are generating C++ code from slang, then should we really be using these values -> aren't they what is
being set for the *slang* source, not for the C++ generated code. That being the case it implies that there needs to be a mechanism
(if there isn't already) to specify such information on a particular pass/pass through etc.
On invoking DXC for example include paths do not appear to be set at all (even with pass-through).
*/
auto linkage = getLinkage();
// Add all the search paths
const auto searchDirectories = linkage->getSearchDirectories();
const SearchDirectoryList* searchList = &searchDirectories;
while (searchList)
{
for (const auto& searchDirectory : searchList->searchDirectories)
{
includePaths.add(searchDirectory.path);
}
searchList = searchList->parent;
}
}
// If emitted source is required, emit and set the path
if (_useEmittedSource(compiler, translationUnit))
{
// If it's not file based we can set an appropriate path name, and it doesn't matter if it doesn't
// exist on the file system
options.sourceContentsPath = calcSourcePathForEntryPoints();
CodeGenContext sourceCodeGenContext(this, sourceTarget, extensionTracker);
SLANG_RETURN_ON_FAIL(sourceCodeGenContext.emitEntryPointsSource(options.sourceContents, outMetadata));
}
else
{
// Special case if we have a single file, so that we pass the path, and the contents as is.
const auto& sourceFiles = translationUnit->getSourceFiles();
SLANG_ASSERT(sourceFiles.getCount() == 1);
const SourceFile* sourceFile = sourceFiles[0];
options.sourceContentsPath = sourceFile->getPathInfo().foundPath;
options.sourceContents = sourceFile->getContent();
}
}
else
{
CodeGenContext sourceCodeGenContext(this, sourceTarget, extensionTracker);
SLANG_RETURN_ON_FAIL(sourceCodeGenContext.emitEntryPointsSource(options.sourceContents, outMetadata));
sourceCodeGenContext.maybeDumpIntermediate(options.sourceContents.getBuffer());
sourceLanguage = (SourceLanguage)TypeConvertUtil::getSourceLanguageFromTarget((SlangCompileTarget)sourceTarget);
}
// If we have an extension tracker, we may need to set options such as SPIR-V version
// and CUDA Shader Model.
if (extensionTracker)
{
// Look for the version
if (auto cudaTracker = as<CUDAExtensionTracker>(extensionTracker))
{
cudaTracker->finalize();
if (cudaTracker->m_smVersion.isSet())
{
DownstreamCompiler::CapabilityVersion version;
version.kind = DownstreamCompiler::CapabilityVersion::Kind::CUDASM;
version.version = cudaTracker->m_smVersion;
options.requiredCapabilityVersions.add(version);
}
if (cudaTracker->isBaseTypeRequired(BaseType::Half))
{
options.flags |= CompileOptions::Flag::EnableFloat16;
}
}
else if (GLSLExtensionTracker* glslTracker = as<GLSLExtensionTracker>(extensionTracker))
{
DownstreamCompiler::CapabilityVersion version;
version.kind = DownstreamCompiler::CapabilityVersion::Kind::SPIRV;
version.version = glslTracker->getSPIRVVersion();
options.requiredCapabilityVersions.add(version);
}
}
// Set the file sytem and source manager, as *may* be used by downstream compiler
options.fileSystemExt = getFileSystemExt();
options.sourceManager = getSourceManager();
// Set the source type
options.sourceLanguage = SlangSourceLanguage(sourceLanguage);
// Disable exceptions and security checks
options.flags &= ~(CompileOptions::Flag::EnableExceptionHandling | CompileOptions::Flag::EnableSecurityChecks);
Profile profile;
if (compilerType == PassThroughMode::Fxc ||
compilerType == PassThroughMode::Dxc ||
compilerType == PassThroughMode::Glslang)
{
const auto entryPointIndices = getEntryPointIndices();
auto targetReq = getTargetReq();
const auto entryPointIndicesCount = entryPointIndices.getCount();
// Whole program means
// * can have 0-N entry points
// * 'doesn't build into an executable/kernel'
//
// So in some sense it is a library
if (targetReq->isWholeProgramRequest())
{
if (compilerType == PassThroughMode::Dxc)
{
// Can support no entry points on DXC because we can build libraries
profile = targetReq->getTargetProfile();
}
else
{
auto downstreamCompilerName = TypeTextUtil::getPassThroughName((SlangPassThrough)compilerType);
sink->diagnose(SourceLoc(), Diagnostics::downstreamCompilerDoesntSupportWholeProgramCompilation, downstreamCompilerName);
return SLANG_FAIL;
}
}
else if (entryPointIndicesCount == 1)
{
// All support a single entry point
const Index entryPointIndex = entryPointIndices[0];
auto entryPoint = getEntryPoint(entryPointIndex);
profile = getEffectiveProfile(entryPoint, targetReq);
options.entryPointName = getText(entryPoint->getName());
auto entryPointNameOverride = getProgram()->getEntryPointNameOverride(entryPointIndex);
if (entryPointNameOverride.getLength() != 0)
{
options.entryPointName = entryPointNameOverride;
}
}
else
{
// We only support a single entry point on this target
SLANG_ASSERT(!"Can only compile with a single entry point on this target");
return SLANG_FAIL;
}
options.stage = SlangStage(profile.getStage());
if (compilerType == PassThroughMode::Dxc)
{
// We will enable the flag to generate proper code for 16 - bit types
// by default, as long as the user is requesting a sufficiently
// high shader model.
//
// TODO: Need to check that this is safe to enable in all cases,
// or if it will make a shader demand hardware features that
// aren't always present.
//
// TODO: Ideally the dxc back-end should be passed some information
// on the "capabilities" that were used and/or requested in the code.
//
if (profile.getVersion() >= ProfileVersion::DX_6_2)
{
options.flags |= CompileOptions::Flag::EnableFloat16;
}
// Set the matrix layout
options.matrixLayout = getTargetReq()->getDefaultMatrixLayoutMode();
}
// Set the profile
options.profileName = GetHLSLProfileName(profile);
}
// If we aren't using LLVM 'host callable', we want downstream compile to produce a shared library
if (compilerType != PassThroughMode::LLVM && target == CodeGenTarget::ShaderHostCallable)
{
target = CodeGenTarget::ShaderSharedLibrary;
}
if (!isPassThroughEnabled())
{
if (_isCPUHostTarget(target))
{
options.libraryPaths.add(Path::getParentDirectory(Path::getExecutablePath()));
// Set up the library artifact
ComPtr<IArtifact> artifact(new Artifact(ArtifactDesc::make(ArtifactKind::Library, Artifact::Payload::HostCPU), "slang-rt"));
options.libraries.add(artifact);
}
}
options.targetType = (SlangCompileTarget)target;
// Need to configure for the compilation
{
auto linkage = getLinkage();
switch (linkage->optimizationLevel)
{
case OptimizationLevel::None: options.optimizationLevel = DownstreamCompiler::OptimizationLevel::None; break;
case OptimizationLevel::Default: options.optimizationLevel = DownstreamCompiler::OptimizationLevel::Default; break;
case OptimizationLevel::High: options.optimizationLevel = DownstreamCompiler::OptimizationLevel::High; break;
case OptimizationLevel::Maximal: options.optimizationLevel = DownstreamCompiler::OptimizationLevel::Maximal; break;
default: SLANG_ASSERT(!"Unhandled optimization level"); break;
}
switch (linkage->debugInfoLevel)
{
case DebugInfoLevel::None: options.debugInfoType = DownstreamCompiler::DebugInfoType::None; break;
case DebugInfoLevel::Minimal: options.debugInfoType = DownstreamCompiler::DebugInfoType::Minimal; break;
case DebugInfoLevel::Standard: options.debugInfoType = DownstreamCompiler::DebugInfoType::Standard; break;
case DebugInfoLevel::Maximal: options.debugInfoType = DownstreamCompiler::DebugInfoType::Maximal; break;
default: SLANG_ASSERT(!"Unhandled debug level"); break;
}
switch( getTargetReq()->getFloatingPointMode())
{
case FloatingPointMode::Default: options.floatingPointMode = DownstreamCompiler::FloatingPointMode::Default; break;
case FloatingPointMode::Precise: options.floatingPointMode = DownstreamCompiler::FloatingPointMode::Precise; break;
case FloatingPointMode::Fast: options.floatingPointMode = DownstreamCompiler::FloatingPointMode::Fast; break;
default: SLANG_ASSERT(!"Unhandled floating point mode");
}
{
// We need to look at the stage of the entry point(s) we are
// being asked to compile, since this will determine the
// "pipeline" that the result should be compiled for (e.g.,
// compute vs. ray tracing).
//
// TODO: This logic is kind of messy in that it assumes
// a program to be compiled will only contain kernels for
// a single pipeline type, but that invariant isn't expressed
// at all in the front-end today. It also has no error
// checking for the case where there are conflicts.
//
// HACK: Right now none of the above concerns matter
// because we always perform code generation on a single
// entry point at a time.
//
Index entryPointCount = getEntryPointCount();
for(Index ee = 0; ee < entryPointCount; ++ee)
{
auto stage = getEntryPoint(ee)->getStage();
switch(stage)
{
default:
break;
case Stage::Compute:
options.pipelineType = DownstreamCompiler::PipelineType::Compute;
break;
case Stage::Vertex:
case Stage::Hull:
case Stage::Domain:
case Stage::Geometry:
case Stage::Fragment:
options.pipelineType = DownstreamCompiler::PipelineType::Rasterization;
break;
case Stage::RayGeneration:
case Stage::Intersection:
case Stage::AnyHit:
case Stage::ClosestHit:
case Stage::Miss:
case Stage::Callable:
options.pipelineType = DownstreamCompiler::PipelineType::RayTracing;
break;
}
}
}
// Add all the search paths (as calculated earlier - they will only be set if this is a pass through else will be empty)
options.includePaths = includePaths;
// Add the specified defines (as calculated earlier - they will only be set if this is a pass through else will be empty)
{
for(auto& def : preprocessorDefinitions)
{
DownstreamCompiler::Define define;
define.nameWithSig = def.Key;
define.value = def.Value;
options.defines.add(define);
}
}
// Add all of the module libraries
options.libraries.addRange(linkage->m_libModules.getBuffer(), linkage->m_libModules.getCount());
}
// Compile
RefPtr<DownstreamCompileResult> downstreamCompileResult;
auto downstreamStartTime = std::chrono::high_resolution_clock::now();
SLANG_RETURN_ON_FAIL(compiler->compile(options, downstreamCompileResult));
auto downstreamElapsedTime =
(std::chrono::high_resolution_clock::now() - downstreamStartTime).count() * 0.000000001;
getSession()->addDownstreamCompileTime(downstreamElapsedTime);
const auto& diagnostics = downstreamCompileResult->getDiagnostics();
if (diagnostics.diagnostics.getCount())
{
StringBuilder compilerText;
compiler->getDesc().appendAsText(compilerText);
StringBuilder builder;
for (const auto& diagnostic : diagnostics.diagnostics)
{
builder.Clear();
const Severity severity = _getDiagnosticSeverity(diagnostic.severity);
if (diagnostic.filePath.getLength() == 0 && diagnostic.fileLine == 0 && severity == Severity::Note)
{
// If theres no filePath line number and it's info, output severity and text alone
builder << getSeverityName(severity) << " : ";
}
else
{
if (diagnostic.filePath.getLength())
{
builder << diagnostic.filePath;
}
if (diagnostic.fileLine)
{
builder << "(" << diagnostic.fileLine <<")";
}
builder << ": ";
if (diagnostic.stage == DownstreamDiagnostic::Stage::Link)
{
builder << "link ";
}
builder << getSeverityName(severity);
builder << " " << diagnostic.code << ": ";
}
builder << diagnostic.text;
reportExternalCompileError(compilerText.getBuffer(), severity, SLANG_OK, builder.getUnownedSlice(), sink);
}
}
// If any errors are emitted, then we are done
if (diagnostics.has(DownstreamDiagnostic::Severity::Error))
{
return SLANG_FAIL;
}
outResult = downstreamCompileResult;
return SLANG_OK;
}
SlangResult CodeGenContext::dissassembleWithDownstream(
const void* data,
size_t dataSizeInBytes,
ISlangBlob** outBlob)
{
auto session = getSession();
auto sink = getSink();
auto target = getTargetFormat();
// Get the downstream compiler that can be used for this target
// TODO(JS):
// This could perhaps be performed in some other manner if there was more than one way to produce
// disassembly from a binary.
auto downstreamCompiler = getDownstreamCompilerRequiredForTarget(target);
// Get the required downstream compiler
DownstreamCompiler* compiler = session->getOrLoadDownstreamCompiler(downstreamCompiler, sink);
if (!compiler)
{
auto compilerName = TypeTextUtil::getPassThroughAsHumanText((SlangPassThrough)downstreamCompiler);
sink->diagnose(SourceLoc(), Diagnostics::passThroughCompilerNotFound, compilerName);
return SLANG_FAIL;
}
ComPtr<ISlangBlob> dissassemblyBlob;
SLANG_RETURN_ON_FAIL(compiler->disassemble(SlangCompileTarget(target), data, dataSizeInBytes, dissassemblyBlob.writeRef()));
*outBlob = dissassemblyBlob.detach();
return SLANG_OK;
}
SlangResult CodeGenContext::dissassembleWithDownstream(
DownstreamCompileResult* downstreamResult,
ISlangBlob** outBlob)
{
ComPtr<ISlangBlob> codeBlob;
SLANG_RETURN_ON_FAIL(downstreamResult->getBinary(codeBlob));
return dissassembleWithDownstream(codeBlob->getBufferPointer(), codeBlob->getBufferSize(), outBlob);
}
SlangResult emitSPIRVForEntryPointsDirectly(
CodeGenContext* codeGenContext,
List<uint8_t>& spirvOut,
RefPtr<PostEmitMetadata>& outMetadata);
static CodeGenTarget _getIntermediateTarget(CodeGenTarget target)
{
switch (target)
{
case CodeGenTarget::DXBytecodeAssembly: return CodeGenTarget::DXBytecode;
case CodeGenTarget::DXILAssembly: return CodeGenTarget::DXIL;
case CodeGenTarget::SPIRVAssembly: return CodeGenTarget::SPIRV;
default: return CodeGenTarget::None;
}
}
/// Function to simplify the logic around emitting, and dissassembling
SlangResult CodeGenContext::_emitEntryPoints(
RefPtr<DownstreamCompileResult>& outDownstreamResult,
RefPtr<PostEmitMetadata>& outMetadata)
{
auto target = getTargetFormat();
switch (target)
{
case CodeGenTarget::SPIRVAssembly:
case CodeGenTarget::DXBytecodeAssembly:
case CodeGenTarget::DXILAssembly:
{
// First compile to an intermediate target for the corresponding binary format.
const CodeGenTarget intermediateTarget = _getIntermediateTarget(target);
CodeGenContext intermediateContext(this, intermediateTarget);
RefPtr<DownstreamCompileResult> code;
SLANG_RETURN_ON_FAIL(intermediateContext._emitEntryPoints(code, outMetadata));
intermediateContext.maybeDumpIntermediate(code);
// Then disassemble the intermediate binary result to get the desired output
// Output the disassembly
ComPtr<ISlangBlob> disassemblyBlob;
SLANG_RETURN_ON_FAIL(intermediateContext.dissassembleWithDownstream(code, disassemblyBlob.writeRef()));
outDownstreamResult = new BlobDownstreamCompileResult(DownstreamDiagnostics(), disassemblyBlob);
return SLANG_OK;
}
case CodeGenTarget::SPIRV:
if (getTargetReq()->shouldEmitSPIRVDirectly())
{
List<uint8_t> spirv;
SLANG_RETURN_ON_FAIL(emitSPIRVForEntryPointsDirectly(this, spirv, outMetadata));
auto spirvBlob = ListBlob::moveCreate(spirv);
outDownstreamResult = new BlobDownstreamCompileResult(DownstreamDiagnostics(), spirvBlob);
return SLANG_OK;
}
/* fall through to: */
case CodeGenTarget::DXIL:
case CodeGenTarget::DXBytecode:
case CodeGenTarget::PTX:
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary:
case CodeGenTarget::HostExecutable:
SLANG_RETURN_ON_FAIL(emitWithDownstreamForEntryPoints(outDownstreamResult, outMetadata));
return SLANG_OK;
default: break;
}
return SLANG_FAIL;
}
// Do emit logic for a zero or more entry points
CompileResult CodeGenContext::emitEntryPoints()
{
CompileResult result;
auto target = getTargetFormat();
switch (target)
{
case CodeGenTarget::SPIRVAssembly:
case CodeGenTarget::DXBytecodeAssembly:
case CodeGenTarget::DXILAssembly:
case CodeGenTarget::SPIRV:
case CodeGenTarget::DXIL:
case CodeGenTarget::DXBytecode:
case CodeGenTarget::PTX:
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary:
case CodeGenTarget::HostExecutable:
{
RefPtr<DownstreamCompileResult> downstreamResult;
RefPtr<PostEmitMetadata> metadata;
if (SLANG_SUCCEEDED(_emitEntryPoints(downstreamResult, metadata)))
{
maybeDumpIntermediate(downstreamResult);
result = CompileResult(downstreamResult, metadata);
}
}
break;
case CodeGenTarget::GLSL:
case CodeGenTarget::HLSL:
case CodeGenTarget::CUDASource:
case CodeGenTarget::CPPSource:
case CodeGenTarget::HostCPPSource:
case CodeGenTarget::CSource:
{
RefPtr<ExtensionTracker> extensionTracker = _newExtensionTracker(target);
RefPtr<PostEmitMetadata> metadata;
CodeGenContext subContext(this, target, extensionTracker);
String code;
if (SLANG_FAILED(subContext.emitEntryPointsSource(code, metadata)))
{
return result;
}
subContext.maybeDumpIntermediate(code.getBuffer());
result = CompileResult(code, metadata);
}
break;
case CodeGenTarget::None:
// The user requested no output
break;
// Note(tfoley): We currently hit this case when compiling the stdlib
case CodeGenTarget::Unknown:
break;
default:
SLANG_UNEXPECTED("unhandled code generation target");
break;
}
return result;
}
enum class OutputFileKind
{
Text,
Binary,
};
static void writeOutputFile(
CodeGenContext* context,
FILE* file,
String const& path,
void const* data,
size_t size)
{
size_t count = fwrite(data, size, 1, file);
if (count != 1)
{
context->getSink()->diagnose(
SourceLoc(),
Diagnostics::cannotWriteOutputFile,
path);
}
}
static void writeOutputFile(
CodeGenContext* context,
ISlangWriter* writer,
String const& path,
void const* data,
size_t size)
{
if (SLANG_FAILED(writer->write((const char*)data, size)))
{
context->getSink()->diagnose(
SourceLoc(),
Diagnostics::cannotWriteOutputFile,
path);
}
}
static void writeOutputFile(
CodeGenContext* context,
String const& path,
void const* data,
size_t size,
OutputFileKind kind)
{
FILE* file = fopen(
path.getBuffer(),
kind == OutputFileKind::Binary ? "wb" : "w");
if (!file)
{
context->getSink()->diagnose(
SourceLoc(),
Diagnostics::cannotWriteOutputFile,
path);
return;
}
writeOutputFile(context, file, path, data, size);
fclose(file);
}
static void writeCompileResultToFile(
CodeGenContext* context,
String const& outputPath,
CompileResult const& result)
{
switch (result.format)
{
case ResultFormat::Text:
{
auto text = result.outputString;
writeOutputFile(context,
outputPath,
text.begin(),
text.end() - text.begin(),
OutputFileKind::Text);
}
break;
case ResultFormat::Binary:
{
ComPtr<ISlangBlob> blob;
if (SLANG_FAILED(result.getBlob(blob)))
{
SLANG_UNEXPECTED("No blob to emit");
return;
}
writeOutputFile(context,
outputPath,
blob->getBufferPointer(),
blob->getBufferSize(),
OutputFileKind::Binary);
}
break;
default:
SLANG_UNEXPECTED("unhandled output format");
break;
}
}
static void writeOutputToConsole(
ISlangWriter* writer,
String const& text)
{
writer->write(text.getBuffer(), text.getLength());
}
static void writeCompileResultToStandardOutput(
CodeGenContext* codeGenContext,
EndToEndCompileRequest* endToEndReq,
CompileResult const& result)
{
auto targetReq = codeGenContext->getTargetReq();
ISlangWriter* writer = endToEndReq->getWriter(WriterChannel::StdOutput);
switch (result.format)
{
case ResultFormat::Text:
writeOutputToConsole(writer, result.outputString);
break;
case ResultFormat::Binary:
{
ComPtr<ISlangBlob> blob;
if (SLANG_FAILED(result.getBlob(blob)))
{
if (targetReq->getTarget() == CodeGenTarget::ShaderHostCallable)
{
// Some HostCallable are not directly representable as a 'binary'.
// So here, we just ignore if that appears the case, and don't output an unexpected error.
return;
}
SLANG_UNEXPECTED("No blob to emit");
return;
}
const void* blobData = blob->getBufferPointer();
size_t blobSize = blob->getBufferSize();
if (writer->isConsole())
{
// Writing to console, so we need to generate text output.
switch (targetReq->getTarget())
{
case CodeGenTarget::SPIRVAssembly:
case CodeGenTarget::DXBytecodeAssembly:
case CodeGenTarget::DXILAssembly:
{
const UnownedStringSlice disassembly = StringUtil::getSlice(blob);
writeOutputToConsole(writer, disassembly);
}
break;
case CodeGenTarget::SPIRV:
case CodeGenTarget::DXIL:
case CodeGenTarget::DXBytecode:
{
ComPtr<ISlangBlob> disassemblyBlob;
if (SLANG_SUCCEEDED(codeGenContext->dissassembleWithDownstream(blobData, blobSize, disassemblyBlob.writeRef())))
{
const UnownedStringSlice disassembly = StringUtil::getSlice(disassemblyBlob);
writeOutputToConsole(writer, disassembly);
}
}
break;
case CodeGenTarget::PTX:
// For now we just dump PTX out as hex
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary:
case CodeGenTarget::HostExecutable:
HexDumpUtil::dumpWithMarkers((const uint8_t*)blobData, blobSize, 24, writer);
break;
default:
SLANG_UNEXPECTED("unhandled output format");
return;
}
}
else
{
// Redirecting stdout to a file, so do the usual thing
writer->setMode(SLANG_WRITER_MODE_BINARY);
writeOutputFile(
codeGenContext,
writer,
"stdout",
blobData,
blobSize);
}
}
break;
default:
SLANG_UNEXPECTED("unhandled output format");
break;
}
}
void EndToEndCompileRequest::writeWholeProgramResult(
TargetRequest* targetReq)
{
auto program = getSpecializedGlobalAndEntryPointsComponentType();
auto targetProgram = program->getTargetProgram(targetReq);
auto& result = targetProgram->getExistingWholeProgramResult();
// Skip the case with no output
if (result.format == ResultFormat::None)
return;
CodeGenContext::EntryPointIndices entryPointIndices;
for (Index i = 0; i < program->getEntryPointCount(); ++i)
entryPointIndices.add(i);
CodeGenContext::Shared sharedCodeGenContext(targetProgram, entryPointIndices, getSink(), this);
CodeGenContext codeGenContext(&sharedCodeGenContext);
// It is possible that we are dynamically discovering entry
// points (using `[shader(...)]` attributes), so that there
// might be entry points added to the program that did not
// get paths specified via command-line options.
//
RefPtr<EndToEndCompileRequest::TargetInfo> targetInfo;
if (m_targetInfos.TryGetValue(targetReq, targetInfo))
{
String outputPath = targetInfo->wholeTargetOutputPath;
if (outputPath != "")
{
writeCompileResultToFile(&codeGenContext, outputPath, result);
return;
}
}
writeCompileResultToStandardOutput(&codeGenContext, this, result);
}
void EndToEndCompileRequest::writeEntryPointResult(
TargetRequest* targetReq,
Int entryPointIndex)
{
auto program = getSpecializedGlobalAndEntryPointsComponentType();
auto targetProgram = program->getTargetProgram(targetReq);
auto& result = targetProgram->getExistingEntryPointResult(entryPointIndex);
// Skip the case with no output
if (result.format == ResultFormat::None)
return;
CodeGenContext::EntryPointIndices entryPointIndices;
entryPointIndices.add(entryPointIndex);
CodeGenContext::Shared sharedCodeGenContext(targetProgram, entryPointIndices, getSink(), this);
CodeGenContext codeGenContext(&sharedCodeGenContext);
// It is possible that we are dynamically discovering entry
// points (using `[shader(...)]` attributes), so that there
// might be entry points added to the program that did not
// get paths specified via command-line options.
//
RefPtr<EndToEndCompileRequest::TargetInfo> targetInfo;
auto entryPoint = program->getEntryPoint(entryPointIndex);
if(m_targetInfos.TryGetValue(targetReq, targetInfo))
{
String outputPath;
if(targetInfo->entryPointOutputPaths.TryGetValue(entryPointIndex, outputPath))
{
writeCompileResultToFile(&codeGenContext, outputPath, result);
return;
}
}
writeCompileResultToStandardOutput(&codeGenContext, this, result);
}
CompileResult& TargetProgram::_createWholeProgramResult(
DiagnosticSink* sink,
EndToEndCompileRequest* endToEndReq)
{
// We want to call `emitEntryPoints` function to generate code that contains
// all the entrypoints defined in `m_program`.
// The current logic of `emitEntryPoints` takes a list of entry-point indices to
// emit code for, so we construct such a list first.
List<Int> entryPointIndices;
m_entryPointResults.setCount(m_program->getEntryPointCount());
entryPointIndices.setCount(m_program->getEntryPointCount());
for (Index i = 0; i < entryPointIndices.getCount(); i++)
entryPointIndices[i] = i;
auto& result = m_wholeProgramResult;
CodeGenContext::Shared sharedCodeGenContext(this, entryPointIndices, sink, endToEndReq);
CodeGenContext codeGenContext(&sharedCodeGenContext);
result = codeGenContext.emitEntryPoints();
return result;
}
CompileResult& TargetProgram::_createEntryPointResult(
Int entryPointIndex,
DiagnosticSink* sink,
EndToEndCompileRequest* endToEndReq)
{
// It is possible that entry points got added to the `Program`
// *after* we created this `TargetProgram`, so there might be
// a request for an entry point that we didn't allocate space for.
//
// TODO: Change the construction logic so that a `Program` is
// constructed all at once rather than incrementally, to avoid
// this problem.
//
if(entryPointIndex >= m_entryPointResults.getCount())
m_entryPointResults.setCount(entryPointIndex+1);
auto& result = m_entryPointResults[entryPointIndex];
CodeGenContext::EntryPointIndices entryPointIndices;
entryPointIndices.add(entryPointIndex);
CodeGenContext::Shared sharedCodeGenContext(this, entryPointIndices, sink, endToEndReq);
CodeGenContext codeGenContext(&sharedCodeGenContext);
result = codeGenContext.emitEntryPoints();
return result;
}
CompileResult& TargetProgram::getOrCreateWholeProgramResult(
DiagnosticSink* sink)
{
auto& result = m_wholeProgramResult;
if (result.format != ResultFormat::None)
return result;
// If we haven't yet computed a layout for this target
// program, we need to make sure that is done before
// code generation.
//
if (!getOrCreateIRModuleForLayout(sink))
{
return result;
}
return _createWholeProgramResult(sink);
}
CompileResult& TargetProgram::getOrCreateEntryPointResult(
Int entryPointIndex,
DiagnosticSink* sink)
{
if(entryPointIndex >= m_entryPointResults.getCount())
m_entryPointResults.setCount(entryPointIndex+1);
auto& result = m_entryPointResults[entryPointIndex];
if( result.format != ResultFormat::None )
return result;
// If we haven't yet computed a layout for this target
// program, we need to make sure that is done before
// code generation.
//
if( !getOrCreateIRModuleForLayout(sink) )
{
return result;
}
return _createEntryPointResult(
entryPointIndex,
sink);
}
void EndToEndCompileRequest::generateOutput(
TargetProgram* targetProgram)
{
auto program = targetProgram->getProgram();
auto targetReq = targetProgram->getTargetReq();
// Generate target code any entry points that
// have been requested for compilation.
auto entryPointCount = program->getEntryPointCount();
if (targetReq->isWholeProgramRequest())
{
targetProgram->_createWholeProgramResult(getSink(), this);
}
else
{
for (Index ii = 0; ii < entryPointCount; ++ii)
{
targetProgram->_createEntryPointResult(
ii,
getSink(),
this);
}
}
}
SlangResult EndToEndCompileRequest::writeContainerToStream(Stream* stream)
{
auto linkage = getLinkage();
// Set up options
SerialContainerUtil::WriteOptions options;
options.compressionType = linkage->serialCompressionType;
if (linkage->m_obfuscateCode)
{
// If code is obfuscated, we *disable* AST output as it is not obfuscated and will reveal
// too much about IR.
// Also currently only IR is needed.
options.optionFlags &= ~SerialOptionFlag::ASTModule;
}
else if (linkage->debugInfoLevel != DebugInfoLevel::None && linkage->getSourceManager())
{
options.optionFlags |= SerialOptionFlag::SourceLocation;
options.sourceManager = linkage->getSourceManager();
}
{
RiffContainer container;
{
SerialContainerData data;
SLANG_RETURN_ON_FAIL(SerialContainerUtil::addEndToEndRequestToData(this, options, data));
SLANG_RETURN_ON_FAIL(SerialContainerUtil::write(data, options, &container));
}
// We now write the RiffContainer to the stream
SLANG_RETURN_ON_FAIL(RiffUtil::write(container.getRoot(), true, stream));
}
return SLANG_OK;
}
SlangResult EndToEndCompileRequest::maybeCreateContainer()
{
switch (m_containerFormat)
{
case ContainerFormat::SlangModule:
{
m_containerBlob.setNull();
OwnedMemoryStream stream(FileAccess::Write);
SlangResult res = writeContainerToStream(&stream);
if (SLANG_FAILED(res))
{
getSink()->diagnose(SourceLoc(), Diagnostics::unableToCreateModuleContainer);
return res;
}
// Need to turn into a blob
RefPtr<ListBlob> blob(new ListBlob);
// Swap the streams contents into the blob
stream.swapContents(blob->m_data);
m_containerBlob = blob;
return res;
}
default: break;
}
return SLANG_OK;
}
SlangResult EndToEndCompileRequest::maybeWriteContainer(const String& fileName)
{
// If there is no container, or filename, don't write anything
if (fileName.getLength() == 0 || !m_containerBlob)
{
return SLANG_OK;
}
FileStream stream;
SLANG_RETURN_ON_FAIL(stream.init(fileName, FileMode::Create, FileAccess::Write, FileShare::ReadWrite));
SLANG_RETURN_ON_FAIL(stream.write(m_containerBlob->getBufferPointer(), m_containerBlob->getBufferSize()));
return SLANG_OK;
}
static void _writeString(Stream& stream, const char* string)
{
stream.write(string, strlen(string));
}
static void _escapeDependencyString(const char* string, StringBuilder& outBuilder)
{
// make has unusual escaping rules, but we only care about characters that are acceptable in a path
for (const char* p = string; *p; ++p)
{
char c = *p;
switch(c)
{
case ' ':
case ':':
case '#':
case '[':
case ']':
case '\\':
outBuilder.appendChar('\\');
break;
case '$':
outBuilder.appendChar('$');
break;
}
outBuilder.appendChar(c);
}
}
// Writes a line to the file stream, formatted like this:
// <output-file>: <dependency-file> <dependency-file...>
static void _writeDependencyStatement(Stream& stream, EndToEndCompileRequest* compileRequest, const String& outputPath)
{
if (outputPath.getLength() == 0)
return;
StringBuilder builder;
_escapeDependencyString(outputPath.begin(), builder);
_writeString(stream, builder.begin());
_writeString(stream, ": ");
int dependencyCount = compileRequest->getDependencyFileCount();
for (int dependencyIndex = 0; dependencyIndex < dependencyCount; ++dependencyIndex)
{
builder.Clear();
_escapeDependencyString(compileRequest->getDependencyFilePath(dependencyIndex), builder);
_writeString(stream, builder.begin());
_writeString(stream, (dependencyIndex + 1 < dependencyCount) ? " " : "\n");
}
}
// Writes a file with dependency info, with one line in the output file per compile product.
static SlangResult _writeDependencyFile(EndToEndCompileRequest* compileRequest)
{
if (compileRequest->m_dependencyOutputPath.getLength() == 0)
return SLANG_OK;
FileStream stream;
SLANG_RETURN_ON_FAIL(stream.init(compileRequest->m_dependencyOutputPath, FileMode::Create, FileAccess::Write, FileShare::ReadWrite));
auto linkage = compileRequest->getLinkage();
auto program = compileRequest->getSpecializedGlobalAndEntryPointsComponentType();
// Iterate over all the targets and their outputs
for (const auto& targetReq : linkage->targets)
{
if (targetReq->isWholeProgramRequest())
{
RefPtr<EndToEndCompileRequest::TargetInfo> targetInfo;
if (compileRequest->m_targetInfos.TryGetValue(targetReq, targetInfo))
{
_writeDependencyStatement(stream, compileRequest, targetInfo->wholeTargetOutputPath);
}
}
else
{
Index entryPointCount = program->getEntryPointCount();
for (Index entryPointIndex = 0; entryPointIndex < entryPointCount; ++entryPointIndex)
{
RefPtr<EndToEndCompileRequest::TargetInfo> targetInfo;
if (compileRequest->m_targetInfos.TryGetValue(targetReq, targetInfo))
{
String outputPath;
if (targetInfo->entryPointOutputPaths.TryGetValue(entryPointIndex, outputPath))
{
_writeDependencyStatement(stream, compileRequest, outputPath);
}
}
}
}
}
return SLANG_OK;
}
void EndToEndCompileRequest::generateOutput(
ComponentType* program)
{
// When dynamic dispatch is disabled, the program must
// be fully specialized by now. So we check if we still
// have unspecialized generic/existential parameters,
// and report them as an error.
//
auto specializationParamCount = program->getSpecializationParamCount();
if (disableDynamicDispatch && specializationParamCount != 0)
{
auto sink = getSink();
for( Index ii = 0; ii < specializationParamCount; ++ii )
{
auto specializationParam = program->getSpecializationParam(ii);
if( auto decl = as<Decl>(specializationParam.object) )
{
sink->diagnose(specializationParam.loc, Diagnostics::specializationParameterOfNameNotSpecialized, decl);
}
else if( auto type = as<Type>(specializationParam.object) )
{
sink->diagnose(specializationParam.loc, Diagnostics::specializationParameterOfNameNotSpecialized, type);
}
else
{
sink->diagnose(specializationParam.loc, Diagnostics::specializationParameterNotSpecialized);
}
}
return;
}
// Go through the code-generation targets that the user
// has specified, and generate code for each of them.
//
auto linkage = getLinkage();
for (auto targetReq : linkage->targets)
{
auto targetProgram = program->getTargetProgram(targetReq);
generateOutput(targetProgram);
}
}
void EndToEndCompileRequest::generateOutput()
{
generateOutput(getSpecializedGlobalAndEntryPointsComponentType());
// If we are in command-line mode, we might be expected to actually
// write output to one or more files here.
if (m_isCommandLineCompile)
{
auto linkage = getLinkage();
auto program = getSpecializedGlobalAndEntryPointsComponentType();
for (auto targetReq : linkage->targets)
{
if (targetReq->isWholeProgramRequest())
{
writeWholeProgramResult(
targetReq);
}
else
{
Index entryPointCount = program->getEntryPointCount();
for (Index ee = 0; ee < entryPointCount; ++ee)
{
writeEntryPointResult(
targetReq,
ee);
}
}
}
maybeCreateContainer();
maybeWriteContainer(m_containerOutputPath);
_writeDependencyFile(this);
}
}
// Debug logic for dumping intermediate outputs
//
void CodeGenContext::dumpIntermediate(
void const* data,
size_t size,
char const* ext,
bool isBinary)
{
// Try to generate a unique ID for the file to dump,
// even in cases where there might be multiple threads
// doing compilation.
//
// This is primarily a debugging aid, so we don't
// really need/want to do anything too elaborate
static uint32_t counter = 0;
#ifdef _WIN32
uint32_t id = InterlockedIncrement(&counter);
#else
// TODO: actually implement the case for other platforms
uint32_t id = counter++;
#endif
String path;
path.append(getIntermediateDumpPrefix());
path.append(id);
path.append(ext);
FILE* file = fopen(path.getBuffer(), isBinary ? "wb" : "w");
if (!file) return;
fwrite(data, size, 1, file);
fclose(file);
}
void CodeGenContext::dumpIntermediateText(
void const* data,
size_t size,
char const* ext)
{
dumpIntermediate(data, size, ext, false);
}
void CodeGenContext::dumpIntermediateBinary(
void const* data,
size_t size,
char const* ext)
{
dumpIntermediate(data, size, ext, true);
}
void CodeGenContext::maybeDumpIntermediate(
DownstreamCompileResult* compileResult)
{
if (!shouldDumpIntermediates())
return;
ComPtr<ISlangBlob> blob;
if (SLANG_SUCCEEDED(compileResult->getBinary(blob)))
{
maybeDumpIntermediate(blob->getBufferPointer(), blob->getBufferSize());
}
}
static const char* _getTargetExtension(CodeGenTarget target)
{
switch (target)
{
case CodeGenTarget::HLSL: return ".hlsl";
case CodeGenTarget::GLSL: return ".glsl";
case CodeGenTarget::SPIRV: return ".spv";
case CodeGenTarget::DXBytecode: return ".dxbc";
case CodeGenTarget::DXIL: return ".dxil";
case CodeGenTarget::SPIRVAssembly: return ".spv.asm";
case CodeGenTarget::DXBytecodeAssembly: return ".dxbc.asm";
case CodeGenTarget::DXILAssembly: return ".dxil.asm";
case CodeGenTarget::CSource: return ".c";
case CodeGenTarget::CUDASource: return ".cu";
case CodeGenTarget::CPPSource: return ".cpp";
case CodeGenTarget::HostCPPSource: return ".cpp";
// What these should be called is target specific, but just use these exts to make clear for now
// for now
case CodeGenTarget::HostExecutable: return ".exe";
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary: return ".shared-lib";
default: break;
}
return nullptr;
}
void CodeGenContext::maybeDumpIntermediate(
void const* data,
size_t size)
{
if (!shouldDumpIntermediates())
return;
auto target = getTargetFormat();
switch (target)
{
case CodeGenTarget::CPPSource:
case CodeGenTarget::HostCPPSource:
case CodeGenTarget::CUDASource:
case CodeGenTarget::CSource:
case CodeGenTarget::DXILAssembly:
case CodeGenTarget::DXBytecodeAssembly:
case CodeGenTarget::SPIRVAssembly:
case CodeGenTarget::GLSL:
case CodeGenTarget::HLSL:
{
dumpIntermediateText(data, size, _getTargetExtension(target));
break;
}
#if 0
case CodeGenTarget::SlangIRAssembly:
{
dumpIntermediateText(compileRequest, data, size, ".slang-ir.asm");
break;
}
#endif
case CodeGenTarget::DXIL:
case CodeGenTarget::DXBytecode:
case CodeGenTarget::SPIRV:
{
const char* ext = _getTargetExtension(target);
SLANG_ASSERT(ext);
dumpIntermediateBinary(data, size, ext);
ComPtr<ISlangBlob> disassemblyBlob;
if (SLANG_SUCCEEDED(dissassembleWithDownstream(data, size, disassemblyBlob.writeRef())))
{
StringBuilder buf;
buf << ext << ".asm";
dumpIntermediateText(disassemblyBlob->getBufferPointer(), disassemblyBlob->getBufferSize(), buf.getBuffer());
}
break;
}
case CodeGenTarget::ShaderHostCallable:
case CodeGenTarget::ShaderSharedLibrary:
case CodeGenTarget::HostExecutable:
{
dumpIntermediateBinary(data, size, _getTargetExtension(target));
break;
}
default: break;
}
}
void CodeGenContext::maybeDumpIntermediate(
char const* text)
{
if (!shouldDumpIntermediates())
return;
maybeDumpIntermediate(text, strlen(text));
}
IRDumpOptions CodeGenContext::getIRDumpOptions()
{
if (auto endToEndReq = isEndToEndCompile())
{
return endToEndReq->getFrontEndReq()->m_irDumpOptions;
}
return IRDumpOptions();
}
bool CodeGenContext::shouldValidateIR()
{
if (auto endToEndReq = isEndToEndCompile())
{
if (endToEndReq->getFrontEndReq()->shouldValidateIR)
return true;
}
return false;
}
bool CodeGenContext::shouldDumpIR()
{
if (getTargetReq()->getTargetFlags() & SLANG_TARGET_FLAG_DUMP_IR)
return true;
if (auto endToEndReq = isEndToEndCompile())
{
if (endToEndReq->getFrontEndReq()->shouldDumpIR)
return true;
}
return false;
}
bool CodeGenContext::shouldDumpIntermediates()
{
if (getTargetReq()->shouldDumpIntermediates())
return true;
if (auto endToEndReq = isEndToEndCompile())
{
if (endToEndReq->shouldDumpIntermediates)
return true;
}
return false;
}
bool CodeGenContext::shouldTrackLiveness()
{
auto endToEndReq = isEndToEndCompile();
return (endToEndReq && endToEndReq->enableLivenessTracking) ||
getTargetReq()->shouldTrackLiveness();
}
String CodeGenContext::getIntermediateDumpPrefix()
{
if (auto endToEndReq = isEndToEndCompile())
{
return endToEndReq->m_dumpIntermediatePrefix;
}
return String();
}
bool CodeGenContext::getUseUnknownImageFormatAsDefault()
{
if (auto endToEndReq = isEndToEndCompile())
{
return endToEndReq->useUnknownImageFormatAsDefault;
}
return false;
}
bool CodeGenContext::isSpecializationDisabled()
{
if (auto endToEndReq = isEndToEndCompile())
{
return endToEndReq->disableSpecialization;
}
return false;
}
}
| 35.779029 | 157 | 0.573054 | [
"mesh",
"geometry",
"object",
"model"
] |
741c79cc812967348ad8cfe5b8e890e844460bf4 | 13,538 | cc | C++ | src/chromium/web_runner_tests/web_runner_pixel_tests.cc | EnderNightLord-ChromeBook/zircon-rpi | b09b1eb3aa7a127c65568229fe10edd251869283 | [
"BSD-2-Clause"
] | 1 | 2020-12-29T17:07:06.000Z | 2020-12-29T17:07:06.000Z | src/chromium/web_runner_tests/web_runner_pixel_tests.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | null | null | null | src/chromium/web_runner_tests/web_runner_pixel_tests.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuchsia/sys/cpp/fidl.h>
#include <fuchsia/ui/app/cpp/fidl.h>
#include <fuchsia/ui/policy/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fdio/spawn.h>
#include <lib/fit/function.h>
#include <lib/gtest/real_loop_fixture.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <lib/zx/clock.h>
#include <lib/zx/time.h>
#include <zircon/status.h>
#include <iomanip>
#include <map>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "src/chromium/web_runner_tests/mock_get.h"
#include "src/chromium/web_runner_tests/test_server.h"
#include "src/chromium/web_runner_tests/web_context.h"
#include "src/lib/fsl/vmo/vector.h"
#include "src/lib/fxl/strings/string_printf.h"
#include "src/lib/ui/base_view/embedded_view_utils.h"
#include "src/ui/testing/views/embedder_view.h"
namespace {
// Max time to wait in failure cases before bailing.
constexpr zx::duration kTimeout = zx::sec(15);
constexpr uint32_t kBlankColor = 0x00000000;
constexpr zx::duration kTestTimeout = zx::sec(60);
std::map<uint32_t, size_t> Histogram(const fuchsia::ui::scenic::ScreenshotData& screenshot) {
EXPECT_GT(screenshot.info.width, 0u);
EXPECT_GT(screenshot.info.height, 0u);
std::vector<uint8_t> data;
EXPECT_TRUE(fsl::VectorFromVmo(screenshot.data, &data)) << "Failed to read screenshot";
std::map<uint32_t, size_t> histogram;
const uint32_t* bitmap = reinterpret_cast<const uint32_t*>(data.data());
const size_t size = screenshot.info.width * screenshot.info.height;
EXPECT_EQ(size * sizeof(uint32_t), data.size());
for (size_t i = 0; i < size; ++i) {
++histogram[bitmap[i]];
}
return histogram;
}
// Invokes the input tool for input injection.
// See src/ui/tools/input/README.md or `input --help` for usage details.
// Commands used here:
// * tap <x> <y> (scaled out of 1000)
// TODO(fxbug.dev/24462): Expose as a FIDL service.
void Input(std::vector<const char*> args) {
// start with proc name, end with nullptr
args.insert(args.begin(), "input");
args.push_back(nullptr);
zx_handle_t proc;
zx_status_t status =
fdio_spawn(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL, "/bin/input", args.data(), &proc);
FX_CHECK(status == ZX_OK) << "fdio_spawn: " << zx_status_get_string(status);
status = zx_object_wait_one(proc, ZX_PROCESS_TERMINATED,
(zx::clock::get_monotonic() + kTimeout).get(), nullptr);
FX_CHECK(status == ZX_OK) << "zx_object_wait_one: " << zx_status_get_string(status);
zx_info_process_t info;
status = zx_object_get_info(proc, ZX_INFO_PROCESS, &info, sizeof(info), nullptr, nullptr);
FX_CHECK(status == ZX_OK) << "zx_object_get_info: " << zx_status_get_string(status);
FX_CHECK(info.return_code == 0) << info.return_code;
}
// Base fixture for pixel tests, containing Scenic and presentation setup, and
// screenshot utilities.
class PixelTest : public gtest::RealLoopFixture {
protected:
PixelTest() : context_(sys::ComponentContext::CreateAndServeOutgoingDirectory()) {
scenic_ = context_->svc()->Connect<fuchsia::ui::scenic::Scenic>();
scenic_.set_error_handler([](zx_status_t status) {
FAIL() << "Lost connection to Scenic: " << zx_status_get_string(status);
});
// TODO(fxbug.dev/40933)
//
// These tests can flake when a screenshot captures a frame from the previous test, which can
// advance the test logic early. This is a temporary solution that waits for a blank on setup.
// Better solutions include hermetic Scenic (using src/ui/scenic/lib/gfx/tests/pixel_test.h) or
// refactoring to use view state events (probably the best solution; greatly improves
// determinism at the expense of added harness complexity).
//
// WebRunnerPixelTest.Static below is factored to use view state events, but the others are not.
FX_CHECK(WaitForBlank());
}
sys::ComponentContext* context() { return context_.get(); }
fuchsia::ui::scenic::Scenic* scenic() { return scenic_.get(); }
// Gets a view token for presentation by |RootPresenter|. See also
// garnet/examples/ui/hello_base_view
fuchsia::ui::views::ViewToken CreatePresentationViewToken() {
auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
auto presenter = context_->svc()->Connect<fuchsia::ui::policy::Presenter>();
presenter.set_error_handler(
[](zx_status_t status) { FAIL() << "presenter: " << zx_status_get_string(status); });
presenter->PresentOrReplaceView(std::move(view_holder_token), nullptr);
return std::move(view_token);
}
bool ScreenshotUntil(fit::function<bool(fuchsia::ui::scenic::ScreenshotData, bool)> condition,
zx::duration timeout = kTimeout) {
zx::time start = zx::clock::get_monotonic();
while (zx::clock::get_monotonic() - start <= timeout) {
fuchsia::ui::scenic::ScreenshotData screenshot;
bool ok;
scenic_->TakeScreenshot(
[this, &screenshot, &ok](fuchsia::ui::scenic::ScreenshotData screenshot_in, bool status) {
ok = status;
screenshot = std::move(screenshot_in);
QuitLoop();
});
if (!RunLoopWithTimeout(timeout) && condition(std::move(screenshot), ok)) {
return true;
}
}
return false;
}
// Blank can manifest as invalid screenshots or blackness.
// TODO(fxbug.dev/40933): remove
bool WaitForBlank() {
return ScreenshotUntil([](fuchsia::ui::scenic::ScreenshotData screenshot, bool status) {
return !status || Histogram(screenshot)[kBlankColor] > 0u;
});
}
void ExpectSolidColor(uint32_t argb) {
std::map<uint32_t, size_t> histogram;
FX_LOGS(INFO) << "Looking for color " << std::hex << argb << ".";
EXPECT_TRUE(ScreenshotUntil(
[argb, &histogram](fuchsia::ui::scenic::ScreenshotData screenshot, bool status) {
if (!status)
return false;
histogram = Histogram(screenshot);
FX_LOGS(INFO) << "Looking for color " << std::hex << argb << ": found " << std::dec
<< histogram[argb] << " px.";
return histogram[argb] > 0u;
}));
histogram.erase(argb);
EXPECT_EQ((std::map<uint32_t, size_t>){}, histogram) << "Unexpected colors";
}
void ExpectPrimaryColor(uint32_t color) {
std::multimap<size_t, uint32_t> inverse_histogram;
FX_LOGS(INFO) << "Looking for color " << std::hex << color;
EXPECT_TRUE(ScreenshotUntil([color, &inverse_histogram](
fuchsia::ui::scenic::ScreenshotData screenshot, bool status) {
if (!status)
return false;
std::map<uint32_t, size_t> histogram = Histogram(screenshot);
FX_LOGS(INFO) << histogram[color] << " px";
inverse_histogram.clear();
for (const auto entry : histogram) {
inverse_histogram.emplace(entry.second, entry.first);
}
return (--inverse_histogram.end())->second == color;
})) << "Primary color: "
<< std::hex << (--inverse_histogram.end())->second;
}
private:
std::unique_ptr<sys::ComponentContext> context_;
fuchsia::sys::ComponentControllerPtr runner_ctrl_;
fuchsia::ui::scenic::ScenicPtr scenic_;
};
using WebRunnerPixelTest = PixelTest;
// Loads a static page with a solid color via the component framework and
// verifies that the color is the only color onscreen.
TEST_F(WebRunnerPixelTest, Static) {
static constexpr uint32_t kTargetColor = 0xffff00ff;
web_runner_tests::TestServer server;
FX_CHECK(server.FindAndBindPort());
// Chromium and the Fuchsia network package loader both send us requests. This
// may go away after fxbug.dev/17641; although the race seems to be in Modular, the
// fix may remove the unnecessary net request in component framework.
auto serve = server.ServeAsync([&server] {
while (server.Accept()) {
web_runner_tests::MockHttpGetResponse(&server, "static.html");
}
});
fuchsia::sys::ComponentControllerPtr controller;
fuchsia::sys::LauncherPtr launcher;
context()->svc()->Connect(launcher.NewRequest());
auto info = scenic::LaunchComponentAndCreateView(
launcher, fxl::StringPrintf("http://localhost:%d/static.html", server.port()), {});
info.controller.events().OnTerminated = [](int64_t code, fuchsia::sys::TerminationReason reason) {
FAIL();
};
// Present the view.
scenic::EmbedderView embedder_view({
.session_and_listener_request = scenic::CreateScenicSessionPtrAndListenerRequest(scenic()),
.view_token = CreatePresentationViewToken(),
});
embedder_view.EmbedView(
std::move(info),
/*view_state_changed_callback=*/[this](fuchsia::ui::gfx::ViewState view_state) {
EXPECT_TRUE(view_state.is_rendering);
QuitLoop();
});
// Wait to get a signal that the view is being rendered.
EXPECT_FALSE(RunLoopWithTimeout(kTestTimeout))
<< "Timed out waiting for a ViewStateChanged event.";
ExpectSolidColor(kTargetColor);
}
// This fixture uses fuchsia.web FIDL services to interact with the WebEngine.
class WebPixelTest : public PixelTest {
protected:
WebPixelTest()
: web_context_(context(), fuchsia::web::ContextFeatureFlags::VULKAN |
fuchsia::web::ContextFeatureFlags::HARDWARE_VIDEO_DECODER),
embedder_view_({
.session_and_listener_request =
scenic::CreateScenicSessionPtrAndListenerRequest(scenic()),
.view_token = CreatePresentationViewToken(),
}) {
auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
web_context_.web_frame()->CreateView(std::move(view_token));
scenic::EmbeddedViewInfo embedded_view_info;
embedded_view_info.view_holder_token = std::move(view_holder_token);
embedder_view_.EmbedView(
std::move(embedded_view_info),
/*view_state_changed_callback=*/[this](fuchsia::ui::gfx::ViewState view_state) {
EXPECT_TRUE(view_state.is_rendering);
QuitLoop();
});
// Wait to get a signal that the view is being rendered.
EXPECT_FALSE(RunLoopWithTimeout(kTestTimeout))
<< "Timed out waiting for a ViewStateChanged event.";
}
WebContext* web_context() { return &web_context_; }
private:
WebContext web_context_;
scenic::EmbedderView embedder_view_;
};
// Loads a static page with a solid color via fuchsia.web interfaces and
// verifies that the color is the only color onscreen.
TEST_F(WebPixelTest, Static) {
static constexpr uint32_t kTargetColor = 0xffff00ff;
web_runner_tests::TestServer server;
FX_CHECK(server.FindAndBindPort());
auto serve = server.ServeAsync([&server] {
FX_LOGS(INFO) << "Waiting for HTTP request from Chromium";
ASSERT_TRUE(server.Accept()) << "Did not receive HTTP request from Chromium";
web_runner_tests::MockHttpGetResponse(&server, "static.html");
});
web_context()->Navigate(fxl::StringPrintf("http://localhost:%d/static.html", server.port()));
ExpectSolidColor(kTargetColor);
}
// Loads a dynamic page that starts with a Fuchsia background. This test verifies the initial color,
// taps on the view, and verifies that the color changed.
TEST_F(WebPixelTest, Dynamic) {
static constexpr uint32_t kBeforeColor = 0xffff00ff;
static constexpr uint32_t kAfterColor = 0xff40e0d0;
web_runner_tests::TestServer server;
FX_CHECK(server.FindAndBindPort());
auto serve = server.ServeAsync([&server] {
ASSERT_TRUE(server.Accept());
web_runner_tests::MockHttpGetResponse(&server, "dynamic.html");
});
web_context()->Navigate(fxl::StringPrintf("http://localhost:%d/dynamic.html", server.port()));
ExpectPrimaryColor(kBeforeColor);
Input({"tap", "500", "125"}); // centered in top quarter of screen
ExpectPrimaryColor(kAfterColor);
}
// Loads a static page with a video.
TEST_F(WebPixelTest, Video) {
web_runner_tests::TestServer server;
FX_CHECK(server.FindAndBindPort());
auto serve = server.ServeAsync([&server] {
FX_LOGS(INFO) << "Waiting for HTTP request from Chromium";
ASSERT_TRUE(server.Accept()) << "Did not receive HTTP request from Chromium";
web_runner_tests::MockHttpGetResponse(&server, "video.html");
web_runner_tests::MockHttpGetResponse(&server, "blackwhite_yuv420p.webm");
});
web_context()->Navigate(fxl::StringPrintf("http://localhost:%d/video.html", server.port()));
static constexpr uint32_t kBlackColor = 0xff010001;
static constexpr uint32_t kWhiteColor = 0xfffffeff;
static constexpr uint32_t kVideoBackgroundColor = 0xffff00ff;
std::map<uint32_t, size_t> histogram;
EXPECT_TRUE(
ScreenshotUntil([&histogram](fuchsia::ui::scenic::ScreenshotData screenshot, bool status) {
if (!status)
return false;
histogram = Histogram(screenshot);
return histogram[kBlackColor] > 0u;
}));
// We expect 240x240 <video> with black and white quadrants with grey on top. <video> background
// color should not be visible at all.
EXPECT_GT(histogram[kBlackColor], 10000u) << "Unexpected colors";
EXPECT_GT(histogram[kWhiteColor], 10000u) << "Unexpected colors";
EXPECT_EQ(histogram[kVideoBackgroundColor], 0u) << "Unexpected colors";
}
} // namespace
| 37.605556 | 100 | 0.698331 | [
"vector",
"solid"
] |
741ef8f25749353f1b1f437cbe4130905c5cdd3a | 396 | cpp | C++ | solutions/1024.video-stitching.321553631.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/1024.video-stitching.321553631.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/1024.video-stitching.321553631.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
int videoStitching(vector<vector<int>> &clips, int T) {
sort(clips.begin(), clips.end());
int n = clips.size();
int ans = 0;
for (int i = 0, start = 0, end = 0; start < T; ans++, start = end) {
while (i < n && clips[i][0] <= start)
end = max(end, clips[i++][1]);
if (end == start)
return -1;
}
return ans;
}
};
| 19.8 | 72 | 0.5 | [
"vector"
] |
742124cff8a89b51929f3f16f3b1878eef788830 | 22,571 | hpp | C++ | mmap_lib/include/mmap_str.hpp | bokket/livehd | 93d7533a6254cc404f58f54029d3106c19882743 | [
"BSD-3-Clause"
] | null | null | null | mmap_lib/include/mmap_str.hpp | bokket/livehd | 93d7533a6254cc404f58f54029d3106c19882743 | [
"BSD-3-Clause"
] | null | null | null | mmap_lib/include/mmap_str.hpp | bokket/livehd | 93d7533a6254cc404f58f54029d3106c19882743 | [
"BSD-3-Clause"
] | null | null | null | // This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <array>
#include <cstdint>
#include <string_view>
#include "mmap_map.hpp"
#define posShifter(s) s<4 ? (s-1):3
namespace mmap_lib {
class str {
protected:
// Keeping the code constexpr for small strings (not long) requires templates (A challenge but reasonable).
// Some references:
// https://github.com/tcsullivan/constexpr-to-string
// https://github.com/vesim987/constexpr_string/blob/master/constexpr_string.hpp
// https://github.com/vivkin/constexprhash/blob/master/constexprhash.h
// https://github.com/unterumarmung/fixed_string
// https://github.com/proxict/constexpr-string
// https://github.com/tonypilz/ConstexprString
//
// 16 bytes data structure:
//
// ptr_or_start:
// 10 "special" character (allow to encode 2 digits as 1 character when (c&0x80) is true)
// _size is the str _size (original not compressed)
//
// NOTE: Maybe it is faster/easier to have this instead:
//
// ptr_or_start
// 12 special characters
// if e[11]&0x80 || e[12]==0 -> overflow (ptr not start)
// end of string is first zero (or last e[11]&0x80)
//
// This avoid having a "size" in the costly str in-place data. The overflow
// can have a string size like a string_view does
//
// The only drawback is that to compute size, it needs to iterate over the e
// field, but asking size is not a common operation in LiveHD
uint32_t ptr_or_start; // 4 chars if _size < 14, is a ptr to string_map2 otherwise
std::array<char, 10> e; // last 10 "special <128" characters ending the string
uint16_t _size; // 2 bytes
constexpr bool is_digit(char c) const { return c >= '0' && c <= '9'; }
public:
//string_map2 <sv of long_str (key), and position in str_vec (val)>
static mmap_lib::map<std::string_view, uint32_t> string_map2;
// this holds all the raw data, (int kinda weird?)
inline static std::vector<int> string_vector; // ptr_or_start points here!
//===========constructor 1=========
template<std::size_t N, typename = std::enable_if_t<(N - 1) < 14>>
constexpr str(const char(&s)[N]): ptr_or_start(0), e{0}, _size(N-1) {
// if _size is less than 4, then whole string will be in ptr_or_start
auto stop = _size < 4 ? _size : 4;
// ptr_or_start will hold first 4 chars
// | first | second | third | forth |
// 31 23 15 7 0
for(auto i = 0; i < stop; ++i) {
ptr_or_start <<= 8;
ptr_or_start |= s[i];
}
auto e_pos = 0u; // e indx starts at 0
// stores rest of string in e, starting from stop to end
for(auto i = stop; i < N - 1; ++i) {
e[e_pos] = s[i];
++e_pos;
}
}
//=====helper function to check if a string exists in string_vector=====
std::pair<int, int> insertfind(const char *string_to_check, uint32_t size) {
std::string_view sv(string_to_check); // string to sv
// using substr here to take out all the weird things that come with sview
auto it = string_map2.find(sv.substr(0, size)); // find the sv in the string_map2
if (it == string_map2.end()) { // if we can't find the sv
//<std::string_view, uint32_t(position in vec)> string_map2
string_map2.set(sv.substr(0, size), string_vector.size()); // insert it
return std::make_pair(0,0);
} else {
return std::make_pair(string_map2.get(it), size); //found it, return
// pair is (ptr_or_start, size of string)
}
}
//==========constructor 2==========
template<std::size_t N, typename = std::enable_if_t<(N-1)>=14>, typename=void>
str(const char (&s)[N]) : ptr_or_start(0), e{0}, _size(N - 1) {
// the first two characters saved in e
e[0] = s[0]; e[1] = s[1];
// the last eight characters saved in e
for (int i = 0; i < 8; i++) { e[9 - i] = s[_size - 1 - i]; }
char long_str[_size-10]; // holds the long part
// filling long_str with long part of string
for (int i = 0; i < (_size - 10); ++i) { long_str[i] = s[i + 2]; }
// checking if long part of string already exists in vector
std::pair<int, int> pair = insertfind(long_str, _size - 10);
// if string exists in vector, get the ptr to it in string_map2
// pair is (position in string_map2, size of string)
if (pair.second) {
ptr_or_start = pair.first;
} else { // if string is not in vector, put it in vector
for (int i = 0; i < _size - 10; i++) {
string_vector.push_back(long_str[i]);
}
ptr_or_start = string_vector.size() - (_size - 10);
}
}
//============constructor 3=============
// const char * will go through this one
// implicit conversion from const char* --> string_view
//
// std::string will also go through this one
str(std::string_view sv) : ptr_or_start(0), e{0}, _size(sv.size()) {
if (_size < 14 ){ // constructor 1 logic
auto stop = _size<4?_size:4;
for(auto i=0;i<stop;++i) {
ptr_or_start <<= 8;
ptr_or_start |= sv.at(i);
}
auto e_pos = 0u;
for(auto i=stop;i<_size;++i) {
e[e_pos] = sv.at(i);
++e_pos;
}
} else { // constructor 2 logic
e[0] = sv.at(0);
e[1] = sv.at(1);
// the last eight characters
for (int i = 0; i < 8; i++) {
e[9-i] = sv.at(_size -1- i); //there is no null terminator in sv
}
// checking if it exists
char long_str[_size-10];
for (int i = 0; i < _size - 10; i++) {
long_str[i] = sv.at(i + 2);
}
std::pair<int, int> pair = insertfind(long_str, _size - 10);
if (pair.second) {
ptr_or_start = pair.first;
} else {
for (int i = 0; i < _size - 10; i++) {
string_vector.push_back(long_str[i]);
}
ptr_or_start = string_vector.size() - (_size-10);
}
}
}
void print_PoS () {
std::cout << "ptr_or_start is";
if (_size >= 14) {
std::cout << "(ptr): " << ptr_or_start << std::endl;
} else if (_size < 14) {
std::cout << "(start): ";
// [first] [sec] [thr] [fourth]
for (int i = 3; i >= 0; --i) {
std::cout << char(ptr_or_start >> (i * 8));
}
std::cout << std::endl;
}
}
void print_e () {
std::cout << "e is: [ ";
for (int i = 0; i < e.size(); ++i) { std::cout << e[i] << " "; }
std::cout << "]" << std::endl;
}
void print_StrVec () {
std::cout << "StrVec{ ";
for (std::vector<int>::const_iterator i = string_vector.begin(); i != string_vector.end(); ++i)
{
std::cout << char(*i) << " ";
}
std::cout << "}" << std::endl;
}
void print_StrMap () {
std::cout << "StrMap{ ";
for (auto it = string_map2.begin(), end = string_map2.end(); it != end; ++it) {
std::string key = std::string(string_map2.get_key(it));
uint32_t value = string_map2.get(it);
std::cout << "<" << key << ", " << value << "> ";
}
std::cout << "}" << std::endl;
}
void print_string() {
if (_size <= 13) {
uint8_t mx = posShifter(_size);
for (uint8_t i = mx; i >= 0, i <= 3; --i) {
std::cout << static_cast<char>((ptr_or_start >> (i*8)) & 0xff);
}
if (_size > 4) {
for (uint8_t j = 0; j < e.size(); ++j) {
std::cout << static_cast<char>(e[j]);
}
}
} else {
std::cout << char(e[0]) << char(e[1]);
for (auto i = 0; i < _size - 10; ++i) {
std::cout << static_cast<char>(string_vector.at(i + ptr_or_start));
}
for (uint8_t k = 2; k < 10; ++k) {
std::cout << static_cast<char>(e[k]);
}
}
}
#if 0
fixme_const_iterator begin() const {
for(const auto &ch:data.b) {
if (ch!=0)
return &ch;
}
if (size<16)
return &e[0];
return ptr;
}
fixme_const_iterator end() const {
if (size<16)
return &e[size-4];
for(const auto &ch:e) {
if (ch==0)
return &ch;
}
return e.end();}
#endif
[[nodiscard]] constexpr std::size_t size() const { return _size; }
[[nodiscard]] constexpr std::size_t length() const { return _size; }
[[nodiscard]] constexpr std::size_t max_size() const { return 65535; }
[[nodiscard]] constexpr bool empty() const { return 0 == _size; }
template <std::size_t N>
constexpr bool operator==(const char (&rhs)[N]) const {
auto rhs_size = N - 1;
if (_size != rhs_size) { return false; } // if size doesnt match, false
if (_size < 14) { return str(rhs) == *this; }
else if (_size >= 14) { // string_vector ptr in ptr_or_start, chars in e
if (e[0] != rhs[0] || e[1] != rhs[1]) { return false; } // check first two
uint8_t idx = 8;
for (auto i = 2; i < 10; ++i) {
if (e[i] != rhs[rhs_size - idx--]) { return false; } // check last eight
}
// Getting data from string_vector and comparing with rest of rhs
auto j = 2; // rhs[2 .. _size - 8] --> the long part
// for loop range: (ptr_or_start) .. (ptr_or_start + _size-10)
for (auto i = ptr_or_start; i < (ptr_or_start + _size - 10); ++i) {
if (string_vector.at(i) != rhs[j]) { return false; }
j = j < _size-8 ? j+1 : j;
}
return true;
}
return false;
}
// const char * will go through this one
// implicit conversion from const char* --> string_view
//
// std::string will also go through this one
constexpr bool operator==(std::string_view rhs) const {
auto rhs_size = rhs.size();
if (_size != rhs_size) { return false; } // if size doesnt match, false
if (_size < 14) { return str(rhs) == *this; }
else if (_size >= 14) { // string_vector ptr in ptr_or_start, chars in e
if (e[0] != rhs.at(0) || e[1] != rhs.at(1)) { return false; } // chk first two
uint8_t idx = 8;
for (auto i = 2; i < 10; ++i) {
if (e[i] != rhs.at(rhs_size - idx--)) { return false; } // chk last eight
}
// return if rhs w/out first two and last eight is in string_map2
return !(string_map2.find(rhs.substr(2, rhs_size-10)) == string_map2.end());
}
return false;
}
//constexpr bool operator==(const char* rhs) const { return *this == rhs; }
constexpr bool operator==(const str &rhs) const {
//1) compare size
//1) compare e
//2) compare ptr_or_start
if (_size != rhs._size) { return false; }
for (auto i = 0; i < e.size(); ++i) {
if (e[i] != rhs.e[i]) { return false; }
}
return (ptr_or_start == rhs.ptr_or_start);
}
constexpr bool operator!=(const str &rhs) const { return !(*this == rhs); }
template <std::size_t N>
constexpr bool operator!=(const char (&rhs)[N]) const { return !(*this == rhs); }
//constexpr bool operator!=(const char* rhs) const { return !(*this == rhs); }
constexpr bool operator!=(std::string_view rhs) const { return !(*this == rhs); }
constexpr char operator[](std::size_t pos) const {
#ifndef NDEBUG
if (pos >= _size)
throw std::out_of_range("");
#endif
if (_size < 14) {
if (pos < 4){
if(_size == 1) return (ptr_or_start >> (8 * (0 - pos))) & 0xFF;
if(_size == 2) return (ptr_or_start >> (8 * (1 - pos))) & 0xFF;
if(_size == 3) return (ptr_or_start >> (8 * (2 - pos))) & 0xFF;
return (ptr_or_start >> (8 * (3 - pos))) & 0xFF;
}else{
return e[pos - 4];
}
} else {
if(pos <2){
return e[pos];
} else if (pos >= (_size-8)) {
return e[10 -( _size - pos)];
} else{
return string_vector.at(ptr_or_start+pos-2);
}
}
}
// checks if *this pstr starts with st
bool starts_with(const str &st) const {
if (st._size > _size) { return false; }// st.size > *this.size, false
else if (st._size == _size) { return *this == st; }
else { // if (st._size < *this._size), compare
uint8_t mx = posShifter(_size);
uint8_t mx_st = posShifter(st._size);
if (_size <= 13) { //==== case 1: if *this is SHORT, st is SHORT
for (auto i = 0; i < st._size; ++i) { // iterate based on st
if (i < 4) { // for *this and st, first 4 will be in p_o_s
if (((st.ptr_or_start >> (mx_st*8)) & 0xff) != ((ptr_or_start >> (mx*8)) & 0xff)) {
return false;
} else { --mx_st; --mx; }
} else { // rest of string will be in e
if (e[i-4] != st.e[i-4]) { return false; }
}
}
return true;
} else if (_size > 13) { //==== case 2: if *this is LONG, st can be LONG or SHORT
uint32_t v_ptr = ptr_or_start;
uint8_t e_ptr = 0;
if (st._size <= 13) { //==== case 2a: *this is LONG, st is SHORT
for (auto i = 0; i < st._size; ++i) { //i refers to st index
if (i < 2) { // i = 0, 1 : *this.e is used, st.ptr_or_start is used
if (e[e_ptr] != ((st.ptr_or_start >> (mx_st*8)) & 0xff)) {
return false;
} else { --mx_st; ++e_ptr; }
} else if ((i >= 2) && (i < 4)) { // 1 = 2,3 *this uses vec, st uses p_o_s
if (string_vector.at(v_ptr) != ((st.ptr_or_start >> (mx_st*8)) & 0xff)) {
return false;
} else { --mx_st; ++v_ptr; }
} else { //i = 4..12 (max), *this uses vec/e, st uses e
// if we're done using string_vector, we use last 8 of e of *this
if ((v_ptr - ptr_or_start) >= (_size - 10)) {
if (e[e_ptr] != st.e[i - 4]) { return false; }
else { ++e_ptr; }
} else { // use e for st and use vector for *this
if (string_vector.at(v_ptr) != (st.e[i - 4])) { return false; }
else { ++v_ptr; }
}
}
}
return true; // made it out of the for loop means no mismatch
} else if (st._size > 13) { //==== case 2b: *this is LONG, st is LONG
uint8_t e_ptr = 2, ste_ptr = 2; // used to iterate through last 8 of e
uint32_t v_ptr = ptr_or_start, stv_ptr = st.ptr_or_start;
// NOTE: be careful when *this is still in vec, and st runs out of vec
for (auto i = 0; i < st._size; ++i) { // using st._size to iterate
if (i < 2) { // i = 0,1, for both use e
if (e[i] != st.e[i]) { return false; }
// i = 2..last 8, both uses vec, BUT st ALWAYS reaches e before *this
} else if ((i >= 2) && (i < (_size - 8))) {
// when st runs out of vector, need to use last 8 of e
if ((stv_ptr - st.ptr_or_start) >= (st._size - 10)) {
if (string_vector.at(v_ptr) != st.e[ste_ptr]) { return false; }
else { ++v_ptr; ++ste_ptr; }
} else { // use vec for both
if (string_vector.at(v_ptr) != string_vector.at(stv_ptr)) {
return false;
} else { ++v_ptr; ++stv_ptr; }
}
} else { // i = last 8 of st, *this could be in vec, st always in e
// if *this has reached last 8, we use e for *this
if ((v_ptr - ptr_or_start) >= (_size - 10)) {
if (e[e_ptr] != st.e[ste_ptr]) { return false; }
else { ++e_ptr; ++ste_ptr; }
} else { // use vec for *this, e for st
if (st.e[ste_ptr] != string_vector.at(v_ptr)) { return false; }
else { ++ste_ptr; ++v_ptr; }
}
}
}
return true;
}
}
return false;
}
}
// const char * and std::string will come thru here
bool starts_with(std::string_view st) const {
if (st.size() > _size) { return false; }
else if (st.size() == _size) { return *this == st; }
else if (st.size() == 0) { return true; }
else if (st.size() < _size) {
// Actual compare logic
auto fndsize = 0;
if (_size <= 13) {
uint8_t mx = posShifter(_size);
for (auto i = mx; i >= 0, i <= 3; --i) {
if (((ptr_or_start >> (i*8)) & 0xff) != st[fndsize++] ) {
return false;
}
if (fndsize == st.size()) { return true; }
}
for (uint8_t j = 0; j < e.size(); ++j) {
if (e[j] != st[fndsize++]) { return false; }
if (fndsize == st.size()) { return true; }
}
} else {
// compare first two of e
// then all the way up till _size-10
for (auto i = 0; i < 2; ++i) {
if (e[i] != st[i]) { return false; }
else {
++fndsize;
if (fndsize == st.size()) { return true; }
}
}
for (auto i = 0; i < _size-10; ++i) {
if (string_vector.at(ptr_or_start + i) != st[fndsize++]) {
return false;
}
if (fndsize == st.size()) { return true; }
}
for (uint8_t i = 2; i < 10; ++i) {
if (e[i] != st[fndsize++]) { return false; }
if (fndsize == st.size()) { return true; }
}
}
return false;
}
}
bool ends_with(const str &v) const;
bool ends_with(std::string_view sv) const;
bool ends_with(std::string s) const;
std::size_t find(const str &v, std::size_t pos = 0) const{
if (v._size >_size) return -1;
//if size ==vsize and == is true return 0 else return -1
if (_size<14){
char first = ((v.ptr_or_start >> (8 * (v._size-1))) & 0xFF);//different ways
size_t retval = 0;
bool found_flag = false;
int i,j,k;
int e_pos_self =0;
int e_pos_thier =0;
for ( i =0; i <4 ; i++){
retval = 0;
found_flag = false;
e_pos_self =0;
e_pos_thier =0;
if ((first == ((ptr_or_start >> (8 * (3 - i))) & 0xFF)) and ( pos >= i)) {
retval = i;
found_flag = true;
for ( j = i, k =1; j< 4; j++,k++){
if (((v.ptr_or_start >> (8 * (3 - k))) & 0xFF) != ((ptr_or_start >> (8 * (3 - j))) & 0xFF)){
found_flag = false;
break;
}
}
while(k < v._size){
if (k < 4){
if(((v.ptr_or_start >> (8 * (3 - k))) & 0xFF) != e[e_pos_self]) {
found_flag = false;
break;
}
} else {
if (v.e[e_pos_thier ] != e[e_pos_self]){
found_flag = false;
e_pos_thier++;
break;
}
}
e_pos_self++;
k++;
}
}
if (found_flag == true) return retval;
}
//if you havent found the string at this point and this string is < 4 chaars then find returns -1
//if((_size < 4 ) and (found_flag == false)) return -1;
return -1;
} else {
std::string my_string = this->to_s();
std::string their_string = v.to_s ();
return my_string.find(their_string);
}
}
std::size_t find(char c, std::size_t pos = 0) const;
template <std::size_t N>
constexpr std::size_t find(const char (&s)[N], std::size_t pos = 0) {
return find(str(s), pos);
}
std::size_t rfind(const str &v, std::size_t pos = 0) const;
std::size_t rfind(char c, std::size_t pos = 0) const;
std::size_t rfind(const char *s, std::size_t pos, std::size_t n) const;
std::size_t rfind(const char *s, std::size_t pos = 0) const;
// returns a pstr from two objects (pstr)
static str concat(const str &a, const str &b);
static str concat(std::string_view a, const str &b);
static str concat(const str &a, std::string_view b);
static str concat(const str &a, int v); // just puts two things together concat(x, b); -> x.append(b)
// concat(b, x); -> b.append(x)
str append(const str &b) const;
str append(std::string_view b) const;
str append(int b) const;
std::vector<str> split(const char chr); // used as a tokenizing func, return vector of pstr's
bool is_i() const{
if (_size < 14) {
char first = ((ptr_or_start >> (8 * (_size -1))) & 0xFF);
if (first !='-' and( first <'0' or first > '9')) {
return false;
}
for (int i= 1; i<(_size>4?4:_size);i++){
switch ((ptr_or_start >> (8 * (3 - i))) & 0xFF){
case '0'...'9':
break;
default:
return false;
break;
}
}
for (int i=0; i<(_size>4?_size-4:0);i++){
switch (e[i]){
case '0'...'9':
break;
default:
return false;
break;
}
}
} else {
char first = e[0];
if (first !='-' and( first <'0' or first > '9')) {
return false;
}
for (int i = 1;i<10 ; i++){
switch (e[i]){
case '0'...'9':
break;
default:
return false;
break;
}
}
for (int i = ptr_or_start ; i< _size-10;i++){
switch (string_vector.at(i)){
case '0'...'9':
break;
default:
return false;
break;
}
}
}
return true;
}
int64_t to_i() const; // convert to integer
std::string to_s() const{ // convert to string
std::string out;
if (_size <= 14 ){
//adding charactors from ptr_or_start based on the size of the string
for (int i =0; i<((_size>4) ? 4: _size); i++){
out += (ptr_or_start >> (8 * (3-i))) & 0xFF;
}
//if there are any characotrs in e, we add them as well
if(_size>4){
for(int i =0 ; i< (_size-4); i++){
out += e[i];
}
}
} else{
//adding the first two charactors
for (int i =0; i< 2; i++){
out += e[i];
}
//adding the middle section of the string from string vector
for (int i = ptr_or_start; i < (ptr_or_start + _size - 10); i++) {
out += string_vector.at(i);
}
//adding the last 8 charactors
for (int i = 2; i<10; i++){
out += e[i];
}
}
return out;
}
str get_str_after_last(const char chr) const;
str get_str_after_first(const char chr) const;
str get_str_before_last(const char chr) const;
str get_str_before_first(const char chr) const;
str substr(size_t start) const;
str substr(size_t start, size_t end) const;
};
// For static string_map
mmap_lib::map<std::string_view, uint32_t> str::string_map2;
} // namespace mmap_lib
| 34.459542 | 109 | 0.523592 | [
"vector"
] |
742603ae73ccdba9de7fcbcca2c64bfad0e8f196 | 30,016 | cpp | C++ | src/core/hw/gfxip/universalCmdBuffer.cpp | Zakhrov/pal | c5bf5ff777e90f143a9e5b59e485cb2169e29e79 | [
"MIT"
] | null | null | null | src/core/hw/gfxip/universalCmdBuffer.cpp | Zakhrov/pal | c5bf5ff777e90f143a9e5b59e485cb2169e29e79 | [
"MIT"
] | null | null | null | src/core/hw/gfxip/universalCmdBuffer.cpp | Zakhrov/pal | c5bf5ff777e90f143a9e5b59e485cb2169e29e79 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2015-2019 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#include "core/cmdAllocator.h"
#include "core/device.h"
#include "core/hw/gfxip/borderColorPalette.h"
#include "core/hw/gfxip/gfxDevice.h"
#include "core/hw/gfxip/graphicsPipeline.h"
#include "core/hw/gfxip/pipeline.h"
#include "core/hw/gfxip/universalCmdBuffer.h"
#include "core/gpuMemory.h"
#include "core/perfExperiment.h"
#include "core/platform.h"
#include "palDequeImpl.h"
#include "palMath.h"
#include <limits.h>
using namespace Util;
namespace Pal
{
// =====================================================================================================================
UniversalCmdBuffer::UniversalCmdBuffer(
const GfxDevice& device,
const CmdBufferCreateInfo& createInfo,
GfxCmdStream* pDeCmdStream,
GfxCmdStream* pCeCmdStream,
bool blendOptEnable)
:
GfxCmdBuffer(device, createInfo),
m_device(device),
m_pDeCmdStream(pDeCmdStream),
m_pCeCmdStream(pCeCmdStream),
m_blendOptEnable(blendOptEnable)
#if PAL_ENABLE_PRINTS_ASSERTS
, m_graphicsStateIsPushed(false)
#endif
{
PAL_ASSERT(createInfo.queueType == QueueTypeUniversal);
memset(&m_computeState, 0, sizeof(m_computeState));
memset(&m_computeRestoreState, 0, sizeof(m_computeRestoreState));
memset(&m_graphicsState, 0, sizeof(m_graphicsState));
memset(&m_graphicsRestoreState, 0, sizeof(m_graphicsRestoreState));
memset(&m_blendOpts[0], 0, sizeof(m_blendOpts));
SwitchCmdSetUserDataFunc(PipelineBindPoint::Compute, &GfxCmdBuffer::CmdSetUserDataCs);
SwitchCmdSetUserDataFunc(PipelineBindPoint::Graphics, &CmdSetUserDataGfx<true>);
}
// =====================================================================================================================
// Resets the command buffer's previous contents and state, then puts it into a building state allowing new commands
// to be recorded.
// Also starts command buffer dumping, if it is enabled.
Result UniversalCmdBuffer::Begin(
const CmdBufferBuildInfo& info)
{
Result result = GfxCmdBuffer::Begin(info);
if (info.pInheritedState != nullptr)
{
m_graphicsState.inheritedState = *(info.pInheritedState);
}
#if PAL_ENABLE_PRINTS_ASSERTS
if ((result == Result::Success) && (IsDumpingEnabled()))
{
char filename[MaxFilenameLength] = {};
// filename is: computexx_yyyyy, where "xx" is the number of universal command buffers that have been created
// so far (one based) and "yyyyy" is the number of times this command buffer has been begun (also
// one based).
//
// All streams associated with this command buffer are included in this one file.
Snprintf(filename, MaxFilenameLength, "universal%02d_%05d", UniqueId(), NumBegun());
OpenCmdBufDumpFile(&filename[0]);
}
#endif
return result;
}
// =====================================================================================================================
// Puts the command streams into a state that is ready for command building.
Result UniversalCmdBuffer::BeginCommandStreams(
CmdStreamBeginFlags cmdStreamFlags,
bool doReset)
{
Result result = GfxCmdBuffer::BeginCommandStreams(cmdStreamFlags, doReset);
if (doReset)
{
m_pDeCmdStream->Reset(nullptr, true);
m_pCeCmdStream->Reset(nullptr, true);
}
if (result == Result::Success)
{
result = m_pDeCmdStream->Begin(cmdStreamFlags, m_pMemAllocator);
}
if (result == Result::Success)
{
result = m_pCeCmdStream->Begin(cmdStreamFlags, m_pMemAllocator);
}
return result;
}
// =====================================================================================================================
// Completes recording of a command buffer in the building state, making it executable.
// Also ends command buffer dumping, if it is enabled.
Result UniversalCmdBuffer::End()
{
// Amoung other things, this will add the postamble. Be sure to add this before ending the command streams so that
// they get padded correctly.
Result result = GfxCmdBuffer::End();
if (result == Result::Success)
{
result = m_pDeCmdStream->End();
}
if (result == Result::Success)
{
result = m_pCeCmdStream->End();
}
if (result == Result::Success)
{
m_graphicsState.leakFlags.u32All |= m_graphicsState.dirtyFlags.u32All;
#if PAL_ENABLE_PRINTS_ASSERTS
if (IsDumpingEnabled() && DumpFile()->IsOpen())
{
if (m_device.Parent()->Settings().cmdBufDumpFormat == CmdBufDumpFormatBinaryHeaders)
{
const CmdBufferDumpFileHeader fileHeader =
{
static_cast<uint32>(sizeof(CmdBufferDumpFileHeader)), // Structure size
1, // Header version
m_device.Parent()->ChipProperties().familyId, // ASIC family
m_device.Parent()->ChipProperties().eRevId, // ASIC revision
0 // Reserved
};
DumpFile()->Write(&fileHeader, sizeof(fileHeader));
CmdBufferListHeader listHeader =
{
static_cast<uint32>(sizeof(CmdBufferListHeader)), // Structure size
0, // Engine index
0 // Number of command buffer chunks
};
listHeader.count = m_pDeCmdStream->GetNumChunks() + m_pCeCmdStream->GetNumChunks();
DumpFile()->Write(&listHeader, sizeof(listHeader));
}
DumpCmdStreamsToFile(DumpFile(), m_device.Parent()->Settings().cmdBufDumpFormat);
DumpFile()->Close();
}
#endif
}
return result;
}
// =====================================================================================================================
// Explicitly resets a command buffer, releasing any internal resources associated with it and putting it in the reset
// state.
Result UniversalCmdBuffer::Reset(
ICmdAllocator* pCmdAllocator,
bool returnGpuMemory)
{
Result result = GfxCmdBuffer::Reset(pCmdAllocator, returnGpuMemory);
if (result == Result::Success)
{
m_pDeCmdStream->Reset(static_cast<CmdAllocator*>(pCmdAllocator), returnGpuMemory);
m_pCeCmdStream->Reset(static_cast<CmdAllocator*>(pCmdAllocator), returnGpuMemory);
}
// Command buffers initialize blend opts to default based on setting.
// This must match default settings in Pal::ColorTargetView
for (uint32 idx = 0; idx < MaxColorTargets; ++idx)
{
if (m_blendOptEnable)
{
m_blendOpts[idx].dontRdDst = GfxBlendOptimizer::BlendOpt::ForceOptAuto;
m_blendOpts[idx].discardPixel = GfxBlendOptimizer::BlendOpt::ForceOptAuto;
}
else
{
m_blendOpts[idx].dontRdDst = GfxBlendOptimizer::BlendOpt::ForceOptDisable;
m_blendOpts[idx].discardPixel = GfxBlendOptimizer::BlendOpt::ForceOptDisable;
}
}
PAL_ASSERT(result == Result::Success);
return result;
}
// =====================================================================================================================
// Resets all of the state tracked by this command buffer
void UniversalCmdBuffer::ResetState()
{
GfxCmdBuffer::ResetState();
memset(&m_computeState, 0, sizeof(m_computeState));
memset(&m_graphicsState, 0, sizeof(m_graphicsState));
// Clear the pointer to the performance experiment object currently used by this command buffer.
m_pCurrentExperiment = nullptr;
// NULL color target will only be bound if the slot was not NULL and is being set to NULL. Use a value of all 1s
// so NULL color targets will be bound when BuildNullColorTargets() is called for the first time.
m_graphicsState.boundColorTargetMask = NoNullColorTargetMask;
if (IsNested() == false)
{
// Fully open scissor by default
m_graphicsState.targetExtent.width = MaxScissorExtent;
m_graphicsState.targetExtent.height = MaxScissorExtent;
}
else
{
// For nested case, default to an invalid value to trigger validation if BindTarget called.
static_assert(static_cast<uint16>(USHRT_MAX) > static_cast<uint16>(MaxScissorExtent), "Check Scissor logic");
m_graphicsState.targetExtent.width = USHRT_MAX;
m_graphicsState.targetExtent.height = USHRT_MAX;
}
m_graphicsState.clipRectsState.clipRule = DefaultClipRectsRule;
}
// =====================================================================================================================
void UniversalCmdBuffer::CmdBindPipeline(
const PipelineBindParams& params)
{
if (params.pipelineBindPoint == PipelineBindPoint::Compute)
{
m_computeState.dynamicCsInfo = params.cs;
m_computeState.pipelineState.pPipeline = static_cast<const Pipeline*>(params.pPipeline);
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 471
m_computeState.pipelineState.apiPsoHash = params.apiPsoHash;
#endif
m_computeState.pipelineState.dirtyFlags.pipelineDirty = 1;
}
else
{
m_graphicsState.dynamicGraphicsInfo = params.graphics;
m_graphicsState.pipelineState.pPipeline = static_cast<const Pipeline*>(params.pPipeline);
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 471
m_graphicsState.pipelineState.apiPsoHash = params.apiPsoHash;
#endif
m_graphicsState.pipelineState.dirtyFlags.pipelineDirty = 1;
}
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 471
m_device.DescribeBindPipeline(this, params.pPipeline, params.apiPsoHash, params.pipelineBindPoint);
#endif
}
// =====================================================================================================================
// CmdSetUserData callback which updates the tracked user-data entries for the graphics state.
template <bool filterRedundantUserData>
void PAL_STDCALL UniversalCmdBuffer::CmdSetUserDataGfx(
ICmdBuffer* pCmdBuffer,
uint32 firstEntry,
uint32 entryCount,
const uint32* pEntryValues)
{
PAL_ASSERT((pCmdBuffer != nullptr) && (entryCount != 0) && (pEntryValues != nullptr));
auto*const pSelf = static_cast<UniversalCmdBuffer*>(pCmdBuffer);
auto*const pEntries = &pSelf->m_graphicsState.gfxUserDataEntries;
UserDataArgs userDataArgs;
userDataArgs.firstEntry = firstEntry;
userDataArgs.entryCount = entryCount;
userDataArgs.pEntryValues = pEntryValues;
if ((filterRedundantUserData == false) || pSelf->FilterSetUserDataGfx(&userDataArgs))
{
if (userDataArgs.entryCount == 1)
{
WideBitfieldSetBit(pEntries->touched, userDataArgs.firstEntry);
WideBitfieldSetBit(pEntries->dirty, userDataArgs.firstEntry);
pEntries->entries[userDataArgs.firstEntry] = userDataArgs.pEntryValues[0];
}
else
{
const uint32 entryLimit = (userDataArgs.firstEntry + userDataArgs.entryCount);
for (uint32 e = userDataArgs.firstEntry; e < entryLimit ; ++e)
{
WideBitfieldSetBit(pEntries->touched, e);
WideBitfieldSetBit(pEntries->dirty, e);
}
memcpy(&pEntries->entries[userDataArgs.firstEntry],
userDataArgs.pEntryValues,
(sizeof(uint32) * userDataArgs.entryCount));
}
} // if (filtering is disabled OR user data not redundant)
}
// Instantiate templates for the linker.
template
void PAL_STDCALL UniversalCmdBuffer::CmdSetUserDataGfx<false>(
ICmdBuffer* pCmdBuffer,
uint32 firstEntry,
uint32 entryCount,
const uint32* pEntryValues);
template
void PAL_STDCALL UniversalCmdBuffer::CmdSetUserDataGfx<true>(
ICmdBuffer* pCmdBuffer,
uint32 firstEntry,
uint32 entryCount,
const uint32* pEntryValues);
// =====================================================================================================================
// Compares the client-specified user data update parameters against the current user data values, and filters any
// redundant updates at the beginning of ending of the range. Filtering redundant values in the middle of the range
// would involve significant updates to the rest of PAL, and we typically expect a good hit rate for redundant updates
// at the beginning or end. The most common updates are setting 2-dword addresses (best hit rate on high bits) and
// 4-dword buffer SRDs (best hit rate on last dword).
//
// Returns true if there are still entries that should be processed after filtering. False means that the entire set
// is redundant.
bool UniversalCmdBuffer::FilterSetUserDataGfx(
UserDataArgs* pUserDataArgs)
{
uint32 firstEntry = pUserDataArgs->firstEntry;
uint32 entryCount = pUserDataArgs->entryCount;
const uint32* pEntryValues = pUserDataArgs->pEntryValues;
// Adjust the start entry and entry value pointer for any redundant entries found at the beginning of the range.
while ((entryCount > 0) &&
(*pEntryValues == m_graphicsState.gfxUserDataEntries.entries[firstEntry]) &&
WideBitfieldIsSet(m_graphicsState.gfxUserDataEntries.touched, firstEntry))
{
firstEntry++;
pEntryValues++;
entryCount--;
}
bool result = false;
if (entryCount > 0)
{
// Search from the end of the range for the last non-redundant entry. We are guaranteed to find one since the
// earlier loop found at least one non-redundant entry.
uint32 idx = entryCount - 1;
while ((pEntryValues[idx] == m_graphicsState.gfxUserDataEntries.entries[firstEntry + idx]) &&
WideBitfieldIsSet(m_graphicsState.gfxUserDataEntries.touched, firstEntry + idx))
{
idx--;
}
// Update the caller's values.
pUserDataArgs->firstEntry = firstEntry;
pUserDataArgs->entryCount = idx + 1;
pUserDataArgs->pEntryValues = pEntryValues;
result = true;
}
return result;
}
// =====================================================================================================================
// Updates the given stencil state ref and masks params based on the flags set in StencilRefMaskParams
void UniversalCmdBuffer::SetStencilRefMasksState(
const StencilRefMaskParams& updatedRefMaskState, // [in] Updated state
StencilRefMaskParams* pStencilRefMaskState) // [out] State to be set
{
if (updatedRefMaskState.flags.u8All == 0xFF)
{
*pStencilRefMaskState = updatedRefMaskState;
}
else
{
if (updatedRefMaskState.flags.updateFrontOpValue)
{
pStencilRefMaskState->flags.updateFrontOpValue = 1;
pStencilRefMaskState->frontOpValue = updatedRefMaskState.frontOpValue;
}
if (updatedRefMaskState.flags.updateFrontRef)
{
pStencilRefMaskState->flags.updateFrontRef = 1;
pStencilRefMaskState->frontRef = updatedRefMaskState.frontRef;
}
if (updatedRefMaskState.flags.updateFrontReadMask)
{
pStencilRefMaskState->flags.updateFrontReadMask = 1;
pStencilRefMaskState->frontReadMask = updatedRefMaskState.frontReadMask;
}
if (updatedRefMaskState.flags.updateFrontWriteMask)
{
pStencilRefMaskState->flags.updateFrontWriteMask = 1;
pStencilRefMaskState->frontWriteMask = updatedRefMaskState.frontWriteMask;
}
if (updatedRefMaskState.flags.updateBackOpValue)
{
pStencilRefMaskState->flags.updateBackOpValue = 1;
pStencilRefMaskState->backOpValue = updatedRefMaskState.backOpValue;
}
if (updatedRefMaskState.flags.updateBackRef)
{
pStencilRefMaskState->flags.updateBackRef = 1;
pStencilRefMaskState->backRef = updatedRefMaskState.backRef;
}
if (updatedRefMaskState.flags.updateBackReadMask)
{
pStencilRefMaskState->flags.updateBackReadMask = 1;
pStencilRefMaskState->backReadMask = updatedRefMaskState.backReadMask;
}
if (updatedRefMaskState.flags.updateBackWriteMask)
{
pStencilRefMaskState->flags.updateBackWriteMask = 1;
pStencilRefMaskState->backWriteMask = updatedRefMaskState.backWriteMask;
}
}
}
// =====================================================================================================================
// Binds an index buffer to this command buffer for use.
void UniversalCmdBuffer::CmdBindIndexData(
gpusize gpuAddr,
uint32 indexCount,
IndexType indexType)
{
PAL_ASSERT(IsPow2Aligned(gpuAddr, (1ull << static_cast<uint64>(indexType))));
PAL_ASSERT((indexType == IndexType::Idx8) || (indexType == IndexType::Idx16) || (indexType == IndexType::Idx32));
// Update the currently active index buffer state.
m_graphicsState.iaState.indexAddr = gpuAddr;
m_graphicsState.iaState.indexCount = indexCount;
m_graphicsState.iaState.indexType = indexType;
m_graphicsState.dirtyFlags.nonValidationBits.iaState = 1;
}
// =====================================================================================================================
void UniversalCmdBuffer::CmdSetViewInstanceMask(
uint32 mask)
{
m_graphicsState.viewInstanceMask = mask;
}
// =====================================================================================================================
// Sets parameters controlling line stippling.
void UniversalCmdBuffer::CmdSetLineStippleState(
const LineStippleStateParams& params)
{
m_graphicsState.lineStippleState = params;
m_graphicsState.dirtyFlags.validationBits.lineStippleState = 1;
}
#if PAL_ENABLE_PRINTS_ASSERTS
// =====================================================================================================================
// Dumps this command buffer's DE and CE command streams to the given file with an appropriate header.
void UniversalCmdBuffer::DumpCmdStreamsToFile(
File* pFile,
CmdBufDumpFormat mode
) const
{
m_pDeCmdStream->DumpCommands(pFile, "# Universal Queue - DE Command length = ", mode);
m_pCeCmdStream->DumpCommands(pFile, "# Universal Queue - CE Command length = ", mode);
}
#endif
// =====================================================================================================================
// Copies the currently bound state to m_graphicsRestoreState. This cannot be called again until PopGraphicsState is
// called.
void UniversalCmdBuffer::PushGraphicsState()
{
#if PAL_ENABLE_PRINTS_ASSERTS
PAL_ASSERT(m_graphicsStateIsPushed == false);
m_graphicsStateIsPushed = true;
#endif
m_graphicsRestoreState = m_graphicsState;
memset(&m_graphicsState.gfxUserDataEntries.touched[0], 0, sizeof(m_graphicsState.gfxUserDataEntries.touched));
if (m_pCurrentExperiment != nullptr)
{
// Inform the performance experiment that we're starting some internal operations.
m_pCurrentExperiment->BeginInternalOps(m_pDeCmdStream);
}
}
// =====================================================================================================================
// Restores the last saved to m_graphicsRestoreState, rebinding all objects as necessary.
void UniversalCmdBuffer::PopGraphicsState()
{
#if PAL_ENABLE_PRINTS_ASSERTS
PAL_ASSERT(m_graphicsStateIsPushed);
m_graphicsStateIsPushed = false;
#endif
// Note: Vulkan does allow blits in nested command buffers, but they do not support inheriting user-data values
// from the caller. Therefore, simply "setting" the restored-state's user-data is sufficient, just like it is
// in a root command buffer. (If Vulkan decides to support user-data inheritance in a later API version, we'll
// need to revisit this!)
SetGraphicsState(m_graphicsRestoreState);
// All RMP GFX Blts should push/pop command buffer's graphics state,
// so this is a safe opprotunity to mark that a GFX Blt is active
SetGfxCmdBufGfxBltState(true);
SetGfxCmdBufGfxBltWriteCacheState(true);
if (m_pCurrentExperiment != nullptr)
{
// Inform the performance experiment that we've finished some internal operations.
m_pCurrentExperiment->EndInternalOps(m_pDeCmdStream);
}
}
// =====================================================================================================================
// Set all specified state on this command buffer.
void UniversalCmdBuffer::SetGraphicsState(
const GraphicsState& newGraphicsState)
{
const auto& pipelineState = newGraphicsState.pipelineState;
if (pipelineState.pPipeline != m_graphicsState.pipelineState.pPipeline)
{
PipelineBindParams bindParams = {};
bindParams.pipelineBindPoint = PipelineBindPoint::Graphics;
bindParams.pPipeline = pipelineState.pPipeline;
bindParams.graphics = newGraphicsState.dynamicGraphicsInfo;
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 471
bindParams.apiPsoHash = pipelineState.apiPsoHash;
#endif
CmdBindPipeline(bindParams);
}
if (pipelineState.pBorderColorPalette != m_graphicsState.pipelineState.pBorderColorPalette)
{
CmdBindBorderColorPalette(PipelineBindPoint::Graphics, pipelineState.pBorderColorPalette);
}
m_graphicsState.gfxUserDataEntries = newGraphicsState.gfxUserDataEntries;
for (uint32 i = 0; i < NumUserDataFlagsParts; ++i)
{
m_graphicsState.gfxUserDataEntries.dirty[i] |= newGraphicsState.gfxUserDataEntries.touched[i];
}
}
// =====================================================================================================================
Pal::PipelineState* UniversalCmdBuffer::PipelineState(
PipelineBindPoint bindPoint)
{
PAL_ASSERT((bindPoint == PipelineBindPoint::Compute) || (bindPoint == PipelineBindPoint::Graphics));
return (bindPoint == PipelineBindPoint::Compute) ? &m_computeState.pipelineState : &m_graphicsState.pipelineState;
}
// =====================================================================================================================
// Helper method for handling the state "leakage" from a nested command buffer back to its caller. Since the callee has
// tracked its own state during the building phase, we can access the final state of the command buffer since its stored
// in the UniversalCmdBuffer object itself.
void UniversalCmdBuffer::LeakNestedCmdBufferState(
const UniversalCmdBuffer& cmdBuffer) // [in] Nested command buffer whose state we're absorbing.
{
LeakPerPipelineStateChanges(cmdBuffer.m_computeState.pipelineState,
cmdBuffer.m_computeState.csUserDataEntries,
&m_computeState.pipelineState,
&m_computeState.csUserDataEntries);
LeakPerPipelineStateChanges(cmdBuffer.m_graphicsState.pipelineState,
cmdBuffer.m_graphicsState.gfxUserDataEntries,
&m_graphicsState.pipelineState,
&m_graphicsState.gfxUserDataEntries);
const GraphicsState& graphics = cmdBuffer.m_graphicsState;
if (graphics.pColorBlendState != nullptr)
{
m_graphicsState.pColorBlendState = graphics.pColorBlendState;
}
if (graphics.pDepthStencilState != nullptr)
{
m_graphicsState.pDepthStencilState = graphics.pDepthStencilState;
}
if (graphics.pMsaaState != nullptr)
{
m_graphicsState.pMsaaState = graphics.pMsaaState;
}
if (graphics.pipelineState.pPipeline != nullptr)
{
m_graphicsState.enableMultiViewport = graphics.enableMultiViewport;
m_graphicsState.everUsedMultiViewport |= graphics.everUsedMultiViewport;
}
if (graphics.leakFlags.validationBits.colorTargetView != 0)
{
memcpy(&m_graphicsState.bindTargets.colorTargets[0],
&graphics.bindTargets.colorTargets[0],
sizeof(m_graphicsState.bindTargets.colorTargets));
m_graphicsState.bindTargets.colorTargetCount = graphics.bindTargets.colorTargetCount;
m_graphicsState.targetExtent.value = graphics.targetExtent.value;
}
if (graphics.leakFlags.validationBits.depthStencilView != 0)
{
m_graphicsState.bindTargets.depthTarget = graphics.bindTargets.depthTarget;
m_graphicsState.targetExtent.value = graphics.targetExtent.value;
}
if (graphics.leakFlags.nonValidationBits.streamOutTargets != 0)
{
m_graphicsState.bindStreamOutTargets = graphics.bindStreamOutTargets;
}
if (graphics.leakFlags.nonValidationBits.iaState != 0)
{
m_graphicsState.iaState = graphics.iaState;
}
if (graphics.leakFlags.validationBits.inputAssemblyState != 0)
{
m_graphicsState.inputAssemblyState = graphics.inputAssemblyState;
}
if (graphics.leakFlags.nonValidationBits.blendConstState != 0)
{
m_graphicsState.blendConstState = graphics.blendConstState;
}
if (graphics.leakFlags.nonValidationBits.depthBiasState != 0)
{
m_graphicsState.depthBiasState = graphics.depthBiasState;
}
if (graphics.leakFlags.nonValidationBits.depthBoundsState != 0)
{
m_graphicsState.depthBoundsState = graphics.depthBoundsState;
}
if (graphics.leakFlags.nonValidationBits.pointLineRasterState != 0)
{
m_graphicsState.pointLineRasterState = graphics.pointLineRasterState;
}
if (graphics.leakFlags.nonValidationBits.stencilRefMaskState != 0)
{
m_graphicsState.stencilRefMaskState = graphics.stencilRefMaskState;
}
if (graphics.leakFlags.validationBits.triangleRasterState != 0)
{
m_graphicsState.triangleRasterState = graphics.triangleRasterState;
}
if (graphics.leakFlags.validationBits.viewports != 0)
{
m_graphicsState.viewportState = graphics.viewportState;
}
if (graphics.leakFlags.validationBits.scissorRects != 0)
{
m_graphicsState.scissorRectState = graphics.scissorRectState;
}
if (graphics.leakFlags.nonValidationBits.globalScissorState != 0)
{
m_graphicsState.globalScissorState = graphics.globalScissorState;
}
if (graphics.leakFlags.nonValidationBits.clipRectsState != 0)
{
m_graphicsState.clipRectsState = graphics.clipRectsState;
}
m_graphicsState.viewInstanceMask = graphics.viewInstanceMask;
m_graphicsState.dirtyFlags.u32All |= graphics.leakFlags.u32All;
memcpy(&m_blendOpts[0], &cmdBuffer.m_blendOpts[0], sizeof(m_blendOpts));
// It is not expected that nested command buffers will use performance experiments.
PAL_ASSERT(cmdBuffer.m_pCurrentExperiment == nullptr);
}
// =====================================================================================================================
// Returns a pointer to the command stream specified by "cmdStreamIdx".
const CmdStream* UniversalCmdBuffer::GetCmdStream(
uint32 cmdStreamIdx
) const
{
PAL_ASSERT(cmdStreamIdx < NumCmdStreams());
CmdStream* pStream = nullptr;
// CE command stream index < DE command stream index so CE will be launched before the DE.
// DE cmd stream index > all others because CmdBuffer::End() uses
// GetCmdStream(NumCmdStreams() - 1) to get a "root" chunk.
switch (cmdStreamIdx)
{
case 0:
pStream = m_pCeCmdStream;
break;
case 1:
pStream = m_pDeCmdStream;
break;
}
PAL_ASSERT(pStream != nullptr);
return pStream;
}
// =====================================================================================================================
uint32 UniversalCmdBuffer::GetUsedSize(
CmdAllocType type
) const
{
uint32 sizeInBytes = GfxCmdBuffer::GetUsedSize(type);
if (type == CommandDataAlloc)
{
sizeInBytes += (m_pDeCmdStream->GetUsedCmdMemorySize() + m_pCeCmdStream->GetUsedCmdMemorySize());
}
return sizeInBytes;
}
} // Pal
| 39.494737 | 120 | 0.625466 | [
"object"
] |
742c4d1a17f02a860e6d5a95868e660c3d8db4e3 | 4,113 | cpp | C++ | src/robustness.cpp | zju3dv/eval-vislam | 03ad90dc97a50149045f7c426f5e63ee5b34bd80 | [
"Apache-2.0"
] | 112 | 2019-04-01T01:39:56.000Z | 2022-03-31T06:14:40.000Z | src/robustness.cpp | zju3dv/eval-vislam | 03ad90dc97a50149045f7c426f5e63ee5b34bd80 | [
"Apache-2.0"
] | 11 | 2019-04-29T02:39:29.000Z | 2022-01-11T04:00:08.000Z | src/robustness.cpp | zju3dv/eval-vislam | 03ad90dc97a50149045f7c426f5e63ee5b34bd80 | [
"Apache-2.0"
] | 25 | 2019-04-24T02:45:45.000Z | 2021-12-27T03:41:22.000Z | #include "benchmark.h"
#include <cmath>
using namespace benchmark;
int main(int argc, char *argv[]) {
if (argc != 4) {
fputs("Usage:\n robustness <groundtruth> <input> <fix scale>", stderr);
return EXIT_FAILURE;
}
std::string dataset_root(argv[1]);
std::string input_filename(argv[2]);
bool fix_scale = false;
if (argc == 3) {
fix_scale = false;
} else {
fix_scale = (std::atoi(argv[3]) != 0);
}
CameraDataset cam_dataset;
ImuDataset imu_dataset;
ViconDataset vic_dataset;
cam_dataset.load(dataset_root + "/camera");
imu_dataset.load(dataset_root + "/imu");
vic_dataset.load(dataset_root + "/groundtruth"); // gt has same format to vicon
auto [gt_trajectory, in_trajectory] = get_synchronized_data(input_filename, vic_dataset, cam_dataset, imu_dataset);
std::vector<vector<3>> gt_positions, in_positions;
for (size_t i = 0; i < in_trajectory.size(); ++i) {
const PoseData >_pose = gt_trajectory[i];
const PoseData &in_pose = in_trajectory[i];
if (is_valid_pose(in_pose)) {
gt_positions.push_back(gt_pose.p);
in_positions.push_back(in_pose.p);
}
}
auto [sg, qg, tg] = umeyama(gt_positions, in_positions, fix_scale);
for (size_t i = 0; i < in_positions.size(); ++i) {
in_positions[i] = (qg * in_positions[i] + tg) / sg;
}
double ape = 0, Acount = 0;
for (size_t i = 0; i < in_positions.size(); ++i) {
vector<3> p_error = in_positions[i] - gt_positions[i];
ape += p_error.squaredNorm();
Acount++;
}
Acount = std::max(Acount, 1.0);
ape = sqrt(ape / Acount) * 1e3;
size_t lost_count = 0;
std::vector<std::vector<PoseData>> gt_segments, in_segments;
gt_segments.emplace_back();
in_segments.emplace_back();
for (size_t i = 0; i < in_trajectory.size(); ++i) {
const PoseData >_pose = gt_trajectory[i];
const PoseData &in_pose = in_trajectory[i];
if (is_valid_pose(in_pose)) {
gt_segments.back().push_back(gt_pose);
in_segments.back().push_back(in_pose);
} else {
lost_count++;
if (!in_segments.back().empty()) {
gt_segments.emplace_back();
in_segments.emplace_back();
}
}
}
double lost_ratio = lost_count / (double)in_trajectory.size() * 1e2;
std::vector<std::tuple<double, quaternion, vector<3>>> similarities;
for (size_t i = 0; i < in_segments.size(); ++i) {
const std::vector<PoseData> >_segment = gt_segments[i];
const std::vector<PoseData> &in_segment = in_segments[i];
std::vector<vector<3>> gt_positions, in_positions;
for (size_t j = 0; j < in_segment.size(); ++j) {
gt_positions.push_back(gt_segment[j].p);
in_positions.push_back(in_segment[j].p);
}
similarities.emplace_back(umeyama(gt_positions, in_positions, fix_scale));
}
double relocalization_error = 0;
for (size_t j = 1; j < similarities.size(); ++j) {
auto Si = similarities[j - 1];
auto Sj = similarities[j];
double s_diff = std::get<0>(Si) - std::get<0>(Sj);
if (std::isnan(s_diff)) continue; // not enough poses for umeyama
vector<3> q_diff = logmap(std::get<1>(Si).conjugate() * std::get<1>(Sj));
vector<3> t_diff = std::get<2>(Si) - std::get<2>(Sj);
double local_reloc_err = sqrt(s_diff * s_diff + q_diff.squaredNorm() + t_diff.squaredNorm());
if (std::isnan(local_reloc_err)) continue;
relocalization_error += local_reloc_err;
}
double robustness = (lost_ratio + 5) / 100.0 * (relocalization_error + 0.1 * ape);
const double sigma_robustness = fix_scale ? 0.95 : 2.27;
printf("lost ratio: %.3f%%\nreloc error: %.3f\nAPE: %.3f [mm]\nrobustness: %.3f\nScore: %.4f\n",
lost_ratio,
relocalization_error,
ape,
robustness,
compute_score(robustness, sigma_robustness));
return EXIT_SUCCESS;
}
| 36.723214 | 119 | 0.60248 | [
"vector"
] |
742da9d6d877dd78ce7947cf6d311a177c3d4165 | 2,403 | cpp | C++ | dev/Gems/CryLegacy/Code/Source/CryAction/GameConfigPhysicsSettings.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/CryLegacy/Code/Source/CryAction/GameConfigPhysicsSettings.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/CryLegacy/Code/Source/CryAction/GameConfigPhysicsSettings.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "CryLegacy_precompiled.h"
#include "GameConfigPhysicsSettings.h"
#include "ISystem.h"
#include <stdio.h>
#include <cstdlib>
#include <AzFramework/StringFunc/StringFunc.h>
void GameConfigPhysicsSettings::Init()
{
REGISTER_STRING("collision_classes", "", 0, "Specifies collision classes");
ICVar* collisionClassesVar = gEnv->pConsole->GetCVar("collision_classes");
if (collisionClassesVar == nullptr)
{
CRY_ASSERT_MESSAGE(false, "collision_classes cvar could not be found");
return;
}
AZStd::vector<AZStd::string> collisionClassPairList;
AzFramework::StringFunc::Tokenize(collisionClassesVar->GetString(), collisionClassPairList, ",");
CRY_ASSERT_MESSAGE(collisionClassPairList.size() <= IGamePhysicsSettings::kNumCollisionClasses, "Too many collision classes specified in config file");
AZStd::vector<AZStd::string> collisionClassPair;
collisionClassPair.reserve(2);
for (size_t i = 0; i < collisionClassPairList.size() && i < IGamePhysicsSettings::kNumCollisionClasses; ++i)
{
AzFramework::StringFunc::Tokenize(collisionClassPairList[i].c_str(), collisionClassPair, "=");
if (collisionClassPair.size() >= 2)
{
int bitIndex = std::atoi(collisionClassPair[1].c_str());
CRY_ASSERT_MESSAGE(bitIndex >= 0 && bitIndex < kNumCollisionClasses, "Specified bit index for collision class is out of bounds");
if (bitIndex >= 0 && bitIndex < kNumCollisionClasses)
{
m_collisionClasses[bitIndex] = string(collisionClassPair[0].c_str());
}
}
collisionClassPair.clear();
}
ExportCollisionClassesToLua();
}
const char* GameConfigPhysicsSettings::GetCollisionClassName(unsigned int bitIndex)
{
return bitIndex < kNumCollisionClasses ? m_collisionClasses[bitIndex].c_str() : "";
} | 37.546875 | 155 | 0.71161 | [
"vector"
] |
7430d1306d8be106dae4943b90883fe41a5b36b1 | 6,275 | cpp | C++ | addons/ofxMidi/example-output/src/testApp.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 18 | 2015-01-18T22:34:22.000Z | 2020-09-06T20:30:30.000Z | addons/ofxMidi/example-output/src/testApp.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 2 | 2015-08-04T00:07:46.000Z | 2017-05-10T15:53:51.000Z | addons/ofxMidi/example-output/src/testApp.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 10 | 2015-01-18T23:46:10.000Z | 2019-08-25T12:10:04.000Z | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup() {
ofSetVerticalSync(true);
ofBackground(255);
ofSetLogLevel(OF_LOG_VERBOSE);
// print the available output ports to the console
midiOut.listPorts(); // via instance
//ofxMidiOut::listPorts(); // via static too
// connect
midiOut.openPort(0); // by number
//midiOut.openPort("IAC Driver Pure Data In"); // by name
//midiOut.openVirtualPort("ofxMidiOut"); // open a virtual port
channel = 1;
currentPgm = 0;
note = 0;
velocity = 0;
pan = 0;
bend = 0;
touch = 0;
polytouch = 0;
}
//--------------------------------------------------------------
void testApp::update() {}
//--------------------------------------------------------------
void testApp::draw() {
// let's see something
ofSetColor(0);
stringstream text;
text << "connected to port " << midiOut.getPort()
<< " \"" << midiOut.getName() << "\"" << endl
<< "is virtual?: " << midiOut.isVirtual() << endl << endl
<< "sending to channel " << channel << endl << endl
<< "current program: " << currentPgm << endl << endl
<< "note: " << note << endl
<< "velocity: " << velocity << endl
<< "pan: " << pan << endl
<< "bend: " << bend << endl
<< "touch: " << touch << endl
<< "polytouch: " << polytouch;
ofDrawBitmapString(text.str(), 20, 20);
}
//--------------------------------------------------------------
void testApp::exit() {
// clean up
midiOut.closePort();
}
//--------------------------------------------------------------
void testApp::keyPressed(int key) {
// send a note on if the key is a letter or a number
if(isalnum((unsigned char) key)) {
// scale the ascii values to midi velocity range 0-127
// see an ascii table: http://www.asciitable.com/
note = ofMap(key, 48, 122, 0, 127);
velocity = 64;
midiOut.sendNoteOn(channel, note, velocity);
}
if(key == 'l') {
ofxMidiOut::listPorts();
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key) {
switch(key) {
// send pgm change on arrow keys
case OF_KEY_UP:
currentPgm = (int) ofClamp(currentPgm+1, 0, 127);
midiOut.sendProgramChange(channel, currentPgm);
break;
case OF_KEY_DOWN:
currentPgm = (int) ofClamp(currentPgm-1, 0, 127);
midiOut << ProgramChange(channel, currentPgm); // stream interface
break;
// aftertouch
case '[':
touch = 64;
midiOut.sendAftertouch(channel, touch);
break;
case ']':
touch = 127;
midiOut << Aftertouch(channel, touch); // stream interface
break;
// poly aftertouch
case '<':
polytouch = 64;
midiOut.sendPolyAftertouch(channel, 64, polytouch);
break;
case '>':
polytouch = 127;
midiOut << PolyAftertouch(channel, 64, polytouch); // stream interface
break;
// sysex using raw bytes (use shift + s)
case 'S': {
// send a pitch change to Part 1 of a MULTI on an Akai sampler
// from http://troywoodfield.tripod.com/sysex.html
//
// do you have an S2000 to try?
//
// note: this is probably not as efficient as the next two methods
// since it sends only one byte at a time, instead of all
// at once
//
midiOut.sendMidiByte(MIDI_SYSEX);
midiOut.sendMidiByte(0x47); // akai manufacturer code
midiOut.sendMidiByte(0x00); // channel 0
midiOut.sendMidiByte(0x42); // MULTI
midiOut.sendMidiByte(0x48); // using an Akai S2000
midiOut.sendMidiByte(0x00); // Part 1
midiOut.sendMidiByte(0x00); // transpose
midiOut.sendMidiByte(0x01); // Access Multi Parts
midiOut.sendMidiByte(0x4B); // offset
midiOut.sendMidiByte(0x00); // offset
midiOut.sendMidiByte(0x01); // Field size = 1
midiOut.sendMidiByte(0x00); // Field size = 1
midiOut.sendMidiByte(0x04); // pitch value = 4
midiOut.sendMidiByte(0x00); // offset
midiOut.sendMidiByte(MIDI_SYSEX_END);
// send again using a vector
//
// sends all bytes within one message
//
vector<unsigned char> sysexMsg;
sysexMsg.push_back(MIDI_SYSEX);
sysexMsg.push_back(0x47);
sysexMsg.push_back(0x00);
sysexMsg.push_back(0x42);
sysexMsg.push_back(0x48);
sysexMsg.push_back(0x00);
sysexMsg.push_back(0x00);
sysexMsg.push_back(0x01);
sysexMsg.push_back(0x4B);
sysexMsg.push_back(0x00);
sysexMsg.push_back(0x01);
sysexMsg.push_back(0x00);
sysexMsg.push_back(0x04);
sysexMsg.push_back(0x00);
sysexMsg.push_back(MIDI_SYSEX_END);
midiOut.sendMidiBytes(sysexMsg);
// send again with the byte stream interface
//
// builds the message, then sends it on FinishMidi()
//
midiOut << StartMidi() << MIDI_SYSEX
<< 0x47 << 0x00 << 0x42 << 0x48 << 0x00 << 0x00 << 0x01
<< 0x4B << 0x00 << 0x01 << 0x00 << 0x04 << 0x00
<< MIDI_SYSEX_END << FinishMidi();
break;
}
// print the port list
case '?':
midiOut.listPorts();
break;
// note off using raw bytes
case ' ':
// send with the byte stream interface, noteoff for note 60
midiOut << StartMidi() << 0x80 << 0x3C << 0x40 << FinishMidi();
break;
default:
// send a note off if the key is a letter or a number
if(isalnum(key)) {
note = ofMap(key, 48, 122, 0, 127);
velocity = 0;
midiOut << NoteOff(channel, note, velocity); // stream interface
}
break;
}
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button) {
// x pos controls the pan (ctl = 10)
pan = ofMap(x, 0, ofGetWidth(), 0, 127);
midiOut.sendControlChange(channel, 10, pan);
// y pos controls the pitch bend
bend = ofMap(y, 0, ofGetHeight(), 0, MIDI_MAX_BEND);
midiOut.sendPitchBend(channel, bend);
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mouseReleased() {
}
| 28.784404 | 74 | 0.554263 | [
"vector"
] |
7431504bf567c52d7883a407de1d55f28e5793ed | 1,578 | hpp | C++ | umllib/include/UMLFile.hpp | mucsci-students/2021fa-420-nullptr | ca9dda5f755e5487befb8c1cfd6bca9723809fc3 | [
"BSD-2-Clause"
] | 6 | 2021-09-01T01:38:21.000Z | 2021-10-09T19:31:00.000Z | umllib/include/UMLFile.hpp | mucsci-students/2021fa-420-nullptr | ca9dda5f755e5487befb8c1cfd6bca9723809fc3 | [
"BSD-2-Clause"
] | 92 | 2021-09-07T21:14:44.000Z | 2021-12-09T23:29:37.000Z | umllib/include/UMLFile.hpp | mucsci-students/2021fa-420-nullptr | ca9dda5f755e5487befb8c1cfd6bca9723809fc3 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
/*
Filename : UMLFile.hpp
Description: Serves as an object for which information about a class
in the UML diagram is stored in a JSON file.
*/
//--------------------------------------------------------------------
// System includes
#include <vector>
#include <string>
#include <fstream>
#include <nlohmann/json.hpp>
#include <inja/inja.hpp>
#include "UMLClass.hpp"
#include "UMLData.hpp"
#include "UMLAttribute.hpp"
#include "UMLRelationship.hpp"
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Using declarations
using std::string;
using std::vector;
using json = nlohmann::json;
//--------------------------------------------------------------------
class UMLFile
{
private:
json jsonFile;
string path;
public:
// Constructor: takes in the name of the file to save
UMLFile(const string&);
// Saves information from UML diagram to JSON
void save(UMLData& data);
// Loads a system file and returns a UML data object
UMLData load();
// Makes a list of all JSON files in the build directory that can be used for loading.
static json listSaves();
// Gets the classes from the json file and adds them to the UMLData object
static void addClasses(UMLData& data, const json& j);
// Gets the relationships from the json file and adds them to the UMLData object
static void addRelationships(UMLData& data, const json& j);
}; | 29.222222 | 94 | 0.54943 | [
"object",
"vector"
] |
74339ee496bf41ab071816532929e30565c90900 | 34,542 | cpp | C++ | cpp/jni/javet_converter.cpp | Cormanz/Javet | 47c098f7b355e9033349335d1fdef7fab987ddb2 | [
"Apache-2.0"
] | null | null | null | cpp/jni/javet_converter.cpp | Cormanz/Javet | 47c098f7b355e9033349335d1fdef7fab987ddb2 | [
"Apache-2.0"
] | null | null | null | cpp/jni/javet_converter.cpp | Cormanz/Javet | 47c098f7b355e9033349335d1fdef7fab987ddb2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 caoccao.com Sam Cao
* 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 "javet_converter.h"
#include "javet_enums.h"
#include "javet_logging.h"
// Primitive
#define IS_JAVA_BOOLEAN(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueBoolean)
#define IS_JAVA_DOUBLE(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueDouble)
#define IS_JAVA_INTEGER(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueInteger)
#define IS_JAVA_LONG(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueLong)
#define IS_JAVA_NULL(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueNull)
#define IS_JAVA_STRING(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueString)
#define IS_JAVA_UNDEFINED(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueUndefined)
#define IS_JAVA_ZONED_DATE_TIME(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueZonedDateTime)
// Reference
#define IS_JAVA_ARGUMENTS(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueArguments)
#define IS_JAVA_ARRAY(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueArray)
#define IS_JAVA_ARRAY_BUFFER(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueArrayBuffer)
#define IS_JAVA_DATA_VIEW(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueDataView)
#define IS_JAVA_MODULE(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueModule)
#define IS_JAVA_FUNCTION(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueFunction)
#define IS_JAVA_ERROR(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueError)
#define IS_JAVA_GLOBAL_OBJECT(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueGlobalObject)
#define IS_JAVA_MAP(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueMap)
#define IS_JAVA_ITERATOR(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueIterator)
#define IS_JAVA_OBJECT(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueObject)
#define IS_JAVA_PROMISE(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValuePromise)
#define IS_JAVA_PROXY(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueProxy)
#define IS_JAVA_REFERENCE(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueReference)
#define IS_JAVA_REG_EXP(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueRegExp)
#define IS_JAVA_SET(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueSet)
#define IS_JAVA_SHARED_ARRAY_BUFFER(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueSharedArrayBuffer)
#define IS_JAVA_SYMBOL(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueSymbol)
#define IS_JAVA_SYMBOL_OBJECT(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueSymbolObject)
#define IS_JAVA_WEAK_MAP(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueWeakMap)
#define IS_JAVA_WEAK_SET(jniEnv, obj) jniEnv->IsInstanceOf(obj, jclassV8ValueWeakSet)
namespace Javet {
namespace Converter {
void Initialize(JNIEnv* jniEnv) {
/*
@see https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/types.html
@see https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html
*/
// Runtime
jclassV8Runtime = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/interop/V8Runtime"));
jmethodIDV8RuntimeCreateV8ValueBoolean = jniEnv->GetMethodID(jclassV8Runtime, "createV8ValueBoolean", "(Z)Lcom/caoccao/javet/values/primitive/V8ValueBoolean;");
jmethodIDV8RuntimeCreateV8ValueInteger = jniEnv->GetMethodID(jclassV8Runtime, "createV8ValueInteger", "(I)Lcom/caoccao/javet/values/primitive/V8ValueInteger;");
jmethodIDV8RuntimeCreateV8ValueLong = jniEnv->GetMethodID(jclassV8Runtime, "createV8ValueLong", "(J)Lcom/caoccao/javet/values/primitive/V8ValueLong;");
jmethodIDV8RuntimeCreateV8ValueNull = jniEnv->GetMethodID(jclassV8Runtime, "createV8ValueNull", "()Lcom/caoccao/javet/values/primitive/V8ValueNull;");
jmethodIDV8RuntimeCreateV8ValueUndefined = jniEnv->GetMethodID(jclassV8Runtime, "createV8ValueUndefined", "()Lcom/caoccao/javet/values/primitive/V8ValueUndefined;");
// Primitive
jclassV8ValueBoolean = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueBoolean"));
jmethodIDV8ValueBooleanConstructor = jniEnv->GetMethodID(jclassV8ValueBoolean, "<init>", "(Z)V");
jmethodIDV8ValueBooleanToPrimitive = jniEnv->GetMethodID(jclassV8ValueBoolean, JAVA_METHOD_TO_PRIMITIVE, "()Z");
jclassV8ValueDouble = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueDouble"));
jmethodIDV8ValueDoubleConstructor = jniEnv->GetMethodID(jclassV8ValueDouble, "<init>", "(D)V");
jmethodIDV8ValueDoubleToPrimitive = jniEnv->GetMethodID(jclassV8ValueDouble, JAVA_METHOD_TO_PRIMITIVE, "()D");
jclassV8ValueInteger = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueInteger"));
jmethodIDV8ValueIntegerConstructor = jniEnv->GetMethodID(jclassV8ValueInteger, "<init>", "(I)V");
jmethodIDV8ValueIntegerToPrimitive = jniEnv->GetMethodID(jclassV8ValueInteger, JAVA_METHOD_TO_PRIMITIVE, "()I");
jclassV8ValueLong = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueLong"));
jmethodIDV8ValueLongConstructorFromLong = jniEnv->GetMethodID(jclassV8ValueLong, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueLongToPrimitive = jniEnv->GetMethodID(jclassV8ValueLong, JAVA_METHOD_TO_PRIMITIVE, "()J");
jclassV8ValueNull = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueNull"));
jclassV8ValueString = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueString"));
jmethodIDV8ValueStringConstructor = jniEnv->GetMethodID(jclassV8ValueString, "<init>", "(Ljava/lang/String;)V");
jmethodIDV8ValueStringToPrimitive = jniEnv->GetMethodID(jclassV8ValueString, JAVA_METHOD_TO_PRIMITIVE, "()Ljava/lang/String;");
jclassV8ValueUndefined = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueUndefined"));
jclassV8ValueUnknown = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueUnknown"));
jmethodIDV8ValueUnknownConstructor = jniEnv->GetMethodID(jclassV8ValueUnknown, "<init>", "(Ljava/lang/String;)V");
jclassV8ValueZonedDateTime = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/primitive/V8ValueZonedDateTime"));
jmethodIDV8ValueZonedDateTimeConstructor = jniEnv->GetMethodID(jclassV8ValueZonedDateTime, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueZonedDateTimeToPrimitive = jniEnv->GetMethodID(jclassV8ValueZonedDateTime, JAVA_METHOD_TO_PRIMITIVE, "()J");
// Reference
jclassV8Module = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8Module"));
jmethodIDV8ModuleConstructor = jniEnv->GetMethodID(jclassV8Module, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ModuleGetHandle = jniEnv->GetMethodID(jclassV8Module, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8Script = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8Script"));
jmethodIDV8ScriptConstructor = jniEnv->GetMethodID(jclassV8Script, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ScriptGetHandle = jniEnv->GetMethodID(jclassV8Script, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueArguments = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueArguments"));
jmethodIDV8ValueArgumentsConstructor = jniEnv->GetMethodID(jclassV8ValueArguments, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueArgumentsGetHandle = jniEnv->GetMethodID(jclassV8ValueArguments, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueArray = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueArray"));
jmethodIDV8ValueArrayConstructor = jniEnv->GetMethodID(jclassV8ValueArray, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueArrayGetHandle = jniEnv->GetMethodID(jclassV8ValueArray, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueArrayBuffer = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueArrayBuffer"));
jmethodIDV8ValueArrayBufferConstructor = jniEnv->GetMethodID(jclassV8ValueArrayBuffer, "<init>", "(JLjava/nio/ByteBuffer;)V");
jmethodIDV8ValueArrayBufferGetHandle = jniEnv->GetMethodID(jclassV8ValueArrayBuffer, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueDataView = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueDataView"));
jmethodIDV8ValueDataViewConstructor = jniEnv->GetMethodID(jclassV8ValueDataView, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueDataViewGetHandle = jniEnv->GetMethodID(jclassV8ValueDataView, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueFunction = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueFunction"));
jmethodIDV8ValueFunctionConstructor = jniEnv->GetMethodID(jclassV8ValueFunction, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueFunctionGetHandle = jniEnv->GetMethodID(jclassV8ValueFunction, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueError = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueError"));
jmethodIDV8ValueErrorConstructor = jniEnv->GetMethodID(jclassV8ValueError, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueErrorGetHandle = jniEnv->GetMethodID(jclassV8ValueError, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueGlobalObject = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueGlobalObject"));
jmethodIDV8ValueGlobalObjectConstructor = jniEnv->GetMethodID(jclassV8ValueGlobalObject, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueGlobalObjectGetHandle = jniEnv->GetMethodID(jclassV8ValueGlobalObject, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueMap = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueMap"));
jmethodIDV8ValueMapConstructor = jniEnv->GetMethodID(jclassV8ValueMap, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueMapGetHandle = jniEnv->GetMethodID(jclassV8ValueMap, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueIterator = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueIterator"));
jmethodIDV8ValueIteratorConstructor = jniEnv->GetMethodID(jclassV8ValueIterator, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueIteratorGetHandle = jniEnv->GetMethodID(jclassV8ValueIterator, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueObject = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueObject"));
jmethodIDV8ValueObjectConstructor = jniEnv->GetMethodID(jclassV8ValueObject, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueObjectGetHandle = jniEnv->GetMethodID(jclassV8ValueObject, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValuePromise = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValuePromise"));
jmethodIDV8ValuePromiseConstructor = jniEnv->GetMethodID(jclassV8ValuePromise, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValuePromiseGetHandle = jniEnv->GetMethodID(jclassV8ValuePromise, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueProxy = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueProxy"));
jmethodIDV8ValueProxyConstructor = jniEnv->GetMethodID(jclassV8ValueProxy, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueProxyGetHandle = jniEnv->GetMethodID(jclassV8ValueProxy, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueReference = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueReference"));
jclassV8ValueRegExp = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueRegExp"));
jmethodIDV8ValueRegExpConstructor = jniEnv->GetMethodID(jclassV8ValueRegExp, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueRegExpGetHandle = jniEnv->GetMethodID(jclassV8ValueRegExp, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueSet = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueSet"));
jmethodIDV8ValueSetConstructor = jniEnv->GetMethodID(jclassV8ValueSet, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueSetGetHandle = jniEnv->GetMethodID(jclassV8ValueSet, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueSharedArrayBuffer = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueSharedArrayBuffer"));
jmethodIDV8ValueSharedArrayBufferConstructor = jniEnv->GetMethodID(jclassV8ValueSharedArrayBuffer, "<init>", "(JLjava/nio/ByteBuffer;)V");
jmethodIDV8ValueSharedArrayBufferGetHandle = jniEnv->GetMethodID(jclassV8ValueSharedArrayBuffer, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueSymbol = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueSymbol"));
jmethodIDV8ValueSymbolConstructor = jniEnv->GetMethodID(jclassV8ValueSymbol, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueSymbolGetHandle = jniEnv->GetMethodID(jclassV8ValueSymbol, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueSymbolObject = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueSymbolObject"));
jmethodIDV8ValueSymbolObjectConstructor = jniEnv->GetMethodID(jclassV8ValueSymbolObject, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueSymbolObjectGetHandle = jniEnv->GetMethodID(jclassV8ValueSymbolObject, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueTypedArray = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueTypedArray"));
jmethodIDV8ValueTypedArrayConstructor = jniEnv->GetMethodID(jclassV8ValueTypedArray, "<init>", "(JI)V");
jmethodIDV8ValueTypedArrayGetHandle = jniEnv->GetMethodID(jclassV8ValueTypedArray, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueWeakMap = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueWeakMap"));
jmethodIDV8ValueWeakMapConstructor = jniEnv->GetMethodID(jclassV8ValueWeakMap, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueWeakMapGetHandle = jniEnv->GetMethodID(jclassV8ValueWeakMap, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
jclassV8ValueWeakSet = (jclass)jniEnv->NewGlobalRef(jniEnv->FindClass("com/caoccao/javet/values/reference/V8ValueWeakSet"));
jmethodIDV8ValueWeakSetConstructor = jniEnv->GetMethodID(jclassV8ValueWeakSet, JAVA_CONSTRUCTOR_AND_SIGNATURE_FROM_HANDLE);
jmethodIDV8ValueWeakSetGetHandle = jniEnv->GetMethodID(jclassV8ValueWeakSet, JAVA_METHOD_AND_SIGNATURE_GET_HANDLE);
}
jobject ToExternalV8ValueArray(
JNIEnv* jniEnv, jobject externalV8Runtime,
const V8LocalContext& v8Context, const v8::FunctionCallbackInfo<v8::Value>& args) {
int argLength = args.Length();
if (argLength > 0) {
auto v8Array = v8::Array::New(v8Context->GetIsolate(), argLength);
for (int i = 0; i < argLength; ++i) {
auto maybeResult = v8Array->Set(v8Context, i, args[i]);
maybeResult.Check();
}
return ToExternalV8Value(jniEnv, externalV8Runtime, v8Context, v8Array);
}
return nullptr;
}
jobject ToExternalV8Module(JNIEnv* jniEnv, jobject externalV8Runtime, const V8LocalContext& v8Context, const V8LocalModule& v8Module) {
return jniEnv->NewObject(jclassV8Module, jmethodIDV8ModuleConstructor, ToV8PersistentDataReference(v8Context, v8Module));
}
jobject ToExternalV8Script(JNIEnv* jniEnv, jobject externalV8Runtime, const V8LocalContext& v8Context, const V8LocalScript& v8Script) {
return jniEnv->NewObject(jclassV8Script, jmethodIDV8ScriptConstructor, ToV8PersistentScriptReference(v8Context, v8Script));
}
jobject ToExternalV8Value(JNIEnv* jniEnv, jobject externalV8Runtime, const V8LocalContext& v8Context, const V8LocalValue v8Value) {
if (v8Value->IsUndefined()) {
return ToExternalV8ValueUndefined(jniEnv, externalV8Runtime);
}
if (v8Value->IsNull()) {
return ToExternalV8ValueNull(jniEnv, externalV8Runtime);
}
// Reference types
// Note: Reference types must be checked before primitive types are checked.
if (v8Value->IsArray()) {
return jniEnv->NewObject(jclassV8ValueArray, jmethodIDV8ValueArrayConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
using V8ValueReferenceType = Javet::Enums::V8ValueReferenceType::V8ValueReferenceType;
if (v8Value->IsTypedArray()) {
int type = V8ValueReferenceType::Invalid;
if (v8Value->IsBigInt64Array()) {
type = V8ValueReferenceType::BigInt64Array;
}
else if (v8Value->IsBigUint64Array()) {
type = V8ValueReferenceType::BigUint64Array;
}
else if (v8Value->IsFloat32Array()) {
type = V8ValueReferenceType::Float32Array;
}
else if (v8Value->IsFloat64Array()) {
type = V8ValueReferenceType::Float64Array;
}
else if (v8Value->IsInt16Array()) {
type = V8ValueReferenceType::Int16Array;
}
else if (v8Value->IsInt32Array()) {
type = V8ValueReferenceType::Int32Array;
}
else if (v8Value->IsInt8Array()) {
type = V8ValueReferenceType::Int8Array;
}
else if (v8Value->IsUint16Array()) {
type = V8ValueReferenceType::Uint16Array;
}
else if (v8Value->IsUint32Array()) {
type = V8ValueReferenceType::Uint32Array;
}
else if (v8Value->IsUint8Array()) {
type = V8ValueReferenceType::Uint8Array;
}
else if (v8Value->IsUint8ClampedArray()) {
type = V8ValueReferenceType::Uint8ClampedArray;
}
if (type != V8ValueReferenceType::Invalid) {
return jniEnv->NewObject(jclassV8ValueTypedArray, jmethodIDV8ValueTypedArrayConstructor, ToV8PersistentValueReference(v8Context, v8Value), type);
}
}
if (v8Value->IsDataView()) {
return jniEnv->NewObject(jclassV8ValueDataView, jmethodIDV8ValueDataViewConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsArrayBuffer()) {
auto v8ArrayBuffer = v8Value.As<v8::ArrayBuffer>();
return jniEnv->NewObject(jclassV8ValueArrayBuffer, jmethodIDV8ValueArrayBufferConstructor, ToV8PersistentValueReference(v8Context, v8Value),
jniEnv->NewDirectByteBuffer(v8ArrayBuffer->GetBackingStore()->Data(), v8ArrayBuffer->ByteLength()));
}
if (v8Value->IsSharedArrayBuffer()) {
auto v8SharedArrayBuffer = v8Value.As<v8::SharedArrayBuffer>();
return jniEnv->NewObject(jclassV8ValueSharedArrayBuffer, jmethodIDV8ValueSharedArrayBufferConstructor, ToV8PersistentValueReference(v8Context, v8Value),
jniEnv->NewDirectByteBuffer(v8SharedArrayBuffer->GetBackingStore()->Data(), v8SharedArrayBuffer->ByteLength()));
}
if (v8Value->IsArrayBufferView()) {
/*
ArrayBufferView is a helper type representing any of typed array or DataView.
This block shouldn't be entered.
*/
}
if (v8Value->IsWeakMap()) {
return jniEnv->NewObject(jclassV8ValueWeakMap, jmethodIDV8ValueWeakMapConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsWeakSet()) {
return jniEnv->NewObject(jclassV8ValueWeakSet, jmethodIDV8ValueWeakSetConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsMap()) {
return jniEnv->NewObject(jclassV8ValueMap, jmethodIDV8ValueMapConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsSet()) {
return jniEnv->NewObject(jclassV8ValueSet, jmethodIDV8ValueSetConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsMapIterator() || v8Value->IsSetIterator() || v8Value->IsGeneratorObject()) {
return jniEnv->NewObject(jclassV8ValueIterator, jmethodIDV8ValueIteratorConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsArgumentsObject()) {
return jniEnv->NewObject(jclassV8ValueArguments, jmethodIDV8ValueArgumentsConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsPromise()) {
return jniEnv->NewObject(jclassV8ValuePromise, jmethodIDV8ValuePromiseConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsRegExp()) {
return jniEnv->NewObject(jclassV8ValueRegExp, jmethodIDV8ValueRegExpConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsAsyncFunction()) {
// It defaults to V8ValueFunction.
}
if (v8Value->IsGeneratorFunction()) {
// It defaults to V8ValueFunction.
}
if (v8Value->IsProxy()) {
// Proxy is also a function. So, it needs to be tested before IsFunction().
return jniEnv->NewObject(jclassV8ValueProxy, jmethodIDV8ValueProxyConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsFunction()) {
return jniEnv->NewObject(jclassV8ValueFunction, jmethodIDV8ValueFunctionConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsNativeError()) {
return jniEnv->NewObject(jclassV8ValueError, jmethodIDV8ValueErrorConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsSymbolObject()) {
return jniEnv->NewObject(jclassV8ValueSymbolObject, jmethodIDV8ValueSymbolObjectConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
if (v8Value->IsSymbol()) {
return jniEnv->NewObject(jclassV8ValueSymbol, jmethodIDV8ValueSymbolConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
// Primitive types
if (v8Value->IsBoolean() || v8Value->IsBooleanObject()) {
return jniEnv->CallObjectMethod(externalV8Runtime, jmethodIDV8RuntimeCreateV8ValueBoolean, v8Value->IsTrue());
}
if (v8Value->IsInt32()) {
return jniEnv->CallObjectMethod(externalV8Runtime, jmethodIDV8RuntimeCreateV8ValueInteger, v8Value->Int32Value(v8Context).FromMaybe(0));
}
if (v8Value->IsBigInt() || v8Value->IsBigIntObject()) {
return jniEnv->CallObjectMethod(externalV8Runtime, jmethodIDV8RuntimeCreateV8ValueLong, v8Value->ToBigInt(v8Context).ToLocalChecked()->Int64Value());
}
if (v8Value->IsDate()) {
auto v8Date = v8Value->ToObject(v8Context).ToLocalChecked().As<v8::Date>();
return jniEnv->NewObject(jclassV8ValueZonedDateTime, jmethodIDV8ValueZonedDateTimeConstructor, static_cast<std::int64_t>(v8Date->ValueOf()));
}
if (v8Value->IsNumber() || v8Value->IsNumberObject()) {
return jniEnv->NewObject(jclassV8ValueDouble, jmethodIDV8ValueDoubleConstructor, v8Value->NumberValue(v8Context).FromMaybe(0));
}
if (v8Value->IsString() || v8Value->IsStringObject()) {
return ToExternalV8ValuePrimitive(jniEnv, jclassV8ValueString, jmethodIDV8ValueStringConstructor, v8Context, v8Value);
}
if (v8Value->IsName()) {
/*
* Name is handled by either String or Symbol.
* This block should not be entered.
*/
}
#ifndef ENABLE_NODE
if (v8Value->IsModule()) {
return jniEnv->NewObject(jclassV8Module, jmethodIDV8ModuleConstructor, ToV8PersistentDataReference(v8Context, v8Value));
}
#endif
// Object needs to be the last one.
if (v8Value->IsObject()) {
return jniEnv->NewObject(jclassV8ValueObject, jmethodIDV8ValueObjectConstructor, ToV8PersistentValueReference(v8Context, v8Value));
}
// Something is wrong. It defaults to toString().
return ToExternalV8ValuePrimitive(jniEnv, jclassV8ValueUnknown, jmethodIDV8ValueUnknownConstructor, v8Context, v8Value);
}
jobject ToExternalV8ValueGlobalObject(JNIEnv* jniEnv, V8PersistentObject& v8PersistentObject) {
return jniEnv->NewObject(jclassV8ValueGlobalObject, jmethodIDV8ValueGlobalObjectConstructor, TO_JAVA_LONG(&v8PersistentObject));
}
jobject ToExternalV8ValueUndefined(JNIEnv* jniEnv, jobject externalV8Runtime) {
return jniEnv->CallObjectMethod(externalV8Runtime, jmethodIDV8RuntimeCreateV8ValueUndefined);
}
std::unique_ptr<v8::ScriptOrigin> ToV8ScriptOringinPointer(JNIEnv* jniEnv, const V8LocalContext& v8Context,
jstring& mResourceName, jint& mResourceLineOffset, jint& mResourceColumnOffset, jint& mScriptId, jboolean& mIsWASM, jboolean& mIsModule) {
return std::make_unique<v8::ScriptOrigin>(
ToV8String(jniEnv, v8Context, mResourceName),
ToV8Integer(v8Context, mResourceLineOffset),
ToV8Integer(v8Context, mResourceColumnOffset),
V8LocalBoolean(),
ToV8Integer(v8Context, mScriptId),
V8LocalValue(),
V8LocalBoolean(),
ToV8Boolean(v8Context, mIsWASM),
ToV8Boolean(v8Context, mIsModule),
V8LocalPrimitiveArray());
}
V8LocalString ToV8String(JNIEnv* jniEnv, const V8LocalContext& v8Context, jstring& managedString) {
if (managedString == nullptr) {
return V8LocalString();
}
const uint16_t* unmanagedString = jniEnv->GetStringChars(managedString, nullptr);
int length = jniEnv->GetStringLength(managedString);
auto twoByteString = v8::String::NewFromTwoByte(
v8Context->GetIsolate(), unmanagedString, v8::NewStringType::kNormal, length);
if (twoByteString.IsEmpty()) {
return V8LocalString();
}
auto localV8String = twoByteString.ToLocalChecked();
jniEnv->ReleaseStringChars(managedString, unmanagedString);
return localV8String;
}
V8LocalValue ToV8Value(JNIEnv* jniEnv, const V8LocalContext& v8Context, jobject& obj) {
if (obj == nullptr || IS_JAVA_NULL(jniEnv, obj)) {
return ToV8Null(v8Context);
}
else if (IS_JAVA_INTEGER(jniEnv, obj)) {
jint integerObject = jniEnv->CallIntMethod(obj, jmethodIDV8ValueIntegerToPrimitive);
return ToV8Integer(v8Context, integerObject);
}
else if (IS_JAVA_STRING(jniEnv, obj)) {
jstring stringObject = (jstring)jniEnv->CallObjectMethod(obj, jmethodIDV8ValueStringToPrimitive);
return ToV8String(jniEnv, v8Context, stringObject);
}
else if (IS_JAVA_BOOLEAN(jniEnv, obj)) {
jboolean booleanObject = jniEnv->CallBooleanMethod(obj, jmethodIDV8ValueBooleanToPrimitive);
return ToV8Boolean(v8Context, booleanObject);
}
else if (IS_JAVA_DOUBLE(jniEnv, obj)) {
jdouble doubleObject = jniEnv->CallDoubleMethod(obj, jmethodIDV8ValueDoubleToPrimitive);
return ToV8Double(v8Context, doubleObject);
}
else if (IS_JAVA_LONG(jniEnv, obj)) {
jlong longObject = jniEnv->CallLongMethod(obj, jmethodIDV8ValueLongToPrimitive);
return ToV8Long(v8Context, longObject);
}
else if (IS_JAVA_ZONED_DATE_TIME(jniEnv, obj)) {
jlong longObject = (jlong)jniEnv->CallObjectMethod(obj, jmethodIDV8ValueZonedDateTimeToPrimitive);
return ToV8Date(v8Context, longObject);
}
else if (IS_JAVA_REFERENCE(jniEnv, obj)) {
if (IS_JAVA_ARRAY(jniEnv, obj)) {
return V8LocalArray::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_ARRAY_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueArrayGetHandle)));
}
else if (IS_JAVA_GLOBAL_OBJECT(jniEnv, obj)) {
// Global object is a tricky one.
return V8LocalObject::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_OBJECT_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueGlobalObjectGetHandle)));
}
else if (IS_JAVA_MAP(jniEnv, obj)) {
return V8LocalMap::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_MAP_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueMapGetHandle)));
}
else if (IS_JAVA_PROMISE(jniEnv, obj)) {
return V8LocalPromise::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_PROMISE_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValuePromiseGetHandle)));
}
else if (IS_JAVA_PROXY(jniEnv, obj)) {
return V8LocalProxy::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_PROXY_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueProxyGetHandle)));
}
else if (IS_JAVA_REG_EXP(jniEnv, obj)) {
return V8LocalRegExp::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_REG_EXP_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueRegExpGetHandle)));
}
else if (IS_JAVA_SET(jniEnv, obj)) {
return V8LocalSet::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_SET_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueSetGetHandle)));
}
else if (IS_JAVA_SYMBOL(jniEnv, obj)) {
return V8LocalSymbol::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_SYMBOL_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueSymbolGetHandle)));
}
else if (IS_JAVA_SYMBOL_OBJECT(jniEnv, obj)) {
return V8LocalSymbolObject::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_SYMBOL_OBJECT_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueSymbolObjectGetHandle)));
}
else if (
IS_JAVA_ARGUMENTS(jniEnv, obj) ||
IS_JAVA_ERROR(jniEnv, obj) ||
IS_JAVA_ITERATOR(jniEnv, obj) ||
IS_JAVA_OBJECT(jniEnv, obj) ||
IS_JAVA_WEAK_MAP(jniEnv, obj) ||
IS_JAVA_WEAK_SET(jniEnv, obj)) {
return V8LocalObject::New(v8Context->GetIsolate(), TO_V8_PERSISTENT_OBJECT_POINTER(
jniEnv->CallLongMethod(obj, jmethodIDV8ValueObjectGetHandle)));
}
}
return ToV8Undefined(v8Context);
}
std::unique_ptr<V8LocalValue[]> ToV8Values(JNIEnv* jniEnv, const V8LocalContext& v8Context, jobjectArray& mValues) {
std::unique_ptr<V8LocalValue[]> umValuesPointer;
uint32_t valueCount = mValues == nullptr ? 0 : jniEnv->GetArrayLength(mValues);
if (valueCount > 0) {
umValuesPointer.reset(new V8LocalValue[valueCount]);
for (uint32_t i = 0; i < valueCount; ++i) {
jobject obj = jniEnv->GetObjectArrayElement(mValues, i);
umValuesPointer.get()[i] = ToV8Value(jniEnv, v8Context, obj);
}
}
return umValuesPointer;
}
}
}
| 67.729412 | 177 | 0.692403 | [
"object"
] |
29364b6be435932ac6ec13bbd413d65a9b735b71 | 72,673 | cpp | C++ | layer3/Editor.cpp | kingdavid72/pymol-OpenSource | 8068af8b53a4ae16657b536e83bfd5310e58a8bd | [
"CNRI-Python"
] | null | null | null | layer3/Editor.cpp | kingdavid72/pymol-OpenSource | 8068af8b53a4ae16657b536e83bfd5310e58a8bd | [
"CNRI-Python"
] | null | null | null | layer3/Editor.cpp | kingdavid72/pymol-OpenSource | 8068af8b53a4ae16657b536e83bfd5310e58a8bd | [
"CNRI-Python"
] | null | null | null |
/*
A* -------------------------------------------------------------------
B* This file contains source code for the PyMOL computer program
C* copyright 1998-2000 by Warren Lyford Delano of DeLano Scientific.
D* -------------------------------------------------------------------
E* It is unlawful to modify or remove this copyright notice.
F* -------------------------------------------------------------------
G* Please see the accompanying LICENSE file for further information.
H* -------------------------------------------------------------------
I* Additional authors of this source file include:
-*
-*
-*
Z* -------------------------------------------------------------------
*/
#include"os_python.h"
#include"os_predef.h"
#include"os_std.h"
#include"os_gl.h"
#include"Err.h"
#include"PConv.h"
#include"MemoryDebug.h"
#include"Vector.h"
#include"Matrix.h"
#include"ButMode.h"
#include"Scene.h"
#include"Editor.h"
#include"Selector.h"
#include"Ortho.h"
#include"main.h"
#include"Color.h"
#include"Setting.h"
#include"Util.h"
#include"Executive.h"
#include"P.h"
#include"CGO.h"
#include "Lex.h"
struct _CEditor {
ObjectMolecule *DihedObject;
WordType DragSeleName;
int Active;
int ActiveState;
int DragIndex;
int DragSelection;
int DragHaveAxis, DragHaveBase, DragBondFlag, DragSlowFlag;
int PickMode; /* 1 = atom, 2 = bond, 3 = multiatom */
int NextPickSele;
int BondMode;
CObject *DragObject;
int NFrag;
float V0[3], V1[3], Axis[3], Center[3], DragBase[3];
float *PosVLA;
int ShowFrags;
int DihedralInvalid;
int MouseInvalid;
int FavorOrigin;
float FavoredOrigin[3];
CGO *shaderCGO;
};
int EditorGetScheme(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
int scheme = EDITOR_SCHEME_OBJ;
if(EditorActive(G))
scheme = EDITOR_SCHEME_FRAG;
else if(I->DragObject) {
if(I->DragIndex >= 0) {
scheme = EDITOR_SCHEME_OBJ;
} else {
scheme = EDITOR_SCHEME_DRAG;
}
}
return scheme;
}
void EditorFavorOrigin(PyMOLGlobals * G, float *v1)
{
CEditor *I = G->Editor;
if(v1) {
I->FavorOrigin = true;
copy3f(v1, I->FavoredOrigin);
} else {
I->FavorOrigin = false;
}
}
static void EditorDrawDihedral(PyMOLGlobals * G)
{
if(EditorActive(G) && EditorIsBondMode(G)
&& SettingGetGlobal_b(G, cSetting_editor_auto_dihedral)) {
ObjectMolecule *obj1, *obj2;
int at1, at2, at0, at3;
int sele1 = SelectorIndexByName(G, cEditorSele1);
int sele2 = SelectorIndexByName(G, cEditorSele2);
if((sele1 >= 0) && (sele2 >= 0)) {
obj1 = SelectorGetFastSingleAtomObjectIndex(G, sele1, &at1);
obj2 = SelectorGetFastSingleAtomObjectIndex(G, sele2, &at2);
if(obj1 && (obj1 == obj2)) {
CEditor *I = G->Editor;
I->DihedObject = obj1;
at0 = ObjectMoleculeGetTopNeighbor(G, obj1, at1, at2);
at3 = ObjectMoleculeGetTopNeighbor(G, obj1, at2, at1);
if((at0 >= 0) && (at3 >= 0)) {
float result;
/* find the highest priority atom attached to index1 */
SelectorCreateOrderedFromObjectIndices(G, cEditorDihe1, obj1, &at0, 1);
SelectorCreateOrderedFromObjectIndices(G, cEditorDihe2, obj2, &at3, 1);
ExecutiveDihedral(G, &result, cEditorDihedral, cEditorDihe1,
cEditorSele1, cEditorSele2, cEditorDihe2,
0, true, true, false, true, -1);
ExecutiveColor(G, cEditorDihedral, "white", 1, true);
ExecutiveSetSettingFromString(G, cSetting_float_labels,
"1", cEditorDihedral, 0, true, true);
#ifndef _PYMOL_FREETYPE
ExecutiveSetSettingFromString(G, cSetting_label_font_id,
"4", cEditorDihedral, 0, true, true);
#else
ExecutiveSetSettingFromString(G, cSetting_label_font_id,
"8", cEditorDihedral, 0, true, true);
ExecutiveSetSettingFromString(G, cSetting_label_size,
"20", cEditorDihedral, 0, true, true);
#endif
ExecutiveSetSettingFromString(G, cSetting_label_color,
"brightorange", cEditorDihedral, 0, true, true);
}
}
}
}
}
void EditorDihedralInvalid(PyMOLGlobals * G, ObjectMolecule * obj)
{
CEditor *I = G->Editor;
if(!obj)
I->DihedralInvalid = true;
else if(obj == I->DihedObject)
I->DihedralInvalid = true;
}
void EditorMouseInvalid(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
I->MouseInvalid = true;
}
static void EditorConfigMouse(PyMOLGlobals * G)
{
int scheme = EditorGetScheme(G);
const char *mouse_mode = SettingGetGlobal_s(G, cSetting_button_mode_name);
if(mouse_mode && (!strcmp(mouse_mode, "3-Button Editing") ||
!strcmp(mouse_mode, "3-Button Motions"))) {
/* WEAK! */
int button;
button = cButModeMiddleShft;
{
int action = ButModeGet(G, button);
if((action == cButModeMovFrag) ||
(action == cButModeMovObj) || (action == cButModeMovDrag)) {
switch (scheme) {
case EDITOR_SCHEME_OBJ:
action = cButModeMovObj;
break;
case EDITOR_SCHEME_FRAG:
action = cButModeMovFrag;
break;
case EDITOR_SCHEME_DRAG:
action = cButModeMovDrag;
break;
}
ButModeSet(G, button, action);
}
}
button = cButModeLeftShft;
{
int action = ButModeGet(G, button);
if((action == cButModeRotFrag) ||
(action == cButModeRotObj) || (action == cButModeRotDrag)) {
switch (scheme) {
case EDITOR_SCHEME_OBJ:
action = cButModeRotObj;
break;
case EDITOR_SCHEME_FRAG:
action = cButModeRotFrag;
break;
case EDITOR_SCHEME_DRAG:
action = cButModeRotDrag;
break;
}
ButModeSet(G, button, action);
}
}
button = cButModeRightShft;
{
int action = ButModeGet(G, button);
if((action == cButModeMovFragZ) ||
(action == cButModeMovObjZ) || (action == cButModeMovDragZ)) {
switch (scheme) {
case EDITOR_SCHEME_OBJ:
action = cButModeMovObjZ;
break;
case EDITOR_SCHEME_FRAG:
action = cButModeMovFragZ;
break;
case EDITOR_SCHEME_DRAG:
action = cButModeMovDragZ;
break;
}
ButModeSet(G, button, action);
}
}
button = cButModeLeftCtrl;
{
int action = ButModeGet(G, button);
if((action == cButModeMoveAtom) || (action == cButModeTorFrag)) {
switch (scheme) {
case EDITOR_SCHEME_OBJ:
action = cButModeMoveAtom;
break;
case EDITOR_SCHEME_FRAG:
action = cButModeTorFrag;
break;
case EDITOR_SCHEME_DRAG:
action = cButModeMoveAtom;
break;
}
ButModeSet(G, button, action);
}
}
button = cButModeLeftDouble;
{
int action = ButModeGet(G, button);
if((action == cButModeMoveAtom) || (action == cButModeTorFrag)) {
switch (scheme) {
case EDITOR_SCHEME_OBJ:
action = cButModeMoveAtom;
break;
case EDITOR_SCHEME_FRAG:
action = cButModeTorFrag;
break;
case EDITOR_SCHEME_DRAG:
action = cButModeMoveAtom;
break;
}
ButModeSet(G, button, action);
}
}
button = cButModeLeftCtSh;
{
int action = ButModeGet(G, button);
if((action == cButModeMoveAtom) || (action == cButModeMoveAtomZ)) {
switch (scheme) {
case EDITOR_SCHEME_OBJ:
action = cButModeMoveAtomZ;
break;
case EDITOR_SCHEME_FRAG:
action = cButModeMoveAtom;
break;
case EDITOR_SCHEME_DRAG:
action = cButModeMoveAtomZ;
break;
}
ButModeSet(G, button, action);
}
}
}
}
void EditorUpdate(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
if(I->DihedralInvalid) {
EditorDrawDihedral(G);
I->DihedralInvalid = false;
}
if(I->MouseInvalid) {
EditorConfigMouse(G);
I->MouseInvalid = false;
}
}
static int EditorGetEffectiveState(PyMOLGlobals * G, CObject * obj, int state)
{
if(obj && (obj->type == cObjectMolecule)) {
ObjectMolecule *objMol = (ObjectMolecule*)(void*)obj;
if(!objMol)
objMol = SelectorGetFastSingleObjectMolecule(G, SelectorIndexByName(G, cEditorSele1));
if(!objMol)
objMol = SelectorGetFastSingleObjectMolecule(G, SelectorIndexByName(G, cEditorSele2));
if(!objMol)
objMol = SelectorGetFastSingleObjectMolecule(G, SelectorIndexByName(G, cEditorSele3));
if(!objMol)
objMol = SelectorGetFastSingleObjectMolecule(G, SelectorIndexByName(G, cEditorSele4));
if(objMol) {
if((objMol->NCSet == 1) && (state > 0))
if(SettingGet_i(G, NULL, objMol->Obj.Setting, cSetting_static_singletons))
return 0;
}
}
return state;
}
int EditorGetNFrag(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
if(EditorActive(G)) {
return I->NFrag;
}
return 0;
}
void EditorDefineExtraPks(PyMOLGlobals * G)
{
WordType name;
WordType buffer;
if(EditorGetSinglePicked(G, name)) {
sprintf(buffer, "(byres %s)", name);
SelectorCreate(G, cEditorRes, buffer, NULL, true, NULL);
sprintf(buffer, "(bychain %s)", name);
SelectorCreate(G, cEditorChain, buffer, NULL, true, NULL);
sprintf(buffer, "(byobject %s)", name);
SelectorCreate(G, cEditorObject, buffer, NULL, true, NULL);
if(SettingGetGlobal_b(G, cSetting_auto_hide_selections))
ExecutiveHideSelections(G);
EditorInvalidateShaderCGO(G);
}
}
int EditorDeselectIfSelected(PyMOLGlobals * G, ObjectMolecule * obj, int index,
int update)
{
CEditor *I = G->Editor;
int result = false;
int s, sele;
if(obj) {
if((index >= 0) && (index < obj->NAtom)) {
s = obj->AtomInfo[index].selEntry;
sele = SelectorIndexByName(G, cEditorSele1);
if(SelectorIsMember(G, s, sele)) {
ExecutiveDelete(G, cEditorSele1);
result = true;
}
sele = SelectorIndexByName(G, cEditorSele2);
if(SelectorIsMember(G, s, sele)) {
ExecutiveDelete(G, cEditorSele2);
result = true;
}
sele = SelectorIndexByName(G, cEditorSele3);
if(SelectorIsMember(G, s, sele)) {
ExecutiveDelete(G, cEditorSele3);
result = true;
}
sele = SelectorIndexByName(G, cEditorSele4);
if(SelectorIsMember(G, s, sele)) {
ExecutiveDelete(G, cEditorSele4);
result = true;
}
if(result && update)
EditorActivate(G, I->ActiveState, I->BondMode);
}
}
return result;
}
int EditorIsBondMode(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
return (I->BondMode);
}
PyObject *EditorAsPyList(PyMOLGlobals * G)
{
PyObject *result = NULL;
CEditor *I = G->Editor;
if(!EditorActive(G)) {
result = PyList_New(0); /* not editing? return null list */
} else {
result = PyList_New(3);
PyList_SetItem(result, 0, PyString_FromString(""));
PyList_SetItem(result, 1, PyInt_FromLong(I->ActiveState));
PyList_SetItem(result, 2, PyInt_FromLong(I->BondMode));
}
return (PConvAutoNone(result));
}
int EditorFromPyList(PyMOLGlobals * G, PyObject * list)
{
int ok = true;
int active_flag = false;
int active_state;
WordType obj_name;
int ll = 0;
int bond_mode = true;
if(ok)
ok = (list != NULL);
if(ok)
ok = PyList_Check(list);
if(ok)
ll = PyList_Size(list);
/* TO SUPPORT BACKWARDS COMPATIBILITY...
Always check ll when adding new PyList_GetItem's */
if(ok)
active_flag = (PyList_Size(list) != 0);
if(!active_flag) {
EditorInactivate(G);
} else {
if(ok)
ok = PConvPyStrToStr(PyList_GetItem(list, 0), obj_name, sizeof(WordType));
if(ok)
ok = PConvPyIntToInt(PyList_GetItem(list, 1), &active_state);
if(ok && (ll > 2))
ok = PConvPyIntToInt(PyList_GetItem(list, 2), &bond_mode); /* newer session files */
if(ok) {
EditorActivate(G, active_state, bond_mode);
EditorDefineExtraPks(G);
} else {
EditorInactivate(G);
}
}
if(!ok) {
EditorInactivate(G);
}
return (ok);
}
int EditorActive(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
return (I->Active);
}
CObject *EditorDragObject(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
return I->DragObject;
}
int EditorGetSinglePicked(PyMOLGlobals * G, char *name)
{
int cnt = 0;
int sele;
if((sele = SelectorIndexByName(G, cEditorSele1)) >= 0) {
cnt++;
if(name)
strcpy(name, cEditorSele1);
}
if((sele = SelectorIndexByName(G, cEditorSele2)) >= 0) {
cnt++;
if(name)
strcpy(name, cEditorSele2);
}
if((sele = SelectorIndexByName(G, cEditorSele3)) >= 0) {
cnt++;
if(name)
strcpy(name, cEditorSele3);
}
if((sele = SelectorIndexByName(G, cEditorSele4)) >= 0) {
cnt++;
if(name)
strcpy(name, cEditorSele4);
}
return (cnt == 1);
}
void EditorGetNextMultiatom(PyMOLGlobals * G, char *name)
{
CEditor *I = G->Editor;
int sele;
sele = SelectorIndexByName(G, cEditorSele1);
if(sele < 0) {
strcpy(name, cEditorSele1);
I->NextPickSele = 0;
return;
}
sele = SelectorIndexByName(G, cEditorSele2);
if(sele < 0) {
strcpy(name, cEditorSele2);
I->NextPickSele = 1;
return;
}
sele = SelectorIndexByName(G, cEditorSele3);
if(sele < 0) {
strcpy(name, cEditorSele3);
I->NextPickSele = 2;
return;
}
sele = SelectorIndexByName(G, cEditorSele4);
if(sele < 0) {
strcpy(name, cEditorSele4);
I->NextPickSele = 3;
return;
}
strcpy(name, cEditorSele4);
I->NextPickSele = 3;
return;
/*
I->NextPickSele = (++I->NextPickSele)&0x3;
switch(I->NextPickSele) {
case 0: strcpy(name,cEditorSele1); break;
case 1: strcpy(name,cEditorSele2); break;
case 2: strcpy(name,cEditorSele3); break;
case 3: strcpy(name,cEditorSele4); break;
}
return;
*/
}
/*========================================================================*/
int EditorLogState(PyMOLGlobals * G, int pkresi)
{
CEditor *I = G->Editor;
if(SettingGetGlobal_i(G, cSetting_logging)) {
OrthoLineType buffer, buf1 = "None", buf2 = "None", buf3 = "None", buf4 = "None";
int pkbond = 1;
if(!EditorActive(G)) {
PLog(G, "edit", cPLog_pml);
} else {
int sele1, sele2, sele3, sele4;
ObjectMolecule *obj1 = NULL, *obj2 = NULL, *obj3 = NULL, *obj4 = NULL;
int index1, index2, index3, index4;
sele1 = SelectorIndexByName(G, cEditorSele1);
sele2 = SelectorIndexByName(G, cEditorSele2);
sele3 = SelectorIndexByName(G, cEditorSele3);
sele4 = SelectorIndexByName(G, cEditorSele4);
obj1 = SelectorGetFastSingleAtomObjectIndex(G, sele1, &index1);
obj2 = SelectorGetFastSingleAtomObjectIndex(G, sele2, &index2);
obj3 = SelectorGetFastSingleAtomObjectIndex(G, sele3, &index3);
obj4 = SelectorGetFastSingleAtomObjectIndex(G, sele4, &index4);
if((sele1 >= 0) && (sele2 >= 0) && I->BondMode && obj1 && obj2) {
/* bond mode */
ObjectMoleculeGetAtomSeleLog(obj1, index1, buf1, true);
ObjectMoleculeGetAtomSeleLog(obj2, index2, buf2, true);
} else {
/* atom mode */
pkbond = 0;
if(obj1) {
ObjectMoleculeGetAtomSeleLog(obj1, index1, buf1, true);
}
if(obj2) {
ObjectMoleculeGetAtomSeleLog(obj2, index2, buf2, true);
}
if(obj3) {
ObjectMoleculeGetAtomSeleLog(obj3, index3, buf3, true);
}
if(obj4) {
ObjectMoleculeGetAtomSeleLog(obj4, index4, buf4, true);
}
}
sprintf(buffer, "cmd.edit(%s,%s,%s,%s,pkresi=%d,pkbond=%d)",
buf1, buf2, buf3, buf4, pkresi ? 1 : 0, pkbond ? 1 : 0);
PLog(G, buffer, cPLog_pym);
}
}
return 1;
}
/*========================================================================*/
int EditorInvert(PyMOLGlobals * G, int quiet)
{
CEditor *I = G->Editor;
int sele0, sele1, sele2;
int i0, frg;
int ia0 = -1;
int ia1 = -1;
float v[3], v0[3], v1[3];
float n0[3], n1[3];
float m[16];
int state;
int vf, vf0, vf1;
int ok = false;
int found = false;
WordType name;
ObjectMolecule *obj0, *obj1, *obj2;
if(!EditorActive(G)) {
ErrMessage(G, "Editor", "Must pick an atom to invert.");
} else {
sele0 = SelectorIndexByName(G, cEditorSele1);
sele1 = SelectorIndexByName(G, cEditorSele2);
sele2 = SelectorIndexByName(G, cEditorSele3);
obj0 = SelectorGetFastSingleAtomObjectIndex(G, sele0, &i0);
obj1 = SelectorGetFastSingleAtomObjectIndex(G, sele1, &ia0);
obj2 = SelectorGetFastSingleAtomObjectIndex(G, sele2, &ia1);
if(sele0 < 0) {
ErrMessage(G, "Editor", "Must pick atom to invert as pk1.");
} else if(sele1 < 0) {
ErrMessage(G, "Editor", "Must pick immobile atom in pk2.");
} else if(sele2 < 0) {
ErrMessage(G, "Editor", "Must pick immobile atom in pk3.");
} else if(!(obj0 && (obj0 == obj1) && (obj0 = obj2))) {
ErrMessage(G, "Editor", "Must pick three atoms in the same object.");
} else {
state = SceneGetState(G);
ObjectMoleculeSaveUndo(obj0, state, false);
vf = ObjectMoleculeGetAtomVertex(obj0, state, i0, v);
vf0 = ObjectMoleculeGetAtomVertex(obj0, state, ia0, v0);
vf1 = ObjectMoleculeGetAtomVertex(obj0, state, ia1, v1);
if(vf & vf0 & vf1) {
subtract3f(v, v0, n0);
subtract3f(v, v1, n1);
normalize3f(n0);
normalize3f(n1);
add3f(n0, n1, n0);
normalize3f(n0);
get_rotation_about3f3fTTTf((float) cPI, n0, v, m);
for(frg = 1; frg <= I->NFrag; frg++) {
sprintf(name, "%s%1d", cEditorFragPref, frg);
sele2 = SelectorIndexByName(G, name);
if(ObjectMoleculeDoesAtomNeighborSele(obj0, i0, sele2) &&
(!ObjectMoleculeDoesAtomNeighborSele(obj0, ia0, sele2)) &&
(!ObjectMoleculeDoesAtomNeighborSele(obj0, ia1, sele2))) {
found = true;
ok =
ObjectMoleculeTransformSelection(obj0, state, sele2, m, false, NULL, false,
false);
}
}
if(found) {
if(!quiet) {
PRINTFB(G, FB_Editor, FB_Actions)
" Editor: Inverted atom.\n" ENDFB(G);
}
} else {
PRINTFB(G, FB_Editor, FB_Errors)
" Editor-Error: No free fragments found for inversion.\n" ENDFB(G);
}
SceneInvalidate(G);
I->DragIndex = -1;
I->DragSelection = -1;
I->DragObject = NULL;
}
}
}
return (ok);
}
/*========================================================================*/
int EditorTorsion(PyMOLGlobals * G, float angle)
{
CEditor *I = G->Editor;
int sele0, sele1, sele2;
int i0, i1;
float v0[3], v1[3];
float d1[3], n0[3];
float theta;
float m[16];
int state;
int vf1, vf2;
int ok = false;
WordType sele;
ObjectMolecule *obj0 = NULL, *obj1 = NULL, *obj2 = NULL;
if(!EditorActive(G)) {
ErrMessage(G, "Editor", "Must specify a bond first.");
} else {
sele0 = SelectorIndexByName(G, cEditorSele1);
if(sele0 >= 0) {
obj0 = SelectorGetFastSingleAtomObjectIndex(G, sele0, &i0);
sele1 = SelectorIndexByName(G, cEditorSele2);
obj1 = SelectorGetFastSingleAtomObjectIndex(G, sele1, &i1);
strcpy(sele, cEditorFragPref);
strcat(sele, "1");
sele2 = SelectorIndexByName(G, sele);
obj2 = SelectorGetFastSingleObjectMolecule(G, sele2);
if(!((sele0 >= 0) && (sele1 >= 0) && (sele2 >= 0) && (obj0 == obj1))) {
ErrMessage(G, "Editor", "Must specify a bond first.");
} else {
if((i0 >= 0) && (i1 >= 0)) {
state = SceneGetState(G);
vf1 = ObjectMoleculeGetAtomVertex(obj0, state, i0, I->V0);
vf2 = ObjectMoleculeGetAtomVertex(obj1, state, i1, I->V1);
if(vf1 && vf2) {
ObjectMoleculeSaveUndo(obj0, SceneGetState(G), false);
subtract3f(I->V1, I->V0, I->Axis);
average3f(I->V1, I->V0, I->Center);
normalize3f(I->Axis);
copy3f(I->V0, v1);
copy3f(I->V1, v0);
subtract3f(v1, v0, d1);
copy3f(d1, n0);
normalize3f(n0);
theta = (float) (cPI * angle / 180.0);
get_rotation_about3f3fTTTf(theta, n0, v1, m);
ok =
ObjectMoleculeTransformSelection(obj2, state, sele2, m, false, NULL, false,
false);
SceneInvalidate(G);
I->DragIndex = -1;
I->DragSelection = -1;
I->DragObject = NULL;
if(I->BondMode && SettingGetGlobal_b(G, cSetting_editor_auto_dihedral))
EditorDihedralInvalid(G, NULL);
}
}
}
}
}
return (ok);
}
/*========================================================================*/
int EditorSelect(PyMOLGlobals * G, const char *s0, const char *s1, const char *s2,
const char *s3, int pkresi, int pkbond, int quiet)
{
int i0 = -1;
int i1 = -1;
int i2 = -1;
int i3 = -1;
int sele0 = -1, sele1 = -1, sele2 = -1, sele3 = -1;
int result = false;
int ok = true;
ObjectMolecule *obj0 = NULL, *obj1 = NULL, *obj2 = NULL, *obj3 = NULL;
if(s0)
if(!*s0)
s0 = NULL;
if(s1)
if(!*s1)
s1 = NULL;
if(s2)
if(!*s2)
s2 = NULL;
if(s3)
if(!*s3)
s3 = NULL;
if(s0) {
sele0 = SelectorIndexByName(G, s0);
obj0 = SelectorGetFastSingleAtomObjectIndex(G, sele0, &i0);
ExecutiveDelete(G, cEditorSele1);
}
if(s1) {
sele1 = SelectorIndexByName(G, s1);
obj1 = SelectorGetFastSingleAtomObjectIndex(G, sele1, &i1);
ExecutiveDelete(G, cEditorSele2);
}
if(s2) {
sele2 = SelectorIndexByName(G, s2);
obj2 = SelectorGetFastSingleAtomObjectIndex(G, sele2, &i2);
ExecutiveDelete(G, cEditorSele3);
}
if(s3) {
sele3 = SelectorIndexByName(G, s3);
obj3 = SelectorGetFastSingleAtomObjectIndex(G, sele3, &i3);
ExecutiveDelete(G, cEditorSele4);
}
if(!(obj0 || obj1 || obj2 || obj3))
ok = false;
if(ok) {
if(obj0)
ObjectMoleculeVerifyChemistry(obj0, -1);
if(obj1 && (obj1 != obj0))
ObjectMoleculeVerifyChemistry(obj1, -1);
if(obj2 && (obj2 != obj0) && (obj2 != obj1))
ObjectMoleculeVerifyChemistry(obj2, -1);
if(obj3 && (obj3 != obj0) && (obj3 != obj1) && (obj3 != obj2))
ObjectMoleculeVerifyChemistry(obj3, -1);
if(i0 >= 0)
SelectorCreate(G, cEditorSele1, s0, NULL, quiet, NULL);
if(i1 >= 0)
SelectorCreate(G, cEditorSele2, s1, NULL, quiet, NULL);
if(i2 >= 0)
SelectorCreate(G, cEditorSele3, s2, NULL, quiet, NULL);
if(i3 >= 0)
SelectorCreate(G, cEditorSele4, s3, NULL, quiet, NULL);
EditorActivate(G, SceneGetState(G), pkbond);
if(pkresi)
EditorDefineExtraPks(G);
SceneInvalidate(G);
result = true;
} else {
EditorInactivate(G);
if(s0 && s0[0]) {
PRINTFB(G, FB_Editor, FB_Errors)
"Editor-Error: Invalid input selection(s).\n" ENDFB(G);
}
}
return (result);
}
/*========================================================================*/
int EditorIsAnActiveObject(PyMOLGlobals * G, ObjectMolecule * obj)
{
if(EditorActive(G)) {
if(obj) {
if(obj == SelectorGetFastSingleObjectMolecule(G,
SelectorIndexByName(G, cEditorSele1)))
return true;
if(obj == SelectorGetFastSingleObjectMolecule(G,
SelectorIndexByName(G, cEditorSele2)))
return true;
if(obj == SelectorGetFastSingleObjectMolecule(G,
SelectorIndexByName(G, cEditorSele3)))
return true;
if(obj == SelectorGetFastSingleObjectMolecule(G,
SelectorIndexByName(G, cEditorSele4)))
return true;
}
}
return false;
}
/*========================================================================*/
void EditorCycleValence(PyMOLGlobals * G, int quiet)
{
CEditor *I = G->Editor;
int sele0, sele1;
if(EditorActive(G)) {
ObjectMolecule *obj0, *obj1;
sele0 = SelectorIndexByName(G, cEditorSele1);
if(sele0 >= 0) {
sele1 = SelectorIndexByName(G, cEditorSele2);
if(sele1 >= 0) {
obj0 = SelectorGetFastSingleObjectMolecule(G, sele0);
obj1 = SelectorGetFastSingleObjectMolecule(G, sele1);
if((obj0 == obj1) && I->BondMode) {
ObjectMoleculeVerifyChemistry(obj0, -1);
ObjectMoleculeAdjustBonds(obj0, sele0, sele1, 0, 0);
}
}
}
}
}
/*========================================================================*/
void EditorAttach(PyMOLGlobals * G, const char *elem, int geom, int valence,
const char *name, int quiet)
{
int i0;
int sele0, sele1;
AtomInfoType *ai;
ObjectMolecule *obj0 = NULL, *obj1 = NULL;
int ok = true;
ai = (AtomInfoType *) VLAMalloc(1, sizeof(AtomInfoType), 1, true);
if(EditorActive(G)) {
sele0 = SelectorIndexByName(G, cEditorSele1);
if(sele0 >= 0) {
sele1 = SelectorIndexByName(G, cEditorSele2);
obj0 = SelectorGetFastSingleObjectMolecule(G, sele0);
obj1 = SelectorGetFastSingleObjectMolecule(G, sele1);
if(obj0) {
if(obj0->DiscreteFlag) {
ErrMessage(G, "Remove", "Can't attach atoms onto discrete objects.");
} else {
ObjectMoleculeVerifyChemistry(obj0, -1); /* remember chemistry for later */
if(obj1) {
if(obj0 == obj1) {
/* bond mode - behave like replace */
EditorReplace(G, elem, geom, valence, name, quiet);
}
} else {
/* atom mode */
i0 = ObjectMoleculeGetAtomIndex(obj0, sele0); /* slow */
if(i0 >= 0) {
UtilNCopy(ai->elem, elem, sizeof(ElemName));
ai->geom = geom;
ai->valence = valence;
if(name[0])
LexAssign(G, ai->name, name);
if (ok)
ok &= ObjectMoleculeAttach(obj0, i0, ai); /* will free ai */
ai = NULL;
}
}
}
}
}
}
VLAFreeP(ai); /* safety */
}
/*========================================================================*/
void EditorRemove(PyMOLGlobals * G, int hydrogen, int quiet)
{
#define cEditorRemoveSele "_EditorRemove"
if(EditorActive(G)) {
OrthoLineType buf;
CEditor *I = G->Editor;
int sele0 = SelectorIndexByName(G, cEditorSele1);
ObjectMolecule *obj0 = SelectorGetFastSingleObjectMolecule(G, sele0);
ObjectMoleculeVerifyChemistry(obj0, -1); /* remember chemistry for later */
if((sele0 >= 0) && obj0) {
int sele1 = SelectorIndexByName(G, cEditorSele2);
ObjectMolecule *obj1 = SelectorGetFastSingleObjectMolecule(G, sele1);
if((sele1 >= 0) && (obj0 == obj1) && I->BondMode) {
/* bond mode */
ObjectMoleculeRemoveBonds(obj0, sele0, sele1);
EditorInactivate(G);
} else {
int h_flag = false;
if(SelectorIndexByName(G, cEditorSet) < 0) {
int i0 = 0;
/* only one atom picked */
if(hydrogen) {
sprintf(buf, "((neighbor %s) and hydro)", cEditorSele1);
h_flag = SelectorCreate(G, cEditorRemoveSele, buf, NULL, false, NULL);
}
if(SelectorGetFastSingleAtomObjectIndex(G, sele0, &i0)) {
/* atom mode */
if(i0 >= 0) {
ExecutiveRemoveAtoms(G, cEditorSele1, quiet);
}
}
} else { /* multiple atoms picked */
if(hydrogen) {
sprintf(buf, "((neighbor %s) and hydro)", cEditorSet);
h_flag = SelectorCreate(G, cEditorRemoveSele, buf, NULL, false, NULL);
}
ExecutiveRemoveAtoms(G, cEditorSet, quiet);
}
EditorInactivate(G);
if(h_flag) {
ExecutiveRemoveAtoms(G, cEditorRemoveSele, quiet);
SelectorDelete(G, cEditorRemoveSele);
}
}
}
}
#undef cEditorRemoveSele
}
/*========================================================================*/
void EditorHFill(PyMOLGlobals * G, int quiet)
{
int sele0, sele1;
int i0;
OrthoLineType buffer, s1, s2;
ObjectMolecule *obj0 = NULL, *obj1 = NULL;
if(EditorActive(G)) {
sele0 = SelectorIndexByName(G, cEditorSele1);
obj0 = SelectorGetFastSingleObjectMolecule(G, sele0);
ObjectMoleculeVerifyChemistry(obj0, -1); /* remember chemistry for later */
if(sele0 >= 0) {
sele1 = SelectorIndexByName(G, cEditorSele2);
if(sele0 >= 0) {
if(sele1 >= 0){
sprintf(s2, "(%s) or (%s)",
cEditorSele1, cEditorSele2);
sprintf(buffer, "((neighbor (%s)) and hydro and not (%s))",
s2, s2);
} else {
sprintf(s2, "(%s)", cEditorSele1);
sprintf(buffer, "((neighbor %s) & hydro)", cEditorSele1);
}
SelectorGetTmp(G, buffer, s1);
ExecutiveRemoveAtoms(G, s1, quiet);
SelectorFreeTmp(G, s1);
i0 = ObjectMoleculeGetAtomIndex(obj0, sele0);
obj0->AtomInfo[i0].chemFlag = false;
ExecutiveAddHydrogens(G, cEditorSele1, quiet);
if(sele1 >= 0) {
obj1 = SelectorGetFastSingleObjectMolecule(G, sele1);
i0 = ObjectMoleculeGetAtomIndex(obj1, sele1);
obj1->AtomInfo[i0].chemFlag = false;
ExecutiveAddHydrogens(G, cEditorSele2, quiet);
}
}
}
}
}
/*========================================================================*/
void EditorHFix(PyMOLGlobals * G, const char *sele, int quiet)
{
int sele0, sele1;
ObjectMolecule *obj0, *obj1;
if((!sele) || (!sele[0])) { /* if selection is empty, then apply to picked atoms */
if(EditorActive(G)) {
sele0 = SelectorIndexByName(G, cEditorSele1);
if(sele0 >= 0) {
obj0 = SelectorGetFastSingleObjectMolecule(G, sele0);
ObjectMoleculeVerifyChemistry(obj0, -1);
ExecutiveFixHydrogens(G, cEditorSele1, quiet);
}
sele1 = SelectorIndexByName(G, cEditorSele2);
if(sele1 >= 0) {
obj1 = SelectorGetFastSingleObjectMolecule(G, sele1);
ObjectMoleculeVerifyChemistry(obj1, -1);
ExecutiveFixHydrogens(G, cEditorSele2, quiet);
}
}
} else {
ExecutiveFixHydrogens(G, sele, quiet);
}
}
/*========================================================================*/
void EditorReplace(PyMOLGlobals * G, const char *elem, int geom, int valence, const char *name,
int quiet)
{
int i0;
int sele0;
AtomInfoType ai;
ObjectMolecule *obj0 = NULL;
int ok = true;
UtilZeroMem(&ai, sizeof(AtomInfoType));
if(EditorActive(G)) {
sele0 = SelectorIndexByName(G, cEditorSele1);
obj0 = SelectorGetFastSingleObjectMolecule(G, sele0);
if(obj0->DiscreteFlag) {
ErrMessage(G, "Remove", "Can't attach atoms onto discrete objects.");
} else {
ObjectMoleculeVerifyChemistry(obj0, -1); /* remember chemistry for later */
if(sele0 >= 0) {
i0 = ObjectMoleculeGetAtomIndex(obj0, sele0); /* slow */
if(i0 >= 0) {
UtilNCopy(ai.elem, elem, sizeof(ElemName));
if(name[0])
LexAssign(G, ai.name, name);
ai.geom = geom;
ai.valence = valence;
if (ok)
ok &= ObjectMoleculePrepareAtom(obj0, i0, &ai);
if (ok)
ok &= ObjectMoleculePreposReplAtom(obj0, i0, &ai);
ObjectMoleculeReplaceAtom(obj0, i0, &ai); /* invalidates */
ObjectMoleculeVerifyChemistry(obj0, -1);
ObjectMoleculeFillOpenValences(obj0, i0);
if (ok)
ok &= ObjectMoleculeSort(obj0);
ObjectMoleculeUpdateIDNumbers(obj0);
EditorInactivate(G);
}
}
}
}
}
static void draw_bond(PyMOLGlobals * G, float *v0, float *v1, CGO *shaderCGO)
{
float v[3], v2[3], v3[3];
float d0[3], n0[3], n1[3], n2[3];
float x[50], y[50];
int nEdge;
int c, a;
float tube_size1 = 0.5F;
float tube_size3 = 0.45F;
nEdge = SettingGetGlobal_i(G, cSetting_stick_quality) * 2;
if(nEdge > 50)
nEdge = 50;
if(nEdge < 3)
nEdge = 3;
subdivide(nEdge, x, y);
subtract3f(v1, v0, d0);
average3f(v1, v0, v2);
average3f(v0, v2, v3);
average3f(v2, v3, v2);
copy3f(d0, n0);
get_system1f3f(n0, n1, n2);
if (shaderCGO){
CGOColorv(shaderCGO, ColorGet(G, 0));
CGOBegin(shaderCGO, GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n1[0] * x[c] + n2[0] * y[c];
v[1] = n1[1] * x[c] + n2[1] * y[c];
v[2] = n1[2] * x[c] + n2[2] * y[c];
normalize3f(v);
CGONormalv(shaderCGO, v);
v[0] = v2[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v2[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v2[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
CGOVertexv(shaderCGO, v);
v[0] = v3[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v3[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v3[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
CGOVertexv(shaderCGO, v);
}
CGOEnd(shaderCGO);
CGOBegin(shaderCGO, GL_TRIANGLE_STRIP);
CGONormalv(shaderCGO, n0);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = v2[0] + n1[0] * tube_size3 * x[c] + n2[0] * tube_size3 * y[c];
v[1] = v2[1] + n1[1] * tube_size3 * x[c] + n2[1] * tube_size3 * y[c];
v[2] = v2[2] + n1[2] * tube_size3 * x[c] + n2[2] * tube_size3 * y[c];
CGOVertexv(shaderCGO, v);
v[0] = v2[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v2[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v2[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
CGOVertexv(shaderCGO, v);
}
CGOEnd(shaderCGO);
CGOBegin(shaderCGO, GL_TRIANGLE_STRIP);
scale3f(n0, -1.0F, v);
CGONormalv(shaderCGO, v);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = v3[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v3[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v3[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
CGOVertexv(shaderCGO, v);
v[0] = v3[0] + n1[0] * tube_size3 * x[c] + n2[0] * tube_size3 * y[c];
v[1] = v3[1] + n1[1] * tube_size3 * x[c] + n2[1] * tube_size3 * y[c];
v[2] = v3[2] + n1[2] * tube_size3 * x[c] + n2[2] * tube_size3 * y[c];
CGOVertexv(shaderCGO, v);
}
CGOEnd(shaderCGO);
} else {
#ifdef PURE_OPENGL_ES_2
/* TODO */
#else
glColor3fv(ColorGet(G, 0));
glBegin(GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n1[0] * x[c] + n2[0] * y[c];
v[1] = n1[1] * x[c] + n2[1] * y[c];
v[2] = n1[2] * x[c] + n2[2] * y[c];
normalize3f(v);
glNormal3fv(v);
v[0] = v2[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v2[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v2[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
glVertex3fv(v);
v[0] = v3[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v3[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v3[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
glVertex3fv(v);
}
glEnd();
#endif
#ifdef PURE_OPENGL_ES_2
/* TODO */
#else
glBegin(GL_TRIANGLE_STRIP);
glNormal3fv(n0);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = v2[0] + n1[0] * tube_size3 * x[c] + n2[0] * tube_size3 * y[c];
v[1] = v2[1] + n1[1] * tube_size3 * x[c] + n2[1] * tube_size3 * y[c];
v[2] = v2[2] + n1[2] * tube_size3 * x[c] + n2[2] * tube_size3 * y[c];
glVertex3fv(v);
v[0] = v2[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v2[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v2[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
glVertex3fv(v);
}
glEnd();
#endif
#ifdef PURE_OPENGL_ES_2
/* TODO */
#else
glBegin(GL_TRIANGLE_STRIP);
scale3f(n0, -1.0F, v);
glNormal3fv(v);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = v3[0] + n1[0] * tube_size1 * x[c] + n2[0] * tube_size1 * y[c];
v[1] = v3[1] + n1[1] * tube_size1 * x[c] + n2[1] * tube_size1 * y[c];
v[2] = v3[2] + n1[2] * tube_size1 * x[c] + n2[2] * tube_size1 * y[c];
glVertex3fv(v);
v[0] = v3[0] + n1[0] * tube_size3 * x[c] + n2[0] * tube_size3 * y[c];
v[1] = v3[1] + n1[1] * tube_size3 * x[c] + n2[1] * tube_size3 * y[c];
v[2] = v3[2] + n1[2] * tube_size3 * x[c] + n2[2] * tube_size3 * y[c];
glVertex3fv(v);
}
glEnd();
#endif
}
}
static void draw_globe(PyMOLGlobals * G, float *v2, int number, CGO *shaderCGO)
{
float v[3];
float n0[3], n1[3], n2[3];
float x[50], y[50];
int nEdge;
int a, c;
float radius = 0.5F;
float width_base = 0.10F;
float width = 0.0F;
float offset = 0.0F;
int cycle_counter;
nEdge = SettingGetGlobal_i(G, cSetting_stick_quality) * 2;
if(nEdge > 50)
nEdge = 50;
if(nEdge < 3)
nEdge = 3;
subdivide(nEdge, x, y);
n0[0] = 1.0;
n0[1] = 0.0;
n0[2] = 0.0;
get_system1f3f(n0, n1, n2);
#ifndef PURE_OPENGL_ES_2
glColor3fv(ColorGet(G, 0));
#endif
if (shaderCGO)
CGOColorv(shaderCGO, ColorGet(G, 0));
cycle_counter = number;
while(cycle_counter) {
switch (number) {
case 1:
width = width_base;
offset = 0.0F;
break;
case 2:
switch (cycle_counter) {
case 2:
width = width_base / 2;
offset = width_base;
break;
case 1:
offset = -width_base;
break;
}
break;
case 3:
switch (cycle_counter) {
case 3:
width = width_base / 2.8F;
offset = 1.33F * width_base;
break;
case 2:
offset = 0.0F;
break;
case 1:
offset = -1.33F * width_base;
break;
}
break;
case 4:
switch (cycle_counter) {
case 4:
width = width_base / 3.2F;
offset = 2 * width_base;
break;
case 3:
offset = 0.66F * width_base;
break;
case 2:
offset = -0.66F * width_base;
break;
case 1:
offset = -2 * width_base;
break;
}
}
if (shaderCGO){
CGOBegin(shaderCGO, GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n1[0] * x[c] + n2[0] * y[c];
v[1] = n1[1] * x[c] + n2[1] * y[c];
v[2] = n1[2] * x[c] + n2[2] * y[c];
normalize3f(v);
CGONormalv(shaderCGO, v);
v[0] =
v2[0] + n1[0] * radius * x[c] + n2[0] * radius * y[c] + n0[0] * (offset + width);
v[1] =
v2[1] + n1[1] * radius * x[c] + n2[1] * radius * y[c] + n0[1] * (offset + width);
v[2] =
v2[2] + n1[2] * radius * x[c] + n2[2] * radius * y[c] + n0[2] * (offset + width);
CGOVertexv(shaderCGO, v);
v[0] =
v2[0] + n1[0] * radius * x[c] + n2[0] * radius * y[c] + n0[0] * (offset - width);
v[1] =
v2[1] + n1[1] * radius * x[c] + n2[1] * radius * y[c] + n0[1] * (offset - width);
v[2] =
v2[2] + n1[2] * radius * x[c] + n2[2] * radius * y[c] + n0[2] * (offset - width);
CGOVertexv(shaderCGO, v);
}
CGOEnd(shaderCGO);
CGOBegin(shaderCGO, GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n2[0] * x[c] + n0[0] * y[c];
v[1] = n2[1] * x[c] + n0[1] * y[c];
v[2] = n2[2] * x[c] + n0[2] * y[c];
normalize3f(v);
CGONormalv(shaderCGO, v);
v[0] =
v2[0] + n2[0] * radius * x[c] + n0[0] * radius * y[c] + n1[0] * (offset + width);
v[1] =
v2[1] + n2[1] * radius * x[c] + n0[1] * radius * y[c] + n1[1] * (offset + width);
v[2] =
v2[2] + n2[2] * radius * x[c] + n0[2] * radius * y[c] + n1[2] * (offset + width);
CGOVertexv(shaderCGO, v);
v[0] =
v2[0] + n2[0] * radius * x[c] + n0[0] * radius * y[c] + n1[0] * (offset - width);
v[1] =
v2[1] + n2[1] * radius * x[c] + n0[1] * radius * y[c] + n1[1] * (offset - width);
v[2] =
v2[2] + n2[2] * radius * x[c] + n0[2] * radius * y[c] + n1[2] * (offset - width);
CGOVertexv(shaderCGO, v);
}
CGOEnd(shaderCGO);
CGOBegin(shaderCGO, GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n0[0] * x[c] + n1[0] * y[c];
v[1] = n0[1] * x[c] + n1[1] * y[c];
v[2] = n0[2] * x[c] + n1[2] * y[c];
normalize3f(v);
CGONormalv(shaderCGO, v);
v[0] =
v2[0] + n0[0] * radius * x[c] + n1[0] * radius * y[c] + n2[0] * (offset + width);
v[1] =
v2[1] + n0[1] * radius * x[c] + n1[1] * radius * y[c] + n2[1] * (offset + width);
v[2] =
v2[2] + n0[2] * radius * x[c] + n1[2] * radius * y[c] + n2[2] * (offset + width);
CGOVertexv(shaderCGO, v);
v[0] =
v2[0] + n0[0] * radius * x[c] + n1[0] * radius * y[c] + n2[0] * (offset - width);
v[1] =
v2[1] + n0[1] * radius * x[c] + n1[1] * radius * y[c] + n2[1] * (offset - width);
v[2] =
v2[2] + n0[2] * radius * x[c] + n1[2] * radius * y[c] + n2[2] * (offset - width);
CGOVertexv(shaderCGO, v);
}
CGOEnd(shaderCGO);
} else {
#ifdef PURE_OPENGL_ES_2
/* TODO */
#else
glBegin(GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n1[0] * x[c] + n2[0] * y[c];
v[1] = n1[1] * x[c] + n2[1] * y[c];
v[2] = n1[2] * x[c] + n2[2] * y[c];
normalize3f(v);
glNormal3fv(v);
v[0] =
v2[0] + n1[0] * radius * x[c] + n2[0] * radius * y[c] + n0[0] * (offset + width);
v[1] =
v2[1] + n1[1] * radius * x[c] + n2[1] * radius * y[c] + n0[1] * (offset + width);
v[2] =
v2[2] + n1[2] * radius * x[c] + n2[2] * radius * y[c] + n0[2] * (offset + width);
glVertex3fv(v);
v[0] =
v2[0] + n1[0] * radius * x[c] + n2[0] * radius * y[c] + n0[0] * (offset - width);
v[1] =
v2[1] + n1[1] * radius * x[c] + n2[1] * radius * y[c] + n0[1] * (offset - width);
v[2] =
v2[2] + n1[2] * radius * x[c] + n2[2] * radius * y[c] + n0[2] * (offset - width);
glVertex3fv(v);
}
glEnd();
#endif
#ifdef PURE_OPENGL_ES_2
/* TODO */
#else
glBegin(GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n2[0] * x[c] + n0[0] * y[c];
v[1] = n2[1] * x[c] + n0[1] * y[c];
v[2] = n2[2] * x[c] + n0[2] * y[c];
normalize3f(v);
glNormal3fv(v);
v[0] =
v2[0] + n2[0] * radius * x[c] + n0[0] * radius * y[c] + n1[0] * (offset + width);
v[1] =
v2[1] + n2[1] * radius * x[c] + n0[1] * radius * y[c] + n1[1] * (offset + width);
v[2] =
v2[2] + n2[2] * radius * x[c] + n0[2] * radius * y[c] + n1[2] * (offset + width);
glVertex3fv(v);
v[0] =
v2[0] + n2[0] * radius * x[c] + n0[0] * radius * y[c] + n1[0] * (offset - width);
v[1] =
v2[1] + n2[1] * radius * x[c] + n0[1] * radius * y[c] + n1[1] * (offset - width);
v[2] =
v2[2] + n2[2] * radius * x[c] + n0[2] * radius * y[c] + n1[2] * (offset - width);
glVertex3fv(v);
}
glEnd();
#endif
#ifdef PURE_OPENGL_ES_2
/* TODO */
#else
glBegin(GL_TRIANGLE_STRIP);
for(a = 0; a <= nEdge; a++) {
c = a % nEdge;
v[0] = n0[0] * x[c] + n1[0] * y[c];
v[1] = n0[1] * x[c] + n1[1] * y[c];
v[2] = n0[2] * x[c] + n1[2] * y[c];
normalize3f(v);
glNormal3fv(v);
v[0] =
v2[0] + n0[0] * radius * x[c] + n1[0] * radius * y[c] + n2[0] * (offset + width);
v[1] =
v2[1] + n0[1] * radius * x[c] + n1[1] * radius * y[c] + n2[1] * (offset + width);
v[2] =
v2[2] + n0[2] * radius * x[c] + n1[2] * radius * y[c] + n2[2] * (offset + width);
glVertex3fv(v);
v[0] =
v2[0] + n0[0] * radius * x[c] + n1[0] * radius * y[c] + n2[0] * (offset - width);
v[1] =
v2[1] + n0[1] * radius * x[c] + n1[1] * radius * y[c] + n2[1] * (offset - width);
v[2] =
v2[2] + n0[2] * radius * x[c] + n1[2] * radius * y[c] + n2[2] * (offset - width);
glVertex3fv(v);
}
glEnd();
#endif
}
cycle_counter--;
}
}
/*
static void draw_string(float *v,char *l)
{
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
if(*l) {
glColor3f(1.0,0.0,0.5);
glRasterPos4f(v[0],v[1],v[2],1.0);
}
while(*l) {
p_g lutBi tmapChar acter(P_G LUT_BITMAP_8_BY_13,*(l++));
}
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
}
*/
/*========================================================================*/
void EditorRender(PyMOLGlobals * G, int state)
{
CEditor *I = G->Editor;
int sele1, sele2, sele3, sele4;
float v0[3], v1[3];
float vp[12], *vv;
/* int v_cnt; */
ObjectMolecule *obj1 = NULL, *obj2 = NULL, *obj3 = NULL, *obj4 = NULL;
int index1, index2, index3, index4;
int st, frozen;
CGO *shaderCGO = NULL;
if(EditorActive(G)) {
int use_shader = SettingGetGlobal_b(G, cSetting_use_shaders);
if (use_shader){
if (!I->shaderCGO){
shaderCGO = CGONew(G);
} else {
CGORenderGL(I->shaderCGO, NULL, NULL, NULL, NULL, NULL);
return;
}
} else {
CGOFree(I->shaderCGO);
}
PRINTFD(G, FB_Editor)
" EditorRender-Debug: rendering...\n" ENDFD;
if(G->HaveGUI && G->ValidContext) {
sele1 = SelectorIndexByName(G, cEditorSele1);
sele2 = SelectorIndexByName(G, cEditorSele2);
sele3 = SelectorIndexByName(G, cEditorSele3);
sele4 = SelectorIndexByName(G, cEditorSele4);
obj1 = SelectorGetFastSingleAtomObjectIndex(G, sele1, &index1);
obj2 = SelectorGetFastSingleAtomObjectIndex(G, sele2, &index2);
obj3 = SelectorGetFastSingleAtomObjectIndex(G, sele3, &index3);
obj4 = SelectorGetFastSingleAtomObjectIndex(G, sele4, &index4);
/* printf("%d %d %d %d\n",sele1,sele2,sele3,sele4);
printf("%p %p %p %p\n",obj1,obj2,obj3,obj4);
printf("%d %d %d %d\n",index1,index2,index3,index4); */
if((sele1 >= 0) && (sele2 >= 0) && I->BondMode && obj1 && obj2) {
/* bond mode */
ObjectMoleculeGetAtomTxfVertex(obj1, state, index1, v0);
ObjectMoleculeGetAtomTxfVertex(obj2, state, index2, v1);
draw_bond(G, v0, v1, shaderCGO);
} else {
/* atom mode */
vv = vp;
if(obj1) {
/* if the user froze a state, use it instead of the global */
if((frozen = SettingGetIfDefined_i(obj1->Obj.G, obj1->Obj.Setting, cSetting_state, &st))) {
state = st-1;
}
if(ObjectMoleculeGetAtomTxfVertex(obj1, state, index1, vv)) {
draw_globe(G, vv, 1, shaderCGO);
vv += 3;
}
}
if(obj2) {
if((frozen = SettingGetIfDefined_i(obj2->Obj.G, obj2->Obj.Setting, cSetting_state, &st))) {
state = st-1;
}
if(ObjectMoleculeGetAtomTxfVertex(obj2, state, index2, vv)) {
draw_globe(G, vv, 2, shaderCGO);
vv += 3;
}
}
if(obj3) {
if((frozen = SettingGetIfDefined_i(obj3->Obj.G, obj3->Obj.Setting, cSetting_state, &st))) {
state = st-1;
}
if(ObjectMoleculeGetAtomTxfVertex(obj3, state, index3, vv)) {
draw_globe(G, vv, 3, shaderCGO);
vv += 3;
}
}
if(obj4) {
if((frozen = SettingGetIfDefined_i(obj4->Obj.G, obj4->Obj.Setting, cSetting_state, &st))) {
state = st-1;
}
if(ObjectMoleculeGetAtomTxfVertex(obj4, state, index4, vv)) {
draw_globe(G, vv, 4, shaderCGO);
vv += 3;
}
}
}
}
if (shaderCGO){
CGO *convertcgo = NULL;
int ok = true;
CGOStop(shaderCGO);
CHECKOK(ok, shaderCGO);
convertcgo = CGOCombineBeginEnd(shaderCGO, 0);
CHECKOK(ok, convertcgo);
CGOFree(shaderCGO);
if (ok){
CGO *tmpCGO = CGONew(G), *convertcgo2 = NULL;
if (ok) ok &= CGOEnable(tmpCGO, GL_DEFAULT_SHADER);
if (ok) ok &= CGODisable(tmpCGO, GL_TWO_SIDED_LIGHTING);
convertcgo2 = CGOOptimizeToVBONotIndexedNoShader(convertcgo, 0);
if (ok) ok &= CGOAppendNoStop(tmpCGO, convertcgo2);
if (ok) ok &= CGODisable(tmpCGO, GL_DEFAULT_SHADER);
if (ok) ok &= CGOStop(tmpCGO);
CGOFreeWithoutVBOs(convertcgo2);
I->shaderCGO = tmpCGO;
I->shaderCGO->use_shader = true;
}
CGOFree(convertcgo);
if (ok){
CGORenderGL(I->shaderCGO, NULL, NULL, NULL, NULL, NULL);
}
}
}
}
/*========================================================================*/
void EditorInactivate(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
PRINTFD(G, FB_Editor)
" EditorInactivate-Debug: callend.\n" ENDFD;
I->DihedObject = NULL;
I->DragObject = NULL;
I->BondMode = false;
I->ShowFrags = false;
I->NFrag = 0;
I->Active = false;
SelectorDeletePrefixSet(G, cEditorFragPref);
SelectorDeletePrefixSet(G, cEditorBasePref);
ExecutiveDelete(G, cEditorSele1);
ExecutiveDelete(G, cEditorSele2);
ExecutiveDelete(G, cEditorSele3);
ExecutiveDelete(G, cEditorSele4);
ExecutiveDelete(G, cEditorSet);
ExecutiveDelete(G, cEditorBond);
ExecutiveDelete(G, cEditorRes);
ExecutiveDelete(G, cEditorChain);
ExecutiveDelete(G, cEditorObject);
ExecutiveDelete(G, cEditorComp);
ExecutiveDelete(G, cEditorLink);
ExecutiveDelete(G, cEditorDihedral);
ExecutiveDelete(G, cEditorDihe1);
ExecutiveDelete(G, cEditorDihe2);
ExecutiveDelete(G, cEditorMeasure);
EditorMouseInvalid(G);
EditorInvalidateShaderCGO(G);
SceneInvalidate(G);
}
/*========================================================================*/
/*
* Create a transient distance, angle, or dihedral measurement between
* the pk1 - pk4 atoms.
*
* Assumes that the cEditorMeasure object does not exist yet.
*/
static
void EditorAutoMeasure(PyMOLGlobals * G,
int sele1, int sele2, int sele3, int sele4, int state)
{
if (sele1 < 0 || sele2 < 0)
return;
float _measure_value;
if (sele3 < 0) {
ExecutiveDist(G, &_measure_value, cEditorMeasure,
cEditorSele1, cEditorSele2,
0, -1.f, true, true, false /* reset */, state, false);
} else if (sele4 < 0) {
ExecutiveAngle(G, &_measure_value, cEditorMeasure,
cEditorSele1, cEditorSele2, cEditorSele3,
0, true, false /* reset */, false, true, state);
} else {
ExecutiveDihedral(G, &_measure_value, cEditorMeasure,
cEditorSele1, cEditorSele2, cEditorSele3, cEditorSele4,
0, true, false /* reset */, false, true, state);
}
ExecutiveColor(G, cEditorMeasure, "gray", 0x1, true);
}
/*========================================================================*/
void EditorActivate(PyMOLGlobals * G, int state, int enable_bond)
{
int sele1, sele2, sele3, sele4;
CEditor *I = G->Editor;
sele1 = SelectorIndexByName(G, cEditorSele1);
sele2 = SelectorIndexByName(G, cEditorSele2);
sele3 = SelectorIndexByName(G, cEditorSele3);
sele4 = SelectorIndexByName(G, cEditorSele4);
if((sele1 >= 0) || (sele2 >= 0) || (sele3 >= 0) || (sele4 >= 0)) {
I->Active = true;
ExecutiveDelete(G, cEditorComp);
ExecutiveDelete(G, cEditorRes);
ExecutiveDelete(G, cEditorChain);
ExecutiveDelete(G, cEditorObject);
ExecutiveDelete(G, cEditorBond);
ExecutiveDelete(G, cEditorDihedral);
ExecutiveDelete(G, cEditorDihe1);
ExecutiveDelete(G, cEditorDihe2);
ExecutiveDelete(G, cEditorMeasure);
I->BondMode = enable_bond;
I->NFrag = SelectorSubdivide(G, cEditorFragPref,
sele1, sele2,
sele3, sele4,
cEditorBasePref, cEditorComp, &I->BondMode);
/* just returns 'state' */
state = EditorGetEffectiveState(G, NULL, state);
I->ActiveState = state;
if(0 && (I->NFrag > 1) && SettingGetGlobal_b(G, cSetting_editor_label_fragments)) {
/* SelectorComputeFragPos(G,obj,I->ActiveState,I->NFrag,cEditorFragPref,&I->PosVLA); */
I->ShowFrags = true;
} else {
I->ShowFrags = false;
}
if(SettingGetGlobal_b(G, cSetting_auto_hide_selections))
ExecutiveHideSelections(G);
if(I->BondMode && SettingGetGlobal_b(G, cSetting_editor_auto_dihedral))
EditorDihedralInvalid(G, NULL);
if (!I->BondMode && SettingGetGlobal_b(G, cSetting_editor_auto_measure))
EditorAutoMeasure(G, sele1, sele2, sele3, sele4, state);
} else {
EditorInactivate(G);
}
EditorMouseInvalid(G);
EditorInvalidateShaderCGO(G);
}
/*========================================================================*/
void EditorSetDrag(PyMOLGlobals * G, CObject * obj, int sele, int quiet, int state)
{
EditorInactivate(G);
state = EditorGetEffectiveState(G, obj, state);
if(obj->type == cObjectMolecule) {
ObjectMolecule *objMol = (ObjectMolecule*)(void*)obj;
if(ObjectMoleculeCheckFullStateSelection(objMol, sele, state)) {
int matrix_mode = SettingGet_i(G, obj->Setting, NULL, cSetting_matrix_mode);
if(matrix_mode>=1) {
/* force / coerce object matrix drags? */
sele = -1;
}
}
}
EditorPrepareDrag(G, obj, sele, -1, state, 0);
}
void EditorReadyDrag(PyMOLGlobals * G, int state)
{
CEditor *I = G->Editor;
if(I->DragObject && (I->DragIndex == -1)) {
EditorPrepareDrag(G, I->DragObject, I->DragSelection, -1, state, 0);
}
}
/*========================================================================*/
void EditorPrepareDrag(PyMOLGlobals * G, CObject * obj,
int sele, int index, int state, int mode)
{
int frg;
int sele0 = -1, sele1 = -1, sele2 = -1, sele3 = -1;
int s;
WordType name;
int seleFlag = false;
int i0, i1, i2, i3;
CEditor *I = G->Editor;
int log_trans = SettingGetGlobal_b(G, cSetting_log_conformations);
int drag_sele = -1;
ObjectMolecule *objMol = NULL;
PRINTFD(G, FB_Editor)
" EditorPrepareDrag-Debug: entered. obj %p index %d\n", (void *) obj, index ENDFD;
if(obj->type == cObjectMolecule)
objMol = (ObjectMolecule*)(void*)obj;
state = EditorGetEffectiveState(G, obj, state);
/* TODO: if user is drags label, then the editor must be deactivated */
if((!EditorActive(G))||(!objMol)) {
/* non-anchored dragging of objects and now selections */
float mn[3], mx[3];
I->DragObject = obj;
I->DragIndex = index; /* set to -1 when in "mouse drag" mode */
I->DragSelection = sele;
I->DragHaveBase = false;
if(sele >= 0) {
char *sele_name = SelectorGetNameFromIndex(G, sele);
if(sele_name) {
strcpy(I->DragSeleName, sele_name);
if(SettingGetGlobal_b(G, cSetting_editor_auto_origin)) {
if(I->FavorOrigin) {
I->DragHaveBase = true;
copy3f(I->FavoredOrigin, I->DragBase);
} else {
if(ExecutiveGetExtent(G, sele_name, mn, mx, true, state, true)) {
average3f(mn, mx, I->DragBase);
I->DragHaveBase = true;
}
}
}
} else {
I->DragSeleName[0] = 0;
}
} else {
if(SettingGetGlobal_b(G, cSetting_editor_auto_origin)) {
if(I->FavorOrigin) {
I->DragHaveBase = true;
copy3f(I->FavoredOrigin, I->DragBase);
} else {
if(ExecutiveGetExtent(G, obj->Name, mn, mx, true, state, true)) {
average3f(mn, mx, I->DragBase);
I->DragHaveBase = true;
}
}
}
}
} else {
/* anchored / fragment dragging */
for(frg = 1; frg <= I->NFrag; frg++) {
sprintf(name, "%s%1d", cEditorFragPref, frg);
drag_sele = SelectorIndexByName(G, name);
if(drag_sele >= 0) {
s = objMol->AtomInfo[index].selEntry;
seleFlag = SelectorIsMember(G, s, drag_sele);
}
if(seleFlag) {
strcpy(I->DragSeleName, name);
break;
}
}
if(seleFlag) { /* normal selection */
PRINTFB(G, FB_Editor, FB_Blather)
" Editor: grabbing (%s).", name ENDFB(G);
I->DragIndex = index;
I->DragSelection = drag_sele;
I->DragObject = obj;
I->DragHaveAxis = false;
I->DragHaveBase = false;
I->DragBondFlag = false;
I->DragSlowFlag = false;
sprintf(name, "%s%1d", cEditorBasePref, frg); /* get relevant base vertex of bond */
sele1 = SelectorIndexByName(G, name);
if(sele1 >= 0) {
i1 = ObjectMoleculeGetAtomIndex(objMol, sele1);
if(i1 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i1, I->DragBase);
I->DragHaveBase = true;
/*printf("base %s\n",name); */
}
}
/* get axis or base atom */
{
int cnt = 0;
if((sele0 = SelectorIndexByName(G, cEditorSele1)) >= 0) {
if(SelectorIsAtomBondedToSele(G, objMol, sele0, drag_sele))
cnt++;
else
sele0 = -1;
}
if((sele1 = SelectorIndexByName(G, cEditorSele2)) >= 0) {
if(SelectorIsAtomBondedToSele(G, objMol, sele1, drag_sele))
cnt++;
else
sele1 = -1;
}
if((sele2 = SelectorIndexByName(G, cEditorSele3)) >= 0) {
if(SelectorIsAtomBondedToSele(G, objMol, sele2, drag_sele))
cnt++;
else
sele2 = -1;
}
if((sele3 = SelectorIndexByName(G, cEditorSele4)) >= 0) {
if(SelectorIsAtomBondedToSele(G, objMol, sele3, drag_sele))
cnt++;
else
sele3 = -1;
}
i0 = ObjectMoleculeGetAtomIndex(objMol, sele0);
i1 = ObjectMoleculeGetAtomIndex(objMol, sele1);
i2 = ObjectMoleculeGetAtomIndex(objMol, sele2);
i3 = ObjectMoleculeGetAtomIndex(objMol, sele3);
if(cnt > 1) { /* bond/multiatom mode */
I->DragBondFlag = I->BondMode;
zero3f(I->Center);
if(i0 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i0, I->V0);
} else if(i1 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i1, I->V0);
} else if(i2 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i2, I->V0);
} else if(i3 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i3, I->V0);
}
if(i0 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i0, I->V1);
add3f(I->V1, I->Center, I->Center);
}
if(i1 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i1, I->V1);
add3f(I->V1, I->Center, I->Center);
}
if(i2 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i2, I->V1);
add3f(I->V1, I->Center, I->Center);
}
if(i3 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i3, I->V1);
add3f(I->V1, I->Center, I->Center);
}
{
float div = 1.0F / cnt;
scale3f(I->Center, div, I->Center);
}
subtract3f(I->Center, I->V0, I->Axis);
normalize3f(I->Axis);
I->DragHaveAxis = true;
if(SettingGetGlobal_b(G, cSetting_editor_auto_origin)) {
if(I->FavorOrigin) {
I->DragHaveBase = true;
copy3f(I->FavoredOrigin, I->DragBase);
} else {
copy3f(I->Center, I->DragBase);
I->DragHaveBase = true;
}
}
} else { /* atom mode */
if(i0 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i0, I->V0);
} else if(i1 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i1, I->V0);
} else if(i2 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i2, I->V0);
} else if(i3 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i3, I->V0);
}
if(I->DragHaveBase) {
copy3f(I->DragBase, I->V1);
subtract3f(I->V1, I->V0, I->Axis);
average3f(I->V1, I->V0, I->Center);
normalize3f(I->Axis);
I->DragHaveAxis = true;
if(mode == cButModeRotFrag) {
copy3f(I->V0, I->DragBase);
}
}
}
}
} else { /* clicked directly on an anchor atom */
sele0 = SelectorIndexByName(G, cEditorSele1);
if(sele0 < 0)
sele0 = SelectorIndexByName(G, cEditorSele2);
if(sele0 < 0)
sele0 = SelectorIndexByName(G, cEditorSele3);
if(sele0 < 0)
sele0 = SelectorIndexByName(G, cEditorSele4);
if(sele0 >= 0) {
s = objMol->AtomInfo[index].selEntry;
seleFlag = SelectorIsMember(G, s, sele0);
}
PRINTFB(G, FB_Editor, FB_Actions)
" Editor: grabbing all fragments." ENDFB(G);
I->DragIndex = index;
I->DragSelection = SelectorIndexByName(G, cEditorComp);
strcpy(I->DragSeleName, cEditorComp);
I->DragObject = obj;
I->DragHaveAxis = false;
I->DragHaveBase = false;
I->DragBondFlag = false;
I->DragSlowFlag = true;
if(sele0 >= 0) { /* just provide a base vector, no valid axis exists */
i1 = ObjectMoleculeGetAtomIndex(objMol, sele0);
if(i1 >= 0) {
ObjectMoleculeGetAtomTxfVertex(objMol, state, i1, I->DragBase);
I->DragHaveBase = true;
I->DragBondFlag = true;
}
}
}
if(!seleFlag) {
I->DragIndex = -1;
I->DragSelection = -1;
I->DragObject = NULL;
}
}
if(I->DragObject) {
I->ShowFrags = false;
if(objMol) {
ObjectMoleculeSaveUndo(objMol, state, log_trans);
if(SettingGetGlobal_b(G, cSetting_auto_sculpt)) {
SettingSetGlobal_b(G, cSetting_sculpting, 1);
if(!objMol->Sculpt)
ObjectMoleculeSculptImprint(objMol, state, -1, 0);
}
}
}
if(log_trans)
PLogFlush(G);
PRINTFD(G, FB_Editor)
" EditorPrepDrag-Debug: leaving Index %d Sele %d Object %p\n Axis %d Base %d BondFlag %d SlowFlag %d seleFlag %d\n",
I->DragIndex, I->DragSelection, (void *) I->DragObject,
I->DragHaveAxis, I->DragHaveBase, I->DragBondFlag, I->DragSlowFlag, seleFlag ENDFD;
}
int EditorDraggingObjectMatrix(PyMOLGlobals *G)
{
CEditor *I = G->Editor;
if(I->DragObject && (I->DragSelection < 0) && (I->DragIndex == -1)) {
return true;
}
return false;
}
void EditorDrag(PyMOLGlobals * G, CObject * obj, int index, int mode, int state,
float *pt, float *mov, float *z_dir)
{
CEditor *I = G->Editor;
float v0[3], v1[3], v2[3], v3[3], v4[4], cp[3];
float d0[3], d1[3], d2[3], n0[3], n1[3], n2[3];
float opp, adj, theta;
float m[16];
int log_trans = SettingGetGlobal_b(G, cSetting_log_conformations);
PRINTFD(G, FB_Editor)
" EditorDrag-Debug: entered. obj %p state %d index %d mode %d \nIndex %d Sele %d Object %p\n Axis %d Base %d BondFlag %d SlowFlag %d\n",
(void *) obj, state, index, mode,
I->DragIndex, I->DragSelection, (void *) I->DragObject,
I->DragHaveAxis, I->DragHaveBase, I->DragBondFlag, I->DragSlowFlag ENDFD;
if((index < 0) && (!obj))
obj = I->DragObject;
if(obj) {
ObjectMolecule *objMol = NULL;
if(obj->type == cObjectMolecule)
objMol = (ObjectMolecule*)(void*)obj;
state = EditorGetEffectiveState(G, obj, state);
if((index == I->DragIndex) && (obj == I->DragObject)) {
if(!EditorActive(G)) {
int matrix_mode = SettingGet_i(G, I->DragObject->Setting,
NULL, cSetting_matrix_mode);
if(matrix_mode<0)
matrix_mode = EditorDraggingObjectMatrix(G) ? 1 : 0;
/* always force use of matrix mode for non-molecular objects */
if((!objMol)&&(!matrix_mode))
matrix_mode = 1;
/* non-achored actions */
switch (mode) {
case cButModeRotDrag:
if(I->DragHaveBase) {
copy3f(I->DragBase, v3);
} else {
SceneOriginGet(G, v3);
}
get_rotation_about3f3fTTTf(pt[0], mov, v3, m);
if(matrix_mode && (I->DragSelection < 0)) {
switch (matrix_mode) {
case 1:
ObjectCombineTTT(obj, m, false, SettingGetGlobal_b(G,cSetting_movie_auto_store));
break;
case 2:
if(objMol)
ObjectMoleculeTransformState44f(objMol, state, m, log_trans, false, true);
break;
}
} else {
if(objMol)
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection,
m, log_trans, I->DragSeleName, false, true);
}
SceneInvalidate(G);
break;
case cButModeRotFrag:
case cButModeRotObj:
case cButModeRotView:
if(I->DragHaveBase) {
copy3f(I->DragBase, v3);
} else {
SceneOriginGet(G, v3);
}
subtract3f(pt, v3, n0);
add3f(pt, mov, n1);
subtract3f(n1, v3, n1);
normalize3f(n0);
normalize3f(n1);
cross_product3f(n0, n1, cp);
theta = (float) asin(length3f(cp));
normalize23f(cp, n2);
get_rotation_about3f3fTTTf(theta, n2, v3, m);
/* matrix m now contains a valid TTT rotation in global
coordinate space that could be applied directly to the
coordinates to effect the desired rotation */
if(mode == cButModeRotView) {
/* modify the object's TTT */
ObjectCombineTTT(obj, m, false,
SettingGetGlobal_b(G,cSetting_movie_auto_store));
} else {
if(matrix_mode) {
switch (matrix_mode) {
case 1:
ObjectCombineTTT(obj, m, false,
SettingGetGlobal_b(G,cSetting_movie_auto_store));
break;
case 2:
if(objMol)
ObjectMoleculeTransformState44f(objMol, state, m, log_trans, false, true);
break;
}
} else {
if(objMol)
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection,
m, log_trans, I->DragSeleName, false,
true);
}
}
SceneInvalidate(G);
break;
case cButModeTorFrag:
if(objMol) {
ObjectMoleculeMoveAtom(objMol, state, index, mov, 1, log_trans);
SceneInvalidate(G);
}
break;
case cButModeMovView:
case cButModeMovViewZ:
ObjectTranslateTTT(obj, mov, SettingGetGlobal_b(G,cSetting_movie_auto_store));
break;
case cButModeMovObj:
case cButModeMovObjZ:
case cButModeMovFrag:
case cButModeMovFragZ:
case cButModeMovDrag:
case cButModeMovDragZ:
if(matrix_mode && (I->DragSelection < 0)) {
identity44f(m);
m[3] = mov[0];
m[7] = mov[1];
m[11] = mov[2];
switch (matrix_mode) {
case 1:
ObjectCombineTTT(obj, m, false, SettingGetGlobal_b(G,cSetting_movie_auto_store));
break;
case 2:
if(objMol)
ObjectMoleculeTransformState44f(objMol, state, m, log_trans, true, true);
break;
}
} else {
identity44f(m);
copy3f(mov, m + 12); /* questionable... */
if(objMol)
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection, m,
log_trans, I->DragSeleName, false, true);
}
SceneInvalidate(G);
break;
}
} else {
switch (mode) {
case cButModeRotFrag:
case cButModeRotObj:
if(I->DragHaveBase) {
copy3f(I->DragBase, v3);
} else {
copy3f(I->V0, v3);
}
if(I->DragSlowFlag) {
SceneGetViewNormal(G, v4);
scale3f(v4, -1.0F, v4);
add3f(v3, v4, v4);
subtract3f(pt, v4, n0);
add3f(pt, mov, n1);
subtract3f(n1, v4, n1);
} else {
subtract3f(pt, v3, n0);
add3f(pt, mov, n1);
subtract3f(n1, v3, n1);
}
normalize3f(n0);
normalize3f(n1);
cross_product3f(n0, n1, cp);
theta = (float) asin(length3f(cp));
normalize23f(cp, n2);
get_rotation_about3f3fTTTf(theta, n2, v3, m);
if(objMol) {
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection,
m, log_trans, I->DragSeleName, false, true);
SceneInvalidate(G);
}
break;
case cButModeTorFrag:
case cButModePkTorBnd:
if(I->DragHaveAxis) {
subtract3f(pt, I->Center, d0);
if(dot_product3f(d0, I->Axis) < 0.0) {
copy3f(I->V0, v1);
copy3f(I->V1, v0);
} else {
copy3f(I->V0, v0);
copy3f(I->V1, v1);
}
subtract3f(v1, v0, d1);
copy3f(d1, n0);
normalize3f(n0);
cross_product3f(n0, d0, n1);
normalize3f(n1);
project3f(d0, n0, v2);
add3f(I->Center, v2, v2); /* v2 is the perpendicular point on the axis */
subtract3f(pt, v2, d2);
opp = (float) length3f(mov);
adj = (float) length3f(d2);
if(adj > R_SMALL4) {
theta = (float) atan(opp / adj);
if(dot_product3f(n1, mov) < 0.0)
theta = -theta;
get_rotation_about3f3fTTTf(theta, n0, v1, m);
if(objMol)
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection, m,
log_trans, I->DragSeleName, false, true);
} else {
if(z_dir) { /* NULL-safety */
cross_product3f(I->Axis, z_dir, d0);
theta = -dot_product3f(d0, mov);
get_rotation_about3f3fTTTf(theta, n0, v1, m);
if(objMol)
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection, m,
log_trans, I->DragSeleName, false, true);
}
}
if(I->BondMode && SettingGetGlobal_b(G, cSetting_editor_auto_dihedral))
EditorDihedralInvalid(G, NULL);
}
SceneInvalidate(G);
break;
case cButModeMovFrag:
case cButModeMovFragZ:
identity44f(m);
copy3f(mov, m + 12); /* questionable */
if(objMol)
ObjectMoleculeTransformSelection(objMol, state, I->DragSelection,
m, log_trans, I->DragSeleName, false, true);
SceneInvalidate(G);
break;
}
}
}
ExecutiveInvalidateSelectionIndicatorsCGO(G);
EditorInvalidateShaderCGO(G);
}
PRINTFD(G, FB_Editor)
" EditorDrag-Debug: leaving...\n" ENDFD;
}
/*========================================================================*/
int EditorInit(PyMOLGlobals * G)
{
CEditor *I = NULL;
if((I = (G->Editor = Calloc(CEditor, 1)))) {
I->DihedObject = NULL;
I->NFrag = 0;
I->Active = false;
I->DragObject = NULL;
I->DragIndex = -1;
I->DragSelection = -1;
I->NextPickSele = 0;
I->BondMode = false;
I->PosVLA = VLAlloc(float, 30);
I->DihedralInvalid = false;
I->MouseInvalid = false;
I->FavorOrigin = false;
I->shaderCGO = NULL;
return 1;
} else
return 0;
}
/*========================================================================*/
void EditorFree(PyMOLGlobals * G)
{
CEditor *I = G->Editor;
VLAFreeP(I->PosVLA);
FreeP(G->Editor);
}
void EditorInvalidateShaderCGO(PyMOLGlobals * G){
CEditor *I = G->Editor;
CGOFree(I->shaderCGO);
}
| 30.343633 | 140 | 0.545952 | [
"object",
"vector"
] |
2936892d33e192bc1021f07d560569436747485d | 9,141 | cpp | C++ | Cpp-Projects/Part_03_OOP/Project_2_System_Monitor/src/linux_parser.cpp | selfbeing/selfdriving | 8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9 | [
"MIT"
] | null | null | null | Cpp-Projects/Part_03_OOP/Project_2_System_Monitor/src/linux_parser.cpp | selfbeing/selfdriving | 8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9 | [
"MIT"
] | null | null | null | Cpp-Projects/Part_03_OOP/Project_2_System_Monitor/src/linux_parser.cpp | selfbeing/selfdriving | 8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9 | [
"MIT"
] | 1 | 2022-03-22T04:02:41.000Z | 2022-03-22T04:02:41.000Z | #include "linux_parser.h"
#include <dirent.h>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// DONE: An example of how to read data from the filesystem
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// DONE: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os, kernel, version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
// BONUS: Update this to use std::filesystem
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
closedir(directory);
return pids;
}
// TODO: Read and return the system memory utilization
float LinuxParser::MemoryUtilization() {
string line;
string key;
int value;
float finalValue;
int MTotal;
int MFree;
std::ifstream filestream(kProcDirectory + kMeminfoFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "MemTotal:") {
MTotal = value;
} else if (key == "MemFree:") {
MFree = value;
}
}
}
}
// std::cout << "MTotal: " << MTotal << " MFree: " << MFree << "\n";
finalValue = (MTotal - MFree) / float(MTotal);
// std::cout << "Final value: " << finalValue << "\n";
return finalValue;
}
// TODO: Read and return the system uptime
long LinuxParser::UpTime() {
string line;
string key;
int value;
std::ifstream filestream(kProcDirectory + kUptimeFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> value) {
return value;
}
}
}
return value;
}
// // TODO: Read and return the number of jiffies for the system
// long LinuxParser::Jiffies() { return 0; }
// // TODO: Read and return the number of active jiffies for a PID
// // REMOVE: [[maybe_unused]] once you define the function
// long LinuxParser::ActiveJiffies(int pid [[maybe_unused]]) { return 0; }
// // TODO: Read and return the number of active jiffies for the system
// long LinuxParser::ActiveJiffies() { return 0; }
// // TODO: Read and return the number of idle jiffies for the system
// long LinuxParser::IdleJiffies() { return 0; }
// TODO: Read and return CPU utilization
vector<string> LinuxParser::CpuUtilization() {
string line;
string key;
vector<string> value;
string value1, value2, value3, value4, value5, value6, value7, value8, value9,
value10;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value1 >> value2 >> value3 >> value4 >>
value5 >> value6 >> value7 >> value8 >> value9 >> value10) {
if (key == "cpu") {
for (int i = 0; i < 10; i++) {
value.push_back(value1);
}
value.push_back(value1);
value.push_back(value2);
value.push_back(value3);
value.push_back(value4);
value.push_back(value5);
value.push_back(value6);
value.push_back(value7);
value.push_back(value8);
value.push_back(value9);
value.push_back(value10);
break;
}
}
}
}
return value;
}
// TODO: Read and return the total number of processes
int LinuxParser::TotalProcesses() {
string line;
string key;
int value;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "processes") {
return value;
}
}
}
}
return value;
}
// TODO: Read and return the number of running processes
int LinuxParser::RunningProcesses() {
string line;
string key;
int value;
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "procs_running") {
return value;
}
}
}
}
return value;
}
// TODO: Read and return the command associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Command(int pid) {
string line;
string value;
std::ifstream filestream(kProcDirectory + std::to_string(pid) +
kCmdlineFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> value) {
return value;
}
}
}
return value;
}
// TODO: Read and return the memory used by a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Ram(int pid) {
string line;
string key;
string size;
string value;
long temp;
std::ifstream filestream(kProcDirectory + std::to_string(pid) +
kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value >> size) {
if (key == "VmSize:") {
if (size == "kB") {
temp = std::stol(value) / float(1000.0);
value = std::to_string(temp);
return value;
}
}
}
}
}
return value;
}
// TODO: Read and return the user ID associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::Uid(int pid) {
string line;
string key;
string value;
std::ifstream filestream(kProcDirectory + std::to_string(pid) +
kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "Uid:") {
return value;
}
}
}
}
return value;
}
// TODO: Read and return the user associated with a process
// REMOVE: [[maybe_unused]] once you define the function
string LinuxParser::User(int pid) {
string line;
string userName;
string value;
string pd;
std::ifstream filestream(kPasswordPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
while (linestream >> userName >> value >> pd) {
if (pd == LinuxParser::Uid(pid)) {
return userName;
}
}
}
}
return userName;
}
// TODO: Read and return the uptime of a process
// REMOVE: [[maybe_unused]] once you define the function
long LinuxParser::UpTime(int pid) {
string line;
string key;
long value;
vector<string> temp;
std::ifstream filestream(kProcDirectory + std::to_string(pid) +
kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key) {
temp.push_back(key);
}
}
}
value = std::stol(temp[21]) / sysconf(_SC_CLK_TCK);
return value;
}
std::vector<std::string> LinuxParser::CpuUtilization(int pid) {
string line;
string key;
vector<string> temp;
int cnt{0};
std::ifstream filestream(kProcDirectory + std::to_string(pid) +
kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key) {
if (cnt == 13 || cnt == 14 || cnt == 15 || cnt == 16 || cnt == 21) {
temp.push_back(key);
}
cnt++;
}
}
}
return temp;
}
| 27.616314 | 80 | 0.608577 | [
"vector"
] |
293915688c8e43481656a8f807fc75f1ede3f818 | 18,934 | cc | C++ | SimG4CMS/Calo/src/ECalSD.cc | Michael-Krohn/cmssw | 25064b40a13dc451b498e850214fcbe141f7cb75 | [
"Apache-2.0"
] | 2 | 2018-06-01T05:18:55.000Z | 2021-04-08T21:44:06.000Z | SimG4CMS/Calo/src/ECalSD.cc | Michael-Krohn/cmssw | 25064b40a13dc451b498e850214fcbe141f7cb75 | [
"Apache-2.0"
] | 26 | 2018-10-30T12:47:58.000Z | 2022-03-29T08:39:00.000Z | SimG4CMS/Calo/src/ECalSD.cc | p2l1pfp/cmssw | 9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z | ///////////////////////////////////////////////////////////////////////////////
// File: ECalSD.cc
// Description: Sensitive Detector class for electromagnetic calorimeters
///////////////////////////////////////////////////////////////////////////////
#include "SimG4CMS/Calo/interface/ECalSD.h"
#include "SimG4Core/Notification/interface/TrackInformation.h"
#include "Geometry/EcalCommonData/interface/EcalBarrelNumberingScheme.h"
#include "Geometry/EcalCommonData/interface/EcalBaseNumber.h"
#include "Geometry/EcalCommonData/interface/EcalEndcapNumberingScheme.h"
#include "Geometry/EcalCommonData/interface/EcalPreshowerNumberingScheme.h"
#include "Geometry/EcalCommonData/interface/ESTBNumberingScheme.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "Geometry/EcalCommonData/interface/EcalBaseNumber.h"
#include "FWCore/Framework/interface/ESTransientHandle.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "SimDataFormats/CaloHit/interface/PCaloHit.h"
#include "G4LogicalVolumeStore.hh"
#include "G4LogicalVolume.hh"
#include "G4Step.hh"
#include "G4Track.hh"
#include "G4VProcess.hh"
#include "G4SystemOfUnits.hh"
#include <algorithm>
//#define EDM_ML_DEBUG
template <class T>
bool any(const std::vector<T>& v, const T& what) {
return std::find(v.begin(), v.end(), what) != v.end();
}
ECalSD::ECalSD(const std::string& name,
const edm::EventSetup& es,
const SensitiveDetectorCatalog& clg,
edm::ParameterSet const& p,
const SimTrackManager* manager)
: CaloSD(name,
es,
clg,
p,
manager,
(float)(p.getParameter<edm::ParameterSet>("ECalSD").getParameter<double>("TimeSliceUnit")),
p.getParameter<edm::ParameterSet>("ECalSD").getParameter<bool>("IgnoreTrackID")),
ecalSimParameters_(nullptr),
numberingScheme_(nullptr) {
// static SimpleConfigurable<bool> on1(false, "ECalSD:UseBirkLaw");
// static SimpleConfigurable<double> bk1(0.00463,"ECalSD:BirkC1");
// static SimpleConfigurable<double> bk2(-0.03, "ECalSD:BirkC2");
// static SimpleConfigurable<double> bk3(1.0, "ECalSD:BirkC3");
// Values from NIM A484 (2002) 239-244: as implemented in Geant3
// useBirk = on1.value();
// birk1 = bk1.value()*(g/(MeV*cm2));
// birk2 = bk2.value()*(g/(MeV*cm2))*(g/(MeV*cm2));
edm::ParameterSet m_EC = p.getParameter<edm::ParameterSet>("ECalSD");
useBirk = m_EC.getParameter<bool>("UseBirkLaw");
useBirkL3 = m_EC.getParameter<bool>("BirkL3Parametrization");
birk1 = m_EC.getParameter<double>("BirkC1") * (g / (MeV * cm2));
birk2 = m_EC.getParameter<double>("BirkC2");
birk3 = m_EC.getParameter<double>("BirkC3");
birkSlope = m_EC.getParameter<double>("BirkSlope");
birkCut = m_EC.getParameter<double>("BirkCut");
slopeLY = m_EC.getParameter<double>("SlopeLightYield");
storeTrack = m_EC.getParameter<bool>("StoreSecondary");
crystalMat = m_EC.getUntrackedParameter<std::string>("XtalMat", "E_PbWO4");
bool isItTB = m_EC.getUntrackedParameter<bool>("TestBeam", false);
bool nullNS = m_EC.getUntrackedParameter<bool>("NullNumbering", false);
storeRL = m_EC.getUntrackedParameter<bool>("StoreRadLength", false);
scaleRL = m_EC.getUntrackedParameter<double>("ScaleRadLength", 1.0);
//Changes for improved timing simulation
storeLayerTimeSim = m_EC.getUntrackedParameter<bool>("StoreLayerTimeSim", false);
ageingWithSlopeLY = m_EC.getUntrackedParameter<bool>("AgeingWithSlopeLY", false);
if (ageingWithSlopeLY)
ageing.setLumies(p.getParameter<edm::ParameterSet>("ECalSD").getParameter<double>("DelivLuminosity"),
p.getParameter<edm::ParameterSet>("ECalSD").getParameter<double>("InstLuminosity"));
edm::ESHandle<EcalSimulationParameters> esp;
es.get<IdealGeometryRecord>().get(name, esp);
if (esp.isValid()) {
ecalSimParameters_ = esp.product();
} else {
edm::LogError("EcalSim") << "ECalSD : Cannot find EcalSimulationParameters for " << name;
throw cms::Exception("Unknown", "ECalSD") << "Cannot find EcalSimulationParameters for " << name << "\n";
}
// Use of Weight
useWeight = ecalSimParameters_->useWeight_;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD:: useWeight " << useWeight;
#endif
depth1Name = ecalSimParameters_->depth1Name_;
depth2Name = ecalSimParameters_->depth2Name_;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "Names (Depth 1):" << depth1Name << " (Depth 2):" << depth2Name << std::endl;
#endif
EcalNumberingScheme* scheme = nullptr;
if (nullNS) {
scheme = nullptr;
} else if (name == "EcalHitsEB") {
scheme = dynamic_cast<EcalNumberingScheme*>(new EcalBarrelNumberingScheme());
} else if (name == "EcalHitsEE") {
scheme = dynamic_cast<EcalNumberingScheme*>(new EcalEndcapNumberingScheme());
} else if (name == "EcalHitsES") {
if (isItTB)
scheme = dynamic_cast<EcalNumberingScheme*>(new ESTBNumberingScheme());
else
scheme = dynamic_cast<EcalNumberingScheme*>(new EcalPreshowerNumberingScheme());
useWeight = false;
} else {
edm::LogWarning("EcalSim") << "ECalSD: ReadoutName not supported";
}
if (scheme)
setNumberingScheme(scheme);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "Constructing a ECalSD with name " << GetName();
#endif
if (useWeight) {
edm::LogVerbatim("EcalSim") << "ECalSD:: Use of Birks law is set to " << useBirk
<< " with three constants kB = " << birk1 << ", C1 = " << birk2
<< ", C2 = " << birk3 << "\n Use of L3 parametrization " << useBirkL3
<< " with slope " << birkSlope << " and cut off " << birkCut << "\n"
<< " Slope for Light yield is set to " << slopeLY;
} else {
edm::LogVerbatim("EcalSim") << "ECalSD:: energy deposit is not corrected "
<< " by Birk or light yield curve";
}
edm::LogVerbatim("EcalSim") << "ECalSD:: Suppression Flag " << suppressHeavy << "\tprotons below " << kmaxProton
<< " MeV,"
<< "\tneutrons below " << kmaxNeutron << " MeV"
<< "\tions below " << kmaxIon << " MeV"
<< "\n\tDepth1 Name = " << depth1Name << "\tDepth2 Name = " << depth2Name << "\n\tstoreRL"
<< storeRL << ":" << scaleRL << "\tstoreLayerTimeSim " << storeLayerTimeSim
<< "\n\ttime Granularity "
<< p.getParameter<edm::ParameterSet>("ECalSD").getParameter<double>("TimeSliceUnit")
<< " ns";
if (useWeight)
initMap();
#ifdef plotDebug
edm::Service<TFileService> tfile;
if (tfile.isAvailable()) {
TFileDirectory ecDir = tfile->mkdir("ProfileFromECalSD");
static const std::string ctype[4] = {"EB", "EBref", "EE", "EERef"};
for (int k = 0; k < 4; ++k) {
std::string name = "ECLL_" + ctype[k];
std::string title = "Local vs Global for " + ctype[k];
double xmin = (k > 1) ? 3000.0 : 1000.0;
g2L_[k] = ecDir.make<TH2F>(name.c_str(), title.c_str(), 100, xmin, xmin + 1000., 100, 0.0, 3000.);
}
} else {
for (int k = 0; k < 4; ++k)
g2L_[k] = 0;
}
#endif
}
ECalSD::~ECalSD() { delete numberingScheme_; }
double ECalSD::getEnergyDeposit(const G4Step* aStep) {
const G4StepPoint* preStepPoint = aStep->GetPreStepPoint();
const G4Track* theTrack = aStep->GetTrack();
double edep = aStep->GetTotalEnergyDeposit();
// take into account light collection curve for crystals
double weight = 1.;
if (suppressHeavy) {
TrackInformation* trkInfo = (TrackInformation*)(theTrack->GetUserInformation());
if (trkInfo) {
int pdg = theTrack->GetDefinition()->GetPDGEncoding();
if (!(trkInfo->isPrimary())) { // Only secondary particles
double ke = theTrack->GetKineticEnergy();
if (((pdg / 1000000000 == 1 && ((pdg / 10000) % 100) > 0 && ((pdg / 10) % 100) > 0)) && (ke < kmaxIon))
weight = 0;
if ((pdg == 2212) && (ke < kmaxProton))
weight = 0;
if ((pdg == 2112) && (ke < kmaxNeutron))
weight = 0;
}
}
}
const G4LogicalVolume* lv = preStepPoint->GetTouchable()->GetVolume(0)->GetLogicalVolume();
double wt1 = 1.0;
if (useWeight && !any(noWeight, lv)) {
weight *= curve_LY(lv);
if (useBirk) {
if (useBirkL3)
weight *= getBirkL3(aStep);
else
weight *= getAttenuation(aStep, birk1, birk2, birk3);
}
wt1 = getResponseWt(theTrack);
}
edep *= weight * wt1;
// Russian Roulette
double wt2 = theTrack->GetWeight();
if (wt2 > 0.0) {
edep *= wt2;
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << lv->GetName() << " Light Collection Efficiency " << weight << ":" << wt1
<< " wt2= " << wt2 << " Weighted Energy Deposit " << edep / MeV << " MeV";
#endif
return edep;
}
int ECalSD::getTrackID(const G4Track* aTrack) {
int primaryID(0);
if (storeTrack && depth > 0) {
forceSave = true;
primaryID = aTrack->GetTrackID();
} else {
primaryID = CaloSD::getTrackID(aTrack);
}
return primaryID;
}
uint16_t ECalSD::getDepth(const G4Step* aStep) {
// this method should be called first at a step
const G4StepPoint* hitPoint = aStep->GetPreStepPoint();
currentLocalPoint = setToLocal(hitPoint->GetPosition(), hitPoint->GetTouchable());
const G4LogicalVolume* lv = hitPoint->GetTouchable()->GetVolume(0)->GetLogicalVolume();
auto ite = xtalLMap.find(lv);
crystalLength = (ite == xtalLMap.end()) ? 230.0 : std::abs(ite->second);
crystalDepth = (ite == xtalLMap.end()) ? 0.0 : (std::abs(0.5 * (ite->second) + currentLocalPoint.z()));
depth = any(useDepth1, lv) ? 1 : (any(useDepth2, lv) ? 2 : 0);
uint16_t depth1(0), depth2(0);
if (storeRL) {
depth1 = (ite == xtalLMap.end()) ? 0 : (((ite->second) >= 0) ? 0 : PCaloHit::kEcalDepthRefz);
depth2 = getRadiationLength(hitPoint, lv);
depth |= (((depth2 & PCaloHit::kEcalDepthMask) << PCaloHit::kEcalDepthOffset) | depth1);
} else if (storeLayerTimeSim) {
depth2 = getLayerIDForTimeSim();
depth |= ((depth2 & PCaloHit::kEcalDepthMask) << PCaloHit::kEcalDepthOffset);
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::Depth " << std::hex << depth1 << ":" << depth2 << ":" << depth << std::dec
<< " L " << (ite == xtalLMap.end()) << ":" << ite->second;
#endif
return depth;
}
uint16_t ECalSD::getRadiationLength(const G4StepPoint* hitPoint, const G4LogicalVolume* lv) {
uint16_t thisX0 = 0;
if (useWeight) {
double radl = hitPoint->GetMaterial()->GetRadlen();
thisX0 = (uint16_t)floor(scaleRL * crystalDepth / radl);
#ifdef plotDebug
const std::string& lvname = lv->GetName();
int k1 = (lvname.find("EFRY") != std::string::npos) ? 2 : 0;
int k2 = (lvname.find("refl") != std::string::npos) ? 1 : 0;
int kk = k1 + k2;
double rz = (k1 == 0) ? (hitPoint->GetPosition()).rho() : std::abs((hitPoint->GetPosition()).z());
edm::LogVerbatim("EcalSim") << lvname << " # " << k1 << ":" << k2 << ":" << kk << " rz " << rz << " D " << thisX0;
g2L_[kk]->Fill(rz, thisX0);
#endif
#ifdef EDM_ML_DEBUG
G4ThreeVector localPoint = setToLocal(hitPoint->GetPosition(), hitPoint->GetTouchable());
edm::LogVerbatim("EcalSim") << lv->GetName() << " Global " << hitPoint->GetPosition() << ":"
<< (hitPoint->GetPosition()).rho() << " Local " << localPoint << " Crystal Length "
<< crystalLength << " Radl " << radl << " crystalDepth " << crystalDepth << " Index "
<< thisX0 << " : " << getLayerIDForTimeSim();
#endif
}
return thisX0;
}
uint16_t ECalSD::getLayerIDForTimeSim() {
const double invLayerSize = 0.1; //layer size in 1/mm
return (int)crystalDepth * invLayerSize;
}
uint32_t ECalSD::setDetUnitId(const G4Step* aStep) {
if (numberingScheme_ == nullptr) {
return EBDetId(1, 1)();
} else {
getBaseNumber(aStep);
return numberingScheme_->getUnitID(theBaseNumber);
}
}
void ECalSD::setNumberingScheme(EcalNumberingScheme* scheme) {
if (scheme != nullptr) {
edm::LogVerbatim("EcalSim") << "EcalSD: updates numbering scheme for " << GetName();
if (numberingScheme_)
delete numberingScheme_;
numberingScheme_ = scheme;
}
}
void ECalSD::initMap() {
std::vector<const G4LogicalVolume*> lvused;
const G4LogicalVolumeStore* lvs = G4LogicalVolumeStore::GetInstance();
std::map<const std::string, const G4LogicalVolume*> nameMap;
for (auto lvi = lvs->begin(), lve = lvs->end(); lvi != lve; ++lvi)
nameMap.emplace((*lvi)->GetName(), *lvi);
for (unsigned int it = 0; it < ecalSimParameters_->lvNames_.size(); ++it) {
const std::string& matname = ecalSimParameters_->matNames_[it];
const std::string& lvname = ecalSimParameters_->lvNames_[it];
const G4LogicalVolume* lv = nameMap[lvname];
int ibec = (lvname.find("EFRY") == std::string::npos) ? 0 : 1;
int iref = (lvname.find("refl") == std::string::npos) ? 0 : 1;
int type = (ibec + iref == 1) ? 1 : -1;
if (depth1Name != " ") {
if (strncmp(lvname.c_str(), depth1Name.c_str(), 4) == 0) {
if (!any(useDepth1, lv)) {
useDepth1.push_back(lv);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::initMap Logical Volume " << lvname << " in Depth 1 volume list";
#endif
}
const G4LogicalVolume* lvr = nameMap[lvname + "_refl"];
if (lvr != nullptr && !any(useDepth1, lvr)) {
useDepth1.push_back(lvr);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::initMap Logical Volume " << lvname << "_refl"
<< " in Depth 1 volume list";
#endif
}
}
}
if (depth2Name != " ") {
if (strncmp(lvname.c_str(), depth2Name.c_str(), 4) == 0) {
if (!any(useDepth2, lv)) {
useDepth2.push_back(lv);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::initMap Logical Volume " << lvname << " in Depth 2 volume list";
#endif
}
const G4LogicalVolume* lvr = nameMap[lvname + "_refl"];
if (lvr != nullptr && !any(useDepth2, lvr)) {
useDepth2.push_back(lvr);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::initMap Logical Volume " << lvname << "_refl"
<< " in Depth 2 volume list";
#endif
}
}
}
if (lv != nullptr) {
if (crystalMat.size() == matname.size() && !strcmp(crystalMat.c_str(), matname.c_str())) {
if (!any(lvused, lv)) {
lvused.push_back(lv);
double dz = ecalSimParameters_->dzs_[it];
xtalLMap.insert(std::pair<const G4LogicalVolume*, double>(lv, dz * type));
lv = nameMap[lvname + "_refl"];
if (lv != nullptr) {
xtalLMap.insert(std::pair<const G4LogicalVolume*, double>(lv, -dz * type));
}
}
} else {
if (!any(noWeight, lv)) {
noWeight.push_back(lv);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::initMap Logical Volume " << lvname << " Material " << matname
<< " in noWeight list";
#endif
}
lv = nameMap[lvname];
if (lv != nullptr && !any(noWeight, lv)) {
noWeight.push_back(lv);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::initMap Logical Volume " << lvname << " Material " << matname
<< " in noWeight list";
#endif
}
}
}
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD: Length Table:";
int i = 0;
for (auto ite : xtalLMap) {
G4String name("Unknown");
if (ite.first != 0)
name = (ite.first)->GetName();
edm::LogVerbatim("EcalSim") << " " << i << " " << ite.first << " " << name << " L = " << ite.second;
++i;
}
#endif
}
double ECalSD::curve_LY(const G4LogicalVolume* lv) {
double weight = 1.;
if (ageingWithSlopeLY) {
//position along the crystal in mm from 0 to 230 (in EB)
if (crystalDepth >= -0.1 || crystalDepth <= crystalLength + 0.1)
weight = ageing.calcLightCollectionEfficiencyWeighted(currentID.unitID(), crystalDepth / crystalLength);
} else {
double dapd = crystalLength - crystalDepth;
if (dapd >= -0.1 || dapd <= crystalLength + 0.1) {
if (dapd <= 100.)
weight = 1.0 + slopeLY - dapd * 0.01 * slopeLY;
} else {
edm::LogWarning("EcalSim") << "ECalSD: light coll curve : wrong distance "
<< "to APD " << dapd << " crlength = " << crystalLength
<< " crystal name = " << lv->GetName()
<< " z of localPoint = " << currentLocalPoint.z() << " take weight = " << weight;
}
}
return weight;
}
void ECalSD::getBaseNumber(const G4Step* aStep) {
theBaseNumber.reset();
const G4VTouchable* touch = aStep->GetPreStepPoint()->GetTouchable();
int theSize = touch->GetHistoryDepth() + 1;
if (theBaseNumber.getCapacity() < theSize)
theBaseNumber.setSize(theSize);
//Get name and copy numbers
if (theSize > 1) {
for (int ii = 0; ii < theSize; ii++) {
theBaseNumber.addLevel(touch->GetVolume(ii)->GetName(), touch->GetReplicaNumber(ii));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::getBaseNumber(): Adding level " << ii << ": "
<< touch->GetVolume(ii)->GetName() << "[" << touch->GetReplicaNumber(ii) << "]";
#endif
}
}
}
double ECalSD::getBirkL3(const G4Step* aStep) {
double weight = 1.;
const G4StepPoint* preStepPoint = aStep->GetPreStepPoint();
double charge = preStepPoint->GetCharge();
if (charge != 0. && aStep->GetStepLength() > 0.) {
const G4Material* mat = preStepPoint->GetMaterial();
double density = mat->GetDensity();
double dedx = aStep->GetTotalEnergyDeposit() / aStep->GetStepLength();
double rkb = birk1 / density;
if (dedx > 0) {
weight = 1. - birkSlope * log(rkb * dedx);
if (weight < birkCut)
weight = birkCut;
else if (weight > 1.)
weight = 1.;
}
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("EcalSim") << "ECalSD::getBirkL3 in " << mat->GetName() << " Charge " << charge << " dE/dx "
<< dedx << " Birk Const " << rkb << " Weight = " << weight << " dE "
<< aStep->GetTotalEnergyDeposit();
#endif
}
return weight;
}
| 41.52193 | 120 | 0.599715 | [
"geometry",
"vector"
] |
293915bd7a9faa6b9688a53bba30b549e0b1d197 | 27,318 | cpp | C++ | NYUCodebase/space/Space_Invaders.cpp | MarcNYU/Game-Files | 43781cae89ea02d18930b1b2ead04db400c7f1dd | [
"Artistic-2.0"
] | null | null | null | NYUCodebase/space/Space_Invaders.cpp | MarcNYU/Game-Files | 43781cae89ea02d18930b1b2ead04db400c7f1dd | [
"Artistic-2.0"
] | null | null | null | NYUCodebase/space/Space_Invaders.cpp | MarcNYU/Game-Files | 43781cae89ea02d18930b1b2ead04db400c7f1dd | [
"Artistic-2.0"
] | null | null | null | //
// Space_Invaders.cpp
// NYUCodebase
//
// Created by Marcus Williams on 2/20/15.
// Copyright (c) 2015 Ivan Safrin. All rights reserved.
//
#include <stdio.h>
#include <SDL.h>
#include <SDL_opengl.h>
#include <SDL_image.h>
#include <iostream>
#include <vector>
#include <array>
#include <math.h>
#include <string>
#include "Entity.h"
#include "SpriteSheet.h"
//#include "ClassDemoApp.h"
SDL_Window* displayWindow;
#define MAX_BULLETS 30
class Bullet : public Entity {
public:
Bullet() : Entity(0, x, y, 0.015625, 0.03125, 1.0){}
void Update(float elapsed) {y += elapsed;}
float x;
float y;
bool visible;
float angle;
// int texture;
};
std::vector<Entity> makeEnemyLine(int texture, float zero_position_x, float zero_position_y, float w, float h, float spd);
GLuint LoadTexture(const char *image_path);
void DrawSpriteSheetSprite(int spriteTexture, int index, int spriteCountX, int spriteCountY);
void DrawText(int fontTexture, std::string text, float size, float spacing, float r, float g, float b, float a);
void UpdateScore(int num);
void Setup();
void Cleanup();
int main(int argc, char *argv[])
{
Setup();
bool done = false;
SDL_Event event;
const Uint8 *keys = SDL_GetKeyboardState(NULL);
float lastFrameTicks = 0.0f;
float ticks = (float)SDL_GetTicks()/1000000.0f;
float elapsed = ticks - lastFrameTicks;
lastFrameTicks = ticks;
float pace;
pace = elapsed;
int phase = 0;
int score = 0;
Entity nullSpace(0, 0.0, 0.0, 0.0, 0.0, 0.001);
/*----------------------------------PLAYER-------------------------------------*/
Entity player(LoadTexture("playerShip1_red.png"), 0.0, -0.9, 0.1, 0.1, 0.02);
/*----------------------------------BULLETS-------------------------------------*/
std::vector<Entity> bullets;
// for (int amt = 0; amt < MAX_BULLETS; amt++) {
// Bullet laser;
// laser.x = player.x;
// laser.y = player.y;
// laser.visible = false;
// laser.angle = 0.0;
//
// bullets.push_back(laser);
// }
for (int amt = 0; amt < MAX_BULLETS; amt++) {
Entity laser(0, player.x, player.y, 0.015625, 0.03125, 1.0);
// laser.x = player.x;
// laser.y = -0.7;
// laser.visible = false;
// laser.angle = 0.0;
bullets.push_back(laser);
}
bool shot = false;
int clip = -1;
// Entity laser(0, player.x, -0.9, 0.015625, 0.03125, 0.001);
/*----------------------------------ALIENS-------------------------------------*/
float zero_position_x = -.9;
std::vector<Entity> enemyLine1 = makeEnemyLine(LoadTexture("enemyRed4.png"), zero_position_x, 0.0, 0.0625, 0.0625, 0.001);
std::vector<Entity> enemyLine2 = makeEnemyLine(LoadTexture("enemyRed4.png"), zero_position_x, 0.1, 0.0625, 0.0625, 0.001);
std::vector<Entity> enemyLine3 = makeEnemyLine(LoadTexture("enemyGreen3.png"), zero_position_x, 0.2, 0.0625, 0.0625, 0.001);
std::vector<Entity> enemyLine4 = makeEnemyLine(LoadTexture("enemyBlue2.png"), zero_position_x, 0.3, 0.0625, 0.0625, 0.001);
std::vector<Entity> enemyLine5 = makeEnemyLine(LoadTexture("enemyBlack1.png"), zero_position_x, 0.4, 0.0625, 0.0625, 0.001);
Entity motherShip (LoadTexture("ufoYellow.png"), -1.5, 0.6, 0.125, 0.125, 0.001);
Entity locator (0, -.75, 0.0, 0.0625, 0.0625, 0.001);
locator.direction_x = 1.0;
locator.direction_y = -1.0;
/*-------------------------------------------------------GAME LOOP-------------------------------------------------*/
while (!done) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
done = true;
}
}
/*----------------------------------PLAYER-------------------------------------*/
if(keys[SDL_SCANCODE_RIGHT]) {
if ((player.x + (player.height/2)) < 0.95) {
float x_position = player.speed;
// bullets[clip].x = player.x;
player.x += x_position;
glClear(GL_COLOR_BUFFER_BIT);
//Update
// bullets[clip].Draw();
player.Draw();
}
} else if(keys[SDL_SCANCODE_LEFT]) {
if ((player.x - (player.height/2)) > -0.95) {
float x_position = player.speed;
// bullets[clip].x = player.x;
player.x -= x_position;
glClear(GL_COLOR_BUFFER_BIT);
//Update
// bullets[clip].Draw();
player.Draw();
}
} else if(keys[SDL_SCANCODE_SPACE]) {
shot = true;
clip++;
bullets[clip].x = player.x;
}
if (clip < bullets.size()) {
if (shot == true) {
// bullets[clip].x = player.x;
// glLoadIdentity();
bullets[clip].y += 0.05;
glClear(GL_COLOR_BUFFER_BIT);
bullets[clip].Draw();
player.Draw();
if (bullets[clip].y > 1.1) {
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
}
}
} else
clip = 0;
/*----------------------------------ENENIES-------------------------------------*/
if (locator.direction_x > 0.0) {
if ((locator.x + locator.width/2) < -0.55) {
glClear(GL_COLOR_BUFFER_BIT);
for (size_t i = 0; i < enemyLine1.size(); i++) {
locator.x += pace/11;
enemyLine1[i].x += pace;
enemyLine2[i].x += pace;
enemyLine3[i].x += pace;
enemyLine4[i].x += pace;
enemyLine5[i].x += pace;
motherShip.x += elapsed;
if (bullets[clip].x == enemyLine1[i].x || (bullets[clip].x >= (enemyLine1[i].x - (enemyLine1[i].width/2)) && bullets[clip].x <= (enemyLine1[i].x + (enemyLine1[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine1[i].y - (enemyLine1[i].height/2))) {
if (enemyLine1[i].textureID != nullSpace.textureID) {
enemyLine1[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 10;
}
}
} else if (bullets[clip].x == enemyLine2[i].x || (bullets[clip].x >= (enemyLine2[i].x - (enemyLine2[i].width/2)) && bullets[clip].x <= (enemyLine2[i].x + (enemyLine2[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine2[i].y - (enemyLine2[i].height/2))) {
if (enemyLine2[i].textureID != nullSpace.textureID) {
enemyLine2[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 10;
}
}
} else if (bullets[clip].x == enemyLine3[i].x || (bullets[clip].x >= (enemyLine3[i].x - (enemyLine3[i].width/2)) && bullets[clip].x <= (enemyLine3[i].x + (enemyLine3[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine3[i].y - (enemyLine3[i].height/2))) {
if (enemyLine3[i].textureID != nullSpace.textureID) {
enemyLine3[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 20;
}
}
} else if (bullets[clip].x == enemyLine4[i].x || (bullets[clip].x >= (enemyLine4[i].x - (enemyLine4[i].width/2)) && bullets[clip].x <= (enemyLine4[i].x + (enemyLine4[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine4[i].y - (enemyLine4[i].height/2))) {
if (enemyLine4[i].textureID != nullSpace.textureID) {
enemyLine4[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 30;
}
}
} else if (bullets[clip].x == enemyLine5[i].x || (bullets[clip].x >= (enemyLine5[i].x - (enemyLine5[i].width/2)) && bullets[clip].x <= (enemyLine5[i].x + (enemyLine5[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine5[i].y - (enemyLine5[i].height/2))) {
if (enemyLine5[i].textureID != nullSpace.textureID) {
enemyLine5[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 50;
}
}
} else if (bullets[clip].x == motherShip.x || (bullets[clip].x >= (motherShip.x - (motherShip.width/2)) && bullets[clip].x <= (motherShip.x + (motherShip.width/2))) || motherShip.x >= 2.5) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (motherShip.y - (motherShip.height/2))) {
motherShip.x = -2.5;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 150;
}
}
//REDRAW ASSETS
if (shot == true) {
bullets[clip].Draw();
}
player.Draw();
// locator.Draw();
enemyLine1[i].Draw();
enemyLine2[i].Draw();
enemyLine3[i].Draw();
enemyLine4[i].Draw();
enemyLine5[i].Draw();
motherShip.Draw();
// UpdateScore(score);
glDisableClientState(GL_COLOR_ARRAY);
switch (phase) {
case 2:
pace += lastFrameTicks/9000;//SPEED SHIFT
enemyLine1[i].y = -0.3;//BOTTOMLINE
enemyLine2[i].y = -0.2;
enemyLine3[i].y = -0.1;
enemyLine4[i].y = 0.0;
enemyLine5[i].y = 0.1;//TOPLINE
break;
case 4:
pace += lastFrameTicks/7000;//SPEED SHIFT
enemyLine1[i].y = -0.5;//BOTTOMLINE
enemyLine2[i].y = -0.4;
enemyLine3[i].y = -0.3;
enemyLine4[i].y = -0.2;
enemyLine5[i].y = -0.1;//TOPLINE
break;
case 6:
pace += lastFrameTicks/100;//SPEED SHIFT
enemyLine1[i].y = -0.71;//BOTTOMLINE
enemyLine2[i].y = -0.6;
enemyLine3[i].y = -0.5;
enemyLine4[i].y = -0.4;
enemyLine5[i].y = -0.3;//TOPLINE
break;
case 8:
pace += lastFrameTicks/100;//SPEED SHIFT
enemyLine3[i].y = -0.71;
enemyLine4[i].y = -0.6;
enemyLine5[i].y = -0.5;//TOPLINE
break;
case 11:
pace += lastFrameTicks/100;//SPEED SHIFT
enemyLine5[i].y = -0.71;//TOPLINE
break;
default:
break;
}
if (enemyLine1[i].y <= -0.7 || enemyLine2[i].y <= -0.7 || enemyLine3[i].y <= -0.7 ||enemyLine4[i].y <= -0.7 || enemyLine5[i].y <= -0.7) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(-0.4, 0.0, 0.0);
DrawText(LoadTexture("font1.png"), "GAME OVER", 0.1, 0.000000000001, 1.0, 1.0, 1.0, 1.0);
}
}
}else {
phase++;
locator.direction_x = -1.0;
enemyLine1[0].direction_x = -1.0;
enemyLine2[0].direction_x = -1.0;
enemyLine3[0].direction_x = -1.0;
enemyLine4[0].direction_x = -1.0;
enemyLine5[0].direction_x = -1.0;
}
}
if (locator.direction_x < 0.0) {
if ((locator.x - enemyLine1[0].width/2) > -0.95) {
glClear(GL_COLOR_BUFFER_BIT);
for (size_t i = 0; i < enemyLine1.size(); i++) {
locator.x -= pace/11;
enemyLine1[i].x -= pace;
enemyLine2[i].x -= pace;
enemyLine3[i].x -= pace;
enemyLine4[i].x -= pace;
enemyLine5[i].x -= pace;
motherShip.x += elapsed;
if (bullets[clip].x == enemyLine1[i].x || (bullets[clip].x >= (enemyLine1[i].x - (enemyLine1[i].width/2)) && bullets[clip].x <= (enemyLine1[i].x + (enemyLine1[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine1[i].y - (enemyLine1[i].height/2))) {
if (enemyLine1[i].textureID != nullSpace.textureID) {
enemyLine1[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 10;
}
}
} else if (bullets[clip].x == enemyLine2[i].x || (bullets[clip].x >= (enemyLine2[i].x - (enemyLine2[i].width/2)) && bullets[clip].x <= (enemyLine2[i].x + (enemyLine2[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine2[i].y - (enemyLine2[i].height/2))) {
if (enemyLine2[i].textureID != nullSpace.textureID) {
enemyLine2[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 10;
}
}
} else if (bullets[clip].x == enemyLine3[i].x || (bullets[clip].x >= (enemyLine3[i].x - (enemyLine3[i].width/2)) && bullets[clip].x <= (enemyLine3[i].x + (enemyLine3[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine3[i].y - (enemyLine3[i].height/2))) {
if (enemyLine3[i].textureID != nullSpace.textureID) {
enemyLine3[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 20;
}
}
} else if (bullets[clip].x == enemyLine4[i].x || (bullets[clip].x >= (enemyLine4[i].x - (enemyLine4[i].width/2)) && bullets[clip].x <= (enemyLine4[i].x + (enemyLine4[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine4[i].y - (enemyLine4[i].height/2))) {
if (enemyLine4[i].textureID != nullSpace.textureID) {
enemyLine4[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 30;
}
}
} else if (bullets[clip].x == enemyLine5[i].x || (bullets[clip].x >= (enemyLine5[i].x - (enemyLine5[i].width/2)) && bullets[clip].x <= (enemyLine5[i].x + (enemyLine5[i].width/2)))) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (enemyLine5[i].y - (enemyLine5[i].height/2))) {
if (enemyLine5[i].textureID != nullSpace.textureID) {
enemyLine5[i] = nullSpace;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 50;
}
}
} else if (bullets[clip].x == motherShip.x || (bullets[clip].x >= (motherShip.x - (motherShip.width/2)) && bullets[clip].x <= (motherShip.x + (motherShip.width/2))) || motherShip.x >= 2.5) {
if ((bullets[clip].y + (bullets[clip].height/2)) > (motherShip.y - (motherShip.height/2))) {
motherShip.x = -2.5;
bullets[clip].y = player.y;
bullets[clip].x = player.x;
shot = false;
score += 150;
}
}
//REDRAW ASSETS
if (shot == true) {
bullets[clip].Draw();
}
player.Draw();
// locator.Draw();
enemyLine1[i].Draw();
enemyLine2[i].Draw();
enemyLine3[i].Draw();
enemyLine4[i].Draw();
enemyLine5[i].Draw();
motherShip.Draw();
// UpdateScore(score);
glDisableClientState(GL_COLOR_ARRAY);
switch (phase) {
case 1:
pace += lastFrameTicks/9000;//SPEED SHIFT
enemyLine1[i].y = -0.2;//BOTTOMLINE
enemyLine2[i].y = -0.1;
enemyLine3[i].y = 0.0;
enemyLine4[i].y = 0.1;
enemyLine5[i].y = 0.2;//TOPLINE
break;
case 3:
pace += lastFrameTicks/7000;//SPEED SHIFT
enemyLine1[i].y = -0.4;//BOTTOMLINE
enemyLine2[i].y = -0.3;
enemyLine3[i].y = -0.2;
enemyLine4[i].y = -0.1;
enemyLine5[i].y = 0.0;//TOPLINE
break;
case 5:
pace += lastFrameTicks/5000;//SPEED SHIFT
enemyLine1[i].y = -0.6;//BOTTOMLINE
enemyLine2[i].y = -0.5;
enemyLine3[i].y = -0.4;
enemyLine4[i].y = -0.3;
enemyLine5[i].y = -0.2;//TOPLINE
break;
case 7:
pace += lastFrameTicks/100;//SPEED SHIFT
enemyLine2[i].y = -0.71;
enemyLine3[i].y = -0.6;
enemyLine4[i].y = -0.5;
enemyLine5[i].y = -0.4;//TOPLINE
break;
case 9:
pace += lastFrameTicks/100;//SPEED SHIFT
enemyLine4[i].y = -0.71;
enemyLine5[i].y = -0.6;//TOPLINE
break;
default:
break;
}
if (enemyLine1[i].y <= -0.7 || enemyLine2[i].y <= -0.7 || enemyLine3[i].y <= -0.7 ||enemyLine4[i].y <= -0.7 || enemyLine5[i].y <= -0.7) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(-0.4, 0.0, 0.0);
DrawText(LoadTexture("font1.png"), "GAME OVER", 0.1, 0.000000000001, 1.0, 1.0, 1.0, 1.0);
}
}
} else {
phase++;
locator.direction_x = 1.0;
enemyLine1[0].direction_x = 1.0;
enemyLine2[0].direction_x = 1.0;
enemyLine3[0].direction_x = 1.0;
enemyLine4[0].direction_x = 1.0;
enemyLine5[0].direction_x = 1.0;
}
}
SDL_GL_SwapWindow(displayWindow);
}
Cleanup();
SDL_Quit();
return 0;
}
void Setup() {
// setup SDL
SDL_Init(SDL_INIT_VIDEO);
displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
// setup OpenGL
SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
SDL_GL_MakeCurrent(displayWindow, context);
// Set our projection matrix
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, 800, 600);
glMatrixMode(GL_PROJECTION);
glMatrixMode(GL_MODELVIEW);
}
std::vector<Entity> makeEnemyLine(int texture, float zero_position_x, float zero_position_y, float w, float h, float spd) {
std::vector<Entity> enemyLine;
for (size_t i = 0; i < 11; i++) {
zero_position_x += 0.15;
Entity alien(texture, zero_position_x, zero_position_y, w, h, spd);
alien.direction_x = 1.0;
alien.direction_y = -1.0;
enemyLine.push_back(alien);
}
return enemyLine;
}
void Cleanup() {
// cleanup joysticks, textures, etc.
glClear(GL_COLOR_BUFFER_BIT);
}
GLuint LoadTexture(const char *image_path) {
SDL_Surface *surface = IMG_Load(image_path);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_BGRA,
GL_UNSIGNED_BYTE, surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surface);
return textureID;
}
void DrawSpriteSheetSprite(int spriteTexture, int index, int spriteCountX, int spriteCountY) {
// our regular sprite drawing
float u = (float)(((int)index) % spriteCountX) / (float) spriteCountX;
float v = (float)(((int)index) / spriteCountX) / (float) spriteCountY;
float spriteWidth = 1.0/(float)spriteCountX;
float spriteHeight = 1.0/(float)spriteCountY;
GLfloat quadUVs[] = { u, v,
u, v+spriteHeight,
u+spriteWidth, v+spriteHeight,
u+spriteWidth, v
};
// our regular sprite drawing
}
void DrawText(int fontTexture, std::string text, float size, float spacing, float r, float g, float b, float a) {
glBindTexture(GL_TEXTURE_2D, fontTexture);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
float texture_size = 1.0/16.0f;
std::vector<float> vertexData;
std::vector<float> texCoordData;
std::vector<float> colorData;
for(int i=0; i < text.size(); i++) {
float texture_x = (float)(((int)text[i]) % 16) / 16.0f;
float texture_y = (float)(((int)text[i]) / 16) / 16.0f;
colorData.insert(colorData.end(), {r,g,b,a, r,g,b,a, r,g,b,a, r,g,b,a});
vertexData.insert(vertexData.end(), {((size+spacing) * i) + (-0.5f * size), 0.5f * size, ((size+spacing) * i) +
(-0.5f * size), -0.5f * size, ((size+spacing) * i) + (0.5f * size), -0.5f * size, ((size+spacing) * i) + (0.5f * size), 0.5f
* size});
texCoordData.insert(texCoordData.end(), {texture_x, texture_y, texture_x, texture_y + texture_size, texture_x +
texture_size, texture_y + texture_size, texture_x + texture_size, texture_y});
}
glColorPointer(4, GL_FLOAT, 0, colorData.data());
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertexData.data());
glEnableClientState(GL_VERTEX_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, texCoordData.data());
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawArrays(GL_QUADS, 0, text.size() * 4);
}
/*-----------------------------------------------------------------------------------------------------------------*/
void UpdateScore(int num){
std::string numDis;
std::string str = std::to_string(num);
if (num < 100) {
numDis = "000000" + str;
} else if (num < 1000) {
numDis = "00000" + str;
} else if (num < 10000) {
numDis = "0000" + str;
} else if (num < 100000) {
numDis = "000" + str;
} else if (num < 1000000) {
numDis = "00" + str;
} else if (num < 10000000) {
numDis = "0" + str;
}
glLoadIdentity();
glTranslatef(-0.9, 0.9, 0.0);
DrawText(LoadTexture("font1.png"), numDis, 0.1, 0.00000000000001, 1.0, 1.0, 1.0, 1.0);
}
| 43.849117 | 210 | 0.424811 | [
"vector"
] |
293c193e54de7c36d0b5ceda38f76dffdfccb304 | 1,173 | hpp | C++ | src/BFS/BFS.hpp | LeGazzelle/AlgoWEB | 1915f2593c39b28a8ea9dd84ea2e8850046f69a9 | [
"MIT"
] | 1 | 2020-06-22T09:45:01.000Z | 2020-06-22T09:45:01.000Z | src/BFS/BFS.hpp | LeGazzelle/AlgoWEB | 1915f2593c39b28a8ea9dd84ea2e8850046f69a9 | [
"MIT"
] | null | null | null | src/BFS/BFS.hpp | LeGazzelle/AlgoWEB | 1915f2593c39b28a8ea9dd84ea2e8850046f69a9 | [
"MIT"
] | null | null | null | //
// Created by Leonardo De Laurentiis on 08/10/16.
//
#ifndef ALGOWEB_BFS_H
#define ALGOWEB_BFS_H
#include <queue>
#include <vector>
#include "../AlgoWEB.hpp"
#include "../Graphs/FastGraphs.hpp"
class BFS {
public:
BFS(FastGraph &g, Vertex u, vertex_index_t Dstr);
void nextStep();
void firstStep();
~BFS();
vertex_index_t getVisitedVertices() const;
vertex_index_t getVisitedEdges() const;
bool isCompleted() const;
bool isGreaterThanDstar() const;
vertex_index_t getUDeg() const;
private:
FastGraph *graph;
Vertex vertexU;
vertex_index_t visitedVertices;
vertex_index_t visitedEdges;
bool completed;
bool greaterThanDstar;
vertex_index_t uDeg;
vertex_index_t Dstar;
//data structures for BFS
std::queue<Vertex> *toBeVisited;
//BfsMatrix visitedEdgesMatrix; //initialized to false
StatefulVertices verticesState;
bool pause;
AdjacencyList *savedAl;
AdjacencyIterator savedAi;
//void edgesMatrixInit(vertex_index_t n);
//void setVisitedEdge(Vertex source, Vertex target);
void setVisited();
void queue(Vertex v);
};
#endif //ALGOWEB_BFS_H
| 18.619048 | 58 | 0.700767 | [
"vector"
] |
2943ad640c6940584b839969288d018a1ddc14f8 | 2,869 | cpp | C++ | solved_problems/732B.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | 1 | 2021-01-27T16:37:31.000Z | 2021-01-27T16:37:31.000Z | solved_problems/732B.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | null | null | null | solved_problems/732B.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | null | null | null | /*Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp
has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two
consecutive days in order to feel good. For example, if k = 5 and yesterday
Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at
least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n
integers a1, a2, ..., an, where ai is the number of times Polycarp will walk
with the dog on the i-th day while doing all his affairs (for example, he has to
go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly
in the next n days so that Cormen will feel good during all the n days. You can
assume that on the day before the first day and on the day after the n-th day
Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the
appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where
bi means the total number of walks with the dog on the i-th day. Input
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of
days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of
walks with Cormen on the i-th day which Polycarp has already planned. Output
In the first line print the smallest number of additional walks that Polycarp
should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b1, b2, ..., bn, where bi — the total number
of walks on the i-th day according to the found solutions (ai ≤ bi for all i
from 1 to n). If there are multiple solutions, print any of them. Examples Input
Copy
3 5
2 0 1
Output
Copy
4
2 3 2
Input
Copy
3 1
0 0 0
Output
Copy
1
0 1 0
Input
Copy
4 6
2 4 3 5
Output
Copy
0
2 4 3 5
*/
// Archit Singh
// 20168018
// Bachelor Of Technology
// Information Technology
// Motilal Nehru National Institute Of Technology
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main() {
// Fast I/O
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll d, t;
cin >> d >> t;
vector<ll> hr;
for (ll i = 0; i < d; i++) {
ll num;
cin >> num;
hr.push_back(num);
}
ll sum = 0;
for (ll i = 1; i < d; i++) {
ll add = hr[i] + hr[i - 1];
if (add < t) {
ll diff = t - add;
sum += diff;
hr[i] += diff;
}
}
cout << sum << endl;
for (ll i = 0; i < d; i++)
cout << hr[i] << " ";
cout << endl;
return 0;
}
| 24.947826 | 81 | 0.659463 | [
"vector"
] |
2945c1ec26107256c15e8a0120fd04e1f7ba88cb | 6,136 | cpp | C++ | tools/llvm-exegesis/lib/Target.cpp | HikariObfuscatorSuite/Hikari-with-llvm | 88514bf7d454b4f25a3c040e2f84e66a3651975c | [
"Apache-2.0"
] | null | null | null | tools/llvm-exegesis/lib/Target.cpp | HikariObfuscatorSuite/Hikari-with-llvm | 88514bf7d454b4f25a3c040e2f84e66a3651975c | [
"Apache-2.0"
] | null | null | null | tools/llvm-exegesis/lib/Target.cpp | HikariObfuscatorSuite/Hikari-with-llvm | 88514bf7d454b4f25a3c040e2f84e66a3651975c | [
"Apache-2.0"
] | 1 | 2022-01-03T19:46:57.000Z | 2022-01-03T19:46:57.000Z | //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Target.h"
#include "LatencyBenchmarkRunner.h"
#include "ParallelSnippetGenerator.h"
#include "SerialSnippetGenerator.h"
#include "UopsBenchmarkRunner.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
namespace llvm {
namespace exegesis {
ExegesisTarget::~ExegesisTarget() {} // anchor.
static ExegesisTarget *FirstTarget = nullptr;
const ExegesisTarget *ExegesisTarget::lookup(Triple TT) {
for (const ExegesisTarget *T = FirstTarget; T != nullptr; T = T->Next) {
if (T->matchesArch(TT.getArch()))
return T;
}
return nullptr;
}
Expected<std::unique_ptr<pfm::Counter>>
ExegesisTarget::createCounter(StringRef CounterName, const LLVMState &) const {
pfm::PerfEvent Event(CounterName);
if (!Event.valid())
return llvm::make_error<Failure>(
llvm::Twine("Unable to create counter with name '")
.concat(CounterName)
.concat("'"));
return std::make_unique<pfm::Counter>(std::move(Event));
}
void ExegesisTarget::registerTarget(ExegesisTarget *Target) {
if (FirstTarget == nullptr) {
FirstTarget = Target;
return;
}
if (Target->Next != nullptr)
return; // Already registered.
Target->Next = FirstTarget;
FirstTarget = Target;
}
std::unique_ptr<SnippetGenerator> ExegesisTarget::createSnippetGenerator(
InstructionBenchmark::ModeE Mode, const LLVMState &State,
const SnippetGenerator::Options &Opts) const {
switch (Mode) {
case InstructionBenchmark::Unknown:
return nullptr;
case InstructionBenchmark::Latency:
return createSerialSnippetGenerator(State, Opts);
case InstructionBenchmark::Uops:
case InstructionBenchmark::InverseThroughput:
return createParallelSnippetGenerator(State, Opts);
}
return nullptr;
}
Expected<std::unique_ptr<BenchmarkRunner>>
ExegesisTarget::createBenchmarkRunner(
InstructionBenchmark::ModeE Mode, const LLVMState &State,
InstructionBenchmark::ResultAggregationModeE ResultAggMode) const {
PfmCountersInfo PfmCounters = State.getPfmCounters();
switch (Mode) {
case InstructionBenchmark::Unknown:
return nullptr;
case InstructionBenchmark::Latency:
case InstructionBenchmark::InverseThroughput:
if (!PfmCounters.CycleCounter) {
const char *ModeName = Mode == InstructionBenchmark::Latency
? "latency"
: "inverse_throughput";
return make_error<Failure>(
Twine("can't run '")
.concat(ModeName)
.concat("' mode, sched model does not define a cycle counter."));
}
return createLatencyBenchmarkRunner(State, Mode, ResultAggMode);
case InstructionBenchmark::Uops:
if (!PfmCounters.UopsCounter && !PfmCounters.IssueCounters)
return make_error<Failure>("can't run 'uops' mode, sched model does not "
"define uops or issue counters.");
return createUopsBenchmarkRunner(State, ResultAggMode);
}
return nullptr;
}
std::unique_ptr<SnippetGenerator> ExegesisTarget::createSerialSnippetGenerator(
const LLVMState &State, const SnippetGenerator::Options &Opts) const {
return std::make_unique<SerialSnippetGenerator>(State, Opts);
}
std::unique_ptr<SnippetGenerator> ExegesisTarget::createParallelSnippetGenerator(
const LLVMState &State, const SnippetGenerator::Options &Opts) const {
return std::make_unique<ParallelSnippetGenerator>(State, Opts);
}
std::unique_ptr<BenchmarkRunner> ExegesisTarget::createLatencyBenchmarkRunner(
const LLVMState &State, InstructionBenchmark::ModeE Mode,
InstructionBenchmark::ResultAggregationModeE ResultAggMode) const {
return std::make_unique<LatencyBenchmarkRunner>(State, Mode, ResultAggMode);
}
std::unique_ptr<BenchmarkRunner> ExegesisTarget::createUopsBenchmarkRunner(
const LLVMState &State,
InstructionBenchmark::ResultAggregationModeE /*unused*/) const {
return std::make_unique<UopsBenchmarkRunner>(State);
}
static_assert(std::is_pod<PfmCountersInfo>::value,
"We shouldn't have dynamic initialization here");
const PfmCountersInfo PfmCountersInfo::Default = {nullptr, nullptr, nullptr,
0u};
const PfmCountersInfo &ExegesisTarget::getPfmCounters(StringRef CpuName) const {
assert(llvm::is_sorted(
CpuPfmCounters,
[](const CpuAndPfmCounters &LHS, const CpuAndPfmCounters &RHS) {
return strcmp(LHS.CpuName, RHS.CpuName) < 0;
}) &&
"CpuPfmCounters table is not sorted");
// Find entry
auto Found = llvm::lower_bound(CpuPfmCounters, CpuName);
if (Found == CpuPfmCounters.end() || StringRef(Found->CpuName) != CpuName) {
// Use the default.
if (CpuPfmCounters.begin() != CpuPfmCounters.end() &&
CpuPfmCounters.begin()->CpuName[0] == '\0') {
Found = CpuPfmCounters.begin(); // The target specifies a default.
} else {
return PfmCountersInfo::Default; // No default for the target.
}
}
assert(Found->PCI && "Missing counters");
return *Found->PCI;
}
ExegesisTarget::SavedState::~SavedState() {} // anchor.
namespace {
// Default implementation.
class ExegesisDefaultTarget : public ExegesisTarget {
public:
ExegesisDefaultTarget() : ExegesisTarget({}) {}
private:
std::vector<MCInst> setRegTo(const MCSubtargetInfo &STI, unsigned Reg,
const APInt &Value) const override {
llvm_unreachable("Not yet implemented");
}
bool matchesArch(Triple::ArchType Arch) const override {
llvm_unreachable("never called");
return false;
}
};
} // namespace
const ExegesisTarget &ExegesisTarget::getDefault() {
static ExegesisDefaultTarget Target;
return Target;
}
} // namespace exegesis
} // namespace llvm
| 34.27933 | 81 | 0.68693 | [
"vector",
"model"
] |
29484da9e7914100a29b09cff4eeebb866215ece | 23,108 | cpp | C++ | sparse/src/magma_z_precond_wrapper.cpp | stomov/magma.github | 79b982c88d64c660a04353fbac77fe00580060aa | [
"BSD-3-Clause"
] | 13 | 2018-03-25T01:03:31.000Z | 2022-03-31T09:12:23.000Z | sparse/src/magma_z_precond_wrapper.cpp | stomov/magma.github | 79b982c88d64c660a04353fbac77fe00580060aa | [
"BSD-3-Clause"
] | null | null | null | sparse/src/magma_z_precond_wrapper.cpp | stomov/magma.github | 79b982c88d64c660a04353fbac77fe00580060aa | [
"BSD-3-Clause"
] | 7 | 2018-03-24T23:33:28.000Z | 2022-01-25T18:41:03.000Z | /*
-- MAGMA (version 2.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date
@precisions normal z -> c d s
@author Hartwig Anzt
*/
#include "magmasparse_internal.h"
/**
Purpose
-------
For a given input matrix A and vectors x, y and the
preconditioner parameters, the respective preconditioner
is chosen. It approximates x for A x = y.
Arguments
---------
@param[in]
A magma_z_matrix
sparse matrix A
@param[in]
b magma_z_matrix
input vector b
@param[in]
x magma_z_matrix*
output vector x
@param[in,out]
precond magma_z_preconditioner
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zaux
********************************************************************/
extern "C" magma_int_t
magma_z_precond(
magma_z_matrix A,
magma_z_matrix b,
magma_z_matrix *x,
magma_z_preconditioner *precond,
magma_queue_t queue )
{
magma_int_t info = 0;
// set up precond parameters as solver parameters
magma_z_solver_par psolver_par;
psolver_par.rtol = precond->rtol;
psolver_par.maxiter = precond->maxiter;
psolver_par.restart = precond->restart;
psolver_par.verbose = 0;
magma_z_preconditioner pprecond;
pprecond.solver = Magma_NONE;
pprecond.maxiter = 3;
switch( precond->solver ) {
case Magma_CG:
CHECK( magma_zcg_res( A, b, x, &psolver_par, queue )); break;
case Magma_BICGSTAB:
CHECK( magma_zbicgstab( A, b, x, &psolver_par, queue )); break;
case Magma_GMRES:
CHECK( magma_zfgmres( A, b, x, &psolver_par, &pprecond, queue )); break;
case Magma_JACOBI:
CHECK( magma_zjacobi( A, b, x, &psolver_par, queue )); break;
case Magma_BAITER:
CHECK( magma_zbaiter( A, b, x, &psolver_par, &pprecond, queue )); break;
case Magma_IDR:
CHECK( magma_zidr( A, b, x, &psolver_par, queue )); break;
case Magma_CGS:
CHECK( magma_zcgs( A, b, x, &psolver_par, queue )); break;
case Magma_QMR:
CHECK( magma_zqmr( A, b, x, &psolver_par, queue )); break;
case Magma_TFQMR:
CHECK( magma_ztfqmr( A, b, x, &psolver_par, queue )); break;
case Magma_BAITERO:
CHECK( magma_zbaiter_overlap( A, b, x, &psolver_par, &pprecond, queue )); break;
default:
CHECK( magma_zcg_res( A, b, x, &psolver_par, queue )); break;
}
cleanup:
return info;
}
/**
Purpose
-------
For a given input matrix M and vectors x, y and the
preconditioner parameters, the respective preconditioner
is preprocessed.
E.g. for Jacobi: the scaling-vetor, for ILU the factorization.
Arguments
---------
@param[in]
A magma_z_matrix
sparse matrix M
@param[in]
b magma_z_matrix
input vector y
@param[in]
solver magma_z_solver_par
solver structure using the preconditioner
@param[in,out]
precond magma_z_preconditioner
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zaux
********************************************************************/
extern "C" magma_int_t
magma_z_precondsetup(
magma_z_matrix A, magma_z_matrix b,
magma_z_solver_par *solver,
magma_z_preconditioner *precond,
magma_queue_t queue )
{
magma_int_t info = 0;
// magma_zprecondfree( precond, queue );
//Chronometry
real_Double_t tempo1, tempo2;
tempo1 = magma_sync_wtime( queue );
if( A.num_rows != A.num_cols ){
printf("%% warning: non-square matrix.\n");
printf("%% Fallback: no preconditioner.\n");
precond->solver = Magma_NONE;
}
if ( precond->solver == Magma_JACOBI ) {
info = magma_zjacobisetup_diagscal( A, &(precond->d), queue );
}
else if ( precond->solver == Magma_PASTIX ) {
//info = magma_zpastixsetup( A, b, precond, queue );
info = MAGMA_ERR_NOT_SUPPORTED;
}
// ILU and related
else if ( precond->solver == Magma_ILU ) {
if ( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ){
info = magma_zcumilusetup( A, precond, queue );
//info = magma_ziluisaisetup( A, b, precond, queue );
info = magma_ziluisaisetup_lower( A, precond->L, precond, queue );
info = magma_ziluisaisetup_upper( A, precond->U, precond, queue );
} else {
info = magma_zcumilusetup( A, precond, queue );
}
}
else if ( precond->solver == Magma_PARILU ) {
info = magma_zparilusetup( A, b, precond, queue );
if ( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ){
info = magma_ziluisaisetup( A, b, precond, queue );
}
}
else if ( precond->solver == Magma_PARILUT ) {
#ifdef _OPENMP
info = magma_zparilut3setup( A, b, precond, queue );
if ( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ){
info = magma_ziluisaisetup( A, b, precond, queue );
}
precond->solver = Magma_PARILU; // handle as PARILU
#else
printf( "error: preconditioner requires OpenMP.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
#endif
}
else if ( precond->solver == Magma_CUSTOMILU ) {
info = magma_zcustomilusetup( A, b, precond, queue );
precond->solver = Magma_PARILU; // handle as PARILU
}
// symmetric: Cholesky variant
else if ( precond->solver == Magma_ICC ) {
if ( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ){
info = magma_zcumiccsetup( A, precond, queue );
info = magma_zicisaisetup( A, b, precond, queue );
} else {
info = magma_zcumiccsetup( A, precond, queue );
}
}
else if ( precond->solver == Magma_PARIC ) {
info = magma_zparicsetup( A, b, precond, queue );
}
else if ( precond->solver == Magma_PARICT ) {
#ifdef _OPENMP
info = magma_zparilut3setup( A, b, precond, queue );
precond->solver = Magma_PARILU; // handle as PARIC
precond->trisolver = Magma_CUSOLVE; // for now only allow cusolve
printf( "%% warning: only PARILUT supported.\n" );
#else
printf( "error: preconditioner requires OpenMP.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
#endif
}
else if ( precond->solver == Magma_CUSTOMIC ) {
info = magma_zcustomicsetup( A, b, precond, queue );
precond->solver = Magma_PARIC; // handle as PARIC
}
// none case
else if ( precond->solver == Magma_NONE ) {
info = MAGMA_SUCCESS;
}
else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
if(
( solver->solver == Magma_PQMR ||
solver->solver == Magma_PQMRMERGE ||
solver->solver == Magma_PBICG ||
solver->solver == Magma_LSQR ) &&
( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ||
precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) ) { // also prepare the transpose
info = magma_zcumilusetup_transpose( A, precond, queue );
if( info == 0 &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) )
{
// simple solution: copy
info = info + magma_zmtranspose( precond->LD, &precond->LDT, queue );
info = info + magma_zmtranspose( precond->UD, &precond->UDT, queue );
// info = magma_ziluisaisetup_t( A, b, precond, queue );
}
}
tempo2 = magma_sync_wtime( queue );
precond->setuptime = tempo2-tempo1;
return info;
}
/**
Purpose
-------
For a given input matrix A and vectors x, y and the
preconditioner parameters, the respective preconditioner
is applied.
E.g. for Jacobi: the scaling-vetor, for ILU the triangular solves.
Arguments
---------
@param[in]
A magma_z_matrix
sparse matrix A
@param[in]
b magma_z_matrix
input vector b
@param[in,out]
x magma_z_matrix*
output vector x
@param[in]
precond magma_z_preconditioner
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zaux
********************************************************************/
extern "C" magma_int_t
magma_z_applyprecond(
magma_z_matrix A,
magma_z_matrix b,
magma_z_matrix *x,
magma_z_preconditioner *precond,
magma_queue_t queue )
{
magma_int_t info = 0;
magma_z_matrix tmp={Magma_CSR};
if ( precond->solver == Magma_JACOBI ) {
CHECK( magma_zjacobi_diagscal( b.num_rows, precond->d, b, x, queue ));
}
else if ( precond->solver == Magma_PASTIX ) {
//CHECK( magma_zapplypastix( b, x, precond, queue ));
info = MAGMA_ERR_NOT_SUPPORTED;
}
else if ( precond->solver == Magma_ILU ) {
CHECK( magma_zvinit( &tmp, Magma_DEV, b.num_rows, b.num_cols, MAGMA_Z_ZERO, queue ));
}
else if ( precond->solver == Magma_ICC ) {
CHECK( magma_zvinit( &tmp, Magma_DEV, b.num_rows, b.num_cols, MAGMA_Z_ZERO, queue ));
}
else if ( precond->solver == Magma_NONE ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
cleanup:
magma_zmfree( &tmp, queue );
//magmablasSetKernelStream( orig_queue );
return info;
}
/**
Purpose
-------
For a given input matrix A and vectors x, y and the
preconditioner parameters, the respective left preconditioner
is applied.
E.g. for Jacobi: the scaling-vetor, for ILU the left triangular solve.
Arguments
---------
@param[in]
trans magma_trans_t
mode of the preconditioner: MagmaTrans or MagmaNoTrans
@param[in]
A magma_z_matrix
sparse matrix A
@param[in]
b magma_z_matrix
input vector b
@param[in,out]
x magma_z_matrix*
output vector x
@param[in]
precond magma_z_preconditioner
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zaux
********************************************************************/
extern "C" magma_int_t
magma_z_applyprecond_left(
magma_trans_t trans,
magma_z_matrix A,
magma_z_matrix b,
magma_z_matrix *x,
magma_z_preconditioner *precond,
magma_queue_t queue )
{
magma_int_t info = 0;
//Chronometry
real_Double_t tempo1, tempo2;
tempo1 = magma_sync_wtime( queue );
magma_zopts zopts;
zopts.solver_par.solver = precond->trisolver;
zopts.solver_par.maxiter = precond->maxiter;
zopts.solver_par.verbose = 0;
zopts.solver_par.version = 0;
zopts.solver_par.restart = 50;
zopts.solver_par.atol = 1e-16;
zopts.solver_par.rtol = 1e-10;
if( trans == MagmaNoTrans ) {
if ( precond->solver == Magma_JACOBI ) {
CHECK( magma_zjacobi_diagscal( b.num_rows, precond->d, b, x, queue ));
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumilu_l( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_SYNCFREESOLVE ) ){
CHECK( magma_zapplycumilu_l( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumicc_l( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) ){
CHECK( magma_zisai_l( b, x, precond, queue ) );
// magma_z_spmv( MAGMA_Z_ONE, precond->L, b,MAGMA_Z_ZERO, *x, queue ); // SPAI
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) ){
CHECK( magma_zisai_l( b, x, precond, queue ) );
// magma_z_spmv( MAGMA_Z_ONE, precond->L, b,MAGMA_Z_ZERO, *x, queue ); // SPAI
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) ){
magma_z_solver( precond->L, b, x, &zopts, queue );
}
else if ( precond->solver == Magma_NONE ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
else if ( precond->solver == Magma_FUNCTION ) {
CHECK( magma_zapplycustomprecond_l( b, x, precond, queue ));
}
else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
} else if ( trans == MagmaTrans ){
if ( precond->solver == Magma_JACOBI ) {
CHECK( magma_zjacobi_diagscal( b.num_rows, precond->d, b, x, queue ));
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumilu_l_transpose( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumicc_l( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) ){
CHECK( magma_zisai_l_t( b, x, precond, queue ) );
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) ){
magma_z_solver( precond->L, b, x, &zopts, queue );
}
else if ( precond->solver == Magma_NONE ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
else if ( precond->solver == Magma_FUNCTION ) {
CHECK( magma_zapplycustomprecond_l( b, x, precond, queue ));
}
else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
} else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
tempo2 = magma_sync_wtime( queue );
precond->runtime += tempo2-tempo1;
cleanup:
return info;
}
/**
Purpose
-------
For a given input matrix A and vectors x, y and the
preconditioner parameters, the respective right-preconditioner
is applied.
E.g. for Jacobi: the scaling-vetor, for ILU the right triangular solve.
Arguments
---------
@param[in]
trans magma_trans_t
mode of the preconditioner: MagmaTrans or MagmaNoTrans
@param[in]
A magma_z_matrix
sparse matrix A
@param[in]
b magma_z_matrix
input vector b
@param[in,out]
x magma_z_matrix*
output vector x
@param[in]
precond magma_z_preconditioner
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_zaux
********************************************************************/
extern "C" magma_int_t
magma_z_applyprecond_right(
magma_trans_t trans,
magma_z_matrix A,
magma_z_matrix b,
magma_z_matrix *x,
magma_z_preconditioner *precond,
magma_queue_t queue )
{
magma_int_t info = 0;
//Chronometry
real_Double_t tempo1, tempo2;
tempo1 = magma_sync_wtime( queue );
magma_zopts zopts;
zopts.solver_par.solver = precond->trisolver;
zopts.solver_par.maxiter = precond->maxiter;
zopts.solver_par.verbose = 0;
zopts.solver_par.version = 0;
zopts.solver_par.restart = 50;
zopts.solver_par.atol = 1e-16;
zopts.solver_par.rtol = 1e-10;
if( trans == MagmaNoTrans ) {
if ( precond->solver == Magma_JACOBI ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ) {
CHECK( magma_zapplycumilu_r( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_SYNCFREESOLVE ) ){
CHECK( magma_zapplycumilu_r( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumicc_r( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) ){
CHECK( magma_zisai_r( b, x, precond, queue ) );
// magma_z_spmv( MAGMA_Z_ONE, precond->L, b,MAGMA_Z_ZERO, *x, queue ); // SPAI
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) ){
CHECK( magma_zisai_r( b, x, precond, queue ) );
// magma_z_spmv( MAGMA_Z_ONE, precond->L, b,MAGMA_Z_ZERO, *x, queue ); // SPAI
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) ){
magma_z_solver( precond->U, b, x, &zopts, queue );
}
else if ( precond->solver == Magma_NONE ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
// else if ( precond->solver == Magma_ISAI ) {
// CHECK( magma_zisai_r( b, x, precond, queue ) );
// // magma_z_spmv( MAGMA_Z_ONE, precond->U, b,MAGMA_Z_ZERO, *x, queue ); // SPAI
// }
else if ( precond->solver == Magma_FUNCTION ) {
CHECK( magma_zapplycustomprecond_r( b, x, precond, queue ));
}
else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
} else if ( trans == MagmaTrans ){
if ( precond->solver == Magma_JACOBI ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumilu_r_transpose( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ICC ||
precond->solver == Magma_PARIC ) &&
( precond->trisolver == Magma_CUSOLVE ||
precond->trisolver == 0 ) ){
CHECK( magma_zapplycumicc_r( b, x, precond, queue ));
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) &&
( precond->trisolver == Magma_ISAI ||
precond->trisolver == Magma_JACOBI ||
precond->trisolver == Magma_VBJACOBI ) ){
CHECK( magma_zisai_r_t( b, x, precond, queue ) );
// magma_z_spmv( MAGMA_Z_ONE, precond->U, b,MAGMA_Z_ZERO, *x, queue ); // SPAI
}
else if ( ( precond->solver == Magma_ILU ||
precond->solver == Magma_PARILU ) ){
magma_z_solver( precond->U, b, x, &zopts, queue );
}
else if ( precond->solver == Magma_NONE ) {
magma_zcopy( b.num_rows*b.num_cols, b.dval, 1, x->dval, 1, queue ); // x = b
}
else if ( precond->solver == Magma_FUNCTION ) {
CHECK( magma_zapplycustomprecond_r( b, x, precond, queue ));
}
else {
printf( "error: preconditioner type not yet supported.\n" );
info = MAGMA_ERR_NOT_SUPPORTED;
}
}
tempo2 = magma_sync_wtime( queue );
precond->runtime += tempo2-tempo1;
cleanup:
return info;
}
| 34.33581 | 96 | 0.53977 | [
"vector"
] |
294dff72323b151abe3f59442ca3f64f7f0b2556 | 56,076 | cpp | C++ | src/tests/hello_xr/openxr_program.cpp | microdee/OpenXR-SDK-Source | 57cfe1711414776556039b1d65fa386ba7c1f4e9 | [
"MIT",
"Unlicense",
"Apache-2.0",
"BSD-3-Clause"
] | 226 | 2019-07-30T00:07:22.000Z | 2022-03-29T03:19:54.000Z | src/tests/hello_xr/openxr_program.cpp | microdee/OpenXR-SDK-Source | 57cfe1711414776556039b1d65fa386ba7c1f4e9 | [
"MIT",
"Unlicense",
"Apache-2.0",
"BSD-3-Clause"
] | 171 | 2019-07-29T17:51:26.000Z | 2022-03-31T18:17:31.000Z | src/tests/hello_xr/openxr_program.cpp | microdee/OpenXR-SDK-Source | 57cfe1711414776556039b1d65fa386ba7c1f4e9 | [
"MIT",
"Unlicense",
"Apache-2.0",
"BSD-3-Clause"
] | 105 | 2019-08-01T09:26:49.000Z | 2022-03-26T03:43:42.000Z | // Copyright (c) 2017-2021, The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0
#include "pch.h"
#include "common.h"
#include "options.h"
#include "platformdata.h"
#include "platformplugin.h"
#include "graphicsplugin.h"
#include "openxr_program.h"
#include <common/xr_linear.h>
#include <array>
#include <cmath>
namespace {
#if !defined(XR_USE_PLATFORM_WIN32)
#define strcpy_s(dest, source) strncpy((dest), (source), sizeof(dest))
#endif
namespace Side {
const int LEFT = 0;
const int RIGHT = 1;
const int COUNT = 2;
} // namespace Side
inline std::string GetXrVersionString(XrVersion ver) {
return Fmt("%d.%d.%d", XR_VERSION_MAJOR(ver), XR_VERSION_MINOR(ver), XR_VERSION_PATCH(ver));
}
inline XrFormFactor GetXrFormFactor(const std::string& formFactorStr) {
if (EqualsIgnoreCase(formFactorStr, "Hmd")) {
return XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
}
if (EqualsIgnoreCase(formFactorStr, "Handheld")) {
return XR_FORM_FACTOR_HANDHELD_DISPLAY;
}
throw std::invalid_argument(Fmt("Unknown form factor '%s'", formFactorStr.c_str()));
}
inline XrViewConfigurationType GetXrViewConfigurationType(const std::string& viewConfigurationStr) {
if (EqualsIgnoreCase(viewConfigurationStr, "Mono")) {
return XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
}
if (EqualsIgnoreCase(viewConfigurationStr, "Stereo")) {
return XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
}
throw std::invalid_argument(Fmt("Unknown view configuration '%s'", viewConfigurationStr.c_str()));
}
inline XrEnvironmentBlendMode GetXrEnvironmentBlendMode(const std::string& environmentBlendModeStr) {
if (EqualsIgnoreCase(environmentBlendModeStr, "Opaque")) {
return XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
}
if (EqualsIgnoreCase(environmentBlendModeStr, "Additive")) {
return XR_ENVIRONMENT_BLEND_MODE_ADDITIVE;
}
if (EqualsIgnoreCase(environmentBlendModeStr, "AlphaBlend")) {
return XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
}
throw std::invalid_argument(Fmt("Unknown environment blend mode '%s'", environmentBlendModeStr.c_str()));
}
namespace Math {
namespace Pose {
XrPosef Identity() {
XrPosef t{};
t.orientation.w = 1;
return t;
}
XrPosef Translation(const XrVector3f& translation) {
XrPosef t = Identity();
t.position = translation;
return t;
}
XrPosef RotateCCWAboutYAxis(float radians, XrVector3f translation) {
XrPosef t = Identity();
t.orientation.x = 0.f;
t.orientation.y = std::sin(radians * 0.5f);
t.orientation.z = 0.f;
t.orientation.w = std::cos(radians * 0.5f);
t.position = translation;
return t;
}
} // namespace Pose
} // namespace Math
inline XrReferenceSpaceCreateInfo GetXrReferenceSpaceCreateInfo(const std::string& referenceSpaceTypeStr) {
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo{XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::Identity();
if (EqualsIgnoreCase(referenceSpaceTypeStr, "View")) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_VIEW;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "ViewFront")) {
// Render head-locked 2m in front of device.
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::Translation({0.f, 0.f, -2.f}),
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_VIEW;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "Local")) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "Stage")) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageLeft")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(0.f, {-2.f, 0.f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageRight")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(0.f, {2.f, 0.f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageLeftRotated")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(3.14f / 3.f, {-2.f, 0.5f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageRightRotated")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(-3.14f / 3.f, {2.f, 0.5f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else {
throw std::invalid_argument(Fmt("Unknown reference space type '%s'", referenceSpaceTypeStr.c_str()));
}
return referenceSpaceCreateInfo;
}
struct OpenXrProgram : IOpenXrProgram {
OpenXrProgram(const std::shared_ptr<Options>& options, const std::shared_ptr<IPlatformPlugin>& platformPlugin,
const std::shared_ptr<IGraphicsPlugin>& graphicsPlugin)
: m_options(options), m_platformPlugin(platformPlugin), m_graphicsPlugin(graphicsPlugin) {}
~OpenXrProgram() override {
if (m_input.actionSet != XR_NULL_HANDLE) {
for (auto hand : {Side::LEFT, Side::RIGHT}) {
xrDestroySpace(m_input.handSpace[hand]);
}
xrDestroyActionSet(m_input.actionSet);
}
for (Swapchain swapchain : m_swapchains) {
xrDestroySwapchain(swapchain.handle);
}
for (XrSpace visualizedSpace : m_visualizedSpaces) {
xrDestroySpace(visualizedSpace);
}
if (m_appSpace != XR_NULL_HANDLE) {
xrDestroySpace(m_appSpace);
}
if (m_session != XR_NULL_HANDLE) {
xrDestroySession(m_session);
}
if (m_instance != XR_NULL_HANDLE) {
xrDestroyInstance(m_instance);
}
}
static void LogLayersAndExtensions() {
// Write out extension properties for a given layer.
const auto logExtensions = [](const char* layerName, int indent = 0) {
uint32_t instanceExtensionCount;
CHECK_XRCMD(xrEnumerateInstanceExtensionProperties(layerName, 0, &instanceExtensionCount, nullptr));
std::vector<XrExtensionProperties> extensions(instanceExtensionCount);
for (XrExtensionProperties& extension : extensions) {
extension.type = XR_TYPE_EXTENSION_PROPERTIES;
}
CHECK_XRCMD(xrEnumerateInstanceExtensionProperties(layerName, (uint32_t)extensions.size(), &instanceExtensionCount,
extensions.data()));
const std::string indentStr(indent, ' ');
Log::Write(Log::Level::Verbose, Fmt("%sAvailable Extensions: (%d)", indentStr.c_str(), instanceExtensionCount));
for (const XrExtensionProperties& extension : extensions) {
Log::Write(Log::Level::Verbose, Fmt("%s Name=%s SpecVersion=%d", indentStr.c_str(), extension.extensionName,
extension.extensionVersion));
}
};
// Log non-layer extensions (layerName==nullptr).
logExtensions(nullptr);
// Log layers and any of their extensions.
{
uint32_t layerCount;
CHECK_XRCMD(xrEnumerateApiLayerProperties(0, &layerCount, nullptr));
std::vector<XrApiLayerProperties> layers(layerCount);
for (XrApiLayerProperties& layer : layers) {
layer.type = XR_TYPE_API_LAYER_PROPERTIES;
}
CHECK_XRCMD(xrEnumerateApiLayerProperties((uint32_t)layers.size(), &layerCount, layers.data()));
Log::Write(Log::Level::Info, Fmt("Available Layers: (%d)", layerCount));
for (const XrApiLayerProperties& layer : layers) {
Log::Write(Log::Level::Verbose,
Fmt(" Name=%s SpecVersion=%s LayerVersion=%d Description=%s", layer.layerName,
GetXrVersionString(layer.specVersion).c_str(), layer.layerVersion, layer.description));
logExtensions(layer.layerName, 4);
}
}
}
void LogInstanceInfo() {
CHECK(m_instance != XR_NULL_HANDLE);
XrInstanceProperties instanceProperties{XR_TYPE_INSTANCE_PROPERTIES};
CHECK_XRCMD(xrGetInstanceProperties(m_instance, &instanceProperties));
Log::Write(Log::Level::Info, Fmt("Instance RuntimeName=%s RuntimeVersion=%s", instanceProperties.runtimeName,
GetXrVersionString(instanceProperties.runtimeVersion).c_str()));
}
void CreateInstanceInternal() {
CHECK(m_instance == XR_NULL_HANDLE);
// Create union of extensions required by platform and graphics plugins.
std::vector<const char*> extensions;
// Transform platform and graphics extension std::strings to C strings.
const std::vector<std::string> platformExtensions = m_platformPlugin->GetInstanceExtensions();
std::transform(platformExtensions.begin(), platformExtensions.end(), std::back_inserter(extensions),
[](const std::string& ext) { return ext.c_str(); });
const std::vector<std::string> graphicsExtensions = m_graphicsPlugin->GetInstanceExtensions();
std::transform(graphicsExtensions.begin(), graphicsExtensions.end(), std::back_inserter(extensions),
[](const std::string& ext) { return ext.c_str(); });
XrInstanceCreateInfo createInfo{XR_TYPE_INSTANCE_CREATE_INFO};
createInfo.next = m_platformPlugin->GetInstanceCreateExtension();
createInfo.enabledExtensionCount = (uint32_t)extensions.size();
createInfo.enabledExtensionNames = extensions.data();
strcpy(createInfo.applicationInfo.applicationName, "HelloXR");
createInfo.applicationInfo.apiVersion = XR_CURRENT_API_VERSION;
CHECK_XRCMD(xrCreateInstance(&createInfo, &m_instance));
}
void CreateInstance() override {
LogLayersAndExtensions();
CreateInstanceInternal();
LogInstanceInfo();
}
void LogViewConfigurations() {
CHECK(m_instance != XR_NULL_HANDLE);
CHECK(m_systemId != XR_NULL_SYSTEM_ID);
uint32_t viewConfigTypeCount;
CHECK_XRCMD(xrEnumerateViewConfigurations(m_instance, m_systemId, 0, &viewConfigTypeCount, nullptr));
std::vector<XrViewConfigurationType> viewConfigTypes(viewConfigTypeCount);
CHECK_XRCMD(xrEnumerateViewConfigurations(m_instance, m_systemId, viewConfigTypeCount, &viewConfigTypeCount,
viewConfigTypes.data()));
CHECK((uint32_t)viewConfigTypes.size() == viewConfigTypeCount);
Log::Write(Log::Level::Info, Fmt("Available View Configuration Types: (%d)", viewConfigTypeCount));
for (XrViewConfigurationType viewConfigType : viewConfigTypes) {
Log::Write(Log::Level::Verbose, Fmt(" View Configuration Type: %s %s", to_string(viewConfigType),
viewConfigType == m_viewConfigType ? "(Selected)" : ""));
XrViewConfigurationProperties viewConfigProperties{XR_TYPE_VIEW_CONFIGURATION_PROPERTIES};
CHECK_XRCMD(xrGetViewConfigurationProperties(m_instance, m_systemId, viewConfigType, &viewConfigProperties));
Log::Write(Log::Level::Verbose,
Fmt(" View configuration FovMutable=%s", viewConfigProperties.fovMutable == XR_TRUE ? "True" : "False"));
uint32_t viewCount;
CHECK_XRCMD(xrEnumerateViewConfigurationViews(m_instance, m_systemId, viewConfigType, 0, &viewCount, nullptr));
if (viewCount > 0) {
std::vector<XrViewConfigurationView> views(viewCount, {XR_TYPE_VIEW_CONFIGURATION_VIEW});
CHECK_XRCMD(
xrEnumerateViewConfigurationViews(m_instance, m_systemId, viewConfigType, viewCount, &viewCount, views.data()));
for (uint32_t i = 0; i < views.size(); i++) {
const XrViewConfigurationView& view = views[i];
Log::Write(Log::Level::Verbose, Fmt(" View [%d]: Recommended Width=%d Height=%d SampleCount=%d", i,
view.recommendedImageRectWidth, view.recommendedImageRectHeight,
view.recommendedSwapchainSampleCount));
Log::Write(Log::Level::Verbose,
Fmt(" View [%d]: Maximum Width=%d Height=%d SampleCount=%d", i, view.maxImageRectWidth,
view.maxImageRectHeight, view.maxSwapchainSampleCount));
}
} else {
Log::Write(Log::Level::Error, Fmt("Empty view configuration type"));
}
LogEnvironmentBlendMode(viewConfigType);
}
}
void LogEnvironmentBlendMode(XrViewConfigurationType type) {
CHECK(m_instance != XR_NULL_HANDLE);
CHECK(m_systemId != 0);
uint32_t count;
CHECK_XRCMD(xrEnumerateEnvironmentBlendModes(m_instance, m_systemId, type, 0, &count, nullptr));
CHECK(count > 0);
Log::Write(Log::Level::Info, Fmt("Available Environment Blend Mode count : (%d)", count));
std::vector<XrEnvironmentBlendMode> blendModes(count);
CHECK_XRCMD(xrEnumerateEnvironmentBlendModes(m_instance, m_systemId, type, count, &count, blendModes.data()));
bool blendModeFound = false;
for (XrEnvironmentBlendMode mode : blendModes) {
const bool blendModeMatch = (mode == m_environmentBlendMode);
Log::Write(Log::Level::Info,
Fmt("Environment Blend Mode (%s) : %s", to_string(mode), blendModeMatch ? "(Selected)" : ""));
blendModeFound |= blendModeMatch;
}
CHECK(blendModeFound);
}
void InitializeSystem() override {
CHECK(m_instance != XR_NULL_HANDLE);
CHECK(m_systemId == XR_NULL_SYSTEM_ID);
m_formFactor = GetXrFormFactor(m_options->FormFactor);
m_viewConfigType = GetXrViewConfigurationType(m_options->ViewConfiguration);
m_environmentBlendMode = GetXrEnvironmentBlendMode(m_options->EnvironmentBlendMode);
XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO};
systemInfo.formFactor = m_formFactor;
CHECK_XRCMD(xrGetSystem(m_instance, &systemInfo, &m_systemId));
Log::Write(Log::Level::Verbose, Fmt("Using system %d for form factor %s", m_systemId, to_string(m_formFactor)));
CHECK(m_instance != XR_NULL_HANDLE);
CHECK(m_systemId != XR_NULL_SYSTEM_ID);
LogViewConfigurations();
// The graphics API can initialize the graphics device now that the systemId and instance
// handle are available.
m_graphicsPlugin->InitializeDevice(m_instance, m_systemId);
}
void LogReferenceSpaces() {
CHECK(m_session != XR_NULL_HANDLE);
uint32_t spaceCount;
CHECK_XRCMD(xrEnumerateReferenceSpaces(m_session, 0, &spaceCount, nullptr));
std::vector<XrReferenceSpaceType> spaces(spaceCount);
CHECK_XRCMD(xrEnumerateReferenceSpaces(m_session, spaceCount, &spaceCount, spaces.data()));
Log::Write(Log::Level::Info, Fmt("Available reference spaces: %d", spaceCount));
for (XrReferenceSpaceType space : spaces) {
Log::Write(Log::Level::Verbose, Fmt(" Name: %s", to_string(space)));
}
}
struct InputState {
XrActionSet actionSet{XR_NULL_HANDLE};
XrAction grabAction{XR_NULL_HANDLE};
XrAction poseAction{XR_NULL_HANDLE};
XrAction vibrateAction{XR_NULL_HANDLE};
XrAction quitAction{XR_NULL_HANDLE};
std::array<XrPath, Side::COUNT> handSubactionPath;
std::array<XrSpace, Side::COUNT> handSpace;
std::array<float, Side::COUNT> handScale = {{1.0f, 1.0f}};
std::array<XrBool32, Side::COUNT> handActive;
};
void InitializeActions() {
// Create an action set.
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy_s(actionSetInfo.actionSetName, "gameplay");
strcpy_s(actionSetInfo.localizedActionSetName, "Gameplay");
actionSetInfo.priority = 0;
CHECK_XRCMD(xrCreateActionSet(m_instance, &actionSetInfo, &m_input.actionSet));
}
// Get the XrPath for the left and right hands - we will use them as subaction paths.
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left", &m_input.handSubactionPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right", &m_input.handSubactionPath[Side::RIGHT]));
// Create actions.
{
// Create an input action for grabbing objects with the left and right hands.
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_FLOAT_INPUT;
strcpy_s(actionInfo.actionName, "grab_object");
strcpy_s(actionInfo.localizedActionName, "Grab Object");
actionInfo.countSubactionPaths = uint32_t(m_input.handSubactionPath.size());
actionInfo.subactionPaths = m_input.handSubactionPath.data();
CHECK_XRCMD(xrCreateAction(m_input.actionSet, &actionInfo, &m_input.grabAction));
// Create an input action getting the left and right hand poses.
actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT;
strcpy_s(actionInfo.actionName, "hand_pose");
strcpy_s(actionInfo.localizedActionName, "Hand Pose");
actionInfo.countSubactionPaths = uint32_t(m_input.handSubactionPath.size());
actionInfo.subactionPaths = m_input.handSubactionPath.data();
CHECK_XRCMD(xrCreateAction(m_input.actionSet, &actionInfo, &m_input.poseAction));
// Create output actions for vibrating the left and right controller.
actionInfo.actionType = XR_ACTION_TYPE_VIBRATION_OUTPUT;
strcpy_s(actionInfo.actionName, "vibrate_hand");
strcpy_s(actionInfo.localizedActionName, "Vibrate Hand");
actionInfo.countSubactionPaths = uint32_t(m_input.handSubactionPath.size());
actionInfo.subactionPaths = m_input.handSubactionPath.data();
CHECK_XRCMD(xrCreateAction(m_input.actionSet, &actionInfo, &m_input.vibrateAction));
// Create input actions for quitting the session using the left and right controller.
// Since it doesn't matter which hand did this, we do not specify subaction paths for it.
// We will just suggest bindings for both hands, where possible.
actionInfo.actionType = XR_ACTION_TYPE_BOOLEAN_INPUT;
strcpy_s(actionInfo.actionName, "quit_session");
strcpy_s(actionInfo.localizedActionName, "Quit Session");
actionInfo.countSubactionPaths = 0;
actionInfo.subactionPaths = nullptr;
CHECK_XRCMD(xrCreateAction(m_input.actionSet, &actionInfo, &m_input.quitAction));
}
std::array<XrPath, Side::COUNT> selectPath;
std::array<XrPath, Side::COUNT> squeezeValuePath;
std::array<XrPath, Side::COUNT> squeezeForcePath;
std::array<XrPath, Side::COUNT> squeezeClickPath;
std::array<XrPath, Side::COUNT> posePath;
std::array<XrPath, Side::COUNT> hapticPath;
std::array<XrPath, Side::COUNT> menuClickPath;
std::array<XrPath, Side::COUNT> bClickPath;
std::array<XrPath, Side::COUNT> triggerValuePath;
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/select/click", &selectPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/select/click", &selectPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/squeeze/value", &squeezeValuePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/squeeze/value", &squeezeValuePath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/squeeze/force", &squeezeForcePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/squeeze/force", &squeezeForcePath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/squeeze/click", &squeezeClickPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/squeeze/click", &squeezeClickPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/grip/pose", &posePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/grip/pose", &posePath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/output/haptic", &hapticPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/output/haptic", &hapticPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/menu/click", &menuClickPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/menu/click", &menuClickPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/b/click", &bClickPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/b/click", &bClickPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/left/input/trigger/value", &triggerValuePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(m_instance, "/user/hand/right/input/trigger/value", &triggerValuePath[Side::RIGHT]));
// Suggest bindings for KHR Simple.
{
XrPath khrSimpleInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(m_instance, "/interaction_profiles/khr/simple_controller", &khrSimpleInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{// Fall back to a click input for the grab action.
{m_input.grabAction, selectPath[Side::LEFT]},
{m_input.grabAction, selectPath[Side::RIGHT]},
{m_input.poseAction, posePath[Side::LEFT]},
{m_input.poseAction, posePath[Side::RIGHT]},
{m_input.quitAction, menuClickPath[Side::LEFT]},
{m_input.quitAction, menuClickPath[Side::RIGHT]},
{m_input.vibrateAction, hapticPath[Side::LEFT]},
{m_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = khrSimpleInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(m_instance, &suggestedBindings));
}
// Suggest bindings for the Oculus Touch.
{
XrPath oculusTouchInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(m_instance, "/interaction_profiles/oculus/touch_controller", &oculusTouchInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{m_input.grabAction, squeezeValuePath[Side::LEFT]},
{m_input.grabAction, squeezeValuePath[Side::RIGHT]},
{m_input.poseAction, posePath[Side::LEFT]},
{m_input.poseAction, posePath[Side::RIGHT]},
{m_input.quitAction, menuClickPath[Side::LEFT]},
{m_input.vibrateAction, hapticPath[Side::LEFT]},
{m_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = oculusTouchInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(m_instance, &suggestedBindings));
}
// Suggest bindings for the Vive Controller.
{
XrPath viveControllerInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(m_instance, "/interaction_profiles/htc/vive_controller", &viveControllerInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{m_input.grabAction, triggerValuePath[Side::LEFT]},
{m_input.grabAction, triggerValuePath[Side::RIGHT]},
{m_input.poseAction, posePath[Side::LEFT]},
{m_input.poseAction, posePath[Side::RIGHT]},
{m_input.quitAction, menuClickPath[Side::LEFT]},
{m_input.quitAction, menuClickPath[Side::RIGHT]},
{m_input.vibrateAction, hapticPath[Side::LEFT]},
{m_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = viveControllerInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(m_instance, &suggestedBindings));
}
// Suggest bindings for the Valve Index Controller.
{
XrPath indexControllerInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(m_instance, "/interaction_profiles/valve/index_controller", &indexControllerInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{m_input.grabAction, squeezeForcePath[Side::LEFT]},
{m_input.grabAction, squeezeForcePath[Side::RIGHT]},
{m_input.poseAction, posePath[Side::LEFT]},
{m_input.poseAction, posePath[Side::RIGHT]},
{m_input.quitAction, bClickPath[Side::LEFT]},
{m_input.quitAction, bClickPath[Side::RIGHT]},
{m_input.vibrateAction, hapticPath[Side::LEFT]},
{m_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = indexControllerInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(m_instance, &suggestedBindings));
}
// Suggest bindings for the Microsoft Mixed Reality Motion Controller.
{
XrPath microsoftMixedRealityInteractionProfilePath;
CHECK_XRCMD(xrStringToPath(m_instance, "/interaction_profiles/microsoft/motion_controller",
µsoftMixedRealityInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{m_input.grabAction, squeezeClickPath[Side::LEFT]},
{m_input.grabAction, squeezeClickPath[Side::RIGHT]},
{m_input.poseAction, posePath[Side::LEFT]},
{m_input.poseAction, posePath[Side::RIGHT]},
{m_input.quitAction, menuClickPath[Side::LEFT]},
{m_input.quitAction, menuClickPath[Side::RIGHT]},
{m_input.vibrateAction, hapticPath[Side::LEFT]},
{m_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = microsoftMixedRealityInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(m_instance, &suggestedBindings));
}
XrActionSpaceCreateInfo actionSpaceInfo{XR_TYPE_ACTION_SPACE_CREATE_INFO};
actionSpaceInfo.action = m_input.poseAction;
actionSpaceInfo.poseInActionSpace.orientation.w = 1.f;
actionSpaceInfo.subactionPath = m_input.handSubactionPath[Side::LEFT];
CHECK_XRCMD(xrCreateActionSpace(m_session, &actionSpaceInfo, &m_input.handSpace[Side::LEFT]));
actionSpaceInfo.subactionPath = m_input.handSubactionPath[Side::RIGHT];
CHECK_XRCMD(xrCreateActionSpace(m_session, &actionSpaceInfo, &m_input.handSpace[Side::RIGHT]));
XrSessionActionSetsAttachInfo attachInfo{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO};
attachInfo.countActionSets = 1;
attachInfo.actionSets = &m_input.actionSet;
CHECK_XRCMD(xrAttachSessionActionSets(m_session, &attachInfo));
}
void CreateVisualizedSpaces() {
CHECK(m_session != XR_NULL_HANDLE);
std::string visualizedSpaces[] = {"ViewFront", "Local", "Stage", "StageLeft", "StageRight", "StageLeftRotated",
"StageRightRotated"};
for (const auto& visualizedSpace : visualizedSpaces) {
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo = GetXrReferenceSpaceCreateInfo(visualizedSpace);
XrSpace space;
XrResult res = xrCreateReferenceSpace(m_session, &referenceSpaceCreateInfo, &space);
if (XR_SUCCEEDED(res)) {
m_visualizedSpaces.push_back(space);
} else {
Log::Write(Log::Level::Warning,
Fmt("Failed to create reference space %s with error %d", visualizedSpace.c_str(), res));
}
}
}
void InitializeSession() override {
CHECK(m_instance != XR_NULL_HANDLE);
CHECK(m_session == XR_NULL_HANDLE);
{
Log::Write(Log::Level::Verbose, Fmt("Creating session..."));
XrSessionCreateInfo createInfo{XR_TYPE_SESSION_CREATE_INFO};
createInfo.next = m_graphicsPlugin->GetGraphicsBinding();
createInfo.systemId = m_systemId;
CHECK_XRCMD(xrCreateSession(m_instance, &createInfo, &m_session));
}
LogReferenceSpaces();
InitializeActions();
CreateVisualizedSpaces();
{
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo = GetXrReferenceSpaceCreateInfo(m_options->AppSpace);
CHECK_XRCMD(xrCreateReferenceSpace(m_session, &referenceSpaceCreateInfo, &m_appSpace));
}
}
void CreateSwapchains() override {
CHECK(m_session != XR_NULL_HANDLE);
CHECK(m_swapchains.empty());
CHECK(m_configViews.empty());
// Read graphics properties for preferred swapchain length and logging.
XrSystemProperties systemProperties{XR_TYPE_SYSTEM_PROPERTIES};
CHECK_XRCMD(xrGetSystemProperties(m_instance, m_systemId, &systemProperties));
// Log system properties.
Log::Write(Log::Level::Info,
Fmt("System Properties: Name=%s VendorId=%d", systemProperties.systemName, systemProperties.vendorId));
Log::Write(Log::Level::Info, Fmt("System Graphics Properties: MaxWidth=%d MaxHeight=%d MaxLayers=%d",
systemProperties.graphicsProperties.maxSwapchainImageWidth,
systemProperties.graphicsProperties.maxSwapchainImageHeight,
systemProperties.graphicsProperties.maxLayerCount));
Log::Write(Log::Level::Info, Fmt("System Tracking Properties: OrientationTracking=%s PositionTracking=%s",
systemProperties.trackingProperties.orientationTracking == XR_TRUE ? "True" : "False",
systemProperties.trackingProperties.positionTracking == XR_TRUE ? "True" : "False"));
// Note: No other view configurations exist at the time this code was written. If this
// condition is not met, the project will need to be audited to see how support should be
// added.
CHECK_MSG(m_viewConfigType == XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, "Unsupported view configuration type");
// Query and cache view configuration views.
uint32_t viewCount;
CHECK_XRCMD(xrEnumerateViewConfigurationViews(m_instance, m_systemId, m_viewConfigType, 0, &viewCount, nullptr));
m_configViews.resize(viewCount, {XR_TYPE_VIEW_CONFIGURATION_VIEW});
CHECK_XRCMD(xrEnumerateViewConfigurationViews(m_instance, m_systemId, m_viewConfigType, viewCount, &viewCount,
m_configViews.data()));
// Create and cache view buffer for xrLocateViews later.
m_views.resize(viewCount, {XR_TYPE_VIEW});
// Create the swapchain and get the images.
if (viewCount > 0) {
// Select a swapchain format.
uint32_t swapchainFormatCount;
CHECK_XRCMD(xrEnumerateSwapchainFormats(m_session, 0, &swapchainFormatCount, nullptr));
std::vector<int64_t> swapchainFormats(swapchainFormatCount);
CHECK_XRCMD(xrEnumerateSwapchainFormats(m_session, (uint32_t)swapchainFormats.size(), &swapchainFormatCount,
swapchainFormats.data()));
CHECK(swapchainFormatCount == swapchainFormats.size());
m_colorSwapchainFormat = m_graphicsPlugin->SelectColorSwapchainFormat(swapchainFormats);
// Print swapchain formats and the selected one.
{
std::string swapchainFormatsString;
for (int64_t format : swapchainFormats) {
const bool selected = format == m_colorSwapchainFormat;
swapchainFormatsString += " ";
if (selected) {
swapchainFormatsString += "[";
}
swapchainFormatsString += std::to_string(format);
if (selected) {
swapchainFormatsString += "]";
}
}
Log::Write(Log::Level::Verbose, Fmt("Swapchain Formats: %s", swapchainFormatsString.c_str()));
}
// Create a swapchain for each view.
for (uint32_t i = 0; i < viewCount; i++) {
const XrViewConfigurationView& vp = m_configViews[i];
Log::Write(Log::Level::Info,
Fmt("Creating swapchain for view %d with dimensions Width=%d Height=%d SampleCount=%d", i,
vp.recommendedImageRectWidth, vp.recommendedImageRectHeight, vp.recommendedSwapchainSampleCount));
// Create the swapchain.
XrSwapchainCreateInfo swapchainCreateInfo{XR_TYPE_SWAPCHAIN_CREATE_INFO};
swapchainCreateInfo.arraySize = 1;
swapchainCreateInfo.format = m_colorSwapchainFormat;
swapchainCreateInfo.width = vp.recommendedImageRectWidth;
swapchainCreateInfo.height = vp.recommendedImageRectHeight;
swapchainCreateInfo.mipCount = 1;
swapchainCreateInfo.faceCount = 1;
swapchainCreateInfo.sampleCount = m_graphicsPlugin->GetSupportedSwapchainSampleCount(vp);
swapchainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
Swapchain swapchain;
swapchain.width = swapchainCreateInfo.width;
swapchain.height = swapchainCreateInfo.height;
CHECK_XRCMD(xrCreateSwapchain(m_session, &swapchainCreateInfo, &swapchain.handle));
m_swapchains.push_back(swapchain);
uint32_t imageCount;
CHECK_XRCMD(xrEnumerateSwapchainImages(swapchain.handle, 0, &imageCount, nullptr));
// XXX This should really just return XrSwapchainImageBaseHeader*
std::vector<XrSwapchainImageBaseHeader*> swapchainImages =
m_graphicsPlugin->AllocateSwapchainImageStructs(imageCount, swapchainCreateInfo);
CHECK_XRCMD(xrEnumerateSwapchainImages(swapchain.handle, imageCount, &imageCount, swapchainImages[0]));
m_swapchainImages.insert(std::make_pair(swapchain.handle, std::move(swapchainImages)));
}
}
}
// Return event if one is available, otherwise return null.
const XrEventDataBaseHeader* TryReadNextEvent() {
// It is sufficient to clear the just the XrEventDataBuffer header to
// XR_TYPE_EVENT_DATA_BUFFER
XrEventDataBaseHeader* baseHeader = reinterpret_cast<XrEventDataBaseHeader*>(&m_eventDataBuffer);
*baseHeader = {XR_TYPE_EVENT_DATA_BUFFER};
const XrResult xr = xrPollEvent(m_instance, &m_eventDataBuffer);
if (xr == XR_SUCCESS) {
if (baseHeader->type == XR_TYPE_EVENT_DATA_EVENTS_LOST) {
const XrEventDataEventsLost* const eventsLost = reinterpret_cast<const XrEventDataEventsLost*>(baseHeader);
Log::Write(Log::Level::Warning, Fmt("%d events lost", eventsLost));
}
return baseHeader;
}
if (xr == XR_EVENT_UNAVAILABLE) {
return nullptr;
}
THROW_XR(xr, "xrPollEvent");
}
void PollEvents(bool* exitRenderLoop, bool* requestRestart) override {
*exitRenderLoop = *requestRestart = false;
// Process all pending messages.
while (const XrEventDataBaseHeader* event = TryReadNextEvent()) {
switch (event->type) {
case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
const auto& instanceLossPending = *reinterpret_cast<const XrEventDataInstanceLossPending*>(event);
Log::Write(Log::Level::Warning, Fmt("XrEventDataInstanceLossPending by %lld", instanceLossPending.lossTime));
*exitRenderLoop = true;
*requestRestart = true;
return;
}
case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
auto sessionStateChangedEvent = *reinterpret_cast<const XrEventDataSessionStateChanged*>(event);
HandleSessionStateChangedEvent(sessionStateChangedEvent, exitRenderLoop, requestRestart);
break;
}
case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED:
LogActionSourceName(m_input.grabAction, "Grab");
LogActionSourceName(m_input.quitAction, "Quit");
LogActionSourceName(m_input.poseAction, "Pose");
LogActionSourceName(m_input.vibrateAction, "Vibrate");
break;
case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING:
default: {
Log::Write(Log::Level::Verbose, Fmt("Ignoring event type %d", event->type));
break;
}
}
}
}
void HandleSessionStateChangedEvent(const XrEventDataSessionStateChanged& stateChangedEvent, bool* exitRenderLoop,
bool* requestRestart) {
const XrSessionState oldState = m_sessionState;
m_sessionState = stateChangedEvent.state;
Log::Write(Log::Level::Info, Fmt("XrEventDataSessionStateChanged: state %s->%s session=%lld time=%lld", to_string(oldState),
to_string(m_sessionState), stateChangedEvent.session, stateChangedEvent.time));
if ((stateChangedEvent.session != XR_NULL_HANDLE) && (stateChangedEvent.session != m_session)) {
Log::Write(Log::Level::Error, "XrEventDataSessionStateChanged for unknown session");
return;
}
switch (m_sessionState) {
case XR_SESSION_STATE_READY: {
CHECK(m_session != XR_NULL_HANDLE);
XrSessionBeginInfo sessionBeginInfo{XR_TYPE_SESSION_BEGIN_INFO};
sessionBeginInfo.primaryViewConfigurationType = m_viewConfigType;
CHECK_XRCMD(xrBeginSession(m_session, &sessionBeginInfo));
m_sessionRunning = true;
break;
}
case XR_SESSION_STATE_STOPPING: {
CHECK(m_session != XR_NULL_HANDLE);
m_sessionRunning = false;
CHECK_XRCMD(xrEndSession(m_session))
break;
}
case XR_SESSION_STATE_EXITING: {
*exitRenderLoop = true;
// Do not attempt to restart because user closed this session.
*requestRestart = false;
break;
}
case XR_SESSION_STATE_LOSS_PENDING: {
*exitRenderLoop = true;
// Poll for a new instance.
*requestRestart = true;
break;
}
default:
break;
}
}
void LogActionSourceName(XrAction action, const std::string& actionName) const {
XrBoundSourcesForActionEnumerateInfo getInfo = {XR_TYPE_BOUND_SOURCES_FOR_ACTION_ENUMERATE_INFO};
getInfo.action = action;
uint32_t pathCount = 0;
CHECK_XRCMD(xrEnumerateBoundSourcesForAction(m_session, &getInfo, 0, &pathCount, nullptr));
std::vector<XrPath> paths(pathCount);
CHECK_XRCMD(xrEnumerateBoundSourcesForAction(m_session, &getInfo, uint32_t(paths.size()), &pathCount, paths.data()));
std::string sourceName;
for (uint32_t i = 0; i < pathCount; ++i) {
constexpr XrInputSourceLocalizedNameFlags all = XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT |
XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT |
XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT;
XrInputSourceLocalizedNameGetInfo nameInfo = {XR_TYPE_INPUT_SOURCE_LOCALIZED_NAME_GET_INFO};
nameInfo.sourcePath = paths[i];
nameInfo.whichComponents = all;
uint32_t size = 0;
CHECK_XRCMD(xrGetInputSourceLocalizedName(m_session, &nameInfo, 0, &size, nullptr));
if (size < 1) {
continue;
}
std::vector<char> grabSource(size);
CHECK_XRCMD(xrGetInputSourceLocalizedName(m_session, &nameInfo, uint32_t(grabSource.size()), &size, grabSource.data()));
if (!sourceName.empty()) {
sourceName += " and ";
}
sourceName += "'";
sourceName += std::string(grabSource.data(), size - 1);
sourceName += "'";
}
Log::Write(Log::Level::Info,
Fmt("%s action is bound to %s", actionName.c_str(), ((!sourceName.empty()) ? sourceName.c_str() : "nothing")));
}
bool IsSessionRunning() const override { return m_sessionRunning; }
bool IsSessionFocused() const override { return m_sessionState == XR_SESSION_STATE_FOCUSED; }
void PollActions() override {
m_input.handActive = {XR_FALSE, XR_FALSE};
// Sync actions
const XrActiveActionSet activeActionSet{m_input.actionSet, XR_NULL_PATH};
XrActionsSyncInfo syncInfo{XR_TYPE_ACTIONS_SYNC_INFO};
syncInfo.countActiveActionSets = 1;
syncInfo.activeActionSets = &activeActionSet;
CHECK_XRCMD(xrSyncActions(m_session, &syncInfo));
// Get pose and grab action state and start haptic vibrate when hand is 90% squeezed.
for (auto hand : {Side::LEFT, Side::RIGHT}) {
XrActionStateGetInfo getInfo{XR_TYPE_ACTION_STATE_GET_INFO};
getInfo.action = m_input.grabAction;
getInfo.subactionPath = m_input.handSubactionPath[hand];
XrActionStateFloat grabValue{XR_TYPE_ACTION_STATE_FLOAT};
CHECK_XRCMD(xrGetActionStateFloat(m_session, &getInfo, &grabValue));
if (grabValue.isActive == XR_TRUE) {
// Scale the rendered hand by 1.0f (open) to 0.5f (fully squeezed).
m_input.handScale[hand] = 1.0f - 0.5f * grabValue.currentState;
if (grabValue.currentState > 0.9f) {
XrHapticVibration vibration{XR_TYPE_HAPTIC_VIBRATION};
vibration.amplitude = 0.5;
vibration.duration = XR_MIN_HAPTIC_DURATION;
vibration.frequency = XR_FREQUENCY_UNSPECIFIED;
XrHapticActionInfo hapticActionInfo{XR_TYPE_HAPTIC_ACTION_INFO};
hapticActionInfo.action = m_input.vibrateAction;
hapticActionInfo.subactionPath = m_input.handSubactionPath[hand];
CHECK_XRCMD(xrApplyHapticFeedback(m_session, &hapticActionInfo, (XrHapticBaseHeader*)&vibration));
}
}
getInfo.action = m_input.poseAction;
XrActionStatePose poseState{XR_TYPE_ACTION_STATE_POSE};
CHECK_XRCMD(xrGetActionStatePose(m_session, &getInfo, &poseState));
m_input.handActive[hand] = poseState.isActive;
}
// There were no subaction paths specified for the quit action, because we don't care which hand did it.
XrActionStateGetInfo getInfo{XR_TYPE_ACTION_STATE_GET_INFO, nullptr, m_input.quitAction, XR_NULL_PATH};
XrActionStateBoolean quitValue{XR_TYPE_ACTION_STATE_BOOLEAN};
CHECK_XRCMD(xrGetActionStateBoolean(m_session, &getInfo, &quitValue));
if ((quitValue.isActive == XR_TRUE) && (quitValue.changedSinceLastSync == XR_TRUE) && (quitValue.currentState == XR_TRUE)) {
CHECK_XRCMD(xrRequestExitSession(m_session));
}
}
void RenderFrame() override {
CHECK(m_session != XR_NULL_HANDLE);
XrFrameWaitInfo frameWaitInfo{XR_TYPE_FRAME_WAIT_INFO};
XrFrameState frameState{XR_TYPE_FRAME_STATE};
CHECK_XRCMD(xrWaitFrame(m_session, &frameWaitInfo, &frameState));
XrFrameBeginInfo frameBeginInfo{XR_TYPE_FRAME_BEGIN_INFO};
CHECK_XRCMD(xrBeginFrame(m_session, &frameBeginInfo));
std::vector<XrCompositionLayerBaseHeader*> layers;
XrCompositionLayerProjection layer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
std::vector<XrCompositionLayerProjectionView> projectionLayerViews;
if (frameState.shouldRender == XR_TRUE) {
if (RenderLayer(frameState.predictedDisplayTime, projectionLayerViews, layer)) {
layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader*>(&layer));
}
}
XrFrameEndInfo frameEndInfo{XR_TYPE_FRAME_END_INFO};
frameEndInfo.displayTime = frameState.predictedDisplayTime;
frameEndInfo.environmentBlendMode = m_environmentBlendMode;
frameEndInfo.layerCount = (uint32_t)layers.size();
frameEndInfo.layers = layers.data();
CHECK_XRCMD(xrEndFrame(m_session, &frameEndInfo));
}
bool RenderLayer(XrTime predictedDisplayTime, std::vector<XrCompositionLayerProjectionView>& projectionLayerViews,
XrCompositionLayerProjection& layer) {
XrResult res;
XrViewState viewState{XR_TYPE_VIEW_STATE};
uint32_t viewCapacityInput = (uint32_t)m_views.size();
uint32_t viewCountOutput;
XrViewLocateInfo viewLocateInfo{XR_TYPE_VIEW_LOCATE_INFO};
viewLocateInfo.viewConfigurationType = m_viewConfigType;
viewLocateInfo.displayTime = predictedDisplayTime;
viewLocateInfo.space = m_appSpace;
res = xrLocateViews(m_session, &viewLocateInfo, &viewState, viewCapacityInput, &viewCountOutput, m_views.data());
CHECK_XRRESULT(res, "xrLocateViews");
if ((viewState.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0 ||
(viewState.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0) {
return false; // There is no valid tracking poses for the views.
}
CHECK(viewCountOutput == viewCapacityInput);
CHECK(viewCountOutput == m_configViews.size());
CHECK(viewCountOutput == m_swapchains.size());
projectionLayerViews.resize(viewCountOutput);
// For each locatable space that we want to visualize, render a 25cm cube.
std::vector<Cube> cubes;
for (XrSpace visualizedSpace : m_visualizedSpaces) {
XrSpaceLocation spaceLocation{XR_TYPE_SPACE_LOCATION};
res = xrLocateSpace(visualizedSpace, m_appSpace, predictedDisplayTime, &spaceLocation);
CHECK_XRRESULT(res, "xrLocateSpace");
if (XR_UNQUALIFIED_SUCCESS(res)) {
if ((spaceLocation.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) != 0 &&
(spaceLocation.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) != 0) {
cubes.push_back(Cube{spaceLocation.pose, {0.25f, 0.25f, 0.25f}});
}
} else {
Log::Write(Log::Level::Verbose, Fmt("Unable to locate a visualized reference space in app space: %d", res));
}
}
// Render a 10cm cube scaled by grabAction for each hand. Note renderHand will only be
// true when the application has focus.
for (auto hand : {Side::LEFT, Side::RIGHT}) {
XrSpaceLocation spaceLocation{XR_TYPE_SPACE_LOCATION};
res = xrLocateSpace(m_input.handSpace[hand], m_appSpace, predictedDisplayTime, &spaceLocation);
CHECK_XRRESULT(res, "xrLocateSpace");
if (XR_UNQUALIFIED_SUCCESS(res)) {
if ((spaceLocation.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) != 0 &&
(spaceLocation.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) != 0) {
float scale = 0.1f * m_input.handScale[hand];
cubes.push_back(Cube{spaceLocation.pose, {scale, scale, scale}});
}
} else {
// Tracking loss is expected when the hand is not active so only log a message
// if the hand is active.
if (m_input.handActive[hand] == XR_TRUE) {
const char* handName[] = {"left", "right"};
Log::Write(Log::Level::Verbose,
Fmt("Unable to locate %s hand action space in app space: %d", handName[hand], res));
}
}
}
// Render view to the appropriate part of the swapchain image.
for (uint32_t i = 0; i < viewCountOutput; i++) {
// Each view has a separate swapchain which is acquired, rendered to, and released.
const Swapchain viewSwapchain = m_swapchains[i];
XrSwapchainImageAcquireInfo acquireInfo{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
uint32_t swapchainImageIndex;
CHECK_XRCMD(xrAcquireSwapchainImage(viewSwapchain.handle, &acquireInfo, &swapchainImageIndex));
XrSwapchainImageWaitInfo waitInfo{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
waitInfo.timeout = XR_INFINITE_DURATION;
CHECK_XRCMD(xrWaitSwapchainImage(viewSwapchain.handle, &waitInfo));
projectionLayerViews[i] = {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW};
projectionLayerViews[i].pose = m_views[i].pose;
projectionLayerViews[i].fov = m_views[i].fov;
projectionLayerViews[i].subImage.swapchain = viewSwapchain.handle;
projectionLayerViews[i].subImage.imageRect.offset = {0, 0};
projectionLayerViews[i].subImage.imageRect.extent = {viewSwapchain.width, viewSwapchain.height};
const XrSwapchainImageBaseHeader* const swapchainImage = m_swapchainImages[viewSwapchain.handle][swapchainImageIndex];
m_graphicsPlugin->RenderView(projectionLayerViews[i], swapchainImage, m_colorSwapchainFormat, cubes);
XrSwapchainImageReleaseInfo releaseInfo{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
CHECK_XRCMD(xrReleaseSwapchainImage(viewSwapchain.handle, &releaseInfo));
}
layer.space = m_appSpace;
layer.viewCount = (uint32_t)projectionLayerViews.size();
layer.views = projectionLayerViews.data();
return true;
}
private:
const std::shared_ptr<Options> m_options;
std::shared_ptr<IPlatformPlugin> m_platformPlugin;
std::shared_ptr<IGraphicsPlugin> m_graphicsPlugin;
XrInstance m_instance{XR_NULL_HANDLE};
XrSession m_session{XR_NULL_HANDLE};
XrSpace m_appSpace{XR_NULL_HANDLE};
XrFormFactor m_formFactor{XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY};
XrViewConfigurationType m_viewConfigType{XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO};
XrEnvironmentBlendMode m_environmentBlendMode{XR_ENVIRONMENT_BLEND_MODE_OPAQUE};
XrSystemId m_systemId{XR_NULL_SYSTEM_ID};
std::vector<XrViewConfigurationView> m_configViews;
std::vector<Swapchain> m_swapchains;
std::map<XrSwapchain, std::vector<XrSwapchainImageBaseHeader*>> m_swapchainImages;
std::vector<XrView> m_views;
int64_t m_colorSwapchainFormat{-1};
std::vector<XrSpace> m_visualizedSpaces;
// Application's current lifecycle state according to the runtime
XrSessionState m_sessionState{XR_SESSION_STATE_UNKNOWN};
bool m_sessionRunning{false};
XrEventDataBuffer m_eventDataBuffer;
InputState m_input;
};
} // namespace
std::shared_ptr<IOpenXrProgram> CreateOpenXrProgram(const std::shared_ptr<Options>& options,
const std::shared_ptr<IPlatformPlugin>& platformPlugin,
const std::shared_ptr<IGraphicsPlugin>& graphicsPlugin) {
return std::make_shared<OpenXrProgram>(options, platformPlugin, graphicsPlugin);
}
| 53.609943 | 132 | 0.641594 | [
"render",
"object",
"vector",
"transform"
] |
294edf74df658a9147d5c578d4b61fab1c7240ec | 20,483 | cc | C++ | tensorflow/lite/micro/micro_interpreter_test.cc | zhangqiang-hf/tensorflow | 4b660b49225b49d62d023506aad248ba50cfe997 | [
"Apache-2.0"
] | 3 | 2020-08-11T13:13:52.000Z | 2020-11-09T12:59:16.000Z | tensorflow/lite/micro/micro_interpreter_test.cc | zhangqiang-hf/tensorflow | 4b660b49225b49d62d023506aad248ba50cfe997 | [
"Apache-2.0"
] | 2 | 2021-08-25T16:12:15.000Z | 2022-02-10T02:19:16.000Z | tensorflow/lite/micro/micro_interpreter_test.cc | zhangqiang-hf/tensorflow | 4b660b49225b49d62d023506aad248ba50cfe997 | [
"Apache-2.0"
] | 1 | 2021-01-22T12:29:32.000Z | 2021-01-22T12:29:32.000Z | /* Copyright 2018 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/lite/micro/micro_interpreter.h"
#include <cstdint>
#include "tensorflow/lite/core/api/flatbuffer_conversions.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_optional_debug_tools.h"
#include "tensorflow/lite/micro/micro_utils.h"
#include "tensorflow/lite/micro/recording_micro_allocator.h"
#include "tensorflow/lite/micro/test_helpers.h"
#include "tensorflow/lite/micro/testing/micro_test.h"
namespace tflite {
namespace {
class MockProfiler : public tflite::Profiler {
public:
MockProfiler() : event_starts_(0), event_ends_(0) {}
~MockProfiler() override = default;
// AddEvent is unused for Tf Micro.
void AddEvent(const char* tag, EventType event_type, uint64_t start,
uint64_t end, int64_t event_metadata1,
int64_t event_metadata2) override{};
// BeginEvent followed by code followed by EndEvent will profile the code
// enclosed. Multiple concurrent events are unsupported, so the return value
// is always 0. Event_metadata1 and event_metadata2 are unused. The tag
// pointer must be valid until EndEvent is called.
uint32_t BeginEvent(const char* tag, EventType event_type,
int64_t event_metadata1,
int64_t event_metadata2) override {
event_starts_++;
return 0;
}
// Event_handle is ignored since TF Micro does not support concurrent events.
void EndEvent(uint32_t event_handle) override { event_ends_++; }
int event_starts() { return event_starts_; }
int event_ends() { return event_ends_; }
private:
int event_starts_;
int event_ends_;
TF_LITE_REMOVE_VIRTUAL_DELETE
};
} // namespace
} // namespace tflite
TF_LITE_MICRO_TESTS_BEGIN
TF_LITE_MICRO_TEST(TestInterpreter) {
const tflite::Model* model = tflite::testing::GetSimpleMockModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size = 2000;
uint8_t allocator_buffer[allocator_buffer_size];
// Create a new scope so that we can test the destructor.
{
tflite::MicroInterpreter interpreter(model, op_resolver, allocator_buffer,
allocator_buffer_size,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(interpreter.AllocateTensors(), kTfLiteOk);
TF_LITE_MICRO_EXPECT_LE(interpreter.arena_used_bytes(), 928 + 100);
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(1), interpreter.inputs_size());
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(2), interpreter.outputs_size());
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(4), interpreter.tensors_size());
TfLiteTensor* input = interpreter.input(0);
TF_LITE_MICRO_EXPECT_NE(nullptr, input);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, input->type);
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->size);
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->data[0]);
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(4), input->bytes);
TF_LITE_MICRO_EXPECT_NE(nullptr, input->data.i32);
input->data.i32[0] = 21;
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter.Invoke());
TfLiteTensor* output = interpreter.output(0);
TF_LITE_MICRO_EXPECT_NE(nullptr, output);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, output->type);
TF_LITE_MICRO_EXPECT_EQ(1, output->dims->size);
TF_LITE_MICRO_EXPECT_EQ(1, output->dims->data[0]);
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(4), output->bytes);
TF_LITE_MICRO_EXPECT_NE(nullptr, output->data.i32);
TF_LITE_MICRO_EXPECT_EQ(42, output->data.i32[0]);
output = interpreter.output(1);
TF_LITE_MICRO_EXPECT_NE(nullptr, output);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, output->type);
TF_LITE_MICRO_EXPECT_EQ(1, output->dims->size);
TF_LITE_MICRO_EXPECT_EQ(1, output->dims->data[0]);
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(4), output->bytes);
TF_LITE_MICRO_EXPECT_NE(nullptr, output->data.i32);
TF_LITE_MICRO_EXPECT_EQ(42, output->data.i32[0]);
// Just to make sure that this method works.
tflite::PrintInterpreterState(&interpreter);
}
TF_LITE_MICRO_EXPECT_EQ(tflite::testing::MockCustom::freed_, true);
}
TF_LITE_MICRO_TEST(TestMultiTenantInterpreter) {
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t arena_size = 8192;
uint8_t arena[arena_size];
size_t simple_model_head_usage = 0, complex_model_head_usage = 0;
// Get simple_model_head_usage.
{
tflite::RecordingMicroAllocator* allocator =
tflite::RecordingMicroAllocator::Create(arena, arena_size,
micro_test::reporter);
const tflite::Model* model0 = tflite::testing::GetSimpleMockModel();
tflite::MicroInterpreter interpreter0(model0, op_resolver, allocator,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter0.AllocateTensors());
simple_model_head_usage =
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes();
TfLiteTensor* input = interpreter0.input(0);
TfLiteTensor* output = interpreter0.output(0);
input->data.i32[0] = 21;
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter0.Invoke());
TF_LITE_MICRO_EXPECT_EQ(42, output->data.i32[0]);
}
// Shared allocator for various models.
tflite::RecordingMicroAllocator* allocator =
tflite::RecordingMicroAllocator::Create(arena, arena_size,
micro_test::reporter);
// Get complex_model_head_usage. No head space reuse since it's the first
// model allocated in the `allocator`.
const tflite::Model* model1 = tflite::testing::GetComplexMockModel();
tflite::MicroInterpreter interpreter1(model1, op_resolver, allocator,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter1.AllocateTensors());
TfLiteTensor* input1 = interpreter1.input(0);
TfLiteTensor* output1 = interpreter1.output(0);
complex_model_head_usage =
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes();
// Allocate simple model from the same `allocator`. Some head space will
// be reused thanks to multi-tenant TFLM support. Also makes sure that
// the output is correct.
const tflite::Model* model2 = tflite::testing::GetSimpleMockModel();
tflite::MicroInterpreter interpreter2(model2, op_resolver, allocator,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter2.AllocateTensors());
TfLiteTensor* input2 = interpreter2.input(0);
TfLiteTensor* output2 = interpreter2.output(0);
// Verify that 1 + 1 < 2.
size_t multi_tenant_head_usage =
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes();
TF_LITE_MICRO_EXPECT_LE(multi_tenant_head_usage,
complex_model_head_usage + simple_model_head_usage);
// Now we have model1 and model2 sharing the same `allocator`.
// Let's make sure that they can produce correct results.
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, input1->type);
input1->data.i32[0] = 10;
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter1.Invoke());
// Output tensor for the first model.
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, output1->type);
TF_LITE_MICRO_EXPECT_EQ(10, output1->data.i32[0]);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, input2->type);
input2->data.i32[0] = 21;
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter2.Invoke());
// Output for the second model.
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, output2->type);
TF_LITE_MICRO_EXPECT_EQ(42, output2->data.i32[0]);
// Allocate another complex model from the `allocator` will not increase
// head space usage.
const tflite::Model* model3 = tflite::testing::GetComplexMockModel();
tflite::MicroInterpreter interpreter3(model3, op_resolver, allocator,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter3.AllocateTensors());
TfLiteTensor* input3 = interpreter3.input(0);
TfLiteTensor* output3 = interpreter3.output(0);
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, input3->type);
input3->data.i32[0] = 10;
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter3.Invoke());
// Output tensor for the third model.
TF_LITE_MICRO_EXPECT_EQ(kTfLiteInt32, output3->type);
TF_LITE_MICRO_EXPECT_EQ(10, output3->data.i32[0]);
// No increase on the head usage as we're reusing the space.
TF_LITE_MICRO_EXPECT_EQ(
multi_tenant_head_usage,
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes());
}
TF_LITE_MICRO_TEST(TestKernelMemoryPlanning) {
const tflite::Model* model = tflite::testing::GetSimpleStatefulModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size = 4096;
uint8_t allocator_buffer[allocator_buffer_size];
tflite::RecordingMicroAllocator* allocator =
tflite::RecordingMicroAllocator::Create(
allocator_buffer, allocator_buffer_size, micro_test::reporter);
// Make sure kernel memory planning works in multi-tenant context.
for (int i = 0; i < 3; i++) {
tflite::MicroInterpreter interpreter(model, op_resolver, allocator,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(interpreter.AllocateTensors(), kTfLiteOk);
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(1), interpreter.inputs_size());
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(2), interpreter.outputs_size());
TfLiteTensor* input = interpreter.input(0);
TF_LITE_MICRO_EXPECT_EQ(1, input->dims->size);
TF_LITE_MICRO_EXPECT_EQ(3, input->dims->data[0]);
input->data.uint8[0] = 2;
input->data.uint8[1] = 3;
input->data.uint8[2] = 1;
uint8_t expected_median = 2;
{
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter.Invoke());
TfLiteTensor* median = interpreter.output(0);
TF_LITE_MICRO_EXPECT_EQ(expected_median, median->data.uint8[0]);
TfLiteTensor* invoke_count = interpreter.output(1);
TF_LITE_MICRO_EXPECT_EQ(1, invoke_count->data.i32[0]);
}
{
TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, interpreter.Invoke());
TfLiteTensor* median = interpreter.output(0);
TF_LITE_MICRO_EXPECT_EQ(expected_median, median->data.uint8[0]);
TfLiteTensor* invoke_count = interpreter.output(1);
TF_LITE_MICRO_EXPECT_EQ(2, invoke_count->data.i32[0]);
}
}
}
TF_LITE_MICRO_TEST(TestVariableTensorReset) {
const tflite::Model* model = tflite::testing::GetComplexMockModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size =
3072 /* optimal arena size at the time of writting. */ +
16 /* alignment */ + 100 /* some headroom */;
uint8_t allocator_buffer[allocator_buffer_size];
tflite::MicroInterpreter interpreter(model, op_resolver, allocator_buffer,
allocator_buffer_size,
micro_test::reporter);
TF_LITE_MICRO_EXPECT_EQ(interpreter.AllocateTensors(), kTfLiteOk);
TF_LITE_MICRO_EXPECT_LE(interpreter.arena_used_bytes(), 2096 + 100);
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(1), interpreter.inputs_size());
TF_LITE_MICRO_EXPECT_EQ(static_cast<size_t>(1), interpreter.outputs_size());
// Assign hard-code values:
for (size_t i = 0; i < interpreter.tensors_size(); ++i) {
TfLiteTensor* cur_tensor = interpreter.tensor(i);
int buffer_length = tflite::ElementCount(*cur_tensor->dims);
// Assign all buffers to non-zero values. Variable tensors will be assigned
// 2 here and will be verified that they have been reset after the API call.
int buffer_value = cur_tensor->is_variable ? 2 : 1;
switch (cur_tensor->type) {
case kTfLiteInt32: {
int32_t* buffer = tflite::GetTensorData<int32_t>(cur_tensor);
for (int j = 0; j < buffer_length; ++j) {
buffer[j] = static_cast<int32_t>(buffer_value);
}
break;
}
case kTfLiteUInt8: {
uint8_t* buffer = tflite::GetTensorData<uint8_t>(cur_tensor);
for (int j = 0; j < buffer_length; ++j) {
buffer[j] = static_cast<uint8_t>(buffer_value);
}
break;
}
default:
TF_LITE_MICRO_FAIL("Unsupported dtype");
}
}
interpreter.ResetVariableTensors();
// Ensure only variable tensors have been reset to zero:
for (size_t i = 0; i < interpreter.tensors_size(); ++i) {
TfLiteTensor* cur_tensor = interpreter.tensor(i);
int buffer_length = tflite::ElementCount(*cur_tensor->dims);
// Variable tensors should be zero (not the value assigned in the for loop
// above).
int buffer_value = cur_tensor->is_variable ? 0 : 1;
switch (cur_tensor->type) {
case kTfLiteInt32: {
int32_t* buffer = tflite::GetTensorData<int32_t>(cur_tensor);
for (int j = 0; j < buffer_length; ++j) {
TF_LITE_MICRO_EXPECT_EQ(buffer_value, buffer[j]);
}
break;
}
case kTfLiteUInt8: {
uint8_t* buffer = tflite::GetTensorData<uint8_t>(cur_tensor);
for (int j = 0; j < buffer_length; ++j) {
TF_LITE_MICRO_EXPECT_EQ(buffer_value, buffer[j]);
}
break;
}
default:
TF_LITE_MICRO_FAIL("Unsupported dtype");
}
}
}
// The interpreter initialization requires multiple steps and this test case
// ensures that simply creating and destructing an interpreter object is ok.
// b/147830765 has one example of a change that caused trouble for this simple
// case.
TF_LITE_MICRO_TEST(TestIncompleteInitialization) {
const tflite::Model* model = tflite::testing::GetComplexMockModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size = 2048;
uint8_t allocator_buffer[allocator_buffer_size];
tflite::MicroInterpreter interpreter(model, op_resolver, allocator_buffer,
allocator_buffer_size,
micro_test::reporter);
}
// Test that an interpreter with a supplied profiler correctly calls the
// profiler each time an operator is invoked.
TF_LITE_MICRO_TEST(InterpreterWithProfilerShouldProfileOps) {
const tflite::Model* model = tflite::testing::GetComplexMockModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size = 2048;
uint8_t allocator_buffer[allocator_buffer_size];
tflite::MockProfiler profiler;
tflite::MicroInterpreter interpreter(model, op_resolver, allocator_buffer,
allocator_buffer_size,
micro_test::reporter, &profiler);
TF_LITE_MICRO_EXPECT_EQ(profiler.event_starts(), 0);
TF_LITE_MICRO_EXPECT_EQ(profiler.event_ends(), 0);
TF_LITE_MICRO_EXPECT_EQ(interpreter.AllocateTensors(), kTfLiteOk);
TF_LITE_MICRO_EXPECT_EQ(interpreter.Invoke(), kTfLiteOk);
#ifndef NDEBUG
TF_LITE_MICRO_EXPECT_EQ(profiler.event_starts(), 3);
TF_LITE_MICRO_EXPECT_EQ(profiler.event_ends(), 3);
#else // Profile events will not occur on release builds.
TF_LITE_MICRO_EXPECT_EQ(profiler.event_starts(), 0);
TF_LITE_MICRO_EXPECT_EQ(profiler.event_ends(), 0);
#endif
}
TF_LITE_MICRO_TEST(TestIncompleteInitializationAllocationsWithSmallArena) {
const tflite::Model* model = tflite::testing::GetComplexMockModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size = 500;
uint8_t allocator_buffer[allocator_buffer_size];
tflite::RecordingMicroAllocator* allocator =
tflite::RecordingMicroAllocator::Create(
allocator_buffer, allocator_buffer_size, micro_test::reporter);
TF_LITE_MICRO_EXPECT_NE(nullptr, allocator);
tflite::MicroInterpreter interpreter(model, op_resolver, allocator,
micro_test::reporter);
// Interpreter fails because arena is too small:
TF_LITE_MICRO_EXPECT_EQ(interpreter.Invoke(), kTfLiteError);
// Ensure allocations are zero (ignore tail since some internal structs are
// initialized with this space):
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes());
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator
->GetRecordedAllocation(
tflite::RecordedAllocationType::kTfLiteEvalTensorData)
.used_bytes);
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator
->GetRecordedAllocation(
tflite::RecordedAllocationType::kTfLiteTensorVariableBufferData)
.used_bytes);
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator->GetRecordedAllocation(tflite::RecordedAllocationType::kOpData)
.used_bytes);
}
TF_LITE_MICRO_TEST(TestInterpreterDoesNotAllocateUntilInvoke) {
const tflite::Model* model = tflite::testing::GetComplexMockModel();
TF_LITE_MICRO_EXPECT_NE(nullptr, model);
tflite::AllOpsResolver op_resolver = tflite::testing::GetOpResolver();
constexpr size_t allocator_buffer_size = 1024 * 10;
uint8_t allocator_buffer[allocator_buffer_size];
tflite::RecordingMicroAllocator* allocator =
tflite::RecordingMicroAllocator::Create(
allocator_buffer, allocator_buffer_size, micro_test::reporter);
TF_LITE_MICRO_EXPECT_NE(nullptr, allocator);
tflite::MicroInterpreter interpreter(model, op_resolver, allocator,
micro_test::reporter);
// Ensure allocations are zero (ignore tail since some internal structs are
// initialized with this space):
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes());
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator
->GetRecordedAllocation(
tflite::RecordedAllocationType::kTfLiteTensorVariableBufferData)
.used_bytes);
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator
->GetRecordedAllocation(
tflite::RecordedAllocationType::kTfLiteEvalTensorData)
.used_bytes);
TF_LITE_MICRO_EXPECT_EQ(
static_cast<size_t>(0),
allocator->GetRecordedAllocation(tflite::RecordedAllocationType::kOpData)
.used_bytes);
TF_LITE_MICRO_EXPECT_EQ(interpreter.Invoke(), kTfLiteOk);
allocator->PrintAllocations();
// Allocation sizes vary based on platform - check that allocations are now
// non-zero:
TF_LITE_MICRO_EXPECT_GT(
allocator->GetSimpleMemoryAllocator()->GetHeadUsedBytes(),
static_cast<size_t>(0));
TF_LITE_MICRO_EXPECT_GT(
allocator
->GetRecordedAllocation(
tflite::RecordedAllocationType::kTfLiteEvalTensorData)
.used_bytes,
0);
TF_LITE_MICRO_EXPECT_GT(
allocator
->GetRecordedAllocation(
tflite::RecordedAllocationType::kTfLiteTensorVariableBufferData)
.used_bytes,
static_cast<size_t>(0));
// TODO(b/160160549): This check is mostly meaningless right now because the
// operator creation in our mock models is inconsistent. Revisit what
// this check should be once the mock models are properly created.
TF_LITE_MICRO_EXPECT_EQ(
allocator->GetRecordedAllocation(tflite::RecordedAllocationType::kOpData)
.used_bytes,
static_cast<size_t>(0));
}
TF_LITE_MICRO_TESTS_END
| 40.884232 | 80 | 0.713519 | [
"object",
"model"
] |
2955e163c3ee7bd5747ed475b9d98787df05b603 | 2,063 | cpp | C++ | aula03122020/media.cpp | imdcode/imd0030_t02_2020 | 9c08e159752fa3d1169518fcc4a1046c045d7cec | [
"MIT"
] | 3 | 2020-09-23T00:59:43.000Z | 2020-10-06T22:27:00.000Z | aula03122020/media.cpp | imdcode/imd0030_t02_2020 | 9c08e159752fa3d1169518fcc4a1046c045d7cec | [
"MIT"
] | null | null | null | aula03122020/media.cpp | imdcode/imd0030_t02_2020 | 9c08e159752fa3d1169518fcc4a1046c045d7cec | [
"MIT"
] | 4 | 2020-10-05T05:36:25.000Z | 2020-12-08T02:47:32.000Z | #include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using std::stringstream;
using std::ifstream;
using std::ofstream;
using std::string;
using std::cout;
using std::endl;
using std::ios;
using std::vector;
using std::fixed;
using std::setprecision;
using std::ostream;
using std::istream;
class Aluno
{
public:
Aluno(string nome, double nota1, double nota2, double nota3):
nome(nome), nota1(nota1), nota2(nota2), nota3(nota3) {}
Aluno() {}
~Aluno() {}
string getNome() const {
return this->nome;
}
double getNota1() const {
return this->nota1;
}
double getNota2() const {
return this->nota2;
}
double getNota3() const {
return this->nota3;
}
double getMedia() const {
return (this->nota1+this->nota2+this->nota3)/3;
}
string getStatus() const {
double media = this->getMedia();
if (media >= 7.0) {
return "Aprovado";
}
return "Reprovado";
}
friend ostream& operator<< (ostream &o, Aluno const aluno) {
o << aluno.nome << " " << fixed << setprecision(1) << aluno.getMedia() << " " << aluno.getStatus();
return o;
}
friend istream& operator>> (istream &i, Aluno aluno) {
i >> aluno.nome >> aluno.nota1 >> aluno.nota2 >> aluno.nota3;
return i;
}
private:
string nome;
double nota1;
double nota2;
double nota3;
};
int main(int argc, char const *argv[])
{
ifstream arqDados("media.dat");
ofstream arqMediasFinais("medias_finais.dat");
string linha;
string palavra;
while(getline(arqDados,linha)) {
//cout << linha;
// linha = "Antonio Silva;10.0;9.0;8.0"
// quebrando a linha
stringstream s(linha);
vector <string> tokens;
while (getline(s, palavra, ';')) {
tokens.push_back(palavra);
// tokens = ["Antonio Silva" "10.0" "9.0" "8.0"]
}
if (tokens.size() == 4) { // tokens.at(0) == tokens[0]
Aluno lido(tokens.at(0), stod(tokens.at(1)),
stod(tokens.at(2)), stod(tokens.at(3)));
cout << lido << endl;
arqMediasFinais << lido << endl;
}
}
return 0;
} | 23.179775 | 101 | 0.623849 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.