text string | size int64 | token_count int64 |
|---|---|---|
// Copyright (C) 2019 Samy Bensaid
// This file is part of the Teal project.
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef TEAL_STATES_HPP
#define TEAL_STATES_HPP
#include <Nazara/Core/String.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Lua/LuaState.hpp>
#include <utility>
#include <unordered_map>
#include "data/elementdata.hpp"
#include "def/typedef.hpp"
#include "util/assert.hpp"
#include "util/util.hpp"
struct State
{
State() = default;
virtual ~State() = default;
virtual void serialize(const Nz::LuaState& state) = 0;
struct FightInfo
{
std::unordered_map<Element, int> maximumDamage; // positive: damage, negative: heal
std::unordered_map<Element, int> attackModifier; // positive: boost, negative: nerf
std::unordered_map<Element, int> resistanceModifier; // positive: boost, negative: nerf
int movementPointsDifference {};
int actionPointsDifference {};
enum StateFlag
{
None,
Paralyzed,
Sleeping,
Confused
} flags { None };
};
virtual FightInfo getFightInfo() = 0;
};
enum class StateType
{
PoisonnedState,
HealedState,
WeaknessState,
PowerState,
ParalyzedState,
SleepingState,
ConfusedState
};
inline Nz::String stateTypeToString(StateType stateType);
inline StateType stringToStateType(Nz::String string);
struct PoisonnedState : public State
{
inline PoisonnedState(const Nz::LuaState& state, int index = -1);
std::pair<Element, unsigned> damage;
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::PoisonnedState; }
};
struct HealedState : public State
{
inline HealedState(const Nz::LuaState& state, int index = -1);
std::pair<Element, unsigned> health;
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::HealedState; }
};
struct StatsModifierState : public State
{
inline StatsModifierState(const Nz::LuaState& state, int index = -1);
std::unordered_map<Element, int> attack;
std::unordered_map<Element, int> resistance;
int movementPoints {};
int actionPoints {};
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
};
struct WeaknessState : public StatsModifierState
{
inline WeaknessState(const Nz::LuaState& state, int index = -1) : StatsModifierState(state, index) {}
virtual inline void serialize(const Nz::LuaState& state) override;
static StateType getStateType() { return StateType::WeaknessState; }
};
struct PowerState : public StatsModifierState
{
inline PowerState(const Nz::LuaState& state, int index = -1) : StatsModifierState(state, index) {}
virtual inline void serialize(const Nz::LuaState& state) override;
static StateType getStateType() { return StateType::PowerState; }
};
struct ParalyzedState : public State
{
inline ParalyzedState(const Nz::LuaState& state, int index = -1) {}
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::ParalyzedState; }
};
struct SleepingState : public State // = paralyzed until attacked
{
inline SleepingState(const Nz::LuaState& state, int index = -1) {}
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::SleepingState; }
};
struct ConfusedState : public State // aka drunk
{
inline ConfusedState(const Nz::LuaState& state, int index = -1) {}
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::ConfusedState; }
};
#include "states.inl"
#endif // TEAL_STATES_HPP
| 4,255 | 1,299 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process/launch.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <utility>
#include <vector>
#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/posix/safe_strerror.h"
#include "base/process/process.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
void LaunchMacTest(const FilePath& exe_path,
LaunchOptions options,
const std::string& expected_output) {
ScopedFD pipe_read_fd;
ScopedFD pipe_write_fd;
{
int pipe_fds[2];
ASSERT_EQ(pipe(pipe_fds), 0) << safe_strerror(errno);
pipe_read_fd.reset(pipe_fds[0]);
pipe_write_fd.reset(pipe_fds[1]);
}
ScopedFILE pipe_read_file(fdopen(pipe_read_fd.get(), "r"));
ASSERT_TRUE(pipe_read_file) << "fdopen: " << safe_strerror(errno);
ignore_result(pipe_read_fd.release());
std::vector<std::string> argv(1, exe_path.value());
options.fds_to_remap.emplace_back(pipe_write_fd.get(), STDOUT_FILENO);
Process process = LaunchProcess(argv, options);
ASSERT_TRUE(process.IsValid());
pipe_write_fd.reset();
// Not ASSERT_TRUE because it's important to reach process.WaitForExit.
std::string output;
EXPECT_TRUE(ReadStreamToString(pipe_read_file.get(), &output));
int exit_code;
ASSERT_TRUE(process.WaitForExit(&exit_code));
EXPECT_EQ(exit_code, 0);
EXPECT_EQ(output, expected_output);
}
#if defined(ARCH_CPU_ARM64)
// Bulk-disabled on arm64 for bot stabilization: https://crbug.com/1154345
#define MAYBE_LaunchMac DISABLED_LaunchMac
#else
#define MAYBE_LaunchMac LaunchMac
#endif
TEST(Process, MAYBE_LaunchMac) {
FilePath data_dir;
ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir));
data_dir = data_dir.AppendASCII("mac");
#if defined(ARCH_CPU_X86_64)
static constexpr char kArchitecture[] = "x86_64";
#elif defined(ARCH_CPU_ARM64)
static constexpr char kArchitecture[] = "arm64";
#endif
LaunchOptions options;
LaunchMacTest(data_dir.AppendASCII(kArchitecture), options,
std::string(kArchitecture) + "\n");
#if defined(ARCH_CPU_ARM64)
static constexpr char kUniversal[] = "universal";
LaunchMacTest(data_dir.AppendASCII(kUniversal), options,
std::string(kArchitecture) + "\n");
static constexpr char kX86_64[] = "x86_64";
LaunchMacTest(data_dir.AppendASCII(kX86_64), options,
std::string(kX86_64) + "\n");
options.launch_x86_64 = true;
LaunchMacTest(data_dir.AppendASCII(kUniversal), options,
std::string(kX86_64) + "\n");
LaunchMacTest(data_dir.AppendASCII(kX86_64), options,
std::string(kX86_64) + "\n");
#endif // ARCH_CPU_ARM64
}
} // namespace
} // namespace base
| 3,059 | 1,188 |
/*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <chrono>
#include <iostream>
#include <vector>
#include "OneCCL.h"
#include "com_intel_oap_mllib_regression_LinearRegressionDALImpl.h"
#include "service.h"
using namespace std;
using namespace daal;
using namespace daal::algorithms;
typedef double algorithmFPType; /* Algorithm floating-point type */
static NumericTablePtr linear_regression_compute(int rankId,
ccl::communicator &comm,
const NumericTablePtr &pData,
const NumericTablePtr &pLabel,
size_t nBlocks) {
using daal::byte;
linear_regression::training::Distributed<step1Local> localAlgorithm;
/* Pass a training data set and dependent values to the algorithm */
localAlgorithm.input.set(linear_regression::training::data, pData);
localAlgorithm.input.set(linear_regression::training::dependentVariables,
pLabel);
/* Train the multiple linear regression model on local nodes */
localAlgorithm.compute();
/* Serialize partial results required by step 2 */
services::SharedPtr<byte> serializedData;
InputDataArchive dataArch;
localAlgorithm.getPartialResult()->serialize(dataArch);
size_t perNodeArchLength = dataArch.getSizeOfArchive();
serializedData =
services::SharedPtr<byte>(new byte[perNodeArchLength * nBlocks]);
byte *nodeResults = new byte[perNodeArchLength];
dataArch.copyArchiveToArray(nodeResults, perNodeArchLength);
std::vector<size_t> aReceiveCount(comm.size(),
perNodeArchLength); // 4 x "14016"
/* Transfer partial results to step 2 on the root node */
ccl::gather((int8_t *)nodeResults, perNodeArchLength,
(int8_t *)(serializedData.get()), perNodeArchLength, comm)
.wait();
delete[] nodeResults;
NumericTablePtr resultTable;
if (rankId == ccl_root) {
/* Create an algorithm object to build the final multiple linear
* regression model on the master node */
linear_regression::training::Distributed<step2Master> masterAlgorithm;
for (size_t i = 0; i < nBlocks; i++) {
/* Deserialize partial results from step 1 */
OutputDataArchive dataArch(serializedData.get() +
perNodeArchLength * i,
perNodeArchLength);
linear_regression::training::PartialResultPtr
dataForStep2FromStep1 =
linear_regression::training::PartialResultPtr(
new linear_regression::training::PartialResult());
dataForStep2FromStep1->deserialize(dataArch);
/* Set the local multiple linear regression model as input for the
* master-node algorithm */
masterAlgorithm.input.add(
linear_regression::training::partialModels,
dataForStep2FromStep1);
}
/* Merge and finalizeCompute the multiple linear regression model on the
* master node */
masterAlgorithm.compute();
masterAlgorithm.finalizeCompute();
/* Retrieve the algorithm results */
linear_regression::training::ResultPtr trainingResult =
masterAlgorithm.getResult();
resultTable =
trainingResult->get(linear_regression::training::model)->getBeta();
printNumericTable(resultTable,
"Linear Regression first 20 columns of "
"coefficients (w0, w1..wn):",
1, 20);
}
return resultTable;
}
static NumericTablePtr ridge_regression_compute(
int rankId, ccl::communicator &comm, const NumericTablePtr &pData,
const NumericTablePtr &pLabel, double regParam, size_t nBlocks) {
using daal::byte;
NumericTablePtr ridgeParams(new HomogenNumericTable<double>(
1, 1, NumericTable::doAllocate, regParam));
ridge_regression::training::Distributed<step1Local> localAlgorithm;
localAlgorithm.parameter.ridgeParameters = ridgeParams;
/* Pass a training data set and dependent values to the algorithm */
localAlgorithm.input.set(ridge_regression::training::data, pData);
localAlgorithm.input.set(ridge_regression::training::dependentVariables,
pLabel);
/* Train the multiple ridge regression model on local nodes */
localAlgorithm.compute();
/* Serialize partial results required by step 2 */
services::SharedPtr<byte> serializedData;
InputDataArchive dataArch;
localAlgorithm.getPartialResult()->serialize(dataArch);
size_t perNodeArchLength = dataArch.getSizeOfArchive();
// std::cout << "perNodeArchLength: " << perNodeArchLength << std::endl;
serializedData =
services::SharedPtr<byte>(new byte[perNodeArchLength * nBlocks]);
byte *nodeResults = new byte[perNodeArchLength];
dataArch.copyArchiveToArray(nodeResults, perNodeArchLength);
std::vector<size_t> aReceiveCount(comm.size(),
perNodeArchLength); // 4 x "14016"
/* Transfer partial results to step 2 on the root node */
ccl::gather((int8_t *)nodeResults, perNodeArchLength,
(int8_t *)(serializedData.get()), perNodeArchLength, comm)
.wait();
delete[] nodeResults;
NumericTablePtr resultTable;
if (rankId == ccl_root) {
/* Create an algorithm object to build the final multiple ridge
* regression model on the master node */
ridge_regression::training::Distributed<step2Master> masterAlgorithm;
for (size_t i = 0; i < nBlocks; i++) {
/* Deserialize partial results from step 1 */
OutputDataArchive dataArch(serializedData.get() +
perNodeArchLength * i,
perNodeArchLength);
ridge_regression::training::PartialResultPtr dataForStep2FromStep1 =
ridge_regression::training::PartialResultPtr(
new ridge_regression::training::PartialResult());
dataForStep2FromStep1->deserialize(dataArch);
/* Set the local multiple ridge regression model as input for the
* master-node algorithm */
masterAlgorithm.input.add(ridge_regression::training::partialModels,
dataForStep2FromStep1);
}
/* Merge and finalizeCompute the multiple ridge regression model on the
* master node */
masterAlgorithm.compute();
masterAlgorithm.finalizeCompute();
/* Retrieve the algorithm results */
ridge_regression::training::ResultPtr trainingResult =
masterAlgorithm.getResult();
resultTable =
trainingResult->get(ridge_regression::training::model)->getBeta();
printNumericTable(resultTable,
"Ridge Regression first 20 columns of "
"coefficients (w0, w1..wn):",
1, 20);
}
return resultTable;
}
JNIEXPORT jlong JNICALL
Java_com_intel_oap_mllib_regression_LinearRegressionDALImpl_cLinearRegressionTrainDAL(
JNIEnv *env, jobject obj, jlong pNumTabData, jlong pNumTabLabel,
jdouble regParam, jdouble elasticNetParam, jint executor_num,
jint executor_cores, jobject resultObj) {
ccl::communicator &comm = getComm();
size_t rankId = comm.rank();
NumericTablePtr pLabel = *((NumericTablePtr *)pNumTabLabel);
NumericTablePtr pData = *((NumericTablePtr *)pNumTabData);
// Set number of threads for oneDAL to use for each rank
services::Environment::getInstance()->setNumberOfThreads(executor_cores);
int nThreadsNew =
services::Environment::getInstance()->getNumberOfThreads();
cout << "oneDAL (native): Number of CPU threads used: " << nThreadsNew
<< endl;
NumericTablePtr resultTable;
if (regParam == 0) {
resultTable = linear_regression_compute(rankId, comm, pData, pLabel,
executor_num);
} else {
resultTable = ridge_regression_compute(rankId, comm, pData, pLabel,
regParam, executor_num);
}
if (rankId == ccl_root) {
// Get the class of the result object
jclass clazz = env->GetObjectClass(resultObj);
// Get Field references
jfieldID coeffNumericTableField =
env->GetFieldID(clazz, "coeffNumericTable", "J");
NumericTablePtr *coeffvectors = new NumericTablePtr(resultTable);
env->SetLongField(resultObj, coeffNumericTableField,
(jlong)coeffvectors);
// intercept is already in first column of coeffvectors
return (jlong)coeffvectors;
} else
return (jlong)0;
}
| 9,794 | 2,625 |
/* heuristic_search library
*
* Copyright (c) 2016,
* Maciej Przybylski <maciej.przybylski@mchtr.pw.edu.pl>,
* Warsaw University of Technology.
* All rights reserved.
*
*/
#include <gtest/gtest.h>
#include "heuristic_search/SearchLoop.h"
#include "heuristic_search/StdOpenList.h"
#include "heuristic_search/StdSearchSpace.h"
#include "heuristic_search/SearchingAlgorithm.h"
#include "heuristic_search/AStar.h"
#include "heuristic_search/RepeatedAStar.h"
#include "heuristic_search/DStarMain.h"
#include "../heuristic_search/test_TestDomain.h"
namespace test_heuristic_search{
typedef heuristic_search::SearchAlgorithmBegin<
heuristic_search::DStarMain<
heuristic_search::SearchLoop<
heuristic_search::RepeatedAStar<
heuristic_search::AStar<
heuristic_search::HeuristicSearch<
heuristic_search::StdOpenList<
heuristic_search::StdSearchSpace<
heuristic_search::SearchAlgorithmEnd<TestDomain> > > > > > > > > RepeatedAStarTestAlgorithm_t;
TEST(test_RepeatedAStar, search_reinitialize_start)
{
TestDomain domain;
RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Backward, true);
ASSERT_FALSE(algorithm.initialized);
ASSERT_FALSE(algorithm.finished);
ASSERT_FALSE(algorithm.found);
ASSERT_TRUE(algorithm.search({1},{5}));
ASSERT_TRUE(algorithm.start_node->visited);
ASSERT_TRUE(algorithm.goal_node->visited);
EXPECT_TRUE(algorithm.finished);
EXPECT_TRUE(algorithm.found);
std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions;
algorithm.reinitialize({0}, updated_actions);
ASSERT_TRUE(algorithm.search());
EXPECT_TRUE(algorithm.finished);
EXPECT_TRUE(algorithm.found);
auto path = algorithm.getStatePath();
ASSERT_EQ(6, path.size());
EXPECT_EQ(TestDomain::State({0}),path[0]);
EXPECT_EQ(TestDomain::State({1}),path[1]);
EXPECT_EQ(TestDomain::State({2}),path[2]);
EXPECT_EQ(TestDomain::State({3}),path[3]);
EXPECT_EQ(TestDomain::State({4}),path[4]);
EXPECT_EQ(TestDomain::State({5}),path[5]);
}
TEST(test_RepeatedAStar, search_cost_increase_backward)
{
TestDomain domain;
RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Backward, true);
ASSERT_FALSE(algorithm.initialized);
ASSERT_FALSE(algorithm.finished);
ASSERT_FALSE(algorithm.found);
ASSERT_TRUE(algorithm.search({0},{5}));
ASSERT_TRUE(algorithm.start_node->visited);
ASSERT_TRUE(algorithm.goal_node->visited);
EXPECT_TRUE(algorithm.finished);
EXPECT_TRUE(algorithm.found);
TestDomain::StateActionState updated_action({2},{10*TestDomain::costFactor()},{3});
domain.updateAction(updated_action);
std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions;
updated_actions.push_back(std::make_pair(updated_action, 1*TestDomain::costFactor()));
algorithm.reinitialize({1}, updated_actions);
ASSERT_TRUE(algorithm.search());
EXPECT_TRUE(algorithm.finished);
EXPECT_TRUE(algorithm.found);
auto path = algorithm.getStatePath();
ASSERT_EQ(5, path.size());
EXPECT_EQ(TestDomain::State({1}),path[0]);
EXPECT_EQ(TestDomain::State({6}),path[1]);
EXPECT_EQ(TestDomain::State({7}),path[2]);
EXPECT_EQ(TestDomain::State({4}),path[3]);
EXPECT_EQ(TestDomain::State({5}),path[4]);
}
TEST(test_RepeatedAStar, search_cost_increase_forward)
{
TestDomain domain;
RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Forward, true);
ASSERT_FALSE(algorithm.initialized);
ASSERT_FALSE(algorithm.finished);
ASSERT_FALSE(algorithm.found);
ASSERT_TRUE(algorithm.search({1},{5}));
ASSERT_TRUE(algorithm.start_node->visited);
ASSERT_TRUE(algorithm.goal_node->visited);
EXPECT_TRUE(algorithm.finished);
EXPECT_TRUE(algorithm.found);
TestDomain::StateActionState updated_action({2},{10*TestDomain::costFactor()},{3});
domain.updateAction(updated_action);
std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions;
updated_actions.push_back(std::make_pair(updated_action, 1*TestDomain::costFactor()));
algorithm.reinitialize({1}, updated_actions);
ASSERT_TRUE(algorithm.search());
EXPECT_TRUE(algorithm.finished);
EXPECT_TRUE(algorithm.found);
auto path = algorithm.getStatePath();
ASSERT_EQ(5, path.size());
EXPECT_EQ(TestDomain::State({1}),path[0]);
EXPECT_EQ(TestDomain::State({6}),path[1]);
EXPECT_EQ(TestDomain::State({7}),path[2]);
EXPECT_EQ(TestDomain::State({4}),path[3]);
EXPECT_EQ(TestDomain::State({5}),path[4]);
}
TEST(test_RepeatedAStar, main_backward)
{
TestDomain domain;
RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Backward);
algorithm.main({0},{5});
EXPECT_EQ(TestDomain::State(5), algorithm.current_state);
}
TEST(test_RepeatedAStar, main_forward)
{
TestDomain domain;
RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain,
heuristic_search::SearchingDirection::Forward);
algorithm.main({0},{5});
EXPECT_EQ(TestDomain::State(5), algorithm.current_state);
}
}
| 5,678 | 1,949 |
#pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass News.News_C
// 0x0048 (0x0428 - 0x03E0)
class UNews_C : public UCommonActivatablePanel
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x03E0(0x0008) (Transient, DuplicateTransient)
class UIconTextButton_C* CloseButton; // 0x03E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UScrollBox* DescriptionScroll; // 0x03F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class ULightbox_C* Lightbox; // 0x03F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UImage* MainIcon; // 0x0400(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UScrollBox* ScrollBoxEntries; // 0x0408(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonTextBlock* TextDescription; // 0x0410(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonTextBlock* Title; // 0x0418(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonButtonGroup* ButtonGroup; // 0x0420(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass News.News_C");
return ptr;
}
void UpdateInfoPanel(const struct FText& BodyText);
void Init();
void PopulateEntries(bool* IsEmpty);
void AddEntry(const struct FText& inEntryText);
void BndEvt__CloseButton_K2Node_ComponentBoundEvent_21_CommonButtonClicked__DelegateSignature(class UCommonButton* Button);
void Construct();
void ExecuteUbergraph_News(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 5,814 | 1,581 |
#pragma once
#include <algorithm>
#include <veritacpp/dsl/math/core_concepts.hpp>
#include <veritacpp/dsl/math/constants.hpp>
namespace veritacpp::dsl::math {
template <uint64_t N>
struct Variable;
template<uint64_t N, Functional F>
struct VariableBindingHolder {
F f;
static constexpr auto VariableID = N;
constexpr VariableBindingHolder(Variable<N>, F f) : f{f} {}
constexpr Functional auto operator()(Variable<N>) const {
return f;
}
};
template <uint64_t N, Functional F>
VariableBindingHolder(Variable<N>, F) -> VariableBindingHolder<N, F>;
template <class T>
struct IsVariableBinding : std::false_type {};
template <uint64_t N, Functional F>
struct IsVariableBinding<VariableBindingHolder<N, F>> : std::true_type {};
template <class T>
concept VariableBinding = IsVariableBinding<T>::value;
template <VariableBinding... Var>
struct VariableBindingGroup : Var... {
using Var::operator()...;
static constexpr auto MaxVariableID = std::max({ Var::VariableID... });
template<uint64_t N> requires ((N != Var::VariableID) && ...)
constexpr Functional auto operator () (Variable<N> x) const {
return x;
}
};
template <VariableBinding... Var>
VariableBindingGroup(Var...) -> VariableBindingGroup<Var...>;
template <uint64_t N>
struct Variable : BasicFunction {
static constexpr auto Id = N;
constexpr Arithmetic auto operator()(Arithmetic auto... args) const
requires (sizeof...(args) > N)
{
return std::get<N>(std::make_tuple(args...));
}
template <Functional F>
constexpr auto operator = (F f) const {
return VariableBindingGroup { VariableBindingHolder<N, F>(*this, f) };
}
};
template <uint64_t N, uint64_t M>
requires (N == M)
Functional auto operator - (Variable<N>, Variable<M>) {
return kZero;
}
template <uint64_t N, uint64_t M>
requires (N == M)
Functional auto operator / (Variable<N>, Variable<M>) {
return kOne;
}
// Veriable<N> requires at least N+1 arguments
static_assert(!(NVariablesFunctional<2, Variable<2>>));
template <VariableBinding... Var>
constexpr bool all_unique_variables = []<uint64_t... idx>(
std::integer_sequence<uint64_t, idx...>){
constexpr std::array arr { idx...};
return ((std::ranges::count(arr, idx) == 1) && ...);
}(std::integer_sequence<uint64_t, Var::VariableID...>{});
template <VariableBinding... Var>
consteval bool group_contains_binding(VariableBindingGroup<Var...>, VariableBinding auto v) {
return ((Var::VariableID == v.VariableID) || ...);
}
template<VariableBinding... V1, VariableBinding... V2>
constexpr auto operator , (VariableBindingGroup<V1...> v1, VariableBindingGroup<V2...> v2) {
static_assert(all_unique_variables<V1..., V2...>,
"rebinding same variable twice is not allowed");
return VariableBindingGroup {
static_cast<V1>(v1)...,
static_cast<V2>(v2)...
};
}
} | 2,950 | 959 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/passwords/manage_passwords_bubble_view.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/timer/timer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/exclusive_access/fullscreen_controller.h"
#include "chrome/browser/ui/passwords/password_dialog_prompts.h"
#include "chrome/browser/ui/passwords/passwords_model_delegate.h"
#include "chrome/browser/ui/views/desktop_ios_promotion/desktop_ios_promotion_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/passwords/credentials_item_view.h"
#include "chrome/browser/ui/views/passwords/credentials_selection_view.h"
#include "chrome/browser/ui/views/passwords/manage_password_items_view.h"
#include "chrome/browser/ui/views/passwords/manage_passwords_icon_views.h"
#include "chrome/grit/generated_resources.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/user_metrics.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/button/blue_button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/link.h"
#include "ui/views/controls/link_listener.h"
#include "ui/views/controls/separator.h"
#include "ui/views/controls/styled_label.h"
#include "ui/views/controls/styled_label_listener.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
int ManagePasswordsBubbleView::auto_signin_toast_timeout_ = 3;
// Helpers --------------------------------------------------------------------
namespace {
enum ColumnSetType {
// | | (FILL, FILL) | |
// Used for the bubble's header, the credentials list, and for simple
// messages like "No passwords".
SINGLE_VIEW_COLUMN_SET,
// | | (TRAILING, CENTER) | | (TRAILING, CENTER) | |
// Used for buttons at the bottom of the bubble which should nest at the
// bottom-right corner.
DOUBLE_BUTTON_COLUMN_SET,
// | | (LEADING, CENTER) | | (TRAILING, CENTER) | |
// Used for buttons at the bottom of the bubble which should occupy
// the corners.
LINK_BUTTON_COLUMN_SET,
// | | (TRAILING, CENTER) | |
// Used when there is only one button which should next at the bottom-right
// corner.
SINGLE_BUTTON_COLUMN_SET,
// | | (LEADING, CENTER) | | (TRAILING, CENTER) | | (TRAILING, CENTER) | |
// Used when there are three buttons.
TRIPLE_BUTTON_COLUMN_SET,
};
enum TextRowType { ROW_SINGLE, ROW_MULTILINE };
// Construct an appropriate ColumnSet for the given |type|, and add it
// to |layout|.
void BuildColumnSet(views::GridLayout* layout, ColumnSetType type) {
views::ColumnSet* column_set = layout->AddColumnSet(type);
int full_width = ManagePasswordsBubbleView::kDesiredBubbleWidth;
switch (type) {
case SINGLE_VIEW_COLUMN_SET:
column_set->AddColumn(views::GridLayout::FILL,
views::GridLayout::FILL,
0,
views::GridLayout::FIXED,
full_width,
0);
break;
case DOUBLE_BUTTON_COLUMN_SET:
column_set->AddColumn(views::GridLayout::TRAILING,
views::GridLayout::CENTER,
1,
views::GridLayout::USE_PREF,
0,
0);
column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
column_set->AddColumn(views::GridLayout::TRAILING,
views::GridLayout::CENTER,
0,
views::GridLayout::USE_PREF,
0,
0);
break;
case LINK_BUTTON_COLUMN_SET:
column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::CENTER,
1,
views::GridLayout::USE_PREF,
0,
0);
column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
column_set->AddColumn(views::GridLayout::TRAILING,
views::GridLayout::CENTER,
0,
views::GridLayout::USE_PREF,
0,
0);
break;
case SINGLE_BUTTON_COLUMN_SET:
column_set->AddColumn(views::GridLayout::TRAILING,
views::GridLayout::CENTER,
1,
views::GridLayout::USE_PREF,
0,
0);
break;
case TRIPLE_BUTTON_COLUMN_SET:
column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::CENTER,
1,
views::GridLayout::USE_PREF,
0,
0);
column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
column_set->AddColumn(views::GridLayout::TRAILING,
views::GridLayout::CENTER,
0,
views::GridLayout::USE_PREF,
0,
0);
column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
column_set->AddColumn(views::GridLayout::TRAILING,
views::GridLayout::CENTER,
0,
views::GridLayout::USE_PREF,
0,
0);
break;
}
}
views::StyledLabel::RangeStyleInfo GetLinkStyle() {
auto result = views::StyledLabel::RangeStyleInfo::CreateForLink();
result.disable_line_wrapping = false;
return result;
}
// If a special title is required (i.e. one that contains links), creates a
// title view and a row for it in |layout|.
// TODO(estade): this should be removed and a replaced by a normal title (via
// GetWindowTitle).
void AddTitleRowWithLink(views::GridLayout* layout,
ManagePasswordsBubbleModel* model,
views::StyledLabelListener* listener) {
if (model->title_brand_link_range().is_empty())
return;
views::StyledLabel* title_label =
new views::StyledLabel(model->title(), listener);
title_label->SetBaseFontList(
ui::ResourceBundle::GetSharedInstance().GetFontList(
ui::ResourceBundle::MediumFont));
title_label->AddStyleRange(model->title_brand_link_range(), GetLinkStyle());
layout->StartRow(0, SINGLE_VIEW_COLUMN_SET);
layout->AddView(title_label);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
}
} // namespace
// ManagePasswordsBubbleView::AutoSigninView ----------------------------------
// A view containing just one credential that was used for for automatic signing
// in.
class ManagePasswordsBubbleView::AutoSigninView
: public views::View,
public views::ButtonListener,
public views::WidgetObserver {
public:
explicit AutoSigninView(ManagePasswordsBubbleView* parent);
private:
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
// views::WidgetObserver:
// Tracks the state of the browser window.
void OnWidgetActivationChanged(views::Widget* widget, bool active) override;
void OnWidgetClosing(views::Widget* widget) override;
void OnTimer();
static base::TimeDelta GetTimeout() {
return base::TimeDelta::FromSeconds(
ManagePasswordsBubbleView::auto_signin_toast_timeout_);
}
base::OneShotTimer timer_;
ManagePasswordsBubbleView* parent_;
ScopedObserver<views::Widget, views::WidgetObserver> observed_browser_;
DISALLOW_COPY_AND_ASSIGN(AutoSigninView);
};
ManagePasswordsBubbleView::AutoSigninView::AutoSigninView(
ManagePasswordsBubbleView* parent)
: parent_(parent),
observed_browser_(this) {
SetLayoutManager(new views::FillLayout);
const autofill::PasswordForm& form = parent_->model()->pending_password();
CredentialsItemView* credential = new CredentialsItemView(
this, base::string16(),
l10n_util::GetStringFUTF16(IDS_MANAGE_PASSWORDS_AUTO_SIGNIN_TITLE,
form.username_value),
kButtonHoverColor, &form,
parent_->model()->GetProfile()->GetRequestContext());
credential->SetEnabled(false);
AddChildView(credential);
// Setup the observer and maybe start the timer.
Browser* browser =
chrome::FindBrowserWithWebContents(parent_->web_contents());
DCHECK(browser);
BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
observed_browser_.Add(browser_view->GetWidget());
if (browser_view->IsActive())
timer_.Start(FROM_HERE, GetTimeout(), this, &AutoSigninView::OnTimer);
}
void ManagePasswordsBubbleView::AutoSigninView::ButtonPressed(
views::Button* sender, const ui::Event& event) {
NOTREACHED();
}
void ManagePasswordsBubbleView::AutoSigninView::OnWidgetActivationChanged(
views::Widget* widget, bool active) {
if (active && !timer_.IsRunning())
timer_.Start(FROM_HERE, GetTimeout(), this, &AutoSigninView::OnTimer);
}
void ManagePasswordsBubbleView::AutoSigninView::OnWidgetClosing(
views::Widget* widget) {
observed_browser_.RemoveAll();
}
void ManagePasswordsBubbleView::AutoSigninView::OnTimer() {
parent_->model()->OnAutoSignInToastTimeout();
parent_->CloseBubble();
}
// ManagePasswordsBubbleView::PendingView -------------------------------------
// A view offering the user the ability to save credentials. Contains a
// single ManagePasswordItemsView, along with a "Save Passwords" button
// and a "Never" button.
class ManagePasswordsBubbleView::PendingView
: public views::View,
public views::ButtonListener,
public views::StyledLabelListener {
public:
explicit PendingView(ManagePasswordsBubbleView* parent);
~PendingView() override;
private:
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
// views::StyledLabelListener:
void StyledLabelLinkClicked(views::StyledLabel* label,
const gfx::Range& range,
int event_flags) override;
ManagePasswordsBubbleView* parent_;
views::Button* save_button_;
views::Button* never_button_;
DISALLOW_COPY_AND_ASSIGN(PendingView);
};
ManagePasswordsBubbleView::PendingView::PendingView(
ManagePasswordsBubbleView* parent)
: parent_(parent) {
views::GridLayout* layout = new views::GridLayout(this);
layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0));
SetLayoutManager(layout);
// Create the pending credential item, save button and refusal combobox.
ManagePasswordItemsView* item = nullptr;
if (!parent->model()->pending_password().username_value.empty()) {
item = new ManagePasswordItemsView(parent_->model(),
&parent->model()->pending_password());
}
save_button_ = views::MdTextButton::CreateSecondaryUiBlueButton(
this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SAVE_BUTTON));
never_button_ = views::MdTextButton::CreateSecondaryUiButton(
this,
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_BUBBLE_BLACKLIST_BUTTON));
// Title row.
BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET);
AddTitleRowWithLink(layout, parent_->model(), this);
// Credential row.
if (item) {
layout->StartRow(0, SINGLE_VIEW_COLUMN_SET);
layout->AddView(item);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
}
// Button row.
BuildColumnSet(layout, DOUBLE_BUTTON_COLUMN_SET);
layout->StartRow(0, DOUBLE_BUTTON_COLUMN_SET);
layout->AddView(save_button_);
layout->AddView(never_button_);
parent_->set_initially_focused_view(save_button_);
}
ManagePasswordsBubbleView::PendingView::~PendingView() {
}
void ManagePasswordsBubbleView::PendingView::ButtonPressed(
views::Button* sender,
const ui::Event& event) {
if (sender == save_button_) {
parent_->model()->OnSaveClicked();
if (parent_->model()->ReplaceToShowPromotionIfNeeded()) {
parent_->Refresh();
return;
}
} else if (sender == never_button_) {
parent_->model()->OnNeverForThisSiteClicked();
} else {
NOTREACHED();
}
parent_->CloseBubble();
}
void ManagePasswordsBubbleView::PendingView::StyledLabelLinkClicked(
views::StyledLabel* label,
const gfx::Range& range,
int event_flags) {
DCHECK_EQ(range, parent_->model()->title_brand_link_range());
parent_->model()->OnBrandLinkClicked();
}
// ManagePasswordsBubbleView::ManageView --------------------------------------
// A view offering the user a list of their currently saved credentials
// for the current page, along with a "Manage passwords" link and a
// "Done" button.
class ManagePasswordsBubbleView::ManageView : public views::View,
public views::ButtonListener,
public views::LinkListener {
public:
explicit ManageView(ManagePasswordsBubbleView* parent);
~ManageView() override;
private:
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
// views::LinkListener:
void LinkClicked(views::Link* source, int event_flags) override;
ManagePasswordsBubbleView* parent_;
views::Link* manage_link_;
views::Button* done_button_;
DISALLOW_COPY_AND_ASSIGN(ManageView);
};
ManagePasswordsBubbleView::ManageView::ManageView(
ManagePasswordsBubbleView* parent)
: parent_(parent) {
views::GridLayout* layout = new views::GridLayout(this);
layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0));
SetLayoutManager(layout);
// If we have a list of passwords to store for the current site, display
// them to the user for management. Otherwise, render a "No passwords for
// this site" message.
BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET);
if (!parent_->model()->local_credentials().empty()) {
ManagePasswordItemsView* item = new ManagePasswordItemsView(
parent_->model(), &parent_->model()->local_credentials());
layout->StartRowWithPadding(0, SINGLE_VIEW_COLUMN_SET, 0,
views::kUnrelatedControlVerticalSpacing);
layout->AddView(item);
} else {
views::Label* empty_label = new views::Label(
l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_NO_PASSWORDS));
empty_label->SetMultiLine(true);
empty_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
empty_label->SetFontList(
ui::ResourceBundle::GetSharedInstance().GetFontList(
ui::ResourceBundle::SmallFont));
layout->StartRowWithPadding(0, SINGLE_VIEW_COLUMN_SET, 0,
views::kUnrelatedControlVerticalSpacing);
layout->AddView(empty_label);
}
// Then add the "manage passwords" link and "Done" button.
manage_link_ = new views::Link(parent_->model()->manage_link());
manage_link_->SetHorizontalAlignment(gfx::ALIGN_LEFT);
manage_link_->SetUnderline(false);
manage_link_->set_listener(this);
done_button_ = views::MdTextButton::CreateSecondaryUiButton(
this, l10n_util::GetStringUTF16(IDS_DONE));
BuildColumnSet(layout, LINK_BUTTON_COLUMN_SET);
layout->StartRowWithPadding(0, LINK_BUTTON_COLUMN_SET, 0,
views::kUnrelatedControlVerticalSpacing);
layout->AddView(manage_link_);
layout->AddView(done_button_);
parent_->set_initially_focused_view(done_button_);
}
ManagePasswordsBubbleView::ManageView::~ManageView() {
}
void ManagePasswordsBubbleView::ManageView::ButtonPressed(
views::Button* sender,
const ui::Event& event) {
DCHECK(sender == done_button_);
parent_->model()->OnDoneClicked();
parent_->CloseBubble();
}
void ManagePasswordsBubbleView::ManageView::LinkClicked(views::Link* source,
int event_flags) {
DCHECK_EQ(source, manage_link_);
parent_->model()->OnManageLinkClicked();
parent_->CloseBubble();
}
// ManagePasswordsBubbleView::SaveConfirmationView ----------------------------
// A view confirming to the user that a password was saved and offering a link
// to the Google account manager.
class ManagePasswordsBubbleView::SaveConfirmationView
: public views::View,
public views::ButtonListener,
public views::StyledLabelListener {
public:
explicit SaveConfirmationView(ManagePasswordsBubbleView* parent);
~SaveConfirmationView() override;
private:
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
// views::StyledLabelListener implementation
void StyledLabelLinkClicked(views::StyledLabel* label,
const gfx::Range& range,
int event_flags) override;
ManagePasswordsBubbleView* parent_;
views::Button* ok_button_;
DISALLOW_COPY_AND_ASSIGN(SaveConfirmationView);
};
ManagePasswordsBubbleView::SaveConfirmationView::SaveConfirmationView(
ManagePasswordsBubbleView* parent)
: parent_(parent) {
views::GridLayout* layout = new views::GridLayout(this);
layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0));
SetLayoutManager(layout);
views::StyledLabel* confirmation =
new views::StyledLabel(parent_->model()->save_confirmation_text(), this);
confirmation->SetBaseFontList(
ui::ResourceBundle::GetSharedInstance().GetFontList(
ui::ResourceBundle::SmallFont));
confirmation->AddStyleRange(
parent_->model()->save_confirmation_link_range(), GetLinkStyle());
BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET);
layout->StartRow(0, SINGLE_VIEW_COLUMN_SET);
layout->AddView(confirmation);
ok_button_ = views::MdTextButton::CreateSecondaryUiButton(
this, l10n_util::GetStringUTF16(IDS_OK));
BuildColumnSet(layout, SINGLE_BUTTON_COLUMN_SET);
layout->StartRowWithPadding(
0, SINGLE_BUTTON_COLUMN_SET, 0, views::kRelatedControlVerticalSpacing);
layout->AddView(ok_button_);
parent_->set_initially_focused_view(ok_button_);
}
ManagePasswordsBubbleView::SaveConfirmationView::~SaveConfirmationView() {
}
void ManagePasswordsBubbleView::SaveConfirmationView::StyledLabelLinkClicked(
views::StyledLabel* label,
const gfx::Range& range,
int event_flags) {
DCHECK_EQ(range, parent_->model()->save_confirmation_link_range());
parent_->model()->OnManageLinkClicked();
parent_->CloseBubble();
}
void ManagePasswordsBubbleView::SaveConfirmationView::ButtonPressed(
views::Button* sender, const ui::Event& event) {
DCHECK_EQ(sender, ok_button_);
parent_->model()->OnOKClicked();
parent_->CloseBubble();
}
// ManagePasswordsBubbleView::SignInPromoView ---------------------------------
// A view that offers user to sign in to Chrome.
class ManagePasswordsBubbleView::SignInPromoView
: public views::View,
public views::ButtonListener {
public:
explicit SignInPromoView(ManagePasswordsBubbleView* parent);
private:
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
ManagePasswordsBubbleView* parent_;
views::Button* signin_button_;
views::Button* no_button_;
DISALLOW_COPY_AND_ASSIGN(SignInPromoView);
};
ManagePasswordsBubbleView::SignInPromoView::SignInPromoView(
ManagePasswordsBubbleView* parent)
: parent_(parent) {
views::GridLayout* layout = new views::GridLayout(this);
layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0));
SetLayoutManager(layout);
signin_button_ = views::MdTextButton::CreateSecondaryUiBlueButton(
this,
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SIGNIN_PROMO_SIGN_IN));
no_button_ = views::MdTextButton::CreateSecondaryUiButton(
this,
l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SIGNIN_PROMO_NO_THANKS));
// Button row.
BuildColumnSet(layout, DOUBLE_BUTTON_COLUMN_SET);
layout->StartRow(0, DOUBLE_BUTTON_COLUMN_SET);
layout->AddView(signin_button_);
layout->AddView(no_button_);
parent_->set_initially_focused_view(signin_button_);
content::RecordAction(
base::UserMetricsAction("Signin_Impression_FromPasswordBubble"));
}
void ManagePasswordsBubbleView::SignInPromoView::ButtonPressed(
views::Button* sender,
const ui::Event& event) {
if (sender == signin_button_)
parent_->model()->OnSignInToChromeClicked();
else if (sender == no_button_)
parent_->model()->OnSkipSignInClicked();
else
NOTREACHED();
parent_->CloseBubble();
}
// ManagePasswordsBubbleView::UpdatePendingView -------------------------------
// A view offering the user the ability to update credentials. Contains a
// single ManagePasswordItemsView (in case of one credentials) or
// CredentialsSelectionView otherwise, along with a "Update Passwords" button
// and a rejection button.
class ManagePasswordsBubbleView::UpdatePendingView
: public views::View,
public views::ButtonListener,
public views::StyledLabelListener {
public:
explicit UpdatePendingView(ManagePasswordsBubbleView* parent);
~UpdatePendingView() override;
private:
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
// views::StyledLabelListener:
void StyledLabelLinkClicked(views::StyledLabel* label,
const gfx::Range& range,
int event_flags) override;
ManagePasswordsBubbleView* parent_;
CredentialsSelectionView* selection_view_;
views::Button* update_button_;
views::Button* nope_button_;
DISALLOW_COPY_AND_ASSIGN(UpdatePendingView);
};
ManagePasswordsBubbleView::UpdatePendingView::UpdatePendingView(
ManagePasswordsBubbleView* parent)
: parent_(parent), selection_view_(nullptr) {
views::GridLayout* layout = new views::GridLayout(this);
layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0));
SetLayoutManager(layout);
// Create the pending credential item, update button.
View* item = nullptr;
if (parent->model()->ShouldShowMultipleAccountUpdateUI()) {
selection_view_ = new CredentialsSelectionView(parent->model());
item = selection_view_;
} else {
item = new ManagePasswordItemsView(parent_->model(),
&parent->model()->pending_password());
}
nope_button_ = views::MdTextButton::CreateSecondaryUiButton(
this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_CANCEL_BUTTON));
update_button_ = views::MdTextButton::CreateSecondaryUiBlueButton(
this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_UPDATE_BUTTON));
// Title row.
BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET);
AddTitleRowWithLink(layout, parent_->model(), this);
// Credential row.
layout->StartRow(0, SINGLE_VIEW_COLUMN_SET);
layout->AddView(item);
// Button row.
BuildColumnSet(layout, DOUBLE_BUTTON_COLUMN_SET);
layout->StartRowWithPadding(0, DOUBLE_BUTTON_COLUMN_SET, 0,
views::kUnrelatedControlVerticalSpacing);
layout->AddView(update_button_);
layout->AddView(nope_button_);
parent_->set_initially_focused_view(update_button_);
}
ManagePasswordsBubbleView::UpdatePendingView::~UpdatePendingView() {}
void ManagePasswordsBubbleView::UpdatePendingView::ButtonPressed(
views::Button* sender,
const ui::Event& event) {
DCHECK(sender == update_button_ || sender == nope_button_);
if (sender == update_button_) {
if (selection_view_) {
// Multi account case.
parent_->model()->OnUpdateClicked(
*selection_view_->GetSelectedCredentials());
} else {
parent_->model()->OnUpdateClicked(parent_->model()->pending_password());
}
} else {
parent_->model()->OnNopeUpdateClicked();
}
parent_->CloseBubble();
}
void ManagePasswordsBubbleView::UpdatePendingView::StyledLabelLinkClicked(
views::StyledLabel* label,
const gfx::Range& range,
int event_flags) {
DCHECK_EQ(range, parent_->model()->title_brand_link_range());
parent_->model()->OnBrandLinkClicked();
}
// ManagePasswordsBubbleView --------------------------------------------------
// static
ManagePasswordsBubbleView* ManagePasswordsBubbleView::manage_passwords_bubble_ =
NULL;
// static
void ManagePasswordsBubbleView::ShowBubble(
content::WebContents* web_contents,
DisplayReason reason) {
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
DCHECK(browser);
DCHECK(browser->window());
DCHECK(!manage_passwords_bubble_ ||
!manage_passwords_bubble_->GetWidget()->IsVisible());
BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
bool is_fullscreen = browser_view->IsFullscreen();
views::View* anchor_view = nullptr;
if (!is_fullscreen) {
if (ui::MaterialDesignController::IsSecondaryUiMaterial()) {
anchor_view = browser_view->GetLocationBarView();
} else {
anchor_view =
browser_view->GetLocationBarView()->manage_passwords_icon_view();
}
}
manage_passwords_bubble_ = new ManagePasswordsBubbleView(
web_contents, anchor_view, reason);
if (is_fullscreen)
manage_passwords_bubble_->set_parent_window(web_contents->GetNativeView());
views::Widget* manage_passwords_bubble_widget =
views::BubbleDialogDelegateView::CreateBubble(manage_passwords_bubble_);
if (anchor_view) {
manage_passwords_bubble_widget->AddObserver(
browser_view->GetLocationBarView()->manage_passwords_icon_view());
}
// Adjust for fullscreen after creation as it relies on the content size.
if (is_fullscreen) {
manage_passwords_bubble_->AdjustForFullscreen(
browser_view->GetBoundsInScreen());
}
manage_passwords_bubble_->ShowForReason(reason);
}
// static
void ManagePasswordsBubbleView::CloseCurrentBubble() {
if (manage_passwords_bubble_)
manage_passwords_bubble_->CloseBubble();
}
// static
void ManagePasswordsBubbleView::ActivateBubble() {
DCHECK(manage_passwords_bubble_);
DCHECK(manage_passwords_bubble_->GetWidget()->IsVisible());
manage_passwords_bubble_->GetWidget()->Activate();
}
content::WebContents* ManagePasswordsBubbleView::web_contents() const {
return model_.GetWebContents();
}
ManagePasswordsBubbleView::ManagePasswordsBubbleView(
content::WebContents* web_contents,
views::View* anchor_view,
DisplayReason reason)
: LocationBarBubbleDelegateView(anchor_view, web_contents),
model_(PasswordsModelDelegateFromWebContents(web_contents),
reason == AUTOMATIC ? ManagePasswordsBubbleModel::AUTOMATIC
: ManagePasswordsBubbleModel::USER_ACTION),
initially_focused_view_(nullptr) {
mouse_handler_.reset(new WebContentMouseHandler(this, this->web_contents()));
}
ManagePasswordsBubbleView::~ManagePasswordsBubbleView() {
if (manage_passwords_bubble_ == this)
manage_passwords_bubble_ = NULL;
}
views::View* ManagePasswordsBubbleView::GetInitiallyFocusedView() {
return initially_focused_view_;
}
void ManagePasswordsBubbleView::Init() {
SetLayoutManager(new views::FillLayout);
CreateChild();
}
void ManagePasswordsBubbleView::CloseBubble() {
mouse_handler_.reset();
LocationBarBubbleDelegateView::CloseBubble();
}
base::string16 ManagePasswordsBubbleView::GetWindowTitle() const {
return model_.title();
}
bool ManagePasswordsBubbleView::ShouldShowWindowTitle() const {
// Since bubble titles don't support links, fall back to a custom title view
// if we need to show a link. Only use the normal title path if there's no
// link.
return model_.title_brand_link_range().is_empty();
}
bool ManagePasswordsBubbleView::ShouldShowCloseButton() const {
return model_.state() == password_manager::ui::PENDING_PASSWORD_STATE ||
model_.state() == password_manager::ui::CHROME_SIGN_IN_PROMO_STATE ||
model_.state() == password_manager::ui::CHROME_DESKTOP_IOS_PROMO_STATE;
}
void ManagePasswordsBubbleView::Refresh() {
RemoveAllChildViews(true);
initially_focused_view_ = NULL;
CreateChild();
// Show/hide the close button.
GetWidget()->non_client_view()->ResetWindowControls();
GetWidget()->UpdateWindowTitle();
SizeToContents();
}
void ManagePasswordsBubbleView::CreateChild() {
if (model_.state() == password_manager::ui::PENDING_PASSWORD_STATE) {
AddChildView(new PendingView(this));
} else if (model_.state() ==
password_manager::ui::PENDING_PASSWORD_UPDATE_STATE) {
AddChildView(new UpdatePendingView(this));
} else if (model_.state() == password_manager::ui::CONFIRMATION_STATE) {
AddChildView(new SaveConfirmationView(this));
} else if (model_.state() == password_manager::ui::AUTO_SIGNIN_STATE) {
AddChildView(new AutoSigninView(this));
} else if (model_.state() ==
password_manager::ui::CHROME_SIGN_IN_PROMO_STATE) {
AddChildView(new SignInPromoView(this));
} else if (model_.state() ==
password_manager::ui::CHROME_DESKTOP_IOS_PROMO_STATE) {
AddChildView(new DesktopIOSPromotionView(
desktop_ios_promotion::PromotionEntryPoint::SAVE_PASSWORD_BUBBLE));
} else {
AddChildView(new ManageView(this));
}
}
| 29,813 | 9,426 |
/* hw16_9 */
#include <iostream>
#include <cstdlib>
using namespace std;
int _max(int,int,int);
int _max(int,int);
int main(void)
{
int a=2,b=1,c=3;
cout<<"_max("<<a<<", "<<b<<", "<<c<<")="<<_max(a,b,c)<<endl;
cout<<"_max("<<b<<", "<<a<<")="<<_max(b,a)<<endl;
system("pause");
return 0;
}
int _max(int a,int b,int c)
{
int n=a;
if(n<b)
n=b;
if(n<c)
n=c;
return n;
}
int _max(int a,int b)
{
int n=a;
if(n<b)
n=b;
return n;
}
/*
_max(2, 1, 3)=3
_max(1, 2)=2
Press any key to continue . . .
*/
| 521 | 302 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "ReloadknockBackMod.h"
#include "GruntCharacter.h"
#include "Kismet/KismetMathLibrary.h"
#include "Kismet/GameplayStatics.h"
#include "GameFramework/PawnMovementComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
UReloadKnockBackMod::UReloadKnockBackMod()
{
}
UReloadKnockBackMod::~UReloadKnockBackMod()
{
}
void UReloadKnockBackMod::OnReload_Implementation(AActor* player)
{
TArray<AActor*> enemies;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), classToFind, enemies);
for (AActor* enemy : enemies)
{
FVector dir = enemy->GetActorLocation() - player->GetActorLocation();
float distance = dir.Size();
dir.Normalize();
UE_LOG(LogTemp, Warning, TEXT("Reload knockback: TestingDistance to Enemy, Distance: %f"), distance);
if (distance < range + additionalRangePerStack * stacks)
{
dir.Z = FMath::Clamp(dir.Z, 0.2f, 0.3f);
AGruntCharacter* character = Cast<AGruntCharacter>(enemy);
character->GetCharacterMovement()->MovementMode = EMovementMode::MOVE_Flying;
character->LaunchCharacter(dir * (strength + additionalStrengthPerStack * stacks + distance), true, true);
}
}
} | 1,224 | 459 |
//----------------------------------------------------------------------------//
// Part of the Fox project, licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
// File : Lexer.hpp
// Author : Pierre van Houtryve
//----------------------------------------------------------------------------//
// This file declares the Fox Lexer.
//----------------------------------------------------------------------------//
#pragma once
#include "Token.hpp"
#include "Fox/Common/SourceLoc.hpp"
#include "Fox/Common/string_view.hpp"
namespace fox {
class DiagnosticEngine;
class SourceManager;
/// Lexer
/// The Fox Lexer. An instance of the lexer is tied to a SourceFile
/// (FileID). The lexing process can be initiated by calling lex(), and
/// the resulting tokens will be found in the token vector returned by
/// getTokens()
/// The Token Vector's last token will always be TokenKind::EndOfFile.
class Lexer {
public:
/// Constructor for the Lexer.
/// \param srcMgr The SourceManager instance to use
/// \param diags the DiagnosticEngine instance to use for diagnostics
/// \param file the File that's going to be lexed. It must be a file
/// owned by \p srcMgr.
Lexer(SourceManager& srcMgr, DiagnosticEngine& diags, FileID file);
/// Make this class non copyable, but movable
Lexer(const Lexer&) = delete;
Lexer& operator=(const Lexer&) = delete;
Lexer(Lexer&&) = default;
Lexer& operator=(Lexer&&) = default;
/// lex the full file. the tokens can be retrieved using getTokens()
void lex();
/// \returns the vector of tokens, can only be called if lex() has
/// been called. The token vector is guaranteed to have a EOF token
/// as the last token.
TokenVector& getTokens();
/// Returns a SourceLoc for the character (or codepoint beginning) at
/// \p ptr.
///
/// \p ptr cannot be null and must be contained in the buffer of
/// \ref theFile
SourceLoc getLocFromPtr(const char* ptr) const;
/// Returns a SourceRange for the range beginning at \p a and ending
/// at \p b (range [a, b])
///
/// Both pointers must satisfy the same constraint as the argument of
/// \ref getLocFromPtr
SourceRange getRangeFromPtrs(const char* a, const char* b) const;
/// \returns the number of tokens in the vector
std::size_t numTokens() const;
/// The DiagnosticEngine instance used by this Lexer
DiagnosticEngine& diagEngine;
/// The SourceManager instance used by this Lexer
SourceManager& sourceMgr;
/// The FileID of the file being lexed
const FileID theFile;
private:
// Pushes the current token with the kind "kind"
void pushTok(TokenKind kind);
// Pushes the current token character as a token with the kind "kind"
// (calls resetToken() + pushToken())
void beginAndPushToken(TokenKind kind);
// Calls advance(), then pushes the current token with the kind 'kind'
void advanceAndPushTok(TokenKind kind);
// Returns true if we reached EOF.
bool isEOF() const;
// Begins a new token
void resetToken();
// Entry point of the lexing process
void lexImpl();
// Lex an identifier or keyword
void lexIdentifierOrKeyword();
// Lex an int or double literal
void lexIntOrDoubleConstant();
/// Lex any number of text items (a string_item or char_item,
/// depending on \p delimiter)
/// \p delimiter The delimiter. Can only be ' or ".
/// \return true if the delimiter was found, false otherwise
bool lexTextItems(FoxChar delimiter);
// Lex a piece of text delimited by single quotes '
void lexCharLiteral();
// Lex a piece of text delimited by double quotes "
void lexStringLiteral();
// Lex an integer literal
void lexIntConstant();
// Handles a single-line comment
void skipLineComment();
// Handles a multi-line comment
void skipBlockComment();
// Returns true if 'ch' is a valid identifier head.
bool isValidIdentifierHead(FoxChar ch) const;
// Returns true if 'ch' is a valid identifier character.
bool isValidIdentifierChar(FoxChar ch) const;
// Returns the current character being considered
FoxChar getCurChar() const;
// Peeks the next character that will be considered
FoxChar peekNextChar() const;
// Advances to the next codepoint in the input.
// Returns false if we reached EOF.
bool advance();
SourceLoc getCurPtrLoc() const;
SourceLoc getCurtokBegLoc() const;
SourceRange getCurtokRange() const;
string_view getCurtokStringView() const;
const char* fileBeg_ = nullptr;
const char* fileEnd_ = nullptr;
// The pointer to the first byte of the token
const char* tokBegPtr_ = nullptr;
// The pointer to the current character being considered.
// (pointer to the first byte in the UTF8 codepoint)
const char* curPtr_ = nullptr;
TokenVector tokens_;
};
}
| 5,267 | 1,405 |
#include "stdafx.h"
#include "FingerTapAndDragTapEvent.h"
#include "Mouse.h"
namespace envyTouchPad
{
FingerTapAndDragTapEvent::FingerTapAndDragTapEvent(int numberOfFingersTrigger)
{
fNumberOfFingersTrigger = numberOfFingersTrigger;
clear(true);
}
bool FingerTapAndDragTapEvent::fingersPresent(Configurations^ configurations, Packet^ packet, TapState& tapState, TouchPad& touchPad)
{
fMaxNumberOfFingers = max(fMaxNumberOfFingers, packet->getCurrentNumberOfFingers());
if (fIsDoubleTap)
{
return true;
}
TapConfiguration^ tapConfiguration = configurations->getTapConfiguration();
// handle the double tap event
if (fHasPreviousSingleClick && fMaxNumberOfFingers == fNumberOfFingersTrigger)
{
long previousClickTimeDifference = packet->getTimestamp() - fPreviousSingleClickTimestamp;
if (previousClickTimeDifference < tapConfiguration->getSingleTapIntervalThreshold())
{
fIsDoubleTap = true;
Mouse::buttonDown(tapConfiguration->getMouseButton(fNumberOfFingersTrigger));
clear(true);
return true;
}
}
return false; //(fMaxNumberOfFingers == fNumberOfFingersTrigger);
}
// should always return false since we don't want the mouse cursor to move.
bool FingerTapAndDragTapEvent::fingersNotPresent(Configurations^ configurations, Packet^ packet, TapState& tapState, TouchPad& touchPad)
{
TapConfiguration^ tapConfiguration = configurations->getTapConfiguration();
if (fIsDoubleTap)
{
fIsDoubleTap = false;
Mouse::buttonUp(tapConfiguration->getMouseButton(fNumberOfFingersTrigger));
// perform the second click if it was a double tap and the finger didn't move
// and the time difference isn't too large. otherwise, this was a double
// tap and drag
if
(
(fMaxNumberOfFingers == fNumberOfFingersTrigger)
&&
TapEvent::isTap(tapConfiguration, packet, tapState)
)
{
Mouse::buttonClick(tapConfiguration->getMouseButton(fNumberOfFingersTrigger));
}
return true;
}
else
{
if
(
fMaxNumberOfFingers == fNumberOfFingersTrigger
&&
TapEvent::isTap(tapConfiguration, packet, tapState)
)
{
if (!fHasPreviousSingleClick)
{
fHasPreviousSingleClick = true;
fPreviousSingleClickTimestamp = packet->getTimestamp();
clear(false);
return true;
}
}
else if (fHasPreviousSingleClick)
{
long previousClickTimeDifference = packet->getTimestamp() - fPreviousSingleClickTimestamp;
if (previousClickTimeDifference > tapConfiguration->getSingleTapIntervalThreshold())
{
Mouse::buttonClick(tapConfiguration->getMouseButton(fNumberOfFingersTrigger));
clear(true);
}
}
clear(false);
}
return false;
}
void FingerTapAndDragTapEvent::clear(bool clearPrevious)
{
if (clearPrevious)
{
fHasPreviousSingleClick = false;
fPreviousSingleClickTimestamp = 0;
}
fMaxNumberOfFingers = 0;
}
} // end namespace | 3,332 | 936 |
// Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
#include "PointInPolyhedron.h"
WM5_WINDOW_APPLICATION(PointInPolyhedron);
// Enable only one at a time to test the algorithm.
//#define TRIFACES
//#define CVXFACES0
//#define CVXFACES1
//#define CVXFACES2
//#define SIMFACES0
#define SIMFACES1
//----------------------------------------------------------------------------
PointInPolyhedron::PointInPolyhedron ()
:
WindowApplication3("SampleMathematics/PointInPolyhedron", 0, 0, 1024,
768, Float4(0.75f, 0.75f, 0.75f, 1.0f)),
mTextColor(1.0f, 1.0f, 1.0f, 1.0f)
{
mQuery = 0;
mTFaces = 0;
mCFaces = 0;
mSFaces = 0;
mNumRays = 5;
mRayDirections = new1<Vector3f>(mNumRays);
for (int i = 0; i < mNumRays; ++i)
{
double point[3];
RandomPointOnHypersphere(3, point);
for (int j = 0; j < 3; ++j)
{
mRayDirections[i][j] = (float)point[j];
}
}
}
//----------------------------------------------------------------------------
bool PointInPolyhedron::OnInitialize ()
{
if (!WindowApplication3::OnInitialize())
{
return false;
}
// Set up the camera.
mCamera->SetFrustum(60.0f, GetAspectRatio(), 0.001f, 10.0f);
APoint camPosition(4.0f, 0.0f, 0.0f);
AVector camDVector(-1.0f, 0.0f, 0.0f);
AVector camUVector(0.0f, 0.0f, 1.0f);
AVector camRVector = camDVector.Cross(camUVector);
mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector);
CreateScene();
// Initial update of objects.
mScene->Update();
// Initial culling of scene.
mCuller.SetCamera(mCamera);
mCuller.ComputeVisibleSet(mScene);
InitializeCameraMotion(0.01f, 0.01f);
InitializeObjectMotion(mScene);
return true;
}
//----------------------------------------------------------------------------
void PointInPolyhedron::OnTerminate ()
{
delete1(mRayDirections);
mScene = 0;
mWireState = 0;
mPoints = 0;
WindowApplication3::OnTerminate();
}
//----------------------------------------------------------------------------
void PointInPolyhedron::OnIdle ()
{
MeasureTime();
MoveCamera();
MoveObject();
mScene->Update(GetTimeInSeconds());
mCuller.ComputeVisibleSet(mScene);
if (mRenderer->PreDraw())
{
mRenderer->ClearBuffers();
mRenderer->Draw(mCuller.GetVisibleSet());
DrawFrameRate(8, GetHeight()-8, mTextColor);
mRenderer->PostDraw();
mRenderer->DisplayColorBuffer();
}
UpdateFrameCount();
}
//----------------------------------------------------------------------------
bool PointInPolyhedron::OnKeyDown (unsigned char key, int x, int y)
{
if (WindowApplication3::OnKeyDown(key, x, y))
{
return true;
}
switch (key)
{
case 'w':
case 'W':
mWireState->Enabled = !mWireState->Enabled;
break;
}
return false;
}
//----------------------------------------------------------------------------
void PointInPolyhedron::CreateScene ()
{
mScene = new0 Node();
mWireState = new0 WireState();
mRenderer->SetOverrideWireState(mWireState);
// Create a semitransparent sphere mesh.
VertexFormat* vformatMesh = VertexFormat::Create(1,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0);
TriMesh* mesh = StandardMesh(vformatMesh).Sphere(16, 16, 1.0f);
Material* material = new0 Material();
material->Diffuse = Float4(1.0f, 0.0f, 0.0f, 0.25f);
VisualEffectInstance* instance = MaterialEffect::CreateUniqueInstance(
material);
instance->GetEffect()->GetAlphaState(0, 0)->BlendEnabled = true;
mesh->SetEffectInstance(instance);
// Create the data structures for the polyhedron that represents the
// sphere mesh.
CreateQuery(mesh);
// Create a set of random points. Points inside the polyhedron are
// colored white. Points outside the polyhedron are colored blue.
VertexFormat* vformat = VertexFormat::Create(2,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
VertexFormat::AU_COLOR, VertexFormat::AT_FLOAT3, 0);
int vstride = vformat->GetStride();
VertexBuffer* vbuffer = new0 VertexBuffer(1024, vstride);
VertexBufferAccessor vba(vformat, vbuffer);
Float3 white(1.0f, 1.0f, 1.0f);
Float3 blue(0.0f, 0.0f, 1.0f);
for (int i = 0; i < vba.GetNumVertices(); ++i)
{
Vector3f random(Mathf::SymmetricRandom(),
Mathf::SymmetricRandom(), Mathf::SymmetricRandom());
vba.Position<Vector3f>(i) = random;
if (mQuery->Contains(random))
{
vba.Color<Float3>(0, i) = white;
}
else
{
vba.Color<Float3>(0, i) = blue;
}
}
DeleteQuery();
mPoints = new0 Polypoint(vformat, vbuffer);
mPoints->SetEffectInstance(VertexColor3Effect::CreateUniqueInstance());
mScene->AttachChild(mPoints);
mScene->AttachChild(mesh);
}
//----------------------------------------------------------------------------
void PointInPolyhedron::CreateQuery (TriMesh* mesh)
{
const VertexBuffer* vbuffer = mesh->GetVertexBuffer();
const int numVertices = vbuffer->GetNumElements();
const Vector3f* vertices = (Vector3f*)vbuffer->GetData();
const IndexBuffer* ibuffer = mesh->GetIndexBuffer();
const int numIndices = ibuffer->GetNumElements();
const int numFaces = numIndices/3;
const int* indices = (int*)ibuffer->GetData();
const int* currentIndex = indices;
int i;
#ifdef TRIFACES
mTFaces = new1<PointInPolyhedron3f::TriangleFace>(numFaces);
for (i = 0; i < numFaces; ++i)
{
int v0 = *currentIndex++;
int v1 = *currentIndex++;
int v2 = *currentIndex++;
mTFaces[i].Indices[0] = v0;
mTFaces[i].Indices[1] = v1;
mTFaces[i].Indices[2] = v2;
mTFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]);
}
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mTFaces, mNumRays, mRayDirections);
#endif
#if defined(CVXFACES0) || defined(CVXFACES1) || defined(CVXFACES2)
mCFaces = new1<PointInPolyhedron3f::ConvexFace>(numFaces);
for (i = 0; i < numFaces; ++i)
{
int v0 = *currentIndex++;
int v1 = *currentIndex++;
int v2 = *currentIndex++;
mCFaces[i].Indices.resize(3);
mCFaces[i].Indices[0] = v0;
mCFaces[i].Indices[1] = v1;
mCFaces[i].Indices[2] = v2;
mCFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]);
}
#ifdef CVXFACES0
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mCFaces, mNumRays, mRayDirections, 0);
#else
#ifdef CVXFACES1
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mCFaces, mNumRays, mRayDirections, 1);
#else
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mCFaces, mNumRays, mRayDirections, 2);
#endif
#endif
#endif
#if defined (SIMFACES0) || defined (SIMFACES1)
mSFaces = new1<PointInPolyhedron3f::SimpleFace>(numFaces);
for (i = 0; i < numFaces; ++i)
{
int v0 = *currentIndex++;
int v1 = *currentIndex++;
int v2 = *currentIndex++;
mSFaces[i].Indices.resize(3);
mSFaces[i].Indices[0] = v0;
mSFaces[i].Indices[1] = v1;
mSFaces[i].Indices[2] = v2;
mSFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]);
mSFaces[i].Triangles.resize(3);
mSFaces[i].Triangles[0] = v0;
mSFaces[i].Triangles[1] = v1;
mSFaces[i].Triangles[2] = v2;
}
#ifdef SIMFACES0
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mSFaces, mNumRays, mRayDirections, 0);
#else
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mSFaces, mNumRays, mRayDirections, 1);
#endif
#endif
}
//----------------------------------------------------------------------------
void PointInPolyhedron::DeleteQuery ()
{
delete0(mQuery);
#ifdef TRIANGLE_FACES
delete1(mTFaces);
#endif
#if defined(CVXFACES0) || defined(CVXFACES1) || defined(CVXFACES2)
delete1(mCFaces);
#endif
#if defined (SIMFACES0) || defined (SIMFACES1)
delete1(mSFaces);
#endif
}
//----------------------------------------------------------------------------
| 8,572 | 3,128 |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "UObject/LinkerPlaceholderBase.h"
#include "UObject/UnrealType.h"
#include "Blueprint/BlueprintSupport.h"
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
#define DEFERRED_DEPENDENCY_ENSURE(EnsueExpr) ensure(EnsueExpr)
#else // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
#define DEFERRED_DEPENDENCY_ENSURE(EnsueExpr) (EnsueExpr)
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
/*******************************************************************************
* LinkerPlaceholderObjectImpl
******************************************************************************/
/** */
struct FPlaceholderContainerTracker : TThreadSingleton<FPlaceholderContainerTracker>
{
TArray<UObject*> PerspectiveReferencerStack;
TArray<void*> PerspectiveRootDataStack;
// as far as I can tell, structs are going to be the only bridging point
// between property ownership
TArray<const UStructProperty*> IntermediatePropertyStack;
};
/** */
class FLinkerPlaceholderObjectImpl
{
public:
/**
* A recursive method that replaces all leaf references to this object with
* the supplied ReplacementValue.
*
* This function recurses the property chain (from class owner down) because
* at the time of AddReferencingPropertyValue() we cannot know/record the
* address/index of array properties (as they may change during array
* re-allocation or compaction). So we must follow the property chain and
* check every container (array, set, map) property member for references to
* this (hence, the need for this recursive function).
*
* @param PropertyChain An ascending outer chain, where the property at index zero is the leaf (referencer) property.
* @param ChainIndex An index into the PropertyChain that this call should start at and iterate DOWN to zero.
* @param ValueAddress The memory address of the value corresponding to the property at ChainIndex.
* @param OldValue
* @param ReplacementValue The new object to replace all references to this with.
* @return The number of references that were replaced.
*/
static int32 ResolvePlaceholderValues(const TArray<const UProperty*>& PropertyChain, int32 ChainIndex, uint8* ValueAddress, UObject* OldValue, UObject* ReplacementValue);
/**
* Uses the current FPlaceholderContainerTracker::PerspectiveReferencerStack
* to search for a viable placeholder container (expected that it will be
* the top of the stack).
*
* @param PropertyChainRef Defines the nested property path through a UObject, where the end leaf property is one left referencing a placeholder.
* @return The UObject instance that is assumably referencing a placeholder (null if one couldn't be found)
*/
static UObject* FindPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef);
static void* FindRawPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef);
};
//------------------------------------------------------------------------------
int32 FLinkerPlaceholderObjectImpl::ResolvePlaceholderValues(const TArray<const UProperty*>& PropertyChain, int32 ChainIndex, uint8* ValueAddress, UObject* OldValue, UObject* ReplacementValue)
{
int32 ReplacementCount = 0;
for (int32 PropertyIndex = ChainIndex; PropertyIndex >= 0; --PropertyIndex)
{
const UProperty* Property = PropertyChain[PropertyIndex];
if (PropertyIndex == 0)
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(Property->IsA<UObjectProperty>());
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
const UObjectProperty* ReferencingProperty = (const UObjectProperty*)Property;
UObject* CurrentValue = ReferencingProperty->GetObjectPropertyValue(ValueAddress);
if (CurrentValue == OldValue)
{
// @TODO: use an FArchiver with ReferencingProperty->SerializeItem()
// so that we can utilize CheckValidObject()
ReferencingProperty->SetObjectPropertyValue(ValueAddress, ReplacementValue);
// @TODO: unfortunately, this is currently protected
//ReferencingProperty->CheckValidObject(ValueAddress);
++ReplacementCount;
}
}
else if (const UArrayProperty* ArrayProperty = Cast<const UArrayProperty>(Property))
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
const UProperty* NextProperty = PropertyChain[PropertyIndex - 1];
check(NextProperty == ArrayProperty->Inner);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
// because we can't know which array entry was set with a reference
// to this object, we have to comb through them all
FScriptArrayHelper ArrayHelper(ArrayProperty, ValueAddress);
for (int32 ArrayIndex = 0; ArrayIndex < ArrayHelper.Num(); ++ArrayIndex)
{
uint8* MemberAddress = ArrayHelper.GetRawPtr(ArrayIndex);
ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, MemberAddress, OldValue, ReplacementValue);
}
// the above recursive call chewed through the rest of the
// PropertyChain, no need to keep on here
break;
}
else if (const USetProperty* SetProperty = Cast<const USetProperty>(Property))
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
const UProperty* NextProperty = PropertyChain[PropertyIndex - 1];
check(NextProperty == SetProperty->ElementProp);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
// because we can't know which set entry was set with a reference
// to this object, we have to comb through them all
FScriptSetHelper SetHelper(SetProperty, ValueAddress);
int32 Num = SetHelper.Num();
for (int32 SetIndex = 0; Num; ++SetIndex)
{
if (SetHelper.IsValidIndex(SetIndex))
{
--Num;
uint8* ElementAddress = SetHelper.GetElementPtr(SetIndex);
ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, ElementAddress, OldValue, ReplacementValue);
}
}
// the above recursive call chewed through the rest of the
// PropertyChain, no need to keep on here
break;
}
else if (const UMapProperty* MapProperty = Cast<const UMapProperty>(Property))
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
const UProperty* NextProperty = PropertyChain[PropertyIndex - 1];
check(NextProperty == MapProperty->KeyProp);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
// because we can't know which map entry was set with a reference
// to this object, we have to comb through them all
FScriptMapHelper MapHelper(MapProperty, ValueAddress);
int32 Num = MapHelper.Num();
for (int32 MapIndex = 0; Num; ++MapIndex)
{
if (MapHelper.IsValidIndex(MapIndex))
{
--Num;
uint8* KeyAddress = MapHelper.GetKeyPtr(MapIndex);
ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, KeyAddress, OldValue, ReplacementValue);
uint8* MapValueAddress = MapHelper.GetValuePtr(MapIndex);
ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, MapValueAddress, OldValue, ReplacementValue);
}
}
// the above recursive call chewed through the rest of the
// PropertyChain, no need to keep on here
break;
}
else
{
const UProperty* NextProperty = PropertyChain[PropertyIndex - 1];
ValueAddress = NextProperty->ContainerPtrToValuePtr<uint8>(ValueAddress, /*ArrayIndex =*/0);
}
}
return ReplacementCount;
}
//------------------------------------------------------------------------------
UObject* FLinkerPlaceholderObjectImpl::FindPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef)
{
UObject* ContainerObj = nullptr;
TArray<UObject*>& PossibleReferencers = FPlaceholderContainerTracker::Get().PerspectiveReferencerStack;
UClass* OwnerClass = PropertyChainRef.GetOwnerClass();
if ((OwnerClass != nullptr) && (PossibleReferencers.Num() > 0))
{
UObject* ReferencerCandidate = PossibleReferencers.Top();
// we expect that the current object we're looking for (the one we're
// serializing) is at the top of the stack
if (DEFERRED_DEPENDENCY_ENSURE(ReferencerCandidate->GetClass()->IsChildOf(OwnerClass)))
{
ContainerObj = ReferencerCandidate;
}
else
{
// if it's not the top element, then iterate backwards because this
// is meant to act as a stack, where the last entry is most likely
// the one we're looking for
for (int32 CandidateIndex = PossibleReferencers.Num() - 2; CandidateIndex >= 0; --CandidateIndex)
{
ReferencerCandidate = PossibleReferencers[CandidateIndex];
UClass* CandidateClass = ReferencerCandidate->GetClass();
if (CandidateClass->IsChildOf(OwnerClass))
{
ContainerObj = ReferencerCandidate;
break;
}
}
}
}
return ContainerObj;
}
void* FLinkerPlaceholderObjectImpl::FindRawPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef)
{
TArray<void*>& PossibleStructReferencers = FPlaceholderContainerTracker::Get().PerspectiveRootDataStack;
return PossibleStructReferencers[0];
}
/*******************************************************************************
* FPlaceholderContainerTracker / FScopedPlaceholderPropertyTracker
******************************************************************************/
//------------------------------------------------------------------------------
FScopedPlaceholderContainerTracker::FScopedPlaceholderContainerTracker(UObject* InPlaceholderContainerCandidate)
: PlaceholderReferencerCandidate(InPlaceholderContainerCandidate)
{
FPlaceholderContainerTracker::Get().PerspectiveReferencerStack.Add(InPlaceholderContainerCandidate);
}
//------------------------------------------------------------------------------
FScopedPlaceholderContainerTracker::~FScopedPlaceholderContainerTracker()
{
UObject* StackTop = FPlaceholderContainerTracker::Get().PerspectiveReferencerStack.Pop();
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(StackTop == PlaceholderReferencerCandidate);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
}
#if WITH_EDITOR
FScopedPlaceholderRawContainerTracker::FScopedPlaceholderRawContainerTracker(void* InData)
:Data(InData)
{
FPlaceholderContainerTracker::Get().PerspectiveRootDataStack.Add(InData);
}
FScopedPlaceholderRawContainerTracker::~FScopedPlaceholderRawContainerTracker()
{
void* StackTop = FPlaceholderContainerTracker::Get().PerspectiveRootDataStack.Pop();
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(StackTop == Data);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
}
#endif
//------------------------------------------------------------------------------
FScopedPlaceholderPropertyTracker::FScopedPlaceholderPropertyTracker(const UStructProperty* InIntermediateProperty)
: IntermediateProperty(nullptr) // leave null, as a sentinel value (implying that PerspectiveReferencerStack was empty)
{
FPlaceholderContainerTracker& ContainerRepository = FPlaceholderContainerTracker::Get();
if (ContainerRepository.PerspectiveReferencerStack.Num() > 0 || ContainerRepository.PerspectiveRootDataStack.Num() > 0)
{
IntermediateProperty = InIntermediateProperty;
ContainerRepository.IntermediatePropertyStack.Add(InIntermediateProperty);
}
// else, if there's nothing in the PerspectiveReferencerStack, then caching
// a property here would be pointless (the whole point of this is to be able
// to use this to look up the referencing object)
}
//------------------------------------------------------------------------------
FScopedPlaceholderPropertyTracker::~FScopedPlaceholderPropertyTracker()
{
FPlaceholderContainerTracker& ContainerRepository = FPlaceholderContainerTracker::Get();
if (IntermediateProperty != nullptr)
{
const UStructProperty* StackTop = ContainerRepository.IntermediatePropertyStack.Pop();
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(StackTop == IntermediateProperty);
}
else
{
check(ContainerRepository.IntermediatePropertyStack.Num() == 0);
check(ContainerRepository.PerspectiveReferencerStack.Num() == 0);
check(ContainerRepository.PerspectiveRootDataStack.Num() == 0);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
}
}
/*******************************************************************************
* FLinkerPlaceholderBase::FPlaceholderValuePropertyPath
******************************************************************************/
//------------------------------------------------------------------------------
FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::FPlaceholderValuePropertyPath(const UProperty* ReferencingProperty)
{
PropertyChain.Add(ReferencingProperty);
const UObject* PropertyOuter = ReferencingProperty->GetOuter();
const TArray<const UStructProperty*>& StructPropertyStack = FPlaceholderContainerTracker::Get().IntermediatePropertyStack;
int32 StructStackIndex = StructPropertyStack.Num() - 1; // "top" of the array is the last element
while (PropertyOuter && !PropertyOuter->GetClass()->IsChildOf<UClass>())
{
// handle nested properties (like array members)
if (const UProperty* PropertyOwner = Cast<const UProperty>(PropertyOuter))
{
PropertyChain.Add(PropertyOwner);
}
// handle nested struct properties (use the FPlaceholderContainerTracker::IntermediatePropertyStack
// to help trace the property path)
else if (const UScriptStruct* StructOwner = Cast<const UScriptStruct>(PropertyOuter))
{
if (StructStackIndex != INDEX_NONE)
{
// we expect the top struct property to be the one we're currently serializing
const UStructProperty* SerializingStructProp = StructPropertyStack[StructStackIndex];
if (DEFERRED_DEPENDENCY_ENSURE(SerializingStructProp->Struct->IsChildOf(StructOwner)))
{
PropertyOuter = SerializingStructProp;
PropertyChain.Add(SerializingStructProp);
}
else
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
PropertyChain.Empty(); // invalidate this FPlaceholderValuePropertyPath
checkf(false, TEXT("Looks like we couldn't reliably determine the object that a placeholder value should belong to - are we missing a FScopedPlaceholderPropertyTracker?"));
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TEST
break;
}
--StructStackIndex;
}
else
{
// We're serializing a struct that isn't owned by a UObject (e.g. UUserDefinedStructEditorData::DefaultStructInstance)
break;
}
}
PropertyOuter = PropertyOuter->GetOuter();
}
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
if (!DEFERRED_DEPENDENCY_ENSURE(PropertyOuter != nullptr))
{
PropertyChain.Empty(); // invalidate this FPlaceholderValuePropertyPath
}
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TEST
}
//------------------------------------------------------------------------------
bool FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::IsValid() const
{
return (PropertyChain.Num() > 0) && PropertyChain[0]->IsA<UObjectProperty>() && PropertyChain.Last()->GetOuter()->IsA<UClass>();
}
//------------------------------------------------------------------------------
UClass* FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::GetOwnerClass() const
{
return (PropertyChain.Num() > 0) ? Cast<UClass>(PropertyChain.Last()->GetOuter()) : nullptr;
}
//------------------------------------------------------------------------------
int32 FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::Resolve(FLinkerPlaceholderBase* Placeholder, UObject* Replacement, UObject* Container) const
{
const UProperty* OutermostProperty = PropertyChain.Last();
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
UClass* OwnerClass = OutermostProperty->GetOwnerClass();
check(OwnerClass && Container->IsA(OwnerClass));
#endif
uint8* OutermostAddress = OutermostProperty->ContainerPtrToValuePtr<uint8>((uint8*)Container, /*ArrayIndex =*/0);
return FLinkerPlaceholderObjectImpl::ResolvePlaceholderValues(PropertyChain, PropertyChain.Num() - 1, OutermostAddress, Placeholder->GetPlaceholderAsUObject(), Replacement);
}
int32 FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::ResolveRaw(FLinkerPlaceholderBase* Placeholder, UObject* Replacement, void* Container) const
{
const UProperty* OutermostProperty = PropertyChain.Last();
uint8* OutermostAddress = OutermostProperty->ContainerPtrToValuePtr<uint8>((uint8*)Container, /*ArrayIndex =*/0);
return FLinkerPlaceholderObjectImpl::ResolvePlaceholderValues(PropertyChain, PropertyChain.Num() - 1, OutermostAddress, Placeholder->GetPlaceholderAsUObject(), Replacement);;
}
/*******************************************************************************
* FLinkerPlaceholderBase
******************************************************************************/
//------------------------------------------------------------------------------
FLinkerPlaceholderBase::FLinkerPlaceholderBase()
: bResolveWasInvoked(false)
{
}
//------------------------------------------------------------------------------
FLinkerPlaceholderBase::~FLinkerPlaceholderBase()
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(!HasKnownReferences());
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
}
//------------------------------------------------------------------------------
bool FLinkerPlaceholderBase::AddReferencingPropertyValue(const UObjectProperty* ReferencingProperty, void* DataPtr)
{
FPlaceholderValuePropertyPath PropertyChain(ReferencingProperty);
UObject* ReferencingContainer = FLinkerPlaceholderObjectImpl::FindPlaceholderContainer(PropertyChain);
if (ReferencingContainer != nullptr)
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(ReferencingProperty->GetObjectPropertyValue(DataPtr) == GetPlaceholderAsUObject());
check(PropertyChain.IsValid());
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
ReferencingContainers.FindOrAdd(ReferencingContainer).Add(PropertyChain);
return true;
}
else
{
void* ReferencingRootStruct = FLinkerPlaceholderObjectImpl::FindRawPlaceholderContainer(PropertyChain);
if (ReferencingRootStruct)
{
ReferencingRawContainers.FindOrAdd(ReferencingRootStruct).Add(PropertyChain);
}
return ReferencingRootStruct != nullptr;
}
}
//------------------------------------------------------------------------------
bool FLinkerPlaceholderBase::HasKnownReferences() const
{
return (ReferencingContainers.Num() > 0) || ReferencingRawContainers.Num() > 0;
}
//------------------------------------------------------------------------------
int32 FLinkerPlaceholderBase::ResolveAllPlaceholderReferences(UObject* ReplacementObj)
{
int32 ReplacementCount = ResolvePlaceholderPropertyValues(ReplacementObj);
ReferencingContainers.Empty();
ReferencingRawContainers.Empty();
MarkAsResolved();
return ReplacementCount;
}
//------------------------------------------------------------------------------
bool FLinkerPlaceholderBase::HasBeenFullyResolved() const
{
return IsMarkedResolved() && !HasKnownReferences();
}
//------------------------------------------------------------------------------
bool FLinkerPlaceholderBase::IsMarkedResolved() const
{
return bResolveWasInvoked;
}
//------------------------------------------------------------------------------
void FLinkerPlaceholderBase::MarkAsResolved()
{
bResolveWasInvoked = true;
}
//------------------------------------------------------------------------------
int32 FLinkerPlaceholderBase::ResolvePlaceholderPropertyValues(UObject* NewObjectValue)
{
int32 ResolvedTotal = 0;
for (auto& ReferencingPair : ReferencingContainers)
{
TWeakObjectPtr<UObject> ContainerPtr = ReferencingPair.Key;
if (!ContainerPtr.IsValid())
{
continue;
}
UObject* Container = ContainerPtr.Get();
for (const FPlaceholderValuePropertyPath& PropertyRef : ReferencingPair.Value)
{
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(Container->GetClass()->IsChildOf(PropertyRef.GetOwnerClass()));
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
int32 ResolvedCount = PropertyRef.Resolve(this, NewObjectValue, Container);
ResolvedTotal += ResolvedCount;
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
// we expect that (because we have had ReferencingProperties added)
// there should be at least one reference that is resolved... if
// there were none, then a property could have changed its value
// after it was set to this
//
// NOTE: this may seem it can be resolved by properties removing themselves
// from ReferencingProperties, but certain properties may be
// the inner of a container (array, set, map) property (meaning
// there could be multiple references per property)... we'd
// have to inc/decrement a property ref-count to resolve that
// scenario
check(ResolvedCount > 0);
#endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
}
}
for (auto& ReferencingRawPair : ReferencingRawContainers)
{
void* RawValue = ReferencingRawPair.Key;
check(RawValue);
for (const FPlaceholderValuePropertyPath& PropertyRef : ReferencingRawPair.Value)
{
int32 ResolvedCount = PropertyRef.ResolveRaw(this, NewObjectValue, RawValue);
ResolvedTotal += ResolvedCount;
#if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS
check(ResolvedCount > 0);
#endif
}
}
return ResolvedTotal;
}
/*******************************************************************************
* TLinkerImportPlaceholder<UClass>
******************************************************************************/
//------------------------------------------------------------------------------
template<>
int32 TLinkerImportPlaceholder<UClass>::ResolvePropertyReferences(UClass* ReplacementClass)
{
int32 ReplacementCount = 0;
UClass* PlaceholderClass = CastChecked<UClass>(GetPlaceholderAsUObject());
for (UProperty* Property : ReferencingProperties)
{
if (UObjectPropertyBase* BaseObjProperty = Cast<UObjectPropertyBase>(Property))
{
if (BaseObjProperty->PropertyClass == PlaceholderClass)
{
BaseObjProperty->PropertyClass = ReplacementClass;
++ReplacementCount;
}
if (UClassProperty* ClassProperty = Cast<UClassProperty>(BaseObjProperty))
{
if (ClassProperty->MetaClass == PlaceholderClass)
{
ClassProperty->MetaClass = ReplacementClass;
++ReplacementCount;
}
}
else if (USoftClassProperty* SoftClassProperty = Cast<USoftClassProperty>(BaseObjProperty))
{
if (SoftClassProperty->MetaClass == PlaceholderClass)
{
SoftClassProperty->MetaClass = ReplacementClass;
++ReplacementCount;
}
}
}
else if (UInterfaceProperty* InterfaceProp = Cast<UInterfaceProperty>(Property))
{
if (InterfaceProp->InterfaceClass == PlaceholderClass)
{
InterfaceProp->InterfaceClass = ReplacementClass;
++ReplacementCount;
}
}
else
{
checkf(TEXT("Unhandled property type: %s"), *Property->GetClass()->GetName());
}
}
ReferencingProperties.Empty();
return ReplacementCount;
}
/*******************************************************************************
* TLinkerImportPlaceholder<UFunction>
******************************************************************************/
//------------------------------------------------------------------------------
template<>
int32 TLinkerImportPlaceholder<UFunction>::ResolvePropertyReferences(UFunction* ReplacementFunc)
{
int32 ReplacementCount = 0;
UFunction* PlaceholderFunc = CastChecked<UFunction>(GetPlaceholderAsUObject());
for (UProperty* Property : ReferencingProperties)
{
if (UDelegateProperty* DelegateProperty = Cast<UDelegateProperty>(Property))
{
if (DelegateProperty->SignatureFunction == PlaceholderFunc)
{
DelegateProperty->SignatureFunction = ReplacementFunc;
++ReplacementCount;
}
}
else if (UMulticastDelegateProperty* MulticastDelegateProperty = Cast<UMulticastDelegateProperty>(Property))
{
if (MulticastDelegateProperty->SignatureFunction == PlaceholderFunc)
{
MulticastDelegateProperty->SignatureFunction = ReplacementFunc;
++ReplacementCount;
}
}
else
{
checkf(TEXT("Unhandled property type: %s"), *Property->GetClass()->GetName());
}
}
ReferencingProperties.Empty();
return ReplacementCount;
}
#undef DEFERRED_DEPENDENCY_ENSURE
| 24,417 | 7,542 |
// 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/cuda/sequence_arithmetic_compute.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "lite/core/op_registry.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace cuda {
void sequence_arithmetic_compute_ref(const Tensor& x,
const Tensor& y,
Tensor* out,
int op_type) {
auto x_data = x.data<float>();
auto y_data = y.data<float>();
out->Resize(x.dims());
out->set_lod(x.lod());
auto out_data = out->mutable_data<float>();
auto x_seq_offset = x.lod()[0];
auto y_seq_offset = y.lod()[0];
int seq_num = x_seq_offset.size() - 1;
int inner_size = x.numel() / x.dims()[0];
for (int i = 0; i < seq_num; i++) {
int len_x = (x_seq_offset[i + 1] - x_seq_offset[i]) * inner_size;
int len_y = (y_seq_offset[i + 1] - y_seq_offset[i]) * inner_size;
auto input_x = x_data + x_seq_offset[i] * inner_size;
auto input_y = y_data + y_seq_offset[i] * inner_size;
auto t_out = out_data + x_seq_offset[i] * inner_size;
int len = std::min(len_x, len_y);
for (int j = 0; j < len; j++) {
switch (op_type) {
case 1:
t_out[j] = input_x[j] + input_y[j];
break;
case 2:
t_out[j] = input_x[j] - input_y[j];
break;
case 3:
t_out[j] = input_x[j] * input_y[j];
break;
default:
break;
}
}
if (len_x > len) {
memcpy(t_out + len, input_x + len, sizeof(float) * (len_x - len));
}
}
}
void prepare_input(Tensor* x, const LoD& x_lod) {
x->Resize({static_cast<int64_t>(x_lod[0].back()), 3});
x->set_lod(x_lod);
auto x_data = x->mutable_data<float>();
for (int i = 0; i < x->numel(); i++) {
x_data[i] = (i - x->numel() / 2) * 1.1;
}
}
TEST(sequence_arithmetic_cuda, run_test) {
lite::Tensor x, y, x_cpu, y_cpu;
lite::Tensor out, out_cpu, out_ref;
lite::LoD x_lod{{0, 2, 5, 9}}, y_lod{{0, 2, 5, 9}};
prepare_input(&x_cpu, x_lod);
prepare_input(&y_cpu, y_lod);
x.Resize(x_cpu.dims());
x.set_lod(x_cpu.lod());
auto x_cpu_data = x_cpu.mutable_data<float>();
x.Assign<float, lite::DDim, TARGET(kCUDA)>(x_cpu_data, x_cpu.dims());
y.Resize(y_cpu.dims());
y.set_lod(y_cpu.lod());
auto y_cpu_data = y_cpu.mutable_data<float>();
y.Assign<float, lite::DDim, TARGET(kCUDA)>(y_cpu_data, y_cpu.dims());
operators::SequenceArithmeticParam param;
param.X = &x;
param.Y = &y;
param.Out = &out;
param.op_type = 1;
std::unique_ptr<KernelContext> ctx(new KernelContext);
auto& context = ctx->As<CUDAContext>();
cudaStream_t stream;
cudaStreamCreate(&stream);
context.SetExecStream(stream);
SequenceArithmeticCompute sequence_arithmetic;
sequence_arithmetic.SetContext(std::move(ctx));
sequence_arithmetic.SetParam(param);
sequence_arithmetic.Run();
cudaDeviceSynchronize();
auto out_data = out.mutable_data<float>(TARGET(kCUDA));
out_cpu.Resize(out.dims());
auto out_cpu_data = out_cpu.mutable_data<float>();
CopySync<TARGET(kCUDA)>(
out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH);
sequence_arithmetic_compute_ref(x_cpu, y_cpu, &out_ref, param.op_type);
auto out_ref_data = out_ref.data<float>();
for (int i = 0; i < out.numel(); i++) {
EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-3);
}
}
} // namespace cuda
} // namespace kernels
} // namespace lite
} // namespace paddle
| 4,171 | 1,665 |
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
// For other contributors see Contributors.txt
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#pragma once
#include <sfz/memory/Allocator.hpp>
#include <sfz/memory/SmartPointers.hpp>
#include "ph/game_loop/GameLoopUpdateable.hpp"
namespace ph {
using sfz::Allocator;
using sfz::UniquePtr;
using sfz::vec3;
using sfz::vec4;
// DefaultGameUpdateable logic
// ------------------------------------------------------------------------------------------------
struct ImguiControllers final {
bool useMouse = true;
bool useKeyboard = true;
int32_t controllerIndex = -1;
};
class GameLogic {
public:
virtual ~GameLogic() {}
virtual void initialize(Renderer& renderer) = 0;
// Returns the index of the controller to be used for Imgui. If -1 is returned no controller
// input will be provided to Imgui.
virtual ImguiControllers imguiController(const UserInput&) { return ImguiControllers(); }
virtual UpdateOp processInput(
const UserInput& input,
const UpdateInfo& updateInfo,
Renderer& renderer) = 0;
virtual UpdateOp updateTick(const UpdateInfo& updateInfo, Renderer& renderer) = 0;
virtual void render(const UpdateInfo& updateInfo, Renderer& renderer) = 0;
// Small hook that is called last in a frame, after rendering, regardless of whether the
// console is active or not.
//
// This is useful if you need to do some operations each frame when the renderer is not busy
// preparing commands to render a new frame (i.e., not between beginFrame() and finishFrame()).
//
// This is also the last thing that happens each frame, so it can also be a good place to put
// some per frame book keeping you are doing.
virtual void postRenderHook(ph::Renderer& renderer, bool consoleActive) {};
// Renders custom Imgui commands.
//
// This function and injectConsoleMenu() are the only places where Imgui commands can safely
// be called. BeginFrame() and EndFrame() are called before and after this function. Other
// Imgui commands from the DefaultGameUpdateable console itself may be sent within this same
// frame if they are set to be always shown. This function will not be called if the console
// is currently active.
virtual void renderCustomImgui() {}
// Call when console is active after all the built-in menus have been drawn. Can be used to
// inject game-specific custom menus into the console.
virtual void injectConsoleMenu() {}
// These two functions are used to dock injected console windows. The first one should return
// the number of windows you want to dock, the second one the name of each window given the
// index in the range you provided with the first function. These are typically only called
// during the first boot of the engine/game. You don't need to provide them even if you are
// injecting console windows;
virtual uint32_t injectConsoleMenuNumWindowsToDockInitially() { return 0; }
virtual const char* injectConsoleMenuNameOfWindowToDockInitially(uint32_t idx) { (void)idx; return nullptr; }
// Called when console is activated. The logic instance will not receive any additional calls
// until the console is closed, at which point onConsoleDeactivated() will be called. onQuit()
// may be called before the console is deactivated.
virtual void onConsoleActivated() {}
// Called when the console is deactivated.
virtual void onConsoleDeactivated() {}
virtual void onQuit() { }
};
// DefaultGameUpdateable creation function
// ------------------------------------------------------------------------------------------------
UniquePtr<GameLoopUpdateable> createDefaultGameUpdateable(
Allocator* allocator,
UniquePtr<GameLogic> logic) noexcept;
} // namespace ph
| 4,564 | 1,226 |
#include "CEGame.h"
#include <spdlog/spdlog.h>
#include <windowsx.h>
#include "CEConsole.h"
#include "../Graphics/DirectX12/CEDX12Manager.h"
#include "../Graphics/Vulkan/CEVManager.h"
#include "../Graphics/OpenGL/CEOGLManager.h"
namespace GameEngine = ConceptEngineFramework::Game;
namespace GraphicsEngine = ConceptEngineFramework::Graphics;
namespace DirectXGraphicsEngine = GraphicsEngine::DirectX12;
namespace VulkanGraphicsEngine = GraphicsEngine::Vulkan;
namespace OpenGLGraphicsEngine = GraphicsEngine::OpenGL;
static GameEngine::CEGame* g_pGame = nullptr;
/*
* Instance for std::shared_ptr
*/
class CEConsoleInstance final : public GameEngine::CEConsole {
public:
CEConsoleInstance(const std::wstring& windowName, int maxFileSizeInMB = 5, int maxFiles = 3,
int maxConsoleLines = 500)
: CEConsole(windowName, maxFileSizeInMB, maxFiles, maxConsoleLines) {
spdlog::info("ConceptEngineFramework Console class created.");
}
explicit CEConsoleInstance(const Logger& logger)
: CEConsole(logger) {
spdlog::info("ConceptEngineFramework Console class created.");
CE_LOG("ConceptEngineFramework Console class created.");
}
};
class CEWindowInstance final : public GameEngine::CEWindow {
public:
CEWindowInstance(const std::wstring& windowName, HINSTANCE hInstance, int width, int height)
: CEWindow(windowName, hInstance, width, height) {
spdlog::info("ConceptEngineFramework Window class created.");
}
CEWindowInstance(const std::wstring& windowName, HWND hwnd, int width, int height)
: CEWindow(windowName, hwnd, width, height) {
spdlog::info("ConceptEngineFramework Window class created.");
CE_LOG("ConceptEngineFramework Console class created.")
}
};
class CEDX12ManagerInstance final : public DirectXGraphicsEngine::CEDX12Manager {
public:
CEDX12ManagerInstance(ConceptEngineFramework::Game::CEWindow* window): CEDX12Manager(window) {
spdlog::info("ConceptEngineFramework DirectX 12 Manager class created.");
}
CEDX12ManagerInstance(): CEDX12Manager() {
spdlog::info("ConceptEngineFramework DirectX 12 Manager class created.");
CE_LOG("ConceptEngineFramework DirectX 12 Manager class created.")
}
};
class CEVManagerInstance final : public VulkanGraphicsEngine::CEVManager {
public:
CEVManagerInstance(): CEVManager() {
spdlog::info("ConceptEngineFramework Vulkan Manager class created.");
CE_LOG("ConceptEngineFramework Vulkan Manager class created.")
}
};
class CEOGLManagerInstance final : public OpenGLGraphicsEngine::CEOGLManager {
public:
CEOGLManagerInstance(): CEOGLManager() {
spdlog::info("ConceptEngineFramework OpenGL Manager class created.");
CE_LOG("ConceptEngineFramework OpenGL Manager class created.")
}
};
GameEngine::CEGame::CEGame(std::wstring name,
HINSTANCE hInst,
int width,
int height,
Graphics::API graphicsAPI,
Graphics::CEPlayground* playground) :
m_name(name),
m_hInstance(hInst),
m_width(width),
m_height(height),
m_graphicsAPI(graphicsAPI),
m_systemInfo{},
m_playground(playground) {
}
GameEngine::CEGame::CEGame(HWND hWnd, Graphics::API graphicsAPI, int width, int height,
Graphics::CEPlayground* playground): m_hwnd(hWnd),
m_graphicsAPI(graphicsAPI),
m_systemInfo{},
m_width(width),
m_height(height),
m_playground(playground) {
}
void GameEngine::CEGame::Init() {
SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
CreateConsole(m_name);
CreateMainWindow(m_name, m_width, m_height);
m_window->InitWindow();
SystemInfo();
CreateGraphicsManager(m_graphicsAPI);
}
void GameEngine::CEGame::LinkWithEditor() {
CreateEditorWindow(m_name, m_hwnd, m_width, m_height);
SystemInfo();
CreateEditorGraphicsManager(m_graphicsAPI);
}
CETimer ConceptEngineFramework::Game::CEGame::GetTimer() const {
return m_timer;
}
void ConceptEngineFramework::Game::CEGame::EditorUpdateTimer() {
m_timer.Update();
CalculateFPS(false);
}
void ConceptEngineFramework::Game::CEGame::EditorUpdate() const {
m_graphicsManager->Update(m_timer);
}
void ConceptEngineFramework::Game::CEGame::EditorRender() const {
m_graphicsManager->Render(m_timer);
}
void ConceptEngineFramework::Game::CEGame::EditorResize(int width, int height) const {
m_window->SetWidth(width);
m_window->SetHeight(height);
m_graphicsManager->Resize();
}
GameEngine::CEGame& GameEngine::CEGame::Create(std::wstring name, HINSTANCE hInst, int width, int height,
Graphics::API graphicsAPI, Graphics::CEPlayground* playground) {
if (!g_pGame) {
g_pGame = new CEGame(name, hInst, width, height, graphicsAPI, playground);
spdlog::info("ConceptEngineFramework Game class created.");
}
return *g_pGame;
}
ConceptEngineFramework::Game::CEGame& ConceptEngineFramework::Game::CEGame::Create(
HWND hWnd, Graphics::API graphicsAPI, int width, int height,
Graphics::CEPlayground* playground) {
if (!g_pGame) {
g_pGame = new CEGame(hWnd, graphicsAPI, width, height, playground);
spdlog::info("ConceptEngineFramework Game class created.");
}
return *g_pGame;
}
void ConceptEngineFramework::Game::CEGame::SystemInfo() {
m_systemInfo = GetEngineSystemInfo();
spdlog::info("CPU: {}, Threads: {}, RAM: {} MB", m_systemInfo.CPUName, m_systemInfo.CPUCores, m_systemInfo.RamSize);
std::stringstream ss;
ss << "CPU: " << m_systemInfo.CPUName << ", Threads: " << m_systemInfo.CPUCores << " RAM: " << m_systemInfo.RamSize
<< "MB";
CE_LOG(ss.str())
}
void ConceptEngineFramework::Game::CEGame::CalculateFPS(bool showInTitleBar) const {
static int frameCount = 0;
static float timeElapsed = 0.0f;
frameCount++;
//Compute averages over one second period.
if ((m_timer.TotalTime() - timeElapsed) >= 1.0f) {
float fps = (float)frameCount;
float msPerFrame = 1000.0f / fps;
spdlog::info("FPS: {}", fps);
spdlog::info("MSPF: {}", msPerFrame);
std::stringstream fpsSS;
fpsSS << "FPS: " << fps;
// CE_LOG(fpsSS.str())
std::stringstream mspfSS;
mspfSS << "MSPF: " << msPerFrame;
// CE_LOG(mspfSS.str())
if (showInTitleBar) {
std::wstring wFps = std::to_wstring(fps);
std::wstring wMsPerFrame = std::to_wstring(msPerFrame);
std::wstring fpsWindowName = m_window->GetName() +
L" fps: " + wFps +
L" mspf: " + wMsPerFrame;
}
frameCount = 0;
timeElapsed += 1.0f;
}
}
LRESULT GameEngine::CEGame::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
// WM_ACTIVATE is sent when the window is activated or deactivated.
// We pause the game when the window is deactivated and unpause it
// when it becomes active.
case WM_ACTIVATE:
/*
* NOTE: Potential reason of bug
if (LOWORD(wParam) == WA_INACTIVE) {
m_paused = true;
m_timer.Stop();
}
else {
m_paused = false;
m_timer.Start();
}
*/
return 0;
// WM_SIZE is sent when the user resizes the window.
case WM_SIZE:
// Save the new client area dimensions.
m_window->SetResolution(LOWORD(lParam), HIWORD(lParam));
if (m_graphicsManager) {
if (m_graphicsManager->Initialized()) {
if (wParam == SIZE_MINIMIZED) {
m_paused = true;
m_minimized = true;
m_maximized = false;
}
else if (wParam == SIZE_MAXIMIZED) {
m_paused = false;
m_minimized = false;
m_maximized = true;
m_graphicsManager->Resize();
}
else if (wParam == SIZE_RESTORED) {
if (m_minimized) {
m_paused = false;
m_minimized = false;
m_graphicsManager->Resize();
}
else if (m_maximized) {
m_paused = false;
m_maximized = false;
m_graphicsManager->Resize();
}
else if (m_resizing) {
// If user is dragging the resize bars, we do not resize
// the buffers here because as the user continuously
// drags the resize bars, a stream of WM_SIZE messages are
// sent to the window, and it would be pointless (and slow)
// to resize for each WM_SIZE message received from dragging
// the resize bars. So instead, we reset after the user is
// done resizing the window and releases the resize bars, which
// sends a WM_EXITSIZEMOVE message.
}
else {
m_graphicsManager->Resize();
}
}
}
}
return 0;
// WM_EXITSIZEMOVE is sent when the user grabs the resize bars.
case WM_ENTERSIZEMOVE:
m_paused = true;
m_resizing = true;
m_timer.Stop();
return 0;
// WM_EXITSIZEMOVE is sent when the user releases the resize bars.
// Here we reset everything based on the new window dimensions.
case WM_EXITSIZEMOVE:
m_paused = false;
m_resizing = false;
m_timer.Start();
m_graphicsManager->Resize();
return 0;
// WM_DESTROY is sent when the window is being destroyed.
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// The WM_MENUCHAR message is sent when a menu is active and the user presses
// a key that does not correspond to any mnemonic or accelerator key.
case WM_MENUCHAR:
// Don't beep when we alt-enter.
return MAKELRESULT(0, MNC_CLOSE);
// Catch this message so to prevent the window from becoming too small.
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 200;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 200;
return 0;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
OnMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
OnMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MOUSEMOVE:
OnMouseMove(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_KEYUP:
case WM_SYSKEYUP:
if (wParam == VK_ESCAPE) {
PostQuitMessage(0);
}
else {
OnKeyUp(wParam, lParam, m_timer);
}
return 0;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
OnKeyDown(wParam, lParam, m_timer);
OnKeyDown(wParam, lParam, m_timer);
return 0;
case WM_MOUSEWHEEL: {
OnMouseWheel(wParam, lParam, hwnd);
}
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
GameEngine::CEGame& GameEngine::CEGame::Get() {
assert(g_pGame != nullptr);
return *g_pGame;
}
//TODO: In editor mode instead of call Run, call every function from graphicsManager separately and use connect QT method to bind it with playground
uint32_t GameEngine::CEGame::Run() {
MSG msg = {0};
m_timer.Reset();
while (msg.message != WM_QUIT) {
// If there are Window messages then process them.
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Otherwise, do animation/game stuff.
else {
m_timer.Update();
if (!m_paused) {
CalculateFPS(true);
m_graphicsManager->Update(m_timer);
m_graphicsManager->Render(m_timer);
}
else {
Sleep(100);
}
}
}
return (int)msg.wParam;
}
std::shared_ptr<GameEngine::CEConsole> GameEngine::CEGame::GetConsole() {
return m_console;
}
void GameEngine::CEGame::CreateMainWindow(const std::wstring& windowName, int width, int height) {
m_window = std::make_shared<CEWindowInstance>(windowName, m_hInstance, width, height);
m_window->Create();
}
void ConceptEngineFramework::Game::CEGame::CreateEditorWindow(const std::wstring& windowName, HWND hwnd, int width,
int height) {
m_window = std::make_shared<CEWindowInstance>(windowName, hwnd, width, height);
}
void GameEngine::CEGame::CreateGraphicsManager(Graphics::API graphicsAPI) {
switch (graphicsAPI) {
case Graphics::API::DirectX12_API:
m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get());
break;
case Graphics::API::Vulkan_API:
m_graphicsManager = std::make_shared<CEVManagerInstance>();
break;
case Graphics::API::OpenGL_API:
m_graphicsManager = std::make_shared<CEOGLManagerInstance>();
break;
default:
m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get());
break;
}
m_graphicsManager->InitPlayground(m_playground);
m_graphicsManager->Create();
}
void ConceptEngineFramework::Game::CEGame::CreateEditorGraphicsManager(Graphics::API graphicsAPI) {
switch (graphicsAPI) {
case Graphics::API::DirectX12_API:
m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get());
break;
case Graphics::API::Vulkan_API:
m_graphicsManager = std::make_shared<CEVManagerInstance>();
break;
case Graphics::API::OpenGL_API:
m_graphicsManager = std::make_shared<CEOGLManagerInstance>();
break;
default:
m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get());
break;
}
m_graphicsManager->InitPlayground(m_playground);
m_graphicsManager->Create();
}
void GameEngine::CEGame::CreateConsole(const std::wstring& windowName) {
m_console = std::make_shared<CEConsoleInstance>(windowName);
m_console->Create();
}
| 13,238 | 4,848 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "HotUpdateSubsystem.h"
#include "Serialization/JsonSerializer.h"
#include "FileDownloadManager.h"
#include "FileDownLog.h"
#include "IPlatformFilePak.h"
#include "HttpModule.h"
#include "TimerManager.h"
#include "Kismet/GameplayStatics.h"
#include "Misc/NetworkVersion.h"
#include "Interfaces/IHttpResponse.h"
#include "HotUpdateSettings.h"
#include "Policies/CondensedJsonPrintPolicy.h"
void UHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
if (CanSkipUpdate())
{
return;
}
bIsUpdating = true;
DownloadManager = MakeShareable(new FFileDownloadManager());
if (!DownloadManager.IsValid())
{
return;
}
DownloadManager->OnDownloadEvent.BindUObject(this, &UHotUpdateSubsystem::OnDownloadEvent);
PakManager = MakeShareable(new FFilePakManager());
if (PakManager.IsValid())
{
PakManager->OnMountUpdated.BindUObject(this, &UHotUpdateSubsystem::OnMountProcess);
}
OnHotUpdateStateEvent.BindUObject(this, &UHotUpdateSubsystem::OnHotUpdateState);
}
void UHotUpdateSubsystem::Deinitialize()
{
ShutDown();
Super::Deinitialize();
}
void UHotUpdateSubsystem::StartUp()
{
if (CanSkipUpdate())
{
OnSkipUpdate();
return;
}
ReqGetVersion();
}
void UHotUpdateSubsystem::ShutDown()
{
if (Request.IsValid())
{
Request->OnProcessRequestComplete().Unbind();
}
if (DownloadManager.IsValid())
{
DownloadManager->ShutDown();
DownloadManager = nullptr;
}
if (PakManager.IsValid())
{
PakManager->ShutDown();
PakManager = nullptr;
}
bIsUpdating = false;
}
bool UHotUpdateSubsystem::CanSkipUpdate()
{
#if WITH_EDITOR
return false;
#else
return false;
#endif
}
void UHotUpdateSubsystem::ForceSkipUpdate() const
{
if (CanSkipUpdate())
{
return;
}
if (IsFinished())
{
return;
}
OnSkipUpdate();
}
void UHotUpdateSubsystem::OnSkipUpdate() const
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::END_HOTUPDATE, TEXT("OnSkipUpdate"));
}
FString UHotUpdateSubsystem::GetPlatform()
{
#if PLATFORM_DESKTOP && WITH_EDITOR
return TEXT("editor");
#elif PLATFORM_WINDOWS
return TEXT("win");
#elif PLATFORM_ANDROID
return TEXT("android");
#elif PLATFORM_IOS
return TEXT("ios");
#elif PLATFORM_MAC
return TEXT("mac");
#elif PLATFORM_LINUX
return TEXT("linux");
#endif
}
void UHotUpdateSubsystem::OnMountProcess(const FString& PakName, const float Progress) const
{
OnMountUpdate.Broadcast(PakName, Progress);
}
void UHotUpdateSubsystem::OnHotUpdateState(const EHotUpdateState State, const FString& Message)
{
if (State != EHotUpdateState::ERROR)
{
UE_LOG(LogHotUpdate, Log, TEXT("OnHotUpdateState %s"), *Message);
}
else
{
UE_LOG(LogHotUpdate, Error, TEXT("OnHotUpdateState %s"), *Message);
}
switch (State)
{
case EHotUpdateState::END_GETVERSION:
{
if (DownloadManager.IsValid())
{
DownloadManager->StartUp();
}
}
break;
case EHotUpdateState::END_DOWNLOAD:
{
OnUpdateDownloadProgress();
OnHotUpdateStateEvent.Execute(EHotUpdateState::BEGIN_MOUNT, TEXT("BeginMount"));
}
break;
case EHotUpdateState::BEGIN_MOUNT:
{
if (PakManager.IsValid())
{
PakManager->StartUp();
if (PakManager->IsSuccessful())
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::END_MOUNT, TEXT("EndMount"));
}
else
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::ERROR, TEXT("Mount failed"));
}
}
}
break;
case EHotUpdateState::END_MOUNT:
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::END_HOTUPDATE, TEXT("FinishUpdate"));
}
break;
case EHotUpdateState::END_HOTUPDATE:
{
if (IsSuccessful())
{
ShutDown();
OnHotUpdateFinished.Broadcast();
}
else
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::ERROR, TEXT("Is not successful"));
}
}
break;
default: break;
}
}
void UHotUpdateSubsystem::ReqGetVersion()
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::BEGIN_GETVERSION, TEXT("Begin to get version"));
FString JsonStr;
auto JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&JsonStr);
JsonWriter->WriteObjectStart();
JsonWriter->WriteValue(TEXT("version"), FNetworkVersion::GetProjectVersion());
JsonWriter->WriteValue(TEXT("platform"), GetPlatform());
JsonWriter->WriteObjectEnd();
JsonWriter->Close();
const auto URL = GetHotUpdateServerUrl();
if (!Request.IsValid())
{
Request = FHttpModule::Get().CreateRequest();
}
Request->SetHeader(TEXT("Content-Type"), TEXT("application/json; charset=utf-8"));
Request->SetURL(URL);
Request->SetVerb(TEXT("POST"));
Request->SetContentAsString(JsonStr);
Request->OnProcessRequestComplete().BindUObject(this, &UHotUpdateSubsystem::RetGetVersion);
Request->ProcessRequest();
const auto HotUpdateSettings = GetMutableDefault<UHotUpdateSettings>();
GetWorld()->GetTimerManager().SetTimer(TimeOutHandle, this, &UHotUpdateSubsystem::OnReqGetVersionTimeOut,
HotUpdateSettings != nullptr ? HotUpdateSettings->TimeOutDelay : 10.f,
false);
}
void UHotUpdateSubsystem::OnReqGetVersionTimeOut()
{
if (Request.IsValid())
{
Request->OnProcessRequestComplete().Unbind();
}
CurrentTimeRetry++;
const auto HotUpdateSettings = GetMutableDefault<UHotUpdateSettings>();
const auto MaxRetryTime = HotUpdateSettings != nullptr ? HotUpdateSettings->MaxRetryTime : 3;
if (CurrentTimeRetry <= MaxRetryTime)
{
ReqGetVersion();
}
else
{
CurrentTimeRetry = 0;
GetWorld()->GetTimerManager().ClearTimer(TimeOutHandle);
OnHotUpdateStateEvent.Execute(EHotUpdateState::ERROR, TEXT("Error: Failed to req version"));
}
}
void UHotUpdateSubsystem::RetGetVersion(FHttpRequestPtr, const FHttpResponsePtr Response,
const bool bConnectedSuccessfully)
{
if (TimeOutHandle.IsValid())
{
GetWorld()->GetTimerManager().ClearTimer(TimeOutHandle);
}
if (!bConnectedSuccessfully || !Response.IsValid())
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::ERROR,
TEXT("Error: Failed to get version"));
return;
}
const auto ResponseCode = Response->GetResponseCode();
if (ResponseCode >= 400 || ResponseCode < 200)
{
UE_LOG(LogHotUpdate, Warning, TEXT("Http Response code error : %d"), ResponseCode);
OnHotUpdateStateEvent.Execute(EHotUpdateState::ERROR,
TEXT("Error: Failed to get version"));
return;
}
if (!DownloadManager.IsValid() || !PakManager.IsValid())
{
return;
}
const auto& URL = GetHotUpdateServerUrl() + "/" + FNetworkVersion::GetProjectVersion() + "/" + GetPlatform() + "/";
TSharedPtr<FJsonObject> JsonObject;
const auto& JsonReader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(JsonReader, JsonObject))
{
for (const auto& Value : JsonObject->Values)
{
const auto& Files = Value.Value->AsArray();
for (const auto& File : Files)
{
const auto& FileObject = File->AsObject();
const auto& FileName = FileObject->GetStringField("File");
const auto& Hash = FileObject->GetStringField("HASH");
const auto Size = FileObject->GetIntegerField("Size");
FPakFileProperty PakFileProperty(FileName, Size, Hash);
if (!FFilePakManager::IsPakValid(PakFileProperty))
{
DownloadManager->AddTask(URL + FileName, FileName, Size);
}
PakManager->AddPakFile(MoveTemp(PakFileProperty));
}
}
OnHotUpdateStateEvent.Execute(EHotUpdateState::END_GETVERSION, TEXT("End to get version"));
}
else
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::ERROR,
TEXT("Error: Failed to deserialize json"));
}
}
bool UHotUpdateSubsystem::IsSuccessful() const
{
if (!DownloadManager.IsValid() || !DownloadManager->IsSuccessful())
{
return false;
}
if (!PakManager.IsValid() || !PakManager->IsSuccessful())
{
return false;
}
return true;
}
void UHotUpdateSubsystem::OnDownloadEvent(const EDownloadState Event, const FTaskInfo&) const
{
switch (Event)
{
case EDownloadState::UPDATE_DOWNLOAD:
{
OnUpdateDownloadProgress();
}
break;
case EDownloadState::END_DOWNLOAD:
{
OnHotUpdateStateEvent.Execute(EHotUpdateState::END_DOWNLOAD, FString(TEXT("EndDownload")));
}
break;
default:
break;
}
}
void UHotUpdateSubsystem::OnUpdateDownloadProgress() const
{
if (DownloadManager.IsValid())
{
const auto& DownloadProgress = DownloadManager->GetDownloadProgress();
OnDownloadUpdate.Broadcast(DownloadProgress);
}
}
FString UHotUpdateSubsystem::GetHotUpdateServerUrl() const
{
const auto HotUpdateSettings = GetMutableDefault<UHotUpdateSettings>();
return HotUpdateSettings != nullptr ? HotUpdateSettings->HotUpdateServerUrl : "";
}
| 10,058 | 2,955 |
// Copyright (c) Meta Platforms, Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <c10d/logging.h>
#include <c10d/debug.h>
namespace c10d {
namespace detail {
bool isLogLevelEnabled(LogLevel level) noexcept {
// c10 logger does not support debug and trace levels. In order to map higher
// levels we adjust our ordinal value.
int level_int = static_cast<int>(level) - 2;
if (level_int >= 0) {
return FLAGS_caffe2_log_level <= level_int;
}
// Debug and trace levels are only enabled when c10 log level is set to INFO.
if (FLAGS_caffe2_log_level != 0) {
return false;
}
if (level_int == -1) {
return debug_level() != DebugLevel::Off;
}
if (level_int == -2) {
return debug_level() == DebugLevel::Detail;
}
return false;
}
} // namespace detail
} // namespace c10d
| 956 | 329 |
#pragma once
#include "prism.hpp"
#include "cuboid.hpp"
#include "lacze_do_gnuplota.hpp"
#include <unistd.h>
#include <vector>
/*!
* \file drone.hpp
*
* \brief Plik zawiera definicję klasy reprezentujacej drona,
* budowanie i przemieszczanie go
*/
/*!
* \class Drone
* \brief Opisuje drona o prostopadlosciennym korpusie i 4 rotorach
*/
class Drone
{
private:
/*!
* \brief Zmienna reprezentujaca polozenie drona (dokladnie
* polozenie punktu centralnego prostopadloscianu body)
*/
Vector3D drone_pos;
/*!
* \brief Zmienna reprezentujaca zwrot drona.
* Reprezentowana przez jednostkowy Vector,
* nie dopuszcza sie zwrotu pionowego.
*/
Vector3D drone_orient;
/*!
* \brief Zmienna reprezentujaca zwrot drona jako kat w stopniach.
*/
double drone_angle;
/*!
* \brief Tablica graniastoslupow szesciokatnych,
* reprezentujaca rotory drona
*/
Prism rotors[4];
/*!
* \brief Prostopadloscian reprezentujacy korpus drona
*/
Cuboid body;
public:
/*!
* \brief Konstruktor bezparametryczny klasy Drone.
* Powstaly dron jest skonstruowany z bezparametrycznych
* prostopadloscianu (body) oraz rotorow przeskalowanych
* 10-krotnie (aby sie poprawnie wyswietlal) w poziomie i
* 5-krotnie w pionie (aby zachowac pewna poprawna skale)
* \post Inicjalizuje podstawowego drona
*/
Drone();
/*!
* \brief Metoda uzywana przy konstruowania drona
* Ustawia rotory w ten sposob, ze srodek ich dolnej
* podstawy jest w tym samym punkcie co wierzcholki
* gornej podstawy body
* \post Zmienia pozycje rotorow = *this
*/
void set_rotors_in_place();
/*!
* \brief Przesuwa drona o zadany wektor w 3D
* \param[in] trans - Vector3D
* \param[out] translated - Dron po operacji przesuniecia
*/
Drone translation(Vector3D const &tran) const;
/*!
* \brief Metoda uzywana przy konstruowania drona
* przesuwa drona w ten sposob, ze Vector3D
* centre prostopadloscianu body pokrywa sie
* z Vector3D pos
* \returns translated - przesuniety dron
*/
Drone translation_to_pos() const;
/*!
* \brief Metoda obracajaca dron o zadany kat w 3D wokol srodka figury
* \param[in] mat - macierz obrotu
* \param[out] rotated - dron po przeprowadzonej rotacji
*/
Drone rotation_around_cen(const Matrix3D &mat) const;
/*!
* \brief Metoda skalujaca wszystkie elementy drona przez skale kazdego elementu
* \param[out] scaled - dron po operacji skalowania
*/
Drone scale_dro() const;
/*!
* \brief Przeciazenie operatora == dla klasy Drone
* \param[in] dro - porownywany dron
* \retval false - nie sa rowne,
* \retval true - sa rowne
*/
bool operator==(const Drone &dro) const;
/*!
* \brief Metoda ustawiajaca drone_pos
* \pre Pozycja drona musi znajdowac sie nad plaszcyzna.
* Punktem referencji jest srodek prostopadloscianu body, wiec
* aby dron nie zapadal sie w podloze, minimalna wspolrzedna z polozenia
* nie moze nigdy byc mniejsza od polowy wysokosci prostopadloscianu
* \param[in] pos - wektor pozycji
* \post Ustawia pozycje drona (zadana przez uzytkownika)
* \retval false - jesli wprowadzona pozycja jest bledna
* \retval true - jesli jest prawidlowa
*/
bool set_drone_pos(Vector3D const &pos);
/*!
* \brief Metoda wypisuje na standardowym wyjsciu pozycje drona (bez wysokosci)
*/
void print_drone_pos() const;
/*!
* \brief Metoda ustawiajaca skale wszystkich elementow drona
* \param[in] bod - skala korpusu
* \param[in] rot - skala rotorow
* \post Ustawia skale korpusa i rotorow
*/
void set_scale_all(Vector3D const &bod, Vector3D const &rot);
/*!
* \brief Metoda zwracajaca wszystkie elementy drona do odpowiednich zmiennych
* \param[in] b - tu zwrocone bedzie body
* \param[in] rot - tu zostana zwrocone odpowiednio rotory
* \param[in] p - wektor pozycji
* \post Zwraca odpowiednio pola klasy Drone
*/
void get_dro(Cuboid &b, Prism (&rot)[4], Vector3D &p) const;
/*!
* \brief Metoda sprawdzajaca budowe drona
* \retval true - dron odpowiednio zbudowany
* \retval false - dron blednie zbudowany
*/
bool check_dro() const;
/*!
* \brief Metoda zwracajaca orientacje drona
* \return res - Zwracana orientacja
*/
Vector3D get_orien() const;
/*!
* \brief Metoda sprawdzajaca orientacje drona
* Vector3D dron_orien musi byc jednostkowy, oraz miec skladowa z=0
* \retval true - odpowiednia orientacja
* \retval false - bledna orientacja
*/
bool check_orien() const;
/*!
* \brief Metoda ustawiajaca nazwy plikow do zapisu dla drona
* \param[in] bod - tablica nazw plikow odpowiednio 0-sample_name, 1-final_name;
* zawierajacych dane do korpusu drona
* \param[in] rots - analogiczna tablica co bod, dla rotorow drona
* \post Zmienia obiekt, przypisuje mu odpowiednie parametry
*/
void setup_filenames(std::string const (&bod)[2], std::string const (&rots)[4][2]);
/*!
* \brief Metoda ustawiajaca nazwy plikow w laczy do gnuplota (nazwy final!)
* \param[in] Lacze - lacze do ktorego wpisane zostana nazwy
* \pre Metoda wymaga zainicjowanych nazw elementow drona
* \post Zmienia lacze, przypisuje mu odpowiednie parametry
*/
bool set_filenames_gnuplot(PzG::LaczeDoGNUPlota &Lacze) const;
/*!
* \brief Metoda zwracajaca nazwy plikow do zapisu dla drona
* \param[in] bod - tablica nazw plikow odpowiednio 0-sample_name, 1-final_name;
* do ktorych zwracane sa nazwy
* \param[in] rots - analogiczna tablica co bod, dla rotorow drona
* \return przypisuje argumentom odpowiednie wartosci
*/
void get_filenames(std::string (&bod)[2], std::string (&rots)[4][2]) const;
/*!
* \brief Metoda rysujaca drona w gnuplocie. Przeznaczona do testow
* \post Wyswietla okienko gnuplota z wyrysowanym dronem
*/
void Print_to_gnuplot_drone() const;
/*!
* \brief Metoda zapisujaca parametry drona do plikow (do plikow final kazdego z elementow)
* \post Aktualizuje pliki z danymi
*/
void Print_to_files_drone() const;
/*!
* \brief Metoda animujaca obrot rotorow i zapisujaca to w plikach.
* Metoda sluzy jako metoda pomocnicza, przy kazdej animacji (translacji czy
* rotacji drona) rotory sie niezaleznie obracaja. Ta metoda to umozliwia.
* \pre Pliki musza byc odpowiednio skonfigurowane
* \post Rotory sa obracane o kat 1 stopnia, zmieniany jest obiekt drona
* efekt rotacji zapisywnay jest w plikach
*/
void Rotors_rotation_animation();
/*!
* \brief Metoda animujaca obrot drona i wyrysowujaca calosc w gnuplocie
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] Lacze - aktywne lacze do gnuplota
* \param[in] angle - kat obrotu w stopniach, obrot wykonuje sie wylacznie wokol osi z
* \post W oknie gnuplota wykonuje sie animacja obrotu drona
*/
void Drone_rotation_animation(PzG::LaczeDoGNUPlota Lacze, double const &angle);
/*!
* \brief Metoda przygotowujaca sciezke drona z uzyciem std::vector<>
* \pre Lacze musi byc odpowiednio skonfigurowane. Wektor translacji
* musi miec zerowa wpolrzedna z
* \param[in] tran - wektor translacji
* \param[in] path - std::vector<> do ktorego zapisywana jest sciezka
* \post W oknie gnuplota wyrysowuje sie sciezka drona
* \retval true - jesli jest odpowiednio skonfigurowane lacze
* \retval false - w przeciwnym wypadku
*/
bool Drone_make_path( Vector3D const &tran, std::vector<Vector3D> &path);
/*!
* \brief Metoda zapisujaca sciezke do pliku oraz do lacza
* \param[in] path - std::vector<> z ktorego wypisywana jest sciezka
* \param[in] name - nazwa pliku do zapisu
* \param[in] Lacze - lacze do gnuplota
* \post W podanym pliku zapisuje sie sciezka, jest rysowana w gnuplocie
* \retval true - jesli zapis sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_path_to_file(std::vector<Vector3D> &path, std::string const &name, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Oczyszcza plik ze sciezka
* \param[in] name - nazwa pliku ze sciezka
* \retval true - jesli operacja sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_path_clear(std::string const &name);
/*!
* \brief Metoda animujaca translacje drona i wyrysowujaca calosc w gnuplocie
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] Lacze - aktywne lacze do gnuplota
* \param[in] tran - wektor translacji
* \post W oknie gnuplota wykonuje sie animacja translacji drona
*/
void Drone_translation_animation(PzG::LaczeDoGNUPlota &Lacze, Vector3D const &tran);
/*!
* \brief Metoda zamieniajaca drona na tego z pliku sample
* \pre PLiki musza byc odpowiednio skonfigurowane
* \param[in] angle - jesli dron roboczy jest obrocony o pewien kat, nalezy
* podac ten kat w metodzie
* \post Zamienia drona na tego o wzorcowych wymiarach
*/
void Drone_change_to_sample(double const &angle);
/*!
* \brief Metoda wczytywania odpowiednich wierzcholkow z pliku wzorcowego
* zgodnie z zaproponowanym sposobem w zadaniu dron.
* Przypisuje wczytane wierzcholki do elementow drona.
* \param[out] dro - wczytwany dron
*/
Drone Drone_From_Sample() const;
/*!
* \brief Metoda obliczajaca i przeprowadzajaca caly ruch drona
* (obrot o kat i przelot z zadania 5.1)
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] angle - kat w stopniach
* \param[in] len - dlugosc przelotu
* \param[in] Lacze - aktywne lacze do gnuplota
* \post W oknie gnuplota wykonuje sie animacja ruchu drona
* \retval true - jesli operacja sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_basic_motion(double const &angle, double const &len, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Metoda robiaca "oblot" drona wokol punktu (z modyfikacji)
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] radius - promien okregu
* \param[in] Lacze - aktywne lacze do gnuplota
* \post W oknie gnuplota wykonuje sie animacja ruchu drona
* \retval true - jesli operacja sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_roundabout(double const &radius, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Metoda przygotowujaca sciezke drona z uzyciem std::vector<> do roundabout
* \pre Lacze musi byc odpowiednio skonfigurowane. Promien musi byc dodatni
* \param[in] radius - promien okregu
* \param[in] path - std::vector<> do ktorego zapisywana jest sciezka
* \post W oknie gnuplota wyrysowuje sie sciezka drona
* \retval true - jesli jest odpowiednio skonfigurowane lacze
* \retval false - w przeciwnym wypadku
*/
bool Drone_make_path_roundabout(double const &radius, std::vector<Vector3D> &path);
}; | 14,576 | 4,504 |
#include "Arduino.h"
#ifndef __COLOR__
#define __COLOR__
#include "Color.cpp"
#endif
extern unsigned long timer0_millis;
class ColorAnimator {
private:
int time;
float durationMs;
unsigned long offset, position;
int dr, dg, db, r, g, b;
Color color, from, to;
public:
float Progress;
ColorAnimator(Color from, Color to, float durationMs) {
this->from = from;
this->to = to;
this->durationMs = durationMs;
}
void Start() {
offset = millis();
position = 0;
Progress = 0;
color = from;
}
Color Update() {
position = millis() - offset;
Progress = position / durationMs;
Progress = min(1, Progress);
dr = to.r - from.r;
dg = to.g - from.g;
db = to.b - from.b;
r = from.r + (int)(dr * Progress);
g = from.g + (int)(dg * Progress);
b = from.b + (int)(db * Progress);
color = Color(r, g, b);
return color;
}
};
| 908 | 344 |
#include "stdafx.h"
#include "Hypodermic/ContainerBuilder.h"
#include "TestingTypes.h"
namespace Hypodermic
{
namespace Testing
{
BOOST_AUTO_TEST_SUITE(RegistrationTests)
BOOST_AUTO_TEST_CASE(should_call_activation_handler_everytime_an_instance_is_activated_through_resolution)
{
// Arrange
ContainerBuilder builder;
std::vector< std::shared_ptr< DefaultConstructible1 > > activatedInstances;
// Act
builder.registerType< DefaultConstructible1 >().onActivated([&activatedInstances](ComponentContext&, const std::shared_ptr< DefaultConstructible1 >& instance)
{
activatedInstances.push_back(instance);
});
auto container = builder.build();
// Assert
auto instance1 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance1 != nullptr);
auto instance2 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance2 != nullptr);
BOOST_CHECK(instance1 != instance2);
BOOST_REQUIRE_EQUAL(activatedInstances.size(), 2u);
BOOST_CHECK(instance1 == activatedInstances[0]);
BOOST_CHECK(instance2 == activatedInstances[1]);
}
BOOST_AUTO_TEST_CASE(should_call_activation_handler_only_once_for_single_instance_mode)
{
// Arrange
ContainerBuilder builder;
std::vector< std::shared_ptr< DefaultConstructible1 > > activatedInstances;
// Act
builder.registerType< DefaultConstructible1 >()
.singleInstance()
.onActivated([&activatedInstances](ComponentContext&, const std::shared_ptr< DefaultConstructible1 >& instance)
{
activatedInstances.push_back(instance);
});
auto container = builder.build();
// Assert
auto instance1 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance1 != nullptr);
auto instance2 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance2 != nullptr);
BOOST_CHECK(instance1 == instance2);
BOOST_REQUIRE_EQUAL(activatedInstances.size(), 1u);
BOOST_CHECK(instance1 == activatedInstances[0]);
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace Testing
} // namespace Hypodermic | 2,325 | 697 |
/*
* ghex-org
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <oomph/util/mpi_error.hpp>
#include "./context.hpp"
namespace oomph
{
class channel_base
{
protected:
using heap_type = context_impl::heap_type;
using pointer = heap_type::pointer;
using handle_type = typename pointer::handle_type;
using key_type = typename handle_type::key_type;
using flag_basic_type = key_type;
using flag_type = flag_basic_type volatile;
protected:
//heap_type& m_heap;
std::size_t m_size;
std::size_t m_T_size;
std::size_t m_levels;
std::size_t m_capacity;
communicator::rank_type m_remote_rank;
communicator::tag_type m_tag;
bool m_connected = false;
MPI_Request m_init_req;
public:
channel_base(/*heap_type& h,*/ std::size_t size, std::size_t T_size,
communicator::rank_type remote_rank, communicator::tag_type tag, std::size_t levels)
//: m_heap{h}
: m_size{size}
, m_T_size{T_size}
, m_levels{levels}
, m_capacity{levels}
, m_remote_rank{remote_rank}
, m_tag{tag}
{
}
void connect()
{
OOMPH_CHECK_MPI_RESULT(MPI_Wait(&m_init_req, MPI_STATUS_IGNORE));
m_connected = true;
}
protected:
// index of flag in buffer (in units of flag_basic_type)
std::size_t flag_offset() const noexcept
{
return (m_size * m_T_size + 2 * sizeof(flag_basic_type) - 1) / sizeof(flag_basic_type) - 1;
}
// number of elements of type T (including padding)
std::size_t buffer_size() const noexcept
{
return ((flag_offset() + 1) * sizeof(flag_basic_type) + m_T_size - 1) / m_T_size;
}
// pointer to flag location for a given buffer
void* flag_ptr(void* ptr) const noexcept
{
return (void*)((char*)ptr + flag_offset() * sizeof(flag_basic_type));
}
};
} // namespace oomph
| 2,096 | 761 |
#ifndef MENOH_IMPL_COMPOSITE_BACKEND_BACKEND_GENERIC_OPERATOR_IDENTITY_HPP
#define MENOH_IMPL_COMPOSITE_BACKEND_BACKEND_GENERIC_OPERATOR_IDENTITY_HPP
#include <algorithm>
#include <menoh/array.hpp>
#include <menoh/composite_backend/procedure.hpp>
namespace menoh_impl {
namespace composite_backend {
namespace generic_backend {
inline procedure
make_identity(node const& /*node*/,
std::vector<array> const& input_list,
std::vector<array> const& output_list) {
assert(input_list.size() == 1);
assert(output_list.size() == 1);
auto procedure = [input = input_list.at(0),
output = output_list.at(0)]() {
for(decltype(total_size(input)) i = 0;
i < total_size(input); ++i) {
fat(output, i) = fat(input, i);
std::copy(static_cast<char*>(input.data()),
static_cast<char*>(input.data()) +
total_size(input) *
get_size_in_bytes(input.dtype()),
static_cast<char*>(output.data()));
}
};
return procedure;
}
} // namespace generic_backend
} // namespace composite_backend
} // namespace menoh_impl
#endif // MENOH_IMPL_COMPOSITE_BACKEND_BACKEND_GENERIC_OPERATOR_IDENTITY_HPP
| 1,554 | 455 |
/***********************************************************
* AGSBlend *
* *
* Author: Steven Poulton *
* *
* Date: 09/01/2011 *
* *
* Description: An AGS Plugin to allow true Alpha Blending *
* *
***********************************************************/
#pragma region Defines_and_Includes
#define MIN_EDITOR_VERSION 1
#define MIN_ENGINE_VERSION 3
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#if !defined(BUILTIN_PLUGINS)
#define THIS_IS_THE_PLUGIN
#endif
#include "../../Common/agsplugin.h"
#if defined(BUILTIN_PLUGINS)
namespace agsblend {
#endif
typedef unsigned char uint8;
#define DEFAULT_RGB_R_SHIFT_32 16
#define DEFAULT_RGB_G_SHIFT_32 8
#define DEFAULT_RGB_B_SHIFT_32 0
#define DEFAULT_RGB_A_SHIFT_32 24
#if !defined(WINDOWS_VERSION)
#define min(x,y) (((x) < (y)) ? (x) : (y))
#define max(x,y) (((x) > (y)) ? (x) : (y))
#endif
#define abs(a) ((a)<0 ? -(a) : (a))
#define ChannelBlend_Normal(B,L) ((uint8)(B))
#define ChannelBlend_Lighten(B,L) ((uint8)((L > B) ? L:B))
#define ChannelBlend_Darken(B,L) ((uint8)((L > B) ? B:L))
#define ChannelBlend_Multiply(B,L) ((uint8)((B * L) / 255))
#define ChannelBlend_Average(B,L) ((uint8)((B + L) / 2))
#define ChannelBlend_Add(B,L) ((uint8)(min(255, (B + L))))
#define ChannelBlend_Subtract(B,L) ((uint8)((B + L < 255) ? 0:(B + L - 255)))
#define ChannelBlend_Difference(B,L) ((uint8)(abs(B - L)))
#define ChannelBlend_Negation(B,L) ((uint8)(255 - abs(255 - B - L)))
#define ChannelBlend_Screen(B,L) ((uint8)(255 - (((255 - B) * (255 - L)) >> 8)))
#define ChannelBlend_Exclusion(B,L) ((uint8)(B + L - 2 * B * L / 255))
#define ChannelBlend_Overlay(B,L) ((uint8)((L < 128) ? (2 * B * L / 255):(255 - 2 * (255 - B) * (255 - L) / 255)))
#define ChannelBlend_SoftLight(B,L) ((uint8)((L < 128)?(2*((B>>1)+64))*((float)L/255):(255-(2*(255-((B>>1)+64))*(float)(255-L)/255))))
#define ChannelBlend_HardLight(B,L) (ChannelBlend_Overlay(L,B))
#define ChannelBlend_ColorDodge(B,L) ((uint8)((L == 255) ? L:min(255, ((B << 8 ) / (255 - L)))))
#define ChannelBlend_ColorBurn(B,L) ((uint8)((L == 0) ? L:max(0, (255 - ((255 - B) << 8 ) / L))))
#define ChannelBlend_LinearDodge(B,L)(ChannelBlend_Add(B,L))
#define ChannelBlend_LinearBurn(B,L) (ChannelBlend_Subtract(B,L))
#define ChannelBlend_LinearLight(B,L)((uint8)(L < 128)?ChannelBlend_LinearBurn(B,(2 * L)):ChannelBlend_LinearDodge(B,(2 * (L - 128))))
#define ChannelBlend_VividLight(B,L) ((uint8)(L < 128)?ChannelBlend_ColorBurn(B,(2 * L)):ChannelBlend_ColorDodge(B,(2 * (L - 128))))
#define ChannelBlend_PinLight(B,L) ((uint8)(L < 128)?ChannelBlend_Darken(B,(2 * L)):ChannelBlend_Lighten(B,(2 * (L - 128))))
#define ChannelBlend_HardMix(B,L) ((uint8)((ChannelBlend_VividLight(B,L) < 128) ? 0:255))
#define ChannelBlend_Reflect(B,L) ((uint8)((L == 255) ? L:min(255, (B * B / (255 - L)))))
#define ChannelBlend_Glow(B,L) (ChannelBlend_Reflect(L,B))
#define ChannelBlend_Phoenix(B,L) ((uint8)(min(B,L) - max(B,L) + 255))
#define ChannelBlend_Alpha(B,L,O) ((uint8)(O * B + (1 - O) * L))
#define ChannelBlend_AlphaF(B,L,F,O) (ChannelBlend_Alpha(F(B,L),B,O))
#pragma endregion
#if defined(WINDOWS_VERSION)
// The standard Windows DLL entry point
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
//define engine
IAGSEngine *engine;
#pragma region Color_Functions
int getr32(int c)
{
return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF);
}
int getg32 (int c)
{
return ((c >> DEFAULT_RGB_G_SHIFT_32) & 0xFF);
}
int getb32 (int c)
{
return ((c >> DEFAULT_RGB_B_SHIFT_32) & 0xFF);
}
int geta32 (int c)
{
return ((c >> DEFAULT_RGB_A_SHIFT_32) & 0xFF);
}
int makeacol32 (int r, int g, int b, int a)
{
return ((r << DEFAULT_RGB_R_SHIFT_32) |
(g << DEFAULT_RGB_G_SHIFT_32) |
(b << DEFAULT_RGB_B_SHIFT_32) |
(a << DEFAULT_RGB_A_SHIFT_32));
}
#pragma endregion
#pragma region Pixel32_Definition
struct Pixel32{
public:
Pixel32();
~Pixel32() {}
int GetColorAsInt();
int Red;
int Green;
int Blue;
int Alpha;
};
Pixel32::Pixel32() {
Red = 0;
Blue = 0;
Green = 0;
Alpha = 0;
}
int Pixel32::GetColorAsInt() {
return makeacol32(Red,Green,Blue,Alpha);
}
#pragma endregion
/// <summary>
/// Gets the alpha value at coords x,y
/// </summary>
int GetAlpha(int sprite, int x, int y){
BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
unsigned char **charbuffer = engine->GetRawBitmapSurface (engineSprite);
unsigned int **longbuffer = (unsigned int**)charbuffer;
int alpha = geta32(longbuffer[y][x]);
engine->ReleaseBitmapSurface (engineSprite);
return alpha;
}
/// <summary>
/// Sets the alpha value at coords x,y
/// </summary>
int PutAlpha(int sprite, int x, int y, int alpha){
BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
unsigned char **charbuffer = engine->GetRawBitmapSurface (engineSprite);
unsigned int **longbuffer = (unsigned int**)charbuffer;
int r = getr32(longbuffer[y][x]);
int g = getg32(longbuffer[y][x]);
int b = getb32(longbuffer[y][x]);
longbuffer[y][x] = makeacol32(r,g,b,alpha);
engine->ReleaseBitmapSurface (engineSprite);
return alpha;
}
/// <summary>
/// Translates index from a 2D array to a 1D array
/// </summary>
int xytolocale(int x, int y, int width){
return (y * width + x);
}
int HighPass(int sprite, int threshold){
BITMAP* src = engine->GetSpriteGraphic(sprite);
long srcWidth, srcHeight;
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
for (int y = 0; y<srcHeight; y++){
for (int x = 0; x<srcWidth; x++){
int srcr = getb32(srclongbuffer[y][x]);
int srcg = getg32(srclongbuffer[y][x]);
int srcb = getr32(srclongbuffer[y][x]);
int tempmaxim = max(srcr, srcg);
int maxim = max(tempmaxim, srcb);
int tempmin = min( srcr, srcg);
int minim = min( srcb, tempmin);
int light = (maxim + minim) /2 ;
if (light < threshold) srclongbuffer[y][x] = makeacol32(0,0,0,0);
}
}
return 0;
}
int Blur (int sprite, int radius) {
BITMAP* src = engine->GetSpriteGraphic(sprite);
long srcWidth, srcHeight;
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
int negrad = -1 * radius;
//use a 1Dimensional array since the array is on the free store, not the stack
Pixel32 * Pixels = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; // this defines a copy of the individual channels in class form.
Pixel32 * Dest = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; // this is the destination sprite. both have a border all the way round equal to the radius for the blurring.
Pixel32 * Temp = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];
int arraywidth = srcWidth + (radius * 2); //define the array width since its used many times in the algorithm
for (int y = 0; y<srcHeight; y++){ //copy the sprite to the Pixels class array
for (int x = 0; x<srcWidth; x++){
int locale = xytolocale(x + radius, y + radius, arraywidth);
Pixels[locale].Red = getr32(srclongbuffer[y][x]);
Pixels[locale].Green = getg32(srclongbuffer[y][x]);
Pixels[locale].Blue = getb32(srclongbuffer[y][x]);
Pixels[locale].Alpha = geta32(srclongbuffer[y][x]);
}
}
int numofpixels = (radius * 2 + 1);
for (int y = 0; y < srcHeight; y++) {
int totalr = 0;
int totalg = 0;
int totalb = 0;
int totala = 0;
// Process entire window for first pixel
for (int kx = negrad; kx <= radius; kx++){
int locale = xytolocale(kx + radius, y + radius, arraywidth);
totala += Pixels[locale].Alpha;
totalr += (Pixels[locale].Red * Pixels[locale].Alpha)/ 255;
totalg += (Pixels[locale].Green * Pixels[locale].Alpha)/ 255;
totalb += (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255;
}
int locale = xytolocale(radius, y + radius, arraywidth);
Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Temp[locale].Green = totalg / numofpixels;
Temp[locale].Blue = totalb / numofpixels;
Temp[locale].Alpha = totala / numofpixels;
// Subsequent pixels just update window total
for (int x = 1; x < srcWidth; x++) {
// Subtract pixel leaving window
int locale = xytolocale(x - 1, y + radius, arraywidth);
totala -= Pixels[locale].Alpha;
totalr -= (Pixels[locale].Red * Pixels[locale].Alpha)/ 255;
totalg -= (Pixels[locale].Green * Pixels[locale].Alpha)/ 255;
totalb -= (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255;
// Add pixel entering window
locale = xytolocale(x + radius + radius, y + radius, arraywidth);
totala += Pixels[locale].Alpha;
totalr += (Pixels[locale].Red * Pixels[locale].Alpha)/ 255;
totalg += (Pixels[locale].Green * Pixels[locale].Alpha)/ 255;
totalb += (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255;
locale = xytolocale(x + radius, y + radius, arraywidth);
Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Temp[locale].Green = totalg / numofpixels;
Temp[locale].Blue = totalb / numofpixels;
Temp[locale].Alpha = totala / numofpixels;
}
}
for (int x = 0; x < srcWidth; x++) {
int totalr = 0;
int totalg = 0;
int totalb = 0;
int totala = 0;
// Process entire window for first pixel
for (int ky = negrad; ky <= radius; ky++){
int locale = xytolocale(x + radius, ky + radius, arraywidth);
totala += Temp[locale].Alpha;
totalr += (Temp[locale].Red * Temp[locale].Alpha)/ 255;
totalg += (Temp[locale].Green * Temp[locale].Alpha)/ 255;
totalb += (Temp[locale].Blue * Temp[locale].Alpha)/ 255;
}
int locale = xytolocale(x + radius,radius, arraywidth);
Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Dest[locale].Green = totalg / numofpixels;
Dest[locale].Blue = totalb / numofpixels;
Dest[locale].Alpha = totala / numofpixels;
// Subsequent pixels just update window total
for (int y = 1; y < srcHeight; y++) {
// Subtract pixel leaving window
int locale = xytolocale(x + radius, y - 1, arraywidth);
totala -= Temp[locale].Alpha;
totalr -= (Temp[locale].Red * Temp[locale].Alpha)/ 255;
totalg -= (Temp[locale].Green * Temp[locale].Alpha)/ 255;
totalb -= (Temp[locale].Blue * Temp[locale].Alpha)/ 255;
// Add pixel entering window
locale = xytolocale(x + radius, y + radius + radius, arraywidth);
totala += Temp[locale].Alpha;
totalr += (Temp[locale].Red * Temp[locale].Alpha)/ 255;
totalg += (Temp[locale].Green * Temp[locale].Alpha)/ 255;
totalb += (Temp[locale].Blue * Temp[locale].Alpha)/ 255;
locale = xytolocale(x + radius, y + radius, arraywidth);
Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Dest[locale].Green = totalg / numofpixels;
Dest[locale].Blue = totalb / numofpixels;
Dest[locale].Alpha = totala / numofpixels;
}
}
for (int y = 0; y<srcHeight; y++){
for (int x = 0; x<srcWidth; x++){
int locale = xytolocale(x + radius, y + radius, arraywidth);
srclongbuffer[y][x] = Dest[locale].GetColorAsInt(); //write the destination array to the main buffer
}
}
delete [] Pixels;
delete [] Dest;
delete [] Temp;
engine->ReleaseBitmapSurface(src);
delete srclongbuffer;
delete srccharbuffer;
return 0;
}
int Clamp(int val, int min, int max){
if (val < min) return min;
else if (val > max) return max;
else return val;
}
int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans){
trans = 100 - trans;
long srcWidth, srcHeight, destWidth, destHeight;
BITMAP* src = engine->GetSpriteGraphic(sprite);
BITMAP* dest = engine->GetSpriteGraphic(destination);
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL);
if (x > destWidth || y > destHeight || x + srcWidth < 0 || y + srcHeight < 0) return 1; // offscreen
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest);
unsigned int **destlongbuffer = (unsigned int**)destcharbuffer;
if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
int destx, desty;
int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
unsigned int col;
int starty = 0;
int startx = 0;
if (x < 0) startx = -1 * x;
if (y < 0) starty = -1 * y;
int ycount = 0;
int xcount = 0;
for(ycount = starty; ycount<srcHeight; ycount ++){
for(xcount = startx; xcount<srcWidth; xcount ++){
destx = xcount + x;
desty = ycount + y;
srca = (geta32(srclongbuffer[ycount][xcount]));
if (srca != 0) {
srca = srca * trans / 100;
srcr = getr32(srclongbuffer[ycount][xcount]);
srcg = getg32(srclongbuffer[ycount][xcount]);
srcb = getb32(srclongbuffer[ycount][xcount]);
destr = getr32(destlongbuffer[desty][destx]);
destg = getg32(destlongbuffer[desty][destx]);
destb = getb32(destlongbuffer[desty][destx]);
desta = geta32(destlongbuffer[desty][destx]);
switch (DrawMode) {
case 0:
finalr = srcr;
finalg = srcg;
finalb = srcb;
break;
case 1:
finalr = ChannelBlend_Lighten(srcr,destr);
finalg = ChannelBlend_Lighten(srcg,destg);
finalb = ChannelBlend_Lighten(srcb,destb);
break;
case 2:
finalr = ChannelBlend_Darken(srcr,destr);
finalg = ChannelBlend_Darken(srcg,destg);
finalb = ChannelBlend_Darken(srcb,destb);
break;
case 3:
finalr = ChannelBlend_Multiply(srcr,destr);
finalg = ChannelBlend_Multiply(srcg,destg);
finalb = ChannelBlend_Multiply(srcb,destb);
break;
case 4:
finalr = ChannelBlend_Add(srcr,destr);
finalg = ChannelBlend_Add(srcg,destg);
finalb = ChannelBlend_Add(srcb,destb);
break;
case 5:
finalr = ChannelBlend_Subtract(srcr,destr);
finalg = ChannelBlend_Subtract(srcg,destg);
finalb = ChannelBlend_Subtract(srcb,destb);
break;
case 6:
finalr = ChannelBlend_Difference(srcr,destr);
finalg = ChannelBlend_Difference(srcg,destg);
finalb = ChannelBlend_Difference(srcb,destb);
break;
case 7:
finalr = ChannelBlend_Negation(srcr,destr);
finalg = ChannelBlend_Negation(srcg,destg);
finalb = ChannelBlend_Negation(srcb,destb);
break;
case 8:
finalr = ChannelBlend_Screen(srcr,destr);
finalg = ChannelBlend_Screen(srcg,destg);
finalb = ChannelBlend_Screen(srcb,destb);
break;
case 9:
finalr = ChannelBlend_Exclusion(srcr,destr);
finalg = ChannelBlend_Exclusion(srcg,destg);
finalb = ChannelBlend_Exclusion(srcb,destb);
break;
case 10:
finalr = ChannelBlend_Overlay(srcr,destr);
finalg = ChannelBlend_Overlay(srcg,destg);
finalb = ChannelBlend_Overlay(srcb,destb);
break;
case 11:
finalr = ChannelBlend_SoftLight(srcr,destr);
finalg = ChannelBlend_SoftLight(srcg,destg);
finalb = ChannelBlend_SoftLight(srcb,destb);
break;
case 12:
finalr = ChannelBlend_HardLight(srcr,destr);
finalg = ChannelBlend_HardLight(srcg,destg);
finalb = ChannelBlend_HardLight(srcb,destb);
break;
case 13:
finalr = ChannelBlend_ColorDodge(srcr,destr);
finalg = ChannelBlend_ColorDodge(srcg,destg);
finalb = ChannelBlend_ColorDodge(srcb,destb);
break;
case 14:
finalr = ChannelBlend_ColorBurn(srcr,destr);
finalg = ChannelBlend_ColorBurn(srcg,destg);
finalb = ChannelBlend_ColorBurn(srcb,destb);
break;
case 15:
finalr = ChannelBlend_LinearDodge(srcr,destr);
finalg = ChannelBlend_LinearDodge(srcg,destg);
finalb = ChannelBlend_LinearDodge(srcb,destb);
break;
case 16:
finalr = ChannelBlend_LinearBurn(srcr,destr);
finalg = ChannelBlend_LinearBurn(srcg,destg);
finalb = ChannelBlend_LinearBurn(srcb,destb);
break;
case 17:
finalr = ChannelBlend_LinearLight(srcr,destr);
finalg = ChannelBlend_LinearLight(srcg,destg);
finalb = ChannelBlend_LinearLight(srcb,destb);
break;
case 18:
finalr = ChannelBlend_VividLight(srcr,destr);
finalg = ChannelBlend_VividLight(srcg,destg);
finalb = ChannelBlend_VividLight(srcb,destb);
break;
case 19:
finalr = ChannelBlend_PinLight(srcr,destr);
finalg = ChannelBlend_PinLight(srcg,destg);
finalb = ChannelBlend_PinLight(srcb,destb);
break;
case 20:
finalr = ChannelBlend_HardMix(srcr,destr);
finalg = ChannelBlend_HardMix(srcg,destg);
finalb = ChannelBlend_HardMix(srcb,destb);
break;
case 21:
finalr = ChannelBlend_Reflect(srcr,destr);
finalg = ChannelBlend_Reflect(srcg,destg);
finalb = ChannelBlend_Reflect(srcb,destb);
break;
case 22:
finalr = ChannelBlend_Glow(srcr,destr);
finalg = ChannelBlend_Glow(srcg,destg);
finalb = ChannelBlend_Glow(srcb,destb);
break;
case 23:
finalr = ChannelBlend_Phoenix(srcr,destr);
finalg = ChannelBlend_Phoenix(srcg,destg);
finalb = ChannelBlend_Phoenix(srcb,destb);
break;
}
finala = 255-(255-srca)*(255-desta)/255;
finalr = srca*finalr/finala + desta*destr*(255-srca)/finala/255;
finalg = srca*finalg/finala + desta*destg*(255-srca)/finala/255;
finalb = srca*finalb/finala + desta*destb*(255-srca)/finala/255;
col = makeacol32(finalr, finalg, finalb, finala);
destlongbuffer[desty][destx] = col;
}
}
}
engine->ReleaseBitmapSurface(src);
engine->ReleaseBitmapSurface(dest);
engine->NotifySpriteUpdated(destination);
return 0;
}
int DrawAdd(int destination, int sprite, int x, int y, float scale){
long srcWidth, srcHeight, destWidth, destHeight;
BITMAP* src = engine->GetSpriteGraphic(sprite);
BITMAP* dest = engine->GetSpriteGraphic(destination);
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL);
if (x > destWidth || y > destHeight) return 1; // offscreen
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest);
unsigned int **destlongbuffer = (unsigned int**)destcharbuffer;
if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
int destx, desty;
int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
unsigned int col;
int ycount = 0;
int xcount = 0;
int starty = 0;
int startx = 0;
if (x < 0) startx = -1 * x;
if (y < 0) starty = -1 * y;
for(ycount = starty; ycount<srcHeight; ycount ++){
for(xcount = startx; xcount<srcWidth; xcount ++){
destx = xcount + x;
desty = ycount + y;
srca = (geta32(srclongbuffer[ycount][xcount]));
if (srca != 0) {
srcr = getr32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
srcg = getg32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
srcb = getb32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
desta = geta32(destlongbuffer[desty][destx]);
if (desta == 0){
destr = 0;
destg = 0;
destb = 0;
}
else {
destr = getr32(destlongbuffer[desty][destx]);
destg = getg32(destlongbuffer[desty][destx]);
destb = getb32(destlongbuffer[desty][destx]);
}
finala = 255-(255-srca)*(255-desta)/255;
finalr = Clamp(srcr + destr, 0, 255);
finalg = Clamp(srcg + destg, 0, 255);
finalb = Clamp(srcb + destb, 0, 255);
col = makeacol32(finalr, finalg, finalb, finala);
destlongbuffer[desty][destx] = col;
}
}
}
engine->ReleaseBitmapSurface(src);
engine->ReleaseBitmapSurface(dest);
engine->NotifySpriteUpdated(destination);
return 0;
}
int DrawAlpha(int destination, int sprite, int x, int y, int trans)
{
trans = 100 - trans;
long srcWidth, srcHeight, destWidth, destHeight;
BITMAP* src = engine->GetSpriteGraphic(sprite);
BITMAP* dest = engine->GetSpriteGraphic(destination);
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL);
if (x > destWidth || y > destHeight) return 1; // offscreen
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest);
unsigned int **destlongbuffer = (unsigned int**)destcharbuffer;
if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
int destx, desty;
int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
int ycount = 0;
int xcount = 0;
int starty = 0;
int startx = 0;
if (x < 0) startx = -1 * x;
if (y < 0) starty = -1 * y;
for(ycount = starty; ycount<srcHeight; ycount ++){
for(xcount = startx; xcount<srcWidth; xcount ++){
destx = xcount + x;
desty = ycount + y;
srca = (geta32(srclongbuffer[ycount][xcount])) * trans / 100;
if (srca != 0) {
srcr = getr32(srclongbuffer[ycount][xcount]);
srcg = getg32(srclongbuffer[ycount][xcount]);
srcb = getb32(srclongbuffer[ycount][xcount]);
destr = getr32(destlongbuffer[desty][destx]);
destg = getg32(destlongbuffer[desty][destx]);
destb = getb32(destlongbuffer[desty][destx]);
desta = geta32(destlongbuffer[desty][destx]);
finala = 255-(255-srca)*(255-desta)/255;
finalr = srca*srcr/finala + desta*destr*(255-srca)/finala/255;
finalg = srca*srcg/finala + desta*destg*(255-srca)/finala/255;
finalb = srca*srcb/finala + desta*destb*(255-srca)/finala/255;
destlongbuffer[desty][destx] = makeacol32(finalr, finalg, finalb, finala);
}
}
}
engine->ReleaseBitmapSurface(src);
engine->ReleaseBitmapSurface(dest);
engine->NotifySpriteUpdated(destination);
return 0;
}
#if defined(WINDOWS_VERSION)
//==============================================================================
// ***** Design time *****
IAGSEditor *editor; // Editor interface
const char *ourScriptHeader =
"import int DrawAlpha(int destination, int sprite, int x, int y, int transparency);\r\n"
"import int GetAlpha(int sprite, int x, int y);\r\n"
"import int PutAlpha(int sprite, int x, int y, int alpha);\r\n"
"import int Blur(int sprite, int radius);\r\n"
"import int HighPass(int sprite, int threshold);\r\n"
"import int DrawAdd(int destination, int sprite, int x, int y, float scale);\r\n"
"import int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans);";
//------------------------------------------------------------------------------
LPCSTR AGS_GetPluginName()
{
return ("AGSBlend");
}
//------------------------------------------------------------------------------
int AGS_EditorStartup(IAGSEditor *lpEditor)
{
// User has checked the plugin to use it in their game
// If it's an earlier version than what we need, abort.
if (lpEditor->version < MIN_EDITOR_VERSION)
return (-1);
editor = lpEditor;
editor->RegisterScriptHeader(ourScriptHeader);
// Return 0 to indicate success
return (0);
}
//------------------------------------------------------------------------------
void AGS_EditorShutdown()
{
// User has un-checked the plugin from their game
editor->UnregisterScriptHeader(ourScriptHeader);
}
//------------------------------------------------------------------------------
void AGS_EditorProperties(HWND parent) //*** optional ***
{
// User has chosen to view the Properties of the plugin
// We could load up an options dialog or something here instead
/* MessageBox(parent,
L"AGSBlend v1.0 By Calin Leafshade",
L"About",
MB_OK | MB_ICONINFORMATION);
*/
}
//------------------------------------------------------------------------------
int AGS_EditorSaveGame(char *buffer, int bufsize) //*** optional ***
{
// Called by the editor when the current game is saved to disk.
// Plugin configuration can be stored in [buffer] (max [bufsize] bytes)
// Return the amount of bytes written in the buffer
return (0);
}
//------------------------------------------------------------------------------
void AGS_EditorLoadGame(char *buffer, int bufsize) //*** optional ***
{
// Called by the editor when a game is loaded from disk
// Previous written data can be read from [buffer] (size [bufsize]).
// Make a copy of the data, the buffer is freed after this function call.
}
//==============================================================================
#endif
// ***** Run time *****
// Engine interface
//------------------------------------------------------------------------------
#define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x));
#define STRINGIFY(s) STRINGIFY_X(s)
#define STRINGIFY_X(s) #s
void AGS_EngineStartup(IAGSEngine *lpEngine)
{
engine = lpEngine;
// Make sure it's got the version with the features we need
if (engine->version < MIN_ENGINE_VERSION)
engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
//register functions
REGISTER(GetAlpha)
REGISTER(PutAlpha)
REGISTER(DrawAlpha)
REGISTER(Blur)
REGISTER(HighPass)
REGISTER(DrawAdd)
REGISTER(DrawSprite)
}
//------------------------------------------------------------------------------
void AGS_EngineShutdown()
{
// Called by the game engine just before it exits.
// This gives you a chance to free any memory and do any cleanup
// that you need to do before the engine shuts down.
}
//------------------------------------------------------------------------------
int AGS_EngineOnEvent(int event, int data) //*** optional ***
{
switch (event)
{
/*
case AGSE_KEYPRESS:
case AGSE_MOUSECLICK:
case AGSE_POSTSCREENDRAW:
case AGSE_PRESCREENDRAW:
case AGSE_SAVEGAME:
case AGSE_RESTOREGAME:
case AGSE_PREGUIDRAW:
case AGSE_LEAVEROOM:
case AGSE_ENTERROOM:
case AGSE_TRANSITIONIN:
case AGSE_TRANSITIONOUT:
case AGSE_FINALSCREENDRAW:
case AGSE_TRANSLATETEXT:
case AGSE_SCRIPTDEBUG:
case AGSE_SPRITELOAD:
case AGSE_PRERENDER:
case AGSE_PRESAVEGAME:
case AGSE_POSTRESTOREGAME:
*/
default:
break;
}
// Return 1 to stop event from processing further (when needed)
return (0);
}
//------------------------------------------------------------------------------
int AGS_EngineDebugHook(const char *scriptName,
int lineNum, int reserved) //*** optional ***
{
// Can be used to debug scripts, see documentation
return 0;
}
//------------------------------------------------------------------------------
void AGS_EngineInitGfx(const char *driverID, void *data) //*** optional ***
{
// This allows you to make changes to how the graphics driver starts up.
// See documentation
}
//..............................................................................
#if defined(BUILTIN_PLUGINS)
}
#endif | 37,370 | 11,470 |
/*
* Timebased_rules.cpp
*
* Created on: Nov 16, 2021
* Author: nikolaj
*/
/***********************************************************************************************+
* \brief -- XX -- Library - CPP Source file
* \par
* \par @DETAILS
*
*
* \li LIMITATION-TO-CLASS
* \li LIMITATION-TO-CLASS
*
* \note ANY RELEVANT NOTES
*
* \file Timebased_rules.cpp
* \author N.G Pedersen <nikolajgliese@tutanota.com>
* \version 1.0
* \date 2021
* \copyright --
*
*
***********************************************************************************************/
#include "../include/Timebased_rules.hpp"
//#define DEBUG // default uncommeted
#ifdef DEBUG
static const char* LOG_TAG = "Timebased_rules";
#endif
constexpr int NIGHT_TIME_START = 20;
constexpr int NIGHT_TIME_END = 5;
constexpr int VACATION_START = 4;
constexpr int VACATION_END = 12;
bool Timebased_rules::isItNight(void)
{
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
if(tstruct.tm_hour >= NIGHT_TIME_START or tstruct.tm_hour <= NIGHT_TIME_END)
{
return true;
}
return false;
}
bool Timebased_rules::isItVacation(void)
{
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
std::cout << " current day is : " << (int)tstruct.tm_mday << "\n";
if(tstruct.tm_mday >= VACATION_START and tstruct.tm_mday <= VACATION_END)
{
return true;
}
return false;
}
| 1,468 | 548 |
#ifndef _TENSOR_OPS_HPP_
#define _TENSOR_OPS_HPP_
#include "common.hpp"
#include "network.hpp"
#include "vector.hpp"
#include <vector>
// Routine to compute the second left eigenvector of the Markov Chain
// induced by the stationary distribution.
//
// triples is the list of third order moments (must be symmetric)
// counts is a counter such that counts[(u, v)] is the number of
// third-order moments containing u and v
// stationary_distrib is the multilinear PageRank vector
// alpha is the teleportation parameter
// max_iter is the maximum number of power iterations to run
// tol is the relative error tolerance for stopping
template <typename Scalar>
Vector<Scalar> SecondLeftEvec(std::vector<Tuple>& triples, Counts& counts,
Vector<Scalar>& stationary_distrib,
Scalar alpha, int max_iter,
double tol);
// Find the multilinear PageRank vector.
// We use the SS-HOPM by Kolda and Mayo to compute the vector.
//
// triples is the list of third order moments (must be symmetric)
// counts is a counter such that counts[(u, v)] is the number of
// third-order moments containing u and v
// alpha is the teleportation parameter
// gamma is the shift parameter for SS-HOPM
// num_nodes is the number of nodes
// max_iter is the maximum number of SS-HOPM iterations
// tol is the relative error tolerance for stopping
template <typename Scalar>
Vector<Scalar> MPRVec(std::vector<Tuple>& triples, Counts& counts,
Scalar alpha, Scalar gamma, int num_nodes, int max_iter,
double tol);
#endif // _TENSOR_OPS_HPP_
| 1,576 | 494 |
// generated from rosidl_typesupport_c/resource/idl__type_support.cpp.em
// with input from deepracer_interfaces_pkg:srv/SoftwareUpdateStateSrv.idl
// generated code does not contain a copyright notice
#include "cstddef"
#include "rosidl_runtime_c/message_type_support_struct.h"
#include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h"
#include "deepracer_interfaces_pkg/srv/detail/software_update_state_srv__struct.h"
#include "rosidl_typesupport_c/identifier.h"
#include "rosidl_typesupport_c/message_type_support_dispatch.h"
#include "rosidl_typesupport_c/type_support_map.h"
#include "rosidl_typesupport_c/visibility_control.h"
#include "rosidl_typesupport_interface/macros.h"
namespace deepracer_interfaces_pkg
{
namespace srv
{
namespace rosidl_typesupport_c
{
typedef struct _SoftwareUpdateStateSrv_Request_type_support_ids_t
{
const char * typesupport_identifier[2];
} _SoftwareUpdateStateSrv_Request_type_support_ids_t;
static const _SoftwareUpdateStateSrv_Request_type_support_ids_t _SoftwareUpdateStateSrv_Request_message_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier,
"rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier,
}
};
typedef struct _SoftwareUpdateStateSrv_Request_type_support_symbol_names_t
{
const char * symbol_name[2];
} _SoftwareUpdateStateSrv_Request_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _SoftwareUpdateStateSrv_Request_type_support_symbol_names_t _SoftwareUpdateStateSrv_Request_message_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Request)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Request)),
}
};
typedef struct _SoftwareUpdateStateSrv_Request_type_support_data_t
{
void * data[2];
} _SoftwareUpdateStateSrv_Request_type_support_data_t;
static _SoftwareUpdateStateSrv_Request_type_support_data_t _SoftwareUpdateStateSrv_Request_message_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _SoftwareUpdateStateSrv_Request_message_typesupport_map = {
2,
"deepracer_interfaces_pkg",
&_SoftwareUpdateStateSrv_Request_message_typesupport_ids.typesupport_identifier[0],
&_SoftwareUpdateStateSrv_Request_message_typesupport_symbol_names.symbol_name[0],
&_SoftwareUpdateStateSrv_Request_message_typesupport_data.data[0],
};
static const rosidl_message_type_support_t SoftwareUpdateStateSrv_Request_message_type_support_handle = {
rosidl_typesupport_c__typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_SoftwareUpdateStateSrv_Request_message_typesupport_map),
rosidl_typesupport_c__get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_c
} // namespace srv
} // namespace deepracer_interfaces_pkg
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Request)() {
return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::SoftwareUpdateStateSrv_Request_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
// already included above
// #include "cstddef"
// already included above
// #include "rosidl_runtime_c/message_type_support_struct.h"
// already included above
// #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h"
// already included above
// #include "deepracer_interfaces_pkg/srv/detail/software_update_state_srv__struct.h"
// already included above
// #include "rosidl_typesupport_c/identifier.h"
// already included above
// #include "rosidl_typesupport_c/message_type_support_dispatch.h"
// already included above
// #include "rosidl_typesupport_c/type_support_map.h"
// already included above
// #include "rosidl_typesupport_c/visibility_control.h"
// already included above
// #include "rosidl_typesupport_interface/macros.h"
namespace deepracer_interfaces_pkg
{
namespace srv
{
namespace rosidl_typesupport_c
{
typedef struct _SoftwareUpdateStateSrv_Response_type_support_ids_t
{
const char * typesupport_identifier[2];
} _SoftwareUpdateStateSrv_Response_type_support_ids_t;
static const _SoftwareUpdateStateSrv_Response_type_support_ids_t _SoftwareUpdateStateSrv_Response_message_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier,
"rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier,
}
};
typedef struct _SoftwareUpdateStateSrv_Response_type_support_symbol_names_t
{
const char * symbol_name[2];
} _SoftwareUpdateStateSrv_Response_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _SoftwareUpdateStateSrv_Response_type_support_symbol_names_t _SoftwareUpdateStateSrv_Response_message_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Response)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Response)),
}
};
typedef struct _SoftwareUpdateStateSrv_Response_type_support_data_t
{
void * data[2];
} _SoftwareUpdateStateSrv_Response_type_support_data_t;
static _SoftwareUpdateStateSrv_Response_type_support_data_t _SoftwareUpdateStateSrv_Response_message_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _SoftwareUpdateStateSrv_Response_message_typesupport_map = {
2,
"deepracer_interfaces_pkg",
&_SoftwareUpdateStateSrv_Response_message_typesupport_ids.typesupport_identifier[0],
&_SoftwareUpdateStateSrv_Response_message_typesupport_symbol_names.symbol_name[0],
&_SoftwareUpdateStateSrv_Response_message_typesupport_data.data[0],
};
static const rosidl_message_type_support_t SoftwareUpdateStateSrv_Response_message_type_support_handle = {
rosidl_typesupport_c__typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_SoftwareUpdateStateSrv_Response_message_typesupport_map),
rosidl_typesupport_c__get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_c
} // namespace srv
} // namespace deepracer_interfaces_pkg
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Response)() {
return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::SoftwareUpdateStateSrv_Response_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
// already included above
// #include "cstddef"
#include "rosidl_runtime_c/service_type_support_struct.h"
// already included above
// #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h"
// already included above
// #include "rosidl_typesupport_c/identifier.h"
#include "rosidl_typesupport_c/service_type_support_dispatch.h"
// already included above
// #include "rosidl_typesupport_c/type_support_map.h"
// already included above
// #include "rosidl_typesupport_interface/macros.h"
namespace deepracer_interfaces_pkg
{
namespace srv
{
namespace rosidl_typesupport_c
{
typedef struct _SoftwareUpdateStateSrv_type_support_ids_t
{
const char * typesupport_identifier[2];
} _SoftwareUpdateStateSrv_type_support_ids_t;
static const _SoftwareUpdateStateSrv_type_support_ids_t _SoftwareUpdateStateSrv_service_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier,
"rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier,
}
};
typedef struct _SoftwareUpdateStateSrv_type_support_symbol_names_t
{
const char * symbol_name[2];
} _SoftwareUpdateStateSrv_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _SoftwareUpdateStateSrv_type_support_symbol_names_t _SoftwareUpdateStateSrv_service_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv)),
}
};
typedef struct _SoftwareUpdateStateSrv_type_support_data_t
{
void * data[2];
} _SoftwareUpdateStateSrv_type_support_data_t;
static _SoftwareUpdateStateSrv_type_support_data_t _SoftwareUpdateStateSrv_service_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _SoftwareUpdateStateSrv_service_typesupport_map = {
2,
"deepracer_interfaces_pkg",
&_SoftwareUpdateStateSrv_service_typesupport_ids.typesupport_identifier[0],
&_SoftwareUpdateStateSrv_service_typesupport_symbol_names.symbol_name[0],
&_SoftwareUpdateStateSrv_service_typesupport_data.data[0],
};
static const rosidl_service_type_support_t SoftwareUpdateStateSrv_service_type_support_handle = {
rosidl_typesupport_c__typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_SoftwareUpdateStateSrv_service_typesupport_map),
rosidl_typesupport_c__get_service_typesupport_handle_function,
};
} // namespace rosidl_typesupport_c
} // namespace srv
} // namespace deepracer_interfaces_pkg
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg
const rosidl_service_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv)() {
return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::SoftwareUpdateStateSrv_service_type_support_handle;
}
#ifdef __cplusplus
}
#endif
| 10,548 | 3,878 |
/*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <boost/bind/bind.hpp>
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreManualObject.h>
#include <OgreBillboardSet.h>
#include <rviz/frame_manager.h>
#include <rviz/ogre_helpers/arrow.h>
#include <rviz/ogre_helpers/point_cloud.h>
#include <rviz/properties/color_property.h>
#include <rviz/properties/float_property.h>
#include <rviz/properties/parse_color.h>
#include <rviz/validate_floats.h>
#include <rviz/display_context.h>
#include "grid_cells_display.h"
namespace rviz
{
GridCellsDisplay::GridCellsDisplay() : MFDClass(), last_frame_count_(uint64_t(-1))
{
color_property_ = new ColorProperty("Color", QColor(25, 255, 0), "Color of the grid cells.", this);
alpha_property_ = new FloatProperty("Alpha", 1.0, "Amount of transparency to apply to the cells.",
this, SLOT(updateAlpha()));
alpha_property_->setMin(0);
alpha_property_->setMax(1);
}
void GridCellsDisplay::onInitialize()
{
static int count = 0;
std::stringstream ss;
ss << "PolyLine" << count++;
cloud_ = new PointCloud();
cloud_->setRenderMode(PointCloud::RM_TILES);
cloud_->setCommonDirection(Ogre::Vector3::UNIT_Z);
cloud_->setCommonUpVector(Ogre::Vector3::UNIT_Y);
scene_node_->attachObject(cloud_);
updateAlpha();
MFDClass::onInitialize();
}
GridCellsDisplay::~GridCellsDisplay()
{
if (initialized())
{
unsubscribe();
GridCellsDisplay::reset();
scene_node_->detachObject(cloud_);
delete cloud_;
}
}
void GridCellsDisplay::reset()
{
MFDClass::reset();
cloud_->clear();
}
void GridCellsDisplay::updateAlpha()
{
cloud_->setAlpha(alpha_property_->getFloat());
context_->queueRender();
}
bool validateFloats(const nav_msgs::GridCells& msg)
{
bool valid = true;
valid = valid && validateFloats(msg.cell_width);
valid = valid && validateFloats(msg.cell_height);
valid = valid && validateFloats(msg.cells);
return valid;
}
void GridCellsDisplay::processMessage(const nav_msgs::GridCells::ConstPtr& msg)
{
if (context_->getFrameCount() == last_frame_count_)
return;
last_frame_count_ = context_->getFrameCount();
cloud_->clear();
if (!validateFloats(*msg))
{
setStatus(StatusProperty::Error, "Topic",
"Message contained invalid floating point values (nans or infs)");
return;
}
Ogre::Vector3 position;
Ogre::Quaternion orientation;
if (!context_->getFrameManager()->getTransform(msg->header, position, orientation))
{
ROS_DEBUG("Error transforming from frame '%s' to frame '%s'", msg->header.frame_id.c_str(),
qPrintable(fixed_frame_));
}
scene_node_->setPosition(position);
scene_node_->setOrientation(orientation);
if (msg->cell_width == 0)
{
setStatus(StatusProperty::Error, "Topic", "Cell width is zero, cells will be invisible.");
}
else if (msg->cell_height == 0)
{
setStatus(StatusProperty::Error, "Topic", "Cell height is zero, cells will be invisible.");
}
cloud_->setDimensions(msg->cell_width, msg->cell_height, 0.0);
Ogre::ColourValue color_int = qtToOgre(color_property_->getColor());
uint32_t num_points = msg->cells.size();
typedef std::vector<PointCloud::Point> V_Point;
V_Point points;
points.resize(num_points);
for (uint32_t i = 0; i < num_points; i++)
{
PointCloud::Point& current_point = points[i];
current_point.position.x = msg->cells[i].x;
current_point.position.y = msg->cells[i].y;
current_point.position.z = msg->cells[i].z;
current_point.color = color_int;
}
cloud_->clear();
if (!points.empty())
{
cloud_->addPoints(&points.front(), points.size());
}
}
} // namespace rviz
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz::GridCellsDisplay, rviz::Display)
| 5,378 | 1,877 |
#include "Game.h"
#include "Log.h"
#include <mutex>
#include <future>
#include <chrono>
#include "UserAction.h"
#include "../component/Health.h"
namespace tbsd {
void Game::processAction(const Action& action) {
switch (action.getType()) {
case Action::Type::Connected:
users.emplace_back(std::any_cast<CppServer::WS::WSSession*>(action.data.back()));
{
entityx::Entity playableChar = entities.create();
playableChar.assign<Position>(0, 0, 0);
playableChar.assign<Health>(100);
users.back().owned.push_back(playableChar);
}
break;
case Action::Type::Disconnected:
auto session = std::any_cast<CppServer::WS::WSSession*>(action.data.back());
users.erase(
std::remove_if(users.begin(), users.end(), [&](User& u) {return u.session == session;}),
users.end());
break;
}
}
void Game::processCommand(ServerCommand command) {
switch (command) {
case Empty:
break;
case Invalid:
default:
Log::send("Invalid command", Log::Warning);
}
}
void Game::mainLoop(std::function<void(void)> newActionsHandler) {
std::string consoleInput;
std::future<std::string> console = std::async([&]{return IO::getFromConsole();});
// Main game loop
while (true) {
// Process data from console
if (console.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
consoleInput = console.get();
ServerCommand command = IO::parseCommand(consoleInput);
if (command == Shutdown)
return;
else
processCommand(command);
console = std::async([&]{return IO::getFromConsole();});
}
// Process data from server
static std::mutex m;
m.lock();
if (server.hasUserActions()) {
auto action = server.getUserAction();
try {
Action newAction(action->data);
// TODO: thing of a better way of adding pointers
// and not adding session where there no need for that
newAction.data.emplace_back(action->session);
actions.push(newAction);
} catch (std::exception &ex) {
Log::send(ex.what(), Log::Error);
}
m.unlock();
Log::send(action->data, Log::Received);
server.send(*action); // echo
} else
m.unlock();
// processActions();
newActionsHandler();
}
}
void Game::decreaseTime(Unit amount) {
// TODO: replace with a better solution. Create priority queue with random access?
std::priority_queue<Action, std::vector<Action>, Action::Greater> decreased;
while (!actions.empty()) {
auto action = actions.top();
actions.pop();
action.time -= amount;
decreased.push(action);
}
actions = decreased;
}
}
| 2,862 | 847 |
/// \file BoundarySetting.cpp
/// \brief Model of Boundaries in the XML
/// \date Dec 01, 2021
/// \author von Mach
/// \copyright <2015-2021> Forschungszentrum Juelich GmbH. All rights reserved.
#include "BoundarySetting.h"
namespace Settings {
BoundarySetting::BoundarySetting(tinyxml2::XMLElement *xml_element) :
field(xml_element->Attribute("field")),
patch(xml_element->Attribute("patch")),
type(xml_element->Attribute("type")),
value(std::atof(xml_element->Attribute("value"))) {
}
#ifndef BENCHMARKING
void BoundarySetting::print(spdlog::logger logger) const {
logger.debug("field={} patch={} type={} value={}", field, patch, type, value);
}
#endif
}
| 703 | 241 |
//== ВКЛЮЧЕНИЯ.
#include "dialog-about.h"
#include "ui_dialog-about.h"
//== ФУНКЦИИ КЛАССОВ.
//== Класс диалога "О программе".
// Конструктор.
DialogAbout::DialogAbout(QWidget *p_WidgetParent) : QDialog(p_WidgetParent), p_UI(new Ui::DialogAbout) { p_UI->setupUi(this); }
// Деструктор.
DialogAbout::~DialogAbout() { delete p_UI; }
| 333 | 144 |
/*
===============================================================================
FILE: Rxp2Lasdll
CONTENTS:
This source code converts rxp riegl format to LAS format (1.4)
or - its compressed, but identical twin - the LAZ format.
via RIVLIB (dll) + LasLib (dll)
VERSIONS:
--> CODEBLOCKS 16.01 + mingw 4.9 (GCC 4.9)
--> RIVLIB: rivlib-2_5_7-x86-windows-mgw49(Riegl DLL v7.1)
--> LASzip DLL v3.4 r1 (build 190728)
REFERENCES and LIBRARIES COPYRIGHT:
(c) Riegl 2008
pointclouddll.c - Example for reading pointcloud data (PC EXAMPLE)
SEE FOLDER:RIVLIB\doc\rivlib\examples
(c) LASZIP EXAMPLES: 2007-2014, martin isenburg, rapidlasso - fast tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the LICENSE.txt file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
martin.isenburg@rapidlasso.com - http://rapidlasso.com
SEE FOLDER:LAStools\LASzip\example
PROGRAMMERS:
MARIANA BATISTA CAMPOS - mariana.campos@nls.fi - https://orcid.org/0000-0003-3430-7521
RESEARCHER AT FINNISH GEOSPATIAL INSTITUTE - NATIONAL LAND SURVEY OF FINLAND
COPYRIGHT UNDER MIT LICENSE
Copyright (C) 2019-2020, NATIONAL LAND SURVEY OF FINLAND
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.
HISTORY:
DEC/2020 - FIRST VERSION RELEASE
======================================================================================
*/
/*
======================================================================================
I.PROJECT CONFIGURATION
PROJECT (CLICK ON THE PROJECT NAME)
NOTE: rivilib expects a working C++ 11 setup - more instructions in CmakeLists.txt
PROJECT --> Build options --> Compiler settings --> Compiler Flags [-std=c++11] * Compatibility with RIVLIB
PROJECT --> Build options --> Compiler settings --> OtherCompilerOptions:
-std=gnu++11
-std=gnu++0x
-fexceptions
PROJECT --> Build options --> Linker settings --> Linker options -->include standard C/C++ libs (kernel32, user32, gdi32, winspool comdig32 advapi32,
shell32, ole32, oleaut32, uuid, odbc32, obdc32)
PROJECT --> Build options --> Linker settings --> Other Linker options:
-static-libstdc++
-static-libgcc
-static
-Wl,--allow-multiple-definition
PROJECT --> Build options --> Search directory --> compiler/linker --> point to Lastools/Laslib/src
Lastools/Laslib/inc
Lastools/Laszip/src
Lastools/Laszip/dll
RIVLIB/include
RIVLIB/lib
TO RUN IN DEBUG MODE (CLICK ON DEBUG)
SET APPEND TARGET OPTIONS TO PROJECT OPTIONS
PROJECT --> Build options --> Compiler settings (SET THE SAME CONF. AS PROJECT) - OPTIONAL
PROJECT --> Build options --> Linker settings --> Linker options -->include RIVLIB libraries (-s.lib)
PROJECT --> Build options --> Search directory --> compiler/linker --> point to
RIVLIB/include
RIVLIB/lib RIVLIB/lib
TO RUN IN RELEASE MODE (CLICK ON RELEASE)
SET APPEND TARGET OPTIONS TO PROJECT OPTIONS
PROJECT --> Build options --> Compiler settings (SET THE SAME CONF. AS PROJECT)- OPTIONAL
PROJECT --> Build options --> Linker settings --> Linker options -->include RIVLIB libraries (-s.lib)
PROJECT --> Build options --> Search directory --> compiler/linker --> point to
RIVLIB/include
RIVLIB/lib
II. INPUT FILES: (Right click on the project name --> add files)
HEADERS: laszip_api.h, ctrlifc.h, scanifc.h
SOURCES:laszip_api.c, Rxp2Lasdll.cpp
III. By default, an executable will be build at bin\Debug or bin\Release
To change this path set Project --> Properties --> Build Targets
To run the executable, copy to the folder RIVLIB (dll) and LasLib (dll)
*MORE DETAILS AT DOCUMENTATION FILE
======================================================================================
*/
//------------------------------------INCLUDES---------------------------------
// C/C++ DEFAULT
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define _USE_MATH_DEFINES
#include <string.h>
#include <time.h>
#include <stdbool.h>
#include <sstream>
#include<algorithm>
// RIEGL and LASZIP DLL HEADER
#include <riegl/scanifc.h> // HEADER FOR RIEGL DLL
#include <riegl/pointcloud.hpp>
#include "laszip_api.h" // HEADER FOR LASZIP DLL
#if defined(_MSC_VER) && \
(_MSC_FULL_VER >= 150000000)
#define LASCopyString _strdup
#else
#define LASCopyString strdup
#endif
/*
==============================================================================================
INIT FUNCTIONS FROM LASZIP AND RIEGL
==============================================================================================
*/
void print_last_error() //FROM PC EXAMPLE (RIEGL)
{
char buffer[512];
scanifc_uint32_t bs;
scanifc_get_last_error(buffer, 512, &bs);
printf("%s\n", buffer);
}
void usage(bool wait = false){ //FROM LASZIP EXAMPLE
fprintf(stderr, "usage:\n");
fprintf(stderr, "lasexample_write_only_with_extra_bytes out.las\n");
fprintf(stderr, "lasexample_write_only_with_extra_bytes -o out.las -verbose\n");
fprintf(stderr, "lasexample_write_only_with_extra_bytes > out.las\n");
fprintf(stderr, "lasexample_write_only_with_extra_bytes -h\n");
if (wait)
{
fprintf(stderr, "<press ENTER>\n");
getc(stdin);
}
exit(1);
}
static void dll_error(laszip_POINTER laszip) //FROM LASZIP EXAMPLE
{
if (laszip)
{
laszip_CHAR* error;
if (laszip_get_error(laszip, &error))
{
fprintf(stderr,"DLL ERROR: getting error messages\n");
}
fprintf(stderr,"DLL ERROR MESSAGE: %s\n", error);
}
}
static void byebye(bool error=false, bool wait=false, laszip_POINTER laszip=0) //FROM LASZIP EXAMPLE
{
if (error)
{
dll_error(laszip);
}
if (wait)
{
fprintf(stderr,"<press ENTER>\n");
getc(stdin);
}
exit(error);
}
static double taketime() //FROM LASZIP EXAMPLE
{
return (double)(clock())/CLOCKS_PER_SEC;
}
int Check_Intersection(scanifc_xyz32 *pm, int countt, laszip_F64 sub_min_x, laszip_F64 sub_min_y, laszip_F64 sub_min_z,laszip_F64 sub_max_x,laszip_F64 sub_max_y,laszip_F64 sub_max_z)
{
int Flag_Intersection;
double MaxMin[6];
int n;
MaxMin[0]=MaxMin[1]=MaxMin[2]=-100000000;//MAX x,y,z
MaxMin[3]=MaxMin[4]=MaxMin[5]=10000000000;//MIN x,y,z
//FIND MAX AND MIN BUFFER
for(n=0; n<countt; n++){
if (pm[n].x > MaxMin[0]) { MaxMin[0]=pm[n].x;}
if (pm[n].y > MaxMin[1]) { MaxMin[1]=pm[n].y;}
if (pm[n].z > MaxMin[2]) { MaxMin[2]=pm[n].z;}
if (pm[n].x < MaxMin[3]) { MaxMin[3]=pm[n].x;}
if (pm[n].y < MaxMin[4]) { MaxMin[4]=pm[n].y;}
if (pm[n].z < MaxMin[5]) { MaxMin[5]=pm[n].z;}
}
//CHECK CASES WITH NO INTERSECTION
if(MaxMin[0]<sub_min_x
||MaxMin[3]>sub_max_x
||MaxMin[1]<sub_min_y
||MaxMin[4]>sub_max_y
||MaxMin[2]<sub_min_z
||MaxMin[5]>sub_max_z
){
Flag_Intersection=0;
}
else{Flag_Intersection=1;}
return Flag_Intersection;
}
/* Number of points to fetch per call; adjust to your preference. */
#define N_TARG 1024
/*
==============================================================================================
MAIN FUNCTIONS
==============================================================================================
*/
int main(int argc, char* argv[])
{
//-----------------------INIT VARS DEFINITIONS-----------------------
double start_time = 0.0;
char* file_name_out = 0;
//RIVLIB Variables
point3dstream_handle h3ds = 0; // This is the handle to the data stream (returned from open) */
int sync_to_pps = 0; // Set to 1 if reading data with gps sync information
scanifc_uint32_t countt;//Number of points in the buffer
scanifc_uint32_t n;
scanifc_uint32_t CropBuffer[3];
int end_of_frame;
int counter, counter_len;
counter=counter_len=0;
//These are the arrays for the RIVLIB buffer
scanifc_xyz32 rg_xyz32[N_TARG]; // The x,y,z coordinates*/
scanifc_attributes rg_attributes[N_TARG]; // The amplitude and quality attributes */
scanifc_time_ns rg_time[N_TARG]; // The timestamp (internal or gps) */
//LASZIP Variables
laszip_U32 i;
laszip_I64 p_count = 0;
scanifc_uint16_t major;
scanifc_uint16_t minor;
scanifc_uint16_t build;
//These are auxiliary Vars./arrays to build the LAS data (extra bytes)
laszip_F64 coordinates[3];
float range=0.0;
float theta=0.0;
float phi=0.0;
//VARS - BOUNDARY BOX DEFINITION
laszip_F64 sub_min_x;
laszip_F64 sub_min_y;
laszip_F64 sub_min_z;
laszip_F64 sub_max_x;
laszip_F64 sub_max_y;
laszip_F64 sub_max_z;
laszip_F64 sub_min_theta;
laszip_F64 sub_min_phi;
laszip_F64 sub_max_theta;
laszip_F64 sub_max_phi;
laszip_F64 sub_min_range;
laszip_F64 sub_max_range;
//RIVLIB BUFFER CHECK MAX/MIN AND INTERSECTION WITH BOUNDARY BOX
int Flag_Intersection;// TRUE IF FLAG ==1
//---------------------------------------------------------
//-----------------------LOADING DLL-----------------------
// load LASzip VIA DLL
if (laszip_load_dll())
{
fprintf(stderr,"DLL ERROR: loading LASzip DLL\n");
byebye(true, argc==1);
}
// get version of LASzip DLL
laszip_U8 version_major;
laszip_U8 version_minor;
laszip_U16 version_revision;
laszip_U32 version_build;
if (laszip_get_version(&version_major, &version_minor, &version_revision, &version_build))
{
fprintf(stderr,"DLL ERROR: getting LASzip DLL version number\n");
byebye(true, argc==1);
}
fprintf(stderr,"LASzip DLL v%d.%d r%d (build %d)\n", (int)version_major, (int)version_minor, (int)version_revision, (int)version_build);
// get version of Riegl DLL
if(scanifc_get_library_version(&major, &minor, &build)){
fprintf(stderr,"DLL ERROR: getting LASzip DLL version number\n");
return 1;
}
fprintf(stderr,"Riegl DLL v%d.%d\n", (int)major, (int)minor);
// ------------------------USER INPUT FILES------------------------------
if (argc == 1) {
char file_name_in[256];
char file_nameout[256];
fprintf(stderr,"Running via command line:%s\n", argv[0]);
fprintf(stderr,"enter input file: " ); fgets(file_name_in, 256, stdin);
file_name_in[strlen(file_name_in)-1] = '\0';
argv[1]=file_name_in;
fprintf(stderr, "FILE >> %s LOADED >>\n", argv[1]);
fprintf(stderr,"enter output file: "); fgets(file_nameout, 256, stdin);
file_nameout[strlen(file_nameout)-1] = '\0';
argv[2]=file_nameout;
fprintf(stderr, ">>FILE %s OPENED>>\n", argv[2]);
file_name_out = LASCopyString(argv[2]);
//argc=3;
}
//DEFINING CLIPPING
cout << "Please enter the min values x y z and max values x y z for the bounding box (optional - press enter to convert the complete file):" << endl;
if (std::cin.peek() == '\n'|| std::cin.peek() == ' ') // pressed enter after string?
{
sub_min_x=-10000000000;
sub_min_y=-10000000000;
sub_min_z=-10000000000;
sub_max_x= 10000000000;
sub_max_y= 10000000000;
sub_max_z= 10000000000;
}
else
{
std::cin >> sub_min_x>> sub_min_y>> sub_min_z >> sub_max_x>> sub_max_y>> sub_max_z; // will not block if we have char in buffer
}
cout << "Please enter the min values THETA PHI (DEGREES) RANGE (M) and max values THETA PHI RANGE for the bounding box (optional - press enter to convert the complete file):"<< endl;
cin.ignore();
if (std::cin.peek() == '\n'|| std::cin.peek() == ' ') // pressed enter after string?
{
sub_min_theta= -10000000000;
sub_min_phi= -10000000000;
sub_min_range= -10000000000;
sub_max_theta= 10000000000;
sub_max_phi= 10000000000;
sub_max_range= 10000000000;
}
else
{
std::cin >> sub_min_theta>> sub_min_phi>> sub_min_range>>sub_max_theta >> sub_max_phi >>sub_max_range; // will not block if we have char in buffer
}
//END OF BUFFER DEFINITION*/
//END OF USER INPUT
start_time = taketime();
if (scanifc_point3dstream_open(argv[1], sync_to_pps, &h3ds)) {
fprintf(stderr, "Cannot open: %s\n", argv[1]);
print_last_error();
return 1;
}
if (scanifc_point3dstream_add_demultiplexer(
h3ds
, "hk.txt", 0, "status protocol")) {
print_last_error();
return 1;
}
// ------------------CREATING WRITER VIA DLL-------------------
laszip_POINTER laszip_writer;
if (laszip_create(&laszip_writer))
{
fprintf(stderr,"DLL ERROR: creating laszip writer\n");
byebye(true, argc==1);
}
//HERE WE HAVE TWO WRITER OPTIONS
//OPTION 1 - SAVE FORMAT 1.2 + COMPATIBILITY MODE
//OPTION 2 - SAVE NATIVE FORMAT
// OPTION 1 : enable the compatibility mode to 1.4
/* laszip_BOOL request = 1;
if (laszip_request_compatibility_mode(laszip_writer, request))
{
fprintf(stderr,"DLL ERROR: enabling laszip LAS 1.4 compatibility mode\n");
byebye(true, argc==1, laszip_writer);
}*/
// OPTION 2 :enable to save the version in 1.4 format
laszip_BOOL request_native = 1;
if (laszip_request_native_extension(laszip_writer, request_native))
{
fprintf(stderr,"DLL ERROR: requesting native LAS 1.4 extension for the writer\n");
byebye(true, argc==1, laszip_writer);
}
// ----------------------------------HEADER-------------------------------
// get a pointer to the header of the writer so we can populate it
laszip_header* header;
if (laszip_get_header_pointer(laszip_writer, &header))
{
fprintf(stderr,"DLL ERROR: getting header pointer from laszip writer\n");
byebye(true, argc==1, laszip_writer);
}
//GET TIME OF CREATION
time_t t = time(NULL);
tm* timePtr = localtime(&t);
//HEADER DEFINE
header->file_source_ID = 4711;
header->global_encoding = (1<<0) | (1<<4);// see LAS specification for details
//header->global_encoding = 0x0001; // time stamps are in adjusted standard GPS time
header->version_major=1;
header->version_minor=4;
strncpy(header->system_identifier, "rxp2laz", 32);
strncpy(header->generating_software, "LASZIP&RIEGLdll", 32);
header->file_creation_day=timePtr->tm_mday;
header->file_creation_year=timePtr->tm_year+1900;
header->header_size = 375; // must be 375 for LAS 1.4
header->offset_to_point_data = 375;
header->point_data_format = 1;//Version 1.4(V1)to use all extra bytes
//header->point_data_format = 6;//Version 1.4(0 to 10), but 6 to 10 are preferred formats
header->number_of_point_records = 0;// legacy 32-bit counters should be zero for new point types > 5
header->x_scale_factor = 0.0001;//X,Y,Z recorded on mm level
header->y_scale_factor = 0.0001;
header->z_scale_factor = 0.0001;
//header->x_offset = 0.0;
//header->y_offset = 0.0;
//header->z_offset = 0.0;
// SET EXTRA BYTES: 30 + using short format(2 extra bytes per info)
//header->point_data_record_length = 30 + 18;//TO BE USED WITH FORMAT 6.0
header->point_data_record_length = 28 + 18;//reflectance, range, deviation, theta, phi #TO BE USED WITH FORMAT 1.0
header->start_of_waveform_data_packet_record = 0;
header->number_of_extended_variable_length_records = 0;
header->start_of_first_extended_variable_length_record = 0;
//SET MAX AND MIN VALUES OF X,Y,Z
//header->max_x =;
//header->min_x =;
//header->max_y =;
//header->min_y =;
//header->max_z =;
//header->min_z =;
// array of the total point records per return.
for (i = 0; i < 5; i++)//standard - 0 to 5
{
header->number_of_points_by_return[i] = 0;
}
//SET record return number - extension available at 1.4 format - MAX 15
header->extended_number_of_point_records = 0;// a-priori unknown number of points
for (i = 0; i < 15; i++)
{
header->extended_number_of_points_by_return[i] = 0;
}
// If the offset is not set in the header -->use the bounding box and the scale factor to create a offset (optional)
if (laszip_auto_offset(laszip_writer))
{
fprintf(stderr,"DLL ERROR: during automatic offset creation\n");
byebye(true, argc==1, laszip_writer);
}
// add description for the attributes in the "extra bytes": reflectance, deviation and range
if (laszip_add_attribute(laszip_writer, 8, "Reflectance", "Reflectance of a point", 1.00, 0.0))
{
fprintf(stderr,"DLL ERROR: adding 'Reflectance' attribute\n");
byebye(true, argc==1, laszip_writer);
}
if (laszip_add_attribute(laszip_writer, 3, "Deviation", "Deviation of a point", 1.00, 0.0))
{
fprintf(stderr,"DLL ERROR: adding 'Deviation' attribute\n");
byebye(true, argc==1, laszip_writer);
}
if (laszip_add_attribute(laszip_writer, 8, "Range", "Range of a point", 1.00, 0.0))
{
fprintf(stderr,"DLL ERROR: adding 'Range' attribute\n");
byebye(true, argc==1, laszip_writer);
}
//add description for the attributes in the "extra bytes": theta and phi
if (laszip_add_attribute(laszip_writer, 8, "Theta", "Scan_Angle_Theta", 1.00, 0.0))
{
fprintf(stderr,"DLL ERROR: adding 'Theta' attribute\n");
byebye(true, argc==1, laszip_writer);
}
if (laszip_add_attribute(laszip_writer, 8, "Phi", "Scan_Angle_Phi", 1.00, 0.0))
{
fprintf(stderr,"DLL ERROR: adding 'Phi' attribute\n");
byebye(true, argc==1, laszip_writer);
}
//END OF HEADER DEFINITION
// -------------------------------------------------------------
fprintf(stderr,"\n opening rxp format.... \n");
fprintf(stderr,"writing LAS 1.4 points with \"extra bytes\" *with* compatibility to compressed LAZ *and* also uncompressed LAS\n");
/** ------------------------WRITING-----------------------------
// I - OPEN THE WRITER*/
laszip_BOOL compress = (strstr(file_name_out, ".laz") != 0);
if (laszip_open_writer(laszip_writer, file_name_out, compress))
{
fprintf(stderr,"DLL ERROR: opening laszip writer for '%s'\n", file_name_out);
byebye(true, argc==1, laszip_writer);
}
fprintf(stderr,"writing file '%s' %scompressed\n", file_name_out, (compress ? "" : "un"));
/** II - Define a pointer to the point of the writer that we will populate and write */
laszip_point* point;
if (laszip_get_point_pointer(laszip_writer, &point))
{
fprintf(stderr,"DLL ERROR: getting point pointer from laszip writer\n");
byebye(true, argc==1, laszip_writer);
}
do {
/**************************************************************************//**
*III -The read function will fill point data into user supplied buffers.
* \param h3ds [in] the stream heandle that has been returned from open.
* \param want [in] the size of the result buffers (count of points).
* \param pxyz32 [out] pointer to xyz buffer
* \param pattributes [out] pointer to amplitude and quality buffer
* \param ptime [out] pointer to timestamp buffer
* \param got [out] number of points returned (may be smaller than want).
* \param end_of_frame [out] != 0 if end of frame detected
* \return 0 for success, !=0 for failure
pattributes - Amplitude, deviation, reflectance, background radiation, flags
flags (rg_attributes[n].flags) --> The flags combine some attributes into a single value for compact storage.
bit0-1: 0 single echo 1 first echo 2 interior echo 3 last echo (rg_attributes[n].flags & 0x03 to select multi return bits)
bit2: reserved
bit3: waveform available
bit4: 1 pseudo echo with fixed range 0.1m
bit5: 1 sw calculated target
bit6: 1 pps not older than 1.5 sec
bit7: 1 time in pps timeframe (rg_attributes[n].flags & 0x40)>>6)
bit8-9: facet or segment number 0 to 3
bits10-15: reserved
*****************************************************************************/
if (scanifc_point3dstream_read(
h3ds
, N_TARG
, rg_xyz32 //3d COORDINATES
, rg_attributes //Amplitude, deviation, reflectance, background radiation, flags
, rg_time
, &countt
, &end_of_frame
)) {
fprintf(stderr, "Error reading %s\n", argv[1]);
return 1;
}
//Checking intersection between buffer and bounding box
Flag_Intersection=Check_Intersection(rg_xyz32, countt, sub_min_x, sub_min_y, sub_min_z, sub_max_x,sub_max_y,sub_max_z);
if (Flag_Intersection==1)
{
/**-------------------------------------------------------------
V - populating points*/
for (n=0; n<countt; ++n) {
// Checking points from buffer inside of the bounding box
if ( rg_xyz32[n].x <= sub_max_x
&&rg_xyz32[n].x >= sub_min_x
&&rg_xyz32[n].y <= sub_max_y
&&rg_xyz32[n].y >= sub_min_y
&&rg_xyz32[n].z <= sub_max_z
&&rg_xyz32[n].z >= sub_min_z
)
{
// Range = Distance
range=sqrt((rg_xyz32[n].x*rg_xyz32[n].x)+(rg_xyz32[n].y*rg_xyz32[n].y)+(rg_xyz32[n].z*rg_xyz32[n].z));
// Polar coordinates Phi(Horizontal) and Theta(Vertical)
theta=acos(rg_xyz32[n].z/range);
phi=atan2(rg_xyz32[n].y, rg_xyz32[n].x); //scanning right to left
phi=((phi < 0.0) ? (phi + 2.0 * M_PI) : phi);
//sub_min_theta>> sub_min_phi>> sub_max_theta >> sub_max_phi
if (phi > (sub_min_phi*M_PI/180) && phi < (sub_max_phi*M_PI/180) && theta > (sub_min_theta*M_PI/180) && theta < (sub_max_theta*M_PI/180) && (range > sub_min_range) && (range < sub_max_range)){
//Saving X,Y,Z coordinates
coordinates[0] = rg_xyz32[n].x;
coordinates[1] = rg_xyz32[n].y;
coordinates[2] = rg_xyz32[n].z;
// Calculating Row and line
//RC=RowColumn(theta, phi, thetaStart, phiStart, Angle_Step);
if (laszip_set_coordinates(laszip_writer, coordinates))
{
fprintf(stderr,"DLL ERROR: setting coordinates for point %I64d\n", p_count);
byebye(true, argc==1, laszip_writer);
}
//saving standard parameters
//intensity, return number, number of returns, classification, scan angle, scanner channel, gps_time
point->intensity = rg_attributes[n].amplitude;
point->gps_time = rg_time[n];
//point->classification = 5; // it must be set because it "fits" in 5 bits
//point->edge_of_flight_line=;
//point->rgb= ;
//point->user_data= ;
//point->scan_angle_rank= ;
//point->scan_direction_flag= ;
// saving extended parameters (V 1.4)
//extended_number_of_returns and extended_return_number
//SINGLE RETURN
if ((rg_attributes[n].flags & 0x03) == 0){
point->number_of_returns =1;
point->return_number = 1;
//point->extended_number_of_returns =1; //FOR FORMAT > 5 USE EXTENDED...
//point->extended_return_number = 1;
counter=0;
counter_len=0;
}
//MULTIPLE RETURNS(1,2,3)
else{
if ((rg_attributes[n].flags & 0x03) == 1){
counter=0;
counter_len=0;
int it=n+1;
while ((rg_attributes[it].flags & 0x03)>1){
counter=counter+1;
it=it+1;
}
if(counter>5){ counter=4;}
point->number_of_returns=counter+1;
point->return_number=1;
//point->extended_number_of_returns=counter+1;
//point->extended_return_number=1;
it=counter=0;
counter_len=1;
}
if ((rg_attributes[n].flags & 0x03) == 2){
counter=counter_len;
int it=n;
while ((rg_attributes[it].flags & 0x03)==2){
counter=counter+1;
it=it+1;
}
if(counter>5){counter=3;}
if(counter_len>5){ counter_len=3;}
point->number_of_returns=counter+1;
point->return_number=counter_len+1;
//point->extended_number_of_returns=counter+1;
//point->extended_return_number=counter_len+1;
it=counter=0;
counter_len=counter_len+1;
}
if ((rg_attributes[n].flags & 0x03) == 3){
point->number_of_returns=counter_len+1;
point->return_number=counter_len+1;
//point->extended_number_of_returns=counter_len+1;
//point->extended_return_number=counter_len+1;
counter=0;
counter_len=0;
}
}
//point->extended_classification = 5; //3 to 5 vegetation
//point->extended_scan_angle =;
//point->extended_scanner_channel = ;
//point->extended_classification_flags= ;
//point->extended_point_type= ;
// set attribute 'reflectance', 'Deviation' and 'Range', 'Theta' and 'Phi'
*((laszip_F32*)(point->extra_bytes+0))=rg_attributes[n].reflectance; //reflectance of a point
*((laszip_I16*)(point->extra_bytes+4))=rg_attributes[n].deviation+1; //deviation - shape deviation of point
*((laszip_F32*)(point->extra_bytes+6))=(laszip_F32)range;//distance computed from coordinates - range of point
*((laszip_F32*)(point->extra_bytes+10))=(laszip_F32)theta*(180/M_PI);//theta angle computed - Vertical resolution
*((laszip_F32*)(point->extra_bytes+14))=(laszip_F32)phi*(180/M_PI);//phi angle computed - Horizontal Resolution
if (laszip_write_point(laszip_writer))
{
fprintf(stderr,"DLL ERROR: writing point %I64d\n", p_count);
byebye(true, argc==1, laszip_writer);
}
if (laszip_update_inventory(laszip_writer))
{
fprintf(stderr,"DLL ERROR: setting header pointer from laszip writer\n");
byebye(true, argc==1, laszip_writer);
}
p_count++;
} //END IF POINT INSIDE BOUNDARY THETA PHI CHECK
} //END IF POINT INSIDE BOUNDARY XYZ CHECK
} //END IF BUFFER AND BOUNDARY INTERSECTION
} //END FOR
} while(countt >0); /* END DO: count will be zero at the end of available data */
// ----------------------------------------------------------------------
// get the number of points written so far
if (laszip_get_point_count(laszip_writer, &p_count))
{
fprintf(stderr,"DLL ERROR: getting point count\n");
byebye(true, argc==1, laszip_writer);
}
fprintf(stderr,"successfully written %I64d points\n", p_count);
/* CLOSING LASZIP AND RIEGL , to prevent a memory leak. */
// close the writer
if (laszip_close_writer(laszip_writer))
{
fprintf(stderr,"DLL ERROR: closing laszip writer\n");
byebye(true, argc==1, laszip_writer);
}
// destroy the writer
if (laszip_destroy(laszip_writer))
{
fprintf(stderr,"DLL ERROR: destroying laszip writer\n");
byebye(true, argc==1);
}
fprintf(stderr,"total time: %g sec for writing %scompressed\n", taketime()-start_time, (compress ? "" : "un"));
// unload LASzip DLL
if (laszip_unload_dll())
{
fprintf(stderr,"DLL ERROR: unloading LASzip DLL\n");
byebye(true, argc==1);
}
// close the scanifc
if (scanifc_point3dstream_close(h3ds)) {
fprintf(stderr, "Error, closing %s\n", argv[1]);
return 1;
}
return 0;
fprintf(stderr, "Usage: %s <input-uri>\n", argv[0]);
return 1;
} // END MAIN CODE
| 30,205 | 10,693 |
/*
* $Id: $
*
* System I/O dispatching implementation
*
* Copyright (c) 2014-2015 Zerone.IO (Shanghai). All rights reserved.
*
* $Log: $
*
*/
#include "Base.h"
#include "Log.h"
#include "Trace.h"
#include "GlobalDefine.h"
#include "DispatchIO.h"
#include "algoapi/zmq/ZmqHelper.h"
#include <string>
using namespace std;
using namespace ATS;
#define USE_ZMQ_POLL 1
#define ZMQ_POLL_TIMEOUT 10 // 10ms
DispatchIO::DispatchIO(void) : n_mq(0)
{
m_zmqctx = zmq_ctx_new();
zmq_ctx_set(m_zmqctx, ZMQ_MAX_SOCKETS, 128);
}
DispatchIO::~DispatchIO(void)
{
for (int i = 0; i < n_mq; i++) {
delete a_mqs[i];
}
zmq_ctx_term(m_zmqctx);
// zmq_ctx_destroy(m_zmqctx); // deprecated
}
BaseZmqClient *DispatchIO::AssignSfHandler(SwordFishIntf *psf, BaseMsgDispatcher *dsp)
{
if (n_mq < (int)MAX_MQ_COUNT) {
psf->SetContext(m_zmqctx);
psf->SetUserParseFunc(dsp->GetMessageParser());
a_mqs[n_mq++] = new _MqDesc(psf, dsp, dsp);
}
return (BaseZmqClient *)psf;
}
BaseZmqClient *DispatchIO::AssignMqHandler(BaseZmqClient *pmq, IDispatcher *dsp)
{
if (n_mq < (int)MAX_MQ_COUNT) {
pmq->SetContext(m_zmqctx);
a_mqs[n_mq++] = new _MqDesc(pmq, dsp, NULL);
}
return pmq;
}
int DispatchIO::DispatchInfinitely(void *ctx, bool do_egress)
{
int i;
#if USE_ZMQ_POLL
int n_items = 0;
zmq_pollitem_t poll_items[MAX_MQ_COUNT];
for (i = 0; i < n_mq && i < (int)MAX_MQ_COUNT; i++) {
zmq_pollitem_t *pitem = &poll_items[i];
pitem->socket = a_mqs[i]->GetSocket();
pitem->fd = a_mqs[i]->GetFd();
pitem->events = ZMQ_POLLIN | ZMQ_POLLERR;
pitem->revents = 0;
n_items++;
TRACE_THREAD(7, "poll_item { socket: 0x%x, fd: %d }",
pitem->socket, pitem->fd);
}
LOGFILE(LOG_DEBUG, "ZMQ polling on %d items", n_items);
#endif /* USE_ZMQ_POLL */
do {
#if USE_ZMQ_POLL
int rc = zmq_poll(poll_items, n_items, ZMQ_POLL_TIMEOUT);
if (rc > 0) { // has events
i = 0;
TRACE_THREAD(8, "Got %d events", rc);
while (i < n_items && rc > 0) {
int revts = poll_items[i].revents;
if (revts) { // this item got an event
rc--;
TRACE_THREAD(8, "ZMQ#%d polled!", i);
if (revts & ZMQ_POLLIN) {
onDispatch(a_mqs[i]);
}
if (revts & ZMQ_POLLERR) {
LOGFILE(LOG_WARN, "socket %d has error", i);
// TODO
}
}
i++;
} // while (i && rc)
} else if (0 == rc) { // timeout
// TODO ---
// TRACE_THREAD(7, "timeout!");
} else { // -1 check errors
int err = zmq_errno();
switch (err) {
case EBADF: // fd or socket closed
// TODO: reopen or re-initialize MQ
LOGFILE(LOG_WARN, "zmq_poll got EBADF: %s", zmq_strerror(err));
break;
case EINTR:
// got SIGCHLD or SIGALRM
// assert(0);
LOGFILE(LOG_WARN, "got SIGCHLD or SIGALRM");
break;
default:
// what's up?
LOGFILE(LOG_WARN, "zmq_poll got error: %s", zmq_strerror(err));
// assert(0);
break;
}
} // if (rc)
#else /* !USE_ZMQ_POLL */
for (i = 0; i < n_mq; i++) {
onDispatch(&a_mqs[i]);
}
#endif /* USE_ZMQ_POLL */
if (do_egress) {
ProcessEgress();
}
} while (!g_is_exiting);
return 0;
}
TDispResult DispatchIO::onDispatch(Object desc)
{
_MqDesc *mqd = (_MqDesc *)desc;
TDispResult ret = DR_DROPPED;
Object obj;
if (NULL != (obj = mqd->doRecv())) {
ret = mqd->doDispatch(obj);
} else {
TRACE_THREAD(7, "DispatchIO::onDispatch: unknown message");
}
if (DR_SUCCESS != ret) {
// TODO: to check status
}
if (DR_CONTINUE == ret) {
// TODO: broadcast this message to all
}
return ret;
}
| 4,356 | 1,658 |
/*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
/* @migen@ */
#include <MI.h>
#include "X_Halves_Class_Provider.h"
MI_BEGIN_NAMESPACE
X_SmallNumber_Class FillNumberByKey(
Uint64 key);
X_Halves_Class_Provider::X_Halves_Class_Provider(
Module* module) :
m_Module(module)
{
}
X_Halves_Class_Provider::~X_Halves_Class_Provider()
{
}
void X_Halves_Class_Provider::EnumerateInstances(
Context& context,
const String& nameSpace,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::GetInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& instance_ref,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::CreateInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& new_instance)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::ModifyInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& new_instance,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::DeleteInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& instance_ref)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::AssociatorInstances(
Context& context,
const String& nameSpace,
const MI_Instance* instanceName,
const String& resultClass,
const String& role,
const String& resultRole,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
if (!X_SmallNumber_IsA(instanceName))
{
context.Post(MI_RESULT_FAILED);
return ;
}
X_SmallNumber_Class number((const X_SmallNumber*)instanceName,true);
if (!number.Number().exists)
{ // key is missing
context.Post(MI_RESULT_FAILED);
return ;
}
Uint64 num = number.Number().value;
// check if we have smaller half
if (num % 2 == 0 &&
(role.GetSize() == 0 || role == MI_T("number")) && // check role
(resultRole.GetSize() == 0 || resultRole == MI_T("half")) // check result role
)
{
context.Post(FillNumberByKey(num / 2));
}
// check if we have bigger half
if (num * 2 < 10000 &&
(role.GetSize() == 0 || role == MI_T("half")) && // check role
(resultRole.GetSize() == 0 || resultRole == MI_T("number")) // check result role
)
{
context.Post(FillNumberByKey(num * 2));
}
context.Post(MI_RESULT_OK);
}
void X_Halves_Class_Provider::ReferenceInstances(
Context& context,
const String& nameSpace,
const MI_Instance* instanceName,
const String& role,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
MI_END_NAMESPACE
MI_BEGIN_NAMESPACE
void X_Halves_Class_Provider::Load(
Context& context)
{
context.Post(MI_RESULT_OK);
}
void X_Halves_Class_Provider::Unload(
Context& context)
{
context.Post(MI_RESULT_OK);
}
MI_END_NAMESPACE
| 3,494 | 1,201 |
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <unordered_set>
#include "caf/fwd.hpp"
#include "caf/group.hpp"
namespace caf::mixin {
/// Marker for `subscriber`.
struct subscriber_base {};
/// A `subscriber` is an actor that can subscribe
/// to a `group` via `self->join(...)`.
template <class Base, class Subtype>
class subscriber : public Base, public subscriber_base {
public:
// -- member types -----------------------------------------------------------
/// Allows subtypes to refer mixed types with a simple name.
using extended_base = subscriber;
/// A container for storing subscribed groups.
using subscriptions = std::unordered_set<group>;
// -- constructors, destructors, and assignment operators --------------------
template <class... Ts>
subscriber(actor_config& cfg, Ts&&... xs)
: Base(cfg, std::forward<Ts>(xs)...) {
if (cfg.groups != nullptr)
for (auto& grp : *cfg.groups)
join(grp);
}
// -- overridden functions of monitorable_actor ------------------------------
bool cleanup(error&& fail_state, execution_unit* ptr) override {
auto me = this->ctrl();
for (auto& subscription : subscriptions_)
subscription->unsubscribe(me);
subscriptions_.clear();
return Base::cleanup(std::move(fail_state), ptr);
}
// -- group management -------------------------------------------------------
/// Causes this actor to subscribe to the group `what`.
/// The group will be unsubscribed if the actor finishes execution.
void join(const group& what) {
CAF_LOG_TRACE(CAF_ARG(what));
if (what == invalid_group)
return;
if (what->subscribe(this->ctrl()))
subscriptions_.emplace(what);
}
/// Causes this actor to leave the group `what`.
void leave(const group& what) {
CAF_LOG_TRACE(CAF_ARG(what));
if (subscriptions_.erase(what) > 0)
what->unsubscribe(this->ctrl());
}
/// Returns all subscribed groups.
const subscriptions& joined_groups() const {
return subscriptions_;
}
private:
// -- data members -----------------------------------------------------------
/// Stores all subscribed groups.
subscriptions subscriptions_;
};
} // namespace caf
| 3,545 | 943 |
#include <dis6/LinearSegmentParameter.h>
using namespace DIS;
LinearSegmentParameter::LinearSegmentParameter():
_segmentNumber(0),
_segmentAppearance(),
_location(),
_orientation(),
_segmentLength(0),
_segmentWidth(0),
_segmentHeight(0),
_segmentDepth(0),
_pad1(0)
{
}
LinearSegmentParameter::~LinearSegmentParameter()
{
}
unsigned char LinearSegmentParameter::getSegmentNumber() const
{
return _segmentNumber;
}
void LinearSegmentParameter::setSegmentNumber(unsigned char pX)
{
_segmentNumber = pX;
}
SixByteChunk& LinearSegmentParameter::getSegmentAppearance()
{
return _segmentAppearance;
}
const SixByteChunk& LinearSegmentParameter::getSegmentAppearance() const
{
return _segmentAppearance;
}
void LinearSegmentParameter::setSegmentAppearance(const SixByteChunk &pX)
{
_segmentAppearance = pX;
}
Vector3Double& LinearSegmentParameter::getLocation()
{
return _location;
}
const Vector3Double& LinearSegmentParameter::getLocation() const
{
return _location;
}
void LinearSegmentParameter::setLocation(const Vector3Double &pX)
{
_location = pX;
}
Orientation& LinearSegmentParameter::getOrientation()
{
return _orientation;
}
const Orientation& LinearSegmentParameter::getOrientation() const
{
return _orientation;
}
void LinearSegmentParameter::setOrientation(const Orientation &pX)
{
_orientation = pX;
}
unsigned short LinearSegmentParameter::getSegmentLength() const
{
return _segmentLength;
}
void LinearSegmentParameter::setSegmentLength(unsigned short pX)
{
_segmentLength = pX;
}
unsigned short LinearSegmentParameter::getSegmentWidth() const
{
return _segmentWidth;
}
void LinearSegmentParameter::setSegmentWidth(unsigned short pX)
{
_segmentWidth = pX;
}
unsigned short LinearSegmentParameter::getSegmentHeight() const
{
return _segmentHeight;
}
void LinearSegmentParameter::setSegmentHeight(unsigned short pX)
{
_segmentHeight = pX;
}
unsigned short LinearSegmentParameter::getSegmentDepth() const
{
return _segmentDepth;
}
void LinearSegmentParameter::setSegmentDepth(unsigned short pX)
{
_segmentDepth = pX;
}
unsigned int LinearSegmentParameter::getPad1() const
{
return _pad1;
}
void LinearSegmentParameter::setPad1(unsigned int pX)
{
_pad1 = pX;
}
void LinearSegmentParameter::marshal(DataStream& dataStream) const
{
dataStream << _segmentNumber;
_segmentAppearance.marshal(dataStream);
_location.marshal(dataStream);
_orientation.marshal(dataStream);
dataStream << _segmentLength;
dataStream << _segmentWidth;
dataStream << _segmentHeight;
dataStream << _segmentDepth;
dataStream << _pad1;
}
void LinearSegmentParameter::unmarshal(DataStream& dataStream)
{
dataStream >> _segmentNumber;
_segmentAppearance.unmarshal(dataStream);
_location.unmarshal(dataStream);
_orientation.unmarshal(dataStream);
dataStream >> _segmentLength;
dataStream >> _segmentWidth;
dataStream >> _segmentHeight;
dataStream >> _segmentDepth;
dataStream >> _pad1;
}
bool LinearSegmentParameter::operator ==(const LinearSegmentParameter& rhs) const
{
bool ivarsEqual = true;
if( ! (_segmentNumber == rhs._segmentNumber) ) ivarsEqual = false;
if( ! (_segmentAppearance == rhs._segmentAppearance) ) ivarsEqual = false;
if( ! (_location == rhs._location) ) ivarsEqual = false;
if( ! (_orientation == rhs._orientation) ) ivarsEqual = false;
if( ! (_segmentLength == rhs._segmentLength) ) ivarsEqual = false;
if( ! (_segmentWidth == rhs._segmentWidth) ) ivarsEqual = false;
if( ! (_segmentHeight == rhs._segmentHeight) ) ivarsEqual = false;
if( ! (_segmentDepth == rhs._segmentDepth) ) ivarsEqual = false;
if( ! (_pad1 == rhs._pad1) ) ivarsEqual = false;
return ivarsEqual;
}
int LinearSegmentParameter::getMarshalledSize() const
{
int marshalSize = 0;
marshalSize = marshalSize + 1; // _segmentNumber
marshalSize = marshalSize + _segmentAppearance.getMarshalledSize(); // _segmentAppearance
marshalSize = marshalSize + _location.getMarshalledSize(); // _location
marshalSize = marshalSize + _orientation.getMarshalledSize(); // _orientation
marshalSize = marshalSize + 2; // _segmentLength
marshalSize = marshalSize + 2; // _segmentWidth
marshalSize = marshalSize + 2; // _segmentHeight
marshalSize = marshalSize + 2; // _segmentDepth
marshalSize = marshalSize + 4; // _pad1
return marshalSize;
}
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
| 6,228 | 1,998 |
#ifndef ENCODER_HPP
#define ENCODER_HPP
#include <QImage>
#include <QSize>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}
struct OutputStream {
AVStream *st = NULL;
AVCodecContext *enc = NULL;
int64_t nextPts = 0;
AVFrame *frame = NULL;
SwsContext *sws = NULL;
};
struct CodecSettings {
int bitrate;
int gopSize;
int bFrames;
int mbDecisions;
QString h264Profile;
int h264Crf;
bool vp9Lossless;
};
class Encoder {
public:
Encoder(QString &targetFile, QSize res, CodecSettings *settings = NULL);
~Encoder();
bool addFrame(QImage frm);
bool isRunning();
bool end();
private:
AVCodec *codec = NULL;
OutputStream *out = new OutputStream;
AVFormatContext *fc = NULL;
bool success = false;
bool ended = false;
QSize size;
void setFrameRGB(QImage img);
};
#endif // ENCODER_HPP
| 946 | 362 |
#include <Kin/F_qFeatures.h>
#include <Kin/F_PairCollision.h>
#include <Kin/TM_angVel.h>
#include <Kin/F_dynamics.h>
#include <Kin/F_pose.h>
#include <Kin/F_contacts.h>
#include <Kin/forceExchange.h>
#include <iomanip>
extern bool orsDrawWires;
extern bool rai_Kin_frame_ignoreQuatNormalizationWarning;
//===========================================================================
void testFeature() {
rai::Configuration C;
rai::Frame world(C), obj1(&world), obj2(&world);
world.name = "world";
obj1.name = "obj1";
obj2.name = "obj2";
obj1.setRelativePosition({1.,1.,1.});
obj2.setRelativePosition({-1.,-1.,1.});
obj1.setShape(rai::ST_ssBox, ARR(1.,1.,1.,rnd.uni(.01, .3)));
obj2.setShape(rai::ST_ssBox, ARR(1.,1.,1.,rnd.uni(.01, .3)));
obj1.setColor({.5,.8,.5,.4});
obj2.setColor({.5,.5,.8,.4});
rai::Joint j1(obj1, rai::JT_free);
rai::Joint j2(obj2, rai::JT_transXYPhi);
rai::Inertia m1(obj1), m2(obj2);
m1.defaultInertiaByShape();
m2.defaultInertiaByShape();
rai::ForceExchange con(obj1, obj2);
C.setTimes(.1);
rai::Configuration C1(C), C2(C);
ConfigurationL Ktuple = {&C, &C1, &C2};
uint n=3*C.getJointStateDimension();
rai::Array<ptr<Feature>> F;
F.append(make_shared<F_PairCollision>(C, "obj1", "obj2", F_PairCollision::_negScalar));
F.append(make_shared<F_PairCollision>(C, "obj1", "obj2", F_PairCollision::_vector));
F.append(make_shared<F_PairCollision>(C, "obj1", "obj2", F_PairCollision::_center));
F.append(make_shared<TM_LinAngVel>(C, "obj1"));
F.append(make_shared<TM_LinAngVel>(C, "obj2")) -> order=2;
F.append(make_shared<F_Pose>(C, "obj1"));
F.append(make_shared<F_Pose>(C, "obj2")) -> order=1;
F.append(make_shared<F_Pose>(C, "obj1")) -> order=2;
F.append(symbols2feature(FS_poseRel, {"obj1", "obj2"}, C)) -> order=0;
F.append(symbols2feature(FS_poseRel, {"obj1", "obj2"}, C)) -> order=1;
F.append(symbols2feature(FS_poseRel, {"obj1", "obj2"}, C)) -> order=2;
F.append(symbols2feature(FS_poseDiff, {"obj1", "obj2"}, C)) -> order=0;
F.append(symbols2feature(FS_poseDiff, {"obj1", "obj2"}, C)) -> order=1;
F.append(symbols2feature(FS_poseDiff, {"obj1", "obj2"}, C)) -> order=2;
F.append(make_shared<F_NewtonEuler>(C, "obj1"));
rai_Kin_frame_ignoreQuatNormalizationWarning=true;
for(uint k=0;k<100;k++){
arr x = 5.*(rand(n)-.5);
bool succ=true;
for(ptr<Feature>& f: F){
cout <<k <<std::setw(30) <<f->shortTag(C) <<' ';
succ &= checkJacobian(f->vf(Ktuple), x, 1e-5);
}
arr y;
F.first()->__phi(y, NoArr, Ktuple);
if(!succ)
C2.watch(true);
}
}
//===========================================================================
int MAIN(int argc, char** argv){
rai::initCmdLine(argc, argv);
rnd.clockSeed();
testFeature();
return 0;
}
| 2,796 | 1,214 |
#include<bits/stdc++.h>
#define FOR(i,m,n) for(int i=m;i<(n);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
int main(void){
int q;
cin >> q;
if (q == 1)
cout << "ABC" << endl;
else
cout << "chokudai" << endl;
return 0;
}
| 306 | 147 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/common/api/bluetooth/bluetooth_manifest_handler.h"
#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h"
#include "extensions/common/api/bluetooth/bluetooth_manifest_permission.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
namespace extensions {
BluetoothManifestHandler::BluetoothManifestHandler() {}
BluetoothManifestHandler::~BluetoothManifestHandler() {}
bool BluetoothManifestHandler::Parse(Extension* extension,
base::string16* error) {
const base::Value* bluetooth = NULL;
CHECK(extension->manifest()->Get(manifest_keys::kBluetooth, &bluetooth));
std::unique_ptr<BluetoothManifestData> data =
BluetoothManifestData::FromValue(*bluetooth, error);
if (!data)
return false;
extension->SetManifestData(manifest_keys::kBluetooth, data.release());
return true;
}
ManifestPermission* BluetoothManifestHandler::CreatePermission() {
return new BluetoothManifestPermission();
}
ManifestPermission* BluetoothManifestHandler::CreateInitialRequiredPermission(
const Extension* extension) {
BluetoothManifestData* data = BluetoothManifestData::Get(extension);
if (data)
return data->permission()->Clone();
return NULL;
}
const std::vector<std::string> BluetoothManifestHandler::Keys() const {
return SingleKey(manifest_keys::kBluetooth);
}
} // namespace extensions
| 1,597 | 474 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "longformer_attention_base.h"
namespace onnxruntime {
namespace contrib {
Status LongformerAttentionBase::CheckInputs(const TensorShape& input_shape,
const TensorShape& weights_shape,
const TensorShape& bias_shape,
const TensorShape& mask_shape,
const TensorShape& global_weights_shape,
const TensorShape& global_bias_shape,
const TensorShape& global_shape) const {
// Input shapes:
// input : (batch_size, sequence_length, hidden_size)
// weights : (hidden_size, 3 * hidden_size)
// bias : (3 * hidden_size)
// mask : (batch_size, sequence_length)
// global_weights : (hidden_size, 3 * hidden_size)
// global_bias : (3 * hidden_size)
// global : (batch_size, sequence_length)
const auto& dims = input_shape.GetDims();
if (dims.size() != 3) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'input' is expected to have 3 dimensions, got ",
dims.size());
}
int batch_size = static_cast<int>(dims[0]);
int sequence_length = static_cast<int>(dims[1]);
int hidden_size = static_cast<int>(dims[2]);
if (sequence_length % (2 * window_) != 0) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Input 'input' dimension 1 should be divisiable by 2W, where W is value of the window attribute.");
}
if (hidden_size % num_heads_ != 0) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Input 'input' dimension 2 should be divisiable by value of the num_heads attribute.");
}
const auto& weights_dims = weights_shape.GetDims();
if (weights_dims.size() != 2) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'weights' is expected to have 2 dimensions, got ",
weights_dims.size());
}
if (weights_dims[0] != dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Input 'weights' dimension 0 should have same length as dimension 2 of input 0");
}
if (weights_dims[1] != 3 * weights_dims[0]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'weights' dimension 1 should be 3 times of dimension 0");
}
const auto& bias_dims = bias_shape.GetDims();
if (bias_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'bias' is expected to have 1 dimension, got ",
bias_dims.size());
}
if (bias_dims[0] != weights_dims[1]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Input 'bias' dimension 0 should have same length as dimension 1 of input 'weights'");
}
const auto& mask_dims = mask_shape.GetDims();
if (mask_dims.size() == 2) {
if (static_cast<int>(mask_dims[0]) != batch_size || static_cast<int>(mask_dims[1]) != sequence_length) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Inputs 'mask' shall have shape batch_size x sequence_length");
}
} else {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'mask' is expected to have 2 dimensions, got ",
mask_dims.size());
}
const auto& global_weights_dims = global_weights_shape.GetDims();
if (global_weights_dims.size() != 2) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_weights' is expected to have 2 dimensions, got ",
weights_dims.size());
}
if (global_weights_dims[0] != dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Input 'global_weights' dimension 0 should have same length as dimension 2 of input 0");
}
if (global_weights_dims[1] != 3 * global_weights_dims[0]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_weights' dimension 1 should be 3 times of dimension 0");
}
const auto& global_bias_dims = global_bias_shape.GetDims();
if (global_bias_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_bias' is expected to have 1 dimension, got ",
global_bias_dims.size());
}
if (global_bias_dims[0] != global_weights_dims[1]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Input 'global_bias' dimension 0 should have same length as dimension 1 of input 'global_weights'");
}
const auto& global_dims = global_shape.GetDims();
if (global_dims.size() == 2) {
if (static_cast<int>(global_dims[0]) != batch_size || static_cast<int>(global_dims[1]) != sequence_length) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Inputs 'global' shall have shape batch_size x sequence_length");
}
} else {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global' is expected to have 2 dimensions, got ",
global_dims.size());
}
return Status::OK();
}
} // namespace contrib
} // namespace onnxruntime
| 5,364 | 1,815 |
/*
** EPITECH PROJECT, 2019
** PauseState.hpp
** File description:
** MenuState header
*/
#ifndef PAUSESTATE_HPP
#define PAUSESTATE_HPP
#include "State.hpp"
class PauseState : public State {
public:
PauseState(std::shared_ptr<GameData> gameData);
~PauseState();
void onStart();
void onStop();
void onPause();
void onResume();
Transition update();
Transition handleEvent(sf::Event &event);
};
#endif /* !PAUSESTATE_HPP */
| 494 | 165 |
/*
*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "source/loader/driver_discovery.h"
#include "source/inc/ze_util.h"
#include <iostream>
#include <sstream>
#include <string>
namespace loader {
static const char *knownDriverNames[] = {
MAKE_LIBRARY_NAME("ze_intel_gpu", "1"),
};
std::vector<DriverLibraryPath> discoverEnabledDrivers() {
std::vector<DriverLibraryPath> enabledDrivers;
const char *altDrivers = nullptr;
// ZE_ENABLE_ALT_DRIVERS is for development/debug only
altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS");
if (altDrivers == nullptr) {
for (auto path : knownDriverNames) {
enabledDrivers.emplace_back(path);
}
} else {
std::stringstream ss(altDrivers);
while (ss.good()) {
std::string substr;
getline(ss, substr, ',');
enabledDrivers.emplace_back(substr);
}
}
return enabledDrivers;
}
} // namespace loader
| 936 | 345 |
#pragma once
#include "Channel.hpp"
#include "TObject.h"
#include <string>
#include <vector>
class Event: public TObject
{
public:
Event()=default;
void addChannel(const Channel& ch);
void clear();
double BoardID{0};
int EventNumber{0};
int Pattern{0};
int ChannelMask{0};
double EventSize{0};
double TriggerTimeTag{0};
double Period_ns{0.0};
std::string Model{""};
std::string FamilyCode{""};
std::vector<Channel> Channels;
ClassDef(Event, 2);
};
| 636 | 188 |
/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 1999-2012 Vaclav Slavik
* Copyright (C) 2005 Olivier Sannier
*
* 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 "cat_sorting.h"
#include <wx/config.h>
/*static*/ SortOrder SortOrder::Default()
{
SortOrder order;
wxString by = wxConfig::Get()->Read(_T("/sort_by"), _T("file-order"));
long untrans = wxConfig::Get()->Read(_T("/sort_untrans_first"), 1L);
if ( by == _T("source") )
order.by = By_Source;
else if ( by == _T("translation") )
order.by = By_Translation;
else
order.by = By_FileOrder;
order.untransFirst = (untrans != 0);
return order;
}
void SortOrder::Save()
{
wxString bystr;
switch ( by )
{
case By_FileOrder:
bystr = _T("file-order");
break;
case By_Source:
bystr = _T("source");
break;
case By_Translation:
bystr = _T("translation");
break;
}
wxConfig::Get()->Write(_T("/sort_by"), bystr);
wxConfig::Get()->Write(_T("/sort_untrans_first"), untransFirst);
}
bool CatalogItemsComparator::operator()(int i, int j) const
{
const CatalogItem& a = Item(i);
const CatalogItem& b = Item(j);
if ( m_order.untransFirst )
{
if ( a.GetValidity() == CatalogItem::Val_Invalid && b.GetValidity() != CatalogItem::Val_Invalid )
return true;
if ( a.GetValidity() != CatalogItem::Val_Invalid && b.GetValidity() == CatalogItem::Val_Invalid )
return false;
if ( !a.IsTranslated() && b.IsTranslated() )
return true;
if ( a.IsTranslated() && !b.IsTranslated() )
return false;
if ( a.IsFuzzy() && !b.IsFuzzy() )
return true;
if ( !a.IsFuzzy() && b.IsFuzzy() )
return false;
}
switch ( m_order.by )
{
case SortOrder::By_FileOrder:
{
return i < j;
}
case SortOrder::By_Source:
{
int r = CompareStrings(a.GetString(), b.GetString());
if ( r != 0 )
return r < 0;
break;
}
case SortOrder::By_Translation:
{
int r = CompareStrings(a.GetTranslation(), b.GetTranslation());
if ( r != 0 )
return r < 0;
break;
}
}
// As last resort, sort by position in file. Note that this means that
// no two items are considered equal w.r.t. sort order; this ensures stable
// ordering.
return i < j;
}
int CatalogItemsComparator::CompareStrings(wxString a, wxString b) const
{
// TODO: * use ICU for correct ordering
// * use natural sort (for numbers)
// * use ICU for correct case insensitivity
a.Replace(_T("&"), _T(""));
a.Replace(_T("_"), _T(""));
b.Replace(_T("&"), _T(""));
b.Replace(_T("_"), _T(""));
return a.CmpNoCase(b);
}
| 4,040 | 1,341 |
/*
Obq_LightSaturationFilter :
Send receive test.
*------------------------------------------------------------------------
Copyright (c) 2012-2015 Marc-Antoine Desjardins, ObliqueFX (marcantoinedesjardins@gmail.com)
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.
Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*------------------------------------------------------------------------
*/
#include "O_Common.h"
//---------------
// Arnold thingy
AI_SHADER_NODE_EXPORT_METHODS(ObqLightSaturationFilterMethod);
//-------------------
// Arnold enum params
enum Obq_LightSaturationFilter_Params {p_mode, p_key, p_triggerValue, p_saturation, p_defaultSaturation};
enum Obq_LightSaturationFilter_Mode {SIMPLE, TRIGGER, ASVALUE};
static const char* Obq_LightSaturationFilter_ModeNames[] =
{
"Simple saturation modifier",
"Use trigger message",
"Use message as saturation",
NULL
};
// shader data struct
//
typedef struct
{
int mode;
const char* key;
float triggerValue;
float saturation;
float defaultSaturation;
}
ShaderData;
//-----------------------
// Arnold node parameters
node_parameters
{
AiParameterENUM("mode", SIMPLE,Obq_LightSaturationFilter_ModeNames);
AiParameterSTR("key", "O1");
AiParameterFLT("triggerValue", 1.0f);
AiParameterFLT("saturation", 0.0f);
AiParameterFLT("defaultSaturation", 1.0f);
}
//------------------
// Arnold initialize
node_initialize
{
ShaderData *data = (ShaderData*) AiMalloc(sizeof(ShaderData));
data->mode = SIMPLE;
data->key = "O1";
data->triggerValue = 1.0f;
data->saturation = 0.0f;
data->defaultSaturation = 1.0f;
AiNodeSetLocalData (node, data);
}
//--------------
// Arnold update
node_update
{
ShaderData *data = (ShaderData*) AiNodeGetLocalData(node);
data->mode = AiNodeGetInt(node,"mode");
data->key = AiNodeGetStr(node,"key");
data->triggerValue = AiNodeGetFlt(node,"triggerValue");
data->saturation = minimax(0.0f,AiNodeGetFlt(node,"saturation"),1.0f);
data->defaultSaturation = minimax(0.0f,AiNodeGetFlt(node,"defaultSaturation"),1.0f);
}
inline void saturateLiu(AtColor& liu, float saturation)
{
float oneMinusSaturation = 1.0f-saturation;
float mixluminance = oneMinusSaturation*(0.2126f*liu.r + 0.7152f*liu.g + 0.0722f*liu.b);
liu.r = mixluminance + saturation*liu.r;
liu.g = mixluminance + saturation*liu.g;
liu.b = mixluminance + saturation*liu.b;
}
//----------------
// Arnold evaluate
shader_evaluate
{
ShaderData *data = (ShaderData*) AiNodeGetLocalData(node);
// Unoccluded intensity
float ret = -1.0f;
if(data->mode == SIMPLE)
{
saturateLiu(sg->Liu,data->saturation);
}
else if(AiStateGetMsgFlt(data->key, &ret)) // a message exists
{
if(data->mode == TRIGGER && ret == data->triggerValue )
saturateLiu(sg->Liu,data->saturation);
else if(data->mode == ASVALUE)
saturateLiu(sg->Liu,minimax(0.0f,ret,1.0f));
else
saturateLiu(sg->Liu,data->defaultSaturation);
}
else
saturateLiu(sg->Liu,data->defaultSaturation);
}
//--------------
// Arnold finish
node_finish
{
ShaderData *data = (ShaderData*) AiNodeGetLocalData(node);
AiFree(data);
}
//node_loader
//{
// if (i > 0)
// return false;
//
// node->methods = ObqLightSaturationFilterMethod;
// node->output_type = AI_TYPE_RGB;
// node->name = "Obq_LightSaturationFilter";
// node->node_type = AI_NODE_SHADER;
//#ifdef _WIN32
// strcpy_s(node->version, AI_VERSION);
//#else
// strcpy(node->version, AI_VERSION);
//#endif
// return true;
//}
| 4,505 | 1,701 |
/* AUTHOR: julianferres */
#include <bits/stdc++.h>
using namespace std;
// neal Debugger
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef LOCAL
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
typedef long long ll;
typedef vector<ll> vi; typedef pair<ll,ll> ii;
typedef vector<ii> vii; typedef vector<bool> vb;
#define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define forr(i, a, b) for(int i = (a); i < (int) (b); i++)
#define forn(i, n) forr(i, 0, n)
#define DBG(x) cerr << #x << " = " << (x) << endl
#define RAYA cerr << "===============================" << endl
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define esta(x,c) ((c).find(x) != (c).end())
const int MOD = 1e9+7; // 998244353
const int MAXN = 2e5+5;
const int GRUNDY_GRANDE = 1000;
vector<vector<int>> grundy(105, vector<int>(105));
int mex(int r, int c){
unordered_set<int> mex_set;
forn(i, r) mex_set.insert(grundy[i][c]);
forn(i, c) mex_set.insert(grundy[r][i]);
forr(i, 1, min(r, c)) //Diagonales
mex_set.insert(grundy[r-i][c-i]);
forn(i, GRUNDY_GRANDE + 1)
if(!esta(i, mex_set)) return i;
}
int main(){
FIN;
forn(i, 104){
grundy[i][0] = grundy[i][i] = grundy[0][i] = GRUNDY_GRANDE;
}
forr(i, 1, 101){
forr(j, 1, 101)
if(i != j) grundy[i][j] = mex(i, j);
}
int n; cin >> n;
int resultado_final = 0;
forn(i, n){
int ri, ci; cin >> ri >> ci;
if(grundy[ri][ci] == GRUNDY_GRANDE){
cout << "Y\n"; // YA directamente gana
return 0;
}
resultado_final ^= grundy[ri][ci]; // Cada ficha juega individualmente
}
cout << (resultado_final ? "Y" : "N") << "\n";
return 0;
}
| 2,354 | 998 |
/*
* Copyright (C) 2011-2020 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "sgx_tprotected_fs.h"
#include "sgx_tprotected_fs_t.h"
#include "protected_fs_file.h"
#include "benchmark_utils.h"
#include <sgx_utils.h>
//#include <sgx_trts.h>
#include <errno.h>
// this function returns 0 only if the specified file existed and it was actually deleted
// before we do that, we try to see if the file contained a monotonic counter, and if it did, we delete it from the system
int32_t protected_fs_file::remove(const char* filename)
{
sgx_status_t status;
int32_t result32 = 0;
/*
void* file = NULL;
int64_t real_file_size = 0;
if (filename == NULL)
return 1;
meta_data_node_t* file_meta_data = NULL;
meta_data_encrypted_t* encrypted_part_plain = NULL;
// if we have a problem in any of the stages, we simply jump to the end and try to remove the file...
do {
status = u_sgxprotectedfs_check_if_file_exists(&result, filename);
if (status != SGX_SUCCESS)
break;
if (result == 0)
{
errno = EINVAL;
return 1; // no such file, or file locked so we can't delete it anyways
}
try {
file_meta_data = new meta_data_node_t;
encrypted_part_plain = new meta_data_encrypted_t;
}
catch (std::bad_alloc e) {
break;
}
status = u_sgxprotectedfs_exclusive_file_open(&file, filename, 1, &real_file_size, &result32);
if (status != SGX_SUCCESS || file == NULL)
break;
if (real_file_size == 0 || real_file_size % NODE_SIZE != 0)
break; // empty file or not an SGX protected FS file
// might be an SGX protected FS file
status = u_sgxprotectedfs_fread_node(&result32, file, 0, (uint8_t*)file_meta_data, NODE_SIZE);
if (status != SGX_SUCCESS || result32 != 0)
break;
if (file_meta_data->plain_part.major_version != SGX_FILE_MAJOR_VERSION)
break;
sgx_aes_gcm_128bit_key_t zero_key_id = {0};
sgx_aes_gcm_128bit_key_t key = {0};
if (consttime_memequal(&file_meta_data->plain_part.key_id, &zero_key_id, sizeof(sgx_aes_gcm_128bit_key_t)) == 1)
break; // shared file - no monotonic counter
sgx_key_request_t key_request = {0};
key_request.key_name = SGX_KEYSELECT_SEAL;
key_request.key_policy = SGX_KEYPOLICY_MRENCLAVE;
memcpy(&key_request.key_id, &file_meta_data->plain_part.key_id, sizeof(sgx_key_id_t));
status = sgx_get_key(&key_request, &key);
if (status != SGX_SUCCESS)
break;
status = benchmark_sgx_rijndael128GCM_decrypt(&key,
file_meta_data->encrypted_part, sizeof(meta_data_encrypted_blob_t),
(uint8_t*)encrypted_part_plain,
file_meta_data->plain_part.meta_data_iv, SGX_AESGCM_IV_SIZE,
NULL, 0,
&file_meta_data->plain_part.meta_data_gmac);
if (status != SGX_SUCCESS)
break;
sgx_mc_uuid_t empty_mc_uuid = {0};
if (consttime_memequal(&empty_mc_uuid, &encrypted_part_plain->mc_uuid, sizeof(sgx_mc_uuid_t)) == 0)
{
status = sgx_destroy_monotonic_counter(&encrypted_part_plain->mc_uuid);
if (status != SGX_SUCCESS)
break;
// monotonic counter was deleted, mission accomplished!!
}
}
while (0);
// cleanup
if (file_meta_data != NULL)
delete file_meta_data;
if (encrypted_part_plain != NULL)
{
// scrub the encrypted part
memset_s(encrypted_part_plain, sizeof(meta_data_encrypted_t), 0, sizeof(meta_data_encrypted_t));
delete encrypted_part_plain;
}
if (file != NULL)
u_sgxprotectedfs_fclose(&result32, file);
*/
// do the actual file removal
status = u_sgxprotectedfs_remove(&result32, filename);
if (status != SGX_SUCCESS)
{
errno = status;
return 1;
}
if (result32 != 0)
{
if (result32 == -1) // no external errno value
errno = EPERM;
else
errno = result32;
return 1;
}
return 0;
}
int64_t protected_fs_file::tell()
{
int64_t result;
sgx_thread_mutex_lock(&mutex);
if (file_status != SGX_FILE_STATUS_OK)
{
errno = EPERM;
last_error = SGX_ERROR_FILE_BAD_STATUS;
sgx_thread_mutex_unlock(&mutex);
return -1;
}
result = offset;
sgx_thread_mutex_unlock(&mutex);
return result;
}
// we don't support sparse files, fseek beyond the current file size will fail
int protected_fs_file::seek(int64_t new_offset, int origin)
{
sgx_thread_mutex_lock(&mutex);
if (file_status != SGX_FILE_STATUS_OK)
{
last_error = SGX_ERROR_FILE_BAD_STATUS;
sgx_thread_mutex_unlock(&mutex);
return -1;
}
//if (open_mode.binary == 0 && origin != SEEK_SET && new_offset != 0)
//{
// last_error = EINVAL;
// sgx_thread_mutex_unlock(&mutex);
// return -1;
//}
int result = -1;
switch (origin)
{
case SEEK_SET:
if (new_offset >= 0 && new_offset <= encrypted_part_plain.size)
{
offset = new_offset;
result = 0;
}
break;
case SEEK_CUR:
if ((offset + new_offset) >= 0 && (offset + new_offset) <= encrypted_part_plain.size)
{
offset += new_offset;
result = 0;
}
break;
case SEEK_END:
if (new_offset <= 0 && new_offset >= (0 - encrypted_part_plain.size))
{
offset = encrypted_part_plain.size + new_offset;
result = 0;
}
break;
default:
break;
}
if (result == 0)
end_of_file = false;
else
last_error = EINVAL;
sgx_thread_mutex_unlock(&mutex);
return result;
}
uint32_t protected_fs_file::get_error()
{
uint32_t result = SGX_SUCCESS;
sgx_thread_mutex_lock(&mutex);
if (last_error != SGX_SUCCESS)
result = last_error;
else if (file_status != SGX_FILE_STATUS_OK)
result = SGX_ERROR_FILE_BAD_STATUS;
sgx_thread_mutex_unlock(&mutex);
return result;
}
bool protected_fs_file::get_eof()
{
return end_of_file;
}
void protected_fs_file::clear_error()
{
sgx_thread_mutex_lock(&mutex);
if (file_status == SGX_FILE_STATUS_NOT_INITIALIZED ||
file_status == SGX_FILE_STATUS_CLOSED ||
file_status == SGX_FILE_STATUS_CRYPTO_ERROR ||
file_status == SGX_FILE_STATUS_CORRUPTED ||
file_status == SGX_FILE_STATUS_MEMORY_CORRUPTED) // can't fix these...
{
sgx_thread_mutex_unlock(&mutex);
return;
}
if (file_status == SGX_FILE_STATUS_FLUSH_ERROR)
{
if (internal_flush(/*false,*/ true) == true)
file_status = SGX_FILE_STATUS_OK;
}
if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED)
{
if (write_all_changes_to_disk(true) == true)
{
need_writing = false;
file_status = SGX_FILE_STATUS_OK;
}
}
/*
if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED_NEED_MC)
{
if (write_all_changes_to_disk(true) == true)
{
need_writing = false;
file_status = SGX_FILE_STATUS_MC_NOT_INCREMENTED; // fall through...next 'if' should take care of this one
}
}
if ((file_status == SGX_FILE_STATUS_MC_NOT_INCREMENTED) &&
(encrypted_part_plain.mc_value <= (UINT_MAX-2)))
{
uint32_t mc_value;
sgx_status_t status = sgx_increment_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value);
if (status == SGX_SUCCESS)
{
assert(mc_value == encrypted_part_plain.mc_value);
file_status = SGX_FILE_STATUS_OK;
}
else
{
last_error = status;
}
}
*/
if (file_status == SGX_FILE_STATUS_OK)
{
last_error = SGX_SUCCESS;
end_of_file = false;
}
sgx_thread_mutex_unlock(&mutex);
}
// clears the cache with all the plain data that was in it
// doesn't clear the meta-data and first node, which are part of the 'main' structure
int32_t protected_fs_file::clear_cache()
{
sgx_thread_mutex_lock(&mutex);
if (file_status != SGX_FILE_STATUS_OK)
{
sgx_thread_mutex_unlock(&mutex);
clear_error(); // attempt to fix the file, will also flush it
sgx_thread_mutex_lock(&mutex);
}
else // file_status == SGX_FILE_STATUS_OK
{
internal_flush(/*false,*/ true);
}
if (file_status != SGX_FILE_STATUS_OK) // clearing the cache might lead to losing un-saved data
{
sgx_thread_mutex_unlock(&mutex);
return 1;
}
while (cache.size() > 0)
{
void* data = cache.get_last();
assert(data != NULL);
assert(((file_data_node_t*)data)->need_writing == false); // need_writing is in the same offset in both node types
// for production -
if (data == NULL || ((file_data_node_t*)data)->need_writing == true)
{
sgx_thread_mutex_unlock(&mutex);
return 1;
}
cache.remove_last();
// before deleting the memory, need to scrub the plain secrets
if (((file_data_node_t*)data)->type == FILE_DATA_NODE_TYPE) // type is in the same offset in both node types
{
file_data_node_t* file_data_node = (file_data_node_t*)data;
memset_s(&file_data_node->plain, sizeof(data_node_t), 0, sizeof(data_node_t));
delete file_data_node;
}
else
{
file_mht_node_t* file_mht_node = (file_mht_node_t*)data;
memset_s(&file_mht_node->plain, sizeof(mht_node_t), 0, sizeof(mht_node_t));
delete file_mht_node;
}
}
sgx_thread_mutex_unlock(&mutex);
return 0;
}
| 10,192 | 4,366 |
#include "generator/osm_source.hpp"
#include "generator/intermediate_data.hpp"
#include "generator/intermediate_elements.hpp"
#include "generator/osm_element.hpp"
#include "generator/towns_dumper.hpp"
#include "generator/translator_factory.hpp"
#include "platform/platform.hpp"
#include "geometry/mercator.hpp"
#include "geometry/tree4d.hpp"
#include "base/assert.hpp"
#include "base/stl_helpers.hpp"
#include "base/file_name_utils.hpp"
#include <fstream>
#include <memory>
#include <set>
#include "defines.hpp"
using namespace std;
namespace generator
{
// SourceReader ------------------------------------------------------------------------------------
SourceReader::SourceReader() : m_file(unique_ptr<istream, Deleter>(&cin, Deleter(false)))
{
LOG_SHORT(LINFO, ("Reading OSM data from stdin"));
}
SourceReader::SourceReader(string const & filename)
: m_file(unique_ptr<istream, Deleter>(new ifstream(filename), Deleter()))
{
CHECK(static_cast<ifstream *>(m_file.get())->is_open(), ("Can't open file:", filename));
LOG_SHORT(LINFO, ("Reading OSM data from", filename));
}
SourceReader::SourceReader(istringstream & stream)
: m_file(unique_ptr<istream, Deleter>(&stream, Deleter(false)))
{
LOG_SHORT(LINFO, ("Reading OSM data from memory"));
}
uint64_t SourceReader::Read(char * buffer, uint64_t bufferSize)
{
m_file->read(buffer, bufferSize);
return m_file->gcount();
}
// Functions ---------------------------------------------------------------------------------------
void AddElementToCache(cache::IntermediateDataWriter & cache, OsmElement & element)
{
switch (element.m_type)
{
case OsmElement::EntityType::Node:
{
auto const pt = mercator::FromLatLon(element.m_lat, element.m_lon);
cache.AddNode(element.m_id, pt.y, pt.x);
break;
}
case OsmElement::EntityType::Way:
{
// Store way.
WayElement way(element.m_id);
for (uint64_t nd : element.Nodes())
way.m_nodes.push_back(nd);
if (way.IsValid())
cache.AddWay(element.m_id, way);
break;
}
case OsmElement::EntityType::Relation:
{
// store relation
RelationElement relation;
for (auto const & member : element.Members())
{
switch (member.m_type) {
case OsmElement::EntityType::Node:
relation.m_nodes.emplace_back(member.m_ref, string(member.m_role));
break;
case OsmElement::EntityType::Way:
relation.m_ways.emplace_back(member.m_ref, string(member.m_role));
break;
case OsmElement::EntityType::Relation:
relation.m_relations.emplace_back(member.m_ref, string(member.m_role));
break;
default:
break;
}
}
for (auto const & tag : element.Tags())
relation.m_tags.emplace(tag.m_key, tag.m_value);
if (relation.IsValid())
cache.AddRelation(element.m_id, relation);
break;
}
default:
break;
}
}
void BuildIntermediateDataFromXML(SourceReader & stream, cache::IntermediateDataWriter & cache,
TownsDumper & towns)
{
ProcessorOsmElementsFromXml processorOsmElementsFromXml(stream);
OsmElement element;
while (processorOsmElementsFromXml.TryRead(element))
{
towns.CheckElement(element);
AddElementToCache(cache, element);
}
}
void ProcessOsmElementsFromXML(SourceReader & stream, function<void(OsmElement *)> processor)
{
ProcessorOsmElementsFromXml processorOsmElementsFromXml(stream);
OsmElement element;
while (processorOsmElementsFromXml.TryRead(element))
processor(&element);
}
void BuildIntermediateDataFromO5M(SourceReader & stream, cache::IntermediateDataWriter & cache,
TownsDumper & towns)
{
auto processor = [&](OsmElement * element) {
towns.CheckElement(*element);
AddElementToCache(cache, *element);
};
// Use only this function here, look into ProcessOsmElementsFromO5M
// for more details.
ProcessOsmElementsFromO5M(stream, processor);
}
void ProcessOsmElementsFromO5M(SourceReader & stream, function<void(OsmElement *)> processor)
{
ProcessorOsmElementsFromO5M processorOsmElementsFromO5M(stream);
OsmElement element;
while (processorOsmElementsFromO5M.TryRead(element))
processor(&element);
}
ProcessorOsmElementsFromO5M::ProcessorOsmElementsFromO5M(SourceReader & stream)
: m_stream(stream)
, m_dataset([&](uint8_t * buffer, size_t size) {
return m_stream.Read(reinterpret_cast<char *>(buffer), size);
})
, m_pos(m_dataset.begin())
{
}
bool ProcessorOsmElementsFromO5M::TryRead(OsmElement & element)
{
if (m_pos == m_dataset.end())
return false;
using Type = osm::O5MSource::EntityType;
auto const translate = [](Type t) -> OsmElement::EntityType {
switch (t)
{
case Type::Node: return OsmElement::EntityType::Node;
case Type::Way: return OsmElement::EntityType::Way;
case Type::Relation: return OsmElement::EntityType::Relation;
default: return OsmElement::EntityType::Unknown;
}
};
element = {};
// Be careful, we could call Nodes(), Members(), Tags() from O5MSource::Entity
// only once (!). Because these functions read data from file simultaneously with
// iterating in loop. Furthermore, into Tags() method calls Nodes.Skip() and Members.Skip(),
// thus first call of Nodes (Members) after Tags() will not return any results.
// So don not reorder the "for" loops (!).
auto const entity = *m_pos;
element.m_id = entity.id;
switch (entity.type)
{
case Type::Node:
{
element.m_type = OsmElement::EntityType::Node;
element.m_lat = entity.lat;
element.m_lon = entity.lon;
break;
}
case Type::Way:
{
element.m_type = OsmElement::EntityType::Way;
for (uint64_t nd : entity.Nodes())
element.AddNd(nd);
break;
}
case Type::Relation:
{
element.m_type = OsmElement::EntityType::Relation;
for (auto const & member : entity.Members())
element.AddMember(member.ref, translate(member.type), member.role);
break;
}
default: break;
}
for (auto const & tag : entity.Tags())
element.AddTag(tag.key, tag.value);
++m_pos;
return true;
}
ProcessorOsmElementsFromXml::ProcessorOsmElementsFromXml(SourceReader & stream)
: m_xmlSource([&, this](auto * element) { m_queue.emplace(*element); })
, m_parser(stream, m_xmlSource)
{
}
bool ProcessorOsmElementsFromXml::TryReadFromQueue(OsmElement & element)
{
if (m_queue.empty())
return false;
element = m_queue.front();
m_queue.pop();
return true;
}
bool ProcessorOsmElementsFromXml::TryRead(OsmElement & element)
{
do {
if (TryReadFromQueue(element))
return true;
} while (m_parser.Read());
return TryReadFromQueue(element);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Generate functions implementations.
///////////////////////////////////////////////////////////////////////////////////////////////////
bool GenerateIntermediateData(feature::GenerateInfo & info)
{
auto nodes =
cache::CreatePointStorageWriter(info.m_nodeStorageType, info.GetCacheFileName(NODES_FILE));
cache::IntermediateDataWriter cache(*nodes, info);
TownsDumper towns;
SourceReader reader = info.m_osmFileName.empty() ? SourceReader() : SourceReader(info.m_osmFileName);
LOG(LINFO, ("Data source:", info.m_osmFileName));
switch (info.m_osmFileType)
{
case feature::GenerateInfo::OsmSourceType::XML:
BuildIntermediateDataFromXML(reader, cache, towns);
break;
case feature::GenerateInfo::OsmSourceType::O5M:
BuildIntermediateDataFromO5M(reader, cache, towns);
break;
}
cache.SaveIndex();
towns.Dump(info.GetIntermediateFileName(TOWNS_FILE));
LOG(LINFO, ("Added points count =", nodes->GetNumProcessedPoints()));
return true;
}
} // namespace generator
| 7,805 | 2,531 |
#include "../menu.hpp"
void Menu::drawRageTab() {
ImGui::Text("Rage");
} | 77 | 32 |
//
// Copyright (C) OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/common/ModuleAccess.h"
#include "inet/common/OSGUtils.h"
#include "inet/visualizer/transportlayer/TransportConnectionOsgVisualizer.h"
namespace inet {
namespace visualizer {
Define_Module(TransportConnectionOsgVisualizer);
#ifdef WITH_OSG
TransportConnectionOsgVisualizer::TransportConnectionOsgVisualization::TransportConnectionOsgVisualization(osg::Node *sourceNode, osg::Node *destinationNode, int sourceModuleId, int destinationModuleId, int count) :
TransportConnectionVisualization(sourceModuleId, destinationModuleId, count),
sourceNode(sourceNode),
destinationNode(destinationNode)
{
}
void TransportConnectionOsgVisualizer::initialize(int stage)
{
TransportConnectionVisualizerBase::initialize(stage);
if (!hasGUI()) return;
if (stage == INITSTAGE_LOCAL) {
networkNodeVisualizer = getModuleFromPar<NetworkNodeOsgVisualizer>(par("networkNodeVisualizerModule"), this);
}
}
osg::Node *TransportConnectionOsgVisualizer::createConnectionEndNode(tcp::TCPConnection *tcpConnection) const
{
auto path = resolveResourcePath((std::string(icon) + ".png").c_str());
auto image = inet::osg::createImage(path.c_str());
auto texture = new osg::Texture2D();
texture->setImage(image);
auto geometry = osg::createTexturedQuadGeometry(osg::Vec3(-image->s() / 2, 0.0, 0.0), osg::Vec3(image->s(), 0.0, 0.0), osg::Vec3(0.0, image->t(), 0.0), 0.0, 0.0, 1.0, 1.0);
auto stateSet = geometry->getOrCreateStateSet();
stateSet->setTextureAttributeAndModes(0, texture);
stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
auto color = iconColorSet.getColor(connectionVisualizations.size());
auto colorArray = new osg::Vec4Array();
colorArray->push_back(osg::Vec4((double)color.red / 255.0, (double)color.green / 255.0, (double)color.blue / 255.0, 1));
geometry->setColorArray(colorArray, osg::Array::BIND_OVERALL);
auto geode = new osg::Geode();
geode->addDrawable(geometry);
return geode;
}
const TransportConnectionVisualizerBase::TransportConnectionVisualization *TransportConnectionOsgVisualizer::createConnectionVisualization(cModule *source, cModule *destination, tcp::TCPConnection *tcpConnection) const
{
auto sourceNode = createConnectionEndNode(tcpConnection);
auto destinationNode = createConnectionEndNode(tcpConnection);
return new TransportConnectionOsgVisualization(sourceNode, destinationNode, source->getId(), destination->getId(), 1);
}
void TransportConnectionOsgVisualizer::addConnectionVisualization(const TransportConnectionVisualization *connectionVisualization)
{
TransportConnectionVisualizerBase::addConnectionVisualization(connectionVisualization);
auto connectionOsgVisualization = static_cast<const TransportConnectionOsgVisualization *>(connectionVisualization);
auto sourceModule = getSimulation()->getModule(connectionVisualization->sourceModuleId);
auto sourceVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(sourceModule));
sourceVisualization->addAnnotation(connectionOsgVisualization->sourceNode, osg::Vec3d(0, 0, 32), 0); // TODO: size
auto destinationModule = getSimulation()->getModule(connectionVisualization->destinationModuleId);
auto destinationVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(destinationModule));
destinationVisualization->addAnnotation(connectionOsgVisualization->destinationNode, osg::Vec3d(0, 0, 32), 0); // TODO: size
}
void TransportConnectionOsgVisualizer::removeConnectionVisualization(const TransportConnectionVisualization *connectionVisualization)
{
TransportConnectionVisualizerBase::removeConnectionVisualization(connectionVisualization);
auto connectionOsgVisualization = static_cast<const TransportConnectionOsgVisualization *>(connectionVisualization);
auto sourceModule = getSimulation()->getModule(connectionVisualization->sourceModuleId);
auto sourceVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(sourceModule));
sourceVisualization->removeAnnotation(connectionOsgVisualization->sourceNode);
auto destinationModule = getSimulation()->getModule(connectionVisualization->destinationModuleId);
auto destinationVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(destinationModule));
destinationVisualization->removeAnnotation(connectionOsgVisualization->destinationNode);
}
#endif // ifdef WITH_OSG
} // namespace visualizer
} // namespace inet
| 5,442 | 1,513 |
/* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright © 2019 Fragcolor Pte. Ltd. */
#pragma once
#include "foundation.hpp"
#include "imgui.h"
#include "ImGuizmo.h"
namespace ImGuiExtra {
#include "imgui_memory_editor.h"
};
namespace chainblocks {
namespace ImGui {
constexpr uint32_t ImGuiContextCC = 'gui ';
struct Context {
static inline Type Info{
{CBType::Object,
{.object = {.vendorId = CoreCC, .typeId = ImGuiContextCC}}}};
// Useful to compare with with plugins, they might mismatch!
static inline const char *Version = ::ImGui::GetVersion();
// ImGuiContext *context = ::ImGui::CreateContext();
// ~Context() { ::ImGui::DestroyContext(context); }
// void Set() { ::ImGui::SetCurrentContext(context); }
// void Reset() {
// ::ImGui::DestroyContext(context);
// context = ::ImGui::CreateContext();
// }
};
struct Enums {
#define REGISTER_FLAGS_EX(_NAME_, _CC_) \
REGISTER_FLAGS(_NAME_, _CC_); \
static inline Type _NAME_##SeqType = Type::SeqOf(_NAME_##Type); \
static inline Type _NAME_##VarType = Type::VariableOf(_NAME_##Type); \
static inline Type _NAME_##VarSeqType = Type::VariableOf(_NAME_##SeqType)
enum class GuiButton {
Normal,
Small,
Invisible,
ArrowLeft,
ArrowRight,
ArrowUp,
ArrowDown
};
REGISTER_ENUM(GuiButton, 'guiB'); // FourCC = 0x67756942
enum class GuiTableFlags {
None = ::ImGuiTableFlags_None,
Resizable = ::ImGuiTableFlags_Resizable,
Reorderable = ::ImGuiTableFlags_Reorderable,
Hideable = ::ImGuiTableFlags_Hideable,
Sortable = ::ImGuiTableFlags_Sortable
};
REGISTER_FLAGS_EX(GuiTableFlags, 'guiT'); // FourCC = 0x67756954
enum class GuiTableColumnFlags {
None = ::ImGuiTableColumnFlags_None,
Disabled = ::ImGuiTableColumnFlags_Disabled,
DefaultHide = ::ImGuiTableColumnFlags_DefaultHide,
DefaultSort = ::ImGuiTableColumnFlags_DefaultSort
};
REGISTER_FLAGS_EX(GuiTableColumnFlags, 'guTC'); // FourCC = 0x67755443
enum class GuiTreeNodeFlags {
None = ::ImGuiTreeNodeFlags_None,
Selected = ::ImGuiTreeNodeFlags_Selected,
Framed = ::ImGuiTreeNodeFlags_Framed,
OpenOnDoubleClick = ::ImGuiTreeNodeFlags_OpenOnDoubleClick,
OpenOnArrow = ::ImGuiTreeNodeFlags_OpenOnArrow,
Leaf = ::ImGuiTreeNodeFlags_Leaf,
Bullet = ::ImGuiTreeNodeFlags_Bullet,
SpanAvailWidth = ::ImGuiTreeNodeFlags_SpanAvailWidth,
SpanFullWidth = ::ImGuiTreeNodeFlags_SpanFullWidth
};
REGISTER_FLAGS_EX(GuiTreeNodeFlags, 'guTN'); // FourCC = 0x6775544E
enum class GuiWindowFlags {
None = ::ImGuiWindowFlags_None,
NoTitleBar = ::ImGuiWindowFlags_NoTitleBar,
NoResize = ::ImGuiWindowFlags_NoResize,
NoMove = ::ImGuiWindowFlags_NoMove,
NoScrollbar = ::ImGuiWindowFlags_NoScrollbar,
NoScrollWithMouse = ::ImGuiWindowFlags_NoScrollWithMouse,
NoCollapse = ::ImGuiWindowFlags_NoCollapse,
AlwaysAutoResize = ::ImGuiWindowFlags_AlwaysAutoResize,
NoBackground = ::ImGuiWindowFlags_NoBackground,
NoSavedSettings = ::ImGuiWindowFlags_NoSavedSettings,
NoMouseInputs = ::ImGuiWindowFlags_NoMouseInputs,
MenuBar = ::ImGuiWindowFlags_MenuBar,
HorizontalScrollbar = ::ImGuiWindowFlags_HorizontalScrollbar,
NoFocusOnAppearing = ::ImGuiWindowFlags_NoFocusOnAppearing,
NoBringToFrontOnFocus = ::ImGuiWindowFlags_NoBringToFrontOnFocus,
AlwaysVerticalScrollbar = ::ImGuiWindowFlags_AlwaysVerticalScrollbar,
AlwaysHorizontalScrollbar = ::ImGuiWindowFlags_AlwaysHorizontalScrollbar,
AlwaysUseWindowPadding = ::ImGuiWindowFlags_AlwaysUseWindowPadding,
NoNavInputs = ::ImGuiWindowFlags_NoNavInputs,
NoNavFocus = ::ImGuiWindowFlags_NoNavFocus
};
REGISTER_FLAGS_EX(GuiWindowFlags, 'guiW'); // FourCC = 0x67756957
};
}; // namespace ImGui
}; // namespace chainblocks
| 3,909 | 1,336 |
#include <bits/stdc++.h>
#define False 'N'
#define True 'S'
using namespace std;
char memo[100002][1002];
void resetar_memo(int n, int m) {
for(int i=0;i<=n;i++) {
for(int j=0;j<=m;j++) {
memo[i][j] = 'F';
}
}
}
char coins(int v, int m, vector<int> moedas) {
int troco;
char ans, add, nadd;
if(memo[v][m] == 'F') {
if(m == 0 and v != 0) {
ans = False;
} else if(v == 0) {
ans = True;
} else if(v < 0) {
ans = False;
} else {
troco = v-moedas[m-1];
if(troco == 0) {
ans = True;
} else {
if(troco >= 0) {
add = coins(troco, m-1, moedas);
} else
add = False;
nadd = (add == True ? True : coins(v, m-1, moedas));
ans = (add == True ? add : nadd);
}
}
memo[v][m] = ans;
}
return memo[v][m];
}
int main() {
int v, m, in;
vector<int> moedas;
cin >> v >> m;
for(int i=0;i<m;i++) {
scanf("%d", &in);
moedas.push_back(in);
}
sort(moedas.begin(), moedas.begin()+m);
vector<int>::iterator lb;
lb = lower_bound(moedas.begin(), moedas.end(), v);
if(moedas[lb - moedas.begin()] == v) {
cout << True << "\n";
} else {
resetar_memo(v+1, m+1);
cout << coins(v, lb-moedas.begin()+1, moedas) << "\n";
}
return 0;
} | 1,198 | 652 |
#include "Piece.hpp"
#include "server/board/Board.hpp"
#include <algorithm>
#include <iostream>
namespace chesspp { namespace server
{
namespace piece
{
Piece::Piece(board::Board &b, Position_t const &pos_, Suit_t const &s_, Class_t const &pc)
: board(b) //can't use {}
, p{pos_}
, s{s_}
, c{pc}
{
std::clog << "Creation of " << *this << std::endl;
}
void Piece::addTrajectory(Position_t const &tile)
{
board.pieceTrajectories().add(*this, tile);
}
void Piece::removeTrajectory(Position_t const &tile)
{
board.pieceTrajectories().remove(*this, tile);
}
void Piece::addCapturing(Position_t const &tile)
{
board.pieceCapturings().add(*this, tile);
}
void Piece::removeCapturing(Position_t const &tile)
{
board.pieceCapturings().remove(*this, tile);
}
void Piece::addCapturable(Position_t const &tile)
{
board.pieceCapturables().add(*this, tile);
}
void Piece::removeCapturable(Position_t const &tile)
{
board.pieceCapturables().remove(*this, tile);
}
std::ostream &operator<<(std::ostream &os, Piece const &p)
{
return os << "Piece (" << typeid(p).name() << ") \"" << p.suit << "\" \"" << p.pclass << "\" at " << p.pos << " having made " << p.moves << " moves";
}
}
}}
| 1,506 | 491 |
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct Node* node, vector<int>& v)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left,v);
/* then print the data of node */
v.push_back(node->data);
/* now recur on right child */
printInorder(node->right,v);
}
/* Given a binary tree, print its nodes in preorder*/
/* Driver program to test above functions*/
int main()
{
struct Node* root = new Node(2);
root->left = new Node(1);
root->right = new Node(3);
vector<int> v;
printInorder(root,v);
int t=0;
for(int i=0;i<v.size()-1;i++)
{
if(v[i]>v[i+1])
{
t=1;
break;
}
}
if(t==0)
{
cout<<"It is a bst";
}
else
{
cout<<"It is not a bst";
}
return 0;
}
| 1,153 | 443 |
#include <bits/stdc++.h>
using namespace std;
/*
Given an array of elements, return the length of the longest
subarray where all its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1],
return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1].
*/
int longestSubarrayDistinct(int arr[], int n){
int start = 0, max_len = 0;
unordered_map<int, int> seen;
for(int i=0; i<n; i++){
if(seen.find(arr[i]) != seen.end()){
int last_seen = seen[arr[i]];
if(last_seen >= start){
int length = start - i;
max_len = max(max_len, length);
start = last_seen + 1;
}
}
else{
seen[arr[i]] = i;
}
}
return max_len;
}
// main function
int main(){
int arr[] = {5, 1, 3, 5, 2, 3, 4, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << longestSubarrayDistinct(arr, n) << "\n";
return 0;
} | 849 | 381 |
/**
* @file np2arg.cpp
* @brief 引数情報クラスの動作の定義を行います
*/
#include "compiler.h"
#include "np2arg.h"
#include "dosio.h"
#define MAXARG 32 //!< 最大引数エントリ数
#define ARG_BASE 1 //!< win32 の lpszCmdLine の場合の開始エントリ
//! 唯一のインスタンスです
Np2Arg Np2Arg::sm_instance;
/**
* コンストラクタ
*/
Np2Arg::Np2Arg()
{
ZeroMemory(this, sizeof(*this));
}
/**
* デストラクタ
*/
Np2Arg::~Np2Arg()
{
free(m_lpArg);
if(m_lpIniFile) free((TCHAR*)m_lpIniFile); // np21w ver0.86 rev8
}
/**
* パース
*/
void Np2Arg::Parse()
{
// 引数読み出し
free(m_lpArg);
m_lpArg = _tcsdup(::GetCommandLine());
LPTSTR argv[MAXARG];
const int argc = ::milstr_getarg(m_lpArg, argv, _countof(argv));
int nDrive = 0;
for (int i = ARG_BASE; i < argc; i++)
{
LPCTSTR lpArg = argv[i];
if ((lpArg[0] == TEXT('/')) || (lpArg[0] == TEXT('-')))
{
switch (_totlower(lpArg[1]))
{
case 'f':
m_fFullscreen = true;
break;
case 'i':
m_lpIniFile = &lpArg[2];
break;
}
}
else
{
LPCTSTR lpExt = ::file_getext(lpArg);
if (::file_cmpname(lpExt, TEXT("ini")) == 0 || ::file_cmpname(lpExt, TEXT("npc")) == 0 || ::file_cmpname(lpExt, TEXT("npcfg")) == 0 || ::file_cmpname(lpExt, TEXT("np2cfg")) == 0 || ::file_cmpname(lpExt, TEXT("np21cfg")) == 0 || ::file_cmpname(lpExt, TEXT("np21wcfg")) == 0)
{
m_lpIniFile = lpArg;
}
else if (nDrive < _countof(m_lpDisk))
{
m_lpDisk[nDrive++] = lpArg;
}
}
}
if(m_lpIniFile){ // np21w ver0.86 rev8
LPTSTR strbuf;
strbuf = (LPTSTR)calloc(500, sizeof(TCHAR));
if(!(_tcsstr(m_lpIniFile,_T(":"))!=NULL || (m_lpIniFile[0]=='\\'))){
// ファイル名のみの指定っぽかったら現在のディレクトリを結合
//getcwd(pathname, 300);
GetCurrentDirectory(500, strbuf);
if(strbuf[_tcslen(strbuf)-1]!='\\'){
_tcscat(strbuf, _T("\\")); // XXX: Linuxとかだったらスラッシュじゃないと駄目だよね?
}
}
_tcscat(strbuf, m_lpIniFile);
m_lpIniFile = strbuf;
}
}
/**
* ディスク情報をクリア
*/
void Np2Arg::ClearDisk()
{
ZeroMemory(m_lpDisk, sizeof(m_lpDisk));
}
| 2,056 | 1,181 |
#pragma once
#include "../Input/KeyStates.hpp"
#include "../WindowEvent/EventStates.hpp"
namespace teaGameLib {
input::KeyStates GetKeyStates();
windowEvent::EventStates GetEventStates();
} | 192 | 65 |
#include <string>
#include <vector>
/* Model data */
static const struct CatboostModel {
unsigned int FloatFeatureCount = 50;
unsigned int BinaryFeatureCount = 12;
unsigned int TreeCount = 2;
unsigned int TreeDepth[2] = {6, 6};
unsigned int TreeSplits[12] = {7, 5, 0, 4, 9, 3, 11, 6, 1, 10, 2, 8};
unsigned int BorderCounts[50] = {1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0};
float Borders[12] = {0.168183506f, 0.136649996f, 0.5f, 0.645990014f, 0.272549003f, 0.5f, 0.5f, 0.00311657996f, 0.392024517f, 0.163893014f, 0.387494028f, 0.767975509f, };
/* Aggregated array of leaf values for trees. Each tree is represented by a separate line: */
double LeafValues[128] = {
0, 0, 0.001049999981001019, 0, 0.0006999999873340129, 0.0004199999924004077, 0, 0.0003499999936670065, 0.0006999999873340129, 0, 0, 0, 0.0008999999837151595, 0.0008399999848008155, 0, 0.005499108720590722, 0, 0, 0.001310204828003209, 0, 0, 0, 0.002099799992893635, 0.003281666943095616, 0, 0, 0.001081739094670376, 0, 0, 0, 0.001261285375551461, 0.003276219466932844, 0.0001235294095295317, 0, 0.001143749976810068, 0, 0, 0, 0.002145652130229966, 0.001699999969239746, 0.0005409089896827957, 0, 0.0004052632035001316, 0, 0.001076041724695822, 0, 0.001088611397153381, 0.001412068939966888, 0, 0, 0.001978133278083802, 0.001049999981001019, 0, 0, 0.002257627220401316, 0.002847457878670443, 0, 0, 0.002380742281139534, 0, 0, 0, 0.00181075114546265, 0.003175870739941051,
0.0008166451595296908, 0, 0.001435124236388357, 0, 0.002230458559199401, 0, 0.002666874626702434, 0, 0.001534999525103938, 0.001002557986130936, 0.001371602072510968, 0.001025428335548242, 0.002692151343928724, 0.002324272621936243, 0.001188379847259753, 0.002102531171547649, 0.0002273645927514973, 0, 0.002259198170953273, 0, 0.0005932082092034878, 0, 0.001936697595469175, 0, 0.002274218690520189, 0.00329724810179383, 0.003553552019915716, -2.457164545277724e-05, 0.001361408072189387, 0.002058595183732444, 0.002040357509679229, 0.006411161288685438, 0.001238019183794491, 0, 0.0007759661277461006, 0, 0.002378015135461136, 0, 0.0005649959300306291, 0, 0.001080913918043391, 0.005514189264833609, 0.001790046575156435, 0.001103960055365507, 0.002146005492857177, 0.002352553092417847, 0.001165392567571486, 0, 0.0003389142165572722, 0, 0.000740077287450055, 0, 0.0006711111753359577, 0, 0.001173741518772528, 0, 0.0008677387848554152, 0.003458858412712405, 0.001394273280892068, 0.002416533521423629, 0.003145683167659726, 0.002795911932059462, 0.001047576512888525, 0.003163031305315038
};
} CatboostModelStatic;
/* Model applicator */
double ApplyCatboostModel(
const std::vector<float>& features
) {
const struct CatboostModel& model = CatboostModelStatic;
/* Binarise features */
std::vector<unsigned char> binaryFeatures(model.BinaryFeatureCount);
unsigned int binFeatureIndex = 0;
for (unsigned int i = 0; i < model.FloatFeatureCount; ++i) {
for(unsigned int j = 0; j < model.BorderCounts[i]; ++j) {
binaryFeatures[binFeatureIndex] = (unsigned char)(features[i] > model.Borders[binFeatureIndex]);
++binFeatureIndex;
}
}
/* Extract and sum values from trees */
double result = 0.0;
const unsigned int* treeSplitsPtr = model.TreeSplits;
const double* leafValuesForCurrentTreePtr = model.LeafValues;
for (unsigned int treeId = 0; treeId < model.TreeCount; ++treeId) {
const unsigned int currentTreeDepth = model.TreeDepth[treeId];
unsigned int index = 0;
for (unsigned int depth = 0; depth < currentTreeDepth; ++depth) {
index |= (binaryFeatures[treeSplitsPtr[depth]] << depth);
}
result += leafValuesForCurrentTreePtr[index];
treeSplitsPtr += currentTreeDepth;
leafValuesForCurrentTreePtr += (1 << currentTreeDepth);
}
return result;
}
double ApplyCatboostModel(
const std::vector<float>& floatFeatures,
const std::vector<std::string>&
) {
return ApplyCatboostModel(floatFeatures);
}
| 4,174 | 2,793 |
#include "CfgPatches.hpp"
#include "..\CfgAreaCategories.inc"
class MAP_METADATA_ROOTCLASS
{
class Altis
{
class Fotia
{
#include "Fotia.hpp"
};
class KavalaPier
{
#include "KavalaPier.hpp"
};
class Kastro
{
#include "Kastro.hpp"
};
class Kavala
{
#include "Kavala.hpp"
};
class Athanos
{
#include "Athanos.hpp"
};
class Aggelochori
{
#include "Aggelochori.hpp"
};
class AgiosKonstantinos
{
#include "AgiosKonstantinos.hpp"
};
class Neri
{
#include "Neri.hpp"
};
class PowerPlant02
{
#include "PowerPlant02.hpp"
};
class quarry01
{
#include "quarry01.hpp"
};
class Oreokastro
{
#include "Oreokastro.hpp"
};
class Negades
{
#include "Negades.hpp"
};
class castle
{
#include "castle.hpp"
};
class Panochori
{
#include "Panochori.hpp"
};
class factory04
{
#include "factory04.hpp"
};
class Stadium
{
#include "Stadium.hpp"
};
class Gori
{
#include "Gori.hpp"
};
class factory03
{
#include "factory03.hpp"
};
class Faros
{
#include "Faros.hpp"
};
class Kore
{
#include "Kore.hpp"
};
class Edessa
{
#include "Edessa.hpp"
};
class Topolia
{
#include "Topolia.hpp"
};
class Aristi
{
#include "Aristi.hpp"
};
class Syrta
{
#include "Syrta.hpp"
};
class AgiosKosmas
{
#include "AgiosKosmas.hpp"
};
class Zaros
{
#include "Zaros.hpp"
};
class XirolimniDam
{
#include "XirolimniDam.hpp"
};
class AgiosDionysios
{
#include "AgiosDionysios.hpp"
};
class Abdera
{
#include "Abdera.hpp"
};
class KryaNera
{
#include "KryaNera.hpp"
};
class Galati
{
#include "Galati.hpp"
};
class Orino
{
#include "Orino.hpp"
};
class Therisa
{
#include "Therisa.hpp"
};
class Drimea
{
#include "Drimea.hpp"
};
class Poliakko
{
#include "Poliakko.hpp"
};
class Alikampos
{
#include "Alikampos.hpp"
};
class AACairfield
{
#include "AACairfield.hpp"
};
class Eginio
{
#include "Eginio.hpp"
};
class Vikos
{
#include "Vikos.hpp"
};
class Katalaki
{
#include "Katalaki.hpp"
};
class Lakka
{
#include "Lakka.hpp"
};
class Neochori
{
#include "Neochori.hpp"
};
class factory02
{
#include "factory02.hpp"
};
class Ifestiona
{
#include "Ifestiona.hpp"
};
class Stavros
{
#include "Stavros.hpp"
};
class Athira
{
#include "Athira.hpp"
};
class airbase01
{
#include "airbase01.hpp"
};
class Gravia
{
#include "Gravia.hpp"
};
class terminal01
{
#include "terminal01.hpp"
};
class Frini
{
#include "Frini.hpp"
};
class Faronaki
{
#include "Faronaki.hpp"
};
class military02
{
#include "military02.hpp"
};
class PowerPlant01
{
#include "PowerPlant01.hpp"
};
class military03
{
#include "military03.hpp"
};
class Telos
{
#include "Telos.hpp"
};
class Anthrakia
{
#include "Anthrakia.hpp"
};
class ChelonisiIsland
{
#include "ChelonisiIsland.hpp"
};
class AgiaTriada
{
#include "AgiaTriada.hpp"
};
class Pyrgos
{
#include "Pyrgos.hpp"
};
class Nychi
{
#include "Nychi.hpp"
};
class quarry02
{
#include "quarry02.hpp"
};
class Kalithea
{
#include "Kalithea.hpp"
};
class Charkia
{
#include "Charkia.hpp"
};
class storage01
{
#include "storage01.hpp"
};
class Livadi
{
#include "Livadi.hpp"
};
class Mine01
{
#include "Mine01.hpp"
};
class Rodopoli
{
#include "Rodopoli.hpp"
};
class Dorida
{
#include "Dorida.hpp"
};
class AgiosPetros
{
#include "AgiosPetros.hpp"
};
class Nifi
{
#include "Nifi.hpp"
};
class quarry03
{
#include "quarry03.hpp"
};
class Chalkeia
{
#include "Chalkeia.hpp"
};
class Panagia
{
#include "Panagia.hpp"
};
class Selakano
{
#include "Selakano.hpp"
};
class Paros
{
#include "Paros.hpp"
};
class SufrClub
{
#include "SufrClub.hpp"
};
class Kalochori
{
#include "Kalochori.hpp"
};
class Aktinarki
{
#include "Aktinarki.hpp"
};
class Iraklia
{
#include "Iraklia.hpp"
};
class Feres
{
#include "Feres.hpp"
};
class Trachia
{
#include "Trachia.hpp"
};
class AgiaPelagia
{
#include "AgiaPelagia.hpp"
};
class CapKategidis
{
#include "CapKategidis.hpp"
};
class Ioannina
{
#include "Ioannina.hpp"
};
class Sideras
{
#include "Sideras.hpp"
};
class Nidasos
{
#include "Nidasos.hpp"
};
class Delfinaki
{
#include "Delfinaki.hpp"
};
class CapThelos
{
#include "CapThelos.hpp"
};
class Sofia
{
#include "Sofia.hpp"
};
class Limnichori
{
#include "Limnichori.hpp"
};
class Gatolia
{
#include "Gatolia.hpp"
};
class MolosAirfield
{
#include "MolosAirfield.hpp"
};
class Molos
{
#include "Molos.hpp"
};
class Polemistia
{
#include "Polemistia.hpp"
};
class CapStrigla
{
#include "CapStrigla.hpp"
};
};
};
| 5,127 | 2,795 |
#include "cpp_header.h"
class Solution
{
struct customGreater1 {
bool operator()(const string & a, const string & b) const
{
return a.length() > b.length();
}
} ;
struct {
bool operator()(const string & a, const string & b) const
{
return a.length() > b.length();
}
} customGreater2;
public:
int findLUSlength(vector<string> strs)
{
int res = -1;
if(strs.size() > 0)
{
sort(strs.begin(), strs.end(), customGreater2); // nlgn
unordered_map<string, int> str_count;
for(auto & s : strs)
{
str_count[s]++;
}
auto last = unique(strs.begin(), strs.end()); // n
strs.erase(last, strs.end());
/*
cout << "--------------------------\n";
for(auto x : str_count)
{
cout << x.first << ", " << x.second << "\n";
}
cout << "--------------------------\n";
*/
for(auto it = strs.begin(); it != strs.end(); it++)
{
if(str_count[*it] == 1)
{
bool is_solo = true;
for(auto it2 = strs.begin(); it2 != it; it2++)
{
if(is_contained(*it, *it2))
{
is_solo = false;
break;
}
}
if(is_solo)
{
res = it->length();
break;
}
}
}
}
return res;
}
// time: O(n)
// memory: O(1)
bool is_contained(const string & s1, const string & s2)
{
int m = 0, n = 0;
bool res = false;
while( m < s1.length() && n < s2.length() )
{
if(s1[m] != s2[n])
{
n++;
}
else
{
m++;
n++;
}
}
if(m == s1.length())
{
res = true;
}
return res;
}
};
bool testcase(vector<string> strs, int res, int casenum)
{
Solution sol;
if( sol.findLUSlength(strs) == res )
{
cout << casenum << " pass\n";
}
else
{
cout << casenum << " no pass\n";
cout << "detail:\n";
for(auto & s : strs)
{
cout << s << "-- ";
}
cout << "\n";
}
cout << "-----------------------------------------\n";
}
int main()
{
vector<pair<vector<string>, int>> cases;
vector<string> strs;
strs = {"abc", "abd", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "ab", "bc", "abc", "b", "c", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "ab", "bc", "abc", "b", "c", "bcd", "abc", "bcd"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "a", "a", "a", "a"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "a", "v", "v", "v"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "a", "b", "v", "v"};
cases.push_back(make_pair(strs, 1));
strs = {"aaa", "aaa", "ba", "va", "vaaaaaaaaaaaaaaaaaaaa"};
cases.push_back(make_pair(strs, 21));
strs = {"aaa", "aaa", "ba", "va", "vaaaa", "vaaaa", "ab"};
cases.push_back(make_pair(strs, 2));
strs = {"", ""};
cases.push_back(make_pair(strs, -1));
strs = {"a", "", ""};
cases.push_back(make_pair(strs, 1));
strs = {"aa", "ab"};
cases.push_back(make_pair(strs, 2));
int num = 1;
for(auto & x : cases)
{
testcase(x.first, x.second, num);
num++;
}
/*
strs = {"a", "b", "c", "d", "e",
"ab", "ac", "ad", "ae", "bc", "bd", "be", "cd", "ce",
"ba", "ca", "da", "ea", "cb", "db", "eb", "dc", "ec",
"abc", "abd", "abe", "acd", "ace", "ade",
"acb", "adb", "aeb", "adc", "aec", "aed",
"bca", "bad", "bae", "cad", "cae", "dae",
"bac", "bda", "bea",
"cab", "dab", "eab",
"cba", "dba", "eba",
"abcd", "abce", "aced",
"abcde", "abcde"
};
testcase(strs, -1, 3);
*/
}
| 3,430 | 1,774 |
#include <iostream>
#include <fstream>
#include <limits>
#include <algorithm>
#include <vector>
#include <iterator>
#include <ctime>
#include <cstdio>
using namespace std;
int minimum(int a, int b) {
return a > b ? b : a;
}
void findMax(vector<int> v, vector<int> &indexes, vector<int> &prev) {
int n = v.size();
vector<int> p;
vector<int> d;
vector<int> answer;
d.push_back(-2);
for (int i = 0; i <= n; ++i) {
p.push_back(0);
d.push_back(100001);
prev.push_back(-1);
indexes.push_back(1);
}
int buf;
for (int i = 0; i < n; i++) {
int j = int(upper_bound(d.begin(), d.end(), v[i]) - d.begin());
if (d[j - 1] == v[i]) {
indexes[i] = j - 1;
}
else {
indexes[i] = j;
}
if (d[j - 1] < v[i] && v[i] < d[j]) {
d[j] = v[i];
if (j == 1) {
prev[i] = -1;
p[j] = i;
}
else {
prev[i] = p[j - 1];
p[j] = i;
}
}
else if(d[j - 1] == v[i]){
if (j == 2) {
prev[i] = -1;
}
else {
prev[i] = p[j - 2];
}
}
}
}
int main()
{
FILE *fin = fopen("report.in","r");
FILE *fout = fopen("report.out", "w");
int n;
int k;
int max = -1;
int index;
fscanf(fin, "%d", &n);
vector<int> numbers;
vector<int> indexInc;
vector<int> prevInc;
vector<int> reversed;
vector<int> indexDec;
vector<int> prevDec;
vector<int> answer;
for (int i = 0; i < n; i++)
{
fscanf(fin, "%d", &k);
numbers.push_back(k);
}
copy(numbers.begin(), numbers.end(), back_inserter(reversed));
reverse(reversed.begin(), reversed.end());
findMax(numbers, indexInc, prevInc);
findMax(reversed, indexDec, prevDec);
indexInc.pop_back();
prevInc.pop_back();
indexDec.pop_back();
prevDec.pop_back();
reverse(indexDec.begin(), indexDec.end());
reverse(prevDec.begin(), prevDec.end());
for (int i = 0; i < n; i++)
{
if (minimum(indexInc[i] - 1, indexDec[i] - 1) > max) {
max = minimum(indexInc[i] - 1, indexDec[i] - 1);
index = i;
}
}
int j = index;
for (int i = 0; i < max; i++)
{
answer.push_back(prevInc[j] + 1);
j = prevInc[j];
}
reverse(answer.begin(), answer.end());
answer.push_back(index + 1);
j = index;
for (int i = 0; i < max; i++)
{
answer.push_back(n - prevDec[j]);
j = n - prevDec[j] - 1;
}
fprintf(fout, "%d\n", max);
for (int i = 0; i < answer.size(); i++)
{
fprintf(fout, "%d ", answer[i]);
}
fclose(fin);
fclose(fout);
system("pause");
return 0;
}
| 2,497 | 1,219 |
#pragma once
namespace nestris_x86 {
class Das {
public:
constexpr static int NTSC_FULL_CHARGE = 16;
constexpr static int NTSC_MIN_CHARGE = 10;
constexpr static int PAL_FULL_CHARGE = 12;
constexpr static int PAL_MIN_CHARGE = 8;
Das(const int das_full_charge, const int das_min_charge)
: das_full_charge_{das_full_charge}, das_min_charge_{das_min_charge} {}
inline void fullyChargeDas(int& das_counter) const { das_counter = das_full_charge_; }
inline void softResetDas(int& das_counter) const { das_counter = das_min_charge_; }
inline void hardResetDas(int& das_counter) const { das_counter = 0; }
inline bool dasFullyCharged(const int das_counter) const {
return das_counter >= das_full_charge_;
}
inline bool dasSoftlyCharged(const int das_counter) const {
return das_counter >= das_min_charge_;
}
inline int getFullDasChargeCount() const { return das_full_charge_; }
inline int getMinDasChargeCount() const { return das_min_charge_; }
private:
int das_full_charge_;
int das_min_charge_;
};
} // namespace nestris_x86
| 1,075 | 382 |
#include "SceneObjectLocation.hpp"
#include "../Math/QuaternionUtils.hpp"
void SceneObjectLocation::SetPrincipalRight(DirectX::XMVECTOR right)
{
DirectX::XMVECTOR defaultRight = DirectX::XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultRight, right));
}
void SceneObjectLocation::SetPrincipalUp(DirectX::XMVECTOR newUpNrm)
{
DirectX::XMVECTOR defaultUp = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultUp, newUpNrm));
}
void SceneObjectLocation::SetPrincipalForward(DirectX::XMVECTOR newForwardNrm)
{
DirectX::XMVECTOR defaultForward = DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultForward, newForwardNrm));
} | 893 | 365 |
#include "StdAfx.h"
#ifndef DISABLE_MULTITHREADED
#include "StringConv.h"
#include "Win32ThreadSupport.h"
MultiThreaded::Win32ThreadConstructionInfo::~Win32ThreadConstructionInfo()
{
this->!Win32ThreadConstructionInfo();
}
MultiThreaded::Win32ThreadConstructionInfo::!Win32ThreadConstructionInfo()
{
if (_native) {
StringConv::FreeUnmanagedString(_uniqueName);
delete _native;
_native = NULL;
}
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc, int numThreads,
int threadStackSize)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc, numThreads, threadStackSize);
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc, int numThreads)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc, numThreads);
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc);
}
BulletSharp::Win32LSMemorySetupFunc MultiThreaded::Win32ThreadConstructionInfo::LSMemorySetupFunc::get()
{
if (_native->m_lsMemoryFunc == createCollisionLocalStoreMemory) {
return Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory;
} else if (_native->m_lsMemoryFunc == SolverlsMemoryFunc) {
return Win32LSMemorySetupFunc::SolverLSMemoryFunc;
}
throw gcnew NotImplementedException();
}
void MultiThreaded::Win32ThreadConstructionInfo::LSMemorySetupFunc::set(BulletSharp::Win32LSMemorySetupFunc value)
{
if (value == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
_native->m_lsMemoryFunc = createCollisionLocalStoreMemory;
} else if (value == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
_native->m_lsMemoryFunc = SolverlsMemoryFunc;
}
}
int MultiThreaded::Win32ThreadConstructionInfo::NumThreads::get()
{
return _native->m_numThreads;
}
void MultiThreaded::Win32ThreadConstructionInfo::NumThreads::set(int value)
{
_native->m_numThreads = value;
}
int MultiThreaded::Win32ThreadConstructionInfo::ThreadStackSize::get()
{
return _native->m_threadStackSize;
}
void MultiThreaded::Win32ThreadConstructionInfo::ThreadStackSize::set(int value)
{
_native->m_threadStackSize = value;
}
String^ MultiThreaded::Win32ThreadConstructionInfo::UniqueName::get()
{
return StringConv::UnmanagedToManaged(_native->m_uniqueName);
}
void MultiThreaded::Win32ThreadConstructionInfo::UniqueName::set(String^ value)
{
StringConv::FreeUnmanagedString(_uniqueName);
_uniqueName = StringConv::ManagedToUnmanaged(value);
}
BulletSharp::Win32ThreadFunc MultiThreaded::Win32ThreadConstructionInfo::UserThreadFunc::get()
{
if (_native->m_userThreadFunc == processCollisionTask) {
return Win32ThreadFunc::ProcessCollisionTask;
} else if (_native->m_userThreadFunc == SolverThreadFunc) {
return Win32ThreadFunc::SolverThreadFunc;
}
throw gcnew NotImplementedException();
}
void MultiThreaded::Win32ThreadConstructionInfo::UserThreadFunc::set(BulletSharp::Win32ThreadFunc value)
{
if (value == Win32ThreadFunc::ProcessCollisionTask) {
_native->m_userThreadFunc = processCollisionTask;
} else if (value == Win32ThreadFunc::SolverThreadFunc) {
_native->m_userThreadFunc = SolverThreadFunc;
}
}
#define Native static_cast<::Win32ThreadSupport*>(_native)
MultiThreaded::Win32ThreadSupport::Win32ThreadSupport(Win32ThreadConstructionInfo^ threadConstructionInfo)
: ThreadSupportInterface(new ::Win32ThreadSupport(*threadConstructionInfo->_native))
{
}
/*
bool MultiThreaded::Win32ThreadSupport::IsTaskCompleted(unsigned int^ puiArgument0, unsigned int^ puiArgument1,
int timeOutInMilliseconds)
{
return Native->isTaskCompleted(puiArgument0->_native, puiArgument1->_native, timeOutInMilliseconds);
}
*/
void MultiThreaded::Win32ThreadSupport::StartThreads(Win32ThreadConstructionInfo^ threadInfo)
{
Native->startThreads(*threadInfo->_native);
}
#endif
| 6,581 | 2,152 |
/*
* @Author: gpinchon
* @Date: 2021-03-12 16:08:58
* @Last Modified by: gpinchon
* @Last Modified time: 2021-05-18 18:26:25
*/
#include <Camera/Camera.hpp>
#include <Light/SkyLight.hpp>
#include <Renderer/Renderer.hpp>
#include <Renderer/Surface/GeometryRenderer.hpp>
#include <Scene/Scene.hpp>
#include <Shader/Program.hpp>
#include <SphericalHarmonics.hpp>
#include <Surface/CubeMesh.hpp>
#include <Surface/Geometry.hpp>
#include <Texture/Texture2D.hpp>
#include <Texture/TextureCubemap.hpp>
#if RENDERINGAPI == OpenGL
#include <Driver/OpenGL/Renderer/Light/SkyLightRenderer.hpp>
#endif
#define num_samples 16
#define num_samples_light 8
/// \private
struct ray_t {
glm::vec3 origin;
glm::vec3 direction;
};
/// \private
struct sphere_t {
glm::vec3 origin;
float radius;
};
bool isect_sphere(const ray_t ray, const sphere_t sphere, float& t0, float& t1)
{
glm::vec3 rc = sphere.origin - ray.origin;
float radius2 = sphere.radius * sphere.radius;
float tca = dot(rc, ray.direction);
float d2 = dot(rc, rc) - tca * tca;
if (d2 > radius2)
return false;
float thc = sqrt(radius2 - d2);
t0 = tca - thc;
t1 = tca + thc;
return true;
}
float rayleigh_phase_func(float mu)
{
return 3. * (1. + mu * mu)
/ //------------------------
(16. * M_PI);
}
float henyey_greenstein_phase_func(float mu)
{
const float g = 0.76;
return (1. - g * g)
/ //---------------------------------------------
((4. * M_PI) * pow(1. + g * g - 2. * g * mu, 1.5));
}
bool get_sun_light(const ray_t& ray, float& optical_depthR, float& optical_depthM, const SkyLight& sky)
{
float t0, t1;
const sphere_t atmosphere = sphere_t {
glm::vec3(0, 0, 0), sky.GetAtmosphereRadius()
};
isect_sphere(ray, atmosphere, t0, t1);
float march_pos = 0.;
float march_step = t1 / float(num_samples_light);
for (int i = 0; i < num_samples_light; i++) {
glm::vec3 s = ray.origin + ray.direction * float(march_pos + 0.5 * march_step);
float height = length(s) - sky.GetPlanetRadius();
if (height < 0.)
return false;
optical_depthR += exp(-height / sky.GetHRayleigh()) * march_step;
optical_depthM += exp(-height / sky.GetHMie()) * march_step;
march_pos += march_step;
}
return true;
}
static inline glm::vec3 GetIncidentLight(ray_t ray, const SkyLight& sky)
{
const sphere_t atmosphere = sphere_t {
glm::vec3(0, 0, 0), sky.GetAtmosphereRadius()
};
// "pierce" the atmosphere with the viewing ray
float t0, t1;
if (!isect_sphere(
ray, atmosphere, t0, t1)) {
return glm::vec3(0);
}
float march_step = t1 / float(num_samples);
// cosine of angle between view and light directions
float mu = glm::dot(ray.direction, sky.GetSunDirection());
// Rayleigh and Mie phase functions
// A black box indicating how light is interacting with the material
// Similar to BRDF except
// * it usually considers a single angle
// (the phase angle between 2 directions)
// * integrates to 1 over the entire sphere of directions
float phaseR = rayleigh_phase_func(mu);
float phaseM = henyey_greenstein_phase_func(mu);
// optical depth (or "average density")
// represents the accumulated extinction coefficients
// along the path, multiplied by the length of that path
float optical_depthR = 0.;
float optical_depthM = 0.;
glm::vec3 sumR = glm::vec3(0);
glm::vec3 sumM = glm::vec3(0);
float march_pos = 0.;
for (int i = 0; i < num_samples; i++) {
glm::vec3 s = ray.origin + ray.direction * float(march_pos + 0.5 * march_step);
float height = glm::length(s) - sky.GetPlanetRadius();
// integrate the height scale
float hr = exp(-height / sky.GetHRayleigh()) * march_step;
float hm = exp(-height / sky.GetHMie()) * march_step;
optical_depthR += hr;
optical_depthM += hm;
// gather the sunlight
ray_t light_ray {
s,
sky.GetSunDirection()
};
float optical_depth_lightR = 0.;
float optical_depth_lightM = 0.;
bool overground = get_sun_light(
light_ray,
optical_depth_lightR,
optical_depth_lightM,
sky);
if (overground) {
glm::vec3 tau = sky.GetBetaRayleigh() * (optical_depthR + optical_depth_lightR) + sky.GetBetaMie() * 1.1f * (optical_depthM + optical_depth_lightM);
glm::vec3 attenuation = exp(-tau);
sumR += hr * attenuation;
sumM += hm * attenuation;
}
march_pos += march_step;
}
return sky.GetSunPower() * (sumR * phaseR * sky.GetBetaRayleigh() + sumM * phaseM * sky.GetBetaMie());
}
SkyLight::SkyLight()
: DirectionalLight()
{
}
glm::vec3 SkyLight::GetSunDirection() const
{
return GetDirection();
}
void SkyLight::SetSunDirection(const glm::vec3& sunDir)
{
if (sunDir != GetSunDirection())
GetRenderer().FlagDirty();
SetDirection(sunDir);
}
float SkyLight::GetSunPower() const
{
return _sunPower;
}
void SkyLight::SetSunPower(const float sunPower)
{
if (sunPower != _sunPower)
GetRenderer().FlagDirty();
_sunPower = sunPower;
}
float SkyLight::GetPlanetRadius() const
{
return _planetRadius;
}
void SkyLight::SetPlanetRadius(float planetRadius)
{
if (planetRadius != _planetRadius)
GetRenderer().FlagDirty();
_planetRadius = planetRadius;
}
float SkyLight::GetAtmosphereRadius() const
{
return _atmosphereRadius;
}
void SkyLight::SetAtmosphereRadius(float atmosphereRadius)
{
if (atmosphereRadius != _atmosphereRadius)
GetRenderer().FlagDirty();
_atmosphereRadius = atmosphereRadius;
}
float SkyLight::GetHRayleigh() const
{
return _hRayleigh;
}
void SkyLight::SetHRayleigh(float hRayleigh)
{
if (hRayleigh != _hRayleigh)
GetRenderer().FlagDirty();
_hRayleigh = hRayleigh;
}
float SkyLight::GetHMie() const
{
return _hMie;
}
void SkyLight::SetHMie(float hMie)
{
if (hMie != _hMie)
GetRenderer().FlagDirty();
_hMie = hMie;
}
glm::vec3 SkyLight::GetBetaRayleigh() const
{
return _betaRayleigh;
}
void SkyLight::SetBetaRayleigh(glm::vec3 betaRayleigh)
{
if (betaRayleigh != _betaRayleigh)
GetRenderer().FlagDirty();
_betaRayleigh = betaRayleigh;
}
glm::vec3 SkyLight::GetBetaMie() const
{
return _betaMie;
}
void SkyLight::SetBetaMie(glm::vec3 betaMie)
{
if (betaMie != _betaMie)
GetRenderer().FlagDirty();
_betaMie = betaMie;
}
glm::vec3 SkyLight::GetIncidentLight(glm::vec3 direction) const
{
return ::GetIncidentLight({ glm::vec3(0, GetPlanetRadius() + 1, 0),
direction },
*this);
}
| 7,143 | 2,584 |
#include "search/result.hpp"
#include "search/common.hpp"
#include "search/geometry_utils.hpp"
namespace search
{
Result::Result(FeatureID const & id, m2::PointD const & pt, string const & str,
string const & address, string const & type, uint32_t featureType,
Metadata const & meta)
: m_id(id)
, m_center(pt)
, m_str(str.empty() ? type : str) //!< Features with empty names can be found after suggestion.
, m_address(address)
, m_type(type)
, m_featureType(featureType)
, m_metadata(meta)
{
}
Result::Result(m2::PointD const & pt, string const & latlon, string const & address)
: m_center(pt), m_str(latlon), m_address(address)
{
}
Result::Result(string const & str, string const & suggest)
: m_str(str), m_suggestionStr(suggest)
{
}
Result::Result(Result const & res, string const & suggest)
: m_id(res.m_id)
, m_center(res.m_center)
, m_str(res.m_str)
, m_address(res.m_address)
, m_type(res.m_type)
, m_featureType(res.m_featureType)
, m_suggestionStr(suggest)
, m_hightlightRanges(res.m_hightlightRanges)
{
}
Result::ResultType Result::GetResultType() const
{
bool const idValid = m_id.IsValid();
if (!m_suggestionStr.empty())
return (idValid ? RESULT_SUGGEST_FROM_FEATURE : RESULT_SUGGEST_PURE);
if (idValid)
return RESULT_FEATURE;
else
return RESULT_LATLON;
}
bool Result::IsSuggest() const
{
return !m_suggestionStr.empty();
}
bool Result::HasPoint() const
{
return (GetResultType() != RESULT_SUGGEST_PURE);
}
FeatureID const & Result::GetFeatureID() const
{
#if defined(DEBUG)
auto const type = GetResultType();
ASSERT(type == RESULT_FEATURE, (type));
#endif
return m_id;
}
m2::PointD Result::GetFeatureCenter() const
{
ASSERT(HasPoint(), ());
return m_center;
}
char const * Result::GetSuggestionString() const
{
ASSERT(IsSuggest(), ());
return m_suggestionStr.c_str();
}
bool Result::IsEqualSuggest(Result const & r) const
{
return (m_suggestionStr == r.m_suggestionStr);
}
bool Result::IsEqualFeature(Result const & r) const
{
ResultType const type = GetResultType();
if (type != r.GetResultType())
return false;
ASSERT_EQUAL(type, Result::RESULT_FEATURE, ());
ASSERT(m_id.IsValid() && r.m_id.IsValid(), ());
if (m_id == r.m_id)
return true;
// This function is used to filter duplicate results in cases:
// - emitted World.mwm and Country.mwm
// - after additional search in all mwm
// so it's suitable here to test for 500m
return (m_str == r.m_str && m_address == r.m_address &&
m_featureType == r.m_featureType &&
PointDistance(m_center, r.m_center) < 500.0);
}
void Result::AddHighlightRange(pair<uint16_t, uint16_t> const & range)
{
m_hightlightRanges.push_back(range);
}
pair<uint16_t, uint16_t> const & Result::GetHighlightRange(size_t idx) const
{
ASSERT(idx < m_hightlightRanges.size(), ());
return m_hightlightRanges[idx];
}
void Result::AppendCity(string const & name)
{
// Prepend only if city is absent in region (mwm) name.
if (m_address.find(name) == string::npos)
m_address = name + ", " + m_address;
}
string Result::ToStringForStats() const
{
string s;
s.append(GetString());
s.append("|");
s.append(GetFeatureType());
s.append("|");
s.append(IsSuggest() ? "1" : "0");
return s;
}
bool Results::AddResult(Result && res)
{
// Find first feature result.
auto it = find_if(m_vec.begin(), m_vec.end(), [](Result const & r)
{
switch (r.GetResultType())
{
case Result::RESULT_FEATURE:
return true;
default:
return false;
}
});
if (res.IsSuggest())
{
if (distance(m_vec.begin(), it) >= MAX_SUGGESTS_COUNT)
return false;
for (auto i = m_vec.begin(); i != it; ++i)
if (res.IsEqualSuggest(*i))
return false;
for (auto i = it; i != m_vec.end(); ++i)
{
auto & r = *i;
auto const oldPos = r.GetPositionInResults();
r.SetPositionInResults(oldPos + 1);
}
res.SetPositionInResults(distance(m_vec.begin(), it));
m_vec.insert(it, move(res));
}
else
{
for (; it != m_vec.end(); ++it)
if (res.IsEqualFeature(*it))
return false;
res.SetPositionInResults(m_vec.size());
m_vec.push_back(move(res));
}
return true;
}
size_t Results::GetSuggestsCount() const
{
size_t res = 0;
for (size_t i = 0; i < GetCount(); i++)
{
if (m_vec[i].IsSuggest())
++res;
else
{
// Suggests always go first, so we can exit here.
break;
}
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////
// AddressInfo implementation
////////////////////////////////////////////////////////////////////////////////////
bool AddressInfo::IsEmptyName() const
{
return m_name.empty() && m_house.empty();
}
string AddressInfo::GetPinName() const
{
if (IsEmptyName() && !m_types.empty())
return m_types[0];
else
return m_name.empty() ? m_house : m_name;
}
string AddressInfo::GetPinType() const
{
return GetBestType();
}
string AddressInfo::FormatPinText() const
{
// select name or house if name is empty
string const & ret = (m_name.empty() ? m_house : m_name);
string const type = GetBestType();
if (type.empty())
return ret;
return (ret.empty() ? type : (ret + " (" + type + ')'));
}
string AddressInfo::FormatHouseAndStreet(AddressType type /* = DEFAULT */) const
{
// Check whether we can format address according to the query type and actual address distance.
/// @todo We can add "Near" prefix here in future according to the distance.
if (m_distanceMeters > 0.0)
{
if (type == SEARCH_RESULT && m_distanceMeters > 50.0)
return string();
if (m_distanceMeters > 200.0)
return string();
}
string result = m_street;
if (!m_house.empty())
{
if (!result.empty())
result += ", ";
result += m_house;
}
return result;
}
string AddressInfo::FormatAddress(AddressType type /* = DEFAULT */) const
{
string result = FormatHouseAndStreet(type);
if (!m_city.empty())
{
if (!result.empty())
result += ", ";
result += m_city;
}
if (!m_country.empty())
{
if (!result.empty())
result += ", ";
result += m_country;
}
return result;
}
string AddressInfo::FormatNameAndAddress(AddressType type /* = DEFAULT */) const
{
string const addr = FormatAddress(type);
return (m_name.empty() ? addr : m_name + ", " + addr);
}
string AddressInfo::FormatTypes() const
{
string result;
for (size_t i = 0; i < m_types.size(); ++i)
{
ASSERT ( !m_types.empty(), () );
if (!result.empty())
result += ' ';
result += m_types[i];
}
return result;
}
string AddressInfo::GetBestType() const
{
if (m_types.empty())
return string();
/// @todo Probably, we should skip some "common" types here like in TypesHolder::SortBySpec.
ASSERT(!m_types[0].empty(), ());
return m_types[0];
}
void AddressInfo::Clear()
{
m_country.clear();
m_city.clear();
m_street.clear();
m_house.clear();
m_name.clear();
m_types.clear();
}
string DebugPrint(AddressInfo const & info)
{
return info.FormatNameAndAddress();
}
string DebugPrint(Result const & result)
{
return "Result { Name: " + result.GetString() + "; Type: " + result.GetFeatureType() +
"; Info: " + DebugPrint(result.GetRankingInfo()) + " }";
}
} // namespace search
| 7,404 | 2,677 |
/* B O O L E A N . C P P
* BRL-CAD
*
* Copyright (c) 2013-2022 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file boolean.cpp
*
* Evaluate NURBS booleans (union, intersection and difference).
*
* Additional documentation can be found in the "NURBS Boolean Evaluation
* Development Guide" docbook article (bool_eval_development.html).
*/
#include "common.h"
#include <assert.h>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include "bio.h"
#include "vmath.h"
#include "bu/log.h"
#include "brep/defines.h"
#include "brep/boolean.h"
#include "brep/intersect.h"
#include "brep/pullback.h"
#include "brep/ray.h"
#include "brep/util.h"
#include "debug_plot.h"
#include "brep_except.h"
#include "brep_defines.h"
DebugPlot *dplot = NULL;
// Whether to output the debug messages about b-rep booleans.
#define DEBUG_BREP_BOOLEAN 0
struct IntersectPoint {
ON_3dPoint m_pt; // 3D intersection point
double m_seg_t; // param on the loop curve
int m_loop_seg; // which curve of the loop
int m_ssx_curve; // which intersection curve
int m_curve_pos; // rank on the chain
double m_curve_t; // param on the SSI curve
enum {
UNSET,
IN_HIT,
OUT_HIT,
TANGENT
} m_dir; // dir is going inside/outside
int m_split_li; // between clx_points[m_split_li] and
// clx_points[m_split_li+1]
// after the outerloop is split
};
// A structure to represent the curve segments generated from surface-surface
// intersections, including some information needed by the connectivity graph
struct SSICurve {
ON_Curve *m_curve;
SSICurve()
{
m_curve = NULL;
}
SSICurve(ON_Curve *curve)
{
m_curve = curve;
}
SSICurve *Duplicate() const
{
SSICurve *out = new SSICurve();
if (out != NULL) {
*out = *this;
out->m_curve = m_curve->Duplicate();
}
return out;
}
};
void
append_to_polycurve(ON_Curve *curve, ON_PolyCurve &polycurve);
// We link the SSICurves that share an endpoint, and form this new structure,
// which has many similar behaviors as ON_Curve, e.g. PointAt(), Reverse().
struct LinkedCurve {
private:
ON_Curve *m_curve; // an explicit storage of the whole curve
public:
// The curves contained in this LinkedCurve, including
// the information needed by the connectivity graph
ON_SimpleArray<SSICurve> m_ssi_curves;
// Default constructor
LinkedCurve()
{
m_curve = NULL;
}
void Empty()
{
m_ssi_curves.Empty();
delete m_curve;
m_curve = NULL;
}
~LinkedCurve()
{
Empty();
}
LinkedCurve &operator= (const LinkedCurve &_lc)
{
Empty();
m_curve = _lc.m_curve ? _lc.m_curve->Duplicate() : NULL;
m_ssi_curves = _lc.m_ssi_curves;
return *this;
}
ON_3dPoint PointAtStart() const
{
if (m_ssi_curves.Count()) {
return m_ssi_curves[0].m_curve->PointAtStart();
} else {
return ON_3dPoint::UnsetPoint;
}
}
ON_3dPoint PointAtEnd() const
{
if (m_ssi_curves.Count()) {
return m_ssi_curves.Last()->m_curve->PointAtEnd();
} else {
return ON_3dPoint::UnsetPoint;
}
}
bool IsClosed() const
{
if (m_ssi_curves.Count() == 0) {
return false;
}
return PointAtStart().DistanceTo(PointAtEnd()) < ON_ZERO_TOLERANCE;
}
bool IsValid() const
{
// Check whether the curve has "gaps".
for (int i = 1; i < m_ssi_curves.Count(); i++) {
if (m_ssi_curves[i].m_curve->PointAtStart().DistanceTo(m_ssi_curves[i - 1].m_curve->PointAtEnd()) >= ON_ZERO_TOLERANCE) {
bu_log("The LinkedCurve is not valid.\n");
return false;
}
}
return true;
}
bool Reverse()
{
ON_SimpleArray<SSICurve> new_array;
for (int i = m_ssi_curves.Count() - 1; i >= 0; i--) {
if (!m_ssi_curves[i].m_curve->Reverse()) {
return false;
}
new_array.Append(m_ssi_curves[i]);
}
m_ssi_curves = new_array;
return true;
}
void Append(const LinkedCurve &lc)
{
m_ssi_curves.Append(lc.m_ssi_curves.Count(), lc.m_ssi_curves.Array());
}
void Append(const SSICurve &sc)
{
m_ssi_curves.Append(sc);
}
void AppendCurvesToArray(ON_SimpleArray<ON_Curve *> &arr) const
{
for (int i = 0; i < m_ssi_curves.Count(); i++) {
arr.Append(m_ssi_curves[i].m_curve->Duplicate());
}
}
const ON_Curve *Curve()
{
if (m_curve != NULL) {
return m_curve;
}
if (m_ssi_curves.Count() == 0 || !IsValid()) {
return NULL;
}
ON_PolyCurve *polycurve = new ON_PolyCurve;
for (int i = 0; i < m_ssi_curves.Count(); i++) {
append_to_polycurve(m_ssi_curves[i].m_curve->Duplicate(), *polycurve);
}
m_curve = polycurve;
return m_curve;
}
const ON_3dPoint PointAt(double t)
{
const ON_Curve *c = Curve();
if (c == NULL) {
return ON_3dPoint::UnsetPoint;
}
return c->PointAt(t);
}
const ON_Interval Domain()
{
const ON_Curve *c = Curve();
if (c == NULL) {
return ON_Interval::EmptyInterval;
}
return c->Domain();
}
ON_Curve *SubCurve(double t1, double t2)
{
const ON_Curve *c = Curve();
if (c == NULL) {
return NULL;
}
try {
return sub_curve(c, t1, t2);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
return NULL;
}
}
};
struct TrimmedFace {
// curve segments in the face's outer loop
ON_SimpleArray<ON_Curve *> m_outerloop;
// several inner loops, each has some curves
std::vector<ON_SimpleArray<ON_Curve *> > m_innerloop;
const ON_BrepFace *m_face;
enum {
UNKNOWN = -1,
NOT_BELONG = 0,
BELONG = 1
} m_belong_to_final;
bool m_rev;
// Default constructor
TrimmedFace()
{
m_face = NULL;
m_belong_to_final = UNKNOWN;
m_rev = false;
}
// Destructor
~TrimmedFace()
{
// Delete the curve segments if it's not belong to the result.
if (m_belong_to_final != BELONG) {
for (int i = 0; i < m_outerloop.Count(); i++) {
if (m_outerloop[i]) {
delete m_outerloop[i];
m_outerloop[i] = NULL;
}
}
for (unsigned int i = 0; i < m_innerloop.size(); i++) {
for (int j = 0; j < m_innerloop[i].Count(); j++) {
if (m_innerloop[i][j]) {
delete m_innerloop[i][j];
m_innerloop[i][j] = NULL;
}
}
}
}
}
TrimmedFace *Duplicate() const
{
TrimmedFace *out = new TrimmedFace();
out->m_face = m_face;
for (int i = 0; i < m_outerloop.Count(); i++) {
if (m_outerloop[i]) {
out->m_outerloop.Append(m_outerloop[i]->Duplicate());
}
}
out->m_innerloop = m_innerloop;
for (unsigned int i = 0; i < m_innerloop.size(); i++) {
for (int j = 0; j < m_innerloop[i].Count(); j++) {
if (m_innerloop[i][j]) {
out->m_innerloop[i][j] = m_innerloop[i][j]->Duplicate();
}
}
}
return out;
}
};
HIDDEN int
loop_t_compare(const IntersectPoint *p1, const IntersectPoint *p2)
{
// Use for sorting an array. Use strict FP comparison.
if (p1->m_loop_seg != p2->m_loop_seg) {
return p1->m_loop_seg - p2->m_loop_seg;
}
return p1->m_seg_t > p2->m_seg_t ? 1 : (p1->m_seg_t < p2->m_seg_t ? -1 : 0);
}
HIDDEN int
curve_t_compare(const IntersectPoint *p1, const IntersectPoint *p2)
{
// Use for sorting an array. Use strict FP comparison.
return p1->m_curve_t > p2->m_curve_t ? 1 : (p1->m_curve_t < p2->m_curve_t ? -1 : 0);
}
void
append_to_polycurve(ON_Curve *curve, ON_PolyCurve &polycurve)
{
// use this function rather than ON_PolyCurve::Append() to avoid
// getting nested polycurves, which makes ON_Brep::IsValid() to fail.
ON_PolyCurve *nested = ON_PolyCurve::Cast(curve);
if (nested != NULL) {
// The input curve is a polycurve
const ON_CurveArray &segments = nested->SegmentCurves();
for (int i = 0; i < segments.Count(); i++) {
append_to_polycurve(segments[i]->Duplicate(), polycurve);
}
delete nested;
} else {
polycurve.Append(curve);
}
}
HIDDEN bool
is_loop_valid(const ON_SimpleArray<ON_Curve *> &loop, double tolerance, ON_PolyCurve *polycurve = NULL)
{
bool delete_curve = false;
bool ret = true;
if (loop.Count() == 0) {
bu_log("The input loop is empty.\n");
ret = false;
}
// First, use a ON_PolyCurve to represent the loop.
if (ret) {
if (polycurve == NULL) {
polycurve = new ON_PolyCurve;
if (polycurve) {
delete_curve = true;
} else {
ret = false;
}
}
}
// Check the loop is continuous and closed or not.
if (ret) {
if (loop[0] != NULL) {
append_to_polycurve(loop[0]->Duplicate(), *polycurve);
}
for (int i = 1 ; i < loop.Count(); i++) {
if (loop[i] && loop[i - 1] && loop[i]->PointAtStart().DistanceTo(loop[i - 1]->PointAtEnd()) < ON_ZERO_TOLERANCE) {
append_to_polycurve(loop[i]->Duplicate(), *polycurve);
} else {
bu_log("The input loop is not continuous.\n");
ret = false;
}
}
}
if (ret && (polycurve->PointAtStart().DistanceTo(polycurve->PointAtEnd()) >= ON_ZERO_TOLERANCE ||
!polycurve->IsClosed()))
{
bu_log("The input loop is not closed.\n");
ret = false;
}
if (ret) {
// Check whether the loop is degenerated.
ON_BoundingBox bbox = polycurve->BoundingBox();
ret = !ON_NearZero(bbox.Diagonal().Length(), tolerance)
&& !polycurve->IsLinear(tolerance);
}
if (delete_curve) {
delete polycurve;
}
return ret;
}
enum {
OUTSIDE_OR_ON_LOOP,
INSIDE_OR_ON_LOOP
};
// Returns whether the point is inside/on or outside/on the loop
// boundary.
//
// Throws InvalidGeometry if loop is invalid.
//
// If you want to know whether this point is on the loop boundary,
// call is_point_on_loop().
HIDDEN int
point_loop_location(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
ON_PolyCurve polycurve;
if (!is_loop_valid(loop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("point_loop_location() given invalid loop\n");
}
ON_BoundingBox bbox = polycurve.BoundingBox();
if (!bbox.IsPointIn(pt)) {
return OUTSIDE_OR_ON_LOOP;
}
// The input point is inside the loop's bounding box.
// out must be outside the closed region (and the bbox).
ON_2dPoint out = pt + ON_2dVector(bbox.Diagonal());
ON_LineCurve linecurve(pt, out);
ON_3dVector line_dir = linecurve.m_line.Direction();
ON_SimpleArray<ON_X_EVENT> tmp_x;
for (int i = 0; i < loop.Count(); ++i) {
ON_SimpleArray<ON_X_EVENT> li_x;
ON_Intersect(&linecurve, loop[i], li_x, INTERSECTION_TOL);
for (int j = 0; j < li_x.Count(); ++j) {
// ignore tangent and overlap intersections
if (li_x[j].m_type != ON_X_EVENT::ccx_overlap &&
!loop[i]->TangentAt(li_x[j].m_b[0]).IsParallelTo(line_dir, ANGLE_TOL))
{
tmp_x.Append(li_x[j]);
}
}
}
ON_SimpleArray<ON_X_EVENT> x_event;
for (int i = 0; i < tmp_x.Count(); i++) {
int j;
for (j = 0; j < x_event.Count(); j++) {
if (tmp_x[i].m_A[0].DistanceTo(x_event[j].m_A[0]) < INTERSECTION_TOL &&
tmp_x[i].m_A[1].DistanceTo(x_event[j].m_A[1]) < INTERSECTION_TOL &&
tmp_x[i].m_B[0].DistanceTo(x_event[j].m_B[0]) < INTERSECTION_TOL &&
tmp_x[i].m_B[1].DistanceTo(x_event[j].m_B[1]) < INTERSECTION_TOL)
{
break;
}
}
if (j == x_event.Count()) {
x_event.Append(tmp_x[i]);
}
}
return (x_event.Count() % 2) ? INSIDE_OR_ON_LOOP : OUTSIDE_OR_ON_LOOP;
}
// Returns whether or not point is on the loop boundary.
// Throws InvalidGeometry if loop is invalid.
HIDDEN bool
is_point_on_loop(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
ON_PolyCurve polycurve;
if (!is_loop_valid(loop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("is_point_on_loop() given invalid loop\n");
}
ON_3dPoint pt3d(pt);
for (int i = 0; i < loop.Count(); ++i) {
ON_ClassArray<ON_PX_EVENT> px_event;
if (ON_Intersect(pt3d, *loop[i], px_event, INTERSECTION_TOL)) {
return true;
}
}
return false;
}
HIDDEN bool
is_point_inside_loop(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
return (point_loop_location(pt, loop) == INSIDE_OR_ON_LOOP) && !is_point_on_loop(pt, loop);
}
HIDDEN bool
is_point_outside_loop(const ON_2dPoint &pt, const ON_SimpleArray<ON_Curve *> &loop)
{
return (point_loop_location(pt, loop) == OUTSIDE_OR_ON_LOOP) && !is_point_on_loop(pt, loop);
}
HIDDEN ON_SimpleArray<ON_Interval>
get_curve_intervals_inside_or_on_face(
ON_Curve *curve2D,
const ON_ClassArray<ON_SimpleArray<ON_Curve *> > &face_loops,
double isect_tol)
{
// get curve-loop intersections
ON_SimpleArray<double> isect_curve_t;
ON_SimpleArray<ON_X_EVENT> ccx_events;
for (int i = 0; i < face_loops.Count(); ++i) {
for (int j = 0; j < face_loops[i].Count(); ++j) {
ON_Intersect(curve2D, face_loops[i][j], ccx_events, isect_tol);
}
}
// get a sorted list of just the parameters on the first curve
// where it intersects the outerloop
for (int i = 0; i < ccx_events.Count(); i++) {
isect_curve_t.Append(ccx_events[i].m_a[0]);
if (ccx_events[i].m_type == ON_X_EVENT::ccx_overlap) {
isect_curve_t.Append(ccx_events[i].m_a[1]);
}
}
isect_curve_t.QuickSort(ON_CompareIncreasing);
// insert start and end parameters so every part of the curve is tested
isect_curve_t.Insert(0, curve2D->Domain().Min());
isect_curve_t.Append(curve2D->Domain().Max());
// if the midpoint of an interval is inside/on the face, keep the
// entire interval
ON_SimpleArray<ON_Interval> included_intervals;
for (int i = 0; i < isect_curve_t.Count() - 1; i++) {
ON_Interval interval(isect_curve_t[i], isect_curve_t[i + 1]);
if (ON_NearZero(interval.Length(), isect_tol)) {
continue;
}
ON_2dPoint pt = curve2D->PointAt(interval.Mid());
bool point_included = false;
try {
// inside/on outerloop
if (!is_point_outside_loop(pt, face_loops[0])) {
// outside/on innerloops
point_included = true;
for (int j = 1; j < face_loops.Count(); ++j) {
if (is_point_inside_loop(pt, face_loops[j])) {
point_included = false;
break;
}
}
}
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
}
if (point_included) {
included_intervals.Append(interval);
}
}
// merge continuous intervals
ON_SimpleArray<ON_Interval> final_intervals;
for (int j, i = 0; i < included_intervals.Count(); i = j) {
ON_Interval merged_interval = included_intervals[i];
for (j = i + 1; j < included_intervals.Count(); ++j) {
ON_Interval &next = included_intervals[j];
if (ON_NearZero(next.Min() - merged_interval.Max(), isect_tol)) {
ON_Interval new_interval = merged_interval;
if (new_interval.Union(next)) {
merged_interval = new_interval;
} else {
break;
}
} else {
break;
}
}
final_intervals.Append(merged_interval);
}
return final_intervals;
}
struct IntervalPoints {
ON_3dPoint min;
ON_3dPoint mid;
ON_3dPoint max;
};
class IntervalParams {
public:
double min;
double mid;
double max;
void
MakeIncreasing(void)
{
if (min > mid) {
std::swap(min, mid);
}
if (mid > max) {
std::swap(mid, max);
if (min > mid) {
std::swap(min, mid);
}
}
}
};
// given parameters in a curve interval, create new interval
// parameters that reflect the the non-degenerate (different
// dimensioned) curve interval used to generate the curve parameters
HIDDEN IntervalParams
curve_interval_from_params(
IntervalParams interval_t,
const ON_Curve *curve)
{
if (!curve->IsClosed()) {
return interval_t;
}
if (interval_t.min > interval_t.max) {
std::swap(interval_t.min, interval_t.max);
}
double min_t = interval_t.min;
double max_t = interval_t.max;
ON_Interval cdom = curve->Domain();
if (!(min_t < max_t || min_t > max_t)) {
// if endpoints are both at closed curve joint, put them at
// either end of the curve domain
if (ON_NearZero(cdom.Min() - min_t, ON_ZERO_TOLERANCE)) {
interval_t.max = cdom.Max();
} else if (ON_NearZero(cdom.Max() - min_t, ON_ZERO_TOLERANCE)) {
interval_t.min = cdom.Min();
}
} else {
// if interval doesn't include midpt, assume the point nearest
// the seam needs to be on the opposite side of the domain
ON_Interval curr(min_t, max_t);
if (!curr.Includes(interval_t.mid)) {
if (fabs(cdom.Min() - min_t) > fabs(cdom.Max() - max_t)) {
interval_t.max = cdom.Min();
} else {
interval_t.min = cdom.Max();
}
}
}
interval_t.MakeIncreasing();
return interval_t;
}
enum seam_location {SEAM_NONE, SEAM_ALONG_V, SEAM_ALONG_U, SEAM_ALONG_UV};
// given interval points in surface uv space, create new interval
// points that reflect the non-degenerate curve parameter interval
// used to generate the input points
HIDDEN IntervalPoints
uv_interval_from_points(
IntervalPoints interval_pts,
const ON_Surface *surf)
{
ON_3dPoint &min_uv = interval_pts.min;
ON_3dPoint &max_uv = interval_pts.max;
ON_Interval udom = surf->Domain(0);
ON_Interval vdom = surf->Domain(1);
int seam_min = IsAtSeam(surf, min_uv, ON_ZERO_TOLERANCE);
int seam_max = IsAtSeam(surf, max_uv, ON_ZERO_TOLERANCE);
if ((seam_min && seam_max) && (min_uv == max_uv)) {
// if uv endpoints are identical and on a seam
// they need to be on opposite sides of the domain
if (ON_NearZero(udom.Min() - min_uv[0], ON_ZERO_TOLERANCE) ||
ON_NearZero(udom.Max() - min_uv[0], ON_ZERO_TOLERANCE))
{
// point on west/east edge becomes one point on west
// edge, one point on east edge
min_uv[0] = udom.Min();
max_uv[0] = udom.Max();
} else if (ON_NearZero(vdom.Min() - min_uv[1], ON_ZERO_TOLERANCE) ||
ON_NearZero(vdom.Max() - min_uv[1], ON_ZERO_TOLERANCE))
{
// point on south/north edge becomes one point on
// south edge, one point on north edge
min_uv[1] = vdom.Min();
max_uv[1] = vdom.Max();
}
} else if (!seam_min != !seam_max) { // XOR
// if just one point is on a seam, make sure it's on the
// correct side of the domain
// get interval midpoint in uv space
ON_ClassArray<ON_PX_EVENT> events;
ON_3dPoint midpt = surf->PointAt(interval_pts.mid.x,
interval_pts.mid.y);
ON_Intersect(midpt, *surf, events, INTERSECTION_TOL);
if (events.Count() == 1) {
// Check that the non-seam parameter of the
// midpoint is between the non-seam parameters of
// the interval uv on the seam and the other
// interval uv. If the midpoint non-seam parameter
// is outside the interval we'll move the seam_uv
// to the other side of the domain.
//
// For example, if the surface has a seam at the
// west/east edge and we have seam_uv (0.0, .1)
// and other_uv (.5, .6) we'll check that the
// interval midpoint uv has a u in [0.0, .5].
//
// A midpoint of (.25, .25) would be okay. A
// midpoint of (.75, .25) would necessitate us
// moving the seam_uv from the west edge to the
// east edge, e.g (1.0, .1).
int seam = seam_min ? seam_min : seam_max;
ON_3dPoint &seam_uv = seam_min ? min_uv : max_uv;
ON_3dPoint other_uv = seam_min ? max_uv : min_uv;
double *seam_t = &seam_uv[1];
double seam_opp_t = vdom.Max() - seam_uv[1];
double other_t = other_uv[1];
double midpt_t = events[0].m_b[1];
if (seam != SEAM_ALONG_U) {
seam_t = &seam_uv[0];
seam_opp_t = udom.Max() - seam_uv[0];
other_t = other_uv[0];
midpt_t = events[0].m_b[0];
}
ON_Interval curr(*seam_t, other_t);
if (!curr.Includes(midpt_t)) {
// need to flip the seam point to the other
// side of the domain
*seam_t = seam_opp_t;
}
}
}
return interval_pts;
}
HIDDEN IntervalPoints
interval_2d_to_uv(
const ON_Interval &interval_2d,
const ON_Curve *curve2d,
const ON_Surface *surf)
{
// initialize endpoints from evaluated surface uv points
IntervalPoints pts;
pts.min = curve2d->PointAt(interval_2d.Min());
pts.mid = curve2d->PointAt(interval_2d.Mid());
pts.max = curve2d->PointAt(interval_2d.Max());
return uv_interval_from_points(pts, surf);
}
HIDDEN std::pair<IntervalPoints, IntervalPoints>
interval_2d_to_2uv(
const ON_Interval &interval_2d,
const ON_Curve *curve2d,
const ON_Surface *surf,
double split_t)
{
std::pair<IntervalPoints, IntervalPoints> out;
ON_Interval left(interval_2d.Min(), split_t);
ON_Interval right(split_t, interval_2d.Max());
out.first = interval_2d_to_uv(left, curve2d, surf);
out.second = interval_2d_to_uv(right, curve2d, surf);
return out;
}
HIDDEN IntervalPoints
points_uv_to_3d(
const IntervalPoints &interval_uv,
const ON_Surface *surf)
{
// evaluate surface at uv points to get 3d interval points
IntervalPoints pts_3d;
pts_3d.min = surf->PointAt(interval_uv.min.x, interval_uv.min.y);
pts_3d.mid = surf->PointAt(interval_uv.mid.x, interval_uv.mid.y);
pts_3d.max = surf->PointAt(interval_uv.max.x, interval_uv.max.y);
return pts_3d;
}
HIDDEN IntervalParams
points_3d_to_params_3d(
const IntervalPoints &pts_3d,
const ON_Curve *curve3d)
{
ON_ClassArray<ON_PX_EVENT> events;
ON_Intersect(pts_3d.min, *curve3d, events, INTERSECTION_TOL);
ON_Intersect(pts_3d.mid, *curve3d, events, INTERSECTION_TOL);
ON_Intersect(pts_3d.max, *curve3d, events, INTERSECTION_TOL);
if (events.Count() != 3) {
throw AlgorithmError("points_3d_to_params_3d: conversion failed\n");
}
IntervalParams params_3d;
params_3d.min = events[0].m_b[0];
params_3d.mid = events[1].m_b[0];
params_3d.max = events[2].m_b[0];
return params_3d;
}
HIDDEN std::vector<ON_Interval>
interval_2d_to_3d(
const ON_Interval &interval,
const ON_Curve *curve2d,
const ON_Curve *curve3d,
const ON_Surface *surf)
{
std::vector<ON_Interval> intervals_3d;
ON_Interval c2_dom = curve2d->Domain();
ON_Interval c3_dom = curve3d->Domain();
c2_dom.MakeIncreasing();
if (ON_NearZero(interval.Min() - c2_dom.Min(), ON_ZERO_TOLERANCE) &&
ON_NearZero(interval.Max() - c2_dom.Max(), ON_ZERO_TOLERANCE))
{
// entire 2d domain equates to entire 3d domain
c3_dom.MakeIncreasing();
if (c3_dom.IsValid()) {
intervals_3d.push_back(c3_dom);
}
} else {
// get 2d curve interval points as uv points
IntervalPoints interval_uv =
interval_2d_to_uv(interval, curve2d, surf);
// evaluate surface at uv points to get 3d interval points
IntervalPoints pts_3d = points_uv_to_3d(interval_uv, surf);
// convert 3d points into 3d curve parameters
try {
std::vector<IntervalParams> int_params;
IntervalParams curve_t = points_3d_to_params_3d(pts_3d, curve3d);
if (curve3d->IsClosed()) {
// get 3d seam point as surf point
ON_3dPoint seam_pt = curve3d->PointAt(c3_dom.Min());
ON_ClassArray<ON_PX_EVENT> events;
ON_Intersect(seam_pt, *surf, events, INTERSECTION_TOL);
if (events.Count() == 1) {
ON_3dPoint surf_pt = events[0].m_b;
std::vector<double> split_t;
// get surf point as 2d curve t
events.Empty();
ON_Intersect(surf_pt, *curve2d, events, INTERSECTION_TOL);
if (events.Count() == 1) {
split_t.push_back(events[0].m_b[0]);
}
int surf_seam = IsAtSeam(surf, surf_pt, ON_ZERO_TOLERANCE);
if (surf_seam != SEAM_NONE) {
// move surf_pt to other side of seam
if (surf_seam == SEAM_ALONG_U || surf_seam == SEAM_ALONG_UV) {
ON_Interval vdom = surf->Domain(1);
if (ON_NearZero(surf_pt.y - vdom.Min(),
ON_ZERO_TOLERANCE)) {
surf_pt.y = vdom.Max();
} else {
surf_pt.y = vdom.Min();
}
}
if (surf_seam == SEAM_ALONG_V || surf_seam == SEAM_ALONG_UV) {
ON_Interval udom = surf->Domain(0);
if (ON_NearZero(surf_pt.x - udom.Min(),
ON_ZERO_TOLERANCE)) {
surf_pt.x = udom.Max();
} else {
surf_pt.x = udom.Min();
}
}
// get alternative surf point as 2d curve t
events.Empty();
ON_Intersect(surf_pt, *curve2d, events, INTERSECTION_TOL);
if (events.Count() == 1) {
split_t.push_back(events[0].m_b[0]);
}
}
// see if 3d curve seam point is in the 2d curve interval
for (size_t i = 0; i < split_t.size(); ++i) {
double min2split = fabs(curve_t.min - split_t[i]);
double max2split = fabs(curve_t.max - split_t[i]);
if (min2split > ON_ZERO_TOLERANCE ||
max2split > ON_ZERO_TOLERANCE)
{
// split 2d interval at seam point
std::pair<IntervalPoints, IntervalPoints> halves =
interval_2d_to_2uv(interval, curve2d, surf,
split_t[i]);
// convert new intervals to 3d curve intervals
IntervalPoints left_3d, right_3d;
IntervalParams left_t, right_t;
left_3d = points_uv_to_3d(halves.first, surf);
left_t = points_3d_to_params_3d(left_3d, curve3d);
int_params.push_back(left_t);
right_3d = points_uv_to_3d(halves.second, surf);
right_t = points_3d_to_params_3d(right_3d, curve3d);
int_params.push_back(right_t);
}
}
}
}
if (int_params.empty()) {
int_params.push_back(curve_t);
}
// get final 3d intervals
for (size_t i = 0; i < int_params.size(); ++i) {
curve_t = curve_interval_from_params(int_params[i], curve3d);
ON_Interval interval_3d(curve_t.min, curve_t.max);
if (interval_3d.IsValid()) {
intervals_3d.push_back(interval_3d);
}
}
} catch (AlgorithmError &e) {
bu_log("%s", e.what());
}
}
return intervals_3d;
}
// Convert parameter interval of a 3d curve into the equivalent parameter
// interval on a matching 2d face curve.
HIDDEN ON_Interval
interval_3d_to_2d(
const ON_Interval &interval,
const ON_Curve *curve2d,
const ON_Curve *curve3d,
const ON_BrepFace *face)
{
ON_Interval interval_2d;
ON_Interval whole_domain = curve3d->Domain();
whole_domain.MakeIncreasing();
if (ON_NearZero(interval.Min() - whole_domain.Min(), ON_ZERO_TOLERANCE) &&
ON_NearZero(interval.Max() - whole_domain.Max(), ON_ZERO_TOLERANCE))
{
interval_2d = curve2d->Domain();
interval_2d.MakeIncreasing();
} else {
const ON_Surface *surf = face->SurfaceOf();
IntervalPoints pts;
pts.min = curve3d->PointAt(interval.Min());
pts.mid = curve3d->PointAt(interval.Mid());
pts.max = curve3d->PointAt(interval.Max());
ON_ClassArray<ON_PX_EVENT> events;
ON_Intersect(pts.min, *surf, events, INTERSECTION_TOL);
ON_Intersect(pts.mid, *surf, events, INTERSECTION_TOL);
ON_Intersect(pts.max, *surf, events, INTERSECTION_TOL);
if (events.Count() == 3) {
IntervalPoints interval_uv;
interval_uv.min = events[0].m_b;
interval_uv.mid = events[1].m_b;
interval_uv.max = events[2].m_b;
interval_uv = uv_interval_from_points(interval_uv, surf);
// intersect surface uv parameters with 2d curve to convert
// surface uv parameters to 2d curve parameters
events.Empty();
ON_Intersect(interval_uv.min, *curve2d, events, INTERSECTION_TOL);
ON_Intersect(interval_uv.mid, *curve2d, events, INTERSECTION_TOL);
ON_Intersect(interval_uv.max, *curve2d, events, INTERSECTION_TOL);
if (events.Count() == 3) {
IntervalParams curve_t;
curve_t.min = events[0].m_b[0];
curve_t.mid = events[1].m_b[0];
curve_t.max = events[2].m_b[0];
curve_t = curve_interval_from_params(curve_t, curve2d);
interval_2d.Set(curve_t.min, curve_t.max);
}
}
}
return interval_2d;
}
HIDDEN void
get_subcurves_inside_faces(
ON_SimpleArray<ON_Curve *> &subcurves_on1,
ON_SimpleArray<ON_Curve *> &subcurves_on2,
const ON_Brep *brep1,
const ON_Brep *brep2,
int face_i1,
int face_i2,
ON_SSX_EVENT *event)
{
// The ON_SSX_EVENT from SSI is the intersection of two whole surfaces.
// We need to get the part that lies inside both trimmed patches.
// (brep1's face[face_i1] and brep2's face[face_i2])
ON_SimpleArray<ON_SSX_EVENT *> out;
if (event == NULL) {
return;
}
if (event->m_curve3d == NULL || event->m_curveA == NULL || event->m_curveB == NULL) {
return;
}
// get the face loops
if (face_i1 < 0 || face_i1 >= brep1->m_F.Count() || brep1->m_F[face_i1].m_li.Count() <= 0) {
bu_log("get_subcurves_inside_faces(): invalid face_i1 (%d).\n", face_i1);
return;
}
if (face_i2 < 0 || face_i2 >= brep2->m_F.Count() || brep2->m_F[face_i2].m_li.Count() <= 0) {
bu_log("get_subcurves_inside_faces(): invalid face_i2 (%d).\n", face_i2);
return;
}
const ON_SimpleArray<int> &face1_li = brep1->m_F[face_i1].m_li;
ON_ClassArray<ON_SimpleArray<ON_Curve *> > face1_loops;
for (int i = 0; i < face1_li.Count(); ++i) {
const ON_BrepLoop &brep_loop = brep1->m_L[face1_li[i]];
ON_SimpleArray<ON_Curve *> loop_curves;
for (int j = 0; j < brep_loop.m_ti.Count(); ++j) {
ON_Curve *trim2d =
brep1->m_C2[brep1->m_T[brep_loop.m_ti[j]].m_c2i];
loop_curves.Append(trim2d);
}
face1_loops.Append(loop_curves);
}
const ON_SimpleArray<int> &face2_li = brep2->m_F[face_i2].m_li;
ON_ClassArray<ON_SimpleArray<ON_Curve *> > face2_loops;
for (int i = 0; i < face2_li.Count(); ++i) {
const ON_BrepLoop &brep_loop = brep2->m_L[face2_li[i]];
ON_SimpleArray<ON_Curve *> loop_curves;
for (int j = 0; j < brep_loop.m_ti.Count(); ++j) {
ON_Curve *trim2d =
brep2->m_C2[brep2->m_T[brep_loop.m_ti[j]].m_c2i];
loop_curves.Append(trim2d);
}
face2_loops.Append(loop_curves);
}
// find the intervals of the curves that are inside/on each face
ON_SimpleArray<ON_Interval> intervals1, intervals2;
intervals1 = get_curve_intervals_inside_or_on_face(event->m_curveA,
face1_loops, INTERSECTION_TOL);
intervals2 = get_curve_intervals_inside_or_on_face(event->m_curveB,
face2_loops, INTERSECTION_TOL);
// get subcurves for each face
for (int i = 0; i < intervals1.Count(); ++i) {
// convert interval on face 1 to equivalent interval on face 2
std::vector<ON_Interval> intervals_3d;
intervals_3d = interval_2d_to_3d(intervals1[i], event->m_curveA,
event->m_curve3d, &brep1->m_F[face_i1]);
for (size_t j = 0; j < intervals_3d.size(); ++j) {
ON_Interval interval_on2 = interval_3d_to_2d(intervals_3d[j],
event->m_curveB, event->m_curve3d, &brep2->m_F[face_i2]);
if (interval_on2.IsValid()) {
// create subcurve from interval
try {
ON_Curve *subcurve_on2 = sub_curve(event->m_curveB,
interval_on2.Min(), interval_on2.Max());
subcurves_on2.Append(subcurve_on2);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
}
}
}
for (int i = 0; i < intervals2.Count(); ++i) {
// convert interval on face 1 to equivalent interval on face 2
std::vector<ON_Interval> intervals_3d;
intervals_3d = interval_2d_to_3d(intervals2[i], event->m_curveB,
event->m_curve3d, &brep2->m_F[face_i2]);
for (size_t j = 0; j < intervals_3d.size(); ++j) {
ON_Interval interval_on1 = interval_3d_to_2d(intervals_3d[j],
event->m_curveA, event->m_curve3d, &brep1->m_F[face_i1]);
if (interval_on1.IsValid()) {
// create subcurve from interval
try {
ON_Curve *subcurve_on1 = sub_curve(event->m_curveA,
interval_on1.Min(), interval_on1.Max());
subcurves_on1.Append(subcurve_on1);
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
}
}
}
}
HIDDEN double
bbox_diagonal_length(ON_Curve *curve)
{
double len = 0.0;
if (curve) {
ON_BoundingBox bbox;
if (curve->GetTightBoundingBox(bbox)) {
len = bbox.Diagonal().Length();
} else {
len = curve->PointAtStart().DistanceTo(curve->PointAtEnd());
}
}
return len;
}
HIDDEN void
split_curve(ON_Curve *&left, ON_Curve *&right, const ON_Curve *in, double t)
{
try {
left = sub_curve(in, in->Domain().m_t[0], t);
} catch (InvalidInterval &) {
left = NULL;
}
try {
right = sub_curve(in, t, in->Domain().m_t[1]);
} catch (InvalidInterval &) {
right = NULL;
}
}
HIDDEN double
configure_for_linking(
LinkedCurve *&first,
LinkedCurve *&second,
LinkedCurve &in1,
LinkedCurve &in2)
{
double dist_s1s2 = in1.PointAtStart().DistanceTo(in2.PointAtStart());
double dist_s1e2 = in1.PointAtStart().DistanceTo(in2.PointAtEnd());
double dist_e1s2 = in1.PointAtEnd().DistanceTo(in2.PointAtStart());
double dist_e1e2 = in1.PointAtEnd().DistanceTo(in2.PointAtEnd());
double min_dist = std::min(dist_s1s2, dist_s1e2);
min_dist = std::min(min_dist, dist_e1s2);
min_dist = std::min(min_dist, dist_e1e2);
first = second = NULL;
if (dist_s1e2 <= min_dist) {
first = &in2;
second = &in1;
} else if (dist_e1s2 <= min_dist) {
first = &in1;
second = &in2;
} else if (dist_s1s2 <= min_dist) {
if (in1.Reverse()) {
first = &in1;
second = &in2;
}
} else if (dist_e1e2 <= min_dist) {
if (in2.Reverse()) {
first = &in1;
second = &in2;
}
}
return min_dist;
}
struct LinkedCurveX {
int ssi_idx_a;
int ssi_idx_b;
ON_SimpleArray<ON_X_EVENT> events;
};
HIDDEN ON_ClassArray<LinkedCurve>
get_joinable_ssi_curves(const ON_SimpleArray<SSICurve> &in)
{
ON_SimpleArray<SSICurve> curves;
for (int i = 0; i < in.Count(); ++i) {
curves.Append(in[i]);
}
for (int i = 0; i < curves.Count(); ++i) {
if (curves[i].m_curve == NULL || curves[i].m_curve->IsClosed()) {
continue;
}
for (int j = i + 1; j < curves.Count(); j++) {
if (curves[j].m_curve == NULL || curves[j].m_curve->IsClosed()) {
continue;
}
ON_Curve *icurve = curves[i].m_curve;
ON_Curve *jcurve = curves[j].m_curve;
ON_SimpleArray<ON_X_EVENT> events;
ON_Intersect(icurve, jcurve, events, INTERSECTION_TOL);
if (events.Count() != 1) {
if (events.Count() > 1) {
bu_log("unexpected intersection between curves\n");
}
continue;
}
ON_X_EVENT event = events[0];
if (event.m_type == ON_X_EVENT::ccx_overlap) {
// curves from adjacent surfaces may overlap and have
// common endpoints, but we don't want the linked
// curve to double back on itself creating a
// degenerate section
ON_Interval dom[2], range[2];
dom[0] = icurve->Domain();
dom[1] = jcurve->Domain();
range[0].Set(event.m_a[0], event.m_a[1]);
range[1].Set(event.m_b[0], event.m_b[1]);
// overlap endpoints that are near the endpoints
// should be snapped to the endpoints
for (int k = 0; k < 2; ++k) {
dom[k].MakeIncreasing();
range[k].MakeIncreasing();
for (int l = 0; l < 2; ++l) {
if (ON_NearZero(dom[k].m_t[l] - range[k].m_t[l],
ON_ZERO_TOLERANCE)) {
range[k].m_t[l] = dom[k].m_t[l];
}
}
}
if (dom[0].Includes(range[0], true) ||
dom[1].Includes(range[1], true))
{
// overlap is in the middle of one or both curves
continue;
}
// if one curve is completely contained by the other,
// keep just the larger curve (or the first curve if
// they're the same)
if (dom[1] == range[1]) {
curves[j].m_curve = NULL;
continue;
}
if (dom[0] == range[0]) {
curves[i].m_curve = NULL;
continue;
}
// remove the overlapping portion from the end of one
// curve so the curves meet at just a single point
try {
double start = dom[0].m_t[0];
double end = range[0].m_t[0];
if (ON_NearZero(start - end, ON_ZERO_TOLERANCE)) {
start = range[0].m_t[1];
end = dom[0].m_t[1];
}
ON_Curve *isub = sub_curve(icurve, start, end);
delete curves[i].m_curve;
curves[i] = isub;
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
} else {
// For a single intersection, assume that one or both
// curve endpoints is just a little past where it
// should be. Split the curves at the intersection,
// and discard the portion with the smaller bbox
// diagonal.
ON_Curve *ileft, *iright, *jleft, *jright;
ileft = iright = jleft = jright = NULL;
split_curve(ileft, iright, icurve, event.m_a[0]);
split_curve(jleft, jright, jcurve, event.m_b[0]);
if (bbox_diagonal_length(ileft) <
bbox_diagonal_length(iright))
{
std::swap(ileft, iright);
}
ON_Curve *isub = ileft;
delete iright;
if (bbox_diagonal_length(jleft) <
bbox_diagonal_length(jright))
{
std::swap(jleft, jright);
}
ON_Curve *jsub = jleft;
delete jright;
if (isub && jsub) {
// replace the original ssi curves with the
// trimmed versions
curves[i].m_curve = isub;
curves[j].m_curve = jsub;
isub = jsub = NULL;
}
delete isub;
delete jsub;
}
}
}
ON_ClassArray<LinkedCurve> out;
for (int i = 0; i < curves.Count(); ++i) {
if (curves[i].m_curve != NULL) {
LinkedCurve linked;
linked.Append(curves[i]);
out.Append(linked);
}
}
return out;
}
HIDDEN ON_ClassArray<LinkedCurve>
link_curves(const ON_SimpleArray<SSICurve> &in)
{
// There might be two reasons why we need to link these curves.
// 1) They are from intersections with two different surfaces.
// 2) They are not continuous in the other surface's UV domain.
ON_ClassArray<LinkedCurve> tmp = get_joinable_ssi_curves(in);
// As usual, we use a greedy approach.
for (int i = 0; i < tmp.Count(); i++) {
for (int j = 0; j < tmp.Count(); j++) {
if (tmp[i].m_ssi_curves.Count() == 0 || tmp[i].IsClosed()) {
break;
}
if (tmp[j].m_ssi_curves.Count() == 0 || tmp[j].IsClosed() || j == i) {
continue;
}
LinkedCurve *c1 = NULL, *c2 = NULL;
double dist = configure_for_linking(c1, c2, tmp[i], tmp[j]);
if (dist > INTERSECTION_TOL) {
continue;
}
if (c1 != NULL && c2 != NULL) {
LinkedCurve new_curve;
new_curve.Append(*c1);
if (dist > ON_ZERO_TOLERANCE) {
new_curve.Append(SSICurve(new ON_LineCurve(c1->PointAtEnd(), c2->PointAtStart())));
}
new_curve.Append(*c2);
tmp[i] = new_curve;
tmp[j].m_ssi_curves.Empty();
}
// Check whether tmp[i] is closed within a tolerance
if (tmp[i].PointAtStart().DistanceTo(tmp[i].PointAtEnd()) < INTERSECTION_TOL && !tmp[i].IsClosed()) {
// make IsClosed() true
tmp[i].Append(SSICurve(new ON_LineCurve(tmp[i].PointAtEnd(), tmp[i].PointAtStart())));
}
}
}
// Append the remaining curves to out.
ON_ClassArray<LinkedCurve> out;
for (int i = 0; i < tmp.Count(); i++) {
if (tmp[i].m_ssi_curves.Count() != 0) {
out.Append(tmp[i]);
}
}
if (DEBUG_BREP_BOOLEAN) {
bu_log("link_curves(): %d curves remaining.\n", out.Count());
}
return out;
}
class CurvePoint {
public:
int source_loop;
int loop_index;
double curve_t;
ON_2dPoint pt;
enum Location {
BOUNDARY,
INSIDE,
OUTSIDE
} location;
static CurvePoint::Location
PointLoopLocation(ON_2dPoint pt, const ON_SimpleArray<ON_Curve *> &loop);
CurvePoint(
int loop,
int li,
double pt_t,
ON_Curve *curve,
const ON_SimpleArray<ON_Curve *> &other_loop)
: source_loop(loop), loop_index(li), curve_t(pt_t)
{
pt = curve->PointAt(curve_t);
location = PointLoopLocation(pt, other_loop);
}
CurvePoint(
int loop,
int li,
double t,
ON_2dPoint p,
CurvePoint::Location l)
: source_loop(loop), loop_index(li), curve_t(t), pt(p), location(l)
{
}
bool
operator<(const CurvePoint &other) const
{
// for points not on the same loop, compare the actual points
if (source_loop != other.source_loop) {
if (ON_NearZero(pt.DistanceTo(other.pt), INTERSECTION_TOL)) {
return false;
}
return pt < other.pt;
}
// for points on the same loop, compare loop position
if (loop_index == other.loop_index) {
if (ON_NearZero(curve_t - other.curve_t, INTERSECTION_TOL)) {
return false;
}
return curve_t < other.curve_t;
}
return loop_index < other.loop_index;
}
bool
operator==(const CurvePoint &other) const
{
return ON_NearZero(pt.DistanceTo(other.pt), INTERSECTION_TOL);
}
bool
operator!=(const CurvePoint &other) const
{
return !ON_NearZero(pt.DistanceTo(other.pt), INTERSECTION_TOL);
}
};
class CurvePointAbsoluteCompare {
public:
bool
operator()(const CurvePoint &a, const CurvePoint &b) const
{
if (ON_NearZero(a.pt.DistanceTo(b.pt), INTERSECTION_TOL)) {
return false;
}
return a.pt < b.pt;
}
};
CurvePoint::Location
CurvePoint::PointLoopLocation(
ON_2dPoint point,
const ON_SimpleArray<ON_Curve *> &loop)
{
if (is_point_on_loop(point, loop)) {
return CurvePoint::BOUNDARY;
}
if (point_loop_location(point, loop) == OUTSIDE_OR_ON_LOOP) {
return CurvePoint::OUTSIDE;
}
return CurvePoint::INSIDE;
}
class CurveSegment {
public:
ON_SimpleArray<ON_Curve *> orig_loop;
CurvePoint from, to;
enum Location {
BOUNDARY,
INSIDE,
OUTSIDE
} location;
CurveSegment(
ON_SimpleArray<ON_Curve *> &loop,
CurvePoint f,
CurvePoint t,
CurveSegment::Location l)
: orig_loop(loop), from(f), to(t), location(l)
{
if (!orig_loop.Capacity()) {
size_t c = (from.loop_index > to.loop_index) ? from.loop_index : to.loop_index;
orig_loop.SetCapacity(c + 1);
}
}
void
Reverse(void)
{
std::swap(from, to);
}
ON_Curve *
Curve(void) const
{
ON_Curve *from_curve = orig_loop[from.loop_index];
ON_Curve *to_curve = orig_loop[to.loop_index];
ON_Interval from_dom = from_curve->Domain();
ON_Interval to_dom = to_curve->Domain();
// if endpoints are on the same curve, just get the part between them
if (from.loop_index == to.loop_index) {
ON_Curve *seg_curve =
sub_curve(from_curve, from.curve_t, to.curve_t);
return seg_curve;
}
// if endpoints are on different curves, we may need a subcurve of
// just the 'from' curve, just the 'to' curve, or both
if (ON_NearZero(from.curve_t - from_dom.m_t[1], INTERSECTION_TOL)) {
// starting at end of 'from' same as starting at start of 'to'
ON_Curve *seg_curve = sub_curve(to_curve, to_dom.m_t[0],
to.curve_t);
return seg_curve;
}
if (ON_NearZero(to.curve_t - to_dom.m_t[0], INTERSECTION_TOL)) {
// ending at start of 'to' same as ending at end of 'from'
ON_Curve *seg_curve = sub_curve(from_curve, from.curve_t,
from_dom.m_t[1]);
return seg_curve;
}
ON_PolyCurve *pcurve = new ON_PolyCurve();
append_to_polycurve(sub_curve(from_curve, from.curve_t,
from_dom.m_t[1]), *pcurve);
append_to_polycurve(sub_curve(to_curve, to_dom.m_t[0], to.curve_t),
*pcurve);
return pcurve;
}
bool
IsDegenerate(void)
{
ON_Curve *seg_curve = NULL;
try {
seg_curve = Curve();
} catch (InvalidInterval &) {
return true;
}
double length = 0.0;
if (seg_curve->IsLinear(INTERSECTION_TOL)) {
length = seg_curve->PointAtStart().DistanceTo(
seg_curve->PointAtEnd());
} else {
double min[3] = {0.0, 0.0, 0.0};
double max[3] = {0.0, 0.0, 0.0};
seg_curve->GetBBox(min, max, true);
length = DIST_PNT_PNT(min, max);
}
delete seg_curve;
return length < INTERSECTION_TOL;
}
bool
operator<(const CurveSegment &other) const
{
return from < other.from;
}
};
class LoopBooleanResult {
public:
std::vector<ON_SimpleArray<ON_Curve *> > outerloops;
std::vector<ON_SimpleArray<ON_Curve *> > innerloops;
void ClearOuterloops() {
for (size_t i = 0; i < outerloops.size(); ++i) {
for (int j = 0; j < outerloops[i].Count(); ++j) {
delete outerloops[i][j];
}
}
}
void ClearInnerloops() {
for (size_t i = 0; i < innerloops.size(); ++i) {
for (int j = 0; j < innerloops[i].Count(); ++j) {
delete innerloops[i][j];
}
}
}
};
#define LOOP_DIRECTION_CCW 1
#define LOOP_DIRECTION_CW -1
#define LOOP_DIRECTION_NONE 0
HIDDEN bool
close_small_gap(ON_SimpleArray<ON_Curve *> &loop, int curr, int next)
{
ON_3dPoint end_curr = loop[curr]->PointAtEnd();
ON_3dPoint start_next = loop[next]->PointAtStart();
double gap = end_curr.DistanceTo(start_next);
if (gap <= INTERSECTION_TOL && gap >= ON_ZERO_TOLERANCE) {
ON_Curve *closing_seg = new ON_LineCurve(end_curr, start_next);
loop.Insert(next, closing_seg);
return true;
}
return false;
}
HIDDEN void
close_small_gaps(ON_SimpleArray<ON_Curve *> &loop)
{
if (loop.Count() == 0) {
return;
}
for (int i = 0; i < loop.Count() - 1; ++i) {
if (close_small_gap(loop, i, i + 1)) {
++i;
}
}
close_small_gap(loop, loop.Count() - 1, 0);
}
ON_Curve *
get_loop_curve(const ON_SimpleArray<ON_Curve *> &loop)
{
ON_PolyCurve *pcurve = new ON_PolyCurve();
for (int i = 0; i < loop.Count(); ++i) {
append_to_polycurve(loop[i]->Duplicate(), *pcurve);
}
return pcurve;
}
std::list<ON_SimpleArray<ON_Curve *> >::iterator
find_innerloop(std::list<ON_SimpleArray<ON_Curve *> > &loops)
{
std::list<ON_SimpleArray<ON_Curve *> >::iterator k;
for (k = loops.begin(); k != loops.end(); ++k) {
ON_Curve *loop_curve = get_loop_curve(*k);
if (ON_ClosedCurveOrientation(*loop_curve, NULL) == LOOP_DIRECTION_CW) {
delete loop_curve;
return k;
}
delete loop_curve;
}
return loops.end();
}
bool
set_loop_direction(ON_SimpleArray<ON_Curve *> &loop, int dir)
{
ON_Curve *curve = get_loop_curve(loop);
int curr_dir = ON_ClosedCurveOrientation(*curve, NULL);
delete curve;
if (curr_dir == LOOP_DIRECTION_NONE) {
// can't set the correct direction
return false;
}
if (curr_dir != dir) {
// need reverse
for (int i = 0; i < loop.Count(); ++i) {
if (!loop[i]->Reverse()) {
return false;
}
}
loop.Reverse();
}
// curve already has the correct direction
return true;
}
void
add_point_to_set(std::multiset<CurvePoint> &set, CurvePoint pt)
{
if (set.count(pt) < 2) {
set.insert(pt);
}
}
std::multiset<CurveSegment>
make_segments(
std::multiset<CurvePoint> &curve1_points,
ON_SimpleArray<ON_Curve *> &loop1,
ON_SimpleArray<ON_Curve *> &loop2)
{
std::multiset<CurveSegment> out;
std::multiset<CurvePoint>::iterator first = curve1_points.begin();
std::multiset<CurvePoint>::iterator curr = first;
std::multiset<CurvePoint>::iterator next = ++curve1_points.begin();
for (; next != curve1_points.end(); ++curr, ++next) {
CurvePoint from = *curr;
CurvePoint to = *next;
CurveSegment new_seg(loop1, from, to, CurveSegment::BOUNDARY);
if (new_seg.IsDegenerate()) {
continue;
}
if (from.location == CurvePoint::BOUNDARY &&
to.location == CurvePoint::BOUNDARY)
{
ON_Curve *seg_curve = loop1[from.loop_index];
double end_t = to.curve_t;
if (from.loop_index != to.loop_index) {
end_t = seg_curve->Domain().m_t[1];
}
ON_2dPoint seg_midpt = seg_curve->PointAt(
ON_Interval(from.curve_t, end_t).Mid());
CurvePoint::Location midpt_location =
CurvePoint::PointLoopLocation(seg_midpt, loop2);
if (midpt_location == CurvePoint::INSIDE) {
new_seg.location = CurveSegment::INSIDE;
} else if (midpt_location == CurvePoint::OUTSIDE) {
new_seg.location = CurveSegment::OUTSIDE;
}
} else if (from.location == CurvePoint::INSIDE ||
to.location == CurvePoint::INSIDE)
{
new_seg.location = CurveSegment::INSIDE;
} else if (from.location == CurvePoint::OUTSIDE ||
to.location == CurvePoint::OUTSIDE)
{
new_seg.location = CurveSegment::OUTSIDE;
}
out.insert(new_seg);
}
return out;
}
void
set_append_segment(
std::multiset<CurveSegment> &out,
const CurveSegment &seg)
{
std::multiset<CurveSegment>::iterator i;
for (i = out.begin(); i != out.end(); ++i) {
if ((i->from == seg.to) && (i->to == seg.from)) {
// if this segment is a reversed version of an existing
// segment, it cancels the existing segment out
ON_Curve *prev_curve = i->Curve();
ON_Curve *seg_curve = seg.Curve();
ON_SimpleArray<ON_X_EVENT> events;
ON_Intersect(prev_curve, seg_curve, events, INTERSECTION_TOL);
if (events.Count() == 1 && events[0].m_type == ON_X_EVENT::ccx_overlap) {
out.erase(i);
return;
}
}
}
out.insert(seg);
}
void
set_append_segments_at_location(
std::multiset<CurveSegment> &out,
std::multiset<CurveSegment> &in,
CurveSegment::Location location,
bool reversed_segs_cancel)
{
std::multiset<CurveSegment>::iterator i;
if (reversed_segs_cancel) {
for (i = in.begin(); i != in.end(); ++i) {
if (i->location == location) {
set_append_segment(out, *i);
}
}
} else {
for (i = in.begin(); i != in.end(); ++i) {
if (i->location == location) {
out.insert(*i);
}
}
}
}
std::multiset<CurveSegment>
find_similar_segments(
std::multiset<CurveSegment> &set,
const CurveSegment &seg)
{
std::multiset<CurveSegment> out;
std::multiset<CurveSegment>::iterator i;
for (i = set.begin(); i != set.end(); ++i) {
if (((i->from == seg.from) && (i->to == seg.to)) ||
((i->from == seg.to) && (i->to == seg.from)))
{
out.insert(*i);
}
}
return out;
}
HIDDEN std::multiset<CurveSegment>
get_op_segments(
std::multiset<CurveSegment> &curve1_segments,
std::multiset<CurveSegment> &curve2_segments,
op_type op)
{
std::multiset<CurveSegment> out;
std::multiset<CurveSegment> c1_boundary_segs;
set_append_segments_at_location(c1_boundary_segs, curve1_segments,
CurveSegment::BOUNDARY, false);
std::multiset<CurveSegment> c2_boundary_segs;
set_append_segments_at_location(c2_boundary_segs, curve2_segments,
CurveSegment::BOUNDARY, false);
if (op == BOOLEAN_INTERSECT) {
set_append_segments_at_location(out, curve1_segments,
CurveSegment::INSIDE, true);
set_append_segments_at_location(out, curve2_segments,
CurveSegment::INSIDE, true);
std::multiset<CurveSegment>::iterator i;
for (i = c1_boundary_segs.begin(); i != c1_boundary_segs.end(); ++i) {
std::multiset<CurveSegment> curve1_matches =
find_similar_segments(c1_boundary_segs, *i);
std::multiset<CurveSegment> curve2_matches =
find_similar_segments(c2_boundary_segs, *i);
if (curve1_matches.size() > 1 || curve2_matches.size() > 1) {
continue;
}
if (curve1_matches.begin()->from == curve2_matches.begin()->from) {
out.insert(*i);
}
}
} else if (op == BOOLEAN_DIFF) {
set_append_segments_at_location(out, curve1_segments,
CurveSegment::OUTSIDE, true);
set_append_segments_at_location(out, curve2_segments,
CurveSegment::INSIDE, true);
std::multiset<CurveSegment>::iterator i;
for (i = c1_boundary_segs.begin(); i != c1_boundary_segs.end(); ++i) {
std::multiset<CurveSegment> curve1_matches =
find_similar_segments(c1_boundary_segs, *i);
std::multiset<CurveSegment> curve2_matches =
find_similar_segments(c2_boundary_segs, *i);
if (curve1_matches.size() > 1) {
continue;
}
if (curve1_matches.begin()->from == curve2_matches.begin()->from ||
curve2_matches.size() > 1)
{
out.insert(*i);
}
}
} else if (op == BOOLEAN_UNION) {
set_append_segments_at_location(out, curve1_segments,
CurveSegment::OUTSIDE, true);
set_append_segments_at_location(out, curve2_segments,
CurveSegment::OUTSIDE, true);
std::multiset<CurveSegment>::iterator i;
for (i = c1_boundary_segs.begin(); i != c1_boundary_segs.end(); ++i) {
std::multiset<CurveSegment> curve1_matches =
find_similar_segments(c1_boundary_segs, *i);
std::multiset<CurveSegment> curve2_matches =
find_similar_segments(c2_boundary_segs, *i);
if (curve1_matches.size() > 1 && curve2_matches.size() > 1) {
continue;
}
std::multiset<CurveSegment>::iterator a, b;
for (a = curve1_matches.begin(); a != curve1_matches.end(); ++a) {
b = curve2_matches.begin();
for (; b != curve2_matches.end(); ++b) {
if (a->from == b->from) {
out.insert(*i);
}
}
}
}
}
return out;
}
std::list<ON_SimpleArray<ON_Curve *> >
construct_loops_from_segments(
std::multiset<CurveSegment> &segments)
{
std::list<ON_SimpleArray<ON_Curve *> > out;
while (!segments.empty()) {
std::vector<std::multiset<CurveSegment>::iterator> loop_segs;
std::multiset<CurvePoint, CurvePointAbsoluteCompare> visited_points;
std::multiset<CurveSegment>::iterator curr_seg, prev_seg;
curr_seg = segments.begin();
loop_segs.push_back(curr_seg);
visited_points.insert(curr_seg->from);
visited_points.insert(curr_seg->to);
bool closed_curve = (curr_seg->from == curr_seg->to);
while (!closed_curve) {
// look for a segment that connects to the previous
prev_seg = curr_seg;
for (curr_seg = segments.begin(); curr_seg != segments.end(); ++curr_seg) {
if (curr_seg->from == prev_seg->to) {
break;
}
}
if (curr_seg == segments.end()) {
// no segment connects to the prev one
break;
} else {
// Extend our loop with the joining segment.
// If we've visited its endpoint before, then the loop
// is now closed.
loop_segs.push_back(curr_seg);
visited_points.insert(curr_seg->to);
closed_curve = (visited_points.count(curr_seg->to) > 1);
}
}
if (closed_curve) {
// find the segment the closing segment connected to (it
// may not be the first segment)
size_t i;
for (i = 0; i < loop_segs.size(); ++i) {
if (loop_segs[i]->from == loop_segs.back()->to) {
break;
}
}
// Form a curve from the closed chain of segments.
// Remove the used segments from the available set.
ON_SimpleArray<ON_Curve *> loop;
for (; i < loop_segs.size(); ++i) {
try {
loop.Append(loop_segs[i]->Curve());
} catch (InvalidInterval &e) {
bu_log("%s", e.what());
}
segments.erase(loop_segs[i]);
}
out.push_back(loop);
} else {
// couldn't join to the last segment, discard it
segments.erase(loop_segs.back());
bu_log("construct_loops_from_segments: found unconnected segment\n");
}
loop_segs.clear();
visited_points.clear();
}
return out;
}
std::multiset<CurvePoint>
get_loop_points(
int source_loop,
ON_SimpleArray<ON_Curve *> loop1,
ON_SimpleArray<ON_Curve *> loop2)
{
std::multiset<CurvePoint> out;
if (loop1.Count() <= 0)
return out;
ON_Curve *loop1_seg = loop1[0];
out.insert(CurvePoint(source_loop, 0, loop1_seg->Domain().m_t[0], loop1_seg,
loop2));
for (int i = 0; i < loop1.Count(); ++i) {
loop1_seg = loop1[i];
out.insert(CurvePoint(source_loop, i, loop1_seg->Domain().m_t[1],
loop1_seg, loop2));
}
return out;
}
// separate outerloops and innerloops
HIDDEN LoopBooleanResult
make_result_from_loops(const std::list<ON_SimpleArray<ON_Curve *> > &loops)
{
LoopBooleanResult out;
std::list<ON_SimpleArray<ON_Curve *> >::const_iterator li;
for (li = loops.begin(); li != loops.end(); ++li) {
ON_Curve *loop_curve = get_loop_curve(*li);
int dir = ON_ClosedCurveOrientation(*loop_curve, NULL);
if (dir == LOOP_DIRECTION_CCW) {
out.outerloops.push_back(*li);
} else if (dir == LOOP_DIRECTION_CW) {
out.innerloops.push_back(*li);
}
delete loop_curve;
}
return out;
}
// Get the result of a boolean combination of two loops. Based on the
// algorithm from this paper:
//
// Margalit, Avraham and Gary D. Knott. 1989. "An Algorithm for
// Computing the Union, Intersection or Difference of two Polygons."
// Computers & Graphics 13:167-183.
//
// gvu.gatech.edu/people/official/jarek/graphics/papers/04PolygonBooleansMargalit.pdf
LoopBooleanResult
loop_boolean(
const ON_SimpleArray<ON_Curve *> &l1,
const ON_SimpleArray<ON_Curve *> &l2,
op_type op)
{
LoopBooleanResult out;
if (op != BOOLEAN_INTERSECT &&
op != BOOLEAN_DIFF &&
op != BOOLEAN_UNION)
{
bu_log("loop_boolean: unsupported operation\n");
return out;
}
if (l1.Count() <= 0 || l2.Count() <= 0) {
bu_log("loop_boolean: one or more empty loops\n");
return out;
}
// copy input loops
ON_SimpleArray<ON_Curve *> loop1, loop2;
for (int i = 0; i < l1.Count(); ++i) {
loop1.Append(l1[i]->Duplicate());
}
for (int i = 0; i < l2.Count(); ++i) {
loop2.Append(l2[i]->Duplicate());
}
// set curve directions based on operation
int loop1_dir, loop2_dir;
loop1_dir = loop2_dir = LOOP_DIRECTION_CCW;
if (op == BOOLEAN_DIFF) {
loop2_dir = LOOP_DIRECTION_CW;
}
if (!set_loop_direction(loop1, loop1_dir) ||
!set_loop_direction(loop2, loop2_dir))
{
bu_log("loop_boolean: couldn't standardize curve directions\n");
for (int i = 0; i < l1.Count(); ++i) {
delete loop1[i];
}
for (int i = 0; i < l2.Count(); ++i) {
delete loop2[i];
}
return out;
}
// get curve endpoints and intersection points for each loop
std::multiset<CurvePoint> loop1_points, loop2_points;
loop1_points = get_loop_points(1, loop1, loop2);
loop2_points = get_loop_points(2, loop2, loop1);
for (int i = 0; i < loop1.Count(); ++i) {
for (int j = 0; j < loop2.Count(); ++j) {
ON_SimpleArray<ON_X_EVENT> x_events;
ON_Intersect(loop1[i], loop2[j], x_events, INTERSECTION_TOL);
for (int k = 0; k < x_events.Count(); ++k) {
add_point_to_set(loop1_points, CurvePoint(1, i,
x_events[k].m_a[0], x_events[k].m_A[0],
CurvePoint::BOUNDARY));
add_point_to_set(loop2_points, CurvePoint(2, j,
x_events[k].m_b[0], x_events[k].m_B[0],
CurvePoint::BOUNDARY));
if (x_events[k].m_type == ON_X_EVENT::ccx_overlap) {
add_point_to_set(loop1_points, CurvePoint(1, i,
x_events[k].m_a[1], x_events[k].m_A[1],
CurvePoint::BOUNDARY));
add_point_to_set(loop2_points, CurvePoint(2, j,
x_events[k].m_b[1], x_events[k].m_B[1],
CurvePoint::BOUNDARY));
}
}
}
}
// classify segments and determine which belong in the result
std::multiset<CurveSegment> loop1_segments, loop2_segments;
loop1_segments = make_segments(loop1_points, loop1, loop2);
loop2_segments = make_segments(loop2_points, loop2, loop1);
std::multiset<CurveSegment> out_segments =
get_op_segments(loop1_segments, loop2_segments, op);
// build result
std::list<ON_SimpleArray<ON_Curve *> > new_loops;
new_loops = construct_loops_from_segments(out_segments);
for (int i = 0; i < l1.Count(); ++i) {
delete loop1[i];
}
for (int i = 0; i < l2.Count(); ++i) {
delete loop2[i];
}
std::list<ON_SimpleArray<ON_Curve *> >::iterator li;
for (li = new_loops.begin(); li != new_loops.end(); ++li) {
close_small_gaps(*li);
}
out = make_result_from_loops(new_loops);
return out;
}
std::list<ON_SimpleArray<ON_Curve *> >
innerloops_inside_outerloop(
const ON_SimpleArray<ON_Curve *> &outerloop_curve,
const std::vector<ON_SimpleArray<ON_Curve *> > &innerloop_curves)
{
std::list<ON_SimpleArray<ON_Curve *> > out;
for (size_t i = 0; i < innerloop_curves.size(); ++i) {
LoopBooleanResult new_loops;
new_loops = loop_boolean(outerloop_curve, innerloop_curves[i],
BOOLEAN_INTERSECT);
// grab outerloops
for (size_t j = 0; j < new_loops.outerloops.size(); ++j) {
set_loop_direction(new_loops.outerloops[j], LOOP_DIRECTION_CW);
out.push_back(new_loops.outerloops[j]);
}
new_loops.ClearInnerloops();
}
return out;
}
TrimmedFace *
make_face_from_loops(
const TrimmedFace *orig_face,
const ON_SimpleArray<ON_Curve *> &outerloop,
const std::vector<ON_SimpleArray<ON_Curve *> > &innerloops)
{
TrimmedFace *face = new TrimmedFace();
face->m_face = orig_face->m_face;
face->m_outerloop.Append(outerloop.Count(), outerloop.Array());
// TODO: the innerloops found here can't be inside any other
// outerloop, and should be removed from the innerloop set in the
// interest of efficiency
std::list<ON_SimpleArray<ON_Curve *> > new_innerloops;
new_innerloops = innerloops_inside_outerloop(outerloop, innerloops);
std::list<ON_SimpleArray<ON_Curve *> >::iterator i;
for (i = new_innerloops.begin(); i != new_innerloops.end(); ++i) {
face->m_innerloop.push_back(*i);
}
return face;
}
HIDDEN LoopBooleanResult
combine_loops(
const TrimmedFace *orig_face,
const LoopBooleanResult &new_loops)
{
// Intersections always produce a single outerloop.
//
// Subtractions may produce multiple outerloops, or a single
// outerloop that optionally includes a single innerloop.
//
// So, the possible results are:
// 1) Single outerloop.
// 2) Multiple outerloops.
// 3) Single outerloop with single innerloop.
// First we'll combine the old and new innerloops.
std::vector<ON_SimpleArray<ON_Curve *> > merged_innerloops;
if (new_loops.innerloops.size() == 1) {
// If the result has an innerloop, it may overlap any of the
// original innerloops. We'll union all overlapping loops with
// the new innerloop.
ON_SimpleArray<ON_Curve *> candidate_innerloop(new_loops.innerloops[0]);
for (size_t i = 0; i < orig_face->m_innerloop.size(); ++i) {
LoopBooleanResult merged = loop_boolean(candidate_innerloop,
orig_face->m_innerloop[i], BOOLEAN_UNION);
if (merged.outerloops.size() == 1) {
candidate_innerloop = merged.outerloops[0];
} else {
merged_innerloops.push_back(orig_face->m_innerloop[i]);
merged.ClearOuterloops();
}
}
merged_innerloops.push_back(candidate_innerloop);
} else if (!orig_face->m_innerloop.empty()) {
for (size_t i = 0; i < orig_face->m_innerloop.size(); ++i) {
merged_innerloops.push_back(orig_face->m_innerloop[i]);
}
}
// Next we'll attempt to subtract all merged innerloops from each
// new outerloop to get the final set of loops. For each
// subtraction, there are four possibilities:
// 1) The innerloop is outside the outerloop, and the result is
// the original outerloop.
// 2) The innerloop completely encloses the outerloop, and the
// result is empty.
// 3) The innerloop is completely contained by the outerloop, and
// the result is the input outerloop and innerloop.
// 4) The innerloop overlaps the outerloop, and the result is one
// or more outerloops.
LoopBooleanResult out;
for (size_t i = 0; i < new_loops.outerloops.size(); ++i) {
std::list<ON_SimpleArray<ON_Curve *> >::iterator part, next_part;
std::list<ON_SimpleArray<ON_Curve *> > outerloop_parts;
// start with the original outerloop
outerloop_parts.push_back(new_loops.outerloops[i]);
// attempt to subtract all innerloops from it, and from
// whatever subparts of it are created along the way
for (size_t j = 0; j < merged_innerloops.size(); ++j) {
part = outerloop_parts.begin();
for (; part != outerloop_parts.end(); part = next_part) {
LoopBooleanResult diffed = loop_boolean(*part,
merged_innerloops[j], BOOLEAN_DIFF);
next_part = part;
++next_part;
if (diffed.innerloops.size() == 1) {
// The outerloop part contains the innerloop, so
// the innerloop belongs in the final set.
//
// Note that any innerloop added here will remains
// completely inside an outerloop part even if the
// part list changes. In order for a subsequent
// subtraction to put any part of it outside an
// outerloop, that later innerloop would have to
// overlap this one, in which case, the innerloops
// would have been unioned together in the
// previous merging step.
out.innerloops.push_back(diffed.innerloops[0]);
} else {
// outerloop part has been erased, modified, or
// split, so we need to remove it
for (int k = 0; k < part->Count(); ++k) {
delete (*part)[k];
}
outerloop_parts.erase(part);
// add any new parts for subsequent subtractions
for (size_t k = 0; k < diffed.outerloops.size(); ++k) {
outerloop_parts.push_front(diffed.outerloops[k]);
}
}
}
}
// whatever parts of the outerloop that remain after
// subtracting all innerloops belong in the final set
part = outerloop_parts.begin();
for (; part != outerloop_parts.end(); ++part) {
out.outerloops.push_back(*part);
}
}
return out;
// Only thing left to do is make a face from each outerloop. If
// one of the innerloops is inside the outerloop, make it part of
// the face and remove it for consideration for other faces.
}
HIDDEN void
append_faces_from_loops(
ON_SimpleArray<TrimmedFace *> &out,
const TrimmedFace *orig_face,
const LoopBooleanResult &new_loops)
{
std::vector<TrimmedFace *> o;
LoopBooleanResult combined_loops = combine_loops(orig_face, new_loops);
// make a face from each outerloop, using appropriate innerloops
for (size_t i = 0; i < combined_loops.outerloops.size(); ++i) {
o.push_back(make_face_from_loops(orig_face,
combined_loops.outerloops[i],
combined_loops.innerloops));
}
for (size_t i = 0; i < o.size(); i++) {
out.Append(o[i]);
}
}
/* Turn an open curve into a closed curve by using segments from the
* face outerloop to connect its endpoints.
*
* Returns false on failure, true otherwise.
*/
std::vector<ON_SimpleArray<ON_Curve *> >
split_face_into_loops(
const TrimmedFace *orig_face,
LinkedCurve &linked_curve)
{
std::vector<ON_SimpleArray<ON_Curve *> > out;
if (linked_curve.IsClosed()) {
ON_SimpleArray<ON_Curve *> loop;
for (int i = 0; i < orig_face->m_outerloop.Count(); ++i) {
loop.Append(orig_face->m_outerloop[i]->Duplicate());
}
out.push_back(loop);
return out;
}
/* We followed the algorithms described in:
* S. Krishnan, A. Narkhede, and D. Manocha. BOOLE: A System to Compute
* Boolean Combinations of Sculptured Solids. Technical Report TR95-008,
* Department of Computer Science, University of North Carolina, 1995.
* Appendix B: Partitioning a Simple Polygon using Non-Intersecting
* Chains.
*/
// Get the intersection points between the SSI curves and the outerloop.
ON_SimpleArray<IntersectPoint> clx_points;
bool intersects_outerloop = false;
for (int i = 0; i < orig_face->m_outerloop.Count(); i++) {
ON_SimpleArray<ON_X_EVENT> x_events;
ON_Intersect(orig_face->m_outerloop[i], linked_curve.Curve(),
x_events, INTERSECTION_TOL);
for (int j = 0; j < x_events.Count(); j++) {
IntersectPoint tmp_pt;
tmp_pt.m_pt = x_events[j].m_A[0];
tmp_pt.m_seg_t = x_events[j].m_a[0];
tmp_pt.m_curve_t = x_events[j].m_b[0];
tmp_pt.m_loop_seg = i;
clx_points.Append(tmp_pt);
if (x_events[j].m_type == ON_X_EVENT::ccx_overlap) {
tmp_pt.m_pt = x_events[j].m_A[1];
tmp_pt.m_seg_t = x_events[j].m_a[1];
tmp_pt.m_curve_t = x_events[j].m_b[1];
clx_points.Append(tmp_pt);
}
if (x_events.Count()) {
intersects_outerloop = true;
}
}
}
// can't close curves that don't partition the face
if (!intersects_outerloop || clx_points.Count() < 2) {
ON_SimpleArray<ON_Curve *> loop;
for (int i = 0; i < orig_face->m_outerloop.Count(); ++i) {
loop.Append(orig_face->m_outerloop[i]->Duplicate());
}
out.push_back(loop);
return out;
}
// rank these intersection points
clx_points.QuickSort(curve_t_compare);
for (int i = 0; i < clx_points.Count(); i++) {
clx_points[i].m_curve_pos = i;
}
// classify intersection points
ON_SimpleArray<IntersectPoint> new_pts;
double curve_min_t = linked_curve.Domain().Min();
double curve_max_t = linked_curve.Domain().Max();
for (int i = 0; i < clx_points.Count(); i++) {
bool is_first_ipt = (i == 0);
bool is_last_ipt = (i == (clx_points.Count() - 1));
IntersectPoint *ipt = &clx_points[i];
double curve_t = ipt->m_curve_t;
ON_3dPoint prev = linked_curve.PointAtStart();
if (!is_first_ipt) {
double prev_curve_t = clx_points[i - 1].m_curve_t;
prev = linked_curve.PointAt((curve_t + prev_curve_t) * .5);
}
ON_3dPoint next = linked_curve.PointAtEnd();
if (!is_last_ipt) {
double next_curve_t = clx_points[i + 1].m_curve_t;
next = linked_curve.PointAt((curve_t + next_curve_t) * .5);
}
// If the point is on the boundary, we treat it with the same
// way as it's outside.
// For example, the prev side is inside, and the next's on
// boundary, that point should be IntersectPoint::OUT, the
// same as the next's outside the loop.
// Other cases are similar.
bool prev_in, next_in;
try {
prev_in = is_point_inside_loop(prev, orig_face->m_outerloop);
next_in = is_point_inside_loop(next, orig_face->m_outerloop);
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
// not a loop
ipt->m_dir = IntersectPoint::UNSET;
continue;
}
if (is_first_ipt && ON_NearZero(curve_t - curve_min_t)) {
ipt->m_dir = next_in ? IntersectPoint::IN_HIT : IntersectPoint::OUT_HIT;
continue;
}
if (is_last_ipt && ON_NearZero(curve_t - curve_max_t)) {
ipt->m_dir = prev_in ? IntersectPoint::OUT_HIT : IntersectPoint::IN_HIT;
continue;
}
if (prev_in && next_in) {
// tangent point, both sides in, duplicate that point
new_pts.Append(*ipt);
new_pts.Last()->m_dir = IntersectPoint::TANGENT;
new_pts.Last()->m_curve_pos = ipt->m_curve_pos;
ipt->m_dir = IntersectPoint::TANGENT;
} else if (!prev_in && !next_in) {
// tangent point, both sides out, useless
ipt->m_dir = IntersectPoint::UNSET;
} else if (prev_in && !next_in) {
// transversal point, going outside
ipt->m_dir = IntersectPoint::OUT_HIT;
} else {
// transversal point, going inside
ipt->m_dir = IntersectPoint::IN_HIT;
}
}
clx_points.Append(new_pts.Count(), new_pts.Array());
clx_points.QuickSort(loop_t_compare);
// Split the outer loop.
ON_SimpleArray<ON_Curve *> outerloop_segs;
int clx_i = 0;
for (int loop_seg = 0; loop_seg < orig_face->m_outerloop.Count(); loop_seg++) {
ON_Curve *remainder = orig_face->m_outerloop[loop_seg]->Duplicate();
if (remainder == NULL) {
bu_log("ON_Curve::Duplicate() failed.\n");
return out;
}
for (; clx_i < clx_points.Count() && clx_points[clx_i].m_loop_seg == loop_seg; clx_i++) {
IntersectPoint &ipt = clx_points[clx_i];
ON_Curve *portion_before_ipt = NULL;
if (remainder) {
double start_t = remainder->Domain().Min();
double end_t = remainder->Domain().Max();
if (ON_NearZero(ipt.m_seg_t - end_t)) {
// Can't call Split() if ipt is at start (that
// case is handled by the initialization) or ipt
// is at end (handled here).
portion_before_ipt = remainder;
remainder = NULL;
} else if (!ON_NearZero(ipt.m_seg_t - start_t)) {
if (!remainder->Split(ipt.m_seg_t, portion_before_ipt, remainder)) {
bu_log("Split failed.\n");
bu_log("Domain: [%f, %f]\n", end_t, start_t);
bu_log("m_seg_t: %f\n", ipt.m_seg_t);
}
}
}
if (portion_before_ipt) {
outerloop_segs.Append(portion_before_ipt);
}
ipt.m_split_li = outerloop_segs.Count() - 1;
}
outerloop_segs.Append(remainder);
}
// Append the first element at the last to handle some special cases.
if (clx_points.Count()) {
clx_points.Append(clx_points[0]);
clx_points.Last()->m_loop_seg += orig_face->m_outerloop.Count();
for (int i = 0; i <= clx_points[0].m_split_li; i++) {
ON_Curve *dup = outerloop_segs[i]->Duplicate();
if (dup == NULL) {
bu_log("ON_Curve::Duplicate() failed.\n");
}
outerloop_segs.Append(dup);
}
clx_points.Last()->m_split_li = outerloop_segs.Count() - 1;
}
if (DEBUG_BREP_BOOLEAN) {
for (int i = 0; i < clx_points.Count(); i++) {
IntersectPoint &ipt = clx_points[i];
bu_log("clx_points[%d](count = %d): ", i, clx_points.Count());
bu_log("m_curve_pos = %d, m_dir = %d\n", ipt.m_curve_pos, ipt.m_dir);
}
}
std::stack<int> s;
for (int i = 0; i < clx_points.Count(); i++) {
if (clx_points[i].m_dir == IntersectPoint::UNSET) {
continue;
}
if (s.empty()) {
s.push(i);
continue;
}
const IntersectPoint &p = clx_points[s.top()];
const IntersectPoint &q = clx_points[i];
if (loop_t_compare(&p, &q) > 0 || q.m_split_li < p.m_split_li) {
bu_log("stack error or sort failure.\n");
bu_log("s.top() = %d, i = %d\n", s.top(), i);
bu_log("p->m_split_li = %d, q->m_split_li = %d\n", p.m_split_li, q.m_split_li);
bu_log("p->m_loop_seg = %d, q->m_loop_seg = %d\n", p.m_loop_seg, q.m_loop_seg);
bu_log("p->m_seg_t = %g, q->m_seg_t = %g\n", p.m_seg_t, q.m_seg_t);
continue;
}
if (q.m_curve_pos - p.m_curve_pos == 1 &&
q.m_dir != IntersectPoint::IN_HIT &&
p.m_dir != IntersectPoint::OUT_HIT)
{
s.pop();
} else if (p.m_curve_pos - q.m_curve_pos == 1 &&
p.m_dir != IntersectPoint::IN_HIT &&
q.m_dir != IntersectPoint::OUT_HIT)
{
s.pop();
} else {
s.push(i);
continue;
}
// need to form a new loop
ON_SimpleArray<ON_Curve *> newloop;
int curve_count = q.m_split_li - p.m_split_li;
for (int j = p.m_split_li + 1; j <= q.m_split_li; j++) {
// No need to duplicate the curve, because the pointer
// in the array 'outerloop_segs' will be moved out later.
newloop.Append(outerloop_segs[j]);
}
// The curves on the outer loop is from p to q, so the curves on the
// SSI curve should be from q to p (to form a loop)
double t1 = p.m_curve_t, t2 = q.m_curve_t;
bool need_reverse = true;
if (t1 > t2) {
std::swap(t1, t2);
need_reverse = false;
}
ON_Curve *seg_on_SSI = linked_curve.SubCurve(t1, t2);
if (seg_on_SSI == NULL) {
bu_log("sub_curve() failed.\n");
continue;
}
if (need_reverse) {
if (!seg_on_SSI->Reverse()) {
bu_log("Reverse failed.\n");
continue;
}
}
newloop.Append(seg_on_SSI);
close_small_gaps(newloop);
ON_Curve *rev_seg_on_SSI = seg_on_SSI->Duplicate();
if (!rev_seg_on_SSI || !rev_seg_on_SSI->Reverse()) {
bu_log("Reverse failed.\n");
continue;
} else {
// Update the outerloop
outerloop_segs[p.m_split_li + 1] = rev_seg_on_SSI;
int k = p.m_split_li + 2;
for (int j = q.m_split_li + 1; j < outerloop_segs.Count(); j++) {
outerloop_segs[k++] = outerloop_segs[j];
}
while (k < outerloop_segs.Count()) {
outerloop_segs[outerloop_segs.Count() - 1] = NULL;
outerloop_segs.Remove();
}
// Update m_split_li
for (int j = i + 1; j < clx_points.Count(); j++) {
clx_points[j].m_split_li -= curve_count - 1;
}
}
// append the new loop if it's valid
if (is_loop_valid(newloop, ON_ZERO_TOLERANCE)) {
ON_SimpleArray<ON_Curve *> loop;
loop.Append(newloop.Count(), newloop.Array());
out.push_back(loop);
} else {
for (int j = 0; j < newloop.Count(); j++) {
delete newloop[j];
}
}
}
// Remove the duplicated segments before the first intersection point.
if (clx_points.Count()) {
for (int i = 0; i <= clx_points[0].m_split_li; i++) {
delete outerloop_segs[0];
outerloop_segs[0] = NULL;
outerloop_segs.Remove(0);
}
}
if (!out.empty()) {
// The remaining part after splitting some parts out.
close_small_gaps(outerloop_segs);
if (is_loop_valid(outerloop_segs, ON_ZERO_TOLERANCE)) {
ON_SimpleArray<ON_Curve *> loop;
loop.Append(outerloop_segs.Count(), outerloop_segs.Array());
out.push_back(loop);
} else {
for (int i = 0; i < outerloop_segs.Count(); i++)
if (outerloop_segs[i]) {
delete outerloop_segs[i];
}
}
}
return out;
}
void
free_loops(std::vector<ON_SimpleArray<ON_Curve *> > &loops)
{
for (size_t i = 0; i < loops.size(); ++i) {
for (int j = 0; j < loops[i].Count(); ++j) {
delete loops[i][j];
loops[i][j] = NULL;
}
}
}
bool
loop_is_degenerate(const ON_SimpleArray<ON_Curve *> &loop)
{
if (loop.Count() < 1) {
return true;
}
// want sufficient distance between non-adjacent curve points
ON_Curve *loop_curve = get_loop_curve(loop);
ON_Interval dom = loop_curve->Domain();
ON_3dPoint pt1 = loop_curve->PointAt(dom.ParameterAt(.25));
ON_3dPoint pt2 = loop_curve->PointAt(dom.ParameterAt(.75));
delete loop_curve;
return pt1.DistanceTo(pt2) < INTERSECTION_TOL;
}
// It might be worth investigating the following approach to building a set of faces from the splitting
// in order to achieve robustness in the final result:
//
// A) trim the raw SSI curves with the trimming loops from both faces and get "final" curve segments in
// 3D and both 2D parametric spaces. Consolidate curves where different faces created the same curve.
// B) assemble the new 2D segments and whatever pieces are needed from the existing trimming curves to
// form new 2D loops (which must be non-self-intersecting), whose roles in A and B respectively
// would be determined by the boolean op and each face's role within it.
// C) build "representative polygons" for all the 2D loops in each face, new and old - representative in
// this case meaning that the intersection behavior of the general loops is accurately duplicated
// by the polygons, which should be assurable by identifying and using all 2D curve intersections and possibly
// horizontal and vertical tangents - and use clipper to perform the boolean ops. Using the resulting polygons,
// deduce and assemble the final trimming loops (and face or faces) created from A and B respectively.
// Note that the 2D information alone cannot be enough to decide *which* faces created from these splits
// end up in the final brep. A case to think about here is the case of two spheres intersecting -
// depending on A, the exact trimming
// loop in B may need to either define the small area as a new face, or everything BUT the small area
// as a new face - different A spheres may either almost fully contain B or just intersect it. That case
// would seem to suggest that we do need some sort of inside/outside test, since B doesn't have enough
// information to determine which face is to be saved without consulting A. Likewise, A may either save
// just the piece inside the loop or everything outside it, depending on B. This is the same situation we
// were in with the original face sets.
//
// A possible improvement here might be to calculate the best fit plane of the intersection curve and rotate
// both the faces in question and A so that that plane is centered at the origin with the normal in z+.
// In that orientation, axis aligned bounding box tests can be made that will be as informative
// as possible, and may allow many inside/outside decisions to be made without an explicit raytrace. Coplanar
// faces will have to be handled differently, but for convex cases there should be enough information to decide.
// Concave cases may require a raytrace, but there is one other possible approach - if, instead of using the
// whole brep and face bounding boxes we start with the bounding box of the intersection curve and construct
// the sub-box that 'slices' through the parent bbox to the furthest wall in the opposite direction from the
// surface normal, then see which of the two possible
// faces' bounding boxes removes the most volume from that box when subtracted, we may be able to decide
// (say, for a subtraction) which face is cutting deeper. It's not clear to me yet if such an approach would
// work or would scale to complex cases, but it may be worth thinking about.
HIDDEN ON_SimpleArray<TrimmedFace *>
split_trimmed_face(
const TrimmedFace *orig_face,
ON_ClassArray<LinkedCurve> &ssx_curves)
{
ON_SimpleArray<TrimmedFace *> out;
out.Append(orig_face->Duplicate());
if (ssx_curves.Count() == 0) {
// no curves, no splitting
return out;
}
ON_Curve *face_outerloop = get_loop_curve(orig_face->m_outerloop);
if (!face_outerloop->IsClosed()) {
// need closed outerloop
delete face_outerloop;
return out;
}
delete face_outerloop;
for (int i = 0; i < ssx_curves.Count(); ++i) {
std::vector<ON_SimpleArray<ON_Curve *> > ssx_loops;
// get current ssx curve as closed loops
if (ssx_curves[i].IsClosed()) {
ON_SimpleArray<ON_Curve *> loop;
loop.Append(ssx_curves[i].Curve()->Duplicate());
ssx_loops.push_back(loop);
} else {
ssx_loops = split_face_into_loops(orig_face, ssx_curves[i]);
}
// combine each intersection loop with the original face (or
// the previous iteration of split faces) to create new split
// faces
ON_SimpleArray<TrimmedFace *> next_out;
for (size_t j = 0; j < ssx_loops.size(); ++j) {
if (loop_is_degenerate(ssx_loops[j])) {
continue;
}
for (int k = 0; k < out.Count(); ++k) {
LoopBooleanResult intersect_loops, diff_loops;
// get the portion of the face outerloop inside the
// ssx loop
intersect_loops = loop_boolean(out[k]->m_outerloop,
ssx_loops[j], BOOLEAN_INTERSECT);
if (ssx_curves[i].IsClosed()) {
if (intersect_loops.outerloops.empty()) {
// no intersection, just keep the face as-is
next_out.Append(out[k]->Duplicate());
continue;
}
// for a naturally closed ssx curve, we also need
// the portion outside the loop
diff_loops = loop_boolean(out[k]->m_outerloop, ssx_loops[j],
BOOLEAN_DIFF);
append_faces_from_loops(next_out, out[k], diff_loops);
diff_loops.ClearInnerloops();
}
append_faces_from_loops(next_out, out[k], intersect_loops);
intersect_loops.ClearInnerloops();
}
}
free_loops(ssx_loops);
if (next_out.Count() > 0) {
// replace previous faces with the new ones
for (int j = 0; j < out.Count(); ++j) {
delete out[j];
}
out.Empty();
out.Append(next_out.Count(), next_out.Array());
}
}
for (int i = 0; i < out.Count(); ++i) {
close_small_gaps(out[i]->m_outerloop);
for (size_t j = 0; j < out[i]->m_innerloop.size(); ++j) {
close_small_gaps(out[i]->m_innerloop[j]);
}
}
if (DEBUG_BREP_BOOLEAN) {
bu_log("Split to %d faces.\n", out.Count());
for (int i = 0; i < out.Count(); i++) {
bu_log("Trimmed Face %d:\n", i);
bu_log("outerloop:\n");
ON_wString wstr;
ON_TextLog textlog(wstr);
textlog.PushIndent();
for (int j = 0; j < out[i]->m_outerloop.Count(); j++) {
textlog.Print("Curve %d\n", j);
out[i]->m_outerloop[j]->Dump(textlog);
}
if (ON_String(wstr).Array()) {
bu_log("%s", ON_String(wstr).Array());
}
for (unsigned int j = 0; j < out[i]->m_innerloop.size(); j++) {
bu_log("innerloop %d:\n", j);
ON_wString wstr2;
ON_TextLog textlog2(wstr2);
textlog2.PushIndent();
for (int k = 0; k < out[i]->m_innerloop[j].Count(); k++) {
textlog2.Print("Curve %d\n", k);
out[i]->m_innerloop[j][k]->Dump(textlog2);
}
if (ON_String(wstr2).Array()) {
bu_log("%s", ON_String(wstr2).Array());
}
}
}
}
return out;
}
HIDDEN bool
is_same_surface(const ON_Surface *surf1, const ON_Surface *surf2)
{
// Approach: Get their NURBS forms, and compare their CVs.
// If their CVs are all the same (location and weight), they are
// regarded as the same surface.
if (surf1 == NULL || surf2 == NULL) {
return false;
}
/*
// Deal with two planes, if that's what we have - in that case
// the determination can be more general than the CV comparison
ON_Plane surf1_plane, surf2_plane;
if (surf1->IsPlanar(&surf1_plane) && surf2->IsPlanar(&surf2_plane)) {
ON_3dVector surf1_normal = surf1_plane.Normal();
ON_3dVector surf2_normal = surf2_plane.Normal();
if (surf1_normal.IsParallelTo(surf2_normal) == 1) {
if (surf1_plane.DistanceTo(surf2_plane.Origin()) < ON_ZERO_TOLERANCE) {
return true;
} else {
return false;
}
} else {
return false;
}
}
*/
ON_NurbsSurface nurbs_surf1, nurbs_surf2;
if (!surf1->GetNurbForm(nurbs_surf1) || !surf2->GetNurbForm(nurbs_surf2)) {
return false;
}
if (nurbs_surf1.Degree(0) != nurbs_surf2.Degree(0)
|| nurbs_surf1.Degree(1) != nurbs_surf2.Degree(1)) {
return false;
}
if (nurbs_surf1.CVCount(0) != nurbs_surf2.CVCount(0)
|| nurbs_surf1.CVCount(1) != nurbs_surf2.CVCount(1)) {
return false;
}
for (int i = 0; i < nurbs_surf1.CVCount(0); i++) {
for (int j = 0; j < nurbs_surf2.CVCount(1); j++) {
ON_4dPoint cvA, cvB;
nurbs_surf1.GetCV(i, j, cvA);
nurbs_surf2.GetCV(i, j, cvB);
if (cvA != cvB) {
return false;
}
}
}
if (nurbs_surf1.KnotCount(0) != nurbs_surf2.KnotCount(0)
|| nurbs_surf1.KnotCount(1) != nurbs_surf2.KnotCount(1)) {
return false;
}
for (int i = 0; i < nurbs_surf1.KnotCount(0); i++) {
if (!ON_NearZero(nurbs_surf1.m_knot[0][i] - nurbs_surf2.m_knot[0][i])) {
return false;
}
}
for (int i = 0; i < nurbs_surf1.KnotCount(1); i++) {
if (!ON_NearZero(nurbs_surf1.m_knot[1][i] - nurbs_surf2.m_knot[1][i])) {
return false;
}
}
return true;
}
HIDDEN void
add_elements(ON_Brep *brep, ON_BrepFace &face, const ON_SimpleArray<ON_Curve *> &loop, ON_BrepLoop::TYPE loop_type)
{
if (!loop.Count()) {
return;
}
ON_BrepLoop &breploop = brep->NewLoop(loop_type, face);
const ON_Surface *srf = face.SurfaceOf();
// Determine whether a segment should be a seam trim, according to the
// requirements in ON_Brep::IsValid() (See opennurbs_brep.cpp)
for (int k = 0; k < loop.Count(); k++) {
ON_BOOL32 bClosed[2];
bClosed[0] = srf->IsClosed(0);
bClosed[1] = srf->IsClosed(1);
if (bClosed[0] || bClosed[1]) {
ON_Surface::ISO iso1, iso2, iso_type;
int endpt_index = -1;
iso1 = srf->IsIsoparametric(*loop[k]);
if (ON_Surface::E_iso == iso1 && bClosed[0]) {
iso_type = ON_Surface::W_iso;
endpt_index = 1;
} else if (ON_Surface::W_iso == iso1 && bClosed[0]) {
iso_type = ON_Surface::E_iso;
endpt_index = 1;
} else if (ON_Surface::S_iso == iso1 && bClosed[1]) {
iso_type = ON_Surface::N_iso;
endpt_index = 0;
} else if (ON_Surface::N_iso == iso1 && bClosed[1]) {
iso_type = ON_Surface::S_iso;
endpt_index = 0;
}
if (endpt_index != -1) {
ON_Interval side_interval;
const double side_tol = 1.0e-4;
double s0, s1;
bool seamed = false;
side_interval.Set(loop[k]->PointAtStart()[endpt_index], loop[k]->PointAtEnd()[endpt_index]);
if (((ON_Surface::N_iso == iso_type || ON_Surface::W_iso == iso_type) && side_interval.IsIncreasing())
|| ((ON_Surface::S_iso == iso_type || ON_Surface::E_iso == iso_type) && side_interval.IsDecreasing())) {
for (int i = 0; i < breploop.m_ti.Count(); i++) {
ON_BrepTrim &trim = brep->m_T[breploop.m_ti[i]];
if (ON_BrepTrim::boundary != trim.m_type) {
continue;
}
iso2 = srf->IsIsoparametric(trim);
if (iso2 != iso_type) {
continue;
}
s1 = side_interval.NormalizedParameterAt(trim.PointAtStart()[endpt_index]);
if (fabs(s1 - 1.0) > side_tol) {
continue;
}
s0 = side_interval.NormalizedParameterAt(trim.PointAtEnd()[endpt_index]);
if (fabs(s0) > side_tol) {
continue;
}
// Check 3D distances - not included in ON_Brep::IsValid().
// So with this check, we only add seam trims if their end points
// are the same within ON_ZERO_TOLERANCE. This will cause IsValid()
// reporting "they should be seam trims connected to the same edge",
// because the 2D tolerance (side_tol) are hardcoded to 1.0e-4.
// We still add this check because we treat two vertexes to be the
// same only if their distance < ON_ZERO_TOLERANCE. (Maybe 3D dist
// should also be added to ON_Brep::IsValid()?)
if (srf->PointAt(trim.PointAtStart().x, trim.PointAtStart().y).DistanceTo(
srf->PointAt(loop[k]->PointAtEnd().x, loop[k]->PointAtEnd().y)) >= ON_ZERO_TOLERANCE) {
continue;
}
if (srf->PointAt(trim.PointAtEnd().x, trim.PointAtEnd().y).DistanceTo(
srf->PointAt(loop[k]->PointAtStart().x, loop[k]->PointAtStart().y)) >= ON_ZERO_TOLERANCE) {
continue;
}
// We add another checking, which is not included in ON_Brep::IsValid()
// - they should be iso boundaries of the surface.
double s2 = srf->Domain(1 - endpt_index).NormalizedParameterAt(loop[k]->PointAtStart()[1 - endpt_index]);
double s3 = srf->Domain(1 - endpt_index).NormalizedParameterAt(trim.PointAtStart()[1 - endpt_index]);
if ((fabs(s2 - 1.0) < side_tol && fabs(s3) < side_tol) ||
(fabs(s2) < side_tol && fabs(s3 - 1.0) < side_tol)) {
// Find a trim that should share the same edge
int ti = brep->AddTrimCurve(loop[k]);
ON_BrepTrim &newtrim = brep->NewTrim(brep->m_E[trim.m_ei], true, breploop, ti);
// newtrim.m_type = ON_BrepTrim::seam;
newtrim.m_tolerance[0] = newtrim.m_tolerance[1] = MAX_FASTF;
seamed = true;
break;
}
}
if (seamed) {
continue;
}
}
}
}
ON_Curve *c3d = NULL;
// First, try the ON_Surface::Pushup() method.
// If Pushup() does not succeed, use sampling method.
c3d = face.SurfaceOf()->Pushup(*(loop[k]), INTERSECTION_TOL);
if (!c3d) {
ON_3dPointArray ptarray(101);
for (int l = 0; l <= 100; l++) {
ON_3dPoint pt2d;
pt2d = loop[k]->PointAt(loop[k]->Domain().ParameterAt(l / 100.0));
ptarray.Append(face.SurfaceOf()->PointAt(pt2d.x, pt2d.y));
}
c3d = new ON_PolylineCurve(ptarray);
}
if (c3d->BoundingBox().Diagonal().Length() < ON_ZERO_TOLERANCE) {
// The trim is singular
int i;
ON_3dPoint vtx = c3d->PointAtStart();
for (i = brep->m_V.Count() - 1; i >= 0; i--) {
if (brep->m_V[i].Point().DistanceTo(vtx) < ON_ZERO_TOLERANCE) {
break;
}
}
if (i < 0) {
i = brep->m_V.Count();
brep->NewVertex(c3d->PointAtStart(), 0.0);
}
int ti = brep->AddTrimCurve(loop[k]);
ON_BrepTrim &trim = brep->NewSingularTrim(brep->m_V[i], breploop, srf->IsIsoparametric(*loop[k]), ti);
trim.m_tolerance[0] = trim.m_tolerance[1] = MAX_FASTF;
delete c3d;
continue;
}
ON_2dPoint start = loop[k]->PointAtStart(), end = loop[k]->PointAtEnd();
int start_idx, end_idx;
// Get the start vertex index
if (k > 0) {
start_idx = brep->m_T.Last()->m_vi[1];
} else {
ON_3dPoint vtx = face.SurfaceOf()->PointAt(start.x, start.y);
int i;
for (i = 0; i < brep->m_V.Count(); i++) {
if (brep->m_V[i].Point().DistanceTo(vtx) < ON_ZERO_TOLERANCE) {
break;
}
}
start_idx = i;
if (i == brep->m_V.Count()) {
brep->NewVertex(vtx, 0.0);
}
}
// Get the end vertex index
if (c3d->IsClosed()) {
end_idx = start_idx;
} else {
ON_3dPoint vtx = face.SurfaceOf()->PointAt(end.x, end.y);
int i;
for (i = 0; i < brep->m_V.Count(); i++) {
if (brep->m_V[i].Point().DistanceTo(vtx) < ON_ZERO_TOLERANCE) {
break;
}
}
end_idx = i;
if (i == brep->m_V.Count()) {
brep->NewVertex(vtx, 0.0);
}
}
brep->AddEdgeCurve(c3d);
int ti = brep->AddTrimCurve(loop[k]);
ON_BrepEdge &edge = brep->NewEdge(brep->m_V[start_idx], brep->m_V[end_idx],
brep->m_C3.Count() - 1, (const ON_Interval *)0, MAX_FASTF);
ON_BrepTrim &trim = brep->NewTrim(edge, 0, breploop, ti);
trim.m_tolerance[0] = trim.m_tolerance[1] = MAX_FASTF;
}
}
HIDDEN bool
is_point_on_brep_surface(const ON_3dPoint &pt, const ON_Brep *brep, ON_SimpleArray<Subsurface *> &surf_tree)
{
// Decide whether a point is on a brep's surface.
// Basic approach: use PSI on the point with all the surfaces.
if (brep == NULL || pt.IsUnsetPoint()) {
bu_log("is_point_on_brep_surface(): brep == NULL || pt.IsUnsetPoint()\n");
return false;
}
if (surf_tree.Count() != brep->m_S.Count()) {
bu_log("is_point_on_brep_surface(): surf_tree.Count() != brep->m_S.Count()\n");
return false;
}
ON_BoundingBox bbox = brep->BoundingBox();
bbox.m_min -= ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
bbox.m_max += ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
if (!bbox.IsPointIn(pt)) {
return false;
}
for (int i = 0; i < brep->m_F.Count(); i++) {
const ON_BrepFace &face = brep->m_F[i];
const ON_Surface *surf = face.SurfaceOf();
ON_ClassArray<ON_PX_EVENT> px_event;
if (!ON_Intersect(pt, *surf, px_event, INTERSECTION_TOL, 0, 0, surf_tree[face.m_si])) {
continue;
}
// Get the trimming curves of the face, and determine whether the
// points are inside the outerloop
ON_SimpleArray<ON_Curve *> outerloop;
const ON_BrepLoop &loop = brep->m_L[face.m_li[0]]; // outerloop only
for (int j = 0; j < loop.m_ti.Count(); j++) {
outerloop.Append(brep->m_C2[brep->m_T[loop.m_ti[j]].m_c2i]);
}
ON_2dPoint pt2d(px_event[0].m_b[0], px_event[0].m_b[1]);
try {
if (!is_point_outside_loop(pt2d, outerloop)) {
return true;
}
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
}
}
return false;
}
HIDDEN bool
is_point_inside_brep(const ON_3dPoint &pt, const ON_Brep *brep, ON_SimpleArray<Subsurface *> &surf_tree)
{
// Decide whether a point is inside a brep's surface.
// Basic approach: intersect a ray with the brep, and count the number of
// intersections (like the raytrace)
// Returns true (inside) or false (outside) provided the pt is not on the
// surfaces. (See also is_point_on_brep_surface())
if (brep == NULL || pt.IsUnsetPoint()) {
bu_log("is_point_inside_brep(): brep == NULL || pt.IsUnsetPoint()\n");
return false;
}
if (surf_tree.Count() != brep->m_S.Count()) {
bu_log("is_point_inside_brep(): surf_tree.Count() != brep->m_S.Count()\n");
return false;
}
ON_BoundingBox bbox = brep->BoundingBox();
bbox.m_min -= ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
bbox.m_max += ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
if (!bbox.IsPointIn(pt)) {
return false;
}
ON_3dVector diag = bbox.Diagonal() * 1.5; // Make it even longer
ON_LineCurve line(pt, pt + diag); // pt + diag should be outside, if pt
// is inside the bbox
ON_3dPointArray isect_pt;
for (int i = 0; i < brep->m_F.Count(); i++) {
const ON_BrepFace &face = brep->m_F[i];
const ON_Surface *surf = face.SurfaceOf();
ON_SimpleArray<ON_X_EVENT> x_event;
if (!ON_Intersect(&line, surf, x_event, INTERSECTION_TOL, 0.0, 0, 0, 0, 0, 0, surf_tree[face.m_si])) {
continue;
}
// Get the trimming curves of the face, and determine whether the
// points are inside the outerloop
ON_SimpleArray<ON_Curve *> outerloop;
const ON_BrepLoop &loop = brep->m_L[face.m_li[0]]; // outerloop only
for (int j = 0; j < loop.m_ti.Count(); j++) {
outerloop.Append(brep->m_C2[brep->m_T[loop.m_ti[j]].m_c2i]);
}
try {
for (int j = 0; j < x_event.Count(); j++) {
ON_2dPoint pt2d(x_event[j].m_b[0], x_event[j].m_b[1]);
if (!is_point_outside_loop(pt2d, outerloop)) {
isect_pt.Append(x_event[j].m_B[0]);
}
if (x_event[j].m_type == ON_X_EVENT::ccx_overlap) {
pt2d = ON_2dPoint(x_event[j].m_b[2], x_event[j].m_b[3]);
if (!is_point_outside_loop(pt2d, outerloop)) {
isect_pt.Append(x_event[j].m_B[1]);
}
}
}
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
}
}
// Remove duplications
ON_3dPointArray pt_no_dup;
for (int i = 0; i < isect_pt.Count(); i++) {
int j;
for (j = 0; j < pt_no_dup.Count(); j++) {
if (isect_pt[i].DistanceTo(pt_no_dup[j]) < INTERSECTION_TOL) {
break;
}
}
if (j == pt_no_dup.Count()) {
// No duplication, append to the array
pt_no_dup.Append(isect_pt[i]);
}
}
return pt_no_dup.Count() % 2 != 0;
}
HIDDEN bool
is_point_inside_trimmed_face(const ON_2dPoint &pt, const TrimmedFace *tface)
{
bool inside = false;
if (is_point_inside_loop(pt, tface->m_outerloop)) {
inside = true;
for (size_t i = 0; i < tface->m_innerloop.size(); ++i) {
if (!is_point_outside_loop(pt, tface->m_innerloop[i])) {
inside = false;
break;
}
}
}
return inside;
}
// TODO: For faces that have most of their area trimmed away, this is
// a very inefficient algorithm. If the grid approach doesn't work
// after a small number of samples, we should switch to an alternative
// algorithm, such as sampling around points on the inner loops.
HIDDEN ON_2dPoint
get_point_inside_trimmed_face(const TrimmedFace *tface)
{
const int GP_MAX_STEPS = 8; // must be a power of two
ON_PolyCurve polycurve;
if (!is_loop_valid(tface->m_outerloop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("face_brep_location(): invalid outerloop.\n");
}
ON_BoundingBox bbox = polycurve.BoundingBox();
double u_len = bbox.m_max.x - bbox.m_min.x;
double v_len = bbox.m_max.y - bbox.m_min.y;
ON_2dPoint test_pt2d;
bool found = false;
for (int steps = 1; steps <= GP_MAX_STEPS && !found; steps *= 2) {
double u_halfstep = u_len / (steps * 2.0);
double v_halfstep = v_len / (steps * 2.0);
for (int i = 0; i < steps && !found; ++i) {
test_pt2d.x = bbox.m_min.x + u_halfstep * (1 + 2 * i);
for (int j = 0; j < steps && !found; ++j) {
test_pt2d.y = bbox.m_min.y + v_halfstep * (1 + 2 * j);
found = is_point_inside_trimmed_face(test_pt2d, tface);
}
}
}
if (!found) {
throw AlgorithmError("Cannot find a point inside this trimmed face. Aborted.\n");
}
return test_pt2d;
}
enum {
OUTSIDE_BREP,
INSIDE_BREP,
ON_BREP_SURFACE
};
// Returns the location of the face with respect to the brep.
//
// Throws InvalidGeometry if given invalid arguments.
// Throws AlgorithmError if a point inside the TrimmedFace can't be
// found for testing.
HIDDEN int
face_brep_location(const TrimmedFace *tface, const ON_Brep *brep, ON_SimpleArray<Subsurface *> &surf_tree)
{
if (tface == NULL || brep == NULL) {
throw InvalidGeometry("face_brep_location(): given NULL argument.\n");
}
const ON_BrepFace *bface = tface->m_face;
if (bface == NULL) {
throw InvalidGeometry("face_brep_location(): TrimmedFace has NULL face.\n");
}
ON_BoundingBox brep2box = brep->BoundingBox();
brep2box.m_min -= ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
brep2box.m_max += ON_3dVector(INTERSECTION_TOL, INTERSECTION_TOL, INTERSECTION_TOL);
if (!bface->BoundingBox().Intersection(brep2box)) {
return OUTSIDE_BREP;
}
if (tface->m_outerloop.Count() == 0) {
throw InvalidGeometry("face_brep_location(): the input TrimmedFace is not trimmed.\n");
}
ON_PolyCurve polycurve;
if (!is_loop_valid(tface->m_outerloop, ON_ZERO_TOLERANCE, &polycurve)) {
throw InvalidGeometry("face_brep_location(): invalid outerloop.\n");
}
ON_2dPoint test_pt2d = get_point_inside_trimmed_face(tface);
ON_3dPoint test_pt3d = tface->m_face->PointAt(test_pt2d.x, test_pt2d.y);
if (DEBUG_BREP_BOOLEAN) {
bu_log("valid test point: (%g, %g, %g)\n", test_pt3d.x, test_pt3d.y, test_pt3d.z);
}
if (is_point_on_brep_surface(test_pt3d, brep, surf_tree)) {
// because the overlap parts will be split out as separated trimmed
// faces, if one point on a trimmed face is on the brep's surface,
// the whole trimmed face should be on the surface
return ON_BREP_SURFACE;
}
return is_point_inside_brep(test_pt3d, brep, surf_tree) ? INSIDE_BREP : OUTSIDE_BREP;
}
HIDDEN ON_ClassArray<ON_SimpleArray<SSICurve> >
get_face_intersection_curves(
ON_SimpleArray<Subsurface *> &surf_tree1,
ON_SimpleArray<Subsurface *> &surf_tree2,
const ON_Brep *brep1,
const ON_Brep *brep2,
op_type operation)
{
std::vector<Subsurface *> st1, st2;
std::set<int> unused1, unused2;
std::set<int> finalform1, finalform2;
ON_ClassArray<ON_SimpleArray<SSICurve> > curves_array;
int face_count1 = brep1->m_F.Count();
int face_count2 = brep2->m_F.Count();
int surf_count1 = brep1->m_S.Count();
int surf_count2 = brep2->m_S.Count();
// We're not well set up currently to handle a situation where
// one of the breps has no faces - don't try. Also make sure
// we don't have too many faces.
if (!face_count1 || !face_count2 || ((face_count1 + face_count2) < 0))
return curves_array;
if (!surf_count1 || !surf_count2 || ((surf_count1 + surf_count2) < 0))
return curves_array;
/* Depending on the operation type and the bounding box behaviors, we
* can sometimes decide immediately whether a face will end up in the
* final brep or will have no role in the intersections - do that
* categorization up front */
for (int i = 0; i < face_count1 + face_count2; i++) {
const ON_BrepFace &face = i < face_count1 ? brep1->m_F[i] : brep2->m_F[i - face_count1];
const ON_Brep *brep = i < face_count1 ? brep2 : brep1;
std::set<int> *unused = i < face_count1 ? &unused1 : &unused2;
std::set<int> *intact = i < face_count1 ? &finalform1 : &finalform2;
int curr_index = i < face_count1 ? i : i - face_count1;
if (face.BoundingBox().MinimumDistanceTo(brep->BoundingBox()) > INTERSECTION_TOL) {
switch (operation) {
case BOOLEAN_UNION:
intact->insert(curr_index);
break;
case BOOLEAN_DIFF:
if (i < face_count1) {
intact->insert(curr_index);
}
if (i >= face_count1) {
unused->insert(curr_index);
}
break;
case BOOLEAN_INTERSECT:
unused->insert(curr_index);
break;
default:
throw InvalidBooleanOperation("Error - unknown "
"boolean operation\n");
}
}
}
// For the faces that we can't rule out, there are several possible roles they can play:
//
// 1. Fully utilized in the new brep
// 2. Changed into a new set of faces by intersections, each of which must be evaluated
// 3. Fully discarded by the new brep
//
// We won't be able to distinguish between 1 and 3 at this stage, but we can narrow in
// on which faces might fall into category 2 and what faces they might interact with.
std::set<std::pair<int, int> > intersection_candidates;
for (int i = 0; i < face_count1; i++) {
if (unused1.find(i) == unused1.end() && finalform1.find(i) == finalform1.end()) {
for (int j = 0; j < face_count2; j++) {
if (unused2.find(j) == unused2.end() && finalform2.find(j) == finalform2.end()) {
// If the two faces don't interact according to their bounding boxes,
// they won't be a source of events - otherwise, they must be checked.
fastf_t face_dist = brep1->m_F[i].BoundingBox().MinimumDistanceTo(brep2->m_F[j].BoundingBox());
if (face_dist <= INTERSECTION_TOL) {
intersection_candidates.insert(std::pair<int, int>(i, j));
}
}
}
}
}
// For those not in category 2 an inside/outside test on the breps combined with the boolean op
// should be enough to decide the issue, but there is a problem. If *all* faces of a brep are
// inside the other brep and the operation is a subtraction, we don't want a "floating" inside-out
// brep volume inside the outer volume and topologically isolated. Normally this is handled by
// creating a face that connects the outer and inner shells, but this is potentially a non-trivial
// operation. The only thing that comes immediately to mind is to find the center point of the
// bounding box of the inner brep, create a plane using that point and the z+ unit vector for a normal, and
// cut both breps in half with that plane to form four new breps and two new subtraction problems.
//
// More broadly, this is a problem - unioning two half-spheres with a sphere subtracted out of their
// respective centers will end up with isolated surfaces in the middle of the union unless the routines
// know they must keep one of the coplanar faces in order to topologically connect the middle. However,
// in the case where there is no center sphere the central face should be removed. It may be that the
// condition to satisfy for removal is no interior trimming loops on the face.
//
//
// Also worth thinking about - would it be possible to then do edge comparisons to
// determine which of the "fully used/fully non-used" faces are needed?
if (DEBUG_BREP_BOOLEAN) {
//bu_log("Summary of brep status: \n unused1: %zd\n unused2: %zd\n finalform1: %zd\n finalform2 %zd\nintersection_candidates(%zd):\n", unused1.size(), unused2.size(), finalform1.size(), finalform2.size(), intersection_candidates.size());
for (std::set<std::pair<int, int> >::iterator it = intersection_candidates.begin(); it != intersection_candidates.end(); ++it) {
bu_log(" (%d, %d)\n", (*it).first, (*it).second);
}
}
for (int i = 0; i < surf_count1; i++) {
Subsurface *ss = new Subsurface(brep1->m_S[i]->Duplicate());
st1.push_back(ss);
}
for (int i = 0; i < surf_count2; i++) {
Subsurface *ss = new Subsurface(brep2->m_S[i]->Duplicate());
st2.push_back(ss);
}
curves_array.SetCapacity(face_count1 + face_count2);
// count must equal capacity for array copy to work as expected
// when the result of the function is assigned
curves_array.SetCount(curves_array.Capacity());
// calculate intersection curves
for (int i = 0; i < face_count1; i++) {
if ((int)st1.size() < brep1->m_F[i].m_si + 1)
continue;
for (int j = 0; j < face_count2; j++) {
if (intersection_candidates.find(std::pair<int, int>(i, j)) != intersection_candidates.end()) {
ON_Surface *surf1, *surf2;
ON_ClassArray<ON_SSX_EVENT> events;
int results = 0;
surf1 = brep1->m_S[brep1->m_F[i].m_si];
surf2 = brep2->m_S[brep2->m_F[j].m_si];
if (is_same_surface(surf1, surf2)) {
continue;
}
if (surf_tree2.Count() < brep2->m_F[j].m_si + 1)
continue;
// Possible enhancement: Some faces may share the same surface.
// We can store the result of SSI to avoid re-computation.
results = ON_Intersect(surf1,
surf2,
events,
INTERSECTION_TOL,
0.0,
0.0,
NULL,
NULL,
NULL,
NULL,
st1[brep1->m_F[i].m_si],
st2[brep2->m_F[j].m_si]);
if (results <= 0) {
continue;
}
dplot->SSX(events, brep1, brep1->m_F[i].m_si, brep2, brep2->m_F[j].m_si);
dplot->WriteLog();
ON_SimpleArray<ON_Curve *> face1_curves, face2_curves;
for (int k = 0; k < events.Count(); k++) {
if (events[k].m_type == ON_SSX_EVENT::ssx_tangent ||
events[k].m_type == ON_SSX_EVENT::ssx_transverse ||
events[k].m_type == ON_SSX_EVENT::ssx_overlap)
{
ON_SimpleArray<ON_Curve *> subcurves_on1, subcurves_on2;
get_subcurves_inside_faces(subcurves_on1,
subcurves_on2, brep1, brep2, i, j, &events[k]);
for (int l = 0; l < subcurves_on1.Count(); ++l) {
SSICurve ssi_on1;
ssi_on1.m_curve = subcurves_on1[l];
curves_array[i].Append(ssi_on1);
face1_curves.Append(subcurves_on1[l]);
}
for (int l = 0; l < subcurves_on2.Count(); ++l) {
SSICurve ssi_on2;
ssi_on2.m_curve = subcurves_on2[l];
curves_array[face_count1 + j].Append(ssi_on2);
face2_curves.Append(subcurves_on2[l]);
}
}
}
dplot->ClippedFaceCurves(surf1, surf2, face1_curves, face2_curves);
dplot->WriteLog();
if (DEBUG_BREP_BOOLEAN) {
// Look for coplanar faces
ON_Plane surf1_plane, surf2_plane;
if (surf1->IsPlanar(&surf1_plane) && surf2->IsPlanar(&surf2_plane)) {
/* We already checked for disjoint above, so the only remaining question is the normals */
if (surf1_plane.Normal().IsParallelTo(surf2_plane.Normal())) {
bu_log("Faces brep1->%d and brep2->%d are coplanar and intersecting\n", i, j);
}
}
}
}
}
}
for (size_t i = 0; i < st1.size(); i++) {
surf_tree1.Append(st1[i]);
}
for (size_t i = 0; i < st2.size(); i++) {
surf_tree2.Append(st2[i]);
}
return curves_array;
}
HIDDEN ON_SimpleArray<ON_Curve *>get_face_trim_loop(const ON_Brep *brep, int face_loop_index)
{
const ON_BrepLoop &loop = brep->m_L[face_loop_index];
const ON_SimpleArray<int> &trim_index = loop.m_ti;
ON_SimpleArray<ON_Curve *> face_trim_loop;
for (int i = 0; i < trim_index.Count(); ++i) {
ON_Curve *curve2d = brep->m_C2[brep->m_T[trim_index[i]].m_c2i];
face_trim_loop.Append(curve2d->Duplicate());
}
return face_trim_loop;
}
HIDDEN ON_SimpleArray<TrimmedFace *>
get_trimmed_faces(const ON_Brep *brep)
{
std::vector<TrimmedFace *> trimmed_faces;
int face_count = brep->m_F.Count();
for (int i = 0; i < face_count; i++) {
const ON_BrepFace &face = brep->m_F[i];
const ON_SimpleArray<int> &loop_index = face.m_li;
if (loop_index.Count() <= 0) {
continue;
}
TrimmedFace *trimmed_face = new TrimmedFace();
trimmed_face->m_face = &face;
ON_SimpleArray<ON_Curve *> index_loop = get_face_trim_loop(brep, loop_index[0]);
trimmed_face->m_outerloop = index_loop;
for (int j = 1; j < loop_index.Count(); j++) {
index_loop = get_face_trim_loop(brep, loop_index[j]);
trimmed_face->m_innerloop.push_back(index_loop);
}
trimmed_faces.push_back(trimmed_face);
}
ON_SimpleArray<TrimmedFace *> tf;
for (size_t i = 0; i < trimmed_faces.size(); i++) {
tf.Append(trimmed_faces[i]);
}
return tf;
}
HIDDEN void
categorize_trimmed_faces(
ON_ClassArray<ON_SimpleArray<TrimmedFace *> > &trimmed_faces,
const ON_Brep *brep1,
const ON_Brep *brep2,
ON_SimpleArray<Subsurface *> &surf_tree1,
ON_SimpleArray<Subsurface *> &surf_tree2,
op_type operation)
{
int face_count1 = brep1->m_F.Count();
for (int i = 0; i < trimmed_faces.Count(); i++) {
/* Perform inside-outside test to decide whether the trimmed face should
* be used in the final b-rep structure or not.
* Different operations should be dealt with accordingly.
* Use connectivity graphs (optional) which represents the topological
* structure of the b-rep. This can reduce time-consuming inside-outside
* tests.
*/
const ON_SimpleArray<TrimmedFace *> &splitted = trimmed_faces[i];
const ON_Brep *another_brep = i >= face_count1 ? brep1 : brep2;
ON_SimpleArray<Subsurface *> &surf_tree = i >= face_count1 ? surf_tree1 : surf_tree2;
for (int j = 0; j < splitted.Count(); j++) {
if (splitted[j]->m_belong_to_final != TrimmedFace::UNKNOWN) {
// Visited before, don't need to test again
continue;
}
int face_location = -1;
try {
face_location = face_brep_location(splitted[j], another_brep, surf_tree);
} catch (InvalidGeometry &e) {
bu_log("%s", e.what());
} catch (AlgorithmError &e) {
bu_log("%s", e.what());
}
if (face_location < 0) {
if (DEBUG_BREP_BOOLEAN) {
bu_log("Whether the trimmed face is inside/outside is unknown.\n");
}
splitted[j]->m_belong_to_final = TrimmedFace::NOT_BELONG;
continue;
}
splitted[j]->m_rev = false;
splitted[j]->m_belong_to_final = TrimmedFace::NOT_BELONG;
switch (face_location) {
case INSIDE_BREP:
if (operation == BOOLEAN_INTERSECT ||
operation == BOOLEAN_XOR ||
(operation == BOOLEAN_DIFF && i >= face_count1))
{
splitted[j]->m_belong_to_final = TrimmedFace::BELONG;
}
if (operation == BOOLEAN_DIFF || operation == BOOLEAN_XOR) {
splitted[j]->m_rev = true;
}
break;
case OUTSIDE_BREP:
if (operation == BOOLEAN_UNION ||
operation == BOOLEAN_XOR ||
(operation == BOOLEAN_DIFF && i < face_count1))
{
splitted[j]->m_belong_to_final = TrimmedFace::BELONG;
}
break;
case ON_BREP_SURFACE:
// get a 3d point on the face
ON_2dPoint face_pt2d = get_point_inside_trimmed_face(splitted[j]);
ON_3dPoint face_pt3d = splitted[j]->m_face->PointAt(face_pt2d.x, face_pt2d.y);
// find the matching point on the other brep
ON_3dPoint brep_pt2d;
const ON_Surface *brep_surf;
bool found = false;
for (int fi = 0; fi < another_brep->m_F.Count(); ++fi) {
const ON_BrepFace &face = another_brep->m_F[fi];
brep_surf = face.SurfaceOf();
ON_ClassArray<ON_PX_EVENT> px_event;
if (ON_Intersect(face_pt3d, *brep_surf, px_event,
INTERSECTION_TOL, 0, 0, surf_tree[face.m_si]))
{
found = true;
brep_pt2d = px_event[0].m_b;
break;
}
}
if (found) {
// compare normals of surfaces at shared point
ON_3dVector brep_norm, face_norm;
brep_surf->EvNormal(brep_pt2d.x, brep_pt2d.y, brep_norm);
splitted[j]->m_face->SurfaceOf()->EvNormal(face_pt2d.x, face_pt2d.y, face_norm);
double dot = ON_DotProduct(brep_norm, face_norm);
bool same_direction = false;
if (dot > 0) {
// normals appear to have same direction
same_direction = true;
}
if ((operation == BOOLEAN_UNION && same_direction) ||
(operation == BOOLEAN_INTERSECT && same_direction) ||
(operation == BOOLEAN_DIFF && !same_direction && i < face_count1))
{
splitted[j]->m_belong_to_final = TrimmedFace::BELONG;
}
}
// TODO: Actually only one of them is needed in the final brep structure
}
if (DEBUG_BREP_BOOLEAN) {
bu_log("The trimmed face is %s the other brep.",
(face_location == INSIDE_BREP) ? "inside" :
((face_location == OUTSIDE_BREP) ? "outside" : "on the surface of"));
}
}
}
}
HIDDEN ON_ClassArray<ON_SimpleArray<TrimmedFace *> >
get_evaluated_faces(const ON_Brep *brep1, const ON_Brep *brep2, op_type operation)
{
ON_SimpleArray<Subsurface *> surf_tree1, surf_tree2;
int face_count1 = brep1->m_F.Count();
int face_count2 = brep2->m_F.Count();
// check for face counts high enough to cause overflow
if ((face_count1 + face_count2) < 0)
return ON_ClassArray<ON_SimpleArray<TrimmedFace *> > ();
ON_ClassArray<ON_SimpleArray<SSICurve> > curves_array =
get_face_intersection_curves(surf_tree1, surf_tree2, brep1, brep2, operation);
ON_SimpleArray<TrimmedFace *> brep1_faces, brep2_faces;
brep1_faces = get_trimmed_faces(brep1);
brep2_faces = get_trimmed_faces(brep2);
ON_SimpleArray<TrimmedFace *> original_faces = brep1_faces;
for (int i = 0; i < brep2_faces.Count(); ++i) {
original_faces.Append(brep2_faces[i]);
}
if (original_faces.Count() != face_count1 + face_count2) {
throw GeometryGenerationError("ON_Boolean() Error: TrimmedFace"
" generation failed.\n");
}
// split the surfaces with the intersection curves
ON_ClassArray<ON_SimpleArray<TrimmedFace *> > trimmed_faces;
for (int i = 0; i < original_faces.Count(); i++) {
TrimmedFace *first = original_faces[i];
ON_ClassArray<LinkedCurve> linked_curves = link_curves(curves_array[i]);
dplot->LinkedCurves(first->m_face->SurfaceOf(), linked_curves);
dplot->WriteLog();
ON_SimpleArray<TrimmedFace *> splitted = split_trimmed_face(first, linked_curves);
trimmed_faces.Append(splitted);
// Delete the curves passed in.
// Only the copies of them will be used later.
for (int j = 0; j < linked_curves.Count(); j++) {
for (int k = 0; k < linked_curves[j].m_ssi_curves.Count(); k++) {
if (linked_curves[j].m_ssi_curves[k].m_curve) {
delete linked_curves[j].m_ssi_curves[k].m_curve;
linked_curves[j].m_ssi_curves[k].m_curve = NULL;
}
}
}
}
if (trimmed_faces.Count() != original_faces.Count()) {
throw GeometryGenerationError("ON_Boolean() Error: "
"trimmed_faces.Count() != original_faces.Count()\n");
}
for (int i = 0; i < original_faces.Count(); i++) {
delete original_faces[i];
original_faces[i] = NULL;
}
categorize_trimmed_faces(trimmed_faces, brep1, brep2, surf_tree1, surf_tree2, operation);
dplot->SplitFaces(trimmed_faces);
dplot->WriteLog();
for (int i = 0; i < surf_tree1.Count(); i++) {
delete surf_tree1[i];
}
for (int i = 0; i < surf_tree2.Count(); i++) {
delete surf_tree2[i];
}
return trimmed_faces;
}
HIDDEN void
standardize_loop_orientations(ON_Brep *brep)
{
std::map<int, int> reversed_curve2d, reversed_edge;
for (int face_idx = 0; face_idx < brep->m_F.Count(); ++face_idx) {
const ON_BrepFace &eb_face = brep->m_F[face_idx];
for (int loop_idx = 0; loop_idx < eb_face.LoopCount(); ++loop_idx) {
const ON_BrepLoop &face_loop = brep->m_L[eb_face.m_li[loop_idx]];
if (face_loop.m_type != ON_BrepLoop::outer &&
face_loop.m_type != ON_BrepLoop::inner) {
continue;
}
int loop_direction = brep->LoopDirection(face_loop);
if ((loop_direction == LOOP_DIRECTION_CCW && face_loop.m_type == ON_BrepLoop::inner) ||
(loop_direction == LOOP_DIRECTION_CW && face_loop.m_type == ON_BrepLoop::outer))
{
// found reversed loop
int brep_li = eb_face.m_li[loop_idx];
ON_BrepLoop &reversed_loop = brep->m_L[brep_li];
// reverse all the loop's curves
for (int trim_idx = 0; trim_idx < reversed_loop.TrimCount(); ++trim_idx) {
ON_BrepTrim *trim = reversed_loop.Trim(trim_idx);
// Replace trim curve2d with a reversed copy.
// We'll use a previously made curve, or else
// make a new one.
if (reversed_curve2d.find(trim->m_c2i) != reversed_curve2d.end()) {
trim->ChangeTrimCurve(reversed_curve2d[trim->m_c2i]);
} else {
ON_Curve *curve_copy = trim->TrimCurveOf()->DuplicateCurve();
int copy_c2i = brep->AddTrimCurve(curve_copy);
reversed_curve2d[trim->m_c2i] = copy_c2i;
trim->ChangeTrimCurve(copy_c2i);
trim->Reverse();
}
// Replace trim edge with a reversed copy.
// We'll use a previously made edge, or else
// make a new one.
if (reversed_edge.find(trim->m_ei) != reversed_edge.end()) {
trim->RemoveFromEdge(false, false);
trim->AttachToEdge(reversed_edge[trim->m_ei], trim->m_bRev3d);
} else {
ON_BrepEdge *edge = trim->Edge();
ON_BrepVertex &v_start = *edge->Vertex(0);
ON_BrepVertex &v_end = *edge->Vertex(1);
ON_Interval dom = edge->ProxyCurveDomain();
ON_Curve *curve_copy = trim->EdgeCurveOf()->DuplicateCurve();
int copy_c3i = brep->AddEdgeCurve(curve_copy);
ON_BrepEdge &edge_copy = brep->NewEdge(v_start,
v_end, copy_c3i, &dom, edge->m_tolerance);
reversed_edge[trim->m_ei] = copy_c3i;
trim->RemoveFromEdge(false, false);
trim->AttachToEdge(edge_copy.m_edge_index, trim->m_bRev3d);
trim->Edge()->Reverse();
}
}
// need to reverse the order of trims in the loop
// too so they appear continuous
reversed_loop.m_ti.Reverse();
}
}
}
}
int
ON_Boolean(ON_Brep *evaluated_brep, const ON_Brep *brep1, const ON_Brep *brep2, op_type operation)
{
static int calls = 0;
++calls;
std::ostringstream prefix;
prefix << "bool" << calls;
dplot = new DebugPlot(prefix.str().c_str());
dplot->Surfaces(brep1, brep2);
dplot->WriteLog();
ON_ClassArray<ON_SimpleArray<TrimmedFace *> > trimmed_faces;
try {
/* Deal with the trivial cases up front */
if (brep1->BoundingBox().MinimumDistanceTo(brep2->BoundingBox()) > ON_ZERO_TOLERANCE) {
switch (operation) {
case BOOLEAN_UNION:
evaluated_brep->Append(*brep1);
evaluated_brep->Append(*brep2);
break;
case BOOLEAN_DIFF:
evaluated_brep->Append(*brep1);
break;
case BOOLEAN_INTERSECT:
return 0;
break;
default:
throw InvalidBooleanOperation("Error - unknown boolean operation\n");
}
evaluated_brep->ShrinkSurfaces();
evaluated_brep->Compact();
dplot->WriteLog();
return 0;
}
trimmed_faces = get_evaluated_faces(brep1, brep2, operation);
} catch (InvalidBooleanOperation &e) {
bu_log("%s", e.what());
dplot->WriteLog();
return -1;
} catch (GeometryGenerationError &e) {
bu_log("%s", e.what());
dplot->WriteLog();
return -1;
}
int face_count1 = brep1->m_F.Count();
int face_count2 = brep2->m_F.Count();
// check for face counts high enough to cause overflow
if ((face_count1 + face_count2) < 0)
return -1;
for (int i = 0; i < trimmed_faces.Count(); i++) {
const ON_SimpleArray<TrimmedFace *> &splitted = trimmed_faces[i];
const ON_Surface *surf = splitted.Count() ? splitted[0]->m_face->SurfaceOf() : NULL;
bool added = false;
for (int j = 0; j < splitted.Count(); j++) {
TrimmedFace *t_face = splitted[j];
if (t_face->m_belong_to_final == TrimmedFace::BELONG) {
// Add the surfaces, faces, loops, trims, vertices, edges, etc.
// to the brep structure.
if (!added) {
ON_Surface *new_surf = surf->Duplicate();
evaluated_brep->AddSurface(new_surf);
added = true;
}
ON_BrepFace &new_face = evaluated_brep->NewFace(evaluated_brep->m_S.Count() - 1);
add_elements(evaluated_brep, new_face, t_face->m_outerloop, ON_BrepLoop::outer);
// ON_BrepLoop &loop = evaluated_brep->m_L[evaluated_brep->m_L.Count() - 1];
for (unsigned int k = 0; k < t_face->m_innerloop.size(); k++) {
add_elements(evaluated_brep, new_face, t_face->m_innerloop[k], ON_BrepLoop::inner);
}
evaluated_brep->SetTrimIsoFlags(new_face);
const ON_BrepFace &original_face = i >= face_count1 ? brep2->m_F[i - face_count1] : brep1->m_F[i];
if (original_face.m_bRev ^ t_face->m_rev) {
evaluated_brep->FlipFace(new_face);
}
}
}
}
for (int i = 0; i < face_count1 + face_count2; i++) {
for (int j = 0; j < trimmed_faces[i].Count(); j++) {
if (trimmed_faces[i][j]) {
delete trimmed_faces[i][j];
trimmed_faces[i][j] = NULL;
}
}
}
evaluated_brep->ShrinkSurfaces();
evaluated_brep->Compact();
standardize_loop_orientations(evaluated_brep);
// Check IsValid() and output the message.
ON_wString ws;
ON_TextLog log(ws);
evaluated_brep->IsValid(&log);
if (ON_String(ws).Array()) {
bu_log("%s", ON_String(ws).Array());
}
dplot->WriteLog();
delete dplot;
dplot = NULL;
return 0;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
| 122,528 | 50,538 |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_DEBUG_HANDLER_DECEMBER_05_2008_0734PM)
#define BOOST_SPIRIT_DEBUG_HANDLER_DECEMBER_05_2008_0734PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/qi/nonterminal/rule.hpp>
#include <boost/spirit/home/qi/nonterminal/debug_handler_state.hpp>
#include <boost/spirit/home/qi/operator/expect.hpp>
#include <boost/function.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/out.hpp>
#include <iostream>
namespace boost { namespace spirit { namespace qi
{
template <
typename Iterator, typename Context
, typename Skipper, typename F>
struct debug_handler
{
typedef function<
bool(Iterator& first, Iterator const& last
, Context& context
, Skipper const& skipper
)>
function_type;
debug_handler(
function_type subject_
, F f_
, std::string const& rule_name_)
: subject(subject_)
, f(f_)
, rule_name(rule_name_)
{
}
bool operator()(
Iterator& first, Iterator const& last
, Context& context, Skipper const& skipper) const
{
f(first, last, context, pre_parse, rule_name);
try // subject might throw an exception
{
if (subject(first, last, context, skipper))
{
f(first, last, context, successful_parse, rule_name);
return true;
}
f(first, last, context, failed_parse, rule_name);
}
catch (expectation_failure<Iterator> const& e)
{
f(first, last, context, failed_parse, rule_name);
boost::throw_exception(e);
}
return false;
}
function_type subject;
F f;
std::string rule_name;
};
template <typename Iterator
, typename T1, typename T2, typename T3, typename T4, typename F>
void debug(rule<Iterator, T1, T2, T3, T4>& r, F f)
{
typedef rule<Iterator, T1, T2, T3, T4> rule_type;
typedef
debug_handler<
Iterator
, typename rule_type::context_type
, typename rule_type::skipper_type
, F>
debug_handler;
r.f = debug_handler(r.f, f, r.name());
}
struct simple_trace;
namespace detail
{
// This class provides an extra level of indirection through a
// template to produce the simple_trace type. This way, the use
// of simple_trace below is hidden behind a dependent type, so
// that compilers eagerly type-checking template definitions
// won't complain that simple_trace is incomplete.
template<typename T>
struct get_simple_trace
{
typedef simple_trace type;
};
}
template <typename Iterator
, typename T1, typename T2, typename T3, typename T4>
void debug(rule<Iterator, T1, T2, T3, T4>& r)
{
typedef rule<Iterator, T1, T2, T3, T4> rule_type;
typedef
debug_handler<
Iterator
, typename rule_type::context_type
, typename rule_type::skipper_type
, simple_trace>
debug_handler;
typedef typename qi::detail::get_simple_trace<Iterator>::type trace;
r.f = debug_handler(r.f, trace(), r.name());
}
}}}
///////////////////////////////////////////////////////////////////////////////
// Utility macro for easy enabling of rule and grammar debugging
#if !defined(BOOST_SPIRIT_DEBUG_NODE)
#if defined(BOOST_SPIRIT_DEBUG) || defined(BOOST_SPIRIT_QI_DEBUG)
#define BOOST_SPIRIT_DEBUG_NODE(r) r.name(#r); debug(r)
#else
#define BOOST_SPIRIT_DEBUG_NODE(r) r.name(#r)
#endif
#endif
#define BOOST_SPIRIT_DEBUG_NODE_A(r, _, name) \
BOOST_SPIRIT_DEBUG_NODE(name); \
/***/
#define BOOST_SPIRIT_DEBUG_NODES(seq) \
BOOST_PP_SEQ_FOR_EACH(BOOST_SPIRIT_DEBUG_NODE_A, _, seq) \
/***/
#endif
| 4,708 | 1,439 |
{Aviso: Coerção implícita do valor atribuído para 'a', variável a flutuante recebendo um inteiro}
{Erro: Função 'func' do tipo inteiro retornando flutuante}
{Aviso: Função 'func' declarada, mas não utilizada}
{Aviso: Chamada recursiva para a função 'principal'}
{Erro: Função 'principal' deveria retornar inteiro, mas retorna vazio}
flutuante: a
inteiro: b
inteiro func()
a := 10
retorna(a)
fim
inteiro principal()
b := 18
fim
| 435 | 176 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include <iomanip>
#ifdef HAVE_OPENCL
using namespace cv;
using namespace cv::ocl;
using namespace cvtest;
using namespace testing;
using namespace std;
#define FILTER_IMAGE "../../../samples/gpu/road.png"
TEST(SURF, Performance)
{
cv::Mat img = readImage(FILTER_IMAGE, cv::IMREAD_GRAYSCALE);
ASSERT_FALSE(img.empty());
ocl::SURF_OCL d_surf;
ocl::oclMat d_keypoints;
ocl::oclMat d_descriptors;
double totalgputick = 0;
double totalgputick_kernel = 0;
double t1 = 0;
double t2 = 0;
for(int j = 0; j < LOOP_TIMES + 1; j ++)
{
t1 = (double)cvGetTickCount();//gpu start1
ocl::oclMat d_src(img);//upload
t2 = (double)cvGetTickCount(); //kernel
d_surf(d_src, ocl::oclMat(), d_keypoints, d_descriptors);
t2 = (double)cvGetTickCount() - t2;//kernel
cv::Mat cpu_kp, cpu_dp;
d_keypoints.download (cpu_kp);//download
d_descriptors.download (cpu_dp);//download
t1 = (double)cvGetTickCount() - t1;//gpu end1
if(j == 0)
continue;
totalgputick = t1 + totalgputick;
totalgputick_kernel = t2 + totalgputick_kernel;
}
cout << "average gpu runtime is " << totalgputick / ((double)cvGetTickFrequency()* LOOP_TIMES * 1000.) << "ms" << endl;
cout << "average gpu runtime without data transfer is " << totalgputick_kernel / ((double)cvGetTickFrequency()* LOOP_TIMES * 1000.) << "ms" << endl;
}
#endif //Have opencl | 3,736 | 1,162 |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Store;
using namespace std;
using namespace Management::ClusterManager;
StoreDataComposeDeploymentInstanceCounter::StoreDataComposeDeploymentInstanceCounter()
: StoreData()
, value_(0)
{
}
wstring const & StoreDataComposeDeploymentInstanceCounter::get_Type() const
{
return Constants::StoreType_ComposeDeploymentInstanceCounter;
}
wstring StoreDataComposeDeploymentInstanceCounter::ConstructKey() const
{
return Constants::StoreKey_ComposeDeploymentInstanceCounter;
}
void StoreDataComposeDeploymentInstanceCounter::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
w.Write("ComposeDeploymentInstanceCounter[{0}]", value_);
}
ErrorCode StoreDataComposeDeploymentInstanceCounter::GetTypeNameAndVersion(
StoreTransaction const &storeTx,
__out ServiceModelTypeName &typeName,
__out ServiceModelVersion &version)
{
// refresh the latest version from store.
ErrorCode error = storeTx.ReadExact(*this);
if (error.IsSuccess())
{
++value_;
error = storeTx.Update(*this);
}
else if (error.IsError(ErrorCodeValue::NotFound))
{
value_ = 0;
error = storeTx.Insert(*this);
}
if (error.IsSuccess())
{
//
// Application type name is used as a part of the directory name for the package, so using a sequence number to limit the length of
// name.
//
typeName = ServiceModelTypeName(wformatString("{0}{1}", *Constants::ComposeDeploymentTypePrefix, this->Value));
version = StoreDataComposeDeploymentInstanceCounter::GenerateServiceModelVersion(this->Value);
}
return error;
}
ErrorCode StoreDataComposeDeploymentInstanceCounter::GetVersionNumber(ServiceModelVersion const &version, uint64 *versionNumber)
{
auto versionString = version.Value;
StringUtility::TrimLeading<wstring>(versionString, L"v");
if (!StringUtility::TryFromWString(versionString, *versionNumber))
{
return ErrorCodeValue::NotFound;
}
return ErrorCodeValue::Success;
}
ServiceModelVersion StoreDataComposeDeploymentInstanceCounter::GenerateServiceModelVersion(uint64 number)
{
return ServiceModelVersion(wformatString("v{0}", number));
}
| 2,574 | 696 |
#ifndef RECTANGULAR_PARTICLE_HPP
#define RECTANGULAR_PARTICLE_HPP
#include <SFML\Graphics.hpp>
#include "..\..\include\MiniParticle.hpp"
class RectangularParticle : public MiniParticle
{
public:
RectangularParticle();
RectangularParticle(sf::Vector2f pos,sf::Vector2f velocity,sf::Color color,sf::Vector2f size,float lifeTime,bool resize,float gravity,float rotationSpeed,unsigned short ID = 0);
void update(float elapsed,float deltaTime);
const sf::Vector2f& getSize() const;
sf::Color getColor() const;
const sf::Vector2f& getStartSize() const;
float getRotation() const;
float getStartLifeTime() const;
void setSize(sf::Vector2f size);
void setColor(sf::Color color);
private:
sf::Vector2f m_size, m_startSize;
float m_rotationSpeed, m_rotation;
float m_startLifeTime;
bool m_resize;
float m_gravity;
sf::Color m_color;
};
#endif // RECTANGULAR_PARTICLE_HPP
| 885 | 325 |
template <class T>
class BinaryTreeNode {
public:
BinaryTreeNode(const T &e, BinaryTreeNode *lchild, BinaryTreeNode *rchild) {
data = e;
BinaryTreeNode::lchild = lchild;
BinaryTreeNode::rchild = rchild;
}
private:
T data;
BinaryTreeNode<T> *lchild, *rchild;
};
| 308 | 104 |
/********************************************************************************
* File Name:
* listing.hpp
*
* Description:
* List out all the threads in use with the project
*
* 2021 | Brandon Braun | brandonbraun653@gmail.com
*******************************************************************************/
#pragma once
#ifndef VALKYRIE_THREAD_LISTING_HPP
#define VALKYRIE_THREAD_LISTING_HPP
/* Chimera Includes */
#include <Chimera/thread>
namespace Valkyrie::Thread
{
/*-------------------------------------------------------------------------------
Public Functions
-------------------------------------------------------------------------------*/
/**
* @brief Starts up the system threads
*/
void CreateThreads();
/*-------------------------------------------------------------------------------
Background Thread: Idle processing and low priority tasks
-------------------------------------------------------------------------------*/
namespace Background
{
static const std::string_view Name = "Bkgd";
static constexpr size_t StackDepth = STACK_BYTES( 1024 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace Background
/*-------------------------------------------------------------------------------
Hardware Manager: Performs IO access to system hardware
-------------------------------------------------------------------------------*/
namespace HardwareManager
{
static const std::string_view Name = "HWMgr";
static constexpr size_t Period = 5;
static constexpr size_t StackDepth = STACK_BYTES( 2048 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace HardwareManager
/*-------------------------------------------------------------------------------
System Monitor: Watches the system state, like a more complicated watchdog.
-------------------------------------------------------------------------------*/
namespace SystemMonitor
{
static const std::string_view Name = "SYSMon";
static constexpr size_t StackDepth = STACK_BYTES( 1024 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace SystemMonitor
#if defined( SIMULATOR )
/*-------------------------------------------------------------------------------
Simulator Thread: Pumps RX/TX data through the simulator ports
-------------------------------------------------------------------------------*/
namespace Sim
{
static const std::string_view Name = "SimPump";
static constexpr size_t Period = 5;
static constexpr size_t StackDepth = STACK_BYTES( 10 * 1024 );
/**
* @brief Entry for the background thread
*
* @param arg Unused
*/
void main( void *arg );
} // namespace Sim
#endif /* SIMULATOR */
} // namespace Valkyrie::Thread
#endif /* !VALKYRIE_THREAD_LISTING_HPP */
| 3,100 | 808 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* OpenSceneGraph example, osgstereomatch.
*
* 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 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 "StereoMultipass.h"
#include <osgDB/FileUtils>
#include <iostream>
SubtractPass::SubtractPass(osg::TextureRectangle *left_tex,
osg::TextureRectangle *right_tex,
int width, int height,
int start_disparity) :
_TextureWidth(width),
_TextureHeight(height),
_StartDisparity(start_disparity)
{
_RootGroup = new osg::Group;
_InTextureLeft = left_tex;
_InTextureRight = right_tex;
createOutputTextures();
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_subtract.frag");
}
SubtractPass::~SubtractPass()
{
}
osg::ref_ptr<osg::Group> SubtractPass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
_StateSet->setTextureAttributeAndModes(0, _InTextureLeft.get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(1, _InTextureRight.get(), osg::StateAttribute::ON);
_StateSet->addUniform(new osg::Uniform("textureLeft", 0));
_StateSet->addUniform(new osg::Uniform("textureRight", 1));
_StateSet->addUniform(new osg::Uniform("start_disparity", _StartDisparity));
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void SubtractPass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
// attach the 4 textures
for (int i=0; i<4; i++) {
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+i), _OutTexture[i].get());
}
}
void SubtractPass::createOutputTextures()
{
for (int i=0; i<4; i++) {
_OutTexture[i] = new osg::TextureRectangle;
_OutTexture[i]->setTextureSize(_TextureWidth, _TextureHeight);
_OutTexture[i]->setInternalFormat(GL_RGBA);
_OutTexture[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_OutTexture[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
}
}
void SubtractPass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
AggregatePass::AggregatePass(osg::TextureRectangle *diff_tex0,
osg::TextureRectangle *diff_tex1,
osg::TextureRectangle *diff_tex2,
osg::TextureRectangle *diff_tex3,
osg::TextureRectangle *agg_tex_in,
osg::TextureRectangle *agg_tex_out,
int width, int height,
int start_disparity, int window_size):
_TextureWidth(width),
_TextureHeight(height),
_StartDisparity(start_disparity),
_WindowSize(window_size)
{
_RootGroup = new osg::Group;
_InTextureDifference[0] = diff_tex0;
_InTextureDifference[1] = diff_tex1;
_InTextureDifference[2] = diff_tex2;
_InTextureDifference[3] = diff_tex3;
_InTextureAggregate = agg_tex_in;
_OutTextureAggregate = agg_tex_out;
_OutTexture = _OutTextureAggregate;
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_aggregate.frag");
}
AggregatePass::~AggregatePass()
{
}
osg::ref_ptr<osg::Group> AggregatePass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
_StateSet->setTextureAttributeAndModes(0, _InTextureDifference[0].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(1, _InTextureDifference[1].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(2, _InTextureDifference[2].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(3, _InTextureDifference[3].get(), osg::StateAttribute::ON);
_StateSet->setTextureAttributeAndModes(4, _InTextureAggregate.get(), osg::StateAttribute::ON);
_StateSet->addUniform(new osg::Uniform("textureDiff0", 0));
_StateSet->addUniform(new osg::Uniform("textureDiff1", 1));
_StateSet->addUniform(new osg::Uniform("textureDiff2", 2));
_StateSet->addUniform(new osg::Uniform("textureDiff3", 3));
_StateSet->addUniform(new osg::Uniform("textureAggIn", 4));
_StateSet->addUniform(new osg::Uniform("start_disparity", _StartDisparity));
_StateSet->addUniform(new osg::Uniform("window_size", _WindowSize));
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void AggregatePass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+0), _OutTexture.get());
}
void AggregatePass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
SelectPass::SelectPass(osg::TextureRectangle *in_tex,
int width, int height,
int min_disparity, int max_disparity) :
_TextureWidth(width),
_TextureHeight(height),
_MinDisparity(min_disparity),
_MaxDisparity(max_disparity)
{
_RootGroup = new osg::Group;
_InTexture = in_tex;
createOutputTextures();
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_select.frag");
}
SelectPass::~SelectPass()
{
}
osg::ref_ptr<osg::Group> SelectPass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
_StateSet->setTextureAttributeAndModes(0, _InTexture.get(), osg::StateAttribute::ON);
_StateSet->addUniform(new osg::Uniform("textureIn", 0));
_StateSet->addUniform(new osg::Uniform("min_disparity", _MinDisparity));
_StateSet->addUniform(new osg::Uniform("max_disparity", _MaxDisparity));
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void SelectPass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+0), _OutTexture.get());
}
void SelectPass::createOutputTextures()
{
_OutTexture = new osg::TextureRectangle;
_OutTexture->setTextureSize(_TextureWidth, _TextureHeight);
_OutTexture->setInternalFormat(GL_RGBA);
_OutTexture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_OutTexture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
}
void SelectPass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
StereoMultipass::StereoMultipass(osg::TextureRectangle *left_tex,
osg::TextureRectangle *right_tex,
int width, int height,
int min_disparity, int max_disparity, int window_size) :
_TextureWidth(width),
_TextureHeight(height)
{
_RootGroup = new osg::Group;
createOutputTextures();
_Camera = new osg::Camera;
setupCamera();
_Camera->addChild(createTexturedQuad().get());
_RootGroup->addChild(_Camera.get());
setShader("shaders/stereomatch_clear.frag");
flip=1;
flop=0;
// we can do 16 differences in one pass,
// but we must ping-pong the aggregate textures between passes
// add passes until we cover the disparity range
for (int i=min_disparity; i<=max_disparity; i+=16) {
SubtractPass *subp = new SubtractPass(left_tex, right_tex,
width, height,
i);
AggregatePass *aggp = new AggregatePass(subp->getOutputTexture(0).get(),
subp->getOutputTexture(1).get(),
subp->getOutputTexture(2).get(),
subp->getOutputTexture(3).get(),
_OutTexture[flip].get(),
_OutTexture[flop].get(),
width, height,
i, window_size);
_RootGroup->addChild(subp->getRoot().get());
_RootGroup->addChild(aggp->getRoot().get());
flip = flip ? 0 : 1;
flop = flop ? 0 : 1;
}
// add select pass
_SelectPass = new SelectPass(_OutTexture[flip].get(),
width, height,
min_disparity, max_disparity);
_RootGroup->addChild(_SelectPass->getRoot().get());
}
StereoMultipass::~StereoMultipass()
{
}
osg::ref_ptr<osg::Group> StereoMultipass::createTexturedQuad()
{
osg::ref_ptr<osg::Group> top_group = new osg::Group;
osg::ref_ptr<osg::Geode> quad_geode = new osg::Geode;
osg::ref_ptr<osg::Vec3Array> quad_coords = new osg::Vec3Array; // vertex coords
// counter-clockwise
quad_coords->push_back(osg::Vec3d(0, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 0, -1));
quad_coords->push_back(osg::Vec3d(1, 1, -1));
quad_coords->push_back(osg::Vec3d(0, 1, -1));
osg::ref_ptr<osg::Vec2Array> quad_tcoords = new osg::Vec2Array; // texture coords
quad_tcoords->push_back(osg::Vec2(0, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, 0));
quad_tcoords->push_back(osg::Vec2(_TextureWidth, _TextureHeight));
quad_tcoords->push_back(osg::Vec2(0, _TextureHeight));
osg::ref_ptr<osg::Geometry> quad_geom = new osg::Geometry;
osg::ref_ptr<osg::DrawArrays> quad_da = new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4);
osg::ref_ptr<osg::Vec4Array> quad_colors = new osg::Vec4Array;
quad_colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
quad_geom->setVertexArray(quad_coords.get());
quad_geom->setTexCoordArray(0, quad_tcoords.get());
quad_geom->addPrimitiveSet(quad_da.get());
quad_geom->setColorArray(quad_colors.get());
quad_geom->setColorBinding(osg::Geometry::BIND_OVERALL);
_StateSet = quad_geom->getOrCreateStateSet();
_StateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
quad_geode->addDrawable(quad_geom.get());
top_group->addChild(quad_geode.get());
return top_group;
}
void StereoMultipass::setupCamera()
{
// clearing
_Camera->setClearColor(osg::Vec4(10.0f,0.0f,0.0f,1.0f));
_Camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// projection and view
_Camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
_Camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
_Camera->setViewMatrix(osg::Matrix::identity());
// viewport
_Camera->setViewport(0, 0, _TextureWidth, _TextureHeight);
_Camera->setRenderOrder(osg::Camera::PRE_RENDER);
_Camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
// attach two textures for aggregating results
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+0), _OutTexture[0].get());
_Camera->attach(osg::Camera::BufferComponent(osg::Camera::COLOR_BUFFER0+1), _OutTexture[1].get());
}
void StereoMultipass::createOutputTextures()
{
for (int i=0; i<2; i++) {
_OutTexture[i] = new osg::TextureRectangle;
_OutTexture[i]->setTextureSize(_TextureWidth, _TextureHeight);
_OutTexture[i]->setInternalFormat(GL_RGBA);
_OutTexture[i]->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
_OutTexture[i]->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
// hdr, we want to store floats
_OutTexture[i]->setInternalFormat(GL_RGBA16F_ARB);
//_OutTexture[i]->setInternalFormat(GL_FLOAT_RGBA32_NV);
//_OutTexture[i]->setInternalFormat(GL_FLOAT_RGBA16_NV);
_OutTexture[i]->setSourceFormat(GL_RGBA);
_OutTexture[i]->setSourceType(GL_FLOAT);
}
}
void StereoMultipass::setShader(std::string filename)
{
osg::ref_ptr<osg::Shader> fshader = new osg::Shader( osg::Shader::FRAGMENT );
fshader->loadShaderSourceFromFile(osgDB::findDataFile(filename));
_FragmentProgram = 0;
_FragmentProgram = new osg::Program;
_FragmentProgram->addShader(fshader.get());
_StateSet->setAttributeAndModes(_FragmentProgram.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
}
| 19,622 | 7,743 |
// (C) Copyright Gennadiy Rozental 2001-2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile: unit_test.hpp,v $
//
// Version : $Revision: 1.19 $
//
// Description : Entry point for the end user into the Unit Test Framework.
// ***************************************************************************
#ifndef BOOST_TEST_UNIT_TEST_HPP_071894GER
#define BOOST_TEST_UNIT_TEST_HPP_071894GER
// Boost.Test
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_suite.hpp>
//____________________________________________________________________________//
// ************************************************************************** //
// ************** Auto Linking ************** //
// ************************************************************************** //
#if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_TEST_NO_LIB) && \
!defined(BOOST_TEST_SOURCE) && !defined(BOOST_TEST_INCLUDED)
# define BOOST_LIB_NAME boost_unit_test_framework
# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TEST_DYN_LINK)
# define BOOST_DYN_LINK
# endif
# include <boost/config/auto_link.hpp>
#endif // auto-linking disabled
// ************************************************************************** //
// ************** unit_test_main ************** //
// ************************************************************************** //
namespace boost { namespace unit_test {
#if defined(BOOST_TEST_DYN_LINK)
int BOOST_TEST_DECL unit_test_main( bool (*init_unit_test_func)(), int argc, char* argv[] );
#else
int BOOST_TEST_DECL unit_test_main( int argc, char* argv[] );
#endif
}}
#if defined(BOOST_TEST_DYN_LINK) && defined(BOOST_TEST_MAIN) && !defined(BOOST_TEST_NO_MAIN)
// ************************************************************************** //
// ************** main function for tests using dll ************** //
// ************************************************************************** //
int BOOST_TEST_CALL_DECL
main( int argc, char* argv[] )
{
return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );
}
//____________________________________________________________________________//
#endif // BOOST_TEST_DYN_LINK && BOOST_TEST_MAIN && !BOOST_TEST_NO_MAIN
// ***************************************************************************
// Revision History :
//
// $Log: unit_test.hpp,v $
// Revision 1.19 2006/03/19 11:45:26 rogeeff
// main function renamed for consistancy
//
// Revision 1.18 2006/02/07 16:15:20 rogeeff
// BOOST_TEST_INCLUDED guard were missing
//
// Revision 1.17 2006/02/06 10:04:55 rogeeff
// BOOST_TEST_MODULE - master test suite name
//
// Revision 1.16 2005/12/14 05:21:36 rogeeff
// dll support introduced
// auto linking support introduced
//
// Revision 1.15 2005/02/20 08:27:06 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// Revision 1.14 2005/02/01 06:40:06 rogeeff
// copyright update
// old log entries removed
// minor stilistic changes
// depricated tools removed
//
// ***************************************************************************
#endif // BOOST_TEST_UNIT_TEST_HPP_071894GER
| 3,488 | 1,188 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2017 Microsoft
* Licensed under The Apache-2.0 License [see LICENSE for details]
* \file deformable_psroi_pooling.cc
* \brief
* \author Yi Li, Guodong Zhang, Jifeng Dai
*/
#include "./deformable_psroi_pooling-inl.h"
#include <mshadow/base.h>
#include <mshadow/tensor.h>
#include <mshadow/packet-inl.h>
#include <mshadow/dot_engine-inl.h>
#include <cassert>
using std::max;
using std::min;
using std::floor;
using std::ceil;
namespace mshadow {
template<typename DType>
inline void DeformablePSROIPoolForward(const Tensor<cpu, 4, DType> &out,
const Tensor<cpu, 4, DType> &data,
const Tensor<cpu, 2, DType> &bbox,
const Tensor<cpu, 4, DType> &trans,
const Tensor<cpu, 4, DType> &top_count,
const bool no_trans,
const float spatial_scale,
const int output_dim,
const int group_size,
const int pooled_size,
const int part_size,
const int sample_per_part,
const float trans_std) {
// NOT_IMPLEMENTED;
return;
}
template<typename DType>
inline void DeformablePSROIPoolBackwardAcc(const Tensor<cpu, 4, DType> &in_grad,
const Tensor<cpu, 4, DType> &trans_grad,
const Tensor<cpu, 4, DType> &out_grad,
const Tensor<cpu, 4, DType> &data,
const Tensor<cpu, 2, DType> &bbox,
const Tensor<cpu, 4, DType> &trans,
const Tensor<cpu, 4, DType> &top_count,
const bool no_trans,
const float spatial_scale,
const int output_dim,
const int group_size,
const int pooled_size,
const int part_size,
const int sample_per_part,
const float trans_std) {
// NOT_IMPLEMENTED;
return;
}
} // namespace mshadow
namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(DeformablePSROIPoolingParam param, int dtype) {
Operator* op = nullptr;
MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
op = new DeformablePSROIPoolingOp<cpu, DType>(param);
});
return op;
}
Operator *DeformablePSROIPoolingProp::CreateOperatorEx(
Context ctx, std::vector<TShape> *in_shape,
std::vector<int> *in_type) const {
std::vector<TShape> out_shape, aux_shape;
std::vector<int> out_type, aux_type;
CHECK(InferType(in_type, &out_type, &aux_type));
CHECK(InferShape(in_shape, &out_shape, &aux_shape));
DO_BIND_DISPATCH(CreateOp, param_, in_type->at(0));
}
DMLC_REGISTER_PARAMETER(DeformablePSROIPoolingParam);
MXNET_REGISTER_OP_PROPERTY(_contrib_DeformablePSROIPooling, DeformablePSROIPoolingProp)
.describe("Performs deformable position-sensitive region-of-interest pooling on inputs.\n"
"The DeformablePSROIPooling operation is described in https://arxiv.org/abs/1703.06211 ."
"batch_size will change to the number of region bounding boxes after DeformablePSROIPooling")
.add_argument("data", "Symbol", "Input data to the pooling operator, a 4D Feature maps")
.add_argument("rois", "Symbol", "Bounding box coordinates, a 2D array of "
"[[batch_index, x1, y1, x2, y2]]. (x1, y1) and (x2, y2) are top left and down right corners "
"of designated region of interest. batch_index indicates the index of corresponding image "
"in the input data")
.add_argument("trans", "Symbol", "transition parameter")
.add_arguments(DeformablePSROIPoolingParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 4,135 | 1,444 |
/*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include "pjs/pjs.hpp"
#include "data.hpp"
#include <openssl/evp.h>
namespace pipy {
namespace crypto {
//
// AliasType
//
enum class AliasType {
sm2,
};
//
// PublicKey
//
class PublicKey : public pjs::ObjectTemplate<PublicKey> {
public:
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
PublicKey(Data *data, pjs::Object *options);
PublicKey(pjs::Str *data, pjs::Object *options);
~PublicKey();
EVP_PKEY* m_pkey = nullptr;
static auto read_pem(const void *data, size_t size) -> EVP_PKEY*;
friend class pjs::ObjectTemplate<PublicKey>;
};
//
// PrivateKey
//
class PrivateKey : public pjs::ObjectTemplate<PrivateKey> {
public:
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
PrivateKey(Data *data, pjs::Object *options);
PrivateKey(pjs::Str *data, pjs::Object *options);
~PrivateKey();
EVP_PKEY* m_pkey = nullptr;
static auto read_pem(const void *data, size_t size) -> EVP_PKEY*;
friend class pjs::ObjectTemplate<PrivateKey>;
};
//
// Cipher
//
class Cipher : public pjs::ObjectTemplate<Cipher> {
public:
enum class Algorithm {
sm4_cbc,
sm4_ecb,
sm4_cfb,
sm4_cfb128,
sm4_ofb,
sm4_ctr,
};
static auto cipher(Algorithm algorithm) -> const EVP_CIPHER*;
auto update(Data *data) -> Data*;
auto update(pjs::Str *str) -> Data*;
auto final() -> Data*;
private:
Cipher(Algorithm algorithm, pjs::Object *options);
~Cipher();
EVP_CIPHER_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Cipher>;
};
//
// Decipher
//
class Decipher : public pjs::ObjectTemplate<Decipher> {
public:
auto update(Data *data) -> Data*;
auto update(pjs::Str *str) -> Data*;
auto final() -> Data*;
private:
Decipher(Cipher::Algorithm algorithm, pjs::Object *options);
~Decipher();
EVP_CIPHER_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Decipher>;
};
//
// Hash
//
class Hash : public pjs::ObjectTemplate<Hash> {
public:
enum class Algorithm {
md4,
md5,
md5_sha1,
blake2b512,
blake2s256,
sha1,
sha224,
sha256,
sha384,
sha512,
sha512_224,
sha512_256,
sha3_224,
sha3_256,
sha3_384,
sha3_512,
shake128,
shake256,
mdc2,
ripemd160,
whirlpool,
sm3,
};
static auto digest(Algorithm algorithm) -> const EVP_MD*;
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto digest() -> Data*;
auto digest(Data::Encoding enc) -> pjs::Str*;
private:
Hash(Algorithm algorithm);
~Hash();
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Hash>;
};
//
// Hmac
//
class Hmac : public pjs::ObjectTemplate<Hmac> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto digest() -> Data*;
auto digest(Data::Encoding enc) -> pjs::Str*;
private:
Hmac(Hash::Algorithm algorithm, Data *key);
Hmac(Hash::Algorithm algorithm, pjs::Str *key);
~Hmac();
HMAC_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Hmac>;
};
//
// Sign
//
class Sign : public pjs::ObjectTemplate<Sign> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto sign(PrivateKey *key, Object *options = nullptr) -> Data*;
auto sign(PrivateKey *key, Data::Encoding enc, Object *options = nullptr) -> pjs::Str*;
private:
Sign(Hash::Algorithm algorithm);
~Sign();
const EVP_MD* m_md = nullptr;
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Sign>;
};
//
// Verify
//
class Verify : public pjs::ObjectTemplate<Verify> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
bool verify(PublicKey *key, Data *signature, Object *options = nullptr);
bool verify(PublicKey *key, pjs::Str *signature, Data::Encoding enc, Object *options = nullptr);
private:
Verify(Hash::Algorithm algorithm);
~Verify();
const EVP_MD* m_md = nullptr;
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Verify>;
};
//
// JWK
//
class JWK : public pjs::ObjectTemplate<JWK> {
public:
bool is_valid() const { return m_pkey; }
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
JWK(pjs::Object *json);
~JWK();
EVP_PKEY* m_pkey = nullptr;
friend class pjs::ObjectTemplate<JWK>;
};
//
// JWT
//
class JWT : public pjs::ObjectTemplate<JWT> {
public:
enum class Algorithm {
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
ES512,
};
bool is_valid() const { return m_is_valid; }
auto header() const -> const pjs::Value& { return m_header; }
auto payload() const -> const pjs::Value& { return m_payload; }
void sign(pjs::Str *key);
bool verify(Data *key);
bool verify(pjs::Str *key);
bool verify(JWK *key);
private:
JWT(pjs::Str *token);
~JWT();
bool m_is_valid = false;
Algorithm m_algorithm = Algorithm::HS256;
pjs::Value m_header;
pjs::Value m_payload;
std::string m_header_str;
std::string m_payload_str;
std::string m_signature_str;
std::string m_signature;
auto get_md() -> const EVP_MD*;
bool verify(const char *key, int key_len);
bool verify(EVP_PKEY *pkey);
int jose2der(char *out, const char *inp, int len);
friend class pjs::ObjectTemplate<JWT>;
};
//
// Crypto
//
class Crypto : public pjs::ObjectTemplate<Crypto>
{
};
} // namespace crypto
} // namespace pipy
#endif // CRYPTO_HPP | 6,504 | 2,576 |
#define CATCH_CONFIG_MAIN
#define CATCH_CONFIG_NOSTDOUT
#include <catch2/catch.hpp>
class out_buff : public std::stringbuf {
std::FILE *m_stream;
public:
out_buff(std::FILE *stream) : m_stream(stream) {}
~out_buff() { pubsync(); }
int sync() {
int ret = 0;
for (unsigned char c : str()) {
if (putc(c, m_stream) == EOF) {
ret = -1;
break;
}
}
// Reset the buffer to avoid printing it multiple times
str("");
return ret;
}
};
namespace Catch {
std::ostream &cout() {
static std::ostream ret(new out_buff(stdout));
return ret;
}
std::ostream &clog() {
static std::ostream ret(new out_buff(stderr));
return ret;
}
std::ostream &cerr() {
return clog();
}
}
| 708 | 300 |
#include "pch_script.h"
#include "WeaponShotgun.h"
#include "WeaponAutomaticShotgun.h"
using namespace luabind;
#pragma optimize("s",on)
void CWeaponShotgun::script_register (lua_State *L)
{
module(L)
[
class_<CWeaponShotgun,CGameObject>("CWeaponShotgun")
.def(constructor<>()),
class_<CWeaponAutomaticShotgun,CGameObject>("CWeaponAutomaticShotgun")
.def(constructor<>())
];
}
| 409 | 182 |
// Copyright 2015 The Gemmlowp 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 <unistd.h>
#ifdef __APPLE__
#include <sys/time.h>
#endif
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>
#include "../meta/legacy_multi_thread_gemm.h"
#include "../public/gemmlowp.h"
#include "test.h"
// lets include these so we make sure they always compile
#include "../meta/multi_thread_gemm.h"
#include "../meta/multi_thread_transform.h"
#include "../meta/legacy_multi_thread_common.h"
#if defined(__arm__) && !defined(GEMMLOWP_NEON)
#warning "Building without NEON support on ARM, check your compiler setup!"
#endif
double time() {
#ifdef __APPLE__
timeval t;
gettimeofday(&t, nullptr);
return t.tv_sec + 1e-6 * t.tv_usec;
#else
timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv_sec + 1e-9 * t.tv_nsec;
#endif
}
void prepare_test_data(std::uint8_t* data, std::int32_t rows, std::int32_t cols,
std::int32_t seed, std::int32_t seed_2) {
std::int32_t value = seed;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
data[i * cols + j] = static_cast<std::uint8_t>(value);
value = ((value * seed_2) + seed) % 256;
}
}
}
void check_result(std::uint8_t* left, std::uint8_t* right, std::uint8_t* result,
std::int32_t rows, std::int32_t cols, std::int32_t depth,
std::int32_t lhs_offset, std::int32_t rhs_offset,
std::int32_t sum_offset, std::int32_t mul_offset,
std::int32_t shift) {
std::int32_t rounding = (1 << (shift - 1));
std::int32_t wrong = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::int32_t expected = 0;
for (int k = 0; k < depth; ++k) {
expected +=
(static_cast<std::int32_t>(left[depth * i + k]) + lhs_offset) *
(static_cast<std::int32_t>(right[depth * j + k]) + rhs_offset);
}
expected += sum_offset;
expected *= mul_offset;
expected += rounding;
expected = (expected >> shift);
if (expected < 0) {
expected = 0;
} else if (expected > 255) {
expected = 255;
}
expected = static_cast<std::int32_t>(static_cast<std::uint8_t>(expected));
std::int32_t actual = static_cast<std::int32_t>(result[i * cols + j]);
if (actual != expected) {
std::cout << "(" << i << ", " << j << "): " << expected << "!="
<< actual << std::endl;
wrong++;
}
}
}
if (wrong > 0) {
std::cout << "Wrong: " << rows << "x" << cols << "x" << depth << " : "
<< wrong << "/" << (rows * cols) << std::endl
<< std::flush;
std::exit(1);
} else {
std::cout << "." << std::flush;
}
}
void check_result_f(std::uint8_t* left, std::uint8_t* right, float* result,
std::int32_t rows, std::int32_t cols, std::int32_t depth,
std::int32_t lhs_offset, std::int32_t rhs_offset,
float result_offset) {
std::int32_t wrong = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::int32_t expected = 0;
for (int k = 0; k < depth; ++k) {
expected +=
(static_cast<std::int32_t>(left[depth * i + k]) + lhs_offset) *
(static_cast<std::int32_t>(right[depth * j + k]) + rhs_offset);
}
float expected_float = static_cast<float>(expected) * result_offset;
float actual_float = result[i * cols + j];
if (actual_float != expected_float) {
std::cout << "(" << i << ", " << j << "): " << expected_float << "!="
<< actual_float << std::endl;
wrong++;
}
}
}
if (wrong > 0) {
std::cout << "Wrong: " << rows << "x" << cols << "x" << depth << " : "
<< wrong << "/" << (rows * cols) << std::endl
<< std::flush;
std::exit(1);
} else {
std::cout << "." << std::flush;
}
}
void check_result_i32(std::uint8_t* left, std::uint8_t* right,
std::int32_t* result, std::int32_t rows,
std::int32_t cols, std::int32_t depth,
std::int32_t lhs_offset, std::int32_t rhs_offset) {
std::int32_t wrong = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::int32_t expected = 0;
for (int k = 0; k < depth; ++k) {
expected +=
(static_cast<std::int32_t>(left[depth * i + k]) + lhs_offset) *
(static_cast<std::int32_t>(right[depth * j + k]) + rhs_offset);
}
std::int32_t actual = result[i * cols + j];
if (actual != expected) {
std::cout << "(" << i << ", " << j << "): " << expected << "!="
<< actual << std::endl;
wrong++;
}
}
}
if (wrong > 0) {
std::cout << "Wrong: " << rows << "x" << cols << "x" << depth << " : "
<< wrong << "/" << (rows * cols) << std::endl
<< std::flush;
std::exit(1);
} else {
std::cout << "." << std::flush;
}
}
template <typename T>
void clear(T* result, std::int32_t rows, std::int32_t cols) {
for (int i = 0; i < rows * cols; ++i) {
result[i] = static_cast<T>(0);
}
}
void test(std::uint8_t* scratch, std::uint8_t* lhs, std::uint8_t* rhs,
std::int32_t m, std::int32_t n, std::int32_t k, std::uint8_t* result,
gemmlowp::WorkersPool* pool, std::int32_t pool_size) {
prepare_test_data(lhs, m, k, 11, 13);
prepare_test_data(rhs, n, k, 177, 19);
clear(result, m, n);
gemmlowp::meta::multi_thread_gemm_q8(pool, pool_size, scratch, lhs, rhs, m, n,
k, -127, -127, 127 * k, 1, 7, result);
check_result(lhs, rhs, result, m, n, k, -127, -127, 127 * k, 1, 7);
}
void test_f(std::uint8_t* scratch, std::uint8_t* lhs, std::uint8_t* rhs,
std::int32_t m, std::int32_t n, std::int32_t k, float* result,
gemmlowp::WorkersPool* pool, std::int32_t pool_size) {
prepare_test_data(lhs, m, k, 11, 13);
prepare_test_data(rhs, n, k, 177, 19);
clear(result, m, n);
float scale = 1.0f / 1234567.8f;
gemmlowp::meta::multi_thread_gemm_f(pool, pool_size, scratch, lhs, rhs, m, n,
k, -127, -127, scale, result);
check_result_f(lhs, rhs, result, m, n, k, -127, -127, scale);
}
void test_i32(std::uint8_t* scratch, std::uint8_t* lhs, std::uint8_t* rhs,
std::int32_t m, std::int32_t n, std::int32_t k,
std::int32_t* result, gemmlowp::WorkersPool* pool,
std::int32_t pool_size) {
prepare_test_data(lhs, m, k, 11, 13);
prepare_test_data(rhs, n, k, 177, 19);
clear(result, m, n);
gemmlowp::meta::multi_thread_gemm_i32(pool, pool_size, scratch, lhs, rhs, m,
n, k, -127, -127, result);
check_result_i32(lhs, rhs, result, m, n, k, -127, -127);
}
void q_suite(int mi, int ni, int ki, int mx, int nx, int kx, int md, int nd,
int kd, std::uint8_t* scratch, std::uint8_t* left,
std::uint8_t* right, std::uint8_t* result,
gemmlowp::WorkersPool* pool, int t) {
for (int m = mi; m < mx; m += md) {
for (int n = ni; n < nx; n += nd) {
for (int k = ki; k < kx; k += kd) {
test(scratch, left, right, m, n, k, result, pool, t);
}
}
}
std::cout << std::endl;
}
void f_suite(int mi, int ni, int ki, int mx, int nx, int kx, int md, int nd,
int kd, std::uint8_t* scratch, std::uint8_t* left,
std::uint8_t* right, float* result, gemmlowp::WorkersPool* pool,
int t) {
for (int m = mi; m < mx; m += md) {
for (int n = ni; n < nx; n += nd) {
for (int k = ki; k < kx; k += kd) {
test_f(scratch, left, right, m, n, k, result, pool, t);
}
}
}
std::cout << std::endl;
}
void i32_suite(int mi, int ni, int ki, int mx, int nx, int kx, int md, int nd,
int kd, std::uint8_t* scratch, std::uint8_t* left,
std::uint8_t* right, std::int32_t* result,
gemmlowp::WorkersPool* pool, int t) {
for (int m = mi; m < mx; m += md) {
for (int n = ni; n < nx; n += nd) {
for (int k = ki; k < kx; k += kd) {
test_i32(scratch, left, right, m, n, k, result, pool, t);
}
}
}
std::cout << std::endl;
}
int main(int argc, char* argv[]) {
bool run_long_test = false;
if (argc > 1 && strcmp(argv[1], "long")) {
run_long_test = true;
}
const std::int32_t min_n = 1;
const std::int32_t min_m = 1;
const std::int32_t min_k = 8;
const std::int32_t max_n = 1024;
const std::int32_t max_m = 1024;
const std::int32_t max_k = 2048;
std::uint8_t* left = new std::uint8_t[max_m * max_k];
std::uint8_t* right = new std::uint8_t[max_n * max_k];
std::uint8_t* result = new std::uint8_t[max_m * max_n];
float* result_float = new float[max_m * max_n];
std::int32_t* result_i32 = new std::int32_t[max_m * max_n];
std::uint8_t* scratch = new std::uint8_t[1024 * 1024 * 64];
gemmlowp::WorkersPool pool;
int max_repetitions = run_long_test ? 10 : 1;
for (int repetitions = 0; repetitions < max_repetitions; ++repetitions) {
int t = std::min(repetitions + 1, 4);
std::cout << "Threads: " << t << std::endl << std::flush;
std::cout << "Quantized 8 bit." << std::endl << std::flush;
std::cout << "Small." << std::endl << std::flush;
q_suite(1, 1, 1, 16, 16, 32, 1, 1, 1, scratch, left, right, result, &pool,
t);
if (run_long_test) {
std::cout << "Big." << std::endl << std::flush;
q_suite(1, 1, 1, 512, 512, 2048, 111, 111, 111, scratch, left, right,
result, &pool, t);
}
std::cout << "Gemv." << std::endl << std::flush;
q_suite(1, 1, 1, 2, 512, 2048, 1, 111, 111, scratch, left, right, result,
&pool, t);
q_suite(1, 1, 1, 512, 2, 2048, 111, 1, 111, scratch, left, right, result,
&pool, t);
std::cout << std::endl << "Floats." << std::endl << std::flush;
std::cout << "Small." << std::endl << std::flush;
f_suite(1, 1, 1, 16, 16, 32, 1, 1, 1, scratch, left, right, result_float,
&pool, t);
if (run_long_test) {
std::cout << "Big." << std::endl << std::flush;
f_suite(1, 1, 1, 512, 512, 2048, 111, 111, 111, scratch, left, right,
result_float, &pool, t);
}
std::cout << "Gemv." << std::endl << std::flush;
f_suite(1, 1, 1, 2, 512, 2048, 1, 111, 111, scratch, left, right,
result_float, &pool, t);
f_suite(1, 1, 1, 512, 2, 2048, 111, 1, 111, scratch, left, right,
result_float, &pool, t);
std::cout << std::endl << "Int32." << std::endl << std::flush;
std::cout << "Small." << std::endl << std::flush;
i32_suite(1, 1, 1, 16, 16, 32, 1, 1, 1, scratch, left, right, result_i32,
&pool, t);
if (run_long_test) {
std::cout << "Big." << std::endl << std::flush;
i32_suite(1, 1, 1, 512, 512, 2048, 111, 111, 111, scratch, left, right,
result_i32, &pool, t);
}
std::cout << "Gemv." << std::endl << std::flush;
i32_suite(1, 1, 1, 2, 512, 2048, 1, 111, 111, scratch, left, right,
result_i32, &pool, t);
i32_suite(1, 1, 1, 512, 2, 2048, 111, 1, 111, scratch, left, right,
result_i32, &pool, t);
std::cout << std::endl << std::flush;
}
std::cout << "Done." << std::endl << std::flush;
}
| 12,064 | 5,040 |
//
// Copyright (C) 2007-2013 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <DataStructs/SparseIntVect.h>
#include <RDGeneral/hash/hash.hpp>
#include <cstdint>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
#include <GraphMol/Fingerprints/FingerprintUtil.h>
namespace RDKit {
namespace AtomPairs {
template <typename T1, typename T2>
void updateElement(SparseIntVect<T1> &v, T2 elem) {
v.setVal(elem, v.getVal(elem) + 1);
}
template <typename T1>
void updateElement(ExplicitBitVect &v, T1 elem) {
v.setBit(elem % v.getNumBits());
}
template <typename T>
void setAtomPairBit(std::uint32_t i, std::uint32_t j,
std::uint32_t nAtoms,
const std::vector<std::uint32_t> &atomCodes,
const double *dm, T *bv, unsigned int minLength,
unsigned int maxLength, bool includeChirality) {
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bitId =
getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);
updateElement(*bv, static_cast<std::uint32_t>(bitId));
}
}
SparseIntVect<std::int32_t> *getAtomPairFingerprint(
const ROMol &mol, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D,
confId);
};
SparseIntVect<std::int32_t> *getAtomPairFingerprint(
const ROMol &mol, unsigned int minLength, unsigned int maxLength,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
auto *res = new SparseIntVect<std::int32_t>(
1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(*lmol);
} else {
dm = MolOps::get3DDistanceMat(*lmol, confId);
}
const unsigned int nAtoms = lmol->getNumAtoms();
std::vector<std::uint32_t> atomCodes;
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %
((1 << codeSize) - 1));
}
}
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != lmol->endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
} else {
BOOST_FOREACH (std::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
}
}
}
return res;
}
SparseIntVect<std::int32_t> *getHashedAtomPairFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
auto *res = new SparseIntVect<std::int32_t>(nBits);
const double *dm;
try {
if (use2D) {
dm = MolOps::getDistanceMat(*lmol);
} else {
dm = MolOps::get3DDistanceMat(*lmol, confId);
}
} catch (const ConformerException &) {
delete res;
throw;
}
const unsigned int nAtoms = lmol->getNumAtoms();
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(nAtoms);
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);
}
}
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != lmol->endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<std::int32_t>(bit % nBits));
}
}
} else {
BOOST_FOREACH (std::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<std::int32_t>(bit % nBits));
}
}
}
}
}
return res;
}
ExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<std::int32_t> *sres = getHashedAtomPairFingerprint(
mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D, confId);
auto *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i)) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
SparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
boost::uint64_t sz = 1;
sz = (sz << (targetSize *
(codeSize + (includeChirality ? numChiralBits : 0))));
// NOTE: this -1 is incorrect but it's needed for backwards compatibility.
// hopefully we'll never have a case with a torsion that hits this.
//
// mmm, bug compatible.
sz -= 1;
auto *res = new SparseIntVect<boost::int64_t>(sz);
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(lmol->getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(
(*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);
}
}
boost::dynamic_bitset<> *fromAtomsBV = nullptr;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
boost::dynamic_bitset<> pAtoms(lmol->getNumAtoms());
PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
std::vector<std::uint32_t> pathCodes;
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
pAtoms.reset();
for (auto pIt = path.begin(); pIt < path.end(); ++pIt) {
// look for a cycle that doesn't start at the first atom
// we can't effectively canonicalize these at the moment
// (was github #811)
if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {
pathCodes.clear();
break;
}
pAtoms.set(*pIt);
unsigned int code = atomCodes[*pIt] - 1;
// subtract off the branching number:
if (pIt != path.begin() && pIt + 1 != path.end()) {
--code;
}
pathCodes.push_back(code);
}
if (pathCodes.size()) {
boost::int64_t code =
getTopologicalTorsionCode(pathCodes, includeChirality);
updateElement(*res, code);
}
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
return res;
}
namespace {
template <typename T>
void TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,
unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(lmol->getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);
}
}
boost::dynamic_bitset<> *fromAtomsBV = nullptr;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
std::vector<std::uint32_t> pathCodes(targetSize);
for (unsigned int i = 0; i < targetSize; ++i) {
unsigned int code = atomCodes[path[i]] - 1;
// subtract off the branching number:
if (i > 0 && i < targetSize - 1) {
--code;
}
pathCodes[i] = code;
}
size_t bit = getTopologicalTorsionHash(pathCodes);
updateElement(*res, bit % nBits);
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
}
} // namespace
SparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
auto *res = new SparseIntVect<boost::int64_t>(nBits);
TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
return res;
}
ExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
auto *sres = new SparseIntVect<boost::int64_t>(blockLength);
TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
auto *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i)) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
} // end of namespace AtomPairs
} // end of namespace RDKit
| 18,412 | 6,680 |
#include "LoopManager.hpp"
LoopManager::LoopManager(const sf::Time & _timePerFrame)
:timePerFrame(_timePerFrame)
{
timeSinceLastUpdate = sf::Time::Zero;
}
void LoopManager::increaseTime()
{
timeSinceLastUpdate += clock.restart();
}
bool LoopManager::canChangeTheFrame()
{
return timeSinceLastUpdate <= timePerFrame;
}
void LoopManager::reduceTime()
{
timeSinceLastUpdate -= timePerFrame;
}
| 404 | 134 |
#include "label_utils.h"
#include <QtXml/QDomDocument>
#include <QtCore/QFile>
#include <QtCore/QStringList>
#include <QtCore/QString>
void getLabelNames(const std::string& filename,
std::map<uint32_t, std::string>& label_names)
{
QDomDocument doc("mydocument");
QFile file(QString::fromStdString(filename));
if (!file.open(QIODevice::ReadOnly)) return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomElement rootNode = doc.firstChildElement("config");
QDomElement n = rootNode.firstChildElement("label");
for (; !n.isNull(); n = n.nextSiblingElement("label"))
{
std::string name = n.firstChildElement("name").text().toStdString();
uint32_t id = n.firstChildElement("id").text().toInt();
label_names[id] = name;
}
}
void getLabelColors(const std::string& filename,
std::map<uint32_t, glow::GlColor>& label_colors)
{
QDomDocument doc("mydocument");
QFile file(QString::fromStdString(filename));
if (!file.open(QIODevice::ReadOnly)) return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomElement rootNode = doc.firstChildElement("config");
QDomElement n = rootNode.firstChildElement("label");
for (; !n.isNull(); n = n.nextSiblingElement("label"))
{
std::string name = n.firstChildElement("name").text().toStdString();
uint32_t id = n.firstChildElement("id").text().toInt();
QString color_string = n.firstChildElement("color").text();
QStringList tokens = color_string.split(" ");
int32_t R = tokens.at(0).toInt();
int32_t G = tokens.at(1).toInt();
int32_t B = tokens.at(2).toInt();
label_colors[id] = glow::GlColor::FromRGB(R, G, B);
}
}
| 1,811 | 657 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/Util.h"
#include "nsIDOMHTMLDivElement.h"
#include "nsIDOMEventTarget.h"
#include "nsGenericHTMLElement.h"
#include "nsGkAtoms.h"
#include "nsStyleConsts.h"
#include "nsMappedAttributes.h"
using namespace mozilla;
class nsHTMLDivElement : public nsGenericHTMLElement,
public nsIDOMHTMLDivElement
{
public:
nsHTMLDivElement(already_AddRefed<nsINodeInfo> aNodeInfo);
virtual ~nsHTMLDivElement();
// nsISupports
NS_DECL_ISUPPORTS_INHERITED
// nsIDOMNode
NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::)
// nsIDOMElement
NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLElement::)
// nsIDOMHTMLElement
NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLElement::)
// nsIDOMHTMLDivElement
NS_DECL_NSIDOMHTMLDIVELEMENT
virtual bool ParseAttribute(int32_t aNamespaceID,
nsIAtom* aAttribute,
const nsAString& aValue,
nsAttrValue& aResult);
NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const;
virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
virtual nsXPCClassInfo* GetClassInfo();
virtual nsIDOMNode* AsDOMNode() { return this; }
};
NS_IMPL_NS_NEW_HTML_ELEMENT(Div)
nsHTMLDivElement::nsHTMLDivElement(already_AddRefed<nsINodeInfo> aNodeInfo)
: nsGenericHTMLElement(aNodeInfo)
{
}
nsHTMLDivElement::~nsHTMLDivElement()
{
}
NS_IMPL_ADDREF_INHERITED(nsHTMLDivElement, nsGenericElement)
NS_IMPL_RELEASE_INHERITED(nsHTMLDivElement, nsGenericElement)
DOMCI_NODE_DATA(HTMLDivElement, nsHTMLDivElement)
// QueryInterface implementation for nsHTMLDivElement
NS_INTERFACE_TABLE_HEAD(nsHTMLDivElement)
NS_HTML_CONTENT_INTERFACE_TABLE1(nsHTMLDivElement, nsIDOMHTMLDivElement)
NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLDivElement,
nsGenericHTMLElement)
NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLDivElement)
NS_IMPL_ELEMENT_CLONE(nsHTMLDivElement)
NS_IMPL_STRING_ATTR(nsHTMLDivElement, Align, align)
bool
nsHTMLDivElement::ParseAttribute(int32_t aNamespaceID,
nsIAtom* aAttribute,
const nsAString& aValue,
nsAttrValue& aResult)
{
if (aNamespaceID == kNameSpaceID_None) {
if (mNodeInfo->Equals(nsGkAtoms::marquee)) {
if ((aAttribute == nsGkAtoms::width) ||
(aAttribute == nsGkAtoms::height)) {
return aResult.ParseSpecialIntValue(aValue);
}
if (aAttribute == nsGkAtoms::bgcolor) {
return aResult.ParseColor(aValue);
}
if ((aAttribute == nsGkAtoms::hspace) ||
(aAttribute == nsGkAtoms::vspace)) {
return aResult.ParseIntWithBounds(aValue, 0);
}
}
if (mNodeInfo->Equals(nsGkAtoms::div) &&
aAttribute == nsGkAtoms::align) {
return ParseDivAlignValue(aValue, aResult);
}
}
return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
aResult);
}
static void
MapAttributesIntoRule(const nsMappedAttributes* aAttributes, nsRuleData* aData)
{
nsGenericHTMLElement::MapDivAlignAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapCommonAttributesInto(aAttributes, aData);
}
static void
MapMarqueeAttributesIntoRule(const nsMappedAttributes* aAttributes, nsRuleData* aData)
{
nsGenericHTMLElement::MapImageMarginAttributeInto(aAttributes, aData);
nsGenericHTMLElement::MapImageSizeAttributesInto(aAttributes, aData);
nsGenericHTMLElement::MapCommonAttributesInto(aAttributes, aData);
nsGenericHTMLElement::MapBGColorInto(aAttributes, aData);
}
NS_IMETHODIMP_(bool)
nsHTMLDivElement::IsAttributeMapped(const nsIAtom* aAttribute) const
{
if (mNodeInfo->Equals(nsGkAtoms::div)) {
static const MappedAttributeEntry* const map[] = {
sDivAlignAttributeMap,
sCommonAttributeMap
};
return FindAttributeDependence(aAttribute, map);
}
if (mNodeInfo->Equals(nsGkAtoms::marquee)) {
static const MappedAttributeEntry* const map[] = {
sImageMarginSizeAttributeMap,
sBackgroundColorAttributeMap,
sCommonAttributeMap
};
return FindAttributeDependence(aAttribute, map);
}
return nsGenericHTMLElement::IsAttributeMapped(aAttribute);
}
nsMapRuleToAttributesFunc
nsHTMLDivElement::GetAttributeMappingFunction() const
{
if (mNodeInfo->Equals(nsGkAtoms::div)) {
return &MapAttributesIntoRule;
}
if (mNodeInfo->Equals(nsGkAtoms::marquee)) {
return &MapMarqueeAttributesIntoRule;
}
return nsGenericHTMLElement::GetAttributeMappingFunction();
}
| 5,027 | 1,697 |
////////////////////////////////////////////////////////////////////////////
//
// splitex.cpp
// Based upon code from Oleg G. Galkin
// Modified to handle multiple hidden rows
#include "stdafx.h"
#include "splitex.h"
#if defined(_DEBUG) && !defined(MMGR)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
////////////////////////////////////////////////////////////////////////////
//
// CSplitterWndEx
CSplitterWndEx::CSplitterWndEx()
{
m_arr = 0;
m_length = 0;
}
CSplitterWndEx::~CSplitterWndEx()
{
delete [] m_arr;
}
int CSplitterWndEx::Id_short(int row, int col)
{
return AFX_IDW_PANE_FIRST + row * 16 + col;
}
void CSplitterWndEx::ShowRow(int r)
{
ASSERT_VALID(this);
ASSERT(m_nRows < m_nMaxRows);
ASSERT(m_arr);
ASSERT(r < m_length);
ASSERT(m_arr[r] >= m_nRows);
ASSERT(m_arr[r] < m_length);
int rowNew = r;
int cyNew = m_pRowInfo[m_arr[r]].nCurSize;
int cyIdealNew = m_pRowInfo[m_arr[r]].nIdealSize;
int new_val = 0;
for (int i = rowNew - 1; i >= 0; i--)
if (m_arr[i] < m_nRows) // not hidden
{
new_val = m_arr[i] + 1;
break;
}
int old_val = m_arr[rowNew];
m_nRows++; // add a row
// fill the hided row
int row;
for (int col = 0; col < m_nCols; col++)
{
CWnd* pPaneShow = GetDlgItem(
Id_short(old_val, col));
ASSERT(pPaneShow != NULL);
pPaneShow->ShowWindow(SW_SHOWNA);
for (row = m_length - 1; row >= 0; row--)
{
if ((m_arr[row] >= new_val) &&
(m_arr[row] < old_val))
{
CWnd* pPane = CSplitterWnd::GetPane(m_arr[row], col);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(m_arr[row] + 1, col));
}
}
pPaneShow->SetDlgCtrlID(Id_short(new_val, col));
}
for (row = 0; row < m_length; row++)
if ((m_arr[row] >= new_val) &&
(m_arr[row] < old_val))
m_arr[row]++;
m_arr[rowNew] = new_val;
//new panes have been created -- recalculate layout
for (row = new_val + 1; row < m_length; row++)
{
if (m_arr[row]<m_nRows)
{
m_pRowInfo[m_arr[row]].nIdealSize = m_pRowInfo[m_arr[row-1]].nCurSize;
m_pRowInfo[m_arr[row]].nCurSize = m_pRowInfo[m_arr[row-1]].nCurSize;
}
}
if (cyNew>=0x10000)
{
int rowToResize=(cyNew>>16)-1;
cyNew%=0x10000;
cyIdealNew%=0x10000;
m_pRowInfo[m_arr[rowToResize]].nCurSize-=cyNew+m_cxSplitter;
m_pRowInfo[m_arr[rowToResize]].nIdealSize=m_pRowInfo[m_arr[rowToResize]].nCurSize;//-=cyIdealNew+m_cxSplitter;
}
m_pRowInfo[new_val].nIdealSize = cyNew;
m_pRowInfo[new_val].nCurSize = cyNew;
RecalcLayout();
}
void CSplitterWndEx::ShowColumn(int c)
{
ASSERT_VALID(this);
ASSERT(m_nCols < m_nMaxCols);
ASSERT(m_arr);
ASSERT(c < m_length);
ASSERT(m_arr[c] >= m_nRows);
ASSERT(m_arr[c] < m_length);
int colNew = c;
int cxNew = m_pColInfo[m_arr[c]].nCurSize;
int cxIdealNew = m_pColInfo[m_arr[c]].nIdealSize;
int new_val = 0;
for (int i = colNew - 1; i >= 0; i--)
if (m_arr[i] < m_nCols) // not hidden
{
new_val = m_arr[i] + 1;
break;
}
int old_val = m_arr[colNew];
m_nCols++; // add a col
// fill the hided col
int col;
for (int row = 0; row < m_nRows; row++)
{
CWnd* pPaneShow = GetDlgItem(
Id_short(row, old_val));
ASSERT(pPaneShow != NULL);
pPaneShow->ShowWindow(SW_SHOWNA);
for (col = m_length - 1; col >= 0; col--)
{
if ((m_arr[col] >= new_val) &&
(m_arr[col] < old_val))
{
CWnd* pPane = CSplitterWnd::GetPane(row, m_arr[col]);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row, m_arr[col]+1));
}
}
pPaneShow->SetDlgCtrlID(Id_short(row, new_val));
}
for (col = 0; col < m_length; col++)
if ((m_arr[col] >= new_val) &&
(m_arr[col] < old_val))
m_arr[col]++;
m_arr[colNew] = new_val;
//new panes have been created -- recalculate layout
for (col = new_val + 1; col < m_length; col++)
{
if (m_arr[col]<m_nCols)
{
m_pColInfo[m_arr[col]].nIdealSize = m_pColInfo[m_arr[col-1]].nCurSize;
m_pColInfo[m_arr[col]].nCurSize = m_pColInfo[m_arr[col-1]].nCurSize;
}
}
if (cxNew>=0x10000)
{
int colToResize=(cxNew>>16)-1;
cxNew%=0x10000;
cxIdealNew%=0x10000;
m_pColInfo[m_arr[colToResize]].nCurSize-=cxNew+m_cySplitter;
m_pColInfo[m_arr[colToResize]].nIdealSize=m_pColInfo[m_arr[colToResize]].nCurSize;//-=cxIdealNew+m_cySplitter;
}
m_pColInfo[new_val].nIdealSize = cxNew;
m_pColInfo[new_val].nCurSize = cxNew;
RecalcLayout();
}
void CSplitterWndEx::HideRow(int rowHide,int rowToResize)
{
ASSERT_VALID(this);
ASSERT(m_nRows > 1);
if (m_arr)
ASSERT(m_arr[rowHide] < m_nRows);
// if the row has an active window -- change it
int rowActive, colActive;
if (!m_arr)
{
m_arr = new int[m_nRows];
for (int i = 0; i < m_nRows; i++)
m_arr[i] = i;
m_length = m_nRows;
}
if (GetActivePane(&rowActive, &colActive) != NULL &&
rowActive == rowHide) //colActive == rowHide)
{
if (++rowActive >= m_nRows)
rowActive = 0;
//SetActivePane(rowActive, colActive);
SetActivePane(rowActive, colActive);
}
// hide all row panes
for (int col = 0; col < m_nCols; col++)
{
CWnd* pPaneHide = CSplitterWnd::GetPane(m_arr[rowHide], col);
ASSERT(pPaneHide != NULL);
pPaneHide->ShowWindow(SW_HIDE);
for (int row = rowHide + 1; row < m_length; row++)
{
if (m_arr[row] < m_nRows )
{
CWnd* pPane = CSplitterWnd::GetPane(m_arr[row], col);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row-1, col));
m_arr[row]--;
}
}
pPaneHide->SetDlgCtrlID(
Id_short(m_nRows -1 , col));
}
int oldsize=m_pRowInfo[m_arr[rowHide]].nCurSize;
for (int row=rowHide;row<(m_length-1);row++)
{
if (m_arr[row+1] < m_nRows )
{
m_pRowInfo[m_arr[row]].nCurSize=m_pRowInfo[m_arr[row+1]].nCurSize;
m_pRowInfo[m_arr[row]].nIdealSize=m_pRowInfo[m_arr[row+1]].nCurSize;
}
}
if (rowToResize!=-1)
{
m_pRowInfo[m_arr[rowToResize]].nCurSize+=oldsize+m_cySplitter;
m_pRowInfo[m_arr[rowToResize]].nIdealSize+=oldsize+m_cySplitter;
oldsize+=0x10000*(rowToResize+1);
}
m_pRowInfo[m_nRows - 1].nCurSize =oldsize;
m_pRowInfo[m_nRows - 1].nIdealSize =oldsize;
m_arr[rowHide] = m_nRows-1;
m_nRows--;
RecalcLayout();
}
void CSplitterWndEx::HideColumn(int colHide, int colToResize)
{
ASSERT_VALID(this);
ASSERT(m_nCols > 1);
if (m_arr)
ASSERT(m_arr[colHide] < m_nCols);
// if the col has an active window -- change it
int colActive, rowActive;
if (!m_arr)
{
m_arr = new int[m_nCols];
for (int i = 0; i < m_nCols; i++)
m_arr[i] = i;
m_length = m_nCols;
}
if (GetActivePane(&rowActive, &colActive) != NULL &&
colActive == colHide)
{
if (++colActive >= m_nCols)
colActive = 0;
SetActivePane(rowActive, colActive);
}
// hide all row panes
for (int row = 0; row < m_nRows; row++)
{
CWnd* pPaneHide = CSplitterWnd::GetPane(row, m_arr[colHide]);
ASSERT(pPaneHide != NULL);
pPaneHide->ShowWindow(SW_HIDE);
for (int col = colHide + 1; col < m_length; col++)
{
if (m_arr[col] < m_nCols )
{
CWnd* pPane = CSplitterWnd::GetPane(row, m_arr[col]);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row, col-1));
m_arr[col]--;
}
}
pPaneHide->SetDlgCtrlID(
Id_short(row, m_nCols -1));
}
int oldsize = m_pColInfo[m_arr[colHide]].nCurSize;
for (int col = colHide; col < (m_length - 1); ++col)
{
if (m_arr[col + 1] < m_nCols)
{
m_pColInfo[m_arr[col]].nCurSize = m_pColInfo[m_arr[col + 1]].nCurSize;
m_pColInfo[m_arr[col]].nIdealSize = m_pColInfo[m_arr[col + 1]].nCurSize;
}
}
if (colToResize != -1)
{
m_pColInfo[m_arr[colToResize]].nCurSize += oldsize + m_cxSplitter;
m_pColInfo[m_arr[colToResize]].nIdealSize += oldsize + m_cxSplitter;
oldsize += 0x10000 * (colToResize + 1);
}
m_pColInfo[m_nCols - 1].nCurSize = oldsize;
m_pColInfo[m_nCols - 1].nIdealSize = oldsize;
m_arr[colHide] = m_nCols - 1;
m_nCols--;
RecalcLayout();
}
BEGIN_MESSAGE_MAP(CSplitterWndEx, CSplitterWnd)
//{{AFX_MSG_MAP(CSplitterWndEx)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CWnd* CSplitterWndEx::GetPane(int row, int col)
{
if (!m_arr)
return CSplitterWnd::GetPane(row,col);
else
{
ASSERT_VALID(this);
CWnd* pView = GetDlgItem(IdFromRowCol(m_arr[row], col));
ASSERT(pView != NULL); // panes can be a CWnd, but are usually CViews
return pView;
}
}
int CSplitterWndEx::IdFromRowCol(int row, int col) const
{
ASSERT_VALID(this);
ASSERT(row >= 0);
ASSERT(row < (m_arr?m_length:m_nRows));
ASSERT(col >= 0);
ASSERT(col < m_nCols);
return AFX_IDW_PANE_FIRST + row * 16 + col;
}
BOOL CSplitterWndEx::IsChildPane(CWnd* pWnd, int* pRow, int* pCol)
{
ASSERT_VALID(this);
ASSERT_VALID(pWnd);
UINT nID = ::GetDlgCtrlID(pWnd->m_hWnd);
if (IsChild(pWnd) && nID >= AFX_IDW_PANE_FIRST && nID <= AFX_IDW_PANE_LAST)
{
if (pWnd->GetParent()!=this)
return FALSE;
if (pRow != NULL)
*pRow = (nID - AFX_IDW_PANE_FIRST) / 16;
if (pCol != NULL)
*pCol = (nID - AFX_IDW_PANE_FIRST) % 16;
ASSERT(pRow == NULL || *pRow < (m_arr?m_length:m_nRows));
ASSERT(pCol == NULL || *pCol < m_nCols);
return TRUE;
}
else
{
if (pRow != NULL)
*pRow = -1;
if (pCol != NULL)
*pCol = -1;
return FALSE;
}
}
CWnd* CSplitterWndEx::GetActivePane(int* pRow, int* pCol)
// return active view, NULL when no active view
{
ASSERT_VALID(this);
// attempt to use active view of frame window
CWnd* pView = NULL;
CFrameWnd* pFrameWnd = GetParentFrame();
ASSERT_VALID(pFrameWnd);
pView = pFrameWnd->GetActiveView();
// failing that, use the current focus
if (pView == NULL)
pView = GetFocus();
// make sure the pane is a child pane of the splitter
if (pView != NULL && !IsChildPane(pView, pRow, pCol))
pView = NULL;
return pView;
}
BOOL CSplitterWndEx::IsRowHidden(int row)
{
return m_arr[row]>=m_nRows;
}
void CSplitterWndEx::GetRowInfoEx(int row, int &cyCur, int &cyMin)
{
if (!m_arr)
GetRowInfo(row,cyCur,cyMin);
else
{
if (m_pRowInfo[m_arr[row]].nCurSize>0x10000)
cyCur=m_pRowInfo[m_arr[row]].nCurSize/0x10000;
else
cyCur=m_pRowInfo[m_arr[row]].nCurSize%0x10000;
cyMin=0;
}
}
__int64 CSplitterWndEx::GetSizes() const
{
LARGE_INTEGER v;
int dummy;
int s1, s2;
if (BarIsHorizontal())
{
GetRowInfo(0, s1, dummy);
GetRowInfo(1, s2, dummy);
v.HighPart = s1;
v.LowPart = s2;
}
else
{
GetColumnInfo(0, s1, dummy);
GetColumnInfo(1, s2, dummy);
v.HighPart = s1;
v.LowPart = s2;
}
return v.QuadPart;
}
| 11,109 | 5,406 |
////////////////////////////////////////////////////////////
//
// PySFML - Python binding for SFML (Simple and Fast Multimedia Library)
// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#include "Shape.hpp"
#include <SFML/Graphics/Color.hpp>
#include "Color.hpp"
#include "compat.hpp"
extern PyTypeObject PySfColorType;
extern PyTypeObject PySfDrawableType;
static void
PySfShape_dealloc(PySfShape* self)
{
delete self->obj;
free_object(self);
}
static PyObject *
PySfShape_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PySfShape *self;
self = (PySfShape *)type->tp_alloc(type, 0);
if (self != NULL)
{
self->obj = new sf::Shape();
self->IsCustom = false;
}
return (PyObject *)self;
}
// void AddPoint(float X, float Y, const Color& Col = Color(255, 255, 255), const Color& OutlineCol = Color(0, 0, 0));
static PyObject *
PySfShape_AddPoint(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X", "Y", "Col", "OutlineCol", NULL};
float X, Y;
sf::Color *Col, *OutlineCol;
PySfColor *ColTmp=NULL, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "ff|O!O!:Shape.AddPoint", (char **)kwlist, &X, &Y, &PySfColorType, &ColTmp, &PySfColorType, &OutlineColTmp))
return NULL;
if (ColTmp)
{
PySfColorUpdate(ColTmp);
Col = ColTmp->obj;
}
else
Col = (sf::Color *)&sf::Color::White;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
self->obj->AddPoint(X, Y, *Col, *OutlineCol);
Py_RETURN_NONE;
}
static PyObject *
PySfShape_SetOutlineWidth(PySfShape* self, PyObject *args)
{
self->obj->SetOutlineWidth(PyFloat_AsDouble(args));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_GetOutlineWidth(PySfShape* self)
{
return PyFloat_FromDouble(self->obj->GetOutlineWidth());
}
// static Shape Line(float X0, float Y0, float X1, float Y1, float Thickness, const Color& Col, float Outline = 0.f, const Color& OutlineCol = sf::Color(0, 0, 0));
static PyObject *
PySfShape_Line(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X0", "Y0", "X1", "Y1", "Thickness", "Col", "Outline", "OutlineCol", NULL};
PySfShape *Line = GetNewPySfShape();
float X0, Y0, X1, Y1, Thickness, Outline = 0.f;
sf::Color *OutlineCol;
PySfColor *ColTmp, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffffO!|fO!:Shape.Line", (char **)kwlist, &X0, &Y0, &X1, &Y1, &Thickness, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp))
return NULL;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
PySfColorUpdate(ColTmp);
Line->obj = new sf::Shape(sf::Shape::Line(X0, Y0, X1, Y1, Thickness, *(ColTmp->obj), Outline, *OutlineCol));
return (PyObject *)Line;
}
// static Shape Rectangle(float X0, float Y0, float X1, float Y1, const Color& Col, float Outline = 0.f, const Color& OutlineCol = sf::Color(0, 0, 0));
static PyObject *
PySfShape_Rectangle(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X0", "Y0", "X1", "Y1", "Col", "Outline", "OutlineCol", NULL};
PySfShape *Rectangle = GetNewPySfShape();
float X0, Y0, X1, Y1, Outline = 0.f;
sf::Color *OutlineCol;
PySfColor *ColTmp, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "ffffO!|fO!:Shape.Rectangle", (char **)kwlist, &X0, &Y0, &X1, &Y1, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp))
return NULL;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
PySfColorUpdate(ColTmp);
Rectangle->obj = new sf::Shape(sf::Shape::Rectangle(X0, Y0, X1, Y1, *(ColTmp->obj), Outline, *OutlineCol));
return (PyObject *)Rectangle;
}
// static Shape Circle(float X, float Y, float Radius, const Color& Col, float Outline = 0.f, const Color& OutlineCol = sf::Color(0, 0, 0));
static PyObject *
PySfShape_Circle(PySfShape* self, PyObject *args, PyObject *kwds)
{
const char *kwlist[] = {"X", "Y", "Radius", "Col", "Outline", "OutlineCol", NULL};
PySfShape *Circle = GetNewPySfShape();
float X, Y, Radius, Outline = 0.f;
sf::Color *OutlineCol;
PySfColor *ColTmp, *OutlineColTmp=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffO!|fO!:Shape.Circle", (char **)kwlist, &X, &Y, &Radius, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp))
return NULL;
if (OutlineColTmp)
{
PySfColorUpdate(OutlineColTmp);
OutlineCol = OutlineColTmp->obj;
}
else
OutlineCol = (sf::Color *)&sf::Color::Black;
PySfColorUpdate(ColTmp);
Circle->obj = new sf::Shape(sf::Shape::Circle(X, Y, Radius, *(ColTmp->obj), Outline, *OutlineCol));
return (PyObject *)Circle;
}
static PyObject *
PySfShape_GetPointPosition(PySfShape* self, PyObject *args)
{
sf::Vector2f result = self->obj->GetPointPosition(PyLong_AsUnsignedLong(args));
return Py_BuildValue("ff", result.x, result.y);
}
static PyObject *
PySfShape_GetPointColor(PySfShape* self, PyObject *args)
{
PySfColor *PyColor = GetNewPySfColor();
PyColor->obj = new sf::Color(self->obj->GetPointColor(PyLong_AsUnsignedLong(args)));
PyColor->r = PyColor->obj->r;
PyColor->g = PyColor->obj->g;
PyColor->b = PyColor->obj->b;
PyColor->a = PyColor->obj->a;
return (PyObject *)PyColor;
}
static PyObject *
PySfShape_GetPointOutlineColor(PySfShape* self, PyObject *args)
{
PySfColor *PyColor = GetNewPySfColor();
PyColor->obj = new sf::Color(self->obj->GetPointOutlineColor(PyLong_AsUnsignedLong(args)));
PyColor->r = PyColor->obj->r;
PyColor->g = PyColor->obj->g;
PyColor->b = PyColor->obj->b;
PyColor->a = PyColor->obj->a;
return (PyObject *)PyColor;
}
static PyObject *
PySfShape_SetPointPosition(PySfShape* self, PyObject *args)
{
unsigned int Index;
float X, Y;
if (!PyArg_ParseTuple(args, "Iff:Shape.SetPointPosition", &Index, &X, &Y))
return NULL;
self->obj->SetPointPosition(Index, X, Y);
Py_RETURN_NONE;
}
static PyObject *
PySfShape_SetPointColor(PySfShape* self, PyObject *args)
{
unsigned int Index;
PySfColor *Color;
if (!PyArg_ParseTuple(args, "IO!:Shape.SetPointColor", &Index, &PySfColorType, &Color))
return NULL;
PySfColorUpdate(Color);
self->obj->SetPointColor(Index, *(Color->obj));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_SetPointOutlineColor(PySfShape* self, PyObject *args)
{
unsigned int Index;
PySfColor *Color;
if (!PyArg_ParseTuple(args, "IO!:Shape.SetPointOutlineColor", &Index, &PySfColorType, &Color))
return NULL;
PySfColorUpdate(Color);
self->obj->SetPointOutlineColor(Index, *(Color->obj));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_GetNbPoints(PySfShape* self, PyObject *args)
{
return PyLong_FromUnsignedLong(self->obj->GetNbPoints());
}
static PyObject *
PySfShape_EnableFill(PySfShape* self, PyObject *args)
{
self->obj->EnableFill(PyBool_AsBool(args));
Py_RETURN_NONE;
}
static PyObject *
PySfShape_EnableOutline(PySfShape* self, PyObject *args)
{
self->obj->EnableOutline(PyBool_AsBool(args));
Py_RETURN_NONE;
}
static PyMethodDef PySfShape_methods[] = {
{"GetPointPosition", (PyCFunction)PySfShape_GetPointPosition, METH_O, "GetPointPosition(Index)\n\
Get the position of a point.\n\
Index : Index-th point."},
{"GetPointColor", (PyCFunction)PySfShape_GetPointColor, METH_O, "GetPointColor(Index)\n\
Get the color of a point.\n Index : Index-th point."},
{"GetPointOutlineColor", (PyCFunction)PySfShape_GetPointOutlineColor, METH_O, "GetPointOutlineColor(Index)\n\
Get the outline color of a point.\n Index : Index-th point."},
{"SetPointPosition", (PyCFunction)PySfShape_SetPointPosition, METH_VARARGS, "SetPointPosition(Index, X, Y).\n\
Set the position of a point\n\
Index : Index of the point, in range [0, GetNbPoints() - 1]\n\
X : New X coordinate of the Index-th point\n\
Y : New Y coordinate of the Index-th point."},
{"SetPointColor", (PyCFunction)PySfShape_SetPointColor, METH_VARARGS, "SetPointColor(Index, Color).\n\
Set the color of a point\n\
Index : Index of the point, in range [0, GetNbPoints() - 1]\n\
Col : New color of the Index-th point."},
{"SetPointOutlineColor", (PyCFunction)PySfShape_SetPointOutlineColor, METH_VARARGS, "SetPointOutlineColor(Index, Color).\n\
Set the outline color of a point\n\
Index : Index of the point, in range [0, GetNbPoints() - 1]\n\
Col : New color of the Index-th point."},
{"GetNbPoints", (PyCFunction)PySfShape_GetNbPoints, METH_NOARGS, "GetNbPoints()\n\
Get the number of points composing the shape."},
{"EnableFill", (PyCFunction)PySfShape_EnableFill, METH_O, "EnableFill(Enable)\n\
Enable or disable filling the shape. Fill is enabled by default.\n\
Enable : True to enable, false to disable."},
{"EnableOutline", (PyCFunction)PySfShape_EnableOutline, METH_O, "EnableOutline(Enable)\n\
Enable or disable drawing the shape outline. Outline is enabled by default.\n\
Enable : True to enable, false to disable"},
{"AddPoint", (PyCFunction)PySfShape_AddPoint, METH_VARARGS | METH_KEYWORDS, "AddPoint(X, Y, Col=sf.Color.White, OutlineCol=sf.Color.Black)\n\
Add a point to the shape.\n\
X : X coordinate of the point\n\
Y : Y coordinate of the point\n\
Col : Color of the point (white by default)\n\
OutlineCol : Outline color of the point (black by default)."},
{"SetOutlineWidth", (PyCFunction)PySfShape_SetOutlineWidth, METH_O, "SetOutlineWidth(Width)\n\
Change the width of the shape outline.\n\
Width : New width (use 0 to remove the outline)."},
{"GetOutlineWidth", (PyCFunction)PySfShape_GetOutlineWidth, METH_NOARGS, "GetOutlineWidth()\n\
Get the width of the shape outline."},
{"Line", (PyCFunction)PySfShape_Line, METH_STATIC | METH_VARARGS | METH_KEYWORDS, "Line(X0, Y0, X1, Y1, Thickness, Col, Outline = 0., OutlineCol = sf.Color(0, 0, 0))\n\
Create a shape made of a single line.\n\
X0 : X coordinate of the first point.\n\
Y0 : Y coordinate of the first point.\n\
X1 : X coordinate of the second point.\n\
Y1 : Y coordinate of the second point.\n\
Thickness : Line thickness.\n\
Col : Color used to draw the line\n\
Outline : Outline width (0 by default)\n\
OutlineCol : Color used to draw the outline (black by default)."},
{"Rectangle", (PyCFunction)PySfShape_Rectangle, METH_STATIC | METH_VARARGS | METH_KEYWORDS, "Rectangle(X0, Y0, X1, Y1, Col, Outline = 0., OutlineCol = sf.Color(0, 0, 0))\n\
Create a shape made of a single rectangle.\n\
X0 : X coordinate of the first point.\n\
Y0 : Y coordinate of the first point.\n\
X1 : X coordinate of the second point.\n\
Y1 : Y coordinate of the second point.\n\
Col : Color used to fill the rectangle.\n\
Outline : Outline width (0 by default).\n\
OutlineCol : Color used to draw the outline (black by default)."},
{"Circle", (PyCFunction)PySfShape_Circle, METH_STATIC | METH_VARARGS | METH_KEYWORDS, "Circle(X, Y, Radius, Col, Outline = 0., OutlineCol = sf.Color(0, 0, 0))\n\
Create a shape made of a single circle.\n\
X : X coordinate of the center.\n\
Y : Y coordinate of the center.\n\
Radius : Radius\n\
Col : Color used to fill the rectangle.\n\
Outline : Outline width (0 by default).\n\
OutlineCol : Color used to draw the outline (black by default)."},
{NULL} /* Sentinel */
};
PyTypeObject PySfShapeType = {
head_init
"Shape", /*tp_name*/
sizeof(PySfShape), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PySfShape_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Shape defines a drawable convex shape ; it also defines helper functions to draw simple shapes like lines, rectangles, circles, etc.\nDefault constructor: Shape()", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
PySfShape_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PySfDrawableType, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PySfShape_new, /* tp_new */
};
PySfShape *
GetNewPySfShape()
{
PySfShape *Shape = PyObject_New(PySfShape, &PySfShapeType);
Shape->IsCustom = false;
return Shape;
}
| 13,736 | 5,481 |
#include <stdio.h>
#include <algorithm>
#define MAX_N 250
using namespace std;
pair<int, int> p[MAX_N];
int main()
{
int n, x, y, a, b;
scanf("%d%d%d", &n, &x, &y);
for (int i = 0; i < n; i++)
{
scanf("%d%d", &a, &b);
p[i] = make_pair((x-a) * (x-a) + (y-b) * (y - b), i + 1);
}
sort(p, p + n);
printf("%d\n%d\n%d\n", p[0].second, p[1].second, p[2].second);
return 0;
} | 421 | 213 |
#include "Ticket.h"
using namespace std;
Ticket::Ticket(const Flight& flight, const bool& baggage): flight(flight)
{
this->baggage = baggage;
checked_in = false;
}
Flight Ticket::getFlight() const
{
return flight;
}
bool Ticket::getBaggage() const
{
return baggage;
}
void Ticket::checkIn()
{
checked_in = true;
}
bool Ticket::hasCheckedIn() const
{
return checked_in;
} | 394 | 152 |
#include "fileIOPlugin.h"
#include "../../SharedMemoryPublic.h"
#include "../b3PluginContext.h"
#include <stdio.h>
#include "../../../CommonInterfaces/CommonFileIOInterface.h"
#include "../../../Utils/b3ResourcePath.h"
#include "Bullet3Common/b3HashMap.h"
#include <string.h> //memcpy/strlen
#ifndef B3_EXCLUDE_DEFAULT_FILEIO
#include "../../../Utils/b3BulletDefaultFileIO.h"
#endif //B3_EXCLUDE_DEFAULT_FILEIO
#ifdef B3_USE_ZIPFILE_FILEIO
#include "zipFileIO.h"
#endif //B3_USE_ZIPFILE_FILEIO
#ifdef B3_USE_CNS_FILEIO
#include "CNSFileIO.h"
#endif //B3_USE_CNS_FILEIO
#define B3_MAX_FILEIO_INTERFACES 1024
struct WrapperFileHandle
{
CommonFileIOInterface* childFileIO;
int m_childFileHandle;
};
struct InMemoryFile
{
char* m_buffer;
int m_fileSize;
};
struct InMemoryFileAccessor
{
InMemoryFile* m_file;
int m_curPos;
};
struct InMemoryFileIO : public CommonFileIOInterface
{
b3HashMap<b3HashString,InMemoryFile*> m_fileCache;
InMemoryFileAccessor m_fileHandles[B3_MAX_FILEIO_INTERFACES];
int m_numAllocs;
int m_numFrees;
InMemoryFileIO()
:CommonFileIOInterface(eInMemoryFileIO,0)
{
m_numAllocs=0;
m_numFrees=0;
for (int i=0;i<B3_FILEIO_MAX_FILES;i++)
{
m_fileHandles[i].m_curPos = 0;
m_fileHandles[i].m_file = 0;
}
}
virtual ~InMemoryFileIO()
{
clearCache();
if (m_numAllocs != m_numFrees)
{
printf("Error: InMemoryFile::~InMemoryFileIO (numAllocs %d numFrees %d\n", m_numAllocs, m_numFrees);
}
}
void clearCache()
{
for (int i=0;i<m_fileCache.size();i++)
{
b3HashString name = m_fileCache.getKeyAtIndex(i);
InMemoryFile** memPtr = m_fileCache.getAtIndex(i);
if (memPtr && *memPtr)
{
InMemoryFile* mem = *memPtr;
freeBuffer(mem->m_buffer);
m_numFrees++;
delete (mem);
m_numFrees++;
m_fileCache.remove(name);
}
}
}
char* allocateBuffer(int len)
{
char* buffer = 0;
if (len)
{
m_numAllocs++;
buffer = new char[len];
}
return buffer;
}
void freeBuffer(char* buffer)
{
delete[] buffer;
}
virtual int registerFile(const char* fileName, char* buffer, int len)
{
m_numAllocs++;
InMemoryFile* f = new InMemoryFile();
f->m_buffer = buffer;
f->m_fileSize = len;
b3HashString key(fileName);
m_fileCache.insert(key,f);
return 0;
}
void removeFileFromCache(const char* fileName)
{
InMemoryFile* f = getInMemoryFile(fileName);
if (f)
{
m_fileCache.remove(fileName);
freeBuffer(f->m_buffer);
delete (f);
}
}
InMemoryFile* getInMemoryFile(const char* fileName)
{
InMemoryFile** fPtr = m_fileCache[fileName];
if (fPtr && *fPtr)
{
return *fPtr;
}
return 0;
}
virtual int fileOpen(const char* fileName, const char* mode)
{
//search a free slot
int slot = -1;
for (int i=0;i<B3_FILEIO_MAX_FILES;i++)
{
if (m_fileHandles[i].m_file==0)
{
slot=i;
break;
}
}
if (slot>=0)
{
InMemoryFile* f = getInMemoryFile(fileName);
if (f)
{
m_fileHandles[slot].m_curPos = 0;
m_fileHandles[slot].m_file = f;
} else
{
slot=-1;
}
}
//printf("InMemoryFileIO fileOpen %s, %d\n", fileName, slot);
return slot;
}
virtual int fileRead(int fileHandle, char* destBuffer, int numBytes)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES)
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
//if (numBytes>1)
// printf("curPos = %d\n", f.m_curPos);
if (f.m_curPos+numBytes <= f.m_file->m_fileSize)
{
memcpy(destBuffer,f.m_file->m_buffer+f.m_curPos,numBytes);
f.m_curPos+=numBytes;
//if (numBytes>1)
// printf("read %d bytes, now curPos = %d\n", numBytes, f.m_curPos);
return numBytes;
} else
{
if (numBytes!=1)
{
printf("InMemoryFileIO::fileRead Attempt to read beyond end of file\n");
}
}
}
}
return 0;
}
virtual int fileWrite(int fileHandle,const char* sourceBuffer, int numBytes)
{
return 0;
}
virtual void fileClose(int fileHandle)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES)
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
m_fileHandles[fileHandle].m_file = 0;
m_fileHandles[fileHandle].m_curPos = 0;
//printf("InMemoryFileIO fileClose %d\n", fileHandle);
}
}
}
virtual bool findResourcePath(const char* fileName, char* resourcePathOut, int resourcePathMaxNumBytes)
{
InMemoryFile* f = getInMemoryFile(fileName);
int fileNameLen = strlen(fileName);
if (f && fileNameLen<(resourcePathMaxNumBytes-1))
{
memcpy(resourcePathOut, fileName, fileNameLen);
resourcePathOut[fileNameLen]=0;
return true;
}
return false;
}
virtual char* readLine(int fileHandle, char* destBuffer, int numBytes)
{
int numRead = 0;
int endOfFile = 0;
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES )
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
//return ::fgets(destBuffer, numBytes, m_fileHandles[fileHandle]);
char c = 0;
do
{
int bytesRead = fileRead(fileHandle,&c,1);
if (bytesRead != 1)
{
endOfFile = 1;
c=0;
}
if (c && c!='\n')
{
if (c!=13)
{
destBuffer[numRead++]=c;
} else
{
destBuffer[numRead++]=0;
}
}
} while (c != 0 && c != '\n' && numRead<(numBytes-1));
}
}
if (numRead==0 && endOfFile)
{
return 0;
}
if (numRead<numBytes)
{
if (numRead >=0)
{
destBuffer[numRead]=0;
}
return &destBuffer[0];
} else
{
if (endOfFile==0)
{
printf("InMemoryFileIO::readLine readLine warning: numRead=%d, numBytes=%d\n", numRead, numBytes);
}
}
return 0;
}
virtual int getFileSize(int fileHandle)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES )
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
return f.m_file->m_fileSize;
}
}
return 0;
}
virtual void enableFileCaching(bool enable)
{
(void)enable;
}
};
struct WrapperFileIO : public CommonFileIOInterface
{
CommonFileIOInterface* m_availableFileIOInterfaces[B3_MAX_FILEIO_INTERFACES];
int m_numWrapperInterfaces;
WrapperFileHandle m_wrapperFileHandles[B3_MAX_FILEIO_INTERFACES];
InMemoryFileIO m_cachedFiles;
bool m_enableFileCaching;
WrapperFileIO()
:CommonFileIOInterface(0,0),
m_numWrapperInterfaces(0),
m_enableFileCaching(true)
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
m_availableFileIOInterfaces[i]=0;
m_wrapperFileHandles[i].childFileIO=0;
m_wrapperFileHandles[i].m_childFileHandle=0;
}
//addFileIOInterface(&m_cachedFiles);
}
virtual ~WrapperFileIO()
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
removeFileIOInterface(i);
}
m_cachedFiles.clearCache();
}
int addFileIOInterface(CommonFileIOInterface* fileIO)
{
int result = -1;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_availableFileIOInterfaces[i]==0)
{
m_availableFileIOInterfaces[i]=fileIO;
result = i;
break;
}
}
return result;
}
CommonFileIOInterface* getFileIOInterface(int fileIOIndex)
{
if (fileIOIndex>=0 && fileIOIndex<B3_MAX_FILEIO_INTERFACES)
{
return m_availableFileIOInterfaces[fileIOIndex];
}
return 0;
}
void removeFileIOInterface(int fileIOIndex)
{
if (fileIOIndex>=0 && fileIOIndex<B3_MAX_FILEIO_INTERFACES)
{
if (m_availableFileIOInterfaces[fileIOIndex])
{
delete m_availableFileIOInterfaces[fileIOIndex];
m_availableFileIOInterfaces[fileIOIndex]=0;
}
}
}
virtual int fileOpen(const char* fileName, const char* mode)
{
//find an available wrapperFileHandle slot
int wrapperFileHandle=-1;
int slot = -1;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_wrapperFileHandles[i].childFileIO==0)
{
slot=i;
break;
}
}
if (slot>=0)
{
//first check the cache
int cacheHandle = m_cachedFiles.fileOpen(fileName, mode);
if (cacheHandle>=0)
{
m_cachedFiles.fileClose(cacheHandle);
}
if (cacheHandle<0)
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* childFileIO=m_availableFileIOInterfaces[i];
if (childFileIO)
{
int childHandle = childFileIO->fileOpen(fileName, mode);
if (childHandle>=0)
{
if (m_enableFileCaching)
{
int fileSize = childFileIO->getFileSize(childHandle);
char* buffer = 0;
if (fileSize)
{
buffer = m_cachedFiles.allocateBuffer(fileSize);
if (buffer)
{
int readBytes = childFileIO->fileRead(childHandle, buffer, fileSize);
if (readBytes!=fileSize)
{
if (readBytes<fileSize)
{
fileSize = readBytes;
} else
{
printf("WrapperFileIO error: reading more bytes (%d) then reported file size (%d) of file %s.\n", readBytes, fileSize, fileName);
}
}
} else
{
fileSize=0;
}
}
//potentially register a zero byte file, or files that only can be read partially
m_cachedFiles.registerFile(fileName, buffer, fileSize);
}
childFileIO->fileClose(childHandle);
break;
}
}
}
}
{
int childHandle = m_cachedFiles.fileOpen(fileName, mode);
if (childHandle>=0)
{
wrapperFileHandle = slot;
m_wrapperFileHandles[slot].childFileIO = &m_cachedFiles;
m_wrapperFileHandles[slot].m_childFileHandle = childHandle;
} else
{
//figure out what wrapper interface to use
//use the first one that can open the file
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* childFileIO=m_availableFileIOInterfaces[i];
if (childFileIO)
{
int childHandle = childFileIO->fileOpen(fileName, mode);
if (childHandle>=0)
{
wrapperFileHandle = slot;
m_wrapperFileHandles[slot].childFileIO = childFileIO;
m_wrapperFileHandles[slot].m_childFileHandle = childHandle;
break;
}
}
}
}
}
}
return wrapperFileHandle;
}
virtual int fileRead(int fileHandle, char* destBuffer, int numBytes)
{
int fileReadResult=-1;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
fileReadResult = m_wrapperFileHandles[fileHandle].childFileIO->fileRead(
m_wrapperFileHandles[fileHandle].m_childFileHandle, destBuffer, numBytes);
}
}
return fileReadResult;
}
virtual int fileWrite(int fileHandle,const char* sourceBuffer, int numBytes)
{
//todo
return -1;
}
virtual void fileClose(int fileHandle)
{
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
m_wrapperFileHandles[fileHandle].childFileIO->fileClose(
m_wrapperFileHandles[fileHandle].m_childFileHandle);
m_wrapperFileHandles[fileHandle].childFileIO = 0;
m_wrapperFileHandles[fileHandle].m_childFileHandle = -1;
}
}
}
virtual bool findResourcePath(const char* fileName, char* resourcePathOut, int resourcePathMaxNumBytes)
{
if (m_cachedFiles.findResourcePath(fileName, resourcePathOut, resourcePathMaxNumBytes))
return true;
bool found = false;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_availableFileIOInterfaces[i])
{
found = m_availableFileIOInterfaces[i]->findResourcePath(fileName, resourcePathOut, resourcePathMaxNumBytes);
}
if (found)
break;
}
return found;
}
virtual char* readLine(int fileHandle, char* destBuffer, int numBytes)
{
char* result = 0;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
result = m_wrapperFileHandles[fileHandle].childFileIO->readLine(
m_wrapperFileHandles[fileHandle].m_childFileHandle,
destBuffer, numBytes);
}
}
return result;
}
virtual int getFileSize(int fileHandle)
{
int numBytes = 0;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
numBytes = m_wrapperFileHandles[fileHandle].childFileIO->getFileSize(
m_wrapperFileHandles[fileHandle].m_childFileHandle);
}
}
return numBytes;
}
virtual void enableFileCaching(bool enable)
{
m_enableFileCaching = enable;
if (!enable)
{
m_cachedFiles.clearCache();
}
}
};
struct FileIOClass
{
int m_testData;
WrapperFileIO m_fileIO;
FileIOClass()
: m_testData(42),
m_fileIO()
{
}
virtual ~FileIOClass()
{
}
};
B3_SHARED_API int initPlugin_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = new FileIOClass();
context->m_userPointer = obj;
#ifndef B3_EXCLUDE_DEFAULT_FILEIO
obj->m_fileIO.addFileIOInterface(new b3BulletDefaultFileIO());
#endif //B3_EXCLUDE_DEFAULT_FILEIO
return SHARED_MEMORY_MAGIC_NUMBER;
}
B3_SHARED_API int executePluginCommand_fileIOPlugin(struct b3PluginContext* context, const struct b3PluginArguments* arguments)
{
int result=-1;
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
printf("text argument:%s\n", arguments->m_text);
printf("int args: [");
//remove a fileIO type
if (arguments->m_numInts==1)
{
int fileIOIndex = arguments->m_ints[0];
obj->m_fileIO.removeFileIOInterface(fileIOIndex);
}
if (arguments->m_numInts==2)
{
int action = arguments->m_ints[0];
switch (action)
{
case eAddFileIOAction:
{
//if the fileIO already exists, skip this action
int fileIOType = arguments->m_ints[1];
bool alreadyExists = false;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* fileIO = obj->m_fileIO.getFileIOInterface(i);
if (fileIO)
{
if (fileIO->m_fileIOType == fileIOType)
{
if (fileIO->m_pathPrefix && strcmp(fileIO->m_pathPrefix,arguments->m_text)==0)
{
result = i;
alreadyExists = true;
break;
}
}
}
}
//create new fileIO interface
if (!alreadyExists)
{
switch (fileIOType)
{
case ePosixFileIO:
{
#ifdef B3_EXCLUDE_DEFAULT_FILEIO
printf("ePosixFileIO is not enabled in this build.\n");
#else
result = obj->m_fileIO.addFileIOInterface(new b3BulletDefaultFileIO(ePosixFileIO, arguments->m_text));
#endif
break;
}
case eZipFileIO:
{
#ifdef B3_USE_ZIPFILE_FILEIO
if (arguments->m_text[0])
{
result = obj->m_fileIO.addFileIOInterface(new ZipFileIO(eZipFileIO, arguments->m_text, &obj->m_fileIO));
}
#else
printf("eZipFileIO is not enabled in this build.\n");
#endif
break;
}
case eCNSFileIO:
{
#ifdef B3_USE_CNS_FILEIO
result = obj->m_fileIO.addFileIOInterface(new CNSFileIO(eCNSFileIO, arguments->m_text));
#else//B3_USE_CNS_FILEIO
printf("CNSFileIO is not enabled in this build.\n");
#endif //B3_USE_CNS_FILEIO
break;
}
default:
{
}
}//switch (fileIOType)
}//if (!alreadyExists)
break;
}
case eRemoveFileIOAction:
{
//remove fileIO interface
int fileIOIndex = arguments->m_ints[1];
obj->m_fileIO.removeFileIOInterface(fileIOIndex);
result = fileIOIndex;
break;
}
default:
{
printf("executePluginCommand_fileIOPlugin: unknown action\n");
}
}
}
return result;
}
B3_SHARED_API struct CommonFileIOInterface* getFileIOFunc_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
return &obj->m_fileIO;
}
B3_SHARED_API void exitPlugin_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
delete obj;
context->m_userPointer = 0;
}
| 15,832 | 7,307 |
//-------------------------------------------------------------------------------------
// ExportMaterial.cpp
//
// Advanced Technology Group (ATG)
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=226208
//-------------------------------------------------------------------------------------
#include "stdafx.h"
#include "ExportMaterial.h"
using namespace ATG;
ExportMaterial::ExportMaterial()
: ExportBase(nullptr),
m_pMaterialDefinition(nullptr),
m_bTransparent(false)
{
}
ExportMaterial::ExportMaterial(ExportString name)
: ExportBase(name),
m_pMaterialDefinition(nullptr),
m_bTransparent(false)
{
}
ExportMaterial::~ExportMaterial()
{
}
ExportMaterialParameter* ExportMaterial::FindParameter(const ExportString strName)
{
MaterialParameterList::iterator iter = m_Parameters.begin();
MaterialParameterList::iterator end = m_Parameters.end();
while (iter != end)
{
ExportMaterialParameter& param = *iter;
if (param.Name == strName)
return ¶m;
++iter;
}
return nullptr;
}
ExportString ExportMaterial::GetDefaultDiffuseMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultDiffuseMapTextureName);
}
ExportString ExportMaterial::GetDefaultNormalMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultNormalMapTextureName);
}
ExportString ExportMaterial::GetDefaultSpecularMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultSpecMapTextureName);
}
| 1,638 | 457 |
//
// Created by Quentin Liardeaux on 10/5/19.
//
#include "AddFriendWidget.hpp"
ui::AddFriendWidget::AddFriendWidget(boost::shared_ptr<NotificationHandler> notifHandler, QWidget *parent) :
QWidget(parent),
notifHandler_(notifHandler) {
QPointer<QPushButton> closeButton = new QPushButton(tr("Close"));
usernameLineEdit_ = QSharedPointer<QLineEdit>(new QLineEdit());
QPointer<QLabel> usernameLabel = new QLabel(tr("Username:"));
QPointer<QLabel> passwordLabel = new QLabel(tr("Password:"));
connect(closeButton, SIGNAL(clicked()), this, SLOT(closeTap()));
QPointer<QFormLayout> formLayout = new QFormLayout();
formLayout->addRow(closeButton);
formLayout->addRow(usernameLabel, usernameLineEdit_.get());
setLayout(formLayout);
setWindowTitle(tr("Add a friend"));
}
void ui::AddFriendWidget::closeTap()
{
for (auto action : actions()) {
if (action->text() == "close") {
action->trigger();
break;
}
}
}
| 1,012 | 321 |
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This is a GPU-backend specific test.
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrBackendSurface.h"
#include "GrContextPriv.h"
#include "GrProxyProvider.h"
#include "GrRenderTargetPriv.h"
#include "GrRenderTargetProxy.h"
#include "GrResourceProvider.h"
#include "GrSurfaceProxyPriv.h"
#include "GrTexture.h"
#include "GrTextureProxy.h"
#include "SkGr.h"
// Check that the surface proxy's member vars are set as expected
static void check_surface(skiatest::Reporter* reporter,
GrSurfaceProxy* proxy,
GrSurfaceOrigin origin,
int width, int height,
GrPixelConfig config,
SkBudgeted budgeted) {
REPORTER_ASSERT(reporter, proxy->origin() == origin);
REPORTER_ASSERT(reporter, proxy->width() == width);
REPORTER_ASSERT(reporter, proxy->height() == height);
REPORTER_ASSERT(reporter, proxy->config() == config);
REPORTER_ASSERT(reporter, !proxy->uniqueID().isInvalid());
REPORTER_ASSERT(reporter, proxy->isBudgeted() == budgeted);
}
static void check_rendertarget(skiatest::Reporter* reporter,
const GrCaps& caps,
GrResourceProvider* provider,
GrRenderTargetProxy* rtProxy,
int numSamples,
SkBackingFit fit,
int expectedMaxWindowRects) {
REPORTER_ASSERT(reporter, rtProxy->maxWindowRectangles(caps) == expectedMaxWindowRects);
REPORTER_ASSERT(reporter, rtProxy->numStencilSamples() == numSamples);
GrSurfaceProxy::UniqueID idBefore = rtProxy->uniqueID();
REPORTER_ASSERT(reporter, rtProxy->instantiate(provider));
GrRenderTarget* rt = rtProxy->priv().peekRenderTarget();
REPORTER_ASSERT(reporter, rtProxy->uniqueID() == idBefore);
// Deferred resources should always have a different ID from their instantiated rendertarget
REPORTER_ASSERT(reporter, rtProxy->uniqueID().asUInt() != rt->uniqueID().asUInt());
if (SkBackingFit::kExact == fit) {
REPORTER_ASSERT(reporter, rt->width() == rtProxy->width());
REPORTER_ASSERT(reporter, rt->height() == rtProxy->height());
} else {
REPORTER_ASSERT(reporter, rt->width() >= rtProxy->width());
REPORTER_ASSERT(reporter, rt->height() >= rtProxy->height());
}
REPORTER_ASSERT(reporter, rt->config() == rtProxy->config());
REPORTER_ASSERT(reporter, rt->fsaaType() == rtProxy->fsaaType());
REPORTER_ASSERT(reporter, rt->numColorSamples() == rtProxy->numColorSamples());
REPORTER_ASSERT(reporter, rt->numStencilSamples() == rtProxy->numStencilSamples());
REPORTER_ASSERT(reporter, rt->renderTargetPriv().flags() == rtProxy->testingOnly_getFlags());
}
static void check_texture(skiatest::Reporter* reporter,
GrResourceProvider* provider,
GrTextureProxy* texProxy,
SkBackingFit fit) {
GrSurfaceProxy::UniqueID idBefore = texProxy->uniqueID();
REPORTER_ASSERT(reporter, texProxy->instantiate(provider));
GrTexture* tex = texProxy->priv().peekTexture();
REPORTER_ASSERT(reporter, texProxy->uniqueID() == idBefore);
// Deferred resources should always have a different ID from their instantiated texture
REPORTER_ASSERT(reporter, texProxy->uniqueID().asUInt() != tex->uniqueID().asUInt());
if (SkBackingFit::kExact == fit) {
REPORTER_ASSERT(reporter, tex->width() == texProxy->width());
REPORTER_ASSERT(reporter, tex->height() == texProxy->height());
} else {
REPORTER_ASSERT(reporter, tex->width() >= texProxy->width());
REPORTER_ASSERT(reporter, tex->height() >= texProxy->height());
}
REPORTER_ASSERT(reporter, tex->config() == texProxy->config());
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(DeferredProxyTest, reporter, ctxInfo) {
GrProxyProvider* proxyProvider = ctxInfo.grContext()->contextPriv().proxyProvider();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
const GrCaps& caps = *ctxInfo.grContext()->caps();
int attempt = 0; // useful for debugging
for (auto origin : { kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin }) {
for (auto widthHeight : { 100, 128, 1048576 }) {
for (auto config : { kAlpha_8_GrPixelConfig, kRGB_565_GrPixelConfig,
kRGBA_8888_GrPixelConfig, kRGBA_1010102_GrPixelConfig }) {
for (auto fit : { SkBackingFit::kExact, SkBackingFit::kApprox }) {
for (auto budgeted : { SkBudgeted::kYes, SkBudgeted::kNo }) {
for (auto numSamples : {1, 4, 16, 128}) {
GrSurfaceDesc desc;
desc.fFlags = kRenderTarget_GrSurfaceFlag;
desc.fOrigin = origin;
desc.fWidth = widthHeight;
desc.fHeight = widthHeight;
desc.fConfig = config;
desc.fSampleCnt = numSamples;
{
sk_sp<GrTexture> tex;
if (SkBackingFit::kApprox == fit) {
tex = resourceProvider->createApproxTexture(desc, 0);
} else {
tex = resourceProvider->createTexture(desc, budgeted);
}
sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
desc, fit, budgeted);
REPORTER_ASSERT(reporter, SkToBool(tex) == SkToBool(proxy));
if (proxy) {
REPORTER_ASSERT(reporter, proxy->asRenderTargetProxy());
// This forces the proxy to compute and cache its
// pre-instantiation size guess. Later, when it is actually
// instantiated, it checks that the instantiated size is <= to
// the pre-computation. If the proxy never computed its
// pre-instantiation size then the check is skipped.
proxy->gpuMemorySize();
check_surface(reporter, proxy.get(), origin,
widthHeight, widthHeight, config, budgeted);
int supportedSamples =
caps.getRenderTargetSampleCount(numSamples, config);
check_rendertarget(reporter, caps, resourceProvider,
proxy->asRenderTargetProxy(),
supportedSamples,
fit, caps.maxWindowRectangles());
}
}
desc.fFlags = kNone_GrSurfaceFlags;
{
sk_sp<GrTexture> tex;
if (SkBackingFit::kApprox == fit) {
tex = resourceProvider->createApproxTexture(desc, 0);
} else {
tex = resourceProvider->createTexture(desc, budgeted);
}
sk_sp<GrTextureProxy> proxy(proxyProvider->createProxy(
desc, fit, budgeted));
REPORTER_ASSERT(reporter, SkToBool(tex) == SkToBool(proxy));
if (proxy) {
// This forces the proxy to compute and cache its
// pre-instantiation size guess. Later, when it is actually
// instantiated, it checks that the instantiated size is <= to
// the pre-computation. If the proxy never computed its
// pre-instantiation size then the check is skipped.
proxy->gpuMemorySize();
check_surface(reporter, proxy.get(), origin,
widthHeight, widthHeight, config, budgeted);
check_texture(reporter, resourceProvider,
proxy->asTextureProxy(), fit);
}
}
attempt++;
}
}
}
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(WrappedProxyTest, reporter, ctxInfo) {
GrProxyProvider* proxyProvider = ctxInfo.grContext()->contextPriv().proxyProvider();
GrResourceProvider* resourceProvider = ctxInfo.grContext()->contextPriv().resourceProvider();
GrGpu* gpu = ctxInfo.grContext()->contextPriv().getGpu();
const GrCaps& caps = *ctxInfo.grContext()->caps();
static const int kWidthHeight = 100;
if (kOpenGL_GrBackend != ctxInfo.backend()) {
return;
}
for (auto origin : { kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin }) {
for (auto colorType : { kAlpha_8_SkColorType, kRGBA_8888_SkColorType,
kRGBA_1010102_SkColorType }) {
for (auto numSamples : {1, 4}) {
GrPixelConfig config = SkImageInfo2GrPixelConfig(colorType, nullptr, caps);
SkASSERT(kUnknown_GrPixelConfig != config);
int supportedNumSamples = caps.getRenderTargetSampleCount(numSamples, config);
if (!supportedNumSamples) {
continue;
}
// External on-screen render target.
// Tests createWrappedRenderTargetProxy with a GrBackendRenderTarget
{
GrGLFramebufferInfo fboInfo;
fboInfo.fFBOID = 0;
GrBackendRenderTarget backendRT(kWidthHeight, kWidthHeight, numSamples, 8,
config, fboInfo);
sk_sp<GrSurfaceProxy> sProxy(proxyProvider->createWrappedRenderTargetProxy(
backendRT, origin));
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendRT.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_rendertarget(reporter, caps, resourceProvider,
sProxy->asRenderTargetProxy(),
supportedNumSamples, SkBackingFit::kExact, 0);
}
// Tests createWrappedRenderTargetProxy with a GrBackendTexture
{
GrBackendTexture backendTex =
gpu->createTestingOnlyBackendTexture(nullptr, kWidthHeight,
kWidthHeight, colorType, true,
GrMipMapped::kNo);
sk_sp<GrSurfaceProxy> sProxy =
proxyProvider->createWrappedRenderTargetProxy(backendTex, origin,
supportedNumSamples);
if (!sProxy) {
gpu->deleteTestingOnlyBackendTexture(&backendTex);
continue; // This can fail on Mesa
}
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendTex.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_rendertarget(reporter, caps, resourceProvider,
sProxy->asRenderTargetProxy(),
supportedNumSamples, SkBackingFit::kExact,
caps.maxWindowRectangles());
gpu->deleteTestingOnlyBackendTexture(&backendTex);
}
// Tests createWrappedTextureProxy that is only renderable
{
GrBackendTexture backendTex =
gpu->createTestingOnlyBackendTexture(nullptr, kWidthHeight,
kWidthHeight, colorType, true,
GrMipMapped::kNo);
sk_sp<GrSurfaceProxy> sProxy =
proxyProvider->createWrappedTextureProxy(backendTex, origin,
supportedNumSamples);
if (!sProxy) {
gpu->deleteTestingOnlyBackendTexture(&backendTex);
continue; // This can fail on Mesa
}
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendTex.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_rendertarget(reporter, caps, resourceProvider,
sProxy->asRenderTargetProxy(),
supportedNumSamples, SkBackingFit::kExact,
caps.maxWindowRectangles());
gpu->deleteTestingOnlyBackendTexture(&backendTex);
}
// Tests createWrappedTextureProxy that is only textureable
{
// Internal offscreen texture
GrBackendTexture backendTex =
gpu->createTestingOnlyBackendTexture(nullptr, kWidthHeight,
kWidthHeight, colorType, false,
GrMipMapped::kNo);
sk_sp<GrSurfaceProxy> sProxy =
proxyProvider->createWrappedTextureProxy(backendTex, origin,
kBorrow_GrWrapOwnership,
nullptr, nullptr);
if (!sProxy) {
gpu->deleteTestingOnlyBackendTexture(&backendTex);
continue;
}
check_surface(reporter, sProxy.get(), origin,
kWidthHeight, kWidthHeight,
backendTex.testingOnly_getPixelConfig(), SkBudgeted::kNo);
check_texture(reporter, resourceProvider, sProxy->asTextureProxy(),
SkBackingFit::kExact);
gpu->deleteTestingOnlyBackendTexture(&backendTex);
}
}
}
}
}
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ZeroSizedProxyTest, reporter, ctxInfo) {
GrProxyProvider* provider = ctxInfo.grContext()->contextPriv().proxyProvider();
for (auto flags : { kRenderTarget_GrSurfaceFlag, kNone_GrSurfaceFlags }) {
for (auto fit : { SkBackingFit::kExact, SkBackingFit::kApprox }) {
for (int width : { 0, 100 }) {
for (int height : { 0, 100}) {
if (width && height) {
continue; // not zero-sized
}
GrSurfaceDesc desc;
desc.fFlags = flags;
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
desc.fWidth = width;
desc.fHeight = height;
desc.fConfig = kRGBA_8888_GrPixelConfig;
desc.fSampleCnt = 1;
sk_sp<GrTextureProxy> proxy = provider->createProxy(desc, fit, SkBudgeted::kNo);
REPORTER_ASSERT(reporter, !proxy);
}
}
}
}
}
#endif
| 16,809 | 4,264 |
#include "include/gcc_builtin.hpp"
#include "include/mss.hpp"
charBuffer *pb;
int FORCE_NOINLINE helper(bool option) {
charBuffer buffer;
if(option) {
update_by_pointer(pb->data, 0, 8, 1, 'c');
return check(buffer.data, 7, 1, 'c');
} else {
pb = &buffer;
char_buffer_init(&buffer, 'u', 'd', 'o');
return 0;
}
}
int main() {
int rv0 = helper(false);
int rv1 = helper(true);
return rv0+rv1;
}
| 430 | 185 |
/*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "./aom_dsp_rtcd.h"
#include "./av1_rtcd.h"
#include "aom_ports/mem.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/transform_test_base.h"
#include "test/util.h"
using libaom_test::ACMRandom;
#if !CONFIG_DAALA_TX
namespace {
typedef void (*IhtFunc)(const tran_low_t *in, uint8_t *out, int stride,
const TxfmParam *txfm_param);
using std::tr1::tuple;
using libaom_test::FhtFunc;
typedef tuple<FhtFunc, IhtFunc, TX_TYPE, aom_bit_depth_t, int> Ht4x8Param;
void fht4x8_ref(const int16_t *in, tran_low_t *out, int stride,
TxfmParam *txfm_param) {
av1_fht4x8_c(in, out, stride, txfm_param);
}
void iht4x8_ref(const tran_low_t *in, uint8_t *out, int stride,
const TxfmParam *txfm_param) {
av1_iht4x8_32_add_c(in, out, stride, txfm_param);
}
class AV1Trans4x8HT : public libaom_test::TransformTestBase,
public ::testing::TestWithParam<Ht4x8Param> {
public:
virtual ~AV1Trans4x8HT() {}
virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
pitch_ = 4;
height_ = 8;
fwd_txfm_ref = fht4x8_ref;
inv_txfm_ref = iht4x8_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
num_coeffs_ = GET_PARAM(4);
txfm_param_.tx_type = GET_PARAM(2);
}
virtual void TearDown() { libaom_test::ClearSystemState(); }
protected:
void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, &txfm_param_);
}
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, &txfm_param_);
}
FhtFunc fwd_txfm_;
IhtFunc inv_txfm_;
};
TEST_P(AV1Trans4x8HT, AccuracyCheck) { RunAccuracyCheck(0, 0.00001); }
TEST_P(AV1Trans4x8HT, CoeffCheck) { RunCoeffCheck(); }
TEST_P(AV1Trans4x8HT, MemCheck) { RunMemCheck(); }
TEST_P(AV1Trans4x8HT, InvCoeffCheck) { RunInvCoeffCheck(); }
TEST_P(AV1Trans4x8HT, InvAccuracyCheck) { RunInvAccuracyCheck(0); }
using std::tr1::make_tuple;
const Ht4x8Param kArrayHt4x8Param_c[] = {
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_FLIPADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, IDTX, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_FLIPADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_FLIPADST, AOM_BITS_8, 32)
};
INSTANTIATE_TEST_CASE_P(C, AV1Trans4x8HT,
::testing::ValuesIn(kArrayHt4x8Param_c));
#if HAVE_SSE2
const Ht4x8Param kArrayHt4x8Param_sse2[] = {
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_DCT, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_DCT, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_DCT,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_ADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, IDTX, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_FLIPADST, AOM_BITS_8,
32)
};
INSTANTIATE_TEST_CASE_P(SSE2, AV1Trans4x8HT,
::testing::ValuesIn(kArrayHt4x8Param_sse2));
#endif // HAVE_SSE2
} // namespace
#endif // !CONFIG_DAALA_TX
| 5,844 | 3,068 |
struct MSX2 : MSX {
auto name() -> string override { return "MSX2"; }
auto extensions() -> vector<string> override { return {"msx2"}; }
};
| 143 | 48 |
// Copyright (C) 1998 Microsoft Corporation
//
// Splash screen for unattended mode
//
// 10-1-98 sburns
#include "headers.hxx"
#include "UnattendSplashDialog.hpp"
#include "resource.h"
#include "state.hpp"
const UINT SELF_DESTRUCT_MESSAGE = WM_USER + 200;
static const DWORD HELP_MAP[] =
{
0, 0
};
UnattendSplashDialog::UnattendSplashDialog(int splashMessageResId)
:
Dialog(IDD_UNATTEND_SPLASH, HELP_MAP),
messageResId(splashMessageResId)
{
LOG_CTOR(UnattendSplashDialog);
ASSERT(messageResId);
}
UnattendSplashDialog::~UnattendSplashDialog()
{
LOG_DTOR(UnattendSplashDialog);
}
void
UnattendSplashDialog::OnInit()
{
LOG_FUNCTION(UnattendSplashDialog::OnInit);
// Since the window does not have a title bar, we need to give it some
// text to appear on the button label on the shell task bar.
Win::SetWindowText(hwnd, String::load(IDS_WIZARD_TITLE));
// NTRAID#NTBUG9-502991-2001/12/07-sburns
Win::SetDlgItemText(hwnd, IDC_MESSAGE, messageResId);
}
void
UnattendSplashDialog::SelfDestruct()
{
LOG_FUNCTION(UnattendSplashDialog::SelfDestruct);
// Post our window proc a self destruct message. We use Post instead of
// send, as we expect that in some cases, this function will be called from
// a thread other than the one that created the window. (It is illegal to
// try to destroy a window from a thread that it not the thread that
// created the window.)
Win::PostMessage(hwnd, SELF_DESTRUCT_MESSAGE, 0, 0);
}
bool
UnattendSplashDialog::OnMessage(
UINT message,
WPARAM /* wparam */ ,
LPARAM /* lparam */ )
{
if (message == SELF_DESTRUCT_MESSAGE)
{
delete this;
return true;
}
return false;
}
| 1,842 | 729 |
#include "switch_wrapper.h"
#include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <zlib.h>
#include "main/main.h"
#include "os_switch.h"
#define FB_WIDTH 1280
#define FB_HEIGHT 720
int main(int argc, char *argv[])
{
socketInitializeDefault();
nxlinkStdio();
int apptype = appletGetAppletType();
if(apptype != AppletType_Application && apptype != AppletType_SystemApplication)
{
romfsInit();
NWindow* win = nwindowGetDefault();
Framebuffer fb;
framebufferCreate(&fb, win, FB_WIDTH, FB_HEIGHT, PIXEL_FORMAT_RGBA_8888, 1);
framebufferMakeLinear(&fb);
u32 stride;
u32* framebuf = (u32*) framebufferBegin(&fb, &stride);
FILE *splash = fopen("romfs:/applet_splash.rgba.gz", "rb");
if(splash)
{
fseek(splash, 0, SEEK_END);
size_t splash_size = ftell(splash);
u8 *compressed_splash = (u8*)malloc(splash_size);
memset(compressed_splash, 0, splash_size);
fseek(splash, 0, SEEK_SET);
size_t amt_read = fread(compressed_splash, 1, splash_size, splash);
fclose(splash);
memset(framebuf, 0, stride * FB_HEIGHT);
struct z_stream_s stream;
memset(&stream, 0, sizeof(stream));
stream.zalloc = NULL;
stream.zfree = NULL;
stream.next_in = compressed_splash;
stream.avail_in = splash_size;
stream.next_out = (u8*)framebuf;
stream.avail_out = stride * FB_HEIGHT;
if(inflateInit2(&stream, 16+MAX_WBITS) == Z_OK)
{
int err = 0;
if((err = inflate(&stream, 0)) != Z_STREAM_END)
{
// idk
}
inflateEnd(&stream);
}
}
else
{
// this REALLY shouldn't fail. Hm.
}
framebufferEnd(&fb);
while(appletMainLoop())
{
hidScanInput();
if(hidKeysDown(CONTROLLER_P1_AUTO) &
~(KEY_TOUCH|
KEY_LSTICK_LEFT|KEY_LSTICK_RIGHT|
KEY_LSTICK_UP|KEY_LSTICK_DOWN|
KEY_RSTICK_LEFT|KEY_RSTICK_RIGHT|
KEY_RSTICK_UP|KEY_RSTICK_DOWN))
{
break;
}
}
framebufferClose(&fb);
romfsExit();
socketExit();
return 0;
}
OS_Switch os;
os.set_executable_path(argv[0]);
char *cwd = (char *)malloc(PATH_MAX);
getcwd(cwd, PATH_MAX);
Error err = Main::setup(argv[0], argc - 1, &argv[1]);
if (err != OK) {
free(cwd);
socketExit();
return 255;
}
if (Main::start())
{
os.run(); // it is actually the OS that decides how to run
}
Main::cleanup();
chdir(cwd);
free(cwd);
socketExit();
return os.get_exit_code();
}
| 2,405 | 1,179 |
/******************************************************************************
** Copyright (C) 1998 by CEA
*******************************************************************************
**
** UNIT
**
** Version: 1.4
**
** Author: 07/01/99
**
** Date: 99/07/05
**
** File: mc_mwfilter.cc
**
*******************************************************************************/
#include "wk_memfilter.h"
#include "MW_mcFilter.h"
#include "MR_Filter.h"
#include "MR_Edge.h"
#define MAX_ITER 100
#define DEF_SIGMA_PCA -1
#define DEF_SIGMA_MR2D 3
#define MAX_IMAG_VALUE 255
#define DEF_CORREL_COMP E_LOCAL
#define DEF_CORREL_NOISE E_THRESHOLD
#define DEF_CONV_PARAM DEF_MEM_FILT_CONGER
#define DEF_REGUL_PARAM 1
#define MAX_NBR_TYPE_OPT 3
#define DEF_SIZE_BLK DEFAULT_SIZE_BLOCK_SIG
#define DEF_ITER_SIGCLP 1
#define DEF_ITER_ENTROP DEF_MEM_FILT_MAX_ITER
extern int OptInd;
extern char *OptArg;
/***********************************************************************************/
char* getTypeOpt (int ind) {
switch (ind) {
case 1 : return ("fixed user Alpha value");break;
case 2 : return ("Estimate the optimal Alpha");break;
case 3 : return ("Estimate one Alpha value per band");break;
default : return ("Error: bad optim type");break;
}
}
/***********************************************************************************/
void mr_getmodel_from_edge(MultiResol & MR_Data, MultiResol &MR_Edge,
MRNoiseModel & ModelData) {
/* Find a multiresolution model for edges:
-- create an SNR edge image: ImaEdge
-- threshold ImaEdge if ImaEdge < NSigma
-- kill isolated pixel in ImaEdge
-- in each band,
. threshold wavelet coefficient if there is no edge
.average the wavelet coefficient
with the two other values in the edge direction
!! This routine works only if the a-trou algorithm is choosen
*/
int Nbr_Band = MR_Data.nbr_band()-1;
int i,j,Nl = MR_Data.size_ima_nl();
int Nc = MR_Data.size_ima_nc();
Ifloat ImaEdge(Nl,Nc,"ImaEdge");
Iint ImaAngle(Nl,Nc,"ImaAngle");
mr_get_edge( MR_Data, MR_Edge, ImaEdge, ImaAngle, ModelData);
for (i = 0; i < Nl; i++)
for (j = 0; j < Nc; j++)
{
ImaEdge(i,j) /= ModelData.NSigma[1];
if (ImaEdge(i,j) > 1) ImaEdge(i,j) = 1.;
else ImaEdge(i,j) = 0.;
}
for (i=0;i < Nl; i++)
for (j=0;j < Nc; j++)
if (isolated_pixel(ImaEdge,i,j,I_MIRROR) == True) ImaEdge(i,j) = 0.;
for (int b = 0; b < Nbr_Band; b++)
{
int Nlb = MR_Data.size_band_nl(b);
int Ncb = MR_Data.size_band_nc(b);
int Step = (MR_Data.band_to_scale(b) == b) ? b : 0;
for (i = 0; i < Nlb; i++)
for (j = 0; j < Ncb; j++)
{
if (ImaEdge(i,j) > FLOAT_EPSILON)
MR_Edge(b,i,j) = val_contour_min(MR_Data.band(b), ImaEdge, ImaAngle,
i,j, FLOAT_EPSILON, Step);
else MR_Edge(b,i,j) = 0.;
}
}
}
int main(int argc, char *argv[])
{
extern softinfo Soft;
Soft.mr3();
lm_check(LIC_MR3);
// licence manager
//lm2();
// init local var
mw_Param o_Param;
// Read param IN
o_Param (argc, argv);
// init Result and Iter classes
mw_Result o_Result (&o_Param);
mw_Iter o_Iter (&o_Result);
for (o_Iter.iter_Begin(); o_Iter.iter_End(); o_Iter++) {}
// write result
o_Result.res_Write ();
exit(0);
}
/******************************************************************************
classe mw_Param
******************************************************************************/
mw_Param::mw_Param () {
//default init of read var
e_Transform = DEFAULT_TRANSFORM;
e_Norm = NORM_L1;
e_SBFilter = F_MALLAT_7_9;
po_FAS = (FilterAnaSynt*)NULL;
i_NbPlan = DEFAULT_NBR_SCALE;
i_NbIter = 1;
e_WithNoiseModel = True; // always use noise model, def gaussian
e_UseReconsAdjoint = False;
e_TypeNoise = DEFAULT_STAT_NOISE;
e_PositivImag = False;
e_MaxImag = False;
e_NormCorrelMatrix = True;
e_CorrelComp = DEF_CORREL_COMP;
po_ImportCorMat = NULL;
e_CorrelNoise = DEF_CORREL_NOISE;
f_NoiseIma = 0.;
f_Gain = 0.;
f_SigmaGauss = 0.;
f_MeanGauss = 0.;
f_NSigmaMr2d = DEF_SIGMA_MR2D;
f_NSigmaPCA = DEF_SIGMA_PCA;
e_Verbose = False;
e_WriteTransf = False;
e_WriteEigenOnDisk = False;
e_WriteSupportMr2d = False;
e_WriteSupportPCA = False;
e_TraceParamIn = False;
f_CvgParam = DEF_CONV_PARAM;
f_RegulVal = 1.;
i_TypeOpt = DEF_MEM_ALPHA_CST;
e_DataEdge = False;
e_DataSNR = False;
e_UseRMSMap = False;
i_SizeBlock = DEF_SIZE_BLK;
i_NiterClip = DEF_ITER_SIGCLP;
i_NbIterEntrop = DEF_ITER_ENTROP;
e_NscaleOpt = False;
e_TransfOpt = False;
#ifdef LARGE_BUFF
e_OptZ = False;
i_VMSSize = -1;
#endif
for (int b=0;b<MAX_NB_BAND;b++) {
ti_NbrUseEigen[b] = 0;
for (int i=0;i<MAX_NBR_PCA_IMA;i++)
tti_TabKill[i][b] = 0;
}
}
void mw_Param::operator () (int argc, char *argv[]) {
int c,i,b;
Bool readfile = False, Optf = False, OptL = False;;
while ((c = GetOpt(argc,argv,"t:m:g:c:n:s:S:x:O:y:WwrkRapvLbPF:K:C:G:U:T:M:B:N:i:ADzZ:")) != -1) {
switch (c) {
case 't': /* -d <type> type of transform */
readint (i, "bad type of multiresolution transform: %s\n");
if (testborn (1 ,NBR_TRANSFORM, i, "bad type of transform: %s\n"))
e_Transform = (type_transform) (i-1);
e_TransfOpt = True;
break;
case 'T':
Optf = True;
e_SBFilter = get_filter_bank(OptArg);
break;
case 'L':
e_Norm = NORM_L2;OptL = True;break;
case 'm':
readint (i, "Error: bad type of noise: %s\n");
if (testborn(1, NBR_NOISE, i, "Error: bad type of noise: %s\n"))
e_TypeNoise = (type_noise) (i-1);
e_WithNoiseModel = True;
break;
case 'n': /* -n <NbPlan> */
readint (i_NbPlan, "bad number of scales: %s\n");
testborn (2, MAX_SCALE, i_NbPlan, "bad number of scales: %s\n");
e_NscaleOpt = True;
break;
//case 'i': /* -i <NbIter> */
// readint (i_NbIter, "bad number of iterarions: %s\n");
// testborn (1, MAX_ITER, i_NbIter, "bad number of iterations: %s\n");
// break;
case 'g': /* -g <sigma_noise> */
readfloat (f_NoiseIma, "Error: bad sigma noise: %s\n");
e_TypeNoise = NOISE_GAUSSIAN;
e_WithNoiseModel = True;
break;
case 'c': /* -c <gain sigma mean> */
readfloat (f_Gain, "Error: bad sigma noise: %s\n");
readfloat (f_SigmaGauss, "Error: bad sigma noise: %s\n");
readfloat (f_MeanGauss, "Error: bad sigma noise: %s\n");
e_TypeNoise = NOISE_POISSON;
e_WithNoiseModel = True;
f_NoiseIma = 1.;
break;
case 's': /* -s <nsigma> */
readfloat (f_NSigmaMr2d, "Error: bad NSigma: %s\n");
break;
case 'S': /* -S <nsigma> */
readfloat (f_NSigmaPCA, "Error: bad NSigma: %s\n");
break;
case 'F':
readint (i, "Error: bad number of eigen vectors: %s\n");
for (b=0;b<MAX_NB_BAND;b++) ti_NbrUseEigen[b] = i;
break;
case 'K':
readint (i, "Error: bad eigen vector number: %s\n");
testborn (1, MAX_NBR_PCA_IMA, i, "Error: bad eigen vector number: %s\n");
for (b=0;b<MAX_NB_BAND;b++) tti_TabKill[i-1][b] = 1;
break;
case 'C':
readfloat (f_CvgParam, "Error: bad Cvg Parameter: %s\n");
if (f_CvgParam <= 0.) f_CvgParam = 0.1;
break;
case 'G':
readfloat (f_RegulVal, "Error: bad Regularization Parameter: %s\n");
if (f_RegulVal < 0.) f_RegulVal = 1.;
break;
case 'U':
readint (i_TypeOpt, "bad type of regularization %s\n");
testborn (1, MAX_NBR_TYPE_OPT, i_TypeOpt, "Error: regularization type must be in [1,3]");
break;
case 'M':
if (sscanf(OptArg,"%s", tc_NameRMSMap) != 1) {
fprintf(stderr, "Error: bad file name: %s\n", OptArg); exit(-1);
}
e_UseRMSMap = True;
break;
case 'B':
readint (i_SizeBlock, "bad block size (sigma clipping): %s\n");
break;
case 'N':
readint (i_NiterClip, "Error: ad it. number for the 3sigma clipping: %s\n");
break;
case 'i':
readint (i_NbIterEntrop, "Error: bad number of iterations: %s\n");
break;
case 'x': /* -x type of compute correlation */
readint (i, "bad type of correlation compute : %s\n");
if (testborn (0 ,MAX_CORREL_COMP-1, i, "bad type of correlation compute: %s\n"))
e_CorrelComp = (CorrelComputeType) (i);
break;
case 'O': /* -C correaltion matrix name file */
if (sscanf(OptArg,"%s", tc_ImportCorMatName) != 1) {
fprintf(stderr, "Error: bad correlation matrix file name: %s\n", OptArg); exit(-1);
}
readfile = True;
break;
case 'y': /* -x type of noise correlation */
readint (i, "bad type of correlation noise : %s\n");
if (testborn (0 ,MAX_CORREL_NOISE-1, i, "bad type of correlation noise: %s\n"))
e_CorrelNoise = (CorrelNoiseType) (i);
break;
#ifdef LARGE_BUFF
case 'z':
if (e_OptZ == True) {
fprintf(OUTMAN, "Error: Z option already set...\n"); exit(-1);
}
e_OptZ = True; break;
case 'Z':
if (sscanf(OptArg,"%d:%s",&i_VMSSize, tc_VMSName) < 1) {
fprintf(OUTMAN, "Error: syntaxe is Size:Directory ... \n"); exit(-1);
}
if (e_OptZ == True) {
fprintf(OUTMAN, "Error: z option already set...\n"); exit(-1);
}
e_OptZ = True;
break;
#endif
case 'p':
e_NormCorrelMatrix = False;break;
case 'P':
e_PositivImag = True;break;
case 'b':
e_MaxImag = True;break;
case 'a':
e_UseReconsAdjoint = True;break;
case 'W':
e_WriteTransf = True;break;
case 'w':
e_WriteEigenOnDisk = True;break;
case 'r':
e_WriteSupportMr2d = True;break;
case 'R':
e_WriteSupportPCA = True;break;
case 'A' :
e_DataEdge = True; break;
case 'D' :
e_DataSNR = True; break;
case 'k':
e_TraceParamIn = True;break;
case 'v':
e_Verbose = True;break;
case '?':
usage(argv);
}
}
if ( (e_Transform != TO_UNDECIMATED_MALLAT)
&& (e_Transform != TO_MALLAT)
&& ((OptL == True) || (Optf == True))) {
fprintf(OUTMAN, "Error: option -T and -L are only valid with Mallat transform ... \n");
exit(0);
}
if ( (e_Transform == TO_UNDECIMATED_MALLAT)
|| (e_Transform == TO_MALLAT) ) {
po_FAS = new FilterAnaSynt(); /* mem loss, never free ... */
po_FAS->alloc(e_SBFilter);
po_FAS->Verbose = e_Verbose;
}
// get optional input file names from trailing parameters and open files
// read input image names */
if (OptInd < argc) strcpy(tc_NameIn, argv[OptInd++]);
else usage(argv);
if (OptInd < argc) strcpy(tc_NameOut, argv[OptInd++]);
else usage(argv);
// make sure there are not too many parameters
if (OptInd < argc) {
fprintf(OUTMAN, "Error: too many parameters: %s ...\n", argv[OptInd]);
usage(argv);
}
// Test inconsistencies in the option call
if (e_TypeNoise == NOISE_EVENT_POISSON) {
if ((e_TransfOpt == True) && (e_Transform != TO_PAVE_BSPLINE)) {
cerr << "WARNING: with this noise model, only the BSPLINE A TROUS can be used ... " << endl;
cerr << " Type transform is set to: BSPLINE A TROUS ALGORITHM " << endl;
}
e_Transform = TO_PAVE_BSPLINE;
if (e_NscaleOpt != True) i_NbPlan = DEF_N_SCALE;
}
if ((e_TypeNoise == NOISE_CORREL) && (e_UseRMSMap != True)) {
cerr << endl << endl;
cerr << " Error: this noise model need a noise map (-R option) " << endl;
exit(-1);
}
if (e_UseRMSMap == True) {
if ((e_TypeNoise != NOISE_NON_UNI_ADD) && (e_TypeNoise != NOISE_CORREL)) {
cerr << "Error: this noise model is not correct when RMS map option is set." << endl;
cerr << " Valid models are: " << endl;
cerr << " " << StringNoise(NOISE_NON_UNI_ADD) << endl;
cerr << " " << StringNoise(NOISE_CORREL) << endl;
exit(-1);
}
// Stat_Noise = NOISE_NON_UNI_ADD;
}
if ((isotrop(e_Transform) == False)
&& ((e_TypeNoise == NOISE_NON_UNI_ADD) || (e_TypeNoise == NOISE_NON_UNI_MULT))) {
cerr << endl << endl;
cerr << " Error: with this transform, non stationary noise models are not valid : " << StringFilter(FILTER_THRESHOLD) << endl;
exit(-1);
}
#ifdef LARGE_BUFF
if (e_OptZ == True) vms_init(i_VMSSize, tc_VMSName, e_Verbose);
#endif
read_image (argv);
// matrix file name
if (e_CorrelComp == E_IMPORT) {
if (readfile != True) {
cout << " -O Matrix_File_Name not initialized" << endl;
exit (-1);
}
fitsstruct Header;
po_ImportCorMat = new Ifloat(i_NbImage, i_NbImage, "");
io_read_ima_float(tc_ImportCorMatName, *po_ImportCorMat, &Header);
int Nl = po_ImportCorMat->nl();
int Nc = po_ImportCorMat->nc();
if (Nl != Nc || Nl != i_NbImage) {
cout << " bad size of Matrix File Name" << endl;
exit (-1);
}
}
if (e_TraceParamIn) trace ();
}
void mw_Param::usage (char *argv[]) {
fprintf(OUTMAN, "Usage: %s options input_image output_image\n", argv[0]);
manline();
transform_usage (e_Transform); manline();
wk_filter (F_MALLAT_7_9); manline();
//wk_noise_usage (); manline();
nbr_scale_usage (i_NbPlan); manline();
gauss_usage (); manline();
//ccd_usage (); manline();
// normalize_correl_matrix (); manline();
correl_compute (DEF_CORREL_COMP); manline();
import_correl_file(); manline();
correl_noise (DEF_CORREL_NOISE); manline();
nsigma_mr2d (DEF_SIGMA_MR2D); manline();
//nsigma_pca (DEF_SIGMA_PCA); manline();
positiv_imag_constraint(); manline();
max_imag_constraint(); manline();
write_eigen_on_disk (); manline();
nb_eigen_used (); manline();
vector_not_used (); manline();
wk_conv_param (DEF_CONV_PARAM); manline();
wk_regul_param (DEF_REGUL_PARAM); manline();
wk_type_opt (); manline();
// wk_model_edge (); manline();
wk_data_snr (); manline();
// wk_rms_map () ; manline();
// wk_size_block_sig_clip (DEF_SIZE_BLK); manline();
// wk_nb_iter_sig_clip (DEF_ITER_SIGCLP); manline();
wk_nb_iter_entrop (DEF_ITER_ENTROP); manline();
//write_support_mr2d (); manline();
//write_support_pca (); manline();
verbose (); manline();
exit(-1);
}
void mw_Param::read_image (char *argv[]) {
if (e_Verbose) cout << "Name file IN : " << tc_NameIn << endl;
// read the data (-> fltarray)
fits_read_fltarr (tc_NameIn, ao_3dDataIn);
i_NbCol = ao_3dDataIn.nx(); //col
i_NbLin = ao_3dDataIn.ny(); //lin
i_NbImage = ao_3dDataIn.nz(); //image
// convert data -> Ifloat
po_TabIma = new Ifloat [i_NbImage];
for (int k=0;k<i_NbImage;k++) {
po_TabIma[k].alloc (i_NbLin, i_NbCol, "");
for (int i=0;i<i_NbLin;i++)
for (int j=0;j<i_NbCol;j++)
po_TabIma[k](i,j) = ao_3dDataIn(j,i,k);
}
// verify that all Mr2d have same size
if (!control_image (i_NbImage, po_TabIma)) exit(-1);
// set by default the number of eigen vectors used for the reconstruction
// to the number of images
for (int b=0;b<MAX_NB_BAND;b++)
if (ti_NbrUseEigen[b] < 1 || ti_NbrUseEigen[b] >= i_NbImage)
ti_NbrUseEigen[b] = i_NbImage;
}
void mw_Param::trace () {
cout << "Param IN :" << endl;
cout << " -- [-t:] : type of transform : " << StringTransform(e_Transform) << endl;
if (e_WithNoiseModel) cout << " -- [-m:] : with noise model : " << StringNoise(e_TypeNoise) << endl;
cout << " -- [-n:] : number of plan : " << i_NbPlan << endl;
//cout << " -- [-i:] : number of iteration : " << i_NbIter << endl;
cout << " : number of iteration : " << i_NbIter << endl;
if (f_NoiseIma != 0.) cout << " -- [-g:] : gauss noise : " << f_NoiseIma << endl;
if (f_Gain != 0.) cout << " -- [-c:] : gain : " << f_Gain << ", sigma : " << f_SigmaGauss << ", mean : " << f_MeanGauss << endl;
if (e_NormCorrelMatrix) cout << " -- [-p] : normalize correl matrix" << endl;
if (e_WithNoiseModel) {
cout << " -- [-x:] : correlation compute : " << CorCompTransform(e_CorrelComp) << endl;
if (e_CorrelComp == E_IMPORT)
cout << " -- [-O:] : import correlation file : " << tc_ImportCorMatName << endl;cout << " -- [-y:] : correlation noise : " << CorNoiseTransform(e_CorrelNoise) << endl;
cout << " -- [-s:] : multiresol nsigma : " << f_NSigmaMr2d << endl;
cout << " -- [-S:] : pca nsigma : " << f_NSigmaPCA << endl;
}
cout << " -- [-F:] : number of eigen vector used : " << ti_NbrUseEigen[0] << endl;
cout << " -- [-C:] : convergence parametre : " << f_CvgParam << endl;
cout << " -- [-G:] : regulation parametre : " << f_RegulVal << endl;
cout << " -- [-T:] : type optimisation : " << getTypeOpt (i_TypeOpt) << endl;
if (e_DataEdge) cout << " -- [-A] : use model edge" << endl;
if (e_DataSNR) cout << " -- [-D] : use data SNR" << endl;
if (e_UseRMSMap) cout << "-- [-M] : RMS Map file : " << tc_NameRMSMap << endl;
cout << " -- [-B:] : block size sigma clipping : " << i_SizeBlock << endl;
cout << " -- [-N:] : number of iteration sigma clipping : " << i_NiterClip << endl;
cout << " -- [-i:] : number of iteration for entrop programm : " << i_NbIterEntrop << endl;
if (e_UseReconsAdjoint) cout << " -- [-a] : use rec_adjoint in recons process" << endl;
if (e_PositivImag) cout << " -- [-P] : positivity constraint" << endl;
if (e_MaxImag) cout << " -- [-b] : max image constraint (255)" << endl;
if (e_WriteTransf) cout << " -- [-W] : write transf vect images" << endl;
if (e_WriteEigenOnDisk) cout << " -- [-w] : write eigen vector images" << endl;
if (e_WriteSupportMr2d) cout << " -- [-r] : write Multiresol support" << endl;
if (e_WriteSupportPCA) cout << " -- [-R] : write PCA support" << endl;
if (e_Verbose) cout << " -- [-v] : verbose" << endl;
}
/******************************************************************************
classe mw_Result
******************************************************************************/
mw_Result::mw_Result (mw_Param* ppo_Param) {
po_Param = ppo_Param;
// allocate fltarray for write result
o_3dDataOut.alloc (po_Param->i_NbCol, po_Param->i_NbLin, po_Param->i_NbImage);
// allocate the memory for all multiresol
po_TabMr2d = new MultiResol [po_Param->i_NbImage];
for (int k=0; k<po_Param->i_NbImage; k++)
po_TabMr2d[k].alloc (po_Param->i_NbLin, po_Param->i_NbCol, po_Param->i_NbPlan,
po_Param->e_Transform, po_Param->po_FAS, po_Param->e_Norm);
// init number of band
po_Param->i_NbBand = po_TabMr2d[0].nbr_band();
// class for image correlation analysis
o_Mr2dPca.alloc (po_Param->i_NbImage, po_Param->i_NbBand);
for (int b=0; b<po_Param->i_NbBand-1; b++) {
o_Mr2dPca.MatCor[b].Verbose = po_Param->e_Verbose;
o_Mr2dPca.MatCor[b].NormAna = po_Param->e_NormEigen;
}
// allocate memory for Noise Model classes
if (po_Param->e_WithNoiseModel)
po_TabNoiseModel = new MRNoiseModel [po_Param->i_NbImage];
else
po_TabNoiseModel = (MRNoiseModel*)NULL;
}
mw_Result::~mw_Result () {
delete [] po_TabMr2d;
if (po_Param->e_WithNoiseModel) delete [] po_TabNoiseModel;
}
void mw_Result::res_FirstCompute () {
// create all multiresol
if (po_Param->e_Verbose) cout << "Multiresol transform of data ..." << endl;
for (int k=0; k<po_Param->i_NbImage; k++)
po_TabMr2d[k].transform (po_Param->po_TabIma[k]);
if (po_Param->e_WriteTransf) {
char Mr2dRecons[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(Mr2dRecons, "mr2d_Transf_%d",k+1);
po_TabMr2d[k].write (Mr2dRecons);
}
}
// create all noise model
if (po_Param->e_WithNoiseModel)
res_InitNoiseModelMr2d();
if (po_Param->e_WriteTransf) {
char Mr2dRecons[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(Mr2dRecons, "mr2d_Transf_Thresh_%d",k+1);
po_TabMr2d[k].write (Mr2dRecons);
}
}
// calculate the correlation matrix and its eigen values
if (po_Param->e_Verbose) cout << "Principal component analysis ..." << endl;
if (po_Param->e_WithNoiseModel)
o_Mr2dPca.compute (po_TabMr2d, po_TabNoiseModel,
po_Param->e_NormCorrelMatrix,
po_Param->e_CorrelComp,
po_Param->e_CorrelNoise,
po_Param->po_ImportCorMat);
else
o_Mr2dPca.compute(po_TabMr2d, (MRNoiseModel*)NULL);
// print the result to the standard output
if (po_Param->e_Verbose) o_Mr2dPca.print();
// calculate the eigen vector images
if (po_Param->e_Verbose) cout << "Compute eigen vector images ..." << endl;
o_Mr2dPca.pca_TransfSignal (po_TabMr2d, po_TabMr2d);
if (po_Param->e_WriteTransf) {
char NameEigen[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(NameEigen, "pca_%dEigenVectors_Aft",k+1);
po_TabMr2d[k].write (NameEigen);
}
}
if (po_Param->e_WithNoiseModel) {
res_InitNoiseModelPca ();
//o_Mr2dPca.pca_Thresold (po_TabMr2d, po_TabNoiseModel);
// entrop filter
// -------------
if (po_Param->e_Verbose) cout << "Multiscale Entropy Filtering ..." << endl;
for (int k=0; k<po_Param->i_NbImage; k++) {
fltarray o_TabAlpha(po_Param->i_NbBand-1);
for (int b=0; b < po_Param->i_NbBand-1; b++) o_TabAlpha(b) = po_Param->f_RegulVal;
MultiResol *o_MR_Model = NULL;
if ((po_Param->e_DataEdge == True) && (po_Param->e_Transform == TO_PAVE_BSPLINE)) {
o_MR_Model = new MultiResol(po_Param->i_NbLin, po_Param->i_NbCol,
po_Param->i_NbPlan, po_Param->e_Transform, "Model");
mr_getmodel_from_edge(po_TabMr2d[k], *o_MR_Model, po_TabNoiseModel[k]);
(*o_MR_Model).write("xx_model.mr");
}
for (int b=0; b<po_Param->i_NbBand-1; b++) {
mw_mcfilter (b, po_TabMr2d[k], po_TabNoiseModel[k], po_Param->i_TypeOpt,
o_TabAlpha, po_Param->e_DataSNR, po_Param->e_DataEdge,
o_MR_Model, po_Param->f_CvgParam, po_Param->i_NbIterEntrop,
po_Param->e_PositivImag, po_Param->e_Verbose);
}
}
}
if (po_Param->e_WriteEigenOnDisk) {
char NameEigen[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(NameEigen, "wk_ev_%d",k+1);
po_TabMr2d[k].write (NameEigen);
}
}
}
void mw_Result::res_CurrentCompute () {
// not used
cout << "!!!!! NOT USED !!!!!" << endl;
}
void mw_Result::res_Recons () {
if (po_Param->e_Verbose) cout << "Reconstruction process ..." << endl;
int ai_NbEigen=0;
for (int i=0; i<po_Param->ti_NbrUseEigen[0]; i++) //same value for all bands
if (po_Param->tti_TabKill[i][0] == 0) ai_NbEigen++;
if (po_Param->e_Verbose) cout << "Number of eigen vector used for the reconstruction : " ;
if (po_Param->e_Verbose) cout << "Ne = " << ai_NbEigen << " (in all band)" << endl;
// apply the inverse reconstruction from a subset of eigen vectors
o_Mr2dPca.invsubtransform (po_TabMr2d, po_TabMr2d, po_Param->ti_NbrUseEigen,
po_Param->tti_TabKill);
// inv transform Mr2d
for (int k=0; k<po_Param->i_NbImage; k++)
if (po_Param->e_UseReconsAdjoint) po_TabMr2d[k].rec_adjoint(po_Param->po_TabIma[k]);
else po_TabMr2d[k].recons(po_Param->po_TabIma[k]);
// Write Mr2d recons
if (po_Param->e_WriteTransf == True) {
char Mr2dRecons[256];
for (int k=0; k < po_Param->i_NbImage; k++) {
sprintf(Mr2dRecons, "mr2d_pca_InvTransf_%d",k+1);
po_TabMr2d[k].write (Mr2dRecons);
sprintf(Mr2dRecons, "mr2d_pca_InvImag_%d", k+1);
io_write_ima_float(Mr2dRecons, po_Param->po_TabIma[k]);
}
}
}
void mw_Result::res_Write () {
if (po_Param->e_Verbose) cout << "Write result ..." << endl;
for (int k=0;k<po_Param->i_NbImage;k++)
for (int i=0;i<po_Param->i_NbLin;i++)
for (int j=0;j<po_Param->i_NbCol;j++)
o_3dDataOut(j,i,k) = po_Param->po_TabIma[k](i,j);
// write the data
fits_write_fltarr (po_Param->tc_NameOut, o_3dDataOut);
}
void mw_Result::res_InitNoiseModelMr2d () {
// noise model class initialization
if (po_Param->e_Verbose) cout << "Create mr2d noise model ..." << endl;
for (int k=0; k<po_Param->i_NbImage; k++) {
po_TabNoiseModel[k].alloc (po_Param->e_TypeNoise, po_Param->i_NbLin,
po_Param->i_NbCol, po_Param->i_NbPlan,
po_Param->e_Transform);
if (po_Param->f_NoiseIma > FLOAT_EPSILON)
po_TabNoiseModel[k].SigmaNoise = po_Param->f_NoiseIma;
po_TabNoiseModel[k].CCD_Gain = po_Param->f_Gain;
po_TabNoiseModel[k].CCD_ReadOutSigma = po_Param->f_SigmaGauss;
po_TabNoiseModel[k].CCD_ReadOutMean = po_Param->f_MeanGauss;
// entrop
po_TabNoiseModel[k].NiterSigmaClip = po_Param->i_NiterClip;
po_TabNoiseModel[k].SizeBlockSigmaNoise = po_Param->i_SizeBlock;
if (po_Param->e_UseRMSMap == True) {
po_TabNoiseModel[k].UseRmsMap = True;
io_read_ima_float(po_Param->tc_NameRMSMap, po_TabNoiseModel[k].RmsMap);
}
if (po_Param->e_TypeNoise == NOISE_SPECKLE)
po_TabNoiseModel[k].SigmaApprox = True;
// end entrop
if (po_Param->f_NSigmaMr2d >= 0)
for (int i=0; i<po_Param->i_NbPlan; i++)
po_TabNoiseModel[k].NSigma[i] = po_Param->f_NSigmaMr2d;
//po_TabNoiseModel[k].SupIsol = po_Param->e_SupIsolPixel;
po_TabNoiseModel[k].model (po_Param->po_TabIma[k]);
if (po_Param->e_WriteSupportMr2d) {
char NameSupport[256];
sprintf(NameSupport, "mr2d_Support_%d",k+1);
po_TabNoiseModel[k].write_support_mr (NameSupport);
}
}
//if (po_Param->e_ModNoiseModelMr2d) res_ModSupport (po_Param->f_ModNsigmaMr2d);
}
void mw_Result::res_InitNoiseModelPca () {
// noise model class initialization
if (po_Param->e_Verbose) cout << "Create pca noise model ..." << endl;
int k;
o_Mr2dPca.pca_ComputeNoise (po_TabMr2d, po_TabNoiseModel, po_TabNoiseModel);
for (k=0; k<po_Param->i_NbImage; k++) {
//if (po_Param->e_DilateSupportPCA) po_TabNoiseModel[k].DilateSupport = True;
if (po_Param->f_NSigmaPCA >= 0)
for (int i=0; i<po_Param->i_NbPlan; i++)
po_TabNoiseModel[k].NSigma[i] = po_Param->f_NSigmaPCA;
else {
po_TabNoiseModel[k].NSigma[0] = 4;
for (int i=1; i<po_Param->i_NbPlan; i++)
po_TabNoiseModel[k].NSigma[i] = 3;
}
po_TabNoiseModel[k].set_support (po_TabMr2d[k]);
//if (po_Param->e_DestroyRings) res_DestroyRingsInPcaSup ();
}
//if (po_Param->e_ModNoiseModelEntrop) res_ModSupport (po_Param->f_ModNsigmaEntrop);
for (k=0; k<po_Param->i_NbImage; k++)
if (po_Param->e_WriteSupportPCA) {
char NameSupport[256];
sprintf(NameSupport, "pca_Support_%d",k+1);
po_TabNoiseModel[k].write_support_mr (NameSupport);
}
}
to_Param* mw_Result::res_GetpParam () {return po_Param;}
/******************************************************************************
classe pca_Iter
******************************************************************************/
Bool mw_Iter::iter_End () {
//cout << " ==> END" << endl;
NbIter++;
if (NbIter > po_Result->po_Param->i_NbIter) {
for (int k=0;k<po_Result->po_Param->i_NbImage;k++)
for (int i=0;i<po_Result->po_Param->i_NbLin;i++)
for (int j=0;j<po_Result->po_Param->i_NbCol;j++) {
po_Result->po_Param->po_TabIma[k](i,j) = o_3dResidu(i,j,k);
if ( po_Result->po_Param->e_PositivImag
&& po_Result->po_Param->po_TabIma[k](i,j)<0.)
po_Result->po_Param->po_TabIma[k](i,j) = 0.0;
if ( po_Result->po_Param->e_MaxImag
&& po_Result->po_Param->po_TabIma[k](i,j)>MAX_IMAG_VALUE)
po_Result->po_Param->po_TabIma[k](i,j) = MAX_IMAG_VALUE;
}
return False;
} else return True;
}
void mw_Iter::iter_Residu () {
for (int k=0;k<po_Result->po_Param->i_NbImage;k++)
for (int i=0;i<po_Result->po_Param->i_NbLin;i++)
for (int j=0;j<po_Result->po_Param->i_NbCol;j++) {
// positiv constraint
if ( po_Result->po_Param->e_PositivImag
&& po_Result->po_Param->po_TabIma[k](i,j)<0.)
po_Result->po_Param->po_TabIma[k](i,j) = 0.0;
if ( po_Result->po_Param->e_MaxImag
&& po_Result->po_Param->po_TabIma[k](i,j)>MAX_IMAG_VALUE)
po_Result->po_Param->po_TabIma[k](i,j) = MAX_IMAG_VALUE;
// I(i) = I(i) + E(i)
o_3dResidu(i,j,k) += po_Result->po_Param->po_TabIma[k](i,j);
// E(i) = Einit - I(i)
po_Result->po_Param->po_TabIma[k](i,j) = o_3dInit(i,j,k) - o_3dResidu(i,j,k);
}
}
to_Result* mw_Iter::iter_getpResult() {return po_Result;}
| 30,382 | 12,111 |