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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0308f42528363987663d097e764d7249ded9cf85 | 960 | cc | C++ | http/http_request.cc | kianooshm/cpp-base | aa9722a73fc2dd73ad9278b560b4feb1565dbb7b | [
"Apache-2.0"
] | 2 | 2016-06-11T22:51:15.000Z | 2017-03-21T00:58:18.000Z | http/http_request.cc | kianooshm/cpp-base | aa9722a73fc2dd73ad9278b560b4feb1565dbb7b | [
"Apache-2.0"
] | null | null | null | http/http_request.cc | kianooshm/cpp-base | aa9722a73fc2dd73ad9278b560b4feb1565dbb7b | [
"Apache-2.0"
] | null | null | null | /*
* -
*
* Copyright 2011 David Parrish <david@dparrish.com>
*
* vim: sw=2 tw=120
*
*/
#include "cpp-base/http/http_request.h"
#include <string>
#include <vector>
using std::string;
namespace cpp_base {
bool HttpRequest::HasParam(const string &key) const {
for (const auto& param : uri.params) {
if (param.key == key)
return true;
}
return false;
}
const string &HttpRequest::GetParam(const string &key) const {
static const string empty_string("");
for (const auto& param : uri.params) {
if (param.key == key)
return param.value;
}
return empty_string;
}
void HttpRequest::WriteFirstline(Socket *sock) {
Cord firstline;
firstline.CopyFrom(StringPrintf("%s %s %s\r\n", method().c_str(),
uri.Assemble().c_str(),
http_version().c_str()));
sock->Write(firstline);
sock->Flush();
}
} // namespace cpp_base
| 21.333333 | 75 | 0.590625 | [
"vector"
] |
030d551601389df8d04e493e84723aa32a2d053f | 5,230 | cpp | C++ | qtmultimedia/src/imports/multimedia/qdeclarativecameraflash.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtmultimedia/src/imports/multimedia/qdeclarativecameraflash.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtmultimedia/src/imports/multimedia/qdeclarativecameraflash.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativecamera_p.h"
#include "qdeclarativecameraflash_p.h"
QT_BEGIN_NAMESPACE
/*!
\qmltype CameraFlash
\instantiates QDeclarativeCameraFlash
\inqmlmodule QtMultimedia
\brief An interface for flash related camera settings.
\ingroup multimedia_qml
\ingroup camera_qml
This type allows you to operate the camera flash
hardware and control the flash mode used. Not all cameras have
flash hardware (and in some cases it is shared with the
\l {Torch}{torch} hardware).
It should not be constructed separately, instead the
\c flash property of a \l Camera should be used.
\qml
Camera {
id: camera
exposure.exposureCompensation: -1.0
flash.mode: Camera.FlashRedEyeReduction
}
\endqml
*/
/*!
Construct a declarative camera flash object using \a parent object.
*/
QDeclarativeCameraFlash::QDeclarativeCameraFlash(QCamera *camera, QObject *parent) :
QObject(parent)
{
m_exposure = camera->exposure();
connect(m_exposure, SIGNAL(flashReady(bool)), this, SIGNAL(flashReady(bool)));
}
QDeclarativeCameraFlash::~QDeclarativeCameraFlash()
{
}
/*!
\qmlproperty bool QtMultimedia::CameraFlash::ready
This property indicates whether the flash is charged.
*/
bool QDeclarativeCameraFlash::isFlashReady() const
{
return m_exposure->isFlashReady();
}
/*!
\qmlproperty enumeration QtMultimedia::CameraFlash::mode
This property holds the camera flash mode.
The mode can be one of the following:
\table
\header \li Value \li Description
\row \li Camera.FlashOff \li Flash is Off.
\row \li Camera.FlashOn \li Flash is On.
\row \li Camera.FlashAuto \li Automatic flash.
\row \li Camera.FlashRedEyeReduction \li Red eye reduction flash.
\row \li Camera.FlashFill \li Use flash to fillin shadows.
\row \li Camera.FlashTorch \li Constant light source. If supported, torch can be
enabled without loading the camera.
\row \li Camera.FlashVideoLight \li Constant light source, useful for video capture.
The light is turned on only while the camera is active.
\row \li Camera.FlashSlowSyncFrontCurtain
\li Use the flash in conjunction with a slow shutter speed.
This mode allows better exposure of distant objects and/or motion blur effect.
\row \li Camera.FlashSlowSyncRearCurtain
\li The similar mode to FlashSlowSyncFrontCurtain but flash is fired at the end of exposure.
\row \li Camera.FlashManual \li Flash power is manually set.
\endtable
*/
QDeclarativeCameraFlash::FlashMode QDeclarativeCameraFlash::flashMode() const
{
return QDeclarativeCameraFlash::FlashMode(int(m_exposure->flashMode()));
}
void QDeclarativeCameraFlash::setFlashMode(QDeclarativeCameraFlash::FlashMode mode)
{
if (flashMode() != mode) {
m_exposure->setFlashMode(QCameraExposure::FlashModes(mode));
emit flashModeChanged(mode);
}
}
/*!
\qmlsignal QtMultimedia::CameraFlash::flashModeChanged(int)
This signal is emitted when the \c flashMode property is changed.
The corresponding handler is \c onFlashModeChanged.
*/
/*!
\qmlsignal QtMultimedia::CameraFlash::flashReady(bool)
This signal is emitted when QCameraExposure indicates that
the flash is ready to use.
The corresponding handler is \c onFlashReadyChanged.
*/
QT_END_NAMESPACE
#include "moc_qdeclarativecameraflash_p.cpp"
| 35.821918 | 124 | 0.68566 | [
"object"
] |
0311cef285e533f69c0a6adf6f622aef961b4217 | 3,132 | ipp | C++ | ddsrouter_yaml/test/unittest/entities/address/test_units/YamlGetEntityAddressTest_get_address_ip.ipp | eProsima/DDS-Router | 59ff7e87acc718fad7ad9e38912100210675cbca | [
"Apache-2.0"
] | 25 | 2021-11-17T11:48:40.000Z | 2022-03-28T05:59:45.000Z | ddsrouter_yaml/test/unittest/entities/address/test_units/YamlGetEntityAddressTest_get_address_ip.ipp | eProsima/DDS-Router | 59ff7e87acc718fad7ad9e38912100210675cbca | [
"Apache-2.0"
] | 128 | 2021-11-16T11:38:59.000Z | 2022-03-25T10:32:12.000Z | ddsrouter_yaml/test/unittest/entities/address/test_units/YamlGetEntityAddressTest_get_address_ip.ipp | eProsima/DDS-Router | 59ff7e87acc718fad7ad9e38912100210675cbca | [
"Apache-2.0"
] | 4 | 2021-12-17T18:14:36.000Z | 2022-03-11T10:10:16.000Z | // Copyright 2022 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 <gtest_aux.hpp>
#include <gtest/gtest.h>
#include <ddsrouter_core/types/address/Address.hpp>
#include <ddsrouter_yaml/YamlReader.hpp>
#include <ddsrouter_yaml/yaml_configuration_tags.hpp>
#include "../../../YamlConfigurationTestUtils.hpp"
using namespace eprosima::ddsrouter;
using namespace eprosima::ddsrouter::yaml;
/**
* Test read an address with IP
*
* POSITIVE CASES:
* - ipv4
* - ipv6
*/
TEST(YamlGetEntityAddressTest, get_address_ip)
{
// ipv4
{
std::vector<core::types::IpType> ips = {
"1.1.1.1",
"127.0.0.1",
"8.8.8.8",
};
for (core::types::IpType ip : ips)
{
Yaml yml_address;
// Add IP
test::add_field_to_yaml(
yml_address,
test::YamlField<core::types::IpType>(ip),
ADDRESS_IP_TAG);
// Add IP version
test::add_field_to_yaml(
yml_address,
test::YamlField<std::string>(ADDRESS_IP_VERSION_V4_TAG),
ADDRESS_IP_VERSION_TAG);
Yaml yml;
yml["address"] = yml_address;
// Get core::types::Address from Yaml
core::types::Address result = YamlReader::get<core::types::Address>(yml, "address", LATEST);
// Check result
ASSERT_EQ(core::types::IpVersion::IPv4, result.ip_version());
ASSERT_EQ(ip, result.ip());
}
}
// ipv6
{
std::vector<core::types::IpType> ips = {
"::1",
"12:34::89",
"2001:0DB8:0000:0000:0000:0000:1428:57ab",
};
for (core::types::IpType ip : ips)
{
Yaml yml_address;
// Add IP
test::add_field_to_yaml(
yml_address,
test::YamlField<core::types::IpType>(ip),
ADDRESS_IP_TAG);
// Add IP version
test::add_field_to_yaml(
yml_address,
test::YamlField<std::string>(ADDRESS_IP_VERSION_V6_TAG),
ADDRESS_IP_VERSION_TAG);
Yaml yml;
yml["address"] = yml_address;
// Get core::types::Address from Yaml
core::types::Address result = YamlReader::get<core::types::Address>(yml, "address", LATEST);
// Check result
ASSERT_EQ(core::types::IpVersion::IPv6, result.ip_version());
ASSERT_EQ(ip, result.ip());
}
}
}
| 29 | 104 | 0.574074 | [
"vector"
] |
031b68e73172c30e7e21fe0792c3b0bc4a06cac5 | 3,818 | cpp | C++ | framework/preprocess/GenerateAnchor.cpp | OAID/TengineFactory | 6276677c9eb2a0b145f6e663c05dbb1e4fb19050 | [
"Apache-2.0"
] | 70 | 2021-03-09T06:36:28.000Z | 2022-03-09T06:35:47.000Z | framework/preprocess/GenerateAnchor.cpp | FeiGeChuanShu/TengineFactory | 89524b8edc3fb6d00f60f12ebfcfdea985639e03 | [
"Apache-2.0"
] | 3 | 2021-03-12T11:08:57.000Z | 2021-04-21T02:18:45.000Z | framework/preprocess/GenerateAnchor.cpp | FeiGeChuanShu/TengineFactory | 89524b8edc3fb6d00f60f12ebfcfdea985639e03 | [
"Apache-2.0"
] | 20 | 2021-03-23T13:04:49.000Z | 2022-03-09T06:35:41.000Z | #include "GenerateAnchor.hpp"
namespace TFactory {
GenerateAnchor::GenerateAnchor(/* args */)
{
}
Anchor GenerateAnchor::GenerateDetectAnchor(Dataset *data)
{
Anchor result_anchor;
std::vector<std::vector<float>> featuremap_size;
std::vector<std::vector<float>> shrinkage_size;
std::vector<int> w_h_list = { data->width(), data->height() };
for (auto size : w_h_list)
{
std::vector<float> fm_item;
for (float stride : data->getStrides())
{
fm_item.push_back(ceil(size / stride));
}
featuremap_size.push_back(fm_item);
shrinkage_size.push_back(data->getStrides());
}
for (std::size_t index = 0; index < num_featuremap; index++)
{
std::vector<float> ws_atfer_scales;
std::vector<float> hs_after_scales;
if (data->getMinSizes().size() > 0)
{
for (std::size_t j = 0; j < data->getMinSizes()[index].size(); j++)
{
ws_atfer_scales.push_back(data->getMinSizes()[index][j] / data->width());
hs_after_scales.push_back(data->getMinSizes()[index][j] / data->height());
}
}
else if (data->getBaseSizes().size() > 0)
{
float sk_x = data->getBaseSizes()[index];
float sk_y = data->getBaseSizes()[index];
float box_area = sk_x * sk_y;
std::vector<float> width_scale;
std::vector<float> height_scale;
for (std::size_t rat = 0; rat < data->getRatios().size(); rat++)
{
width_scale.push_back(round(sqrt(box_area / data->getRatios()[rat])));
height_scale.push_back(round(width_scale[rat] * data->getRatios()[rat]));
}
for (std::size_t x = 0; x < width_scale.size(); x ++)
{
std::vector<float> width_tmp_scale;
std::vector<float> height_tmp_scale;
for (std::size_t y = 0; y < data->getScales()[index].size(); y++)
{
width_tmp_scale.push_back(width_scale[x] * data->getScales()[index][y]);
height_tmp_scale.push_back(height_scale[x] * data->getScales()[index][y]);
}
for (std::size_t z = 0; z < width_tmp_scale.size(); z++)
{
ws_atfer_scales.push_back(width_tmp_scale[z] * 1.0f / data->width());
hs_after_scales.push_back(height_tmp_scale[z] * 1.0f / data->height());
}
}
}
else
{
std::cout << "Error Json Data min_sizes and base_size is worry " << std::endl;
}
float scale_w = data->width() / shrinkage_size[0][index];
float scale_h = data->height() / shrinkage_size[1][index];
for (std::size_t j = 0; j < featuremap_size[1][index]; j++)
{
for (std::size_t i = 0; i < featuremap_size[0][index]; i++)
{
float x_center = (i + 0.5f) / scale_w;
float y_center = (j + 0.5f) / scale_h;
for (std::size_t k = 0; k < ws_atfer_scales.size(); k++)
{
if (data->getClip())
{
result_anchor.anchors.push_back(
{ clip(x_center, 1), clip(y_center, 1), clip(ws_atfer_scales[k], 1), clip(hs_after_scales[k], 1)});
}
else
{
result_anchor.anchors.push_back({ x_center, y_center, ws_atfer_scales[k], hs_after_scales[k] });
}
}
}
}
}
result_anchor.anchor_num = result_anchor.anchors.size();
return result_anchor;
}
GenerateAnchor::~GenerateAnchor()
{
}
} | 38.18 | 127 | 0.514929 | [
"vector"
] |
031e2df5d9590eb829254ed7d4806cd83ef6b60e | 536 | hpp | C++ | Spaceliens/EntityManager.hpp | aclonegeek/Spaceliens | 4dd10bd1f70ebc405499e71be1369927c65dc02a | [
"MIT"
] | null | null | null | Spaceliens/EntityManager.hpp | aclonegeek/Spaceliens | 4dd10bd1f70ebc405499e71be1369927c65dc02a | [
"MIT"
] | 1 | 2016-08-11T21:22:09.000Z | 2020-09-22T01:41:13.000Z | Spaceliens/EntityManager.hpp | aclonegeek/Spaceliens | 4dd10bd1f70ebc405499e71be1369927c65dc02a | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <memory>
#include <vector>
#include "Entity.hpp"
class EntityManager {
public:
EntityManager(sf::RenderWindow& window);
void add(const std::string& name, std::unique_ptr<Entity> entity);
bool exists(const std::string& name);
void remove();
void update(const sf::Time& dt);
void draw();
const Entity& getEntity(const std::string& name) const;
private:
std::map<std::string, std::unique_ptr<Entity>> m_entities;
std::vector<std::string> m_entitiesToRemove;
sf::RenderWindow& m_window;
}; | 23.304348 | 67 | 0.727612 | [
"vector"
] |
031f6cf57e5ac7228849b8ccc5363d77972377b5 | 2,724 | hpp | C++ | engine/core/asset/image.hpp | warnwar/KestrelEngine | 985d1664b71aad62dd51721e0f81d5937d8ae9d4 | [
"MIT"
] | 47 | 2020-09-14T04:11:09.000Z | 2022-01-21T03:15:35.000Z | engine/core/asset/image.hpp | warnwar/KestrelEngine | 985d1664b71aad62dd51721e0f81d5937d8ae9d4 | [
"MIT"
] | 19 | 2020-09-30T19:04:19.000Z | 2021-12-21T03:41:22.000Z | engine/core/asset/image.hpp | warnwar/KestrelEngine | 985d1664b71aad62dd51721e0f81d5937d8ae9d4 | [
"MIT"
] | 3 | 2020-09-30T19:00:09.000Z | 2021-03-08T08:41:02.000Z | // Copyright (c) 2020 Tom Hancocks
//
// 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.
#if !defined(KESTREL_IMAGE_HPP)
#define KESTREL_IMAGE_HPP
#include <string>
#include "core/graphics/common/color.hpp"
#include "core/asset/resource_reference.hpp"
#include "core/graphics/common/spritesheet.hpp"
#include "scripting/state.hpp"
#include "util/hint.hpp"
#include "core/graphics/common/entity.hpp"
namespace asset
{
class image: public scripting::lua::object
{
public:
typedef luabridge::RefCountedPtr<asset::image> lua_reference;
static auto enroll_object_api_in_state(const std::shared_ptr<scripting::lua::state>& lua) -> void;
protected:
int64_t m_id { INT64_MIN };
std::string m_name { "" };
std::shared_ptr<graphics::spritesheet> m_sheet;
auto configure(const int64_t& id, const std::string& name, const math::size& size, std::vector<uint32_t> data) -> void;
public:
image() = default;
image(const math::size& size, const graphics::color& color = graphics::color::white_color());
image(const int64_t& id, const std::string& name, const math::size& size, std::vector<uint32_t> data);
lua_api image(const math::size& size, const graphics::color::lua_reference& color);
lua_api auto size() const -> math::size;
lua_api virtual auto sprite_count() const -> int;
lua_api virtual auto layout_sprites(const math::size& sprite_size) -> void;
auto spritesheet() const -> std::shared_ptr<graphics::spritesheet>;
lua_api virtual auto spawn_entity(const math::vector& position) const -> graphics::entity::lua_reference;
};
}
#endif //KESTREL_IMAGE_HPP
| 40.656716 | 127 | 0.720999 | [
"object",
"vector"
] |
0320bea5f95128a961c83ef789996e53fa9640d5 | 1,047 | cpp | C++ | DirectX3D11/Scenes/TerrainScene.cpp | GyumLee/DirectX3D11 | 6158874aa12e790747e6fd8a53de608071c49574 | [
"Apache-2.0"
] | null | null | null | DirectX3D11/Scenes/TerrainScene.cpp | GyumLee/DirectX3D11 | 6158874aa12e790747e6fd8a53de608071c49574 | [
"Apache-2.0"
] | null | null | null | DirectX3D11/Scenes/TerrainScene.cpp | GyumLee/DirectX3D11 | 6158874aa12e790747e6fd8a53de608071c49574 | [
"Apache-2.0"
] | null | null | null | #include "Framework.h"
#include "TerrainScene.h"
TerrainScene::TerrainScene()
{
terrain = new Terrain();
terrain->GetMaterial()->Load("TextData/Materials/Dirt2.mat");
sphere = new Sphere();
sphere->GetMaterial()->Load("TextData/Materials/FieldStone.mat");
sphere->Load();
destPos = sphere->position;
}
TerrainScene::~TerrainScene()
{
delete terrain;
delete sphere;
}
void TerrainScene::Update()
{
if (MOUSE_CLICK(0) && !ImGui::GetIO().WantCaptureMouse)
{
destPos = terrain->Picking();
}
Vector3 direction = destPos - sphere->position;
if (direction.Length() > 1.0f)
{
sphere->position += direction.Normalize() * 30.0f * DELTA;
}
sphere->position.y = terrain->GetHeight(sphere->position);
terrain->UpdateWorld();
sphere->UpdateWorld();
}
void TerrainScene::PreRender()
{
}
void TerrainScene::Render()
{
terrain->Render();
sphere->Render();
}
void TerrainScene::PostRender()
{
}
void TerrainScene::GUIRender()
{
sphere->GUIRender();
sphere->GetMaterial()->GUIRender();
terrain->GetMaterial()->GUIRender();
}
| 16.619048 | 66 | 0.690544 | [
"render"
] |
03220af39b930d3ca41805246ee3f95ef007b255 | 13,368 | cpp | C++ | secure-indices/tests/AggTreeUnitTest.cpp | ucbrise/waldo | d435d7f447a36b5d000f45ff1b0c73747c1d7aa2 | [
"Apache-2.0"
] | 7 | 2021-12-19T11:31:06.000Z | 2022-03-01T04:19:51.000Z | secure-indices/tests/AggTreeUnitTest.cpp | ucbrise/waldo | d435d7f447a36b5d000f45ff1b0c73747c1d7aa2 | [
"Apache-2.0"
] | null | null | null | secure-indices/tests/AggTreeUnitTest.cpp | ucbrise/waldo | d435d7f447a36b5d000f45ff1b0c73747c1d7aa2 | [
"Apache-2.0"
] | null | null | null | #include "secure-indices/core/players.h"
#include <string>
using namespace std;
//using namespace osuCrypto;
using namespace dorydb;
//#define VERBOSE_PRINT
bool malicious = true;
int mac_factor = malicious ? 2 : 1;
void copy_keys_to_server(clkey* ckey, svkey* s0key, svkey* s1key){
uint64_t dpf_size = ckey->dpf_size;
uint64_t dcf_size = ckey->dcf_size;
// DPF
if(dpf_size > 0){
s0key->dpf_key = (block*) malloc(dpf_size * sizeof(block));
s1key->dpf_key = (block*) malloc(dpf_size * sizeof(block));
s0key->dpf_g = (uint128_t*) malloc(dpf_size * sizeof(uint128_t));
s1key->dpf_g = (uint128_t*) malloc(dpf_size * sizeof(uint128_t));
memcpy(s0key->dpf_key, ckey->dpf_key0, dpf_size * sizeof(block));
memcpy(s1key->dpf_key, ckey->dpf_key1, dpf_size * sizeof(block));
memcpy(s0key->dpf_g, ckey->dpf_g0, dpf_size * sizeof(uint128_t));
memcpy(s1key->dpf_g, ckey->dpf_g1, dpf_size * sizeof(uint128_t));
if(malicious){
s0key->dpf_mac_key = (block*) malloc(dpf_size * sizeof(block));
s1key->dpf_mac_key = (block*) malloc(dpf_size * sizeof(block));
s0key->dpf_mac_g = (uint128_t*) malloc(dpf_size * sizeof(uint128_t));
s1key->dpf_mac_g = (uint128_t*) malloc(dpf_size * sizeof(uint128_t));
memcpy(s0key->dpf_mac_key, ckey->dpf_mac_key0, dpf_size * sizeof(block));
memcpy(s1key->dpf_mac_key, ckey->dpf_mac_key1, dpf_size * sizeof(block));
memcpy(s0key->dpf_mac_g, ckey->dpf_mac_g0, dpf_size * sizeof(uint128_t));
memcpy(s1key->dpf_mac_g, ckey->dpf_mac_g1, dpf_size * sizeof(uint128_t));
}
}
s0key->dpf_size = dpf_size;
s1key->dpf_size = dpf_size;
// DCF
if(dcf_size > 0){
s0key->dcf_key = (block*) malloc(dcf_size * sizeof(block));
s1key->dcf_key = (block*) malloc(dcf_size * sizeof(block));
s0key->dcf_v = (uint128_t*) malloc(dcf_size * sizeof(uint128_t));
s1key->dcf_v = (uint128_t*) malloc(dcf_size * sizeof(uint128_t));
memcpy(s0key->dcf_key, ckey->dcf_key0, dcf_size * sizeof(block));
memcpy(s1key->dcf_key, ckey->dcf_key1, dcf_size * sizeof(block));
memcpy(s0key->dcf_v, ckey->dcf_v0, dcf_size * sizeof(uint128_t));
memcpy(s1key->dcf_v, ckey->dcf_v1, dcf_size * sizeof(uint128_t));
if(malicious){
s0key->dcf_mac_key = (block*) malloc(dcf_size * sizeof(block));
s1key->dcf_mac_key = (block*) malloc(dcf_size * sizeof(block));
s0key->dcf_mac_v = (uint128_t*) malloc(dcf_size * sizeof(uint128_t));
s1key->dcf_mac_v = (uint128_t*) malloc(dcf_size * sizeof(uint128_t));
memcpy(s0key->dcf_mac_key, ckey->dcf_mac_key0, dcf_size * sizeof(block));
memcpy(s1key->dcf_mac_key, ckey->dcf_mac_key1, dcf_size * sizeof(block));
memcpy(s0key->dcf_mac_v, ckey->dcf_mac_v0, dcf_size * sizeof(uint128_t));
memcpy(s1key->dcf_mac_v, ckey->dcf_mac_v1, dcf_size * sizeof(uint128_t));
}
}
s0key->dcf_size = dcf_size;
s1key->dcf_size = dcf_size;
s0key->role = EVAL0;
s1key->role = EVAL1;
s0key->init = true;
s1key->init = true;
}
bool check_agg_tree_correctness(uint128_t left_x, uint128_t right_x, RootNode *tree, uint128_t* res1, uint128_t* res_child1, uint128_t* res2, uint128_t* res_child2, uint64_t depth, uint64_t size, bool use_modulus, uint128_t modulus, bool malicious, uint128_t alpha){
uint64_t ctr = 0;
uint64_t idx = 0;
// Processing truth
#ifdef VERBOSE_PRINT
for(int d=0; d<=depth; d++){
std::cout<<"Truth || depth "<<d<<endl;
for(int i=0; i<(1<<d); i++){
std::cout<<(uint64_t)truth[ctr++]<<" ";
}
std::cout<<endl;
}
ctr = 0;
#endif
uint128_t* truth_res = (uint128_t*)malloc(sizeof(uint128_t)*(depth + 1));
uint128_t* truth_res_child = (uint128_t*)malloc(sizeof(uint128_t)*(depth + 1));
memset(truth_res, 0, sizeof(uint128_t)*(depth + 1));
memset(truth_res_child, 0, sizeof(uint128_t)*(depth + 1));
uint128_t* truth_res_r = (uint128_t*)malloc(sizeof(uint128_t)*(depth + 1));
uint128_t* truth_res_child_r = (uint128_t*)malloc(sizeof(uint128_t)*(depth + 1));
memset(truth_res_r, 0, sizeof(uint128_t)*(depth + 1));
memset(truth_res_child_r, 0, sizeof(uint128_t)*(depth + 1));
queue<Node *>next;
int traversalIdx = 0;
int levelIdx = 0;
int currDepth = 0;
next.push(tree->root);
while (!next.empty()) {
Node *front = next.front();
next.pop();
if (currDepth != front->depth) levelIdx = 0;
int idx = (levelIdx << ((depth-1) - front->depth)) + (1ULL << ((depth-1) - front->depth)) - 1ULL;
uint128_t activated_l = (idx < left_x) ? 1 : 0;
uint128_t activated_r = (idx > right_x) ? 1 : 0;
//cout << "activated? " << activated << endl;
//cout << "Adding " << front->aggVal << " and " << front->getChildAggVals() << endl;
truth_res_child[front->depth] += activated_l * front->getChildAggVals();
truth_res[front->depth] += activated_l * front->aggVal;
truth_res_child_r[front->depth] += activated_r * front->getChildAggVals();
truth_res_r[front->depth] += activated_r * front->aggVal;
if (use_modulus) {
truth_res_child[front->depth] %= modulus;
truth_res[front->depth] %= modulus;
truth_res_child_r[front->depth] %= modulus;
truth_res_r[front->depth] %= modulus;
}
if (front->leftChild) next.push(front->leftChild);
if (front->rightChild) next.push(front->rightChild);
levelIdx++;
currDepth = front->depth;
}
// Processing secure protocol results
uint128_t* res1_r = res1 + mac_factor*(depth+1);
uint128_t* res_child1_r = res_child1 + mac_factor*(depth+1);
uint128_t* res2_r = res2 + mac_factor*(depth+1);
uint128_t* res_child2_r = res_child2 + mac_factor*(depth+1);
for(int d=1; d<depth; d++){
// truth
truth_res[d] -= truth_res_child[d-1];
truth_res[d] %= modulus;
truth_res_r[d] -= truth_res_child_r[d-1];
truth_res_r[d] %= modulus;
// protocol
res1[d] -= res_child1[d-1];
res2[d] -= res_child2[d-1];
res1[d] %= modulus;
res2[d] %= modulus;
res1_r[d] -= res_child1_r[d-1];
res2_r[d] -= res_child2_r[d-1];
res1_r[d] %= modulus;
res2_r[d] %= modulus;
if (malicious) {
res1[d + depth] -= res_child1[(d-1) + depth];
res2[d + depth] -= res_child2[(d-1) + depth];
res1[d + depth] %= modulus;
res2[d + depth] %= modulus;
res1_r[d + depth] -= res_child1_r[(d-1) + depth];
res2_r[d + depth] -= res_child2_r[(d-1) + depth];
res1_r[d + depth] %= modulus;
res2_r[d + depth] %= modulus;
}
}
for(int d=0; d<depth; d++){
cout << "res1 = " << res1[d] << "; res2 = " << res2[d] << endl;
res1[d] += res2[d];
res1[d] %= modulus;
res1_r[d] += res2_r[d];
res1_r[d] %= modulus;
if (malicious) {
res1[d + depth] += res2[d + depth];
res1[d + depth] %= modulus;
res1_r[d + depth] += res2_r[d + depth];
res1_r[d + depth] %= modulus;
}
if(res1[d] != truth_res[d]){
cout<<RED<<"Result mismatch from ground truth at depth "<<d<<RESET<<": "<<truth_res[d]<<" vs "<<res1[d]<<endl;
}
if (malicious) {
if (((res1[d] * alpha) % modulus) != res1[d + depth]) {
cout << RED << "MAC check failed at level " << d << RESET << ": result = " << res1[d] << ", alpha = " << alpha << ", MAC = " << res1[d + depth] << endl;
}
}
if(res1_r[d] != truth_res_r[d]){
cout<<RED<<"Result mismatch from ground truth at depth "<<d<<RESET<<": "<<truth_res_r[d]<<" vs "<<res1_r[d]<<endl;
}
if (malicious) {
if (((res1_r[d] * alpha) % modulus) != res1_r[d + depth]) {
cout << RED << "MAC check failed at level " << d << RESET << ": result = " << res1_r[d] << ", alpha = " << alpha << ", MAC = " << res1_r[d + depth] << endl;
}
}
#ifdef VERBOSE_PRINT
std::cout<<"Protocol || depth "<<d<<endl;
std::cout<<(uint64_t)res1[d]<<endl;
#endif
}
delete[] truth_res;
delete[] truth_res_child;
return true;
}
int main(int argc, char** argv){
cout<<BLUE<<"Running test on AggTree..."<<RESET<<endl;
int depth = 8;
cout<<"Enter depth"<<endl;
cin>>depth;
//TODO: multithreading is creating issues with agg tree
//TODO: DCF server eval function is not thread safe
//TODO: Some state is shared across all threads in that function
//TODO: which leads to error.
cout<<"Depth = "<<depth<<endl;
int ctr = 0;
uint128_t query_left_x = 1000; // incorrect
uint128_t query_right_x = 10;
uint64_t gout_bitsize = 125;
uint128_t one = 1;
uint128_t group_mod = (one<<gout_bitsize);
uint64_t size = (1ULL << (depth)) - 1;
uint64_t leaves = (1ULL << ((depth) - 1));
block seed;
PRNG prng;
int cores = 2;
srand(time(NULL));
seed = toBlock(rand(), rand());
prng.SetSeed(seed);
client* cl = new client();
server* sv1 = new server(SERVER1);
server* sv2 = new server(SERVER2);
cout<<"Generating a random aggregate tree..."<<endl;
cl->agg_tree_oracle = new AggTreeIndexClient(mx, to_string(ctr), depth, malicious);
cout<<"Generating DCF keys for aggregate tree..."<<endl;
cl->agg_tree_oracle->gen_agg_tree_keys(query_left_x, query_right_x, depth, gout_bitsize, true, group_mod);
cout<<"Generated"<<endl;
vector<uint128_t> aggVals;
map<uint64_t, uint128_t> aggValMap;
for (uint64_t i=0; i<leaves; i++){
aggValMap[i] = (uint128_t)1;
aggVals.push_back((uint128_t)1);
}
vector<uint128_t> childAggVals;
for (uint64_t i=0; (2*i + 2) < leaves; i++){
childAggVals.push_back(aggVals[2*i + 1] + aggVals[2*i + 2]);
}
for (uint64_t i=0; i<(1ULL << depth); i++){
childAggVals.push_back(0ULL);
}
cout << "Setting up server state" << endl;
sv1->agg_tree_oracle = new AggTreeIndexServer(to_string(ctr), depth, sum, cores, malicious);
sv2->agg_tree_oracle = new AggTreeIndexServer(to_string(ctr), depth, sum, cores, malicious);
for (uint64_t i = 0; i < leaves; i++) {
uint128_t one = 1;
sv1->agg_tree_oracle->append(i, one);
sv2->agg_tree_oracle->append(i, one);
}
svkey *svk1_l = new svkey();
svkey *svk2_l = new svkey();
svkey *svk1_r = new svkey();
svkey *svk2_r = new svkey();
copy_keys_to_server(cl->agg_tree_oracle->key[2*ctr], svk1_l, svk2_l);
copy_keys_to_server(cl->agg_tree_oracle->key[2*ctr + 1], svk1_r, svk2_r);
cout << "Finished setting up server state" << endl;
sv1->add_keys(AGG_Tree, svk1_l);
sv2->add_keys(AGG_Tree, svk2_l);
sv1->add_keys(AGG_Tree, svk1_r);
sv2->add_keys(AGG_Tree, svk2_r);
/* uint8_t *key0;
uint8_t *key1;
size_t sz;
cl->agg_tree_oracle->serialize_keys(&key0, &key1, &sz);
sv1->agg_tree_oracle->deserialize_key(key0, true);
sv2->agg_tree_oracle->deserialize_key(key1, false);*/
cout<<"Keys transferred to servers"<<endl;
cout<<"Servers running aggregate tree evaluation..."<<endl;
uint64_t tree_size = cl->agg_tree_oracle->size;
int lf_factor = 2;
uint128_t* res1 = (uint128_t*)malloc(lf_factor*mac_factor*sizeof(uint128_t)*(depth + 1));
uint128_t* res_child1 = (uint128_t*)malloc(lf_factor*mac_factor*sizeof(uint128_t)*(depth + 1));
uint128_t* res2 = (uint128_t*)malloc(lf_factor*mac_factor*sizeof(uint128_t)*(depth + 1));
uint128_t* res_child2 = (uint128_t*)malloc(lf_factor*mac_factor*sizeof(uint128_t)*(depth + 1));
memset(res1, 0, lf_factor*mac_factor * sizeof(uint128_t) * (depth + 1));
memset(res_child1, 0, lf_factor*mac_factor * sizeof(uint128_t) * (depth + 1));
memset(res2, 0, lf_factor*mac_factor * sizeof(uint128_t) * (depth + 1));
memset(res_child2, 0, lf_factor*mac_factor * sizeof(uint128_t) * (depth + 1));
INIT_TIMER;
START_TIMER;
cout<<"First server evaluation"<<endl;
sv1->agg_tree_oracle->eval_agg_tree(res1, res_child1, gout_bitsize, true, group_mod, true);
cout<<"Second server evaluation"<<endl;
sv2->agg_tree_oracle->eval_agg_tree(res2, res_child2, gout_bitsize, true, group_mod, true);
STOP_TIMER("Agg tree evaluation time for 1 party");
cout<<"Aggregate tree evalation done"<<endl;
cout<<"Testing correctness..."<<endl;
assert(check_agg_tree_correctness(query_left_x, query_right_x, sv1->agg_tree_oracle->tree, res1, res_child1, res2, res_child2, depth, tree_size, true, group_mod, malicious, cl->agg_tree_oracle->alpha) == true && "Aggregate tree is incorrect!");
cout<<GREEN<<"Aggregate tree correct!"<<RESET<<endl;
cout<<"FSS keysize / server = "<<cl->agg_tree_oracle->key[2*ctr]->get_keysize()<<" bytes"<<endl;
ctr++;
delete cl;
delete sv1;
delete sv2;
delete[] res1;
delete[] res_child1;
delete[] res2;
delete[] res_child2;
return 0;
}
| 42.170347 | 266 | 0.608019 | [
"vector"
] |
03227a4c743827314111fd4e3313e88134f0c8cf | 1,180 | cpp | C++ | lib/libcpp/Mesh/meshvisitorinterface.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | lib/libcpp/Mesh/meshvisitorinterface.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | lib/libcpp/Mesh/meshvisitorinterface.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #include "Mesh/meshvisitorinterface.hpp"
#include <cassert>
using namespace mesh;
/*--------------------------------------------------------------------------*/
MeshVisitorInterface::~MeshVisitorInterface() {}
MeshVisitorInterface::MeshVisitorInterface(): alat::InterfaceBase(){}
MeshVisitorInterface::MeshVisitorInterface( const MeshVisitorInterface& meshvisitorinterface): alat::InterfaceBase(meshvisitorinterface) {}
MeshVisitorInterface& MeshVisitorInterface::operator=( const MeshVisitorInterface& meshvisitorinterface)
{
assert(0);
alat::InterfaceBase::operator=(meshvisitorinterface);
return *this;
}
std::string MeshVisitorInterface::getClassName() const
{
return "MeshVisitorInterface";
}
/*--------------------------------------------------------------------------*/
double MeshVisitorInterface::computeMeasureOfCell(int iK, const mesh::MeshUnitInterface* mesh) const {_notWritten("computeMeasureOfCell"); return 0.;}
void MeshVisitorInterface::computeNormal(MeshUnitInterface::Normal normal, const mesh::MeshUnitInterface* mesh, const alat::Node& xS, const MeshUnitInterface::Side S, int iK0, int ii0, int iK1, int ii1) const{_notWritten("computeNormal");}
| 51.304348 | 239 | 0.700847 | [
"mesh"
] |
0323db8e251b4fec5c4581b8c5391015e90df288 | 697 | cpp | C++ | crack-data-structures-and-algorithms/leetcode/gas_station_q134.cpp | Watch-Later/Eureka | 3065e76d5bf8b37d5de4f9ee75b2714a42dd4c35 | [
"MIT"
] | 20 | 2016-05-16T11:09:04.000Z | 2021-12-08T09:30:33.000Z | crack-data-structures-and-algorithms/leetcode/gas_station_q134.cpp | Watch-Later/Eureka | 3065e76d5bf8b37d5de4f9ee75b2714a42dd4c35 | [
"MIT"
] | 1 | 2018-12-30T09:55:31.000Z | 2018-12-30T14:08:30.000Z | crack-data-structures-and-algorithms/leetcode/gas_station_q134.cpp | Watch-Later/Eureka | 3065e76d5bf8b37d5de4f9ee75b2714a42dd4c35 | [
"MIT"
] | 11 | 2016-05-02T09:17:12.000Z | 2021-12-08T09:30:35.000Z | #include <vector>
using namespace std;
// 核心思路
// 使用两个累计变量跟踪油量和旅途消耗差值
// total: 全局的 gas[i] - cost[i];要能跑完一圈,总量肯定要至少不小于0
// accum: 从起点开始的累计 gas[i] - cost[i];如果对某个station i,导致accum < 0
// 那么说明从[start, i] 之间的加油站都不能作为起点;这个时候只能尝试i+1为起点的case
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int total = 0;
int accum = 0, start = 0;
for (auto i = start; i < gas.size(); ++i) {
auto delta = gas[i] - cost[i];
total += delta;
accum += delta;
if (accum < 0) {
accum = 0;
start = i + 1;
}
}
return total < 0 ? -1 : start;
}
};
| 24.892857 | 65 | 0.516499 | [
"vector"
] |
032812f56fa9cffdf72211acc9bca8b4e88ffe9f | 6,160 | hpp | C++ | lib/stages/frbNetworkProcess.hpp | james-s-willis/kotekan | 155e874bb039702cec72c1785362a017548aa00a | [
"MIT"
] | null | null | null | lib/stages/frbNetworkProcess.hpp | james-s-willis/kotekan | 155e874bb039702cec72c1785362a017548aa00a | [
"MIT"
] | null | null | null | lib/stages/frbNetworkProcess.hpp | james-s-willis/kotekan | 155e874bb039702cec72c1785362a017548aa00a | [
"MIT"
] | null | null | null | /**
* @file frbNetworkProcess.hpp
* @brief Network transmission stage for FRB obs
* - frbNetworkProcess : public kotekan::Stage
*/
#ifndef FRBNETWORKPROCESS_HPP
#define FRBNETWORKPROCESS_HPP
#include "Stage.hpp"
#include "buffer.h"
#include "restServer.hpp"
#include <atomic>
#include <functional>
#include <string>
#include <vector>
/**
* @class frbNetworkProcess
* @brief frbNetworkProcess Network transmission stage for FRB obs
*
*
* This is an Kotekan stage that read packetized data from frbPostProcess and transmits 1024 beams
* to 256 links of frb backend. frbNetworkProcess distributes the out going traffic to four VLANS
* (10.6 10.7 10.8 10.9) on single 1 Gig port. The frb total data rate is ~0.55 gbps. The node IP
* address is derived by parsing the hostname.
*
* @par REST Endpoints
* @endpoint /frb/update_gains/``gpu_id`` Any contact here triggers a re-parse of the gains file.
* @endpoint /frb/update_destination Set the active status of param ``host`` to value of param
* ``active``. Data is sent only to active hosts.
*
* @par Buffers
* @buffer in_buf The kotkean buffer to hold the packets to be transmitted to L1 nodes
* @buffer_format Array of unsigned char.
* @buffer_metadata none
*
*
* @conf udp_frb_packet_size Int (default 4264). packet size including header
* @conf udp_frb_port_number Int (default 1313). udp Port number for frb streams
* @conf number_of_nodes Int (default 256). Number of L0 nodes
* @conf number_of_subnets Int (default 4). Number of subnets or VLANS used for transmission of
* FRB data
* @conf packets_per_stream Int (default 8). Number of packets for each stream within each frame
* @conf L1_node_ips Array of Strings. List of IPs to send to. (?)
* @conf beam_offset Int (default 0). Offset the beam_id going to L1 Process
* @conf time_interval Unsigned long (default 125829120). Time per buffer in ns.
* @conf column_mode bool (default false) Send beams in a single CHIME cylinder.
* @conf ping_interval Uint32 (default 6 min) Time in seconds between sending a ping to
* check destination is live
* @conf quick_ping_interval Uint32 (default 5 sec) Time in seconds for sending pings when a live
* node stops responding
* @conf ping_dead_threshold Uint32 (default 30 sec) Duration in seconds of quick-checking state
* after which a node is declared dead if it still hasn't responded. If 0, disable the checks
* entirely.
*
* @todo Resolve the issue of NTP clock vs Monotonic clock.
*
* @author Arun Naidu, Davor Cubranic
*
*/
struct SrcAddrSocket {
const sockaddr_in addr;
const int socket_fd;
};
/**
* @brief Convenience struct used to hold all relevant information about an FRB L1 destination
*/
struct DestIpSocket {
/// Regular constructor used with data from the config file
DestIpSocket(std::string host, sockaddr_in addr, int s, bool active = true);
/// Move constructor is necessary for inserting into standard containers
DestIpSocket(DestIpSocket&& other);
//@{
/// host address as a string and a `sockaddr` structure
const std::string host;
const sockaddr_in addr;
//@}
/// index of the entry in @p src_sockets used to communicate with the destination
const int sending_socket;
/// flag to indicate if the destination is a "dummy" placeholder
const bool active;
/// flag to indicate if the host has been responding to pings
std::atomic_bool live;
};
class frbNetworkProcess : public kotekan::Stage {
public:
/// Constructor, also initializes internal variables from config.
frbNetworkProcess(kotekan::Config& config, const string& unique_name,
kotekan::bufferContainer& buffer_container);
/// Destructor , cleaning local allocations
virtual ~frbNetworkProcess();
/// Callback to update the beam offset
void update_offset_callback(kotekan::connectionInstance& conn, json& json_request);
/// Callback to change destination active status
void set_destination_active_callback(kotekan::connectionInstance& conn, json& json_request);
/// main thread
void main_thread() override;
private:
/// pointer to Input FRB buffer
struct Buffer* in_buf;
/// frb packet size
int udp_frb_packet_size;
/// port number
int udp_frb_port_number;
/// number of L0 nodes
int number_of_nodes;
/// number of VLANS
int number_of_subnets;
/// number of packets to each L1 nodes
int packets_per_stream;
/// beam offset for 8-node frb system
int beam_offset;
// time per buffer frame in ns
unsigned long time_interval;
// samples per packet
int samples_per_packet;
// Beam kotekan::Configuration Mode
bool column_mode;
/// Interval between checks of a node's liveliness
const std::chrono::seconds _ping_interval;
/// Accelerated interval between checks of a node's liveliness, used when a live node stops
/// responding
const std::chrono::seconds _quick_ping_interval;
/// Duration at which a node is declared dead if it hasn't responded to pings
const std::chrono::seconds _ping_dead_threshold;
/// array of sending socket descriptors
std::vector<SrcAddrSocket> src_sockets;
/// destination addresses and associated sending sockets, indexed by IP @c s_addr
std::map<uint32_t, DestIpSocket> dest_sockets;
/// stream destinations (references to @p dest_sockets, because a single destination can be used
/// for multiple streams)
std::vector<std::reference_wrapper<DestIpSocket>> stream_dest;
/// initialize sockets used to send data to FRB nodes
int initialize_source_sockets();
/// initialize destination addresses and determine the sending socket to use
int initialize_destinations();
/// background thread that periodically pings destination hosts and updates their @c live status
void ping_destinations();
/// used by @p ping_destinations for periodic sleep interruptible by the @p main_thread on
/// Kotekan stop
std::condition_variable ping_cv;
};
#endif
| 34.222222 | 100 | 0.717208 | [
"vector"
] |
03348698269ca9ae660337cee7bdd26a128bd1a2 | 894 | cpp | C++ | examples/reverse/example-reverse-gradient-derivatives-using-eigen.cpp | pariterre/autodiff | 62586497b621fd6296e060162394f849d0dea1fb | [
"MIT"
] | null | null | null | examples/reverse/example-reverse-gradient-derivatives-using-eigen.cpp | pariterre/autodiff | 62586497b621fd6296e060162394f849d0dea1fb | [
"MIT"
] | null | null | null | examples/reverse/example-reverse-gradient-derivatives-using-eigen.cpp | pariterre/autodiff | 62586497b621fd6296e060162394f849d0dea1fb | [
"MIT"
] | 1 | 2019-11-22T08:36:38.000Z | 2019-11-22T08:36:38.000Z | // C++ includes
#include <iostream>
using namespace std;
// Eigen includes
#include <eigen3/Eigen/Core>
using namespace Eigen;
// autodiff include
#include <autodiff/reverse.hpp>
#include <autodiff/reverse/eigen.hpp>
using namespace autodiff;
// The scalar function for which the gradient is needed
var f(const VectorXvar& x)
{
return sqrt(x.cwiseProduct(x).sum()); // sqrt(sum([x(i) * x(i) for i = 1:5]))
}
int main()
{
VectorXvar x(5); // the input vector x with 5 variables
x << 1, 2, 3, 4, 5; // x = [1, 2, 3, 4, 5]
var y = f(x); // the output variable y
VectorXd dydx = gradient(y, x); // evaluate the gradient vector dy/dx
cout << "y = " << y << endl; // print the evaluated output y
cout << "dy/dx = \n" << dydx << endl; // print the evaluated gradient vector dy/dx
}
| 27.9375 | 87 | 0.577181 | [
"vector"
] |
03493f4d44b665638e4bac9fad349ec3bf49ce15 | 1,338 | hpp | C++ | pomegranate/graphics/color.hpp | alexa-griffin/sycamore | 4d2608cbbf56cde1828b6bf0350012c6d8d84896 | [
"Apache-2.0"
] | null | null | null | pomegranate/graphics/color.hpp | alexa-griffin/sycamore | 4d2608cbbf56cde1828b6bf0350012c6d8d84896 | [
"Apache-2.0"
] | null | null | null | pomegranate/graphics/color.hpp | alexa-griffin/sycamore | 4d2608cbbf56cde1828b6bf0350012c6d8d84896 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "base.hpp"
#include "maths/vector.hpp"
#include <cmath>
namespace pom {
/// @addtogroup graphics
/// @{
/// Standard shader parsable color. `r` `g` `b` and `a` are the channels, where 0.0f is the minimum value and 1.0f
/// is the maximum value for a given channel.
struct Color {
/// @private
union {
f32 data[4];
maths::vec4 vec;
struct {
f32 r;
f32 g;
f32 b;
f32 a;
};
};
static const Color TRANSPARENT;
static const Color BLACK;
static const Color WHITE;
/// @brief Creates a color in standard rgb color format, `r`, `g`, and `b` are in the range [0, 255]. `a` will
/// be `1.0f`
static constexpr Color rgb(u8 r, u8 g, u8 b)
{
return { r / 255.f, g / 255.f, b / 255.f, 1.f };
}
/// @brief Creates a color in standard rgba color format, `r`, `g`, and `b` are in the range [0, 255], `a` is in
/// the range [0, 1].
static constexpr Color rgba(u8 r, u8 g, u8 b, f32 a)
{
return { r / 255.f, g / 255.f, b / 255.f, a };
}
};
/// @}
std::ostream& operator<<(std::ostream& os, const Color& color);
} // namespace pom | 27.875 | 120 | 0.493274 | [
"vector"
] |
034a8bdc134868977e06916e55ad3324a18b4cf8 | 4,919 | hpp | C++ | AudioKit/Core/AudioKitCore/Common/ADSREnvelope.hpp | niklassaers/AudioKit | 26c559128751ef95f56366cfabd0ac9edf16cbb8 | [
"MIT"
] | 1 | 2019-11-17T09:02:32.000Z | 2019-11-17T09:02:32.000Z | AudioKit/Core/AudioKitCore/Common/ADSREnvelope.hpp | niklassaers/AudioKit | 26c559128751ef95f56366cfabd0ac9edf16cbb8 | [
"MIT"
] | null | null | null | AudioKit/Core/AudioKitCore/Common/ADSREnvelope.hpp | niklassaers/AudioKit | 26c559128751ef95f56366cfabd0ac9edf16cbb8 | [
"MIT"
] | null | null | null | //
// ADSREnvelope.hpp
// AudioKit Core
//
// Created by Shane Dunne, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
#pragma once
#include "LinearRamper.hpp"
#include "FunctionTable.hpp"
namespace AudioKitCore
{
/// many ADSREnvelopes can share a common set of parameters
struct ADSREnvelopeParameters
{
float sampleRateHz;
float attackSamples, decaySamples, releaseSamples;
float sustainFraction; // [0.0, 1.0]
ADSREnvelopeParameters();
void init(float newSampleRateHz, float attackSeconds, float decaySeconds, float susFraction, float releaseSeconds);
void init(float attackSeconds, float decaySeconds, float susFraction, float releaseSeconds);
void updateSampleRate(float newSampleRateHz);
void setAttackDurationSeconds(float attackSeconds) { attackSamples = attackSeconds * sampleRateHz; }
float getAttackDurationSeconds() { return attackSamples / sampleRateHz; }
void setDecayDurationSeconds(float decaySeconds) { decaySamples = decaySeconds * sampleRateHz; }
float getDecayDurationSeconds() { return decaySamples / sampleRateHz; }
void setReleaseDurationSeconds(float releaseSeconds) { releaseSamples = releaseSeconds * sampleRateHz; }
float getReleaseDurationSeconds() { return releaseSamples / sampleRateHz; }
};
struct ADSREnvelope
{
ADSREnvelopeParameters* pParameters; // many ADSREnvelopes can share a common set of parameters
LinearRamper ramper;
enum EG_Segment
{
kIdle,
kSilence,
kAttack,
kDecay,
kSustain,
kRelease
} segment;
void init();
void start(); // called for note-on
void restart(); // quickly dampen note then start again
void release(); // called for note-off
void reset(); // reset to idle state
bool isIdle() { return segment == kIdle; }
bool isPreStarting() { return segment == kSilence; }
bool isReleasing() { return segment == kRelease; }
inline float getSample()
{
if (segment == kIdle) { return 0.0f; }
if (segment == kSustain) return pParameters->sustainFraction;
if (ramper.isRamping()) return float(ramper.getNextValue());
if (segment == kSilence) // end of quick-damp prior to restart
{
segment = kAttack;
ramper.init(0.0f, 1.01f, pParameters->attackSamples);
return 0.0f;
}
if (segment == kAttack) // end of attack segment
{
segment = kDecay;
ramper.init(1.01f, pParameters->sustainFraction, pParameters->decaySamples);
return 1.01f;
}
if (segment == kDecay) // end of decay segment
{
segment = kSustain;
ramper.init(pParameters->sustainFraction);
return pParameters->sustainFraction;
}
// end of release or silence segment
segment = kIdle;
ramper.init(0.0f);
return 0.0f;
}
};
struct UnityMappingWaveTable: public FunctionTable
{
float tbl[2];
UnityMappingWaveTable()
{
tbl[0] = 0.0f;
tbl[1] = 1.0f;
pWaveTable = tbl;
}
~UnityMappingWaveTable() { deinit(); }
void deinit() { pWaveTable = 0; }
};
struct ShapedEnvelope: public ADSREnvelope
{
// Pointers to shape tables
FunctionTable *pAttTbl, *pDecTbl, *pRelTbl;
// For safety, all 3 pointers are initialized to point to this do-nothing table at first
UnityMappingWaveTable nullTable;
ShapedEnvelope()
{
// This ensures no null-pointer crashes in case user forgets to call initTables()
pAttTbl = pDecTbl = pRelTbl = &nullTable;
}
void initTables(FunctionTable* pAttackTable, FunctionTable* pDecayTable, FunctionTable* pReleaseTable)
{
pAttTbl = pAttackTable; pDecTbl = pDecayTable; pRelTbl = pReleaseTable;
}
inline float getSample()
{
float x = ADSREnvelope::getSample();
switch (segment) {
case kAttack:
return pAttTbl->interp_bounded(x);
case kDecay:
return pDecTbl->interp_bounded(x);
case kRelease:
return pRelTbl->interp_bounded(x);
default:
break;
}
return x;
}
};
}
| 33.013423 | 123 | 0.56048 | [
"shape"
] |
035cbd34391e1708ae12d1049d4cfe6c5cf1bd6b | 8,069 | cc | C++ | test/nosync/lines-reader-test.cc | nokia/libNoSync | af0f0e5b738feac8c42c357c9dbdf3dc7e541a76 | [
"BSD-3-Clause"
] | 2 | 2018-04-28T18:29:08.000Z | 2018-07-03T08:16:34.000Z | test/nosync/lines-reader-test.cc | nokia/libNoSync | af0f0e5b738feac8c42c357c9dbdf3dc7e541a76 | [
"BSD-3-Clause"
] | null | null | null | test/nosync/lines-reader-test.cc | nokia/libNoSync | af0f0e5b738feac8c42c357c9dbdf3dc7e541a76 | [
"BSD-3-Clause"
] | 1 | 2018-04-27T07:53:16.000Z | 2018-04-27T07:53:16.000Z | // This file is part of libnosync library. See LICENSE file for license details.
#include <cstddef>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <nosync/bytes-reader-mock.h>
#include <nosync/const-bytes-reader.h>
#include <nosync/event-loop-utils.h>
#include <nosync/event-loop.h>
#include <nosync/lines-reader.h>
#include <nosync/manual-event-loop.h>
#include <nosync/result.h>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
using namespace std::chrono_literals;
using namespace std::string_literals;
using nosync::bytes_reader_mock;
using nosync::manual_event_loop;
using nosync::make_const_bytes_reader;
using nosync::make_error_result;
using nosync::make_lines_reader;
using nosync::make_ok_result;
using nosync::make_timeout_error_result;
using nosync::request_handler;
using nosync::result;
using std::errc;
using std::function;
using std::make_error_code;
using std::make_shared;
using std::move;
using std::nullptr_t;
using std::shared_ptr;
using std::string;
using std::vector;
using testing::_;
using testing::Ge;
using testing::Invoke;
namespace
{
constexpr auto test_req_timeout = 10ns;
template<typename Req, typename Res>
void repeat_request_handler_calls(
shared_ptr<request_handler<Req, Res>> req_handler,
unsigned repeat_count,
function<void(request_handler<Req, Res> &, function<void(result<string>)>)> req_caller,
function<void(result<string>)> res_handler)
{
if (repeat_count != 0) {
req_caller(
*req_handler,
[req_handler, repeat_count, req_caller, res_handler = move(res_handler)](auto res) mutable {
res_handler(move(res));
repeat_request_handler_calls(req_handler, repeat_count - 1, move(req_caller), move(res_handler));
});
}
}
template<typename T>
function<void(T)> make_vector_pusher(vector<T> &out_vector)
{
return [&out_vector](auto value) {
out_vector.push_back(move(value));
};
}
}
TEST(NosyncLinesReader, ValidLines)
{
auto evloop = manual_event_loop::create();
auto lines_reader = make_lines_reader(
*evloop, make_const_bytes_reader(*evloop, "\n\n123\n456789\n\nabcdefg\n"s), 7);
vector<result<string>> saved_results;
repeat_request_handler_calls<nullptr_t, string>(
lines_reader, 6,
[](auto &lines_reader, auto res_handler) {
lines_reader.handle_request(nullptr, test_req_timeout, move(res_handler));
},
make_vector_pusher(saved_results));
evloop->process_time_passage(1ns);
ASSERT_EQ(saved_results.size(), 6U);
ASSERT_EQ(saved_results[0], make_ok_result(""s));
ASSERT_EQ(saved_results[1], make_ok_result(""s));
ASSERT_EQ(saved_results[2], make_ok_result("123"s));
ASSERT_EQ(saved_results[3], make_ok_result("456789"s));
ASSERT_EQ(saved_results[4], make_ok_result(""s));
ASSERT_EQ(saved_results[5], make_ok_result("abcdefg"s));
}
TEST(NosyncLinesReader, ValidLinesWithBigMax)
{
auto evloop = manual_event_loop::create();
auto lines_reader = make_lines_reader(
*evloop, make_const_bytes_reader(*evloop, "\n\n123\n"s), 1024 * 1024);
vector<result<string>> saved_results;
repeat_request_handler_calls<nullptr_t, string>(
lines_reader, 3,
[](auto &lines_reader, auto res_handler) {
lines_reader.handle_request(nullptr, test_req_timeout, move(res_handler));
},
make_vector_pusher(saved_results));
evloop->process_time_passage(1ns);
ASSERT_EQ(saved_results.size(), 3U);
ASSERT_EQ(saved_results[0], make_ok_result(""s));
ASSERT_EQ(saved_results[1], make_ok_result(""s));
ASSERT_EQ(saved_results[2], make_ok_result("123"s));
}
TEST(NosyncLinesReader, Eof)
{
auto evloop = manual_event_loop::create();
auto lines_reader = make_lines_reader(
*evloop, make_const_bytes_reader(*evloop, "123\n456"s), 3);
vector<result<string>> saved_results;
repeat_request_handler_calls<nullptr_t, string>(
lines_reader, 3,
[](auto &lines_reader, auto res_handler) {
lines_reader.handle_request(nullptr, test_req_timeout, move(res_handler));
},
make_vector_pusher(saved_results));
evloop->process_time_passage(1ns);
ASSERT_EQ(saved_results.size(), 3U);
ASSERT_EQ(saved_results[0], make_ok_result("123"s));
ASSERT_EQ(saved_results[1], make_error_result<string>(make_error_code(errc::no_message_available)));
ASSERT_EQ(saved_results[2], make_error_result<string>(make_error_code(errc::no_message_available)));
}
TEST(NosyncLinesReader, TooLongLine)
{
auto evloop = manual_event_loop::create();
auto lines_reader = make_lines_reader(
*evloop, make_const_bytes_reader(*evloop, "123\n456\nabcdefghi\n"s), 3);
vector<result<string>> saved_results;
repeat_request_handler_calls<nullptr_t, string>(
lines_reader, 3,
[](auto &lines_reader, auto res_handler) {
lines_reader.handle_request(nullptr, test_req_timeout, move(res_handler));
},
make_vector_pusher(saved_results));
evloop->process_time_passage(1ns);
ASSERT_EQ(saved_results.size(), 3U);
ASSERT_EQ(saved_results[0], make_ok_result("123"s));
ASSERT_EQ(saved_results[1], make_ok_result("456"s));
ASSERT_EQ(saved_results[2], make_error_result<string>(make_error_code(errc::file_too_large)));
}
TEST(NosyncLinesReader, ReadError)
{
auto evloop = manual_event_loop::create();
auto mock_reader = make_shared<bytes_reader_mock>();
EXPECT_CALL(*mock_reader, read_some_bytes_impl(_, _, _)).WillRepeatedly(Invoke(
[&evloop](auto, auto, auto result_handler) {
evloop->invoke_at(
evloop->get_etime(),
[result_handler = move(result_handler)]() {
result_handler(make_error_result<string>(make_error_code(errc::io_error)));
});
}));
auto lines_reader = make_lines_reader(*evloop, mock_reader, 10);
vector<result<string>> saved_results;
repeat_request_handler_calls<nullptr_t, string>(
lines_reader, 1,
[](auto &lines_reader, auto res_handler) {
lines_reader.handle_request(nullptr, test_req_timeout, move(res_handler));
},
make_vector_pusher(saved_results));
evloop->process_time_passage(1ns);
ASSERT_EQ(saved_results.size(), 1U);
ASSERT_EQ(saved_results[0], make_error_result<string>(make_error_code(errc::io_error)));
}
TEST(NosyncLinesReader, Timeout)
{
auto evloop = manual_event_loop::create();
auto mock_reader = make_shared<bytes_reader_mock>();
EXPECT_CALL(*mock_reader, read_some_bytes_impl(Ge(1), _, _)).WillRepeatedly(Invoke(
[&evloop](auto, auto timeout, auto result_handler) {
if (timeout >= 10ns) {
evloop->invoke_at(
evloop->get_etime() + 10ns,
[result_handler = move(result_handler)]() {
result_handler(make_ok_result("\n"s));
});
} else {
evloop->invoke_at(
evloop->get_etime() + timeout,
[result_handler = move(result_handler)]() {
result_handler(make_timeout_error_result<string>());
});
}
}));
auto lines_reader = make_lines_reader(*evloop, mock_reader, 10);
vector<result<string>> saved_results;
repeat_request_handler_calls<nullptr_t, string>(
lines_reader, 2,
[&](auto &lines_reader, auto res_handler) {
lines_reader.handle_request(nullptr, saved_results.empty() ? 20ns : 5ns, move(res_handler));
},
make_vector_pusher(saved_results));
evloop->process_time_passage(0ns);
evloop->process_time_passage(10ns);
evloop->process_time_passage(5ns);
ASSERT_EQ(saved_results.size(), 2U);
ASSERT_EQ(saved_results[0], make_ok_result(""s));
ASSERT_EQ(saved_results[1], make_timeout_error_result<string>());
}
| 32.800813 | 113 | 0.684471 | [
"vector"
] |
035e14fbe2f2c74241d0266bc7d9040c51ecd3b1 | 16,500 | hpp | C++ | reef-env/rocclr/device/pal/palgpuopen.hpp | SJTU-IPADS/reef-artifacts | 8750974f2d6655525a2cc317bf2471914fe68dab | [
"Apache-2.0"
] | 7 | 2022-03-23T07:04:20.000Z | 2022-03-30T02:44:42.000Z | reef-env/rocclr/device/pal/palgpuopen.hpp | SJTU-IPADS/reef-artifacts | 8750974f2d6655525a2cc317bf2471914fe68dab | [
"Apache-2.0"
] | null | null | null | reef-env/rocclr/device/pal/palgpuopen.hpp | SJTU-IPADS/reef-artifacts | 8750974f2d6655525a2cc317bf2471914fe68dab | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2016-present 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. */
#pragma once
#include <queue>
#include "device/pal/paldefs.hpp"
#include "platform/commandqueue.hpp"
#include "protocols/rgpServer.h"
#include "device/blit.hpp"
// PAL headers
#include "palUtil.h"
#include "palPlatform.h"
#include "palCmdBuffer.h"
#include "palCmdAllocator.h"
#include "palQueue.h"
#include "palFence.h"
#include "palLinearAllocator.h"
#include "palHashMap.h"
#include "palQueue.h"
#include "palUtil.h"
namespace pal {
class Settings;
class Device;
class VirtualGPU;
class HSAILKernel;
// ================================================================================================
enum class RgpSqqtBarrierReason : uint32_t {
Invalid = 0,
MemDependency = 0xC0000000,
ProfilingControl = 0xC0000001,
SignalSubmit = 0xC0000002,
PostDeviceEnqueue = 0xC0000003,
Unknown = 0xffffffff
};
}
#ifdef PAL_GPUOPEN_OCL
// gpuopen headers
#include "gpuopen.h"
// gpuutil headers
#include "gpuUtil/palGpaSession.h"
// PAL forward declarations
namespace Pal {
class ICmdBuffer;
class IFence;
class IQueueSemaphore;
struct PalPublicSettings;
} // namespace Pal
// GPUOpen forward declarations
namespace DevDriver {
class DevDriverServer;
class IMsgChannel;
struct MessageBuffer;
namespace DriverControlProtocol {
enum struct DeviceClockMode : uint32_t;
class HandlerServer;
} // namespace DriverControlProtocol
namespace SettingsProtocol {
class HandlerServer;
}
} // namespace DevDriver
namespace pal {
// ================================================================================================
// RgpSqttMarkerIdentifier - Identifiers for RGP SQ thread-tracing markers (Table 1)
enum RgpSqttMarkerIdentifier : uint32_t {
RgpSqttMarkerIdentifierEvent = 0x0,
RgpSqttMarkerIdentifierCbStart = 0x1,
RgpSqttMarkerIdentifierCbEnd = 0x2,
RgpSqttMarkerIdentifierBarrierStart = 0x3,
RgpSqttMarkerIdentifierBarrierEnd = 0x4,
RgpSqttMarkerIdentifierUserEvent = 0x5,
RgpSqttMarkerIdentifierGeneralApi = 0x6,
RgpSqttMarkerIdentifierSync = 0x7,
RgpSqttMarkerIdentifierPresent = 0x8,
RgpSqttMarkerIdentifierLayoutTransition = 0x9,
RgpSqttMarkerIdentifierRenderPass = 0xA,
RgpSqttMarkerIdentifierReserved2 = 0xB,
RgpSqttMarkerIdentifierReserved3 = 0xC,
RgpSqttMarkerIdentifierReserved4 = 0xD,
RgpSqttMarkerIdentifierReserved5 = 0xE,
RgpSqttMarkerIdentifierReserved6 = 0xF
};
// ================================================================================================
enum class RgpSqttMarkerEventType : uint32_t {
CmdNDRangeKernel = 0,
CmdScheduler = 1,
CmdCopyBuffer = 2,
CmdCopyImageToBuffer = 3,
CmdCopyBufferToImage = 4,
CmdFillBuffer = 5,
CmdCopyImage = 6,
CmdFillImage = 7,
CmdPipelineBarrier = 8,
InternalUnknown = 26,
Invalid = 0xffffffff
};
// ================================================================================================
// RgpSqttMarkerEvent - "Event (Per-draw/dispatch)" RGP SQ thread-tracing marker.
// These are generated ahead of draws or dispatches for commands that trigger generation of waves
// i.e. draws/dispatches (Table 4).
struct RgpSqttMarkerEvent {
union {
struct {
uint32_t identifier : 4; // Identifier for this marker
uint32_t extDwords : 3; // Number of extra dwords following this marker
uint32_t apiType : 24; // The API type for this command
uint32_t hasThreadDims : 1; // Whether thread dimensions are included
};
uint32_t dword01; // The first dword
};
union {
// Some information about the vertex/instance/draw register indices. These values are not
// always valid because they are not available for one reason or another:
//
// - If vertex offset index or instance offset index are not (together) valid, they are both
// equal to 0
// - If draw index is not valid, it is equal to the vertex offset index
struct {
uint32_t cbID : 20; // Command buffer ID for this marker
uint32_t vertexOffsetRegIdx : 4; // SPI userdata register index for the first vertex offset
uint32_t
instanceOffsetRegIdx : 4; // SPI userdata register index for the first instance offset
uint32_t drawIndexRegIdx : 4; // SPI userdata register index for the draw index (multi draw
// indirect)
};
uint32_t dword02; // The second dword
};
union {
uint32_t cmdID; // Command index within the command buffer
uint32_t dword03; // The third dword
};
};
// ================================================================================================
// RgpSqttMarkerEventWithDims - Per-dispatch specific marker where workgroup dims are included
struct RgpSqttMarkerEventWithDims {
RgpSqttMarkerEvent
event; // Per-draw/dispatch marker. API type should be Dispatch, threadDim = 1
uint32_t threadX; // Work group count in X
uint32_t threadY; // Work group count in Y
uint32_t threadZ; // Work group count in Z
};
// ================================================================================================
// RgpSqttMarkerBarrierStart - "Barrier Start" RGP SQTT instrumentation marker (Table 5)
struct RgpSqttMarkerBarrierStart {
union {
struct {
uint32_t identifier : 4; // Identifier for this marker
uint32_t extDwords : 3; // Number of extra dwords following this marker
uint32_t cbId : 20; // Command buffer ID within queue
uint32_t reserved : 5; // Reserved
};
uint32_t dword01; // The first dword
};
union {
struct {
uint32_t driverReason : 31;
uint32_t internal : 1;
};
uint32_t dword02; // The second dword
};
};
// ================================================================================================
// RgpSqttMarkerBarrierEnd - "Barrier End" RGP SQTT instrumentation marker (Table 6)
struct RgpSqttMarkerBarrierEnd {
union {
struct {
uint32_t identifier : 4; // Identifier for this marker
uint32_t extDwords : 3; // Number of extra dwords following this marker
uint32_t cbId : 20; // Command buffer ID within queue
uint32_t waitOnEopTs : 1; // Issued EOP_TS VGT event followed by a WAIT_REG_MEM for that
// timestamp to be written. Quintessential full pipeline stall.
uint32_t vsPartialFlush : 1; // Stall at ME waiting for all prior VS waves to complete.
uint32_t psPartialFlush : 1; // Stall at ME waiting for all prior PS waves to complete.
uint32_t csPartialFlush : 1; // Stall at ME waiting for all prior CS waves to complete.
uint32_t pfpSyncMe : 1; // Stall PFP until ME is at same point in command stream.
};
uint32_t dword01; // The first dword
};
union {
struct {
uint32_t
syncCpDma : 1; // Issue dummy CP-DMA command to confirm all prior CP-DMAs have completed.
uint32_t invalTcp : 1; // Invalidate the L1 vector caches.
uint32_t invalSqI : 1; // Invalidate the SQ instruction caches
uint32_t invalSqK : 1; // Invalidate the SQ constant caches (i.e. L1 scalar caches)
uint32_t flushTcc : 1; // Flush L2
uint32_t invalTcc : 1; // Invalidate L2
uint32_t flushCb : 1; // Flush CB caches (including DCC, cmask, fmask)
uint32_t invalCb : 1; // Invalidate CB caches (including DCC, cmask, fmask)
uint32_t flushDb : 1; // Flush DB caches (including htile)
uint32_t invalDb : 1; // Invalidate DB caches (including htile)
uint32_t numLayoutTransitions : 16; // Number of layout transitions following this packet
uint32_t reserved : 6; // Reserved for future expansion. Always 0
};
uint32_t dword02; // The second dword
};
};
// RGP SQTT Instrumentation Specification version (API-independent)
constexpr uint32_t RgpSqttInstrumentationSpecVersion = 1;
// RGP SQTT Instrumentation Specification version for Vulkan-specific tables
constexpr uint32_t RgpSqttInstrumentationApiVersion = 0;
// RgpSqttMarkeUserEventDataType - Data types used in RGP SQ thread-tracing markers for an user
// event
enum RgpSqttMarkerUserEventType : uint32_t {
RgpSqttMarkerUserEventTrigger = 0x0,
RgpSqttMarkerUserEventPop = 0x1,
RgpSqttMarkerUserEventPush = 0x2,
RgpSqttMarkerUserEventObjectName = 0x3,
RgpSqttMarkerUserEventReserved1 = 0x4,
RgpSqttMarkerUserEventReserved2 = 0x5,
RgpSqttMarkerUserEventReserved3 = 0x6,
RgpSqttMarkerUserEventReserved4 = 0x7,
};
// RgpSqttMarkerUserEvent - RGP SQ thread-tracing marker for an user event.
union RgpSqttMarkerUserEvent {
struct {
uint32_t identifier : 4; // Identifier for this marker
uint32_t extDwords : 8; // Number of extra dwords following this marker
uint32_t dataType : 8; // The type for this marker
uint32_t reserved : 12; // reserved
};
uint32_t dword01; // The first dword
};
constexpr uint32_t RgpSqttMarkerUserEventWordCount = 1;
// The max lengths of frame marker strings
static constexpr size_t RgpSqttMaxUserEventStringLengthInDwords = 1024;
// RgpSqttMarkerUserEvent - RGP SQ thread-tracing marker for an user event with a string (push and
// trigger data types)
struct RgpSqttMarkerUserEventWithString {
RgpSqttMarkerUserEvent header;
uint32_t stringLength; // Length of the string (in characters)
uint32_t stringData[RgpSqttMaxUserEventStringLengthInDwords]; // String data in UTF-8 format
};
// ================================================================================================
// This class provides functionality to interact with the GPU Open Developer Mode message passing
// service and the rest of the driver.
class RgpCaptureMgr {
public:
~RgpCaptureMgr();
static RgpCaptureMgr* Create(Pal::IPlatform* platform, const Device& device);
void Finalize();
void PreDispatch(VirtualGPU* gpu, const HSAILKernel& kernel, size_t x, size_t y, size_t z);
void PostDispatch(VirtualGPU* gpu);
void WaitForDriverResume();
void PostDeviceCreate();
void PreDeviceDestroy();
void FinishRGPTrace(VirtualGPU* gpu, bool aborted);
bool IsQueueTimingActive() const;
void WriteBarrierStartMarker(const VirtualGPU* gpu,
const Pal::Developer::BarrierData& data) const;
void WriteBarrierEndMarker(const VirtualGPU* gpu, const Pal::Developer::BarrierData& data) const;
bool RegisterTimedQueue(uint32_t queue_id, Pal::IQueue* iQueue, bool* debug_vmid) const;
Pal::Result TimedQueueSubmit(Pal::IQueue* queue, uint64_t cmdId,
const Pal::SubmitInfo& submitInfo) const;
bool Update(Pal::IPlatform* platform);
private:
// Steps that an RGP trace goes through
enum class TraceStatus {
Idle = 0, // No active trace and none requested
Preparing, // A trace has been requested but is not active yet because we are
// currently sampling timing information over some number of lead frames.
Running, // SQTT and queue timing is currently active for all command buffer submits.
WaitingForSqtt,
WaitingForResults // Tracing is no longer active, but all results are not yet ready.
};
// All per-device state to support RGP tracing
struct TraceState {
TraceStatus status_; // Current trace status (idle, running, etc.)
GpuEvent begin_sqtt_event_; // Event that is signaled when a trace-end cmdbuf retires
GpuEvent end_sqtt_event_; // Event that is signaled when a trace-end cmdbuf retires
GpuEvent end_event_; // Event that is signaled when a trace-end cmdbuf retires
VirtualGPU* prepare_queue_; // The queue that triggered the full start of a trace
VirtualGPU* begin_queue_; // The queue that triggered starting SQTT
GpuUtil::GpaSession* gpa_session_; // GPA session helper object for building RGP data
uint32_t gpa_sample_id_; // Sample ID associated with the current trace
bool queue_timing_; // Queue timing is enabled
uint32_t prepared_disp_count_; // Number of dispatches counted while preparing for a trace
uint32_t sqtt_disp_count_; // Number of dispatches counted while SQTT tracing is active
mutable uint32_t current_event_id_; // Current event ID
};
RgpCaptureMgr(Pal::IPlatform* platform, const Device& device);
bool Init(Pal::IPlatform* platform);
Pal::Result PrepareRGPTrace(VirtualGPU* pQueue);
Pal::Result BeginRGPTrace(VirtualGPU* pQueue);
Pal::Result EndRGPHardwareTrace(VirtualGPU* pQueue);
Pal::Result EndRGPTrace(VirtualGPU* pQueue);
void DestroyRGPTracing();
Pal::Result CheckForTraceResults();
static bool GpuSupportsTracing(const Pal::DeviceProperties& props, const Settings& settings);
RgpSqttMarkerEvent BuildEventMarker(const VirtualGPU* gpu, RgpSqttMarkerEventType api_type) const;
void WriteMarker(const VirtualGPU* gpu, const void* data, size_t data_size) const;
void WriteEventWithDimsMarker(const VirtualGPU* gpu, RgpSqttMarkerEventType apiType, uint32_t x,
uint32_t y, uint32_t z) const;
void WriteUserEventMarker(const VirtualGPU* gpu, RgpSqttMarkerUserEventType eventType,
const std::string& name) const;
const Device& device_;
DevDriver::DevDriverServer* dev_driver_server_;
DevDriver::RGPProtocol::RGPServer* rgp_server_;
mutable amd::Monitor trace_mutex_;
TraceState trace_;
RgpSqttMarkerUserEventWithString* user_event_;
uint32_t num_prep_disp_;
uint32_t max_sqtt_disp_; // Maximum number of the dispatches allowed in the trace
uint32_t trace_gpu_mem_limit_;
uint32_t global_disp_count_;
uint32_t se_mask_; // Shader engine mask
uint64_t perf_counter_mem_limit_; // Memory limit for perf counters
uint32_t perf_counter_frequency_; // Counter sample frequency
std::vector<GpuUtil::PerfCounterId> perf_counter_ids_; // List of perf counter ids
union {
struct {
uint32_t trace_enabled_ : 1; // True if tracing is currently enabled (master flag)
uint32_t inst_tracing_enabled_; // Enable instruction-level SQTT tokens
uint32_t perf_counters_enabled_; // True if perf counters are enabled
};
uint32_t value_;
};
PAL_DISALLOW_DEFAULT_CTOR(RgpCaptureMgr);
PAL_DISALLOW_COPY_AND_ASSIGN(RgpCaptureMgr);
};
// ================================================================================================
// Returns true if queue operations are currently being timed by RGP traces.
inline bool RgpCaptureMgr::IsQueueTimingActive() const {
return (trace_.queue_timing_ &&
(trace_.status_ == TraceStatus::Running || trace_.status_ == TraceStatus::Preparing ||
trace_.status_ == TraceStatus::WaitingForSqtt));
}
} // namespace pal
#else // PAL_GPUOPEN_OCL
namespace pal {
class RgpCaptureMgr {
public:
static RgpCaptureMgr* Create(Pal::IPlatform* platform, const Device& device) { return nullptr; }
Pal::Result TimedQueueSubmit(Pal::IQueue* queue, uint64_t cmdId,
const Pal::SubmitInfo& submitInfo) const {}
void PreDispatch(VirtualGPU* gpu, const HSAILKernel& kernel, size_t x, size_t y, size_t z) {}
void PostDispatch(VirtualGPU* gpu) {}
void FinishRGPTrace(VirtualGPU* gpu, bool aborted) {}
bool RegisterTimedQueue(uint32_t queue_id, Pal::IQueue* iQueue, bool* debug_vmid) const { return true; }
};
} // namespace pal
#endif // PAL_GPUOPEN_OCL
| 39.568345 | 106 | 0.688545 | [
"object",
"vector"
] |
03626baa6c977449975da165d9f4cce5e54e372b | 310 | hpp | C++ | src/ai.hpp | jgke/putkijuoksu | bf34eb707a7a5681341940ec203aec9b42f75bc7 | [
"MIT"
] | null | null | null | src/ai.hpp | jgke/putkijuoksu | bf34eb707a7a5681341940ec203aec9b42f75bc7 | [
"MIT"
] | null | null | null | src/ai.hpp | jgke/putkijuoksu | bf34eb707a7a5681341940ec203aec9b42f75bc7 | [
"MIT"
] | null | null | null | #ifndef AI_HPP
#define AI_HPP
#include "coord.hpp"
#include "qtree.hpp"
class Searcher {
public:
Searcher();
void tick(Qtree<char> &level, GLCoord target);
void render();
private:
GLCoord pos;
GLCoord delta;
Coord target;
int movec;
};
#endif
| 15.5 | 54 | 0.577419 | [
"render"
] |
24eca2fced4bed801c5713d4bb4aa36929ee9770 | 38,537 | cpp | C++ | src/maple_me/src/irmap.cpp | harmonyos-mirror/OpenArkCompiler-test | 1755550ea22eb185cbef8cc5864fa273caebf95a | [
"MulanPSL-1.0"
] | 796 | 2019-08-30T16:20:33.000Z | 2021-12-25T14:45:06.000Z | src/maple_me/src/irmap.cpp | harmonyos-mirror/OpenArkCompiler-test | 1755550ea22eb185cbef8cc5864fa273caebf95a | [
"MulanPSL-1.0"
] | 16 | 2019-08-30T18:04:08.000Z | 2021-09-19T05:02:58.000Z | src/maple_me/src/irmap.cpp | harmonyos-mirror/OpenArkCompiler-test | 1755550ea22eb185cbef8cc5864fa273caebf95a | [
"MulanPSL-1.0"
] | 326 | 2019-08-30T16:11:29.000Z | 2021-11-26T12:31:17.000Z | /*
* Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
*/
#include "irmap.h"
#include <queue>
#include "ssa_mir_nodes.h"
#include "ssa.h"
#include "mir_builder.h"
#include "factory.h"
namespace maple {
using MeStmtFactory = FunctionFactory<Opcode, MeStmt*, IRMap*, StmtNode&, AccessSSANodes&>;
// recursively invoke itself in a pre-order traversal of the dominator tree of
// the CFG to build the HSSA representation for the code in each BB
void IRMap::BuildBB(BB &bb, std::vector<bool> &bbIRMapProcessed) {
BBId bbID = bb.GetBBId();
if (bbIRMapProcessed[bbID]) {
return;
}
bbIRMapProcessed[bbID] = true;
curBB = &bb;
SetCurFunction(bb);
// iterate phi list to update the definition by phi
BuildPhiMeNode(bb);
if (!bb.IsEmpty()) {
for (auto &stmt : bb.GetStmtNodes()) {
MeStmt *meStmt = BuildMeStmt(stmt);
bb.AddMeStmtLast(meStmt);
}
}
// travesal bb's dominated tree
ASSERT(bbID < dom.GetDomChildrenSize(), " index out of range in IRMap::BuildBB");
const MapleSet<BBId> &domChildren = dom.GetDomChildren(bbID);
for (auto bbIt = domChildren.begin(); bbIt != domChildren.end(); ++bbIt) {
BBId childBBId = *bbIt;
BuildBB(*GetBB(childBBId), bbIRMapProcessed);
}
}
void IRMap::BuildPhiMeNode(BB &bb) {
for (auto &phi : bb.GetPhiList()) {
const OriginalSt *oSt = ssaTab.GetOriginalStFromID(phi.first);
VersionSt *vSt = phi.second.GetResult();
auto *phiMeNode = NewInPool<MePhiNode>();
phiMeNode->SetDefBB(&bb);
(void)bb.GetMePhiList().insert(std::make_pair(oSt->GetIndex(), phiMeNode));
if (oSt->IsPregOst()) {
RegMeExpr *meDef = GetOrCreateRegFromVerSt(*vSt);
phiMeNode->UpdateLHS(*meDef);
// build phi operands
for (VersionSt *opnd : phi.second.GetPhiOpnds()) {
phiMeNode->GetOpnds().push_back(GetOrCreateRegFromVerSt(*opnd));
}
} else {
VarMeExpr *meDef = GetOrCreateVarFromVerSt(*vSt);
phiMeNode->UpdateLHS(*meDef);
// build phi operands
for (VersionSt *opnd : phi.second.GetPhiOpnds()) {
phiMeNode->GetOpnds().push_back(GetOrCreateVarFromVerSt(*opnd));
}
}
}
}
VarMeExpr *IRMap::CreateVarMeExprVersion(const VarMeExpr &origExpr) {
auto *varMeExpr = New<VarMeExpr>(&irMapAlloc, exprID++, origExpr.GetOStIdx(), vst2MeExprTable.size());
vst2MeExprTable.push_back(varMeExpr);
varMeExpr->InitBase(origExpr.GetOp(), origExpr.GetPrimType(), origExpr.GetNumOpnds());
varMeExpr->SetFieldID(origExpr.GetFieldID());
return varMeExpr;
}
MeExpr *IRMap::CreateAddrofMeExpr(OStIdx ostIdx) {
AddrofMeExpr addrofMeExpr(-1, ostIdx);
addrofMeExpr.SetOp(OP_addrof);
addrofMeExpr.SetPtyp(PTY_ptr);
addrofMeExpr.SetNumOpnds(0);
return HashMeExpr(addrofMeExpr);
}
MeExpr *IRMap::CreateAddrofMeExpr(MeExpr &expr) {
if (expr.GetMeOp() == kMeOpVar) {
auto &varMeExpr = static_cast<VarMeExpr&>(expr);
return CreateAddrofMeExpr(varMeExpr.GetOStIdx());
} else {
ASSERT(expr.GetMeOp() == kMeOpIvar, "expecting IVarMeExpr");
auto &ivarExpr = static_cast<IvarMeExpr&>(expr);
OpMeExpr opMeExpr(kInvalidExprID);
opMeExpr.SetFieldID(ivarExpr.GetFieldID());
opMeExpr.SetTyIdx(ivarExpr.GetTyIdx());
opMeExpr.SetOpnd(0, ivarExpr.GetBase());
opMeExpr.SetOp(OP_iaddrof);
opMeExpr.SetPtyp(PTY_ptr);
opMeExpr.SetNumOpnds(1);
return HashMeExpr(opMeExpr);
}
}
MeExpr *IRMap::CreateAddroffuncMeExpr(PUIdx puIdx) {
AddroffuncMeExpr addroffuncMeExpr(-1, puIdx);
addroffuncMeExpr.SetOp(OP_addroffunc);
addroffuncMeExpr.SetPtyp(PTY_ptr);
addroffuncMeExpr.SetNumOpnds(0);
return HashMeExpr(addroffuncMeExpr);
}
MeExpr *IRMap::CreateIaddrofMeExpr(MeExpr &expr, TyIdx tyIdx, MeExpr &base) {
ASSERT(expr.GetMeOp() == kMeOpIvar, "expecting IVarMeExpr");
auto &ivarExpr = static_cast<IvarMeExpr&>(expr);
OpMeExpr opMeExpr(kInvalidExprID);
opMeExpr.SetFieldID(ivarExpr.GetFieldID());
opMeExpr.SetTyIdx(tyIdx);
opMeExpr.SetOpnd(0, &base);
opMeExpr.SetOp(OP_iaddrof);
opMeExpr.SetPtyp(PTY_ptr);
opMeExpr.SetNumOpnds(1);
return HashMeExpr(opMeExpr);
}
MeExpr *IRMap::CreateIvarMeExpr(MeExpr &expr, TyIdx tyIdx, MeExpr &base) {
ASSERT(expr.GetMeOp() == kMeOpVar, "expecting IVarMeExpr");
auto &varMeExpr = static_cast<VarMeExpr&>(expr);
IvarMeExpr ivarMeExpr(-1);
ivarMeExpr.SetFieldID(varMeExpr.GetFieldID());
ivarMeExpr.SetTyIdx(tyIdx);
ivarMeExpr.SetBase(&base);
ivarMeExpr.InitBase(varMeExpr.GetOp(), varMeExpr.GetPrimType(), 1);
ivarMeExpr.SetOp(OP_iread);
ivarMeExpr.SetMuVal(&varMeExpr);
return HashMeExpr(ivarMeExpr);
}
VarMeExpr *IRMap::CreateNewVarMeExpr(OStIdx ostIdx, PrimType pType, FieldID fieldID) {
VarMeExpr *varMeExpr = meBuilder.BuildVarMeExpr(exprID++, ostIdx, vst2MeExprTable.size(), pType, fieldID);
PushBackVerst2MeExprTable(varMeExpr);
return varMeExpr;
}
VarMeExpr *IRMap::CreateNewVarMeExpr(OriginalSt &oSt, PrimType pType, FieldID fieldID) {
VarMeExpr *varMeExpr = CreateNewVarMeExpr(oSt.GetIndex(), pType, fieldID);
oSt.PushbackVersionIndex(varMeExpr->GetVstIdx());
return varMeExpr;
}
VarMeExpr *IRMap::CreateNewGlobalTmp(GStrIdx strIdx, PrimType pType) {
MIRSymbol *st =
mirModule.GetMIRBuilder()->CreateSymbol((TyIdx)pType, strIdx, kStVar, kScGlobal, nullptr, kScopeGlobal);
st->SetIsTmp(true);
OriginalSt *oSt = ssaTab.CreateSymbolOriginalSt(*st, 0, 0);
auto *varx = New<VarMeExpr>(&irMapAlloc, exprID++, oSt->GetIndex(), oSt->GetZeroVersionIndex());
varx->InitBase(OP_dread, pType, 0);
return varx;
}
VarMeExpr *IRMap::CreateNewLocalRefVarTmp(GStrIdx strIdx, TyIdx tIdx) {
MIRSymbol *st =
mirModule.GetMIRBuilder()->CreateSymbol(tIdx, strIdx, kStVar, kScAuto, mirModule.CurFunction(), kScopeLocal);
st->SetInstrumented();
OriginalSt *oSt = ssaTab.CreateSymbolOriginalSt(*st, mirModule.CurFunction()->GetPuidx(), 0);
oSt->SetZeroVersionIndex(vst2MeExprTable.size());
vst2MeExprTable.push_back(nullptr);
oSt->PushbackVersionIndex(oSt->GetZeroVersionIndex());
auto *newLocalRefVar = New<VarMeExpr>(&irMapAlloc, exprID++, oSt->GetIndex(), vst2MeExprTable.size());
vst2MeExprTable.push_back(newLocalRefVar);
newLocalRefVar->InitBase(OP_dread, PTY_ref, 0);
return newLocalRefVar;
}
RegMeExpr *IRMap::CreateRegMeExprVersion(const OriginalSt &pregOSt) {
auto *regReadExpr =
NewInPool<RegMeExpr>(exprID++, pregOSt.GetPregIdx(), pregOSt.GetPuIdx(), pregOSt.GetIndex(), 0);
regReadExpr->InitBase(OP_regread, pregOSt.GetMIRPreg()->GetPrimType(), 0);
regMeExprTable.push_back(regReadExpr);
return regReadExpr;
}
RegMeExpr *IRMap::CreateRegMeExprVersion(const RegMeExpr &origExpr) {
auto *regReadExpr =
NewInPool<RegMeExpr>(exprID++, origExpr.GetRegIdx(), origExpr.GetPuIdx(), origExpr.GetOstIdx(), 0);
regReadExpr->InitBase(origExpr.GetOp(), origExpr.GetPrimType(), origExpr.GetNumOpnds());
regMeExprTable.push_back(regReadExpr);
return regReadExpr;
}
RegMeExpr *IRMap::CreateRefRegMeExpr(const MIRSymbol &mirSt) {
MIRFunction *mirFunc = mirModule.CurFunction();
MIRType *stType = mirSt.GetType();
PrimType pType = stType->GetPrimType();
ASSERT(pType == PTY_ref, "only PTY_ref needed");
PregIdx regIdx = mirFunc->GetPregTab()->CreateRefPreg(*stType);
ASSERT(regIdx <= 0xffff, "register oversized");
MIRPreg *preg = mirFunc->GetPregTab()->PregFromPregIdx(regIdx);
if (!mirSt.IgnoreRC()) {
preg->SetNeedRC();
}
OriginalSt *oSt = ssaTab.GetOriginalStTable().CreatePregOriginalSt(regIdx, mirFunc->GetPuidx());
auto *regreadexpr = NewInPool<RegMeExpr>(exprID++, regIdx, mirFunc->GetPuidx(), oSt->GetIndex(), 0);
regreadexpr->InitBase(OP_regread, pType, 0);
regMeExprTable.push_back(regreadexpr);
return regreadexpr;
}
RegMeExpr *IRMap::CreateRegMeExpr(PrimType pType) {
MIRFunction *mirFunc = mirModule.CurFunction();
PregIdx regIdx = mirFunc->GetPregTab()->CreatePreg(pType);
ASSERT(regIdx <= 0xffff, "register oversized");
OriginalSt *ost = ssaTab.GetOriginalStTable().CreatePregOriginalSt(regIdx, mirFunc->GetPuidx());
auto *regReadExpr = NewInPool<RegMeExpr>(exprID++, regIdx, mirFunc->GetPuidx(), ost->GetIndex(), 0);
regReadExpr->InitBase(OP_regread, pType, 0);
regMeExprTable.push_back(regReadExpr);
return regReadExpr;
}
RegMeExpr *IRMap::CreateRegRefMeExpr(MIRType &mirType) {
MIRFunction *mirFunc = mirModule.CurFunction();
PregIdx regIdx = mirFunc->GetPregTab()->CreateRefPreg(mirType);
ASSERT(regIdx <= 0xffff, "register oversized");
OriginalSt *ost = ssaTab.GetOriginalStTable().CreatePregOriginalSt(regIdx, mirFunc->GetPuidx());
auto *regReadExpr = NewInPool<RegMeExpr>(exprID++, regIdx, mirFunc->GetPuidx(), ost->GetIndex(), 0);
regReadExpr->InitBase(OP_regread, mirType.GetPrimType(), 0);
regMeExprTable.push_back(regReadExpr);
return regReadExpr;
}
RegMeExpr *IRMap::CreateRegRefMeExpr(const MeExpr &meExpr) {
MIRType *mirType = nullptr;
switch (meExpr.GetMeOp()) {
case kMeOpVar: {
auto &varMeExpr = static_cast<const VarMeExpr&>(meExpr);
const OriginalSt *ost = ssaTab.GetOriginalStFromID(varMeExpr.GetOStIdx());
ASSERT(ost->GetTyIdx() != 0u, "expect ost->tyIdx to be initialized");
mirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ost->GetTyIdx());
break;
}
case kMeOpIvar: {
auto &ivarMeExpr = static_cast<const IvarMeExpr&>(meExpr);
MIRType *ptrMirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ivarMeExpr.GetTyIdx());
ASSERT(ptrMirType->GetKind() == kTypePointer, "must be point type for ivar");
auto *realMirType = static_cast<MIRPtrType*>(ptrMirType);
FieldID fieldID = ivarMeExpr.GetFieldID();
if (fieldID > 0) {
mirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(realMirType->GetPointedTyIdxWithFieldID(fieldID));
} else {
mirType = realMirType->GetPointedType();
}
ASSERT(mirType->GetPrimType() == meExpr.GetPrimType() ||
!(IsAddress(mirType->GetPrimType()) && IsAddress(meExpr.GetPrimType())),
"inconsistent type");
ASSERT(mirType->GetPrimType() == PTY_ref, "CreateRegRefMeExpr: only ref type expected");
break;
}
case kMeOpOp:
if (meExpr.GetOp() == OP_retype) {
auto &opMeExpr = static_cast<const OpMeExpr&>(meExpr);
ASSERT(opMeExpr.GetTyIdx() != 0u, "expect opMeExpr.tyIdx to be initialized");
mirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(opMeExpr.GetTyIdx());
break;
}
// fall thru
[[clang::fallthrough]];
default:
return CreateRegMeExpr(PTY_ptr);
}
return CreateRegRefMeExpr(*mirType);
}
VarMeExpr *IRMap::GetOrCreateVarFromVerSt(const VersionSt &vst) {
size_t vindex = vst.GetIndex();
ASSERT(vindex < vst2MeExprTable.size(), "GetOrCreateVarFromVerSt: index %d is out of range", vindex);
MeExpr *meExpr = vst2MeExprTable.at(vindex);
if (meExpr != nullptr) {
return static_cast<VarMeExpr*>(meExpr);
}
const OriginalSt *ost = vst.GetOrigSt();
ASSERT(ost->IsSymbolOst(), "GetOrCreateVarFromVerSt: wrong ost_type");
auto *varx = New<VarMeExpr>(&irMapAlloc, exprID++, ost->GetIndex(), vindex);
ASSERT(!GlobalTables::GetTypeTable().GetTypeTable().empty(), "container check");
varx->InitBase(OP_dread, GlobalTables::GetTypeTable().GetTypeFromTyIdx(ost->GetTyIdx())->GetPrimType(), 0);
varx->SetFieldID(ost->GetFieldID());
vst2MeExprTable[vindex] = varx;
return varx;
}
VarMeExpr *IRMap::GetOrCreateZeroVersionVarMeExpr(const OriginalSt &ost) {
ASSERT(ost.GetZeroVersionIndex() < vst2MeExprTable.size(),
"GetOrCreateZeroVersionVarMeExpr: version index of osym's kInitVersion out of range");
if (ost.GetZeroVersionIndex() == 0) {
ssaTab.SetZeroVersionIndex(ost.GetIndex(), vst2MeExprTable.size());
vst2MeExprTable.push_back(nullptr);
}
if (vst2MeExprTable[ost.GetZeroVersionIndex()] == nullptr) {
auto *varMeExpr = New<VarMeExpr>(&irMapAlloc, exprID++, ost.GetIndex(), ost.GetZeroVersionIndex());
varMeExpr->SetFieldID(ost.GetFieldID());
varMeExpr->SetOp(OP_dread);
ASSERT(!GlobalTables::GetTypeTable().GetTypeTable().empty(), "container check");
varMeExpr->SetPtyp(GlobalTables::GetTypeTable().GetTypeFromTyIdx(ost.GetTyIdx())->GetPrimType());
varMeExpr->SetNumOpnds(0);
vst2MeExprTable[ost.GetZeroVersionIndex()] = varMeExpr;
return varMeExpr;
}
return static_cast<VarMeExpr*>(vst2MeExprTable[ost.GetZeroVersionIndex()]);
}
RegMeExpr *IRMap::GetOrCreateRegFromVerSt(const VersionSt &vst) {
size_t vindex = vst.GetIndex();
ASSERT(vindex < vst2MeExprTable.size(), " GetOrCreateRegFromVerSt: index %d is out of range", vindex);
MeExpr *meExpr = vst2MeExprTable[vindex];
if (meExpr != nullptr) {
return static_cast<RegMeExpr*>(meExpr);
}
const OriginalSt *ost = vst.GetOrigSt();
ASSERT(ost->IsPregOst(), "GetOrCreateRegFromVerSt: PregOST expected");
auto *regx =
NewInPool<RegMeExpr>(exprID++, ost->GetPregIdx(), mirModule.CurFunction()->GetPuidx(), ost->GetIndex(), vindex);
regx->InitBase(OP_regread, ost->GetMIRPreg()->GetPrimType(), 0);
regMeExprTable.push_back(regx);
vst2MeExprTable[vindex] = regx;
return regx;
}
MeExpr *IRMap::BuildLHSVar(const VersionSt &vst, DassignMeStmt &defMeStmt) {
VarMeExpr *meDef = GetOrCreateVarFromVerSt(vst);
meDef->SetDefStmt(&defMeStmt);
meDef->SetDefBy(kDefByStmt);
vst2MeExprTable.at(vst.GetIndex()) = meDef;
return meDef;
}
MeExpr *IRMap::BuildLHSReg(const VersionSt &vst, RegassignMeStmt &defMeStmt, const RegassignNode ®assign) {
RegMeExpr *meDef = GetOrCreateRegFromVerSt(vst);
meDef->SetPtyp(regassign.GetPrimType());
meDef->SetDefStmt(&defMeStmt);
meDef->SetDefBy(kDefByStmt);
vst2MeExprTable.at(vst.GetIndex()) = meDef;
return meDef;
}
IvarMeExpr *IRMap::BuildLHSIvar(MeExpr &baseAddr, IassignMeStmt &iassignMeStmt, FieldID fieldID) {
auto *meDef = New<IvarMeExpr>(exprID++);
meDef->SetFieldID(fieldID);
meDef->SetTyIdx(iassignMeStmt.GetTyIdx());
meDef->SetBase(&baseAddr);
meDef->SetDefStmt(&iassignMeStmt);
meDef->SetOp(OP_iread);
meDef->SetPtyp(iassignMeStmt.GetRHS()->GetPrimType());
PutToBucket(meDef->GetHashIndex() % mapHashLength, *meDef);
return meDef;
}
IvarMeExpr *IRMap::BuildIvarFromOpMeExpr(OpMeExpr &opMeExpr) {
IvarMeExpr *ivar = New<IvarMeExpr>(exprID++);
ivar->SetFieldID(opMeExpr.GetFieldID());
ivar->SetTyIdx(opMeExpr.GetTyIdx());
ivar->SetBase(opMeExpr.GetOpnd(0));
return ivar;
}
IvarMeExpr *IRMap::BuildLHSIvarFromIassMeStmt(IassignMeStmt &iassignMeStmt) {
return BuildLHSIvar(*iassignMeStmt.GetLHSVal()->GetBase(), iassignMeStmt, iassignMeStmt.GetLHSVal()->GetFieldID());
}
// build Me chilist from MayDefNode list
void IRMap::BuildChiList(MeStmt &meStmt, TypeOfMayDefList &mayDefNodes,
MapleMap<OStIdx, ChiMeNode*> &outList) {
for (auto &mayDefNode : mayDefNodes) {
VersionSt *opndSt = mayDefNode.GetOpnd();
VersionSt *resSt = mayDefNode.GetResult();
auto *chiMeStmt = New<ChiMeNode>(&meStmt);
chiMeStmt->SetRHS(GetOrCreateVarFromVerSt(*opndSt));
VarMeExpr *lhs = GetOrCreateVarFromVerSt(*resSt);
lhs->SetDefBy(kDefByChi);
lhs->SetDefChi(*chiMeStmt);
chiMeStmt->SetLHS(lhs);
outList.insert(std::make_pair(lhs->GetOStIdx(), chiMeStmt));
}
}
void IRMap::BuildMustDefList(MeStmt &meStmt, TypeOfMustDefList &mustDefList,
MapleVector<MustDefMeNode> &mustDefMeList) {
for (auto &mustDefNode : mustDefList) {
VersionSt *vst = mustDefNode.GetResult();
VarMeExpr *lhs = GetOrCreateVarFromVerSt(*vst);
ASSERT(lhs->GetMeOp() == kMeOpReg || lhs->GetMeOp() == kMeOpVar, "unexpected opcode");
mustDefMeList.push_back(MustDefMeNode(lhs, &meStmt));
}
}
MeStmt *IRMap::BuildMeStmtWithNoSSAPart(StmtNode &stmt) {
Opcode op = stmt.GetOpCode();
switch (op) {
case OP_jscatch:
case OP_finally:
case OP_endtry:
case OP_cleanuptry:
case OP_membaracquire:
case OP_membarrelease:
case OP_membarstorestore:
case OP_membarstoreload:
return New<MeStmt>(&stmt);
case OP_goto:
return New<GotoMeStmt>(&stmt);
case OP_comment:
return NewInPool<CommentMeStmt>(&stmt);
case OP_jstry:
return New<JsTryMeStmt>(&stmt);
case OP_catch:
return NewInPool<CatchMeStmt>(&stmt);
case OP_brfalse:
case OP_brtrue: {
auto &condGotoNode = static_cast<CondGotoNode&>(stmt);
auto *condGotoMeStmt = New<CondGotoMeStmt>(&stmt);
condGotoMeStmt->SetOpnd(0, BuildExpr(*condGotoNode.Opnd(0)));
return condGotoMeStmt;
}
case OP_try: {
auto &tryNode = static_cast<TryNode&>(stmt);
auto *tryMeStmt = NewInPool<TryMeStmt>(&stmt);
for (size_t i = 0; i < tryNode.GetOffsetsCount(); ++i) {
tryMeStmt->OffsetsPushBack(tryNode.GetOffset(i));
}
return tryMeStmt;
}
case OP_assertnonnull:
case OP_eval:
case OP_free:
case OP_switch: {
auto &unaryStmt = static_cast<UnaryStmtNode&>(stmt);
auto *unMeStmt =
static_cast<UnaryMeStmt*>((op == OP_switch) ? NewInPool<SwitchMeStmt>(&stmt) : New<UnaryMeStmt>(&stmt));
unMeStmt->SetOpnd(0, BuildExpr(*unaryStmt.Opnd(0)));
return unMeStmt;
}
default:
CHECK_FATAL(false, "NYI");
}
}
MeStmt *IRMap::BuildDassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto *meStmt = NewInPool<DassignMeStmt>(&stmt);
auto &dassiNode = static_cast<DassignNode&>(stmt);
meStmt->SetRHS(BuildExpr(*dassiNode.GetRHS()));
auto *varLHS = static_cast<VarMeExpr*>(BuildLHSVar(*ssaPart.GetSSAVar(), *meStmt));
meStmt->SetLHS(varLHS);
BuildChiList(*meStmt, ssaPart.GetMayDefNodes(), *meStmt->GetChiList());
return meStmt;
}
MeStmt *IRMap::BuildRegassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto *meStmt = New<RegassignMeStmt>(&stmt);
auto ®Node = static_cast<RegassignNode&>(stmt);
meStmt->SetRHS(BuildExpr(*regNode.Opnd(0)));
auto *regLHS = static_cast<RegMeExpr*>(BuildLHSReg(*ssaPart.GetSSAVar(), *meStmt, regNode));
meStmt->SetLHS(regLHS);
return meStmt;
}
MeStmt *IRMap::BuildIassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto &iasNode = static_cast<IassignNode&>(stmt);
auto *meStmt = NewInPool<IassignMeStmt>(&stmt);
meStmt->SetTyIdx(iasNode.GetTyIdx());
meStmt->SetRHS(BuildExpr(*iasNode.GetRHS()));
meStmt->SetLHSVal(BuildLHSIvar(*BuildExpr(*iasNode.Opnd(0)), *meStmt, iasNode.GetFieldID()));
BuildChiList(*meStmt, ssaPart.GetMayDefNodes(), *(meStmt->GetChiList()));
return meStmt;
}
MeStmt *IRMap::BuildMaydassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto *meStmt = NewInPool<MaydassignMeStmt>(&stmt);
auto &dassiNode = static_cast<DassignNode&>(stmt);
meStmt->SetRHS(BuildExpr(*dassiNode.GetRHS()));
meStmt->SetMayDassignSym(ssaPart.GetSSAVar()->GetOrigSt());
meStmt->SetFieldID(dassiNode.GetFieldID());
BuildChiList(*meStmt, ssaPart.GetMayDefNodes(), *(meStmt->GetChiList()));
return meStmt;
}
MeStmt *IRMap::BuildCallMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto *callMeStmt = NewInPool<CallMeStmt>(&stmt);
auto &intrinNode = static_cast<CallNode&>(stmt);
callMeStmt->SetPUIdx(intrinNode.GetPUIdx());
for (size_t i = 0; i < intrinNode.NumOpnds(); ++i) {
callMeStmt->PushBackOpnd(BuildExpr(*intrinNode.Opnd(i)));
}
BuildMuList(ssaPart.GetMayUseNodes(), *(callMeStmt->GetMuList()));
if (kOpcodeInfo.IsCallAssigned(stmt.GetOpCode())) {
BuildMustDefList(*callMeStmt, ssaPart.GetMustDefNodes(), *(callMeStmt->GetMustDefList()));
}
BuildChiList(*callMeStmt, ssaPart.GetMayDefNodes(), *(callMeStmt->GetChiList()));
return callMeStmt;
}
MeStmt *IRMap::BuildNaryMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
Opcode op = stmt.GetOpCode();
NaryMeStmt *naryMeStmt = (op == OP_icall || op == OP_icallassigned)
? static_cast<NaryMeStmt*>(NewInPool<IcallMeStmt>(&stmt))
: static_cast<NaryMeStmt*>(NewInPool<IntrinsiccallMeStmt>(&stmt));
auto &naryStmtNode = static_cast<NaryStmtNode&>(stmt);
for (size_t i = 0; i < naryStmtNode.NumOpnds(); ++i) {
naryMeStmt->PushBackOpnd(BuildExpr(*naryStmtNode.Opnd(i)));
}
BuildMuList(ssaPart.GetMayUseNodes(), *(naryMeStmt->GetMuList()));
if (kOpcodeInfo.IsCallAssigned(op)) {
BuildMustDefList(*naryMeStmt, ssaPart.GetMustDefNodes(), *(naryMeStmt->GetMustDefList()));
}
BuildChiList(*naryMeStmt, ssaPart.GetMayDefNodes(), *(naryMeStmt->GetChiList()));
return naryMeStmt;
}
MeStmt *IRMap::BuildRetMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto &retStmt = static_cast<NaryStmtNode&>(stmt);
auto *meStmt = NewInPool<RetMeStmt>(&stmt);
for (size_t i = 0; i < retStmt.NumOpnds(); ++i) {
meStmt->PushBackOpnd(BuildExpr(*retStmt.Opnd(i)));
}
BuildMuList(ssaPart.GetMayUseNodes(), *(meStmt->GetMuList()));
return meStmt;
}
MeStmt *IRMap::BuildWithMuMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto *retSub = NewInPool<WithMuMeStmt>(&stmt);
BuildMuList(ssaPart.GetMayUseNodes(), *(retSub->GetMuList()));
return retSub;
}
MeStmt *IRMap::BuildGosubMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto *goSub = NewInPool<GosubMeStmt>(&stmt);
BuildMuList(ssaPart.GetMayUseNodes(), *(goSub->GetMuList()));
return goSub;
}
MeStmt *IRMap::BuildThrowMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto &unaryNode = static_cast<UnaryStmtNode&>(stmt);
auto *tmeStmt = NewInPool<ThrowMeStmt>(&stmt);
tmeStmt->SetMeStmtOpndValue(BuildExpr(*unaryNode.Opnd(0)));
BuildMuList(ssaPart.GetMayUseNodes(), *(tmeStmt->GetMuList()));
return tmeStmt;
}
MeStmt *IRMap::BuildSyncMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) {
auto &naryNode = static_cast<NaryStmtNode&>(stmt);
auto *naryStmt = NewInPool<SyncMeStmt>(&stmt);
for (size_t i = 0; i < naryNode.NumOpnds(); ++i) {
naryStmt->PushBackOpnd(BuildExpr(*naryNode.Opnd(i)));
}
BuildMuList(ssaPart.GetMayUseNodes(), *(naryStmt->GetMuList()));
BuildChiList(*naryStmt, ssaPart.GetMayDefNodes(), *(naryStmt->GetChiList()));
return naryStmt;
}
MeStmt *IRMap::BuildMeStmt(StmtNode &stmt) {
AccessSSANodes *ssaPart = ssaTab.GetStmtsSSAPart().SSAPartOf(stmt);
if (ssaPart == nullptr) {
return BuildMeStmtWithNoSSAPart(stmt);
}
auto func = CreateProductFunction<MeStmtFactory>(stmt.GetOpCode());
CHECK_FATAL(func != nullptr, "func nullptr check");
return func(this, stmt, *ssaPart);
}
void IRMap::BuildMuList(TypeOfMayUseList &mayUseList, MapleMap<OStIdx, VarMeExpr*> &muList) {
for (auto &mayUseNode : mayUseList) {
VersionSt *vst = mayUseNode.GetOpnd();
VarMeExpr *varMeExpr = GetOrCreateVarFromVerSt(*vst);
muList.insert(std::make_pair(varMeExpr->GetOStIdx(), varMeExpr));
}
}
MeExpr *IRMap::BuildExpr(BaseNode &mirNode) {
Opcode op = mirNode.GetOpCode();
if (op == OP_dread) {
auto &addrOfNode = static_cast<AddrofSSANode &>(mirNode);
VersionSt *vst = addrOfNode.GetSSAVar();
VarMeExpr *varMeExpr = GetOrCreateVarFromVerSt(*vst);
varMeExpr->InitBase(mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds());
if (vst->GetOrigSt()->IsRealSymbol()) {
ASSERT(!vst->GetOrigSt()->IsPregOst(), "not expect preg symbol here");
varMeExpr->SetPtyp(GlobalTables::GetTypeTable().GetTypeFromTyIdx(vst->GetOrigSt()->GetTyIdx())->GetPrimType());
varMeExpr->SetFieldID(addrOfNode.GetFieldID());
}
return varMeExpr;
}
if (op == OP_regread) {
auto ®Node = static_cast<RegreadSSANode &>(mirNode);
VersionSt *vst = regNode.GetSSAVar();
RegMeExpr *regMeExpr = GetOrCreateRegFromVerSt(*vst);
regMeExpr->InitBase(mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds());
return regMeExpr;
}
MeExpr *meExpr = meBuilder.BuildMeExpr(mirNode);
SetMeExprOpnds(*meExpr, mirNode);
if (op == OP_iread) {
auto *ivarMeExpr = static_cast<IvarMeExpr*>(meExpr);
auto &iReadSSANode = static_cast<IreadSSANode&>(mirNode);
ivarMeExpr->SetBase(BuildExpr(*iReadSSANode.Opnd(0)));
VersionSt *verSt = iReadSSANode.GetSSAVar();
if (verSt != nullptr) {
VarMeExpr *varMeExpr = GetOrCreateVarFromVerSt(*verSt);
ivarMeExpr->SetMuVal(varMeExpr);
}
}
MeExpr *retMeExpr = HashMeExpr(*meExpr);
if (op == OP_iread) {
ASSERT(static_cast<IvarMeExpr*>(retMeExpr)->GetMu() != nullptr, "BuildExpr: ivar node cannot have mu == nullptr");
}
return retMeExpr;
}
void IRMap::SetMeExprOpnds(MeExpr &meExpr, BaseNode &mirNode) {
auto &opMeExpr = static_cast<OpMeExpr&>(meExpr);
if (mirNode.IsUnaryNode()) {
if (mirNode.GetOpCode() != OP_iread) {
opMeExpr.SetOpnd(0, BuildExpr(*static_cast<UnaryNode&>(mirNode).Opnd(0)));
}
} else if (mirNode.IsBinaryNode()) {
auto &binaryNode = static_cast<BinaryNode&>(mirNode);
opMeExpr.SetOpnd(0, BuildExpr(*binaryNode.Opnd(0)));
opMeExpr.SetOpnd(1, BuildExpr(*binaryNode.Opnd(1)));
} else if (mirNode.IsTernaryNode()) {
auto &ternaryNode = static_cast<TernaryNode&>(mirNode);
opMeExpr.SetOpnd(0, BuildExpr(*ternaryNode.Opnd(0)));
opMeExpr.SetOpnd(1, BuildExpr(*ternaryNode.Opnd(1)));
opMeExpr.SetOpnd(2, BuildExpr(*ternaryNode.Opnd(2)));
} else if (mirNode.IsNaryNode()) {
auto &naryMeExpr = static_cast<NaryMeExpr&>(meExpr);
auto &naryNode = static_cast<NaryNode&>(mirNode);
for (size_t i = 0; i < naryNode.NumOpnds(); ++i) {
naryMeExpr.GetOpnds().push_back(BuildExpr(*naryNode.Opnd(i)));
}
} else {
// No need to do anything
}
}
void IRMap::PutToBucket(uint32 hashIdx, MeExpr &meExpr) {
MeExpr *headExpr = hashTable[hashIdx];
if (headExpr != nullptr) {
meExpr.SetNext(headExpr);
}
hashTable[hashIdx] = &meExpr;
}
MeExpr *IRMap::HashMeExpr(MeExpr &meExpr) {
MeExpr *resultExpr = nullptr;
uint32 hashIdx = meExpr.GetHashIndex() % mapHashLength;
MeExpr *hashedExpr = hashTable[hashIdx];
if (hashedExpr != nullptr && meExpr.GetMeOp() != kMeOpGcmalloc) {
resultExpr = meExpr.GetIdenticalExpr(*hashedExpr, mirModule.CurFunction()->IsConstructor());
}
if (resultExpr == nullptr) {
resultExpr = &meBuilder.CreateMeExpr(exprID++, meExpr);
PutToBucket(hashIdx, *resultExpr);
}
return resultExpr;
}
MeExpr *IRMap::ReplaceMeExprExpr(MeExpr &origExpr, MeExpr &newExpr, size_t opndsSize,
const MeExpr &meExpr, MeExpr &repExpr) {
bool needRehash = false;
for (size_t i = 0; i < opndsSize; ++i) {
MeExpr *origOpnd = origExpr.GetOpnd(i);
if (origOpnd == nullptr) {
continue;
}
if (origOpnd == &meExpr) {
needRehash = true;
newExpr.SetOpnd(i, &repExpr);
} else if (!origOpnd->IsLeaf()) {
newExpr.SetOpnd(i, ReplaceMeExprExpr(*newExpr.GetOpnd(i), meExpr, repExpr));
if (newExpr.GetOpnd(i) != origOpnd) {
needRehash = true;
}
}
}
return needRehash ? HashMeExpr(newExpr) : &origExpr;
}
// replace meExpr with repexpr. meExpr must be a kid of origexpr
// return repexpr's parent if replaced, otherwise return nullptr
MeExpr *IRMap::ReplaceMeExprExpr(MeExpr &origExpr, const MeExpr &meExpr, MeExpr &repExpr) {
if (origExpr.IsLeaf()) {
return &origExpr;
}
switch (origExpr.GetMeOp()) {
case kMeOpOp: {
auto &opMeExpr = static_cast<OpMeExpr&>(origExpr);
OpMeExpr newMeExpr(opMeExpr, kInvalidExprID);
return ReplaceMeExprExpr(opMeExpr, newMeExpr, kOperandNumTernary, meExpr, repExpr);
}
case kMeOpNary: {
auto &naryMeExpr = static_cast<NaryMeExpr&>(origExpr);
NaryMeExpr newMeExpr(&irMapAlloc, kInvalidExprID, naryMeExpr);
return ReplaceMeExprExpr(naryMeExpr, newMeExpr, naryMeExpr.GetOpnds().size(), meExpr, repExpr);
}
case kMeOpIvar: {
auto &ivarExpr = static_cast<IvarMeExpr&>(origExpr);
IvarMeExpr newMeExpr(kInvalidExprID, ivarExpr);
bool needRehash = false;
if (ivarExpr.GetBase() == &meExpr) {
newMeExpr.SetBase(&repExpr);
needRehash = true;
} else if (!ivarExpr.GetBase()->IsLeaf()) {
newMeExpr.SetBase(ReplaceMeExprExpr(*newMeExpr.GetBase(), meExpr, repExpr));
if (newMeExpr.GetBase() != ivarExpr.GetBase()) {
needRehash = true;
}
}
return needRehash ? HashMeExpr(newMeExpr) : &origExpr;
}
default:
ASSERT(false, "NYI");
return nullptr;
}
}
bool IRMap::ReplaceMeExprStmtOpnd(uint32 opndID, MeStmt &meStmt, const MeExpr &meExpr, MeExpr &repExpr) {
MeExpr *opnd = meStmt.GetOpnd(opndID);
if (opnd == &meExpr) {
meStmt.SetOpnd(opndID, &repExpr);
return true;
} else if (!opnd->IsLeaf()) {
meStmt.SetOpnd(opndID, ReplaceMeExprExpr(*opnd, meExpr, repExpr));
return meStmt.GetOpnd(opndID) != opnd;
}
return false;
}
// replace meExpr in meStmt with repexpr
bool IRMap::ReplaceMeExprStmt(MeStmt &meStmt, const MeExpr &meExpr, MeExpr &repexpr) {
bool isReplaced = false;
Opcode op = meStmt.GetOp();
for (size_t i = 0; i < meStmt.NumMeStmtOpnds(); ++i) {
if (op == OP_intrinsiccall || op == OP_xintrinsiccall || op == OP_intrinsiccallwithtype ||
op == OP_intrinsiccallassigned || op == OP_xintrinsiccallassigned ||
op == OP_intrinsiccallwithtypeassigned) {
MeExpr *opnd = meStmt.GetOpnd(i);
if (opnd->IsLeaf() && opnd->GetMeOp() == kMeOpVar) {
auto *varMeExpr = static_cast<VarMeExpr*>(opnd);
const OriginalSt *ost = ssaTab.GetOriginalStFromID(varMeExpr->GetOStIdx());
if (ost->IsSymbolOst() && ost->GetMIRSymbol()->GetAttr(ATTR_static)) {
// its address may be taken
continue;
}
}
}
bool curOpndReplaced = false;
if (i == 0 && op == OP_iassign) {
auto &ivarStmt = static_cast<IassignMeStmt&>(meStmt);
MeExpr *oldBase = ivarStmt.GetLHS()->GetOpnd(0);
MeExpr *newBase = nullptr;
if (oldBase == &meExpr) {
newBase = &repexpr;
curOpndReplaced = true;
} else if (!oldBase->IsLeaf()) {
newBase = ReplaceMeExprExpr(*oldBase, meExpr, repexpr);
curOpndReplaced = (newBase != oldBase);
}
if (curOpndReplaced) {
ASSERT_NOT_NULL(newBase);
ivarStmt.SetLHSVal(BuildLHSIvar(*newBase, ivarStmt, ivarStmt.GetLHSVal()->GetFieldID()));
}
} else {
curOpndReplaced = ReplaceMeExprStmtOpnd(i, meStmt, meExpr, repexpr);
}
isReplaced = isReplaced || curOpndReplaced;
}
return isReplaced;
}
MePhiNode *IRMap::CreateMePhi(ScalarMeExpr &meExpr) {
auto *phiMeVar = NewInPool<MePhiNode>();
phiMeVar->UpdateLHS(meExpr);
return phiMeVar;
}
DassignMeStmt *IRMap::CreateDassignMeStmt(MeExpr &lhs, MeExpr &rhs, BB &currBB) {
auto *meStmt = NewInPool<DassignMeStmt>();
meStmt->SetRHS(&rhs);
auto &var = static_cast<VarMeExpr&>(lhs);
meStmt->SetLHS(&var);
var.SetDefBy(kDefByStmt);
var.SetDefStmt(meStmt);
meStmt->SetBB(&currBB);
return meStmt;
}
IassignMeStmt *IRMap::CreateIassignMeStmt(TyIdx tyIdx, IvarMeExpr &lhs, MeExpr &rhs,
const MapleMap<OStIdx, ChiMeNode*> &clist) {
return NewInPool<IassignMeStmt>(tyIdx, &lhs, &rhs, &clist);
}
RegassignMeStmt *IRMap::CreateRegassignMeStmt(MeExpr &lhs, MeExpr &rhs, BB &currBB) {
auto *meStmt = New<RegassignMeStmt>();
ASSERT(lhs.GetMeOp() == kMeOpReg, "Create regassign without lhs == regread");
meStmt->SetRHS(&rhs);
auto ® = static_cast<RegMeExpr&>(lhs);
meStmt->SetLHS(®);
reg.SetDefBy(kDefByStmt);
reg.SetDefStmt(meStmt);
meStmt->SetBB(&currBB);
return meStmt;
}
// get the false goto bb, if condgoto is brtrue, take the other bb of brture @lable
// otherwise, take the bb of @lable
BB *IRMap::GetFalseBrBB(const CondGotoMeStmt &condgoto) {
LabelIdx lblIdx = (LabelIdx)condgoto.GetOffset();
BB *gotoBB = GetBBForLabIdx(lblIdx);
BB *bb = condgoto.GetBB();
ASSERT(bb->GetSucc().size() == kBBVectorInitialSize, "array size error");
if (condgoto.GetOp() == OP_brfalse) {
return gotoBB;
} else {
return gotoBB == bb->GetSucc(0) ? bb->GetSucc(1) : bb->GetSucc(0);
}
}
MeExpr *IRMap::CreateConstMeExpr(PrimType pType, MIRConst &mirConst) {
ConstMeExpr constMeExpr(kInvalidExprID, &mirConst);
constMeExpr.SetOp(OP_constval);
constMeExpr.SetPtyp(pType);
return HashMeExpr(constMeExpr);
}
MeExpr *IRMap::CreateIntConstMeExpr(int64 value, PrimType pType) {
auto *intConst =
GlobalTables::GetIntConstTable().GetOrCreateIntConst(value, *GlobalTables::GetTypeTable().GetPrimType(pType));
return CreateConstMeExpr(pType, *intConst);
}
MeExpr *IRMap::CreateMeExprBinary(Opcode op, PrimType pType, MeExpr &expr0, MeExpr &expr1) {
OpMeExpr opMeExpr(kInvalidExprID);
opMeExpr.SetOpnd(0, &expr0);
opMeExpr.SetOpnd(1, &expr1);
opMeExpr.InitBase(op, pType, kOperandNumBinary);
return HashMeExpr(opMeExpr);
}
MeExpr *IRMap::CreateMeExprSelect(PrimType pType, MeExpr &expr0, MeExpr &expr1, MeExpr &expr2) {
OpMeExpr opMeExpr(kInvalidExprID);
opMeExpr.SetOpnd(0, &expr0);
opMeExpr.SetOpnd(1, &expr1);
opMeExpr.SetOpnd(2, &expr2);
opMeExpr.InitBase(OP_select, pType, kOperandNumTernary);
return HashMeExpr(opMeExpr);
}
MeExpr *IRMap::CreateMeExprCompare(Opcode op, PrimType resptyp, PrimType opndptyp, MeExpr &opnd0, MeExpr &opnd1) {
OpMeExpr opMeExpr(kInvalidExprID);
opMeExpr.SetOpnd(0, &opnd0);
opMeExpr.SetOpnd(1, &opnd1);
opMeExpr.InitBase(op, resptyp, kOperandNumBinary);
opMeExpr.SetOpndType(opndptyp);
MeExpr *retMeExpr = HashMeExpr(opMeExpr);
static_cast<OpMeExpr*>(retMeExpr)->SetOpndType(opndptyp);
return retMeExpr;
}
MeExpr *IRMap::CreateMeExprTypeCvt(PrimType pType, PrimType opndptyp, MeExpr &opnd0) {
OpMeExpr opMeExpr(kInvalidExprID);
opMeExpr.SetOpnd(0, &opnd0);
opMeExpr.InitBase(OP_cvt, pType, kOperandNumUnary);
opMeExpr.SetOpndType(opndptyp);
return HashMeExpr(opMeExpr);
}
IntrinsiccallMeStmt *IRMap::CreateIntrinsicCallMeStmt(MIRIntrinsicID idx, std::vector<MeExpr*> &opnds, TyIdx tyIdx) {
auto *meStmt =
NewInPool<IntrinsiccallMeStmt>(tyIdx == 0u ? OP_intrinsiccall : OP_intrinsiccallwithtype, idx, tyIdx);
for (MeExpr *opnd : opnds) {
meStmt->PushBackOpnd(opnd);
}
return meStmt;
}
IntrinsiccallMeStmt *IRMap::CreateIntrinsicCallAssignedMeStmt(MIRIntrinsicID idx, std::vector<MeExpr*> &opnds,
MeExpr *ret, TyIdx tyIdx) {
auto *meStmt = NewInPool<IntrinsiccallMeStmt>(
tyIdx == 0u ? OP_intrinsiccallassigned : OP_intrinsiccallwithtypeassigned, idx, tyIdx);
for (MeExpr *opnd : opnds) {
meStmt->PushBackOpnd(opnd);
}
if (ret != nullptr) {
ASSERT(ret->GetMeOp() == kMeOpReg || ret->GetMeOp() == kMeOpVar, "unexpected opcode");
auto *mustDef = New<MustDefMeNode>(ret, meStmt);
meStmt->GetMustDefList()->push_back(*mustDef);
}
return meStmt;
}
MeExpr *IRMap::CreateAddrofMeExprFromSymbol(MIRSymbol &st, PUIdx puIdx) {
OriginalSt *baseOst = ssaTab.FindOrCreateSymbolOriginalSt(st, puIdx, 0);
AddrofMeExpr addrOfMe(kInvalidExprID, baseOst->GetIndex());
addrOfMe.SetOp(OP_addrof);
addrOfMe.SetPtyp(PTY_ptr);
return HashMeExpr(addrOfMe);
}
bool IRMap::InitMeStmtFactory() {
RegisterFactoryFunction<MeStmtFactory>(OP_dassign, &IRMap::BuildDassignMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_regassign, &IRMap::BuildRegassignMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_iassign, &IRMap::BuildIassignMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_maydassign, &IRMap::BuildMaydassignMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_call, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_virtualcall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_virtualicall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_superclasscall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_interfacecall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_interfaceicall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_customcall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_polymorphiccall, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_callassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_virtualcallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_virtualicallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_superclasscallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_interfacecallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_interfaceicallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_customcallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_polymorphiccallassigned, &IRMap::BuildCallMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_icall, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_icallassigned, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_intrinsiccall, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_xintrinsiccall, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_intrinsiccallwithtype, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_intrinsiccallassigned, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_intrinsiccallwithtypeassigned, &IRMap::BuildNaryMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_return, &IRMap::BuildRetMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_retsub, &IRMap::BuildWithMuMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_gosub, &IRMap::BuildGosubMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_throw, &IRMap::BuildThrowMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_syncenter, &IRMap::BuildSyncMeStmt);
RegisterFactoryFunction<MeStmtFactory>(OP_syncexit, &IRMap::BuildSyncMeStmt);
return true;
}
} // namespace maple
| 39.85212 | 118 | 0.71469 | [
"vector"
] |
24f462859d0247b22538637fea3fcba3cb4bab3d | 858 | cpp | C++ | kernel/source/interactive/acroform/AcroFormSignatureSVMDPDictionary.cpp | Hydrorastaman/PDFOut-SDK | 329e08068f96c1623493ed4ddb292a333f668762 | [
"MIT"
] | 4 | 2021-03-23T15:04:08.000Z | 2021-08-28T08:08:14.000Z | kernel/source/interactive/acroform/AcroFormSignatureSVMDPDictionary.cpp | Hydrorastaman/PDFOut-SDK | 329e08068f96c1623493ed4ddb292a333f668762 | [
"MIT"
] | null | null | null | kernel/source/interactive/acroform/AcroFormSignatureSVMDPDictionary.cpp | Hydrorastaman/PDFOut-SDK | 329e08068f96c1623493ed4ddb292a333f668762 | [
"MIT"
] | null | null | null | #include <interactive/acroform/AcroFormSignatureSVMDPDictionary.h>
namespace{
std::string const keyP = "P";
}
namespace kernel{ namespace interactive{
std::unordered_map<AcroFormSignatureSVMDPDictionaryKey, std::pair<std::string, uint32_t>> AcroFormSignatureSVMDPDictionary::mAcroFormSignatureSVMDPDictionaryMap{
{AcroFormSignatureSVMDPDictionaryKeyP, {keyP, ObjectTypeInteger}},
};
AcroFormSignatureSVMDPDictionary::AcroFormSignatureSVMDPDictionary(void)
: ObjectDictionary(IndirectTypeIndirectable){
}
AcroFormSignatureSVMDPDictionary::~AcroFormSignatureSVMDPDictionary(void) {}
void AcroFormSignatureSVMDPDictionary::addKey(AcroFormSignatureSVMDPDictionaryKey key, std::unique_ptr<Object> value){
ObjectDictionary::addKey(mAcroFormSignatureSVMDPDictionaryMap, key, std::move(value));
}
}}
| 35.75 | 164 | 0.786713 | [
"object"
] |
24fd6c4d82c276b0d0f91673bb02e63125a6f8dc | 5,116 | cc | C++ | src/ComponentBased/BaseComponents.cc | 3DExtended/Dreamroam | c924715cdb77965e352f2748911944c28bd8e464 | [
"MIT"
] | 1 | 2020-08-13T12:00:02.000Z | 2020-08-13T12:00:02.000Z | src/ComponentBased/BaseComponents.cc | 3DExtended/Dreamroam | c924715cdb77965e352f2748911944c28bd8e464 | [
"MIT"
] | 4 | 2020-07-20T18:28:08.000Z | 2020-09-27T09:56:10.000Z | src/ComponentBased/BaseComponents.cc | 3DExtended/Dreamroam | c924715cdb77965e352f2748911944c28bd8e464 | [
"MIT"
] | 2 | 2020-08-16T23:24:17.000Z | 2020-10-09T10:42:19.000Z | #include "BaseComponents.hh"
#include <Utils/Base.hh>
using namespace DCore::ComponentSystem;
glm::mat4 TransformComponent::getModelMatrix() {
// TODO make it possible to set a parent on the entity
#if 0
if (parent != nullptr)
{
return getPosMatrix() * getRotationMatrix() * getScaleMatrix() * parent->getModelMatrix();
}
else
{
#endif
return getPosMatrix() * getRotationMatrix() * getScaleMatrix();
//}
}
glm::mat4 TransformComponent::getScaleMatrix() { return glm::scale(scale); }
glm::mat4 TransformComponent::getRotationMatrix() {
glm::mat4 rotX = glm::rotate(rotation.x, glm::vec3(1, 0, 0));
glm::mat4 rotY = glm::rotate(rotation.y, glm::vec3(0, 1, 0));
glm::mat4 rotZ = glm::rotate(rotation.z, glm::vec3(0, 0, 1));
glm::mat4 rotMat = rotX * rotY * rotZ;
return rotMat;
}
glm::mat4 TransformComponent::getPosMatrix() {
return glm::translate(position);
}
void DCore::ComponentSystem::CameraComponent::setHorizontalFieldOfView(
float _fovh) {
DR_ASSERT(_fovh < 180.0f);
DR_ASSERT(_fovh > 0.0f);
mHorizontalFieldOfView = _fovh;
}
void DCore::ComponentSystem::CameraComponent::setVerticalFieldOfView(
float _fovv) {
DR_ASSERT(_fovv < 180.0f);
DR_ASSERT(_fovv > 0.0f);
// we only save the aspectRatio and the horizontal FoV
// so if we change the vertical FoV, we change the aspectRatio
// mAspectRatio = tan( glm::radians(0.5f * mHorizontalFieldOfView) ) /
// tan( glm::radians(0.5f * _fovv) );
float x = tan(glm::radians(0.5f * _fovv)) * mAspectRatio;
mHorizontalFieldOfView = glm::degrees(2.0f * atan(x));
}
float DCore::ComponentSystem::CameraComponent::getVerticalFieldOfView() const {
return glm::degrees(
atan(tan(glm::radians(0.5f * mHorizontalFieldOfView)) / mAspectRatio) *
2.0f);
}
void DCore::ComponentSystem::CameraComponent::setNearClippingPlane(
float _plane) {
DR_ASSERT(_plane > 0.0f);
mNearClippingPlane = _plane;
}
void DCore::ComponentSystem::CameraComponent::setFarClippingPlane(
float _plane) {
DR_ASSERT(_plane > 0.0f);
mFarClippingPlane = _plane;
}
glm::mat4 DCore::ComponentSystem::CameraComponent::getProjectionMatrix() const {
glm::mat4 projectionMatrix{}; // identity matrix
if (getProjectionMode() == IsometricProjection) {
// we don't set the left/right/top/bottom values explicitly, so we want
// that
// all object at our focal distance appear the same in perspective and
// isometric view
float right = tan(glm::radians(getHorizontalFieldOfView() * 0.5f)) *
mLookAtDistance;
float left = -right;
float top = tan(glm::radians(getVerticalFieldOfView() * 0.5f)) *
mLookAtDistance;
float bottom = -top;
// we do the same here as a glOrtho call would do, but with flipped y
projectionMatrix[0][0] = 2.0f / (right - left);
projectionMatrix[1][1] = -2.0f / (top - bottom);
projectionMatrix[2][2] =
-2.0f / (mFarClippingPlane - mNearClippingPlane);
projectionMatrix[0][3] = -(right + left) / (right - left);
projectionMatrix[1][3] = -(top + bottom) / (top - bottom);
projectionMatrix[2][3] = -(mFarClippingPlane + mNearClippingPlane) /
(mFarClippingPlane - mNearClippingPlane);
projectionMatrix[3][3] = 1.0;
} else if (mProjectionMode == PerspectiveProjectionDXReverse) {
if (std::isinf(mFarClippingPlane)) {
float e = 1.0f / tan(glm::radians(getVerticalFieldOfView() * 0.5f));
const float a = getAspectRatio();
// infinite Perspective matrix reversed mapping to 1..0, but flip y
projectionMatrix = {e / a, 0.0f, 0.0f,
0.0f, //
0.0f, -e, 0.0f,
0.0f, //
0.0f, 0.0f, 0.0f,
-1.0f, //
0.0f, 0.0f, mNearClippingPlane,
0.0f};
} else {
// TODO: convert this into a matrix with finite far distance but
// from 0 to 1 instead of 1 to 0
float e = 1.0f / tan(glm::radians(getVerticalFieldOfView() * 0.5f));
const float a = getAspectRatio();
// infinite Perspective matrix reversed mapping to 1..0, but flip y
projectionMatrix = {e / a, 0.0f, 0.0f, 0.0f, //
0.0f, -e, 0.0f, 0.0f, //
0.0f, 0.0f, 0.0f, -1.0f, //
0.0f, 0.0f, 0.0f, 0.0f};
projectionMatrix[2][2] =
mFarClippingPlane / (mNearClippingPlane - mFarClippingPlane);
projectionMatrix[3][2] = (mFarClippingPlane * mNearClippingPlane) /
(mNearClippingPlane - mFarClippingPlane);
}
}
else
assert(0 && "unsupported projection mode");
return projectionMatrix;
} | 36.805755 | 98 | 0.583659 | [
"object"
] |
7001931d87ba50a86fa4f83ccd8a9b73635f4c51 | 412 | cpp | C++ | Day-17/Day-17-Codeforces/34B-Sale.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | Day-17/Day-17-Codeforces/34B-Sale.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | Day-17/Day-17-Codeforces/34B-Sale.cpp | LawranceMichaelite/100-Days-of-Code | de80015c2ab7c94956d4fe39f6e143627cdd7bc9 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin >> n >>m ;
vector<int>arr(n);
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
sort(arr.begin(),arr.end());
auto i = arr.begin();
int ans = 0;
int carry = 0;
while(i != arr.end() && *i <= 0 && carry < m)
{
ans += *i;
i++;
carry++;
}
cout << abs(ans) << endl;
return 0;
}
| 17.166667 | 49 | 0.434466 | [
"vector"
] |
700228df5a68a321a87ce1e53bc780f02cefb92a | 11,960 | cpp | C++ | src/shared_library/markdown/markdown.cpp | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | src/shared_library/markdown/markdown.cpp | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | 7 | 2021-05-30T21:52:39.000Z | 2021-06-25T22:35:28.000Z | src/shared_library/markdown/markdown.cpp | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | #include <unordered_map>
#include <stack>
#include "markdown.h"
namespace projectfarm::shared::markdown
{
auto ReadColor(std::uint32_t& index,
std::string_view text,
const shared::graphics::colors::Color& defaultColor) noexcept
-> std::pair<shared::graphics::colors::Color, bool>
{
auto colorFound {false};
std::string colorBuffer;
auto colorIndex = index + 1;
while (colorIndex < text.size())
{
auto colorC = text[colorIndex];
if (colorC == ')')
{
colorFound = true;
break;
}
colorBuffer += colorC;
++colorIndex;
}
shared::graphics::colors::Color color {defaultColor};
// if a color was found, don't add that text to
// the part
if (colorFound)
{
index = colorIndex;
if (auto foundColor = graphics::colors::FromString(colorBuffer); foundColor)
{
color = *foundColor;
}
else
{
color = defaultColor;
}
}
return { color, colorFound };
}
std::vector<TextPart> GetTextParts(std::string_view text,
shared::graphics::colors::Color defaultColor) noexcept
{
static const std::unordered_map<char, TextPartTypes> controlCharacters
{
{ '*', TextPartTypes::Italic },
{ '_', TextPartTypes::Bold },
{ '$', TextPartTypes::BoldItalic },
};
if (text.empty())
{
return {};
}
std::vector<TextPart> parts;
TextPartTypes typeState {TextPartTypes::Normal};
shared::graphics::colors::Color colorState { defaultColor };
auto isControlCharacter = [](char c) -> bool
{
for (const auto& controlCharacter : controlCharacters)
{
if (controlCharacter.first == c)
{
return true;
}
}
return false;
};
auto savePart = [&parts, &typeState, &colorState](uint32_t index,
uint32_t partEndPos,
std::string_view readText)
{
if (readText.empty())
{
return;
}
TextPart part;
part._text = readText;
part._originalTextStartIndex = index;
part._endTextPosition = partEndPos;
part._type = typeState;
part._color = colorState;
parts.push_back(part);
};
auto readColor = [&colorState, &defaultColor, &savePart, &typeState](uint32_t& i,
uint32_t& partStartPosition,
std::string_view textToProcess,
std::string readText) -> bool
{
auto originalIndex = i;
auto colorFinished {false};
auto c = textToProcess[i];
if (c != '(')
{
return false;
}
std::string colorText;
auto originalStartPosition {i};
++i;
for (; i < textToProcess.size(); ++i)
{
c = textToProcess[i];
if (c == ')')
{
colorFinished = true;
break;
}
colorText += c;
}
// the color markup wasn't completed
if (i >= textToProcess.size())
{
i = originalIndex;
return false;
}
if (!readText.empty())
{
for (const auto& controlCharacter : controlCharacters)
{
if (typeState != TextPartTypes::Normal &&
typeState == controlCharacter.second)
{
// as we are finishing an existing part, remove
// the control character from the beginning rather
// than add a control character to the end, as we
// shouldn't be saving parts with control characters
// both at the beginning and the end
readText = readText.substr(1);
}
}
}
savePart(partStartPosition, colorFinished ? i + 1 : i, readText);
originalStartPosition = i;
partStartPosition = colorFinished ? originalStartPosition + 1 : originalStartPosition;
if (auto color = shared::graphics::colors::FromString(colorText); color)
{
colorState = *color;
}
else
{
colorState = defaultColor;
}
return true;
};
auto readBackslash = [&isControlCharacter](uint32_t i, std::string_view textToProcess) -> bool
{
if (i == textToProcess.size() - 1)
{
return false;
}
auto c = textToProcess[i];
if (c != '\\')
{
return false;
}
auto c2 = textToProcess[i + 1];
return isControlCharacter(c2) || c2 == '(';
};
auto readUntilControlCharacter = [&isControlCharacter, &readColor, &readBackslash](uint32_t& i,
uint32_t& partStartPosition,
std::string_view textToProcess)
-> std::string
{
std::string line;
partStartPosition = i;
for (; i < textToProcess.size(); ++i)
{
auto c = textToProcess[i];
auto isBackslash = readBackslash(i, textToProcess);
if (isBackslash)
{
++i;
c = textToProcess[i];
}
else
{
if (readColor(i, partStartPosition, textToProcess, line))
{
line = "";
continue;
}
if (isControlCharacter(c))
{
break;
}
}
line += c;
}
return line;
};
auto readAllOfNextControlCharacter = [&typeState, &readColor, &readBackslash](uint32_t& i,
uint32_t& partStartPosition,
uint32_t& partEndPosition,
std::string_view textToProcess)
-> std::string
{
auto controlCharacter = textToProcess[i++];
auto controlCharacterIter = controlCharacters.find(controlCharacter);
if (controlCharacterIter == controlCharacters.end())
{
// TODO: Handle this error...
return "error";
}
typeState = controlCharacterIter->second;
std::string line;
line += controlCharacter;
// in case this control section is not complete, we can revert
auto previousStartPos = partStartPosition;
// set the here in case we need to read a color, then the correct
// starting pos will be saved
partStartPosition = i;
for (; i < textToProcess.size(); ++i)
{
auto c = textToProcess[i];
auto isBackslash = readBackslash(i, textToProcess);
if (isBackslash)
{
++i;
c = textToProcess[i];
}
if (!isBackslash && readColor(i, partStartPosition, textToProcess, line))
{
// if we read a color, a new part would have been added
// start off this new part with the current control character
line = controlCharacter;
continue;
}
line += c;
if (!isBackslash && c == controlCharacter)
{
break;
}
}
if (line.size() > 1 &&
line[0] == controlCharacter &&
line[line.size() - 1] == controlCharacter)
{
line = line.substr(1, line.size() - 2);
partStartPosition = i - static_cast<uint32_t>(line.size());
partEndPosition = i + 1;
}
else
{
partStartPosition = previousStartPos;
partEndPosition = i;
}
return line;
};
auto partStartPosition {0u};
for (auto i = 0u; i < text.size(); ++i)
{
typeState = TextPartTypes::Normal;
auto readText = readUntilControlCharacter(i, partStartPosition, text);
savePart(partStartPosition, i, readText);
if (i >= text.size())
{
break;
}
auto partEndPosition {0u};
readText = readAllOfNextControlCharacter(i, partStartPosition, partEndPosition, text);
savePart(partStartPosition, partEndPosition, readText);
}
return parts;
}
uint32_t GetMarkdownPositionFromPartPosition(std::string_view text, uint32_t partPosition) noexcept
{
if (text.empty())
{
return 0;
}
auto parts = GetTextParts(text);
if (parts.empty())
{
// perhaps we have just color markup as our text
return static_cast<uint32_t>(text.size());
}
auto markdownPosition {0u};
for (auto i = 0u; i < parts.size(); ++i)
{
const auto& part = parts[i];
if (part._text.size() < partPosition)
{
partPosition -= static_cast<uint32_t>(part._text.size());
}
else
{
if (partPosition == part._text.size())
{
// for text such as `$text$(blue)hi`
if (i < parts.size() - 1 &&
parts[i + 1]._originalTextStartIndex - part._endTextPosition > 1)
{
markdownPosition = parts[i + 1]._originalTextStartIndex;
}
// for text such as `$text$(blue)`
// if the end of the text is color markup, there won't
// be a part for it
else if (i == parts.size() - 1 &&
part._endTextPosition < text.size())
{
markdownPosition = static_cast<uint32_t>(text.size());
}
else
{
markdownPosition = part._endTextPosition;
}
}
else
{
markdownPosition = part._originalTextStartIndex + partPosition;
}
break;
}
}
return markdownPosition;
}
} | 30.510204 | 122 | 0.426338 | [
"vector"
] |
70026187ba6329a0534c29d6e8c2f6e4334cf4f9 | 556 | cc | C++ | Greedy/JumpGame2.cc | plantree/LeetCode | 0ac6734b6a4c6e826df15a3d2e43e8f8df92a510 | [
"MIT"
] | null | null | null | Greedy/JumpGame2.cc | plantree/LeetCode | 0ac6734b6a4c6e826df15a3d2e43e8f8df92a510 | [
"MIT"
] | null | null | null | Greedy/JumpGame2.cc | plantree/LeetCode | 0ac6734b6a4c6e826df15a3d2e43e8f8df92a510 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int max(int x, int y) {
return x > y ? x : y;
}
int jump(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int res = 0, n = nums.size(), i = 0, cur = 0;
while (cur < n-1) {
res++;
int pre = cur;
for (; i <= pre; ++i) {
cur = max(cur, i+nums[i]);
}
if (pre == cur) {
return - 1;
}
}
return res;
}
int main() {
vector<int> nums = {2, 3, 1, 1, 4};
cout << jump(nums) << endl;
} | 17.935484 | 49 | 0.429856 | [
"vector"
] |
700a3cc4543611e3393f7302639fd41dc7c216f3 | 15,827 | cpp | C++ | NOLF/ObjectDLL/ObjectRemover.cpp | haekb/nolf1-modernizer | 25bac3d43c40a83b8e90201a70a14ef63b4240e7 | [
"Unlicense"
] | 38 | 2019-09-16T14:46:42.000Z | 2022-03-10T20:28:10.000Z | NOLF/ObjectDLL/ObjectRemover.cpp | haekb/nolf1-modernizer | 25bac3d43c40a83b8e90201a70a14ef63b4240e7 | [
"Unlicense"
] | 39 | 2019-08-12T01:35:33.000Z | 2022-02-28T16:48:16.000Z | NOLF/ObjectDLL/ObjectRemover.cpp | haekb/nolf1-modernizer | 25bac3d43c40a83b8e90201a70a14ef63b4240e7 | [
"Unlicense"
] | 6 | 2019-09-17T12:49:18.000Z | 2022-03-10T20:28:12.000Z | // ----------------------------------------------------------------------- //
//
// MODULE : ObjectRemover.h
//
// PURPOSE : ObjectRemover - Implementation
//
// CREATED : 04.23.1999
//
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "ObjectRemover.h"
#include "ServerUtilities.h"
#include "ObjectMsgs.h"
BEGIN_CLASS(ObjectRemover)
PROP_DEFINEGROUP(Groups0and1, PF_GROUP1)
ADD_STRINGPROP_FLAG(Group00Object00, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object01, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object02, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object03, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object04, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object05, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object06, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object07, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object08, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object09, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group00Object10, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object00, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object01, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object02, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object03, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object04, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object05, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object06, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object07, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object08, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object09, "", PF_GROUP1|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group01Object10, "", PF_GROUP1|PF_OBJECTLINK)
PROP_DEFINEGROUP(Groups2and3, PF_GROUP2)
ADD_STRINGPROP_FLAG(Group02Object00, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object01, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object02, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object03, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object04, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object05, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object06, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object07, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object08, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object09, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group02Object10, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object00, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object01, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object02, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object03, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object04, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object05, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object06, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object07, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object08, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object09, "", PF_GROUP2|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group03Object10, "", PF_GROUP2|PF_OBJECTLINK)
PROP_DEFINEGROUP(Groups4and5, PF_GROUP3)
ADD_STRINGPROP_FLAG(Group04Object00, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object01, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object02, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object03, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object04, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object05, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object06, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object07, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object08, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object09, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group04Object10, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object00, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object01, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object02, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object03, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object04, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object05, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object06, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object07, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object08, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object09, "", PF_GROUP3|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group05Object10, "", PF_GROUP3|PF_OBJECTLINK)
PROP_DEFINEGROUP(Groups6and7, PF_GROUP4)
ADD_STRINGPROP_FLAG(Group06Object00, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object01, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object02, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object03, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object04, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object05, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object06, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object07, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object08, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object09, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group06Object10, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object00, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object01, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object02, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object03, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object04, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object05, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object06, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object07, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object08, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object09, "", PF_GROUP4|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group07Object10, "", PF_GROUP4|PF_OBJECTLINK)
PROP_DEFINEGROUP(Groups8and9, PF_GROUP5)
ADD_STRINGPROP_FLAG(Group08Object00, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object01, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object02, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object03, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object04, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object05, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object06, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object07, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object08, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object09, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group08Object10, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object00, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object01, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object02, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object03, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object04, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object05, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object06, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object07, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object08, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object09, "", PF_GROUP5|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group09Object10, "", PF_GROUP5|PF_OBJECTLINK)
PROP_DEFINEGROUP(Groups10and11, PF_GROUP6)
ADD_STRINGPROP_FLAG(Group10Object00, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object01, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object02, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object03, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object04, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object05, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object06, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object07, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object08, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object09, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group10Object10, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object00, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object01, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object02, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object03, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object04, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object05, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object06, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object07, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object08, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object09, "", PF_GROUP6|PF_OBJECTLINK)
ADD_STRINGPROP_FLAG(Group11Object10, "", PF_GROUP6|PF_OBJECTLINK)
ADD_LONGINTPROP(GroupsToKeep, 1)
END_CLASS_DEFAULT(ObjectRemover, BaseClass, NULL, NULL)
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::ObjectRemover()
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
ObjectRemover::ObjectRemover() : BaseClass()
{
m_cGroupsToKeep = 1;
for ( int iGroup = 0 ; iGroup < kMaxGroups ; iGroup++ )
{
for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
m_ahstrObjects[iGroup][iObject] = LTNULL;
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::~ObjectRemover()
//
// PURPOSE: Destructor
//
// ----------------------------------------------------------------------- //
ObjectRemover::~ObjectRemover()
{
for ( int iGroup = 0 ; iGroup < kMaxGroups ; iGroup++ )
{
for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
FREE_HSTRING(m_ahstrObjects[iGroup][iObject]);
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::EngineMessageFn
//
// PURPOSE: Handle engine messages
//
// ----------------------------------------------------------------------- //
uint32 ObjectRemover::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData)
{
switch(messageID)
{
case MID_UPDATE:
{
Update();
break;
}
case MID_PRECREATE:
{
if (fData == PRECREATE_WORLDFILE || fData == PRECREATE_STRINGPROP)
{
ReadProp((ObjectCreateStruct*)pData);
}
break;
}
case MID_INITIALUPDATE:
{
if (fData != INITIALUPDATE_SAVEGAME)
{
g_pLTServer->SetNextUpdate(m_hObject, 0.001f);
}
break;
}
case MID_SAVEOBJECT:
{
Save((HMESSAGEWRITE)pData);
}
break;
case MID_LOADOBJECT:
{
Load((HMESSAGEREAD)pData);
}
break;
default : break;
}
return BaseClass::EngineMessageFn(messageID, pData, fData);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::ReadProp
//
// PURPOSE: Set property value
//
// ----------------------------------------------------------------------- //
LTBOOL ObjectRemover::ReadProp(ObjectCreateStruct *pInfo)
{
if (!pInfo) return LTFALSE;
GenericProp genProp;
for ( int iGroup = 0 ; iGroup < kMaxGroups ; iGroup++ )
{
for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
char szProp[128];
sprintf(szProp, "Group%2.2dObject%2.2d", iGroup, iObject);
if ( g_pLTServer->GetPropGeneric( szProp, &genProp ) == LT_OK )
if ( genProp.m_String[0] )
m_ahstrObjects[iGroup][iObject] = g_pLTServer->CreateString( genProp.m_String );
}
}
if ( g_pLTServer->GetPropGeneric( "GroupsToKeep", &genProp ) == LT_OK )
m_cGroupsToKeep = genProp.m_Long;
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::Update()
//
// PURPOSE: Update
//
// ----------------------------------------------------------------------- //
LTBOOL ObjectRemover::Update()
{
HOBJECT ahObjects[kMaxGroups][kMaxObjectsPerGroup][128];
memset(ahObjects, LTNULL, sizeof(HOBJECT)*kMaxGroups*kMaxObjectsPerGroup*128);
int cGroupsWithObjects = 0;
{for ( int iGroup = 0 ; iGroup < kMaxGroups ; iGroup++ )
{
LTBOOL bGroupHasObjects = LTFALSE;
{for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
if ( m_ahstrObjects[iGroup][iObject] )
{
char szString[1024];
strcpy(szString, g_pLTServer->GetStringData(m_ahstrObjects[iGroup][iObject]));
uint32 cTokens = 0;
const char* szToken = strtok(szString, ";");
while ( szToken )
{
HOBJECT hObject;
if ( LT_OK == FindNamedObject(szToken, hObject) )
{
ahObjects[cGroupsWithObjects][iObject][cTokens++] = hObject;
bGroupHasObjects = LTTRUE;
}
szToken = strtok(NULL, ";");
}
}
}}
if ( bGroupHasObjects )
{
cGroupsWithObjects++;
}
}}
// Remove the objects
LTBOOL abRemoved[kMaxGroups];
memset(abRemoved, LTFALSE, sizeof(LTBOOL)*kMaxGroups);
int iSafety = 50000;
int cRemove = cGroupsWithObjects-m_cGroupsToKeep;
while ( (cRemove > 0) && (--iSafety > 0) )
{
int iRemove = GetRandom(0, cGroupsWithObjects-1);
if ( !abRemoved[iRemove] )
{
for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
for ( int iToken = 0 ; iToken < 128 ; iToken++ )
{
if ( ahObjects[iRemove][iObject][iToken] )
{
if ( IsAI(ahObjects[iRemove][iObject][iToken]) )
{
SendTriggerMsgToObject(this, ahObjects[iRemove][iObject][iToken], LTFALSE, "REMOVE");
}
else
{
g_pLTServer->RemoveObject(ahObjects[iRemove][iObject][iToken]);
}
}
}
}
abRemoved[iRemove] = LTTRUE;
cRemove--;
}
}
// Remove ourselves...
g_pLTServer->RemoveObject(m_hObject);
return LTTRUE;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::Save
//
// PURPOSE: Save the object
//
// ----------------------------------------------------------------------- //
void ObjectRemover::Save(HMESSAGEWRITE hWrite)
{
ILTServer* pServerDE = GetServerDE();
if (!pServerDE || !hWrite) return;
for ( int iGroup = 0 ; iGroup < kMaxGroups ; iGroup++ )
{
for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
SAVE_HSTRING(m_ahstrObjects[iGroup][iObject]);
}
}
SAVE_INT(m_cGroupsToKeep);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: ObjectRemover::Load
//
// PURPOSE: Load the object
//
// ----------------------------------------------------------------------- //
void ObjectRemover::Load(HMESSAGEREAD hRead)
{
ILTServer* pServerDE = GetServerDE();
if (!pServerDE || !hRead) return;
for ( int iGroup = 0 ; iGroup < kMaxGroups ; iGroup++ )
{
for ( int iObject = 0 ; iObject < kMaxObjectsPerGroup ; iObject++ )
{
LOAD_HSTRING(m_ahstrObjects[iGroup][iObject]);
}
}
LOAD_INT(m_cGroupsToKeep);
} | 36.636574 | 100 | 0.699059 | [
"object"
] |
701e5d40d761883e1b66f0fd644834ff698862f7 | 3,093 | cpp | C++ | torch/lib/c10d/test/ProcessGroupMPITest.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | 1 | 2019-07-21T02:13:22.000Z | 2019-07-21T02:13:22.000Z | torch/lib/c10d/test/ProcessGroupMPITest.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | torch/lib/c10d/test/ProcessGroupMPITest.cpp | DavidKo3/mctorch | 53ffe61763059677978b4592c8b2153b0c15428f | [
"BSD-3-Clause"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <unistd.h>
#include <c10d/ProcessGroupMPI.hpp>
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
void testAllreduce(int iter = 1000) {
auto pg = c10d::ProcessGroupMPI::createProcessGroupMPI();
// Generate inputs
std::vector<std::vector<at::Tensor>> allTensors(iter);
for (auto i = 0; i < iter; ++i) {
auto tensor = at::ones(at::CPU(at::kFloat), {16, 16}) * i;
allTensors[i] = std::vector<at::Tensor>({tensor});
}
std::vector<std::shared_ptr<::c10d::ProcessGroup::Work>> works;
for (auto& tensors : allTensors) {
// Kick off work
std::shared_ptr<::c10d::ProcessGroup::Work> work = pg->allreduce(tensors);
works.push_back(std::move(work));
}
for (auto& work : works) {
// Wait for work to complete
if (!work->wait()) {
std::cerr << "Exception received: " << work->exception().what()
<< std::endl;
pg->abort();
}
}
// Get the world size
auto worldSize = pg->getSize();
// Verify outputs
for (int i = 0; i < iter; ++i) {
const auto expected = worldSize * i;
auto data = allTensors[i][0].data<float>();
for (auto i = 0; i < allTensors[i][0].numel(); ++i) {
if (data[i] != expected) {
throw std::runtime_error("BOOM!");
}
}
}
}
void testBroadcast(int iter = 10000) {
auto pg = c10d::ProcessGroupMPI::createProcessGroupMPI();
// Generate inputs
std::vector<std::vector<at::Tensor>> allTensors(iter);
for (auto i = 0; i < iter; ++i) {
if (pg->getRank() == 0) {
auto tensor = at::ones(at::CPU(at::kFloat), {16, 16}) * i;
allTensors[i] = std::vector<at::Tensor>({tensor});
} else {
auto tensor = at::zeros(at::CPU(at::kFloat), {16, 16});
allTensors[i] = std::vector<at::Tensor>({tensor});
}
}
std::vector<std::shared_ptr<::c10d::ProcessGroup::Work>> works;
for (auto& tensors : allTensors) {
// Kick off work
std::shared_ptr<::c10d::ProcessGroup::Work> work = pg->broadcast(tensors);
works.push_back(std::move(work));
}
for (auto& work : works) {
// Wait for work to complete
if (!work->wait()) {
std::cerr << "Exception received: " << work->exception().what()
<< std::endl;
pg->abort();
}
}
// Verify outputs
for (int i = 0; i < iter; ++i) {
const auto expected = i;
auto data = allTensors[i][0].data<float>();
for (auto i = 0; i < allTensors[i][0].numel(); ++i) {
if (data[i] != expected) {
throw std::runtime_error("BOOM!");
}
}
}
}
int main(int argc, char** argv) {
#ifdef MPIEXEC
// If we are within an openmpi mpirun, then skip the exec
if (!std::getenv("OMPI_COMM_WORLD_SIZE")) {
std::cout << "Execute mpiexec from: " << STR(MPIEXEC) << std::endl;
execl(STR(MPIEXEC), "-np 2", argv[0]);
}
testAllreduce();
testBroadcast();
std::cout << "Test successful" << std::endl;
#else
std::cout << "MPI executable not found, skipping test" << std::endl;
#endif
return EXIT_SUCCESS;
}
| 27.131579 | 78 | 0.587456 | [
"vector"
] |
70200c0e51b10be3ea709e8dbf2ab205ce892b3b | 2,776 | cpp | C++ | src/plugins/cgal/nodes/selection/logical_op.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 232 | 2017-10-09T11:45:28.000Z | 2022-03-28T11:14:46.000Z | src/plugins/cgal/nodes/selection/logical_op.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 26 | 2019-01-20T21:38:25.000Z | 2021-10-16T03:57:17.000Z | src/plugins/cgal/nodes/selection/logical_op.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 33 | 2017-10-26T19:20:38.000Z | 2022-03-16T11:21:43.000Z | #include <possumwood_sdk/datatypes/enum.h>
#include <possumwood_sdk/node_implementation.h>
#include "datatypes/meshes.h"
#include "datatypes/selection.h"
#include "errors.h"
namespace {
using possumwood::CGALPolyhedron;
using possumwood::FaceSelection;
using possumwood::Meshes;
typedef possumwood::CGALPolyhedron Mesh;
dependency_graph::InAttr<FaceSelection> a_inSelection1;
dependency_graph::InAttr<FaceSelection> a_inSelection2;
dependency_graph::InAttr<possumwood::Enum> a_mode;
dependency_graph::OutAttr<FaceSelection> a_outSelection;
enum Mode { kAnd, kOr, kXor };
std::vector<std::pair<std::string, Mode>> s_modes{{"And", kAnd}, {"Or", kOr}, {"Xor", kXor}};
dependency_graph::State compute(dependency_graph::Values& data) {
FaceSelection result;
const auto& in1 = data.get(a_inSelection1);
const auto& in2 = data.get(a_inSelection2);
if(in1.size() != in2.size())
throw std::runtime_error("Input meshes must be the same.");
for(std::size_t i = 0; i < in1.size(); ++i) {
const auto& inSel1 = in1[i];
const auto& inSel2 = in2[i];
if(inSel1.mesh() != inSel2.mesh())
throw std::runtime_error("Input meshes must be the same.");
FaceSelection::Item out = inSel1;
out.clear();
switch(data.get(a_mode).intValue()) {
case kAnd:
for(auto fit = out.mesh().polyhedron().facets_begin(); fit != out.mesh().polyhedron().facets_end();
++fit)
if(inSel1.contains(fit) && inSel2.contains(fit))
out.push_back(fit);
break;
case kOr:
for(auto fit = out.mesh().polyhedron().facets_begin(); fit != out.mesh().polyhedron().facets_end();
++fit)
if(inSel1.contains(fit) || inSel2.contains(fit))
out.push_back(fit);
break;
case kXor:
for(auto fit = out.mesh().polyhedron().facets_begin(); fit != out.mesh().polyhedron().facets_end();
++fit)
if(inSel1.contains(fit) != inSel2.contains(fit))
out.push_back(fit);
break;
}
result.push_back(out);
}
data.set(a_outSelection, result);
return dependency_graph::State();
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inSelection1, "in_selection_1", possumwood::FaceSelection(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_inSelection2, "in_selection_2", possumwood::FaceSelection(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_mode, "mode", possumwood::Enum(s_modes.begin(), s_modes.end()));
meta.addAttribute(a_outSelection, "out_selection", possumwood::FaceSelection(), possumwood::AttrFlags::kVertical);
meta.addInfluence(a_inSelection1, a_outSelection);
meta.addInfluence(a_inSelection2, a_outSelection);
meta.addInfluence(a_mode, a_outSelection);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("cgal/selection/logical_op", init);
} // namespace
| 31.191011 | 116 | 0.714697 | [
"mesh",
"vector"
] |
702443e68194b5397902f0312110f58706073c81 | 4,075 | cpp | C++ | Sources/Elastos/LibCore/src/org/xml/sax/helpers/CAttributeListImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/src/org/xml/sax/helpers/CAttributeListImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/src/org/xml/sax/helpers/CAttributeListImpl.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "CAttributeListImpl.h"
namespace Org {
namespace Xml {
namespace Sax {
namespace Helpers {
CAR_INTERFACE_IMPL_2(CAttributeListImpl, Object, IAttributeList, IAttributeListImpl)
CAR_OBJECT_IMPL(CAttributeListImpl)
CAttributeListImpl::CAttributeListImpl()
{
}
ECode CAttributeListImpl::GetLength(
/* [out] */ Int32* length)
{
VALIDATE_NOT_NULL(length);
*length = mNames.GetSize();
return NOERROR;
}
ECode CAttributeListImpl::GetName(
/* [in] */ Int32 i,
/* [out] */ String* name)
{
VALIDATE_NOT_NULL(name);
if (i < 0 || i >= mNames.GetSize()) {
*name = NULL;
}
*name = mNames[i];
return NOERROR;
}
ECode CAttributeListImpl::GetType(
/* [in] */ Int32 i,
/* [out] */ String* type)
{
VALIDATE_NOT_NULL(type);
if (i < 0 || i >= mTypes.GetSize()) {
*type = NULL;
}
*type = mTypes[i];
return NOERROR;
}
ECode CAttributeListImpl::GetValue(
/* [in] */ Int32 i,
/* [out] */ String* value)
{
VALIDATE_NOT_NULL(value);
if (i < 0 || i >= mValues.GetSize()) {
*value = NULL;
}
*value = mValues[i];
return NOERROR;
}
ECode CAttributeListImpl::GetType(
/* [in] */ const String& name,
/* [out] */ String* type)
{
VALIDATE_NOT_NULL(type);
Int32 index = GetListIndex(&mNames, name);
return GetType(index, type);
}
ECode CAttributeListImpl::GetValue(
/* [in] */ const String& name,
/* [out] */ String* value)
{
VALIDATE_NOT_NULL(value);
Int32 index = GetListIndex(&mNames, name);
return GetValue(index, value);
}
ECode CAttributeListImpl::SetAttributeList(
/* [in] */ IAttributeList* atts)
{
Int32 count = 0;
atts->GetLength(&count);
Clear();
if(count > 0){
String name("");
String type("");
String value("");
for (Int32 i = 0; i < count; i++) {
atts->GetName(i, &name);
atts->GetType(i, &type);
atts->GetValue(i, &value);
AddAttribute(name, type, value);
}
}
return NOERROR;
}
ECode CAttributeListImpl::AddAttribute(
/* [in] */ const String& name,
/* [in] */ const String& type,
/* [in] */ const String& value)
{
mNames.PushBack(name);
mTypes.PushBack(type);
mValues.PushBack(value);
return NOERROR;
}
ECode CAttributeListImpl::RemoveAttribute(
/* [in] */ const String& name)
{
int index = GetListIndex(&mNames, name);
if (index != -1) {
mNames.Remove(index);
mTypes.Remove(index);
mValues.Remove(index);
}
return NOERROR;
}
ECode CAttributeListImpl::Clear()
{
mNames.Clear();
mTypes.Clear();
mValues.Clear();
return NOERROR;
}
ECode CAttributeListImpl::constructor()
{
return NOERROR;
}
ECode CAttributeListImpl::constructor(
/* [in] */ IAttributeList* atts)
{
SetAttributeList(atts);
return NOERROR;
}
Int32 CAttributeListImpl::GetListIndex(
/* [in] */ List<String>* list,
/* [in] */ const String& value)
{
VALIDATE_NOT_NULL(list);
Int32 size = list->GetSize();
for(Int32 i = 0; i < size; i++){
if(value.Equals((*list)[i])) {
return i;
}
}
return -1;
}
} // namespace Helpers
} // namespace Sax
} // namespace Xml
} // namespace Org
| 20.073892 | 84 | 0.588712 | [
"object"
] |
702d7c99a49cc00769fcfbc7bec674e2300be5eb | 22,945 | cc | C++ | src/HistTool.cc | zhenbinwu/SuperTopTagger | 82376d028e341ab79c498cb02a2eb43c6ec23ec6 | [
"MIT"
] | null | null | null | src/HistTool.cc | zhenbinwu/SuperTopTagger | 82376d028e341ab79c498cb02a2eb43c6ec23ec6 | [
"MIT"
] | null | null | null | src/HistTool.cc | zhenbinwu/SuperTopTagger | 82376d028e341ab79c498cb02a2eb43c6ec23ec6 | [
"MIT"
] | null | null | null | // ===========================================================================
//
// Filename: HistTool.hh
//
// Description: A helpful class to handle the histograms
//
// Version: 1.0
// Created: 05/29/2013 02:19:25 PM
// Revision: none
// Compiler: g++
//
// Author: Zhenbin Wu (benwu), benwu@fnal.gov
// Company: Baylor University, CMS@FNAL
//
// ===========================================================================
#include "UserCode/SuperTopTagger/interface/HistTool.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class: HistTool
// Method: HistTool
// Description: constructor
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistTool::HistTool (std::string name)
{
prefix = name;
HWeight = -999.;
} // ~~~~~ end of method HistTool::HistTool (constructor) ~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class: HistTool
// Method: HistTool
// Description: copy constructor
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistTool::HistTool ( const HistTool &other )
{
} // ~~~~~ end of method HistTool::HistTool (copy constructor) ~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class: HistTool
// Method: ~HistTool
// Description: destructor
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistTool::~HistTool ()
{
OutFile->Close();
delete OutFile;
} // ~~~~~ end of method HistTool::~HistTool (destructor) ~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class: HistTool
// Method: operator =
// Description: assignment operator
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistTool&
HistTool::operator = ( const HistTool &other )
{
if ( this != &other ) {
}
return *this;
} // ~~~~~ end of method HistTool::operator = (assignment operator) ~~~
// === FUNCTION ============================================================
// Name: HistTool::Cutorder
// Description:
// ===========================================================================
std::vector<std::string> HistTool::Cutorder()
{
order.push_back("noCut");
order.push_back("CTVBF");
order.push_back("CTLepV");
order.push_back("CTMet50");
order.push_back("CTMjj");
order.push_back("CTMet200");
order.push_back("AllCut");
CutSize = order.size();
return order;
} // ----- end of function HistTool::Cutorder -----
// === FUNCTION ============================================================
// Name: HistTool::Cutorder
// Description:
// ===========================================================================
int HistTool::Cutorder(std::vector<std::string> Order)
{
order = Order;
CutSize = order.size();
return CutSize;
} // ----- end of function HistTool::Cutorder -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH1C
// Description:
// ===========================================================================
int HistTool::AddTH1C (const std::string name, const std::string title,
const std::string xlabel, const std::string ylabel,
Int_t nxbins, Axis_t xmin, Axis_t xmax,
Int_t logx, Int_t logy)
{
for (Long_t i = 0; i < CutSize; ++i)
{
TString mapname = name+"_"+i;
TString maptitle = title+" ("+order.at(i)+")";
AddTH1(mapname.Data(), maptitle.Data(), xlabel, ylabel, nxbins, xmin, xmax, logx, logy);
}
return 1;
} // ----- end of function HistTool::AddTH1C -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH1C
// Description:
// ===========================================================================
int HistTool::AddTH1C (const std::string name, const std::string title,
Int_t nxbins, Axis_t xmin, Axis_t xmax)
{
for (Long_t i = 0; i < CutSize; ++i)
{
TString mapname = name+"_"+i;
TString maptitle = title+" ("+order.at(i)+")";
AddTH1(mapname.Data(), maptitle.Data(), nxbins, xmin, xmax);
}
return 1;
} // ----- end of function HistTool::AddTH1C -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH1
// Description: degenrous! What if the external th gets destroy? Need to
// figure out a better way for this!
// ===========================================================================
TH1D* HistTool::AddTH1(TH1D* th)
{
HisMap[th->GetName()] = th;
return HisMap[th->GetName()];
} // ----- end of function HistTool::AddTH1 -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH1
// Description:
// ===========================================================================
TH1D* HistTool::AddTH1 (const std::string name, const std::string title,
const std::string xlabel, const std::string ylabel,
Int_t nxbins, Axis_t xmin, Axis_t xmax,
Int_t logx, Int_t logy)
{
TString xlb, ylb;
if (logx) xlb = "log_"+xlabel;
else xlb = xlabel;
if (logy) ylb = "log_"+ylabel;
else ylb = ylabel;
TString Title = title +";"+xlb+";"+ylb;
HisMap[name.c_str()] = fs->make<TH1D>(name.c_str(), Title, nxbins, xmin, xmax);
HisMap[name.c_str()]->Sumw2();
return HisMap[name.c_str()];
} // ----- end of function HistTool::AddTH1C -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH1
// Description:
// ===========================================================================
TH1D* HistTool::AddTH1 (const std::string name, const std::string title,
Int_t nxbins, Axis_t xmin, Axis_t xmax)
{
HisMap[name.c_str()] = fs->make<TH1D>(name.c_str(), title.c_str(), nxbins, xmin, xmax);
HisMap[name.c_str()]->Sumw2();
return HisMap[name.c_str()];
} // ----- end of function HistTool::AddTH1 -----
// === FUNCTION ============================================================
// Name: HistTool::::FillTH1
// Description:
// ===========================================================================
int HistTool::FillTH1(int Ncut, std::string HisName, double value, double weight)
{
TString mapname = HisName+"_"+static_cast<Long_t>(Ncut);
if (HisMap.find(mapname.Data()) == HisMap.end())
return 0;
if (weight != -999.)
HisMap[mapname.Data()]->Fill(value, weight);
else if (HWeight != -999.)
HisMap[mapname.Data()]->Fill(value, HWeight);
else
HisMap[mapname.Data()]->Fill(value);
return 1;
} // ----- end of function HistTool::::FillTH1 -----
int HistTool::FillTH1(int Ncut, std::string HisName, int value, double weight)
{
TString mapname = HisName+"_"+static_cast<Long_t>(Ncut);
if (HisMap.find(mapname.Data()) == HisMap.end())
return 0;
if (weight != -999.)
HisMap[mapname.Data()]->Fill(value, weight);
else if (HWeight != -999.)
HisMap[mapname.Data()]->Fill(value, HWeight);
else
HisMap[mapname.Data()]->Fill(value);
return 1;
} // ----- end of function HistTool::::FillTH1 -----
int HistTool::FillTH1(std::string HisName, int value, double weight)
{
if (HisMap.find(HisName) == HisMap.end())
return 0;
if (weight != -999.)
HisMap[HisName]->Fill(value, weight);
else if (HWeight != -999.)
HisMap[HisName]->Fill(value, HWeight);
else
HisMap[HisName]->Fill(value);
return 1;
} // ----- end of function HistTool::::FillTH1 -----
int HistTool::FillTH1(std::string HisName, double value, double weight)
{
if (HisMap.find(HisName) == HisMap.end())
return 0;
if (weight != -999.)
HisMap[HisName]->Fill(value, weight);
else if (HWeight != -999.)
HisMap[HisName]->Fill(value, HWeight);
else
HisMap[HisName]->Fill(value);
return 1;
} // ----- end of function HistTool::::FillTH1 -----
// === FUNCTION ============================================================
// Name: HistTool::WriteTH1
// Description: Save the TH1
// ===========================================================================
int HistTool::WriteTH1()
{
OutFile->cd();
for(std::map<std::string, TH1D*>::iterator it=HisMap.begin();
it!=HisMap.end(); it++)
{
it->second->Write();
}
return 1;
} // ----- end of function HistTool::WriteTH1 -----
// === FUNCTION ============================================================
// Name: HistTool::DrawTH1
// Description: Save the TH1
// ===========================================================================
int HistTool::DrawTH1()
{
TCanvas *c1 = new TCanvas("TH1", "Canvas for TH1", 600, 500);
for(std::map<std::string, TH1D*>::iterator it=HisMap.begin();
it!=HisMap.end(); it++)
{
c1->cd();
c1->Clear();
it->second->Draw();
TString picname = prefix + "_" + it->second->GetName() + ".png";
c1->Print(picname);
}
delete c1;
return 1;
} // ----- end of function HistTool::DrawTH1 -----
// === FUNCTION ============================================================
// Name: HistTool::AddTProC
// Description:
// ===========================================================================
int HistTool::AddTProC (const std::string name, const std::string title,
const std::string xlabel, const std::string ylabel,
Int_t nxbins, Axis_t xmin, Axis_t xmax,
Int_t logx, Int_t logy)
{
for (Long_t i = 0; i < CutSize; ++i)
{
TString mapname = name+"_"+i;
TString maptitle = title+" ("+order.at(i)+")";
AddTPro(mapname.Data(), maptitle.Data(), xlabel, ylabel, nxbins, xmin, xmax, logx, logy);
}
return 1;
} // ----- end of function HistTool::AddTProC -----
// === FUNCTION ============================================================
// Name: HistTool::AddTProC
// Description:
// ===========================================================================
int HistTool::AddTProC (const std::string name, const std::string title,
Int_t nxbins, Axis_t xmin, Axis_t xmax)
{
for (Long_t i = 0; i < CutSize; ++i)
{
TString mapname = name+"_"+i;
TString maptitle = title+" ("+order.at(i)+")";
AddTPro(mapname.Data(), maptitle.Data(), nxbins, xmin, xmax);
}
return 1;
} // ----- end of function HistTool::AddTProC -----
// === FUNCTION ============================================================
// Name: HistTool::AddTPro
// Description:
// ===========================================================================
TProfile* HistTool::AddTPro (const std::string name, const std::string title,
const std::string xlabel, const std::string ylabel,
Int_t nxbins, Axis_t xmin, Axis_t xmax,
Int_t logx, Int_t logy)
{
TString xlb, ylb;
if (logx) xlb = "log_"+xlabel;
else xlb = xlabel;
if (logy) ylb = "log_"+ylabel;
else ylb = ylabel;
TString Title = title +";"+xlb+";"+ylb;
ProMap[name.c_str()] = fs->make<TProfile>(name.c_str(), Title, nxbins, xmin, xmax, "s");
return ProMap[name.c_str()];
} // ----- end of function HistTool::AddTProC -----
// === FUNCTION ============================================================
// Name: HistTool::AddTPro
// Description:
// ===========================================================================
TProfile* HistTool::AddTPro(TProfile* pro)
{
ProMap[pro->GetName()] = pro;
return ProMap[pro->GetName()];
} // ----- end of function HistTool::AddTPro -----
// === FUNCTION ============================================================
// Name: HistTool::AddTPro
// Description:
// ===========================================================================
TProfile* HistTool::AddTPro (const std::string name, const std::string title,
Int_t nxbins, Axis_t xmin, Axis_t xmax)
{
ProMap[name.c_str()] = fs->make<TProfile>(name.c_str(), title.c_str(), nxbins, xmin, xmax, "s");
return ProMap[name.c_str()];
} // ----- end of function HistTool::AddTPro -----
// === FUNCTION ============================================================
// Name: HistTool::::FillTPro
// Description:
// ===========================================================================
int HistTool::FillTPro(int Ncut, std::string HisName, double xvalue, double yvalue, double weight)
{
TString mapname = HisName+"_"+static_cast<Long_t>(Ncut);
if (ProMap.find(mapname.Data()) == ProMap.end())
return 0;
if (weight != -999.)
ProMap[mapname.Data()]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
ProMap[mapname.Data()]->Fill(xvalue, yvalue, HWeight);
else
ProMap[mapname.Data()]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTPro -----
int HistTool::FillTPro(int Ncut, std::string HisName, int xvalue, double yvalue, double weight)
{
TString mapname = HisName+"_"+static_cast<Long_t>(Ncut);
if (ProMap.find(mapname.Data()) == ProMap.end())
return 0;
if (weight != -999.)
ProMap[mapname.Data()]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
ProMap[mapname.Data()]->Fill(xvalue, yvalue, HWeight);
else
ProMap[mapname.Data()]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTPro -----
int HistTool::FillTPro(std::string HisName, double xvalue, double yvalue, double weight)
{
if (ProMap.find(HisName) == ProMap.end())
return 0;
if (weight != -999.)
ProMap[HisName]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
ProMap[HisName]->Fill(xvalue, yvalue, HWeight);
else
ProMap[HisName]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTPro -----
int HistTool::FillTPro(std::string HisName, int xvalue, double yvalue, double weight)
{
if (ProMap.find(HisName) == ProMap.end())
return 0;
if (weight != -999.)
ProMap[HisName]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
ProMap[HisName]->Fill(xvalue, yvalue, HWeight);
else
ProMap[HisName]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTPro -----
// === FUNCTION ============================================================
// Name: HistTool::WriteTPro
// Description: Save the TPro
// ===========================================================================
int HistTool::WriteTPro()
{
OutFile->cd();
for(std::map<std::string, TProfile*>::iterator it=ProMap.begin();
it!=ProMap.end(); it++)
{
it->second->Write();
}
return 1;
} // ----- end of function HistTool::WriteTPro -----
// === FUNCTION ============================================================
// Name: HistTool::DrawTPro
// Description: Save the TPro
// ===========================================================================
int HistTool::DrawTPro()
{
TCanvas *c1 = new TCanvas("TPro", "Canvas for TPro", 600, 500);
for(std::map<std::string, TProfile*>::iterator it=ProMap.begin();
it!=ProMap.end(); it++)
{
c1->cd();
c1->Clear();
it->second->Draw();
TString picname = prefix + "_" + it->second->GetName() + ".png";
c1->Print(picname);
}
delete c1;
return 1;
} // ----- end of function HistTool::DrawTPro -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH2C
// Description:
// ===========================================================================
int HistTool::AddTH2C (const std::string name, const std::string title,
const std::string xlabel, const std::string ylabel,
Int_t nxbins, Axis_t xmin, Axis_t xmax,
Int_t nybins, Axis_t ymin, Axis_t ymax,
Int_t logx, Int_t logy)
{
for (Long_t i = 0; i < CutSize; ++i)
{
TString mapname = name+"_"+i;
TString xlb, ylb;
if (logx) xlb = "log_"+xlabel;
else xlb = xlabel;
if (logy) ylb = "log_"+ylabel;
else ylb = ylabel;
TString maptitle = title+" ("+order.at(i)+")" + ";" + xlb + ";" + ylb;
HisMap2D[mapname.Data()] = fs->make<TH2D>(mapname.Data(), maptitle.Data(), nxbins,
xmin, xmax, nybins, ymin, ymax);
}
return 1;
} // ----- end of function HistTool::AddTH2C -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH2C
// Description:
// ===========================================================================
int HistTool::AddTH2C (const std::string name, const std::string title,
Int_t nxbins, Axis_t xmin, Axis_t xmax, Int_t nybins, Axis_t ymin, Axis_t ymax)
{
for (Long_t i = 0; i < CutSize; ++i)
{
TString mapname = name+"_"+i;
TString maptitle = title+" ("+order.at(i)+")";
HisMap2D[mapname.Data()] = fs->make<TH2D>(mapname.Data(), maptitle.Data(),
nxbins, xmin, xmax, nybins, ymin, ymax);
//HisMap2D[mapname.Data()] = result.AddHist1D(mapname.Data(),
//maptitle.Data(), xlabel.c_str(), ylabel.c_str(), nxbins, xmin, xmax);
}
return 1;
} // ----- end of function HistTool::AddTH2C -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH2
// Description:
// ===========================================================================
TH2D* HistTool::AddTH2 (const std::string name, const std::string title,
const std::string xlabel, const std::string ylabel,
Int_t nxbins, Axis_t xmin, Axis_t xmax,
Int_t nybins, Axis_t ymin, Axis_t ymax,
Int_t logx, Int_t logy)
{
TString xlb, ylb;
if (logx) xlb = "log_"+xlabel;
else xlb = xlabel;
if (logy) ylb = "log_"+ylabel;
else ylb = ylabel;
TString Title = title +";"+xlb+";"+ylb;
HisMap2D[name.c_str()] = fs->make<TH2D>(name.c_str(), Title.Data(),
nxbins, xmin, xmax, nybins, ymin, ymax);
return HisMap2D[name.c_str()];
} // ----- end of function HistTool::AddTH2C -----
// === FUNCTION ============================================================
// Name: HistTool::AddTH2
// Description:
// ===========================================================================
TH2D* HistTool::AddTH2 (const std::string name, const std::string title,
Int_t nxbins, Axis_t xmin, Axis_t xmax, Int_t nybins, Axis_t ymin, Axis_t ymax)
{
HisMap2D[name.c_str()] = fs->make<TH2D>(name.c_str(), title.c_str(), nxbins,
xmin, xmax , nybins, ymin, ymax);
return HisMap2D[name.c_str()];
} // ----- end of function HistTool::AddTH2 -----
// === FUNCTION ============================================================
// Name: HistTool::FillTH2
// Description:
// ===========================================================================
int HistTool::FillTH2(int Ncut, std::string HisName, double xvalue, double yvalue, double weight)
{
TString mapname = HisName+"_"+static_cast<Long_t>(Ncut);
if (HisMap2D.find(mapname.Data()) == HisMap2D.end())
return 0;
if (weight != -999.)
HisMap2D[mapname.Data()]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
HisMap2D[mapname.Data()]->Fill(xvalue, yvalue, HWeight);
else
HisMap2D[mapname.Data()]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTH2 -----
int HistTool::FillTH2(int Ncut, std::string HisName, int xvalue, double yvalue, double weight)
{
TString mapname = HisName+"_"+static_cast<Long_t>(Ncut);
if (HisMap2D.find(mapname.Data()) == HisMap2D.end())
return 0;
if (weight != -999.)
HisMap2D[mapname.Data()]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
HisMap2D[mapname.Data()]->Fill(xvalue, yvalue, HWeight);
else
HisMap2D[mapname.Data()]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTH2 -----
int HistTool::FillTH2(std::string HisName, int xvalue, double yvalue, double weight)
{
if (HisMap2D.find(HisName) == HisMap2D.end())
return 0;
if (weight != -999.)
HisMap2D[HisName]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
HisMap2D[HisName]->Fill(xvalue, yvalue, HWeight);
else
HisMap2D[HisName]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTH2 -----
int HistTool::FillTH2(std::string HisName, double xvalue, double yvalue, double weight)
{
if (HisMap2D.find(HisName) == HisMap2D.end())
return 0;
if (weight != -999.)
HisMap2D[HisName]->Fill(xvalue, yvalue, weight);
else if (HWeight != -999.)
HisMap2D[HisName]->Fill(xvalue, yvalue, HWeight);
else
HisMap2D[HisName]->Fill(xvalue, yvalue);
return 1;
} // ----- end of function HistTool::::FillTH2 -----
// === FUNCTION ============================================================
// Name: HistTool::WriteTH2
// Description: Save the TH2
// ===========================================================================
int HistTool::WriteTH2()
{
OutFile->cd();
for(std::map<std::string, TH2D*>::iterator it=HisMap2D.begin();
it!=HisMap2D.end(); it++)
{
it->second->Write();
}
return 1;
} // ----- end of function HistTool::WriteTH2 -----
// === FUNCTION ============================================================
// Name: HistTool::DrawTH2
// Description: Save the TH2
// ===========================================================================
int HistTool::DrawTH2()
{
TCanvas *c1 = new TCanvas("TH2", "Canvas for TH2", 600, 500);
for(std::map<std::string, TH2D*>::iterator it=HisMap2D.begin();
it!=HisMap2D.end(); it++)
{
c1->cd();
c1->Clear();
//it->second->SetMarkerStyle(7);
//it->second->SetMarkerSize(1.5);
it->second->Draw();
TString picname = prefix + "_" + it->second->GetName() + ".png";
c1->Print(picname);
}
delete c1;
return 1;
} // ----- end of function HistTool::DrawTH2 -----
// === FUNCTION ============================================================
// Name: HistTool::SetWeight
// Description:
// ===========================================================================
bool HistTool::SetWeight(double weight)
{
HWeight = weight;
return true;
} // ----- end of function HistTool::SetWeight -----
// === FUNCTION ============================================================
// Name: HistTool::CalEfficiency
// Description: /* cursor */
// ===========================================================================
bool HistTool::CalEfficiency(std::string output, std::string Numerator, std::string DeNumerator)
{
HisMap[output]->Divide(HisMap[Numerator], HisMap[DeNumerator]);
return true;
} // ----- end of function HistTool::CalEfficiency -----
| 36.133858 | 98 | 0.486293 | [
"vector"
] |
7042c6c33c20926fe98d00f04afc91ab18e08e28 | 6,418 | cpp | C++ | ddot/alignOntology/alignOntology.cpp | pupster90/ddot2 | 1952bff30383b35dff72b332592e1471201d40f3 | [
"MIT"
] | 15 | 2018-07-11T07:59:53.000Z | 2022-01-10T20:20:42.000Z | ddot/alignOntology/alignOntology.cpp | pupster90/ddot2 | 1952bff30383b35dff72b332592e1471201d40f3 | [
"MIT"
] | 6 | 2018-10-23T11:35:49.000Z | 2022-02-09T00:11:50.000Z | ddot/alignOntology/alignOntology.cpp | pupster90/ddot2 | 1952bff30383b35dff72b332592e1471201d40f3 | [
"MIT"
] | 9 | 2018-05-15T06:15:12.000Z | 2022-01-10T20:20:44.000Z | #include <iostream>
#include <time.h>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <stdlib.h>
#include "graph.h"
#include "alignmentUtils.h"
int main(int argc, char* argv[]) {
if (argc < 5) {
cout << "Needs 4 arguments - ontologyComputed, referenceOntology, minimum similarity value accepted, version of semantic verification (options are 'criss_cross', 'strict_hierarchy', 'sib_sib', and 'none')" << endl;
cout << "Optional 5th argument - allow multiple mappings of same node when scores are identical. 1 will allow multiple mappings, 0 will not (default is 0 if no 5th argument is given" << endl;
cout << "Optional 6th argument - treat genes as terms. Default is 1 (yes). 0 is no." << endl;
cout << "Optional 7th argument - category name of terminal nodes (i.e. gene, patient, etc.). Default is gene" << endl;
cout << "similarity value can range from 0 to 1 (1 means nodes in ontology are identical)" << endl;
return 0;
}
map<string, unsigned> geneNamesToIDs;
string ontology1 = argv[1];
string ontology2 = argv[2];
string terminalName = "gene";
if (argc >= 8) {
terminalName = argv[7];
}
cout << "Getting ontology 1" << endl;
DAGraph g1(ontology1, geneNamesToIDs, true, terminalName);
cout << "Getting ontology 2" << endl;
DAGraph g2(ontology2, geneNamesToIDs, true, terminalName);
bool allowMultiples = false;
if ((argc >= 6) && (atoi(argv[5]) == 1)) {
allowMultiples = true;
}
bool genesAsTerms = true;
if ((argc >=7) && (atoi(argv[6]) == 0)) {
genesAsTerms = false;
}
vector<string> geneIDsToNames(geneNamesToIDs.size());
for (map<string, unsigned>::iterator it = geneNamesToIDs.begin(); it != geneNamesToIDs.end(); ++it) {
geneIDsToNames[it->second] = it->first;
}
float threshold = 0.01;
float minSimilarityForPrealignment = atof(argv[3]);
cout << "Minimum similarity value accepted: " << minSimilarityForPrealignment << endl;
int verificationMode = 0;
string verMode = argv[4];
if (verMode == "criss_cross") {
cout << "No parent child criss cross allowed" << endl;
verificationMode = 1;
} else if (verMode == "strict_hierarchy") {
cout << "Strict hierarchy maintained in mappings" << endl;
verificationMode = 2;
} else if (verMode == "none") {
cout << "No hierarchy information enforced in mappings" << endl;
} else if (verMode == "sib_sib") {
cout << "No parent child criss cross allowed and no sibling-sibling to parent-child mapping allowed" << endl;
verificationMode = 3;
} else {
cout << "Options for semantic verification (argument 4) are 'criss_cross', 'strict_hierarchy', 'sib_sib', and 'none'" << endl;
return 1;
}
cout << "Terms in first ontology: " << g1.numNodes() << "\t" << "Nodes in second ontology: " << g2.numNodes() << endl;
boost::numeric::ublas::matrix<float> extSim(g1.numNodes(),g2.numNodes());
cout << "Calculating extsim" << endl;
time_t start, end;
time (&start);
alignmentUtils::calculateExtSim(extSim, g1, g2);
time (&end);
double dif = difftime(end,start);
cout << "calculateExtSim took " << dif << " seconds" << endl;
boost::numeric::ublas::matrix<float> lastSim = extSim;
//removalListType removalList(g1.numNodes(), g2.numNodes());
vector< alignmentType > verifiedAlignments;
alignmentType finalAlignment;
//boost::numeric::ublas::matrix<bool> foreverRemoved(g1.numNodes(), g2.numNodes());
// Mike Yu edit: limit the number of iterations
int max_iter = 10;
int curr_iter = 1;
cout << "Max iterations: " << max_iter << endl;
bool repeatAlignmentFound = false;
while (!repeatAlignmentFound) {
// Mike Yu: print out iteration number
//cout << "Starting iteration" << endl;
cout << "Starting iteration " << curr_iter << endl;
boost::numeric::ublas::matrix<float> simMat(extSim);
cout << "Adding relSim to simMat" << endl;
time (&start);
alignmentUtils::addRelSimToSimMat(simMat, lastSim, g1, g2, genesAsTerms);
time (&end);
double dif = difftime(end,start);
cout << "addRelSimToSimMat took " << dif << " seconds" << endl;
//for (int i = 0; i < relSim.size1(); ++i) {
// cout << g1.getName(i) << "\t" << extSim(i,i) << "\t" << relSim(i,i) << endl;
//}
//return 0;
alignmentType alignment;
time(&start);
cout << "Aligning" << endl;
alignmentUtils::getAlignment(simMat,alignment,threshold,
g1,g2,minSimilarityForPrealignment, verificationMode, allowMultiples);
time (&end);
dif = difftime(end,start);
cout << "Alignment took " << dif << " seconds" << endl;
cout << "Got an alignment" << endl;
for (vector<alignmentType>::iterator it = verifiedAlignments.begin();
it != verifiedAlignments.end(); ++it) {
if (alignment == *it) {
repeatAlignmentFound = true;
finalAlignment = alignment;
cout << "Matched" << endl;
}
}
lastSim = simMat;
/*
for (int i = 0; i < lastSim.size1(); ++i) {
for (int j = 0; j < lastSim.size2(); ++j) {
if (removalList.isInRemovalList(make_pair(i,j))) {
foreverRemoved(i,j) = true;
}
}
}
*/
verifiedAlignments.push_back(alignment);
// End early
//repeatAlignmentFound = true;
//finalAlignment = verifiedAlignment;
//cout << "Matched" << endl;
// Mike Yu edit: limit the number of iterations
curr_iter += 1;
if (curr_iter > max_iter) {
repeatAlignmentFound = true;
finalAlignment = alignment;
cout << "Matched" << endl;
}
}
for (alignmentType::iterator it = finalAlignment.begin(); it != finalAlignment.end(); ++it) {
if (!g1.isGene(it->first)) {
cout << g1.getName(it->first) << "\t" << g2.getName(it->second) << "\t" << lastSim(it->first,it->second) << endl;
}
/* THE BELOW CODE WILL PRINT DESCENDENTS OF EACH TERM
cout << g1.getName(it->first) << "\t" << g2.getName(it->second) << "\t" << lastSim(it->first,it->second) << "\t";
for (set<unsigned>::iterator genesIt = g1.getGenesBegin(it->first); genesIt != g1.getGenesEnd(it->first); ++genesIt) {
cout << geneIDsToNames[*genesIt] << ",";
}
cout << "\t";
for (set<unsigned>::iterator genesIt = g2.getGenesBegin(it->second); genesIt != g2.getGenesEnd(it->second); ++genesIt) {
cout << geneIDsToNames[*genesIt] << ",";
}
cout << endl;
*/
}
return 1;
}
| 36.259887 | 218 | 0.634933 | [
"vector"
] |
70484f06c2ce43194adeb18ed007ea12f21556c6 | 13,130 | hxx | C++ | src/engine/ivp/ivp_collision/ivp_compact_ledge_solver.hxx | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/engine/ivp/ivp_collision/ivp_compact_ledge_solver.hxx | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/engine/ivp/ivp_collision/ivp_compact_ledge_solver.hxx | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | // Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
#ifdef SUN4
# define IVP_STATIC_INLINE inline
# define IVP_STATIC
#else
# define IVP_STATIC_INLINE static inline
# define IVP_STATIC static
#endif
#define IVP_MAGIC_INERTIA_RADIUS 100.0f // for ill calculated inertias use this default radius
#ifndef _IVP_CACHE_OBJECT_INCLUDED
# include <ivp_cache_object.hxx>
#endif
#ifndef _IVP_CACHE_LEDGE_POINT_INCLUDED
# include <ivp_cache_ledge_point.hxx>
#endif
class IVP_Cache_Ball;
class IVP_Unscaled_QR_Result {
public:
IVP_FLOAT checks[3]; // check[0] >0 -> inside this
IVP_FLOAT scale;
IVP_BOOL is_outside() {
unsigned int a = *((int *) &checks[0]);
unsigned int b = *((int *) &checks[1]);
unsigned int c = *((int *) &checks[2]);
unsigned int sign_bit = a | b | c;
return IVP_BOOL(sign_bit >> 31);
}
};
class IVP_Unscaled_S_Result {
public:
IVP_FLOAT checks[2];
IVP_BOOL is_outside() {
unsigned int a = *((int *) &checks[0]);
unsigned int b = *((int *) &checks[1]);
unsigned int sign_bit = a | b;
return IVP_BOOL(sign_bit >> 31);
}
};
class IVP_Unscaled_KK_Result {
public:
IVP_FLOAT checks_K[2]; // >0 means L projected onto K, K->next is on K->next side of K
IVP_FLOAT checks_L[2];
IVP_BOOL is_outside_K() {
unsigned int a = *((int *) &checks_K[0]);
unsigned int b = *((int *) &checks_K[1]);
unsigned int sign_bit = a | b;
return IVP_BOOL(sign_bit >> 31);
}
IVP_BOOL is_outside_L() {
unsigned int a = *((int *) &checks_L[0]);
unsigned int b = *((int *) &checks_L[1]);
unsigned int sign_bit = a | b;
return IVP_BOOL(sign_bit >> 31);
}
};
class IVP_KK_Input {
public:
const IVP_U_Float_Point *L_Los[2];
IVP_U_Point K_Los[2];
IVP_U_Point Kvec_Los;
IVP_U_Point Lvec_Los;
const IVP_Compact_Edge *K;
const IVP_Compact_Edge *L;
IVP_Cache_Ledge_Point *cache_K;
IVP_Cache_Ledge_Point *cache_L;
IVP_U_Point cross_KL_Los; // crossproduct of K vec and L vec
IVP_KK_Input(const IVP_Compact_Edge *K, const IVP_Compact_Edge *L, IVP_Cache_Ledge_Point *m_cache_K,
IVP_Cache_Ledge_Point *m_cache_L);
IVP_DOUBLE calc_quad_distance_edge_edge();
};
class IVP_Compact_Ledge_Solver {
int dummy; // there are no zero length classes in some C++ compilers
public:
#ifdef DEBUG
IVP_STATIC IVP_BOOL check_ledge(const IVP_Compact_Ledge *c_ledge); // for debugging
#endif
/********************************************************************************
* Name: calc s_vals
* Description: find the point on an edge with the shortest distance to a given other point
* and return the position of that point on the edge as a relative
* value between 0 and 1: 0 means projected point is identical to first point of edge
* 1 means projected point is identical to second point od the edge
********************************************************************************/
IVP_STATIC_INLINE IVP_DOUBLE
calc_dot_product_vec_dot_connection(const IVP_U_Point *vector, const IVP_U_Float_Point *s1,
const IVP_U_Float_Point *e1);
IVP_STATIC IVP_DOUBLE calc_s_val(const IVP_Compact_Edge *edge, const IVP_U_Point *p_world,
IVP_Cache_Ledge_Point *m_cache_edge); // calcs intersect pos
IVP_STATIC void calc_unscaled_s_val_K_space(const IVP_Compact_Ledge *c_ledge, const IVP_Compact_Edge *edge,
const IVP_U_Point *P_Kos, IVP_Unscaled_S_Result *result);
/********************************************************************************
* Name: calc qr_vals
* Description: find the point on an area with the shortest distance to a given other point
* and return the position of that point on the edge as a relative
* values between 0 and 1:
* q, r refer to
* q=0, r=0 -> projected_point (pp) == this->next
* q=1, r=0 -> pp == this
* q=0, r=1 -> pp == this->prev
* q+r=1 -> pp == [this,this->prev]
********************************************************************************/
IVP_STATIC void calc_qr_vals(const IVP_Compact_Edge *e_tri, const IVP_Compact_Edge *p,
IVP_DOUBLE *out_q, IVP_DOUBLE *out_r,
IVP_Cache_Ledge_Point *m_cache_e_tri, IVP_Cache_Ledge_Point *m_cache_p);
IVP_STATIC void calc_qr_vals(const IVP_Compact_Edge *e_tri, const IVP_U_Point *p_world,
IVP_DOUBLE *out_q, IVP_DOUBLE *out_r,
IVP_Cache_Ledge_Point *m_cache_e_tri);
IVP_STATIC void calc_unscaled_qr_vals_F_space(const IVP_Compact_Ledge *c_ledge, const IVP_Compact_Edge *tri,
const IVP_U_Point *object_point,
IVP_Unscaled_QR_Result *result);
/********************************************************************************
* Name: calc calc_unscaled_KK_vals
* Description: find the points on two edges with the shortest distance to each other
* and return the position of that points on the edges as a relative
* value between 0 and 1: 0 means projected point is identical to first point of edge
* 1 means projected point is identical to second point od the edge
********************************************************************************/
IVP_STATIC IVP_RETURN_TYPE calc_unscaled_KK_vals(const IVP_KK_Input &in, IVP_Unscaled_KK_Result *result);
/********************************************************************************
* Name: hesse vectors of an area
********************************************************************************/
IVP_STATIC void
calc_hesse_normized_AT(const IVP_Compact_Edge *edge, IVP_Cache_Ledge_Point *cc, IVP_U_Hesse *hesse_out_ws);
IVP_STATIC void
calc_hesse_object(const IVP_Compact_Edge *edge, const IVP_Compact_Ledge *ledge, IVP_U_Hesse *hesse_out_os);
IVP_STATIC void calc_hesse_vec_object_not_normized(const IVP_Compact_Edge *edge, const IVP_Compact_Ledge *ledge,
IVP_U_Point *out_vec);
IVP_STATIC void calc_hesse_vec_object_not_normized(const IVP_Compact_Edge *edge, const IVP_Compact_Ledge *ledge,
IVP_U_Float_Point *out_vec);
/********************************************************************************
* Name: minimize_on_other_side
* Description: Pierce through convex object and
* traverse triangles until valid q/r values (or valid term.len?).
* Returned edge represents the triangle found.
********************************************************************************/
IVP_STATIC const IVP_Compact_Edge *
minimize_on_other_side(const IVP_Compact_Edge *edge, const IVP_U_Point *partner_this_os);
/********************************************************************************
* Name: various functions to get the coordinates of a point
********************************************************************************/
IVP_STATIC void
give_world_coords_AT(const IVP_Compact_Edge *edge, IVP_Cache_Ledge_Point *clp, IVP_U_Point *p_ws_out);
IVP_STATIC inline const IVP_Compact_Poly_Point *
give_object_coords(const IVP_Compact_Edge *edge, IVP_Cache_Ledge_Point *clp);
IVP_STATIC inline const IVP_Compact_Poly_Point *
give_object_coords(const IVP_Compact_Edge *edge, const IVP_Compact_Ledge *ledge);
IVP_STATIC void calc_pos_other_space(const IVP_Compact_Edge *P, IVP_Cache_Ledge_Point *m_cache_P,
IVP_Cache_Ledge_Point *m_cache_other_space, IVP_U_Point *res);
IVP_STATIC void transform_vec_other_space(const IVP_U_Point *dir_os, IVP_Cache_Ledge_Point *m_cache_dir,
IVP_Cache_Ledge_Point *m_cache_other_space, IVP_U_Point *res);
IVP_STATIC void transform_pos_other_space(const IVP_U_Float_Point *pos_os, IVP_Cache_Ledge_Point *m_cache_pos,
IVP_Cache_Ledge_Point *m_cache_other_space, IVP_U_Point *res);
/********************************************************************************
* Name: various functions to get the distance between two primitives
********************************************************************************/
IVP_STATIC IVP_DOUBLE quad_dist_edge_to_point_K_space(const IVP_Compact_Ledge *ledge_K, const IVP_Compact_Edge *K,
const IVP_U_Point *object_pos);
IVP_STATIC IVP_DOUBLE
calc_qlen_PP_P_space(const IVP_Compact_Ledge *P_ledge, const IVP_Compact_Edge *P, const IVP_U_Point *P_Pos);
IVP_STATIC IVP_DOUBLE
calc_qlen_PK_K_space(const IVP_U_Point *P_in_K_space, const IVP_Compact_Ledge *K_ledge, const IVP_Compact_Edge *K);
IVP_STATIC IVP_DOUBLE
calc_qlen_KK(const IVP_Compact_Edge *K, const IVP_Compact_Edge *L, IVP_Cache_Ledge_Point *m_cache_K,
IVP_Cache_Ledge_Point *m_cache_L);
IVP_STATIC IVP_DOUBLE
calc_qlen_PF_F_space(const IVP_Compact_Ledge *tri_ledge, const IVP_Compact_Triangle *tri, const IVP_U_Point *P_Fos);
/********************************************************************************
* Names: Convenience Routines
********************************************************************************/
IVP_STATIC void
get_all_ledges(const class IVP_Compact_Ledgetree_Node *node, IVP_U_BigVector<IVP_Compact_Ledge> *ledges_out);
IVP_STATIC void
get_all_ledges(const class IVP_Compact_Surface *surface, IVP_U_BigVector<IVP_Compact_Ledge> *ledges_out);
#ifdef HAVOK_MOPP
IVP_STATIC void get_all_ledges(const class IVP_Compact_Mopp *mopp, IVP_U_BigVector<IVP_Compact_Ledge> *ledges_out);
#endif // HAVOK_MOPP
/********************************************************************************
* Name: Bounding box and radius calculation
********************************************************************************/
private:
public:
IVP_STATIC void calc_bounding_box(const IVP_Compact_Ledge *c_ledge_in,
IVP_U_Point *min_extents_out, IVP_U_Point *max_extents_out);
IVP_STATIC void calc_radius_to_given_center(const IVP_Compact_Surface *c_surface_in, const IVP_U_Point *center_in,
IVP_DOUBLE *radius_out, IVP_DOUBLE *radius_dev_out = 0);
#ifdef HAVOK_MOPP
IVP_STATIC void calc_radius_to_given_center(const class IVP_Compact_Mopp *c_mopp_in, const IVP_U_Point *center_in,
IVP_DOUBLE *radius_out, IVP_DOUBLE *radius_dev_out = 0);
#endif // HAVOK_MOPP
IVP_STATIC void calc_radius_to_given_center(const IVP_Compact_Ledge *c_ledge,
const IVP_U_Point *center_in, // note does not init radius_out and radius_dev_out
IVP_DOUBLE *radius_out, IVP_DOUBLE *radius_dev_out = 0);
IVP_STATIC void calc_geom_center_and_radius(const IVP_Compact_Ledge *c_ledge_in,
IVP_U_Point *geom_center_out, IVP_DOUBLE *geom_radius_out);
IVP_STATIC void calc_mass_center_and_radius(const IVP_Compact_Ledge *c_ledge_in,
IVP_U_Point *mass_center_out, IVP_DOUBLE *mass_radius_out);
};
extern IVP_Compact_Ledge_Solver IVP_CLS;
const IVP_Compact_Poly_Point *
IVP_Compact_Ledge_Solver::give_object_coords(const IVP_Compact_Edge *edge, const IVP_Compact_Ledge *ledge) {
IVP_ASSERT(ledge == edge->get_compact_ledge());
int point_index = edge->get_start_point_index();
const IVP_Compact_Poly_Point *res = &ledge->get_point_array()[point_index];
return res;
}
const IVP_Compact_Poly_Point *
IVP_Compact_Ledge_Solver::give_object_coords(const IVP_Compact_Edge *edge, IVP_Cache_Ledge_Point *clp) {
IVP_ASSERT(clp->compact_ledge == edge->get_compact_ledge());
int point_index = edge->get_start_point_index();
const IVP_Compact_Poly_Point *res = &clp->compact_poly_points[point_index];
IVP_ASSERT ((int(res) & 15) == 0);
return res;
}
IVP_DOUBLE
IVP_Compact_Ledge_Solver::calc_dot_product_vec_dot_connection(const IVP_U_Point *vector, const IVP_U_Float_Point *s0,
const IVP_U_Float_Point *e0) {
IVP_DOUBLE ax = e0->k[0] - s0->k[0];
IVP_DOUBLE ay = e0->k[1] - s0->k[1];
IVP_DOUBLE az = e0->k[2] - s0->k[2];
IVP_DOUBLE bx = ax * vector->k[0];
IVP_DOUBLE by = ay * vector->k[1];
IVP_DOUBLE bz = az * vector->k[2];
return bx + by + bz;
}
| 43.190789 | 132 | 0.592993 | [
"object",
"vector"
] |
704be60f9c04f2118f0df55dbad00b393cd56820 | 2,064 | cpp | C++ | STL/NonModifyingAlgorithms/search-find_end.cpp | NibiruCpp/CppCert | 8de7fa61f0327a6f0ed6a0ee1663235e55277cca | [
"MIT"
] | 1 | 2016-10-27T15:06:34.000Z | 2016-10-27T15:06:34.000Z | STL/NonModifyingAlgorithms/search-find_end.cpp | NibiruCpp/CppCert | 8de7fa61f0327a6f0ed6a0ee1663235e55277cca | [
"MIT"
] | null | null | null | STL/NonModifyingAlgorithms/search-find_end.cpp | NibiruCpp/CppCert | 8de7fa61f0327a6f0ed6a0ee1663235e55277cca | [
"MIT"
] | null | null | null | /*
Both functions search a given range of elements (last, first) for the presence of sequence of elements
specified by iterators s_first and s_last. search() algorithm will return an iterator to the first
occurrence of the sequence s_first, s_last, whereas the find_end() function will return an iterator
to the last occurrence of the mentioned sequence. This is the only difference between both algorithms.
As should be noticed, both functions come in two versions. The second version must be provided with a
binary predicate used to perform a comparison between the two elements of the collection. The first
version uses the equality operator (==) for the same purpose. Below you can see a possible header of
such binary predicate:
template <class Element1, class Element2> bool f(Element1 e1, Element2 e2);
It can also be implemented as a functional object. It is important that this predicate does not
perform any modifications to the collection element, as it would be a violation of STL policy towards
the so-called non-modifying algorithms.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
void print(const int& value)
{
cout << value << " ";
}
int main()
{
int t[] = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 2};
vector<int> v1(t, t+18);
for_each(v1.begin(), v1.end(), print);
cout << endl;
int ts[] = {2, 3};
cout << "Searching for the sequence 2, 3 from the beginning:" << endl;
vector<int>::iterator found = search(v1.begin(), v1.end(), ts, ts+2);
if (found != v1.end())
cout << "Sequence 2, 3 has been found at position: " << distance(v1.begin(), found) << endl;
else
cout << "Sequence 2, 3 could not be found" << endl;
cout << endl;
cout << "Searching for sequence 2, 3 from the end" << endl;
found = find_end(v1.begin(), v1.end(), ts, ts+2);
if (found != v1.end())
cout << "Sequence 2, 3 has been found at position: " << distance(v1.begin(), found) << endl;
else
cout << "Sequence 2, 3 could not be found" << endl;
return 0;
} | 37.527273 | 103 | 0.70155 | [
"object",
"vector"
] |
704e241be726b12d25739d3a875d8a1b4286ad0f | 2,478 | cpp | C++ | src/module/HardwareIO/Muscle/Muscle.cpp | tayloryoung6396/FYP | 3ad6589fa67f89d5522510aeea7cfa433530d398 | [
"MIT"
] | null | null | null | src/module/HardwareIO/Muscle/Muscle.cpp | tayloryoung6396/FYP | 3ad6589fa67f89d5522510aeea7cfa433530d398 | [
"MIT"
] | null | null | null | src/module/HardwareIO/Muscle/Muscle.cpp | tayloryoung6396/FYP | 3ad6589fa67f89d5522510aeea7cfa433530d398 | [
"MIT"
] | null | null | null | #include "Muscle.hpp"
#include <stdint.h>
#include <iostream>
#include <vector>
#include "utility/io/gpio.hpp"
#include "utility/io/uart.hpp"
#include "utility/math/median.hpp"
namespace module {
namespace HardwareIO {
Muscle::Muscle(module::HardwareIO::muscle_t muscle)
: valve(muscle.valve)
, pressure_sensor(muscle.pressure_sensor)
, linear_pot(muscle.linear_pot)
, properties(muscle.properties) {
// Populate our previous position vector to all 0
for (int i = 0; i < 10; i++) {
prev_position.push_back(0);
}
utility::io::debug.out("Muscle Initialisation\n");
}
float Muscle::GetPosition() { return linear_pot.GetPosition(); }
void Muscle::UpdateVelocity() {
prev_position.erase(prev_position.begin());
prev_position.push_back(GetPosition());
}
float Muscle::GetVelocity() {
// https://en.wikipedia.org/wiki/Median_filter
// To demonstrate, using a window size of three with one entry immediately preceding and following each entry, a
// median filter will be applied to the following simple 1D signal:
// TODO Fix this
const int w = 1; // This is the window size for the medians either side of the center value
std::vector<float> velocity;
for (int i = 0; i < 10; i++) {
std::vector<float> position;
for (int j = -w; j < w; j++) {
if (i + j < 0) {
j++;
}
else if (i + j > prev_position.size()) {
break;
}
position.push_back(prev_position[i + j]);
}
velocity.push_back(utility::math::median(position));
position.clear();
}
// Now the discrete difference needs to be calculated and returned
float Sampling_time3 = 0.05; // 0.01 T_s
float vel_avg = 0;
for (int v = 1; v < velocity.size(); v++) {
vel_avg += (velocity[v] - velocity[v - 1]) / Sampling_time3;
}
// return (vel_avg / (velocity.size() - 1));
return (0);
}
float Muscle::GetPressure() { return pressure_sensor.GetPressure(); }
void Muscle::SetValveState(bool state) { valve = state; }
bool Muscle::GetValveState() { return valve; }
} // namespace HardwareIO
} // namespace module | 33.04 | 121 | 0.560533 | [
"vector"
] |
704f4dc07647dc8f830d13c51bf47291913061ed | 1,227 | cpp | C++ | Sorting and Searching/Factory_Machines.cpp | hamzahasbi/my-cses | fe5a92b9ff126d6a4fbd7b4c61538f32c9ee4f80 | [
"MIT"
] | 3 | 2021-03-28T22:29:20.000Z | 2021-03-29T13:25:54.000Z | Sorting and Searching/Factory_Machines.cpp | hamzahasbi/my-cses | fe5a92b9ff126d6a4fbd7b4c61538f32c9ee4f80 | [
"MIT"
] | null | null | null | Sorting and Searching/Factory_Machines.cpp | hamzahasbi/my-cses | fe5a92b9ff126d6a4fbd7b4c61538f32c9ee4f80 | [
"MIT"
] | null | null | null | /*
Author: Hamza Hasbi
@Copyrights: __Morty
*/
#include<bits/stdc++.h>
#ifdef ONLINE_JUDGE
#pragma GCC optimize("O3")
#endif
#define ll long long
#define ld long double
#define ull unsigned long long
#define uld unsigned long double
#define ud unsigned double
#define uf unsigned float
#define pi 2 * acos(0.0)
#define module cin.ignore()
//inline long long lcm(ll a,ll b) {return a * b / __gcd(a,b);}
//inline long long gcd(ll a,ll b) {return 1LL * b == 0 ? a : gcd(1LL*b, a * 1LL % b * 1LL);}
inline bool IsPowerOfTwo (ull x){ return (x != 0) && ((x & (x - 1)) == 0);}
using namespace std;
void READ() {
#ifndef ONLINE_JUDGE
freopen("IO/Input.in", "r", stdin);
#endif
}
vector<ll> v;
int n;
ll t;
ll sum(ll x) {
ll res = 0LL;
for(ll item : v) {
res += x / item;
if (res > t) break;
}
return res;
}
int main(){
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie();
cin >> n;
cin >> t;
v.resize(n);
for(ll &item : v) cin>>item;
ll mx = 1e18;
ll mn = 0;
while (mn <= mx) {
ll mid = mn + (mx - mn) / 2;
ll s = sum(mid);
if(s >= t) {
mx = mid - 1;
} else {
mn = mid + 1;
}
}
cout << mn << endl;
return 0;
} | 17.528571 | 92 | 0.577832 | [
"vector"
] |
70529ab71cf72796ee5a8656846f910030d8cb03 | 944 | cpp | C++ | src/Renderer/Buffer.cpp | kettlekern/raytracer-kettlekern | 27a8df15a2e5b629b7491e5852d83ef273eed7cb | [
"MIT"
] | null | null | null | src/Renderer/Buffer.cpp | kettlekern/raytracer-kettlekern | 27a8df15a2e5b629b7491e5852d83ef273eed7cb | [
"MIT"
] | null | null | null | src/Renderer/Buffer.cpp | kettlekern/raytracer-kettlekern | 27a8df15a2e5b629b7491e5852d83ef273eed7cb | [
"MIT"
] | null | null | null | #include "Buffer.h"
using namespace std;
void Buffer::push_back(FragmentOutput & frag) {
fragBuffer.push_back(frag);
}
//This functions leaks memory, but since it is only ever called at the end of a program I don't have to care for now
unsigned char* Buffer::toArray(){
//make_shared does not support arrays until c++17 and you need an external library for it then, so we will just manage the memory ourselves for now
unsigned char* colArray = (unsigned char*)malloc(width*height*3);
//Could also make a vector with the colors as elements, but this is more efficent.
for (int i = 0; i < width*height; i++) {
//This assumes that the color in fragments is scaled from 0-1, may change later.
colArray[3 * i] = (unsigned char) (fragBuffer[i].getColor().r * 255);
colArray[3 * i + 1] = (unsigned char)(fragBuffer[i].getColor().g * 255);
colArray[3 * i + 2] = (unsigned char)(fragBuffer[i].getColor().b * 255);
}
return colArray;
}
| 42.909091 | 148 | 0.709746 | [
"vector"
] |
705cad7694c64ffb4aeff8cd643e1aeb9a3cd8c0 | 717 | cpp | C++ | LeetCode/Problems/Algorithms/#1429_FirstUniqueNumber_sol1_map_660ms_82.8MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#1429_FirstUniqueNumber_sol1_map_660ms_82.8MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#1429_FirstUniqueNumber_sol1_map_660ms_82.8MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class FirstUnique {
private:
queue<int> q;
map<int, int> cnt;
public:
FirstUnique(vector<int>& nums) {
for(int num: nums){
q.push(num);
++cnt[num];
}
}
int showFirstUnique() {
while(!q.empty() && cnt[q.front()] >= 2){
q.pop();
}
if(!q.empty()){
return q.front();
}
return -1;
}
void add(int value) {
q.push(value);
++cnt[value];
}
};
/**
* Your FirstUnique object will be instantiated and called as such:
* FirstUnique* obj = new FirstUnique(nums);
* int param_1 = obj->showFirstUnique();
* obj->add(value);
*/ | 20.485714 | 68 | 0.458856 | [
"object",
"vector"
] |
705eb16a8ce49d1f810cbf164207319d50473a81 | 5,292 | cc | C++ | tests/structure_test.cc | scylla-zpp-blas/linear-algebra | 823fe4085fdac992ed9695416d9a38d2cf6908d8 | [
"Apache-2.0"
] | 2 | 2021-09-07T18:36:37.000Z | 2021-10-01T19:23:30.000Z | tests/structure_test.cc | scylla-zpp-blas/linear-algebra | 823fe4085fdac992ed9695416d9a38d2cf6908d8 | [
"Apache-2.0"
] | 16 | 2020-12-19T18:10:34.000Z | 2021-06-14T18:06:17.000Z | tests/structure_test.cc | scylla-zpp-blas/linear-algebra | 823fe4085fdac992ed9695416d9a38d2cf6908d8 | [
"Apache-2.0"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include "scylla_blas/queue/scylla_queue.hh"
#include "scylla_blas/matrix.hh"
#include "scylla_blas/vector.hh"
#include "scylla_blas/config.hh"
#include "fixture.hh"
BOOST_FIXTURE_TEST_SUITE(structure_tests, scylla_fixture)
BOOST_AUTO_TEST_CASE(matrices)
{
scylla_blas::matrix<float>::init(session, 0, 5, 4, true);
auto matrix = scylla_blas::matrix<float>(session, 0);
auto matrix_2 = scylla_blas::matrix<float>(session, 0);
matrix.insert_value(1, 0, M_PI);
matrix.insert_value(1, 1, 42);
BOOST_REQUIRE_EQUAL(std::ceil(matrix.get_value(1, 0) * 10000), std::ceil(M_PI * 10000));
BOOST_REQUIRE_EQUAL(matrix.get_value(1, 1), 42);
matrix.insert_value(1, 0, M_PI);
BOOST_REQUIRE_EQUAL(std::ceil(matrix.get_value(1, 0) * 10000), std::ceil(M_PI * 10000));
matrix.insert_value(1, 1, 100);
BOOST_REQUIRE_EQUAL(std::ceil(matrix.get_value(1, 0) * 10000), std::ceil(M_PI * 10000));
BOOST_REQUIRE_EQUAL(matrix.get_value(1, 1), 100);
BOOST_REQUIRE_EQUAL(matrix.get_row_count(), 5);
BOOST_REQUIRE_EQUAL(matrix.get_column_count(), 4);
BOOST_REQUIRE_EQUAL(matrix.get_row_count(), matrix_2.get_row_count());
BOOST_REQUIRE_EQUAL(matrix.get_column_count(), matrix_2.get_column_count());
}
BOOST_AUTO_TEST_CASE(vector_segments)
{
auto vector_1 = scylla_blas::vector_segment<float>();
for (int i = 0; i < 10; i++) {
vector_1.emplace_back(i, 10);
}
std::cout << "Vec_1: ";
for (auto entry : vector_1) {
std::cout << "(" << entry.index << ": " << entry.value << "), ";
}
std::cout << std::endl;
auto vector_2 = scylla_blas::vector_segment<float>();
for (int i = 0; i < 5; i++) {
vector_2.emplace_back(i, (float)M_PI * i * i);
}
for (int i = 15; i < 20; i++) {
vector_2.emplace_back(i, (float) M_PI * i * i);
}
std::cout << "Vec_2: ";
for (auto entry : vector_2) {
std::cout << "(" << entry.index << ": " << entry.value << "), ";
}
std::cout << std::endl;
vector_1 *= M_E;
std::cout << "Vec_1 * e: ";
for (auto entry : vector_1) {
std::cout << "(" << entry.index << ": " << entry.value << "), ";
}
std::cout << std::endl;
vector_1 += vector_2;
std::cout << "Vec_1 * e + Vec_2: ";
for (auto entry : vector_1) {
std::cout << "(" << entry.index << ": " << entry.value << "), ";
}
std::cout << std::endl;
}
BOOST_AUTO_TEST_CASE(vectors)
{
/* init */
auto vector_1 = scylla_blas::vector<float>::init_and_return(session, 0, 2*DEFAULT_BLOCK_SIZE+1);
BOOST_REQUIRE_EQUAL(vector_1.get_segment_count(), 3);
/* update_values */
std::vector<scylla_blas::vector_value<float>> values_1;
for (int i = 1; i <= vector_1.get_length(); i++) {
values_1.emplace_back(i, M_PI);
}
vector_1.update_values(values_1);
BOOST_REQUIRE_EQUAL(std::ceil(vector_1.get_value(1) * 10000), std::ceil(M_PI * 10000));
BOOST_REQUIRE_EQUAL(std::ceil(vector_1.get_value(vector_1.get_length()) * 10000), std::ceil(M_PI * 10000));
/* get_segment */
auto seg_1 = vector_1.get_segment(2);
BOOST_REQUIRE_EQUAL(std::ceil(seg_1[0].value * 10000), std::ceil(M_PI * 10000));
BOOST_REQUIRE_EQUAL(std::ceil(seg_1[vector_1.get_block_size()-1].value * 10000), std::ceil(M_PI * 10000));
BOOST_REQUIRE_EQUAL(seg_1[0].index, 1);
BOOST_REQUIRE_EQUAL(seg_1[vector_1.get_block_size()-1].index, vector_1.get_block_size());
BOOST_REQUIRE_EQUAL(seg_1.size(), vector_1.get_block_size());
/* get_segment last */
auto seg_end = vector_1.get_segment(3);
BOOST_REQUIRE_EQUAL(seg_end.size(), 1);
/* update_value */
vector_1.update_value(1, M_E);
vector_1.update_value(2, 0);
BOOST_REQUIRE_EQUAL(std::ceil(vector_1.get_value(1) * 10000), std::ceil(M_E * 10000));
BOOST_REQUIRE_EQUAL(vector_1.get_value(2), 0);
/* update_segment */
scylla_blas::vector_segment<float> seg_2;
seg_2.emplace_back(1, M_E);
seg_2.emplace_back(2, 0);
vector_1.update_segment(2, seg_2);
BOOST_REQUIRE_EQUAL(std::ceil(vector_1.get_value(vector_1.get_block_size()+1) * 10000), std::ceil(M_E * 10000));
BOOST_REQUIRE_EQUAL(vector_1.get_value(vector_1.get_block_size()+2), 0);
BOOST_REQUIRE_EQUAL(vector_1.get_value(vector_1.get_block_size()+3), 0);
/* get_segment with zeros */
auto seg_3 = vector_1.get_segment(2);
BOOST_REQUIRE_EQUAL(std::ceil(seg_3[0].value * 10000), std::ceil(M_E * 10000));
BOOST_REQUIRE_EQUAL(seg_3[0].index, 1);
BOOST_REQUIRE_EQUAL(seg_3.size(), 1);
/* update_values overwriting */
std::vector<scylla_blas::vector_value<float>> values_2;
values_2.emplace_back(1, 0);
values_2.emplace_back(2, M_PI);
values_2.emplace_back(3, M_E);
vector_1.update_values(values_2);
BOOST_REQUIRE_EQUAL(vector_1.get_value(1), 0);
BOOST_REQUIRE_EQUAL(std::ceil(vector_1.get_value(2) * 10000), std::ceil(M_PI * 10000));
BOOST_REQUIRE_EQUAL(std::ceil(vector_1.get_value(3) * 10000), std::ceil(M_E * 10000));
/* clear */
vector_1.clear_value(2);
BOOST_REQUIRE_EQUAL(vector_1.get_value(2), 0);
vector_1.clear_segment(1);
BOOST_REQUIRE_EQUAL(vector_1.get_value(3), 0);
}
BOOST_AUTO_TEST_SUITE_END();
| 33.075 | 116 | 0.657596 | [
"vector"
] |
0ad537171f0ecadcbf72aface73c0ec490e8cc2b | 11,727 | cpp | C++ | TommyGun/Plugins/ImageEditor/ScreenImage/fScreenType.cpp | tonyt73/TommyGun | 2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36 | [
"BSD-3-Clause"
] | 34 | 2017-05-08T18:39:13.000Z | 2022-02-13T05:05:33.000Z | TommyGun/Plugins/ImageEditor/ScreenImage/fScreenType.cpp | tonyt73/TommyGun | 2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36 | [
"BSD-3-Clause"
] | null | null | null | TommyGun/Plugins/ImageEditor/ScreenImage/fScreenType.cpp | tonyt73/TommyGun | 2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36 | [
"BSD-3-Clause"
] | 6 | 2017-05-27T01:14:20.000Z | 2020-01-20T14:54:30.000Z | /*---------------------------------------------------------------------------
(c) 2004 Scorpio Software
19 Wittama Drive
Glenmore Park
Sydney NSW 2745
Australia
-----------------------------------------------------------------------------
$Workfile:: $
$Revision:: $
$Date:: $
$Author:: $
---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#include "pch.h"
#pragma hdrstop
//---------------------------------------------------------------------------
#include "..\..\..\SafeMacros.h"
#include "fScreenType.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "KSpinEdit"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
using namespace Scorpio;
using namespace ImageTypes;
//---------------------------------------------------------------------------
TfrmScreenType *frmScreenType = NULL;
//---------------------------------------------------------------------------
__fastcall TfrmScreenType::TfrmScreenType(TComponent* Owner)
: TForm(Owner)
, m_pImageManager(NULL)
{
}
//---------------------------------------------------------------------------
HRESULT __fastcall TfrmScreenType::Initialize(TZX_HPLUGIN PluginHandle, HINSTANCE hParentInstance)
{
RL_HRESULT(S_OK);
m_PluginHandle = PluginHandle;
m_ImageEditor.GetInterfaces(hParentInstance);
TTabSheet* pTabSheet = NULL;
m_ImageEditor.TypeAddTab(PluginHandle, "Screens", imgIcon->Picture->Bitmap, pTabSheet);
if (true == SAFE_PTR(pTabSheet))
{
panScreens->Parent = pTabSheet;
}
m_ImageEditor.TypeGetImageManager(PluginHandle, m_pImageManager);
return hResult;
}
//---------------------------------------------------------------------------
HRESULT __fastcall TfrmScreenType::Release(void)
{
return S_OK;
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::SetPalettes(TStrings* pPalettes, std::vector<String>& vSignatures)
{
cmbScreenFormat->Items->Clear();
cmbScreenFormat->Enabled = false;
if (true == SAFE_PTR(pPalettes) && 0 < pPalettes->Count)
{
// filter out the required palettes
for (int i = 0; i < pPalettes->Count; i++)
{
ZXPalette* pPalette = m_pImageManager->GetPalette(i);
if (true == SAFE_PTR(pPalette) && pPalette->IsImageTypeSupported(itScreen))
{
cmbScreenFormat->Items->Add(pPalette->Name);
m_vPaletteSignatures.push_back(vSignatures[i]);
}
}
cmbScreenFormat->Enabled = cmbScreenFormat->Items->Count > 0;
cmbScreenFormat->ItemIndex = 0;
/*cmbScreenFormat->Items->AddStrings(pPalettes);
m_vPaletteSignatures.assign(vSignatures.begin(), vSignatures.end());*/
}
edtScreenName->Enabled = (0 < pPalettes->Count);
lstScreenList->Enabled = edtScreenName->Enabled;
//edtScreenWidth->Enabled = cmdScreenAdd->Enabled;
//edtScreenHeight->Enabled = cmdScreenAdd->Enabled;
cmbScreenFormatChange(NULL);
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::RefreshList(void)
{
lstScreenList->ItemIndex = -1;
m_pImageManager->GetImageList(g_sTypeSignature, lstScreenList->Items);
if (0 < lstScreenList->Items->Count)
{
lstScreenList->ItemIndex = 0;
}
UpdatePreview();
UpdateButtons();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::UpdateButtons(void)
{
cmdScreenAdd->Enabled = false;
cmdScreenRemove->Enabled = false;
cmdScreenRename->Enabled = false;
cmdScreenClone->Enabled = false;
if (true == SAFE_PTR(m_pImageManager))
{
cmdScreenAdd->Enabled = edtScreenName->Text.Trim() != "";
cmdScreenAdd->Enabled &= !m_pImageManager->DoesImageExist(g_sTypeSignature, edtScreenName->Text);
cmdScreenRename->Enabled = cmdScreenAdd->Enabled && -1 != lstScreenList->ItemIndex;
cmdScreenRemove->Enabled = 0 != m_pImageManager->GetImageCount(g_sTypeSignature);
cmdScreenClone->Enabled = 0 != m_pImageManager->GetImageCount(g_sTypeSignature) && -1 != lstScreenList->ItemIndex;
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::UpdatePreview(void)
{
pbxScreenPreview->Canvas->Brush->Color = clWhite;
pbxScreenPreview->Canvas->FillRect(pbxScreenPreview->ClientRect);
if (true == SAFE_PTR(m_pImageManager))
{
ZXImage* pImage = m_pImageManager->GetImage(g_sTypeSignature, lstScreenList->ItemIndex, 0);
if (true == SAFE_PTR(pImage))
{
pImage->Invalidate();
pImage->Draw(pbxScreenPreview->Canvas, 1);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::cmdScreenAddClick(TObject *Sender)
{
if (true == SAFE_PTR(m_pImageManager))
{
int iIndex = m_pImageManager->AddImage(g_sTypeSignature,
m_vPaletteSignatures[cmbScreenFormat->ItemIndex],
edtScreenName->Text,
edtScreensWidth->Value,
edtScreensHeight->Value,
false);
if (-1 != iIndex)
{
m_ImageEditor.TypeSelectImage(m_PluginHandle, g_sTypeSignature, iIndex, 0);
m_pImageManager->GetImageList(g_sTypeSignature, lstScreenList->Items);
lstScreenList->ItemIndex = iIndex;
UpdatePreview();
UpdateButtons();
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::cmdScreenRemoveClick(TObject *Sender)
{
if (true == SAFE_PTR(m_pImageManager))
{
int iAnswer = 0;
m_ImageEditor.SystemMessageBox(mbtWarning,
"Do you want to Remove a screen image?",
"You are about to remove a screen.",
"You have choosen to remove a screen\n"
"This is a permanent operation and you will not be able to Undo this operation\n\n"
"Click\n"
"\tYes\tto Remove the screen permanently\n"
"\tNo\tto cancel the operation and leave the screen",
"No", "Yes", "", iAnswer );
if (1 == iAnswer)
{
if (true == m_pImageManager->RemoveImage(g_sTypeSignature, lstScreenList->ItemIndex))
{
lstScreenList->Items->Strings[lstScreenList->ItemIndex] = edtScreenName->Text;
m_pImageManager->GetImageList(g_sTypeSignature, lstScreenList->Items);
lstScreenList->ItemIndex = -1;
edtScreenName->Text = "";
m_ImageEditor.TypeSelectImage(m_PluginHandle, g_sTypeSignature, -1, 0);
UpdatePreview();
}
}
}
UpdateButtons();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::cmdScreenCloneClick(TObject *Sender)
{
if (true == SAFE_PTR(m_pImageManager))
{
String sName = edtScreenName->Text;
while (true == m_pImageManager->DoesImageExist(g_sTypeSignature, sName))
{
sName = "Copy of " + sName;
}
int iIndex = m_pImageManager->CloneImage(g_sTypeSignature, sName, lstScreenList->ItemIndex);
if (-1 != iIndex)
{
m_ImageEditor.TypeSelectImage(m_PluginHandle, g_sTypeSignature, iIndex, 0);
m_pImageManager->GetImageList(g_sTypeSignature, lstScreenList->Items);
lstScreenList->ItemIndex = iIndex;
UpdatePreview();
UpdateButtons();
}
}
UpdateButtons();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::cmdScreenRenameClick(TObject *Sender)
{
if (true == SAFE_PTR(m_pImageManager) && -1 != lstScreenList->ItemIndex)
{
if (true == m_pImageManager->RenameImage(g_sTypeSignature, lstScreenList->ItemIndex, edtScreenName->Text))
{
lstScreenList->Items->Strings[lstScreenList->ItemIndex] = edtScreenName->Text;
}
}
UpdateButtons();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::edtScreenNameChange(TObject *Sender)
{
UpdateButtons();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::lstScreenListClick(TObject *Sender)
{
ZXImage* pImage = m_pImageManager->GetImage(g_sTypeSignature, lstScreenList->ItemIndex, 0);
if (true == SAFE_PTR(pImage))
{
edtScreenName->Text = pImage->Name;
edtScreensWidth->Value = pImage->Width;
edtScreensHeight->Value = pImage->Height;
SetComboText(cmbScreenFormat, pImage->Palette->Name);
}
m_ImageEditor.TypeSelectImage(m_PluginHandle, g_sTypeSignature, lstScreenList->ItemIndex, 0);
UpdateButtons();
UpdatePreview();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::pbxScreenPreviewPaint(TObject *Sender)
{
UpdatePreview();
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::SetComboText(TComboBox* pComboBox, String sText)
{
for (int i = 0; i < pComboBox->Items->Count; i++)
{
if (pComboBox->Items->Strings[i] == sText)
{
pComboBox->ItemIndex = i;
break;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::cmbScreenFormatChange(TObject *Sender)
{
if (true == SAFE_PTR(m_pImageManager))
{
ZXPalette* pPalette = m_pImageManager->GetPalette(cmbScreenFormat->Items->Strings[cmbScreenFormat->ItemIndex]);
if (true == SAFE_PTR(pPalette))
{
int iWidth = pPalette->DefaultScreenWidth;
int iHeight = pPalette->DefaultScreenHeight;
edtScreensWidth->Enabled = pPalette->ScreenResizeable;
edtScreensHeight->Enabled = pPalette->ScreenResizeable;
edtScreensWidth->Value = iWidth;
edtScreensHeight->Value = iHeight;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmScreenType::AddScorePanel(void)
{
if (true == SAFE_PTR(m_pImageManager))
{
if (!m_pImageManager->DoesImageExist(g_sTypeSignature, "ScorePanel"))
{
m_pImageManager->AddImage(g_sTypeSignature,
m_vPaletteSignatures[cmbScreenFormat->ItemIndex],
"ScorePanel",
edtScreensWidth->Value,
edtScreensHeight->Value,
false);
}
}
}
//---------------------------------------------------------------------------
| 41.003497 | 124 | 0.50081 | [
"vector"
] |
0ad87c0cb595966f92c500a423f03c7b86ba564c | 7,964 | cpp | C++ | SRC/OpenGL/render.cpp | Jollyrogerxp/Z-Treme-Engine-model-converter | 6ae5d1d6c943ae7a0f1a5de2f1eefdf3eafbb410 | [
"MIT"
] | 3 | 2019-12-01T19:55:48.000Z | 2021-08-31T06:22:28.000Z | SRC/OpenGL/render.cpp | Jollyrogerxp/Z-Treme-Engine-model-converter | 6ae5d1d6c943ae7a0f1a5de2f1eefdf3eafbb410 | [
"MIT"
] | null | null | null | SRC/OpenGL/render.cpp | Jollyrogerxp/Z-Treme-Engine-model-converter | 6ae5d1d6c943ae7a0f1a5de2f1eefdf3eafbb410 | [
"MIT"
] | 2 | 2020-11-23T02:50:41.000Z | 2021-07-14T19:06:16.000Z | #include "../COMMON.H"
extern player_t PLAYER[];
extern int ZT_FRAMERATE;
int testAnim = 0;
int playSpeed = 32;
void ztUpdateAnimation(animationControl_t * animCtrl, animated_model_t * currentModel)
{
if (currentModel->nbFrames==0)return;
//XPDATA * currentPDATA = currentModel->pol[0];
//model_t * currentPDATA = currentModel->model[0];
/**Sets the animation data**/
animCtrl->currentFrm+=ZT_FRAMERATE;
uint32_t FPS = animCtrl->fps;
float percent = 1.0f/(float)(1<<FPS);
if (animCtrl->currentFrm>=animCtrl->endFrm<<FPS)
animCtrl->currentFrm-=(animCtrl->endFrm-animCtrl->startFrm)<<FPS;
/**Safety measure**/
if (animCtrl->currentFrm < animCtrl->startFrm<<FPS || animCtrl->currentFrm >= animCtrl->endFrm<<FPS)
animCtrl->currentFrm=animCtrl->startFrm<<FPS;
animCtrl->currentKeyFrm=animCtrl->currentFrm>>FPS; //should be >>currentModel->AnimInterpolation; but I forgot to output 60 fps animations... No time to fix it...
uint16_t nextKeyFrm=animCtrl->currentKeyFrm+1;
if (nextKeyFrm>=animCtrl->endFrm)
nextKeyFrm=animCtrl->startFrm;
// compVert * curKeyFrame = (compVert*)currentModel->animation[animCtrl->currentKeyFrm]->cVert;
// compVert * nextKeyFrame = (compVert*)currentModel->animation[nextKeyFrm]->cVert;
vertex_t * curKeyFrame = (vertex_t*)currentModel->keyFrames[animCtrl->currentKeyFrm].cVert;
vertex_t * nextKeyFrame = (vertex_t*)currentModel->keyFrames[nextKeyFrm].cVert;
uint16_t interpFctr = animCtrl->currentFrm-(animCtrl->currentKeyFrm<<FPS);
/**Uncompress the vertices and apply linear interpolation**/
/*vertex_t *dst=currentPDATA->pntbl[0];
vertex_t *src=curKeyFrame[0];
vertex_t *nxt=nextKeyFrame[0];*/
/*for (i = 0; i < currentPDATA->nbPoint*sizeof(vertex_t); i+= sizeof(vertex_t)) {
*dst++=(*src+(((*nxt-*src)*interpFctr)>>FPS)); //Here is a "mistake" : Using <<8 would be faster since the SH2 supports a shift left 8 instruction, but I didn't know it when I made this animation tool. To be changed to 8 instead
*src++; *nxt++;
}*/
extern int enableInterpolation;
if (!enableInterpolation) {interpFctr=0;}
unsigned int j=0;
for (unsigned int i=0; i<currentModel->nbModels; i++)
{
model_t * currentPDATA = ¤tModel->model[i];
for (unsigned int ii=0; ii<currentModel->model[i].nbPoint; ii++)
{
vertex_t *dst=(vertex_t*)¤tPDATA->pntbl[ii];
vertex_t *src=(vertex_t*)&curKeyFrame[j];
vertex_t *nxt=(vertex_t*)&nextKeyFrame[j];
for (uint32_t v=0; v<3; v++) {
dst->point[v]=(src->point[v]) + (((nxt->point[v]-src->point[v])*interpFctr)*percent);
}
/*(aModel->keyFrames[curFrame].cVert[j].point[X]) + (percentage2 * aModel->keyFrames[nextFrame].cVert[j].point[X]);
aModel->model[i].pntbl[ii].point[Y]=
(percentage * aModel->keyFrames[curFrame].cVert[j].point[Y]) + (percentage2 * aModel->keyFrames[nextFrame].cVert[j].point[Y]);
aModel->model[i].pntbl[ii].point[Z]=
(percentage * aModel->keyFrames[curFrame].cVert[j].point[Z]) + (percentage2 * aModel->keyFrames[nextFrame].cVert[j].point[Z]);*/
j++;
}
}
/* *dst=currentPDATA->pltbl[0].norm[0];
Uint8 *src2=currentModel->animation[animCtrl->currentKeyFrm]->cNorm;
for (i = 0; i < currentPDATA->nbPolygon; i++) {
*dst++=anorms[*src2][X];
*dst++=anorms[*src2][Y];
*dst=anorms[*src2++][Z];
dst=dst+3 ; //++; *dst++;
}*/
}
int render(animated_model_t * aModel)
{
/* ztUnitMatrix(0);
//ztRotY(52.0);
//ztRotX(23.0);
//ztRotZ(-12.5);
ztPushMatrix();
{
ztTranslate((25), (12), (100));
ztPrintMatrix();
glBegin(GL_QUADS);
{
glColor4f(1.0,0.5,1.0,1.0f);
glVertex2f(-0.5, -0.5);
glColor4f(0.0,0.0,1.0,1.0f);
glVertex2f(0.5, -0.5);
glColor4f(0.0,1.0,0.0,1.0f);
glVertex2f(0.5, 0.5);
glColor4f(1.0,0,0,1.0f);
glVertex2f(-0.5, 0.5);
}
glEnd();
}
ztPopMatrix();*/
glPushMatrix();
glRotatef(PLAYER[0].ROTATION[X], 1.0f, 0.0f, 0.0f);
glRotatef(PLAYER[0].ROTATION[Y], 0.0f, 1.0f, 0.0f);
glTranslatef(-PLAYER[0].POSITION[X], -PLAYER[0].POSITION[Y], -PLAYER[0].POSITION[Z]);
extern int DisplayTEST;
if (DisplayTEST==0)glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
else glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
if (aModel->nbFrames>0)
{
ztUpdateAnimation(&PLAYER[0].ANIMCTRL, aModel);
//testAnim+=ZT_FRAMERATE;
//if (testAnim >= aModel->nbFrames*playSpeed) testAnim=0;
}
const float cOffset = 0.3;
extern unsigned int texId[];
for (unsigned int m=0; m<aModel->nbModels; m++)
{
model_t * curModel = &aModel->model[m];
vertex_t * curVert;
for (unsigned int i=0; i<curModel->nbPolygon; i++)
{
glBindTexture(GL_TEXTURE_2D, texId[curModel->pltbl[i].texture]);
if (aModel->texture[curModel->pltbl[i].texture].attributes & TEX_NO_GOURAUD) glColor4f(1,1,1,1);
glBegin(GL_QUADS);
{
glTexCoord2f(0.0f, 1.0f/ aModel->texture[curModel->pltbl[i].texture].nbFrames);
curVert = &curModel->pntbl[curModel->pltbl[i].vertIdx[3]];
if ((aModel->texture[curModel->pltbl[i].texture].attributes & TEX_NO_GOURAUD) == 0)
glColor4f(curVert->color[0]+cOffset,curVert->color[1]+cOffset,curVert->color[2]+cOffset,1.0f);
glVertex3f(curVert->point[X], curVert->point[Y], curVert->point[Z]);
glTexCoord2f(1.0f, 1.0f/ aModel->texture[curModel->pltbl[i].texture].nbFrames);
curVert = &curModel->pntbl[curModel->pltbl[i].vertIdx[2]];
if ((aModel->texture[curModel->pltbl[i].texture].attributes & TEX_NO_GOURAUD) == 0)
glColor4f(curVert->color[0]+cOffset,curVert->color[1]+cOffset,curVert->color[2]+cOffset,1.0f);
glVertex3f(curVert->point[X], curVert->point[Y], curVert->point[Z]);
glTexCoord2f(1.0f, 0.0f);
curVert = &curModel->pntbl[curModel->pltbl[i].vertIdx[1]];
if ((aModel->texture[curModel->pltbl[i].texture].attributes & TEX_NO_GOURAUD) == 0)
glColor4f(curVert->color[0]+cOffset,curVert->color[1]+cOffset,curVert->color[2]+cOffset,1.0f);
glVertex3f(curVert->point[X], curVert->point[Y], curVert->point[Z]);
glTexCoord2f(0.0f, 0.0f);
curVert = &curModel->pntbl[curModel->pltbl[i].vertIdx[0]];
if ((aModel->texture[curModel->pltbl[i].texture].attributes & TEX_NO_GOURAUD) == 0)
glColor4f(curVert->color[0]+cOffset,curVert->color[1]+cOffset,curVert->color[2]+cOffset,1.0f);
glVertex3f(curVert->point[X], curVert->point[Y], curVert->point[Z]);
}
glEnd();
}
}
glPopMatrix();
return 1;
}
| 43.048649 | 231 | 0.550603 | [
"render",
"model"
] |
0ad8dc7e6f9689f40d865c1568e29bba056c755a | 16,520 | cpp | C++ | auv_ekf_slam/src/ekf_slam_core.cpp | nilsbore/smarc_navigation | 97d0a30498e72506e7472c98c5fa0d86d19f0f04 | [
"BSD-3-Clause"
] | 15 | 2020-01-24T10:24:10.000Z | 2022-03-19T10:22:41.000Z | auv_ekf_slam/src/ekf_slam_core.cpp | nilsbore/smarc_navigation | 97d0a30498e72506e7472c98c5fa0d86d19f0f04 | [
"BSD-3-Clause"
] | 20 | 2018-02-08T09:46:01.000Z | 2021-05-07T09:40:26.000Z | auv_ekf_slam/src/ekf_slam_core.cpp | nilsbore/smarc_navigation | 97d0a30498e72506e7472c98c5fa0d86d19f0f04 | [
"BSD-3-Clause"
] | 14 | 2018-01-25T14:42:24.000Z | 2022-03-08T15:18:28.000Z | /* Copyright 2018 Ignacio Torroba (ignaciotb@kth.se)
*
* 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 its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "ekf_slam_core/ekf_slam_core.hpp"
EKFCore::EKFCore(Eigen::VectorXd &mu, Eigen::MatrixXd &Sigma, Eigen::MatrixXd &R, Eigen::MatrixXd &Q_fls, Eigen::MatrixXd &Q_mbes,
double &lambda_fls, double &lambda_mbes, tf::StampedTransform &tf_base_sensor, const double mh_dist_fls, const double mh_dist_mbes){
// Initialize internal params
mu_ = mu;
mu_hat_ = mu_;
mu_auv_odom_.setZero(3);
Sigma_ = Sigma;
Sigma_hat_ = Sigma_;
R_ = R;
Q_fls_ = Q_fls;
Q_mbes_ = Q_mbes;
lambda_fls_ = lambda_fls;
lambda_mbes_ = lambda_mbes;
lm_num_ = (mu_.rows() - 6) / 3;
tf_base_sensor_ = tf_base_sensor;
tf_sensor_base_ = tf_base_sensor.inverse();
mh_dist_fls_ = mh_dist_fls;
mh_dist_mbes_ = mh_dist_mbes;
// const Eigen::MatrixXd CorrespondenceMBES::Q_ = Q;
}
void EKFCore::predictMotion(nav_msgs::Odometry odom_reading){
// Construct Fx (6,3N) for dimension mapping
Eigen::SparseMatrix<double> F_x(6, 6 + 3*lm_num_);
std::vector<Eigen::Triplet<double>> tripletList;
tripletList.reserve(6);
unsigned int j;
int input = 1;
for(unsigned int i=0; i<6; i++){
j = i;
tripletList.push_back(Eigen::Triplet<double>(i,j,input));
}
F_x.setFromTriplets(tripletList.begin(), tripletList.end());
Eigen::SparseMatrix<double> F_x_transp = F_x.transpose();
// Extract latest orientation from odom at time t
tf::Quaternion q_odom;
tf::quaternionMsgToTF(odom_reading.pose.pose.orientation, q_odom);
q_odom.normalize();
// Compute predicted mu_hat
Eigen::Vector3d u_t(odom_reading.pose.pose.position.x,
odom_reading.pose.pose.position.y,
odom_reading.pose.pose.position.z);
u_t -= mu_auv_odom_; // Increment in x,y,z
mu_hat_.segment(0, 3) = mu_.segment(0,3);
mu_hat_.segment(0, 3) += u_t;
mu_auv_odom_ += u_t;
// Global orientation roll, pitch and yaw
tf::Quaternion q(
odom_reading.pose.pose.orientation.x,
odom_reading.pose.pose.orientation.y,
odom_reading.pose.pose.orientation.z,
odom_reading.pose.pose.orientation.w);
tf::Matrix3x3 m(q);
m.getRPY(mu_hat_(3), mu_hat_(4), mu_hat_(5));
mu_hat_(3) = utils::angleLimit(mu_hat_(3));
mu_hat_(4) = utils::angleLimit(mu_hat_(4));
mu_hat_(5) = utils::angleLimit(mu_hat_(5));
// Derivative of motion model in mu_ (t-1)
Eigen::MatrixXd g_t(6,6);
g_t.setZero(6, 6);
using namespace std;
g_t(0,3) = u_t(1)*(sin(mu_hat_(3))*sin(mu_hat_(5)) + cos(mu_hat_(3))*cos(mu_hat_(5))*sin(mu_hat_(4)))
+ u_t(2)*(cos(mu_hat_(3))*sin(mu_hat_(5)) - cos(mu_hat_(5))*sin(mu_hat_(4))*sin(mu_hat_(3)));
g_t(0,4) = cos(mu_hat_(5))*(u_t(2)*cos(mu_hat_(4))*cos(mu_hat_(3)) - u_t(0)*sin(mu_hat_(4))
+ u_t(1)*cos(mu_hat_(4))*sin(mu_hat_(3)));
g_t(0,5) = u_t(2)*(cos(mu_hat_(5))*sin(mu_hat_(3)) - cos(mu_hat_(3))*sin(mu_hat_(4))*sin(mu_hat_(5)))
- u_t(1)*(cos(mu_hat_(3))*cos(mu_hat_(5)) + sin(mu_hat_(4))*sin(mu_hat_(3))*sin(mu_hat_(5)))
- u_t(0)*cos(mu_hat_(4))*sin(mu_hat_(5));
g_t(1,3) = - u_t(1)*(cos(mu_hat_(5))*sin(mu_hat_(3)) - cos(mu_hat_(3))*sin(mu_hat_(4))*sin(mu_hat_(5)))
- u_t(2)*(cos(mu_hat_(3))*cos(mu_hat_(5)) + sin(mu_hat_(4))*sin(mu_hat_(3))*sin(mu_hat_(5)));
g_t(1,4) = sin(mu_hat_(5))*(u_t(2)*cos(mu_hat_(4))*cos(mu_hat_(3)) - u_t(0)*sin(mu_hat_(4))
+ u_t(1)*cos(mu_hat_(4))*sin(mu_hat_(3)));
g_t(1,5) = u_t(2)*(sin(mu_hat_(3))*sin(mu_hat_(5)) + cos(mu_hat_(3))*cos(mu_hat_(5))*sin(mu_hat_(4)))
- u_t(1)*(cos(mu_hat_(3))*sin(mu_hat_(5)) - cos(mu_hat_(5))*sin(mu_hat_(4))*sin(mu_hat_(3)))
+ u_t(0)*cos(mu_hat_(4))*cos(mu_hat_(5));
g_t(2,3) = cos(mu_hat_(4))*(u_t(1)*cos(mu_hat_(3)) - u_t(2)*sin(mu_hat_(3)));
g_t(2,4) = - u_t(0)*cos(mu_hat_(4)) - u_t(2)*cos(mu_hat_(3))*sin(mu_hat_(4))
- u_t(1)*sin(mu_hat_(4))*sin(mu_hat_(3));
g_t(2,5) = 0;
// Compute Jacobian G_t
Eigen::MatrixXd G_t = Eigen::MatrixXd::Identity(6 + 3*lm_num_, 6 + 3*lm_num_);
G_t(3,3) = 0; // G_t is zero here because the motion model uses abs values for RPY
G_t(4,4) = 0;
G_t(5,5) = 0;
G_t += F_x_transp * g_t * F_x;
// Predicted covariance matrix
Sigma_hat_ = G_t * Sigma_ * G_t.transpose();
Sigma_hat_ += F_x_transp * R_ * F_x;
}
void EKFCore::predictBatchMeasurement(const Eigen::Vector3d &landmark_j,
const Eigen::Vector3d &z_i,
unsigned int i,
unsigned int j,
const tf::Transform &transf_base_map,
const Eigen::MatrixXd &temp_sigma,
h_comp h_comps,
const utils::MeasSensor &sens_type,
std::vector<CorrespondenceClass> &corresp_i_list,
Eigen::MatrixXd &corresp_table){
CorrespondenceClass* corresp_i_j;
std::tuple<Eigen::Vector3d, Eigen::Vector3d> z_hat_tuple;
tf::Vector3 landmark_j_map(landmark_j(0),
landmark_j(1),
landmark_j(2));
// Measurement model: z_expected and z_expected_sensor (in sensor frame)
Eigen::MatrixXd Q_t;
tf::Transform tf_sensor_map;
double lambda_meas;
switch(sens_type){
case utils::MeasSensor::MBES: // MBES
corresp_i_j = new CorrespondenceMBES(i, j);
tf_sensor_map = transf_base_map;
Q_t = Q_mbes_;
lambda_meas = lambda_mbes_;
break;
case utils::MeasSensor::FLS: // FLS
corresp_i_j = new CorrespondenceFLS(i, j);
tf_sensor_map = tf_sensor_base_ * transf_base_map;
Q_t = Q_fls_;
lambda_meas = lambda_fls_;
break;
}
z_hat_tuple = corresp_i_j->measModel(landmark_j_map, tf_sensor_map);
// Compute MHL distance of correspondence cij: z_i with m_j
corresp_i_j->computeH(h_comps, landmark_j_map, std::get<1>(z_hat_tuple));
corresp_i_j->computeNu(std::get<0>(z_hat_tuple), z_i);
corresp_i_j->computeMHLDistance(temp_sigma, Q_t);
// Store correspondence object
corresp_i_list.push_back(std::move(*corresp_i_j));
// Add MHD distance to assignment table
ROS_DEBUG_STREAM("MHD distance " << corresp_i_j->d_m_);
// Outlier rejection
if(corresp_i_j->d_m_ < lambda_meas){
corresp_table(j, i) = corresp_i_j->d_m_;
}
else{
corresp_table(j, i) = 10000; // Infinite value
// ROS_INFO("Outlier rejected");
}
delete (corresp_i_j);
}
void EKFCore::batchDataAssociation(std::vector<Eigen::Vector3d> z_t, const utils::MeasSensor &sens_type){
std::vector<CorrespondenceClass> corresp_list;
tf::Transform transf_base_map;
tf::Transform transf_map_base;
Eigen::MatrixXd temp_sigma(9,9);
// For each observation z_i at time t
lm_num_ = (mu_.rows() - 6) / 3;
h_comp h_comps;
tf::Matrix3x3 m;
// Compute transform map --> base from current state state estimate at time t
transf_map_base = tf::Transform(tf::createQuaternionFromRPY(mu_hat_(3), mu_hat_(4), mu_hat_(5)).normalize(),
tf::Vector3(mu_hat_(0), mu_hat_(1), mu_hat_(2)));
transf_base_map = transf_map_base.inverse();
// Store current mu_hat_ estimate in struct for faster computation of H in DA
m.setRotation(tf_sensor_base_.getRotation());
tf::matrixTFToEigen(m, h_comps.R_fls_base_);
{
using namespace std;
h_comps.mu_0 = mu_hat_(0);
h_comps.mu_1 = mu_hat_(1);
h_comps.mu_2 = mu_hat_(2);
h_comps.c_3 = cos(mu_hat_(3));
h_comps.c_4 = cos(mu_hat_(4));
h_comps.c_5 = cos(mu_hat_(5));
h_comps.s_3 = sin(mu_hat_(3));
h_comps.s_4 = sin(mu_hat_(4));
h_comps.s_5 = sin(mu_hat_(5));
}
// Select meas model depending on the sensor input type
CorrespondenceClass* sensor_input;
tf::Transform tf_map_sensor;
std::tuple<double, double, double> new_lm_cov;
double new_mh_dist;
switch(sens_type){
case utils::MeasSensor::MBES:
sensor_input = new CorrespondenceMBES();
tf_map_sensor = transf_map_base;
// Covariance of new lm
new_lm_cov = std::make_tuple(100,100,100); // TODO: make dependent on the sensor
// MH dist of new lm
new_mh_dist = mh_dist_mbes_;
break;
case utils::MeasSensor::FLS:
sensor_input = new CorrespondenceFLS();
tf_map_sensor = transf_map_base * tf_base_sensor_;
// Covariance of new lm
new_lm_cov = std::make_tuple(400,200,1000);
// MH dist of new lm
new_mh_dist = mh_dist_fls_;
break;
}
// Store latest mu_hat_ and sigma_hat_ for next steps
Eigen::VectorXd mu_hat_temp = mu_hat_;
Eigen::MatrixXd Sigma_hat_temp = Sigma_hat_;
// Back-project new possible landmark (in map frame) for every z_i
Eigen::Vector3d new_lm_map;
for(unsigned int i = 0; i<z_t.size(); i++){
new_lm_map = sensor_input->backProjectNewLM(z_t.at(i), tf_map_sensor);
// Add new possible lm to filter
utils::addLMtoFilter(mu_hat_temp, Sigma_hat_temp, new_lm_map, new_lm_cov);
}
// Construct correspondences table for global assignment
unsigned int temp_num_lm = (mu_hat_temp.rows()-6)/3;
Eigen::MatrixXd corresp_table(temp_num_lm, z_t.size());
// For every meas z_i in z_t
for(unsigned int i = 0; i<z_t.size(); i++){
// For each possible landmark j in Map
Eigen::Vector3d landmark_j;
for(unsigned int j=0; j<temp_num_lm; j++){
landmark_j = mu_hat_temp.segment(3 * j + 6, 3);
utils::updateMatrixBlock(Sigma_hat_temp, temp_sigma, j);
predictBatchMeasurement(landmark_j, z_t.at(i), i, j, transf_base_map, temp_sigma, h_comps, sens_type, corresp_list, corresp_table);
}
}
// Add new_mh_dist to backprojected lm candidates in correspondence table
unsigned int cnt = 0;
for(unsigned int j=lm_num_; j<temp_num_lm; j++){
for(unsigned int i=0; i<z_t.size(); i++){
if(i == cnt){ // Diagonal elements of submatrix with new backprojected landmarks
corresp_table(j, i) = new_mh_dist;
}
else{
corresp_table(j, i) = 10000; // Infinite value
}
}
cnt += 1;
}
// Initialize Munkres matrix from Eigen matrix
Matrix<double> munkres_matrix(temp_num_lm, z_t.size());
for (unsigned int row = 0 ; row < temp_num_lm ; row++ ) {
for (unsigned int col = 0 ; col < z_t.size() ; col++ ) {
munkres_matrix(row,col) = corresp_table(row,col);
}
}
// ROS_INFO("Munkres matrix initialized");
// // Display initial matrix.
// std::cout << "Initial matrix" << std::endl;
// for ( int row = 0 ; row < temp_num_lm ; row++ ) {
// for ( int col = 0 ; col < z_t.size() ; col++ ) {
// std::cout.width(10);
// std::cout << munkres_matrix(row,col) << ",";
// }
// std::cout << std::endl;
// }
// Solve correspondence problem
Munkres<double> munkres_solver;
munkres_solver.solve(munkres_matrix);
// Display solved matrix.
// std::cout << "Solved matrix" << std::endl;
// for ( int row = 0 ; row < temp_num_lm ; row++ ) {
// for ( int col = 0 ; col < z_t.size() ; col++ ) {
// std::cout.width(2);
// std::cout << munkres_matrix(row,col) << ",";
// }
// std::cout << std::endl;
// }
// Update step with selected correspondences
unsigned int lm;
for(unsigned int i=0; i<z_t.size(); i++){
for (unsigned int j=0; j<temp_num_lm; j++){
if(munkres_matrix(j,i) == 0){
if(j >= lm_num_){ // If new landmark added
ROS_DEBUG_STREAM("New lm added");
// Resize mu and sigma with final landmarks in map (if any new one added)
utils::addLMtoFilter(mu_hat_, Sigma_hat_, corresp_list.at(j + temp_num_lm * i).landmark_pos_, new_lm_cov);
// Recompute new lm index based on its order in the filter
lm = ((Sigma_hat_.rows() - 6) / 3) - 1;
corresp_list.at(j + temp_num_lm * i).i_j_.second = lm;
}
else{
ROS_DEBUG_STREAM("Known lm seen");
// Known lm index based on its order in the filter
lm = j;
}
utils::updateMatrixBlock(Sigma_hat_, temp_sigma, lm);
sequentialUpdate(corresp_list.at(j + temp_num_lm * i), temp_sigma);
continue;
}
}
}
delete (sensor_input);
// Make sure mu and sigma have the same size at the end!
while(mu_hat_.size() < Sigma_hat_.rows()){
ROS_WARN("Sizes of mu and sigma differ!!");
Sigma_hat_.conservativeResize(Sigma_hat_.rows()-3, Sigma_hat_.cols()-3);
}
}
void EKFCore::sequentialUpdate(CorrespondenceClass const& c_i_j, Eigen::MatrixXd temp_sigma){
// Compute Kalman gain
utils::updateMatrixBlock(Sigma_hat_, temp_sigma, c_i_j.i_j_.second);
Eigen::MatrixXd K_t_i = temp_sigma * c_i_j.H_t_.transpose() * c_i_j.S_inverted_;
// Update mu_hat and sigma_hat
Eigen::VectorXd aux_vec = K_t_i * c_i_j.nu_;
mu_hat_.head(6) += aux_vec.head(6);
mu_hat_(3) = utils::angleLimit(mu_hat_(3));
mu_hat_(4) = utils::angleLimit(mu_hat_(4));
mu_hat_(5) = utils::angleLimit(mu_hat_(5));
mu_hat_.segment((c_i_j.i_j_.second) * 3 + 6, 3) += aux_vec.segment(6, 3);
Eigen::MatrixXd aux_mat = (Eigen::MatrixXd::Identity(temp_sigma.rows(), temp_sigma.cols()) - K_t_i * c_i_j.H_t_) * temp_sigma;
Sigma_hat_.block(0,0,6,6) = aux_mat.block(0,0,6,6);
Sigma_hat_.block((c_i_j.i_j_.second) * 3 + 6, (c_i_j.i_j_.second) * 3 + 6, 3, 3) = aux_mat.block(6, 6, 3, 3);
Sigma_hat_.block((c_i_j.i_j_.second) * 3 + 6, 0, 3, 6) = aux_mat.block(6,0,3,6);
Sigma_hat_.block(0, (c_i_j.i_j_.second) * 3 + 6, 6, 3) = aux_mat.block(0,6,6,3);
}
std::tuple<Eigen::VectorXd, Eigen::MatrixXd> EKFCore::ekfUpdate(){
// Update step
if (mu_.rows()!= mu_hat_.rows()){
int n_t = mu_hat_.rows() - mu_.rows();
mu_.conservativeResize(mu_.size() + n_t, true);
Sigma_.conservativeResize(Sigma_.rows() + n_t, Sigma_.cols() + n_t);
// TODO: check that Sigma_ is still semi-definite positive
}
mu_ = mu_hat_;
Sigma_ = Sigma_hat_;
lm_num_ = (mu_.rows() - 6) / 3;
return std::make_pair(mu_, Sigma_);
}
EKFCore::~EKFCore(){
// Empty queues
// Delete instance pointers
}
| 41.928934 | 758 | 0.616949 | [
"object",
"vector",
"model",
"transform"
] |
0ae092536dddb975843f3004bb9bb2e2f1c56edf | 2,430 | cpp | C++ | demo-topdown/Player.cpp | leftidev/cpp-GEngine | fb1a000336f8295386c5e9e401072cfe0679b587 | [
"MIT"
] | 4 | 2016-04-02T05:52:59.000Z | 2021-05-15T21:03:17.000Z | demo-topdown/Player.cpp | lefti-/cpp-GEngine | fb1a000336f8295386c5e9e401072cfe0679b587 | [
"MIT"
] | null | null | null | demo-topdown/Player.cpp | lefti-/cpp-GEngine | fb1a000336f8295386c5e9e401072cfe0679b587 | [
"MIT"
] | 1 | 2016-04-13T17:25:44.000Z | 2016-04-13T17:25:44.000Z | #include <iostream>
#include <algorithm>
#include <SDL/SDL.h>
#include "Player.h"
const float TILE_WIDTH = 64.0f;
Player::Player() { }
Player::~Player() { }
void Player::init(glm::fvec2 pos, GEngine::InputManager* inputManager, GEngine::Camera2D* camera) {
m_textureID = GEngine::ResourceManager::getTexture("../assets/textures/soldier_torso_1h.png").id;
m_textureID2 = GEngine::ResourceManager::getTexture("../assets/textures/soldier_legs_0004.png").id;
width = 64.0f;
height = 64.0f;
m_speed.x = 8.0f;
m_speed.y = 8.0f;
m_position = pos;
m_inputManager = inputManager;
m_camera = camera;
m_color.r = 255;
m_color.g = 255;
m_color.b = 255;
m_color.a = 255;
}
void Player::draw(GEngine::SpriteBatch& spriteBatch) {
const glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
glm::vec4 destRect;
destRect.x = m_position.x;
destRect.y = m_position.y;
destRect.z = width;
destRect.w = height;
spriteBatch.draw(destRect, uvRect, m_textureID, 0.5f, m_color, m_direction);
spriteBatch.draw(destRect, uvRect, m_textureID2, 0.0f, m_color, m_direction);
// Debug bounding box drawing
/*
glm::vec4 aabbRect;
aabbRect.x = m_position.x + 16.0f;
aabbRect.y = m_position.y + 16.0f;
aabbRect.z = width - 32.0f;
aabbRect.w = height - 32.0f;
spriteBatch.draw(aabbRect, uvRect, m_debugTextureID, 1.0f, m_color);
*/
}
void Player::update(const std::vector<std::string>& levelData, std::vector<Projectile>& projectiles, float deltaTime) {
// Shoot projectile
if (m_inputManager->isKeyPressed(SDL_BUTTON_LEFT)) {
shootProjectile(projectiles);
}
if (m_inputManager->isKeyDown(SDLK_w)) {
m_position.y += m_speed.y * deltaTime;
}
else if (m_inputManager->isKeyDown(SDLK_s)) {
m_position.y -= m_speed.y * deltaTime;
}
if (m_inputManager->isKeyDown(SDLK_a)) {
m_position.x -= m_speed.x * deltaTime;
}
else if (m_inputManager->isKeyDown(SDLK_d)) {
m_position.x += m_speed.x * deltaTime;
}
glm::vec2 mouseCoords = m_inputManager->getMouseCoords();
mouseCoords = m_camera->convertScreenToWorld(mouseCoords);
glm::vec2 centerPosition = m_position + glm::vec2(width / 2, height / 2);
m_direction = glm::normalize(mouseCoords - centerPosition);
collideWithLevel(levelData);
}
void Player::shootProjectile(std::vector<Projectile>& projectiles) {
if (projectiles.size() < 10000) {
projectiles.emplace_back(16.0f, m_direction, m_position + glm::fvec2(32.0f));
}
} | 27 | 119 | 0.705761 | [
"vector"
] |
0ae22f72cbb606884f1f20ca97068a7e0dfa6457 | 764 | cpp | C++ | lib/qt4/AbilitiesComboBox.cpp | codemonkey85/LibPKMN | 96a1800a24bf3861da405cf56daa2d7afd6c850d | [
"MIT"
] | null | null | null | lib/qt4/AbilitiesComboBox.cpp | codemonkey85/LibPKMN | 96a1800a24bf3861da405cf56daa2d7afd6c850d | [
"MIT"
] | null | null | null | lib/qt4/AbilitiesComboBox.cpp | codemonkey85/LibPKMN | 96a1800a24bf3861da405cf56daa2d7afd6c850d | [
"MIT"
] | 1 | 2019-07-08T20:43:57.000Z | 2019-07-08T20:43:57.000Z | /*
* Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <string>
#include <vector>
#include <pkmn/qt4/AbilitiesComboBox.hpp>
#include <pkmn/lists.hpp>
namespace pkmn
{
namespace qt4
{
AbilitiesComboBox::AbilitiesComboBox(unsigned int gen, QWidget* parent): QComboBox(parent)
{
std::vector<std::string> abilities_vec;
get_ability_list(abilities_vec, gen);
for(unsigned int i = 0; i < abilities_vec.size(); i++)
{
addItem(tr(abilities_vec[i].c_str()), QVariant(i));
}
}
}
} /* namespace pkmn */
| 25.466667 | 98 | 0.617801 | [
"vector"
] |
0ae6fecb63390a18f04525bd54dccf962fcf3a3e | 893 | cpp | C++ | src/skeleton.cpp | Reesy/sdl-rpg-battle-system | 40a7b5027f6891495484d01f39b72a1162bdf6a8 | [
"MIT"
] | null | null | null | src/skeleton.cpp | Reesy/sdl-rpg-battle-system | 40a7b5027f6891495484d01f39b72a1162bdf6a8 | [
"MIT"
] | null | null | null | src/skeleton.cpp | Reesy/sdl-rpg-battle-system | 40a7b5027f6891495484d01f39b72a1162bdf6a8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <Skeleton.hpp>
#include <Animator.hpp>
Skeleton::Skeleton(SDL_Texture *_texture, SDL_Texture *_idleTexture)
{
this->texture = _texture;
this->idleTexture = _idleTexture;
this->textureRect = {0, 0, 32, 32};
this->positionRect = {0, 0, 60, 60};
this->isIdle = false;
this->attackAnimation = new Animator(5, 150, 32, 32);
};
void Skeleton::move(int _x, int _y)
{
this->positionRect.x += _x;
this->positionRect.y += _y;
};
void Skeleton::animate(double elapsedTime)
{
this->attackAnimation->Animate(elapsedTime, &this->textureRect);
};
void Skeleton::render(SDL_Renderer *_renderer)
{
SDL_RenderCopy(_renderer, this->texture, &this->textureRect, &this->positionRect);
};
void Skeleton::setIdle(bool _idle)
{
this->isIdle = _idle;
};
int Skeleton::getX()
{
return x;
};
int Skeleton::getY()
{
return y;
};
| 19.844444 | 86 | 0.665174 | [
"render"
] |
0af003b40ad855a4b348fea3eb2c7479f4c887e8 | 1,524 | cpp | C++ | source/io/load_tri_file.cpp | RichardJ112/Nebula | 072e5a8c003aedd07f850cd62cd32bea61828fb5 | [
"BSD-3-Clause"
] | 3 | 2021-02-13T17:54:43.000Z | 2021-09-09T14:29:08.000Z | source/io/load_tri_file.cpp | RichardJ112/Nebula | 072e5a8c003aedd07f850cd62cd32bea61828fb5 | [
"BSD-3-Clause"
] | 2 | 2021-02-13T19:21:00.000Z | 2021-02-16T19:07:45.000Z | source/io/load_tri_file.cpp | RichardJ112/Nebula | 072e5a8c003aedd07f850cd62cd32bea61828fb5 | [
"BSD-3-Clause"
] | 4 | 2020-10-02T11:01:45.000Z | 2021-03-20T16:43:12.000Z | #include "../config/config.h"
#include "load_tri_file.h"
#include <fstream>
#include <sstream>
namespace nbl {
std::vector<triangle> load_tri_file(std::string const & filename)
{
std::vector<triangle> triangle_vec;
std::ifstream ifs(filename);
if(!ifs.is_open())
return triangle_vec;
size_t line_num = 1;
while(!ifs.eof())
{
std::string line_str;
std::getline(ifs, line_str);
line_num++;
if(line_str.empty())
continue;
const size_t i = line_str.find_first_not_of(" \t");
if(i < line_str.size() && line_str[i] == '#')
continue;
// Split columns in line into a vector
std::stringstream ss;
ss << line_str;
std::vector<std::string> tag_vec;
while(!ss.eof())
{
std::string tag_str;
ss >> tag_str;
if(!tag_str.empty())
tag_vec.push_back(tag_str);
}
if(tag_vec.size() != 11)
{
std::ostringstream oss;
oss << "invalid number of columns in line '" << line_num << "'";
throw std::runtime_error(oss.str());
}
// Interpret line
int in, out;
in = std::stoi(tag_vec[0]);
out = std::stoi(tag_vec[1]);
vec3 A, B, C;
A.x = (real)std::stod(tag_vec[2]); A.y = (real)std::stod(tag_vec[3]); A.z = (real)std::stod(tag_vec[4]);
B.x = (real)std::stod(tag_vec[5]); B.y = (real)std::stod(tag_vec[6]); B.z = (real)std::stod(tag_vec[7]);
C.x = (real)std::stod(tag_vec[8]); C.y = (real)std::stod(tag_vec[9]); C.z = (real)std::stod(tag_vec[10]);
triangle_vec.push_back(triangle(A, B, C, in, out));
}
ifs.close();
return triangle_vec;
}
} // namespace nbl
| 24.190476 | 107 | 0.629921 | [
"vector"
] |
0af0eb3ebc0c0b94284257a3f20087cfaaf29708 | 13,626 | cpp | C++ | extras/debug.cpp | danielsuo/cuSIFT | 224f0490b6a315fa44132d7b94e36f73b0d84541 | [
"MIT"
] | 15 | 2016-06-21T09:10:12.000Z | 2022-01-02T05:26:29.000Z | extras/debug.cpp | danielsuo/cuSIFT | 224f0490b6a315fa44132d7b94e36f73b0d84541 | [
"MIT"
] | 47 | 2015-12-10T21:51:48.000Z | 2016-10-19T08:25:05.000Z | extras/debug.cpp | danielsuo/cuSIFT | 224f0490b6a315fa44132d7b94e36f73b0d84541 | [
"MIT"
] | 6 | 2015-12-17T14:29:37.000Z | 2021-07-01T02:24:26.000Z | #include "debug.h"
////////////////////////////////////////////////////////////////////////////////
void writeMatToFile(cv::Mat& m, const char* filename)
{
ofstream fout(filename);
double sum = 0;
if(!fout) {
cout<<"File Not Opened"<<endl; return;
}
for(int i = 0; i < m.rows; i++) {
for(int j = 0; j < m.cols; j++) {
fout << m.at<float>(i, j) << "\t";
sum += m.at<float>(i, j);
}
fout << endl;
}
fprintf(stderr, "Sum of matrix: %f\n", sum);
fout.close();
}
void PrintSiftData(SiftData &data)
{
#ifdef MANAGEDMEM
SiftPoint *h_data = data.m_data;
#else
SiftPoint *h_data = data.h_data;
if (data.h_data==NULL) {
h_data = (SiftPoint *)malloc(sizeof(SiftPoint)*data.maxPts);
safeCall(cudaMallocHost((void **)&h_data, sizeof(SiftPoint)*data.maxPts));
safeCall(cudaMemcpy(h_data, data.d_data, sizeof(SiftPoint)*data.numPts, cudaMemcpyDeviceToHost));
data.h_data = h_data;
}
#endif
for (int i=0;i<data.numPts;i++) {
printf("xpos = %.2f\n", h_data[i].coords2D[0]);
printf("ypos = %.2f\n", h_data[i].coords2D[1]);
printf("scale = %.2f\n", h_data[i].scale);
printf("sharpness = %.2f\n", h_data[i].sharpness);
printf("edgeness = %.2f\n", h_data[i].edgeness);
printf("orientation = %.2f\n", h_data[i].orientation);
printf("score = %.2f\n", h_data[i].score);
float *siftData = (float*)&h_data[i].data;
for (int j = 0; j < 8; j++) {
if (j == 0) {
printf("data = ");
}
else {
printf(" ");
}
for (int k = 0; k<16; k++) {
if (siftData[j * 16 + k] < 0.01) {
printf(" . ");
}
else {
printf("%.2f ", siftData[j * 16 + k]);
}
}
printf("\n");
}
}
printf("Number of available points: %d\n", data.numPts);
printf("Number of allocated points: %d\n", data.maxPts);
}
cv::Mat PrintMatchData(SiftData &siftData1, SiftData &siftData2, cv::Mat limg, cv::Mat rimg)
{
int numPts = siftData1.numPts;
SiftPoint *sift1 = siftData1.h_data;
cv::Mat im3(limg.size().height, limg.size().width + rimg.size().width, CV_32FC1);
cv::Mat left(im3, cv::Rect(0, 0, limg.size().width, limg.size().height));
limg.copyTo(left);
cv::Mat right(im3, cv::Rect(limg.size().width, 0, rimg.size().width, rimg.size().height));
rimg.copyTo(right);
int w = limg.size().width + rimg.size().width;
for (int j = 0; j < numPts; j++) {
float dx = sift1[j].match_xpos + limg.size().width - sift1[j].coords2D[0];
float dy = sift1[j].match_ypos - sift1[j].coords2D[1];
int len = (int)(fabs(dx) > fabs(dy) ? fabs(dx) : fabs(dy));
for (int l = 0; l < len; l++) {
int x = (int)(sift1[j].coords2D[0] + dx * l / len);
int y = (int)(sift1[j].coords2D[1] + dy * l / len);
im3.at<float>(y, x) = 255.0f;
}
}
return im3;
}
void PrintMatchSiftData(SiftData &siftData1, const char* filename, int imgw) {
ofstream fout(filename);
if (!fout)
{
cout << "File Not Opened" << endl; return;
}
SiftPoint *sift1 = siftData1.h_data;
for (int i = 0; i < siftData1.numPts; i++)
{
int ind = ((int)sift1[i].coords2D[0] + (int)sift1[i].coords2D[1] * imgw);
int ind2 = ((int)sift1[i].match_xpos + (int)sift1[i].match_ypos * imgw);
fout << sift1[i].coords2D[0] << "\t" << sift1[i].coords2D[1] << "\t";
fout << sift1[i].match_xpos << "\t" << sift1[i].match_ypos << "\t";
fout << ind << "\t" << ind2 << "\t";
fout << endl;
}
fout.close();
}
/* Assumes output was created by vl_sift_tofile.m
* Binary format
* - uint32_t numPts: number of sift points that will follow
* - float points: 4 x numPts that contains x, y, scale, and orientation
* (in radians)
* - float descriptors: 128 x numPts that contain descriptors (0.0 to 1.0)
*/
void ReadVLFeatSiftData(SiftData &siftData, const char *filename) {
fprintf(stderr, "Reading vlfeat data from %s", filename);
// InitSiftData(siftData, 1024, true, true);
FILE *fp = fopen(filename, "rb");
// First, read number of SIFT points in the VLFeat SIFT data file
uint32_t numPts;
fread((void *)&numPts, sizeof(uint32_t), 1, fp);
// Next, grab matrix containing x, y, scale, orientation (in radians)
float *points = new float[4 * numPts];
fread((void *)points, sizeof(float), 4 * numPts, fp);
// Finally, get SIFT descriptor arrays
float *descriptors = new float[128 * numPts];
fread((void *)descriptors, sizeof(float), 128 * numPts, fp);
// Finish reading
fclose(fp);
SiftPoint *h_data = (SiftPoint *)calloc(numPts, sizeof(SiftPoint));
fprintf(stderr, " ... and got %d points\n", numPts);
for (int i = 0; i < numPts; i++) {
h_data[i].coords2D[0] = points[i * 4];
h_data[i].coords2D[1] = points[i * 4 + 1];
h_data[i].scale = points[i * 4 + 2];
h_data[i].orientation = points[i * 4 + 3];
memcpy(h_data[i].data, descriptors + i * 128, sizeof(float) * 128);
}
AddSiftData(siftData, h_data, numPts);
free(points);
free(descriptors);
free(h_data);
}
int ReadMATLABMatchIndices(const char *indices_filename, uint32_t *indices_i, uint32_t *indices_j) {
fprintf(stderr, "Reading match indices data from %s\n", indices_filename);
FILE *fp = fopen(indices_filename, "rb");
uint32_t numPts;
fread((void *)&numPts, sizeof(uint32_t), 1, fp);
if (indices_i != NULL && indices_j != NULL) {
fread((void *)indices_i, sizeof(uint32_t), numPts, fp);
fread((void *)indices_j, sizeof(uint32_t), numPts, fp);
}
fclose(fp);
return numPts;
}
vector<float *> ReadVLFeatSiftDataAsFloatArray(const char *filename) {
fprintf(stderr, "Reading vlfeat sift data as double array from %s\n", filename);
FILE *fp = fopen(filename, "rb");
uint32_t numPts;
fread((void *)&numPts, sizeof(uint32_t), 1, fp);
vector<float *> siftPoints;
for (int i = 0; i < numPts; i++) {
float siftPoint[128];
fread((void *)siftPoint, sizeof(float), 128, fp);
siftPoints.push_back(siftPoint);
}
fclose(fp);
return siftPoints;
}
void ReadMATLABMatchData(cv::Mat &curr_match, cv::Mat &next_match, const char *filename) {
fprintf(stderr, "Reading MATLAB match data from %s\n", filename);
FILE *fp = fopen(filename, "rb");
// First, read number of matched points
uint32_t numPts;
fread((void *)&numPts, sizeof(uint32_t), 1, fp);
// Next, grab matrix containing world coordinates from current frame and
// world coordinates from next frame (x1, y1, z1, x2, y2, z2)
double *matchedPoints = new double[6 * numPts];
fread((void *)matchedPoints, sizeof(double), 6 * numPts, fp);
// Resize the match matrices
curr_match.resize(numPts);
next_match.resize(numPts);
fprintf(stderr, "Number of matches %d\n", curr_match.rows);
// Store match data in curr_match and next_match, which are 3xnumPts matrices
for (int i = 0; i < numPts; i++) {
curr_match.at<float>(i, 0) = matchedPoints[i * 6 + 0];
curr_match.at<float>(i, 1) = matchedPoints[i * 6 + 1];
curr_match.at<float>(i, 2) = matchedPoints[i * 6 + 2];
next_match.at<float>(i, 0) = matchedPoints[i * 6 + 3];
next_match.at<float>(i, 1) = matchedPoints[i * 6 + 4];
next_match.at<float>(i, 2) = matchedPoints[i * 6 + 5];
fprintf(stderr, "Matches %0.4f %0.4f %0.4f %0.4f %0.4f %0.4f\n",
curr_match.at<float>(i, 0),
curr_match.at<float>(i, 1),
curr_match.at<float>(i, 2),
next_match.at<float>(i, 0),
next_match.at<float>(i, 1),
next_match.at<float>(i, 2)
);
}
free(matchedPoints);
}
vector<SiftMatch *> ReadMATLABMatchData(const char *filename) {
fprintf(stderr, "Reading MATLAB match data from %s\n", filename);
FILE *fp = fopen(filename, "rb");
uint32_t numPts;
fread((void *)&numPts, sizeof(uint32_t), 1, fp);
vector<SiftMatch *> matches;
for (int i = 0; i < numPts; i++) {
SiftMatch *match = new SiftMatch();
SiftPoint *pt1 = new SiftPoint();
SiftPoint *pt2 = new SiftPoint();
double coords1[3];
double coords2[3];
fread((void *)coords1, sizeof(double), 3, fp);
fread((void *)coords2, sizeof(double), 3, fp);
pt1->coords3D[0] = coords1[0];
pt1->coords3D[1] = coords1[1];
pt1->coords3D[2] = coords1[2];
pt2->coords3D[0] = coords2[0];
pt2->coords3D[1] = coords2[1];
pt2->coords3D[2] = coords2[2];
match->pt1 = pt1;
match->pt2 = pt2;
matches.push_back(match);
}
return(matches);
}
// Read MATLAB before RANSAC
vector<SiftMatch *> ReadMATLABMatchDataBeforeRANSAC(const char *filename) {
fprintf(stderr, "Reading MATLAB match data before ransac from %s\n", filename);
FILE *fp = fopen(filename, "rb");
uint32_t numPts;
fread((void *)&numPts, sizeof(uint32_t), 1, fp);
int matchPointsID_i[numPts];
fread((void *)matchPointsID_i, sizeof(uint32_t), numPts, fp);
int matchPointsID_j[numPts];
fread((void *)matchPointsID_j, sizeof(uint32_t), numPts, fp);
float SIFTdes_i[numPts * 128];
fread((void *)SIFTdes_i, sizeof(float), numPts * 128, fp);
float SIFTdes_j[numPts * 128];
fread((void *)SIFTdes_j, sizeof(float), numPts * 128, fp);
vector<SiftMatch *> matches;
for (int i = 0; i < numPts; i++) {
SiftMatch *match = new SiftMatch();
SiftPoint *pt1 = new SiftPoint();
SiftPoint *pt2 = new SiftPoint();
memcpy(pt1->data, SIFTdes_i + i * 128, sizeof(float) * 128);
memcpy(pt2->data, SIFTdes_j + i * 128, sizeof(float) * 128);
matches.push_back(match);
}
return matches;
}
vector<SiftMatch *> ReadMATLABRANSAC(const char *filename, vector<int> &indices, float *Rt) {
fprintf(stderr, "Reading MATLAB RANSAC data produced using DEBUG_ransactfitRt.m from %s\n", filename);
FILE *fp = fopen(filename, "rb");
uint32_t numMatches;
fread((void *)&numMatches, sizeof(uint32_t), 1, fp);
vector<SiftMatch *> matches(numMatches);
uint32_t numLoops;
fread((void *)&numLoops, sizeof(uint32_t), 1, fp);
fprintf(stderr, "Read %d matches and %d loop indices\n", numMatches, numLoops);
float *coords3D_i = new float[numMatches * 3];
fread((void *)coords3D_i, sizeof(float), numMatches * 3, fp);
float *coords3D_j = new float[numMatches * 3];
fread((void *)coords3D_j, sizeof(float), numMatches * 3, fp);
for (int i = 0; i < numMatches; i++) {
SiftMatch *match = new SiftMatch();
SiftPoint *pt1 = new SiftPoint();
SiftPoint *pt2 = new SiftPoint();
memcpy(pt1->coords3D, coords3D_i + i * 3, sizeof(float) * 3);
memcpy(pt2->coords3D, coords3D_j + i * 3, sizeof(float) * 3);
match->pt1 = pt1;
match->pt2 = pt2;
matches[i] = match;
}
for (int i = 0; i < numLoops * 3; i++) {
int index;
fread((void *)&index, sizeof(int), 1, fp);
indices.push_back(index - 1);
}
fread((void *)Rt, sizeof(float), 12, fp);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
fprintf(stderr, "%0.4f ", Rt[i * 4 + j]);
}
fprintf(stderr, "\n");
}
delete [] coords3D_i;
delete [] coords3D_j;
return matches;
}
vector<int> ReadMATLABIndices(const char *filename) {
fprintf(stderr, "Reading MATLAB indices data from %s\n", filename);
FILE *fp = fopen(filename, "rb");
uint32_t nPairs;
fread((void *)&nPairs, sizeof(uint32_t), 1, fp);
vector<int> results;
for (int i = 0; i < nPairs; i++) {
uint32_t tmp;
fread((void *)&tmp, sizeof(uint32_t), 1, fp);
results.push_back(tmp - 1);
fread((void *)&tmp, sizeof(uint32_t), 1, fp);
results.push_back(tmp - 1);
}
return results;
}
void ReadMATLABRt(double *Rt_relative, const char *filename) {
fprintf(stderr, "Reading MATLAB Rt data from %s\n", filename);
FILE *fp = fopen(filename, "rb");
fread((void *)Rt_relative, sizeof(double), 12, fp);
fclose(fp);
fprintf(stderr, "MATLAB Rt: ");
for (int i = 0; i < 12; i++) {
fprintf(stderr, "%0.4f ", Rt_relative[i]);
}
fprintf(stderr, "\n");
}
// Modifying the original AddSiftData to add data from CPU memory, rather than
// from GPU memory. Also, ignore subsampling for now.
//
// Original function:
// void AddSiftData(SiftData &data, float *d_sift, float *d_desc, int numPts, int maxPts, float subsampling)
void AddSiftData(SiftData &data, SiftPoint *h_data, int numPts) {
// Compute new total number of points once we add new points
int newNum = data.numPts + numPts;
// If we haven't allocated enough memory for all of the points, double the
// memory
if (data.maxPts < newNum) {
// Get new amount of memory to allocate
int newMaxNum = 2 * data.maxPts;
while (newNum > newMaxNum)
newMaxNum *= 2;
// If we have host data, allocate new memory, copy over, and free old memory
if (data.h_data != NULL) {
SiftPoint *tmp = (SiftPoint *)malloc(sizeof(SiftPoint) * newMaxNum);
memcpy(tmp, data.h_data, sizeof(SiftPoint) * data.numPts);
free(data.h_data);
data.h_data = tmp;
}
// If we have device data, allocate new memory, copy over, and free old memory
if (data.d_data != NULL) {
SiftPoint *d_data = NULL;
safeCall(cudaMalloc((void**)&d_data, sizeof(SiftPoint) * newMaxNum));
safeCall(cudaMemcpy(d_data, data.d_data, sizeof(SiftPoint) * data.numPts, cudaMemcpyDeviceToDevice));
safeCall(cudaFree(data.d_data));
data.d_data = d_data;
}
data.maxPts = newMaxNum;
}
if (data.h_data != NULL) {
memcpy(data.h_data + data.numPts, h_data, sizeof(SiftPoint) * numPts);
}
if (data.d_data != NULL) {
safeCall(cudaMemcpy(data.d_data + data.numPts, h_data, sizeof(SiftPoint) * numPts, cudaMemcpyHostToDevice));
}
data.numPts = newNum;
} | 30.013216 | 112 | 0.621973 | [
"vector"
] |
0af1561f675afdf6fc30a5cd5a9cc2359fa30166 | 13,061 | cpp | C++ | glwidget.cpp | m4tob/opengl-game-tetris-3d | 025a262ec92cc3988c690f7f95466897e99a4827 | [
"MIT"
] | null | null | null | glwidget.cpp | m4tob/opengl-game-tetris-3d | 025a262ec92cc3988c690f7f95466897e99a4827 | [
"MIT"
] | null | null | null | glwidget.cpp | m4tob/opengl-game-tetris-3d | 025a262ec92cc3988c690f7f95466897e99a4827 | [
"MIT"
] | 2 | 2020-10-18T17:52:29.000Z | 2020-10-25T15:16:08.000Z | /*
* UNIVERSIDADE ESTADUAL DE FEIRA DE SANTANA - UEFS
* Engenharia da Computação
* TEC431 - Computação Gráfica
*
* Trabalho Final - 2019.2E
*
* Alunos:
* Matheus Oliveira Borges <matob@live.com>
* Luiz Ricardo Inês de Souza <lzricardo.ecomp@gmail.com>
*
* -------------------------------------------------------------------------------
*
* ============================================================================
* =============================== INSTRUÇÕES ===============================
* ============================================================================
* O jogo se baseia no tradicional jogo de tetris onde o objetivo é formar o máximo
* de linhas completas de blocos sem deixar tocar o topo da tela.
*
* -> CONTROLES:
* R : Rotaciona a peça no sentido horário (através da manipulação de matriz);
* 2 e 8 : Movimenta o tabuleiro no eixo Z. Efeito de zoom ("escala");
* 4 e 6 : Rotaciona o tabuleiro no eixo X;
* Direcionais (Esquerda,
* Direita e Baixo) : Move a peça na direção pressionada;
* ESC : Fecha o Jogo
*
*/
#include "glwidget.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <QKeyEvent>
#include <QTimer>
#include <QMessageBox>
#include <iostream>
#include <string>
using namespace std;
// Constructor
GLWidget::GLWidget()
:board(Board(10, 20)) {
setWindowTitle("Trabalho Final - Tetris 3D");
timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, SIGNAL(timeout()), this, SLOT(updateGL()));
gameCicleTimer = new QTimer(this);
gameCicleTimer->setSingleShot(true);
connect(gameCicleTimer, SIGNAL(timeout()), this, SLOT(updateGameCicle()));
cicleTime = 1000;
cubeSize = 1; // Dimensão do bloco 1 x 1 x 1
posX = 0;
posY = 0;
posZ = -(board.height * 3) * cubeSize;
angleX = 10;
angleY = 0;
stepRotate = 2 * cubeSize; // Define o passo de rotação
stepTranslate = cubeSize * 5; // Define o passo de translação
}
// Destructor
GLWidget::~GLWidget() {
glDeleteLists(cubeListIndex, 1);
glDeleteTextures(1, &_textureBorder);
glDeleteTextures(PIECE_COUNT, _texturesBox);
}
// Initialize OpenGL
void GLWidget::initializeGL() {
qglClearColor(Qt::black); // Set the clear color to a black background
glClearDepth(1); // Depth buffer setup
glEnable(GL_DEPTH_TEST); // Enable depth testing
glDepthFunc(GL_LEQUAL); // Set type of depth test
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really nice perspective calculations
setupTextures();
setupLighting();
drawCube(); // Cria o displayList utilizado para desenhar um bloco
gameCicleTimer->start(cicleTime * 2); // Inicia o ciclo de jogo
}
// Carrega e configura as texturas que serão utilizadas no projeto
void GLWidget::setupTextures() {
glEnable(GL_TEXTURE_2D);
_textureBorder = loadTexture("textures/border.png");
_texturesBox = (GLuint *) malloc(PIECE_COUNT * sizeof(GLuint));
for(int x = 1; x <= PIECE_COUNT; x++) {
string fileName = "textures/box_" + std::to_string(x);
char _fileName[fileName.size() + 1];
strcpy(_fileName, fileName.c_str());
_texturesBox[x] = loadTexture(_fileName);
}
}
// Carrega uma determinada textura a partir do nome do arquivo
GLuint GLWidget::loadTexture(QString fileName) {
QImage img = convertToGLFormat(QImage(fileName));
// Texture using linear filter
GLuint textureId;
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits());
return textureId;
}
// Realiza a configuração de iluminação e sombreamento
void GLWidget::setupLighting() {
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat ambLight[] = {1.0, 1.0, 1.0, 1.0};
GLfloat diffLight[] = {1.0, 1.0, 1.0, 1.0};
GLfloat lightPos[] = {0.0, 5.0, 5.0, 1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, ambLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffLight);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
}
/* Constrói a DisplayList responsável por gerar um dos cubos
* que irá compor a tela
*/
void GLWidget::drawCube() {
cubeListIndex = glGenLists(1);
glNewList(cubeListIndex, GL_COMPILE);
glBegin(GL_QUADS);
// Front Face
glNormal3f(0, 0, 1);
glTexCoord2f(0, 0); glVertex3f(-cubeSize, -cubeSize, cubeSize); // Bottom Left Of The Texture and Quad
glTexCoord2f(cubeSize, 0); glVertex3f( cubeSize, -cubeSize, cubeSize); // Bottom Right Of The Texture and Quad
glTexCoord2f(cubeSize, cubeSize); glVertex3f( cubeSize, cubeSize, cubeSize); // Top Right Of The Texture and Quad
glTexCoord2f(0, cubeSize); glVertex3f(-cubeSize, cubeSize, cubeSize); // Top Left Of The Texture and Quad
// Back Face
glNormal3f(0, 0, -1);
glTexCoord2f(cubeSize, 0); glVertex3f(-cubeSize, -cubeSize, -cubeSize); // Bottom Right Of The Texture and Quad
glTexCoord2f(cubeSize, cubeSize); glVertex3f(-cubeSize, cubeSize, -cubeSize); // Top Right Of The Texture and Quad
glTexCoord2f(0, cubeSize); glVertex3f( cubeSize, cubeSize, -cubeSize); // Top Left Of The Texture and Quad
glTexCoord2f(0, 0); glVertex3f( cubeSize, -cubeSize, -cubeSize); // Bottom Left Of The Texture and Quad
// Top Face
glNormal3f(0, 1, 0);
glTexCoord2f(0, cubeSize); glVertex3f(-cubeSize, cubeSize, -cubeSize); // Top Left Of The Texture and Quad
glTexCoord2f(0, 0); glVertex3f(-cubeSize, cubeSize, cubeSize); // Bottom Left Of The Texture and Quad
glTexCoord2f(cubeSize, 0); glVertex3f( cubeSize, cubeSize, cubeSize); // Bottom Right Of The Texture and Quad
glTexCoord2f(cubeSize, cubeSize); glVertex3f( cubeSize, cubeSize, -cubeSize); // Top Right Of The Texture and Quad
// Bottom Face
glNormal3f(0, -1, 0);
glTexCoord2f(cubeSize, cubeSize); glVertex3f(-cubeSize, -cubeSize, -cubeSize); // Top Right Of The Texture and Quad
glTexCoord2f(0, cubeSize); glVertex3f( cubeSize, -cubeSize, -cubeSize); // Top Left Of The Texture and Quad
glTexCoord2f(0, 0); glVertex3f( cubeSize, -cubeSize, cubeSize); // Bottom Left Of The Texture and Quad
glTexCoord2f(cubeSize, 0); glVertex3f(-cubeSize, -cubeSize, cubeSize); // Bottom Right Of The Texture and Quad
// Right face
glNormal3f(1, 0, 0);
glTexCoord2f(cubeSize, 0); glVertex3f( cubeSize, -cubeSize, -cubeSize); // Bottom Right Of The Texture and Quad
glTexCoord2f(cubeSize, cubeSize); glVertex3f( cubeSize, cubeSize, -cubeSize); // Top Right Of The Texture and Quad
glTexCoord2f(0, cubeSize); glVertex3f( cubeSize, cubeSize, cubeSize); // Top Left Of The Texture and Quad
glTexCoord2f(0, 0); glVertex3f( cubeSize, -cubeSize, cubeSize); // Bottom Left Of The Texture and Quad
// Left Face
glNormal3f(-1, 0, 0);
glTexCoord2f(0, 0); glVertex3f(-cubeSize, -cubeSize, -cubeSize); // Bottom Left Of The Texture and Quad
glTexCoord2f(cubeSize, 0); glVertex3f(-cubeSize, -cubeSize, cubeSize); // Bottom Right Of The Texture and Quad
glTexCoord2f(cubeSize, cubeSize); glVertex3f(-cubeSize, cubeSize, cubeSize); // Top Right Of The Texture and Quad
glTexCoord2f(0, cubeSize); glVertex3f(-cubeSize, cubeSize, -cubeSize); // Top Left Of The Texture and Quad
glEnd();
glEndList();
}
// OpenGL painting
void GLWidget::paintGL() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(posX, posY, posZ);
glRotatef(angleX, 0, 1, 0);
glRotatef(angleY, 1, 0, 0);
paintBoardBorder(); // Constrói a borda
paintBoardContent(); // Constrói o conteúdo da board
// Framerate control
timer->start(20);
}
/* Renderiza as bordas da board, facilitando a visualização
* dos limites.
*/
void GLWidget::paintBoardBorder() {
glBindTexture(GL_TEXTURE_2D, _textureBorder);
glPushMatrix();
// posiciona a origem na parte superior esquerda da board
glTranslatef(-(board.width * cubeSize), (board.height * cubeSize), 0);
// renderiza a borda superior
glPushMatrix();
for(int x = 0; x < (board.width + 2); x++) {
glCallList(cubeListIndex);
glTranslatef(cubeSize * 2, 0, 0);
}
glPopMatrix();
// renderiza a borda inferior
glPushMatrix();
// posiciona a origem na parte inferior esquerda da board
glTranslatef(0, -(board.height + 1) * (cubeSize * 2), 0);
for(int x = 0; x < (board.width + 2); x++) {
glCallList(cubeListIndex);
glTranslatef(cubeSize * 2, 0, 0);
}
glPopMatrix();
// renderiza a borda esquerda
glPushMatrix();
// posiciona a origem um bloco abaixo da parte superior esquerda da board
glTranslatef(0, -(cubeSize * 2), 0);
for(int y = 0; y < board.height; y++) {
glCallList(cubeListIndex);
glTranslatef(0, -(cubeSize * 2), 0);
}
glPopMatrix();
// renderiza a borda direita
glPushMatrix();
// posiciona a origem um bloco abaixo da parte superior direita da board
glTranslatef((board.width + 1) * (cubeSize * 2), -(cubeSize * 2), 0);
for(int y = 0; y < board.height; y++) {
glCallList(cubeListIndex);
glTranslatef(0, -(cubeSize * 2), 0);
}
glPopMatrix();
glPopMatrix();
}
// Renderiza o conteúdo da board com as peças já posicionadas
void GLWidget::paintBoardContent() {
glTranslatef(-((board.width - 2) * cubeSize), ((board.height - 2) * cubeSize), 0);
for(int x = 0; x < board.width; x++) {
glPushMatrix();
for(int y = 0; y < board.height; y++) {
if(board.currentBoard[x][y] > 0 && board.currentBoard[x][y] <= PIECE_COUNT) {
glBindTexture(GL_TEXTURE_2D, _texturesBox[board.currentBoard[x][y]]);
glCallList(cubeListIndex);
}
glTranslatef(0, -(cubeSize * 2), 0);
}
glPopMatrix();
glTranslatef(cubeSize * 2, 0, 0);
}
}
// This is called when the OpenGL window is resized
void GLWidget::resizeGL(int width, int height) {
// Prevent divide by zero (in the gluPerspective call)
if (height == 0)
height = 1;
glViewport(0, 0, width, height); // Reset current viewport
glMatrixMode(GL_PROJECTION); // Select projection matrix
glLoadIdentity(); // Reset projection matrix
gluPerspective(45, static_cast<GLfloat>(width)/height, 0.1, 1000); // Calculate aspect ratio
glMatrixMode(GL_MODELVIEW); // Select modelview matrix
glLoadIdentity(); // Reset modelview matrix
}
// Executa a atualização do ciclo de jogo
void GLWidget::updateGameCicle() {
board.nextGameCicle();
if(board.gameOver) {
gameOver();
} else // Caso não tenha chegado ao fim, inicia o timer novamente
gameCicleTimer->start(cicleTime);
}
void GLWidget::gameOver() {
string msgPoints = " Você conseguiu " + std::to_string(board.score) + " ponto" + (board.score > 1 ? "s" : "") + ".";
string msg = "GAME OVER!" + (board.score > 1 ? msgPoints : "");
char _msg[msg.size() + 1];
strcpy(_msg, msg.c_str());
QMessageBox msgBox;
msgBox.setText(_msg);
msgBox.exec();
close();
}
// Handler de eventos do teclado
void GLWidget::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_R:
board.rotate();
break;
case Qt::Key_Down:
board.moveDown();
break;
case Qt::Key_Left:
board.moveLeft();
break;
case Qt::Key_Right:
board.moveRight();
break;
case Qt::Key_8:
posZ += stepTranslate;
break;
case Qt::Key_2:
posZ -= stepTranslate;
break;
case Qt::Key_4:
angleX -= stepRotate;
angleX = angleX < 0 ? angleX + 360 : angleX;
break;
case Qt::Key_6:
angleX += stepRotate;
angleX = angleX > 360 ? angleX - 360 : angleX;
break;
case Qt::Key_Escape:
close();
break;
default:
QGLWidget::keyPressEvent(event);
}
}
| 37 | 128 | 0.601562 | [
"3d"
] |
0af3669903df3e334bc7fb37b7ddff535b4c0b5a | 26,291 | cc | C++ | src/trusted/validator_arm/validator_tests.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 4 | 2015-10-27T04:43:02.000Z | 2021-08-13T08:21:45.000Z | src/trusted/validator_arm/validator_tests.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | null | null | null | src/trusted/validator_arm/validator_tests.cc | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 1 | 2015-11-08T10:18:42.000Z | 2015-11-08T10:18:42.000Z | /*
* Copyright 2010 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
/*
* Unit tests for the ARM validator
*
* These tests use the google-test framework (gtest for short) to exercise the
* ARM validator. The tests currently fall into two rough categories:
* 1. Simple method-level tests that exercise the validator's primitive
* capabilities, and
* 2. Instruction pattern tests that run the entire validator.
*
* All instruction pattern tests use hand-assembled machine code fragments,
* embedded as byte arrays. This is somewhat ugly, but deliberate: it isolates
* these tests from gas, which may be buggy or not installed. It also lets us
* hand-craft malicious bit patterns that gas may refuse to produce.
*
* To write a new instruction pattern, or make sense of an existing one, use the
* ARMv7-A ARM (available online). Instructions in this file are written as
* 32-bit integers so the hex encoding matches the docs.
*/
#include <vector>
#include <string>
#include <sstream>
#include "gtest/gtest.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/trusted/validator_arm/validator.h"
using std::vector;
using std::string;
using std::ostringstream;
using nacl_arm_dec::Register;
using nacl_arm_dec::RegisterList;
using nacl_arm_dec::Instruction;
using nacl_arm_val::SfiValidator;
using nacl_arm_val::ProblemSink;
using nacl_arm_val::CodeSegment;
namespace {
#ifdef __BIG_ENDIAN__
#error This test will only succeed on a little-endian machine. Sorry.
#endif
/*
* Since ARM instructions are always little-endian, on a little-endian machine
* we can represent them as ints. This makes things somewhat easier to read
* below.
*/
typedef uint32_t arm_inst;
/*
* We use these parameters to initialize the validator, below. They are
* somewhat different from the parameters used in real NaCl systems, to test
* degrees of validator freedom that we don't currently exercise in prod.
*/
// Number of bytes in each bundle. Theoretically can also be 32 - not tested.
static const uint32_t kBytesPerBundle = 16;
// Limit code to 512MiB.
static const uint32_t kCodeRegionSize = 0x20000000;
// Limit data to 1GiB.
static const uint32_t kDataRegionSize = 0x40000000;
// Untrusted code must not write to r9.
static const RegisterList kAbiReadOnlyRegisters = Register(9);
// The stack pointer can be used for "free" loads and stores.
static const RegisterList kAbiDataAddrRegisters = nacl_arm_dec::kRegisterStack;
/*
* Support code
*/
// Simply records the arguments given to report_problem, below.
struct ProblemRecord {
uint32_t vaddr;
nacl_arm_dec::SafetyLevel safety;
nacl::string problem_code;
uint32_t ref_vaddr;
};
// A ProblemSink that records all calls (implementation of the Spy pattern)
class ProblemSpy : public ProblemSink {
public:
virtual void report_problem(uint32_t vaddr, nacl_arm_dec::SafetyLevel safety,
const nacl::string &problem_code, uint32_t ref_vaddr = 0) {
_problems.push_back(
(ProblemRecord) { vaddr, safety, problem_code, ref_vaddr });
}
/*
* We want *all* the errors that the validator produces. Note that this means
* we're not testing the should_continue functionality. This is probably
* okay.
*/
virtual bool should_continue() { return true; }
vector<ProblemRecord> &get_problems() { return _problems; }
private:
vector<ProblemRecord> _problems;
};
/*
* Coordinates the fixture objects used by test cases below. This is
* forward-declared to the greatest extent possible so we can get on to the
* important test stuff below.
*/
class ValidatorTests : public ::testing::Test {
protected:
ValidatorTests();
// Utility method for validating a sequence of bytes.
bool validate(const arm_inst *pattern,
size_t inst_count,
uint32_t start_addr,
ProblemSink *sink);
/*
* Tests an arbitrary-size instruction fragment that is expected to pass.
* Does not modulate or rewrite the pattern in any way.
*/
void validation_should_pass(const arm_inst *pattern,
size_t inst_count,
uint32_t base_addr,
const string &msg);
/*
* Tests a two-instruction pattern that's expected to pass, at each possible
* bundle alignment. This also tries the pattern across bundle boundaries,
* and makes sure it fails.
*/
void validation_should_pass2(const arm_inst *pattern,
size_t inst_count,
uint32_t base_addr,
const string &msg);
/*
* Tests a pattern that is forbidden in the SFI model.
*
* Note that the 'msg1' and 'msg2' parameters are merely concatentated in the
* output.
*/
vector<ProblemRecord> validation_should_fail(const arm_inst *pattern,
size_t inst_count,
uint32_t base_addr,
const string &msg);
SfiValidator _validator;
};
/*
* Primitive tests checking various constructor properties. Any of these
* failing would be a very bad sign indeed.
*/
TEST_F(ValidatorTests, RecognizesDataAddressRegisters) {
/*
* Note that the logic below needs to be kept in sync with the definition
* of kAbiDataAddrRegisters at the top of this file.
*
* This test is pretty trivial -- we can exercise the data_address_register
* functionality more deeply with pattern tests below.
*/
for (int i = 0; i < 16; i++) {
Register r(i);
if (r == nacl_arm_dec::kRegisterStack) {
EXPECT_TRUE(_validator.is_data_address_register(r))
<< "Stack pointer must be a data address register.";
} else {
EXPECT_FALSE(_validator.is_data_address_register(r))
<< "Only the stack pointer must be a data address register.";
}
}
}
TEST_F(ValidatorTests, GeneratesCorrectMasksFromSizes) {
EXPECT_EQ(0xC0000000, _validator.data_address_mask());
EXPECT_EQ(0xE000000F, _validator.code_address_mask());
// Reinitialize the validator to test a different bundle size.
_validator = SfiValidator(32,
kCodeRegionSize,
kDataRegionSize,
kAbiReadOnlyRegisters,
kAbiDataAddrRegisters);
EXPECT_EQ(0xC0000000, _validator.data_address_mask())
<< "Changes in bundle size should not affect the data mask.";
EXPECT_EQ(0xE000001F, _validator.code_address_mask())
<< "Changes in bundle size must affect the code mask.";
}
/*
* Code validation tests
*/
// This is where untrusted code starts. Most tests use this.
static const uint32_t kDefaultBaseAddr = 0x20000;
/*
* Here are examples of every form of safe store permitted in a Native Client
* program. These stores have common properties:
* 1. The high nibble is 0, to allow tests to write an arbitrary predicate.
* 2. They address memory only through r1.
* 3. They do not do anything dumb, like try to alter SP or PC.
*/
struct AnnotatedInstruction {
arm_inst inst;
const char *about;
};
static const AnnotatedInstruction examples_of_safe_stores[] = {
// Single-register stores
{ 0x05810000, "str r0, [r1]: simple no-displacement store" },
{ 0x05810123, "str r0, [r1, #0x123]: positive displacement" },
{ 0x05010123, "str r0, [r1, #-0x123]: negative displacement" },
{ 0x05A10123, "str r0, [r1, #0x123]!: positive disp + writeback" },
{ 0x05210123, "str r0, [r1, #-0x123]!: negative disp + writeback" },
{ 0x04810123, "str r0, [r1], #0x123: positive post-indexing" },
{ 0x04010123, "str r0, [r1], #-0x123: negative post-indexing" },
{ 0x06810002, "str r0, [r1], r2: positive register post-indexing" },
{ 0x06010002, "str r0, [r1], -r2: negative register post-indexing" },
// Two-register store
{ 0x01C120F0, "strd r2, r3, [r1]: basic 64-bit store" },
{ 0x01C124F2, "strd r2, r3, [r1, #42]: positive disp 64-bit store" },
{ 0x014124F2, "strd r2, r3, [r1, #-42]: negative disp 64-bit store" },
{ 0x01E124F2, "strd r2, r3, [r1, #42]!: positive disp 64-bit store + wb" },
{ 0x016124F2, "strd r2, r3, [r1, #-42]!: negative disp 64-bit store + wb" },
{ 0x00C124F2, "strd r2, r3, [r1], #42: post-inc 64-bit store" },
{ 0x004124F2, "strd r2, r3, [r1], #-42: post-dec 64-bit store" },
// Store-exclusive
{ 0x01810F92, "strex r0, r2, [r1]: store exclusive" },
// Store-multiple
{ 0x0881FFFF, "stm r1, { r0-r15 }: store multiple, no writeback" },
{ 0x08A1FFFF, "stm r1!, { r0-r15 }: store multiple, writeback" },
// Stores from the floating point / vector register file
// These all compile to STC instructions.
{ 0x0D810B00, "vstr d0, [r1]: direct vector store" },
{ 0x0D810B99, "vstr d0, [r1, #0x99]: positive displacement vector store" },
{ 0x0D010B99, "vstr d0, [r1, #-0x99]: negative displacement vector store" },
{ 0x0C810BBF, "vstmia r1, { d0-d7 }: no writeback" },
{ 0x0CA10BBF, "vstmia r1!, { d0-d7 }: writeback" },
};
static const AnnotatedInstruction examples_of_safe_masks[] = {
{ 0x03C11103, "bic r1, r1, #0xC0000000: simple in-place mask (form 1)" },
{ 0x03C114C0, "bic r1, r1, #0xC0000000: simple in-place mask (form 2)" },
{ 0x03C314C0, "bic r1, r3, #0xC0000000: mask with register move" },
{ 0x03C114FF, "bic r1, r1, #0xFF000000: overzealous but correct mask" },
};
TEST_F(ValidatorTests, SafeMaskedStores) {
/*
* Produces many examples of masked stores using the safe store table (above)
* and the list of possible masking instructions (below).
*
* Each mask instruction must leave a valid (data) address in r1.
*/
for (unsigned p = 0; p < 15; p++) {
/*
* Conditionally executed instructions have a top nibble of 0..14.
* 15 is an escape sequence used to fit in additional encodings.
*/
arm_inst predicate = p << 28;
for (unsigned m = 0; m < NACL_ARRAY_SIZE(examples_of_safe_masks); m++) {
for (unsigned s = 0; s < NACL_ARRAY_SIZE(examples_of_safe_stores); s++) {
ostringstream message;
message << examples_of_safe_masks[m].about
<< ", "
<< examples_of_safe_stores[s].about
<< " (predicate #" << p << ")";
arm_inst program[] = {
examples_of_safe_masks[m].inst | predicate,
examples_of_safe_stores[s].inst | predicate,
};
validation_should_pass2(program,
2,
kDefaultBaseAddr,
message.str());
}
}
}
}
/*
* These stores can't be predicated, so we must use a different, simpler
* fixture generator.
*/
static const AnnotatedInstruction examples_of_safe_unconditional_stores[] = {
// Vector stores
{ 0xF481A5AF, "vst2.16 {d10[2],d12[2]}, [r1]: simple vector store" },
{ 0xF401A64F, "vst1.16 {d10-d12}, [r1]: larger vector store" },
{ 0xF4010711, "vst1.8 {d0}, [r1, :64], r1: register post-increment" },
};
TEST_F(ValidatorTests, SafeUnconditionalMaskedStores) {
/*
* Produces many examples of unconditional masked stores using the safe
* unconditional store table (above) and the list of possible masking
* instructions (below).
*
* Each mask instruction must leave a valid (data) address in r1.
*/
// These instructions can't be predicated.
arm_inst predicate = 0xE0000000; // "always"
for (unsigned m = 0; m < NACL_ARRAY_SIZE(examples_of_safe_masks); m++) {
for (unsigned s = 0;
s < NACL_ARRAY_SIZE(examples_of_safe_unconditional_stores);
s++) {
ostringstream message;
message << examples_of_safe_masks[m].about
<< ", "
<< examples_of_safe_unconditional_stores[s].about;
arm_inst program[] = {
examples_of_safe_masks[m].inst | predicate,
examples_of_safe_unconditional_stores[s].inst,
};
validation_should_pass2(program,
2,
kDefaultBaseAddr,
message.str());
}
}
}
TEST_F(ValidatorTests, SafeConditionalStores) {
/*
* Produces many examples of conditional stores using the safe store table
* (above) and the list of possible conditional guards (below).
*
* Each conditional guard must set the Z flag iff r1 contains a valid address.
*/
static const AnnotatedInstruction guards[] = {
{ 0x03110103, "tst r1, #0xC0000000: precise guard, GCC encoding" },
{ 0x031104C0, "tst r1, #0xC0000000: precise guard, alternative encoding" },
{ 0x031101C3, "tst r1, #0xF0000000: overzealous (but correct) guard" },
};
/*
* Currently we only support *unconditional* conditional stores.
* Meaning the guard is unconditional and the store is if-equal.
*/
arm_inst guard_predicate = 0xE0000000, store_predicate = 0x00000000;
for (unsigned m = 0; m < NACL_ARRAY_SIZE(guards); m++) {
for (unsigned s = 0; s < NACL_ARRAY_SIZE(examples_of_safe_stores); s++) {
ostringstream message;
message << guards[m].about
<< ", "
<< examples_of_safe_stores[s].about
<< " (predicate #" << guard_predicate << ")";
arm_inst program[] = {
guards[m].inst | guard_predicate,
examples_of_safe_stores[s].inst | store_predicate,
};
validation_should_pass2(program,
2,
kDefaultBaseAddr,
message.str());
}
}
}
TEST_F(ValidatorTests, InvalidMasksOnSafeStores) {
static const AnnotatedInstruction examples_of_invalid_masks[] = {
{ 0x01A01003, "mov r1, r3: not even a mask" },
{ 0x03C31000, "bic r1, r3, #0: doesn't mask anything" },
{ 0x03C31102, "bic r1, r3, #0x80000000: doesn't mask enough bits" },
{ 0x03C311C1, "bic r1, r3, #0x70000000: masks the wrong bits" },
};
for (unsigned p = 0; p < 15; p++) {
/*
* Conditionally executed instructions have a top nibble of 0..14.
* 15 is an escape sequence used to fit in additional encodings.
*/
arm_inst predicate = p << 28;
for (unsigned m = 0; m < NACL_ARRAY_SIZE(examples_of_invalid_masks); m++) {
for (unsigned s = 0; s < NACL_ARRAY_SIZE(examples_of_safe_stores); s++) {
ostringstream message;
message << examples_of_invalid_masks[m].about
<< ", "
<< examples_of_safe_stores[s].about
<< " (predicate #" << p << ")";
arm_inst program[] = {
examples_of_invalid_masks[m].inst | predicate,
examples_of_safe_stores[s].inst | predicate,
};
vector<ProblemRecord> problems =
validation_should_fail(program,
NACL_ARRAY_SIZE(program),
kDefaultBaseAddr,
message.str());
// EXPECT/continue rather than ASSERT so that we run the other cases.
EXPECT_EQ(1U, problems.size());
if (problems.size() != 1) continue;
ProblemRecord first = problems[0];
EXPECT_EQ(kDefaultBaseAddr + 4, first.vaddr)
<< "Problem report must point to the store: "
<< message.str();
EXPECT_EQ(nacl_arm_dec::MAY_BE_SAFE, first.safety)
<< "Store should not be unsafe even though mask is bogus: "
<< message.str();
EXPECT_EQ(nacl::string(nacl_arm_val::kProblemUnsafeStore),
first.problem_code)
<< message;
}
}
}
}
TEST_F(ValidatorTests, InvalidGuardsOnSafeStores) {
static const AnnotatedInstruction invalid_guards[] = {
{ 0x03110100, "tst r1, #0: always sets Z" },
{ 0x03110102, "tst r1, #0x80000000: doesn't test enough bits" },
{ 0x031101C1, "tst r1, #0x70000000: doesn't test the right bits" },
{ 0x01A01003, "mov r1, r3: not even a test" },
{ 0x03310103, "teq r1, #0xC0000000: does the inverse of what we want" },
{ 0x03510103, "cmp r1, #0xC0000000: does the inverse of what we want" },
};
/*
* We don't currently support conditional versions of the conditional guard.
*
* TODO(cbiffle): verify this in the test
*/
static const arm_inst guard_predicate = 0xE0000000; // unconditional
static const arm_inst store_predicate = 0x00000000; // if-equal
for (unsigned m = 0; m < NACL_ARRAY_SIZE(invalid_guards); m++) {
for (unsigned s = 0; s < NACL_ARRAY_SIZE(examples_of_safe_stores); s++) {
ostringstream message;
message << invalid_guards[m].about
<< ", "
<< examples_of_safe_stores[s].about;
arm_inst program[] = {
invalid_guards[m].inst | guard_predicate,
examples_of_safe_stores[s].inst | store_predicate,
};
vector<ProblemRecord> problems =
validation_should_fail(program,
NACL_ARRAY_SIZE(program),
kDefaultBaseAddr,
message.str());
// EXPECT/continue rather than ASSERT so that we run the other cases.
EXPECT_EQ(1U, problems.size());
if (problems.size() != 1) continue;
ProblemRecord first = problems[0];
EXPECT_EQ(kDefaultBaseAddr + 4, first.vaddr)
<< "Problem report must point to the store: "
<< message.str();
EXPECT_EQ(nacl_arm_dec::MAY_BE_SAFE, first.safety)
<< "Store should not be unsafe even though guard is bogus: "
<< message.str();
EXPECT_EQ(nacl::string(nacl_arm_val::kProblemUnsafeStore),
first.problem_code)
<< message;
}
}
}
TEST_F(ValidatorTests, ValidMasksOnUnsafeStores) {
static const AnnotatedInstruction invalid_stores[] = {
{ 0x07810002, "str r0, [r1, r2]: register-plus-register addressing" },
{ 0x07010002, "str r0, [r1, -r2]: register-minus-register addressing" },
{ 0x07810182, "str r0, [r1, r2, LSL #3]: complicated addressing 1" },
{ 0x07018482, "str r0, [r1, -r2, ASR #16]: complicated addressing 2" },
};
for (unsigned p = 0; p < 15; p++) {
/*
* Conditionally executed instructions have a top nibble of 0..14.
* 15 is an escape sequence used to fit in additional encodings.
*/
arm_inst predicate = p << 28;
for (unsigned m = 0; m < NACL_ARRAY_SIZE(examples_of_safe_masks); m++) {
for (unsigned s = 0; s < NACL_ARRAY_SIZE(invalid_stores); s++) {
ostringstream message;
message << examples_of_safe_masks[m].about
<< ", "
<< invalid_stores[s].about
<< " (predicate #" << p << ")";
arm_inst program[] = {
examples_of_safe_masks[m].inst | predicate,
invalid_stores[s].inst | predicate,
};
vector<ProblemRecord> problems =
validation_should_fail(program,
NACL_ARRAY_SIZE(program),
kDefaultBaseAddr,
message.str());
// EXPECT/continue rather than ASSERT so that we run the other cases.
EXPECT_EQ(1U, problems.size());
if (problems.size() != 1) continue;
ProblemRecord first = problems[0];
EXPECT_EQ(kDefaultBaseAddr + 4, first.vaddr)
<< "Problem report must point to the store: "
<< message.str();
EXPECT_NE(nacl_arm_dec::MAY_BE_SAFE, first.safety)
<< "Store must be flagged by the decoder as unsafe: "
<< message.str();
/*
* Note that we expect kProblemUnsafe, *not* kProblemUnsafeStore. This
* is because the store instructions themselves, in isolation, are
* unsafe to appear anywhere in a Native Client program -- whereas
* kProblemUnsafeStore indicates a legitimate store used in an unsafe
* manner.
*/
EXPECT_EQ(nacl::string(nacl_arm_val::kProblemUnsafe),
first.problem_code)
<< message;
}
}
}
}
TEST_F(ValidatorTests, ScaryUndefinedInstructions) {
/*
* These instructions are undefined today (ARMv7-A) but may become defined
* tomorrow. We ban them since we can't reason about their side effects.
*/
static const AnnotatedInstruction undefined_insts[] = {
{ 0xE05DEA9D, "An undefined instruction in the multiply space" },
};
for (unsigned i = 0; i < NACL_ARRAY_SIZE(undefined_insts); i++) {
arm_inst program[] = { undefined_insts[i].inst };
vector<ProblemRecord> problems =
validation_should_fail(program,
NACL_ARRAY_SIZE(program),
kDefaultBaseAddr,
undefined_insts[i].about);
// EXPECT/continue rather than ASSERT so that we run the other cases.
EXPECT_EQ(1U, problems.size());
if (problems.size() != 1) continue;
ProblemRecord first = problems[0];
EXPECT_EQ(kDefaultBaseAddr, first.vaddr)
<< "Problem report must point to the only instruction: "
<< undefined_insts[i].about;
EXPECT_EQ(nacl_arm_dec::UNDEFINED, first.safety)
<< "Instruction must be flagged as UNDEFINED: "
<< undefined_insts[i].about;
EXPECT_EQ(nacl::string(nacl_arm_val::kProblemUnsafe),
first.problem_code)
<< "Instruction must be marked unsafe: "
<< undefined_insts[i].about;
}
}
TEST_F(ValidatorTests, LessScaryUndefinedInstructions) {
/*
* These instructions are specified by ARM as *permanently* undefined, so we
* treat them as a reliable Illegal Instruction trap.
*/
static const AnnotatedInstruction perm_undefined[] = {
{ 0xE7FFDEFE, "permanently undefined instruction produced by LLVM" },
};
for (unsigned i = 0; i < NACL_ARRAY_SIZE(perm_undefined); i++) {
arm_inst program[] = { perm_undefined[i].inst };
validation_should_pass(program,
1,
kDefaultBaseAddr,
perm_undefined[i].about);
}
}
/*
* Implementation of the ValidatorTests utility methods. These are documented
* toward the top of this file.
*/
ValidatorTests::ValidatorTests()
: _validator(kBytesPerBundle,
kCodeRegionSize,
kDataRegionSize,
kAbiReadOnlyRegisters,
kAbiDataAddrRegisters) {}
bool ValidatorTests::validate(const arm_inst *pattern,
size_t inst_count,
uint32_t start_addr,
ProblemSink *sink) {
// We think in instructions; CodeSegment thinks in bytes.
const uint8_t *bytes = reinterpret_cast<const uint8_t *>(pattern);
CodeSegment segment(bytes, start_addr, inst_count * sizeof(arm_inst));
vector<CodeSegment> segments;
segments.push_back(segment);
return _validator.validate(segments, sink);
}
void ValidatorTests::validation_should_pass(const arm_inst *pattern,
size_t inst_count,
uint32_t base_addr,
const string &msg) {
ProblemSpy spy;
bool validation_result = validate(pattern, inst_count, base_addr, &spy);
ASSERT_TRUE(validation_result) << msg << " should pass at " << base_addr;
vector<ProblemRecord> &problems = spy.get_problems();
EXPECT_EQ(0U, problems.size()) << msg
<< " should have no problems when located at " << base_addr;
}
void ValidatorTests::validation_should_pass2(const arm_inst *pattern,
size_t inst_count,
uint32_t base_addr,
const string &msg) {
// A couple sanity checks for correct usage.
ASSERT_EQ(2U, inst_count)
<< "This routine only supports 2-instruction patterns.";
ASSERT_TRUE(
_validator.bundle_for_address(base_addr).begin_addr() == base_addr)
<< "base_addr parameter must be bundle-aligned";
uint32_t last_addr = base_addr + (kBytesPerBundle - 4);
// Try the legitimate (non-overlapping) variations:
for (uint32_t addr = base_addr; addr < last_addr; addr += 4) {
validation_should_pass(pattern, inst_count, addr, msg);
}
// Make sure it fails over bundle boundaries.
ProblemSpy spy;
bool overlap_result = validate(pattern, inst_count, last_addr, &spy);
EXPECT_FALSE(overlap_result)
<< msg << " should fail at overlapping address " << last_addr;
vector<ProblemRecord> &problems = spy.get_problems();
ASSERT_EQ(1U, problems.size())
<< msg << " should have 1 problem at overlapping address " << last_addr;
ProblemRecord first = problems[0];
EXPECT_EQ(last_addr, first.vaddr)
<< "Problem in valid but mis-aligned pseudo-instruction ("
<< msg
<< ") must be reported at end of bundle";
EXPECT_EQ(nacl_arm_dec::MAY_BE_SAFE, first.safety)
<< "Just crossing a bundle should not make a safe instruction unsafe: "
<< msg;
EXPECT_EQ(nacl::string(nacl_arm_val::kProblemPatternCrossesBundle),
first.problem_code);
}
vector<ProblemRecord> ValidatorTests::validation_should_fail(
const arm_inst *pattern,
size_t inst_count,
uint32_t base_addr,
const string &msg) {
/*
* TODO(cbiffle): test at various overlapping and non-overlapping addresses,
* like above. Not that this is a spectacularly likely failure case, but
* it's worth exercising.
*/
ProblemSpy spy;
bool validation_result = validate(pattern, inst_count, base_addr, &spy);
EXPECT_FALSE(validation_result) << "Expected to fail: " << msg;
vector<ProblemRecord> problems = spy.get_problems();
// Would use ASSERT here, but cannot ASSERT in non-void functions :-(
EXPECT_NE(0U, problems.size())
<< "Must report validation problems: " << msg;
// The rest of the checking is done in the caller.
return problems;
}
}; // anonymous namespace
// Test driver function.
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 37.081805 | 80 | 0.637442 | [
"vector",
"model"
] |
0af3f47f9a3ed8900a7806fa2c90c448c74797c6 | 6,534 | cpp | C++ | tags/20081005_PRE_ENGINE_REFACTORY/ProjectFootball/src/state/CStateQuickPlay.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | tags/20081005_PRE_ENGINE_REFACTORY/ProjectFootball/src/state/CStateQuickPlay.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | tags/20081005_PRE_ENGINE_REFACTORY/ProjectFootball/src/state/CStateQuickPlay.cpp | dividio/projectfootball | 3c0b94937de2e3cd6e7daf9d3b4942fda974f20c | [
"Zlib"
] | null | null | null | /******************************************************************************
* Copyright (C) 2008 - Ikaro Games www.ikarogames.com *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* *
******************************************************************************/
#include <stdio.h>
#include "CStateQuickPlay.h"
#include "CStateMonitor.h"
#include "../db/sqlite/dao/factory/CDAOFactorySQLite.h"
#include "../engine/CGameEngine.h"
#include "../utils/CLog.h"
CStateQuickPlay::CStateQuickPlay()
:CState()
{
CLog::getInstance()->debug("CStateQuickPlay()");
}
CStateQuickPlay::~CStateQuickPlay()
{
CLog::getInstance()->debug("~CStateQuickPlay()");
}
CStateQuickPlay* CStateQuickPlay::getInstance()
{
static CStateQuickPlay instance;
return &instance;
}
void CStateQuickPlay::enter()
{
newQuickGame();
CStateMonitor::getInstance()->enter();
}
void CStateQuickPlay::forcedLeave()
{
CStateMonitor::getInstance()->forcedLeave();
CGameEngine::getInstance()->unloadCurrentGame();
deleteQuickGames();
}
bool CStateQuickPlay::leave()
{
if( CStateMonitor::getInstance()->leave() ){
CGameEngine::getInstance()->unloadCurrentGame();
deleteQuickGames();
return true;
}else{
return false;
}
}
void CStateQuickPlay::update()
{
CStateMonitor::getInstance()->update();
}
void CStateQuickPlay::newQuickGame()
{
// To create a new quickGame, first create a new game
IMasterDAOFactory *masterDatabase = CGameEngine::getInstance()->getCMasterDAOFactory();
const CPfUsers *user = CGameEngine::getInstance()->getCurrentUser();
if( user==NULL || user->getXUser()==0 ){
CLog::getInstance()->exception("[CStateQuickPlay::newQuickGame] User not defined");
}
const char *str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string filename = "data/database/savedgames/";
srand(time(NULL));
for( int i=0; i<8; i++ ){
filename += str[rand()%52];
}
filename += ".sql3";
std::string gameName = "QUICK_PLAY - ";
while( gameName.length()<50 ){
gameName += str[rand()%52];
}
CDate nowDate;
CPfGames game;
game.setDLastSaved(nowDate);
game.setSDriverName("SQLite");
game.setSConnectionString(filename);
game.setSGameName(gameName);
game.setSGameType(S_GAME_TYPE_QUICKPLAY);
game.setXFkUser(user->getXUser());
masterDatabase->getIPfGamesDAO()->insertReg(&game);
CDAOFactorySQLite *daoFactory = new CDAOFactorySQLite(filename);
daoFactory->beginTransaction();
daoFactory->executeScriptFile("data/database/scripts/tables.sql");
daoFactory->executeScriptFile("data/database/scripts/view_ranking.sql");
daoFactory->executeScriptFile("data/database/scripts/indexes.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_countries.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_teams.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_teamplayers.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_competitions.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_registeredteams.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_matches.sql");
daoFactory->executeScriptFile("data/database/scripts/inserts_gameoptions.sql");
daoFactory->commit();
IPfGameStatesDAO *gameStateDAO = daoFactory->getIPfGameStatesDAO();
IPfTeamsDAO *teamsDAO = daoFactory->getIPfTeamsDAO();
std::vector<CPfTeams*> *teamsList = teamsDAO->findTeams();
if( teamsList->empty() ){
CLog::getInstance()->exception("[CStateQuickPlay::newQuickGame] Teams list is empty");
}
CPfGameStates playerTeam;
playerTeam.setSState(S_STATE_PLAYERTEAM);
playerTeam.setSValue(teamsList->operator[](rand()%20)->getXTeam_str());
gameStateDAO->insertReg(&playerTeam);
CPfGameStates newGameState;
newGameState.setSState(S_STATE_NEWGAME);
newGameState.setSValue("false");
gameStateDAO->insertReg(&newGameState);
teamsDAO->freeVector(teamsList);
delete daoFactory;
// Second, test that this new game is correctly created
std::vector<CPfGames*> *gamesList = masterDatabase->getIPfGamesDAO()->findBySGameName(gameName);
if( gamesList->size()!=1){
CLog::getInstance()->exception("[CStateQuickPlay::newQuickGame] New game isn't correctly created [gamesList->size():%d]", gamesList->size());
}
// Third, load the quick game
CGameEngine::getInstance()->loadGame(gamesList->operator[](0)->getXGame());
masterDatabase->getIPfGamesDAO()->freeVector(gamesList);
}
void CStateQuickPlay::deleteQuickGames()
{
IPfGamesDAO *gamesDAO = CGameEngine::getInstance()->getCMasterDAOFactory()->getIPfGamesDAO();
std::vector<CPfGames*> *gamesList = gamesDAO->findBySGameType(S_GAME_TYPE_QUICKPLAY);
std::vector<CPfGames*>::iterator it;
for( it=gamesList->begin(); it!=gamesList->end(); it++ ){
CPfGames *game = (*it);
if( game->getSDriverName()=="SQLite" ){
remove(game->getSConnectionString().c_str());
}
gamesDAO->deleteReg(game);
}
gamesDAO->freeVector(gamesList);
}
| 39.125749 | 149 | 0.6206 | [
"vector"
] |
e400adf978d9b8966c4a192e647d459a1137fcaa | 9,977 | hpp | C++ | graphics/source/environment/device.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | graphics/source/environment/device.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | graphics/source/environment/device.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | #ifndef IRGLAB_DEVICE_HPP
#define IRGLAB_DEVICE_HPP
#include "external/external.hpp"
#if !defined(NDEBUG)
#include "debug_printer.hpp"
#endif
#include "environment.hpp"
#include "window.hpp"
namespace il
{
struct [[maybe_unused]] queue_family_indices
{
std::optional<unsigned int> graphics_family;
std::optional<unsigned int> present_family;
std::optional<unsigned int> transfer_family;
[[nodiscard, maybe_unused]] bool is_complete() const noexcept
{
return graphics_family.has_value()
&& present_family.has_value()
&& transfer_family.has_value();
}
[[nodiscard, maybe_unused]] std::vector<unsigned int> to_vector() const
{
return std::vector<unsigned int>
{
graphics_family.value(),
present_family.value(),
transfer_family.value()
};
}
[[nodiscard, maybe_unused]] bool are_all_unique() const
{
return to_unordered_set().size() == 3;
}
[[nodiscard, maybe_unused]] std::unordered_set<unsigned int> to_unordered_set() const
{
return
{
graphics_family.value(),
present_family.value(),
transfer_family.value()
};
}
};
struct [[maybe_unused]] device_surface_info
{
const vk::SurfaceCapabilitiesKHR capabilities;
const std::vector<vk::SurfaceFormatKHR> formats;
const std::vector<vk::PresentModeKHR> present_modes;
};
class [[maybe_unused]] device
{
const std::array<std::string, 1> _required_device_extension_names
{
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
const vk::PhysicalDevice _physical;
public:
const queue_family_indices queue_family_indices;
private:
const vk::UniqueDevice _inner;
public:
const vk::Queue graphics_queue;
const vk::Queue present_queue;
const vk::Queue transfer_queue;
[[nodiscard, maybe_unused]] explicit device(
const environment &environment,
const window &window) :
_physical(_select_physical_device(environment, window)),
queue_family_indices(_query_queue_families(_physical, window)),
_inner(_create_inner(environment, debug_printer::validation_layer_names)),
graphics_queue(_create_queue(queue_family_indices.graphics_family.value())),
present_queue(_create_queue(queue_family_indices.present_family.value())),
transfer_queue(_create_queue(queue_family_indices.transfer_family.value()))
{
#if !defined(NDEBUG)
std::cout << "Queues created" << std::endl;
std::cout << std::endl << "-- device done --" << std::endl << std::endl;
#endif
}
[[nodiscard, maybe_unused]] const vk::Device &operator*() const
{
return *_inner;
}
[[nodiscard, maybe_unused]] const vk::Device *operator->() const
{
return &*_inner;
}
[[nodiscard, maybe_unused]] const vk::PhysicalDevice &physical() const
{
return _physical;
}
[[nodiscard, maybe_unused]] device_surface_info query_surface_info(const window &window) const
{
return _query_surface_info(_physical, window);
}
private:
[[nodiscard]] vk::PhysicalDevice _select_physical_device(
const environment &environment,
const window &window) const
{
auto devices = environment.vulkan_instance().enumeratePhysicalDevices();
for (const auto &device : devices)
{
if (_device_suitable(device, window))
{
#if !defined(NDEBUG)
std::cout << "Physical device selected" << std::endl;
#endif
return device;
}
}
throw std::runtime_error("Failed to find a suitable GPU.");
}
[[nodiscard]] bool _device_suitable(
const vk::PhysicalDevice &device,
const window &surface) const
{
if (!_device_extensions_supported(device)) return false;
const auto swap_chain_support_info = _query_surface_info(device, surface);
return _query_queue_families(device, surface).is_complete()
&& !swap_chain_support_info.formats.empty()
&& !swap_chain_support_info.present_modes.empty();
}
[[nodiscard]] bool _device_extensions_supported(const vk::PhysicalDevice &device) const
{
auto available_extension_properties =
device.enumerateDeviceExtensionProperties();
for (const auto &required_extension_name : _required_device_extension_names)
{
auto found = false;
for (auto available : available_extension_properties)
{
if (strcmp(required_extension_name.c_str(), available.extensionName) == 0)
{
found = true;
break;
}
}
if (!found) return false;
}
return true;
}
[[nodiscard]] static il::queue_family_indices _query_queue_families(
const vk::PhysicalDevice &device,
const window &window)
{
il::queue_family_indices indices;
auto queue_family_index = 0;
for (const auto &queue_family : device.getQueueFamilyProperties())
{
if (device.getSurfaceSupportKHR(queue_family_index, window.drawing_surface()) == VK_TRUE)
{
indices.present_family = queue_family_index;
}
if (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)
{
indices.graphics_family = queue_family_index;
}
if (queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
{
indices.transfer_family = queue_family_index;
}
if (indices.is_complete())
{
break;
}
queue_family_index++;
}
return indices;
}
[[nodiscard]] static device_surface_info _query_surface_info(
const vk::PhysicalDevice &device,
const window &window)
{
return
{
device.getSurfaceCapabilitiesKHR(window.drawing_surface()),
device.getSurfaceFormatsKHR(window.drawing_surface()),
device.getSurfacePresentModesKHR(window.drawing_surface())
};
}
[[nodiscard]] vk::UniqueDevice _create_inner(
const environment &environment,
const std::array<const char *, 1> &validation_layer_names) const
{
std::vector<vk::DeviceQueueCreateInfo> queues_create_info{ };
const auto queue_priority = 1.0f;
for (auto unique_queue_family_index : queue_family_indices.to_unordered_set())
{
queues_create_info.push_back(
vk::DeviceQueueCreateInfo
{
{ },
unique_queue_family_index,
1,
&queue_priority
});
}
std::vector<char *> extension_names{ };
std::vector<char *> layer_names{ };
vk::PhysicalDeviceFeatures features{ };
for (const auto &device_extension_name : _required_device_extension_names)
{
extension_names.push_back(const_cast<char *>(device_extension_name.c_str()));
}
#if !defined(NDEBUG)
for (const auto &validation_layer_name : validation_layer_names)
{
layer_names.push_back(const_cast<char *>(validation_layer_name));
}
#endif
auto result = _physical.createDeviceUnique(
{
{ },
static_cast<unsigned int>(queues_create_info.size()),
queues_create_info.data(),
static_cast<unsigned int>(layer_names.size()),
layer_names.data(),
static_cast<unsigned int>(extension_names.size()),
extension_names.data(),
&features
});
#if !defined(NDEBUG)
std::cout << "Logical device created" << std::endl;
#endif
environment.update_dynamic_loader(*result);
#if !defined(NDEBUG)
std::cout << "Dynamic loader updated" << std::endl;
#endif
return result;
}
[[nodiscard]] vk::Queue _create_queue(const unsigned int &queue_family_index) const
{
const auto result = _inner->getQueue(queue_family_index, 0);
return result;
}
};
}
#endif
| 33.479866 | 106 | 0.513581 | [
"vector"
] |
e4163cf5a66be53eca57a2cef0c7d5c06fbed342 | 1,625 | cpp | C++ | C++/1250.cpp | rakhi2001/ecom7 | 73790d44605fbd51e8f7e804b9808e364fcfc680 | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | C++/1250.cpp | rakhi2001/ecom7 | 73790d44605fbd51e8f7e804b9808e364fcfc680 | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | C++/1250.cpp | rakhi2001/ecom7 | 73790d44605fbd51e8f7e804b9808e364fcfc680 | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 16 ms submission
static const int __ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
typedef pair<int ,int> pii;
typedef pair<ll, ll> pll;
typedef double rl;
#define pb push_back
#define _x first
#define _y second
#if 1
#define dbg(x) cout << #x << ": " << (x) << endl;
#else
#define dbg(x)
#endif
class Solution {
/*
int gcd(int A, int B)
{
while(B!=0)
{
A%=B;
swap(A, B);
}
return A;
}
*/
public:
bool isGoodArray(vector<int>& nums) {
int G=0;
for(int a: nums)
{
G=gcd(a, G);
if(G==1) break;
}
return G==1;
}
};
__________________________________________________________________________________________________
sample 20 ms submission
inline int gcd(int a, int b) {
int r;
while (b) {
r = a % b;
a = b;
b = r;
}
return a;
}
class Solution {
public:
bool isGoodArray(vector<int>& nums) {
int g = nums[0];
for (int i = 1; i < nums.size(); ++i) {
g = gcd(g, nums[i]);
if (g == 1) return true;
}
return g == 1;
}
};
auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(0);
return 0;
}();
__________________________________________________________________________________________________
| 20.56962 | 98 | 0.577231 | [
"vector"
] |
e42f7e551574f37155c56aaf5ede95ad96df6a0e | 7,369 | cc | C++ | lite/kernels/fpga/elementwise_compute.cc | 714627034/Paddle-Lite | 015ba88a4d639db0b73603e37f83e47be041a4eb | [
"Apache-2.0"
] | 1,799 | 2019-08-19T03:29:38.000Z | 2022-03-31T14:30:50.000Z | lite/kernels/fpga/elementwise_compute.cc | 714627034/Paddle-Lite | 015ba88a4d639db0b73603e37f83e47be041a4eb | [
"Apache-2.0"
] | 3,767 | 2019-08-19T03:36:04.000Z | 2022-03-31T14:37:26.000Z | lite/kernels/fpga/elementwise_compute.cc | 714627034/Paddle-Lite | 015ba88a4d639db0b73603e37f83e47be041a4eb | [
"Apache-2.0"
] | 798 | 2019-08-19T02:28:23.000Z | 2022-03-31T08:31:54.000Z | // Copyright (c) 2019 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 "lite/kernels/fpga/elementwise_compute.h"
#include <string>
#include "lite/backends/arm/math/funcs.h"
#include "lite/backends/fpga/KD/debugger.hpp"
#include "lite/kernels/fpga/activation_compute.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace fpga {
using float16 = zynqmp::float16;
void ElementwiseAddCompute::PrepareForRun() {
zynqmp::ElementwiseAddParam& ew_param = pe_.param();
auto& param = Param<operators::ElementwiseParam>();
param.Out->mutable_data<float16>();
ew_param.inputs = {param.X->ZynqTensor(), param.Y->ZynqTensor()};
ew_param.output = param.Out->ZynqTensor();
ew_param.axis = param.axis;
ew_param.activeParam.type = zynqmp::TYPE_NONE;
pe_.init();
pe_.apply();
}
void ElementwiseAddCompute::Run() {
pe_.dispatch();
#ifdef FPGA_PRINT_TENSOR
zynqmp::ElementwiseAddParam& ew_param = pe_.param();
Debugger::get_instance().registerOutput("ew_add", ew_param.output);
#endif
}
void ElementwiseAddActivationCompute::PrepareForRun() {
zynqmp::ElementwiseAddParam& ew_param = pe_.param();
auto& param = Param<operators::FusionElementwiseActivationParam>();
if (activation_map.count(param.act_type)) {
ew_param.activeParam.type = activation_map[param.act_type];
} else {
LOG(FATAL) << "unsupported Activation type: " << param.act_type;
}
param.Out->mutable_data<float16>();
ew_param.inputs = {param.X->ZynqTensor(), param.Y->ZynqTensor()};
ew_param.output = param.Out->ZynqTensor();
ew_param.axis = param.axis;
pe_.init();
pe_.apply();
}
void ElementwiseAddActivationCompute::Run() {
pe_.dispatch();
#ifdef FPGA_PRINT_TENSOR
zynqmp::ElementwiseAddParam& ew_param = pe_.param();
Debugger::get_instance().registerOutput("ew_add", ew_param.output);
#endif
}
void ElementwiseMulCompute::PrepareForRun() {
zynqmp::ScaleParam& scale_param = pe_.param();
auto& param = Param<operators::ElementwiseParam>();
param.Out->mutable_data<float16>();
scale_param.input = param.X->ZynqTensor();
scale_param.output = param.Out->ZynqTensor();
scale_param.activeParam.type = zynqmp::TYPE_NONE;
int channel = scale_param.input->shape().channel();
scale_param.scale = &scale_;
scale_param.bias = &bias_;
zynqmp::Shape shape(zynqmp::N, {channel});
zynqmp::float16* scale_data =
scale_.mutableData<zynqmp::float16>(zynqmp::FP16, shape);
zynqmp::float16* bias_data =
bias_.mutableData<zynqmp::float16>(zynqmp::FP16, shape);
zynqmp::float16 scale_value = 0;
if (param.Y->ZynqTensor()->dataType() == zynqmp::FP32) {
scale_value = zynqmp::float_to_half(param.Y->data<float>()[0]);
} else {
scale_value = param.Y->data<zynqmp::float16>()[0];
}
scale_param.re_assign = param.Y->dims().production() != 1;
for (int i = 0; i < channel; i++) {
if (param.Y->dims().production() != 1) {
if (param.Y->ZynqTensor()->dataType() == zynqmp::FP32) {
scale_value = zynqmp::float_to_half(param.Y->data<float>()[i]);
} else {
scale_value = param.Y->data<zynqmp::float16>()[i];
}
}
scale_data[i] = scale_value;
bias_data[i] = zero_;
}
pe_.init();
pe_.apply();
}
void ElementwiseMulCompute::Run() {
auto& param = Param<operators::ElementwiseParam>();
if (!param.Y->persistable()) {
// TODO(chonwhite) alignment;
param.Y->ZynqTensor()->invalidate();
scale_.copyFrom(param.Y->ZynqTensor());
scale_.flush();
}
pe_.dispatch();
#ifdef FPGA_PRINT_TENSOR
zynqmp::ScaleParam& scale_param = pe_.param();
Debugger::get_instance().registerOutput("ew_mul", scale_param.output);
#endif
}
} // namespace fpga
} // namespace kernels
} // namespace lite
} // namespace paddle
REGISTER_LITE_KERNEL(elementwise_add,
kFPGA,
kFP16,
kNHWC,
paddle::lite::kernels::fpga::ElementwiseAddCompute,
def)
.BindInput("X",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindInput("Y",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.Finalize();
REGISTER_LITE_KERNEL(
fusion_elementwise_add_activation,
kFPGA,
kFP16,
kNHWC,
paddle::lite::kernels::fpga::ElementwiseAddActivationCompute,
def)
.BindInput("X",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindInput("Y",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.Finalize();
REGISTER_LITE_KERNEL(elementwise_mul,
kFPGA,
kFP16,
kNHWC,
paddle::lite::kernels::fpga::ElementwiseMulCompute,
ew_mul_fpga)
.BindInput("X",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindInput("Y",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.Finalize();
REGISTER_LITE_KERNEL(elementwise_mul,
kFPGA,
kFP16,
kNHWC,
paddle::lite::kernels::fpga::ElementwiseMulCompute,
ew_mul_y_arm)
.BindInput("X",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.BindInput("Y", {LiteType::GetTensorTy(TARGET(kARM))})
.BindOutput("Out",
{LiteType::GetTensorTy(TARGET(kFPGA),
PRECISION(kFP16),
DATALAYOUT(kNHWC))})
.Finalize();
| 34.274419 | 75 | 0.580812 | [
"shape"
] |
e437cf17190abac8f5bc8edd552d2e0412cd0cec | 1,240 | cpp | C++ | coj.uci.cu/DyckWords.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 6 | 2016-09-10T03:16:34.000Z | 2020-04-07T14:45:32.000Z | coj.uci.cu/DyckWords.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | null | null | null | coj.uci.cu/DyckWords.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 2 | 2018-08-11T20:55:35.000Z | 2020-01-15T23:23:11.000Z | /*
By: facug91
From: http://coj.uci.cu/24h/problem.xhtml?abb=2260
Name: Dyck Words
Number: 2260
Date: 02/08/2014
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <iterator>
#include <utility>
#include <list>
#include <stack>
#include <iomanip>
#include <bitset>
#define MAX_INT 2147483647
#define MAX_LONG 9223372036854775807ll
#define MAX_ULONG 18446744073709551615ull
#define MAX_DBL 1.7976931348623158e+308
#define EPS 1e-9
const double PI = 2.0*acos(0.0);
#define INF 1000000000
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<int, pair<int, int> > iii;
int n, DP[1005][1005];
void dp () {
int i, j, k;
memset(DP, 0, sizeof DP);
for (i=0; i<1005; i++)
DP[0][i] = 1;
for (i=1; i<1005; i++)
for (j=i; j<1005; j++)
DP[i][j] = (DP[i-1][j] + DP[i][j-1]) % MOD;
}
int main () {
int t, i, j;
dp();
scanf("%d", &t);
for (int it=1; it<=t; it++) {
scanf("%d", &n);
printf("%d\n", DP[n][n]);
}
return 0;
}
| 18.235294 | 52 | 0.609677 | [
"vector"
] |
e43903818003d5e885cc81d728eb25a1225d1afd | 1,664 | cpp | C++ | 0733_FloodFill.cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | null | null | null | 0733_FloodFill.cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | null | null | null | 0733_FloodFill.cpp | taro-masuda/leetcode | 39739e9fec7c66513b114c740ef982ccc09dc39f | [
"MIT"
] | 1 | 2020-03-18T05:23:40.000Z | 2020-03-18T05:23:40.000Z | class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int R = image.size(); int C = image[0].size();
stack<pair<int, int>> s;
s.push(pair(sr, sc));
set<pair<int,int>> visited;
visited.insert(pair(sr,sc));
int prevColor = image[sr][sc];
// Depth First Search
while(!s.empty()) {
pair<int,int> topVal = s.top(); s.pop();
int r = topVal.first;
int c = topVal.second;
image[r][c] = newColor;
// top
if (r > 0) {
if (visited.find(pair(r-1,c)) == visited.end() && image[r-1][c] == prevColor) {
s.push(pair(r-1,c));
visited.insert(pair(r-1,c));
}
}
// bottom
if (r < R-1) {
if (visited.find(pair(r+1,c)) == visited.end() && image[r+1][c] == prevColor) {
s.push(pair(r+1,c));
visited.insert(pair(r+1,c));
}
}
// left
if (c > 0) {
if (visited.find(pair(r,c-1)) == visited.end() && image[r][c-1] == prevColor) {
s.push(pair(r,c-1));
visited.insert(pair(r,c-1));
}
}
// right
if (c < C-1) {
if (visited.find(pair(r,c+1)) == visited.end() && image[r][c+1] == prevColor) {
s.push(pair(r,c+1));
visited.insert(pair(r,c+1));
}
}
}
return image;
}
};
| 34.666667 | 95 | 0.397837 | [
"vector"
] |
e43bdb137fa2124ee52c651d568b8a15f7a0dac7 | 15,869 | hh | C++ | Replicator/tests/ReplicatorAPITest.hh | mleduque/couchbase-lite-core | 6003a9e9a52d31fb7872dd10717a1ffdcc6f0a9c | [
"Apache-2.0"
] | null | null | null | Replicator/tests/ReplicatorAPITest.hh | mleduque/couchbase-lite-core | 6003a9e9a52d31fb7872dd10717a1ffdcc6f0a9c | [
"Apache-2.0"
] | null | null | null | Replicator/tests/ReplicatorAPITest.hh | mleduque/couchbase-lite-core | 6003a9e9a52d31fb7872dd10717a1ffdcc6f0a9c | [
"Apache-2.0"
] | null | null | null | //
// ReplicatorAPITest.hh
// LiteCore
//
// Created by Jens Alfke on 7/12/17.
// Copyright © 2017 Couchbase. All rights reserved.
//
#pragma once
#include "fleece/slice.hh"
#include "fleece/Fleece.hh"
#include "c4.hh"
#include "c4Certificate.h"
#include "Address.hh"
#include "Response.hh"
#include "c4Test.hh"
#include "StringUtil.hh"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
using namespace fleece;
using namespace litecore;
using namespace litecore::net;
extern "C" {
void C4RegisterBuiltInWebSocket();
}
class ReplicatorAPITest : public C4Test {
public:
// Default address to replicate with (individual tests can override this):
constexpr static const C4Address kDefaultAddress {kC4Replicator2Scheme,
C4STR("localhost"),
4984};
// Common database names:
constexpr static const C4String kScratchDBName = C4STR("scratch");
constexpr static const C4String kITunesDBName = C4STR("itunes");
constexpr static const C4String kWikipedia1kDBName = C4STR("wikipedia1k");
constexpr static const C4String kProtectedDBName = C4STR("seekrit");
constexpr static const C4String kImagesDBName = C4STR("images");
static alloc_slice sPinnedCert;
ReplicatorAPITest()
:C4Test(0)
{
static once_flag once;
call_once(once, [&]() {
// Register the BuiltInWebSocket class as the C4Replicator's WebSocketImpl.
C4RegisterBuiltInWebSocket();
// Pin the server certificate:
sPinnedCert = readFile(sReplicatorFixturesDir + "cert.pem");
});
// Environment variables can also override the default address above:
if (getenv("REMOTE_TLS") || getenv("REMOTE_SSL"))
_address.scheme = C4STR("wss");
const char *hostname = getenv("REMOTE_HOST");
if (hostname)
_address.hostname = c4str(hostname);
const char *portStr = getenv("REMOTE_PORT");
if (portStr)
_address.port = (uint16_t)strtol(portStr, nullptr, 10);
const char *remoteDB = getenv("REMOTE_DB");
if (remoteDB)
_remoteDBName = c4str(remoteDB);
const char *proxyURL = getenv("REMOTE_PROXY");
if (proxyURL) {
Address proxyAddr{slice(proxyURL)};
_proxy = make_unique<ProxySpec>(proxyAddr);
}
if (Address::isSecure(_address)) {
pinnedCert = sPinnedCert;
}
_onDocsEnded = onDocsEnded;
}
#ifdef COUCHBASE_ENTERPRISE
// Create an empty database db2 and make it the target of the replication
void createDB2() {
auto db2Path = TempDir() + "cbl_core_test2.cblite2";
auto db2PathSlice = c4str(db2Path.c_str());
auto config = c4db_getConfig(db);
C4Error error;
if (!c4db_deleteAtPath(db2PathSlice, &error))
REQUIRE(error.code == 0);
db2 = c4db_open(db2PathSlice, config, &error);
REQUIRE(db2 != nullptr);
_address = { };
_remoteDBName = nullslice;
}
#endif
AllocedDict options() {
Encoder enc;
enc.beginDict();
if (pinnedCert) {
enc.writeKey(C4STR(kC4ReplicatorOptionPinnedServerCert));
enc.writeData(pinnedCert);
}
#ifdef COUCHBASE_ENTERPRISE
if (identityCert) {
enc.writeKey(C4STR(kC4ReplicatorOptionAuthentication));
enc.beginDict();
enc[C4STR(kC4ReplicatorAuthType)] = kC4AuthTypeClientCert;
enc.writeKey(C4STR(kC4ReplicatorAuthClientCert));
enc.writeData(alloc_slice(c4cert_copyData(identityCert, false)));
alloc_slice privateKeyData(c4keypair_privateKeyData(identityKey));
if (privateKeyData) {
enc.writeKey(C4STR(kC4ReplicatorAuthClientCertKey));
enc.writeData(privateKeyData);
}
enc.endDict();
}
#endif
if (_enableDocProgressNotifications) {
enc.writeKey(C4STR(kC4ReplicatorOptionProgressLevel));
enc.writeInt(1);
}
// TODO: Set proxy settings from _proxy
// Copy any preexisting options:
for (Dict::iterator i(_options); i; ++i) {
enc.writeKey(i.keyString());
enc.writeValue(i.value());
}
enc.endDict();
return AllocedDict(enc.finish());
}
bool validate(slice docID, Dict body) {
//TODO: Do something here
return true;
}
static bool onValidate(FLString docID, C4RevisionFlags flags, FLDict body, void *context) {
return ((ReplicatorAPITest*)context)->validate(docID, body);
}
void logState(C4ReplicatorStatus status) {
if (status.error.code) {
char message[200];
c4error_getDescriptionC(status.error, message, sizeof(message));
C4Log("*** C4Replicator state: %-s, progress=%llu/%llu, error=%s",
kC4ReplicatorActivityLevelNames[status.level],
status.progress.unitsCompleted, status.progress.unitsTotal,
message);
} else {
C4Log("*** C4Replicator state: %-s, progress=%llu/%llu",
kC4ReplicatorActivityLevelNames[status.level],
status.progress.unitsCompleted, status.progress.unitsTotal);
}
}
void stateChanged(C4Replicator *r, C4ReplicatorStatus s) {
lock_guard<mutex> lock(_mutex);
logState(s);
if(r != _repl) {
WARN("Stray stateChange received, check C4Log for details!");
C4Warn("Stray stateChanged message received (possibly from previous test?): (r = %p, _repl = %p)", r, (C4Replicator *)_repl);
return;
}
_callbackStatus = s;
++_numCallbacks;
Assert(_numCallbacksWithLevel[(int)kC4Stopped] == 0); // Stopped must be the final state
_numCallbacksWithLevel[(int)s.level]++;
if (s.level == kC4Busy)
Assert(s.error.code == 0); // Busy state shouldn't have error
if (s.level == kC4Offline) {
Assert(_mayGoOffline);
_wentOffline = true;
Assert((s.flags & kC4WillRetry) != 0);
}
if (!_headers) {
_headers = AllocedDict(alloc_slice(c4repl_getResponseHeaders(_repl)));
if (!!_headers) {
for (Dict::iterator header(_headers); header; ++header)
C4Log(" %.*s: %.*s", SPLAT(header.keyString()), SPLAT(header.value().asString()));
}
}
if (!_socketFactory && !db2) { // i.e. this is a real WebSocket connection
if ((s.level > kC4Connecting && s.error.code == 0)
|| (s.level == kC4Stopped && s.error.domain == WebSocketDomain))
Assert(_headers);
}
if (s.level == kC4Idle && _stopWhenIdle) {
C4Log("*** Replicator idle; stopping...");
c4repl_stop(r);
}
}
static void onStateChanged(C4Replicator *replicator,
C4ReplicatorStatus status,
void *context)
{
((ReplicatorAPITest*)context)->stateChanged(replicator, status);
}
static void onDocsEnded(C4Replicator *repl,
bool pushing,
size_t nDocs,
const C4DocumentEnded* docs[],
void *context)
{
auto test = (ReplicatorAPITest*)context;
char message[256];
test->_docsEnded += nDocs;
for (size_t i = 0; i < nDocs; ++i) {
auto doc = docs[i];
if (doc->error.code) {
c4error_getDescriptionC(doc->error, message, sizeof(message));
C4Warn(">> Replicator %serror %s '%.*s': %s",
(doc->errorIsTransient ? "transient " : ""),
(pushing ? "pushing" : "pulling"),
SPLAT(doc->docID), message);
lock_guard<mutex> lock(test->_mutex);
if (pushing)
test->_docPushErrors.emplace(slice(doc->docID));
else
test->_docPullErrors.emplace(slice(doc->docID));
}
}
}
bool startReplicator(C4ReplicatorMode push, C4ReplicatorMode pull, C4Error *err) {
_callbackStatus = { };
_numCallbacks = 0;
memset(_numCallbacksWithLevel, 0, sizeof(_numCallbacksWithLevel));
_docPushErrors = _docPullErrors = { };
_docsEnded = 0;
_wentOffline = false;
if (push > kC4Passive && (slice(_remoteDBName).hasPrefix("scratch"_sl))
&& !db2 && !_flushedScratch) {
flushScratchDatabase();
}
C4ReplicatorParameters params = {};
params.push = push;
params.pull = pull;
_options = options();
params.optionsDictFleece = _options.data();
params.pushFilter = _pushFilter;
// params.validationFunc = onValidate;
params.onStatusChanged = onStateChanged;
params.onDocumentsEnded = _onDocsEnded;
params.callbackContext = this;
params.socketFactory = _socketFactory;
if (_remoteDBName.buf) {
_repl = c4repl_new(db, _address, _remoteDBName, params, err);
} else {
#ifdef COUCHBASE_ENTERPRISE
_repl = c4repl_newLocal(db, db2, params, err);
#else
FAIL("Local replication not supported in CE");
#endif
}
if (!_repl)
return false;
c4repl_start(_repl);
return true;
}
void replicate(C4ReplicatorMode push, C4ReplicatorMode pull, bool expectSuccess =true) {
C4Error err;
REQUIRE(startReplicator(push, pull, &err));
C4ReplicatorStatus status = c4repl_getStatus(_repl);
logState(status);
// Sometimes Windows goes so fast that by the time
// it is here, it's already past the connecting stage.
// Furthermore, sometimes in failure cases the failure happens
// so fast that the replicator has already stopped by now with an
// error
if(expectSuccess) {
CHECK((status.level == kC4Connecting || status.level == kC4Busy));
CHECK(status.error.code == 0);
} else if(status.level == kC4Connecting || status.level == kC4Busy) {
CHECK(status.error.code == 0);
}
while ((status = c4repl_getStatus(_repl)).level != kC4Stopped)
this_thread::sleep_for(chrono::milliseconds(100));
int attempts = 0;
while(_numCallbacksWithLevel[kC4Stopped] != 1 && attempts++ < 5) {
this_thread::sleep_for(chrono::milliseconds(100));
}
lock_guard<mutex> lock(_mutex);
CHECK(_numCallbacks > 0);
if (expectSuccess) {
CHECK(status.error.code == 0);
CHECK(_numCallbacksWithLevel[kC4Busy] > 0);
if (!db2)
CHECK(_headers);
}
CHECK(_numCallbacksWithLevel[kC4Stopped] == 1);
CHECK(_callbackStatus.level == status.level);
CHECK(_callbackStatus.error.domain == status.error.domain);
CHECK(_callbackStatus.error.code == status.error.code);
CHECK(asVector(_docPullErrors) == asVector(_expectedDocPullErrors));
CHECK(asVector(_docPushErrors) == asVector(_expectedDocPushErrors));
_repl = nullptr;
}
/// Sends an HTTP request to the remote server.
alloc_slice sendRemoteRequest(const string &method,
string path,
HTTPStatus *outStatus NONNULL,
C4Error *outError NONNULL,
slice body =nullslice,
bool admin =false)
{
if (method != "GET")
REQUIRE(slice(_remoteDBName).hasPrefix("scratch"_sl));
auto port = uint16_t(_address.port + !!admin);
if (!hasPrefix(path, "/"))
path = string("/") + (string)(slice)_remoteDBName + "/" + path;
if (_logRemoteRequests)
C4Log("*** Server command: %s %.*s:%d%s",
method.c_str(), SPLAT(_address.hostname), port, path.c_str());
Encoder enc;
enc.beginDict();
enc["Content-Type"_sl] = "application/json";
enc.endDict();
auto headers = enc.finishDoc();
string scheme = Address::isSecure(_address) ? "https" : "http";
auto r = make_unique<REST::Response>(scheme,
method,
(string)(slice)_address.hostname,
port,
path);
r->setHeaders(headers).setBody(body).setTimeout(5);
if (pinnedCert)
r->allowOnlyCert(pinnedCert);
if (_authHeader)
r->setAuthHeader(_authHeader);
if (_proxy)
r->setProxy(*_proxy);
#ifdef COUCHBASE_ENTERPRISE
if (identityCert)
r->setIdentity(identityCert, identityKey);
#endif
if (r->run()) {
*outStatus = r->status();
*outError = {};
return r->body();
} else {
REQUIRE(r->error().code != 0);
*outStatus = HTTPStatus::undefined;
*outError = r->error();
return nullslice;
}
}
/// Sends an HTTP request to the remote server.
alloc_slice sendRemoteRequest(const string &method,
string path,
slice body =nullslice,
bool admin =false,
HTTPStatus expectedStatus = HTTPStatus::OK)
{
if (method == "PUT" && expectedStatus == HTTPStatus::OK)
expectedStatus = HTTPStatus::Created;
HTTPStatus status;
C4Error error;
alloc_slice response = sendRemoteRequest(method, path, &status, &error, body, admin);
if (error.code)
FAIL("Error: " << c4error_descriptionStr(error));
INFO("Status: " << (int)status);
REQUIRE(status == expectedStatus);
return response;
}
void flushScratchDatabase() {
sendRemoteRequest("POST", "_flush", nullslice, true);
_flushedScratch = true;
}
static vector<string> asVector(const set<string> strings) {
vector<string> out;
for (const string &s : strings)
out.push_back(s);
return out;
}
c4::ref<C4Database> db2;
C4Address _address = kDefaultAddress;
C4String _remoteDBName = kScratchDBName;
AllocedDict _options;
alloc_slice _authHeader;
alloc_slice pinnedCert;
#ifdef COUCHBASE_ENTERPRISE
c4::ref<C4Cert> identityCert;
c4::ref<C4KeyPair> identityKey;
#endif
unique_ptr<ProxySpec> _proxy;
bool _enableDocProgressNotifications {false};
C4ReplicatorValidationFunction _pushFilter {nullptr};
C4ReplicatorDocumentsEndedCallback _onDocsEnded {nullptr};
C4SocketFactory* _socketFactory {nullptr};
bool _flushedScratch {false};
c4::ref<C4Replicator> _repl;
mutex _mutex;
C4ReplicatorStatus _callbackStatus {};
int _numCallbacks {0};
int _numCallbacksWithLevel[5] {0};
AllocedDict _headers;
bool _stopWhenIdle {false};
int _docsEnded {0};
set<string> _docPushErrors, _docPullErrors;
set<string> _expectedDocPushErrors, _expectedDocPullErrors;
int _counter {0};
bool _logRemoteRequests {true};
bool _mayGoOffline {false};
bool _wentOffline {false};
};
| 35.342984 | 137 | 0.575525 | [
"vector"
] |
e4453b06f60083e5b3ab14bacc6709c67cc4b022 | 43,295 | cpp | C++ | test/unit/math/mix/mat/fun/mdivide_right_ldlt_test.cpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | test/unit/math/mix/mat/fun/mdivide_right_ldlt_test.cpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | test/unit/math/mix/mat/fun/mdivide_right_ldlt_test.cpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/mix/mat.hpp>
#include <gtest/gtest.h>
#include <vector>
using stan::math::fvar;
using stan::math::var;
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_matrix_fv_1) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::matrix_fv Av(2, 2);
stan::math::matrix_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_ = 2.0;
Av(0, 1).d_ = 2.0;
Av(1, 0).d_ = 2.0;
Av(1, 1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Ad, ldlt_Ad);
EXPECT_FLOAT_EQ(1.0, I(0, 0).val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val());
EXPECT_FLOAT_EQ(0.0, I(1, 0).val_.val());
EXPECT_FLOAT_EQ(1.0, I(1, 1).val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 0).d_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).d_.val());
EXPECT_FLOAT_EQ(0.0, I(1, 0).d_.val());
EXPECT_FLOAT_EQ(0.0, I(1, 1).d_.val());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0, 0).val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val());
EXPECT_FLOAT_EQ(2.8, I(1, 0).val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1, 1).val_.val());
EXPECT_FLOAT_EQ(0.8, I(0, 0).d_.val());
EXPECT_FLOAT_EQ(-0.2, I(0, 1).d_.val());
EXPECT_FLOAT_EQ(-0.48, I(1, 0).d_.val());
EXPECT_FLOAT_EQ(0.12, I(1, 1).d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
vars.push_back(Av(0, 0).val_);
vars.push_back(Av(0, 1).val_);
vars.push_back(Av(1, 0).val_);
vars.push_back(Av(1, 1).val_);
I(0, 0).val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.4, grads[4]);
EXPECT_FLOAT_EQ(-0.6, grads[5]);
EXPECT_FLOAT_EQ(0, grads[6]);
EXPECT_FLOAT_EQ(0, grads[7]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_matrix_fv_2) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::matrix_fv Av(2, 2);
stan::math::matrix_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_ = 2.0;
Av(0, 1).d_ = 2.0;
Av(1, 0).d_ = 2.0;
Av(1, 1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
vars.push_back(Av(0, 0).val_);
vars.push_back(Av(0, 1).val_);
vars.push_back(Av(1, 0).val_);
vars.push_back(Av(1, 1).val_);
I(0, 0).d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.48, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_FLOAT_EQ(-0.12, grads[3]);
EXPECT_FLOAT_EQ(-0.64, grads[4]);
EXPECT_FLOAT_EQ(0.16, grads[5]);
EXPECT_FLOAT_EQ(0, grads[6]);
EXPECT_FLOAT_EQ(0, grads[7]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_matrix_d_1) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::matrix_d Av(2, 2);
stan::math::matrix_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0, 0).val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val());
EXPECT_FLOAT_EQ(2.8, I(1, 0).val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1, 1).val_.val());
EXPECT_FLOAT_EQ(-0.8, I(0, 0).d_.val());
EXPECT_FLOAT_EQ(0.2, I(0, 1).d_.val());
EXPECT_FLOAT_EQ(-2.08, I(1, 0).d_.val());
EXPECT_FLOAT_EQ(0.52, I(1, 1).d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
I(0, 0).val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_matrix_d_2) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::matrix_d Av(2, 2);
stan::math::matrix_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
I(0, 0).d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.76, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.92, grads[2]);
EXPECT_FLOAT_EQ(0.12, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_matrix_fv_1) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::matrix_fv Av(2, 2);
stan::math::matrix_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_ = 2.0;
Av(0, 1).d_ = 2.0;
Av(1, 0).d_ = 2.0;
Av(1, 1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0, 0).val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val());
EXPECT_FLOAT_EQ(2.8, I(1, 0).val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1, 1).val_.val());
EXPECT_FLOAT_EQ(1.6, I(0, 0).d_.val());
EXPECT_FLOAT_EQ(-0.4, I(0, 1).d_.val());
EXPECT_FLOAT_EQ(1.6, I(1, 0).d_.val());
EXPECT_FLOAT_EQ(-0.4, I(1, 1).d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0, 0).val_);
vars.push_back(Av(0, 1).val_);
vars.push_back(Av(1, 0).val_);
vars.push_back(Av(1, 1).val_);
I(0, 0).val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.4, grads[0]);
EXPECT_FLOAT_EQ(-0.6, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_matrix_fv_2) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::matrix_fv Av(2, 2);
stan::math::matrix_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_ = 2.0;
Av(0, 1).d_ = 2.0;
Av(1, 0).d_ = 2.0;
Av(1, 1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0, 0).val_);
vars.push_back(Av(0, 1).val_);
vars.push_back(Av(1, 0).val_);
vars.push_back(Av(1, 1).val_);
I(0, 0).d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_row_vector_fv_1) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::row_vector_fv Av(2);
stan::math::row_vector_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0).val_.val());
EXPECT_FLOAT_EQ(0.0, I(1).val_.val());
EXPECT_FLOAT_EQ(0.8, I(0).d_.val());
EXPECT_FLOAT_EQ(-0.2, I(1).d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I(0).val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.4, grads[4]);
EXPECT_FLOAT_EQ(-0.6, grads[5]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_row_vector_fv_2) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::row_vector_fv Av(2);
stan::math::row_vector_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I(0).d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.48, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_FLOAT_EQ(-0.12, grads[3]);
EXPECT_FLOAT_EQ(-0.64, grads[4]);
EXPECT_FLOAT_EQ(0.16, grads[5]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_row_vector_d_1) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::row_vector_d Av(2);
stan::math::row_vector_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0).val_.val());
EXPECT_FLOAT_EQ(0, I(1).val_.val());
EXPECT_FLOAT_EQ(-0.8, I(0).d_.val());
EXPECT_FLOAT_EQ(0.2, I(1).d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
I(0).val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_fv_row_vector_d_2) {
stan::math::LDLT_factor<fvar<var>, -1, -1> ldlt_Ad;
stan::math::matrix_fv Ad(2, 2);
stan::math::row_vector_d Av(2);
stan::math::row_vector_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_ = 1.0;
Ad(0, 1).d_ = 1.0;
Ad(1, 0).d_ = 1.0;
Ad(1, 1).d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_);
vars.push_back(Ad(0, 1).val_);
vars.push_back(Ad(1, 0).val_);
vars.push_back(Ad(1, 1).val_);
I(0).d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.76, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.92, grads[2]);
EXPECT_FLOAT_EQ(0.12, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_row_vector_fv_1) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::row_vector_fv Av(2);
stan::math::row_vector_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0).val_.val());
EXPECT_FLOAT_EQ(0.0, I(1).val_.val());
EXPECT_FLOAT_EQ(1.6, I(0).d_.val());
EXPECT_FLOAT_EQ(-0.4, I(1).d_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I(0).val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.4, grads[0]);
EXPECT_FLOAT_EQ(-0.6, grads[1]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_row_vector_fv_2) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::row_vector_fv Av(2);
stan::math::row_vector_fv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_ = 2.0;
Av(1).d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_);
vars.push_back(Av(1).val_);
I(0).d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixMdivideRightLDLT, fv_exceptions) {
using stan::math::matrix_d;
using stan::math::matrix_fv;
using stan::math::row_vector_d;
using stan::math::row_vector_fv;
using stan::math::vector_d;
using stan::math::vector_fv;
matrix_fv fv1_(3, 3), fv2_(4, 4);
fv1_ << 1, 2, 3, 4, 5, 6, 7, 8, 9;
fv2_ << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
vector_fv rvf1(3), rvf2(4);
rvf1.setZero();
rvf2.setZero();
row_vector_fv vf1(3), vf2(4);
vf1.setZero();
vf2.setZero();
matrix_d fd1_(3, 3), fd2_(4, 4);
fd1_ << 1, 2, 3, 4, 5, 6, 7, 8, 9;
fd2_ << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
vector_d rvd1(3), rvd2(4);
rvd1.setZero();
rvd2.setZero();
row_vector_d vd1(3), vd2(4);
vd1.setZero();
vd2.setZero();
stan::math::LDLT_factor<fvar<var>, -1, -1> fv1;
stan::math::LDLT_factor<fvar<var>, -1, -1> fv2;
stan::math::LDLT_factor<double, -1, -1> fd1;
stan::math::LDLT_factor<double, -1, -1> fd2;
fv1.compute(fv1_);
fv2.compute(fv2_);
fd1.compute(fd1_);
fd2.compute(fd2_);
EXPECT_THROW(mdivide_right_ldlt(fd2_, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fv2_, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fv2_, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fd2_, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fv2_, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd1, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vd2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd2, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vd1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf2, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fd2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fd2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf1, fd2), std::invalid_argument);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_ffv_1) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Ad, ldlt_Ad);
EXPECT_FLOAT_EQ(1.0, I(0, 0).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(1, 0).val_.val_.val());
EXPECT_FLOAT_EQ(1.0, I(1, 1).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 0).d_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).d_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(1, 0).d_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(1, 1).d_.val_.val());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0, 0).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val_.val());
EXPECT_FLOAT_EQ(2.8, I(1, 0).val_.val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1, 1).val_.val_.val());
EXPECT_FLOAT_EQ(0.8, I(0, 0).d_.val_.val());
EXPECT_FLOAT_EQ(-0.2, I(0, 1).d_.val_.val());
EXPECT_FLOAT_EQ(-0.48, I(1, 0).d_.val_.val());
EXPECT_FLOAT_EQ(0.12, I(1, 1).d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.4, grads[4]);
EXPECT_FLOAT_EQ(-0.6, grads[5]);
EXPECT_FLOAT_EQ(0, grads[6]);
EXPECT_FLOAT_EQ(0, grads[7]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_ffv_2) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.48, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_FLOAT_EQ(-0.12, grads[3]);
EXPECT_FLOAT_EQ(-0.64, grads[4]);
EXPECT_FLOAT_EQ(0.16, grads[5]);
EXPECT_FLOAT_EQ(0, grads[6]);
EXPECT_FLOAT_EQ(0, grads[7]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_ffv_3) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
Av(0, 0).val_.d_ = 2.0;
Av(0, 1).val_.d_ = 2.0;
Av(1, 0).val_.d_ = 2.0;
Av(1, 1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.48, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_FLOAT_EQ(-0.12, grads[3]);
EXPECT_FLOAT_EQ(-0.64, grads[4]);
EXPECT_FLOAT_EQ(0.16, grads[5]);
EXPECT_FLOAT_EQ(0, grads[6]);
EXPECT_FLOAT_EQ(0, grads[7]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_ffv_4) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
Av(0, 0).val_.d_ = 2.0;
Av(0, 1).val_.d_ = 2.0;
Av(1, 0).val_.d_ = 2.0;
Av(1, 1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-1.232, grads[2]);
EXPECT_FLOAT_EQ(0.208, grads[3]);
EXPECT_FLOAT_EQ(0.768, grads[4]);
EXPECT_FLOAT_EQ(-0.192, grads[5]);
EXPECT_FLOAT_EQ(0, grads[6]);
EXPECT_FLOAT_EQ(0, grads[7]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_d_1) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_d Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0, 0).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val_.val());
EXPECT_FLOAT_EQ(2.8, I(1, 0).val_.val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1, 1).val_.val_.val());
EXPECT_FLOAT_EQ(-0.8, I(0, 0).d_.val_.val());
EXPECT_FLOAT_EQ(0.2, I(0, 1).d_.val_.val());
EXPECT_FLOAT_EQ(-2.08, I(1, 0).d_.val_.val());
EXPECT_FLOAT_EQ(0.52, I(1, 1).d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0, 0).val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_d_2) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_d Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0, 0).d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.76, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.92, grads[2]);
EXPECT_FLOAT_EQ(0.12, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_d_3) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_d Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0, 0).val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.76, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.92, grads[2]);
EXPECT_FLOAT_EQ(0.12, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_matrix_d_4) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::matrix_d Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0, 5.0, 7.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0, 0).d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-3.136, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(1.616, grads[2]);
EXPECT_FLOAT_EQ(-0.208, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_matrix_ffv_1) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0, 0).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(0, 1).val_.val_.val());
EXPECT_FLOAT_EQ(2.8, I(1, 0).val_.val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1, 1).val_.val_.val());
EXPECT_FLOAT_EQ(1.6, I(0, 0).d_.val_.val());
EXPECT_FLOAT_EQ(-0.4, I(0, 1).d_.val_.val());
EXPECT_FLOAT_EQ(1.6, I(1, 0).d_.val_.val());
EXPECT_FLOAT_EQ(-0.4, I(1, 1).d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.4, grads[0]);
EXPECT_FLOAT_EQ(-0.6, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_matrix_ffv_2) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_matrix_ffv_3) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
Av(0, 0).val_.d_ = 2.0;
Av(0, 1).val_.d_ = 2.0;
Av(1, 0).val_.d_ = 2.0;
Av(1, 1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_matrix_ffv_4) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::matrix_ffv Av(2, 2);
stan::math::matrix_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0, 5.0, 7.0;
Av(0, 0).d_.val_ = 2.0;
Av(0, 1).d_.val_ = 2.0;
Av(1, 0).d_.val_ = 2.0;
Av(1, 1).d_.val_ = 2.0;
Av(0, 0).val_.d_ = 2.0;
Av(0, 1).val_.d_ = 2.0;
Av(1, 0).val_.d_ = 2.0;
Av(1, 1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0, 0).val_.val_);
vars.push_back(Av(0, 1).val_.val_);
vars.push_back(Av(1, 0).val_.val_);
vars.push_back(Av(1, 1).val_.val_);
I(0, 0).d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0, grads[2]);
EXPECT_FLOAT_EQ(0, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_ffv_1) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(1).val_.val_.val());
EXPECT_FLOAT_EQ(0.8, I(0).d_.val_.val());
EXPECT_FLOAT_EQ(-0.2, I(1).d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
EXPECT_FLOAT_EQ(1.4, grads[4]);
EXPECT_FLOAT_EQ(-0.6, grads[5]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_ffv_2) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.48, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_FLOAT_EQ(-0.12, grads[3]);
EXPECT_FLOAT_EQ(-0.64, grads[4]);
EXPECT_FLOAT_EQ(0.16, grads[5]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_ffv_3) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-0.48, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_FLOAT_EQ(-0.12, grads[3]);
EXPECT_FLOAT_EQ(-0.64, grads[4]);
EXPECT_FLOAT_EQ(0.16, grads[5]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_ffv_4) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.6, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-1.232, grads[2]);
EXPECT_FLOAT_EQ(0.208, grads[3]);
EXPECT_FLOAT_EQ(0.768, grads[4]);
EXPECT_FLOAT_EQ(-0.192, grads[5]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_d_1) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_d Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0).val_.val_.val());
EXPECT_FLOAT_EQ(0, I(1).val_.val_.val());
EXPECT_FLOAT_EQ(-0.8, I(0).d_.val_.val());
EXPECT_FLOAT_EQ(0.2, I(1).d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0).val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(-1.4, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(0.6, grads[2]);
EXPECT_NEAR(0, grads[3], 1E-12);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_d_2) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_d Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0).d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.76, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.92, grads[2]);
EXPECT_FLOAT_EQ(0.12, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_d_3) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_d Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0).val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.76, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(-0.92, grads[2]);
EXPECT_FLOAT_EQ(0.12, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_ffv_row_vector_d_4) {
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> ldlt_Ad;
stan::math::matrix_ffv Ad(2, 2);
stan::math::row_vector_d Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Ad(0, 0).d_.val_ = 1.0;
Ad(0, 1).d_.val_ = 1.0;
Ad(1, 0).d_.val_ = 1.0;
Ad(1, 1).d_.val_ = 1.0;
Ad(0, 0).val_.d_ = 1.0;
Ad(0, 1).val_.d_ = 1.0;
Ad(1, 0).val_.d_ = 1.0;
Ad(1, 1).val_.d_ = 1.0;
Av << 2.0, 3.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Ad(0, 0).val_.val_);
vars.push_back(Ad(0, 1).val_.val_);
vars.push_back(Ad(1, 0).val_.val_);
vars.push_back(Ad(1, 1).val_.val_);
I(0).d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(-3.136, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
EXPECT_FLOAT_EQ(1.616, grads[2]);
EXPECT_FLOAT_EQ(-0.208, grads[3]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_row_vector_ffv_1) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
EXPECT_FLOAT_EQ(1, I(0).val_.val_.val());
EXPECT_FLOAT_EQ(0.0, I(1).val_.val_.val());
EXPECT_FLOAT_EQ(1.6, I(0).d_.val_.val());
EXPECT_FLOAT_EQ(-0.4, I(1).d_.val_.val());
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).val_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(1.4, grads[0]);
EXPECT_FLOAT_EQ(-0.6, grads[1]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_row_vector_ffv_2) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).d_.val_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_row_vector_ffv_3) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).val_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixMdivideRightLDLT, matrix_d_row_vector_ffv_4) {
stan::math::LDLT_factor<double, -1, -1> ldlt_Ad;
stan::math::matrix_d Ad(2, 2);
stan::math::row_vector_ffv Av(2);
stan::math::row_vector_ffv I;
Ad << 2.0, 3.0, 3.0, 7.0;
Av << 2.0, 3.0;
Av(0).d_.val_ = 2.0;
Av(1).d_.val_ = 2.0;
Av(0).val_.d_ = 2.0;
Av(1).val_.d_ = 2.0;
ldlt_Ad.compute(Ad);
ASSERT_TRUE(ldlt_Ad.success());
I = mdivide_right_ldlt(Av, ldlt_Ad);
std::vector<double> grads;
std::vector<var> vars;
vars.push_back(Av(0).val_.val_);
vars.push_back(Av(1).val_.val_);
I(0).d_.d_.grad(vars, grads);
EXPECT_FLOAT_EQ(0, grads[0]);
EXPECT_FLOAT_EQ(0, grads[1]);
}
TEST(AgradMixMatrixMdivideRightLDLT, ffv_exceptions) {
using stan::math::matrix_d;
using stan::math::matrix_ffv;
using stan::math::row_vector_d;
using stan::math::row_vector_ffv;
using stan::math::vector_d;
using stan::math::vector_ffv;
matrix_ffv fv1_(3, 3), fv2_(4, 4);
fv1_ << 1, 2, 3, 4, 5, 6, 7, 8, 9;
fv2_ << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
vector_ffv rvf1(3), rvf2(4);
rvf1.setZero();
rvf2.setZero();
row_vector_ffv vf1(3), vf2(4);
vf1.setZero();
vf2.setZero();
matrix_d fd1_(3, 3), fd2_(4, 4);
fd1_ << 1, 2, 3, 4, 5, 6, 7, 8, 9;
fd2_ << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;
vector_d rvd1(3), rvd2(4);
rvd1.setZero();
rvd2.setZero();
row_vector_d vd1(3), vd2(4);
vd1.setZero();
vd2.setZero();
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> fv1;
stan::math::LDLT_factor<fvar<fvar<var> >, -1, -1> fv2;
stan::math::LDLT_factor<double, -1, -1> fd1;
stan::math::LDLT_factor<double, -1, -1> fd2;
fv1.compute(fv1_);
fv2.compute(fv2_);
fd1.compute(fd1_);
fd2.compute(fd2_);
EXPECT_THROW(mdivide_right_ldlt(fd2_, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fv2_, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fv2_, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fd2_, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(fv2_, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd1, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vd2, fv1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd2, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvd1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vd1, fv2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf2, fd1), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf2, fd2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(rvf1, fd2), std::invalid_argument);
EXPECT_THROW(mdivide_right_ldlt(vf1, fd2), std::invalid_argument);
}
| 29.312796 | 69 | 0.636309 | [
"vector"
] |
e44966300c28e8d51969f6753b27158c93d8fe76 | 34,146 | cpp | C++ | src/projects/repeat_resolution/mdbg.cpp | fedarko/LJA | f20c85395d741b0f94f6d0172c7451d72d7c8713 | [
"BSD-3-Clause"
] | null | null | null | src/projects/repeat_resolution/mdbg.cpp | fedarko/LJA | f20c85395d741b0f94f6d0172c7451d72d7c8713 | [
"BSD-3-Clause"
] | null | null | null | src/projects/repeat_resolution/mdbg.cpp | fedarko/LJA | f20c85395d741b0f94f6d0172c7451d72d7c8713 | [
"BSD-3-Clause"
] | null | null | null | //
// Created by Andrey Bzikadze on 11/25/21.
//
#include "mdbg.hpp"
using namespace repeat_resolution;
std::vector<SuccinctEdgeInfo> MultiplexDBG::SparseDBG2SuccinctEdgeInfo(
dbg::SparseDBG &dbg, const UniqueClassificator &classificator) {
const std::unordered_map<std::string, uint64_t> vert2ind = [&dbg]() {
std::unordered_map<std::string, uint64_t> vert2ind;
uint64_t cnt;
for (const dbg::Vertex &vertex : dbg.vertices()) {
const std::string &id = vertex.getId();
vert2ind.emplace(id, cnt);
++cnt;
}
return vert2ind;
}();
std::vector<SuccinctEdgeInfo> edge_info;
for (auto it = dbg.edges().begin(); it!=dbg.edges().end(); ++it) {
const dbg::Edge &edge = *it;
const RRVertexType start_ind = vert2ind.at(edge.start()->getId());
const RRVertexType end_ind = vert2ind.at(edge.end()->getId());
edge_info.push_back(
{start_ind, end_ind, &edge, classificator.isUnique(edge)});
}
return edge_info;
}
void MultiplexDBG::AssertValidity() const {
int64_t est_max_vert_index = [this]() {
int64_t est_max_vert_index{-1};
for (const auto &vertex : *this) {
est_max_vert_index = std::max(est_max_vert_index, (int64_t) vertex);
}
return est_max_vert_index;
}();
VERIFY(next_vert_index >= 1 + est_max_vert_index);
int64_t est_max_edge_index = [this]() {
int64_t est_max_edge_index{-1};
for (const auto &vertex : *this) {
auto[out_nbr_begin, out_nbr_end] = out_neighbors(vertex);
for (auto it2 = out_nbr_begin; it2!=out_nbr_end; ++it2) {
est_max_edge_index =
std::max(est_max_edge_index,
(int64_t) it2->second.prop().Index());
}
}
return est_max_edge_index;
}();
VERIFY(next_edge_index >= 1 + est_max_edge_index);
for (const auto &vertex : *this) {
if (count_in_neighbors(vertex)==1 and count_out_neighbors(vertex)==1) {
auto[in_nbr_begin, in_nbr_end] = in_neighbors(vertex);
VERIFY_MSG(in_nbr_begin->first==vertex,
"No 1in-1out vertices are allowed except loops")
VERIFY_MSG(node_prop(vertex).IsFrozen(),
"An isolated loop must be frozen");
}
}
for (const auto &vertex : *this) {
auto[out_nbr_begin, out_nbr_end] = out_neighbors(vertex);
const RRVertexProperty &vertex_prop = node_prop(vertex);
for (auto it = out_nbr_begin; it!=out_nbr_end; ++it) {
const RREdgeProperty &edge_prop = it->second.prop();
const int64_t inner_edge_size = edge_prop.Size();
if (inner_edge_size < 0) {
const RRVertexProperty &neighbor_prop = node_prop(it->first);
VERIFY(vertex_prop.Seq().ToSequence().Suffix(-inner_edge_size)==
neighbor_prop.Seq().ToSequence().Prefix(-inner_edge_size));
}
}
}
for (const RRVertexType &vertex : *this) {
const RRVertexProperty &vertex_prop = node_prop(vertex);
if (not vertex_prop.IsFrozen()) {
VERIFY(vertex_prop.size()==n_iter + start_k);
}
}
if (contains_rc) {
std::map<Sequence, RREdgeIndexType> seq_edge;
std::unordered_map<RREdgeIndexType, bool> is_unique_edge;
for (const RRVertexType &vertex : *this) {
auto[begin, end] = out_neighbors(vertex);
for (auto it = begin; it!=end; ++it) {
const RREdgeProperty &edge_prop = it->second.prop();
seq_edge.emplace(
GetEdgeSequence(find(vertex), it, false, false)
.ToSequence(),
edge_prop.Index());
is_unique_edge.emplace(edge_prop.Index(), edge_prop.IsUnique());
}
}
for (const RRVertexType &vertex : *this) {
auto[begin, end] = out_neighbors(vertex);
for (auto it = begin; it!=end; ++it) {
const RREdgeProperty &edge_prop = it->second.prop();
const Sequence seq =
GetEdgeSequence(find(vertex), it, false, false)
.ToSequence();
VERIFY_MSG(seq_edge.find(!seq)!=seq_edge.end(),
"no rev comp for edge " + itos(edge_prop.Index()));
VERIFY_MSG(is_unique_edge.at(edge_prop.Index())
==is_unique_edge.at(seq_edge.at(!seq)),
"edge_prop " + itos(edge_prop.Index()) + ", unique: "
+ itos(is_unique_edge.at(edge_prop.Index()))
+ " . rev compl uniqueness not equal");
}
}
}
}
void MultiplexDBG::SpreadFrost() {
std::unordered_set<RRVertexType> prev_frozen, new_frozen;
for (const RRVertexType &vertex : *this) {
const RRVertexProperty &vertex_prop = node_prop(vertex);
if (vertex_prop.IsFrozen()) {
prev_frozen.insert(vertex);
}
}
auto upd_new_frozen = [this, &new_frozen](const RRVertexType &vertex,
const RRVertexProperty &vertex_prop,
NeighborsIterator begin,
NeighborsIterator end) {
for (auto it = begin; it!=end; ++it) {
const RREdgeProperty &edge_prop = it->second.prop();
const RRVertexType &neighbor = it->first;
const RRVertexProperty &neighbor_prop = node_prop(neighbor);
if (not neighbor_prop.IsFrozen() and
FullEdgeSize(find(vertex), it)==1 + neighbor_prop.size()) {
FreezeVertex(neighbor);
new_frozen.insert(neighbor);
}
}
};
while (not prev_frozen.empty()) {
for (const RRVertexType &vertex : prev_frozen) {
auto[in_nbr_begin, in_nbr_end] = in_neighbors(vertex);
auto[out_nbr_begin, out_nbr_end] = out_neighbors(vertex);
upd_new_frozen(vertex, node_prop(vertex), in_nbr_begin, in_nbr_end);
upd_new_frozen(vertex,
node_prop(vertex),
out_nbr_begin,
out_nbr_end);
}
prev_frozen = std::move(new_frozen);
}
}
void MultiplexDBG::FreezeUnpairedVertices() {
for (const RRVertexType &vertex : *this) {
RRVertexProperty &vertex_prop = node_prop(vertex);
if (vertex_prop.IsFrozen()) {
continue;
}
auto[in_edges, out_edges] = GetNeighborEdgesIndexes(vertex);
if (in_edges.size()==1 and out_edges.size()==1) {
// must be a self-loop
VERIFY(in_edges==out_edges);
FreezeVertex(vertex);
} else if (in_edges.size() >= 2 and out_edges.size() >= 2) {
auto[ac_s2e, ac_e2s] = GetEdgepairsVertex(vertex);
for (const RREdgeIndexType &edge : in_edges) {
if (ac_s2e.find(edge)==ac_s2e.end()) {
FreezeVertex(vertex);
break;
}
}
for (const RREdgeIndexType &edge : out_edges) {
if (ac_e2s.find(edge)==ac_e2s.end()) {
FreezeVertex(vertex);
break;
}
}
}
}
}
std::unordered_map<RREdgeIndexType, Sequence>
MultiplexDBG::GetEdgeSeqs(size_t threads) const {
ParallelRecordCollector<std::pair<RREdgeIndexType, Sequence>> res(threads);
std::vector<ConstIterator> vits;
for (auto v_it = begin(); v_it!=end(); ++v_it) {
vits.emplace_back(v_it);
}
omp_set_num_threads(threads);
#pragma omp parallel for default(none) shared(vits, res)
for (size_t i = 0; i < vits.size(); i++) {
ConstIterator v_it = vits[i];
auto[e_begin, e_end] = out_neighbors(v_it);
for (auto e_it = e_begin; e_it!=e_end; ++e_it) {
const RREdgeProperty &prop = e_it->second.prop();
res.emplace_back(prop.Index(),
GetEdgeSequence(v_it, e_it, false, false)
.ToSequence());
}
}
return {res.begin(), res.end()};
}
std::unordered_map<RRVertexType, Sequence> MultiplexDBG::GetVertexSeqs(
const std::unordered_map<RREdgeIndexType, Sequence> &edge_seq) const {
std::unordered_map<RRVertexType, Sequence> seqs;
for (auto it = begin(); it!=end(); ++it) {
const RRVertexProperty &vertex_prop = node_prop(it);
const uint64_t vertex_size = vertex_prop.size();
auto[ibegin, iend] = in_neighbors(it);
auto[obegin, oend] = out_neighbors(it);
if (ibegin!=iend) {
const RREdgeIndexType edge_ind = ibegin->second.prop().Index();
seqs.emplace(*it, edge_seq.at(edge_ind).Suffix(vertex_size));
} else if (obegin!=oend) {
const RREdgeIndexType edge_ind = obegin->second.prop().Index();
seqs.emplace(*it, edge_seq.at(edge_ind).Prefix(vertex_size));
} else {
seqs.emplace(*it, vertex_prop.Seq().ToSequence());
}
}
return seqs;
}
void MultiplexDBG::MoveEdge(const RRVertexType &s1, NeighborsIterator e1_it,
const RRVertexType &s2, const RRVertexType &e2) {
// this method by itself does not update read paths
add_edge_with_prop(s2, e2, std::move(e1_it->second.prop()));
ConstIterator s1_it = find(s1);
remove_edge(s1_it, e1_it);
}
void MultiplexDBG::MergeEdges(const RRVertexType &s1, NeighborsIterator e1_it,
NeighborsIterator e2_it) {
const RRVertexType &s2 = e1_it->first;
VERIFY_MSG(not node_prop(s2).IsFrozen(),
"Cannot merge edges via a frozen vertex");
RREdgeProperty &e1_prop = e1_it->second.prop();
RREdgeProperty &e2_prop = e2_it->second.prop();
const RREdgeIndexType e2_index = e2_prop.Index();
rr_paths->Merge(e1_prop.Index(), e2_prop.Index());
const RRVertexProperty &v1 = node_prop(s1);
const RRVertexProperty &v3 = node_prop(e2_it->first);
e1_prop.Merge(std::move(node_prop(s2)), std::move(e2_prop));
MoveEdge(s1, e1_it, s1, e2_it->first);
remove_edge(find(s2), FindOutEdgeIterator(s2, e2_index));
remove_nodes(s2);
}
RREdgeIndexType MultiplexDBG::AddConnectingEdge(NeighborsIterator eleft_it,
const RRVertexType &vright,
NeighborsIterator eright_it) {
const RRVertexType &vleft = eleft_it->first;
VERIFY_MSG(vleft!=vright, "Can only add edge b/w disconnected edges");
const RRVertexProperty &vleft_prop = node_prop(vleft);
const RRVertexProperty &vright_prop = node_prop(vright);
const RREdgeProperty &eleft_prop = eleft_it->second.prop();
const RREdgeProperty &eright_prop = eright_it->second.prop();
const RREdgeIndexType new_index = next_edge_index;
++next_edge_index;
RREdgeProperty e_new_prop = Add(vleft_prop, vright_prop, new_index);
rr_paths->Add(eleft_prop.Index(), eright_prop.Index(), e_new_prop.Index());
add_edge_with_prop(vleft, vright, std::move(e_new_prop));
return new_index;
}
RRVertexType MultiplexDBG::GetNewVertex(MDBGSeq seq) {
RRVertexType new_vertex{next_vert_index};
++next_vert_index;
RRVertexProperty property(std::move(seq), false);
add_node_with_prop(new_vertex, std::move(property));
return new_vertex;
}
MultiplexDBG::MultiplexDBG(const std::vector<SuccinctEdgeInfo> &edges,
const uint64_t start_k, RRPaths *const rr_paths,
bool contains_rc)
: rr_paths{rr_paths}, start_k{start_k}, contains_rc{contains_rc} {
for (const SuccinctEdgeInfo &edge_info : edges) {
const dbg::Edge *edge = edge_info.edge;
next_vert_index = std::max(next_vert_index, 1 + edge_info.start_ind);
next_vert_index = std::max(next_vert_index, 1 + edge_info.end_ind);
add_node_with_prop(edge_info.start_ind,
RRVertexProperty(MDBGSeq(edge, 0, start_k), false));
add_node_with_prop(
edge_info.end_ind,
// Anton's edge does not contain prefix
RRVertexProperty(MDBGSeq(edge,
edge->size(),
edge->size() + start_k),
false));
int64_t infix_size = ((int64_t) edge->size()) - start_k;
VERIFY(infix_size > 0 or -infix_size < start_k);
MDBGSeq edge_seq;
if (infix_size > 0) {
edge_seq = MDBGSeq(edge, start_k, start_k + infix_size);
}
RREdgeProperty edge_property(next_edge_index,
std::move(edge_seq),
infix_size,
edge_info.unique);
add_edge_with_prop(edge_info.start_ind, edge_info.end_ind,
std::move(edge_property));
++next_edge_index;
}
FreezeUnpairedVertices();
SpreadFrost();
}
MultiplexDBG::MultiplexDBG(dbg::SparseDBG &dbg, RRPaths *const rr_paths,
const uint64_t start_k,
UniqueClassificator &classificator)
: MultiplexDBG(SparseDBG2SuccinctEdgeInfo(dbg, classificator), start_k,
rr_paths, true) {}
void MultiplexDBG::ExportToDot(
const std::experimental::filesystem::path &path) const {
graph_lite::Serializer serializer(*this);
serializer.set_max_num_nodes_per_line(1);
serializer.set_max_num_edges_per_line(1);
std::ofstream dot_os(path);
serializer.serialize_to_dot(dot_os);
}
void MultiplexDBG::ExportToGFA(
const std::experimental::filesystem::path &path, size_t threads) const {
const std::unordered_map<RREdgeIndexType, Sequence>
edge_seqs = GetEdgeSeqs(threads);
const std::unordered_map<RRVertexType, Sequence> vertex_seqs =
GetVertexSeqs(edge_seqs);
const std::unordered_map<RRVertexType, RRVertexType> vertex2rc =
MapSeqs2RC<RRVertexType>(vertex_seqs);
const std::unordered_map<RREdgeIndexType, RREdgeIndexType> edge2rc =
MapSeqs2RC<RREdgeIndexType>(edge_seqs);
const std::unordered_map<RRVertexType, bool> vertex_can =
AreSeqsCanonical<RRVertexType>(vertex_seqs);
const std::unordered_map<RREdgeIndexType, bool> edge_can =
AreSeqsCanonical<RREdgeIndexType>(edge_seqs);
ExportToGFA(path, vertex_seqs, edge_seqs, vertex2rc, edge2rc, vertex_can,
edge_can);
}
void MultiplexDBG::ExportToGFA(
const std::experimental::filesystem::path &path,
const std::unordered_map<RRVertexType, Sequence> &vertex_seqs,
const std::unordered_map<RREdgeIndexType, Sequence> &edge_seqs,
const std::unordered_map<RRVertexType, RRVertexType> &vertex2rc,
const std::unordered_map<RREdgeIndexType, RREdgeIndexType> &edge2rc,
const std::unordered_map<RRVertexType, bool> &vertex_can,
const std::unordered_map<RREdgeIndexType, bool> &edge_can) const {
std::ofstream os;
os.open(path);
os << "H\tVN:Z:1.0" << std::endl;
std::unordered_map<RREdgeIndexType, RREdgeIndexType> edge2can_id;
for (auto v_it = begin(); v_it!=end(); ++v_it) {
auto[begin, end] = out_neighbors(v_it);
for (auto e_it = begin; e_it!=end; ++e_it) {
const RREdgeProperty &prop = e_it->second.prop();
const RREdgeIndexType e_ind = prop.Index();
if (edge_can.at(e_ind)) {
edge2can_id.emplace(e_ind, e_ind);
edge2can_id.emplace(edge2rc.at(e_ind), e_ind);
os << "S\t" << e_ind << "\t" << edge_seqs.at(e_ind) << "\n";
}
}
}
for (auto v_it = begin(); v_it!=end(); ++v_it) {
if (not vertex_can.at(*v_it)) {
continue;
}
auto[begin, end] = out_neighbors(v_it);
for (auto out_it = begin; out_it!=end; ++out_it) {
const RREdgeProperty &out_prop = out_it->second.prop();
const RREdgeIndexType out_ind = out_prop.Index();
bool out_sign = edge_can.at(out_ind);
const RREdgeIndexType out_can_ind = edge2can_id.at(out_ind);
const RRVertexType v_rc = vertex2rc.at(*v_it);
auto[begin_rc, end_rc] = out_neighbors(v_rc);
for (auto in_it = begin_rc; in_it!=end_rc; ++in_it) {
const RREdgeProperty &in_prop = in_it->second.prop();
const RREdgeIndexType in_ind = in_prop.Index();
bool in_sign = not edge_can.at(in_ind);
const RREdgeIndexType in_can_ind = edge2can_id.at(in_ind);
os << "L\t" << in_can_ind << "\t" << (in_sign ? "+" : "-")
<< "\t"
<< out_can_ind << "\t" << (out_sign ? "+" : "-") << "\t"
<< node_prop(v_it).size() << "M\n";
}
}
}
}
[[nodiscard]] bool MultiplexDBG::IsFrozen() const {
return std::all_of(begin(), end(), [this](const RRVertexType &v) {
return node_prop(v).IsFrozen();
});
}
std::vector<RREdgeIndexType>
MultiplexDBG::GetInEdgesIndexes(const RRVertexType &vertex) const {
std::vector<RREdgeIndexType> indexes;
auto[in_nbr_begin, in_nbr_end] = in_neighbors(vertex);
for (auto it = in_nbr_begin; it!=in_nbr_end; ++it) {
indexes.push_back(it->second.prop().Index());
}
return indexes;
}
bool MultiplexDBG::IsVertexComplex(const RRVertexType &vertex) const {
const int indegree = count_in_neighbors(vertex);
const int outdegree = count_out_neighbors(vertex);
return indegree >= 2 and outdegree >= 2;
}
bool MultiplexDBG::IsVertexSimple(const RRVertexType &vertex) const {
return not IsVertexComplex(vertex);
}
bool MultiplexDBG::IsVertexCanonical(const RRVertexType &vertex) const {
const RRVertexProperty &vertex_prop = node_prop(vertex);
return vertex_prop.IsCanonical();
}
bool MultiplexDBG::IsEdgeCanonical(ConstIterator vertex,
NeighborsConstIterator e_it) const {
const RREdgeProperty &edge_prop = e_it->second.prop();
const MDBGSeq edge_seq = GetEdgeSequence(vertex, e_it, false, false);
return edge_seq.IsCanonical();
}
size_t MultiplexDBG::FullEdgeSize(ConstIterator st_v_it,
NeighborsConstIterator e_it) const {
const RRVertexType &st_v = *st_v_it;
const RRVertexType &en_v = e_it->first;
const RRVertexProperty &st_v_prop = node_prop(st_v_it);
const RRVertexProperty &en_v_prop = node_prop(en_v);
const RREdgeProperty &edge_prop = e_it->second.prop();
int64_t inner_edge_size = edge_prop.Size();
if (inner_edge_size < 0) {
VERIFY(st_v_prop.size() >= -inner_edge_size);
VERIFY(en_v_prop.size() >= -inner_edge_size);
}
return st_v_prop.size() + inner_edge_size + en_v_prop.size();
}
MDBGSeq MultiplexDBG::ExtractEdgePostStartPrefix(ConstIterator st_v_it,
NeighborsIterator e_it,
uint64_t len) {
const RRVertexType &st_v = *st_v_it;
const RRVertexType &en_v = e_it->first;
const RRVertexProperty &st_v_prop = node_prop(st_v);
const RRVertexProperty &en_v_prop = node_prop(en_v);
RREdgeProperty &edge_prop = e_it->second.prop();
VERIFY(len + st_v_prop.size() <= FullEdgeSize(st_v_it, e_it));
uint64_t inner_part_len =
std::min(len, (uint64_t) std::max(0L, edge_prop.Size()));
MDBGSeq prefix = edge_prop.ExtractSeqPrefix(inner_part_len);
uint64_t en_v_part_len = len - inner_part_len;
VERIFY(en_v_part_len <= en_v_prop.size());
prefix.Append(en_v_prop.GetSeqPrefix(en_v_part_len, -edge_prop.Size()));
if (en_v_part_len) {
edge_prop.ShortenWithEmptySeq(en_v_part_len);
}
return prefix;
}
MDBGSeq MultiplexDBG::ExtractEdgePreEndSuffix(ConstIterator en_v_it,
NeighborsIterator e_it,
uint64_t len) {
// Edge is reversed
const RRVertexType &st_v = e_it->first;
const RRVertexType &en_v = *en_v_it;
const RRVertexProperty &st_v_prop = node_prop(st_v);
const RRVertexProperty &en_v_prop = node_prop(en_v);
RREdgeProperty &edge_prop = e_it->second.prop();
size_t full_edge_size = FullEdgeSize(find(en_v), e_it);
VERIFY(len + en_v_prop.size() <= full_edge_size);
uint64_t inner_part_len =
std::min(len, (uint64_t) std::max(0L, edge_prop.Size()));
uint64_t st_v_part_len = len - inner_part_len;
VERIFY(st_v_part_len <= st_v_prop.size());
MDBGSeq suffix = st_v_prop.GetSeqSuffix(st_v_part_len, -edge_prop.Size());
suffix.Append(edge_prop.ExtractSeqSuffix(inner_part_len));
if (st_v_part_len) {
edge_prop.ShortenWithEmptySeq(st_v_part_len);
}
return suffix;
}
void MultiplexDBG::IncreaseVertex(const RRVertexType &vertex, uint64_t len) {
const int indegree = count_in_neighbors(vertex);
const int outdegree = count_out_neighbors(vertex);
VERIFY((indegree==1)!=(outdegree==1));
if (indegree==1) {
NeighborsIterator edge_it = in_neighbors(vertex).first;
MDBGSeq new_seq = ExtractEdgePreEndSuffix(find(vertex), edge_it, len);
node_prop(vertex).IncLeft(std::move(new_seq));
} else {
VERIFY(outdegree==1);
NeighborsIterator edge_it = out_neighbors(vertex).first;
MDBGSeq
new_seq = ExtractEdgePostStartPrefix(find(vertex), edge_it, len);
node_prop(vertex).IncRight(std::move(new_seq));
}
}
std::vector<RREdgeIndexType>
MultiplexDBG::GetOutEdgesIndexes(const RRVertexType &vertex) const {
std::vector<RREdgeIndexType> indexes;
auto[out_nbr_begin, out_nbr_end] = out_neighbors(vertex);
for (auto it = out_nbr_begin; it!=out_nbr_end; ++it) {
indexes.push_back(it->second.prop().Index());
}
return indexes;
}
std::pair<std::vector<RREdgeIndexType>, std::vector<RREdgeIndexType>>
MultiplexDBG::GetNeighborEdgesIndexes(const RRVertexType &vertex) const {
return {GetInEdgesIndexes(vertex), GetOutEdgesIndexes(vertex)};
}
std::pair<MultiplexDBG::EdgeNeighborMap, MultiplexDBG::EdgeNeighborMap>
MultiplexDBG::GetEdgepairsVertex(const RRVertexType &vertex) const {
auto get_init_transitions =
[this](const std::vector<RREdgeIndexType> &in_edges,
const std::vector<RREdgeIndexType> &out_edges) {
EdgeNeighborMap ac_s2e, ac_e2s;
for (const RREdgeIndexType &in_ind : in_edges) {
for (const RREdgeIndexType &out_ind : out_edges) {
if (rr_paths->ContainsPair(in_ind, out_ind)) {
ac_s2e[in_ind].emplace(out_ind);
ac_e2s[out_ind].emplace(in_ind);
}
}
}
return std::make_pair(ac_s2e, ac_e2s);
};
auto extend_transitions_single_loop =
[this, &vertex](const std::vector<RREdgeIndexType> &in_edges,
const std::vector<RREdgeIndexType> &out_edges,
EdgeNeighborMap &ac_s2e, EdgeNeighborMap &ac_e2s) {
std::vector<RREdgeIndexType> loops;
for (const RREdgeIndexType &index : in_edges) {
if (std::find(out_edges.begin(), out_edges.end(), index)!=
out_edges.end()) {
loops.push_back(index);
}
}
if (loops.size()==1) {
const RREdgeIndexType loop = loops.front();
const RREdgeProperty &loop_prop =
FindOutEdgeConstiterator(vertex, loop)->second.prop();
if (loop_prop.IsUnique()) {
if (in_edges.size()==2) {
const size_t loop_index = in_edges.back()==loop;
const size_t nonloop = in_edges[loop_index ^ 1];
ac_s2e[nonloop].emplace(loop);
ac_e2s[loop].emplace(nonloop);
}
if (out_edges.size()==2) {
const size_t loop_index = out_edges.back()==loop;
const size_t nonloop = out_edges[loop_index ^ 1];
ac_s2e[loop].emplace(nonloop);
ac_e2s[nonloop].emplace(loop);
}
}
}
};
auto extend_transitions_all_unique =
[this, &vertex](const std::vector<RREdgeIndexType> &in_edges,
const std::vector<RREdgeIndexType> &out_edges,
EdgeNeighborMap &ac_s2e, EdgeNeighborMap &ac_e2s) {
std::vector<RREdgeIndexType> unpaired_in, unpaired_out;
for (const RREdgeIndexType &index : out_edges) {
if (ac_e2s.find(index)==ac_e2s.end()) {
unpaired_out.push_back(index);
}
}
for (const RREdgeIndexType &index : in_edges) {
if (ac_s2e.find(index)==ac_s2e.end()) {
unpaired_in.push_back(index);
}
}
bool all_in_unique =
std::all_of(in_edges.begin(), in_edges.end(),
[this, &vertex](const RREdgeIndexType &edge_index) {
return FindInEdgeConstiterator(vertex, edge_index)
->second.prop()
.IsUnique();
});
bool all_out_unique =
std::all_of(out_edges.begin(), out_edges.end(),
[this, &vertex](const RREdgeIndexType &edge_index) {
return FindOutEdgeConstiterator(vertex, edge_index)
->second.prop()
.IsUnique();
});
if (unpaired_in.size()==1 and unpaired_out.size()==1 and
(all_in_unique or all_out_unique)) {
const RRVertexType unp_in = unpaired_in.front();
const RRVertexType unp_out = unpaired_out.front();
VERIFY(ac_s2e.find(unp_in)==ac_s2e.end());
VERIFY(ac_e2s.find(unp_out)==ac_e2s.end());
ac_s2e[unp_in] = {unp_out};
ac_e2s[unp_out] = {unp_in};
}
};
const auto[in_edges, out_edges] = GetNeighborEdgesIndexes(vertex);
auto[ac_s2e, ac_e2s] = get_init_transitions(in_edges, out_edges);
extend_transitions_single_loop(in_edges, out_edges, ac_s2e, ac_e2s);
extend_transitions_all_unique(in_edges, out_edges, ac_s2e, ac_e2s);
return std::make_pair(ac_s2e, ac_e2s);
}
MultiplexDBG::NeighborsIterator
MultiplexDBG::FindInEdgeIterator(const RRVertexType &v,
const RREdgeIndexType &edge) {
auto[it, end] = in_neighbors(v);
while (it!=end and it->second.prop().Index()!=edge) {
++it;
}
return it;
};
MultiplexDBG::NeighborsConstIterator
MultiplexDBG::FindInEdgeConstiterator(const RRVertexType &v,
const RREdgeIndexType &edge) const {
auto[it, end] = in_neighbors(v);
while (it!=end and it->second.prop().Index()!=edge) {
++it;
}
return it;
};
MultiplexDBG::NeighborsIterator
MultiplexDBG::FindOutEdgeIterator(const RRVertexType &v,
const RREdgeIndexType &edge) {
auto[it, end] = out_neighbors(v);
while (it!=end and it->second.prop().Index()!=edge) {
++it;
}
return it;
};
MultiplexDBG::NeighborsConstIterator
MultiplexDBG::FindOutEdgeConstiterator(const RRVertexType &v,
const RREdgeIndexType &edge) const {
auto[it, end] = out_neighbors(v);
while (it!=end and it->second.prop().Index()!=edge) {
++it;
}
return it;
}
int64_t MultiplexDBG::GetInnerEdgeSize(ConstIterator vertex,
NeighborsConstIterator e_it) const {
return e_it->second.prop().Size();
}
MDBGSeq MultiplexDBG::GetEdgeSequence(ConstIterator vertex,
NeighborsConstIterator e_it,
bool trim_left, bool trim_right) const {
const RRVertexProperty &vertex_prop = node_prop(vertex);
const RRVertexProperty &neighbor_prop = node_prop(e_it->first);
const RREdgeProperty &edge_prop = e_it->second.prop();
if (edge_prop.Size() < 0) {
if (trim_left and trim_right) {
return {};
}
MDBGSeq neighbor_seq = neighbor_prop.Seq();
if (trim_left) {
neighbor_seq.TrimLeft(-edge_prop.Size());
return neighbor_seq;
}
MDBGSeq vertex_seq = vertex_prop.Seq();
vertex_seq.TrimRight(-edge_prop.Size());
if (not trim_right) {
vertex_seq.Append(neighbor_seq);
}
return vertex_seq;
}
MDBGSeq seq = edge_prop.Seq();
if (not trim_left) {
MDBGSeq vertex_seq = vertex_prop.Seq();
seq.Prepend(std::move(vertex_seq));
}
if (not trim_right) {
MDBGSeq neighbor_seq = neighbor_prop.Seq();
seq.Append(std::move(neighbor_seq));
}
return seq;
}
std::vector<Contig>
MultiplexDBG::GetContigs(size_t threads) const {
const std::unordered_map<RREdgeIndexType, Sequence>
edge_seqs = GetEdgeSeqs(threads);
const std::unordered_map<RRVertexType, Sequence> vertex_seqs =
GetVertexSeqs(edge_seqs);
const std::unordered_map<RRVertexType, RRVertexType> vertex2rc =
MapSeqs2RC<RRVertexType>(vertex_seqs);
std::unordered_map<RRVertexType, bool> vertex_can =
AreSeqsCanonical<RRVertexType>(vertex_seqs);
std::unordered_map<RREdgeIndexType, bool> edge_can =
AreSeqsCanonical<RREdgeIndexType>(edge_seqs);
return GetContigs(vertex_seqs, edge_seqs, vertex2rc, vertex_can, edge_can);
}
[[nodiscard]] std::vector<Contig> MultiplexDBG::GetContigs(
const std::unordered_map<RRVertexType, Sequence> &vertex_seqs,
const std::unordered_map<RREdgeIndexType, Sequence> &edge_seqs,
const std::unordered_map<RRVertexType, RRVertexType> &vertex2rc,
const std::unordered_map<RRVertexType, bool> &vertex_can,
const std::unordered_map<RREdgeIndexType, bool> &edge_can) const {
const std::unordered_map<RRVertexType, bool> trim = [this, &vertex_can,
&vertex2rc]() {
std::unordered_map<RRVertexType, bool> trim;
for (const RRVertexType &vertex : *this) {
const RRVertexProperty &vertex_prop = node_prop(vertex);
if (vertex_can.at(vertex)) {
const bool trim_vertex = count_out_neighbors(vertex)!=1;
trim.emplace(vertex, trim_vertex);
trim.emplace(vertex2rc.at(vertex), not trim_vertex);
}
}
return trim;
}();
std::vector<Contig> contigs;
for (const RRVertexType &vertex : *this) {
auto vertex_it = find(vertex);
const RRVertexProperty &v_prop = node_prop(vertex_it);
auto[out_begin, out_end] = out_neighbors(vertex);
for (auto it = out_begin; it!=out_end; ++it) {
const RREdgeProperty &e_prop = it->second.prop();
const RREdgeIndexType e_ind = e_prop.Index();
if (edge_can.at(it->second.prop().Index())) {
Sequence edge_str = edge_seqs.at(e_ind);
uint64_t left = 0;
if (trim.at(vertex)) {
left += v_prop.size();
}
uint64_t right = edge_str.size();
if (not trim.at(it->first)) {
right -= node_prop(it->first).size();
}
if (left >= right) {
continue;
}
edge_str = edge_str.Subseq(left, right);
contigs.emplace_back(std::move(edge_str),
itos(it->second.prop().Index()));
}
}
}
return contigs;
}
std::vector<Contig> MultiplexDBG::ExportContigs(
const std::experimental::filesystem::path &f,
const std::unordered_map<RRVertexType, Sequence> &vertex_seqs,
const std::unordered_map<RREdgeIndexType, Sequence> &edge_seqs,
const std::unordered_map<RRVertexType, RRVertexType> &vertex2rc,
const std::unordered_map<RRVertexType, bool> &vertex_can,
const std::unordered_map<RREdgeIndexType, bool> &edge_can) const {
std::ofstream os;
os.open(f);
std::vector<Contig> edges =
GetContigs(vertex_seqs, edge_seqs, vertex2rc, vertex_can, edge_can);
for (const Contig &contig : edges) {
os << ">" << contig.id << "\n" << contig.seq << "\n";
}
os.close();
return edges;
}
std::vector<Contig> MultiplexDBG::ExportContigsAndGFA(
const std::experimental::filesystem::path &contigs_fn,
const std::experimental::filesystem::path &gfa_fn, size_t threads) const {
const std::unordered_map<RREdgeIndexType, Sequence>
edge_seqs = GetEdgeSeqs(threads);
const std::unordered_map<RRVertexType, Sequence> vertex_seqs =
GetVertexSeqs(edge_seqs);
const std::unordered_map<RRVertexType, RRVertexType> vertex2rc =
MapSeqs2RC<RRVertexType>(vertex_seqs);
const std::unordered_map<RREdgeIndexType, RREdgeIndexType> edge2rc =
MapSeqs2RC<RREdgeIndexType>(edge_seqs);
std::unordered_map<RRVertexType, bool> vertex_can =
AreSeqsCanonical<RRVertexType>(vertex_seqs);
std::unordered_map<RREdgeIndexType, bool> edge_can =
AreSeqsCanonical<RREdgeIndexType>(edge_seqs);
ExportToGFA(gfa_fn, vertex_seqs, edge_seqs, vertex2rc, edge2rc, vertex_can,
edge_can);
return ExportContigs(contigs_fn, vertex_seqs, edge_seqs, vertex2rc,
vertex_can, edge_can);
}
void MultiplexDBG::ExportActiveTransitions(
const std::experimental::filesystem::path &path) const {
rr_paths->ExportActiveTransitions(path);
}
| 40.505338 | 82 | 0.605342 | [
"vector"
] |
e455b9155c49cc74d86420c63228a19a1fbb1957 | 1,926 | cxx | C++ | test/src/cli_parser.packed.cxx | isbodand/InfoCLI | 67f9ff2dab575b8bbd7957f6bb3256539010d265 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | test/src/cli_parser.packed.cxx | isbodand/InfoCLI | 67f9ff2dab575b8bbd7957f6bb3256539010d265 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2020-10-24T20:42:36.000Z | 2020-10-24T20:42:36.000Z | test/src/cli_parser.packed.cxx | bodand/InfoCLI | 67f9ff2dab575b8bbd7957f6bb3256539010d265 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 bodand
* Licensed under the BSD 3-Clause license
*
* Tests for parsing packed short options like -abc
*/
#include <array>
#include <string_view>
using namespace std::literals;
#include <catch2/catch.hpp>
#include <info/cli/cli_parser.hxx>
using namespace info::cli::udl;
TEST_CASE("cli_parser parses packed valueless boolean flags correctly",
"[cli_parser][short_options][packed]") {
bool a = false, b = false, c = false;
info::cli::cli_parser cli{
'a'_opt >>= a,
'b'_opt >>= b,
'c'_opt >>= c};
auto args = std::array{"text", "-abc", "asd"};
auto rem = cli(args.size(), const_cast<char**>(args.data()));
CHECK_THAT(rem, Catch::Equals(std::vector{"text"sv, "asd"sv}));
CHECK(a);
CHECK(b);
CHECK(c);
}
TEST_CASE("cli_parser parses packed options with values correctly",
"[cli_parser][short_options][packed]") {
bool b = true;
int i = 0;
char c = '\0';
info::cli::cli_parser cli{
'b'_opt >>= b,
'i'_opt >>= i,
'c'_opt >>= c};
auto args = std::array{"text", "-cii42b0", "asd"};
auto rem = cli(args.size(), const_cast<char**>(args.data()));
CHECK_THAT(rem, Catch::Equals(std::vector{"text"sv, "asd"sv}));
CHECK_FALSE(b);
CHECK(i == 42);
CHECK(c == 'i');
}
TEST_CASE("cli_parser parses packed options where the pack's element allows nothing",
"[cli_parser][short_options][packed]") {
bool b = false;
int i = 0;
char c = '\0';
info::cli::cli_parser cli{
'b'_opt >>= b,
'.'_opt >>= i, // this is a heinous idea -.2
'c'_opt >>= c};
auto args = std::array{"text", "-cib.42", "asd"};
auto rem = cli(args.size(), const_cast<char**>(args.data()));
CHECK_THAT(rem, Catch::Equals(std::vector{"text"sv, "asd"sv}));
CHECK(b);
CHECK(i == 42);
CHECK(c == 'i');
}
| 27.126761 | 85 | 0.567497 | [
"vector"
] |
e4565a89109af8dc22a9f4b5c7ba86ee91153d99 | 2,087 | hpp | C++ | src/SpriteRenderer.hpp | ReeCocho/Snek | fb1aec6516adb0586fcc57bd0dccd0d43082d3b2 | [
"MIT"
] | null | null | null | src/SpriteRenderer.hpp | ReeCocho/Snek | fb1aec6516adb0586fcc57bd0dccd0d43082d3b2 | [
"MIT"
] | null | null | null | src/SpriteRenderer.hpp | ReeCocho/Snek | fb1aec6516adb0586fcc57bd0dccd0d43082d3b2 | [
"MIT"
] | null | null | null | #pragma once
/**
* @file SpriteRenderer.hpp
* @brief Sprite renderer header file.
* @author Connor J. Bramham (ReeCocho)
*/
/** Includes. */
#include "Component.hpp"
#include "Material.hpp"
#include "Mesh.hpp"
#include "Transform.hpp"
namespace snk
{
class SpriteRenderer : public Component
{
public:
/**
* @brief Constructor.
* @param Scene the component is in.
* @param Entity the component belongs to.
* @param ID of the type of component.
*/
SpriteRenderer(Scene* scene, Entity entity, ComponentID id);
/**
* @brief Destructor.
*/
~SpriteRenderer() = default;
/**
* @brief Called when the component is added to a game object.
* @note Please use this for memory aquisition.
*/
void onBegin() override;
/**
* @brief Called once per tick after onLateTick() but before presenting.
* @param Time in seconds since last tick.
*/
void onPreRender(float deltaTime) override;
/**
* @brief Set depth.
* @param New depth.
* @return New depth.
*/
inline uint32_t setDepth(uint32_t depth)
{
m_depth = depth;
return m_depth;
}
/**
* @brief Set mesh.
* @param New mesh.
* @return New mesh.
*/
inline Mesh* setMesh(Mesh* mesh)
{
m_mesh = mesh;
return m_mesh;
}
/**
* @brief Set material.
* @param New material.
* @return New material.
*/
inline Material* setMaterial(Material* material)
{
m_material = material;
return m_material;
}
/**
* @brief Get depth.
* @return Depth.
*/
inline uint32_t getDepth() const
{
return m_depth;
}
/**
* @brief Get mesh.
* @return Mesh.
*/
inline Mesh* getMesh() const
{
return m_mesh;
}
/**
* @brief Get material.
* @return Material.
*/
inline Material* getMaterial() const
{
return m_material;
}
private:
/** Meshes transform. */
Transform* m_transform = nullptr;
/** Mesh to render. */
Mesh* m_mesh = nullptr;
/** Material to render the mesh with. */
Material* m_material = nullptr;
/** Mesh depth. */
uint32_t m_depth = 0;
};
} | 17.391667 | 74 | 0.617633 | [
"mesh",
"render",
"object",
"transform"
] |
e4586ef848779455aa7eb9414ec25743dc62c4b4 | 577 | hpp | C++ | include/flexui/Style/StyleTreeUpdater.hpp | franciscod/flexui | 9af2c32a8ac3fe7127a9dd6927abe8b1945237c4 | [
"MIT"
] | null | null | null | include/flexui/Style/StyleTreeUpdater.hpp | franciscod/flexui | 9af2c32a8ac3fe7127a9dd6927abe8b1945237c4 | [
"MIT"
] | null | null | null | include/flexui/Style/StyleTreeUpdater.hpp | franciscod/flexui | 9af2c32a8ac3fe7127a9dd6927abe8b1945237c4 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "flexui/TreeProcessor.hpp"
#include "flexui/Style/StyleSelectorMatcher.hpp"
namespace flexui {
class StyleSheet;
struct StyleSelector;
class StyleTreeUpdater : public TreeProcessor {
public:
StyleTreeUpdater(Surface* surface);
virtual ~StyleTreeUpdater();
void process() override;
private:
std::vector<StyleSheet*> m_SheetsStack;
std::vector<SelectorMatch> m_MatchedSelectors;
void applyStyles(Element* element);
void processMatchedSelectors(Element* element);
void syncWithLayout(Element* element);
};
}
| 18.612903 | 49 | 0.764298 | [
"vector"
] |
e4694d15dfe4d8ec519a19c0a0b8c940f4544915 | 3,366 | cpp | C++ | bme280.cpp | lupyuen/send-altitude-cocoos | 77f33be2ddf3d243056f78e30a1c86c71b8a9d81 | [
"MIT"
] | 24 | 2018-08-16T09:57:44.000Z | 2020-12-18T22:32:48.000Z | bme280.cpp | lupyuen/send-altitude-cocoos | 77f33be2ddf3d243056f78e30a1c86c71b8a9d81 | [
"MIT"
] | 1 | 2019-04-13T14:37:06.000Z | 2019-04-17T06:34:03.000Z | bme280.cpp | lupyuen/send-altitude-cocoos | 77f33be2ddf3d243056f78e30a1c86c71b8a9d81 | [
"MIT"
] | 6 | 2018-09-10T19:48:05.000Z | 2020-12-14T23:12:07.000Z | // BME280 I2C interface for temperature, humidity and altitude sensors.
// Reuses the Arduino library for BME280, even on Blue Pill: https://github.com/finitespace/BME280
#include "platform.h"
#include "display.h"
#ifdef SENSOR_DATA
#include "bme280.h"
#include <Wire.h>
// We will scan these I2C addresses for the BME280.
static const uint8_t i2cAddresses[] = {
0x76, // Optional address for SparkFun BME280 Breakout Board.
0x77, // Default address for SparkFun BME280 Breakout Board.
};
// If we are simulating the BME280, ignore the SPI port because the simulator runs on I2C.
#if defined(USE_BME280_SPI) && !defined(SIMULATE_BME280) // If we are using real SPI version of BME280...
static BME280Spi::Settings settings(0); // BME280 SPI settings.
BME280Spi bme(settings); // The global instance of the BME280 SPI API.
#else // Else we are using I2C or simulated version of BME280...
static BME280I2C::Settings settings; // BME280 I2C settings, including I2C address.
BME280I2C bme; // The global instance of the BME280 I2C API.
#endif // USE_BME280_SPI && !SIMULATE_BME280
// Default Settings: forced mode, standby time = 1000 ms
// Oversampling = pressure ×1, temperature ×1, humidity ×1, filter off,
void bme280_setup(uint32_t port_id) {
// Set up the BME280 module for reading. Skip if already set up.
static bool firstTime = true;
if (!firstTime) return; // Already set up, quit.
firstTime = false;
Wire.begin(); // Init the Wire library for BME280 library.
#if defined(USE_BME280_SPI) && !defined(SIMULATE_BME280) // If we are using real SPI version of BME280...
const int numAddresses = 1; // Check once only for SPI, which has no address.
#else // If we are using I2C version of BME280...
const int numAddresses = sizeof(i2cAddresses) / sizeof(uint8_t); // Scan each I2C address for the BME280 module.
#endif // USE_BME280_SPI && !SIMULATE_BME280
for (int i = 0; i < numAddresses; i++) {
#if defined(USE_BME280_SPI) && !defined(SIMULATE_BME280) // If we are using real SPI version of BME280...
uint8_t pin = convert_port_to_pin(port_id); // Map the port to a pin.
settings.spiCsPin = pin; // Set the pin for the SPI port.
bme = BME280Spi(settings);
#else // If we are using I2C version of BME280...
uint8_t addr = i2cAddresses[i]; // Fetch the next I2C address to be scanned.
settings.bme280Addr = addr;
bme = BME280I2C(settings);
#endif // USE_BME280_SPI && !SIMULATE_BME280
// Fetch the BME280 model number via I2C or SPI. If not found at this I2C address, try next I2C address.
if (!bme.begin()) { continue; }
switch(bme.chipModel()) {
case BME280::ChipModel_BME280:
#ifdef SIMULATE_BME280 // If we are using a simulated BME280...
debug(F("bme >> simulated bme280")); // Show that we are simulated.
#else // Else we are using a real BME280...
debug(F("bme >> real bme280 with arduino library"));
#endif // SIMULATE_BME280
return;
case BME280::ChipModel_BMP280:
debug(F("bme >> bmp280 without humidity"));
return;
default:
debug(F("***** bme280 Error"));
continue; // Try next address
}
}
debug(F("bme >> bme280 not found"));
delay(1000);
}
#endif // SENSOR_DATA
| 43.153846 | 118 | 0.67142 | [
"model"
] |
e46b8f8b464c0f58843de6a55d08982e8013ccaa | 676 | cpp | C++ | 0084_Largest_Rectangle_in_Histogram/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | 2 | 2019-02-18T15:32:57.000Z | 2019-03-18T12:55:35.000Z | 0084_Largest_Rectangle_in_Histogram/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | null | null | null | 0084_Largest_Rectangle_in_Histogram/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | null | null | null | class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ans = 0;
stack<int> stk;
for (int i = 0; i <= heights.size(); i++)
{
int h = (i == heights.size() ? 0 : heights[i]);
if (stk.size() == 0 || h > heights[stk.top()])
{
stk.push(i);
continue;
}
int top = stk.top();
stk.pop();
int lp = stk.size() == 0 ? 0 : stk.top() + 1;
int rp = i - 1;
ans = max(ans, heights[top] * (rp - lp + 1));
i--;
}
return ans;
}
};
| 25.037037 | 59 | 0.357988 | [
"vector"
] |
e46bd4cb8612c5154995e3f1e9691d33eeb81466 | 6,194 | cpp | C++ | src/utils.cpp | shubhomoydas/computer_graphics | 8a13680967617ab5ffdf0a38604e02a19c4b40fe | [
"MIT"
] | null | null | null | src/utils.cpp | shubhomoydas/computer_graphics | 8a13680967617ab5ffdf0a38604e02a19c4b40fe | [
"MIT"
] | null | null | null | src/utils.cpp | shubhomoydas/computer_graphics | 8a13680967617ab5ffdf0a38604e02a19c4b40fe | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include "utils.h"
bool CommandOptions::parseCommandLine(int argc, char **argv) {
file = "obj/cube.obj";
FFfile = "c:/temp/FF.csv";
cr.set(0.0, 0.0, 1.0); // blue
specular.set(1.0,1.0,1.0,1.0);
e.set(2.0,2.0,2.0); // eye coordinates
at.set(0.0,0.0,0.0); // look at coordinates
l.set(3.0,3.0,3.0); // point light coordinates
normMul = 1.0;
//argc = argc;
//argv = argv;
bool returnOptions = true;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if ((arg == "-h") || (arg == "-help")) {
returnOptions = false;
break;
} else if ((arg == "-tc") || (arg == "-testcase")) {
if (i + 1 < argc) {
testCase = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-nd") || (arg == "-nodepth")) {
depthTest = false;
} else if ((arg == "-debug")) {
debug = true;
} else if ((arg == "-shadows")) {
shadows = true;
} else if ((arg == "-shadowsOnly")) {
shadowsOnly = true;
} else if ((arg == "-rndcolor")) {
rndcolor = true;
} else if ((arg == "-smoothcolor")) {
smoothcolor = true;
} else if ((arg == "-occlusion")) {
occlusion = true;
} else if ((arg == "-patchesOnly")) {
patchesOnly = true;
} else if ((arg == "-loadFF")) {
loadFF = true;
} else if ((arg == "-addPRAmbient")) {
addPRAmbient = true;
} else if ((arg == "-sm") || (arg == "-shademodel")) {
if (i + 1 < argc) {
shadeModel = OSU_FLAT;
int tmp = atoi(argv[++i]);
if (tmp == OSU_SMOOTH) shadeModel = OSU_SMOOTH;
} else {
printf("%s option requires one argument (0|1)\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-s") || (arg == "-scale")) {
if (i + 1 < argc) {
scale = atof(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-rd") || (arg == "-reflectionDepth")) {
if (i + 1 < argc) {
reflectionDepth = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-iters")) {
if (i + 1 < argc) {
iters = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-nparts")) {
if (i + 1 < argc) {
nparts = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-ncontour")) {
if (i + 1 < argc) {
ncontour = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-scene")) {
if (i + 1 < argc) {
scene = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-solver")) {
if (i + 1 < argc) {
solver = atoi(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-normMul")) {
if (i + 1 < argc) {
normMul = atof(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-ambient")) {
if (i + 1 < argc) {
ambient = (float)atof(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-intensity")) {
if (i + 1 < argc) {
intensity = (float)atof(argv[++i]);
} else {
printf("%s option requires one argument.\n", arg.c_str());
returnOptions = false;
break;
}
} else if ((arg == "-f") || arg == "-file") {
if (i + 1 < argc) {
file = argv[++i];
} else {
printf("-file option requires one argument.\n");
returnOptions = false;
break;
}
} else if (arg == "-FFfile") {
if (i + 1 < argc) {
FFfile = argv[++i];
} else {
printf("-FFfile option requires one argument.\n");
returnOptions = false;
break;
}
} else if ((arg == "-diffuse")) {
if (i + 1 < argc) {
std::string diffusestr = argv[++i];
if (!cr.parse(diffusestr)) {
std::cout << "Invalid color value " << diffusestr << std::endl;
}
} else {
printf("-diffuse option requires one argument.\n");
returnOptions = false;
break;
}
} else if ((arg == "-specular")) {
if (i + 1 < argc) {
std::string specularstr = argv[++i];
if (!specular.parse(specularstr)) {
std::cout << "Invalid color value " << specularstr << std::endl;
}
} else {
printf("-specular option requires one argument.\n");
returnOptions = false;
break;
}
} else if ((arg == "-e")) {
if (i + 1 < argc) {
std::string estr = argv[++i];
if (!e.parse(estr)) {
std::cout << "Invalid eye coords " << estr << std::endl;
}
} else {
printf("-e option requires one argument.\n");
returnOptions = false;
break;
}
} else if ((arg == "-at")) {
if (i + 1 < argc) {
std::string atstr = argv[++i];
if (!at.parse(atstr)) {
std::cout << "Invalid look 'at' coords " << atstr << std::endl;
}
} else {
printf("-at option requires one argument.\n");
returnOptions = false;
break;
}
} else if ((arg == "-l")) {
if (i + 1 < argc) {
std::string estr = argv[++i];
if (!l.parse(estr)) {
std::cout << "Invalid light coords " << estr << std::endl;
}
} else {
printf("-l option requires one argument.\n");
returnOptions = false;
break;
}
} else {
printf("WARN: unrecognized argument '%s' will be ignored.\n",arg.c_str());
}
}
if (!shadows && shadowsOnly) {
std::cout << "WARN: Shadows disabled. Use -shadows with -shadowsOnly" << std::endl;
shadowsOnly = false;
}
if (!(solver == 0 || solver == 1)) {
std::cout << "solver must be 0 (Gauss-Seidel) or 1 (progressive)" << std::endl;
returnOptions = false;
}
return returnOptions;
}
| 27.40708 | 85 | 0.532451 | [
"vector"
] |
e47c26cc88e4c38c6f7f52be75a119bd3516ec15 | 2,760 | cpp | C++ | Standard Graph Problems/Labyrinth.cpp | rahulgrover99/Competitive | b975b67e815e0d891eadc2d1f21d88944bb36c63 | [
"MIT"
] | null | null | null | Standard Graph Problems/Labyrinth.cpp | rahulgrover99/Competitive | b975b67e815e0d891eadc2d1f21d88944bb36c63 | [
"MIT"
] | null | null | null | Standard Graph Problems/Labyrinth.cpp | rahulgrover99/Competitive | b975b67e815e0d891eadc2d1f21d88944bb36c63 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define FOR0(i,n) for(int i=0;i<n;i++)
#define FOR1(i,n) for(int i=1;i<=n;i++)
#define FORl(i,l,n) for(int i=l;i<n;i++)
using namespace std;
#define pi pair<ll,ll>
#define pb push_back
#define ll long long
#define ld long double
#define ff first
#define ss second
#define mp make_pair
#define mst0(x) memset(x,0,sizeof(x));
#define vi vector<ll>
#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl '\n'
#define sp <<" "<<
#define intmax 1e14
ll power(ll num,ll g,ll mod){
if(g==0)return 1;
if(g%2==1)return (num*power((num*num)%mod,g/2,mod))%mod;
return power((num*num)%mod,g/2,mod);
}
int x[4] = {0, 0, -1, 1};
int y[4] = {1, -1, 0, 0};
vector<vector<int> > visited;
vector<vector<pi> > parent;
void bfs(int sx, int sy, int n, int m, string grid[]){
visited[sx][sy] = 0;
queue<pi> qu;
qu.push({sx, sy});
while(!qu.empty()){
auto tmp = qu.front();
qu.pop();
int i = tmp.ff;
int j = tmp.ss;
// cout << i << " " << j << endl;
for (int k = 0; k < 4; k++){
int x_new = i + x[k];
int y_new = j + y[k];
if (x_new < n && x_new >= 0 && y_new < m && y_new >= 0 && visited[x_new][y_new] == INT_MAX && grid[x_new][y_new] != '#') {
qu.push({x_new, y_new});
parent[x_new][y_new] = {i, j};
visited[x_new][y_new] = visited[i][j] + 1;
}
}
}
}
void travel(string grid[], int n) {
int m = grid[0].size();
visited.resize(n, vector<int>(m, INT_MAX));
parent.resize(n, vector<pi>(m, {-1, -1}));
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (grid[i][j] == 'A') bfs(i, j, n, m, grid);
}
}
}
string find_path(int i, int j){
string ans = "";
while(parent[i][j] != mp(-1LL, -1LL)){
auto tmp = parent[i][j];
if (tmp.ff == i && tmp.ss == j + 1) ans+="L";
else if (tmp.ff == i && tmp.ss == j - 1) ans += "R";
else if (tmp.ff == i + 1) ans += "U";
else ans += "D";
i = tmp.ff;
j = tmp.ss;
}
reverse(ans.begin(), ans.end());
return ans;
}
int main(){
int n, m;
cin >> n >> m;
string s[n];
FOR0(i, n) cin >> s[i];
travel(s, n);
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (s[i][j] == 'B') {
if (visited[i][j] != INT_MAX){
cout << "YES" << endl;
cout << visited[i][j] << endl;
cout << find_path(i, j) << endl;
}
else {
cout << "NO" << endl;
}
return 0;
}
}
}
} | 25.794393 | 134 | 0.450725 | [
"vector"
] |
e47cb924aa7cc964c71515652c7d5c15a586f601 | 1,184 | hpp | C++ | source/util/string.hpp | copsey/dice | eb7239d93368600c2a0a0fa94315ba5f30dfa7e9 | [
"MIT"
] | null | null | null | source/util/string.hpp | copsey/dice | eb7239d93368600c2a0a0fa94315ba5f30dfa7e9 | [
"MIT"
] | null | null | null | source/util/string.hpp | copsey/dice | eb7239d93368600c2a0a0fa94315ba5f30dfa7e9 | [
"MIT"
] | null | null | null | #ifndef DICE_UTIL_STRING
#define DICE_UTIL_STRING
#include <charconv>
#include <string>
#include <string_view>
#include <vector>
namespace dice {
namespace util {
/// Split `str` into the vector of non-empty substrings that are
/// delimited by whitespace in `str`.
///
/// Empty substrings are automatically removed.
std::vector<std::string_view> split_and_prune(std::string_view str);
/// Convert `str` into an int, using the given numeric base, and store
/// the result in `value`.
///
/// In addition to flagging the same errors as `std::from_chars`,
/// returns `std::errc::invalid_argument` if not all of the characters
/// in `str` were used. If this happens, `value` will be left
/// unchanged.
std::from_chars_result from_chars(std::string_view str, int & value, int base = 10);
/// Insert copies of `ch` at the front of `str` until its length is at
/// least `min_l`.
///
/// If `str.size()` is already `min_l` or more, this function has no
/// effect.
inline void pad_front(std::string & str, char ch, std::string::size_type min_l = 1)
{
str.insert(0, (str.size() < min_l) ? (min_l - str.size()) : 0, ch);
}
}
}
#endif
| 30.358974 | 86 | 0.668919 | [
"vector"
] |
e47de910d679d37469548dc9c3bf10cdcce50ead | 3,117 | cpp | C++ | testing/parsing_test.cpp | stian-svedenborg/xyuv | c725b4f926ef3c5311878b0b8b9c4dacbbf0db34 | [
"MIT"
] | 5 | 2015-08-13T18:46:45.000Z | 2018-04-18T18:51:43.000Z | testing/parsing_test.cpp | stian-svedenborg/xyuv | c725b4f926ef3c5311878b0b8b9c4dacbbf0db34 | [
"MIT"
] | 18 | 2015-08-19T13:25:30.000Z | 2017-05-08T10:55:48.000Z | testing/parsing_test.cpp | stian-svedenborg/xyuv | c725b4f926ef3c5311878b0b8b9c4dacbbf0db34 | [
"MIT"
] | 3 | 2016-07-21T12:18:06.000Z | 2018-05-19T05:32:32.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Stian Valentin Svedenborg
*
* 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 <gtest/gtest.h>
#include "../src/config-parser/minicalc/minicalc.h"
#include <vector>
const static std::vector<std::pair<std::string, uint64_t>> expressions {
{"7", 7},
{"1+2", 3},
{"3-5", -2},
{"2*3", 6},
{"12/3", 4},
{"3**3", 27 },
{"(8)", 8},
{"-56", -56},
{"2 + -43", -41},
{"abs(-54)", 54 },
{"gcd(2,1)", 1},
{"gcd(10,5)", 5},
{"gcd(9,15)", 3},
{"gcd(1,1)", 1},
{"gcd(13,7)", 1},
{"lcm(2,1)", 2},
{"lcm(10,5)", 10},
{"lcm(9,15)", 15*3},
{"lcm(1,1)", 1},
{"lcm(13,7)", 13*7},
// Boolean
{"int(true)", uint64_t(true)},
{"int(false)", uint64_t(false)},
{"int(!true)", uint64_t(!true)},
{"int(!false)", uint64_t(!false)},
{"int(!(1==2))", 1},
{"int(! 1 == 2)", 1},
{"int(1==1)", 1},
{"int(1==2)", 0},
{"int(1!=1)", 0},
{"int(1!=2)", 1},
{"int(1 + 1 == 2)", 1},
{"int(1 < 2)", 1},
{"int(1 < 1)", 0},
{"int(2 < 1)", 0},
{"int(1 > 2)", 0},
{"int(1 > 1)", 0},
{"int(2 > 1)", 1},
{"int(1 <= 2)", 1},
{"int(1 <= 1)", 1},
{"int(2 <= 1)", 0},
{"int(1 >= 2)", 0},
{"int(1 >= 1)", 1},
{"int(2 >= 1)", 1},
{"if(true, 40 + 2, 20 + 4)", 42},
{"if(false, 40 + 2, 20 + 4)", 24},
{"int(true && true)", 1},
{"int(true && false)", 0},
{"int(false && true)", 0},
{"int(false && false)", 0},
{"int(true || true)", 1},
{"int(true || false)", 1},
{"int(false || true)", 1},
{"int(false || false)", 0},
};
TEST(MiniCalc, Expressions) {
for (auto expr : expressions) {
SCOPED_TRACE(expr.first);
MiniCalc expression(expr.first);
ASSERT_EQ(expr.second, expression.evaluate(nullptr));
}
} | 28.59633 | 80 | 0.508181 | [
"vector"
] |
e480a832e78e50f83563d9286b013278149494ff | 1,529 | cpp | C++ | books/tech/cpp/qt/m_shlee-qt_5_3/ch_12-interview_model_presentation_/05-observer_program/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | books/tech/cpp/qt/m_shlee-qt_5_3/ch_12-interview_model_presentation_/05-observer_program/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | books/tech/cpp/qt/m_shlee-qt_5_3/ch_12-interview_model_presentation_/05-observer_program/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | #include <QtWidgets>
int main(int argc, char** argv) {
QApplication app{ argc, argv };
QSplitter spl(Qt::Horizontal);
QFileSystemModel model{};
model.setRootPath(QDir::rootPath());
QTreeView* pTreeView{ new QTreeView };
pTreeView->setModel(&model);
QTableView* pTableView{ new QTableView };
pTableView->setModel(&model);
//QObject::connect(pTreeView,
// SIGNAL(clicked(QModelIndex const&)),
// pTableView,
// SLOT(setRootIndex(QModelIndex const&)));
QObject::connect(pTreeView,
&QTreeView::clicked,
pTableView,
&QTableView::setRootIndex);
//QObject::connect(pTableView,
// SIGNAL(activated(QModelIndex const&)),
// pTreeView,
// SLOT(setCurrentIndex(QModelIndex const&)));
QObject::connect(pTableView,
&QTableView::activated,
pTreeView,
&QTreeView::setCurrentIndex);
//QObject::connect(pTableView,
// SIGNAL(activated(QModelIndex const&)),
// pTableView,
// SLOT(setRootIndex(QModelIndex const&)));
QObject::connect(pTableView,
&QTableView::activated,
pTableView,
&QTableView::setRootIndex);
spl.addWidget(pTreeView);
spl.addWidget(pTableView);
spl.show();
return app.exec();
}
| 30.58 | 66 | 0.534336 | [
"model"
] |
6b07a64c3f2c0199cbcdc9389fffc4825bea7fc2 | 818 | cpp | C++ | CCC/Stage1/02-Done/ccc02s5.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | 1 | 2017-10-01T00:51:39.000Z | 2017-10-01T00:51:39.000Z | CCC/Stage1/02-Done/ccc02s5.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | CCC/Stage1/02-Done/ccc02s5.cpp | zzh8829/CompetitiveProgramming | 36f36b10269b4648ca8be0b08c2c49e96abede25 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <fstream>
#include <bitset>
#include <cstring>
#include <cmath>
#include <ctime>
using namespace std;
double slope;
double w,h;
double sx,sy;
int ans;
int main()
{
cin >> w >> h;
cin >> sx >> sy;
slope = sy/(w-sx);
for(int k=1;k<=100000;k++)
{
double xx = k*w;
double xy = slope*(xx-sx);
int ny = (int)((xy+h/2)/h);
double gy = ny * h;
double yy = k*h;
double yx = yy/slope+sx;
int nx = (int)((yx+w/2)/2);
int gx = nx*w;
if(abs(gy-xy)<5)
{
ans = k+ny-2;
if(xy>gy)ans++;
break;
}
if(abs(gx-yx)<5)
{
ans = k+nx-2;
if(yx>gx)ans++;
break;
}
}
cout<< ans << endl;
return 0;
} | 14.872727 | 30 | 0.52445 | [
"vector"
] |
6b0842236dda53b68348cc9c755227a05fbb0e67 | 6,018 | cc | C++ | dali/operators/decoder/audio/audio_decoder_impl.cc | a-sansanwal/DALI | 83aeb96792d053f60dd4252b8efa0fc8fdd9012a | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-10-07T23:07:23.000Z | 2020-10-07T23:07:23.000Z | dali/operators/decoder/audio/audio_decoder_impl.cc | MAKali4737/DALI | 3b114c6ebee38ff3815a9b4a234402e4d1affaa0 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/decoder/audio/audio_decoder_impl.cc | MAKali4737/DALI | 3b114c6ebee38ff3815a9b4a234402e4d1affaa0 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright (c) 2020, 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 "dali/operators/decoder/audio/audio_decoder_impl.h"
#include "dali/kernels/signal/downmixing.h"
namespace dali {
template <typename T>
span<char> as_raw_span(T *buffer, ptrdiff_t length) {
return make_span(reinterpret_cast<char*>(buffer), length*sizeof(T));
}
TensorShape<> DecodedAudioShape(const AudioMetadata &meta, float target_sample_rate,
bool downmix) {
bool should_resample = target_sample_rate > 0 && meta.sample_rate != target_sample_rate;
bool should_downmix = meta.channels > 1 && downmix;
int channels = meta.channels == 1 || downmix ? 1 : meta.channels;
int64_t len = should_resample ? kernels::signal::resampling::resampled_length(
meta.length, meta.sample_rate, target_sample_rate)
: meta.length;
return downmix ? TensorShape<>{len} : TensorShape<>{len, channels};
}
template <typename T, typename DecoderOutputType>
void DecodeAudio(TensorView<StorageCPU, T, DynamicDimensions> audio, AudioDecoderBase &decoder,
const AudioMetadata &meta, kernels::signal::resampling::Resampler &resampler,
span<DecoderOutputType> decode_scratch_mem,
span<float> resample_scratch_mem,
float target_sample_rate, bool downmix,
const char *audio_filepath) { // audio_filepath for debug purposes
DALI_ENFORCE(meta.sample_rate > 0, "Invalid sampling rate");
bool should_resample = target_sample_rate > 0 && meta.sample_rate != target_sample_rate;
bool should_downmix = meta.channels > 1 && downmix;
int64_t num_samples = meta.length * meta.channels;
assert(audio.data != nullptr);
assert(num_samples > 0);
if (!should_resample && !should_downmix && std::is_same<T, DecoderOutputType>::value) {
int64_t ret = decoder.Decode(as_raw_span(audio.data, num_samples));
DALI_ENFORCE(ret == num_samples, make_string("Error decoding audio file ", audio_filepath));
return;
}
DALI_ENFORCE(decode_scratch_mem.size() >= num_samples,
make_string("Decoder scratch memory provided is not big enough. Got: ",
decode_scratch_mem.size(), ", need: ", num_samples));
const int64_t out_channels = should_downmix ? 1 : meta.channels;
constexpr bool is_float_decoder = std::is_same<DecoderOutputType, float>::value;
if (should_resample) {
if (should_downmix) {
// When downmixing, we need an extra buffer for the input of resampling
assert(resample_scratch_mem.size() >= meta.length * out_channels &&
"Resample scratch memory provided is not big enough");
} else {
// If not downmixing, we expect the decoder output type to be float so that it can be
// directly fed into the resampling kernel
assert(is_float_decoder &&
"Audio should be decoded in float when resampling is required and downmixing is not");
}
}
int64_t ret = decoder.Decode(as_raw_span(decode_scratch_mem.data(), num_samples));
DALI_ENFORCE(ret == num_samples, make_string("Error decoding audio file ", audio_filepath));
const int64_t in_len = meta.length * meta.channels;
if (should_resample) {
if (should_downmix) {
assert(resample_scratch_mem.size() == meta.length);
float *resample_in = resample_scratch_mem.data();
kernels::signal::Downmix(resample_in, decode_scratch_mem.data(), meta.length, meta.channels);
resampler.Resample(audio.data, 0, audio.shape[0], target_sample_rate,
resample_scratch_mem.data(), meta.length,
meta.sample_rate, out_channels);
} else { // No downmix, enforcing the output of the decoder is float (resampling kernel expects
// float)
assert(decode_scratch_mem.size() == meta.length * meta.channels);
assert(is_float_decoder); // logic sanity check
resampler.Resample(audio.data, 0, audio.shape[0], target_sample_rate,
reinterpret_cast<float *>(decode_scratch_mem.data()), meta.length,
meta.sample_rate, meta.channels);
}
} else if (should_downmix) { // downmix only
kernels::signal::Downmix(audio.data, decode_scratch_mem.data(), meta.length, meta.channels);
} else {
// convert or copy only. Should not happen if DecoderOutputType is selected properly
for (int64_t ofs = 0; ofs < in_len; ofs++) {
audio.data[ofs] = ConvertSatNorm<T>(decode_scratch_mem[ofs]);
}
}
}
#define DECLARE_IMPL(OutType, DecoderOutputType) \
template void DecodeAudio<OutType, DecoderOutputType>( \
TensorView<StorageCPU, OutType, DynamicDimensions> audio, AudioDecoderBase & decoder, \
const AudioMetadata &meta, kernels::signal::resampling::Resampler &resampler, \
span<DecoderOutputType> decode_scratch_mem, span<float> resample_scratch_mem, \
float target_sample_rate, bool downmix, const char *audio_filepath)
DECLARE_IMPL(float, int16_t);
DECLARE_IMPL(int16_t, int16_t);
DECLARE_IMPL(int32_t, int16_t);
DECLARE_IMPL(float, float);
DECLARE_IMPL(int16_t, float);
DECLARE_IMPL(int32_t, float);
DECLARE_IMPL(float, int32_t);
DECLARE_IMPL(int16_t, int32_t);
DECLARE_IMPL(int32_t, int32_t);
#undef DECLARE_IMPL
} // namespace dali
| 47.385827 | 100 | 0.685278 | [
"shape"
] |
6b1c93f60d36e8052132974e0afcff8c6d6bdec6 | 2,561 | cpp | C++ | PathPlanningNotes/BehaviourPlanning/cost2.cpp | ahtchow/CarND-PathPlanning-P6 | 887cc1aeb2110791da09e3b9b7cf538479362c21 | [
"MIT"
] | null | null | null | PathPlanningNotes/BehaviourPlanning/cost2.cpp | ahtchow/CarND-PathPlanning-P6 | 887cc1aeb2110791da09e3b9b7cf538479362c21 | [
"MIT"
] | null | null | null | PathPlanningNotes/BehaviourPlanning/cost2.cpp | ahtchow/CarND-PathPlanning-P6 | 887cc1aeb2110791da09e3b9b7cf538479362c21 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
double inefficiency_cost(int target_speed, int intended_lane, int final_lane,
const std::vector<int> &lane_speeds) {
// Cost becomes higher for trajectories with intended lane and final lane
// that have traffic slower than target_speed.
int speed_intended_lane = lane_speeds[intended_lane];
int speed_final_lane = lane_speeds[final_lane];
double cost = cost = 1 - exp(-(std::abs(2.0*target_speed-speed_intended_lane-speed_final_lane)/target_speed));
return cost;
}
int main() {
// Target speed of our vehicle
int target_speed = 10;
// Lane speeds for each lane
std::vector<int> lane_speeds = {6, 7, 8, 9};
// Test cases used for grading - do not change.
double cost;
cout << "Costs for (intended_lane, final_lane):" << endl;
cout << "---------------------------------------------------------" << endl;
cost = inefficiency_cost(target_speed, 3, 3, lane_speeds);
cout << "The cost is " << cost << " for " << "(3, 3)" << endl;
cost = inefficiency_cost(target_speed, 2, 3, lane_speeds);
cout << "The cost is " << cost << " for " << "(2, 3)" << endl;
cost = inefficiency_cost(target_speed, 2, 2, lane_speeds);
cout << "The cost is " << cost << " for " << "(2, 2)" << endl;
cost = inefficiency_cost(target_speed, 1, 2, lane_speeds);
cout << "The cost is " << cost << " for " << "(1, 2)" << endl;
cost = inefficiency_cost(target_speed, 1, 1, lane_speeds);
cout << "The cost is " << cost << " for " << "(1, 1)" << endl;
cost = inefficiency_cost(target_speed, 0, 1, lane_speeds);
cout << "The cost is " << cost << " for " << "(0, 1)" << endl;
cost = inefficiency_cost(target_speed, 0, 0, lane_speeds);
cout << "The cost is " << cost << " for " << "(0, 0)" << endl;
return 0;
}
/**
* @brief Cost Function Design
*
* Difficulties:
* - Solving new problems without unsolving old ones
* - Regression Testing!
* - Balancing Cost of drastically different magnitudes
* - feasibility, safety, legality, comfort, efficiency
* - weights must change on different situations
* - Reasoning about individual CFs
* - specificity of cost function responsibility
* - Binary vs discrete vs continious cost functions
* - ALL CFs output between -1 and 1
* - Parametrization (when possible)
* - Thinking in terms of vehicle state
*
*
*/ | 38.80303 | 112 | 0.600937 | [
"vector"
] |
6b248dbe53629350c92f1d71e9da1f20a2c06b1d | 24,817 | cpp | C++ | srccon/AStyleTestCon_Print.cpp | FabianSchmitt/TP8 | 2b9918322e9f7776d9ef62c06f2c435a00b70322 | [
"MIT"
] | null | null | null | srccon/AStyleTestCon_Print.cpp | FabianSchmitt/TP8 | 2b9918322e9f7776d9ef62c06f2c435a00b70322 | [
"MIT"
] | null | null | null | srccon/AStyleTestCon_Print.cpp | FabianSchmitt/TP8 | 2b9918322e9f7776d9ef62c06f2c435a00b70322 | [
"MIT"
] | null | null | null | // AStyleTestCon_Print.cpp
// Copyright (c) 2018 by Jim Pattee <jimp03@email.com>.
// This code is licensed under the MIT License.
// License.md describes the conditions under which this software may be distributed.
// AStyleTestCon tests the ASConsole class only. This class is used only in
// the console build. It also tests the parseOption function for options used
// by only by the console build (e.g. recursive, preserve-date, verbose). It
// does not explicitely test the ASStreamIterator class or any other part
// of the program.
//----------------------------------------------------------------------------
// headers
//----------------------------------------------------------------------------
#include <algorithm>
#include "AStyleTestCon.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#endif
//----------------------------------------------------------------------------
// global variables
//----------------------------------------------------------------------------
// defined in astyle_main.cpp
namespace astyle {
extern const char* g_version;
}
//----------------------------------------------------------------------------
// anonymous namespace
//----------------------------------------------------------------------------
namespace {
//
//----------------------------------------------------------------------------
// AStyle PrintF Class
//----------------------------------------------------------------------------
class PrintF : public Test
// The PrintF class captures the stdout output stream and redirects it to a file.
// The file is used to verify the Artistic Style console build print format.
// The functions were "borrowed" from the CapturedStream class in gtest-port.cc
// of Google Test (gtest).
{
public:
ASFormatter formatter; // required formatter object
ASConsole* console; // console object
vector<string> fileNames; // files created for test
size_t filesExcluded; // number of files excluded from formatting
// variables for redirecting stdout
int fd_; // stream to capture
int uncaptured_fd_; // stdout stream
string filename_; // temporary file holding the stdout output
public:
PrintF();
~PrintF();
// make adjustments to expected text
void adjustText(string& text);
// make adjustments to textOut
void adjustTextOut(string& textOut);
// build a vector of files to exclude
void buildExcludeVector();
// get today's date in MDY format
string getCurrentDate();
// redirect the stdout stream to a temporary file
void redirectStream();
// restore the stdout stream and return the captured text
string restoreStream();
private:
// called by the constructor to build the test files
void createTestFiles();
// called by restoreStream() to read the entire content of a file as a string
string readEntireFile(FILE* file);
};
PrintF::PrintF()
// c'tor
{
#if defined(_MSC_VER) || defined(__BORLANDC__)
// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
const int stdOutFileno = 1;
#else
const int stdOutFileno = STDOUT_FILENO;
#endif // _MSC_VER
// initialize variables
fd_ = stdOutFileno;
uncaptured_fd_ = dup(stdOutFileno);
filesExcluded = 0;
// create test objects
console = new ASConsole(formatter);
createTestFiles();
// use C locale for consistent formatting
setlocale(LC_ALL, "C");
}
PrintF::~PrintF()
// d'tor
{
if (uncaptured_fd_ != -1)
{
// the stream must be restored first
restoreStream();
systemPause("\nCaptured fd_ was not restored.");
}
removeTestFile(filename_);
delete console;
}
void PrintF::adjustText(string& text)
// make adjustments to expected text
{
// replace first line with version number and date
if (text.compare(0, 14, "Artistic Style") == 0)
{
string tagVersion = "<version>";
string tagDate = "<date>";
string replaceVersion = string(g_version);
size_t verStart = text.find(tagVersion);
size_t verEnd = verStart + replaceVersion.length();
if (verStart != string::npos)
text.replace(verStart, tagVersion.length(), replaceVersion);
if (replaceVersion.length() < tagVersion.length())
text.insert(verEnd, tagVersion.length() - replaceVersion.length(), ' ');
else if (replaceVersion.length() > tagVersion.length())
text.erase(verEnd, replaceVersion.length() - tagVersion.length());
size_t dateStart = text.find(tagDate);
if (dateStart != string::npos)
text.replace(dateStart, tagDate.length(), getCurrentDate());
}
// insert linefeed as first character for readability
text.insert(0, "\n");
// replace <test_directory> with the actual directory
for (size_t i = 0; i < text.length(); i++)
{
i = text.find("<test_directory>", i);
if (i == string::npos)
break;
text.replace(i, 16, getTestDirectory());
}
// replace backslashes in file paths
for (size_t i = 0; i < text.length(); i++)
{
i = text.find('\\', i);
if (i == string::npos)
break;
text[i] = '/';
}
}
void PrintF::adjustTextOut(string& textOut)
// make adjustments to textOut
{
// insert linefeed as first character for readability
textOut.insert(0, "\n");
// replace backslashes in file paths
for (size_t i = 0; i < textOut.length(); i++)
{
i = textOut.find('\\', i);
if (i == string::npos)
break;
textOut[i] = '/';
}
// delete any decimals in the time
size_t decimal = textOut.rfind('.');
if (decimal != string::npos
&& textOut.length() > 30
&& decimal > textOut.length() - 30)
{
// delete to the next space
size_t space = textOut.find(' ', decimal);
if (space != string::npos)
textOut.erase(decimal, space - decimal);
}
#ifdef __BORLANDC__
// delete any bad data at the start of the text (problem with Embarcadero)
// this should be fixed in a future compiler release
// when the white "getinfo1.c" lines are not displayed remove the following
if (textOut.compare(1, 10, "getinfo1.c") == 0)
{
size_t textStart = textOut.find("Artistic Style");
textOut.erase(1, textStart - 1);
}
#endif
}
void PrintF::buildExcludeVector()
// build a vector of files to exclude
{
char textExcluded[] = "\nvoid foo() { bar(); }\n";
// add files to fileNames vector
fileNames.push_back(getTestDirectory() + "/fileExcluded.cpp");
console->standardizePath(fileNames.back());
createTestFile(fileNames.back(), textExcluded);
// build exclude vector
console->updateExcludeVector("fileExcluded.cpp");
filesExcluded += 1;
}
void PrintF::createTestFiles()
// called by the constructor to build the test files
{
char textFormatted[] =
"\nvoid foo()\n"
"{\n"
"bar();\n"
"}\n";
char textUnchanged[] =
"\nvoid foo()\n"
"{\n"
" bar();\n"
"}\n";
cleanTestDirectory(getTestDirectory());
fileNames.push_back(getTestDirectory() + "/fileFormatted.cpp");
console->standardizePath(fileNames.back());
createTestFile(fileNames.back(), textFormatted);
fileNames.push_back(getTestDirectory() + "/fileUnchanged.cpp");
console->standardizePath(fileNames.back());
createTestFile(fileNames.back(), textUnchanged);
}
string PrintF::getCurrentDate()
{
struct tm* ptr;
time_t lt;
char str[20];
lt = time(nullptr);
ptr = localtime(<);
strftime(str, 20, "%x", ptr);
return string(str);
}
string PrintF::readEntireFile(FILE* file)
// called by restoreStream() to read the entire content of a file as a string
{
fseek(file, 0, SEEK_END);
const size_t file_size = ftell(file);
char* const buffer = new char[file_size];
size_t bytes_last_read = 0; // # of bytes read in the last fread()
size_t bytes_read = 0; // # of bytes read so far
fseek(file, 0, SEEK_SET);
// Keeps reading the file until we cannot read further or the
// pre-determined file size is reached.
do
{
bytes_last_read = fread(buffer + bytes_read, 1, file_size - bytes_read, file);
bytes_read += bytes_last_read;
}
while (bytes_last_read > 0 && bytes_read < file_size);
const string textOut(buffer, bytes_read);
delete[] buffer;
return textOut;
}
void PrintF::redirectStream()
// redirect the stdout stream to a temporary file
{
#ifdef _WIN32
char temp_file_path[MAX_PATH + 1] = { '\0' };
const DWORD success = GetTempPath(sizeof(temp_file_path), temp_file_path);
GTEST_CHECK_(success > 0) << "Unable to get temporary directory path";
strcat(temp_file_path, "AStyleTestCon.tmp");
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path;
filename_ = temp_file_path;
#else
// There's no guarantee that a test has write access to the
// current directory, so we create the temporary file in the /tmp
// directory instead.
char temp_file_path[] = "/tmp/AStyleTestCon.tmp";
const int captured_fd = creat(temp_file_path, S_IREAD | S_IWRITE);
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path;
filename_ = temp_file_path;
#endif
fflush(nullptr);
dup2(captured_fd, fd_);
close(captured_fd);
}
string PrintF::restoreStream()
// restore the stdout stream and return the captured text
{
if (uncaptured_fd_ != -1)
{
// restore the original stream
fflush(nullptr);
dup2(uncaptured_fd_, fd_);
close(uncaptured_fd_);
uncaptured_fd_ = -1;
}
FILE* const file = fopen(filename_.c_str(), "r");
const string content = readEntireFile(file);
fclose(file);
return content;
}
//----------------------------------------------------------------------------
// AStyle print tests
//----------------------------------------------------------------------------
TEST_F(PrintF, DefaultWildcard)
// test print wildcard with no options
{
// expected text
string text =
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size(), fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, DefaultWildcard_Exclude)
// test print wildcard with an exclude
{
// expected text
string text =
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"Exclude fileExcluded.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add exclude files
buildExcludeVector();
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, DefaultWildcard_ExcludeError)
// test print wildcard with exclude errors and ignore-exclude-errors
{
// expected text
string text =
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"Exclude fileExcluded.cpp\n"
"Exclude (unmatched) noExcludedFile.cpp\n"
"Exclude (unmatched) noExcludedDirectory\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back("--ignore-exclude-errors");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add exclude files
buildExcludeVector();
console->updateExcludeVector("noExcludedFile.cpp");
console->updateExcludeVector("noExcludedDirectory");
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, DefaultWildcard_ExcludeErrorNoPrint)
// test print wildcard with exclude errors and ignore-exclude-errors-x
{
// expected text
string text =
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"Exclude fileExcluded.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back("--ignore-exclude-errors-x");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add exclude files
buildExcludeVector();
console->updateExcludeVector("noExcludedFile.cpp");
console->updateExcludeVector("noExcludedDirectory");
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, FormattedWildcard)
// test print with "formatted" wildcard
{
console->setIsFormattedOnly(true); // test variable
// expected text
string text =
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size(), fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, VerboseWildcard_DefaultOptionFile)
// test print with "verbose" wildcard and default option file
{
console->setIsVerbose(true); // test variable
// expected text
string text =
"Artistic Style <version> <date>\n"
"Default option file <test_directory>/astylerc.txt\n"
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n"
"------------------------------------------------------------\n"
" 1 formatted 1 unchanged 0 seconds 12 lines\n\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add option file
console->setOptionFileName(getTestDirectory() + "/astylerc.txt");
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, VerboseWildcard_ProjectOptionFile)
// test print with "verbose" wildcard and project option file
{
console->setIsVerbose(true); // test variable
// expected text
string text =
"Artistic Style <version> <date>\n"
"Project option file <test_directory>/astylerc.txt\n"
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n"
"------------------------------------------------------------\n"
" 1 formatted 1 unchanged 0 seconds 12 lines\n\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add project option file
console->setProjectOptionFileName(getTestDirectory() + "/astylerc.txt");
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, VerboseWildcard_DefaultAndProjectOptionFiles)
// test print with "verbose" wildcard and default and project option files
{
console->setIsVerbose(true); // test variable
// expected text
string text =
"Artistic Style <version> <date>\n"
"Default option file <test_directory>/astylerc.txt\n"
"Project option file <test_directory>/astylerc.txt\n"
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"Unchanged fileUnchanged.cpp\n"
"------------------------------------------------------------\n"
" 1 formatted 1 unchanged 0 seconds 12 lines\n\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add option files
console->setOptionFileName(getTestDirectory() + "/astylerc.txt");
console->setProjectOptionFileName(getTestDirectory() + "/astylerc.txt");
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, VerboseFormattedWildcard)
// test print with "verbose" and "formatted" wildcard
{
console->setIsVerbose(true); // test variable
console->setIsFormattedOnly(true); // test variable
// expected text
string text =
"Artistic Style <version> <date>\n"
"------------------------------------------------------------\n"
"Directory <test_directory>/*.cpp\n"
"------------------------------------------------------------\n"
"Formatted fileFormatted.cpp\n"
"------------------------------------------------------------\n"
" 1 formatted 1 unchanged 0 seconds 12 lines\n\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, DefaultSingleFile)
// test print single file with no options
{
// expected text
string text = "Formatted <test_directory>/fileFormatted.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/fileFormatted.cpp");
console->processOptions(astyleOptionsVector);
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(1U, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, FormattedSingleFile)
// test print with "formatted" single file
{
console->setIsFormattedOnly(true); // test variable
// expected text
string text = "Formatted <test_directory>/fileFormatted.cpp\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/fileFormatted.cpp");
console->processOptions(astyleOptionsVector);
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(1U, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, VerboseSingleFile_OptionsFile)
// test print with "verbose" single file
{
console->setIsVerbose(true); // test variable
// expected text
string text =
"Artistic Style <version> <date>\n"
"Default option file <test_directory>/astylerc.txt\n"
"Formatted <test_directory>/fileFormatted.cpp\n"
" 1 formatted 0 unchanged 0 seconds 6 lines\n\n";
adjustText(text);
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/fileFormatted.cpp");
console->processOptions(astyleOptionsVector);
// add options file
console->setOptionFileName(getTestDirectory() + "/astylerc.txt");
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(1U, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
TEST_F(PrintF, Quiet_AllOptions)
// test print with "quiet" and all other options
{
console->setIsFormattedOnly(true);
console->setIsVerbose(true);
console->setIsQuiet(true); // test variable
// expected text
string text = "\n";
// call astyle processOptions()
vector<string> astyleOptionsVector;
astyleOptionsVector.push_back("--ascii");
astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp");
console->processOptions(astyleOptionsVector);
// add options and exclude files
console->setOptionFileName(getTestDirectory() + "/astylerc.txt");
buildExcludeVector();
// redirect stdout and get the report
redirectStream();
console->processFiles();
string textOut = restoreStream();
adjustTextOut(textOut);
// check entries in the fileNameVector
vector<string> fileName = console->getFileName();
ASSERT_EQ(fileNames.size() - filesExcluded, fileName.size()) << "Print format was not checked.";
// check the report content
EXPECT_EQ(text, textOut);
}
//----------------------------------------------------------------------------
} // namespace
| 34.515994 | 97 | 0.654189 | [
"object",
"vector"
] |
6b28e16dbea5f4b2c686807bbf6de30b863bc140 | 44,260 | cpp | C++ | SPOUTSDK/SpoutDirectX/SpoutDX/Tutorial07/Tutorial07.cpp | dlvrydryvr/Spout2 | 9ffa0fb25f67aa2da7778db33dd8ac6f12a37695 | [
"BSD-2-Clause"
] | 465 | 2015-01-12T17:32:29.000Z | 2022-03-31T08:12:48.000Z | SPOUTSDK/SpoutDirectX/SpoutDX/Tutorial07/Tutorial07.cpp | dlvrydryvr/Spout2 | 9ffa0fb25f67aa2da7778db33dd8ac6f12a37695 | [
"BSD-2-Clause"
] | 71 | 2015-01-30T17:54:37.000Z | 2022-03-08T01:30:00.000Z | SPOUTSDK/SpoutDirectX/SpoutDX/Tutorial07/Tutorial07.cpp | dlvrydryvr/Spout2 | 9ffa0fb25f67aa2da7778db33dd8ac6f12a37695 | [
"BSD-2-Clause"
] | 114 | 2015-01-15T06:43:37.000Z | 2022-03-11T06:13:01.000Z | //--------------------------------------------------------------------------------------
// File: Tutorial07.cpp
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Adapted for SPOUT output (http://spout.zeal.co/)
// from : https://github.com/walbourn/directx-sdk-samples/tree/master/Direct3D11Tutorials
// Search on "SPOUT" for additions.
//
// This is a receiver using the SpoutDX support class and ReceiveTexture :
//
// bool spoutDX::ReceiveTexture(ID3D11Texture2D** ppTexture)
//
// Compare with a version using methods directly from the Spout 2.007 SDK.
// Compare also with a Windows example using ReceiveImage.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// This application demonstrates texturing
//
// http://msdn.microsoft.com/en-us/library/windows/apps/ff729724.aspx
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include <windows.h>
#include <d3d11_1.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <directxcolors.h>
#include "DDSTextureLoader.h"
#include "resource.h"
// SPOUT
#include "..\..\SpoutDX\SpoutDX.h"
using namespace DirectX;
//--------------------------------------------------------------------------------------
// Structures
//--------------------------------------------------------------------------------------
struct SimpleVertex
{
XMFLOAT3 Pos;
XMFLOAT2 Tex;
};
struct CBNeverChanges
{
XMMATRIX mView;
};
struct CBChangeOnResize
{
XMMATRIX mProjection;
};
struct CBChangesEveryFrame
{
XMMATRIX mWorld;
XMFLOAT4 vMeshColor;
};
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
HINSTANCE g_hInst = nullptr;
HWND g_hWnd = nullptr;
D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0;
ID3D11Device* g_pd3dDevice = nullptr;
ID3D11Device1* g_pd3dDevice1 = nullptr;
ID3D11DeviceContext* g_pImmediateContext = nullptr;
ID3D11DeviceContext1* g_pImmediateContext1 = nullptr;
IDXGISwapChain* g_pSwapChain = nullptr;
IDXGISwapChain1* g_pSwapChain1 = nullptr;
ID3D11RenderTargetView* g_pRenderTargetView = nullptr;
ID3D11Texture2D* g_pDepthStencil = nullptr;
ID3D11DepthStencilView* g_pDepthStencilView = nullptr;
ID3D11VertexShader* g_pVertexShader = nullptr;
ID3D11PixelShader* g_pPixelShader = nullptr;
ID3D11InputLayout* g_pVertexLayout = nullptr;
ID3D11Buffer* g_pVertexBuffer = nullptr;
ID3D11Buffer* g_pIndexBuffer = nullptr;
ID3D11Buffer* g_pCBNeverChanges = nullptr;
ID3D11Buffer* g_pCBChangeOnResize = nullptr;
ID3D11Buffer* g_pCBChangesEveryFrame = nullptr;
ID3D11ShaderResourceView* g_pTextureRV = nullptr;
ID3D11SamplerState* g_pSamplerLinear = nullptr;
XMMATRIX g_World;
XMMATRIX g_View;
XMMATRIX g_Projection;
// XMFLOAT4 g_vMeshColor( 0.7f, 0.7f, 0.7f, 1.0f );
// SPOUT
XMFLOAT4 g_vMeshColor(1.0f, 1.0f, 1.0f, 1.0f);
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT InitDevice();
void CleanupDevice();
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
void Render();
// SPOUT
spoutDX receiver; // Spout DirectX11 receiver
ID3D11Texture2D* g_pReceivedTexture = nullptr; // Texture received from a sender
ID3D11ShaderResourceView* g_pSpoutTextureRV = nullptr; // Shader resource view of the texture
// Functions for selecting graphics adapter
void ResetDevice();
void SelectAdapter();
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
INT_PTR CALLBACK SenderProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
INT_PTR CALLBACK AdapterProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
bool g_bAutoAdapt = false; // Auto switch to the same adapter as the sender (menu option)
// Statics for dialog box
static char sendername[256];
static std::string adaptername[10];
static int adaptercount = 0;
static int currentadapter = 0;
static int selectedadapter = 0;
static int senderadapter = 0;
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow )
{
UNREFERENCED_PARAMETER( hPrevInstance );
UNREFERENCED_PARAMETER( lpCmdLine );
//
// SPOUT Options
//
// OpenSpoutConsole(); // Console only for debugging
// EnableSpoutLog(); // Enable Spout logging to console
// EnableSpoutLogFile("Tutorial07.log"); // Log to file
// SetSpoutLogLevel(SPOUT_LOG_WARNING); // show only warnings and errors
// Set the name of the sender to receive from.
// The receiver will only connect to that sender.
// The user can over-ride this by selecting another (receiver.SelectSender())
// It can be cleared with a null sender name (receiver.SetReceiverName())
// receiver.SetReceiverName("Spout Demo Sender");
if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
return 0;
// SPOUT
// See InitDevice for creating a Spout class device
if( FAILED( InitDevice() ) )
{
CleanupDevice();
return 0;
}
//
// SPOUT
//
// Initialize DirectX.
// The device pointer must be passed in if a DirectX 11.0 device is available.
// Otherwise a device is created in the SpoutDX class.
// The function does nothing if a class device was already created.
// See InitDevice for creating a class device
//
if (!receiver.OpenDirectX11(g_pd3dDevice))
return FALSE;
//
// Menu options for change of graphics adapter
//
// The "Select graphics adapter" menu option allows selection
// and change to the same adapter as used by a particluar sender.
//
// The "Auto switch adapter" menu option enables auto switch to
// the same adapter as the sender.
// Search for : IDM_AUTO_ADAPTER for more detail on the "SetAdapterAuto()"
// function which enables or disables this option..
//
// Both sender and receiver must use the same graphics adapter.
// If the "Auto switch adapter" menu option is enabled, selection of a different
// graphics adapter will result in change back to the sender graphics adapter.
//
// The D3D11 device must have been be created within the SpoutDX class
// If a class device was not created, remove both menu options.
//
if (!receiver.IsClassDevice()) {
HMENU hPopup = GetSubMenu(GetMenu(g_hWnd), 0);
RemoveMenu(hPopup, IDM_ADAPTER, MF_BYCOMMAND);
RemoveMenu(hPopup, IDM_AUTO_ADAPTER, MF_BYCOMMAND);
}
// Main message loop
MSG msg = {0};
while( WM_QUIT != msg.message )
{
if( PeekMessage( &msg, nullptr, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
Render();
}
}
// SPOUT
receiver.ReleaseReceiver();
receiver.CloseDirectX11();
if (g_pSpoutTextureRV)
g_pSpoutTextureRV->Release();
if (g_pReceivedTexture)
g_pReceivedTexture->Release();
CleanupDevice();
return ( int )msg.wParam;
}
//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon( hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
wcex.hCursor = LoadCursor( nullptr, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_TUTORIAL1); // add a menu
wcex.lpszClassName = L"TutorialWindowClass";
wcex.hIconSm = LoadIcon( wcex.hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
if( !RegisterClassEx( &wcex ) )
return E_FAIL;
// Create window
g_hInst = hInstance;
RECT rc = { 0, 0, 640, 360 };
AdjustWindowRect(&rc, WS_CAPTION | WS_SYSMENU, TRUE); // Resize for the menu
g_hWnd = CreateWindow( L"TutorialWindowClass",
L"Direct3D 11 Tutorial 7 - Spout receiver",
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT,
rc.right - rc.left, rc.bottom - rc.top,
nullptr, nullptr, hInstance, nullptr );
if( !g_hWnd )
return E_FAIL;
//
// SPOUT
//
// Centre the window on the desktop work area
GetWindowRect(g_hWnd, &rc);
RECT WorkArea;
int WindowPosLeft = 0;
int WindowPosTop = 0;
SystemParametersInfo(SPI_GETWORKAREA, 0, (LPVOID)&WorkArea, 0);
WindowPosLeft += ((WorkArea.right - WorkArea.left) - (rc.right - rc.left)) / 2;
WindowPosTop += ((WorkArea.bottom - WorkArea.top) - (rc.bottom - rc.top)) / 2;
MoveWindow(g_hWnd, WindowPosLeft, WindowPosTop,
(rc.right - rc.left), rc.bottom - rc.top, false);
ShowWindow( g_hWnd, nCmdShow );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Helper for compiling shaders with D3DCompile
//
// With VS 11, we could load up prebuilt .cso files instead...
//--------------------------------------------------------------------------------------
HRESULT CompileShaderFromFile( const WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut )
{
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
// Disable optimizations to further improve shader debugging
dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
ID3DBlob* pErrorBlob = nullptr;
hr = D3DCompileFromFile( szFileName, nullptr, nullptr, szEntryPoint, szShaderModel,
dwShaderFlags, 0, ppBlobOut, &pErrorBlob );
if( FAILED(hr) )
{
if( pErrorBlob )
{
OutputDebugStringA( reinterpret_cast<const char*>( pErrorBlob->GetBufferPointer() ) );
pErrorBlob->Release();
}
return hr;
}
if( pErrorBlob ) pErrorBlob->Release();
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
HRESULT hr = S_OK;
RECT rc;
GetClientRect( g_hWnd, &rc );
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
// LJ DEBUG
//
// SPOUT
//
// Option: Create a device within the SpoutDX class.
// See below for device reaction code that has been commented out.
// IsClassDevice() will return the hr result whether this has been done or not.
// See also the option to use OpenDirectX11() after an application device has been created.
// ===============================================================
if (receiver.OpenDirectX11()) {
g_pd3dDevice = receiver.GetDX11Device();
g_pImmediateContext = receiver.GetDX11Context();
}
else {
return 0;
}
// ===============================================================
/*
// ===============================================================
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// SPOUT note
// GL/DX interop Spec
// ID3D11Device can only be used on WDDM operating systems : Must be multithreaded
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
g_driverType = driverTypes[driverTypeIndex];
hr = D3D11CreateDevice(nullptr, g_driverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext);
if (hr == E_INVALIDARG)
{
// DirectX 11.0 platforms will not recognize D3D_FEATURE_LEVEL_11_1 so we need to retry without it
hr = D3D11CreateDevice(nullptr, g_driverType, nullptr, createDeviceFlags, &featureLevels[1], numFeatureLevels - 1,
D3D11_SDK_VERSION, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext);
}
if (SUCCEEDED(hr))
break;
}
if (FAILED(hr))
return hr;
// SPOUT
// If an application DirectX 11.0 device was created above,
// the device pointer must be passed in to the SpoutDX class.
// The function does nothing if a class device was already created.
//
if (!receiver.OpenDirectX11(g_pd3dDevice))
return FALSE;
// ===============================================================
*/
// Obtain DXGI factory from device (since we used nullptr for pAdapter above)
IDXGIFactory1* dxgiFactory = nullptr;
{
IDXGIDevice* dxgiDevice = nullptr;
hr = g_pd3dDevice->QueryInterface( __uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice) );
if (SUCCEEDED(hr))
{
IDXGIAdapter* adapter = nullptr;
hr = dxgiDevice->GetAdapter(&adapter);
if (SUCCEEDED(hr))
{
hr = adapter->GetParent( __uuidof(IDXGIFactory1), reinterpret_cast<void**>(&dxgiFactory) );
adapter->Release();
}
dxgiDevice->Release();
}
}
if (FAILED(hr))
return hr;
// Create swap chain
IDXGIFactory2* dxgiFactory2 = nullptr;
hr = dxgiFactory->QueryInterface( __uuidof(IDXGIFactory2), reinterpret_cast<void**>(&dxgiFactory2) );
if ( dxgiFactory2 )
{
// DirectX 11.1 or later
hr = g_pd3dDevice->QueryInterface( __uuidof(ID3D11Device1), reinterpret_cast<void**>(&g_pd3dDevice1) );
if (SUCCEEDED(hr))
{
(void) g_pImmediateContext->QueryInterface( __uuidof(ID3D11DeviceContext1), reinterpret_cast<void**>(&g_pImmediateContext1) );
}
DXGI_SWAP_CHAIN_DESC1 sd = {};
sd.Width = width;
sd.Height = height;
sd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = 1;
hr = dxgiFactory2->CreateSwapChainForHwnd( g_pd3dDevice, g_hWnd, &sd, nullptr, nullptr, &g_pSwapChain1 );
if (SUCCEEDED(hr))
{
hr = g_pSwapChain1->QueryInterface( __uuidof(IDXGISwapChain), reinterpret_cast<void**>(&g_pSwapChain) );
}
dxgiFactory2->Release();
}
else
{
// DirectX 11.0 systems
DXGI_SWAP_CHAIN_DESC sd = {};
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
hr = dxgiFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain );
}
// Note this tutorial doesn't handle full-screen swapchains so we block the ALT+ENTER shortcut
dxgiFactory->MakeWindowAssociation( g_hWnd, DXGI_MWA_NO_ALT_ENTER );
dxgiFactory->Release();
if (FAILED(hr))
return hr;
// Create a render target view
ID3D11Texture2D* pBackBuffer = nullptr;
hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), reinterpret_cast<void**>( &pBackBuffer ) );
if( FAILED( hr ) )
return hr;
hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, nullptr, &g_pRenderTargetView );
pBackBuffer->Release();
if( FAILED( hr ) )
return hr;
// Create depth stencil texture
D3D11_TEXTURE2D_DESC descDepth = {};
descDepth.Width = width;
descDepth.Height = height;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
hr = g_pd3dDevice->CreateTexture2D( &descDepth, nullptr, &g_pDepthStencil );
if( FAILED( hr ) )
return hr;
// Create the depth stencil view
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV = {};
descDSV.Format = descDepth.Format;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
if( FAILED( hr ) )
return hr;
g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView );
// Setup the viewport
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)width;
vp.Height = (FLOAT)height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
g_pImmediateContext->RSSetViewports( 1, &vp );
// Compile the vertex shader
ID3DBlob* pVSBlob = nullptr;
hr = CompileShaderFromFile( L"Tutorial07.fx", "VS", "vs_4_0", &pVSBlob );
if( FAILED( hr ) )
{
MessageBox( nullptr,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK );
return hr;
}
// Create the vertex shader
hr = g_pd3dDevice->CreateVertexShader( pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &g_pVertexShader );
if( FAILED( hr ) )
{
pVSBlob->Release();
return hr;
}
// Define the input layout
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE( layout );
// Create the input layout
hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVSBlob->GetBufferPointer(),
pVSBlob->GetBufferSize(), &g_pVertexLayout );
pVSBlob->Release();
if( FAILED( hr ) )
return hr;
// Set the input layout
g_pImmediateContext->IASetInputLayout( g_pVertexLayout );
// Compile the pixel shader
ID3DBlob* pPSBlob = nullptr;
hr = CompileShaderFromFile( L"Tutorial07.fx", "PS", "ps_4_0", &pPSBlob );
if( FAILED( hr ) )
{
MessageBox( nullptr,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK );
return hr;
}
// Create the pixel shader
hr = g_pd3dDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &g_pPixelShader );
pPSBlob->Release();
if( FAILED( hr ) )
return hr;
// Create vertex buffer
SimpleVertex vertices[] =
{
{ XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
{ XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
{ XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
{ XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
{ XMFLOAT3( -1.0f, -1.0f, -1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( 1.0f, -1.0f, -1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( 1.0f, 1.0f, -1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
{ XMFLOAT3( -1.0f, 1.0f, -1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( -1.0f, -1.0f, 1.0f ), XMFLOAT2( 1.0f, 1.0f ) },
{ XMFLOAT3( 1.0f, -1.0f, 1.0f ), XMFLOAT2( 0.0f, 1.0f ) },
{ XMFLOAT3( 1.0f, 1.0f, 1.0f ), XMFLOAT2( 0.0f, 0.0f ) },
{ XMFLOAT3( -1.0f, 1.0f, 1.0f ), XMFLOAT2( 1.0f, 0.0f ) },
};
D3D11_BUFFER_DESC bd = {};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( SimpleVertex ) * 24;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA InitData = {};
InitData.pSysMem = vertices;
hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer );
if( FAILED( hr ) )
return hr;
// Set vertex buffer
UINT stride = sizeof( SimpleVertex );
UINT offset = 0;
g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset );
// Create index buffer
// Create vertex buffer
WORD indices[] =
{
3,1,0,
2,1,3,
6,4,5,
7,4,6,
11,9,8,
10,9,11,
14,12,13,
15,12,14,
19,17,16,
18,17,19,
22,20,21,
23,20,22
};
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( WORD ) * 36;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = indices;
hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer );
if( FAILED( hr ) )
return hr;
// Set index buffer
g_pImmediateContext->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );
// Set primitive topology
g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
// Create the constant buffers
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(CBNeverChanges);
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = 0;
hr = g_pd3dDevice->CreateBuffer( &bd, nullptr, &g_pCBNeverChanges );
if( FAILED( hr ) )
return hr;
bd.ByteWidth = sizeof(CBChangeOnResize);
hr = g_pd3dDevice->CreateBuffer( &bd, nullptr, &g_pCBChangeOnResize );
if( FAILED( hr ) )
return hr;
bd.ByteWidth = sizeof(CBChangesEveryFrame);
hr = g_pd3dDevice->CreateBuffer( &bd, nullptr, &g_pCBChangesEveryFrame );
if( FAILED( hr ) )
return hr;
// Load the Texture
hr = CreateDDSTextureFromFile( g_pd3dDevice, L"seafloor.dds", nullptr, &g_pTextureRV );
if( FAILED( hr ) )
return hr;
// Create the sample state
D3D11_SAMPLER_DESC sampDesc = {};
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = g_pd3dDevice->CreateSamplerState( &sampDesc, &g_pSamplerLinear );
if( FAILED( hr ) )
return hr;
// Initialize the world matrices
g_World = XMMatrixIdentity();
// Initialize the view matrix
/*
XMVECTOR Eye = XMVectorSet( 0.0f, 3.0f, -6.0f, 0.0f );
XMVECTOR At = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
*/
// SPOUT - Move it up a bit
XMVECTOR Eye = XMVectorSet(0.0f, 1.0f, -5.0f, 0.0f);
XMVECTOR At = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
g_View = XMMatrixLookAtLH( Eye, At, Up );
CBNeverChanges cbNeverChanges;
cbNeverChanges.mView = XMMatrixTranspose( g_View );
g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, nullptr, &cbNeverChanges, 0, 0 );
// Initialize the projection matrix
g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV4, width / (FLOAT)height, 0.01f, 100.0f );
CBChangeOnResize cbChangesOnResize;
cbChangesOnResize.mProjection = XMMatrixTranspose( g_Projection );
g_pImmediateContext->UpdateSubresource( g_pCBChangeOnResize, 0, nullptr, &cbChangesOnResize, 0, 0 );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Clean up the objects we've created
//--------------------------------------------------------------------------------------
void CleanupDevice()
{
if( g_pImmediateContext ) g_pImmediateContext->ClearState();
if( g_pSamplerLinear ) g_pSamplerLinear->Release();
if( g_pTextureRV ) g_pTextureRV->Release();
if( g_pCBNeverChanges ) g_pCBNeverChanges->Release();
if( g_pCBChangeOnResize ) g_pCBChangeOnResize->Release();
if( g_pCBChangesEveryFrame ) g_pCBChangesEveryFrame->Release();
if( g_pVertexBuffer ) g_pVertexBuffer->Release();
if( g_pIndexBuffer ) g_pIndexBuffer->Release();
if( g_pVertexLayout ) g_pVertexLayout->Release();
if( g_pVertexShader ) g_pVertexShader->Release();
if( g_pPixelShader ) g_pPixelShader->Release();
if( g_pDepthStencil ) g_pDepthStencil->Release();
if( g_pDepthStencilView ) g_pDepthStencilView->Release();
if( g_pRenderTargetView ) g_pRenderTargetView->Release();
if( g_pSwapChain1 ) g_pSwapChain1->Release();
if( g_pSwapChain ) g_pSwapChain->Release();
if( g_pImmediateContext1 ) g_pImmediateContext1->Release();
if( g_pImmediateContext ) g_pImmediateContext->Release();
if( g_pd3dDevice1 ) g_pd3dDevice1->Release();
if( g_pd3dDevice ) g_pd3dDevice->Release();
}
// SPOUT
// Re-initialize for size changes
void ResetDevice()
{
// Close the receiver
receiver.ReleaseReceiver();
// Close the spoutdx class device
receiver.CloseDirectX11();
// Release everything
CleanupDevice();
// Start again
InitDevice();
}
//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
PAINTSTRUCT ps;
HDC hdc;
switch( message )
{
case WM_COMMAND:
// Parse the menu selections:
switch (LOWORD(wParam))
{
// Select sender
case IDM_SENDER:
// Sender selection dialog box
sendername[0] = 0; // Clear static name for dialog
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_SENDERBOX), g_hWnd, (DLGPROC)SenderProc);
break;
// Select graphics adapter
case IDM_ADAPTER:
SelectAdapter();
break;
// Auto switch to sender adapter
case IDM_AUTO_ADAPTER:
{
g_bAutoAdapt = !g_bAutoAdapt;
if (g_bAutoAdapt) {
receiver.SetAdapterAuto(true);
// Switch to sender adapter if connected.
// See details in SelectAdapter()
if (receiver.IsConnected()) {
selectedadapter = receiver.GetSenderAdapter(receiver.GetSenderName());
if (receiver.SetAdapter(selectedadapter)) {
currentadapter = selectedadapter;
ResetDevice();
}
}
CheckMenuItem(GetMenu(g_hWnd), IDM_AUTO_ADAPTER, MF_CHECKED);
}
else {
receiver.SetAdapterAuto(false);
CheckMenuItem(GetMenu(g_hWnd), IDM_AUTO_ADAPTER, MF_UNCHECKED);
}
}
break;
case IDM_ABOUT:
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), g_hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
break;
}
break;
case WM_PAINT:
hdc = BeginPaint( hWnd, &ps );
EndPaint( hWnd, &ps );
break;
// SPOUT - RH click to open SpoutPanel
case WM_RBUTTONDOWN:
receiver.SelectSender();
break;
case WM_DESTROY:
PostQuitMessage( 0 );
break;
// Note that this tutorial does not handle resizing (WM_SIZE) requests,
// so we created the window without the resize border.
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
return 0;
}
//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
// Update our time
static float t = 0.0f;
if( g_driverType == D3D_DRIVER_TYPE_REFERENCE )
{
t += ( float )XM_PI * 0.0125f;
}
else
{
static ULONGLONG timeStart = 0;
ULONGLONG timeCur = GetTickCount64();
if( timeStart == 0 )
timeStart = timeCur;
t = ( timeCur - timeStart ) / 1000.0f;
t /= 2.0f; // SPOUT - slow the cube rotation down a bit
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
// SPOUT
//
// A texture can be received to a local texture
// or to a texture withing the SpoutDX class.
//
// Change the receiving option here for testing
// 1 - receive to a local texture (g_pReceivedTexture)
// 2 - receive to a SpoutDX class texture
//
int option = 1;
if (option == 1) {
//
// Option 1 : Receive from a sender to a local texture
//
if (receiver.ReceiveTexture(&g_pReceivedTexture)) {
// Create or re-create the receiving texture
// for a new sender or if the sender size changed
if (receiver.IsUpdated()) {
// The D3D11 device within the SpoutDX class could have changed
// if it has switched to use a different sender graphics adapter.
// Re-intialize to refresh the application global device pointer.
if (receiver.GetAdapterAuto()) {
if (g_pd3dDevice != receiver.GetDX11Device()) {
ResetDevice();
// No more this round because the receiver has been released
// and there is no width or height to create a texture.
return;
}
}
// Update the receiving texture
if (g_pReceivedTexture) g_pReceivedTexture->Release();
g_pReceivedTexture = nullptr;
receiver.CreateDX11texture(g_pd3dDevice,
receiver.GetSenderWidth(),
receiver.GetSenderHeight(),
receiver.GetSenderFormat(),
&g_pReceivedTexture);
// Any other action required by the receiver can be done here
// In this example, clear the shader resource view
if (g_pSpoutTextureRV) g_pSpoutTextureRV->Release();
g_pSpoutTextureRV = nullptr;
}
// A texture has been received
// In this example, a shader resource view is created if the frame is new
if (receiver.IsFrameNew()) {
if (g_pSpoutTextureRV) g_pSpoutTextureRV->Release();
g_pSpoutTextureRV = nullptr;
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc));
// Matching format with the sender is important
shaderResourceViewDesc.Format = receiver.GetSenderFormat();
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;
g_pd3dDevice->CreateShaderResourceView(g_pReceivedTexture, &shaderResourceViewDesc, &g_pSpoutTextureRV);
}
}
else {
// A sender was not found or the connected sender closed
// Release the receiving texture
if (g_pReceivedTexture) g_pReceivedTexture->Release();
g_pReceivedTexture = nullptr;
// Release the texture resource view so render uses the default
if (g_pSpoutTextureRV) g_pSpoutTextureRV->Release();
g_pSpoutTextureRV = nullptr;
}
}
else if (option == 2) {
//
// Option 2 : Receive from a sender to a SpoutDX class texture
//
if (receiver.ReceiveTexture()) {
//
// Sender details can be retrieved with :
// const char * GetSenderName();
// unsigned int GetSenderWidth();
// unsigned int GetSenderHeight();
// DXGI_FORMAT GetSenderFormat();
// HANDLE GetSenderHandle;
// long GetSenderFrame();
// double GetSenderFps();
//
// The D3D11 device within the SpoutDX class could have changed
// if it has switched to use a different sender graphics adapter.
// Re-intialize to refresh the application global device pointer.
if (receiver.GetAdapterAuto()) {
if (g_pd3dDevice != receiver.GetDX11Device()) {
ResetDevice();
// No more this round because the receiver has been released
// and there is no width or height to create a texture.
return;
}
}
// A class texture has been received
// The received texture can be retrieved with
// ID3D11Texture2D* GetSenderTexture();
// In this example, a shader resource view is created if the frame is new
if (receiver.IsFrameNew()) {
if (g_pSpoutTextureRV) g_pSpoutTextureRV->Release();
g_pSpoutTextureRV = nullptr;
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc;
ZeroMemory(&shaderResourceViewDesc, sizeof(shaderResourceViewDesc));
// Matching format with the sender is important
shaderResourceViewDesc.Format = receiver.GetSenderFormat();
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
shaderResourceViewDesc.Texture2D.MipLevels = 1;
g_pd3dDevice->CreateShaderResourceView(receiver.GetSenderTexture(), &shaderResourceViewDesc, &g_pSpoutTextureRV);
}
}
else {
// A sender was not found or the connected sender closed
// Release the texture resource view so render uses the default
if (g_pSpoutTextureRV) g_pSpoutTextureRV->Release();
g_pSpoutTextureRV = nullptr;
}
}
// End receive texture
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Rotate cube around the origin
// g_World = XMMatrixRotationY(t);
// SPOUT - pitch and yaw
g_World = XMMatrixRotationRollPitchYaw(0.0f, t, t);
// Modify the color
// SPOUT - remove
// g_vMeshColor.x = ( sinf( t * 1.0f ) + 1.0f ) * 0.5f;
// g_vMeshColor.y = ( cosf( t * 3.0f ) + 1.0f ) * 0.5f;
// g_vMeshColor.z = ( sinf( t * 5.0f ) + 1.0f ) * 0.5f;
//
// Clear the back buffer
//
// g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::MidnightBlue );
// SPOUT
// Change backgound colour for better contrast with the blue demo sender
g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, Colors::DarkRed);
//
// Clear the depth buffer to 1.0 (max depth)
//
g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );
//
// Update variables that change once per frame
//
CBChangesEveryFrame cb;
cb.mWorld = XMMatrixTranspose( g_World );
cb.vMeshColor = g_vMeshColor;
g_pImmediateContext->UpdateSubresource( g_pCBChangesEveryFrame, 0, nullptr, &cb, 0, 0 );
//
// Render the cube
//
g_pImmediateContext->VSSetShader( g_pVertexShader, nullptr, 0 );
g_pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pCBNeverChanges );
g_pImmediateContext->VSSetConstantBuffers( 1, 1, &g_pCBChangeOnResize );
g_pImmediateContext->VSSetConstantBuffers( 2, 1, &g_pCBChangesEveryFrame );
g_pImmediateContext->PSSetShader( g_pPixelShader, nullptr, 0 );
g_pImmediateContext->PSSetConstantBuffers( 2, 1, &g_pCBChangesEveryFrame );
// SPOUT
// Use the sender's texture shader resource view if received
if(g_pSpoutTextureRV)
g_pImmediateContext->PSSetShaderResources(0, 1, &g_pSpoutTextureRV);
else
g_pImmediateContext->PSSetShaderResources(0, 1, &g_pTextureRV);
g_pImmediateContext->PSSetSamplers( 0, 1, &g_pSamplerLinear );
g_pImmediateContext->DrawIndexed( 36, 0, 0 );
//
// Present our back buffer to our front buffer
//
//
// SPOUT - fps control
//
// Here the frame rate can be extremely high.
// To avoid exessive processing, hold a target frame rate
// using a different sync interval for the Present method
// to synchronize with vertical blank, typically 60 fps.
// g_pSwapChain->Present( 0, 0 );
g_pSwapChain->Present(1, 0);
}
// Message handler for about box.
// SPOUT : adapted for this example.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
char tmp[MAX_PATH];
char about[1024];
LPDRAWITEMSTRUCT lpdis;
HWND hwnd = NULL;
HCURSOR cursorHand = NULL;
switch (message)
{
case WM_INITDIALOG:
sprintf_s(about, 256, " Tutorial07");
strcat_s(about, 1024, "\n\n\n");
strcat_s(about, 1024, "Spout DirectX texture receiver example\n");
strcat_s(about, 1024, "using DirectX 11 and the SpoutDX class.\n");
strcat_s(about, 1024, "Adapted from DirectX SDK examples by Chuck Walbourn.");
SetDlgItemTextA(hDlg, IDC_ABOUT_TEXT, (LPCSTR)about);
// Spout website hyperlink hand cursor
cursorHand = LoadCursor(NULL, IDC_HAND);
hwnd = GetDlgItem(hDlg, IDC_SPOUT_URL);
SetClassLongPtrA(hwnd, GCLP_HCURSOR, (LONG_PTR)cursorHand);
return (INT_PTR)TRUE;
case WM_DRAWITEM:
// The blue hyperlink
lpdis = (LPDRAWITEMSTRUCT)lParam;
if (lpdis->itemID == -1) break;
SetTextColor(lpdis->hDC, RGB(6, 69, 173));
switch (lpdis->CtlID) {
case IDC_SPOUT_URL:
DrawTextA(lpdis->hDC, "http://spout.zeal.co", -1, &lpdis->rcItem, DT_LEFT);
break;
default:
break;
}
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_SPOUT_URL) {
// Open the website url
sprintf_s(tmp, MAX_PATH, "http://spout.zeal.co");
ShellExecuteA(hDlg, "open", tmp, NULL, NULL, SW_SHOWNORMAL);
EndDialog(hDlg, 0);
return (INT_PTR)TRUE;
}
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
// Message handler for selecting sender
INT_PTR CALLBACK SenderProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam); // suppress warning
switch (message) {
case WM_INITDIALOG:
// Sender combo selection
{
// Create an sender name list for the combo box
HWND hwndList = GetDlgItem(hDlg, IDC_SENDERS);
// Active sender name for initial item
char activename[256];
receiver.GetActiveSender(activename);
int activeindex = 0;
// Sender count
int count = receiver.GetSenderCount();
// Populate the combo box
char name[128];
for (int i = 0; i < count; i++) {
receiver.GetSender(i, name, 128);
// Active sender index for the initial combo box item
if (strcmp(name, activename) == 0)
activeindex = i;
SendMessageA(hwndList, (UINT)CB_ADDSTRING, (WPARAM)0, (LPARAM)name);
}
// Show the active sender as the initial item
SendMessageA(hwndList, CB_SETCURSEL, (WPARAM)activeindex, (LPARAM)0);
}
return TRUE;
case WM_COMMAND:
// Combo box selection
if (HIWORD(wParam) == CBN_SELCHANGE) {
// Get the selected sender name
int index = (int)SendMessageA((HWND)lParam, (UINT)CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
SendMessageA((HWND)lParam, (UINT)CB_GETLBTEXT, (WPARAM)index, (LPARAM)sendername);
}
// Drop through
switch (LOWORD(wParam)) {
case IDOK:
// Selected sender
if (sendername[0]) {
// Make the sender active
receiver.SetActiveSender(sendername);
// Reset the receiving name
// A new sender is detected on the first ReceiveTexture call
receiver.SetReceiverName();
}
EndDialog(hDlg, 1);
break;
case IDCANCEL:
// User pressed cancel.
EndDialog(hDlg, 0);
return (INT_PTR)TRUE;
default:
return (INT_PTR)FALSE;
}
}
return (INT_PTR)FALSE;
}
void SelectAdapter()
{
// The current adapter index
currentadapter = receiver.GetAdapter();
// The index to be selected in the dialog
selectedadapter = currentadapter;
// Create an adapter name list for the dialog
adaptercount = receiver.GetNumAdapters();
adaptername->clear();
char name[64];
for (int i = 0; i < adaptercount; i++) {
receiver.GetAdapterName(i, name, 64);
adaptername[i] = name;
}
// Show the dialog box
int retvalue = (int)DialogBox(g_hInst, MAKEINTRESOURCE(IDD_ADAPTERBOX), g_hWnd, (DLGPROC)AdapterProc);
if (retvalue != 0) {
// OK - adapter index (selectedadapter) has been selected
// Set the selected adapter if different
if (selectedadapter != currentadapter) {
SpoutLogNotice("Tutorial07:SelectAdapter() - selected = %d, current = %d", selectedadapter, currentadapter);
if (receiver.SetAdapter(selectedadapter)) {
// The adapter index was changed successfully.
currentadapter = selectedadapter;
}
else {
MessageBoxA(NULL, "Could not select graphics adapter", "Tutorial07", MB_OK | MB_TOPMOST | MB_ICONEXCLAMATION);
// SetAdapter returns to the primary adapter for failure
// so set the adapter index back to what it was
receiver.SetAdapter(currentadapter);
}
// Reset everything to create a new device with the new adapter
// A new sender using the selected adapter is detected on the first ReceiveTexture call
ResetDevice();
}
}
}
// Message handler for selecting adapter
INT_PTR CALLBACK AdapterProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam); // suppress warning
HWND hwndList = NULL;
int i = 0;
char name[128];
switch (message) {
case WM_INITDIALOG:
// Adapter combo selection
hwndList = GetDlgItem(hDlg, IDC_ADAPTERS);
if (adaptercount < 10) {
for (i = 0; i < adaptercount; i++) {
sprintf_s(name, 128, "%d : %s", i, adaptername[i].c_str());
SendMessageA(hwndList, (UINT)CB_ADDSTRING, (WPARAM)0, (LPARAM)name);
}
// Display an initial item in the selection field
SendMessageA(hwndList, CB_SETCURSEL, (WPARAM)currentadapter, (LPARAM)0);
}
return TRUE;
case WM_COMMAND:
// Combo box selection
if (HIWORD(wParam) == CBN_SELCHANGE) {
selectedadapter = (int)SendMessageA((HWND)lParam, (UINT)CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
}
// Drop through
switch (LOWORD(wParam)) {
case IDOK:
// Return the selected adapter index
EndDialog(hDlg, 1);
break;
case IDCANCEL:
// User pressed cancel.
// Reset the selected index and take down dialog box.
selectedadapter = currentadapter;
EndDialog(hDlg, 0);
return (INT_PTR)TRUE;
default:
return (INT_PTR)FALSE;
}
}
return (INT_PTR)FALSE;
}
// That's all..
| 33.029851 | 148 | 0.63362 | [
"render"
] |
6b2cef5712d0279992692e416a20bab04e12bbfd | 3,755 | cpp | C++ | tc 160+/Quilting.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/Quilting.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/Quilting.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
struct Color {
int orig, cnt;
int susjed;
char c;
Color(int o, int cn, int s, char sym): orig(o), cnt(cn), susjed(s), c(sym) {}
};
bool operator<(const Color& a, const Color&b) {
if (a.susjed != b.susjed)
return (a.susjed < b.susjed);
else if (a.cnt != b.cnt)
return (a.cnt < b.cnt);
else
return (a.orig < b.orig);
}
int dx[] = { -1, 0, 1, 0 };
int dy[] = { 0,-1, 0, 1 };
char board[400][400];
class Quilting {
public:
string lastPatch(int length, int width, vector <string> colorList) {
memset(board, 0, sizeof board);
int n = length*width;
int dir = 0;
int x, y;
vector<Color> clist;
for (int i=0; i<(int)colorList.size(); ++i)
clist.push_back(Color(i, 0, 0, i+'a'));
x = y = 200;
while (n--) {
sort(clist.begin(), clist.end());
if (n == 0)
return colorList[clist[0].orig];
const Color t = clist[0];
board[x][y] = t.c;
++clist[0].cnt;
x += dx[dir];
y += dy[dir];
if (board[x+dx[(dir+1)%4]][y+dy[(dir+1)%4]] == 0)
dir = (dir+1)%4;
for (int k=0; k<(int)clist.size(); ++k)
clist[k].susjed = 0;
for (int i=-1; i<=1; ++i)
for (int j=-1; j<=1; ++j)
if (abs(i)+abs(j)!=0 && board[x+i][y+j]!=0) {
const char tt = board[x+i][y+j];
for (int k=0; k<(int)clist.size(); ++k)
if (tt == clist[k].c) {
++clist[k].susjed;
break;
}
}
}
return "error";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 3; int Arg1 = 2; string Arr2[] = {"RED","BLUE","TAN"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arg3 = "TAN"; verify_case(0, Arg3, lastPatch(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arg0 = 4; int Arg1 = 3; string Arr2[] = {"E","D","C","B","A"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arg3 = "E"; verify_case(1, Arg3, lastPatch(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arg0 = 3; int Arg1 = 3; string Arr2[] = {"A","B","C","D"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arg3 = "C"; verify_case(2, Arg3, lastPatch(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arg0 = 1; int Arg1 = 1; string Arr2[] = {"RED","BLUE","YELLOW"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arg3 = "RED"; verify_case(3, Arg3, lastPatch(Arg0, Arg1, Arg2)); }
void test_case_4() { int Arg0 = 10; int Arg1 = 10; string Arr2[] = {"X","Y","Z"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); string Arg3 = "Z"; verify_case(4, Arg3, lastPatch(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Quilting ___test;
___test.run_test(-1);
}
// END CUT HERE
| 37.929293 | 315 | 0.552597 | [
"vector"
] |
6b358712125f6c4150684badf299cc84d8f98362 | 8,942 | cc | C++ | Algorithms/extractWithCentroiding/ImageSegmentation.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/extractWithCentroiding/ImageSegmentation.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/extractWithCentroiding/ImageSegmentation.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include "ImageSegmentation.h"
ImageSegmentation::ImageSegmentation(Logger::Log& logg) : m_maxRowDepth(0), log(logg)
{
}
ImageSegmentation::~ImageSegmentation()
{
}
void
ImageSegmentation::CloseAllOpenTargets()
{
m_closedTargets.insert(m_closedTargets.end(), m_openTargets.begin(), m_openTargets.end());
m_openTargets.clear();
}
bool
ImageSegmentation::IsClosedTargetsEmpty()
{
return m_closedTargets.empty();
}
SegmentedTargetImagePtr
ImageSegmentation::PopClosedTarget()
{
if (m_closedTargets.size() <= 0) {
LOGERROR << "ImageSegmentation::PopClosedTarget : No images to return" << std::endl;
abort();
}
SegmentedTargetImagePtr temp;
temp = m_closedTargets.back();
m_closedTargets.pop_back();
return temp;
}
void
ImageSegmentation::Dump()
{
TargetList::iterator region;
int count;
count = 0;
for (region = m_openTargets.begin(); region != m_openTargets.end(); region++) {
LOGDEBUG << "--- Open Target #" << count++ << " ---" << std::endl;
(*region)->Dump();
}
count = 0;
for (region = m_closedTargets.begin(); region != m_closedTargets.end(); region++) {
LOGDEBUG << "--- Closed Target #" << count++ << " ---" << std::endl;
(*region)->Dump();
}
LOGDEBUG << "---most recent PRI range->target mapping---" << std::endl;
std::vector<SegmentedTargetImagePtr>::iterator range;
for (range = m_currentMap.begin(); range != m_currentMap.end(); range++) {
if ((*range)) {
count = 0;
bool found = false;
for (region = m_openTargets.begin(); region != m_openTargets.end(); region++) {
count++;
if ((*range) == (*region)) {
LOGDEBUG << count << ",";
found = true;
break;
}
}
if (!found) { LOGDEBUG << "?,"; }
} else {
LOGDEBUG << "N,";
}
}
LOGDEBUG << std::endl;
}
void
ImageSegmentation::IdentifyNeighborsAndSetMergePending(RANGEBIN range)
{
// test the upper-left neighbor/pixel
if (range > 0) {
if (m_currentMap[range - 1]) {
if (!m_currentMap[range - 1]->MergePending()) {
m_currentMap[range - 1]->SetMergePending();
m_mergePendingTargets.push_back(m_currentMap[range - 1]);
}
}
}
// test the upper neighbor/pixel
if (m_currentMap[range]) {
if (!m_currentMap[range]->MergePending()) {
m_currentMap[range]->SetMergePending();
m_mergePendingTargets.push_back(m_currentMap[range]);
}
}
// test the upper-right neighbor/pixel
if ((range + 1) < (RANGEBIN)m_currentMap.size()) {
if (m_currentMap[range + 1]) {
if (!m_currentMap[range + 1]->MergePending()) {
m_currentMap[range + 1]->SetMergePending();
m_mergePendingTargets.push_back(m_currentMap[range + 1]);
}
}
}
}
void
ImageSegmentation::MergePendingTargetsAndSegment(RANGEBIN start, RANGEBIN stop)
{
SegmentedTargetImagePtr newTarget;
switch (m_mergePendingTargets.size()) {
case 0:
// the range [start,stop] is associated with no existing Targets, create a new Target
newTarget = SegmentedTargetImagePtr(new SegmentedTargetImage(log));
newTarget->SetUpdated();
newTarget->AddDataToLastRow(start, stop);
UpdateRangeToTargetMap(start, stop, m_nextMap, newTarget);
m_openTargets.push_back(newTarget);
// LOGDEBUG << "created a new target with range=[" << start << ", " << stop << "]" << std::endl;
break;
case 1:
// the range [start,stop] is associated with only a single Target, simply add the
// range to the existing Target
newTarget = m_mergePendingTargets.front();
newTarget->SetUpdated();
newTarget->ClearMergePending();
newTarget->AddDataToLastRow(start, stop);
UpdateRangeToTargetMap(start, stop, m_nextMap, newTarget);
// LOGDEBUG << "updated a target with range=[" << start << ", " << stop << "]" << std::endl;
break;
default:
// the range was associated with 2 or more Targets, merge the Targets and the range
// to create a new Target.
// remove all Targets in m_mergePendingTargets from m_openTargets. each "*ri" can only
// occur once in m_openTargets, so this is faster than using std::remove)
// LOGDEBUG << "merging Targets (";
TargetVector::iterator ri;
for (ri = m_mergePendingTargets.begin(); ri != m_mergePendingTargets.end(); ri++) {
TargetList::iterator rj;
int count = 0;
for (rj = m_openTargets.begin(); rj != m_openTargets.end(); rj++) {
count++;
if ((*ri) == (*rj)) {
// LOGDEBUG << count-1 << ",";
m_openTargets.erase(rj);
break;
}
}
}
// LOGDEBUG << ") and range [" << start << ", " << stop << "]" << std::endl;
// merge all Targets in m_mergePendingTargets with [start:stop] into newTarget
// this will also update the m_currentMap vector
newTarget = SegmentedTargetImage::Merge(m_mergePendingTargets, start, stop, m_currentMap, m_nextMap, log);
// newTarget->Dump();
newTarget->ClearMergePending();
newTarget->SetUpdated();
m_openTargets.push_back(newTarget);
// LOGDEBUG << "merge done" << std::endl;
break;
}
m_mergePendingTargets.clear();
}
void
ImageSegmentation::AppendScanLine(const BinaryScanLine& binLine, AZIMUTH az, TargetSize discardSize /*= TargetSize()*/)
{
// assumes that binLine[i] corresponds to the i-th range bin
if ((RANGEBIN)m_currentMap.size() < binLine.size()) {
// resize the map to match the number of range bins, newly created entries will
// be "NULL" smart pointers, indicating that the range is not associated with
// a target
m_currentMap.resize(binLine.size());
m_nextMap.resize(binLine.size());
}
// empty the mappings for the next pri
std::fill(m_nextMap.begin(), m_nextMap.end(), SegmentedTargetImagePtr());
bool lastBin = false;
RANGEBIN startOfTarget = 0;
for (RANGEBIN range = 0; range < (RANGEBIN)binLine.size(); range++) {
if (binLine[range] && !lastBin) {
// the start of a Target
// LOGDEBUG << "starting a Target at az=" << az << " range=" << range << std::endl;
IdentifyNeighborsAndSetMergePending(range);
startOfTarget = range;
lastBin = true;
} else if (binLine[range] && lastBin) {
// in the middle of a Target
IdentifyNeighborsAndSetMergePending(range);
} else if (!binLine[range] && lastBin) {
// end of a Target
// LOGDEBUG << "ending a Target at az=" << az << " range=" << range-1 << std::endl;
MergePendingTargetsAndSegment(startOfTarget, range - 1);
lastBin = false;
}
}
if (lastBin) {
// the row ended with an open Target
// LOGDEBUG << "ending a Target at az=" << az << " range=" << ((RANGEBIN)binLine.size())-1 << std::endl;
MergePendingTargetsAndSegment(startOfTarget, ((RANGEBIN)binLine.size()) - 1);
}
m_maxRowDepth = 0;
TargetList::iterator region;
for (region = m_openTargets.begin(); region != m_openTargets.end();) {
if ((*region)->WasUpdated()) {
(*region)->FinalizeRow(az);
(*region)->ClearUpdated();
if ((*region)->GetSize() > discardSize) {
// this Target has violated some constraint. we could remove it completely,
// but that would require updating m_currentMap, which could be costly.
// further, since the Target isn't acutally closed, it will probably just
// be recreated on the next scan line, so deleting it would just be a
// waste. instead, truncate it to one row to conserve memory and keep
// going.
TargetSize size = (*region)->GetSize();
LOGDEBUG << "truncating a Target rangebin=[" << size.minRange << ", " << size.maxRange << "] az=["
<< size.minAz << ", " << size.maxAz << "]" << std::endl;
(*region)->TruncateToOneRow();
}
// determine the most number of rows any target has
m_maxRowDepth = std::max(m_maxRowDepth, (*region)->GetRowCount());
region++;
} else {
m_closedTargets.push_back(*region);
region = m_openTargets.erase(region);
}
}
// make the next map the new map for the next PRI
m_nextMap.swap(m_currentMap);
}
| 35.343874 | 119 | 0.577499 | [
"vector"
] |
6b3692e882cb97836c1cd840f791c26c92f58059 | 1,130 | cpp | C++ | DSA_Implementation/ZRevise01/Sorting/2. SelectionSort.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | 5 | 2021-02-14T17:48:21.000Z | 2022-01-24T14:29:44.000Z | DSA_Implementation/ZRevise01/Sorting/2. SelectionSort.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | DSA_Implementation/ZRevise01/Sorting/2. SelectionSort.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
* Selection Sort
* Time: O(n^2) Best case: O(n^2)
* Space: O(1)
* In-place: Yes
* Stable: NO //example: Given [2, 2, 1], the '2' values will not
* retain their initial order. Selection Sort is not stable because
* it swaps non-adjacent elements.
*
* Selection sort can be made Stable if instead of swapping,
* the minimum element is placed in its position without swapping
* i.e. by placing the number in its position by pushing every element
* one step forward. In simple terms use a technique like insertion sort
* which means inserting element in its correct place.
*
* Class: comparison sort
*/
vector<int> selectionSort(vector<int> &nums){
for(int i=0;i<nums.size()-1;i++){
int smallestIndex = i;
for(int j=i+1;j<nums.size();j++){
if(nums[smallestIndex]>nums[j]){
smallestIndex = j;
}
}
swap(nums[i], nums[smallestIndex]);
}
return nums;
}
int main(){
vector<int> nums = {5, 4, 2, 7, 3, 1, 9, 8};
nums = selectionSort(nums);
for(int i=0;i<nums.size();i++){
cout<<nums[i]<<" ";
}
cout<<endl;
return 0;
}
| 20.925926 | 73 | 0.645133 | [
"vector"
] |
6b3a9a9ab8988f7b4b79ebb406b42ba28a4f803c | 23,980 | cpp | C++ | ccxx/cxapplication.cpp | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 39 | 2015-12-09T09:28:46.000Z | 2021-11-16T12:57:25.000Z | ccxx/cxapplication.cpp | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 1 | 2020-10-17T02:23:42.000Z | 2020-10-17T02:23:42.000Z | ccxx/cxapplication.cpp | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 8 | 2018-05-29T12:48:13.000Z | 2022-02-27T01:45:57.000Z | #include "cxapplication.h"
#include "cxprocess.h"
#include "cxinterinfo.h"
#include "cxlog.h"
#include "cxsystem.h"
using namespace std;
struct ProcessCallBack
{
ProcessCallBack(fn_void_msg_tlv_t fn1)
: fn(fn1), msg(0), tag(0), source(0), target(0), data(), hadRun(false) {}
ProcessCallBack(fn_void_msg_tlv_t fn1, int iMsg, int iTag, void * oSource, void * oTarget)
: fn(fn1), msg(iMsg), tag(iTag), source(oSource), target(oTarget), data(), hadRun(false) {}
ProcessCallBack(fn_void_msg_tlv_t fn1, int iMsg, int iTag, int iLength, const void * pData, void * oSource, void * oTarget)
: fn(fn1), msg(iMsg), tag(iTag), source(oSource), target(oTarget), data((char*)pData, (char*)pData+iLength), hadRun(false) { }
fn_void_msg_tlv_t fn;
int msg;
int tag;
void * source;
void * target;
vector<char> data;
volatile bool hadRun;
};
#define f_iProcessCallBackCount (1024 * 4 * 3)
ProcessCallBack * * fn_oProcessCallBacks()
{
static vector<ProcessCallBack*> m(f_iProcessCallBackCount, (ProcessCallBack*)NULL);
return & m.front();
}
CxMutex * fn_oProcessCallBackPushLock()
{
static CxMutex m;
return & m;
}
static ProcessCallBack * * const f_oProcessCallBacks = fn_oProcessCallBacks();
static ProcessCallBack * * const f_oProcessCallBackEnd = fn_oProcessCallBacks() + f_iProcessCallBackCount;
static CxMutex * f_oProcessCallBackPushLock = fn_oProcessCallBackPushLock();
static int f_iProcessCallBackIndexPush = 0;
static int f_iProcessCallBackIndexPop = 0;
static int f_iProcessCallBackIndexClear = 0;
static ProcessCallBack * f_oRunningProcessCallBack = NULL;
static int f_iProjectType = 0;
static int volatile f_iApplicationStatus = 0;
static bool f_bApplicationHasStop = false;
static int f_iProcessEventsSleep = -1;
static cx_pthread_t f_applicationThreadId = 0;
static pid_os_t f_applicationProcessId;
static msepoch_t f_dtApplicationInit = 0;
static msepoch_t f_dtApplicationStart = 0;
static msepoch_t f_dtApplicationExecute = 0;
//application abort raise signal
#ifdef GM_OS_WIN
long __stdcall fn_Windows_Exception_callback(EXCEPTION_POINTERS* excp)
{
string sMsg = "Windows_Exception(Unhandled) : [CxApplication will exit]";
sMsg += "\nException_Time= " + CxTime::currentSystemTimeString();
sMsg += CxString::format("\nException_Address= %x" , excp->ExceptionRecord->ExceptionAddress);
sMsg += "\nCPU_Register: " + CxTime::currentSystemTimeString();
sMsg += CxString::format("\nException_Time=eax %x ebx %x ecx %x edx %x",
excp->ContextRecord->SegGs,
excp->ContextRecord->SegFs,
excp->ContextRecord->SegEs,
excp->ContextRecord->SegDs);
cxPrompt() << sMsg;
#ifdef _MSC_VER
CxThread::createMiniDump(excp);
#endif
CxApplication::exit();
return EXCEPTION_EXECUTE_HANDLER;
}
#ifdef _MSC_VER
int fn_vc_exec(int iTag)
{
int iResult = 0;
__try
{
CxApplication::doLoopEvents(iTag);
iResult = TRUE;
}
__except (CxThread::createMiniDump(GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER)
{
iResult = -1;
}
return iResult;
}
#endif
#endif
void fn_app_SIGABRT (int param)
{
cxWarning() << "signal signal signal !!! CxApplication Received SIGABRT , param=" << param;
cout << "signal signal signal !!! CxApplication Received SIGABRT , param=" << param << endl;
CxApplication::exit();
}
void fn_app_SIGFPE (int param)
{
cxWarning() << "signal signal signal !!! CxApplication Received SIGFPE , param=" << param;
cout << "signal signal signal !!! CxApplication Received SIGFPE , param=" << param << endl;
CxApplication::exit();
}
void fn_app_SIGILL (int param)
{
cxWarning() << "signal signal signal !!! CxApplication Received SIGILL , param=" << param;
cout << "signal signal signal !!! CxApplication Received SIGILL , param=" << param << endl;
CxApplication::exit();
}
void fn_app_SIGINT (int param)
{
cxWarning() << "signal signal signal !!! CxApplication Received SIGINT , param=" << param;
cout << "signal signal signal !!! CxApplication Received SIGINT , param=" << param << endl;
CxApplication::exit();
}
void fn_app_SIGSEGV (int param)
{
cxWarning() << "signal signal signal !!! CxApplication Received SIGSEGV , param=" << param;
cout << "signal signal signal !!! CxApplication Received SIGSEGV , param=" << param << endl;
CxApplication::exit();
}
void fn_app_SIGTERM (int param)
{
cxWarning() << "signal signal signal !!! CxApplication Received SIGTERM , param=" << param;
cout << "signal signal signal !!! CxApplication Received SIGTERM , param=" << param << endl;
CxApplication::exit();
}
void CxApplication::restartSystem()
{
#ifdef GM_OS_WIN
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
LUID luid;
// Get version info to determine operation
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&osvi) == 0)
{
return;
}
// Determine the platform
if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
{
// Windows NT 3.51, Windows NT 4.0, Windows 2000,
// Windows XP, or Windows .NET Server
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
}
else
{
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &luid);
tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Luid = luid;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), NULL, 0);
}
ExitWindowsEx(EWX_REBOOT, 0);
}
#else
system("reboot");
#endif
}
bool CxApplication::isApplicationThread()
{
return cx_pthread_self() == f_applicationThreadId;
}
cx_pthread_t CxApplication::applicationThreadId()
{
return f_applicationThreadId;
}
pid_os_t CxApplication::applicationProcessId()
{
return f_applicationProcessId;
}
int CxApplication::getCallBackCount()
{
return f_iProcessCallBackIndexPush - f_iProcessCallBackIndexPop;
}
void CxApplication::pushProcessCallBack(fn_void_msg_tlv_t fn, int iMsg, int iTag, const void * pData, int iLength, void * oSource, void * oTarget, bool bOnlyOnePending)
{
if (f_iApplicationStatus)
{
CxMutexScope lock(f_oProcessCallBackPushLock);
ProcessCallBack * oProcessCallBack = NULL;
//*only one waiting run
if (bOnlyOnePending)
{
int iIndex = f_iProcessCallBackIndexClear;
while (iIndex != f_iProcessCallBackIndexPush)
{
oProcessCallBack = f_oProcessCallBacks[iIndex];
if (!oProcessCallBack->hadRun && oProcessCallBack->fn == fn)
{
//has one in waiting run
return;
}
iIndex ++;
if (iIndex >= f_iProcessCallBackCount)
iIndex = 0;
}
}
//*clear
while (f_iProcessCallBackIndexClear != f_iProcessCallBackIndexPush)
{
oProcessCallBack = f_oProcessCallBacks[f_iProcessCallBackIndexClear];
if (oProcessCallBack->hadRun)
{
delete oProcessCallBack;
f_oProcessCallBacks[f_iProcessCallBackIndexClear] = NULL;
f_iProcessCallBackIndexClear ++;
if (f_iProcessCallBackIndexClear >= f_iProcessCallBackCount)
f_iProcessCallBackIndexClear = 0;
}
else
{
break;
}
}
//*push
if (f_oProcessCallBacks[f_iProcessCallBackIndexPush] != NULL)
{
cxWarning() << "Error ! Error ! Error ! CxApplication Cache Full. f_iProcessCallBackIndexPush=" << f_iProcessCallBackIndexPush << "; f_iProcessCallBackIndexPop=" << f_iProcessCallBackIndexPop;
cout << "Error ! Error ! Error ! CxApplication Cache Full. f_iProcessCallBackIndexPush=" << f_iProcessCallBackIndexPush << "; f_iProcessCallBackIndexPop=" << f_iProcessCallBackIndexPop << endl;
if (f_oRunningProcessCallBack)
{
cxWarning() << "Current CallBack : fn=" << (f_oRunningProcessCallBack->fn!=0) << "; msg=" << f_oRunningProcessCallBack->msg << "; tag=" << f_oRunningProcessCallBack->tag << "; source=" << (f_oRunningProcessCallBack->source!=0) << "; target=" << f_oRunningProcessCallBack->target
<< "; data_size=" << f_oRunningProcessCallBack->data.size() << "; data=" << CxString::toHexstring(f_oRunningProcessCallBack->data) << ".";
}
else
{
cxWarning() << "Current CallBack is NULL.";
}
CxApplication::exit();
return;
}
else
{
// has data and < 4M
if (iLength>0)
{
if (iLength<1024*1024*4 && pData)
{
f_oProcessCallBacks[f_iProcessCallBackIndexPush] = new ProcessCallBack(fn, iMsg, iTag, iLength, pData, oSource, oTarget);
}
else
{
cxWarning() << "Error ! Error ! Error ! CxApplication::pushProcessCallBack, but iLength=" << iLength;
cout << "Error ! Error ! Error ! CxApplication::pushProcessCallBack, but iLength=" << iLength << endl;
return;
}
}
else
{
f_oProcessCallBacks[f_iProcessCallBackIndexPush] = new ProcessCallBack(fn, iMsg, iTag, oSource, oTarget);
}
f_iProcessCallBackIndexPush ++;
if (f_iProcessCallBackIndexPush >= f_iProcessCallBackCount)
f_iProcessCallBackIndexPush = 0;
}
}
}
void CxApplication::nullProcessCallBackSource(void *oSource)
{
CxMutexScope lock(f_oProcessCallBackPushLock);
ProcessCallBack * oProcessCallBack = NULL;
int iIndex = f_iProcessCallBackIndexClear;
while (iIndex != f_iProcessCallBackIndexPush)
{
oProcessCallBack = f_oProcessCallBacks[iIndex];
if (oProcessCallBack->source == oSource)
{
oProcessCallBack->source = NULL;
}
iIndex ++;
if (iIndex >= f_iProcessCallBackCount)
iIndex = 0;
}
}
void CxApplication::nullProcessCallBackTarget(void *oTarget)
{
CxMutexScope lock(f_oProcessCallBackPushLock);
ProcessCallBack * oProcessCallBack = NULL;
int iIndex = f_iProcessCallBackIndexClear;
while (iIndex != f_iProcessCallBackIndexPush)
{
oProcessCallBack = f_oProcessCallBacks[iIndex];
if (oProcessCallBack->target == oTarget)
{
oProcessCallBack->target = NULL;
}
iIndex ++;
if (iIndex >= f_iProcessCallBackCount)
iIndex = 0;
}
}
void CxApplication::init(int argc, const char *argv[], int iProjectType)
{
CxGlobal::assertCallBack = CxApplication::assertDeal;
f_iProjectType = iProjectType;
#ifdef GM_OS_WIN
::SetUnhandledExceptionFilter(fn_Windows_Exception_callback);
#endif
if (f_iApplicationStatus>0)
{
return;
}
f_dtApplicationInit = CxTime::currentSystemTime();
f_applicationProcessId = CxProcess::getCurrentPid();
f_applicationThreadId = cx_pthread_self();
CxAppEnv::init(argc, argv);
if (iProjectType != GM_PROJECT_TYPE_LIB_DLL && iProjectType != GM_PROJECT_TYPE_LIB_STATIC)
{
CxThread::setRunInTry(true);
#ifdef _MSC_VER
CxThread::setMiniDumpFilePath(CxAppEnv::applicationFilePath() + ".MiniDump.dmp");
#endif
}
f_iProcessEventsSleep = CxAppEnv::findConfig(CS_SectionProgramConfig, CS_EntryProcessEventsSleep, f_iProcessEventsSleep);
if (f_iProjectType == GM_PROJECT_TYPE_APP_CONSOLE)
{
CxInterinfo::startInterInfo(CxApplication::pushProcessCallBack, CxApplication::signalMainThread);
}
CxLogManager::startLog();
//every init function : do
vector<fn_void_t> * oFnInits = getFnInits();
for (size_t i = 0; i < oFnInits->size(); ++i)
{
fn_void_t fn = oFnInits->at(i);
fn();
}
cxPrompt() << "ApplicationFilePath: " << CxAppEnv::applicationFilePath();
f_iApplicationStatus = 1;
}
void CxApplication::registInitFunction(fn_void_t fn)
{
vector<fn_void_t> * oFnInits = getFnInits();
if (std::find(oFnInits->begin(), oFnInits->end(), fn) == oFnInits->end())
oFnInits->push_back(fn);
}
void CxApplication::registStartFunction(fn_void_t fn, int iOrder)
{
vector<std::pair<fn_void_t, int> > * oFnStarts = getFnStarts();
bool bHas = false;
for (size_t i = 0; i < oFnStarts->size(); ++i)
{
const std::pair<fn_void_t, int> & fnInfo = oFnStarts->at(i);
if (fnInfo.first == fn)
{
bHas = true;
break;
}
}
if (! bHas)
{
bool bInsert = false;
for (vector<std::pair<fn_void_t, int> >::iterator it = oFnStarts->begin(); it != oFnStarts->end(); ++it)
{
const std::pair<fn_void_t, int> & fnInfo = * it;
if (iOrder < fnInfo.second)
{
oFnStarts->insert(it, std::pair<fn_void_t, int>(fn, iOrder));
bInsert = true;
break;
}
}
if (! bInsert)
{
oFnStarts->insert(oFnStarts->end(), std::pair<fn_void_t, int>(fn, iOrder));
}
}
}
void CxApplication::registStopFunction(fn_void_t fn)
{
vector<fn_void_t> * oFnStops = getFnStops();
if (std::find(oFnStops->begin(), oFnStops->end(), fn) == oFnStops->end())
oFnStops->push_back(fn);
}
int CxApplication::projectType()
{
return f_iProjectType;
}
int CxApplication::exec(int iTag)
{
int iResult = 0;
if (f_iApplicationStatus != 1)
return iResult;
f_dtApplicationStart = CxTime::currentSystemTime();
f_applicationThreadId = cx_pthread_self();
//every init function : do
vector<std::pair<fn_void_t, int> > * oFnStarts = getFnStarts();
for (vector<std::pair<fn_void_t, int> >::const_iterator it = oFnStarts->begin(); it != oFnStarts->end(); ++it)
{
const std::pair<fn_void_t, int> & fnInfo = * it;
fn_void_t fn = fnInfo.first;
fn();
}
f_dtApplicationExecute = CxTime::currentSystemTime();
//*running
f_iApplicationStatus = 2;
cxPrompt() << applicationTargetName() << " begin :";
cxPrompt() << "init datetime=" << CxTime::toString(f_dtApplicationInit);
cxPrompt() << "start datetime=" << CxTime::toString(f_dtApplicationStart);
cxPrompt() << "execute datetime=" << CxTime::toString(f_dtApplicationExecute);
cxPrompt() << "..." << CxGlobal::lineString << CxGlobal::lineString << CxGlobal::lineString;
//to CxApplication::assertDeal
//to fn_Windows_Exception_callback
fn_void_int_t fn_sig_handler;
// fn_sig_handler = signal (SIGABRT, fn_app_SIGABRT);
// if (fn_sig_handler == SIG_ERR)
// {
// std::cout << "error : signal (SIGINT , *)" << std::endl;
// }
fn_sig_handler = signal (SIGFPE, fn_app_SIGFPE);
if (fn_sig_handler == SIG_ERR)
{
std::cout << "error : signal (SIGFPE , *)" << std::endl;
}
fn_sig_handler = signal (SIGILL, fn_app_SIGILL);
if (fn_sig_handler == SIG_ERR)
{
std::cout << "error : signal (SIGILL , *)" << std::endl;
}
fn_sig_handler = signal (SIGINT, fn_app_SIGINT);
if (fn_sig_handler == SIG_ERR)
{
std::cout << "error : signal (SIGINT , *)" << std::endl;
}
fn_sig_handler = signal (SIGSEGV, fn_app_SIGSEGV);
if (fn_sig_handler == SIG_ERR)
{
std::cout << "error : signal (SIGSEGV , *)" << std::endl;
}
fn_sig_handler = signal (SIGTERM, fn_app_SIGTERM);
if (fn_sig_handler == SIG_ERR)
{
std::cout << "error : signal (SIGTERM , *)" << std::endl;
}
atexit(CxApplication::exit);
#ifdef _MSC_VER
iResult = fn_vc_exec(iTag);
#else
try
{
iResult = doLoopEvents(iTag);
}
catch (...)
{
}
#endif
if (iResult > 0)
{
cxDebug() << "CxApplication::doLoopEvents end " << CxTime::currentSystemTimeString();
}
else
{
cxPrompt() << "Unknow_Exception(by throw and catch) : [CxApplication will exit] at " << CxTime::currentSystemTimeString();
}
if (! f_bApplicationHasStop)
{
f_bApplicationHasStop = true;
raiseFnStops();
}
if (iTag & 0x00000001)
{
saveConfig();
}
return true;
}
void CxApplication::runProcessCallBacks()
{
do
{
// push 's ProcessCallBack
if (f_oProcessCallBacks[f_iProcessCallBackIndexPop] != NULL)
{
// copy
f_oRunningProcessCallBack = f_oProcessCallBacks[f_iProcessCallBackIndexPop];
f_iProcessCallBackIndexPop ++;
if (f_iProcessCallBackIndexPop >= f_iProcessCallBackCount)
f_iProcessCallBackIndexPop = 0;
if (f_oRunningProcessCallBack->fn)
{
if (f_oRunningProcessCallBack->data.size() > 0)
f_oRunningProcessCallBack->fn(f_oRunningProcessCallBack->msg, f_oRunningProcessCallBack->tag, & f_oRunningProcessCallBack->data.front(), f_oRunningProcessCallBack->data.size(), f_oRunningProcessCallBack->source, f_oRunningProcessCallBack->target);
else
f_oRunningProcessCallBack->fn(f_oRunningProcessCallBack->msg, f_oRunningProcessCallBack->tag, 0, 0, f_oRunningProcessCallBack->source, f_oRunningProcessCallBack->target);
}
f_oRunningProcessCallBack->hadRun = true;
f_oRunningProcessCallBack = NULL;
}
else
{
break;
}
} while (true);
}
void CxApplication::waiting(msepoch_t iTimeOut)
{
if (f_applicationThreadId == cx_pthread_self())
{
msepoch_t dtNow = CxTime::currentSystemTime();
if(dtNow > 0)
{
msepoch_t iG = CxTime::currentSystemTime() - dtNow;
while(iG < iTimeOut)
{
iG = CxTime::currentSystemTime() - dtNow;
CxApplication::processEvents();
CxThread::sleep(1);
}
}
}
else
{
msepoch_t dtNow = CxTime::currentSystemTime();
if(dtNow > 0)
{
msepoch_t iG = CxTime::currentSystemTime() - dtNow;
while(iG < iTimeOut)
{
iG = CxTime::currentSystemTime() - dtNow;
CxThread::sleep(1);
}
}
}
}
int CxApplication::waiting(int iWaitMilliseconds, fn_int_void_t fnCheck, int iSleep)
{
if (f_applicationThreadId == cx_pthread_self())
{
msepoch_t dtNow = CxTime::currentSystemTime();
msepoch_t iG = 0;
if(dtNow > 0)
{
iG = CxTime::currentSystemTime() - dtNow;
while(iG < iWaitMilliseconds)
{
iG = CxTime::currentSystemTime() - dtNow;
CxApplication::processEvents();
if (fnCheck && fnCheck() > 0) break;
CxThread::sleep(iSleep);
}
}
return iG;
}
else
{
msepoch_t dtNow = CxTime::currentSystemTime();
msepoch_t iG = 0;
if(dtNow > 0)
{
iG = CxTime::currentSystemTime() - dtNow;
while(iG < iWaitMilliseconds)
{
iG = CxTime::currentSystemTime() - dtNow;
if (fnCheck && fnCheck() > 0) break;
CxThread::sleep(iSleep);
}
}
return iG;
}
}
void CxApplication::exit()
{
if (f_iApplicationStatus !=0)
{
f_iApplicationStatus = 0;
CxInterinfo::stopInterInfo();
CxLogManager::stopLog();
std::cout << "CxApplication::doExit()." << std::endl;
doExit();
}
}
msepoch_t CxApplication::applicationInitTime()
{
return f_dtApplicationInit;
}
msepoch_t CxApplication::applicationStartTime()
{
return f_dtApplicationStart;
}
msepoch_t CxApplication::applicationExecuteTime()
{
return f_dtApplicationExecute;
}
int CxApplication::applicationStatus()
{
return f_iApplicationStatus;
}
std::vector<fn_void_t> * CxApplication::getFnInits()
{
static vector<fn_void_t> fnInits;
return & fnInits;
}
std::vector<std::pair<fn_void_t, int> > * CxApplication::getFnStarts()
{
static vector<std::pair<fn_void_t, int> > fnStarts;
return & fnStarts;
}
std::vector<fn_void_t> * CxApplication::getFnStops()
{
static vector<fn_void_t> fnStops;
return & fnStops;
}
void CxApplication::assertDeal(int, int, const void *_Expression, int _line, void *_file, void *)
{
string sFilePath = CxFileSystem::mergeFilePath( CxAppEnv::logPath(), "error.log" );
string dtNow = CxTime::currentSystemTimeString();
string sHead = CxString::format("assert\r\n%s\r\n%s\r\n", dtNow.c_str(), CxAppEnv::applicationFilePath().c_str());
FILE * pFile;
pFile = fopen (sFilePath.c_str(), "ab+");
if (pFile==NULL) return;
size_t iWrote = 0;
iWrote += fwrite (sHead.data() , 1, sHead.size(), pFile);
iWrote += fwrite (_Expression , 1, strlen((const char*)_Expression), pFile);
iWrote += fprintf (pFile, "\r\n%s\r\n%d\r\n\r\n",(const char*)_file,_line);
fclose (pFile);
}
void CxApplication::raiseFnStops()
{
vector<fn_void_t> * oFnStops = getFnStops();
cxDebug() << "CxApplication::stop >> " << "oFnStops.size=" << oFnStops->size();
cxDebug() << "CxApplication::stop >> " << CxTime::currentSystemTimeString();
for (size_t i = 0; i < oFnStops->size(); ++i)
{
fn_void_t fn = oFnStops->at(i);
fn();
cxDebug() << "CxApplication::stop >> " << i << " datetime=" << CxTime::currentSystemTimeString();
}
cxDebug() << "CxApplication::stop >> " << CxTime::currentSystemTimeString();
CxLogManager::stopLog();
CxInterinfo::stopInterInfo();
}
//*CxApplicationCustom
static CxSingleWait * f_oSingleWait = new CxSingleWait();
int fn_doLoopEvents_custom(int iTag)
{
while (f_iApplicationStatus)
{
CxApplication::runProcessCallBacks();
f_oSingleWait->wait();
}
return true;
}
void fn_doSignalMainThread_custom()
{
f_oSingleWait->signal();
}
void fn_doProcessEvents_custom()
{
CxApplication::runProcessCallBacks();
if (f_iProcessEventsSleep > -1)
{
CxThread::sleep(f_iProcessEventsSleep);
}
}
void fn_doExit_custom()
{
CxApplication::signalMainThread();
}
void fn_doReset_custom()
{
delete f_oSingleWait;
f_oSingleWait = new CxSingleWait();
}
static fn_int_int_t f_fnLoopEvents = fn_doLoopEvents_custom;
static fn_void_t f_fnSignalMainThread = fn_doSignalMainThread_custom;
static fn_void_t f_fnProcessEvents = fn_doProcessEvents_custom;
static fn_void_t f_fnExit = fn_doExit_custom;
static fn_void_t f_fnReset = fn_doReset_custom;
void CxApplication::setFnCore(fn_int_int_t fnDoLoopEvents, fn_void_t fnSignalMainThread, fn_void_t fnDoProcessEvents, fn_void_t fnDoExit, fn_void_t fnReset)
{
f_fnLoopEvents = fnDoLoopEvents;
f_fnSignalMainThread = fnSignalMainThread;
f_fnProcessEvents = fnDoProcessEvents;
f_fnExit = fnDoExit;
f_fnReset = fnReset;
}
int CxApplication::doLoopEvents(int iTag)
{
return f_fnLoopEvents(iTag);
}
void CxApplication::signalMainThread()
{
f_fnSignalMainThread();
}
void CxApplication::processEvents()
{
f_fnProcessEvents();
}
void CxApplication::doExit()
{
f_fnExit();
}
void CxApplication::reset()
{
f_fnReset();
}
void CxApplication::raiseExit()
{
if (f_iApplicationStatus !=0)
{
cxPrompt() << "CxApplication::raiseExit.";
cout << "CxApplication::raiseExit." << endl;
raise(SIGINT);
}
}
| 29.863014 | 294 | 0.628565 | [
"vector"
] |
6b40f659c18e61a7c4b3a5bdb8ad5c84756a42ea | 85,373 | cpp | C++ | src/saveload/afterload.cpp | trademarks/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 8 | 2016-10-21T09:01:43.000Z | 2021-05-31T06:32:14.000Z | src/saveload/afterload.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | null | null | null | src/saveload/afterload.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 4 | 2017-05-16T00:15:58.000Z | 2020-08-06T01:46:31.000Z | /* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file afterload.cpp Code updating data after game load */
#include "../stdafx.h"
#include "../void_map.h"
#include "../signs_base.h"
#include "../depot_base.h"
#include "../window_func.h"
#include "../fios.h"
#include "../gamelog_internal.h"
#include "../network/network.h"
#include "../gfxinit.h"
#include "../viewport_func.h"
#include "../industry.h"
#include "../clear_map.h"
#include "../vehicle_func.h"
#include "../string_func.h"
#include "../date_func.h"
#include "../roadveh.h"
#include "../train.h"
#include "../station_base.h"
#include "../waypoint_base.h"
#include "../roadstop_base.h"
#include "../tunnelbridge_map.h"
#include "../pathfinder/yapf/yapf_cache.h"
#include "../elrail_func.h"
#include "../signs_func.h"
#include "../aircraft.h"
#include "../object_map.h"
#include "../object_base.h"
#include "../tree_map.h"
#include "../company_func.h"
#include "../road_cmd.h"
#include "../ai/ai.hpp"
#include "../ai/ai_gui.hpp"
#include "../town.h"
#include "../economy_base.h"
#include "../animated_tile_func.h"
#include "../subsidy_base.h"
#include "../subsidy_func.h"
#include "../newgrf.h"
#include "../engine_func.h"
#include "../rail_gui.h"
#include "../core/backup_type.hpp"
#include "../smallmap_gui.h"
#include "../news_func.h"
#include "table/strings.h"
#include "saveload_internal.h"
#include <signal.h>
extern StringID _switch_mode_errorstr;
extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
/**
* Makes a tile canal or water depending on the surroundings.
*
* Must only be used for converting old savegames. Use WaterClass now.
*
* This as for example docks and shipdepots do not store
* whether the tile used to be canal or 'normal' water.
* @param t the tile to change.
* @param include_invalid_water_class Also consider WATER_CLASS_INVALID, i.e. industry tiles on land
*/
void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
{
/* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
* Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
if (include_invalid_water_class) {
SetWaterClass(t, WATER_CLASS_INVALID);
return;
} else {
SlErrorCorrupt("Invalid water class for dry tile");
}
}
/* Mark tile dirty in all cases */
MarkTileDirtyByTile(t);
if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
/* tiles at map borders are always WATER_CLASS_SEA */
SetWaterClass(t, WATER_CLASS_SEA);
return;
}
bool has_water = false;
bool has_canal = false;
bool has_river = false;
for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
TileIndex neighbour = TileAddByDiagDir(t, dir);
switch (GetTileType(neighbour)) {
case MP_WATER:
/* clear water and shipdepots have already a WaterClass associated */
if (IsCoast(neighbour)) {
has_water = true;
} else if (!IsLock(neighbour)) {
switch (GetWaterClass(neighbour)) {
case WATER_CLASS_SEA: has_water = true; break;
case WATER_CLASS_CANAL: has_canal = true; break;
case WATER_CLASS_RIVER: has_river = true; break;
default: SlErrorCorrupt("Invalid water class for tile");
}
}
break;
case MP_RAILWAY:
/* Shore or flooded halftile */
has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
break;
case MP_TREES:
/* trees on shore */
has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
break;
default: break;
}
}
if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
SetWaterClass(t, WATER_CLASS_INVALID);
return;
}
if (has_river && !has_canal) {
SetWaterClass(t, WATER_CLASS_RIVER);
} else if (has_canal || !has_water) {
SetWaterClass(t, WATER_CLASS_CANAL);
} else {
SetWaterClass(t, WATER_CLASS_SEA);
}
}
static void ConvertTownOwner()
{
for (TileIndex tile = 0; tile != MapSize(); tile++) {
switch (GetTileType(tile)) {
case MP_ROAD:
if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
_m[tile].m3 = OWNER_TOWN;
}
/* FALL THROUGH */
case MP_TUNNELBRIDGE:
if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
break;
default: break;
}
}
}
/* since savegame version 4.1, exclusive transport rights are stored at towns */
static void UpdateExclusiveRights()
{
Town *t;
FOR_ALL_TOWNS(t) {
t->exclusivity = INVALID_COMPANY;
}
/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
* could be implemented this way:
* 1.) Go through all stations
* Build an array town_blocked[ town_id ][ company_id ]
* that stores if at least one station in that town is blocked for a company
* 2.) Go through that array, if you find a town that is not blocked for
* one company, but for all others, then give him exclusivity.
*/
}
static const byte convert_currency[] = {
0, 1, 12, 8, 3,
10, 14, 19, 4, 5,
9, 11, 13, 6, 17,
16, 22, 21, 7, 15,
18, 2, 20,
};
/* since savegame version 4.2 the currencies are arranged differently */
static void UpdateCurrencies()
{
_settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
}
/* Up to revision 1413 the invisible tiles at the southern border have not been
* MP_VOID, even though they should have. This is fixed by this function
*/
static void UpdateVoidTiles()
{
uint i;
for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
}
static inline RailType UpdateRailType(RailType rt, RailType min)
{
return rt >= min ? (RailType)(rt + 1): rt;
}
/**
* Update the viewport coordinates of all signs.
*/
void UpdateAllVirtCoords()
{
UpdateAllStationVirtCoords();
UpdateAllSignVirtCoords();
UpdateAllTownVirtCoords();
}
/**
* Initialization of the windows and several kinds of caches.
* This is not done directly in AfterLoadGame because these
* functions require that all saveload conversions have been
* done. As people tend to add savegame conversion stuff after
* the intialization of the windows and caches quite some bugs
* had been made.
* Moving this out of there is both cleaner and less bug-prone.
*/
static void InitializeWindowsAndCaches()
{
/* Initialize windows */
ResetWindowSystem();
SetupColoursAndInitialWindow();
/* Update coordinates of the signs. */
UpdateAllVirtCoords();
ResetViewportAfterLoadGame();
Company *c;
FOR_ALL_COMPANIES(c) {
/* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
* accordingly if it is not the case. No need to set it on companies that are not been used already,
* thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
c->inaugurated_year = _cur_year;
}
}
RecomputePrices();
SetCachedEngineCounts();
Station::RecomputeIndustriesNearForAll();
RebuildSubsidisedSourceAndDestinationCache();
/* Towns have a noise controlled number of airports system
* So each airport's noise value must be added to the town->noise_reached value
* Reset each town's noise_reached value to '0' before. */
UpdateAirportsNoise();
CheckTrainsLengths();
ShowNewGRFError();
ShowAIDebugWindowIfAIError();
/* Rebuild the smallmap list of owners. */
BuildOwnerLegend();
}
typedef void (CDECL *SignalHandlerPointer)(int);
static SignalHandlerPointer _prev_segfault = NULL;
static SignalHandlerPointer _prev_abort = NULL;
static SignalHandlerPointer _prev_fpe = NULL;
static void CDECL HandleSavegameLoadCrash(int signum);
/**
* Replaces signal handlers of SIGSEGV and SIGABRT
* and stores pointers to original handlers in memory.
*/
static void SetSignalHandlers()
{
_prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
_prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
_prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
}
/**
* Resets signal handlers back to original handlers.
*/
static void ResetSignalHandlers()
{
signal(SIGSEGV, _prev_segfault);
signal(SIGABRT, _prev_abort);
signal(SIGFPE, _prev_fpe);
}
/**
* Try to find the overridden GRF identifier of the given GRF.
* @param c the GRF to get the 'previous' version of.
* @return the GRF identifier or \a c if none could be found.
*/
static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
{
const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
if (la->at != GLAT_LOAD) return &c->ident;
const LoggedChange *lcend = &la->change[la->changes];
for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
}
return &c->ident;
}
/** Was the saveload crash because of missing NewGRFs? */
static bool _saveload_crash_with_missing_newgrfs = false;
/**
* Did loading the savegame cause a crash? If so,
* were NewGRFs missing?
* @return when the saveload crashed due to missing NewGRFs.
*/
bool SaveloadCrashWithMissingNewGRFs()
{
return _saveload_crash_with_missing_newgrfs;
}
/**
* Signal handler used to give a user a more useful report for crashes during
* the savegame loading process; especially when there's problems with the
* NewGRFs that are required by the savegame.
* @param signum received signal
*/
static void CDECL HandleSavegameLoadCrash(int signum)
{
ResetSignalHandlers();
char buffer[8192];
char *p = buffer;
p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
_saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
}
if (_saveload_crash_with_missing_newgrfs) {
p += seprintf(p, lastof(buffer),
"This is most likely caused by a missing NewGRF or a NewGRF that\n"
"has been loaded as replacement for a missing NewGRF. OpenTTD\n"
"cannot easily determine whether a replacement NewGRF is of a newer\n"
"or older version.\n"
"It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
"This means that if the author makes incompatible NewGRFs with the\n"
"same GRF ID OpenTTD cannot magically do the right thing. In most\n"
"cases OpenTTD will load the savegame and not crash, but this is an\n"
"exception.\n"
"Please load the savegame with the appropriate NewGRFs installed.\n"
"The missing/compatible NewGRFs are:\n");
for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
if (HasBit(c->flags, GCF_COMPATIBLE)) {
const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
char buf[40];
md5sumToString(buf, lastof(buf), replaced->md5sum);
p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->ident.grfid), buf, c->filename);
}
if (c->status == GCS_NOT_FOUND) {
char buf[40];
md5sumToString(buf, lastof(buf), c->ident.md5sum);
p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
}
}
} else {
p += seprintf(p, lastof(buffer),
"This is probably caused by a corruption in the savegame.\n"
"Please file a bug report and attach this savegame.\n");
}
ShowInfo(buffer);
SignalHandlerPointer call = NULL;
switch (signum) {
case SIGSEGV: call = _prev_segfault; break;
case SIGABRT: call = _prev_abort; break;
case SIGFPE: call = _prev_fpe; break;
default: NOT_REACHED();
}
if (call != NULL) call(signum);
}
/**
* Tries to change owner of this rail tile to a valid owner. In very old versions it could happen that
* a rail track had an invalid owner. When conversion isn't possible, track is removed.
* @param t tile to update
*/
static void FixOwnerOfRailTrack(TileIndex t)
{
assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
/* remove leftover rail piece from crossing (from very old savegames) */
Train *v = NULL, *w;
FOR_ALL_TRAINS(w) {
if (w->tile == t) {
v = w;
break;
}
}
if (v != NULL) {
/* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
SetTileOwner(t, v->owner);
return;
}
/* try to find any connected rail */
for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
TileIndex tt = t + TileOffsByDiagDir(dd);
if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
Company::IsValidID(GetTileOwner(tt))) {
SetTileOwner(t, GetTileOwner(tt));
return;
}
}
if (IsLevelCrossingTile(t)) {
/* else change the crossing to normal road (road vehicles won't care) */
MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
return;
}
/* if it's not a crossing, make it clean land */
MakeClear(t, CLEAR_GRASS, 0);
}
/**
* Fixes inclination of a vehicle. Older OpenTTD versions didn't update the bits correctly.
* @param v vehicle
* @param dir vehicle's direction, or # INVALID_DIR if it can be ignored
* @return inclination bits to set
*/
static uint FixVehicleInclination(Vehicle *v, Direction dir)
{
/* Compute place where this vehicle entered the tile */
int entry_x = v->x_pos;
int entry_y = v->y_pos;
switch (dir) {
case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
case INVALID_DIR: break;
default: NOT_REACHED();
}
byte entry_z = GetSlopeZ(entry_x, entry_y);
/* Compute middle of the tile. */
int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + HALF_TILE_SIZE;
int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + HALF_TILE_SIZE;
byte middle_z = GetSlopeZ(middle_x, middle_y);
/* middle_z == entry_z, no height change. */
if (middle_z == entry_z) return 0;
/* middle_z < entry_z, we are going downwards. */
if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
/* middle_z > entry_z, we are going upwards. */
return 1U << GVF_GOINGUP_BIT;
}
/**
* Perform a (large) amount of savegame conversion *magic* in order to
* load older savegames and to fill the caches for various purposes.
* @return True iff conversion went without a problem.
*/
bool AfterLoadGame()
{
SetSignalHandlers();
TileIndex map_size = MapSize();
if (IsSavegameVersionBefore(98)) GamelogOldver();
GamelogTestRevision();
GamelogTestMode();
if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
if (IsSavegameVersionBefore(119)) {
_pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
} else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
DEBUG(net, 0, "The loading savegame was paused due to an error state.");
DEBUG(net, 0, " The savegame cannot be used for multiplayer!");
/* Restore the signals */
ResetSignalHandlers();
return false;
} else if (!_networking || _network_server) {
/* If we are in single player, i.e. not networking, and loading the
* savegame or we are loading the savegame as network server we do
* not want to be bothered by being paused because of the automatic
* reason of a network server, e.g. joining clients or too few
* active clients. Note that resetting these values for a network
* client are very bad because then the client is going to execute
* the game loop when the server is not, i.e. it desyncs. */
_pause_mode &= ~PMB_PAUSED_NETWORK;
}
/* In very old versions, size of train stations was stored differently.
* They had swapped width and height if station was built along the Y axis.
* TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
* Because the data stored by TTDPatch are unusable for rail stations > 7x7,
* recompute the width and height. Doing this unconditionally for all old
* savegames simplifies the code. */
if (IsSavegameVersionBefore(2)) {
Station *st;
FOR_ALL_STATIONS(st) {
st->train_station.w = st->train_station.h = 0;
}
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_STATION)) continue;
if (_m[t].m5 > 7) continue; // is it a rail station tile?
st = Station::Get(_m[t].m2);
assert(st->train_station.tile != 0);
int dx = TileX(t) - TileX(st->train_station.tile);
int dy = TileY(t) - TileY(st->train_station.tile);
assert(dx >= 0 && dy >= 0);
st->train_station.w = ::max<uint>(st->train_station.w, dx + 1);
st->train_station.h = ::max<uint>(st->train_station.h, dy + 1);
}
}
/* in version 2.1 of the savegame, town owner was unified. */
if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
/* from version 4.1 of the savegame, exclusive rights are stored at towns */
if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
/* from version 4.2 of the savegame, currencies are in a different order */
if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
/* In old version there seems to be a problem that water is owned by
* OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
* (4.3) version, so I just check when versions are older, and then
* walk through the whole map.. */
if (IsSavegameVersionBefore(4, 3)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
SetTileOwner(t, OWNER_WATER);
}
}
}
if (IsSavegameVersionBefore(84)) {
Company *c;
FOR_ALL_COMPANIES(c) {
c->name = CopyFromOldName(c->name_1);
if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
c->president_name = CopyFromOldName(c->president_name_1);
if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
}
Station *st;
FOR_ALL_STATIONS(st) {
st->name = CopyFromOldName(st->string_id);
/* generating new name would be too much work for little effect, use the station name fallback */
if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
}
Town *t;
FOR_ALL_TOWNS(t) {
t->name = CopyFromOldName(t->townnametype);
if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
}
}
/* From this point the old names array is cleared. */
ResetOldNames();
if (IsSavegameVersionBefore(106)) {
/* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
if (st->dock_tile == 0) st->dock_tile = INVALID_TILE;
if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
}
/* the same applies to Company::location_of_HQ */
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
c->location_of_HQ = INVALID_TILE;
}
}
}
/* convert road side to my format. */
if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
/* Check if all NewGRFs are present, we are very strict in MP mode */
GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
if (c->status == GCS_NOT_FOUND) {
GamelogGRFRemove(c->ident.grfid);
} else if (HasBit(c->flags, GCF_COMPATIBLE)) {
GamelogGRFCompatible(&c->ident);
}
}
if (_networking && gcf_res != GLC_ALL_GOOD) {
SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
/* Restore the signals */
ResetSignalHandlers();
return false;
}
switch (gcf_res) {
case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
case GLC_NOT_FOUND: _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_mode = PM_PAUSED_ERROR; break;
default: break;
}
/* The value of _date_fract got divided, so make sure that old games are converted correctly. */
if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(147) && _date_fract > DAY_TICKS)) _date_fract /= 885;
/* Update current year
* must be done before loading sprites as some newgrfs check it */
SetDate(_date, _date_fract);
/* Force dynamic engines off when loading older savegames */
if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
/* Load the sprites */
GfxLoadSprites();
LoadStringWidthTable();
/* Copy temporary data to Engine pool */
CopyTempEngineData();
/* Connect front and rear engines of multiheaded trains and converts
* subtype to the new format */
if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
/* Connect front and rear engines of multiheaded trains */
ConnectMultiheadedTrains();
/* Fix the CargoPackets *and* fix the caches of CargoLists.
* If this isn't done before Stations and especially Vehicles are
* running their AfterLoad we might get in trouble. In the case of
* vehicles we could give the wrong (cached) count of items in a
* vehicle which causes different results when getting their caches
* filled; and that could eventually lead to desyncs. */
CargoPacket::AfterLoad();
/* Oilrig was moved from id 15 to 9. We have to do this conversion
* here as AfterLoadVehicles can check it indirectly via the newgrf
* code. */
if (IsSavegameVersionBefore(139)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
st->airport.type = AT_OILRIG;
}
}
}
/* Update all vehicles */
AfterLoadVehicles(true);
/* Make sure there is an AI attached to an AI company */
{
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
}
}
/* make sure there is a town in the game */
if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
/* Restore the signals */
ResetSignalHandlers();
return false;
}
/* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
* This problem appears in savegame version 21 too, see r3455. But after loading the
* savegame and saving again, the buggy map array could be converted to new savegame
* version. It didn't show up before r12070. */
if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
/* If Load Scenario / New (Scenario) Game is used,
* a company does not exist yet. So create one here.
* 1 exeption: network-games. Those can have 0 companies
* But this exeption is not true for non dedicated network_servers! */
if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
DoStartupNewCompany(false);
}
/* Fix the cache for cargo payments. */
CargoPayment *cp;
FOR_ALL_CARGO_PAYMENTS(cp) {
cp->front->cargo_payment = cp;
cp->current_station = cp->front->last_station_visited;
}
if (IsSavegameVersionBefore(72)) {
/* Locks in very old savegames had OWNER_WATER as owner */
for (TileIndex t = 0; t < MapSize(); t++) {
switch (GetTileType(t)) {
default: break;
case MP_WATER:
if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
break;
case MP_STATION: {
if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
StationGfx gfx = GetStationGfx(t);
StationType st;
if ( IsInsideMM(gfx, 0, 8)) { // Rail station
st = STATION_RAIL;
SetStationGfx(t, gfx - 0);
} else if (IsInsideMM(gfx, 8, 67)) { // Airport
st = STATION_AIRPORT;
SetStationGfx(t, gfx - 8);
} else if (IsInsideMM(gfx, 67, 71)) { // Truck
st = STATION_TRUCK;
SetStationGfx(t, gfx - 67);
} else if (IsInsideMM(gfx, 71, 75)) { // Bus
st = STATION_BUS;
SetStationGfx(t, gfx - 71);
} else if (gfx == 75) { // Oil rig
st = STATION_OILRIG;
SetStationGfx(t, gfx - 75);
} else if (IsInsideMM(gfx, 76, 82)) { // Dock
st = STATION_DOCK;
SetStationGfx(t, gfx - 76);
} else if (gfx == 82) { // Buoy
st = STATION_BUOY;
SetStationGfx(t, gfx - 82);
} else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
st = STATION_AIRPORT;
SetStationGfx(t, gfx - 83 + 67 - 8);
} else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
st = STATION_TRUCK;
SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
} else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
st = STATION_BUS;
SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
} else {
/* Restore the signals */
ResetSignalHandlers();
return false;
}
SB(_m[t].m6, 3, 3, st);
break;
}
}
}
}
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_STATION: {
BaseStation *bst = BaseStation::GetByTile(t);
/* Set up station spread */
bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
/* Waypoints don't have road stops/oil rigs in the old format */
if (!Station::IsExpected(bst)) break;
Station *st = Station::From(bst);
switch (GetStationType(t)) {
case STATION_TRUCK:
case STATION_BUS:
if (IsSavegameVersionBefore(6)) {
/* Before version 5 you could not have more than 250 stations.
* Version 6 adds large maps, so you could only place 253*253
* road stops on a map (no freeform edges) = 64009. So, yes
* someone could in theory create such a full map to trigger
* this assertion, it's safe to assume that's only something
* theoretical and does not happen in normal games. */
assert(RoadStop::CanAllocateItem());
/* From this version on there can be multiple road stops of the
* same type per station. Convert the existing stops to the new
* internal data structure. */
RoadStop *rs = new RoadStop(t);
RoadStop **head =
IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
*head = rs;
}
break;
case STATION_OILRIG: {
/* Very old savegames sometimes have phantom oil rigs, i.e.
* an oil rig which got shut down, but not completly removed from
* the map
*/
TileIndex t1 = TILE_ADDXY(t, 0, 1);
if (IsTileType(t1, MP_INDUSTRY) &&
GetIndustryGfx(t1) == GFX_OILRIG_1) {
/* The internal encoding of oil rigs was changed twice.
* It was 3 (till 2.2) and later 5 (till 5.1).
* Setting it unconditionally does not hurt.
*/
Station::GetByTile(t)->airport.type = AT_OILRIG;
} else {
DeleteOilRig(t);
}
break;
}
default: break;
}
break;
}
default: break;
}
}
/* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
* This has to be called after the oilrig airport_type update above ^^^ ! */
if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
/* In version 6.1 we put the town index in the map-array. To do this, we need
* to use m2 (16bit big), so we need to clean m2, and that is where this is
* all about ;) */
if (IsSavegameVersionBefore(6, 1)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_HOUSE:
_m[t].m4 = _m[t].m2;
SetTownIndex(t, CalcClosestTownFromTile(t)->index);
break;
case MP_ROAD:
_m[t].m4 |= (_m[t].m2 << 4);
if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
SetTownIndex(t, CalcClosestTownFromTile(t)->index);
} else {
SetTownIndex(t, 0);
}
break;
default: break;
}
}
}
/* Force the freeform edges to false for old savegames. */
if (IsSavegameVersionBefore(111)) {
_settings_game.construction.freeform_edges = false;
}
/* From version 9.0, we update the max passengers of a town (was sometimes negative
* before that. */
if (IsSavegameVersionBefore(9)) {
Town *t;
FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
}
/* From version 16.0, we included autorenew on engines, which are now saved, but
* of course, we do need to initialize them for older savegames. */
if (IsSavegameVersionBefore(16)) {
Company *c;
FOR_ALL_COMPANIES(c) {
c->engine_renew_list = NULL;
c->settings.engine_renew = false;
c->settings.engine_renew_months = 6;
c->settings.engine_renew_money = 100000;
}
/* When loading a game, _local_company is not yet set to the correct value.
* However, in a dedicated server we are a spectator, so nothing needs to
* happen. In case we are not a dedicated server, the local company always
* becomes company 0, unless we are in the scenario editor where all the
* companies are 'invalid'.
*/
c = Company::GetIfValid(COMPANY_FIRST);
if (!_network_dedicated && c != NULL) {
c->settings = _settings_client.company;
}
}
if (IsSavegameVersionBefore(48)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (IsPlainRail(t)) {
/* Swap ground type and signal type for plain rail tiles, so the
* ground type uses the same bits as for depots and waypoints. */
uint tmp = GB(_m[t].m4, 0, 4);
SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
SB(_m[t].m2, 0, 4, tmp);
} else if (HasBit(_m[t].m5, 2)) {
/* Split waypoint and depot rail type and remove the subtype. */
ClrBit(_m[t].m5, 2);
ClrBit(_m[t].m5, 6);
}
break;
case MP_ROAD:
/* Swap m3 and m4, so the track type for rail crossings is the
* same as for normal rail. */
Swap(_m[t].m3, _m[t].m4);
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(61)) {
/* Added the RoadType */
bool old_bridge = IsSavegameVersionBefore(42);
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_ROAD:
SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
switch (GetRoadTileType(t)) {
default: SlErrorCorrupt("Invalid road tile type");
case ROAD_TILE_NORMAL:
SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
SB(_m[t].m4, 4, 4, 0);
SB(_m[t].m6, 2, 4, 0);
break;
case ROAD_TILE_CROSSING:
SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
break;
case ROAD_TILE_DEPOT: break;
}
SetRoadTypes(t, ROADTYPES_ROAD);
break;
case MP_STATION:
if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
break;
case MP_TUNNELBRIDGE:
/* Middle part of "old" bridges */
if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
SetRoadTypes(t, ROADTYPES_ROAD);
}
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(114)) {
bool fix_roadtypes = !IsSavegameVersionBefore(61);
bool old_bridge = IsSavegameVersionBefore(42);
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_ROAD:
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
switch (GetRoadTileType(t)) {
default: SlErrorCorrupt("Invalid road tile type");
case ROAD_TILE_NORMAL:
SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
break;
case ROAD_TILE_CROSSING:
SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
break;
case ROAD_TILE_DEPOT:
break;
}
if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
const Town *town = CalcClosestTownFromTile(t);
if (town != NULL) SetTownIndex(t, town->index);
}
_m[t].m4 = 0;
break;
case MP_STATION:
if (!IsRoadStop(t)) break;
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
SB(_m[t].m3, 4, 4, _m[t].m1);
_m[t].m4 = 0;
break;
case MP_TUNNELBRIDGE:
if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
Owner o = GetTileOwner(t);
SB(_me[t].m7, 0, 5, o); // road owner
SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
}
SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
_m[t].m2 = 0;
_m[t].m4 = 0;
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(42)) {
Vehicle *v;
for (TileIndex t = 0; t < map_size; t++) {
if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
if (IsBridgeTile(t)) {
if (HasBit(_m[t].m5, 6)) { // middle part
Axis axis = (Axis)GB(_m[t].m5, 0, 1);
if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
MakeRailNormal(
t,
GetTileOwner(t),
axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
GetRailType(t)
);
} else {
TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
MakeRoadNormal(
t,
axis == AXIS_X ? ROAD_Y : ROAD_X,
ROADTYPES_ROAD,
town,
GetTileOwner(t), OWNER_NONE
);
}
} else {
if (GB(_m[t].m5, 3, 2) == 0) {
MakeClear(t, CLEAR_GRASS, 3);
} else {
if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
MakeShore(t);
} else {
if (GetTileOwner(t) == OWNER_WATER) {
MakeSea(t);
} else {
MakeCanal(t, GetTileOwner(t), Random());
}
}
}
}
SetBridgeMiddle(t, axis);
} else { // ramp
Axis axis = (Axis)GB(_m[t].m5, 0, 1);
uint north_south = GB(_m[t].m5, 5, 1);
DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
_m[t].m5 = 1 << 7 | type << 2 | dir;
}
}
}
FOR_ALL_VEHICLES(v) {
if (!v->IsGroundVehicle()) continue;
if (IsBridgeTile(v->tile)) {
DiagDirection dir = GetTunnelBridgeDirection(v->tile);
if (dir != DirToDiagDir(v->direction)) continue;
switch (dir) {
default: SlErrorCorrupt("Invalid vehicle direction");
case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
}
} else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
v->tile = GetNorthernBridgeEnd(v->tile);
} else {
continue;
}
if (v->type == VEH_TRAIN) {
Train::From(v)->track = TRACK_BIT_WORMHOLE;
} else {
RoadVehicle::From(v)->state = RVSB_WORMHOLE;
}
}
}
/* Elrails got added in rev 24 */
if (IsSavegameVersionBefore(24)) {
RailType min_rail = RAILTYPE_ELECTRIC;
Train *v;
FOR_ALL_TRAINS(v) {
RailType rt = RailVehInfo(v->engine_type)->railtype;
v->railtype = rt;
if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
}
/* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
break;
case MP_ROAD:
if (IsLevelCrossing(t)) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
case MP_STATION:
if (HasStationRail(t)) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
default:
break;
}
}
FOR_ALL_TRAINS(v) {
if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(true);
}
}
/* In version 16.1 of the savegame a company can decide if trains, which get
* replaced, shall keep their old length. In all prior versions, just default
* to false */
if (IsSavegameVersionBefore(16, 1)) {
Company *c;
FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
}
if (IsSavegameVersionBefore(123)) {
/* Waypoints became subclasses of stations ... */
MoveWaypointsToBaseStations();
/* ... and buoys were moved to waypoints. */
MoveBuoysToWaypoints();
}
/* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
* room for PBS. Now in version 21 move it back :P. */
if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (HasSignals(t)) {
/* convert PBS signals to combo-signals */
if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
/* move the signal variant back */
SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
ClrBit(_m[t].m2, 3);
}
/* Clear PBS reservation on track */
if (!IsRailDepotTile(t)) {
SB(_m[t].m4, 4, 4, 0);
} else {
ClrBit(_m[t].m3, 6);
}
break;
case MP_STATION: // Clear PBS reservation on station
ClrBit(_m[t].m3, 6);
break;
default: break;
}
}
}
if (IsSavegameVersionBefore(25)) {
RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) {
rv->vehstatus &= ~0x40;
}
}
if (IsSavegameVersionBefore(26)) {
Station *st;
FOR_ALL_STATIONS(st) {
st->last_vehicle_type = VEH_INVALID;
}
}
YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
if (IsSavegameVersionBefore(34)) {
Company *c;
FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
}
Company *c;
FOR_ALL_COMPANIES(c) {
c->avail_railtypes = GetCompanyRailtypes(c->index);
c->avail_roadtypes = GetCompanyRoadtypes(c->index);
}
if (!IsSavegameVersionBefore(27)) AfterLoadStations();
/* Time starts at 0 instead of 1920.
* Account for this in older games by adding an offset */
if (IsSavegameVersionBefore(31)) {
Station *st;
Waypoint *wp;
Engine *e;
Industry *i;
Vehicle *v;
_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
_cur_year += ORIGINAL_BASE_YEAR;
FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_WAYPOINTS(wp) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
FOR_ALL_VEHICLES(v) {
v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
v->build_year += ORIGINAL_BASE_YEAR;
}
}
/* From 32 on we save the industry who made the farmland.
* To give this prettyness to old savegames, we remove all farmfields and
* plant new ones. */
if (IsSavegameVersionBefore(32)) {
Industry *i;
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
/* remove fields */
MakeClear(t, CLEAR_GRASS, 3);
} else if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
/* remove fences around fields */
SetFenceSE(t, 0);
SetFenceSW(t, 0);
}
}
FOR_ALL_INDUSTRIES(i) {
uint j;
if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
for (j = 0; j != 50; j++) PlantRandomFarmField(i);
}
}
}
/* Setting no refit flags to all orders in savegames from before refit in orders were added */
if (IsSavegameVersionBefore(36)) {
Order *order;
Vehicle *v;
FOR_ALL_ORDERS(order) {
order->SetRefit(CT_NO_REFIT);
}
FOR_ALL_VEHICLES(v) {
v->current_order.SetRefit(CT_NO_REFIT);
}
}
/* from version 38 we have optional elrails, since we cannot know the
* preference of a user, let elrails enabled; it can be disabled manually */
if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
/* do the same as when elrails were enabled/disabled manually just now */
SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
InitializeRailGUI();
/* From version 53, the map array was changed for house tiles to allow
* space for newhouses grf features. A new byte, m7, was also added. */
if (IsSavegameVersionBefore(53)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_HOUSE)) {
if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
/* Move the construction stage from m3[7..6] to m5[5..4].
* The construction counter does not have to move. */
SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
SB(_m[t].m3, 6, 2, 0);
/* The "house is completed" bit is now in m6[2]. */
SetHouseCompleted(t, false);
} else {
/* The "lift has destination" bit has been moved from
* m5[7] to m7[0]. */
SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
ClrBit(_m[t].m5, 7);
/* The "lift is moving" bit has been removed, as it does
* the same job as the "lift has destination" bit. */
ClrBit(_m[t].m1, 7);
/* The position of the lift goes from m1[7..0] to m6[7..2],
* making m1 totally free, now. The lift position does not
* have to be a full byte since the maximum value is 36. */
SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
_m[t].m1 = 0;
_m[t].m3 = 0;
SetHouseCompleted(t, true);
}
}
}
}
/* Check and update house and town values */
UpdateHousesAndTowns();
if (IsSavegameVersionBefore(43)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_INDUSTRY)) {
switch (GetIndustryGfx(t)) {
case GFX_POWERPLANT_SPARKS:
_m[t].m3 = GB(_m[t].m1, 2, 5);
break;
case GFX_OILWELL_ANIMATED_1:
case GFX_OILWELL_ANIMATED_2:
case GFX_OILWELL_ANIMATED_3:
_m[t].m3 = GB(_m[t].m1, 0, 2);
break;
case GFX_COAL_MINE_TOWER_ANIMATED:
case GFX_COPPER_MINE_TOWER_ANIMATED:
case GFX_GOLD_MINE_TOWER_ANIMATED:
_m[t].m3 = _m[t].m1;
break;
default: // No animation states to change
break;
}
}
}
}
if (IsSavegameVersionBefore(45)) {
Vehicle *v;
/* Originally just the fact that some cargo had been paid for was
* stored to stop people cheating and cashing in several times. This
* wasn't enough though as it was cleared when the vehicle started
* loading again, even if it didn't actually load anything, so now the
* amount that has been paid is stored. */
FOR_ALL_VEHICLES(v) {
ClrBit(v->vehicle_flags, 2);
}
}
/* Buoys do now store the owner of the previous water tile, which can never
* be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
if (IsSavegameVersionBefore(46)) {
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
}
}
if (IsSavegameVersionBefore(50)) {
Aircraft *v;
/* Aircraft units changed from 8 mph to 1 km-ish/h */
FOR_ALL_AIRCRAFT(v) {
if (v->subtype <= AIR_AIRCRAFT) {
const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
v->cur_speed *= 128;
v->cur_speed /= 10;
v->acceleration = avi->acceleration;
}
}
}
if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
if (IsSavegameVersionBefore(52)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsStatueTile(t)) {
_m[t].m2 = CalcClosestTownFromTile(t)->index;
}
}
}
/* A setting containing the proportion of towns that grow twice as
* fast was added in version 54. From version 56 this is now saved in the
* town as cities can be built specifically in the scenario editor. */
if (IsSavegameVersionBefore(56)) {
Town *t;
FOR_ALL_TOWNS(t) {
if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
t->larger_town = true;
}
}
}
if (IsSavegameVersionBefore(57)) {
Vehicle *v;
/* Added a FIFO queue of vehicles loading at stations */
FOR_ALL_VEHICLES(v) {
if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
!(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
v->current_order.IsType(OT_LOADING)) { // loading
Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
/* The loading finished flag is *only* set when actually completely
* finished. Because the vehicle is loading, it is not finished. */
ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
}
}
} else if (IsSavegameVersionBefore(59)) {
/* For some reason non-loading vehicles could be in the station's loading vehicle list */
Station *st;
FOR_ALL_STATIONS(st) {
std::list<Vehicle *>::iterator iter;
for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
Vehicle *v = *iter;
iter++;
if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
}
}
}
if (IsSavegameVersionBefore(58)) {
/* Setting difficulty industry_density other than zero get bumped to +1
* since a new option (very low at position 1) has been added */
if (_settings_game.difficulty.industry_density > 0) {
_settings_game.difficulty.industry_density++;
}
/* Same goes for number of towns, although no test is needed, just an increment */
_settings_game.difficulty.number_towns++;
}
if (IsSavegameVersionBefore(64)) {
/* copy the signal type/variant and move signal states bits */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
SetSignalStates(t, GB(_m[t].m2, 4, 4));
SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
ClrBit(_m[t].m2, 7);
}
}
}
if (IsSavegameVersionBefore(69)) {
/* In some old savegames a bit was cleared when it should not be cleared */
RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) {
if (rv->state == 250 || rv->state == 251) {
SetBit(rv->state, 2);
}
}
}
if (IsSavegameVersionBefore(70)) {
/* Added variables to support newindustries */
Industry *i;
FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
}
/* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
Replace the owner for those by OWNER_NONE. */
if (IsSavegameVersionBefore(82)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) &&
GetWaterTileType(t) == WATER_TILE_CLEAR &&
GetTileOwner(t) == OWNER_WATER &&
TileHeight(t) != 0) {
SetTileOwner(t, OWNER_NONE);
}
}
}
/*
* Add the 'previous' owner to the ship depots so we can reset it with
* the correct values when it gets destroyed. This prevents that
* someone can remove canals owned by somebody else and it prevents
* making floods using the removal of ship depots.
*/
if (IsSavegameVersionBefore(83)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) && IsShipDepot(t)) {
_m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
}
}
}
if (IsSavegameVersionBefore(74)) {
Station *st;
FOR_ALL_STATIONS(st) {
for (CargoID c = 0; c < NUM_CARGO; c++) {
st->goods[c].last_speed = 0;
if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::GES_PICKUP);
}
}
}
if (IsSavegameVersionBefore(78)) {
Industry *i;
uint j;
FOR_ALL_INDUSTRIES(i) {
const IndustrySpec *indsp = GetIndustrySpec(i->type);
for (j = 0; j < lengthof(i->produced_cargo); j++) {
i->produced_cargo[j] = indsp->produced_cargo[j];
}
for (j = 0; j < lengthof(i->accepts_cargo); j++) {
i->accepts_cargo[j] = indsp->accepts_cargo[j];
}
}
}
/* Before version 81, the density of grass was always stored as zero, and
* grassy trees were always drawn fully grassy. Furthermore, trees on rough
* land used to have zero density, now they have full density. Therefore,
* make all grassy/rough land trees have a density of 3. */
if (IsSavegameVersionBefore(81)) {
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileType(t) == MP_TREES) {
TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
}
}
}
if (IsSavegameVersionBefore(93)) {
/* Rework of orders. */
Order *order;
FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
v->orders.list->FreeChain();
v->orders.list = NULL;
}
v->current_order.ConvertFromOldSavegame();
if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
}
}
} else if (IsSavegameVersionBefore(94)) {
/* Unload and transfer are now mutual exclusive. */
Order *order;
FOR_ALL_ORDERS(order) {
if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
order->SetUnloadType(OUFB_TRANSFER);
order->SetLoadType(OLFB_NO_LOAD);
}
}
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
v->current_order.SetUnloadType(OUFB_TRANSFER);
v->current_order.SetLoadType(OLFB_NO_LOAD);
}
}
}
if (IsSavegameVersionBefore(84)) {
/* Set all share owners to INVALID_COMPANY for
* 1) all inactive companies
* (when inactive companies were stored in the savegame - TTD, TTDP and some
* *really* old revisions of OTTD; else it is already set in InitializeCompanies())
* 2) shares that are owned by inactive companies or self
* (caused by cheating clients in earlier revisions) */
FOR_ALL_COMPANIES(c) {
for (uint i = 0; i < 4; i++) {
CompanyID company = c->share_owners[i];
if (company == INVALID_COMPANY) continue;
if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
}
}
}
/* The water class was moved/unified. */
if (IsSavegameVersionBefore(146)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_STATION:
switch (GetStationType(t)) {
case STATION_OILRIG:
case STATION_DOCK:
case STATION_BUOY:
SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
SB(_m[t].m3, 0, 2, 0);
break;
default:
SetWaterClass(t, WATER_CLASS_INVALID);
break;
}
break;
case MP_WATER:
SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
SB(_m[t].m3, 0, 2, 0);
break;
case MP_OBJECT:
SetWaterClass(t, WATER_CLASS_INVALID);
break;
default:
/* No water class. */
break;
}
}
}
if (IsSavegameVersionBefore(86)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Move river flag and update canals to use water class */
if (IsTileType(t, MP_WATER)) {
if (GetWaterClass(t) != WATER_CLASS_RIVER) {
if (IsWater(t)) {
Owner o = GetTileOwner(t);
if (o == OWNER_WATER) {
MakeSea(t);
} else {
MakeCanal(t, o, Random());
}
} else if (IsShipDepot(t)) {
Owner o = (Owner)_m[t].m4; // Original water owner
SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
}
}
}
}
/* Update locks, depots, docks and buoys to have a water class based
* on its neighbouring tiles. Done after river and canal updates to
* ensure neighbours are correct. */
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
}
}
if (IsSavegameVersionBefore(87)) {
for (TileIndex t = 0; t < map_size; t++) {
/* skip oil rigs at borders! */
if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
(TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
/* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
* This conversion has to be done before buoys with invalid owner are removed. */
SetWaterClass(t, WATER_CLASS_SEA);
}
if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
Owner o = GetTileOwner(t);
if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
ChangeTileOwner(t, o, INVALID_OWNER);
cur_company.Restore();
}
if (IsBuoyTile(t)) {
/* reset buoy owner to OWNER_NONE in the station struct
* (even if it is owned by active company) */
Waypoint::GetByTile(t)->owner = OWNER_NONE;
}
} else if (IsTileType(t, MP_ROAD)) {
/* works for all RoadTileType */
for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
/* update even non-existing road types to update tile owner too */
Owner o = GetRoadOwner(t, rt);
if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
}
if (IsLevelCrossing(t)) {
if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
}
} else if (IsPlainRailTile(t)) {
if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
}
}
/* Convert old PF settings to new */
if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
_settings_game.pf.pathfinder_for_trains = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_trains = VPF_NPF;
}
if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
_settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
}
if (_settings_game.pf.yapf.ship_use_yapf) {
_settings_game.pf.pathfinder_for_ships = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
}
}
if (IsSavegameVersionBefore(88)) {
/* Profits are now with 8 bit fract */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
v->profit_this_year <<= 8;
v->profit_last_year <<= 8;
v->running_ticks = 0;
}
}
if (IsSavegameVersionBefore(91)) {
/* Increase HouseAnimationFrame from 5 to 7 bits */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
SB(_m[t].m6, 2, 6, GB(_m[t].m6, 3, 5));
SB(_m[t].m3, 5, 1, 0);
}
}
}
if (IsSavegameVersionBefore(62)) {
/* Remove all trams from savegames without tram support.
* There would be trams without tram track under causing crashes sooner or later. */
RoadVehicle *v;
FOR_ALL_ROADVEHICLES(v) {
if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
_switch_mode_errorstr = STR_WARNING_LOADGAME_REMOVED_TRAMS;
}
delete v;
}
}
}
if (IsSavegameVersionBefore(99)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Set newly introduced WaterClass of industry tiles */
if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
SetWaterClassDependingOnSurroundings(t, true);
}
if (IsTileType(t, MP_INDUSTRY)) {
if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
SetWaterClassDependingOnSurroundings(t, true);
} else {
SetWaterClass(t, WATER_CLASS_INVALID);
}
}
/* Replace "house construction year" with "house age" */
if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
_m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
}
}
}
/* Move the signal variant back up one bit for PBS. We don't convert the old PBS
* format here, as an old layout wouldn't work properly anyway. To be safe, we
* clear any possible PBS reservations as well. */
if (IsSavegameVersionBefore(100)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (HasSignals(t)) {
/* move the signal variant */
SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
ClrBit(_m[t].m2, 2);
ClrBit(_m[t].m2, 6);
}
/* Clear PBS reservation on track */
if (IsRailDepot(t)) {
SetDepotReservation(t, false);
} else {
SetTrackReservation(t, TRACK_BIT_NONE);
}
break;
case MP_ROAD: // Clear PBS reservation on crossing
if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
break;
case MP_STATION: // Clear PBS reservation on station
if (HasStationRail(t)) SetRailStationReservation(t, false);
break;
case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
break;
default: break;
}
}
}
/* Reserve all tracks trains are currently on. */
if (IsSavegameVersionBefore(101)) {
const Train *t;
FOR_ALL_TRAINS(t) {
if (t->First() == t) t->ReserveTrackUnderConsist();
}
}
if (IsSavegameVersionBefore(102)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Now all crossings should be in correct state */
if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
}
}
if (IsSavegameVersionBefore(103)) {
/* Non-town-owned roads now store the closest town */
UpdateNearestTownForRoadTiles(false);
/* signs with invalid owner left from older savegames */
Sign *si;
FOR_ALL_SIGNS(si) {
if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
}
/* Station can get named based on an industry type, but the current ones
* are not, so mark them as if they are not named by an industry. */
Station *st;
FOR_ALL_STATIONS(st) {
st->indtype = IT_INVALID;
}
}
if (IsSavegameVersionBefore(104)) {
Aircraft *a;
FOR_ALL_AIRCRAFT(a) {
/* Set engine_type of shadow and rotor */
if (!a->IsNormalAircraft()) {
a->engine_type = a->First()->engine_type;
}
}
/* More companies ... */
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
}
Engine *e;
FOR_ALL_ENGINES(e) {
if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
}
Town *t;
FOR_ALL_TOWNS(t) {
if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
}
}
if (IsSavegameVersionBefore(112)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Check for HQ bit being set, instead of using map accessor,
* since we've already changed it code-wise */
if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
/* Move size and part identification of HQ out of the m5 attribute,
* on new locations */
_m[t].m3 = GB(_m[t].m5, 0, 5);
_m[t].m5 = OBJECT_HQ;
}
}
}
if (IsSavegameVersionBefore(144)) {
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_OBJECT)) continue;
/* Reordering/generalisation of the object bits. */
ObjectType type = GetObjectType(t);
SB(_m[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
_m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
/* Make sure those bits are clear as well! */
_m[t].m4 = 0;
_me[t].m7 = 0;
}
}
if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
/* Make real objects for object tiles. */
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_OBJECT)) continue;
if (Town::GetNumItems() == 0) {
/* No towns, so remove all objects! */
DoClearSquare(t);
} else {
uint offset = _m[t].m3;
/* Also move the animation state. */
_m[t].m3 = GB(_m[t].m6, 2, 4);
SB(_m[t].m6, 2, 4, 0);
if (offset == 0) {
/* No offset, so make the object. */
ObjectType type = GetObjectType(t);
int size = type == OBJECT_HQ ? 2 : 1;
if (!Object::CanAllocateItem()) {
/* Nice... you managed to place 64k lighthouses and
* antennae on the map... boohoo. */
SlError(STR_ERROR_TOO_MANY_OBJECTS);
}
Object *o = new Object();
o->location.tile = t;
o->location.w = size;
o->location.h = size;
o->build_date = _date;
o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
_m[t].m2 = o->index;
Object::IncTypeCount(type);
} else {
/* We're at an offset, so get the ID from our "root". */
TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
assert(IsTileType(northern_tile, MP_OBJECT));
_m[t].m2 = _m[northern_tile].m2;
}
}
}
}
if (IsSavegameVersionBefore(113)) {
/* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
_settings_game.economy.allow_town_roads = false;
_settings_game.economy.town_layout = TL_BETTER_ROADS;
} else {
_settings_game.economy.allow_town_roads = true;
_settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
}
/* Initialize layout of all towns. Older versions were using different
* generator for random town layout, use it if needed. */
Town *t;
FOR_ALL_TOWNS(t) {
if (_settings_game.economy.town_layout != TL_RANDOM) {
t->layout = _settings_game.economy.town_layout;
continue;
}
/* Use old layout randomizer code */
byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
switch (layout) {
default: break;
case 5: layout = 1; break;
case 0: layout = 2; break;
}
t->layout = layout - 1;
}
}
if (IsSavegameVersionBefore(114)) {
/* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
* The conversion affects oil rigs and buoys too, but it doesn't matter as
* they have st->owner == OWNER_NONE already. */
Station *st;
FOR_ALL_STATIONS(st) {
if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
}
}
/* Trains could now stop in a specific location. */
if (IsSavegameVersionBefore(117)) {
Order *o;
FOR_ALL_ORDERS(o) {
if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
}
}
if (IsSavegameVersionBefore(120)) {
extern VehicleDefaultSettings _old_vds;
Company *c;
FOR_ALL_COMPANIES(c) {
c->settings.vehicle = _old_vds;
}
}
if (IsSavegameVersionBefore(121)) {
/* Delete small ufos heading for non-existing vehicles */
Vehicle *v;
FOR_ALL_DISASTERVEHICLES(v) {
if (v->subtype == 2/*ST_SMALL_UFO*/ && v->current_order.GetDestination() != 0) {
const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
delete v;
}
}
}
/* We didn't store cargo payment yet, so make them for vehicles that are
* currently at a station and loading/unloading. If they don't get any
* payment anymore they just removed in the next load/unload cycle.
* However, some 0.7 versions might have cargo payment. For those we just
* add cargopayment for the vehicles that don't have it.
*/
Station *st;
FOR_ALL_STATIONS(st) {
std::list<Vehicle *>::iterator iter;
for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
/* There are always as many CargoPayments as Vehicles. We need to make the
* assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
assert(CargoPayment::CanAllocateItem());
Vehicle *v = *iter;
if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
}
}
}
if (IsSavegameVersionBefore(122)) {
/* Animated tiles would sometimes not be actually animated or
* in case of old savegames duplicate. */
extern TileIndex *_animated_tile_list;
extern uint _animated_tile_count;
for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
/* Remove if tile is not animated */
bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
/* and remove if duplicate */
for (uint j = 0; !remove && j < i; j++) {
remove = _animated_tile_list[i] == _animated_tile_list[j];
}
if (remove) {
DeleteAnimatedTile(_animated_tile_list[i]);
} else {
i++;
}
}
}
if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
/* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->facilities & FACIL_TRAIN) {
wp->train_station.tile = wp->xy;
wp->train_station.w = 1;
wp->train_station.h = 1;
} else {
wp->train_station.tile = INVALID_TILE;
wp->train_station.w = 0;
wp->train_station.h = 0;
}
}
}
if (IsSavegameVersionBefore(125)) {
/* Convert old subsidies */
Subsidy *s;
FOR_ALL_SUBSIDIES(s) {
if (s->remaining < 12) {
/* Converting nonawarded subsidy */
s->remaining = 12 - s->remaining; // convert "age" to "remaining"
s->awarded = INVALID_COMPANY; // not awarded to anyone
const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
switch (cs->town_effect) {
case TE_PASSENGERS:
case TE_MAIL:
/* Town -> Town */
s->src_type = s->dst_type = ST_TOWN;
if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
break;
case TE_GOODS:
case TE_FOOD:
/* Industry -> Town */
s->src_type = ST_INDUSTRY;
s->dst_type = ST_TOWN;
if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
break;
default:
/* Industry -> Industry */
s->src_type = s->dst_type = ST_INDUSTRY;
if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
break;
}
} else {
/* Do our best for awarded subsidies. The original source or destination industry
* can't be determined anymore for awarded subsidies, so invalidate them.
* Town -> Town subsidies are converted using simple heuristic */
s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
switch (cs->town_effect) {
case TE_PASSENGERS:
case TE_MAIL: {
/* Town -> Town */
const Station *ss = Station::GetIfValid(s->src);
const Station *sd = Station::GetIfValid(s->dst);
if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
Company::IsValidID(ss->owner)) {
s->src_type = s->dst_type = ST_TOWN;
s->src = ss->town->index;
s->dst = sd->town->index;
s->awarded = ss->owner;
continue;
}
break;
}
default:
break;
}
}
/* Awarded non-town subsidy or invalid source/destination, invalidate */
delete s;
}
}
if (IsSavegameVersionBefore(126)) {
/* Recompute inflation based on old unround loan limit
* Note: Max loan is 500000. With an inflation of 4% across 170 years
* that results in a max loan of about 0.7 * 2^31.
* So taking the 16 bit fractional part into account there are plenty of bits left
* for unmodified savegames ...
*/
uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
/* ... well, just clamp it then. */
if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
/* Simulate the inflation, so we also get the payment inflation */
while (_economy.inflation_prices < aimed_inflation) {
AddInflation(false);
}
}
if (IsSavegameVersionBefore(127)) {
Station *st;
FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
}
if (IsSavegameVersionBefore(128)) {
const Depot *d;
FOR_ALL_DEPOTS(d) {
_m[d->xy].m2 = d->index;
if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
}
}
/* The behaviour of force_proceed has been changed. Now
* it counts signals instead of some random time out. */
if (IsSavegameVersionBefore(131)) {
Train *t;
FOR_ALL_TRAINS(t) {
if (t->force_proceed != TFP_NONE) {
t->force_proceed = TFP_STUCK;
}
}
}
/* The bits for the tree ground and tree density have
* been swapped (m2 bits 7..6 and 5..4. */
if (IsSavegameVersionBefore(135)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_CLEAR)) {
if (GetRawClearGround(t) == CLEAR_SNOW) {
SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
SetBit(_m[t].m3, 4);
} else {
ClrBit(_m[t].m3, 4);
}
}
if (IsTileType(t, MP_TREES)) {
uint density = GB(_m[t].m2, 6, 2);
uint ground = GB(_m[t].m2, 4, 2);
uint counter = GB(_m[t].m2, 0, 4);
_m[t].m2 = ground << 6 | density << 4 | counter;
}
}
}
/* Wait counter and load/unload ticks got split. */
if (IsSavegameVersionBefore(136)) {
Aircraft *a;
FOR_ALL_AIRCRAFT(a) {
a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
}
Train *t;
FOR_ALL_TRAINS(t) {
t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
}
}
/* Airport tile animation uses animation frame instead of other graphics id */
if (IsSavegameVersionBefore(137)) {
struct AirportTileConversion {
byte old_start;
byte num_frames;
};
static const AirportTileConversion atc[] = {
{31, 12}, // APT_RADAR_GRASS_FENCE_SW
{50, 4}, // APT_GRASS_FENCE_NE_FLAG
{62, 2}, // 1 unused tile
{66, 12}, // APT_RADAR_FENCE_SW
{78, 12}, // APT_RADAR_FENCE_NE
{101, 10}, // 9 unused tiles
{111, 8}, // 7 unused tiles
{119, 15}, // 14 unused tiles (radar)
{140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
};
for (TileIndex t = 0; t < map_size; t++) {
if (IsAirportTile(t)) {
StationGfx old_gfx = GetStationGfx(t);
byte offset = 0;
for (uint i = 0; i < lengthof(atc); i++) {
if (old_gfx < atc[i].old_start) {
SetStationGfx(t, old_gfx - offset);
break;
}
if (old_gfx < atc[i].old_start + atc[i].num_frames) {
SetAnimationFrame(t, old_gfx - atc[i].old_start);
SetStationGfx(t, atc[i].old_start - offset);
break;
}
offset += atc[i].num_frames - 1;
}
}
}
}
if (IsSavegameVersionBefore(140)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport.tile != INVALID_TILE) {
st->airport.w = st->airport.GetSpec()->size_x;
st->airport.h = st->airport.GetSpec()->size_y;
}
}
}
if (IsSavegameVersionBefore(141)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Reset tropic zone for VOID tiles, they shall not have any. */
if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
}
/* We need to properly number/name the depots.
* The first step is making sure none of the depots uses the
* 'default' names, after that we can assign the names. */
Depot *d;
FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
FOR_ALL_DEPOTS(d) MakeDefaultName(d);
}
if (IsSavegameVersionBefore(142)) {
Depot *d;
FOR_ALL_DEPOTS(d) d->build_date = _date;
}
/* In old versions it was possible to remove an airport while a plane was
* taking off or landing. This gives all kind of problems when building
* another airport in the same station so we don't allow that anymore.
* For old savegames with such aircraft we just throw them in the air and
* treat the aircraft like they were flying already. */
if (IsSavegameVersionBefore(146)) {
Aircraft *v;
FOR_ALL_AIRCRAFT(v) {
if (!v->IsNormalAircraft()) continue;
Station *st = GetTargetAirportIfValid(v);
if (st == NULL && v->state != FLYING) {
v->state = FLYING;
UpdateAircraftCache(v);
AircraftNextAirportPos_and_Order(v);
/* get aircraft back on running altitude */
if ((v->vehstatus & VS_CRASHED) == 0) SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlyingAltitude(v));
}
}
}
/* Move the animation frame to the same location (m7) for all objects. */
if (IsSavegameVersionBefore(147)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_HOUSE:
if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
uint per_proc = _me[t].m7;
_me[t].m7 = GB(_m[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
SB(_m[t].m3, 5, 1, 0);
SB(_m[t].m6, 2, 6, min(per_proc, 63));
}
break;
case MP_INDUSTRY: {
uint rand = _me[t].m7;
_me[t].m7 = _m[t].m3;
_m[t].m3 = rand;
break;
}
case MP_OBJECT:
_me[t].m7 = _m[t].m3;
_m[t].m3 = 0;
break;
default:
/* For stations/airports it's already at m7 */
break;
}
}
}
/* Add (random) colour to all objects. */
if (IsSavegameVersionBefore(148)) {
Object *o;
FOR_ALL_OBJECTS(o) {
Owner owner = GetTileOwner(o->location.tile);
o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
}
}
if (IsSavegameVersionBefore(149)) {
for (TileIndex t = 0; t < map_size; t++) {
if (!IsTileType(t, MP_STATION)) continue;
if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && GetTileSlope(t, NULL) == SLOPE_FLAT)) {
SetWaterClass(t, WATER_CLASS_INVALID);
}
}
/* Waypoints with custom name may have a non-unique town_cn,
* renumber those. First set all affected waypoints to the
* highest possible number to get them numbered in the
* order they have in the pool. */
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->name != NULL) wp->town_cn = UINT16_MAX;
}
FOR_ALL_WAYPOINTS(wp) {
if (wp->name != NULL) MakeDefaultName(wp);
}
}
if (IsSavegameVersionBefore(152)) {
_industry_builder.Reset(); // Initialize industry build data.
/* The moment vehicles go from hidden to visible changed. This means
* that vehicles don't always get visible anymore causing things to
* get messed up just after loading the savegame. This fixes that. */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Not all vehicle types can be inside a tunnel. Furthermore,
* testing IsTunnelTile() for invalid tiles causes a crash. */
if (!v->IsGroundVehicle()) continue;
/* Is the vehicle in a tunnel? */
if (!IsTunnelTile(v->tile)) continue;
/* Is the vehicle actually at a tunnel entrance/exit? */
TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
if (!IsTunnelTile(vtile)) continue;
/* Are we actually in this tunnel? Or maybe a lower tunnel? */
if (GetSlopeZ(v->x_pos, v->y_pos) != v->z_pos) continue;
/* What way are we going? */
const DiagDirection dir = GetTunnelBridgeDirection(vtile);
const DiagDirection vdir = DirToDiagDir(v->direction);
/* Have we passed the visibility "switch" state already? */
byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
extern const byte _tunnel_visibility_frame[DIAGDIR_END];
/* Should the vehicle be hidden or not? */
bool hidden;
if (dir == vdir) { // Entering tunnel
hidden = frame >= _tunnel_visibility_frame[dir];
v->tile = vtile;
} else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
/* v->tile changes at the moment when the vehicle leaves the tunnel. */
v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
} else {
/* We could get here in two cases:
* - for road vehicles, it is reversing at the end of the tunnel
* - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
* Whatever case it is, do not change anything and use the old values.
* Especially changing RV's state would break its reversing in the middle. */
continue;
}
if (hidden) {
v->vehstatus |= VS_HIDDEN;
switch (v->type) {
case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
default: NOT_REACHED();
}
} else {
v->vehstatus &= ~VS_HIDDEN;
switch (v->type) {
case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
default: NOT_REACHED();
}
}
}
}
if (IsSavegameVersionBefore(153)) {
RoadVehicle *rv;
FOR_ALL_ROADVEHICLES(rv) {
if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
extern const byte _road_stop_stop_frame[];
SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > _road_stop_stop_frame[rv->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)]);
} else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
}
}
}
if (IsSavegameVersionBefore(156)) {
/* The train's pathfinder lost flag got moved. */
Train *t;
FOR_ALL_TRAINS(t) {
if (!HasBit(t->flags, 5)) continue;
ClrBit(t->flags, 5);
SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
}
/* Introduced terraform/clear limits. */
Company *c;
FOR_ALL_COMPANIES(c) {
c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
}
}
if (IsSavegameVersionBefore(158)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
switch (v->type) {
case VEH_TRAIN: {
Train *t = Train::From(v);
/* Clear old GOINGUP / GOINGDOWN flags.
* It was changed in savegame version 139, but savegame
* version 158 doesn't use these bits, so it doesn't hurt
* to clear them unconditionally. */
ClrBit(t->flags, 1);
ClrBit(t->flags, 2);
/* Clear both bits first. */
ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
/* Crashed vehicles can't be going up/down. */
if (t->vehstatus & VS_CRASHED) break;
/* Only X/Y tracks can be sloped. */
if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
t->gv_flags |= FixVehicleInclination(t, t->direction);
break;
}
case VEH_ROAD: {
RoadVehicle *rv = RoadVehicle::From(v);
ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
/* Crashed vehicles can't be going up/down. */
if (rv->vehstatus & VS_CRASHED) break;
if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
TrackBits trackbits = TrackStatusToTrackBits(ts);
/* Only X/Y tracks can be sloped. */
if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
Direction dir = rv->direction;
/* Test if we are reversing. */
Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
if (AxisToDirection(a) != dir &&
AxisToDirection(a) != ReverseDir(dir)) {
/* When reversing, the road vehicle is on the edge of the tile,
* so it can be safely compared to the middle of the tile. */
dir = INVALID_DIR;
}
rv->gv_flags |= FixVehicleInclination(rv, dir);
break;
}
case VEH_SHIP:
break;
default:
continue;
}
if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
/* In old versions, z_pos was 1 unit lower on bridge heads.
* However, this invalid state could be converted to new savegames
* by loading and saving the game in a new version. */
v->z_pos = GetSlopeZ(v->x_pos, v->y_pos);
DiagDirection dir = GetTunnelBridgeDirection(v->tile);
if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
v->direction != DiagDirToDir(dir)) {
/* If the train has left the bridge, it shouldn't have
* track == TRACK_BIT_WORMHOLE - this could happen
* when the train was reversed while on the last "tick"
* on the ramp before leaving the ramp to the bridge. */
Train::From(v)->track = DiagDirToDiagTrackBits(dir);
}
}
/* If the vehicle is really above v->tile (not in a wormhole),
* it should have set v->z_pos correctly. */
assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopeZ(v->x_pos, v->y_pos));
}
/* Fill Vehicle::cur_real_order_index */
FOR_ALL_VEHICLES(v) {
if (!v->IsPrimaryVehicle()) continue;
/* Older versions are less strict with indices being in range and fix them on the fly */
if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
v->cur_real_order_index = v->cur_implicit_order_index;
v->UpdateRealOrderIndex();
}
}
if (IsSavegameVersionBefore(159)) {
/* If the savegame is old (before version 100), then the value of 255
* for these settings did not mean "disabled". As such everything
* before then did reverse.
* To simplify stuff we disable all turning around or we do not
* disable anything at all. So, if some reversing was disabled we
* will keep reversing disabled, otherwise it'll be turned on. */
_settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
Train *t;
FOR_ALL_TRAINS(t) {
_settings_game.vehicle.max_train_length = ::max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
}
}
if (IsSavegameVersionBefore(160)) {
/* Setting difficulty industry_density other than zero get bumped to +1
* since a new option (minimal at position 1) has been added */
if (_settings_game.difficulty.industry_density > 0) {
_settings_game.difficulty.industry_density++;
}
}
/* Road stops is 'only' updating some caches */
AfterLoadRoadStops();
AfterLoadLabelMaps();
GamelogPrintDebug(1);
InitializeWindowsAndCaches();
/* Restore the signals */
ResetSignalHandlers();
return true;
}
/**
* Reload all NewGRF files during a running game. This is a cut-down
* version of AfterLoadGame().
* XXX - We need to reset the vehicle position hash because with a non-empty
* hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
* to recalculate vehicle data as some NewGRF vehicle sets could have been
* removed or added and changed statistics
*/
void ReloadNewGRFData()
{
/* reload grf data */
GfxLoadSprites();
LoadStringWidthTable();
RecomputePrices();
/* reload vehicles */
ResetVehiclePosHash();
AfterLoadVehicles(false);
StartupEngines();
SetCachedEngineCounts();
/* update station graphics */
AfterLoadStations();
/* Check and update house and town values */
UpdateHousesAndTowns();
/* Delete news referring to no longer existing entities */
DeleteInvalidEngineNews();
/* Update livery selection windows */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
/* redraw the whole screen */
MarkWholeScreenDirty();
CheckTrainsLengths();
}
| 32.326013 | 212 | 0.657152 | [
"object"
] |
6b4194411bc31b4d0b44bb70847f19a01ad5820d | 16,338 | hpp | C++ | svntrunk/src/ParaFrames/fft3d/include/fft3D_MPI.hpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/bgfe/fft3dx/include/fft3D_MPI.hpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/bgfe/fft3dx/include/fft3D_MPI.hpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* 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.
*/
/*#####################################################################
# I.B.M. CONFIDENTIAL #
# (c) COPYRIGHT IBM CORP. 2001, 2003 ALL RIGHTS RESERVED. #
# #
# LICENSED MATERIALS-PROPERTY OF IBM. #
# #
#####################################################################
*/
/* $Id : fft3D.hpp
Date : 07/23/2003 11:41:51
Name : Maria Eleftheriou, IBM T.J.W R.C.
Last Modified:
By :
*/
/** * \addtogroup FFTS
* The FFT class computes the complex DFT of a 3D array. The data is
* distributed on a 3D processor mesh. It is templated on the type
* of 1D FFT. The 1D FFT performs the 1D FFTs locally on each node.
**/
// TO_DO
// need to write the _strideSrc and Trg
// test the code.
#ifndef __FFT3D_H_
#define __FFT3D_H_
#define FORWARD -1
#define REVERSE 1
#include "mpi.h"
#include <pk/platform.hpp>
#include <MPI/PrivateFFT_MPI.hpp>
#define MAX(i, j) ( (i>j)?i:j )
template<class FFT_PLAN, int FWD_REV, class T>
class FFT3D
{
public:
enum{ DIM = 4 };
typedef FFT_PLAN FFT_PLAN_IF;
PrivateFFT<T> *privateFFT;
enum { P_X = FFT_PLAN::P_X };
enum { P_Y = FFT_PLAN::P_Y };
enum { P_Z = FFT_PLAN::P_Z };
FFT3D(){}
void Init(FFT3D** ptr, const int& globalNx, const int& globalNy, const int& globalNz);
//void Init(FFT3D** ptr);
void Init( int localNx,int localNy, int localNz, int pX, int pY, int pZ);
void Initialize();
~FFT3D()
{
(*privateFFT).Finalize();
}
inline void ZeroRealSpace()
{
int localSize = (*privateFFT)._localNx[0]*(*privateFFT)._localNy[0]*(*privateFFT)._localNz[0];
for(int index = 0; index<localSize; index++)
{
(*privateFFT)._localDataIn[index].re = 0.0;
(*privateFFT)._localDataIn[index].im = 0.0;
}
}
inline complexTemplate<T>* GetRealSpaceArray()
{
if(FWD_REV == FORWARD)
{
return (*privateFFT)._localDataIn;
}
else
{
return (*privateFFT)._localDataOut;
}
}
inline T GetRealSpaceElement( int x, int y, int z )
{
if(FWD_REV == FORWARD)
{
int index = x*(*privateFFT)._strideXYZ[0]+y*(*privateFFT)._strideXYZ[1]+z*(*privateFFT)._strideXYZ[2];
return (*privateFFT)._localDataIn[index].re;
}
else
{
int index = x*(*privateFFT)._strideXYZ[0]+y*(*privateFFT)._strideXYZ[1]+z*(*privateFFT)._strideXYZ[2];
assert(index <(*privateFFT)._localNx[0]*(*privateFFT)._localNy[0]*(*privateFFT)._localNz[0]);
return (*privateFFT)._localDataOut[index].re;
}
}
inline void PutRealSpaceArray(T* inArray)
{
(*privateFFT)._localDataIn =(complexTemplate<T>) inArray;
}
inline void PutRealSpaceElement(int x, int y, int z,
T realInput)
{
int index = x*(*privateFFT)._strideXYZ[0]
+y*(*privateFFT)._strideXYZ[1]+z*(*privateFFT)._strideXYZ[2];
(*privateFFT)._localDataIn[index].re = realInput;
(*privateFFT)._localDataIn[index].im = 0.;
assert(index <(*privateFFT)._localNx[0]*(*privateFFT)._localNy[0]*(*privateFFT)._localNz[0]);
}
inline complexTemplate<T> GetRecipSpaceElement( int kx, int ky, int kz )
{
if(FWD_REV == FORWARD)
{
int index =kx*(*privateFFT)._strideR0+ky*(*privateFFT)._strideR1+kz*(*privateFFT)._strideR2;
return (*privateFFT)._localDataOut[index];
}
else
{
int index =kx*(*privateFFT)._strideR0+ky*(*privateFFT)._strideR1+kz*(*privateFFT)._strideR2;
return (*privateFFT)._localDataIn[index];
}
}
inline T* GetRecipSpaceArray()
{
if(FWD_REV == FORWARD)
{
return (*privateFFT)._localDataOut;
}
else
{
return (*privateFFT)._localDataIn;
}
}
inline void PutRecipSpaceElement( int kx, int ky, int kz,complexTemplate<T> value)
{
int index = (*privateFFT)._strideR0*kx + (*privateFFT)._strideR1*ky + (*privateFFT)._strideR2*kz;
(*privateFFT)._localDataIn[index] = value;
}
inline void PutRecipSpaceArray(complexTemplate<T>* inArray)
{
(*privateFFT)._localDataIn = inArray;
}
void GetLocalDimensions( int& aLocalX, int& aLocalSizeX,
int& aLocalY, int& aLocalSizeY,
int& aLocalZ, int& aLocalSizeZ,
int& aLocalRecipX, int& aLocalRecipSizeX,
int& aLocalRecipY, int& aLocalRecipSizeY,
int& aLocalRecipZ, int& aLocalSizeRecipZ );
void DoFFT(complexTemplate<T>* bglfftIn, complexTemplate<T>* bglfftOut) ;
void DoFFT();
void PrintVector(complexTemplate<T>* data, int size, int myGlobalID, int dir)
{
MPI_Comm comm;int dim=3;
int coords[3]; //{-1,-1, -1};
comm= (*privateFFT)._cart_comm;
comm=(*(*privateFFT)._comm)._comm[dir];
if(dir==0 || dir==3){ dim=1;} else {dim=2;}
MPI_Cart_coords(comm, myGlobalID, dim, coords);
for(int i=0; i<size; i++)
printf("Array[%d][ %d->(%d %d %d)][ %d] = %lf \n",dir,
myGlobalID, coords[0], coords[1], coords[2],i, data[i].re);
}
public:
// accepts rectangle in simulation space - vmin and vmax are the corners of it
// fills in the list of nodes where the effected mesh lives - idnum is num of entries returned
int InitProcMesh( int grdvoxleft_X, int grdvoxleft_Y, int grdvoxleft_Z);
inline void GetGridOwnerIDList( const iXYZ& vmin, const iXYZ& vmax, int idlist[], int& idnum );
private:
// this facilitates GetGridOwnerIDList(...)
int *subgridX;
int *subgridY;
int *subgridZ;
};
//in->tmp1->tmp2->out->in->tmp1->tmp2->out
template< class FFT_PLAN, int FWD_REV, class T>
inline void FFT3D<FFT_PLAN, FWD_REV, T>::GetLocalDimensions( int& aLocalX,
int& aLocalSizeX,
int& aLocalY,
int& aLocalSizeY,
int& aLocalZ,
int& aLocalSizeZ,
int& aLocalRecipX,
int& aLocalRecipSizeX,
int& aLocalRecipY,
int& aLocalRecipSizeY,
int& aLocalRecipZ,
int& aLocalRecipSizeZ )
{
aLocalX = (*privateFFT)._myPx*(*privateFFT)._localNx[0]; aLocalSizeX = (*privateFFT)._localNx[0];
aLocalY = (*privateFFT)._myPy*(*privateFFT)._localNy[0]; aLocalSizeY = (*privateFFT)._localNy[0];
aLocalZ = (*privateFFT)._myPz*(*privateFFT)._localNz[0]; aLocalSizeZ = (*privateFFT)._localNz[0];
aLocalRecipX = 0;
aLocalRecipSizeX = (*privateFFT)._localNx[0]*(*privateFFT)._pX;
int d = ((*privateFFT)._localNy[0]*(*privateFFT)._localNz[0]);
int n1 = d*(*privateFFT)._myPx/(*privateFFT)._pX;
int n2 = d*((*privateFFT)._myPx+1)/(*privateFFT)._pX-1;
int j1 = n1%(*privateFFT)._localNy[0];
int j2 = n2%(*privateFFT)._localNy[0];
int k1 = n1/(*privateFFT)._localNy[0];
int k2 = n2/(*privateFFT)._localNy[0];
aLocalRecipY = j1+(*privateFFT)._myPy*(*privateFFT)._localNy[0];
aLocalRecipSizeY = j2-j1+1;
aLocalRecipZ = k1+(*privateFFT)._myPz*(*privateFFT)._localNz[0];
aLocalRecipSizeZ = k2-k1+1;
}
template< class FFT_PLAN, int FWD_REV, class T>
void FFT3D<FFT_PLAN, FWD_REV, T>::Init(FFT3D** ptr, const int& globalNx, const int& globalNy, const int& globalNz)
{
privateFFT = new PrivateFFT<T>();
Platform::Topology::GetDimensions( & (*privateFFT)._pX, & (*privateFFT)._pY, & (*privateFFT)._pZ );
if( (*privateFFT)._pX == 0 )
{
(*privateFFT)._pX = FFT_PLAN::P_X;
(*privateFFT)._pY = FFT_PLAN::P_Y;
(*privateFFT)._pZ = FFT_PLAN::P_Z;
}
(*privateFFT)._localNx[0] = globalNx / (*privateFFT)._pX;
(*privateFFT)._localNy[0] = globalNy / (*privateFFT)._pY;
(*privateFFT)._localNz[0] = globalNz / (*privateFFT)._pZ;
assert( ((((*privateFFT)._localNx[0]*(*privateFFT)._pX)%(*privateFFT)._pX)==0) &&
((((*privateFFT)._localNy[0]*(*privateFFT)._pY)%(*privateFFT)._pY)==0) &&
((((*privateFFT)._localNz[0]*(*privateFFT)._pZ)%(*privateFFT)._pZ)==0));
Initialize();
}
template< class FFT_PLAN, int FWD_REV, class T>
void FFT3D<FFT_PLAN, FWD_REV, T>::Initialize()
{
(*privateFFT).Initialize( FWD_REV );
}
template< class FFT_PLAN, int FWD_REV, class T>
void FFT3D<FFT_PLAN, FWD_REV, T>::Init(int globalNx, int globalNy, int globalNz,
int pX, int pY, int pZ)
{
privateFFT = new PrivateFFT<T>();
(*privateFFT)._pX=pX; (*privateFFT)._pY=pY; (*privateFFT)._pZ=pZ;
(*privateFFT)._localNx[0] = globalNx;
(*privateFFT)._localNy[0] = globalNy;
(*privateFFT)._localNz[0] = globalNz;
assert( ((((*privateFFT)._localNx[0]*(*privateFFT)._pX)%(*privateFFT)._pX)==0) &&
((((*privateFFT)._localNy[0]*(*privateFFT)._pY)%(*privateFFT)._pY)==0) &&
((((*privateFFT)._localNz[0]*(*privateFFT)._pZ)%(*privateFFT)._pZ)==0));
Initialize();
}
//template<class FFT_PLAN, int FWD_REV, class T>
//void FFT3D<FFT_PLAN,FWD_REV,T>::
//DoFFT(complexTemplate<T>* bglfftIn, complexTemplate<T>* bglfftOut)
// {
// if(FWD_REV == FORWARD)
// {
// (*privateFFT).DoFwdFFT(bglfftIn, bglfftOut);
// }
// else
// {
// (*privateFFT).DoRevFFT(bglfftIn, bglfftOut);
// }
//}
//
//template<class FFT_PLAN, int FWD_REV, class T>
//void FFT3D<FFT_PLAN,FWD_REV,T>::DoFFT()
//{
// if(FWD_REV == FORWARD)
// {
// (*privateFFT).DoFwdFFT();
// }
// else
// {
// (*privateFFT).DoRevFFT();
// }
//}
template < class FFT_PLAN, int FWD_REV, typename T >
inline void FFT3D<FFT_PLAN,FWD_REV,T>::GetGridOwnerIDList( const iXYZ& vmin, const iXYZ& vmax, int idlist[], int& idnum )
{
// const int GlobalXSize = FFT_PLAN::GLOBAL_SIZE_X;
// const int GlobalYSize = FFT_PLAN::GLOBAL_SIZE_Y;
// const int GlobalZSize = FFT_PLAN::GLOBAL_SIZE_Z;
int procs_x, procs_y, procs_z;
Platform::Topology::GetDimensions( &procs_x, &procs_y, &procs_z );
const int GlobalXSize = (*privateFFT)._localNx[0] * procs_x;
const int GlobalYSize = (*privateFFT)._localNy[0] * procs_y;
const int GlobalZSize = (*privateFFT)._localNz[0] * procs_z;
iXYZ vmi = vmin;
iXYZ vma = vmax;
// map back into central cell
if( vmi.mX < 0 ) vmi.mX += GlobalXSize;
if( vmi.mY < 0 ) vmi.mY += GlobalYSize;
if( vmi.mZ < 0 ) vmi.mZ += GlobalZSize;
if( vma.mX >= GlobalXSize ) vma.mX -= GlobalXSize;
if( vma.mY >= GlobalYSize ) vma.mY -= GlobalYSize;
if( vma.mZ >= GlobalZSize ) vma.mZ -= GlobalZSize;
int kxmin = procs_x - 1;
while( subgridX[kxmin] > vmi.mX )
kxmin--;
int kxmax = procs_x - 1;
while( subgridX[kxmax] > vma.mX )
kxmax--;
int kymin = procs_y - 1;
while( subgridY[kymin] > vmi.mY )
kymin--;
int kymax = procs_y - 1;
while( subgridY[kymax] > vma.mY )
kymax--;
int kzmin = procs_z - 1;
while( subgridZ[kzmin] > vmi.mZ )
kzmin--;
int kzmax = procs_z - 1;
while( subgridZ[kzmax] > vma.mZ )
kzmax--;
idnum = 0;
int kx = kxmin, kxx;
do
{
kxx = kx % procs_x;
int ky = kymin, kyy;
do
{
kyy = ky % procs_y;
int kz = kzmin, kzz;
do
{
kzz = kz % procs_z;
idlist[idnum++] = Platform::Topology::MakeRankFromCoords( kxx, kyy, kzz );
kz++;
} while( kzz != kzmax );
ky++;
} while( kyy != kymax );
kx++;
} while( kxx != kxmax );
}
template < class FFT_PLAN, int FWD_REV, typename T >
inline int FFT3D<FFT_PLAN,FWD_REV,T>::InitProcMesh( int grdvoxleft_X, int grdvoxleft_Y, int grdvoxleft_Z )
{
int i;
int procs_x, procs_y, procs_z;
Platform::Topology::GetDimensions( &procs_x, &procs_y, &procs_z );
int *subgr;
#ifdef PK_PARALLEL
subgr = new int[procs_x*procs_y*procs_z];
assert(subgr);
#endif
int myproc_x, myproc_y, myproc_z;
Platform::Topology::GetMyCoords( &myproc_x, &myproc_y, &myproc_z );
subgridX = new int[procs_x];
subgridY = new int[procs_y];
subgridZ = new int[procs_z];
assert( subgridX && subgridY && subgridZ );
// X
#ifndef PK_PARALLEL
subgr = subgridX;
#endif
for( i=0; i<procs_x; i++ )
subgr[i] = 0;
if( myproc_y == 0 && myproc_z == 0 )
subgr[ myproc_x ] = grdvoxleft_X;
#ifdef PK_PARALLEL
Platform::Collective::INT_AllReduce_Sum( (int *) subgr, (int *) subgridX, procs_x );
#endif
// Y
#ifndef PK_PARALLEL
subgr = subgridY;
#endif
for( i=0; i<procs_y; i++ )
subgr[i] = 0;
if( myproc_x == 0 && myproc_z == 0 )
subgr[ myproc_y ] = grdvoxleft_Y;
#ifdef PK_PARALLEL
Platform::Collective::INT_AllReduce_Sum( (int *) subgr, (int *) subgridY, procs_y );
#endif
// Z
#ifndef PK_PARALLEL
subgr = subgridZ;
#endif
for( i=0; i<procs_z; i++ )
subgr[i] = 0;
if( myproc_x == 0 && myproc_y == 0 )
subgr[ myproc_z ] = grdvoxleft_Z;
#ifdef PK_PARALLEL
Platform::Collective::INT_AllReduce_Sum( (int *) subgr, (int *) subgridZ, procs_z );
#endif
#ifdef PK_PARALLEL
delete [] subgr;
#endif
return 0;
}
#if defined(FFT_COMPILE) || !defined(FFT_SEPARATE)
template<class FFT_PLAN, int FWD_REV, typename T>
void FFT3D<FFT_PLAN,FWD_REV,T>::DoFFT()
{
static int sequence = 0 ;
if(FWD_REV == FORWARD)
{
#if defined(SCALED_INTEGER_FFT_COMMS)
if ( sequence > 0 )
{
(*privateFFT).DoFwdFFTIntegerComms();
} else {
(*privateFFT).DoFwdFFT() ;
}
#else
(*privateFFT).DoFwdFFT() ;
#endif
}
else
{
#if defined(SCALED_INTEGER_FFT_COMMS)
if ( sequence > 0 )
{
(*privateFFT).DoRevFFTIntegerComms();
} else {
(*privateFFT).DoRevFFT();
}
#else
(*privateFFT).DoRevFFT();
#endif
}
sequence += 1 ;
}
template<class FFT_PLAN, int FWD_REV, typename T>
void FFT3D<FFT_PLAN,FWD_REV,T>::DoFFT(complexTemplate<T>* bglfftIn, complexTemplate<T>* bglfftOut)
{
static int sequence = 0 ;
if(FWD_REV == FORWARD)
{
#if defined(SCALED_INTEGER_FFT_COMMS)
if ( sequence > 0 )
{
(*privateFFT).DoFwdFFTIntegerComms(bglfftIn, bglfftOut);
} else {
(*privateFFT).DoFwdFFT(bglfftIn, bglfftOut) ;
}
#else
(*privateFFT).DoFwdFFT() ;
#endif
}
else
{
#if defined(SCALED_INTEGER_FFT_COMMS)
if ( sequence > 0 )
{
(*privateFFT).DoRevFFTIntegerComms(bglfftIn, bglfftOut);
} else {
(*privateFFT).DoRevFFT(bglfftIn, bglfftOut);
}
#else
(*privateFFT).DoRevFFT();
#endif
}
sequence += 1 ;
}
#if defined(FFT_COMPILE)
template void FFT3D<FFT_PLAN, PK_FORWARD,double>::DoFFT() ;
template void FFT3D<FFT_PLAN, PK_REVERSE,double>::DoFFT() ;
template void FFT3D<FFT_PLAN, PK_FORWARD,float>::DoFFT() ;
template void FFT3D<FFT_PLAN, PK_REVERSE,float>::DoFFT() ;
#endif
#endif
#endif
| 28.764085 | 121 | 0.611764 | [
"mesh",
"3d"
] |
6b41b3fbc4e4ead936556bc200a99cd224821e3d | 7,744 | cpp | C++ | foo_dotnet_component_host/net_objects/fb_file_info.cpp | TheQwertiest/foo_dotnet_component_host | f849849b591a5d85b4bc12790123dc40aaf24f93 | [
"MIT"
] | 4 | 2021-12-01T18:54:26.000Z | 2022-03-30T13:16:17.000Z | foo_dotnet_component_host/net_objects/fb_file_info.cpp | TheQwertiest/foo_dotnet_component_host | f849849b591a5d85b4bc12790123dc40aaf24f93 | [
"MIT"
] | 1 | 2021-11-29T13:25:14.000Z | 2022-01-16T22:54:57.000Z | foo_dotnet_component_host/net_objects/fb_file_info.cpp | TheQwertiest/foo_dotnet_component_host | f849849b591a5d85b4bc12790123dc40aaf24f93 | [
"MIT"
] | null | null | null | #include <stdafx.h>
#include "fb_file_info.h"
#include <convert/to_net.h>
#include <net_objects/impl/enumerable_impl.h>
namespace Qwr::DotnetHost
{
ref class InfoEnumerator;
ref class MetaEnumerator;
ref class MetaValuesEnumerator;
} // namespace Qwr::DotnetHost
namespace Qwr::DotnetHost
{
private
ref class InfoEnumerator : IEnumerator<FileInfoInfo>
{
public:
InfoEnumerator( NetFbFileInfo ^ netFileInfo );
~InfoEnumerator();
public:
virtual bool MoveNext();
virtual void Reset();
virtual property FileInfoInfo Current
{
FileInfoInfo get();
}
// clang-format off
virtual property Object ^ Current1 {
Object ^ get() = Collections::IEnumerator::Current::get;
}
private:
NetFbFileInfo ^ netFileInfo_;
// clang-format on
const file_info& fileInfo_;
const int32_t infoCount_;
int32_t curIndex_ = -1;
FileInfoInfo curValue_{};
};
private
ref class MetaEnumerator : IEnumerator<FileInfoMeta>
{
public:
MetaEnumerator( NetFbFileInfo ^ netFileInfo );
~MetaEnumerator();
public:
virtual bool MoveNext();
virtual void Reset();
virtual property FileInfoMeta Current
{
FileInfoMeta get();
}
// clang-format off
virtual property Object ^ Current1 {
Object ^ get() = Collections::IEnumerator::Current::get;
}
const file_info& FileInfo();
private:
NetFbFileInfo ^ netFileInfo_;
// clang-format on
const file_info& fileInfo_;
const int32_t metaCount_;
int32_t curIndex_ = -1;
FileInfoMeta curValue_{};
};
private
ref class MetaValuesEnumerator : IEnumerator<String ^>
{
public:
MetaValuesEnumerator( MetaEnumerator ^ parent, int32_t index );
~MetaValuesEnumerator();
public:
virtual bool MoveNext();
virtual void Reset();
virtual property String ^ Current {
String ^ get();
}
// clang-format off
virtual property Object ^ Current1 {
Object ^ get() = Collections::IEnumerator::Current::get;
}
// clang-format off
private:
MetaEnumerator ^ parent_;
// clang-format on
const file_info& fileInfo_;
const int32_t metaIndex_;
const int32_t metaValueCount_;
int32_t curIndex_ = -1;
String ^ curValue_ = nullptr;
};
private
ref class InfoEnumFactory : IEnumeratorFactory<FileInfoInfo>
{
public:
InfoEnumFactory( NetFbFileInfo ^ netFileInfo );
virtual IEnumerator<FileInfoInfo> ^ Generate();
private:
NetFbFileInfo ^ netFileInfo_;
};
private
ref class MetaEnumFactory : IEnumeratorFactory<FileInfoMeta>
{
public:
MetaEnumFactory( NetFbFileInfo ^ netFileInfo );
virtual IEnumerator<FileInfoMeta> ^ Generate();
private:
NetFbFileInfo ^ netFileInfo_;
};
private
ref class MetaValuesEnumFactory : IEnumeratorFactory<String ^>
{
public:
MetaValuesEnumFactory( MetaEnumerator ^ parent, int32_t index );
virtual IEnumerator<String ^> ^ Generate();
private:
MetaEnumerator ^ parent_;
int32_t metaIndex_;
};
} // namespace Qwr::DotnetHost
namespace Qwr::DotnetHost
{
InfoEnumerator::InfoEnumerator( NetFbFileInfo ^ netFileInfo )
: netFileInfo_( netFileInfo )
, fileInfo_( netFileInfo_->FileInfo() )
, infoCount_( fileInfo_.info_get_count() )
{
}
InfoEnumerator::~InfoEnumerator()
{
}
bool InfoEnumerator::MoveNext()
{
if ( curIndex_ + 1 >= infoCount_ )
{
return false;
}
++curIndex_;
const auto name = fileInfo_.info_enum_name( curIndex_ );
const auto value = fileInfo_.info_enum_value( curIndex_ );
assert( name );
assert( value );
curValue_ = FileInfoInfo();
curValue_.Name = Convert::ToNet::ToValue( std::string_view{ name } );
curValue_.Value = Convert::ToNet::ToValue( std::string_view{ value } );
return true;
}
void InfoEnumerator::Reset()
{
curIndex_ = -1;
}
FileInfoInfo InfoEnumerator::Current::get()
{
if ( curIndex_ < 0 || curIndex_ >= infoCount_ )
{
throw gcnew InvalidOperationException();
}
return curValue_;
}
Object ^ InfoEnumerator::Current1::get()
{
return Current;
}
MetaEnumerator::MetaEnumerator( NetFbFileInfo ^ netFileInfo )
: netFileInfo_( netFileInfo )
, fileInfo_( netFileInfo_->FileInfo() )
, metaCount_( fileInfo_.meta_get_count() )
{
}
MetaEnumerator::~MetaEnumerator()
{
}
bool MetaEnumerator::MoveNext()
{
if ( curIndex_ + 1 >= metaCount_ )
{
return false;
}
++curIndex_;
const auto name = fileInfo_.info_enum_name( curIndex_ );
const auto value = fileInfo_.info_enum_value( curIndex_ );
assert( name );
assert( value );
curValue_ = FileInfoMeta();
curValue_.Name = Convert::ToNet::ToValue( std::string_view{ name } );
curValue_.Values = MakeEnumerable( gcnew MetaValuesEnumFactory( this, curIndex_ ) );
return true;
}
void MetaEnumerator::Reset()
{
curIndex_ = -1;
}
FileInfoMeta MetaEnumerator::Current::get()
{
if ( curIndex_ < 0 || curIndex_ >= metaCount_ )
{
throw gcnew InvalidOperationException();
}
return curValue_;
}
Object ^ MetaEnumerator::Current1::get()
{
return Current;
}
const file_info& MetaEnumerator::FileInfo()
{
return fileInfo_;
}
MetaValuesEnumerator::MetaValuesEnumerator( MetaEnumerator ^ parent, int32_t index )
: parent_( parent )
, fileInfo_( parent->FileInfo() )
, metaIndex_( index )
, metaValueCount_( fileInfo_.meta_enum_value_count( metaIndex_ ) )
{
}
MetaValuesEnumerator::~MetaValuesEnumerator()
{
}
bool MetaValuesEnumerator::MoveNext()
{
if ( curIndex_ + 1 >= metaValueCount_ )
{
return false;
}
++curIndex_;
const auto value = fileInfo_.meta_enum_value( metaIndex_, curIndex_ );
assert( value );
curValue_ = Convert::ToNet::ToValue( std::string_view{ value } );
return true;
}
void MetaValuesEnumerator::Reset()
{
curIndex_ = -1;
}
String ^ MetaValuesEnumerator::Current::get()
{
if ( curIndex_ < 0 || curIndex_ >= metaValueCount_ )
{
throw gcnew InvalidOperationException();
}
return curValue_;
}
Object ^ MetaValuesEnumerator::Current1::get()
{
return Current;
}
InfoEnumFactory::InfoEnumFactory( NetFbFileInfo ^ netFileInfo )
: netFileInfo_( netFileInfo )
{
}
IEnumerator<FileInfoInfo> ^ InfoEnumFactory::Generate()
{
return gcnew InfoEnumerator( netFileInfo_ );
}
MetaEnumFactory::MetaEnumFactory( NetFbFileInfo ^ netFileInfo )
: netFileInfo_( netFileInfo )
{
}
IEnumerator<FileInfoMeta> ^ MetaEnumFactory::Generate()
{
return gcnew MetaEnumerator( netFileInfo_ );
}
MetaValuesEnumFactory::MetaValuesEnumFactory( MetaEnumerator ^ parent, int32_t index )
: parent_( parent )
, metaIndex_( index )
{
}
IEnumerator<String ^> ^ MetaValuesEnumFactory::Generate()
{
return gcnew MetaValuesEnumerator( parent_, metaIndex_ );
}
} // namespace Qwr::DotnetHost
namespace Qwr::DotnetHost
{
NetFbFileInfo::NetFbFileInfo( metadb_info_container::ptr containerInfo )
: pContainerInfo_( new metadb_info_container::ptr( containerInfo ) )
, fileInfo_( ( *pContainerInfo_ )->info() )
{
}
NetFbFileInfo::~NetFbFileInfo()
{
this->!NetFbFileInfo();
}
NetFbFileInfo::!NetFbFileInfo()
{
if ( !core_api::are_services_available() )
{
return;
}
if ( pContainerInfo_ )
{
delete pContainerInfo_;
pContainerInfo_ = nullptr;
}
}
IEnumerable<FileInfoInfo> ^ NetFbFileInfo::InfoEnum()
{
return MakeEnumerable( gcnew InfoEnumFactory( this ) );
}
IEnumerable<FileInfoMeta> ^ NetFbFileInfo::MetaEnum()
{
return MakeEnumerable( gcnew MetaEnumFactory( this ) );
}
const file_info& NetFbFileInfo::FileInfo()
{
return fileInfo_;
}
} // namespace Qwr::DotnetHost
| 19.555556 | 88 | 0.683368 | [
"object"
] |
6b48c6ae0e8a8e09b0e7fd4a4d9bef910cef0149 | 3,752 | cpp | C++ | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/tools/fixdate/fixdate.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/tools/fixdate/fixdate.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | null | null | null | src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/tools/fixdate/fixdate.cpp | zettadb/zettalib | 3d5f96dc9e3e4aa255f4e6105489758944d37cc4 | [
"Apache-2.0"
] | 2 | 2022-02-27T14:00:01.000Z | 2022-03-31T06:24:22.000Z | /* Copyright (C) 2014 InfiniDB, Inc.
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 Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
/*
* $Id: fixdate.cpp 2101 2013-01-21 14:12:52Z rdempsey $
*
*/
#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
#include <unistd.h>
#include <boost/format.hpp>
#include <boost/scoped_array.hpp>
using namespace boost;
#include "bytestream.h"
using namespace messageqcpp;
#include "dmlpackageprocessor.h"
using namespace dmlpackageprocessor;
namespace
{
const streamsize blkSz = 8192;
void usage()
{
}
u_int64_t fixDate(ByteStream& bs, ostream& out)
{
ByteStream fixed;
ByteStream::quadbyte o;
u_int64_t cnt = 0;
#if 0
DMLPackageProcessor::Date minDate;
DMLPackageProcessor::Date maxDate;
minDate.year = 1992;
minDate.month = 1;
minDate.day = 2;
maxDate.year = 1998;
maxDate.month = 12;
maxDate.day = 25;
ByteStream::quadbyte mxd;
ByteStream::quadbyte mnd;
mxd = *(reinterpret_cast<ByteStream::quadbyte*>(&maxDate));
mnd = *(reinterpret_cast<ByteStream::quadbyte*>(&minDate));
#endif
DMLPackageProcessor::Date fixDate;
fixDate.spare = 0;
ByteStream::quadbyte f;
while (bs.length() > 0)
{
bs >> o;
if (o >= 0xfffffffe)
{
fixed << o;
continue;
}
f = o & 0xffff;
fixDate.year = f;
o >>= 16;
f = o & 0xf;
fixDate.month = f;
o >>= 4;
f = o & 0x3f;
fixDate.day = f;
//o >>= 6;
o = *(reinterpret_cast<ByteStream::quadbyte*>(&fixDate));
fixed << o;
#if 0
cout << DMLPackageProcessor::dateToString(o) << endl;
idbassert(o >= mnd && o <= mxd);
cnt++;
#endif
}
out << fixed;
return cnt;
}
}
int main(int argc, char* argv[])
{
int c;
opterr = 0;
while ((c = getopt(argc, argv, "h")) != EOF)
switch (c)
{
case 'h':
usage();
return 0;
break;
default:
usage();
return 1;
break;
}
if ((argc - optind) < 1)
{
usage();
return 1;
}
ByteStream bs;
ifstream ifs(argv[optind + 0]);
ByteStream::byte inbuf[blkSz];
streampos fLen;
u_int64_t blkNo = 0;
ifs.seekg(0, ios_base::end);
fLen = ifs.tellg();
ifs.seekg(0, ios_base::beg);
idbassert((fLen % blkSz) == 0);
u_int64_t numBlks = fLen / blkSz;
cout << numBlks << " blocks to fix..." << endl;
ofstream ofs("fixdate.cdf");
cout << "pct done: " << setw(3);
for (;;)
{
ifs.read(reinterpret_cast<char*>(inbuf), blkSz);
if (ifs.eof()) break;
bs.load(inbuf, blkSz);
fixDate(bs, ofs);
cout << "\b\b\b" << setw(3) << (u_int64_t)(blkNo * 100 / numBlks);
//cout << setw(3) << (u_int64_t)(blkNo * 100 / numBlks) << endl;
blkNo++;
}
cout << "\b\b\b" << setw(3) << 100 << endl;
//cout << setw(3) << 100 << endl;
return 0;
}
| 21.318182 | 74 | 0.572228 | [
"vector"
] |
6b4a0a2a68b146152ee894dfa65aae585ef500b6 | 25,537 | cpp | C++ | include/mainMenu.cpp | BridgeFan/bridgefan-tbs-game | 062593cf3094cc6fe9858b5575dd76d020774698 | [
"MIT"
] | null | null | null | include/mainMenu.cpp | BridgeFan/bridgefan-tbs-game | 062593cf3094cc6fe9858b5575dd76d020774698 | [
"MIT"
] | 1 | 2020-08-16T18:01:37.000Z | 2020-08-16T18:01:37.000Z | include/mainMenu.cpp | BridgeFan/bridgefan-tbs-game | 062593cf3094cc6fe9858b5575dd76d020774698 | [
"MIT"
] | null | null | null | #include "mainMenu.hpp"
#include "basic/constants.hpp"
#include "LoadingScreen.hpp"
#include "basic/megaTexture.hpp"
#include "Data.hpp"
#include <filesystem>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <chrono>
namespace fs=std::filesystem;
MainMenu::MainMenu(const Data& data, const State& state, const sf::Window* window): data(data), list(window)
{
//if(init(state))
// throw std::exception();
}
void MainMenu::init(const State& mainState)
{
float uiScale = appWindow.getSize().y/1080.f;
float rat = appWindow.getSize().x/appWindow.getSize().y;
float y_size=appWindow.getSize().y;
ls.actualizeSize();
tgui::Layout2d defSize=tgui::Layout2d(0.4f*y_size,"10%");
///NEW GAME BUTTON
newGameButton=tgui::Button::create();
newGameButton->setSize(defSize);
newGameButton->setPosition("40%","5%");
newGameButton->setInheritedFont(data.getFont());
newGameButton->setTextSize(60.f*uiScale);
gui.add(newGameButton,"newGame");
///LOAD GAME BUTTON
loadGameButton=tgui::Button::create();
loadGameButton->setSize(defSize);
loadGameButton->setPosition("40%","20%");
loadGameButton->setInheritedFont(data.getFont());
loadGameButton->setTextSize(60.f*uiScale);
gui.add(loadGameButton,"loadGame");
///SETTINGS BUTTON
settingsButton=tgui::Button::create();
settingsButton->setSize(defSize);
settingsButton->setPosition("40%","35%");
settingsButton->setInheritedFont(data.getFont());
settingsButton->setTextSize(60.f*uiScale);
gui.add(settingsButton,"settings");
///PLAYER NUM BUTTONS (NEW GAME)
for(int i=0;i<8;i++)
{
playerNumButton[i]=tgui::Button::create();
playerNumButton[i]->setSize(my_to_string(10.f/rat)+"%","10%");
playerNumButton[i]->setPosition(my_to_string(10.f*(i+1)/rat)+"%","35%");
playerNumButton[i]->setInheritedFont(data.getFont());
playerNumButton[i]->setTextSize(60.f*uiScale);
playerNumButton[i]->setText(my_to_string(i+1));
gui.add(playerNumButton[i],"playerNum"+my_to_string(i+1));
}
///MAP SIZE BUTTONS (NEW GAME)
for(int i=0;i<8;i++) {
mapSizeButton[i]=tgui::Button::create();
mapSizeButton[i]->setSize(my_to_string(10.f/rat)+"%","10%");
mapSizeButton[i]->setPosition(my_to_string(10.f*(i+1)/rat)+"%","50%");
mapSizeButton[i]->setInheritedFont(data.getFont());
mapSizeButton[i]->setTextSize(60.f*uiScale);
mapSizeButton[i]->setText(my_to_string((i+1)*32));
gui.add(mapSizeButton[i],"mapSize"+my_to_string((i+1)*32));
}
///GENERATE MAP BUTTON (NEW GAME)
generateMapButton=tgui::Button::create();
generateMapButton->setSize(defSize);
generateMapButton->setPosition("40%","65%");
generateMapButton->setInheritedFont(data.getFont());
generateMapButton->setTextSize(60.f*uiScale);
gui.add(generateMapButton,"settings");
///ACTUALIZE NAMES
actualizeNames();
///ESCAPE BUTTON
escapeButton.setSize(1080.f*.4f,1080.f*.1f);
escapeButton.setPosition(appWindow.getSize().x/2.f-1080.f*.2f*uiScale,appWindow.getSize().y*.8f);
escapeButton.unactiveColor=sf::Color::Red;
escapeButton.activeColor=sf::Color(255,196,196);
escapeButton.setOutlineColor(sf::Color::Black);
escapeButton.setOutlineThickness(5.f);
escapeButton.setScale(uiScale,uiScale);
escapeButton.text.setFont(data.getFont());
escapeButton.text.setFillColor(sf::Color::Black);
escapeButton.setCharacterSize(60.f*uiScale);
escapeButton.updateTextTransform();
///UP BUTTON
//if(!upTexture.loadFromFile("data/up.png"))
// return EXIT_FAILURE;
upButton.setSize(64.f,64.f);
data.getUiMegaTexture().assignTexture(upButton,upID,upID+1);
upButton.unactiveColor=sf::Color::White;
upButton.activeColor=sf::Color(196,196,196);
upButton.setPosition(appWindow.getSize().x*.8f,appWindow.getSize().y*.45f);
upButton.setActive(false);
upButton.setOutlineThickness(0.f);
upButton.setScale(uiScale,uiScale);
///DOWN BUTTON
downButton.setSize(64.f,64.f);
data.getUiMegaTexture().assignTexture(downButton,downID,downID+1);
downButton.unactiveColor=sf::Color(196,196,196);
downButton.activeColor=sf::Color::White;
downButton.setPosition(appWindow.getSize().x*.8f,appWindow.getSize().y*.55f);
downButton.setActive(false);
downButton.setOutlineThickness(0.f);
downButton.setScale(uiScale,uiScale);
///NUM OF PLAYERS TEXT
numOfPlayers.setPosition(appWindow.getSize().x/2.f-1080.f*.2f*uiScale,appWindow.getSize().y*.05f);
numOfPlayers.setCharacterSize(80.f*uiScale);
numOfPlayers.setFillColor(sf::Color::White);
numOfPlayers.setFont(data.getFont());
///GRAPHICS SETTING BUTTON
graphicSettingsButton.setSize(1080.f*.4f,1080.f*.1f);
graphicSettingsButton.setPosition(appWindow.getSize().x/2.f-1080.f*.2f*uiScale,appWindow.getSize().y*.2f);
graphicSettingsButton.unactiveColor=sf::Color(196,196,196);
graphicSettingsButton.activeColor=sf::Color::White;
graphicSettingsButton.setTexture(bfUI::uiBackground);
graphicSettingsButton.setOutlineColor(sf::Color::Black);
graphicSettingsButton.setOutlineThickness(5.f);
graphicSettingsButton.setScale(uiScale,uiScale);
graphicSettingsButton.text.setFont(data.getFont());
graphicSettingsButton.text.setFillColor(sf::Color::Black);
graphicSettingsButton.setCharacterSize(60.f*uiScale);
graphicSettingsButton.updateTextTransform();
///LANGUAGE SETTINGS BUTTON
languageSettingsButton.setSize(1080.f*.4f,1080.f*.1f);
languageSettingsButton.setPosition(appWindow.getSize().x/2.f-1080.f*.2f*uiScale,appWindow.getSize().y*.35f);
languageSettingsButton.unactiveColor=sf::Color(196,196,196);
languageSettingsButton.activeColor=sf::Color::White;
languageSettingsButton.setTexture(bfUI::uiBackground);
languageSettingsButton.setOutlineColor(sf::Color::Black);
languageSettingsButton.setOutlineThickness(5.f);
languageSettingsButton.setScale(uiScale,uiScale);
languageSettingsButton.text.setFont(data.getFont());
languageSettingsButton.text.setFillColor(sf::Color::Black);
languageSettingsButton.setCharacterSize(60.f*uiScale);
languageSettingsButton.updateTextTransform();
///FULLSCREEN CHECK BOX
fullscreenCheckBox.setSize(64.f,64.f);
data.getUiMegaTexture().assignTexture(fullscreenCheckBox,checkBoxOff,checkBoxOn);
fullscreenCheckBox.setChecked(mainState.isFullscreen);
fullscreenCheckBox.setPosition(appWindow.getSize().x/2.f+1080.f*.3f*uiScale,appWindow.getSize().y*.5f);
fullscreenCheckBox.unactiveColor=sf::Color(196,196,196);
fullscreenCheckBox.activeColor=sf::Color::White;
///FULLSCREEN TEXT
fullscreenName.setPosition(appWindow.getSize().x/2.f-1080.f*.5f*uiScale,appWindow.getSize().y*.5f);
fullscreenName.setCharacterSize(80.f*uiScale);
fullscreenName.setFillColor(sf::Color::Black);
fullscreenName.setOutlineColor(sf::Color::White);
fullscreenName.setOutlineThickness(2.f);
fullscreenName.setFont(data.getFont());
///SAVE SETTINGS BUTTON
saveSettingsButton.setSize(1080.f*.4f,1080.f*.1f);
saveSettingsButton.setPosition(appWindow.getSize().x/2.f-1080.f*.2f*uiScale,appWindow.getSize().y*.65f);
saveSettingsButton.unactiveColor=sf::Color(196,196,196);
saveSettingsButton.activeColor=sf::Color::White;
saveSettingsButton.setTexture(bfUI::uiBackground);
saveSettingsButton.setOutlineColor(sf::Color::Black);
saveSettingsButton.setOutlineThickness(5.f);
saveSettingsButton.setScale(uiScale,uiScale);
saveSettingsButton.text.setFont(data.getFont());
saveSettingsButton.text.setFillColor(sf::Color::Black);
saveSettingsButton.setCharacterSize(60.f*uiScale);
saveSettingsButton.updateTextTransform();
///REVERT SETTINGS BUTTON
revertSettingsButton.setSize(1080.f*.4f,1080.f*.1f);
revertSettingsButton.setPosition(appWindow.getSize().x/2.f-1080.f*.2f*uiScale,appWindow.getSize().y*.8f);
revertSettingsButton.unactiveColor=sf::Color::Red;
revertSettingsButton.activeColor=sf::Color(255,196,196);
revertSettingsButton.setOutlineColor(sf::Color::Black);
revertSettingsButton.setOutlineThickness(5.f);
revertSettingsButton.setScale(uiScale,uiScale);
revertSettingsButton.text.setFont(data.getFont());
revertSettingsButton.text.setFillColor(sf::Color::Black);
revertSettingsButton.setCharacterSize(60.f*uiScale);
revertSettingsButton.updateTextTransform();
setState(0);
}
void MainMenu::setState(int8_t a) {
state=a;
auto widgets=gui.getWidgets();
for(size_t i=0;i<widgets.size();i++)
widgets[i]->setVisible(false);
switch(a) {
case 0:
newGameButton->setVisible(true);
loadGameButton->setVisible(true);
settingsButton->setVisible(true);
break;
case 1:
for(int i=0;i<8;i++) {
playerNumButton[i]->setVisible(true);
mapSizeButton[i]->setVisible(true);
}
generateMapButton->setVisible(true);
playerNumButton[1]->setEnabled(false);
mapSizeButton[3]->setEnabled(false);
break;
default:
break;
}
}
void MainMenu::init_functions(short& playersNum, const Data& data, State& state, my_vector2i& winSize, bool& wasFullscreen, std::string& oldLanguageName, my_vector2i& oldWinSize) {
newGameButton->connect("pressed", newGameFunction, std::ref(*this), std::ref(playersNum));
loadGameButton->connect("pressed", loadGameFunction, std::ref(*this), std::ref(data), std::ref(state), winSize);
settingsButton->connect("pressed", settingsFunction, std::ref(*this), std::ref(state), std::ref(wasFullscreen), std::ref(oldLanguageName), std::ref(winSize), std::ref(oldWinSize));
generateMapButton->connect("pressed",generateMapFunction, std::ref(*this), std::ref(data), std::ref(state), std::ref(playersNum), std::ref(winSize));
for(int i=0;i<8;i++) {
playerNumButton[i]->connect("pressed", playerNumFunction, std::ref(*this), i, std::ref(playersNum));
mapSizeButton[i]->connect("pressed", mapSizeFunction, std::ref(*this), i);
}
}
void MainMenu::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
if(state==0) //main menu
{
target.draw(escapeButton, states);
}
else if(state==1) //new game menu
{
target.draw(numOfPlayers, states);
target.draw(escapeButton, states);
}
else if(state==2 || state==5)
{
target.draw(escapeButton, states);
}
else if(state==3)
{
target.draw(revertSettingsButton, states);
target.draw(fullscreenCheckBox, states);
target.draw(fullscreenName, states);
target.draw(saveSettingsButton, states);
target.draw(graphicSettingsButton, states);
target.draw(languageSettingsButton, states);
}
else if(state==4)
{
target.draw(escapeButton, states);
}
}
std::string MainMenu::chooseSave(State& state, const std::string& path, const std::string& ext)
{
std::vector<std::pair<std::string, std::filesystem::file_time_type> > names;
//std::string path = "./saves/";
//std::string ext = ".sav";
for (const auto & entry : std::filesystem::directory_iterator(path))
if(entry.path().extension()==ext)
{
names.push_back({entry.path().stem().string(),std::filesystem::last_write_time(entry)});
}
if(this->state==2)
std::sort(names.begin(),names.end(),[](const auto& a, const auto& b)
{if(a.second!=b.second) return a.second>b.second; return a.first<b.first;});
else
std::sort(names.begin(),names.end(),[](const auto& a, const auto& b)
{return a.first<b.first;});
std::vector<std::string> info;
if(this->state==2)
{
std::fstream file;
for(std::size_t i=0u;i<names.size();i++)
{
std::string fileName=path+names[i].first+ext;
file.open(fileName, std::fstream::in | std::ifstream::binary);
if(file.good())
{
info.push_back(my_to_string(load(file))+std::string("x")+my_to_string(load(file)));
}
else
{
names.erase(names.begin()+i);
i--;
}
file.close();
}
}
texts.clear();
dateTexts.clear();
int savesPage=0;
//int savesPageSize=std::ceil(names.size()/14.f);
float scale=appWindow.getSize().y/1080.f;
for(int i=0;i<std::min(14,(int)names.size());i++)
{
texts.push_back(sf::Text(names[i].first,data.getFont(),60));
texts[i].setFillColor(sf::Color::Black);
texts[i].setOutlineThickness(6.f);
texts[i].setScale(scale,scale);
texts[i].setOutlineColor(sf::Color::Transparent);
sf::FloatRect fr=texts[i].getLocalBounds();
texts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
texts[i].setPosition(my_vector2f(appWindow.getSize().x*.4f,i*scale*60.f));
if(this->state==2)
{
dateTexts.push_back(sf::Text(info[i],data.getFont(),60));
dateTexts[i].setFillColor(sf::Color::Black);
dateTexts[i].setOutlineThickness(6.f);
dateTexts[i].setScale(scale,scale);
dateTexts[i].setOutlineColor(sf::Color::Transparent);
fr=dateTexts[i].getLocalBounds();
dateTexts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
dateTexts[i].setPosition(my_vector2f(appWindow.getSize().x*.6f,i*scale*60.f));
}
else
texts[i].move(appWindow.getSize().x*.1f,.0f);
}
upButton.setActive(true);
downButton.setActive(true);
bool isMouseButtonPressed=false;
my_vector2f tmpMousePos;
while(true)
{
tmpMousePos=appWindow.mapPixelToCoords(sf::Mouse::getPosition(appWindow));
while (appWindow.pollEvent(state.event))
{
if(state.event.type==sf::Event::Closed)
{
isMouseButtonPressed=false;
appWindow.close();
setState(0);
upButton.setActive(true);
downButton.setActive(true);
return std::string();
}
else if(state.event.type==sf::Event::MouseButtonReleased)
isMouseButtonPressed=true;
}
for(std::size_t i=0u;i<texts.size();i++)
{
if(inBounds(tmpMousePos,texts[i].getGlobalBounds()))
{
texts[i].setOutlineColor(sf::Color::Yellow);
if(isMouseButtonPressed && sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
setState(0);
upButton.setActive(true);
downButton.setActive(true);
return path+texts[i].getString().toAnsiString()+ext;
}
}
else
{
texts[i].setOutlineColor(sf::Color::Transparent);
}
}
if(isMouseButtonPressed && escapeButton.wasPressed(state.event, appWindow))
{
isMouseButtonPressed=false;
upButton.setActive(true);
downButton.setActive(true);
return std::string();
}
if(isMouseButtonPressed && upButton.wasPressed(state.event, appWindow))
{
isMouseButtonPressed=false;
if(savesPage>0)
{
savesPage--;
for(int i=0;i<14;i++)
if(i+savesPage*14<(int)names.size())
{
texts[i].setString(names[i+savesPage*14].first);
sf::FloatRect fr=texts[i].getLocalBounds();
texts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
texts[i].setPosition(my_vector2f(appWindow.getSize().x*.4f,i*scale*60.f));
if(this->state==2)
{
dateTexts[i].setString(info[i+savesPage*14]);
fr=dateTexts[i].getLocalBounds();
dateTexts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
dateTexts[i].setPosition(my_vector2f(appWindow.getSize().x*.6f,i*scale*60.f));
}
}
else
{
texts[i].setString("");
if(this->state==2)
dateTexts[i].setString("");
}
}
}
if(isMouseButtonPressed && downButton.wasPressed(state.event, appWindow))
{
isMouseButtonPressed=false;
if(savesPage<std::ceil(names.size()/14.f)-1)
{
savesPage++;
for(int i=0;i<14;i++)
if(i+savesPage*14<(int)names.size())
{
texts[i].setString(names[i+savesPage*14].first);
sf::FloatRect fr=texts[i].getLocalBounds();
texts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
texts[i].setPosition(my_vector2f(appWindow.getSize().x*.4f,i*scale*60.f));
if(this->state==2)
{
dateTexts[i].setString(info[i+savesPage*14]);
fr=dateTexts[i].getLocalBounds();
dateTexts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
dateTexts[i].setPosition(my_vector2f(appWindow.getSize().x*.6f,i*scale*60.f));
}
}
else
{
texts[i].setString("");
if(this->state==2)
dateTexts[i].setString("");
}
}
}
appWindow.clear();
appWindow.draw(ls);
appWindow.draw(*this);
for(std::size_t i=0u;i<texts.size();i++)
appWindow.draw(texts[i]);
if(this->state==2)
{
for(std::size_t i=0u;i<dateTexts.size();i++)
appWindow.draw(dateTexts[i]);
}
if(savesPage>0)
appWindow.draw(upButton);
if(savesPage<std::ceil(names.size()/14.f)-1)
appWindow.draw(downButton);
appWindow.display();
}
}
sf::VideoMode MainMenu::chooseResolution(State& state, const std::vector<sf::VideoMode>& validModes)
{
std::vector<sf::Text> texts;
texts.clear();
int savesPage=0;
float scale=appWindow.getSize().y/1080.f;
for(int i=0;i<std::min(14,(int)validModes.size());i++)
{
texts.push_back(sf::Text(VideoModeToString(validModes[i]),data.getFont(),60));
texts[i].setFillColor(sf::Color::Black);
texts[i].setOutlineThickness(6.f);
texts[i].setScale(scale,scale);
texts[i].setOutlineColor(sf::Color::Transparent);
sf::FloatRect fr=texts[i].getLocalBounds();
texts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
texts[i].setPosition(my_vector2f(appWindow.getSize().x*.5f,i*scale*60.f));
}
upButton.setActive(true);
downButton.setActive(true);
bool isMouseButtonPressed=false;
my_vector2f tmpMousePos;
while(true)
{
tmpMousePos=appWindow.mapPixelToCoords(sf::Mouse::getPosition(appWindow));
while (appWindow.pollEvent(state.event))
{
if(state.event.type==sf::Event::Closed)
{
isMouseButtonPressed=false;
appWindow.close();
setState(0);
upButton.setActive(true);
downButton.setActive(true);
return sf::VideoMode();
}
else if(state.event.type==sf::Event::MouseButtonReleased)
isMouseButtonPressed=true;
}
for(std::size_t i=0u;i<texts.size();i++)
{
if(inBounds(tmpMousePos,texts[i].getGlobalBounds()))
{
texts[i].setOutlineColor(sf::Color::Yellow);
if(isMouseButtonPressed && sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
setState(0);
upButton.setActive(true);
downButton.setActive(true);
return validModes[i+savesPage*14];
}
}
else
{
texts[i].setOutlineColor(sf::Color::Transparent);
}
}
if(isMouseButtonPressed && escapeButton.wasPressed(state.event, appWindow))
{
isMouseButtonPressed=false;
upButton.setActive(true);
downButton.setActive(true);
return sf::VideoMode();
}
if(isMouseButtonPressed && upButton.wasPressed(state.event, appWindow))
{
isMouseButtonPressed=false;
if(savesPage>0)
{
savesPage--;
for(int i=0;i<14;i++)
if(i+savesPage*14<(int)validModes.size())
{
texts[i].setString(VideoModeToString(validModes[i+savesPage*14]));
sf::FloatRect fr=texts[i].getLocalBounds();
texts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
texts[i].setPosition(my_vector2f(appWindow.getSize().x*.5f,i*scale*60.f));
}
else
{
texts[i].setString("");
}
}
}
if(isMouseButtonPressed && downButton.wasPressed(state.event, appWindow))
{
isMouseButtonPressed=false;
if(savesPage<std::ceil(validModes.size()/14.f)-1)
{
savesPage++;
for(int i=0;i<14;i++)
if(i+savesPage*14<(int)validModes.size())
{
texts[i].setString(VideoModeToString(validModes[i+savesPage*14]));
sf::FloatRect fr=texts[i].getLocalBounds();
texts[i].setOrigin(fr.left + fr.width/2.0f, .0f);
texts[i].setPosition(my_vector2f(appWindow.getSize().x*.5f,i*scale*60.f));
}
else
{
texts[i].setString("");
}
}
}
appWindow.clear();
appWindow.draw(ls);
appWindow.draw(*this);
for(std::size_t i=0u;i<texts.size();i++)
appWindow.draw(texts[i]);
if(this->state==2)
{
for(std::size_t i=0u;i<dateTexts.size();i++)
appWindow.draw(dateTexts[i]);
}
if(savesPage>0)
appWindow.draw(upButton);
if(savesPage<std::ceil(validModes.size()/14.f)-1)
appWindow.draw(downButton);
appWindow.display();
}
}
void MainMenu::actualizeNames()
{
newGameButton->setText(Lang("MAIN_MENU_NEW_GAME"));
loadGameButton->setText(Lang("MAIN_MENU_LOAD_GAME"));
settingsButton->setText(Lang("MAIN_MENU_SETTINGS"));
escapeButton.text.setString(Lang("MAIN_MENU_EXIT"));
numOfPlayers.setString(Lang("MAIN_MENU_NUMBER_OF_PLAYERS"));
generateMapButton->setText(Lang("MAIN_MENU_GENERATE"));
fullscreenName.setString(Lang("MAIN_MENU_FULLSCREEN"));
saveSettingsButton.text.setString(Lang("MAIN_MENU_SETTINGS_SAVE"));
revertSettingsButton.text.setString(Lang("MAIN_MENU_SETTINGS_REVERT"));
graphicSettingsButton.text.setString(Lang("MAIN_MENU_SETTINGS_GRAPHICS"));
languageSettingsButton.text.setString(Lang("MAIN_MENU_SETTINGS_LANGUAGE"));
}
void newGameFunction(MainMenu& mainMenu, short& playersNum)
{
mainMenu.setState(1);
playersNum=2;
mainMenu.mapSize=128;
}
void loadGameFunction(MainMenu& mainMenu, const Data& data, State& state, my_vector2i winSize)
{
//Main function
mainMenu.setState(2);
std::string saveLocation=mainMenu.chooseSave(state, "./saves/",".sav");
mainMenu.setState(0);
if(!saveLocation.empty())
{
if(mainGameLoop(data, state, mainMenu, saveLocation, 0))
appWindow.close();
else
endGameLoop(winSize,mainMenu,state);
}
}
void playerNumFunction(MainMenu& mainMenu, int i, short& playersNum)
{
mainMenu.playerNumButton[playersNum-1]->setEnabled(true);
playersNum=i+1;
mainMenu.playerNumButton[i]->setEnabled(false);
}
void mapSizeFunction(MainMenu& mainMenu, int i)
{
mainMenu.mapSizeButton[mainMenu.mapSize/32-1]->setEnabled(true);
mainMenu.mapSize=(i+1)*32;
mainMenu.mapSizeButton[i]->setEnabled(false);
}
void revertSettingsFunction(std::vector<std::any> params) {
//Loading parameters
MainMenu* mainMenu=std::any_cast<MainMenu*>(params[0]);
State* state=std::any_cast<State*>(params[1]);
bool wasFullscreen=std::any_cast<bool>(params[2]);
std::string* oldLanguageName=std::any_cast<std::string*>(params[3]);
my_vector2i* winSize=std::any_cast<my_vector2i*>(params[4]);
my_vector2i* oldWinSize=std::any_cast<my_vector2i*>(params[5]);
//Main function
if(state->isFullscreen!=wasFullscreen || winSize!=oldWinSize)
{
appWindow.close();
*winSize=*oldWinSize;
state->isFullscreen=wasFullscreen;
createWindow(appWindow,*oldWinSize,wasFullscreen,*state,mainMenu->gui,sf::ContextSettings());
mainMenu->init(*state);
mainMenu->actualizeLoadingScreenSize();
}
if(state->languageName!=*oldLanguageName)
{
state->languageName=*oldLanguageName;
loadLanguage(*oldLanguageName,*mainMenu,true);
}
mainMenu->setState(0);
}
void settingsFunction(MainMenu& mainMenu, State& state, bool& wasFullscreen, std::string& oldLanguageName, my_vector2i& winSize, my_vector2i& oldWinSize)
{
oldLanguageName=state.languageName;
oldWinSize=winSize;
wasFullscreen=state.isFullscreen;
mainMenu.setState(3);
}
void fullscreenCheckBoxFunction(std::vector<std::any> params)
{
//Loading parameters
MainMenu* mainMenu=std::any_cast<MainMenu*>(params[0]);
State* state=std::any_cast<State*>(params[1]);
std::string* oldLanguageName=std::any_cast<std::string*>(params[2]);
//Main function
sf::ContextSettings conSettings = appWindow.getSettings();
my_vector2u oS = appWindow.getSize();
appWindow.close();
if(!mainMenu->fullscreenCheckBox.getChecked())
{
state->isFullscreen=true;
}
else
{
state->isFullscreen=false;
}
createWindow(appWindow,(my_vector2i)oS,state->isFullscreen,*state, mainMenu->gui, conSettings);
if(state->languageName!=*oldLanguageName)
{
state->languageName=*oldLanguageName;
loadLanguage(state->languageName,*mainMenu,true);
}
mainMenu->init(*state);
mainMenu->setState(3);
} | 38.751138 | 185 | 0.648784 | [
"vector"
] |
6b509d333fef97fceffd4898ccb6167e7cac6d3d | 84,478 | cpp | C++ | test/test_primitives/test_cylinder.cpp | orgarten/blazert | ac645b1e6701c2b1b45101b29d370ef1842f7369 | [
"BSD-3-Clause"
] | null | null | null | test/test_primitives/test_cylinder.cpp | orgarten/blazert | ac645b1e6701c2b1b45101b29d370ef1842f7369 | [
"BSD-3-Clause"
] | null | null | null | test/test_primitives/test_cylinder.cpp | orgarten/blazert | ac645b1e6701c2b1b45101b29d370ef1842f7369 | [
"BSD-3-Clause"
] | null | null | null | /*
* Created by ogarten on 15/05/2020.
* Modified on 11/06/202 by ogarten
*
* This file holds test cases for the cylinder primitive for the following cases:
* 1. correct bounding box
* 1.1 center at origin ( rotated, non-rotated cylinder)
* 1.1 center not at origin (rotated, non-rotated cylinder)
*
* 2. testing primitive center function
* 2.1 center at origin ( rotated, non-rotated cylinder)
* 2.2 center not at origin ( rotated, non-rotated cylinder)
*
* 3. intersection tests
* 3.1 center at origin
* 3.1.1 non-rotated cylinder
* origin hit where?
* __________________________
* above top, perpendicular
* above top, oblique indcidence
* above shell surface
* below bottom, perpendicular
* below bottom, oblique indcidence
* below shell surface
* outside shell surface
* inside top, bottom, shell surface
* above no hits
* below no hits
* outside no hits
* 3.1.2 rotated cylinder
* rotation origin hit where?
* ____________________________
* z-axis z-axis top + no hit
* y-axis x-axis top + no hit
* x-axis y-axis top + no hit
*
*
* 3.2 center not at origin
* The same cases as in 3.1 are implemented for shifted center
*/
#define DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS
#include <blazert/bvh/accel.h>
#include <blazert/bvh/builder.h>
#include <blazert/datatypes.h>
#include <blazert/primitives/cylinder.h>
#include <blazert/ray.h>
#include <memory>
//#include <blazert/scene.h>
#include "../test_helpers.h"
#include "assert_helper.h"
#include <third_party/doctest/doctest/doctest.h>
using namespace blazert;
using namespace doctest;
TEST_CASE_TEMPLATE("cylinder", T, float, double) {
auto centers = std::make_unique<Vec3rList<T>>();
auto semi_axes_a = std::make_unique<std::vector<T>>();
auto semi_axes_b = std::make_unique<std::vector<T>>();
auto heights = std::make_unique<std::vector<T>>();
auto rotations = std::make_unique<Mat3rList<T>>();
SUBCASE("bounding box") {
SUBCASE("center at origin") {
centers->emplace_back(Vec3r<T>{0, 0, 0});
semi_axes_a->emplace_back(1);
semi_axes_b->emplace_back(1);
heights->emplace_back(2);
SUBCASE("non-rotated") {
rotations->emplace_back(blaze::IdentityMatrix<T>(3UL));
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_bmin{-1, -1, -1};
const Vec3r<T> true_bmax{1, 1, 1};
assert_bounding_box(cylinders, 0, true_bmin, true_bmax);
}
SUBCASE("rotated about (0,1,0)") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_bmin{-1, -1, -1};
const Vec3r<T> true_bmax{1, 1, 1};
assert_bounding_box(cylinders, 0, true_bmin, true_bmax);
}
}
SUBCASE("shifted center") {
centers->emplace_back(Vec3r<T>{0, 1, 4});
semi_axes_a->emplace_back(1);
semi_axes_b->emplace_back(1);
heights->emplace_back(2);
SUBCASE("non-rotated") {
rotations->emplace_back(blaze::IdentityMatrix<T>(3UL));
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_bmin{-1, 0, 3};
const Vec3r<T> true_bmax{1, 2, 5};
assert_bounding_box(cylinders, 0, true_bmin, true_bmax);
}
SUBCASE("rotated about (0,1,0)") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_bmin{-1, 0, 3};
const Vec3r<T> true_bmax{1, 2, 5};
assert_bounding_box(cylinders, 0, true_bmin, true_bmax);
}
}
}
SUBCASE("primitive center") {
SUBCASE("center at origin") {
centers->emplace_back(Vec3r<T>{0, 0, 0});
semi_axes_a->emplace_back(1);
semi_axes_b->emplace_back(1);
heights->emplace_back(2);
SUBCASE("non-rotated") {
rotations->emplace_back(blaze::IdentityMatrix<T>(3UL));
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_center{0, 0, 0};
assert_primitive_center(cylinders, 0, true_center);
}
SUBCASE("rotated about (0,1,0)") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_center{0, 0, 0};
assert_primitive_center(cylinders, 0, true_center);
}
}
SUBCASE("shifted center") {
centers->emplace_back(Vec3r<T>{0, 1, 4});
semi_axes_a->emplace_back(1);
semi_axes_b->emplace_back(1);
heights->emplace_back(2);
SUBCASE("non-rotated") {
rotations->emplace_back(blaze::IdentityMatrix<T>(3UL));
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_center{0, 1, 4};
assert_primitive_center(cylinders, 0, true_center);
}
SUBCASE("rotated about (0,1,0)") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
CylinderCollection<T> cylinders(*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations);
const Vec3r<T> true_center{0, 1, 4};
assert_primitive_center(cylinders, 0, true_center);
}
}
}
SUBCASE("intersections") {
SUBCASE("center at origin") {
centers->emplace_back(Vec3r<T>{0, 0, 0});
semi_axes_a->emplace_back(1);
semi_axes_b->emplace_back(2);
heights->emplace_back(2);
SUBCASE("non-rotated") {
rotations->emplace_back(blaze::IdentityMatrix<T>(3UL));
SUBCASE("hits") {
SUBCASE("origin above") {
SUBCASE("perpendicular incidence on top") {
Vec3r<T> org1{0, 0, 7.5};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 6.5;
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on top") {
Vec3r<T> org1{4, 0, 6};
Vec3r<T> dir1{-1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(50));
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{5, 0, 4};
Vec3r<T> dir1{-1, 0, -1};
Ray<T> ray{org1, dir1};
RayHit<T> rayhit;
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-5, 0, 4};
Vec3r<T> dir1{1, 0, -1};
Ray<T> ray{org1, dir1};
RayHit<T> rayhit;
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{0, 5, 3};
Vec3r<T> dir1{0, -1, -1};
Ray<T> ray{org1, dir1};
RayHit<T> rayhit;
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{0, -5, 3};
Vec3r<T> dir1{0, 1, -1};
Ray<T> ray{org1, dir1};
RayHit<T> rayhit;
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin below") {
SUBCASE("perpendicular incidence on bottom") {
Vec3r<T> org1{0, 0, -8.5};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
RayHit<T> rayhit;
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 7.5;
const Vec3r<T> true_normal{0, 0, -1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on bottom") {
Vec3r<T> org1{5, 0, -6};
Vec3r<T> dir1{-1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(50));
const Vec3r<T> true_normal{0, 0, -1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
const Vec3r<T> org1{5, 0, -4};
const Vec3r<T> dir1{-1, 0, 1};
const Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-5, 0, -4};
Vec3r<T> dir1{1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{0, 5, -3};
Vec3r<T> dir1{0, -1, 1};
Ray<T> ray{org1, dir1};
RayHit<T> rayhit;
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{0, -5, -3};
Vec3r<T> dir1{0, 1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin around shell") {
SUBCASE("perpendicular incidence") {
SUBCASE("origin: x+") {
Vec3r<T> org1{5, 0, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 4;
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: x-") {
Vec3r<T> org1{-5, 0, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 4;
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y+") {
Vec3r<T> org1{0, 5, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 3;
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y-") {
Vec3r<T> org1{0, -5, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 3;
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
SUBCASE("origin inside of cylinder") {
SUBCASE("hit top") {
Vec3r<T> org1{0, 0, 0};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit bottom") {
Vec3r<T> org1{0, 0, 0};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{0, 0, -1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 1") {
Vec3r<T> org1{0, 0, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 2") {
Vec3r<T> org1{0, 0, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 3") {
Vec3r<T> org1{0, 0, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 2;
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 4") {
Vec3r<T> org1{0, 0, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 2;
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
SUBCASE("no hits") {
SUBCASE("origin above (direction inverted)") {
SUBCASE("perpendicular incidence on top") {
Vec3r<T> org1{0, 0, 6.5};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on top") {
Vec3r<T> org1{5, 0, 6};
Vec3r<T> dir1{1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{5, 0, 4};
Vec3r<T> dir1{1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-5, 0, 4};
Vec3r<T> dir1{-1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{0, 5, 3};
Vec3r<T> dir1{0, 1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{0, -5, 3};
Vec3r<T> dir1{0, -1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin below (direction inverted)") {
SUBCASE("perpendicular incidence on bottom") {
Vec3r<T> org1{0, 0, -8.5};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on bottom") {
Vec3r<T> org1{5, 0, -6};
Vec3r<T> dir1{1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{5, 0, -4};
Vec3r<T> dir1{1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-5, 0, -4};
Vec3r<T> dir1{-1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{0, 5, -3};
Vec3r<T> dir1{0, 1, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{0, -5, -3};
Vec3r<T> dir1{0, -1, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin around shell (direction inverted") {
SUBCASE("perpendicular incidence") {
SUBCASE("origin: x+") {
Vec3r<T> org1{5, 0, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: x-") {
Vec3r<T> org1{-5, 0, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y+") {
Vec3r<T> org1{0, 5, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y-") {
Vec3r<T> org1{0, -5, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
}
}
SUBCASE("rotated") {
SUBCASE("hits") {
SUBCASE("about z-axis") {
const Vec3r<T> axis{0, 0, 1};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{0, 0, 6.5};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 5.5;
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about y-axis") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{6.5, 0, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 5.5;
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about x-axis") {
const Vec3r<T> axis{1, 0, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{0, 8.5, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 7.5;
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("no hits") {
SUBCASE("about z-axis") {
const Vec3r<T> axis{0, 0, 1};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{0, 0, 6.5};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about y-axis") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{6.5, 0, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about x-axis") {
const Vec3r<T> axis{1, 0, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{0, 6.5, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
}
SUBCASE("shifted center") {
centers->emplace_back(Vec3r<T>{1, 2, 0});
semi_axes_a->emplace_back(1);
semi_axes_b->emplace_back(2);
heights->emplace_back(2);
SUBCASE("non-rotated") {
rotations->emplace_back(blaze::IdentityMatrix<T>(3UL));
SUBCASE("hits") {
SUBCASE("origin above") {
SUBCASE("perpendicular incidence on top") {
Vec3r<T> org1{1, 2, 6.5};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 5.5;
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on top") {
Vec3r<T> org1{6, 2, 6};
Vec3r<T> dir1{-1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(50));
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{6, 2, 4};
Vec3r<T> dir1{-1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-4, 2, 4};
Vec3r<T> dir1{1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{1, 7, 3};
Vec3r<T> dir1{0, -1, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{1, -3, 3};
Vec3r<T> dir1{0, 1, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin below") {
SUBCASE("perpendicular incidence on bottom") {
Vec3r<T> org1{1, 2, -8.5};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 7.5;
const Vec3r<T> true_normal{0, 0, -1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on bottom") {
Vec3r<T> org1{6, 2, -6};
Vec3r<T> dir1{-1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(50));
const Vec3r<T> true_normal{0, 0, -1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{6, 2, -4};
Vec3r<T> dir1{-1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-4, 2, -4};
Vec3r<T> dir1{1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(32));
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{1, 7, -3};
Vec3r<T> dir1{0, -1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{1, -3, -3};
Vec3r<T> dir1{0, 1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = static_cast<T>(std::sqrt(18));
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin around shell") {
SUBCASE("perpendicular incidence") {
SUBCASE("origin: x+") {
Vec3r<T> org1{6, 2, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 4;
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: x-") {
Vec3r<T> org1{-4, 2, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 4;
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y+") {
Vec3r<T> org1{1, 7, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 3;
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y-") {
Vec3r<T> org1{1, -3, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 3;
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
SUBCASE("origin inside of cylinder") {
SUBCASE("hit top") {
Vec3r<T> org1{1, 2, 0};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit bottom") {
Vec3r<T> org1{1, 2, 0};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{0, 0, -1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 1") {
Vec3r<T> org1{1, 2, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{-1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 2") {
Vec3r<T> org1{1, 2, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 1;
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 3") {
Vec3r<T> org1{1, 2, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 2;
const Vec3r<T> true_normal{0, -1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("hit shell 4") {
Vec3r<T> org1{1, 2, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 2;
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
SUBCASE("no hits") {
SUBCASE("origin above (direction inverted)") {
SUBCASE("perpendicular incidence on top") {
Vec3r<T> org1{1, 2, 6.5};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on top") {
Vec3r<T> org1{6, 2, 6};
Vec3r<T> dir1{1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{6, 2, 4};
Vec3r<T> dir1{1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-4, 2, 4};
Vec3r<T> dir1{-1, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{1, 7, 3};
Vec3r<T> dir1{0, 1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{1, -3, 3};
Vec3r<T> dir1{0, -1, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin below (direction inverted)") {
SUBCASE("perpendicular incidence on bottom") {
Vec3r<T> org1{1, 2, -8.5};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on bottom") {
Vec3r<T> org1{6, 2, -6};
Vec3r<T> dir1{1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 1") {
Vec3r<T> org1{6, 2, -4};
Vec3r<T> dir1{1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 2") {
Vec3r<T> org1{-4, 2, -4};
Vec3r<T> dir1{-1, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 3") {
Vec3r<T> org1{1, 7, -3};
Vec3r<T> dir1{0, 1, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("oblique incidence on shell 4") {
Vec3r<T> org1{1, -3, -3};
Vec3r<T> dir1{0, -1, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("origin around shell (direction inverted)") {
SUBCASE("perpendicular incidence") {
SUBCASE("origin: x+") {
Vec3r<T> org1{6, 2, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: x-") {
Vec3r<T> org1{-4, 2, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y+") {
Vec3r<T> org1{1, 7, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("origin: y-") {
Vec3r<T> org1{1, -3, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
}
}
SUBCASE("rotated") {
SUBCASE("hits") {
SUBCASE("about z-axis") {
const Vec3r<T> axis{0, 0, 1};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{1, 2, 6.5};
Vec3r<T> dir1{0, 0, -1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 5.5;
const Vec3r<T> true_normal{0, 0, 1};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about y-axis") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{7.5, 2, 0};
Vec3r<T> dir1{-1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 5.5;
const Vec3r<T> true_normal{1, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about x-axis") {
const Vec3r<T> axis{1, 0, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{1, 10.5, 0};
Vec3r<T> dir1{0, -1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = true;
const unsigned int true_prim_id = 0;
const T true_distance = 7.5;
const Vec3r<T> true_normal{0, 1, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
SUBCASE("no hits") {
SUBCASE("about z-axis") {
const Vec3r<T> axis{0, 0, 1};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{1, 2, 7.5};
Vec3r<T> dir1{0, 0, 1};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about y-axis") {
const Vec3r<T> axis{0, 1, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{8.5, 2, 0};
Vec3r<T> dir1{1, 0, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
SUBCASE("about x-axis") {
const Vec3r<T> axis{1, 0, 0};
Mat3r<T> rot = arbitraryRotationMatrix(axis, pi<T> / 2);
rotations->push_back(rot);
Vec3r<T> org1{1, 5.5, 0};
Vec3r<T> dir1{0, 1, 0};
Ray<T> ray{org1, dir1};
CylinderCollection<T> cylinders{*centers, *semi_axes_a, *semi_axes_b, *heights, *rotations};
const bool true_hit = false;
const unsigned int true_prim_id = static_cast<unsigned int>(-1);
const T true_distance = std::numeric_limits<T>::max();
const Vec3r<T> true_normal{0, 0, 0};
SUBCASE("intersect primitive") {
assert_intersect_primitive_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
SUBCASE("traverse bvh") {
assert_traverse_bvh_hit(cylinders, ray, true_hit, true_prim_id, true_distance, true_normal);
}
}
}
}
}
}
}
| 46.314693 | 117 | 0.552866 | [
"vector"
] |
6b52e42fdc0675807ab32dd7a30153d8d58fa0f5 | 16,885 | cpp | C++ | dwarfz/location.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 2 | 2018-03-19T23:27:47.000Z | 2018-06-24T16:15:19.000Z | dwarfz/location.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | null | null | null | dwarfz/location.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 1 | 2021-11-28T05:39:05.000Z | 2021-11-28T05:39:05.000Z | //
// $Id$
//
// -------------------------------------------------------------------------
// This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// -------------------------------------------------------------------------
#include "zdk/stdexcept.h"
#include <assert.h>
#include <iostream>
#include <stack>
#include <dwarf.h>
#include <pthread.h>
#include "private/log.h"
#include "public/addr_ops.h"
#include "public/abi.h"
#include "public/error.h"
#include "public/impl.h"
#include "public/location.h"
#include "public/unwind.h"
#include "generic/lock.h"
using namespace std;
using namespace Dwarf;
using namespace Dwarf::ABI;
namespace
{
/**
* Stack for evaluating location operations
*/
CLASS Stack : public stack<Dwarf_Addr>
{
public:
void push(Dwarf_Addr addr)
{
stack<Dwarf_Addr>::push(addr);
LOG_DEBUG(2) << "PUSH " << hex << addr << dec << endl;
}
void pop()
{
stack<Dwarf_Addr>::pop();
LOG_DEBUG(2) << "POP" << endl;
}
};
}
static pthread_key_t addrOpsKey;
static void delete_key(void*)
{
LOG_DEBUG(0) << __func__ << endl;
pthread_key_delete(addrOpsKey);
}
namespace Dwarf
{
int init = pthread_key_create(&addrOpsKey, delete_key);
}
/**
* note: the client must ensure thread-safety
*/
AddrOps* Dwarf::set_addr_operations(AddrOps* ops)
{
AddrOps* prev = (AddrOps*)pthread_getspecific(addrOpsKey);
pthread_setspecific(addrOpsKey, ops);
return prev;
}
AddrOps* Dwarf::get_addr_operations()
{
AddrOps* addrOps = (AddrOps*)pthread_getspecific(addrOpsKey);
assert(addrOps);
return addrOps;
}
Location::Location(Dwarf_Debug dbg, Dwarf_Attribute attr)
: dbg_(dbg), list_(0), size_(0), isValue_(false)
{
assert(dbg);
Dwarf_Error err = 0;
if (dwarf_loclist_n(attr, &list_, &size_, &err) == DW_DLV_ERROR)
{
THROW_ERROR(dbg, err);
}
}
Location::~Location()
{
if (list_)
{
for (Dwarf_Signed i(0); i != size_; ++i)
{
dwarf_dealloc(dbg_, list_[i]->ld_s, DW_DLA_LOC_BLOCK);
dwarf_dealloc(dbg_, list_[i], DW_DLA_LOCDESC);
}
dwarf_dealloc(dbg_, list_, DW_DLA_LIST);
}
}
bool Location::is_register(Dwarf_Addr pc, Dwarf_Addr base) const
{
bool result = false;
if (list_)
{
assert(size_ > 0);
for (Dwarf_Signed j = 0; (j < size_) && !result; ++j)
{
const Dwarf_Locdesc* desc = list_[j];
if (pc < desc->ld_lopc + base)
{
continue;
}
// -1 means unlimited to the right
if ((desc->ld_hipc != Dwarf_Addr(-1)) && (pc >= desc->ld_hipc + base))
{
continue;
}
if (desc->ld_cents == 1)
{
const Dwarf_Loc& loc = desc->ld_s[0];
if (loc.lr_atom == DW_OP_regx)
{
result = true;
}
else if (loc.lr_atom >= DW_OP_reg0 && loc.lr_atom < DW_OP_reg31)
{
result = true;
}
}
}
}
return result;
}
Dwarf_Addr Location::eval(Dwarf_Addr frame,
Dwarf_Addr moduleBase,
Dwarf_Addr unitBase,
Dwarf_Addr pc) const
{
LOG_DEBUG(2) << __func__ << " unit base=" << hex << unitBase << dec << endl;
Dwarf_Addr result = 0;
isValue_ = false;
if (list_)
{
assert(size_ > 0);
for (Dwarf_Signed i = 0; i != size_; ++i)
{
const Dwarf_Locdesc* loc = list_[i];
Dwarf_Addr lopc = loc->ld_lopc;
if (loc->ld_lopc)
{
lopc += moduleBase + unitBase;
}
Dwarf_Addr hipc = loc->ld_hipc;
if (hipc != static_cast<Dwarf_Addr>(-1))
{
hipc += moduleBase + unitBase;
}
LOG_DEBUG(2) << "loc[" << i << "]=" << hex << lopc /* loc->ld_lopc */
<< "-" << hipc << " pc=" << pc << dec << endl;
if ((pc >= lopc) && (pc < hipc))
{
LOG_DEBUG(2) << "evaluating loc[" << i << "]" << endl;
result = eval(dbg_, pc, frame, moduleBase, loc, isValue_);
LOG_DEBUG(2) << __func__ << "=" << hex << result << dec << endl;
break;
}
}
}
return result;
}
static void handle_empty_stack(const string& func)
{
LOG_WARN << func << ": stack empty" << endl;
if (getenv("ZERO_DWARF_ABORT_EMPTY_STACK"))
{
abort();
}
throw runtime_error(func + ": state machine stack empty");
}
/**
* The DW_OP_deref operation pops the top stack entry and
* treats it as an address. The value retrieved from that
* address is pushed
*/
static void op_deref(Stack& stack)
{
AddrOps* addrOps = get_addr_operations();
if (!addrOps)
{
throw runtime_error("op_deref: memory operations not set");
}
else
{
if (stack.empty())
{
handle_empty_stack(__func__);
}
else
{
LOG_DEBUG(2) << "deref: " << hex << stack.top() << dec << endl;
Dwarf_Addr addr = addrOps->read_mem(stack.top());
stack.pop();
stack.push(addr);
}
}
}
/**
* The DW_OP_plus_uconst operation pops the top stack entry, adds
* it to the unsigned LEB128 constant operand and pushes the result
*/
static void op_plus_uconst(Stack& stack, Dwarf_Unsigned operand)
{
if (stack.empty())
{
handle_empty_stack(__func__);
}
else
{
Dwarf_Addr addr = stack.top();
LOG_DEBUG(2) << hex << addr << "+=" << operand << dec << endl;
addr += operand;
stack.pop();
stack.push(addr);
}
}
/**
* The DW_OP_minus operations pops the top two stack values,
* subtracts the former top of the stack from the former second
* entry, and pushes the result.
*/
static void op_minus(Stack& stack)
{
if (stack.size() < 2)
{
LOG_ERROR << __func__ << ": not enough operands" << endl;
}
else
{
Dwarf_Addr op2 = stack.top();
stack.pop();
Dwarf_Addr op1 = stack.top();
stack.pop();
const Dwarf_Addr res = op1 - op2;
LOG_DEBUG(2) << hex << op1 << '-' << op2 << '=' << res << dec << endl;
stack.push(res);
}
}
static void op_plus(Stack& stack)
{
if (stack.size() < 2)
{
LOG_ERROR << __func__ << ": not enough operands" << endl;
}
else
{
Dwarf_Addr op2 = stack.top();
stack.pop();
Dwarf_Addr op1 = stack.top();
stack.pop();
Dwarf_Addr result = op1 + op2;
LOG_DEBUG(2) << hex << op1 << "+" << op2
<< "=" << result << dec << endl;
stack.push(result);
}
}
/**
* Evaluate an address using a simple stack machine
*/
Dwarf_Addr
Location::eval(Dwarf_Debug dbg,
Dwarf_Addr pc,
Dwarf_Addr frameBase,
Dwarf_Addr moduleBase,
const Dwarf_Locdesc* desc,
bool& isValue)
{
AddrOps* addrOps = get_addr_operations();
if (!addrOps)
{
throw runtime_error("eval: memory operations not set");
}
assert(desc);
Stack stack;
LOG_DEBUG(2) << "moduleBase=" << hex << moduleBase << dec << endl;
if (frameBase)
{
LOG_DEBUG(2) << "frameBase=" << hex << frameBase << dec << endl;
stack.push(frameBase);
}
for (size_t i(0); i != desc->ld_cents; ++i)
{
const Dwarf_Loc& loc = desc->ld_s[i];
const int atom = loc.lr_atom;
LOG_DEBUG(2) << "opcode=0x" << hex << atom << dec << endl;
switch (atom)
{
case DW_OP_addr:
LOG_DEBUG(2) << "addr " << hex << loc.lr_number
<< " + " << moduleBase << dec << endl;
// adjust the operand to the address where
// the module is loaded in memory
stack.push(loc.lr_number + moduleBase);
break;
case DW_OP_lit0:
case DW_OP_lit1:
case DW_OP_lit2:
case DW_OP_lit3:
case DW_OP_lit4:
case DW_OP_lit5:
case DW_OP_lit6:
case DW_OP_lit7:
case DW_OP_lit8:
case DW_OP_lit9:
case DW_OP_lit10:
case DW_OP_lit11:
case DW_OP_lit12:
case DW_OP_lit13:
case DW_OP_lit14:
case DW_OP_lit15:
case DW_OP_lit16:
case DW_OP_lit17:
case DW_OP_lit18:
case DW_OP_lit19:
case DW_OP_lit20:
case DW_OP_lit21:
case DW_OP_lit22:
case DW_OP_lit23:
case DW_OP_lit24:
case DW_OP_lit25:
case DW_OP_lit26:
case DW_OP_lit27:
case DW_OP_lit28:
case DW_OP_lit29:
case DW_OP_lit30:
case DW_OP_lit31:
LOG_DEBUG(2) << "literal: " << atom - DW_OP_lit0 << endl;
//
// note: assume that literals from 0 thru 31 are
// defined in contiguous, increasing order
//
stack.push(atom - DW_OP_lit0);
break;
case DW_OP_deref:
op_deref(stack);
break;
case DW_OP_dup:
LOG_DEBUG(2) << "dup" << endl;
//
// DW_OP_dup duplicates the value at the top of the stack
//
if (stack.empty())
{
handle_empty_stack("DW_OP_dup");
}
else
{
stack.push(stack.top());
}
break;
case DW_OP_reg0:
case DW_OP_reg1:
case DW_OP_reg2:
case DW_OP_reg3:
case DW_OP_reg4:
case DW_OP_reg5:
case DW_OP_reg6:
case DW_OP_reg7:
case DW_OP_reg8:
case DW_OP_reg9:
case DW_OP_reg10:
case DW_OP_reg11:
case DW_OP_reg12:
case DW_OP_reg13:
case DW_OP_reg14:
case DW_OP_reg15:
case DW_OP_reg16:
case DW_OP_reg17:
case DW_OP_reg18:
case DW_OP_reg19:
case DW_OP_reg20:
case DW_OP_reg21:
case DW_OP_reg22:
case DW_OP_reg23:
case DW_OP_reg24:
case DW_OP_reg25:
case DW_OP_reg26:
case DW_OP_reg27:
case DW_OP_reg28:
case DW_OP_reg29:
case DW_OP_reg30:
case DW_OP_reg31:
{
const size_t nreg = atom - DW_OP_reg0;
const int ureg = user_reg_index(nreg);
LOG_DEBUG(2) << "read_cpu_reg " << nreg << " " << ureg
<< " (" << user_reg_name(nreg) << ")" << endl;
const Dwarf_Addr addr = addrOps->read_cpu_reg(ureg);
LOG_DEBUG(2) << "read_cpu_reg=" << hex << addr << dec << endl;
stack.push(addr);
}
break;
case DW_OP_regx:
{
const int ureg = user_reg_index(loc.lr_number);
const Dwarf_Addr addr = addrOps->read_cpu_reg(ureg);
LOG_DEBUG(2) << "read_cpu_regx=" << hex << addr << dec << endl;
stack.push(addr);
}
break;
case DW_OP_fbreg:
//
// The DW_OP_fbreg operation provides a signed offset from the
// address specified by the location description in the
// DW_AT_frame_base attribute of the current function.
//
LOG_DEBUG(2) << "DW_OP_fbreg: " << hex << loc.lr_number << dec << endl;
stack.push(frameBase + loc.lr_number);
break;
case DW_OP_plus_uconst:
op_plus_uconst(stack, loc.lr_number);
break;
case DW_OP_minus: op_minus(stack); break;
case DW_OP_plus: op_plus(stack); break;
case DW_OP_breg0:
case DW_OP_breg1:
case DW_OP_breg2:
case DW_OP_breg3:
case DW_OP_breg4:
case DW_OP_breg5:
case DW_OP_breg6:
case DW_OP_breg7:
case DW_OP_breg8:
case DW_OP_breg9:
case DW_OP_breg10:
case DW_OP_breg11:
case DW_OP_breg12:
case DW_OP_breg13:
case DW_OP_breg14:
case DW_OP_breg15:
case DW_OP_breg16:
case DW_OP_breg17:
case DW_OP_breg18:
case DW_OP_breg19:
case DW_OP_breg20:
case DW_OP_breg21:
case DW_OP_breg22:
case DW_OP_breg23:
case DW_OP_breg24:
case DW_OP_breg25:
case DW_OP_breg26:
case DW_OP_breg27:
case DW_OP_breg28:
case DW_OP_breg29:
case DW_OP_breg30:
case DW_OP_breg31:
{
const size_t nreg = atom - DW_OP_breg0;
const int ureg = user_reg_index(nreg);
LOG_DEBUG(2) << "DW_OP_breg" << nreg << endl;
LOG_DEBUG(2) << "Read_cpu_reg " << nreg << " " << ureg
<< " (" << user_reg_name(nreg) << ")" << endl;
const Dwarf_Addr addr = addrOps->read_cpu_reg(ureg);
LOG_DEBUG(2) << "Read_cpu_reg=" << hex << addr << dec << endl;
LOG_DEBUG(2) << "loc.lr_num=" << hex << loc.lr_number << dec << endl;
stack.push(addr + loc.lr_number);
}
break;
case DW_OP_piece:
// log it but don't do anything else
/* DWARF 4 Standard: 2.6.1.2 Composite Location Descriptions
"Each piece is described by a composition operation, which
"does not compute a value nor store any result on the DWARF stack"*/
LOG_DEBUG(0) << __func__ << ": opcode=0x"
<< hex << static_cast<int>(loc.lr_atom)
<< " operand=" << dec << loc.lr_number << endl;
/* if (loc.lr_number < sizeof (Dwarf_Addr))
{
assert(!stack.empty());
Dwarf_Addr v = stack.top();
LOG_DEBUG(2) << "stack_top=" << hex << v << dec << endl;
} */
break;
case DW_OP_const1u:
case DW_OP_const2u:
case DW_OP_const4u:
case DW_OP_const8u:
case DW_OP_constu:
LOG_DEBUG(2) << "const: " << hex << loc.lr_number << dec << endl;
stack.push(loc.lr_number);
break;
case DW_OP_const1s:
case DW_OP_const2s:
case DW_OP_const4s:
case DW_OP_const8s:
case DW_OP_consts:
LOG_DEBUG(2) << "const: " << (Dwarf_Signed)loc.lr_number << endl;
stack.push(loc.lr_number);
break;
case DW_OP_call_frame_cfa: // DWARF 3f
{ // temporary stack unwinder for computing
// the Canonical Frame Address
Unwind unwind(dbg);
stack.push(unwind.compute_cfa(pc, *addrOps));
}
break;
case DW_OP_stack_value: // DWARF 4
assert(!stack.empty());
isValue = true;
break;
default:
LOG_WARN << __func__ << ": unhandled opcode=0x"
<< hex << (int)loc.lr_atom << dec << endl;
break;
}
}
const Dwarf_Addr res = stack.empty() ? 0 : stack.top();
LOG_DEBUG(2) << __func__ << "=" << hex << res << dec << endl;
return res;
}
VTableElemLocation::VTableElemLocation(Dwarf_Debug dbg, Dwarf_Attribute attr)
: Location(dbg, attr)
{
}
/**
* GCC emits the index in the vtable.
* Other compilers emit the absolute address in the vtable; in the latter
* case, adapt the result to a GCC-like, index in the vtable. Assume that
* 'base' is where the object begins, and that is where the .vptr
*/
Dwarf_Addr
VTableElemLocation::eval( Dwarf_Addr base,
Dwarf_Addr modBase,
Dwarf_Addr unitBase,
Dwarf_Addr pc
) const
{
Dwarf_Addr addr = Location::eval(base, modBase, unitBase, pc);
if (addr >= base)
{
if (AddrOps* addrOps = get_addr_operations())
{
addr = addrOps->read_mem(base);
addr = Location::eval(addr, modBase, unitBase, pc) - addr;
addr /= sizeof(void*);
}
else
{
throw runtime_error("VTableElemLocation: memory operations not set");
}
}
return addr;
}
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
| 26.507064 | 85 | 0.519337 | [
"object"
] |
6b59f73630aa4de079d6f671f160d5aa3dae67c8 | 54,067 | cc | C++ | src/ifmap/client/test/peer_server_finder_test.cc | biswajit-mandal/contrail-controller | 80c4a7e8515f7296b18ba4c21a439bd3daefcc4a | [
"Apache-2.0"
] | 5 | 2015-01-08T17:34:41.000Z | 2017-09-28T16:00:25.000Z | src/ifmap/client/test/peer_server_finder_test.cc | biswajit-mandal/contrail-controller | 80c4a7e8515f7296b18ba4c21a439bd3daefcc4a | [
"Apache-2.0"
] | null | null | null | src/ifmap/client/test/peer_server_finder_test.cc | biswajit-mandal/contrail-controller | 80c4a7e8515f7296b18ba4c21a439bd3daefcc4a | [
"Apache-2.0"
] | 18 | 2017-01-12T09:28:44.000Z | 2019-04-18T20:47:42.000Z | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "ifmap/client/peer_server_finder.h"
#include "base/logging.h"
#include "base/task.h"
#include "base/task_annotations.h"
#include <sandesh/sandesh.h>
#include "discovery_client.h"
#include "ifmap/client/ifmap_manager.h"
#include "ifmap/client/ifmap_channel.h"
#include "testing/gunit.h"
class MockIFMapManager : public IFMapManager {
public:
MockIFMapManager() : IFMapManager(), start_connection_count(0),
reset_connection_count(0) {
}
virtual void Start(const std::string &host, const std::string &port) {
++start_connection_count;
}
virtual void ResetConnection(const std::string &host,
const std::string &port) {
++reset_connection_count;
}
int get_start_connection_count() { return start_connection_count; }
int get_reset_connection_count() { return reset_connection_count; }
private:
int start_connection_count;
int reset_connection_count;
};
class PeerIFMapServerTestFinder : public PeerIFMapServerFinder {
public:
PeerIFMapServerTestFinder(IFMapManager *ifmap_manager,
DiscoveryServiceClient *client, std::string url) :
PeerIFMapServerFinder(ifmap_manager, client, url) {
}
virtual bool DSExists() {
if (get_url().size()) {
return false;
} else {
return true;
}
}
};
class PeerServerFinderTest : public ::testing::Test {
protected:
PeerServerFinderTest() : peer_finder_(NULL), ifmap_manager_() {
}
void InitFinder(const std::string &url) {
peer_finder_.reset(
new PeerIFMapServerTestFinder(&ifmap_manager_, NULL, url));
}
void AddResponseEntry(std::vector<DSResponse> &ds_resp,
const std::string &host, unsigned short port) {
DSResponse entry;
entry.ep.address(boost::asio::ip::address::from_string(host));
entry.ep.port(port);
ds_resp.push_back(entry);
}
void AddResponseEntryAndProc(std::vector<DSResponse> &ds_resp,
const std::string &host, unsigned short port) {
AddResponseEntry(ds_resp, host, port);
ConcurrencyScope scope("http client");
peer_finder_->ProcPeerIFMapDSResp(ds_resp);
}
void DeleteResponseEntry(std::vector<DSResponse> &ds_resp,
const std::string &host, unsigned short port) {
std::vector<DSResponse>::iterator first = ds_resp.begin();
for (size_t i = 0; i < ds_resp.size(); ++i) {
DSResponse entry = ds_resp[i];
if ((host.compare(entry.ep.address().to_string()) == 0) &&
(port == entry.ep.port())) {
ds_resp.erase(first + i);
break;
}
}
}
void DeleteResponseEntryAndProc(std::vector<DSResponse> &ds_resp,
const std::string &host, unsigned short port) {
DeleteResponseEntry(ds_resp, host, port);
ConcurrencyScope scope("http client");
peer_finder_->ProcPeerIFMapDSResp(ds_resp);
}
std::auto_ptr<PeerIFMapServerTestFinder> peer_finder_;
MockIFMapManager ifmap_manager_;
};
TEST_F(PeerServerFinderTest, StaticPeer) {
InitFinder("https://1.1.1.1:1111");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string stat_peer = peer_finder_->get_static_peer();
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(stat_peer.compare("1.1.1.1:1111"), 0);
EXPECT_EQ(stat_peer.compare(curr_peer), 0);
bool valid = peer_finder_->PeerDown();
EXPECT_EQ(valid, true);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
valid = peer_finder_->PeerDown();
EXPECT_EQ(valid, true);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
valid = peer_finder_->PeerDown();
EXPECT_EQ(valid, true);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
}
// +1, +2, -1, -2
TEST_F(PeerServerFinderTest, DSResp) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
// Add host2. Current should remain host1
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host1. host2 should become current.
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Even after removing host2, current should continue to be host2
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// [+1 +2], [-1 -2]
TEST_F(PeerServerFinderTest, DSResp1) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1 and host2
std::vector<DSResponse> ds_resp;
AddResponseEntry(ds_resp, host1, port1);
AddResponseEntryAndProc(ds_resp, host2, port2);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// After deleting host1, host2 should become current
DeleteResponseEntry(ds_resp, host1, port1);
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, +2, -2, -1
TEST_F(PeerServerFinderTest, DSResp2) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host2. Current should remain host1
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host2. host1 should remain current.
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Even after removing host1, current should continue to be host1
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// [+1 +2], -1, [-2 +1]
TEST_F(PeerServerFinderTest, DSResp3) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1 and host2
std::vector<DSResponse> ds_resp;
AddResponseEntry(ds_resp, host1, port1);
AddResponseEntryAndProc(ds_resp, host2, port2);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// After deleting host1, host2 should become current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// After adding host1 and deleting host2, host1 should become current
AddResponseEntry(ds_resp, host1, port1);
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, +2, +3, -1, -2, -3
TEST_F(PeerServerFinderTest, DSResp4) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string host3 = "1.1.1.3";
unsigned short port3 = 1113;
std::string host3str = "1.1.1.3:1113";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1. host1 should be current
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// Add host2. host1 should be current
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// Add host3. host1 should be current
AddResponseEntryAndProc(ds_resp, host3, port3);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// After deleting host1, host2 should become current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// After deleting host2, host3 should become current
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host3str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// After deleting host3, host3 should remain current
DeleteResponseEntryAndProc(ds_resp, host3, port3);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host3str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, +2, +3, [-1 -3], +1, -1, -2
TEST_F(PeerServerFinderTest, DSResp5) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string host3 = "1.1.1.3";
unsigned short port3 = 1113;
std::string host3str = "1.1.1.3:1113";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1. host1 should be current
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// Add host2. host1 should be current
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// Add host3. host1 should be current
AddResponseEntryAndProc(ds_resp, host3, port3);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// After deleting host1 and host3, host2 should become current
DeleteResponseEntry(ds_resp, host1, port1);
DeleteResponseEntryAndProc(ds_resp, host3, port3);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// After adding host1, host2 should remain current
AddResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// After deleting host1, host2 should remain current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
// After deleting host2, host2 should continue to remain current
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host3, port3));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, -1, +1, -1, +2, -2, +2, -2
TEST_F(PeerServerFinderTest, DSResp6) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1. host1 should be current
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
// Delete host1. host1 should remain current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
// Add host1. host1 should remain current
AddResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
// Delete host1. host1 should remain current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 2);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
std::string host2 = "2.2.2.2";
unsigned short port2 = 2222;
std::string host2str = "2.2.2.2:2222";
// Add host2. host2 should become current
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 2);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host2. host2 should remain current
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 3);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host2. host2 should remain current
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 3);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host2. host2 should remain current
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 4);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, -1, +2, -2, +1, -1, +2, -2
TEST_F(PeerServerFinderTest, DSResp7) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "2.2.2.2";
unsigned short port2 = 2222;
std::string host2str = "2.2.2.2:2222";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1. host1 should be current
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host1. host1 should remain current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host2. host2 should become current
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host2. host2 should remain current
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 2);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host1. host1 should become current
AddResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 2);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host1. host1 should remain current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 3);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host2. host2 should become current
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 3);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 3);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host2. host2 should remain current
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 3);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 4);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, PD, [-1 +2], PD
TEST_F(PeerServerFinderTest, PeerDown) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
// host1 down but it will still be the current peer
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
// Delete host1 and add host2. host2 should become current
DeleteResponseEntry(ds_resp, host1, port1);
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// host2 down but it will still be the current peer
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 3);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// [+1 +2], PD, PD, -1, [+1 -2]
TEST_F(PeerServerFinderTest, PeerDown1) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1 and host2
std::vector<DSResponse> ds_resp;
AddResponseEntry(ds_resp, host1, port1);
AddResponseEntryAndProc(ds_resp, host2, port2);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// host1 down but not removed from DB. host2 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_NE(curr_peer.compare(host1str), 0);
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// host2 down but not removed from DB. host1 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_NE(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host1. host2 should become current
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 3);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host1 and delete host2. host1 should become current
AddResponseEntry(ds_resp, host1, port1);
DeleteResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 4);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, -1, PD, +2, +1, PD
TEST_F(PeerServerFinderTest, PeerDown2) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host1
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
// both the following counters should go up
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// The DB is empty. 'reset_connection' will not go up.
EXPECT_FALSE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_NE(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host2. host2 should become current.
AddResponseEntryAndProc(ds_resp, host2, port2);
curr_peer = peer_finder_->get_current_peer();
EXPECT_NE(curr_peer.compare(host1str), 0);
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host1. No change in current.
AddResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_NE(curr_peer.compare(host1str), 0);
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Peerdown. host1 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_NE(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// +1, -1, PD, [+2 +1], PD
TEST_F(PeerServerFinderTest, PeerDown3) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1
std::vector<DSResponse> ds_resp;
AddResponseEntryAndProc(ds_resp, host1, port1);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 1);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Delete host1
DeleteResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 1);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// The DB is empty. 'reset_connection' will not go up.
EXPECT_FALSE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_NE(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 0);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_FALSE(peer_finder_->HostPortInDSDb(host2, port2));
// Add host2 and host1. Since host1 is current from before, PeerExistsInDb()
// will make us keep using it.
AddResponseEntry(ds_resp, host2, port2);
AddResponseEntryAndProc(ds_resp, host1, port1);
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_NE(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
// Peerdown. host2 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_NE(curr_peer.compare(host1str), 0);
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 2);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 1);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 2);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
// [+1 +2 +3], PD, PD, PD
TEST_F(PeerServerFinderTest, PeerDown4) {
InitFinder("");
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 0);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
std::string host1 = "1.1.1.1";
unsigned short port1 = 1111;
std::string host1str = "1.1.1.1:1111";
std::string host2 = "1.1.1.2";
unsigned short port2 = 1112;
std::string host2str = "1.1.1.2:1112";
std::string host3 = "1.1.1.3";
unsigned short port3 = 1113;
std::string host3str = "1.1.1.3:1113";
std::string stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
// Add host1
std::vector<DSResponse> ds_resp;
AddResponseEntry(ds_resp, host1, port1);
AddResponseEntry(ds_resp, host2, port2);
AddResponseEntryAndProc(ds_resp, host3, port3);
std::string curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 0);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// Peerdown. host2 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host2str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 1);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// Peerdown. host3 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host3str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 2);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
// Peerdown. host1 should become current
EXPECT_TRUE(peer_finder_->PeerDown());
curr_peer = peer_finder_->get_current_peer();
EXPECT_EQ(curr_peer.compare(host1str), 0);
EXPECT_EQ(peer_finder_->get_peer_ifmap_servers_count(), 3);
EXPECT_EQ(ifmap_manager_.get_start_connection_count(), 1);
EXPECT_EQ(ifmap_manager_.get_reset_connection_count(), 3);
EXPECT_EQ(peer_finder_->get_using_non_ds_peer_count(), 0);
EXPECT_EQ(peer_finder_->get_no_best_peer_count(), 0);
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host1, port1));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host2, port2));
EXPECT_TRUE(peer_finder_->HostPortInDSDb(host3, port3));
stat_peer = peer_finder_->get_static_peer();
EXPECT_EQ(stat_peer.size(), 0);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
LoggingInit();
bool success = RUN_ALL_TESTS();
TaskScheduler::GetInstance()->Terminate();
return success;
}
| 45.168755 | 80 | 0.735865 | [
"vector"
] |
6b5b5123e4a9519d69f591096871e47e5950fbee | 1,126 | cpp | C++ | src/08_RecurrentNeuralNetworks/RNN.cpp | jiamny/D2L_pytorch_cpp | 5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09 | [
"MIT"
] | null | null | null | src/08_RecurrentNeuralNetworks/RNN.cpp | jiamny/D2L_pytorch_cpp | 5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09 | [
"MIT"
] | null | null | null | src/08_RecurrentNeuralNetworks/RNN.cpp | jiamny/D2L_pytorch_cpp | 5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09 | [
"MIT"
] | 1 | 2022-03-11T00:12:20.000Z | 2022-03-11T00:12:20.000Z | #include <torch/torch.h>
#include <torch/script.h>
#include <torch/autograd.h>
#include <torch/utils.h>
#include <iostream>
#include <unistd.h>
#include <iomanip>
int main() {
std::cout << "Current path is " << get_current_dir_name() << '\n';
//=============================================
// Recurrent Neural Networks
//=============================================
auto X = torch::normal(0, 1, {3, 1});
auto W_xh = torch::normal(0, 1, {1, 4});
auto H = torch::normal(0, 1, {3, 4});
auto W_hh = torch::normal(0, 1, {4, 4});
auto out1 = torch::matmul(X, W_xh) + torch::matmul(H, W_hh);
std::cout << out1 << std::endl;
/*
* Now we concatenate the matrices X and H along columns (axis 1), and the matrices W_xh and W_hh along rows (axis 0).
* These two concatenations result in matrices of shape (3, 5) and of shape (5, 4), respectively. Multiplying these
* two concatenated matrices, we obtain the same output matrix of shape (3, 4) as above.
*/
auto out2 = torch::matmul(torch::cat({X, H}, 1), torch::cat({W_xh, W_hh}, 0));
std::cout << out2 << std::endl;
std::cout << "Done!\n";
return 0;
}
| 28.871795 | 119 | 0.585258 | [
"shape"
] |
6b61ffb6c48f18022376e1e1af6bc5147f214acb | 4,071 | cpp | C++ | sunglasses/src/Extra/ShadowPointLight.cpp | jonathanbuchanan/Sunglasses | ab82b66f32650a813234cee8963f9b598ef5c1c8 | [
"MIT"
] | 1 | 2016-04-01T02:21:27.000Z | 2016-04-01T02:21:27.000Z | sunglasses/src/Extra/ShadowPointLight.cpp | jonathanbuchanan/Sunglasses | ab82b66f32650a813234cee8963f9b598ef5c1c8 | [
"MIT"
] | 49 | 2015-07-08T13:48:06.000Z | 2017-06-27T01:40:51.000Z | sunglasses/src/Extra/ShadowPointLight.cpp | jonathanbuchanan/Sunglasses | ab82b66f32650a813234cee8963f9b598ef5c1c8 | [
"MIT"
] | null | null | null | // Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include <sunglasses/Extra/ShadowPointLight.h>
#include <sunglasses/Graphics/Primitives.h>
#include <sunglasses/Graphics/Shader.h>
#include <glm/gtc/type_ptr.hpp>
namespace sunglasses {
ShadowPointLight::ShadowPointLight() {
}
ShadowPointLight::ShadowPointLight(glm::vec3 _color, glm::vec3 _position) : PointLight(_color, _position) {
}
void ShadowPointLight::init() {
addAction("shadowMap", &ShadowPointLight::shadowMap);
addAction("action", &ShadowPointLight::update);
addAction("uniform", &ShadowPointLight::uniform);
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
for (int i = 0; i < 6; ++i) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, resolution, resolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texture, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void ShadowPointLight::shadowMap(Action action) {
Shader *shader = action.getParameterPointer<Shader>("shader");
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glViewport(0, 0, resolution, resolution);
clear();
glm::mat4 projection = glm::perspective(90.0f, 1.0f, nearPlane, farPlane); // FOV = 90 degrees, aspect ratio = resolution / resolution = 1
glm::mat4 transforms[6];
transforms[0] = projection * glm::lookAt(position, position + glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f));
transforms[1] = projection * glm::lookAt(position, position + glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f));
transforms[2] = projection * glm::lookAt(position, position + glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f));
transforms[3] = projection * glm::lookAt(position, position + glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f));
transforms[4] = projection * glm::lookAt(position, position + glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f));
transforms[5] = projection * glm::lookAt(position, position + glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f));
for (int i = 0; i < 6; ++i)
(*shader)["shadowMatrices[" + std::to_string(i) + "]"] = transforms[i];
(*shader)["lightPosition"] = position;
(*shader)["farPlane"] = farPlane;
Action render("render");
render.setRecursive(true);
render.addParameter("shader", shader);
sendAction(render, target);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void ShadowPointLight::update(Action action) {
}
void ShadowPointLight::uniform(Action action) {
Shader *shader = action.getParameterPointer<Shader>("shader");
int id = shader->getNextArrayIndex("shadowPointLights");
(*shader)["shadowPointLights[" + std::to_string(id) + "].color"] = color;
(*shader)["shadowPointLights[" + std::to_string(id) + "].position"] = position;
(*shader)["shadowPointLights[" + std::to_string(id) + "].attenuate"] = true;
(*shader)["shadowPointLights[" + std::to_string(id) + "].farPlane"] = farPlane;
int textureUnit = shader->getNextTextureUnit();
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
(*shader)["shadowPointLights[" + std::to_string(id) + "].shadowMap"] = textureUnit;
(*shader)["shadowPointLightCount"] = shader->getArraySize("shadowPointLights");
}
} // namespace
| 38.046729 | 143 | 0.698845 | [
"render"
] |
6b67a024f162881740e8227412bc030387890bff | 148 | cpp | C++ | UUT/Core/ObjectFactory.cpp | kolyden/uut-engine | aa8e5a42c350aceecee668941e06ac626aac6c52 | [
"MIT"
] | null | null | null | UUT/Core/ObjectFactory.cpp | kolyden/uut-engine | aa8e5a42c350aceecee668941e06ac626aac6c52 | [
"MIT"
] | null | null | null | UUT/Core/ObjectFactory.cpp | kolyden/uut-engine | aa8e5a42c350aceecee668941e06ac626aac6c52 | [
"MIT"
] | null | null | null | #include "ObjectFactory.h"
#include "Object.h"
namespace uut
{
ObjectFactory::ObjectFactory()
{
}
ObjectFactory::~ObjectFactory() = default;
} | 13.454545 | 43 | 0.716216 | [
"object"
] |
6b6cb08511912e357c00ef7cf0d846e0c370c2be | 1,748 | cpp | C++ | sgd-comm/test_hash.cpp | a1exwang/dirty-linux-experiments | fb7f89e32e066e764045ab5a50f96d11d6173afe | [
"MIT"
] | null | null | null | sgd-comm/test_hash.cpp | a1exwang/dirty-linux-experiments | fb7f89e32e066e764045ab5a50f96d11d6173afe | [
"MIT"
] | null | null | null | sgd-comm/test_hash.cpp | a1exwang/dirty-linux-experiments | fb7f89e32e066e764045ab5a50f96d11d6173afe | [
"MIT"
] | null | null | null | #include "cache.hpp"
#include <cassert>
using namespace std;
int main() {
std::vector<std::pair<std::set<int>, std::tuple<int64_t, int64_t, int64_t, int64_t, int64_t>>> table = {
// total_images > total_cached_images
{{}, {90, 8, 1, 2, 100}},
// one replication
{{0}, {0, 2, 1, 2, 4}},
{{1}, {1, 2, 1, 2, 4}},
{{0}, {2, 2, 1, 2, 4}},
{{1}, {3, 2, 1, 2, 4}},
// 2 replications
{{0, 1}, {0, 3, 1, 4, 6}},
{{2, 0}, {1, 3, 1, 4, 6}},
{{1, 2}, {2, 3, 1, 4, 6}},
{{0, 1}, {3, 3, 1, 4, 6}},
{{2, 0}, {4, 3, 1, 4, 6}},
{{1, 2}, {5, 3, 1, 4, 6}},
// 2 replications + 1 * 3 replications
{{0, 1, 2}, {0, 3, 1, 3, 4}},
{{0, 1}, {1, 3, 1, 3, 4}},
{{2, 0}, {2, 3, 1, 3, 4}},
{{1, 2}, {3, 3, 1, 3, 4}},
// 2 replications + 2 * 3 replications
{{0, 1, 2}, {0, 5, 1, 2, 4}},
{{3, 4, 0}, {1, 5, 1, 2, 4}},
{{1, 2}, {2, 5, 1, 2, 4}},
{{3, 4}, {3, 5, 1, 2, 4}},
};
int i = 0;
for (auto test_case : table) {
int64_t image_id, process_per_node, nodes, cached_images_per_process, total_images;
std::tie(image_id, process_per_node, nodes, cached_images_per_process, total_images) = test_case.second;
auto expected = test_case.first;
auto actual = caffe::DefaultDistributionHash(0, image_id, process_per_node, nodes, cached_images_per_process, total_images);
if (expected != actual) {
fprintf(stderr, "asserted failed\n");
fprintf(stderr, "expected: (");
for (auto x : expected) {
fprintf(stderr, "%d, ", x);
}
fprintf(stderr, "), actual: (");
for (auto x : actual) {
fprintf(stderr, "%d, ", x);
}
fprintf(stderr, ")\n");
}
i++;
printf("%d passed\n", i);
}
} | 27.3125 | 127 | 0.493135 | [
"vector"
] |
6b7edbe0c8dd38649c722133e86e5a03e765739d | 1,877 | cpp | C++ | cpp/max_heap.cpp | aocsa/cs_hackers_hub | b3c42932260720c60e2cc9a5d552f3987a45fa21 | [
"Apache-2.0"
] | 4 | 2021-03-04T02:45:26.000Z | 2021-05-28T22:51:45.000Z | cpp/max_heap.cpp | aocsa/cs_hackers_hub | b3c42932260720c60e2cc9a5d552f3987a45fa21 | [
"Apache-2.0"
] | 1 | 2021-03-14T16:12:32.000Z | 2021-03-14T16:12:32.000Z | cpp/max_heap.cpp | aocsa/cs_hackers_hub | b3c42932260720c60e2cc9a5d552f3987a45fa21 | [
"Apache-2.0"
] | 5 | 2021-03-16T05:20:48.000Z | 2021-03-24T01:46:28.000Z | #include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <cstring>
//value of the parent node is greater than or equal to the value of its left and right child.
// We use an array to represent a maxheap. The root element is arr[0]. For an index i we have
// https://i1.wp.com/golangbyexample.com/wp-content/uploads/2019/12/Max-Heap.png?resize=201%2C191&ssl=1
// Arr[i]:
// Arr[(i-1)/2] Returns the parent node.
// Arr[(2*i)+1] Returns the left child node.
// Arr[(2*i)+2] Returns the right child node.
struct MaxHeap {
std::vector<int> heap_array;
int size;
int max_size;
MaxHeap(int max_size)
: heap_array(max_size), max_size{max_size}, size{0}
{
}
void insert(int item) {
if (size >= max_size) {
return ;
}
heap_array[size] = item;
size++;
int current = size;
while (heap_array[current] > heap_array[parent(current)]) {
std::swap(heap_array[current], heap_array[parent(current)]);
current = parent(current);
}
}
int parent(int index) {
return index / 2;
}
void print()
{
for (int i = 1; i <= size / 2; i++) {
std::cout <<
" PARENT : " + std::to_string(heap_array[i])
+ " LEFT CHILD : " + std::to_string(heap_array[2 * i])
+ " RIGHT CHILD :" + std::to_string(heap_array[2 * i + 1]);
std::cout << std::endl;
}
}
};
int main(){
// auto maxHeap = {9,4,7,1,-2,6,5};
// auto result = {-2,1,5,9,4,6,7};
MaxHeap maxHeap = new MaxHeap(15);
maxHeap.insert(5);
maxHeap.insert(3);
maxHeap.insert(17);
maxHeap.insert(10);
maxHeap.insert(84);
maxHeap.insert(19);
maxHeap.insert(6);
maxHeap.insert(22);
maxHeap.insert(9);
maxHeap.print();
}
| 25.364865 | 103 | 0.561534 | [
"vector"
] |
6b860a8410685d83c6785773a97426c96f1c6a7a | 4,412 | cpp | C++ | cpp/AnyValue3.cpp | so61pi/examples | 38e2831cd6517864fc05f499f72fbb4ff6ae27c0 | [
"MIT"
] | 4 | 2019-05-01T07:23:53.000Z | 2022-03-05T00:05:06.000Z | cpp/AnyValue3.cpp | so61pi/examples | 38e2831cd6517864fc05f499f72fbb4ff6ae27c0 | [
"MIT"
] | 16 | 2020-02-24T13:04:12.000Z | 2022-02-26T10:19:48.000Z | cpp/AnyValue3.cpp | so61pi/examples | 38e2831cd6517864fc05f499f72fbb4ff6ae27c0 | [
"MIT"
] | 1 | 2019-03-30T07:29:58.000Z | 2019-03-30T07:29:58.000Z | #include <cassert>
#include <list>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include <boost/any.hpp>
enum class Type {
String,
Number,
Boolean,
Null,
Object,
Array
};
struct Value {
Value() : type(Type::Null) {}
Type type;
boost::any internal;
};
using Object = std::list<std::pair<std::string, Value>>;
using Array = std::list<Value>;
bool IsString(Value const& v) {
return v.type == Type::String;
}
bool IsNumber(Value const& v) {
return v.type == Type::Number;
}
bool IsBoolean(Value const& v) {
return v.type == Type::Boolean;
}
bool IsNull(Value const& v) {
return v.type == Type::Null;
}
bool IsObject(Value const& v) {
return v.type == Type::Object;
}
bool IsArray(Value const& v) {
return v.type == Type::Array;
}
Value MakeString(std::string s) {
Value v;
v.type = Type::String;
v.internal = std::move(s);
return v;
}
Value MakeNumber(double n) {
Value v;
v.type = Type::Number;
v.internal = n;
return v;
}
Value MakeBoolean(bool b) {
Value v;
v.type = Type::Boolean;
v.internal = b;
return v;
}
Value MakeNull() {
return Value();
}
Value MakeObject() {
Value v;
v.type = Type::Object;
v.internal = Object();
return v;
}
Value MakeArray() {
Value v;
v.type = Type::Array;
v.internal = Array();
return v;
}
std::string& AsString(Value& v) {
return boost::any_cast<std::string&>(v.internal);
}
std::string const& AsString(Value const& v) {
return boost::any_cast<std::string const&>(v.internal);
}
double& AsNumber(Value& v) {
return boost::any_cast<double&>(v.internal);
}
double const& AsNumber(Value const& v) {
return boost::any_cast<double const&>(v.internal);
}
bool& AsBoolean(Value& v) {
return boost::any_cast<bool&>(v.internal);
}
bool const& AsBoolean(Value const& v) {
return boost::any_cast<bool const&>(v.internal);
}
Object& AsObject(Value& v) {
return boost::any_cast<Object&>(v.internal);
}
Object const& AsObject(Value const& v) {
return boost::any_cast<Object const&>(v.internal);
}
Array& AsArray(Value& v) {
return boost::any_cast<Array&>(v.internal);
}
Array const& AsArray(Value const& v) {
return boost::any_cast<Array const&>(v.internal);
}
std::string to_string(Object const& o);
std::string to_string(Array const& a);
std::string to_string(Value const& v);
std::string to_string(Object const& o) {
if (o.empty()) return "{}";
auto it = o.cbegin();
std::string result = "{ " + it->first + " : " + to_string(it->second);
for (it = std::next(it); it != o.cend(); ++it) {
result += ", " + it->first + " : " + to_string(it->second);
}
result += " }";
return result;
}
std::string to_string(Array const& a) {
if (a.empty()) return "[]";
auto it = a.cbegin();
std::string result = "[ " + to_string(*it);
for (it = std::next(it); it != a.cend(); ++it) {
result += ", " + to_string(*it);
}
result += " ]";
return result;
}
std::string to_string(Value const& v) {
switch (v.type) {
case Type::String:
// Well, we have to escape double quotes & backslashes, but just forget it now.
return '"' + AsString(v) + '"';
case Type::Number:
return std::to_string(AsNumber(v));
case Type::Boolean:
return AsBoolean(v) ? "true" : "false";
case Type::Null:
return "null";
case Type::Object:
return to_string(AsObject(v));
case Type::Array:
return to_string(AsArray(v));
}
}
Array::iterator ArrayAppend(Value& a, Value value) {
Array& array = AsArray(a);
array.emplace_back(std::move(value));
return std::prev(array.end());
}
Object::iterator ObjectAddChild(Value& o, std::string key, Value value) {
Object& object = AsObject(o);
object.emplace_back(std::move(key), std::move(value));
return std::prev(object.end());
}
#include <iostream>
void Test() {
auto o = MakeObject();
ObjectAddChild(o, "message", MakeString("Hello World!"));
auto a = MakeArray();
ArrayAppend(a, MakeNumber(123));
ArrayAppend(a, MakeNumber(456));
ArrayAppend(a, MakeNull());
ArrayAppend(a, MakeString("so61pi"));
ObjectAddChild(o, "array", a);
std::cout << to_string(o) << std::endl;
}
int main(int argc, char *argv[]) {
Test();
}
| 20.054545 | 87 | 0.604034 | [
"object",
"vector"
] |
6b87b57b99c39d806278a5e09f632da6d99c52b3 | 2,467 | tcc | C++ | tuning/util/dp_data.tcc | jungmair/START | 0cb87becf6a4b0a60f4f8eb164c6ac1802c79238 | [
"MIT"
] | 23 | 2020-04-21T19:43:38.000Z | 2022-03-07T06:38:55.000Z | tuning/util/dp_data.tcc | jungmair/START | 0cb87becf6a4b0a60f4f8eb164c6ac1802c79238 | [
"MIT"
] | null | null | null | tuning/util/dp_data.tcc | jungmair/START | 0cb87becf6a4b0a60f4f8eb164c6ac1802c79238 | [
"MIT"
] | 4 | 2020-07-13T19:25:34.000Z | 2022-03-15T02:50:45.000Z | #pragma once
#include "../../util/compile-time-switch.tcc"
//data for optimization with dynamic programming
struct dp_data {
//during the dynamic programming, we need to store accumulated data for the last N tree levels
//for each tree level, one levelInfo struct is maintainted.
struct levelInfo {
size_t cost = 0;
uint32_t childCount = 0;
//how many leaves at this level
uint32_t leaves = 0;
//how many leaves in the total Subtree
uint32_t totalLeaves = 0;
//how many bytes of this level reside in L1/L2/L3 cache?
uint32_t cached_l1 = 0;
uint32_t cached_l2 = 0;
uint32_t cached_l3 = 0;
//8bit vector to store at wich levels multilevel nodes are located
uint8_t mL = 0;
levelInfo &operator+=(levelInfo &other) {
//operator for accumulating levelInfos
mL |= other.mL;
childCount += other.childCount;
leaves += other.leaves;
totalLeaves += other.totalLeaves;
cost += other.cost;
cached_l1 += other.cached_l1;
cached_l2 += other.cached_l2;
cached_l3 += other.cached_l3;
return *this;
}
};
//stores level informations for at most 9 levels
levelInfo infos[9] = {};
//general data:
size_t next_free_level = 0;
bool doReplace = false;
//acumulate dp_datas of lower subtrees, toShift=how much bytes lower
void addShifted(dp_data &other, size_t toShift) {
for (size_t i = 0; i < 9ull - toShift; i++) {
infos[i + toShift] += other.infos[i];
}
}
//when we want to replace, we do not "slice" existing multilevel nodes into two
//-> check if no multilevel node exists
bool canReplace(int depth) {
for (int i = 0; i < depth; i++) {
for (int j = 0; j < 8; j++) {
if (infos[i].mL & (1 << j) && i + j >= depth) {
return false;
}
}
}
return true;
}
levelInfo &top() {
return infos[0];
}
//returns the total number of children, this subtree has until a certain depth
size_t totalChildren(size_t depth) {
depth = depth - 1;
size_t totalChildren = infos[depth].childCount;
for (size_t i = 0; i < depth; i++) {
totalChildren += infos[i].leaves;
}
return totalChildren;
}
};
| 32.038961 | 98 | 0.567896 | [
"vector"
] |
6b87b8333b4c3dffcb212b52f4babe3adb3be936 | 588 | cpp | C++ | ICPC Cookbook/BIT.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | ICPC Cookbook/BIT.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | ICPC Cookbook/BIT.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | // Only ll
typedef struct BIT //ll
{
vector<ll> bit;
int n;
void init(int n)
{
this->n = n;
bit.assign(n,0);
}
ll sum(int i)
{
ll res = 0;
for(;i>=0;i = (i&(i+1)) -1)
{
res+=bit[i];
}
return res;
}
void inc(int i, ll delta)
{
for(;i<n;i = i|(i+1))
{
bit[i]+=delta;
}
}
ll getsum(int l,int r)
{
// If l==0, sum(-1) automatically returns the default calue of res, 0
return sum(r)-sum(l-1);
}
void init(vector<ll> v)
{
init(v.size());
for(int i=0;i<v.size();i++) inc(i,v[i]);
}
} BIT; | 14 | 73 | 0.467687 | [
"vector"
] |
6b8ba5de7c844458206dc9a6c380b2a81867c79e | 30,673 | cpp | C++ | framework/graphics/graphics/texture/texture.cpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | 1 | 2018-03-01T01:05:25.000Z | 2018-03-01T01:05:25.000Z | framework/graphics/graphics/texture/texture.cpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | framework/graphics/graphics/texture/texture.cpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | #include "graphics/texture/texture.hpp"
namespace vg
{
inline uint32_t caculateImageSizeWithMipmapLevel(uint32_t size, uint32_t mipmapLevel);
TextureDataInfo::Component::Component(uint32_t mipLevel
, uint32_t baseArrayLayer
, uint32_t layerCount
, uint32_t size
, Bool32 hasImageExtent
, uint32_t width
, uint32_t height
, uint32_t depth
)
: mipLevel(mipLevel)
, baseArrayLayer(baseArrayLayer)
, layerCount(layerCount)
, size(size)
, hasImageExtent(hasImageExtent)
, width(width)
, height(height)
, depth(depth)
{
}
TextureDataInfo::TextureDataInfo(uint32_t componentCount
, Component *pComponent
)
: componentCount(componentCount)
, pComponent(pComponent)
{
}
Texture::ImageInfo::ImageInfo(vk::ImageCreateFlags flags
, vk::ImageType imageType
, vk::Format format
, vk::Extent3D extent
, uint32_t mipLevels
, uint32_t arrayLayers
, vk::SampleCountFlagBits samples
, vk::ImageTiling tiling
, vk::ImageUsageFlags usage
, vk::SharingMode sharingMode
, vk::ImageLayout layout
, vk::ImageAspectFlags allAspect
)
: flags(flags)
, imageType(imageType)
, format(format)
, extent(extent)
, mipLevels(mipLevels)
, arrayLayers(arrayLayers)
, samples(samples)
, tiling(tiling)
, usage(usage)
, sharingMode(sharingMode)
, layout(layout)
, allAspect(allAspect)
{
}
Texture::Image::Image(ImageInfo info)
: m_info(info)
, m_pImage()
, m_pImageMemory()
{
_create();
}
Texture::ImageInfo Texture::Image::getInfo() const
{
return m_info;
}
const vk::Image *Texture::Image::getImage() const
{
return m_pImage.get();
}
const vk::DeviceMemory *Texture::Image::getImageMemory() const
{
return m_pImageMemory.get();
}
void Texture::Image::_create()
{
auto &info = m_info;
vk::ImageCreateInfo createInfo = {
info.flags,
info.imageType,
info.format,
info.extent,
info.mipLevels,
info.arrayLayers,
info.samples,
info.tiling,
info.usage,
info.sharingMode,
0U,
nullptr,
vk::ImageLayout::eUndefined
};
auto pDevice = pApp->getDevice();
m_pImage = fd::createImage(pDevice, createInfo);
const auto &memRequirements = pDevice->getImageMemoryRequirements(*m_pImage);
vk::MemoryAllocateInfo allocInfo = {
memRequirements.size,
vg::findMemoryType(pApp->getPhysicalDevice(), memRequirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)
};
m_pImageMemory = fd::allocateMemory(pDevice, allocInfo);
pDevice->bindImageMemory(*m_pImage, *m_pImageMemory, vk::DeviceSize(0));
if (m_info.layout != vk::ImageLayout::eUndefined) {
//Transform Image layout to final layout.
auto pCommandBuffer = beginSingleTimeCommands();
vk::ImageMemoryBarrier barrier = {};
barrier.oldLayout = vk::ImageLayout::eUndefined;
barrier.newLayout = info.layout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = *m_pImage;
barrier.subresourceRange.aspectMask = m_info.allAspect;
barrier.subresourceRange.baseMipLevel = 0u;
barrier.subresourceRange.levelCount = m_info.mipLevels;
barrier.subresourceRange.baseArrayLayer = 0u;
barrier.subresourceRange.layerCount = m_info.arrayLayers;
vk::PipelineStageFlags srcStageMask = vk::PipelineStageFlagBits::eAllCommands;
vk::PipelineStageFlags dstStageMask = vk::PipelineStageFlagBits::eAllCommands;
pCommandBuffer->pipelineBarrier(srcStageMask,
dstStageMask,
vk::DependencyFlags(),
nullptr, nullptr,
barrier);
endSingleTimeCommands(pCommandBuffer);
}
}
Texture::ImageViewInfo::ImageViewInfo(vk::ImageViewCreateFlags flags
, vk::Image image
, vk::ImageViewType viewType
, vk::Format format
, vk::ComponentMapping components
, vk::ImageSubresourceRange subResourceRange
)
: flags(flags)
, image(image)
, viewType(viewType)
, format(format)
, components(components)
, subResourceRange(subResourceRange)
{
}
Texture::ImageViewCreateInfo::ImageViewCreateInfo(vk::ImageViewType viewType
, vk::ComponentMapping components
, vk::ImageSubresourceRange subResourceRange
)
: viewType(viewType)
, components(components)
, subResourceRange(subResourceRange)
{
}
Texture::ImageView::ImageView(ImageViewInfo info)
: m_info(info)
, m_pImageView()
{
_create();
}
Texture::ImageViewInfo Texture::ImageView::getInfo() const
{
return m_info;
}
const vk::ImageView *Texture::ImageView::getImageView() const
{
return m_pImageView.get();
}
void Texture::ImageView::_create()
{
auto &info = m_info;
vk::ImageViewCreateInfo createInfo = {
info.flags,
info.image,
info.viewType,
info.format,
info.components,
info.subResourceRange,
};
auto pDevice = pApp->getDevice();
m_pImageView = fd::createImageView(pDevice, createInfo);
}
Texture::SamplerInfo::SamplerInfo(vk::SamplerCreateFlags flags
, vk::Filter magFilter
, vk::Filter minFilter
, vk::SamplerMipmapMode mipmapMode
, vk::SamplerAddressMode addressModeU
, vk::SamplerAddressMode addressModeV
, vk::SamplerAddressMode addressModeW
, float mipLodBias
, vk::Bool32 anisotropyEnable
, float maxAnisotropy
, vk::Bool32 compareEnable
, vk::CompareOp compareOp
, float minLod
, float maxLod
, vk::BorderColor borderColor
, vk::Bool32 unnormalizedCoordinates
)
: flags(flags)
, magFilter(magFilter)
, minFilter(minFilter)
, mipmapMode(mipmapMode)
, addressModeU(addressModeU)
, addressModeV(addressModeV)
, addressModeW(addressModeW)
, mipLodBias(mipLodBias)
, anisotropyEnable(anisotropyEnable)
, maxAnisotropy(maxAnisotropy)
, compareEnable(compareEnable)
, compareOp(compareOp)
, minLod(minLod)
, maxLod(maxLod)
, borderColor(borderColor)
, unnormalizedCoordinates(unnormalizedCoordinates)
{
}
Texture::SamplerCreateInfo::SamplerCreateInfo(vk::SamplerCreateFlags flags
, vk::Filter magFilter
, vk::Filter minFilter
, vk::SamplerMipmapMode mipmapMode
, vk::SamplerAddressMode addressModeU
, vk::SamplerAddressMode addressModeV
, vk::SamplerAddressMode addressModeW
, float mipLodBias
, vk::Bool32 anisotropyEnable
, float maxAnisotropy
, float minLod
, float maxLod
, vk::BorderColor borderColor
)
: flags(flags)
, magFilter(magFilter)
, minFilter(minFilter)
, mipmapMode(mipmapMode)
, addressModeU(addressModeU)
, addressModeV(addressModeV)
, addressModeW(addressModeW)
, mipLodBias(mipLodBias)
, anisotropyEnable(anisotropyEnable)
, maxAnisotropy(maxAnisotropy)
, minLod(minLod)
, maxLod(maxLod)
, borderColor(borderColor)
{
}
Texture::Sampler::Sampler(SamplerInfo info)
: m_info(info)
, m_pSampler()
{
_create();
}
Texture::SamplerInfo Texture::Sampler::getInfo() const
{
return m_info;
}
const vk::Sampler *Texture::Sampler::getSampler() const
{
return m_pSampler.get();
}
void Texture::Sampler::_create()
{
auto &info = m_info;
vk::SamplerCreateInfo createInfo = {
info.flags,
info.magFilter,
info.minFilter,
info.mipmapMode,
info.addressModeU,
info.addressModeV,
info.addressModeW,
info.mipLodBias,
info.anisotropyEnable,
info.maxAnisotropy,
info.compareEnable,
info.compareOp,
info.minLod,
info.maxLod,
info.borderColor,
info.unnormalizedCoordinates,
};
auto pDevice = pApp->getDevice();
m_pSampler = fd::createSampler(pDevice, createInfo);
}
Texture::Texture(vk::Format format
, Bool32 mipMap
, vk::ImageUsageFlags additionalUsage
, Bool32 defaultImageView
, Bool32 defaultSampler
)
: Base(BaseType::TEXTURE)
, m_type()
, m_width(1U)
, m_height(1U)
, m_depth(1U)
, m_arrayLength(1U)
, m_format(format)
, m_mipMap(mipMap)
, m_mipLevels()
, m_arrayLayers()
, m_allAspectFlags()
, m_usageFlags(additionalUsage)
, m_layout()
, m_isCreateDefaultImageView(defaultImageView)
, m_isCreateDefaultSampler(defaultSampler)
, m_dataLayout()
, m_components()
, m_pMemory(nullptr)
, m_memorySize(0u)
, m_pImage()
, m_pImageView()
, m_pSampler()
, m_mapPOtherImageViews()
, m_mapPOtherSamplers()
{
}
Texture::~Texture()
{
if (m_pMemory != nullptr)
{
free(m_pMemory);
}
}
TextureType Texture::getType() const
{
return m_type;
}
Bool32 Texture::getIsMipmap() const
{
return m_mipMap;
}
vk::ImageType Texture::getImageType() const
{
return arrTextureTypeToVKImageType[static_cast<size_t>(m_type)].second;
}
vk::ImageViewType Texture::getImageViewType() const
{
return arrTextureTypeToVKImageViewType[static_cast<size_t>(m_type)].second;
}
const Texture::Image *Texture::getImage() const
{
return m_pImage.get();
}
const Texture::ImageView *Texture::getImageView() const
{
return m_pImageView.get();
}
const Texture::Sampler *Texture::getSampler() const
{
return m_pSampler.get();
}
const Texture::ImageView *Texture::createImageView(std::string name, ImageViewCreateInfo createInfo)
{
auto pImageView = m_mapPOtherImageViews[name];
if (pImageView != nullptr) {
VG_LOG(plog::warning) << "Image view its key is " << name << " has exist!" << std::endl;
return pImageView.get();
}
#ifdef DEBUG
auto allAspect = m_pImage->getInfo().allAspect;
if ((allAspect & createInfo.subResourceRange.aspectMask) != createInfo.subResourceRange.aspectMask) {
auto errorStr = "All aspect of the image don't contain all need aspect to create this image view.";
VG_LOG(plog::error) << errorStr << std::endl;
throw std::invalid_argument(errorStr);
}
#endif //DEBUG
ImageViewInfo info = {
vk::ImageViewCreateFlags(),
*(m_pImage->getImage()),
createInfo.viewType,
m_format,
createInfo.components,
createInfo.subResourceRange,
};
pImageView = std::shared_ptr<ImageView>{new ImageView(info)};
m_mapPOtherImageViews[name] = pImageView;
return pImageView.get();
}
const Texture::ImageView *Texture::getImageView(std::string name) const
{
auto &map = m_mapPOtherImageViews;
const auto& iterator = map.find(name);
if (iterator == map.cend())
{
return nullptr;
}
else
{
return iterator->second.get();
}
}
const Texture::Sampler *Texture::createSampler(std::string name, SamplerCreateInfo createInfo)
{
auto pSampler = m_mapPOtherSamplers[name];
if (pSampler != nullptr) {
VG_LOG(plog::warning) << "Sampler its key is " << name << " has exist!" << std::endl;
return pSampler.get();
}
SamplerInfo info = {
createInfo.flags,
createInfo.magFilter,
createInfo.minFilter,
createInfo.mipmapMode,
createInfo.addressModeU,
createInfo.addressModeV,
createInfo.addressModeW,
createInfo.mipLodBias,
createInfo.anisotropyEnable,
createInfo.maxAnisotropy,
VG_FALSE,
vk::CompareOp::eNever,
createInfo.minLod,
createInfo.maxLod,
createInfo.borderColor,
};
pSampler = std::shared_ptr<Sampler>{new Sampler(info)};
m_mapPOtherSamplers[name] = pSampler;
return pSampler.get();
}
const Texture::Sampler *Texture::getSampler(std::string name) const
{
auto &map = m_mapPOtherSamplers;
const auto& iterator = map.find(name);
if (iterator == map.cend())
{
return nullptr;
}
else
{
return iterator->second.get();
}
}
void Texture::_init(Bool32 importContent)
{
_updateMipMapLevels();
_updateArrayLayer();
_createImage(importContent);
_createImageView();
_createSampler();
}
void Texture::_updateMipMapLevels()
{
if (m_mipMap)
{
// calculate num of mip maps
// numLevels = 1 + floor(log2(max(w, h, d)))
m_mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max({ m_width, m_height, m_depth }))) + 1);
}
else
{
m_mipLevels = 1u;
}
}
void Texture::_updateArrayLayer()
{
m_arrayLayers = getTexArrayLayers(m_type, m_arrayLength);
}
void Texture::_createImage(Bool32 importContent)
{
vk::ImageType vkImageType;
vkImageType = arrTextureTypeToVKImageType[static_cast<size_t>(m_type)].second;
#ifdef DEBUG
//check whether other arguments is compatibility with texture type.
checkTexImageSize(m_type, m_width, m_height, m_depth);
#endif // DEBUG
//caculate compatible array layer and flag.
vk::ImageCreateFlags flags;
flags |= arrTextureTypeToImageCreateFlags[static_cast<size_t>(m_type)].second;
vk::ImageUsageFlags usage = m_usageFlags;
if (importContent)
usage |= vk::ImageUsageFlagBits::eTransferDst;
ImageInfo info = {
flags,
vkImageType,
m_format,
{
m_width,
m_height,
m_depth
},
m_mipLevels,
m_arrayLayers,
vk::SampleCountFlagBits::e1,
vk::ImageTiling::eOptimal,
usage,
vk::SharingMode::eExclusive,
m_layout,
m_allAspectFlags,
};
m_pImage = std::shared_ptr<Image>{new Image(info)};
}
void Texture::_createImageView()
{
if (m_isCreateDefaultImageView == VG_FALSE) return;
vk::ImageViewType vkImageViewType;
vkImageViewType = arrTextureTypeToVKImageViewType[static_cast<size_t>(m_type)].second;
ImageViewInfo info = {
vk::ImageViewCreateFlags(),
*(m_pImage->getImage()),
vkImageViewType,
m_format,
vk::ComponentMapping(),
{
m_allAspectFlags,
uint32_t(0),
m_mipLevels,
uint32_t(0),
m_arrayLayers,
},
};
m_pImageView = std::shared_ptr<ImageView>{new ImageView(info)};
}
void Texture::_createSampler()
{
if (m_isCreateDefaultSampler == VG_FALSE) return;
SamplerInfo info = {
vk::SamplerCreateFlags(),
vk::Filter::eLinear,
vk::Filter::eLinear,
vk::SamplerMipmapMode::eLinear,
vk::SamplerAddressMode::eClampToEdge,
vk::SamplerAddressMode::eClampToEdge,
vk::SamplerAddressMode::eClampToEdge,
0.0f,
VK_FALSE,
0.0f,
VK_FALSE,
vk::CompareOp::eNever,
0.0f,
static_cast<float>(m_mipLevels),
vk::BorderColor::eFloatTransparentBlack,
VK_FALSE,
};
m_pSampler = std::shared_ptr<Sampler>{new Sampler(info)};
}
void Texture::_applyData(const TextureDataInfo &layoutInfo
, const void *memory
, uint32_t size
, Bool32 cacheMemory
, Bool32 createMipmaps)
{
vk::Image image = *(m_pImage->getImage());
if (cacheMemory)
{
m_components.resize(layoutInfo.componentCount);
memcpy(m_components.data(), layoutInfo.pComponent,
sizeof(TextureDataInfo::Component) * layoutInfo.componentCount);
m_dataLayout = layoutInfo;
m_dataLayout.pComponent = m_components.data();
}
if (m_pMemory != nullptr && (m_memorySize < size || ! cacheMemory)) {
free(m_pMemory);
m_pMemory = nullptr;
m_memorySize = 0;
}
if (size)
{
if (cacheMemory)
{
if (m_pMemory == nullptr)
{
m_pMemory = malloc(size);
m_memorySize = size;
}
memcpy(m_pMemory, memory, size);
m_realSize = size;
}
auto pDevice = pApp->getDevice();
//create staging buffer.
std::shared_ptr<vk::Buffer> pStagingBuffer;
std::shared_ptr<vk::DeviceMemory> pStagingBufferMemory;
_createBuffer(size, vk::BufferUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
pStagingBuffer, pStagingBufferMemory);
void *data = pDevice->mapMemory(*pStagingBufferMemory, 0, size);
memcpy(data, memory, static_cast<size_t>(size));
pDevice->unmapMemory(*pStagingBufferMemory);
auto pCommandBuffer = beginSingleTimeCommands();
if (createMipmaps)
{
//transfer image from initial current image layout to dst layout.
//here use undefined layout not to use curr layout of image, it can clear image old data.
_tranImageLayout(pCommandBuffer, image, m_layout, vk::ImageLayout::eTransferDstOptimal,
0, 1, 0, m_arrayLayers);
//copy the first mip of the chain.
_copyBufferToImage(pCommandBuffer, *pStagingBuffer, image, m_width, m_height, m_depth, 0, 0, m_arrayLayers);
#ifdef DEBUG
//check format.
const auto &pPhysicalDevice = pApp->getPhysicalDevice();
const auto &formatProperties = pPhysicalDevice->getFormatProperties(m_format);
if ((formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eBlitSrc) == vk::FormatFeatureFlags())
{
throw std::runtime_error("The texture format don't support for blit source, mip-chain generation requires it.");
}
if ((formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eBlitDst) == vk::FormatFeatureFlags())
{
throw std::runtime_error("The texture format don't support for blit destination, mip-chain generation requires it.");
}
#endif // DEBUG
//transition first mip level to transfer source for read during blit.
_tranImageLayout(pCommandBuffer, image, vk::ImageLayout::eTransferDstOptimal,
vk::ImageLayout::eTransferSrcOptimal, 0, 1, 0, m_arrayLayers);
for (uint32_t i = 1; i < m_mipLevels; ++i)
{
vk::ImageBlit blit;
blit.srcSubresource.aspectMask = m_allAspectFlags;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = m_arrayLayers;
blit.srcSubresource.mipLevel = i - 1;
blit.dstSubresource.aspectMask = m_allAspectFlags;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = m_arrayLayers;
blit.dstSubresource.mipLevel = i;
// each mipmap is the size divided by two
blit.srcOffsets[1] = vk::Offset3D(caculateImageSizeWithMipmapLevel(m_width, i - 1),
caculateImageSizeWithMipmapLevel(m_height, i - 1),
caculateImageSizeWithMipmapLevel(m_depth, i - 1));
blit.dstOffsets[1] = vk::Offset3D(caculateImageSizeWithMipmapLevel(m_width, i),
caculateImageSizeWithMipmapLevel(m_height, i),
caculateImageSizeWithMipmapLevel(m_depth, i));
// transferDst go to transferSrc because this mipmap will be the source for the next iteration (the next level)
_tranImageLayout(pCommandBuffer, image, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal,
i, 1, 0, m_arrayLayers);
pCommandBuffer->blitImage(image, vk::ImageLayout::eTransferSrcOptimal,
image, vk::ImageLayout::eTransferDstOptimal, blit,
vk::Filter::eLinear);
_tranImageLayout(pCommandBuffer, image, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal,
i, 1, 0, m_arrayLayers);
}
//transfer all level and all layer to shader read layout.
_tranImageLayout(pCommandBuffer, image, vk::ImageLayout::eTransferSrcOptimal, m_layout,
0, m_mipLevels, 0, m_arrayLayers);
}
else
{
const auto pComponent = layoutInfo.pComponent;
const auto componentCount = layoutInfo.componentCount;
std::vector<vk::BufferImageCopy> bufferCopyRegions(componentCount);
uint32_t offset = 0u;
for (uint32_t i = 0u; i < componentCount; ++i)
{
uint32_t width;
uint32_t height;
uint32_t depth;
const auto component = *(layoutInfo.pComponent + i);
if (component.hasImageExtent)
{
width = component.width;
height = component.height;
depth = component.depth;
}
else
{
width = caculateImageSizeWithMipmapLevel(m_width, component.mipLevel);
height = caculateImageSizeWithMipmapLevel(m_height, component.mipLevel);
depth = caculateImageSizeWithMipmapLevel(m_depth, component.mipLevel);
}
vk::ImageSubresourceLayers subresourceLayers = {
m_allAspectFlags, //aspectMask
component.mipLevel, //mipLevel
component.baseArrayLayer, //baseArrayLayer
component.layerCount //layerCount
};
vk::BufferImageCopy copyInfo = {
offset, //bufferOffset
0, //bufferRowLength
0, //bufferImageHeight
subresourceLayers, //imageSubresource
vk::Offset3D(0, 0, 0), //imageOffset
vk::Extent3D(width, height, depth) //imageExtent
};
bufferCopyRegions[i] = copyInfo;
offset += component.size;
}
//transfer image from initial current image layout to dst layout.
//here use undefined layout not to use curr layout of image, it can clear image old data.
_tranImageLayout(pCommandBuffer, image, m_layout, vk::ImageLayout::eTransferDstOptimal,
0, m_mipLevels, 0, m_arrayLayers);
pCommandBuffer->copyBufferToImage(*pStagingBuffer, image, vk::ImageLayout::eTransferDstOptimal, bufferCopyRegions);
//transfer to shader read layout.
_tranImageLayout(pCommandBuffer, image, vk::ImageLayout::eTransferDstOptimal, m_layout,
0, m_mipLevels, 0, m_arrayLayers);
}
endSingleTimeCommands(pCommandBuffer);
}
}
void Texture::_createBuffer(vk::DeviceSize size, vk::BufferUsageFlags usage, vk::MemoryPropertyFlags properties,
std::shared_ptr<vk::Buffer>& pBuffer, std::shared_ptr<vk::DeviceMemory>& pBufferMemory)
{
vk::BufferCreateInfo createInfo = {
vk::BufferCreateFlags(),
size,
usage,
vk::SharingMode::eExclusive
};
auto pDevice = pApp->getDevice();
pBuffer = fd::createBuffer(pDevice, createInfo);
vk::MemoryRequirements memReqs = pDevice->getBufferMemoryRequirements(*pBuffer);
vk::MemoryAllocateInfo allocateInfo = {
memReqs.size,
vg::findMemoryType(pApp->getPhysicalDevice(), memReqs.memoryTypeBits, properties)
};
pBufferMemory = fd::allocateMemory(pDevice, allocateInfo);
pDevice->bindBufferMemory(*pBuffer, *pBufferMemory, 0);
}
void Texture::_tranImageLayout(std::shared_ptr<vk::CommandBuffer> &pCommandBuffer, vk::Image image,
vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
uint32_t baseMipLevel, uint32_t levelCount,
uint32_t baseArrayLayer, uint32_t layerCount)
{
vk::ImageMemoryBarrier barrier = {};
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = m_allAspectFlags;
barrier.subresourceRange.baseMipLevel = baseMipLevel;
barrier.subresourceRange.levelCount = levelCount;
barrier.subresourceRange.baseArrayLayer = baseArrayLayer;
barrier.subresourceRange.layerCount = layerCount;
std::vector<std::tuple<vk::ImageLayout, vk::AccessFlags, vk::PipelineStageFlags>> arrLayoutToAccess = {
std::tuple<vk::ImageLayout, vk::AccessFlags, vk::PipelineStageFlags>(vk::ImageLayout::eUndefined
, vk::AccessFlags()
, vk::PipelineStageFlagBits::eTopOfPipe
)
, std::tuple<vk::ImageLayout, vk::AccessFlags, vk::PipelineStageFlags>(vk::ImageLayout::eTransferDstOptimal
, vk::AccessFlagBits::eTransferWrite
, vk::PipelineStageFlagBits::eTransfer
)
, std::tuple<vk::ImageLayout, vk::AccessFlags, vk::PipelineStageFlags>(vk::ImageLayout::eTransferSrcOptimal
, vk::AccessFlagBits::eTransferRead
, vk::PipelineStageFlagBits::eTransfer
)
, std::tuple<vk::ImageLayout, vk::AccessFlags, vk::PipelineStageFlags>(vk::ImageLayout::eShaderReadOnlyOptimal
, vk::AccessFlagBits::eShaderRead
, vk::PipelineStageFlagBits::eFragmentShader
)
, std::tuple<vk::ImageLayout, vk::AccessFlags, vk::PipelineStageFlags>(vk::ImageLayout::eDepthStencilAttachmentOptimal
, vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite
, vk::PipelineStageFlagBits::eEarlyFragmentTests
)
};
vk::PipelineStageFlags srcStageMask;
vk::PipelineStageFlags dstStageMask;
Bool32 isFindSrc = VG_FALSE;
Bool32 isFindDst = VG_FALSE;
for (const auto& item : arrLayoutToAccess)
{
if (oldLayout == std::get<0>(item))
{
barrier.srcAccessMask = std::get<1>(item);
srcStageMask = std::get<2>(item);
isFindSrc = VG_TRUE;
}
if (newLayout == std::get<0>(item))
{
barrier.dstAccessMask = std::get<1>(item);
dstStageMask = std::get<2>(item);
isFindDst = VG_TRUE;
}
if (isFindSrc && isFindDst)
{
break;
}
}
pCommandBuffer->pipelineBarrier(srcStageMask,
dstStageMask,
vk::DependencyFlags(),
nullptr, nullptr,
barrier);
}
inline uint32_t caculateImageSizeWithMipmapLevel(uint32_t size, uint32_t mipmapLevel)
{
return std::max(1u, size >> mipmapLevel);
}
void Texture::_copyBufferToImage(std::shared_ptr<vk::CommandBuffer> &pCommandBuffer, vk::Buffer buffer, vk::Image image,
uint32_t width, uint32_t height, uint32_t depth, uint32_t mipLevel,
uint32_t baseArrayLayer, uint32_t layerCount)
{
vk::BufferImageCopy copyInfo = { 0, 0, 0, vk::ImageSubresourceLayers(
m_allAspectFlags, mipLevel, baseArrayLayer, layerCount),
vk::Offset3D(0, 0, 0),
vk::Extent3D(width, height, depth)
};
pCommandBuffer->copyBufferToImage(buffer, image, vk::ImageLayout::eTransferDstOptimal, copyInfo);
}
} | 34.386771 | 137 | 0.573729 | [
"vector",
"transform"
] |
6b8bb7bf470f4cc16deb0b5c16563d8eedf59659 | 6,444 | cpp | C++ | python/inode.cpp | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | python/inode.cpp | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | python/inode.cpp | EricKTCheung/dmlite | 7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d | [
"Apache-2.0"
] | null | null | null | /*
* inode.cpp
*
* Python bindings for inode.h from the c++ dmlite library
* via Boost:Python.
*/
#include "pydmlite.h"
#include "inodewrapper.cpp"
void export_inode()
{
class_<IDirectory, boost::noncopyable >("IDirectory", no_init)
;
class_<ExtendedStat, bases< Extensible > >("ExtendedStat", init<>())
.def_readwrite("parent", &ExtendedStat::parent)
.def_readwrite("stat", &ExtendedStat::stat)
.def_readwrite("status", &ExtendedStat::status)
.def_readwrite("name", &ExtendedStat::name)
.def_readwrite("guid", &ExtendedStat::guid)
.def_readwrite("csumtype", &ExtendedStat::csumtype)
.def_readwrite("csumvalue", &ExtendedStat::csumvalue)
.def_readwrite("acl", &ExtendedStat::acl)
;
enum_<ExtendedStat::FileStatus>("FileStatus")
.value("kOnline", ExtendedStat::kOnline)
.value("kMigrated", ExtendedStat::kMigrated)
;
class_<struct stat>("stat", init<>())
.def_readwrite("st_dev", &stat::st_dev)
.def_readwrite("st_ino", &stat::st_ino)
.def_readwrite("st_mode", &stat::st_mode)
.def_readwrite("st_nlink", &stat::st_nlink)
.def_readwrite("st_uid", &stat::st_uid)
.def_readwrite("st_gid", &stat::st_gid)
.def_readwrite("st_rdev", &stat::st_rdev)
.def_readwrite("st_size", &stat::st_size)
.def_readwrite("st_blksize", &stat::st_blksize)
.def_readwrite("st_blocks", &stat::st_blocks)
// The following lines produce a weird error Google doesn't know.
// Thus, getters have been created instead.
//.def_readonly("st_atime", &stat::st_atime)
//.def_readwrite("st_mtime", &stat::st_mtime)
//.def_readwrite("st_ctime", &stat::st_ctime)
.def("getATime", &StatGetATime)
.def("getMTime", &StatGetMTime)
.def("getCTime", &StatGetCTime)
.def("isDir", &StatIsDir)
.def("isReg", &StatIsReg)
.def("isLnk", &StatIsLnk)
;
class_<SymLink, bases< Extensible > >("SymLink", init<>())
.def_readwrite("inode", &SymLink::inode)
.def_readwrite("link", &SymLink::link)
;
class_<Replica, bases< Extensible > >("Replica", init<>())
.def_readwrite("replicaid", &Replica::replicaid)
.def_readwrite("fileid", &Replica::fileid)
.def_readwrite("nbaccesses", &Replica::nbaccesses)
.def_readwrite("atime", &Replica::atime)
.def_readwrite("ptime", &Replica::ptime)
.def_readwrite("ltime", &Replica::ltime)
.def_readwrite("status", &Replica::status)
.def_readwrite("type", &Replica::type)
.def_readwrite("server", &Replica::server)
.def_readwrite("rfn", &Replica::rfn)
;
class_< std::vector< Replica > >("vector_Replica")
.def(vector_indexing_suite< std::vector< Replica > >()) // only works with operator== and != in Replica
;
enum_<Replica::ReplicaStatus>("ReplicaStatus")
.value("kAvailable", Replica::kAvailable)
.value("kBeingPopulated", Replica::kBeingPopulated)
.value("kToBeDeleted", Replica::kToBeDeleted)
;
enum_<Replica::ReplicaType>("ReplicaType")
.value("kVolatile", Replica::kVolatile)
.value("kPermanent", Replica::kPermanent)
;
class_<INodeWrapper, bases< BaseInterface >, boost::noncopyable>("INode", no_init)
.def("begin", boost::python::pure_virtual(&INode::begin))
.def("commit", boost::python::pure_virtual(&INode::commit))
.def("rollback", boost::python::pure_virtual(&INode::rollback))
.def("create", boost::python::pure_virtual(&INode::create))
.def("symlink", boost::python::pure_virtual(&INode::symlink))
.def("unlink", boost::python::pure_virtual(&INode::unlink))
.def("move", boost::python::pure_virtual(&INode::move))
.def("rename", boost::python::pure_virtual(&INode::rename))
.def("extendedStat", boost::python::pure_virtual(static_cast< ExtendedStat (INodeWrapper::*)(ino_t) > (&INode::extendedStat)))
.def("extendedStat", boost::python::pure_virtual(static_cast< ExtendedStat (INodeWrapper::*)(ino_t, const std::string&) > (&INode::extendedStat)))
.def("extendedStat", boost::python::pure_virtual(static_cast< ExtendedStat (INodeWrapper::*)(const std::string&) > (&INode::extendedStat)))
.def("readLink", boost::python::pure_virtual(&INode::readLink))
.def("addReplica", boost::python::pure_virtual(&INode::addReplica))
.def("deleteReplica", boost::python::pure_virtual(&INode::deleteReplica))
.def("getReplica", boost::python::pure_virtual(static_cast< Replica (INodeWrapper::*)(int64_t) > (&INode::getReplica)))
.def("getReplica", boost::python::pure_virtual(static_cast< Replica (INodeWrapper::*)(const std::string&) > (&INode::getReplica)))
.def("updateReplica", boost::python::pure_virtual(&INode::updateReplica))
.def("getReplicas", boost::python::pure_virtual(&INode::getReplicas))
.def("utime", boost::python::pure_virtual(&INode::utime))
.def("setMode", boost::python::pure_virtual(&INode::setMode))
.def("setSize", boost::python::pure_virtual(&INode::setSize))
.def("setChecksum", boost::python::pure_virtual(&INode::setChecksum))
.def("getComment", boost::python::pure_virtual(&INode::getComment))
.def("setComment", boost::python::pure_virtual(&INode::setComment))
.def("deleteComment", boost::python::pure_virtual(&INode::deleteComment))
.def("setGuid", boost::python::pure_virtual(&INode::setGuid))
.def("updateExtendedAttributes", boost::python::pure_virtual(&INode::updateExtendedAttributes))
.def("openDir", boost::python::pure_virtual(&INode::openDir), return_value_policy<manage_new_object>())
.def("closeDir", boost::python::pure_virtual(&INode::closeDir))
.def("readDirx", boost::python::pure_virtual(&INode::readDirx), return_value_policy<reference_existing_object>())
.def("readDir", boost::python::pure_virtual(&INode::readDir), return_value_policy<reference_existing_object>())
;
class_<INodeFactoryWrapper, bases< BaseFactory >, boost::noncopyable>("INodeFactory", no_init)
.def("createINode", boost::python::pure_virtual(&INodeFactoryWrapper::createINode), return_value_policy<manage_new_object>())
;
}
| 48.089552 | 154 | 0.647734 | [
"vector"
] |
6b956def2300a1eafa15b4ab077b017bec02b752 | 27,582 | cpp | C++ | branch/old_angsys/angsys_beta3/source/angsys/angsys.shared/source/strings/string.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta3/source/angsys/angsys.shared/source/strings/string.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta3/source/angsys/angsys.shared/source/strings/string.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "angsys.h"
#include "format_parser.h"
#include "string_factory.h"
using namespace ang;
using namespace ang::text;
ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::text::istring_view, intf);
ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::text::istring, istring_view);
#define MY_TYPE ang::text::istring_view
#include "ang/inline/intf_wrapper_specialization.inl"
#undef MY_TYPE
#define MY_TYPE ang::text::istring
#include "ang/inline/intf_wrapper_specialization.inl"
#undef MY_TYPE
//intf_wrapper<istring>::intf_wrapper(raw_str_t str)
// : m_ptr(null)
//{
// istring_factory_t factory = istring_factory::get_factory(str.encoding());
// if (!factory.is_empty())
// set(factory->create_string(str));
//}
intf_wrapper<istring>::intf_wrapper(raw_cstr_t str)
: m_ptr(null)
{
istring_factory_t factory = istring_factory::get_factory(str.encoding());
if (!factory.is_empty())
set(factory->create_string(str));
}
intf_wrapper<istring>::operator raw_cstr_t()const {
#ifdef _DEBUG
return is_empty() ? raw_cstr() : m_ptr->cstr();
#else
return m_ptr->cstr();
#endif
}
intf_wrapper<istring>::operator istring_view_t()const {
return m_ptr;
}
char32_t intf_wrapper<istring>::operator [](windex i)const {
#ifdef _DEBUG
return is_empty() ? 0 : m_ptr->at(i);
#else
return m_ptr->at(i);
#endif
}
intf_wrapper<istring_view>::operator ang::cstr_t()const {
#ifdef _DEBUG
return is_empty() ? raw_cstr() : m_ptr->cstr();
#else
return m_ptr->cstr();
#endif
}
char32_t intf_wrapper<istring_view>::operator [](windex i)const {
#ifdef _DEBUG
return is_empty() ? 0 : m_ptr->at(i);
#else
return m_ptr->at(i);
#endif
}
ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::text::istring_factory, intf);
#define MY_TYPE ang::text::istring_factory
#include "ang/inline/intf_wrapper_specialization.inl"
#undef MY_TYPE
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::ascii>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::ascii>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::ascii>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::unicode>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::unicode>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::unicode>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf8>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf8>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf8>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf16>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf16>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf16>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf16_se>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf16_se>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf16_se>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf16_le>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf16_le>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf16_le>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf16_be>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf16_be>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf16_be>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf32>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf32>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf32>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf32_se>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf32_se>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf32_se>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf32_le>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf32_le>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf32_le>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_CLASS_INFO(ang::text::string_factory<encoding::utf32_be>, object, istring_factory);
template<> ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::string_factory<encoding::utf32_be>);
template<> ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::string_factory<encoding::utf32_be>, object, istring_factory);
basic_string_buffer_base::basic_string_buffer_base()
{
memset(&m_data, 0, sizeof(m_data));
m_map_index = (wsize)invalid_index;
m_map_size = (wsize)invalid_index;
}
basic_string_buffer_base::~basic_string_buffer_base()
{
m_map_index = (wsize)invalid_index;
m_map_size = (wsize)invalid_index;
//clear();
}
ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::text::basic_string_buffer_base, object, istring, ibuffer);
ANG_IMPLEMENT_OBJECT_RUNTIME_INFO(ang::text::basic_string_buffer_base);
ANG_IMPLEMENT_OBJECT_QUERY_INTERFACE(ang::text::basic_string_buffer_base, object, istring, ibuffer, ibuffer_view);
/////////////////////////////////////////////////////////////////////////
string basic_string_buffer_base::to_string()const
{
return const_cast<istring*>(static_cast<istring const*>(this));
}
string basic_string_buffer_base::to_string(text::text_format_t format)const
{
//TODO:
return const_cast<istring*>(static_cast<istring const*>(this));
}
rtti_t const& basic_string_buffer_base::value_type()const
{
return runtime_info();
}
bool basic_string_buffer_base::set_value(rtti_t const& id, unknown_t ptr)
{
if (id.is_type_of(class_info()))
{
basic_string_buffer_base* str = interface_cast<basic_string_buffer_base>((intf*)ptr);
if (!str)
return false;
copy(str->cstr());
return true;
}
else if (id.is_type_of(type_of<char*>()) || id.is_type_of(type_of<char const*>()))
{
char const* str = reinterpret_cast<char const*>(ptr);
copy(castr_t(str));
return true;
}
else if (id.is_type_of(type_of<mchar*>()) || id.is_type_of(type_of<mchar const*>()))
{
mchar const* str = reinterpret_cast<mchar const*>(ptr);
copy(cmstr_t(str));
return true;
}
else if (id.is_type_of(type_of<wchar*>()) || id.is_type_of(type_of<wchar const*>()))
{
wchar const* str = reinterpret_cast<wchar const*>(ptr);
copy(cwstr_t(str));
return true;
}
else if (id.is_type_of(type_of<char16_t*>()) || id.is_type_of(type_of<char16_t const*>()))
{
char16_t const* str = reinterpret_cast<char16_t const*>(ptr);
copy(cstr16_t(str));
return true;
}
else if (id.is_type_of(type_of<char32_t*>()) || id.is_type_of(type_of<char32_t const*>()))
{
char32_t const* str = reinterpret_cast<char32_t const*>(ptr);
copy(cstr32_t(str));
return true;
}
else if (id.is_type_of(type_of<castr_t>()))
{
castr_t& str = *reinterpret_cast<castr_t*>(ptr);
copy(str);
return true;
}
else if (id.is_type_of(type_of<cwstr_t>()))
{
cwstr_t& str = *reinterpret_cast<cwstr_t*>(ptr);
copy(str);
return true;
}
else if (id.is_type_of(type_of<cmstr_t>()))
{
cmstr_t& str = *reinterpret_cast<cmstr_t*>(ptr);
copy(str);
return true;
}
else if (id.is_type_of(type_of<cstr16_t>()))
{
cstr16_t& str = *reinterpret_cast<cstr16_t*>(ptr);
copy(str);
return true;
}
else if (id.is_type_of(type_of<cstr32_t>()))
{
cstr32_t& str = *reinterpret_cast<cstr32_t*>(ptr);
copy(str);
return true;
}
return false;
}
bool basic_string_buffer_base::get_value(rtti_t const& id, unknown_t ptr)const
{
if (id.is_type_of(class_info()))
{
basic_string_buffer_base* str = interface_cast<basic_string_buffer_base>((intf*)ptr);
if (!str)
return false;
str->copy(cstr());
return true;
}
else if (id.is_type_of<astr_t>())
{
astr_t& dest = *reinterpret_cast<astr_t*>(ptr);
auto src = cstr();
dest.set(dest.str(), iencoder::get_encoder(encoding::ascii)->convert(dest, src, true).count());
return true;
}
else if (id.is_type_of<wstr_t>())
{
wstr_t& dest = *reinterpret_cast<wstr_t*>(ptr);
auto src = cstr();
dest.set(dest.str(), iencoder::get_encoder(encoding::unicode)->convert(dest, src, true).count());
return true;
}
else if (id.is_type_of<mstr_t>())
{
mstr_t& dest = *reinterpret_cast<mstr_t*>(ptr);
auto src = cstr();
dest.set(dest.str(), iencoder::get_encoder(encoding::utf8)->convert(dest, src, true).count());
return true;
}
else if (id.is_type_of<str16_t>())
{
str16_t& dest = *reinterpret_cast<str16_t*>(ptr);
auto src = cstr();
dest.set(dest.str(), iencoder::get_encoder(encoding::utf16)->convert(dest, src, true).count());
return true;
}
else if (id.is_type_of<str32_t>())
{
str32_t& dest = *reinterpret_cast<str32_t*>(ptr);
auto src = cstr();
dest.set(dest.str(), iencoder::get_encoder(encoding::utf32)->convert(dest, src, true).count());
return true;
}
else if (id.is_type_of<raw_str_t>())
{
raw_str_t& dest = *reinterpret_cast<raw_str_t*>(ptr);
auto src = cstr();
dest = iencoder::get_encoder(dest.encoding())->convert(dest, src, true);
return true;
}
else if (id.is_type_of<short>())
{
windex i = 0;
short& value = *reinterpret_cast<short*>(ptr);
auto str = cstr();
value = (short)m_parser->to_signed(str, i);
return i > 0;
}
else if (id.is_type_of<ushort>())
{
windex i = 0;
ushort& value = *reinterpret_cast<ushort*>(ptr);
auto str = cstr();
value = (ushort)m_parser->to_unsigned(str, i);
return i > 0;
}
else if (id.is_type_of<int>())
{
windex i = 0;
int& value = *reinterpret_cast<int*>(ptr);
auto str = cstr();
value = (int)m_parser->to_signed(str, i);
return i > 0;
}
else if (id.is_type_of<uint>())
{
windex i = 0;
uint& value = *reinterpret_cast<uint*>(ptr);
auto str = cstr();
value = (uint)m_parser->to_unsigned(str, i);
return i > 0;
}
else if (id.is_type_of<long>())
{
windex i = 0;
long& value = *reinterpret_cast<long*>(ptr);
auto str = cstr();
value = (int)m_parser->to_signed(str, i);
return i > 0;
}
else if (id.is_type_of<ulong>())
{
windex i = 0;
ulong& value = *reinterpret_cast<ulong*>(ptr);
auto str = cstr();
value = (ulong)m_parser->to_unsigned(str, i);
return i > 0;
}
else if (id.is_type_of<long64>())
{
windex i = 0;
long64& value = *reinterpret_cast<long64*>(ptr);
auto str = cstr();
value = m_parser->to_signed(str, i);
return i > 0;
}
else if (id.is_type_of<ulong64>())
{
windex i = 0;
ulong64& value = *reinterpret_cast<ulong64*>(ptr);
auto str = cstr();
value = m_parser->to_unsigned(str, i);
return i > 0;
}
else if (id.is_type_of<float>())
{
windex i = 0;
float& value = *reinterpret_cast<float*>(ptr);
auto str = cstr();
value = (float)m_parser->to_floating(str, i);
return i > 0;
}
else if (id.is_type_of<double>())
{
windex i = 0;
double& value = *reinterpret_cast<double*>(ptr);
auto str = cstr();
value = m_parser->to_floating(str, i);
return i > 0;
}
return false;
}
pointer basic_string_buffer_base::buffer_ptr()
{
return str().ptr();
}
const_pointer basic_string_buffer_base::buffer_ptr()const
{
return cstr().ptr();
}
wsize basic_string_buffer_base::buffer_size()const
{
return capacity() * m_encoder->char_type().size();
}
wsize basic_string_buffer_base::mem_copy(wsize sz, pointer ptr, text::encoding_t format)
{
//if (format == encoding::binary
// || format == encoding::auto_detect)
// throw exception_t(except_code::unsupported);
auto char_size = m_encoder->char_type().size();
if (m_map_index != invalid_index || m_map_size != invalid_index)
{
copy_at(raw_str(ptr, min(m_map_size, sz) / char_size, format), m_map_index / char_size);
return min(m_map_size, sz);
}
else {
copy(raw_str(ptr, sz / char_size, format));
return length() * char_size;
}
}
ibuffer_view_t basic_string_buffer_base::map_buffer(windex start, wsize size)
{
if (m_map_index != invalid_index || m_map_size != invalid_index)
return null;
if ((start + size) > (capacity() * m_encoder->char_type().size()))
return null;
m_map_index = start;
m_map_size = size;
return this;
}
bool basic_string_buffer_base::unmap_buffer(ibuffer_view_t& view, wsize used)
{
if (view.get() != static_cast<ibuffer_view*>(this))
return false;
length((m_map_index + used) / m_encoder->char_type().size());
view = null;
return true;
}
bool basic_string_buffer_base::can_realloc_buffer()const { return (m_map_index == invalid_index && m_map_size == invalid_index); };
bool basic_string_buffer_base::realloc_buffer(wsize size) { return realloc(size / m_encoder->char_type().size(), true); };
text::encoding_t basic_string_buffer_base::encoding()const
{
return m_encoder->format();
}
rtti_t const& basic_string_buffer_base::char_type()const
{
return m_encoder->char_type();
}
raw_str_t basic_string_buffer_base::str(int) {
auto char_size = m_encoder->char_type().size();
if (m_map_index != invalid_index || m_map_size != invalid_index)
return storage_type_stack == storage_type() ? raw_str((pointer)(m_data.m_stack_buffer + m_map_index), m_map_size, encoding()) : raw_str(((byte*)m_data.m_allocated_buffer) + m_map_index, m_map_size, encoding());
else
return storage_type_stack == storage_type() ? raw_str((pointer)m_data.m_stack_buffer, m_data.m_stack_length * char_size, encoding())
: storage_type_allocated == storage_type() ? raw_str(m_data.m_allocated_buffer, m_data.m_allocated_length * char_size, encoding())
: m_data.m_const_string->str();
}
raw_cstr_t basic_string_buffer_base::cstr(int)const {
auto char_size = m_encoder->char_type().size();
if (m_map_index != invalid_index || m_map_size != invalid_index)
return storage_type_stack == storage_type() ? raw_cstr((pointer)(m_data.m_stack_buffer + m_map_index), m_map_size, encoding()) : raw_cstr(((byte*)m_data.m_allocated_buffer) + m_map_index, m_map_size, encoding());
else
return storage_type_stack == storage_type() ? raw_cstr((pointer)m_data.m_stack_buffer, m_data.m_stack_length * char_size, encoding())
: storage_type_allocated == storage_type() ? raw_cstr(m_data.m_allocated_buffer, m_data.m_allocated_length * char_size, encoding())
: ((basic_const_string_buffer_base const*)m_data.m_const_string)->cstr();
}
/////////////////////////////////////////////////////////////////////////
unknown_str_t basic_string_buffer_base::data()const {
return const_cast<basic_string_buffer_base*>(this)->str(0).ptr();
}
void basic_string_buffer_base::dispose()
{
clear();
}
comparision_result_t basic_string_buffer_base::compare(object const* obj)const
{
istring_t other = interface_cast<istring>(const_cast<object*>(obj));
if (other.is_empty())
return comparision_result::diferent;
return (comparision_result)m_encoder->compare(cstr().ptr(), other->cstr().ptr(), other->encoding());
}
basic_string_buffer_base::storage_type_t basic_string_buffer_base::storage_type()const
{
return m_data.m_storage_type == storage_type_allocated ? storage_type_allocated
: m_data.m_storage_type == storage_type_string_pool ? storage_type_string_pool
: storage_type_stack;
}
void basic_string_buffer_base::length(wsize len)
{
dword end = 0; wsize i = 0;
auto char_size = m_encoder->char_type().size();
if (storage_type_stack == storage_type()) {
len = min(len, RAW_CAPACITY / char_size - 1);
m_data.m_stack_length = len;
m_encoder->set_eos(m_data.m_stack_buffer, len); //set end of string
}
else if (storage_type_allocated == storage_type()) {
len = min(len, m_data.m_allocated_capacity - 1);
m_data.m_allocated_length = len;
m_encoder->set_eos(m_data.m_allocated_buffer, len); //set end of string
}
}
bool basic_string_buffer_base::is_empty()const
{
return (m_data.m_stack_length == 0 || m_data.m_allocated_length == 0) ? true : false;
}
wsize basic_string_buffer_base::length() const
{
if (m_map_index != invalid_index || m_map_size != invalid_index)
return m_map_size;
else
return storage_type_stack == storage_type() ? m_data.m_stack_length
: storage_type_allocated == storage_type() ? m_data.m_allocated_length
: m_data.m_const_string->cstr().count();
}
wsize basic_string_buffer_base::capacity() const
{
if (m_map_index != invalid_index || m_map_size != invalid_index)
return m_map_size;
else
return storage_type_stack == storage_type() ? RAW_CAPACITY / m_encoder->char_type().size() - 1
: storage_type_allocated == storage_type() ? m_data.m_allocated_capacity - 1
: 0;//No capacity to write // m_data.m_const_string->cstr().count();
}
void basic_string_buffer_base::set(basic_const_string_buffer_base* ptr)
{
clear();
if (ptr != null && encoding() == ptr->encoding())
{
m_data.m_storage_type = storage_type_string_pool;
m_data.m_const_string = ptr;
m_data.m_const_string->add_ref();
m_data.m_const_string_view = ptr->str().ptr();
}
}
void basic_string_buffer_base::copy(raw_cstr_t str)
{
wsize sz = (encoding()==str.encoding()?str.count() : m_encoder->size(str.ptr(), str.encoding())), j = 0;
wsize cs = text::encoder<encoding::auto_detect>::char_size_by_encoding(encoding());
if (sz == 0U)
return;
if (sz < (RAW_CAPACITY / cs))
{
clear();
m_encoder->convert(ang::str_t(m_data.m_stack_buffer, RAW_CAPACITY, encoding()), m_data.m_stack_length, str, j, true);
}
else
{
realloc(sz, false);
m_encoder->convert(ang::str_t(m_data.m_allocated_buffer, m_data.m_allocated_capacity * cs, encoding()), m_data.m_allocated_length, str, j, true);
}
}
void basic_string_buffer_base::concat(raw_cstr_t str)
{
wsize sz = (encoding() == str.encoding() ? str.count() : m_encoder->size(str.ptr(), str.encoding())), j = 0;
if (sz == 0U)
return;
wsize cs = text::encoder<encoding::auto_detect>::char_size_by_encoding(encoding());
wsize my_len = length();
realloc(my_len + sz, true);
if (storage_type_stack == storage_type())
{
m_encoder->convert(ang::str_t(m_data.m_stack_buffer, RAW_CAPACITY, encoding()), m_data.m_stack_length, str, j, true);
}
else if (storage_type_allocated == storage_type())
{
m_encoder->convert(ang::str_t(m_data.m_allocated_buffer, m_data.m_allocated_capacity * cs, encoding()), m_data.m_allocated_length, str, j, true);
}
else
{
basic_const_string_buffer_base* _const_string = m_data.m_const_string;
auto txt = _const_string->cstr();
memset(&m_data, 0, sizeof(m_data));
realloc(txt.count() + str.count());
copy(txt);
concat(str);
_const_string->release();
}
}
void basic_string_buffer_base::copy_at(raw_str_t str, windex at)
{
wsize sz = (encoding() == str.encoding() ? str.count() : m_encoder->size(str.ptr(), str.encoding())), j = 0;
if (sz == 0U)
return;
wsize cs = text::encoder<encoding::auto_detect>::char_size_by_encoding(encoding());
wsize my_len = min(length(), at);
realloc(my_len + sz, true);
if (storage_type_stack == storage_type())
{
m_data.m_stack_length = my_len;
m_encoder->convert(ang::str_t(m_data.m_stack_buffer, RAW_CAPACITY, encoding()), m_data.m_stack_length, str, j, true);
}
else if (storage_type_allocated == storage_type())
{
m_data.m_allocated_length = my_len;
m_encoder->convert(ang::str_t(m_data.m_allocated_buffer, m_data.m_allocated_capacity * cs, encoding()), m_data.m_allocated_length, str, j, true);
}
else
{
basic_const_string_buffer_base* _const_string = m_data.m_const_string;
auto txt = _const_string->cstr();
memset(&m_data, 0, sizeof(m_data));
realloc(txt.count() + str.count());
copy(txt);
copy_at(str, at);
_const_string->release();
}
}
void basic_string_buffer_base::insert(windex at, raw_cstr_t str)
{
wsize my_len = length();
if (at > my_len)
{
concat(str);
return;
}
wsize sz = (encoding() == str.encoding() ? str.count() : m_encoder->size(str.ptr(), str.encoding())), k = 0, j = 0, i = 0;
if (sz == 0U)
return;
wsize cs = text::encoder<encoding::auto_detect>::char_size_by_encoding(encoding());
if ((my_len + sz) < capacity())
{
if (storage_type() == storage_type_t::storage_type_stack)
{
switch (cs)
{
case 1: for (i = my_len; i >= at; i--)
*((byte*)m_data.m_stack_buffer + i + sz) = *((byte*)m_data.m_stack_buffer + i);
break;
case 2: for (i = my_len; i >= at; i--)
*((word*)m_data.m_stack_buffer + i + sz) = *((word*)m_data.m_stack_buffer + i);
break;
case 4: for (i = my_len; i >= at; i--)
*((dword*)m_data.m_stack_buffer + i + sz) = *((dword*)m_data.m_stack_buffer + i);
break;
}
m_data.m_stack_length = at;
m_encoder->convert(ang::str_t(m_data.m_stack_buffer, RAW_CAPACITY, encoding()), m_data.m_stack_length, str, j, false);
m_data.m_stack_length = my_len + sz;
}
else
{
switch (cs)
{
case 1: for (i = my_len; i >= at; i--)
*((byte*)m_data.m_allocated_buffer + i + sz) = *((byte*)m_data.m_allocated_buffer + i);
break;
case 2: for (i = my_len; i >= at; i--)
*((word*)m_data.m_allocated_buffer + i + sz) = *((word*)m_data.m_allocated_buffer + i);
break;
case 4: for (i = my_len; i >= at; i--)
*((dword*)m_data.m_allocated_buffer + i + sz) = *((dword*)m_data.m_allocated_buffer + i);
break;
}
m_data.m_allocated_length = at;
m_encoder->convert(ang::str_t(m_data.m_allocated_buffer, m_data.m_allocated_capacity * cs, encoding()), m_data.m_allocated_length, str, j, false);
m_data.m_allocated_length = my_len + sz;
}
}
else
{
raw_cstr_t my_data = cstr();
raw_str_t new_data = alloc(my_len + sz);
m_encoder->convert(new_data, i, raw_cstr(my_data.ptr(), at * cs, my_data.encoding()), j, false);
m_encoder->convert(new_data, i, str, k, false);
m_encoder->convert(new_data, i, my_data, j, true);
clear();
m_data.m_allocated_length = i;
m_data.m_allocated_capacity = new_data.size() / cs;
m_data.m_allocated_buffer = new_data.ptr();
m_data.m_storage_type = storage_type_allocated;
}
}
void basic_string_buffer_base::format(raw_cstr_t cstr, var_args_t args)
{
int a;
text::text_format_flags_t f;
iencoder_t encoder = iencoder::get_encoder(cstr.encoding());
iparser_t parser = iparser::get_parser(cstr.encoding());
wsize i = 0, t = 0, n = 0, l = 0, cs = encoder->char_type().size();
clear();
while (char32_t c = encoder->to_char32(cstr.ptr(), i))
{
if (c == U'{') {
f.value = parser->parse(cstr, n, a).format_flags();
if (a > -1 && a < (long64)args->size()) {
concat(raw_cstr(&((byte*)cstr.ptr())[l * cs], (t - l) *cs, cstr.encoding()));
concat(f.value ? (raw_cstr_t)args[a]->to_string(f) : (raw_cstr_t)args[a]->to_string());
i = l = n;
}
}
t = n = i;
}
concat(raw_cstr(&((byte*)cstr.ptr())[l * cs], (i - l) * cs, cstr.encoding()));
}
void basic_string_buffer_base::concat_format(raw_cstr_t cstr, var_args_t args)
{
int a;
text::text_format_flags_t f;
iencoder_t encoder = iencoder::get_encoder(cstr.encoding());
iparser_t parser = iparser::get_parser(cstr.encoding());
wsize i = 0, t = 0, n = 0, l = 0, cs = encoder->char_type().size();
//clear();
while (char32_t c = encoder->to_char32(cstr.ptr(), i))
{
if (c == U'{') {
f.value = parser->parse(cstr, n, a).format_flags();
if (a > -1 && a < (long64)args->size()) {
concat(raw_cstr(&((byte*)cstr.ptr())[l * cs], (t - l) *cs, cstr.encoding()));
concat(f.value ? (raw_cstr_t)args[a]->to_string(f) : (raw_cstr_t)args[a]->to_string());
i = l = n;
}
}
t = n = i;
}
concat(raw_cstr(&((byte*)cstr.ptr())[l * cs], (i - l) * cs, cstr.encoding()));
}
void basic_string_buffer_base::insert_format(windex, raw_cstr_t, var_args_t)
{
}
char32_t basic_string_buffer_base::at(windex i, wsize* sz)const
{
windex idx = i;
char32_t c = m_encoder->to_char32(data(), idx, true);
if (sz) *sz = idx - i;
return c;
}
int basic_string_buffer_base::compare(raw_cstr_t str)const
{
return m_encoder->compare(cstr().ptr(), str.ptr(), str.encoding());
}
windex basic_string_buffer_base::compare_until(raw_cstr_t str)const
{
return m_encoder->compare_until(cstr().ptr(), str.ptr(), str.encoding());
}
windex basic_string_buffer_base::find(raw_cstr_t str, windex start, windex end)const
{
auto my_data = cstr();
return m_encoder->find(raw_cstr(my_data.ptr(), min(my_data.count(), end), my_data.encoding()), str, start);
}
windex basic_string_buffer_base::find_reverse(raw_cstr_t str, windex start, windex end)const
{
auto my_data = cstr();
return m_encoder->find_reverse(raw_cstr(my_data.ptr(), min(my_data.count(), end), my_data.encoding()), str, start);
}
istring_t basic_string_buffer_base::sub_string(istring_ptr_t out, windex start, windex end)const
{
if (start >= end || start > length())
return null;
istring_t str = istring_factory::get_factory(encoding())->create_string();
if (!out.is_empty())
*out = str;
end = min(end, length());
auto encoder = iencoder::get_encoder(str->encoding());
auto my_data = cstr();
wsize cs = encoder->char_type().size();
raw_cstr_t raw = raw_cstr((byte*)my_data.ptr() + start * cs, cs * (end - start), encoder->format());
str->copy(raw);
return str;
}
collections::ienum_ptr<istring_t> basic_string_buffer_base::split(raw_cstr_t val)const
{
collections::vector<istring_t> list;
windex beg = 0, end = 0;
istring_t _word;
raw_cstr_t data = cstr();
wsize l = length(), c = val.count();
end = m_encoder->find(data, val, 0);
if (end == invalid_index)
return list.get();
do {
if (sub_string(&_word, beg, end) > 0)
{
list += _word;
_word = null;
}
beg = end + val.size();
end = m_encoder->find(data, val, beg);
} while (end != invalid_index);
if (sub_string(&_word, beg, l) > 0)
{
list += _word;
_word = null;
}
return list.get();
}
///////////////////////////////////////////////////////////////////////////////////
#define MY_ALLOCATOR ang::memory::buffer_allocator
#define MY_ENCODING ang::text::encoding::ascii
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::unicode
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf8
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16_se
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16_le
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16_be
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32_se
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32_le
#include "inline/string.inl"
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32_be
#include "inline/string.inl"
#undef MY_ENCODING
| 32.072093 | 214 | 0.712421 | [
"object",
"vector"
] |
6b968760d90bde033c6f796deaa838a6e76af814 | 8,505 | cc | C++ | iree/hal/vulkan/dynamic_symbols.cc | aniket-daphale/iree | 6fdbbf8656a20a5ce00c465bef99c01c16e33409 | [
"Apache-2.0"
] | 1 | 2020-08-16T17:38:33.000Z | 2020-08-16T17:38:33.000Z | iree/hal/vulkan/dynamic_symbols.cc | aniket-daphale/iree | 6fdbbf8656a20a5ce00c465bef99c01c16e33409 | [
"Apache-2.0"
] | null | null | null | iree/hal/vulkan/dynamic_symbols.cc | aniket-daphale/iree | 6fdbbf8656a20a5ce00c465bef99c01c16e33409 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/hal/vulkan/dynamic_symbols.h"
#include <cstddef>
#include "absl/base/attributes.h"
#include "absl/base/macros.h"
#include "absl/memory/memory.h"
#include "iree/base/source_location.h"
#include "iree/base/status.h"
#include "iree/base/target_platform.h"
#include "iree/base/tracing.h"
#include "iree/hal/vulkan/dynamic_symbol_tables.h"
#if defined(IREE_PLATFORM_WINDOWS)
#include <windows.h>
#else
#include <dlfcn.h>
#endif // IREE_PLATFORM_WINDOWS
namespace iree {
namespace hal {
namespace vulkan {
// Read-only table of function pointer information designed to be in .rdata.
// To reduce binary size this structure is packed (knowing that we won't have
// gigabytes of function pointers :).
struct FunctionPtrInfo {
// Name of the function (like 'vkSomeFunction').
const char* function_name;
// 1 if the function pointer can be resolved via vkGetDeviceProcAddr.
uint32_t is_device : 1;
// 1 if the function is required and the loader should bail if not found.
uint32_t is_required : 1;
// TODO(benvanik): remove from table by manually walking sizeof(uintptr_t).
// An offset in bytes from the base of &syms to where the PFN_vkSomeFunction
// member is located.
uint32_t member_offset : 30;
} ABSL_ATTRIBUTE_PACKED;
namespace {
#define REQUIRED_PFN_FUNCTION_PTR(function_name, is_device) \
{#function_name, is_device, 1, offsetof(DynamicSymbols, function_name)},
#define OPTIONAL_PFN_FUNCTION_PTR(function_name, is_device) \
{#function_name, is_device, 0, offsetof(DynamicSymbols, function_name)},
#define EXCLUDED_PFN_FUNCTION_PTR(function_name, is_device)
#define INS_PFN_FUNCTION_PTR(requirement, function_name) \
requirement##_PFN_FUNCTION_PTR(function_name, 0)
#define DEV_PFN_FUNCTION_PTR(requirement, function_name) \
requirement##_PFN_FUNCTION_PTR(function_name, 1)
// Defines the table of mandatory FunctionPtrInfos resolved prior to instance
// creation. These are safe to call with no instance parameter and should be
// exported by all loaders/ICDs.
static constexpr const FunctionPtrInfo kInstancelessFunctionPtrInfos[] = {
REQUIRED_PFN_FUNCTION_PTR(vkCreateInstance, false) //
REQUIRED_PFN_FUNCTION_PTR(vkEnumerateInstanceLayerProperties, false) //
REQUIRED_PFN_FUNCTION_PTR(vkEnumerateInstanceExtensionProperties, false) //
};
// Defines the table of FunctionPtrInfos for dynamic loading that must wait
// until an instance has been created to be resolved.
static constexpr const FunctionPtrInfo kDynamicFunctionPtrInfos[] = {
IREE_VULKAN_DYNAMIC_SYMBOL_TABLES(INS_PFN_FUNCTION_PTR,
DEV_PFN_FUNCTION_PTR)};
} // namespace
// static
StatusOr<ref_ptr<DynamicSymbols>> DynamicSymbols::Create(
const GetProcAddrFn& get_proc_addr) {
IREE_TRACE_SCOPE0("DynamicSymbols::Create");
auto syms = make_ref<DynamicSymbols>();
// Resolve the method the shared object uses to resolve other functions.
// Some libraries will export all symbols while others will only export this
// single function.
syms->vkGetInstanceProcAddr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(
get_proc_addr("vkGetInstanceProcAddr"));
if (!syms->vkGetInstanceProcAddr) {
return UnavailableErrorBuilder(IREE_LOC)
<< "Required method vkGetInstanceProcAddr not "
"found in provided Vulkan library (did you pick the wrong file?)";
}
// Resolve the mandatory functions that we need to create instances.
// If the provided |get_proc_addr| cannot resolve these then it's not a loader
// or ICD we want to use, anyway.
for (int i = 0; i < ABSL_ARRAYSIZE(kInstancelessFunctionPtrInfos); ++i) {
const auto& function_ptr = kInstancelessFunctionPtrInfos[i];
auto* member_ptr = reinterpret_cast<PFN_vkVoidFunction*>(
reinterpret_cast<uint8_t*>(syms.get()) + function_ptr.member_offset);
*member_ptr =
syms->vkGetInstanceProcAddr(VK_NULL_HANDLE, function_ptr.function_name);
if (*member_ptr == nullptr) {
return UnavailableErrorBuilder(IREE_LOC)
<< "Mandatory Vulkan function " << function_ptr.function_name
<< " not available; invalid loader/ICD?";
}
}
return syms;
}
// static
StatusOr<ref_ptr<DynamicSymbols>> DynamicSymbols::CreateFromSystemLoader() {
IREE_TRACE_SCOPE0("DynamicSymbols::CreateFromSystemLoader");
// NOTE: we could factor this out into base, but this is the only place we use
// it right now so it's fine.
#if defined(IREE_PLATFORM_WINDOWS)
HMODULE library = ::LoadLibraryA("vulkan-1.dll");
if (!library) {
return UnavailableErrorBuilder(IREE_LOC)
<< "Unable to open vulkan-1.dll; driver not installed/on PATH";
}
ASSIGN_OR_RETURN(auto syms, Create([library](const char* function_name) {
return reinterpret_cast<PFN_vkVoidFunction>(
::GetProcAddress(library, function_name));
}));
syms->close_fn_ = [library]() {
// TODO(benvanik): disable if we want to get profiling results. Sometimes
// closing the library can prevent proper symbolization on crashes or
// in sampling profilers.
::FreeLibrary(library);
};
return syms;
#else
void* library = ::dlopen("libvulkan.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!library) {
return UnavailableErrorBuilder(IREE_LOC)
<< "Unable to open libvulkan.so; driver not installed/on "
"LD_LIBRARY_PATH";
}
ASSIGN_OR_RETURN(auto syms, Create([library](const char* function_name) {
return reinterpret_cast<PFN_vkVoidFunction>(
::dlsym(library, function_name));
}));
syms->close_fn_ = [library]() {
// TODO(benvanik): disable if we want to get profiling results. Sometimes
// closing the library can prevent proper symbolization on crashes or
// in sampling profilers.
::dlclose(library);
};
return syms;
#endif // IREE_PLATFORM_WINDOWS
}
Status DynamicSymbols::LoadFromInstance(VkInstance instance) {
IREE_TRACE_SCOPE0("DynamicSymbols::LoadFromInstance");
return LoadFromDevice(instance, VK_NULL_HANDLE);
}
Status DynamicSymbols::LoadFromDevice(VkInstance instance, VkDevice device) {
IREE_TRACE_SCOPE0("DynamicSymbols::LoadFromDevice");
if (!instance) {
return InvalidArgumentErrorBuilder(IREE_LOC)
<< "Instance must have been created and a default instance proc "
"lookup function is required";
}
// Setup the lookup methods first. The rest of the syms uses these to
// resolve function pointers.
this->vkGetDeviceProcAddr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
this->vkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
if (!this->vkGetDeviceProcAddr) {
return UnavailableErrorBuilder(IREE_LOC)
<< "Required Vulkan function vkGetDeviceProcAddr not available; "
"invalid driver handle?";
}
// Load the rest of the functions.
for (int i = 0; i < ABSL_ARRAYSIZE(kDynamicFunctionPtrInfos); ++i) {
const auto& function_ptr = kDynamicFunctionPtrInfos[i];
auto* member_ptr = reinterpret_cast<PFN_vkVoidFunction*>(
reinterpret_cast<uint8_t*>(this) + function_ptr.member_offset);
if (function_ptr.is_device && device) {
*member_ptr =
this->vkGetDeviceProcAddr(device, function_ptr.function_name);
} else {
*member_ptr =
this->vkGetInstanceProcAddr(instance, function_ptr.function_name);
}
if (*member_ptr == nullptr && function_ptr.is_required) {
return UnavailableErrorBuilder(IREE_LOC)
<< "Required Vulkan function " << function_ptr.function_name
<< " not available";
}
}
return OkStatus();
}
DynamicSymbols::DynamicSymbols() = default;
DynamicSymbols::~DynamicSymbols() {
if (close_fn_) {
close_fn_();
}
}
} // namespace vulkan
} // namespace hal
} // namespace iree
| 38.484163 | 80 | 0.718636 | [
"object"
] |
6b9b0b794432ad766d8a48072338f48806e58809 | 1,832 | cc | C++ | cpp/PalindromePartitioning2.cc | speedfirst/leetcode | a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51 | [
"BSD-3-Clause"
] | null | null | null | cpp/PalindromePartitioning2.cc | speedfirst/leetcode | a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51 | [
"BSD-3-Clause"
] | null | null | null | cpp/PalindromePartitioning2.cc | speedfirst/leetcode | a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51 | [
"BSD-3-Clause"
] | null | null | null | namepsace PalindromePartitioning2 {
class Solution {
public:
// This is a double dp solution.
// The first dp is to calculate the min cuts. dp[i] = min(dp[j + 1] + 1), given i <= j < n
// The second dp is to calculate whether a sub string s[i, j] is a palindrome.
// p[i][j] == p[i + 1][j - 1] && s[i] == s[j]
//
// I tried model the first solution with a 2D dp, but get TIME LIMIT EXCEEDED error
int minCut(string s) {
if (s.empty() || s.size() == 1) {
return 0;
}
int n = s.size();
// dp[i] is the min cuts of sub-string s[i, n)
vector<int> dp(s.size() + 1);
for (int i = 0; i <= n; i++) {
// assume the min cuts is to cut the sub string to single characters
// so dp[n - 1] = 0, dp[n - 2] = 1, ...
// dp[n] is special, we set it to -1. This is real important because
// our dp formula is dp[i] = min(dp[j + 1] + 1). When the whole string
// is a palindrome, we will get dp[i] = dp[n] + 1. And here dp[i] should
// be 0!
dp[i] = n - i - 1;
}
// p[i][j] indicates whether sub-string s[i, j] is a palindrome
vector<vector<bool> > p(s.size(), vector<bool>(s.size(), false));
// scan from the end of string to beginning
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 2 || p[i + 1][j - 1])) {
// s[i, j] is panlindrome
p[i][j] = true;
// so we cut from s[i, j] and s[j + 1, n)
dp[i] = min(dp[i], dp[j + 1] + 1);
}
}
}
return dp[0];
}
};
} | 38.978723 | 95 | 0.433952 | [
"vector",
"model"
] |
6ba1d895f3dd2bf6f22c2e3e6a6d695d75e8d0c8 | 22,366 | cpp | C++ | src/ExtraEventHandlers.cpp | clearly-broken-software/dpf-nanovg-widgets | ddc82f8868b05c403c19c03a5bd13374acb51cc5 | [
"0BSD"
] | 2 | 2021-12-30T17:20:26.000Z | 2021-12-31T02:18:28.000Z | src/ExtraEventHandlers.cpp | clearly-broken-software/dpf-nanovg-widgets | ddc82f8868b05c403c19c03a5bd13374acb51cc5 | [
"0BSD"
] | null | null | null | src/ExtraEventHandlers.cpp | clearly-broken-software/dpf-nanovg-widgets | ddc82f8868b05c403c19c03a5bd13374acb51cc5 | [
"0BSD"
] | null | null | null | /*
* Copyright (C) 2021 Filipe Coelho <falktx@falktx.com>, Rob van den Berg <rghvdberg at gmail dot com
* SPDX-License-Identifier: ISC
*/
#include "ExtraEventHandlers.hpp"
#include "SubWidget.hpp"
START_NAMESPACE_DGL
// --------------------------------------------------------------------------------------------------------------------
struct SwitchEventHandler::PrivateData
{
SwitchEventHandler *const self;
SubWidget *const widget;
SwitchEventHandler::Callback *callback;
bool isDown;
PrivateData(SwitchEventHandler *const s, SubWidget *const w)
: self(s),
widget(w),
isDown(false),
callback(nullptr)
{
}
PrivateData(SwitchEventHandler *const s, SubWidget *const w, PrivateData *const other)
: self(s),
widget(w),
callback(other->callback),
isDown(other->isDown)
{
}
void assignFrom(PrivateData *const other)
{
callback = other->callback;
isDown = other->isDown;
}
bool mouseEvent(const Widget::MouseEvent &ev)
{
if (ev.press && widget->contains(ev.pos))
{
isDown = !isDown;
widget->repaint();
if (callback != nullptr)
{
try
{
callback->switchClicked(widget, isDown);
}
DISTRHO_SAFE_EXCEPTION("SwitchEventHandler::mouseEvent");
}
return true;
}
return false;
}
void setDown(const bool down) noexcept
{
isDown = down;
widget->repaint();
}
};
// --------------------------------------------------------------------------------------------------------------------
SwitchEventHandler::SwitchEventHandler(SubWidget *const self)
: pData(new PrivateData(this, self)) {}
SwitchEventHandler::SwitchEventHandler(SubWidget *const self, const SwitchEventHandler &other)
: pData(new PrivateData(this, self, other.pData)) {}
SwitchEventHandler &SwitchEventHandler::operator=(const SwitchEventHandler &other)
{
pData->assignFrom(other.pData);
return *this;
}
SwitchEventHandler::~SwitchEventHandler()
{
delete pData;
}
void SwitchEventHandler::setCallback(Callback *const callback) noexcept
{
pData->callback = callback;
}
bool SwitchEventHandler::mouseEvent(const Widget::MouseEvent &ev)
{
return pData->mouseEvent(ev);
}
bool SwitchEventHandler::isDown() const noexcept
{
return pData->isDown;
}
void SwitchEventHandler::setDown(const bool down) noexcept
{
return pData->setDown(down);
}
// --------------------------------------------------------------------------------------------------------------------
// begin slider
struct SliderEventHandler::PrivateData
{
SliderEventHandler *const self;
SubWidget *const widget;
SliderEventHandler::Callback *callback;
float minimum;
float maximum;
float step;
float value;
float valueDef;
float valueTmp;
bool usingDefault;
bool usingLog;
bool dragging;
bool inverted;
bool valueIsSet;
double startedX;
double startedY;
Point<int> startPos;
Point<int> endPos;
Rectangle<double> sliderArea;
PrivateData(SliderEventHandler *const s, SubWidget *const w)
: self(s),
widget(w),
callback(nullptr),
minimum(0.0f),
maximum(1.0f),
step(0.0f),
value(0.5f),
valueDef(value),
valueTmp(value),
usingDefault(false),
usingLog(false),
dragging(false),
inverted(false),
valueIsSet(false),
startedX(0.0),
startedY(0.0),
startPos(),
endPos(),
sliderArea()
{
}
PrivateData(SliderEventHandler *const s, SubWidget *const w, PrivateData *const other)
: self(s),
widget(w),
callback(other->callback),
minimum(other->minimum),
maximum(other->maximum),
step(other->step),
value(other->value),
valueDef(other->valueDef),
valueTmp(value),
usingDefault(other->usingDefault),
usingLog(other->usingDefault),
startPos(other->startPos),
endPos(other->endPos),
dragging(false),
inverted(other->inverted),
valueIsSet(false),
sliderArea(other->sliderArea)
{
}
void assignFrom(PrivateData *const other)
{
callback = other->callback;
minimum = other->minimum;
maximum = other->maximum;
step = other->step;
value = other->value;
valueDef = other->valueDef;
valueTmp = value;
usingDefault = other->usingDefault;
usingLog = other->usingLog;
}
inline float logscale(const float v) const
{
const float b = std::log(maximum / minimum) / (maximum - minimum);
const float a = maximum / std::exp(maximum * b);
return a * std::exp(b * v);
}
inline float invlogscale(const float v) const
{
const float b = std::log(maximum / minimum) / (maximum - minimum);
const float a = maximum / std::exp(maximum * b);
return std::log(v / a) / b;
}
bool mouseEvent(const Widget::MouseEvent &ev)
{
if (ev.button != 1)
return false;
if (ev.press)
{
if (!sliderArea.contains(ev.pos))
return false;
if ((ev.mod & kModifierShift) != 0 && usingDefault)
{
setValue(valueDef, true);
valueTmp = value;
return true;
}
float vper;
const double x = ev.pos.getX();
const double y = ev.pos.getY();
if (startPos.getY() == endPos.getY())
{
// horizontal
vper = float(x - sliderArea.getX()) / float(sliderArea.getWidth());
}
else
{
// vertical
vper = float(y - sliderArea.getY()) / float(sliderArea.getHeight());
}
float value;
if (inverted)
value = maximum - vper * (maximum - minimum);
else
value = minimum + vper * (maximum - minimum);
if (value < minimum)
{
valueTmp = value = minimum;
}
else if (value > maximum)
{
valueTmp = value = maximum;
}
else if (d_isNotZero(step))
{
valueTmp = value;
const float rest = std::fmod(value, step);
value = value - rest + (rest > step / 2.0f ? step : 0.0f);
}
dragging = true;
startedX = x;
startedY = y;
if (callback != nullptr)
callback->sliderDragStarted(widget);
setValue(value, true);
return true;
}
else if (dragging)
{
if (callback != nullptr)
callback->sliderDragFinished(widget);
dragging = false;
return true;
}
return false;
}
bool motionEvent(const Widget::MotionEvent &ev)
{
if (!dragging)
return false;
const bool horizontal = startPos.getY() == endPos.getY();
const double x = ev.pos.getX();
const double y = ev.pos.getY();
if ((horizontal && sliderArea.containsX(x)) || (sliderArea.containsY(y) && !horizontal))
{
float vper;
if (horizontal)
{
// horizontal
vper = float(x - sliderArea.getX()) / float(sliderArea.getWidth());
}
else
{
// vertical
vper = float(y - sliderArea.getY()) / float(sliderArea.getHeight());
}
float value;
if (inverted)
value = maximum - vper * (maximum - minimum);
else
value = minimum + vper * (maximum - minimum);
if (value < minimum)
{
valueTmp = value = minimum;
}
else if (value > maximum)
{
valueTmp = value = maximum;
}
else if (d_isNotZero(step))
{
valueTmp = value;
const float rest = std::fmod(value, step);
value = value - rest + (rest > step / 2.0f ? step : 0.0f);
}
setValue(value, true);
}
else if (horizontal)
{
if (x < sliderArea.getX())
setValue(inverted ? maximum : minimum, true);
else
setValue(inverted ? minimum : maximum, true);
}
else
{
if (y < sliderArea.getY())
setValue(inverted ? maximum : minimum, true);
else
setValue(inverted ? minimum : maximum, true);
}
return true;
}
bool scrollEvent(const Widget::ScrollEvent &ev)
{
printf("scroll event\n");
return false;
}
float getNormalizedValue() const noexcept
{
const float diff = maximum - minimum;
return ((usingLog ? invlogscale(value) : value) - minimum) / diff;
}
void setRange(const float min, const float max) noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(max > min, );
if (value < min)
{
valueTmp = value = min;
widget->repaint();
}
else if (value > max)
{
valueTmp = value = max;
widget->repaint();
}
minimum = min;
maximum = max;
}
bool setValue(const float value2, const bool sendCallback)
{
if (d_isEqual(value, value2))
return false;
valueTmp = value = value2;
widget->repaint();
if (sendCallback && callback != nullptr)
{
try
{
callback->sliderValueChanged(widget, value);
}
DISTRHO_SAFE_EXCEPTION("SliderEventHandler::setValue");
}
return true;
}
void setInverted(bool inv) noexcept
{
if (inverted == inv)
return;
inverted = inv;
widget->repaint();
}
};
// --------------------------------------------------------------------------------------------------------------------
SliderEventHandler::SliderEventHandler(SubWidget *const self)
: pData(new PrivateData(this, self)) {}
SliderEventHandler::SliderEventHandler(SubWidget *const self, const SliderEventHandler &other)
: pData(new PrivateData(this, self, other.pData)) {}
SliderEventHandler &SliderEventHandler::operator=(const SliderEventHandler &other)
{
pData->assignFrom(other.pData);
return *this;
}
SliderEventHandler::~SliderEventHandler()
{
delete pData;
}
float SliderEventHandler::getValue() const noexcept
{
return pData->value;
}
bool SliderEventHandler::setValue(const float value, const bool sendCallback) noexcept
{
return pData->setValue(value, sendCallback);
}
float SliderEventHandler::getNormalizedValue() const noexcept
{
return pData->getNormalizedValue();
}
void SliderEventHandler::setDefault(const float def) noexcept
{
pData->valueDef = def;
pData->usingDefault = true;
}
void SliderEventHandler::setSliderArea(const double x, const double y,
const double w, const double h) noexcept
{
pData->sliderArea = Rectangle<double>(x, y, w, h);
}
void SliderEventHandler::setRange(const float min, const float max) noexcept
{
pData->setRange(min, max);
}
void SliderEventHandler::setStep(const float step) noexcept
{
pData->step = step;
}
void SliderEventHandler::setUsingLogScale(const bool yesNo) noexcept
{
pData->usingLog = yesNo;
}
void SliderEventHandler::setStartPos(const int x, const int y) noexcept
{
pData->startPos = Point<int>(x, y);
}
void SliderEventHandler::setEndPos(const int x, const int y) noexcept
{
pData->endPos = Point<int>(x, y);
}
void SliderEventHandler::setInverted(const bool inv) noexcept
{
pData->setInverted(inv);
}
bool SliderEventHandler::isInverted() noexcept
{
return pData->inverted;
}
void SliderEventHandler::setCallback(Callback *const callback) noexcept
{
pData->callback = callback;
}
bool SliderEventHandler::mouseEvent(const Widget::MouseEvent &ev)
{
return pData->mouseEvent(ev);
}
bool SliderEventHandler::motionEvent(const Widget::MotionEvent &ev)
{
return pData->motionEvent(ev);
}
bool SliderEventHandler::scrollEvent(const Widget::ScrollEvent &ev)
{
return pData->scrollEvent(ev);
}
// end slider
// --------------------------------------------------------------------------------------------------------------------
// begin spinner
struct SpinnerEventHandler::PrivateData
{
SpinnerEventHandler *const self;
SubWidget *const widget;
SpinnerEventHandler::Callback *callback;
float minimum;
float maximum;
float step;
float value;
Rectangle<double> incArea;
Rectangle<double> decArea;
PrivateData(SpinnerEventHandler *const s, SubWidget *const w)
: self(s),
widget(w),
callback(nullptr),
minimum(0.0f),
maximum(1.0f),
step(0.0f),
value(0.5f),
incArea(),
decArea()
{
}
PrivateData(SpinnerEventHandler *const s, SubWidget *const w, PrivateData *const other)
: self(s),
widget(w),
callback(other->callback),
minimum(other->minimum),
maximum(other->maximum),
step(other->step),
value(other->value),
incArea(other->incArea),
decArea(other->decArea)
{
}
void assignFrom(PrivateData *const other)
{
callback = other->callback;
minimum = other->minimum;
maximum = other->maximum;
step = other->step;
value = other->value;
incArea = other->incArea;
decArea = other->decArea;
}
bool mouseEvent(const Widget::MouseEvent &ev)
{
if (ev.button != 1)
return false;
if (ev.press)
{
if (!incArea.contains(ev.pos) && !decArea.contains(ev.pos))
return false;
if (incArea.contains(ev.pos))
value += step;
if (decArea.contains(ev.pos))
value -= step;
value = clamp(value, maximum, minimum);
setValue(value, true);
return true;
}
return false;
}
bool motionEvent(const Widget::MotionEvent &ev)
{
return false;
}
bool scrollEvent(const Widget::ScrollEvent &ev)
{
if (!widget->contains(ev.pos))
return false;
auto dir = ev.direction;
switch (dir)
{
case ScrollDirection::kScrollUp:
value += step;
break;
case ScrollDirection::kScrollDown:
value -= step;
default:
break;
}
setValue(value, true);
return true;
}
void setRange(const float min, const float max) noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(max > min, );
minimum = min;
maximum = max;
}
bool setValue(const float value2, const bool sendCallback)
{
value = clamp(value2, maximum, minimum);
if (sendCallback && callback != nullptr)
{
try
{
callback->spinnerValueChanged(widget, value);
}
DISTRHO_SAFE_EXCEPTION("SpinnerEventHandler::setValue");
}
return true;
}
};
// --------------------------------------------------------------------------------------------------------------------
SpinnerEventHandler::SpinnerEventHandler(SubWidget *const self)
: pData(new PrivateData(this, self)) {}
SpinnerEventHandler::SpinnerEventHandler(SubWidget *const self, const SpinnerEventHandler &other)
: pData(new PrivateData(this, self, other.pData)) {}
SpinnerEventHandler &SpinnerEventHandler::operator=(const SpinnerEventHandler &other)
{
pData->assignFrom(other.pData);
return *this;
}
SpinnerEventHandler::~SpinnerEventHandler()
{
delete pData;
}
float SpinnerEventHandler::getValue() const noexcept
{
return pData->value;
}
bool SpinnerEventHandler::setValue(const float value, const bool sendCallback) noexcept
{
return pData->setValue(value, sendCallback);
}
void SpinnerEventHandler::setRange(const float min, const float max) noexcept
{
pData->setRange(min, max);
}
void SpinnerEventHandler::setStep(const float step) noexcept
{
pData->step = step;
}
void SpinnerEventHandler::setIncrementArea(const double x, const double y, const double w, const double h) noexcept
{
pData->incArea = Rectangle<double>(x, y, w, h);
}
void SpinnerEventHandler::setDecrementArea(const double x, const double y, const double w, const double h) noexcept
{
pData->decArea = Rectangle<double>(x, y, w, h);
}
void SpinnerEventHandler::setCallback(Callback *const callback) noexcept
{
pData->callback = callback;
}
Rectangle<double> SpinnerEventHandler::getIncrementArea() noexcept
{
return pData->incArea;
}
Rectangle<double> SpinnerEventHandler::getDecrementArea() noexcept
{
return pData->decArea;
}
bool SpinnerEventHandler::mouseEvent(const Widget::MouseEvent &ev)
{
return pData->mouseEvent(ev);
}
bool SpinnerEventHandler::motionEvent(const Widget::MotionEvent &ev)
{
return pData->motionEvent(ev);
}
bool SpinnerEventHandler::scrollEvent(const Widget::ScrollEvent &ev)
{
return pData->scrollEvent(ev);
printf("scrollEvent \n");
}
// end spinner
// begin radio
struct RadioEventHandler::PrivateData
{
RadioEventHandler *const self;
SubWidget *const widget;
RadioEventHandler::Callback *callback;
// struct Option
// {
// const char *name;
// float value;
// Rectangle<double> hitbox;
// Option(const char *nm, float val)
// {
// name = nm;
// value = val;
// }
// };
float minimum;
float maximum;
float value;
std::vector<Option> options;
PrivateData(RadioEventHandler *const s, SubWidget *const w)
: self(s),
widget(w),
callback(nullptr),
minimum(0.0f),
maximum(1.0f),
value(0.0f)
{
}
PrivateData(RadioEventHandler *const s, SubWidget *const w, PrivateData *const other)
: self(s),
widget(w),
callback(other->callback),
minimum(other->minimum),
maximum(other->maximum),
value(other->value)
{
}
void assignFrom(PrivateData *const other)
{
callback = other->callback;
minimum = other->minimum;
maximum = other->maximum;
value = other->value;
}
bool mouseEvent(const Widget::MouseEvent &ev)
{
if (ev.button != 1 || !ev.press || !widget->contains(ev.pos))
return false;
else
{
for (auto &hb : options)
{
if (hb.hitbox.contains(ev.pos))
{
setValue(hb.value, true);
return true;
}
}
}
return false;
}
bool setValue(const float value2, const bool sendCallback)
{
value = clamp(value2, maximum, minimum);
if (sendCallback && callback != nullptr)
{
try
{
callback->radioValueChanged(widget, value);
}
DISTRHO_SAFE_EXCEPTION("RadioEventHandler::setValue");
}
return true;
}
void addOption(const char *name, float value)
{
options.emplace_back(Option(name, value));
initHitboxes();
}
void getOptions(std::vector<Option> &returnOptions)
{
returnOptions = options;
}
void getHitboxes(std::vector<Rectangle<double>> &hitboxes)
{
for (auto option : options)
{
hitboxes.push_back(option.hitbox);
}
}
void initHitboxes()
{
const int numOptions = options.size();
const double widgetHeight = widget->getHeight();
const double widgetWidth = widget->getWidth();
const double hitboxHeight = widgetHeight / static_cast<float>(numOptions);
const double hitboxWidth = widgetWidth;
double y = 0;
for (auto &hb : options)
{
hb.hitbox = Rectangle<double>(0, y, hitboxWidth, hitboxHeight);
y += hitboxHeight;
}
}
};
// --------------------------------------------------------------------------------------------------------------------
RadioEventHandler::RadioEventHandler(SubWidget *const self)
: pData(new PrivateData(this, self)) {}
RadioEventHandler::RadioEventHandler(SubWidget *const self, const RadioEventHandler &other)
: pData(new PrivateData(this, self, other.pData)) {}
RadioEventHandler &RadioEventHandler::operator=(const RadioEventHandler &other)
{
pData->assignFrom(other.pData);
return *this;
}
RadioEventHandler::~RadioEventHandler()
{
delete pData;
}
float RadioEventHandler::getValue() const noexcept
{
return pData->value;
}
bool RadioEventHandler::setValue(const float value, const bool sendCallback) noexcept
{
return pData->setValue(value, sendCallback);
}
void RadioEventHandler::addOption(const char *optName, float val)
{
pData->addOption(optName, val);
}
void RadioEventHandler::getHitboxes(std::vector<Rectangle<double>> &hitboxes)
{
pData->getHitboxes(hitboxes);
}
void RadioEventHandler::getOptions(std::vector<Option> &options)
{
pData->getOptions(options);
}
void RadioEventHandler::initHitboxes()
{
pData->initHitboxes();
}
void RadioEventHandler::setCallback(Callback *const callback) noexcept
{
pData->callback = callback;
}
bool RadioEventHandler::mouseEvent(const Widget::MouseEvent &ev)
{
return pData->mouseEvent(ev);
}
// end Radio
END_NAMESPACE_DGL
| 24.605061 | 119 | 0.555754 | [
"vector"
] |
6baa38f37421bb5f87cc188f92d33478f4e27432 | 4,851 | cpp | C++ | Game/Source/ModuleParticles.cpp | AMADE128/PlatformerGame | f81b25505781ef82171984e95f2a8b675767a715 | [
"MIT"
] | null | null | null | Game/Source/ModuleParticles.cpp | AMADE128/PlatformerGame | f81b25505781ef82171984e95f2a8b675767a715 | [
"MIT"
] | null | null | null | Game/Source/ModuleParticles.cpp | AMADE128/PlatformerGame | f81b25505781ef82171984e95f2a8b675767a715 | [
"MIT"
] | null | null | null | #include "ModuleParticles.h"
#include "App.h"
#include "Textures.h"
#include "Render.h"
#include "Collisions.h"
#include "Input.h"
#include "Player.h"
#include "Log.h"
#include "SDL/include/SDL_scancode.h"
#include "SDL/include/SDL.h"
#include "SDL/include/SDL_timer.h"
ModuleParticles::ModuleParticles() : Entity()
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
particles[i] = nullptr;
for (int i = 0; i < 96 * 6; i += 96)
{
fruitGet.anim.PushBack({ i, 0, 96, 96 });
}
fruitGet.anim.loop = false;
fruitGet.anim.speed = 0.4f;
fruitGet.lifetime = 25;
fruitGet.speed = { 0, 0 };
rightLeaf.anim.PushBack({ 0, 0, 32, 32 });
rightLeaf.anim.speed = 0;
rightLeaf.speed.x = 15;
rightLeaf.lifetime = 40;
leftLeaf.anim.PushBack({ 0, 0, 32, 32 });
leftLeaf.anim.speed = 0;
leftLeaf.speed.x = -15;
leftLeaf.lifetime = 40;
for (int i = 0; i < 120 * 4; i += 120)
{
chickenFall.anim.PushBack({ i, 0, 120, 144 });
}
chickenFall.anim.loop = false;
chickenFall.anim.speed = 0.2f;
chickenFall.speed.y = 9;
chickenFall.lifetime = 40;
for (int i = 0; i < 120 * 5; i += 120)
{
chickenHit.anim.PushBack({ i, 0, 120, 144 });
}
chickenHit.anim.loop = false;
chickenHit.anim.speed = 0.2f;
chickenFall.speed.x = 0.01f;
chickenHit.lifetime = 40;
}
ModuleParticles::~ModuleParticles()
{
}
bool ModuleParticles::Start()
{
LOG("Loading particles");
fruitGetTex = app->tex->Load("Assets/Textures/Items/Fruits/collect.png");
leafTex = app->tex->Load("Assets/Textures/Drone/leaf.png");
chickenFallTex = app->tex->Load("Assets/Textures/Drone/fall_skill.png");
chickenHitTex = app->tex->Load("Assets/Textures/Drone/hit_skill.png");
return true;
}
bool ModuleParticles::CleanUp()
{
if (!active)
{
return true;
}
LOG("Unloading particles");
// Delete all remaining active particles on application exit
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
if (particles[i] != nullptr)
{
delete particles[i];
particles[i] = nullptr;
}
}
app->tex->UnLoad(fruitGetTex);
app->tex->UnLoad(leafTex);
app->tex->UnLoad(chickenFallTex);
app->tex->UnLoad(chickenHitTex);
active = false;
return true;
}
bool ModuleParticles::Die(Collider* c1, Collider* c2)
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
// Always destroy particles that collide
if (particles[i] != nullptr && particles[i]->collider == c1)
{
app->collision->RemoveCollider(particles[i]->collider);
delete particles[i];
particles[i] = nullptr;
break;
}
}
return true;
}
bool ModuleParticles::Update(float dt)
{
bool ret = true;
chickenFall.speed.y = 500 * dt;
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
Particle* particle = particles[i];
if (particle == nullptr) continue;
// Call particle Update. If it has reached its lifetime, destroy it
if (particle->Update() == false)
{
app->collision->RemoveCollider(particles[i]->collider);
delete particle;
particles[i] = nullptr;
}
}
return ret;
}
bool ModuleParticles::PostUpdate()
{
bool ret = true;
//Iterating all particle array and drawing any active particles
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
Particle* particle = particles[i];
if (particle != nullptr && particle->speed.x == fruitGet.speed.x && particle->speed.y != chickenFall.speed.y)
{
app->render->DrawTexture(fruitGetTex, particle->position.x - 24, particle->position.y - 24, &(particle->anim.GetCurrentFrame()));
}
if (particle != nullptr && (particle->speed.x == rightLeaf.speed.x || particle->speed.x == leftLeaf.speed.x) && particle->speed.x != fruitGet.speed.x)
{
app->render->DrawTexture(leafTex, particle->position.x, particle->position.y + 10, &(particle->anim.GetCurrentFrame()));
}
if (particle != nullptr && particle->speed.y == chickenFall.speed.y)
{
app->render->DrawTexture(chickenFallTex, particle->position.x, particle->position.y, &(particle->anim.GetCurrentFrame()));
}
if (particle != nullptr && particle->speed.x == chickenHit.speed.x && particle->speed.y != chickenFall.speed.y && particle->speed.x != fruitGet.speed.x)
{
app->render->DrawTexture(chickenHitTex, particle->position.x, particle->position.y, &(particle->anim.GetCurrentFrame()));
}
}
return ret;
}
void ModuleParticles::AddParticle(const Particle& particle, int x, int y, Collider::Type colliderType, uint delay)
{
for (uint i = 0; i < MAX_ACTIVE_PARTICLES; ++i)
{
//Finding an empty slot for a new particle
if (particles[i] == nullptr)
{
Particle* p = new Particle(particle);
p->frameCount = -(int)delay; // We start the frameCount as the negative delay
p->position.x = x; // so when frameCount reaches 0 the particle will be activated
p->position.y = y;
p->collider = app->collision->AddCollider(p->anim.GetCurrentFrame(), colliderType, this);
particles[i] = p;
break;
}
}
} | 25.134715 | 154 | 0.670171 | [
"render"
] |
6bac4018580d88d5dcf8ac861bed6a302b1e80c9 | 31,031 | hpp | C++ | Source/cx_matrix/cx_matrix.hpp | Vasar007/CxMatrix | 1ae2fa7bea6fb6377c5fd843b573b94a905c77b1 | [
"MIT"
] | 2 | 2018-12-08T09:13:58.000Z | 2018-12-08T09:14:11.000Z | Source/cx_matrix/cx_matrix.hpp | Vasar007/CxMatrix | 1ae2fa7bea6fb6377c5fd843b573b94a905c77b1 | [
"MIT"
] | 3 | 2018-10-12T21:46:34.000Z | 2019-01-31T11:40:33.000Z | Source/cx_matrix/cx_matrix.hpp | Vasar007/numerical_mathematics_methods | cca8d94057f684c70fbd0093ae56881d9d165aa0 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018 Vasily Vasilyev (vasar007@yandex.ru)
#pragma once
#include <iterator>
#include <algorithm>
#include <array>
#include <stdexcept>
#include <initializer_list>
#include <string>
#include <cmath>
#include <cassert>
#include <iterator>
#include <type_traits>
#include "cx_math.h"
#include "cx_algorthms.hpp"
/*
* TODO:
* 1) Take out several functions (like gauss method) in a separate library.
*/
namespace vv
{
/// ===== CONSTEXPR MATRIX IMLEMENTATION SECTION =====
template <class Type = double, std::size_t Rows = 1, std::size_t Columns = 1>
class cx_matrix
{
public:
using value_type = Type;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template <class ContType = value_type, std::size_t N = Rows>
using container = std::array<ContType, N>;
using row_container = container<value_type, Columns>;
using row_container_reference = container<value_type, Columns>&;
using const_row_container_reference = const container<value_type, Columns>&;
using data_container = container<container<value_type, Columns>, Rows>;
using data_container_reference = data_container&;
using const_data_container_reference = const data_container&;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = value_type&;
using const_reference = const value_type&;
static constexpr value_type EPS = static_cast<value_type>(1e-10);
static_assert(std::is_arithmetic_v<value_type>, "Matrix elements type has to be arithmetic!");
static_assert(Rows > 0 && Columns > 0, "Incorrect size parameters!");
constexpr cx_matrix() noexcept = default;
constexpr cx_matrix(const value_type value) noexcept
: _data()
{
for (auto& row : _data)
{
detail::fill(std::begin(row), std::end(row), value);
}
}
constexpr cx_matrix(const std::initializer_list<value_type> list) noexcept
: _data()
{
size_type row_counter = 0;
size_type col_counter = 0;
for (const auto elem : list)
{
_data.at(row_counter).at(col_counter) = elem;
++col_counter;
if (col_counter == Columns)
{
++row_counter;
if (row_counter == Rows && col_counter == Columns)
{
break;
}
col_counter = 0;
}
}
}
~cx_matrix() noexcept = default;
constexpr cx_matrix(const cx_matrix& other) = default;
constexpr cx_matrix& operator=(const cx_matrix& other) = default;
constexpr cx_matrix(cx_matrix&& other) noexcept = default;
constexpr cx_matrix& operator=(cx_matrix&& other) noexcept = default;
std::string get_dimension() const
{
return std::to_string(get_rows_number()) + std::string("x")
+ std::to_string(get_columns_number());
}
constexpr size_type get_rows_number() const noexcept
{
return Rows;
}
constexpr size_type get_columns_number() const noexcept
{
return Columns;
}
constexpr bool empty() const noexcept
{
// Without any checks because class has static_assert and code won't be compiled
// if number of Rows or Colums is equal to 0.
return false;
}
constexpr typename data_container::iterator begin() noexcept
{
return _data.begin();
}
constexpr typename data_container::const_iterator begin() const noexcept
{
return _data.begin();
}
constexpr typename data_container::const_iterator cbegin() const noexcept
{
return _data.cbegin();
}
constexpr typename data_container::iterator end() noexcept
{
return _data.end();
}
constexpr typename data_container::const_iterator end() const noexcept
{
return _data.end();
}
constexpr typename data_container::const_iterator cend() const noexcept
{
return _data.cend();
}
constexpr typename data_container::reverse_iterator rbegin() noexcept
{
return _data.rbegin();
}
constexpr typename data_container::const_reverse_iterator rbegin() const noexcept
{
return _data.rbegin();
}
constexpr typename data_container::const_reverse_iterator crbegin() const noexcept
{
return _data.crbegin();
}
constexpr typename data_container::reverse_iterator rend() noexcept
{
return _data.rend();
}
constexpr typename data_container::const_reverse_iterator rend() const noexcept
{
return _data.rend();
}
constexpr typename data_container::const_reverse_iterator crend() const noexcept
{
return _data.crend();
}
constexpr data_container_reference data() noexcept
{
return _data;
}
constexpr const_data_container_reference data() const noexcept
{
return _data;
}
constexpr pointer raw_data() noexcept
{
return _data.data()->data();
}
constexpr const_pointer raw_data() const noexcept
{
return _data.data()->data();
}
constexpr std::pair<size_type, size_type> size() const noexcept
{
return { get_rows_number(), get_columns_number() };
}
constexpr row_container_reference operator[](const size_type pos)
{
return _data[pos];
}
constexpr const_row_container_reference operator[](const size_type pos) const
{
return _data[pos];
}
constexpr row_container_reference at(const size_type i)
{
return _data.at(i);
}
constexpr const_row_container_reference at(const size_type i) const
{
return _data.at(i);
}
constexpr reference at(const size_type i, const size_type j)
{
return _data.at(i).at(j);
}
constexpr const_reference at(const size_type i, const size_type j) const
{
return _data.at(i).at(j);
}
constexpr cx_matrix& operator+=(const cx_matrix& rhs) noexcept
{
for (size_type i = 0; i < Rows; ++i)
{
for (size_type j = 0; j < Columns; ++j)
{
_data.at(i).at(j) += rhs.at(i, j);
}
}
return *this;
}
constexpr cx_matrix& operator-=(const cx_matrix& rhs) noexcept
{
for (size_type i = 0; i < Rows; ++i)
{
for (size_type j = 0; j < Columns; ++j)
{
_data.at(i).at(j) -= rhs.at(i, j);
}
}
return *this;
}
constexpr cx_matrix& operator*=(const value_type value) noexcept
{
for (auto& row : _data)
{
for (auto& elem : row)
{
elem *= value;
}
}
return *this;
}
constexpr cx_matrix& operator/=(const value_type value)
{
//assert(value != value_type{});
for (auto& row : _data)
{
for (auto& elem : row)
{
elem /= value;
}
}
return *this;
}
constexpr auto operator^(const int value) const noexcept
{
cx_matrix temp(*this);
return _exp_helper(temp, value);
}
void swap(cx_matrix& other) noexcept(std::is_nothrow_swappable_v<container>)
{
std::swap(_data, other.data());
}
constexpr void swap_rows(const size_type row_1, const size_type row_2) noexcept
{
if (row_1 >= Rows || row_2 >= Rows) return;
detail::swap(_data.at(row_1), _data.at(row_2));
}
constexpr void swap_columns(const size_type column_1, const size_type column_2) noexcept
{
if (column_1 >= Columns || column_2 >= Columns) return;
for (size_type i = 0; i < Rows; ++i)
{
detail::swap(_data.at(i).at(column_1), _data.at(i).at(column_2));
}
}
constexpr void fill(const value_type& value) noexcept
{
for (auto& row : _data)
{
detail::fill(std::begin(row), std::end(row), value);
}
}
constexpr cx_matrix<value_type, Columns, Rows> transpose() const noexcept
{
cx_matrix<value_type, Columns, Rows> transp{};
for (size_type i = 0; i < Rows; ++i)
{
for (size_type j = 0; j < Columns; ++j)
{
transp.at(j, i) = _data.at(i).at(j);
}
}
return transp;
}
constexpr bool is_empty(const size_type start_row_index = 0,
const size_type start_column_index = 0,
const value_type eps = EPS) const noexcept
{
//assert(eps < value_type{});
if (start_row_index > Rows || start_column_index > Columns) return false;
for (size_type i = start_row_index; i < Rows; ++i)
{
for (size_type j = start_column_index; j < Columns; ++j)
{
if (cx::abs(_data.at(i).at(j)) >= eps)
{
return false;
}
}
}
return true;
}
bool is_error_matrix() const noexcept
{
//const auto is_nan = [](const value_type x) { return std::isnan(x); };
for (const auto& row : _data)
{
if (!detail::all_of(std::begin(row), std::end(row), std::isnan<value_type>))
{
return false;
}
}
return true;
}
constexpr std::pair<size_type, size_type>
find_max_element(const size_type start_row_index = 0,
const size_type start_column_index = 0) const noexcept
{
if (start_row_index > Rows || start_column_index > Columns)
{
return { start_row_index, start_column_index };
}
value_type abs_max{};
size_type row = start_row_index;
size_type column = start_column_index;
for (size_type i = start_row_index; i < Rows; ++i)
{
for (size_type j = start_column_index; j < Columns; ++j)
{
if (cx::abs(_data.at(i).at(j)) > abs_max)
{
abs_max = cx::abs(_data.at(i).at(j));
row = i;
column = j;
}
}
}
return { row, column };
}
constexpr value_type calculate_condition_number() const noexcept
{
constexpr auto abs_plus = [](const value_type a, const value_type b)
{
return cx::abs(a) + cx::abs(b);
};
// Using the norm of infinity for matrices.
value_type condition_number{};
for (const auto& row: _data)
{
const auto summ_in_row = detail::accumulate(std::begin(row), std::end(row),
value_type{}, abs_plus);
condition_number = std::max(condition_number, summ_in_row);
}
return condition_number;
}
template <class T = value_type, std::size_t Size = Rows>
static constexpr cx_matrix<T, Size, Size> create_identity() noexcept
{
cx_matrix<T, Size, Size> temp{};
for (size_type i = 0; i < Size; ++i)
{
for (size_type j = 0; j < Size; ++j)
{
if (i == j)
{
temp.at(i, j) = static_cast<T>(1);
}
else
{
temp.at(i, j) = value_type{};
}
}
}
return temp;
}
template <std::size_t Rows_, std::size_t Columns_A, std::size_t Columns_b>
static constexpr std::pair<cx_matrix<value_type, Rows_, Columns_A>,
cx_matrix<value_type, Rows_, Columns_b>>
forward_substitution(cx_matrix<value_type, Rows_, Columns_A> A,
cx_matrix<value_type, Rows_, Columns_b> b,
const value_type eps = EPS)
{
//assert(eps < value_type{});
static_assert(Columns_b == 1, "Matrix contains more than one columns in right hand "
"side vector!");
// Gaussian elimination.
for (size_type i = 0; i < Rows_; ++i)
{
if (cx::abs(A.at(i, i)) < eps)
{
// Pivot ~ 0 => throw error.
throw std::domain_error("Error: the coefficient cx_matrix has 0 as a pivot.");
}
for (size_type j = i + 1; j < Rows_; ++j)
{
for (size_type k = i + 1; k < Columns_A; ++k)
{
A.at(j, k) -= A.at(i, k) * (A.at(j, i) / A.at(i, i));
if (cx::abs(A.at(j, k)) < eps)
{
A.at(j, k) = value_type{};
}
}
b.at(j, 0) -= b.at(i, 0) * (A.at(j, i) / A.at(i, i));
if (cx::abs(A.at(j, 0)) < eps)
{
A.at(j, 0) = value_type{};
}
A.at(j, i) = value_type{};
}
} // for (size_type i = 0; i < Rows_; ++i)
return { A, b };
}
template <std::size_t Rows_, std::size_t Columns_A, std::size_t Columns_b>
static constexpr cx_matrix<value_type, Rows_, Columns_b>
backward_substitution(const cx_matrix<value_type, Rows_, Columns_A>& A,
const cx_matrix<value_type, Rows_, Columns_b>& b,
const value_type eps = EPS)
{
//assert(eps < value_type{});
static_assert(Columns_b == 1, "Matrix contains more than one columns in right "
"hand side vector!");
// Back substitution.
cx_matrix<value_type, Rows_, 1> x{};
for (size_type i = Rows_ - 1; ; --i)
{
value_type sum{};
for (size_type j = i + 1; j < Rows_; ++j)
{
sum += A.at(i, j) * x.at(j, 0);
}
x.at(i, 0) = (b.at(i, 0) - sum) / A.at(i, i);
if (cx::abs(x.at(i, 0)) < eps)
{
x.at(i, 0) = value_type{};
}
if (i == 0) break;
} // for (size_type i = Rows_ - 1; ; --i)
return x;
}
template <std::size_t Rows_, std::size_t Columns_A, std::size_t Columns_b>
static constexpr cx_matrix<value_type, Rows_, Columns_b>
solve(const cx_matrix<value_type, Rows_, Columns_A>& A,
const cx_matrix<value_type, Rows_, Columns_b>& b, const value_type eps = EPS)
{
static_assert(Columns_b == 1, "Matrix contains more than one columns in right hand "
"side vector!");
const auto result_of_forw_subs = forward_substitution(A, b, eps);
return backward_substitution(result_of_forw_subs.first, result_of_forw_subs.second);
}
template <std::size_t Rows_A, std::size_t Columns_A,
std::size_t Rows_b, std::size_t Columns_b>
static constexpr cx_matrix<value_type, Rows_b, 1>
band_solve(cx_matrix<value_type, Rows_A, Columns_A> A,
cx_matrix<value_type, Rows_b, Columns_b> b,
const value_type coef)
{
// Optimized Gaussian elimination.
value_type bandsBelow = static_cast<value_type>((coef - 1) / 2.0);
for (size_type i = 0; i < Rows_A; ++i)
{
if (A.at(i, i) == value_type{})
{
// Pivot ~0 => throw exception.
throw std::domain_error("Error: the coefficient cx_matrix has 0 as a "
"pivot. Please fix the input and try again.");
}
for (size_type j = i + 1; j < Rows_A && j <= i + bandsBelow; ++j)
{
size_type k = i + 1;
while (k < Columns_A && A.at(j, k))
{
A.at(j, k) -= A.at(i, k) * A.at(j, i) / A.at(i, i);
++k;
}
b.at(j, 0) -= b.at(i, 0) * A.at(j, i) / A.at(i, i);
A.at(j, i) = value_type{};
}
}
// Back substitution.
cx_matrix<value_type, Rows_b, 1> x{};
x.at(Rows_b - 1, 0) = b.at(Rows_b - 1, 0) / A.at(Rows_b - 1, Rows_b - 1);
for (size_type i = Rows_b - 2; ; --i)
{
value_type sum{};
for (size_type j = i + 1; j < Rows_b; ++j)
{
sum += A.at(i, j) * x.at(j, 0);
}
x.at(i, 0) = (b.at(i, 0) - sum) / A.at(i, i);
if (i == 0) break;
}
return x;
}
// Functions on vectors.
template <std::size_t Rows_, std::size_t Columns_A, std::size_t Columns_B>
static constexpr value_type dot_product(const cx_matrix<value_type, Rows_, Columns_A>& A,
const cx_matrix<value_type, Rows_, Columns_B>& B,
const size_type column) noexcept
{
value_type sum{};
for (size_type i = 0; i < Rows_; ++i)
{
sum += A.at(i, column) * B.at(i, column);
}
return sum;
}
// Functions on augmented matrices.
template <std::size_t Rows_A, std::size_t Columns_A,
std::size_t Rows_B, std::size_t Columns_B>
static constexpr cx_matrix<value_type, Rows_A, Columns_A + Columns_B>
augment(const cx_matrix<value_type, Rows_A, Columns_A>& A,
const cx_matrix<value_type, Rows_B, Columns_B>& B) noexcept
{
cx_matrix<value_type, Rows_A, Columns_A + Columns_B> AB{};
for (size_type i = 0; i < Rows_A; ++i)
{
for (size_type j = 0; j < Columns_A + Columns_B; ++j)
{
if (j < Columns_A)
{
AB.at(i, j) = A.at(i, j);
}
else
{
AB.at(i, j) = B.at(i, j - Columns_B);
}
}
}
return AB;
}
constexpr cx_matrix gaussian_eliminate(const value_type eps = EPS) const
{
//assert(eps < value_type{});
cx_matrix Ab(*this);
int rows = Rows;
int cols = Columns;
int Acols = cols - 1;
int i = 0; // Row tracker.
int j = 0; // Column tracker.
// Iterate through the rows.
while (i < rows)
{
// Find a pivot for the row.
bool pivot_found = false;
while (j < Acols && !pivot_found)
{
if (Ab.at(i, j) != value_type{})
{ // Pivot not equal to 0.
pivot_found = true;
}
else
{ // Check for a possible swap.
int max_row = i;
value_type max_val{};
for (int k = i + 1; k < rows; ++k)
{
value_type cur_abs = cx::abs(Ab.at(k, j));
if (cur_abs > max_val)
{
max_row = k;
max_val = cur_abs;
}
}
if (max_row != i)
{
Ab.swap_rows(max_row, i);
pivot_found = true;
}
else
{
++j;
}
}
}
// Perform elimination as normal if pivot was found.
if (pivot_found)
{
for (int t = i + 1; t < rows; ++t)
{
for (int s = j + 1; s < cols; ++s)
{
Ab.at(t, s) = Ab.at(t, s) - Ab.at(i, s) * Ab.at(t, j) / Ab.at(i, j);
if (cx::abs(Ab.at(t, s)) < eps)
{
Ab.at(t, s) = value_type{};
}
}
Ab.at(t, j) = value_type{};
}
}
++i;
++j;
}
return Ab;
}
constexpr cx_matrix row_reduce_from_gaussian(const value_type eps = EPS) const
{
//assert(eps < value_type{});
cx_matrix result(*this);
int rows = Rows;
int cols = Columns;
int i = rows - 1; // Row tracker.
int j = cols - 1; // Column tracker.
// Iterate through every row.
while (i >= 0 && j >= 0)
{
// Find the pivot column.
int k = j - 1;
while (k >= 0)
{
if (result.at(i, k) != value_type{})
{
j = k;
}
--k;
}
// Zero out elements above pivots if pivot not 0.
if (result.at(i, j) != value_type{})
{
for (int t = i - 1; t >= 0; --t)
{
for (int s = 0; s < cols; ++s)
{
if (s != j)
{
result.at(t, s) -= result.at(i, s) * result.at(t, j) / result.at(i, j);
if (cx::abs(result.at(t, s)) < eps)
{
result.at(t, s) = value_type{};
}
}
}
result.at(t, j) = value_type{};
}
// Divide row by pivot.
for (int l = j + 1; l < cols; ++l)
{
result.at(i, l) = result.at(i, l) / result.at(i, j);
if (cx::abs(result.at(i, l)) < eps)
{
result.at(i, l) = value_type{};
}
}
result.at(i, j) = static_cast<value_type>(1);
}
--i;
--j;
}
return result;
}
constexpr cx_matrix inverse() const
{
const auto I = create_identity();
const auto AI = augment(*this, I);
const auto U = AI.gaussian_eliminate();
const auto IAInverse = U.row_reduce_from_gaussian();
cx_matrix AInverse{};
for (size_type i = 0; i < Rows; ++i)
{
for (size_type j = 0; j < Columns; ++j)
{
AInverse.at(i, j) = IAInverse.at(i, j + Columns);
}
}
return AInverse;
}
constexpr value_type calculate_elements_sum() const noexcept
{
value_type sum{};
for (const auto& row: _data)
{
const auto sum_in_row = detail::accumulate(std::begin(row), std::end(row),
value_type{});
sum += sum_in_row;
}
return sum;
}
template <class T = value_type, std::size_t Rows_E = Rows, std::size_t Columns_E = Columns>
static constexpr cx_matrix<T, Rows_E, Columns_E> get_error_matrix() noexcept
{
cx_matrix<T, Rows_E, Columns_E> err_matrix{};
for (auto& row: err_matrix._data)
{
detail::fill(std::begin(row), std::end(row), std::numeric_limits<T>::quiet_NaN());
}
return err_matrix;
}
private:
constexpr auto _exp_helper(const cx_matrix& mat, const int value) const noexcept
{
if (value == 0)
{
return create_identity<value_type, Rows>();
}
if (value == 1)
{
return mat;
}
if (value % 2 == 0)
{
// value is even.
return _exp_helper(mat * mat, value / 2);
}
// value is odd.
return mat * _exp_helper(mat * mat, (value - 1) / 2);
}
data_container _data;
};
namespace detail::cx_matrix
{
template <class Type, std::size_t N>
using container = std::array<Type, N>;
} // namespace detail::matrix
template <class value_type, std::size_t Rows, std::size_t Columns>
std::ostream& operator<<(std::ostream& os, const cx_matrix<value_type, Rows, Columns>& mat)
{
os << '[' << mat.get_dimension() << "]\n";
for (const auto& row : mat)
{
std::copy(std::begin(row), std::end(row),
std::ostream_iterator<value_type>(os, " "));
os << '\n';
}
return os;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
std::istream& operator>>(std::istream& is, cx_matrix<value_type, Rows, Columns>& mat)
{
for (auto& row : mat)
{
for (auto& elem : row)
{
is >> elem;
}
}
return is;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr cx_matrix<value_type, Rows, Columns> operator-(
cx_matrix<value_type, Rows, Columns> mat) noexcept
{
return mat *= static_cast<value_type>(-1);
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr cx_matrix<value_type, Rows, Columns> operator+(
cx_matrix<value_type, Rows, Columns> lhs,
const cx_matrix<value_type, Rows, Columns>& rhs) noexcept
{
return lhs += rhs;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr cx_matrix<value_type, Rows, Columns> operator-(
cx_matrix<value_type, Rows, Columns> lhs,
const cx_matrix<value_type, Rows, Columns>& rhs) noexcept
{
return lhs -= rhs;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr cx_matrix<value_type, Rows, Columns> operator*(
cx_matrix<value_type, Rows, Columns> mat, const value_type value) noexcept
{
return mat *= value;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr cx_matrix<value_type, Rows, Columns> operator*(
const value_type value, const cx_matrix<value_type, Rows, Columns>& mat) noexcept
{
return mat * value;
}
template <class value_type, std::size_t Rows_lhs, std::size_t Mid_dimension,
std::size_t Columns_rhs>
constexpr cx_matrix<value_type, Rows_lhs, Columns_rhs> operator*(
const cx_matrix<value_type, Rows_lhs, Mid_dimension>& lhs,
const cx_matrix<value_type, Mid_dimension, Columns_rhs>& rhs) noexcept
{
using size_type = typename cx_matrix<value_type, Rows_lhs, Columns_rhs>::size_type;
cx_matrix<value_type, Rows_lhs, Columns_rhs> result{};
detail::cx_matrix::container<value_type, Mid_dimension> thatColumn{};
for (size_type j = 0; j < Columns_rhs; ++j)
{
for (size_type k = 0; k < Mid_dimension; ++k)
{
thatColumn.at(k) = rhs.at(k, j);
}
for (size_type i = 0; i < Rows_lhs; ++i)
{
const auto thisRow = lhs.at(i);
value_type summand{};
for (size_type k = 0; k < Mid_dimension; ++k)
{
summand += thisRow.at(k) * thatColumn.at(k);
}
result.at(i, j) = summand;
}
}
return result;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr cx_matrix<value_type, Rows, Columns> operator/(
cx_matrix<value_type, Rows, Columns> mat, const value_type value)
{
//assert(value != value_type{});
return mat /= value;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr bool operator==(const cx_matrix<value_type, Rows, Columns>& lhs,
const cx_matrix<value_type, Rows, Columns>& rhs) noexcept
{
using size_type = typename cx_matrix<value_type, Rows, Columns>::size_type;
for (size_type row_index = 0; row_index < Rows; ++row_index)
{
if (!detail::equal(std::begin(lhs(row_index)), std::end(lhs(row_index)),
std::begin(rhs(row_index))))
{
return false;
}
}
return true;
}
template <class value_type, std::size_t Rows, std::size_t Columns>
constexpr bool operator!=(const cx_matrix<value_type, Rows, Columns>& lhs,
const cx_matrix<value_type, Rows, Columns>& rhs) noexcept
{
return !(lhs == rhs);
}
/// Helpers operation
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator+(detail::cx_matrix::container<value_type, N> lhs,
const detail::cx_matrix::container<value_type, N>& rhs) noexcept
{
for (std::size_t i = 0; i < lhs.size(); ++i)
{
lhs.at(i) += rhs.at(i);
}
return lhs;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator+(detail::cx_matrix::container<value_type, N> cont,
const value_type& value) noexcept
{
for (auto& elem : cont)
{
elem += value;
}
return cont;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator+(const value_type& value,
const detail::cx_matrix::container<value_type, N>& cont) noexcept
{
return cont + value;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator-(detail::cx_matrix::container<value_type, N> lhs,
const detail::cx_matrix::container<value_type, N>& rhs) noexcept
{
for (std::size_t i = 0; i < lhs.size(); ++i)
{
lhs.at(i) -= rhs.at(i);
}
return lhs;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator-(detail::cx_matrix::container<value_type, N> cont, const value_type& value) noexcept
{
for (auto& elem : cont)
{
elem -= value;
}
return cont;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator*(detail::cx_matrix::container<value_type, N> cont,
const value_type& value) noexcept
{
for (auto& elem : cont)
{
elem *= value;
}
return cont;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator*(const value_type& value,
const detail::cx_matrix::container<value_type, N>& cont) noexcept
{
return cont * value;
}
template <class value_type, std::size_t N>
constexpr detail::cx_matrix::container<value_type, N>
operator/(detail::cx_matrix::container<value_type, N> cont, const value_type& value)
{
//assert(value != value_type{});
for (auto& elem : cont)
{
elem /= value;
}
return cont;
}
} // namespace vv
| 28.031617 | 99 | 0.519158 | [
"vector"
] |
6bb0694d02e57ac68605615b731106c12c50f2ec | 3,087 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/net/http/X509TrustManagerExtensions.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/net/http/X509TrustManagerExtensions.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/net/http/X509TrustManagerExtensions.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 <Elastos.CoreLibrary.Net.h>
#include <Elastos.CoreLibrary.h>
#include "elastos/droid/net/http/X509TrustManagerExtensions.h"
#include "elastos/droid/R.h"
#include <elastos/utility/etl/List.h>
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::R;
using Elastos::Security::Cert::ICertificate;
using Elastos::Security::Cert::IX509Certificate;
using Elastos::Utility::Etl::List;
using Elastos::Utility::IList;
using Elastos::Utility::Logging::Logger;
using Elastosx::Net::Ssl::EIID_ITrustManager;
using Elastosx::Net::Ssl::ISSLParameters;
using Elastosx::Net::Ssl::ISSLSocket;
using Elastosx::Net::Ssl::ITrustManager;
using Elastosx::Net::Ssl::IX509TrustManager;
using Org::Conscrypt::ITrustManagerImpl;
namespace Elastos {
namespace Droid {
namespace Net {
namespace Http {
CAR_INTERFACE_IMPL(X509TrustManagerExtensions, Object, IX509TrustManagerExtensions)
ECode X509TrustManagerExtensions::constructor(
/* [in] */ IX509TrustManager* tm)
{
VALIDATE_NOT_NULL(tm);
AutoPtr<ITrustManagerImpl> impl;
// TODO: Waiting for TrustManagerImpl
assert(0);
// impl = ITrustManagerImpl::Probe(tm);
if (impl == NULL) {
// throw new IllegalArgumentException("tm is an instance of " + tm.getClass().getName() +
// " which is not a supported type of X509TrustManager");
Logger::E("X509TrustManagerExtensions", "tm is not an instance of X509TrustManager");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
mDelegate = impl;
return NOERROR;
}
ECode X509TrustManagerExtensions::CheckServerTrusted(
/* [in] */ ArrayOf<IX509Certificate*>* chain,
/* [in] */ const String& authType,
/* [in] */ const String& host,
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result)
// TODO: Waiting for TrustManagerImpl
assert(0);
// return mDelegate->CheckServerTrusted(chain, authType, host, result);
return NOERROR;
}
ECode X509TrustManagerExtensions::IsUserAddedCertificate(
/* [in] */ IX509Certificate* cert,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
// TODO: Waiting for TrustManagerImpl
assert(0);
// return mDelegate->IsUserAddedCertificate(cert, result);
return NOERROR;
}
} // namespace Http
} // namespace Net
} // namespace Droid
} // namespace Elastos
| 31.824742 | 101 | 0.681892 | [
"object"
] |
6bb5857f57a0b61ac757d2801bbd65bb4a999229 | 890 | cpp | C++ | tools/info_gen/src/info_gen.cpp | neo-bolea/timen | 5e49caf8e0c9300d883ff3db9e878e4f82886af0 | [
"MIT"
] | null | null | null | tools/info_gen/src/info_gen.cpp | neo-bolea/timen | 5e49caf8e0c9300d883ff3db9e878e4f82886af0 | [
"MIT"
] | null | null | null | tools/info_gen/src/info_gen.cpp | neo-bolea/timen | 5e49caf8e0c9300d883ff3db9e878e4f82886af0 | [
"MIT"
] | null | null | null | #include <assert.h>
#include <direct.h>
#include <fstream>
#include <random>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
struct proc_info
{
int ProcID;
float Time;
};
void main()
{
assert(_chdir("../data") == 0);
std::ifstream sym_file("Log.out");
assert(!sym_file.fail());
std::string cur_proc_str;
std::vector<proc_info> proc_infos;
do
{
int ProcID;
float Time;
sym_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
sym_file >> ProcID;
sym_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
sym_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
sym_file >> Time;
sym_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
sym_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
proc_infos.push_back(proc_info{ ProcID, Time });
} while (!sym_file.eof());
} | 21.190476 | 69 | 0.673034 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.