text string | size int64 | token_count int64 |
|---|---|---|
// Copyright Claudio Bantaloukas 2017-2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <throwing/unique_ptr.hpp>
int main() {
// cannot assign from unique_ptr to another (array version)
throwing::unique_ptr<int[]> from;
throwing::unique_ptr<int[]> to;
to = from;
return 0;
}
| 432 | 153 |
/**
* 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.
*/
#undef NDEBUG
#include <iostream>
#include "IntegrationBase.h"
#include "../StatefulProcessor.h"
#include "../TestBase.h"
#include "utils/IntegrationTestUtils.h"
#include "core/state/ProcessorController.h"
using org::apache::nifi::minifi::processors::StatefulProcessor;
using org::apache::nifi::minifi::state::ProcessorController;
namespace {
using LogChecker = std::function<bool()>;
struct HookCollection {
StatefulProcessor::HookType on_schedule_hook_;
std::vector<StatefulProcessor::HookType> on_trigger_hooks_;
LogChecker log_checker_;
};
class StatefulIntegrationTest : public IntegrationBase {
public:
explicit StatefulIntegrationTest(std::string testCase, HookCollection hookCollection)
: on_schedule_hook_(std::move(hookCollection.on_schedule_hook_))
, on_trigger_hooks_(std::move(hookCollection.on_trigger_hooks_))
, log_checker_(hookCollection.log_checker_)
, test_case_(std::move(testCase)) {
}
void testSetup() override {
LogTestController::getInstance().reset();
LogTestController::getInstance().setDebug<core::ProcessGroup>();
LogTestController::getInstance().setDebug<core::Processor>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<StatefulIntegrationTest>();
logger_->log_info("Running test case \"%s\"", test_case_);
}
void updateProperties(std::shared_ptr<minifi::FlowController> fc) override {
const auto controllerVec = fc->getAllComponents();
/* This tests depends on a configuration that contains only one StatefulProcessor named statefulProcessor
* (See TestStateTransactionality.yml)
* In this case there are two components in the flowcontroller: first is the controller itself,
* second is the processor that the test uses.
* Added here some assertions to make it clear. In case any of these fail without changing the corresponding yml file,
* that most probably means a breaking change. */
assert(controllerVec.size() == 2);
assert(controllerVec[0]->getComponentName() == "FlowController");
assert(controllerVec[1]->getComponentName() == "statefulProcessor");
// set hooks
const auto processController = std::dynamic_pointer_cast<ProcessorController>(controllerVec[1]);
assert(processController != nullptr);
stateful_processor_ = std::dynamic_pointer_cast<StatefulProcessor>(processController->getProcessor());
assert(stateful_processor_ != nullptr);
stateful_processor_->setHooks(on_schedule_hook_, on_trigger_hooks_);
}
void runAssertions() override {
using org::apache::nifi::minifi::utils::verifyEventHappenedInPollTime;
assert(verifyEventHappenedInPollTime(std::chrono::milliseconds(wait_time_), [&] {
return stateful_processor_->hasFinishedHooks() && log_checker_();
}));
}
private:
const StatefulProcessor::HookType on_schedule_hook_;
const std::vector<StatefulProcessor::HookType> on_trigger_hooks_;
const LogChecker log_checker_;
const std::string test_case_;
std::shared_ptr<StatefulProcessor> stateful_processor_;
std::shared_ptr<logging::Logger> logger_{logging::LoggerFactory<StatefulIntegrationTest>::getLogger()};
};
const std::unordered_map<std::string, std::string> exampleState{{"key1", "value1"}, {"key2", "value2"}};
const std::unordered_map<std::string, std::string> exampleState2{{"key3", "value3"}, {"key4", "value4"}};
auto standardLogChecker = [] {
const std::string logs = LogTestController::getInstance().log_output.str();
const auto errorResult = utils::StringUtils::countOccurrences(logs, "[error]");
const auto warningResult = utils::StringUtils::countOccurrences(logs, "[warning]");
return errorResult.second == 0 && warningResult.second == 0;
};
auto commitAndRollbackWarnings = [] {
const std::string logs = LogTestController::getInstance().log_output.str();
const auto errorResult = utils::StringUtils::countOccurrences(logs, "[error]");
const auto commitWarningResult = utils::StringUtils::countOccurrences(logs, "[warning] Caught \"Process Session Operation: State manager commit failed.\"");
const auto rollbackWarningResult = utils::StringUtils::countOccurrences(logs,
"[warning] Caught Exception during process session rollback: Process Session Operation: State manager rollback failed.");
return errorResult.second == 0 && commitWarningResult.second == 1 && rollbackWarningResult.second == 1;
};
auto exceptionRollbackWarnings = [] {
const std::string logs = LogTestController::getInstance().log_output.str();
const auto errorResult = utils::StringUtils::countOccurrences(logs, "[error]");
const auto exceptionWarningResult = utils::StringUtils::countOccurrences(logs, "[warning] Caught \"Triggering rollback\"");
const auto rollbackWarningResult = utils::StringUtils::countOccurrences(logs, "[warning] ProcessSession rollback for statefulProcessor executed");
return errorResult.second == 0 && exceptionWarningResult.second == 1 && rollbackWarningResult.second == 1;
};
const std::unordered_map<std::string, HookCollection> testCasesToHookLists {
{"State_is_recorded_after_committing", {
{},
{
[] (core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[] (core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
}},
{"State_is_discarded_after_rolling_back", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState2));
throw std::runtime_error("Triggering rollback");
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
exceptionRollbackWarnings
}},
{
"Get_in_onSchedule_without_previous_state", {
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
},
{},
standardLogChecker
}
},
{
"Set_in_onSchedule", {
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
{
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
}
},
{
"Clear_in_onSchedule", {
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.clear());
assert(stateManager.set(exampleState));
assert(stateManager.clear());
},
{
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
}
},
standardLogChecker
},
},
{
"Persist_in_onSchedule", {
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
}
},
{},
standardLogChecker
}
},
{
"Manual_beginTransaction", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.beginTransaction());
}
},
standardLogChecker
},
},
{
"Manual_commit", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(stateManager.commit());
}
},
commitAndRollbackWarnings
},
},
{
"Manual_rollback", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.rollback());
}
},
commitAndRollbackWarnings
},
},
{
"Get_without_previous_state", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
}
},
standardLogChecker
},
},
{
"(set),(get,get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
},
},
{
"(set),(get,set)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.set(exampleState));
}
},
standardLogChecker
},
},
{
"(set),(get,clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.clear());
}
},
standardLogChecker
},
},
{
"(set),(get,persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
assert(stateManager.persist());
}
},
standardLogChecker
},
},
{
"(set,!get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
},
},
standardLogChecker
},
},
{
"(set,set)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(stateManager.set(exampleState));
},
},
standardLogChecker
},
},
{
"(set,!clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(!stateManager.clear());
},
},
standardLogChecker
},
},
{
"(set,persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
assert(stateManager.persist());
},
},
standardLogChecker
},
},
{
"(set),(clear,!get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
}
},
standardLogChecker
},
},
{
"(set),(clear),(!get),(set),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(!stateManager.get(state));
assert(state.empty());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
}
},
standardLogChecker
},
},
{
"(set),(clear,set)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
assert(stateManager.set(exampleState));
},
},
standardLogChecker
},
},
{
"(set),(clear),(!clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.clear());
},
},
standardLogChecker
},
},
{
"(set),(clear),(persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
},
standardLogChecker
},
},
{
"(persist),(set),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
},
},
standardLogChecker
},
},
{
"(persist),(set),(clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
},
},
standardLogChecker
},
},
{
"(persist),(persist)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
},
},
standardLogChecker
},
},
{
"No_change_2_rounds", {
{},
{
[](core::CoreComponentStateManager&) {},
[](core::CoreComponentStateManager&) {},
},
standardLogChecker
},
},
{
"(!clear)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(!stateManager.clear());
},
},
standardLogChecker
},
},
{
"(set),(get,throw)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
throw std::runtime_error("Triggering rollback");
},
},
exceptionRollbackWarnings
}
},
{
"(set),(clear,throw),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.set(exampleState));
},
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.clear());
throw std::runtime_error("Triggering rollback");
},
[](core::CoreComponentStateManager& stateManager) {
std::unordered_map<std::string, std::string> state;
assert(stateManager.get(state));
assert(state == exampleState);
},
},
exceptionRollbackWarnings
}
},
{
"(set),(clear,throw),(get)", {
{},
{
[](core::CoreComponentStateManager& stateManager) {
assert(stateManager.persist());
throw std::runtime_error("Triggering rollback");
},
},
exceptionRollbackWarnings
}
}
};
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::cerr << "A test file (*.yml) argument is mandatory, a second argument for test case name is optional\n";
return EXIT_FAILURE;
}
const std::string testFile = argv[1];
if (argc == 2) {
// run all tests
for (const auto& test : testCasesToHookLists) {
StatefulIntegrationTest statefulIntegrationTest(test.first, test.second);
statefulIntegrationTest.run(testFile);
}
} else if (argc == 3) {
// run specified test case
const std::string testCase = argv[2];
auto iter = testCasesToHookLists.find(testCase);
if (iter == testCasesToHookLists.end()) {
std::cerr << "Test case \"" << testCase << "\" cannot be found\n";
return EXIT_FAILURE;
}
StatefulIntegrationTest statefulIntegrationTest(iter->first, iter->second);
statefulIntegrationTest.run(testFile);
} else {
std::cerr << "Too many arguments\n";
return EXIT_FAILURE;
}
}
| 19,087 | 5,447 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "StandaloneRendererPrivate.h"
#include "OpenGL/SlateOpenGLRenderer.h"
FSlateOpenGLContext::FSlateOpenGLContext()
: WindowHandle(NULL)
, Context(NULL)
{
}
FSlateOpenGLContext::~FSlateOpenGLContext()
{
Destroy();
}
void FSlateOpenGLContext::Initialize( void* InWindow, const FSlateOpenGLContext* SharedContext )
{
}
void FSlateOpenGLContext::Destroy()
{
}
void FSlateOpenGLContext::MakeCurrent()
{
}
| 476 | 178 |
//MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
#if !defined(WIN32)
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "finalmq/poller/PollerImplEpoll.h"
#include "finalmq/helpers/OperatingSystem.h"
#include "MockIOperatingSystem.h"
using ::testing::_;
using ::testing::Return;
using ::testing::InSequence;
using ::testing::DoAll;
using namespace finalmq;
static const std::string BUFFER = "Hello";
static const int EPOLL_FD = 3;
static const int CONTROLSOCKET_READ = 4;
static const int CONTROLSOCKET_WRITE = 5;
static const int TESTSOCKET = 7;
static const int NUMBER_OF_BYTES_TO_READ = 20;
static const int TIMEOUT = 10;
MATCHER_P(Event, event, "")
{
return (arg->events == event->events &&
arg->data.fd == event->data.fd);
}
class TestEpoll: public testing::Test
{
protected:
virtual void SetUp()
{
m_mockMockOperatingSystem = new MockIOperatingSystem;
OperatingSystem::setInstance(std::unique_ptr<IOperatingSystem>(m_mockMockOperatingSystem));
m_select = std::make_unique<PollerImplEpoll>();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_create1(EPOLL_CLOEXEC)).Times(1)
.WillRepeatedly(Return(EPOLL_FD));
SocketDescriptorPtr sd1 = std::make_shared<SocketDescriptor>(CONTROLSOCKET_READ);
SocketDescriptorPtr sd2 = std::make_shared<SocketDescriptor>(CONTROLSOCKET_WRITE);
EXPECT_CALL(*m_mockMockOperatingSystem, makeSocketPair(_, _)).Times(1)
.WillRepeatedly(DoAll(testing::SetArgReferee<0>(sd1), testing::SetArgReferee<1>(sd2), Return(0)));
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = CONTROLSOCKET_READ;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, CONTROLSOCKET_READ, Event(&evCtl))).Times(1);
m_select->init();
testing::Mock::VerifyAndClearExpectations(m_mockMockOperatingSystem);
}
virtual void TearDown()
{
EXPECT_CALL(*m_mockMockOperatingSystem, close(EPOLL_FD)).Times(1).WillRepeatedly(Return(0));
EXPECT_CALL(*m_mockMockOperatingSystem, closeSocket(_)).WillRepeatedly(Return(0));
m_select = nullptr;
OperatingSystem::setInstance({});
}
MockIOperatingSystem* m_mockMockOperatingSystem = nullptr;
std::unique_ptr<IPoller> m_select;
};
TEST_F(TestEpoll, timeout)
{
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(10);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, true);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
TEST_F(TestEpoll, testAddSocketReadableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(_, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketReadableEINTR)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
{
InSequence seq;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(_, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(-1));
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(_, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
}
EXPECT_CALL(*m_mockMockOperatingSystem, getLastError()).Times(1)
.WillOnce(Return(SOCKETERROR(EINTR)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketReadableError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(-1));
EXPECT_CALL(*m_mockMockOperatingSystem, getLastError()).Times(1)
.WillOnce(Return(SOCKETERROR(EACCES)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, true);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
TEST_F(TestEpoll, testAddSocketReadableWaitSocketDescriptorsChanged)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
epoll_event evCtlRemove;
evCtlRemove.events = 0;
evCtlRemove.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_DEL, socket->getDescriptor(), Event(&evCtlRemove))).Times(1);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(
testing::DoAll(
testing::Invoke([this, &socket](int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t* sigmask){
m_select->removeSocket(socket);
}),
testing::SetArgPointee<1>(events),
Return(1)
)
);
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(NUMBER_OF_BYTES_TO_READ), Return(0)));
EXPECT_CALL(*m_mockMockOperatingSystem, closeSocket(socket->getDescriptor())).WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, NUMBER_OF_BYTES_TO_READ);
}
}
TEST_F(TestEpoll, testAddSocketDisconnectRead)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(0), Return(0)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketDisconnectEpollError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLERR;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, true);
EXPECT_EQ(result.descriptorInfos[0].readable, false);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketIoCtlError)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLIN;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
EXPECT_CALL(*m_mockMockOperatingSystem, ioctlInt(socket->getDescriptor(), FIONREAD, _)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<2>(0), Return(-1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, true);
EXPECT_EQ(result.descriptorInfos[0].writable, false);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketWritableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
epoll_event evCtlWrite;
evCtlWrite.events = EPOLLIN | EPOLLOUT;
evCtlWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlWrite))).Times(1);
m_select->enableWrite(socket);
struct epoll_event events;
events.data.fd = socket->getDescriptor();
events.events = EPOLLOUT;
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(testing::DoAll(testing::SetArgPointee<1>(events), Return(1)));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, false);
EXPECT_EQ(result.descriptorInfos.size(), 1);
if (result.descriptorInfos.size() == 1)
{
EXPECT_EQ(result.descriptorInfos[0].sd, socket->getDescriptor());
EXPECT_EQ(result.descriptorInfos[0].disconnected, false);
EXPECT_EQ(result.descriptorInfos[0].readable, false);
EXPECT_EQ(result.descriptorInfos[0].writable, true);
EXPECT_EQ(result.descriptorInfos[0].bytesToRead, 0);
}
}
TEST_F(TestEpoll, testAddSocketDisableWritableWait)
{
SocketDescriptorPtr socket = std::make_shared<SocketDescriptor>(TESTSOCKET);
epoll_event evCtl;
evCtl.events = EPOLLIN;
evCtl.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_ADD, socket->getDescriptor(), Event(&evCtl))).Times(1);
m_select->addSocketEnableRead(socket);
epoll_event evCtlWrite;
evCtlWrite.events = EPOLLIN | EPOLLOUT;
evCtlWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlWrite))).Times(1);
m_select->enableWrite(socket);
epoll_event evCtlDisableWrite;
evCtlDisableWrite.events = EPOLLIN;
evCtlDisableWrite.data.fd = socket->getDescriptor();
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_ctl(EPOLL_FD, EPOLL_CTL_MOD, socket->getDescriptor(), Event(&evCtlDisableWrite))).Times(1);
m_select->disableWrite(socket);
EXPECT_CALL(*m_mockMockOperatingSystem, epoll_pwait(EPOLL_FD, _, _, TIMEOUT, nullptr)).Times(1)
.WillRepeatedly(Return(0));
const PollerResult& result = m_select->wait(TIMEOUT);
EXPECT_EQ(result.error, false);
EXPECT_EQ(result.timeout, true);
EXPECT_EQ(result.descriptorInfos.size(), 0);
}
#endif
| 17,597 | 6,238 |
#include <watchdogs.h>
//-------------------------------------------------------------------------
// External attributes
//-------------------------------------------------------------------------
IntervalTimer Watchdogs::_wdgTimer;
unsigned long Watchdogs::_aliveCount;
unsigned long Watchdogs::_timeoutval;
bool Watchdogs::_wwdgRunning;
bool Watchdogs::_iwdgRunning;
//-------------------------------------------------------------------------
// Public methods
//-------------------------------------------------------------------------
// Start watchdog timers
void Watchdogs::begin(unsigned long timeout)
{
bool enableWwdg = true;
bool enableIwdg = true;
Watchdogs::_timeoutval = constrain(timeout, WATCHDOGS_TIMOUT_MIN, WATCHDOGS_TIMOUT_MAX);
Watchdogs::_timeoutval = Watchdogs::_timeoutval / 10;
Watchdogs::_aliveCount = 0;
RCC_LSICmd(ENABLE); //LSI is needed for Watchdogs
Watchdogs::_wdgTimer.begin(Watchdogs::_tickleWDGs, 20, hmSec, TIMER7);
System.disableUpdates();
Watchdogs::_wwdgRunning = enableWwdg;
if (enableWwdg) {
RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE);
WWDG_SetPrescaler(WWDG_Prescaler_8);
WWDG_SetWindowValue(0x7F);
WWDG_Enable(0x7F);
}
Watchdogs::_iwdgRunning = enableIwdg;
if (enableIwdg) {
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
IWDG_SetPrescaler(IWDG_Prescaler_256);
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
IWDG_SetReload(0xFFF);
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
IWDG_Enable();
}
System.on(firmware_update_pending, Watchdogs::_handler);
}
// Reset watchdog timer
void Watchdogs::tickle()
{
Watchdogs::_aliveCount = 0;
}
//-------------------------------------------------------------------------
// Private methods
//-------------------------------------------------------------------------
void Watchdogs::_tickleWDGs()
{
if (Watchdogs::_aliveCount < Watchdogs::_timeoutval) {
if (Watchdogs::_wwdgRunning) {
WWDG_SetCounter(0x7F);
}
if (Watchdogs::_iwdgRunning) {
IWDG_ReloadCounter();
}
Watchdogs::_aliveCount++;
}
}
void Watchdogs::_handler(system_event_t event, int param) {
if (Watchdogs::_wwdgRunning) WWDG_DeInit();
System.enableUpdates();
Watchdogs::_wdgTimer.end();
}
| 2,398 | 804 |
/**
* @file default_sentinel.hpp
*
* @brief default_sentinel の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
#define BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
#include <bksge/fnd/iterator/config.hpp>
#if defined(BKSGE_USE_STD_RANGES_ITERATOR)
namespace bksge
{
using std::default_sentinel_t;
using std::default_sentinel;
} // namespace bksge
#else
#include <bksge/fnd/config.hpp>
namespace bksge
{
struct default_sentinel_t {};
BKSGE_INLINE_VAR BKSGE_CONSTEXPR
default_sentinel_t default_sentinel{};
} // namespace bksge
#endif
#endif // BKSGE_FND_ITERATOR_DEFAULT_SENTINEL_HPP
| 665 | 325 |
#include "RecoLocalCalo/EcalRecAlgos/interface/EcalGainRatiosGPU.h"
#include "FWCore/Utilities/interface/typelookup.h"
#include "HeterogeneousCore/CUDAUtilities/interface/cudaCheck.h"
EcalGainRatiosGPU::EcalGainRatiosGPU(EcalGainRatios const& values)
: gain12Over6_(values.size()), gain6Over1_(values.size()) {
// fill in eb
auto const& barrelValues = values.barrelItems();
for (unsigned int i = 0; i < barrelValues.size(); i++) {
gain12Over6_[i] = barrelValues[i].gain12Over6();
gain6Over1_[i] = barrelValues[i].gain6Over1();
}
// fill in ee
auto const& endcapValues = values.endcapItems();
auto const offset = barrelValues.size();
for (unsigned int i = 0; i < endcapValues.size(); i++) {
gain12Over6_[offset + i] = endcapValues[i].gain12Over6();
gain6Over1_[offset + i] = endcapValues[i].gain6Over1();
}
}
EcalGainRatiosGPU::Product::~Product() {
// deallocation
cudaCheck(cudaFree(gain12Over6));
cudaCheck(cudaFree(gain6Over1));
}
EcalGainRatiosGPU::Product const& EcalGainRatiosGPU::getProduct(cudaStream_t cudaStream) const {
auto const& product = product_.dataForCurrentDeviceAsync(
cudaStream, [this](EcalGainRatiosGPU::Product& product, cudaStream_t cudaStream) {
// malloc
cudaCheck(cudaMalloc((void**)&product.gain12Over6, this->gain12Over6_.size() * sizeof(float)));
cudaCheck(cudaMalloc((void**)&product.gain6Over1, this->gain6Over1_.size() * sizeof(float)));
// transfer
cudaCheck(cudaMemcpyAsync(product.gain12Over6,
this->gain12Over6_.data(),
this->gain12Over6_.size() * sizeof(float),
cudaMemcpyHostToDevice,
cudaStream));
cudaCheck(cudaMemcpyAsync(product.gain6Over1,
this->gain6Over1_.data(),
this->gain6Over1_.size() * sizeof(float),
cudaMemcpyHostToDevice,
cudaStream));
});
return product;
}
TYPELOOKUP_DATA_REG(EcalGainRatiosGPU);
| 2,140 | 749 |
#include "RaZor/Interface/Component/RigidBodyGroup.hpp"
#include "ui_RigidBodyComp.h"
#include <RaZ/Entity.hpp>
#include <RaZ/Physics/RigidBody.hpp>
RigidBodyGroup::RigidBodyGroup(Raz::Entity& entity, AppWindow& appWindow) : ComponentGroup(entity, appWindow) {
Ui::RigidBodyComp rigidBodyComp {};
rigidBodyComp.setupUi(this);
auto& rigidBody = entity.getComponent<Raz::RigidBody>();
// Mass
rigidBodyComp.mass->setValue(static_cast<double>(rigidBody.getMass()));
connect(rigidBodyComp.mass, QOverload<double>::of(&ValuePicker::valueChanged), [&rigidBody] (double val) {
rigidBody.setMass(static_cast<float>(val));
});
// Bounciness
rigidBodyComp.bounciness->setValue(static_cast<double>(rigidBody.getBounciness()));
connect(rigidBodyComp.bounciness, QOverload<double>::of(&ValuePicker::valueChanged), [&rigidBody] (double val) {
rigidBody.setBounciness(static_cast<float>(val));
});
// Velocity
rigidBodyComp.velocityX->setValue(static_cast<double>(rigidBody.getVelocity().x()));
rigidBodyComp.velocityY->setValue(static_cast<double>(rigidBody.getVelocity().y()));
rigidBodyComp.velocityZ->setValue(static_cast<double>(rigidBody.getVelocity().z()));
const auto updateVelocity = [rigidBodyComp, &rigidBody] (double) {
const auto velocityX = static_cast<float>(rigidBodyComp.velocityX->value());
const auto velocityY = static_cast<float>(rigidBodyComp.velocityY->value());
const auto velocityZ = static_cast<float>(rigidBodyComp.velocityZ->value());
rigidBody.setVelocity(Raz::Vec3f(velocityX, velocityY, velocityZ));
};
connect(rigidBodyComp.velocityX, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
connect(rigidBodyComp.velocityY, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
connect(rigidBodyComp.velocityZ, QOverload<double>::of(&ValuePicker::valueChanged), updateVelocity);
}
void RigidBodyGroup::removeComponent() {
m_entity.removeComponent<Raz::RigidBody>();
}
| 1,992 | 707 |
#include "TabItem.h"
namespace StiGame
{
namespace Gui
{
TabItem::TabItem() : Item("TabItem")
{
tabName = "Untitled";
}
TabItem::TabItem(std::string m_tabName) : Item("TabItem")
{
tabName = m_tabName;
}
TabItem::~TabItem()
{
}
std::string TabItem::getTabName(void)
{
return tabName;
}
void TabItem::onClick(Point *relpt)
{
container.iterator().publishOnClick(relpt);
}
void TabItem::onMouseMotion(Point *relpt)
{
container.iterator().publishOnMouseMotion(relpt);
}
void TabItem::setMouseOver(bool m_mouseOver)
{
if(!m_mouseOver)
{
for(ItemIterator it = container.iterator(); it.next();)
{
it.item()->setMouseOver(false);
}
}
}
Surface* TabItem::render(void)
{
Surface *buffer = new Surface(width, height);
buffer->fill(background);
SDL_Rect src = SDL_Rect();
SDL_Rect dst = SDL_Rect();
for(ItemIterator it = container.iterator(); it.next();)
{
Item *item = it.item();
src.w = item->getWidth();
src.h = item->getHeight();
dst.w = src.w;
dst.h = src.h;
dst.x = item->getX();
dst.y = item->getY();
Surface *ibuf = item->render();
buffer->blit(ibuf, &src, &dst);
delete ibuf;
}
return buffer;
}
}
}
| 1,240 | 480 |
// Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0
#pragma once
namespace sf {
class Text;
}
namespace hg::Utils {
[[nodiscard]] float getFontHeight(sf::Text& font);
[[nodiscard]] float getFontHeight(sf::Text& font, const unsigned int charSize);
} // namespace hg::Utils
| 379 | 141 |
#include "bullet-event.h"
#include "../../valve_sdk/interfaces/IVRenderBeams.h"
#include "../../features/ragebot/ragebot.h"
#include "../../features/ragebot/resolver/resolver.h"
void BulletImpactEvent::FireGameEvent(IGameEvent *event) {
if (!g_LocalPlayer || !event) return;
static ConVar* sv_showimpacts = g_CVar->FindVar("sv_showimpacts");
if (g_Options.misc_bullet_impacts)
sv_showimpacts->SetValue(1);
else
sv_showimpacts->SetValue(0);
if (g_Options.misc_bullet_tracer) {
if (g_EngineClient->GetPlayerForUserID(event->GetInt("userid")) == g_EngineClient->GetLocalPlayer() && g_LocalPlayer && g_LocalPlayer->IsAlive())
{
float x = event->GetFloat("x"), y = event->GetFloat("y"), z = event->GetFloat("z");
bulletImpactInfo.push_back({ g_GlobalVars->curtime, Vector(x, y, z) });
}
}
int32_t userid = g_EngineClient->GetPlayerForUserID(event->GetInt("userid"));
if (userid == g_EngineClient->GetLocalPlayer()) {
if (RageBot::Get().iTargetID != NULL) {
auto player = C_BasePlayer::GetPlayerByIndex(RageBot::Get().iTargetID);
if (!player) return;
int32_t idx = player->EntIndex();
auto &player_recs = Resolver::Get().ResolveRecord[idx];
if (!player->IsDormant())
{
int32_t tickcount = g_GlobalVars->tickcount;
if (tickcount != tickHitWall)
{
tickHitWall = tickcount;
originalShotsMissed = player_recs.iMissedShots;
if (tickcount != tickHitPlayer) {
tickHitWall = tickcount;
++player_recs.iMissedShots;
}
}
}
}
}
}
int BulletImpactEvent::GetEventDebugID(void)
{
return EVENT_DEBUG_ID_INIT;
}
void BulletImpactEvent::RegisterSelf()
{
g_GameEvents->AddListener(this, "bullet_impact", false);
}
void BulletImpactEvent::UnregisterSelf()
{
g_GameEvents->RemoveListener(this);
}
void BulletImpactEvent::Paint(void)
{
if (!g_Options.misc_bullet_tracer) return;
if (!g_EngineClient->IsInGame() || !g_LocalPlayer || !g_LocalPlayer->IsAlive()) {
bulletImpactInfo.clear();
return;
}
std::vector<BulletImpactInfo> &impacts = bulletImpactInfo;
if (impacts.empty()) return;
Color current_color(g_Options.color_bullet_tracer);
for (size_t i = 0; i < impacts.size(); i++)
{
auto current_impact = impacts.at(i);
BeamInfo_t beamInfo;
beamInfo.m_nType = TE_BEAMPOINTS;
beamInfo.m_pszModelName = "sprites/purplelaser1.vmt";
beamInfo.m_nModelIndex = -1;
beamInfo.m_flHaloScale = 0.0f;
beamInfo.m_flLife = 3.3f;
beamInfo.m_flWidth = 4.f;
beamInfo.m_flEndWidth = 4.f;
beamInfo.m_flFadeLength = 0.0f;
beamInfo.m_flAmplitude = 2.0f;
beamInfo.m_flBrightness = 255.f;
beamInfo.m_flSpeed = 0.2f;
beamInfo.m_nStartFrame = 0;
beamInfo.m_flFrameRate = 0.f;
beamInfo.m_flRed = current_color.r();
beamInfo.m_flGreen = current_color.g();
beamInfo.m_flBlue = current_color.b();
beamInfo.m_nSegments = 2;
beamInfo.m_bRenderable = true;
beamInfo.m_nFlags = FBEAM_ONLYNOISEONCE | FBEAM_NOTILE | FBEAM_HALOBEAM | FBEAM_FADEIN;
beamInfo.m_vecStart = g_LocalPlayer->GetEyePos();
beamInfo.m_vecEnd = current_impact.m_vecHitPos;
auto beam = g_RenderBeam->CreateBeamPoints(beamInfo);
if (beam) g_RenderBeam->DrawBeam(beam);
impacts.erase(impacts.begin() + i);
}
}
void BulletImpactEvent::AddSound(C_BasePlayer *p) {
} | 3,306 | 1,506 |
/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
/*
* Manipulation of GL extensions.
*
* So far we insert GREMEDY extensions, but in the future we could also clamp
* the GL extensions to core GL versions here.
*/
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <map>
#include "glproc.hpp"
#include "gltrace.hpp"
#include "os.hpp"
#include "config.hpp"
namespace gltrace {
typedef std::map<std::string, const char *> ExtensionsMap;
// Cache of the translated extensions strings
static ExtensionsMap extensionsMap;
// Additional extensions to be advertised
static const char *
extraExtension_stringsFull[] = {
"GL_GREMEDY_string_marker",
"GL_GREMEDY_frame_terminator",
"GL_ARB_debug_output",
"GL_AMD_debug_output",
"GL_KHR_debug",
"GL_EXT_debug_marker",
"GL_EXT_debug_label",
"GL_VMWX_map_buffer_debug",
};
static const char *
extraExtension_stringsES[] = {
"GL_KHR_debug",
"GL_EXT_debug_marker",
"GL_EXT_debug_label",
};
// Description of additional extensions we want to advertise
struct ExtensionsDesc
{
unsigned numStrings;
const char **strings;
};
#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
const struct ExtensionsDesc
extraExtensionsFull = {
ARRAY_SIZE(extraExtension_stringsFull),
extraExtension_stringsFull
};
const struct ExtensionsDesc
extraExtensionsES = {
ARRAY_SIZE(extraExtension_stringsES),
extraExtension_stringsES
};
const struct ExtensionsDesc *
getExtraExtensions(const Context *ctx)
{
switch (ctx->profile.api) {
case glfeatures::API_GL:
return &extraExtensionsFull;
case glfeatures::API_GLES:
return &extraExtensionsES;
default:
assert(0);
return &extraExtensionsFull;
}
}
/**
* Translate the GL extensions string, adding new extensions.
*/
static const char *
overrideExtensionsString(const char *extensions)
{
const Context *ctx = getContext();
const ExtensionsDesc *desc = getExtraExtensions(ctx);
size_t i;
ExtensionsMap::const_iterator it = extensionsMap.find(extensions);
if (it != extensionsMap.end()) {
return it->second;
}
size_t extensionsLen = strlen(extensions);
size_t extraExtensionsLen = 0;
for (i = 0; i < desc->numStrings; ++i) {
const char * extraExtension = desc->strings[i];
size_t extraExtensionLen = strlen(extraExtension);
extraExtensionsLen += extraExtensionLen + 1;
}
// We use malloc memory instead of a std::string because we need to ensure
// that extensions strings will not move in memory as the extensionsMap is
// updated.
size_t newExtensionsLen = extensionsLen + 1 + extraExtensionsLen + 1;
char *newExtensions = (char *)malloc(newExtensionsLen);
if (!newExtensions) {
return extensions;
}
if (extensionsLen) {
memcpy(newExtensions, extensions, extensionsLen);
// Add space separator if necessary
if (newExtensions[extensionsLen - 1] != ' ') {
newExtensions[extensionsLen++] = ' ';
}
}
for (i = 0; i < desc->numStrings; ++i) {
const char * extraExtension = desc->strings[i];
size_t extraExtensionLen = strlen(extraExtension);
memcpy(newExtensions + extensionsLen, extraExtension, extraExtensionLen);
extensionsLen += extraExtensionLen;
newExtensions[extensionsLen++] = ' ';
}
newExtensions[extensionsLen++] = '\0';
assert(extensionsLen <= newExtensionsLen);
extensionsMap[extensions] = newExtensions;
return newExtensions;
}
const GLubyte *
_glGetString_override(GLenum name)
{
const configuration *config = getConfig();
const GLubyte *result;
// Try getting the override string value first
result = getConfigString(config, name);
if (!result) {
// Ask the real GL library
result = _glGetString(name);
}
if (result) {
switch (name) {
case GL_EXTENSIONS:
result = (const GLubyte *)overrideExtensionsString((const char *)result);
break;
default:
break;
}
}
return result;
}
static void
getInteger(const configuration *config,
GLenum pname, GLint *params)
{
// Disable ARB_get_program_binary
switch (pname) {
case GL_NUM_PROGRAM_BINARY_FORMATS:
if (params) {
GLint numProgramBinaryFormats = 0;
_glGetIntegerv(pname, &numProgramBinaryFormats);
if (numProgramBinaryFormats > 0) {
os::log("apitrace: warning: hiding program binary formats (https://git.io/JOM0m)\n");
}
params[0] = 0;
}
return;
case GL_PROGRAM_BINARY_FORMATS:
// params might be NULL here, as we returned 0 for
// GL_NUM_PROGRAM_BINARY_FORMATS.
return;
}
if (params) {
*params = getConfigInteger(config, pname);
if (*params != 0) {
return;
}
}
// Ask the real GL library
_glGetIntegerv(pname, params);
}
/**
* TODO: To be thorough, we should override all glGet*v.
*/
void
_glGetIntegerv_override(GLenum pname, GLint *params)
{
const configuration *config = getConfig();
/*
* It's important to handle params==NULL correctly here, which can and does
* happen, particularly when pname is GL_COMPRESSED_TEXTURE_FORMATS or
* GL_PROGRAM_BINARY_FORMATS and the implementation returns 0 for
* GL_NUM_COMPRESSED_TEXTURE_FORMATS or GL_NUM_PROGRAM_BINARY_FORMATS, as
* the application ends up calling `params = malloc(0)` or `param = new
* GLint[0]` which can yield NULL.
*/
getInteger(config, pname, params);
if (params) {
const Context *ctx;
switch (pname) {
case GL_NUM_EXTENSIONS:
ctx = getContext();
if (ctx->profile.major >= 3) {
const ExtensionsDesc *desc = getExtraExtensions(ctx);
*params += desc->numStrings;
}
break;
case GL_MAX_LABEL_LENGTH:
/* We provide our default implementation of KHR_debug when the
* driver does not. So return something sensible here.
*/
if (params[0] == 0) {
params[0] = 256;
}
break;
case GL_MAX_DEBUG_MESSAGE_LENGTH:
if (params[0] == 0) {
params[0] = 4096;
}
break;
}
}
}
const GLubyte *
_glGetStringi_override(GLenum name, GLuint index)
{
const configuration *config = getConfig();
const Context *ctx = getContext();
const GLubyte *retVal;
if (ctx->profile.major >= 3) {
switch (name) {
case GL_EXTENSIONS:
{
const ExtensionsDesc *desc = getExtraExtensions(ctx);
GLint numExtensions = 0;
getInteger(config, GL_NUM_EXTENSIONS, &numExtensions);
if ((GLuint)numExtensions <= index && index < (GLuint)numExtensions + desc->numStrings) {
return (const GLubyte *)desc->strings[index - (GLuint)numExtensions];
}
}
break;
default:
break;
}
}
retVal = getConfigStringi(config, name, index);
if (retVal)
return retVal;
return _glGetStringi(name, index);
}
} /* namespace gltrace */
| 8,697 | 2,612 |
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
#define MAX 1000001
vector <int> numDiff(MAX, 0);
void numDif()
{
for (int i = 2; i < MAX ; ++i)
{
if (numDiff[i] == 0)
{
for (int j = i; j < MAX; j += i)
{
numDiff[j]++;
}
}
}
}
int main()
{
numDif();
int n;
while (cin >> n && n != 0)
{
cout << n << " : " << numDiff[n] << endl;
}
} | 503 | 201 |
// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.
#include <mbgl/shaders/source.hpp>
#include <mbgl/util/compression.hpp>
#include <cstdint>
namespace mbgl {
namespace shaders {
const char* source() {
static const uint8_t compressed[] = {
0x78, 0xda, 0xed, 0x7d, 0x6b, 0x73, 0x1b, 0x37,
0xb2, 0xe8, 0x7e, 0xf6, 0xaf, 0x40, 0x36, 0x55,
0xc7, 0xa4, 0xcc, 0xb7, 0x24, 0x5b, 0x96, 0x56,
0x27, 0xe5, 0x93, 0x38, 0x39, 0xbe, 0x37, 0x9b,
0xb8, 0x22, 0x67, 0xb3, 0x75, 0x5c, 0x5e, 0xd6,
0x0c, 0x39, 0x24, 0x67, 0x3d, 0x9c, 0x61, 0x66,
0x86, 0xa2, 0xe4, 0x73, 0xf3, 0xdf, 0x6f, 0x3f,
0xf0, 0x9c, 0x97, 0x28, 0x59, 0x92, 0x65, 0x87,
0x5b, 0xab, 0x58, 0x1a, 0x00, 0x8d, 0x06, 0xd0,
0x68, 0x74, 0x37, 0x1a, 0xdd, 0x5f, 0x87, 0xb3,
0x69, 0x30, 0x13, 0x3f, 0xfc, 0x38, 0x7e, 0x79,
0xf6, 0x68, 0x95, 0x06, 0x93, 0x30, 0x0b, 0x93,
0x58, 0x2c, 0xc2, 0xf9, 0x62, 0x25, 0x66, 0x51,
0xe2, 0xe5, 0x27, 0x8f, 0xbe, 0x0e, 0xa2, 0x2c,
0x78, 0xf4, 0xe8, 0xeb, 0x70, 0x26, 0xbe, 0x82,
0xca, 0x61, 0x1c, 0x4c, 0x5b, 0x51, 0xb2, 0x59,
0xb5, 0x1f, 0x7d, 0xcd, 0x7f, 0x0a, 0xfc, 0x0b,
0xaa, 0xc5, 0xd3, 0x70, 0x56, 0xa8, 0xb7, 0x0c,
0xa6, 0xe1, 0x7a, 0x69, 0x55, 0x95, 0x1f, 0xaa,
0x6b, 0x53, 0xb7, 0xa6, 0x2e, 0xfd, 0x69, 0x6a,
0xca, 0x7f, 0xfb, 0x7d, 0xf1, 0x6b, 0xbc, 0xf2,
0x26, 0xef, 0x85, 0x27, 0x56, 0x5e, 0x98, 0x8a,
0x64, 0x26, 0xce, 0xbd, 0x68, 0x1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 0xcc,
0x8c, 0xc9, 0x3a, 0x45, 0xef, 0xb1, 0x6b, 0x4b,
0xc8, 0xca, 0xde, 0x6c, 0x3c, 0xd4, 0x6d, 0x8a,
0x29, 0xca, 0x26, 0xfc, 0x12, 0xea, 0xd4, 0x66,
0xc7, 0x7d, 0xd1, 0x32, 0x9d, 0xee, 0xb9, 0xbb,
0x42, 0x1e, 0x0c, 0xf6, 0xd3, 0xc7, 0xf5, 0x6c,
0x86, 0x9e, 0xd8, 0xa3, 0xc3, 0xa7, 0xf4, 0x60,
0x9f, 0xe3, 0x8a, 0x00, 0x62, 0xf8, 0xb7, 0x2d,
0x8c, 0x4b, 0xe6, 0x5d, 0xf2, 0xba, 0x87, 0xc6,
0x36, 0xed, 0xa9, 0x32, 0x85, 0x58, 0xcb, 0x2c,
0xd6, 0x1e, 0x1c, 0xf4, 0xc3, 0xe7, 0x00, 0x5b,
0x1e, 0x27, 0x4f, 0x2c, 0xac, 0xdb, 0xdb, 0xa0,
0x4d, 0x51, 0x8c, 0x24, 0xbe, 0x8c, 0xad, 0x45,
0x5f, 0x7d, 0x4b, 0xae, 0xd0, 0x7d, 0x38, 0x52,
0xa1, 0x35, 0x6a, 0xf9, 0x56, 0xad, 0xf2, 0xa2,
0x19, 0xaf, 0x99, 0xd5, 0x7b, 0x81, 0xd2, 0x54,
0x33, 0x3e, 0x53, 0x0a, 0xa5, 0x81, 0x03, 0xdc,
0x13, 0xa5, 0xb7, 0x7d, 0x8e, 0xe8, 0x28, 0xaf,
0xbf, 0xad, 0x57, 0x6e, 0x34, 0x80, 0xae, 0x03,
0xad, 0xc3, 0xa3, 0x7a, 0x52, 0xf8, 0x78, 0x83,
0xe7, 0x6c, 0x28, 0x5d, 0xb9, 0xa7, 0xf8, 0x2d,
0x5c, 0x93, 0xff, 0x7f, 0xc9, 0x73, 0xe5, 0xd5
};
static std::string decompressed = util::decompress(std::string(reinterpret_cast<const char*>(compressed), sizeof(compressed)));
return decompressed.c_str();
};
} // namespace shaders
} // namespace mbgl
| 81,624 | 67,706 |
#include "headers/map.h"
#include "headers/json.hpp"
using json = nlohmann::json;
void Map::loadMap(const std::string& path)
{
tiles.clear();
collidable_tiles.clear();
sprite_sheet.Load("./sprites/tilesheet.png");
std::ifstream i(path);
json j = json::parse(i);
map_size.y = j.at("tileshigh");
map_size.x = j.at("tileswide");
olc::vi2d tile_size = { j.at("tilewidth"), j.at("tileheight") };
olc::Sprite temp_sprite = olc::Sprite("./sprites/tilesheet.png");
int tile_sheet_width = sprite_sheet.Sprite()->width / tile_size.x;
auto layers = j.at("layers");
srand(time);
int random_key = rand() % 7 + 1;
int key_id = 1;
// Loop all the layers that we grab from the json file
for (const auto& layer : layers)
{
// Loop each tile in the layer
for (const auto& tile : layer.at("tiles"))
{
// This is the tile ID (position in the tilesheet / spritesheet) determined by Pyxel
int tile_id = tile.at("tile");
// If tileID is -1 that means the tile has no tile aka is transparent
if (tile_id != -1)
{
std::string layer_name = layer.at("name");
int x = tile.at("x");
int y = tile.at("y");
x *= tile_size.x;
y *= tile_size.y;
int tile_sheet_pos_y = 0;
int tile_sheet_pos_x = 0;
// This is an easy way to know what Row in the tilesheet we want to grab the tile from
if (tile_id > tile_sheet_width)
{
int i = tile_id;
while (i > tile_sheet_width)
{
tile_sheet_pos_y += 1;
i -= tile_sheet_width;
}
tile_sheet_pos_x = i - 1;
}
else
{
tile_sheet_pos_x = tile_id - 1;
}
// Make sure we grab just 1 tile / sprite
tile_sheet_pos_y *= tile_size.y;
tile_sheet_pos_x *= tile_size.x;
// Here we store all tile values into a vector of tiles and determine the height of each collidable block
// The data we store is basically the position on the map where it's drawn
// and also the position on the tileSheet where it's stored
if (layer_name != "collectables" && layer_name != "next_level")
{
int tile_height = 0;
for (int i = tile_sheet_pos_y + 1; i < tile_sheet_pos_y + tile_size.y; i++) {
olc::Pixel pixel = temp_sprite.GetPixel(tile_sheet_pos_x - (tile_sheet_pos_x / tile_size.y) + (tile_size.x / 2), i);
if (std::abs(tile_sheet_pos_y - i) >= tile_size.y - 1)
{
tile_height = tile_size.y;
break;
}
if (pixel.a == 0) {
tile_height = std::abs(tile_sheet_pos_y - i);
break;
}
}
tiles.push_back(new Map::tile{ { x - TILE_SIZE, y }, { tile_sheet_pos_x, tile_sheet_pos_y }, { TILE_SIZE, tile_height }, false });
}
else
tiles.push_back(new Map::tile{ { x - TILE_SIZE, y }, { tile_sheet_pos_x, tile_sheet_pos_y }, { TILE_SIZE, TILE_SIZE }, false });
// If the layer_name is related to anything collidable we shall add it to collidable tiles
if (layer_name == "colliders")
collidable_tiles.push_back(std::make_pair("map_terrain", tiles.back()));
if (layer_name == "obstacles")
collidable_tiles.push_back(std::make_pair("map_terrain", tiles.back()));
if(layer_name == "next_level")
collidable_tiles.push_back(std::make_pair("next_level", tiles.back()));
if (layer_name == "collectables")
{
if (key_id == random_key)
collidable_tiles.push_back(std::make_pair("correct_key", tiles.back()));
else
collidable_tiles.push_back(std::make_pair("collectable", tiles.back()));
key_id++;
}
}
}
}
}
void Map::render()
{
m_pge->Clear({ 62, 190, 237 });
for (const auto* tile : tiles)
{
if (tile->destroyed)
continue;
m_pge->DrawPartialDecal(tile->position, sprite_sheet.Decal(), tile->tile_sheet_pos, { TILE_SIZE, TILE_SIZE });
}
} | 4,807 | 1,479 |
/**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "csp_solver_tou_block_schedules.h"
#include "csp_solver_util.h"
#include <algorithm>
void C_block_schedule::check_dimensions()
{
// Check that each schedule is a 12x24 matrix
// If not, throw exception
if (mc_weekdays.nrows() != mc_weekends.nrows()
|| mc_weekdays.nrows() != 12
|| mc_weekdays.ncols() != mc_weekends.ncols()
|| mc_weekdays.ncols() != 24 )
{
m_error_msg = "TOU schedules must have 12 rows and 24 columns";
throw C_csp_exception( m_error_msg, "TOU block schedule init" );
}
/*
if( mc_weekdays.nrows() != mstatic_n_rows )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekday schedule has %d rows.", (int)mc_weekdays.nrows());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekdays.ncols() != mstatic_n_cols )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekday schedule has %d columns.", (int)mc_weekdays.ncols());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekends.nrows() != mstatic_n_rows )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekend schedule has %d rows.",(int) mc_weekends.nrows());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
if( mc_weekends.ncols() != mstatic_n_cols )
{
m_error_msg = util::format("TOU schedules require 12 rows and 24 columns. The loaded weekend schedule has %d columns.", (int)mc_weekends.ncols());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
*/
return;
}
void C_block_schedule::size_vv(int n_arrays)
{
mvv_tou_arrays.resize(n_arrays, std::vector<double>(0, std::numeric_limits<double>::quiet_NaN()));
}
void C_block_schedule::check_arrays_for_tous(int n_arrays)
{
// Check that all TOU periods represented in the schedules are available in the tou arrays
int i_tou_min = 1;
int i_tou_max = 1;
int i_tou_day = -1;
int i_tou_end = -1;
int i_temp_max = -1;
int i_temp_min = -1;
for( int i = 0; i < 12; i++ )
{
for( int j = 0; j < 24; j++ )
{
i_tou_day = (int) mc_weekdays(i, j) - 1;
i_tou_end = (int) mc_weekends(i, j) - 1;
i_temp_max = std::max(i_tou_day, i_tou_end);
i_temp_min = std::min(i_tou_day, i_tou_end);
if( i_temp_max > i_tou_max )
i_tou_max = i_temp_max;
if( i_temp_min < i_tou_min )
i_tou_min = i_temp_min;
}
}
if( i_tou_min < 0 )
{
throw(C_csp_exception("Smallest TOU period cannot be less than 1", "TOU block schedule initialization"));
}
for( int k = 0; k < n_arrays; k++ )
{
if( i_tou_max + 1 > (int)mvv_tou_arrays[k].size() )
{
m_error_msg = util::format("TOU schedule contains TOU period = %d, while the %s array contains %d elements", (int)i_temp_max, mv_labels[k].c_str(), mvv_tou_arrays[k].size());
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
}
void C_block_schedule::set_hr_tou(bool is_leapyear)
{
/*
This method sets the TOU schedule month by hour for an entire year, so only makes sense in the context of an annual simulation.
*/
if( m_hr_tou != 0 )
delete [] m_hr_tou;
int nhrann = 8760+(is_leapyear?24:0);
m_hr_tou = new double[nhrann];
int nday[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if( is_leapyear )
nday[1] ++;
int wday = 5, i = 0;
for( int m = 0; m<12; m++ )
{
for( int d = 0; d<nday[m]; d++ )
{
bool bWeekend = (wday <= 0);
if( wday >= 0 ) wday--;
else wday = 5;
for( int h = 0; h<24 && i<nhrann && m * 24 + h<288; h++ )
{
if( bWeekend )
m_hr_tou[i] = mc_weekends(m, h); // weekends[m * 24 + h];
else
m_hr_tou[i] = mc_weekdays(m, h); // weekdays[m * 24 + h];
i++;
}
}
}
}
void C_block_schedule::init(int n_arrays, bool is_leapyear)
{
check_dimensions();
check_arrays_for_tous(n_arrays);
set_hr_tou(is_leapyear);
}
C_block_schedule_csp_ops::C_block_schedule_csp_ops()
{
// Initializie temporary output 2D vector
size_vv(N_END);
mv_labels.resize(N_END);
mv_labels[0] = "Turbine Fraction";
mv_is_diurnal = true;
}
C_block_schedule_pricing::C_block_schedule_pricing()
{
// Initializie temporary output 2D vector
size_vv(N_END);
mv_labels.resize(N_END);
mv_labels[0] = "Price Multiplier";
mv_is_diurnal = true;
}
void C_csp_tou_block_schedules::init()
{
try
{
ms_params.mc_csp_ops.init(C_block_schedule_csp_ops::N_END, mc_dispatch_params.m_isleapyear);
}
catch( C_csp_exception &csp_exception )
{
m_error_msg = "The CSP ops " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
// time step initialization of actual price multipliers done in calling compute modules.
// mv_is_diurnal is set to true in constructor
if (ms_params.mc_pricing.mv_is_diurnal)
{
try
{
ms_params.mc_pricing.init(C_block_schedule_pricing::N_END, mc_dispatch_params.m_isleapyear);
}
catch (C_csp_exception &csp_exception)
{
m_error_msg = "The CSP pricing " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
if (ms_params.mc_csp_ops.mv_is_diurnal)
{
try
{
ms_params.mc_csp_ops.init(C_block_schedule_csp_ops::N_END, mc_dispatch_params.m_isleapyear);
}
catch (C_csp_exception& csp_exception)
{
m_error_msg = "The CSP ops " + csp_exception.m_error_message;
throw(C_csp_exception(m_error_msg, "TOU block schedule initialization"));
}
}
return;
}
// TODO: move this into dispatch some how
void C_csp_tou_block_schedules::call(double time_s, C_csp_tou::S_csp_tou_outputs & tou_outputs)
{
int i_hour = (int)(ceil(time_s/3600.0 - 1.e-6) - 1);
if( i_hour > 8760 - 1 + (mc_dispatch_params.m_isleapyear ? 24 : 0) || i_hour<0 )
{
m_error_msg = util::format("The hour input to the TOU schedule must be from 1 to 8760. The input hour was %d.", i_hour+1);
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
size_t csp_op_tou = (size_t)ms_params.mc_csp_ops.m_hr_tou[i_hour]; // an 8760-size array of the 1-9 turbine output fraction for the timestep
tou_outputs.m_csp_op_tou = (int)csp_op_tou; // needed for hybrid cooling regardless of turbine output fraction schedule type
if (ms_params.mc_csp_ops.mv_is_diurnal) {
tou_outputs.m_f_turbine = ms_params.mc_csp_ops.mvv_tou_arrays[C_block_schedule_csp_ops::TURB_FRAC][csp_op_tou-1]; // an array of size 9 of the different turbine output fractions
}
else {
tou_outputs.m_f_turbine = ms_params.mc_csp_ops.timestep_load_fractions.at(i_hour);
}
if (ms_params.mc_pricing.mv_is_diurnal)
{
int pricing_tou = (int)ms_params.mc_pricing.m_hr_tou[i_hour];
tou_outputs.m_pricing_tou = pricing_tou;
tou_outputs.m_price_mult = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][pricing_tou - 1];
}
else // note limited to hour but can be extended to timestep using size
{
// these can be set in initialize and we may want to include time series inputs for other multipliers and fractions
size_t nrecs = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE].size();
if (nrecs <= 0)
{
m_error_msg = util::format("The timestep price multiplier array was empty.");
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
size_t nrecs_per_hour = nrecs / 8760;
int ndx = (int)((ceil(time_s / 3600.0 - 1.e-6) - 1) * nrecs_per_hour);
if (ndx > (int)nrecs - 1 + (mc_dispatch_params.m_isleapyear ? 24 : 0) || ndx<0)
{
m_error_msg = util::format("The index input to the TOU schedule must be from 1 to %d. The input timestep index was %d.", (int)nrecs, ndx + 1);
throw(C_csp_exception(m_error_msg, "TOU timestep call"));
}
tou_outputs.m_price_mult = ms_params.mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][ndx];
}
}
void C_csp_tou_block_schedules::setup_block_uniform_tod()
{
int nrows = ms_params.mc_csp_ops.mstatic_n_rows;
int ncols = ms_params.mc_csp_ops.mstatic_n_cols;
for( int i = 0; i < ms_params.mc_csp_ops.N_END; i++ )
ms_params.mc_csp_ops.mvv_tou_arrays[i].resize(2, 1.0);
for( int i = 0; i < ms_params.mc_pricing.N_END; i++ )
ms_params.mc_pricing.mvv_tou_arrays[i].resize(2, 1.0);
ms_params.mc_csp_ops.mc_weekdays.resize_fill(nrows, ncols, 1.0);
ms_params.mc_csp_ops.mc_weekends.resize_fill(nrows, ncols, 1.0);
ms_params.mc_pricing.mc_weekdays.resize_fill(nrows, ncols, 1.0);
ms_params.mc_pricing.mc_weekends.resize_fill(nrows, ncols, 1.0);
}
| 10,282 | 4,496 |
#ifndef __TURBO_ENGINE_DEBUGIMGUI_HPP__
#define __TURBO_ENGINE_DEBUGIMGUI_HPP__
#ifdef __TURBO_USE_IMGUI__
#include <imgui/imgui.h>
#include <imgui/imgui_impl_allegro5.h>
#include "debug_menus/EngineDebug.hpp"
#include "debug_menus/SceneManagerDebug.hpp"
#define ONLYIMGUI(expr) expr;
#else
#define ONLYIMGUI(expr)
#endif
#endif
| 360 | 165 |
#include "y.tab.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "tree.h"
using namespace std;
extern FILE* yyin;
extern FILE* yyout;
typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern YY_BUFFER_STATE yy_scan_string(const char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);
extern void yy_switch_to_buffer(YY_BUFFER_STATE buffer);
TreeNode* root;
TreeNode* curr;
void deleteTree(TreeNode* root)
{
for (int i = 0; i < root->children.size(); i++)
if (root->children[i] != NULL)
deleteTree(root->children[i]);
delete root;
}
void deleteChain(TreeNode* root)
{
TreeNode* tmp;
while(root != NULL)
{
tmp = root->next;
delete root;
root = tmp;
}
}
extern "C"
{
char* getStructuredParsingTree(char* input)
{
YY_BUFFER_STATE buffer = yy_scan_string(input);
yy_switch_to_buffer(buffer);
root = new TreeNode(Non, "<translation_unit>", NULL);
curr = root;
if (yyparse() == 0)
{
yy_delete_buffer(buffer);
char* ret = strdup((root->structuredTree("")).c_str());
deleteTree(root);
return ret;
}
else
{
yy_delete_buffer(buffer);
deleteChain(curr);
return strdup("");
}
}
}
extern "C"
{
void freeCharPtr(char* str)
{
if (str != NULL)
free(str);
}
}
extern "C"
{
void printParsingTree(char* input)
{
YY_BUFFER_STATE buffer = yy_scan_string(input);
yy_switch_to_buffer(buffer);
root = new TreeNode(Non, "<translation_unit>", NULL);
curr = root;
if (yyparse() == 0)
{
root->printTree(0, yyout);
deleteTree(root);
}
else
{
fprintf(stderr, "Syntax Error!\n");
deleteChain(curr);
}
yy_delete_buffer(buffer);
return;
}
} | 1,973 | 674 |
//三角形的面积
#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
double x1, y1, x2, y2, x3, y3, s, a, b, c, A;
while (scanf("%lf%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &x3, &y3))
{
if (x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0 && x3 == 0 && y3 == 0)
{
break;
}
a = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
b = sqrt(pow(x3 - x2, 2) + pow(y3 - y2, 2));
c = sqrt(pow(x3 - x1, 2) + pow(y3 - y1, 2));
s = (a + b + c) / 2;
A = sqrt(s * (s - a) * (s - b) * (s - c));
printf("%.6lf\n", A);
}
return 0;
} | 630 | 330 |
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// AVL tree node
struct AVLwithparent {
struct AVLwithparent* left;
struct AVLwithparent* right;
int key;
struct AVLwithparent* par;
int height;
};
// Function to update the height of
// a node according to its children's
// node's heights
void Updateheight(
struct AVLwithparent* root)
{
if (root != NULL) {
// Store the height of the
// current node
int val = 1;
// Store the height of the left
// and right substree
if (root->left != NULL)
val = root->left->height + 1;
if (root->right != NULL)
val = max(
val, root->right->height + 1);
// Update the height of the
// current node
root->height = val;
}
}
// Function to handle Left Left Case
struct AVLwithparent* LLR(
struct AVLwithparent* root)
{
// Create a reference to the
// left child
struct AVLwithparent* tmpnode = root->left;
// Update the left child of the
// root to the right child of the
// current left child of the root
root->left = tmpnode->right;
// Update parent pointer of the
// left child of the root node
if (tmpnode->right != NULL)
tmpnode->right->par = root;
// Update the right child of
// tmpnode to root
tmpnode->right = root;
// Update parent pointer of
// the tmpnode
tmpnode->par = root->par;
// Update the parent pointer
// of the root
root->par = tmpnode;
// Update tmpnode as the left or the
// right child of its parent pointer
// according to its key value
if (tmpnode->par != NULL
&& root->key < tmpnode->par->key) {
tmpnode->par->left = tmpnode;
}
else {
if (tmpnode->par != NULL)
tmpnode->par->right = tmpnode;
}
// Make tmpnode as the new root
root = tmpnode;
// Update the heights
Updateheight(root->left);
Updateheight(root->right);
Updateheight(root);
Updateheight(root->par);
// Return the root node
return root;
}
// Function to handle Right Right Case
struct AVLwithparent* RRR(
struct AVLwithparent* root)
{
// Create a reference to the
// right child
struct AVLwithparent* tmpnode = root->right;
// Update the right child of the
// root as the left child of the
// current right child of the root
root->right = tmpnode->left;
// Update parent pointer of the
// right child of the root node
if (tmpnode->left != NULL)
tmpnode->left->par = root;
// Update the left child of the
// tmpnode to root
tmpnode->left = root;
// Update parent pointer of
// the tmpnode
tmpnode->par = root->par;
// Update the parent pointer
// of the root
root->par = tmpnode;
// Update tmpnode as the left or
// the right child of its parent
// pointer according to its key value
if (tmpnode->par != NULL
&& root->key < tmpnode->par->key) {
tmpnode->par->left = tmpnode;
}
else {
if (tmpnode->par != NULL)
tmpnode->par->right = tmpnode;
}
// Make tmpnode as the new root
root = tmpnode;
// Update the heights
Updateheight(root->left);
Updateheight(root->right);
Updateheight(root);
Updateheight(root->par);
// Return the root node
return root;
}
// Function to handle Left Right Case
struct AVLwithparent* LRR(
struct AVLwithparent* root)
{
root->left = RRR(root->left);
return LLR(root);
}
// Function to handle right left case
struct AVLwithparent* RLR(
struct AVLwithparent* root)
{
root->right = LLR(root->right);
return RRR(root);
}
// Function to insert a node in
// the AVL tree
struct AVLwithparent* Insert(
struct AVLwithparent* root,
struct AVLwithparent* parent,
int key)
{
if (root == NULL) {
// Create and assign values
// to a new node
root = new struct AVLwithparent;
// If the root is NULL
if (root == NULL) {
cout << "Error in memory"
<< endl;
}
// Otherwise
else {
root->height = 1;
root->left = NULL;
root->right = NULL;
root->par = parent;
root->key = key;
}
}
else if (root->key > key) {
// Recur to the left subtree
// to insert the node
root->left = Insert(root->left,
root, key);
// Store the heights of the
// left and right subtree
int firstheight = 0;
int secondheight = 0;
if (root->left != NULL)
firstheight = root->left->height;
if (root->right != NULL)
secondheight = root->right->height;
// Balance the tree if the
// current node is not balanced
if (abs(firstheight
- secondheight)
== 2) {
if (root->left != NULL
&& key < root->left->key) {
// Left Left Case
root = LLR(root);
}
else {
// Left Right Case
root = LRR(root);
}
}
}
else if (root->key < key) {
// Recur to the right subtree
// to insert the node
root->right = Insert(root->right,
root, key);
// Store the heights of the
// left and right subtree
int firstheight = 0;
int secondheight = 0;
if (root->left != NULL)
firstheight
= root->left->height;
if (root->right != NULL)
secondheight = root->right->height;
// Balance the tree if the
// current node is not balanced
if (abs(firstheight - secondheight) == 2) {
if (root->right != NULL
&& key < root->right->key) {
// Right Left Case
root = RLR(root);
}
else {
// Right Right Case
root = RRR(root);
}
}
}
// Case when given key is already
// in the tree
else {
}
// Update the height of the
// root node
Updateheight(root);
// Return the root node
return root;
}
// Function to print the preorder
// traversal of the AVL tree
void printpreorder(
struct AVLwithparent* root)
{
// Print the node's value along
// with its parent value
cout << "Node: " << root->key
<< ", Parent Node: ";
if (root->par != NULL)
cout << root->par->key << endl;
else
cout << "NULL" << endl;
// Recur to the left subtree
if (root->left != NULL) {
printpreorder(root->left);
}
// Recur to the right subtree
if (root->right != NULL) {
printpreorder(root->right);
}
}
// Driver Code
int main()
{
struct AVLwithparent* root;
root = NULL;
// Function Call to insert nodes
root = Insert(root, NULL, 10);
root = Insert(root, NULL, 20);
root = Insert(root, NULL, 30);
root = Insert(root, NULL, 40);
root = Insert(root, NULL, 50);
root = Insert(root, NULL, 25);
// Function call to print the tree
printpreorder(root);
} | 7,383 | 2,175 |
// Copyright 2021 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 "content/browser/compute_pressure/cpuid_base_frequency_parser.h"
#include <stdint.h>
#include <limits>
#include "base/check_op.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece_forward.h"
#include "third_party/re2/src/re2/re2.h"
#include "third_party/re2/src/re2/stringpiece.h"
namespace content {
int64_t ParseBaseFrequencyFromCpuid(base::StringPiece brand_string) {
// A perfectly accurate number pattern would be quite a bit more complex, as
// we want to capture both integers (1133Mhz) and decimal fractions (1.20Ghz).
// The current pattern is preferred as base::StringToDouble() can catch the
// false positives.
//
// The unit pattern matches the strings "MHz" and "GHz" case-insensitively.
re2::RE2 frequency_re("([0-9.]+)\\s*([GgMm][Hh][Zz])");
// As matches are consumed, `input` will be mutated to reflect the
// non-consumed string.
re2::StringPiece input(brand_string.data(), brand_string.size());
re2::StringPiece number_string; // The frequency number.
re2::StringPiece unit; // MHz or GHz (case-insensitive)
while (
re2::RE2::FindAndConsume(&input, frequency_re, &number_string, &unit)) {
DCHECK_GT(number_string.size(), 0u)
<< "The number pattern should only match non-empty strings";
DCHECK_EQ(unit.size(), 3u)
<< "The unit pattern should match exactly 3 characters";
double number;
if (!base::StringToDouble(
base::StringPiece(number_string.data(), number_string.size()),
&number)) {
continue;
}
DCHECK_GE(number, 0);
double unit_multiplier =
(unit[0] == 'G' || unit[0] == 'g') ? 1'000'000'000 : 1'000'000;
double frequency = number * unit_multiplier;
// Avoid conversion overflows. double can (imprecisely) store larger numbers
// than int64_t.
if (!base::IsValueInRangeForNumericType<int64_t>(frequency))
continue;
int64_t frequency_int = static_cast<int64_t>(frequency);
// It's unlikely that Chrome can run on CPUs with clock speeds below 100MHz.
// This cutoff can catch some bad parses.
static constexpr int64_t kMinimumFrequency = 100'000'000;
if (frequency_int < kMinimumFrequency)
continue;
return frequency_int;
}
return -1;
}
} // namespace content
| 2,538 | 891 |
#include "../../../platform_graphics.hpp"
#include "../../gl_headers.hpp"
#include "core/util.h"
void initGraphics() {
// glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
// glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
// glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
}
void initGraphicsExtensions() {
// start GLEW extension handler
// glewExperimental = GL_TRUE;
//
if ( glewInit() != GLEW_OK ) {
LOGE( "Failed to initialize GLEW" );
}
} | 520 | 217 |
#include <rendercore-examples/GltfExampleRenderer.h>
#include <cppassist/memory/make_unique.h>
#include <glbinding/gl/gl.h>
#include <rendercore/rendercore.h>
#include <rendercore-gltf/GltfConverter.h>
#include <rendercore-gltf/GltfLoader.h>
#include <rendercore-gltf/Asset.h>
using namespace rendercore::opengl;
using namespace rendercore::gltf;
namespace rendercore
{
namespace examples
{
GltfExampleRenderer::GltfExampleRenderer(GpuContainer * container)
: Renderer(container)
, m_counter(0)
, m_angle(0.0f)
{
// Initialize object transformation
m_transform.setTranslation({ 0.0f, 0.0f, 0.0f });
m_transform.setScale ({ 1.0f, 1.0f, 1.0f });
m_transform.setRotation (glm::angleAxis(0.0f, glm::vec3(0.0f, 1.0f, 0.0f)));
// Create camera
m_camera = cppassist::make_unique<Camera>();
// Load GLTF asset
GltfLoader loader;
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/BoxAnimated/BoxAnimated.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/TextureCoordinateTest/TextureCoordinateTest.gltf");
auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/BoomBox/BoomBox.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/PbrTest/PbrTest.gltf");
// auto asset = loader.load(rendercore::dataPath() + "/rendercore/gltf/Taxi/Taxi.gltf");
// Transfer data from GLTF
GltfConverter converter;
converter.convert(*asset.get());
auto & textures = converter.textures();
for (auto & texture : textures) {
texture->setContainer(this);
m_textures.push_back(std::move(texture));
}
auto & materials = converter.materials();
for (auto & material : materials) {
material->setContainer(this);
m_materials.push_back(std::move(material));
}
auto & meshes = converter.meshes();
for (auto & mesh : meshes) {
mesh->setContainer(this);
m_meshes.push_back(std::move(mesh));
}
auto & scenes = converter.scenes();
for (auto & scene : scenes) {
m_scenes.push_back(std::move(scene));
}
// Create mesh renderer
m_sceneRenderer = cppassist::make_unique<SceneRenderer>(this);
}
GltfExampleRenderer::~GltfExampleRenderer()
{
}
void GltfExampleRenderer::onUpdate()
{
// Advance counter
m_counter++;
// Rotate model
m_angle += m_timeDelta * 1.0f;
m_transform.setRotation(glm::angleAxis(m_angle, glm::vec3(0.0f, 1.0f, 0.0f)));
// Animation has been updated, redraw the scene (will also issue another update)
scheduleRedraw();
}
void GltfExampleRenderer::onRender()
{
// Update viewport
gl::glViewport(m_viewport.x, m_viewport.y, m_viewport.z, m_viewport.w);
// Clear screen
gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);
// Update camera
m_camera->lookAt(glm::vec3(0.0f, 0.0, 9.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
m_camera->perspective(glm::radians(40.0f), glm::ivec2(m_viewport.z, m_viewport.w), 0.1f, 64.0f);
// Render scenes
for (auto & scene : m_scenes) {
m_sceneRenderer->render(*scene.get(), m_transform.transform(), m_camera.get());
}
}
} // namespace examples
} // namespace rendercore
| 3,279 | 1,230 |
#include <Arduino.h>
#include <BlynkSimpleSerialBLE.h>
#include "LOT_adc.h"
#include "LOT_ntc103f397.h"
#define SYSTEM_STATE_VIRTUAL_PIN V0
#define FORCED_FAN_ON_OFF_VIRTUAL_PIN V1
#define NTC103F397_VIRTUAL_PIN V2
#define THRESHOLD_TEMPERATURE_VIRTUAL_PIN V3
#define MOTION_STATE_VIRTUAL_PIN V4
#define MAX_PUSH_TIME_MS 500
#define PARALLEL_RESISTOR 9.85f
#define THRESHOLD_TEMPERATURE_SAFETY_ZONE 0.3f
// AT+BAUD6
// AT+NAMEevaporative
// AT+PIN0000
#define HC_O6_BAUDRATE 38400
char auth[] = "3993b1f88d9e4607b04007cd3ebe8876";
BlynkTimer timer;
volatile uint32_t pushtime = 0;
volatile uint8_t system_state = 0;
uint8_t forced_fan_on_off = 0;
float temperature;
float threshold_temperature = 25.0f;
volatile uint8_t motion_state = 0;
volatile uint32_t motion_capture_time = 0;
void fast_timer( void );
void slow_timer( void );
// app -> nano
BLYNK_WRITE( SYSTEM_STATE_VIRTUAL_PIN )
{
system_state = param.asInt();
}
BLYNK_WRITE( FORCED_FAN_ON_OFF_VIRTUAL_PIN )
{
forced_fan_on_off = param.asInt();
}
BLYNK_WRITE( THRESHOLD_TEMPERATURE_VIRTUAL_PIN )
{
threshold_temperature = param.asFloat();
}
void setup()
{
Serial.begin( HC_O6_BAUDRATE );
Blynk.config( Serial, auth );
// Blynk.begin(Serial, auth);
DDRB |= _BV( DDB5 );
MCUCR &= ~_BV( PUD ); // PULL-UP activate
DDRD &= ~_BV( DDD2 ); // INPUT
PORTD |= _BV( PD2 ); // PULL-UP
EIMSK |= _BV( INT0 ); // interrupt enable
EICRA |= _BV( ISC00 ); // any logical change
LOT_adc_setup();
DDRD &= ~_BV( DDD3 ); // INPUT
PORTD |= _BV( PD3 ); // PULL-UP
EIMSK |= _BV( INT1 ); // interrupt enable
EICRA |= _BV( ISC10 ); // any logical change
DDRD |= _BV( DDD5 ) | _BV( DDD4 ); // OUTPUT
timer.setInterval( 450, fast_timer );
timer.setInterval( 2050, slow_timer );
}
void loop()
{
Blynk.run();
timer.run();
if ( system_state )
{
PORTD |= _BV( PD4 );
if ( forced_fan_on_off )
{
PORTD |= _BV( PD5 );
}
else
{
if ( motion_state && ( temperature > threshold_temperature ) )
{
PORTD |= _BV( PD5 );
}
else if ( ( motion_state && ( temperature < threshold_temperature - THRESHOLD_TEMPERATURE_SAFETY_ZONE ) )
|| ( !motion_state ) )
{
PORTD &= ~_BV( PD5 );
}
}
}
else
{
PORTD &= ~( _BV( PD5 ) | _BV( PD4 ) );
}
float thermistor_R = LOT_adc_read( 0 );
thermistor_R = ( PARALLEL_RESISTOR * thermistor_R ) / ( 1024.0 - thermistor_R );
temperature = LOT_ntc_temperature( thermistor_R );
}
void fast_timer( void )
{
Blynk.virtualWrite( SYSTEM_STATE_VIRTUAL_PIN, system_state );
Blynk.virtualWrite( FORCED_FAN_ON_OFF_VIRTUAL_PIN, forced_fan_on_off );
Blynk.virtualWrite( NTC103F397_VIRTUAL_PIN, temperature );
Blynk.virtualWrite( MOTION_STATE_VIRTUAL_PIN, motion_state );
}
void slow_timer( void )
{
Blynk.virtualWrite( THRESHOLD_TEMPERATURE_VIRTUAL_PIN, threshold_temperature );
}
ISR( INT0_vect )
{
if ( PIND & _BV( PIND2 ) )
{
pushtime = millis();
}
else
{
if ( millis() - pushtime > MAX_PUSH_TIME_MS )
{
system_state ^= 1;
}
}
}
ISR( INT1_vect )
{
if ( PIND & _BV( PIND3 ) )
{
motion_state = 1;
}
else
{
motion_state = 0;
}
} | 3,536 | 1,562 |
#include "stdafx.h"
#include "Latitude.h"
namespace GPS
{
Latitude::Latitude(const Cardinal cardinal, const degree_type degree, const minute_type minute, const second_type second)
: Angle(degree,minute,second),cardinal_(cardinal)
{
}
double Latitude::get_degree() const
{
auto angle = Angle::get_degree();
if (cardinal_ == Cardinal::S)
{
angle = -angle;
}
return angle;
}
} | 402 | 162 |
/*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Rlaed4.cpp,v 1.7 2010/08/07 04:48:32 nakatamaho Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
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 listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <mblas.h>
#include <mlapack.h>
#define MTRUE 0
#define MFALSE 1
void Rlaed4(INTEGER n, INTEGER i, REAL * d, REAL * z, REAL * delta, REAL rho, REAL * dlam, INTEGER * info)
{
REAL a, b, c;
INTEGER j;
REAL w;
INTEGER ii;
REAL dw, zz[3];
INTEGER ip1;
REAL del, eta, phi, eps, tau, psi;
INTEGER iim1, iip1;
REAL dphi, dpsi;
INTEGER iter;
REAL temp, prew, temp1, dltlb, dltub, midpt;
INTEGER niter;
INTEGER swtch, swtch3;
INTEGER orgati;
REAL erretm, rhoinv;
REAL Two = 2.0, Three = 3.0, Four = 4.0, One = 1.0, Zero = 0.0, Eight = 8.0, Ten = 10.0;
//Since this routine is called in an inner loop, we do no argument
//checking.
//Quick return for N=1 and 2
*info = 0;
if (n == 1) {
//Presumably, I=1 upon entry
*dlam = d[1] + rho * z[1] * z[1];
delta[1] = One;
return;
}
if (n == 2) {
Rlaed5(i, &d[0], &z[1], &delta[1], rho, dlam);
return;
}
//Compute machine epsilon
eps = Rlamch("Epsilon");
rhoinv = One / rho;
//The case I = N
if (i == n) {
//Initialize some basic variables
ii = n - 1;
niter = 1;
//Calculate initial guess
midpt = rho / Two;
//If ||Z||_2 is not one, then TEMP should be set to
//RHO * ||Z||_2^2 / TWO
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - midpt;
}
psi = Zero;
for (j = 0; j < n - 2; j++) {
psi += z[j] * z[j] / delta[j];
}
c = rhoinv + psi;
w = c + z[ii] * z[ii] / delta[ii] + z[n] * z[n] / delta[n];
if (w <= Zero) {
temp = z[n - 1] * z[n - 1] / (d[n] - d[n - 1] + rho)
+ z[n] * z[n] / rho;
if (c <= temp) {
tau = rho;
} else {
del = d[n] - d[n - 1];
a = -c * del + z[n - 1] * z[n - 1] + z[n] * z[n];
b = z[n] * z[n] * del;
if (a < Zero) {
tau = b * Two / (sqrt(a * a + b * Four * c) - a);
} else {
tau = (a + sqrt(a * a + b * Four * c)) / (c * Two);
}
}
//It can be proved that
//D(N)+RHO/2 <= LAMBDA(N) < D(N)+TAU <= D(N)+RHO
dltlb = midpt;
dltub = rho;
} else {
del = d[n] - d[n - 1];
a = -c * del + z[n - 1] * z[n - 1] + z[n] * z[n];
b = z[n] * z[n] * del;
if (a < Zero) {
tau = b * Two / (sqrt(a * a + b * Four * c) - a);
} else {
tau = (a + sqrt(a * a + b * Four * c)) / (c * Two);
}
//It can be proved that
//D(N) < D(N)+TAU < LAMBDA(N) < D(N)+RHO/2
dltlb = Zero;
dltub = midpt;
}
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - tau;
}
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * Eight + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
//Test for convergence
if (abs(w) <= eps * erretm) {
*dlam = d[i] + tau;
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
++niter;
c = w - delta[n - 1] * dpsi - delta[n] * dphi;
a = (delta[n - 1] + delta[n]) * w - delta[n - 1] * delta[n] * (dpsi + dphi);
b = delta[n - 1] * delta[n] * w;
if (c < Zero) {
c = abs(c);
}
if (c == Zero) {
//ETA = B/A
//ETA = RHO - TAU
eta = dltub - tau;
} else if (a >= Zero) {
eta = (a + sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a - sqrt((abs(a * a - b * Four * c))));
}
//Note, eta should be positive if w is negative, and
//eta should be negative otherwise. However,
//for some reason caused by roundoff, eta*w > 0,
//we simply use one Newton step instead. This way
//will guarantee eta*w < Zero
if (w * eta > Zero) {
eta = -w / (dpsi + dphi);
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * Eight + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
//Main loop to update the values of the array DELTA
iter = niter + 1;
for (niter = iter; niter <= 30; ++niter) {
//Test for convergence
if (abs(w) <= eps * erretm) {
*dlam = d[i] + tau;
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
c = w - delta[n - 1] * dpsi - delta[n] * dphi;
a = (delta[n - 1] + delta[n]) * w - delta[n - 1] * delta[n] * (dpsi + dphi);
b = delta[n - 1] * delta[n] * w;
if (a >= Zero) {
eta = (a + sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a - sqrt(abs(a * a - b * Four * c)));
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta > Zero) {
eta = -w / (dpsi + dphi);
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < ii; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
temp = z[n] / delta[n];
phi = z[n] * temp;
dphi = temp * temp;
erretm = (-phi - psi) * 8. + erretm - phi + rhoinv + abs(tau) * (dpsi + dphi);
w = rhoinv + phi + psi;
}
//Return with INFO = 1, NITER = MAXIT and not converged
*info = 1;
*dlam = d[i] + tau;
goto L250;
//End for the case I = N
} else {
//The case for I < N
niter = 1;
ip1 = i + 1;
//Calculate initial guess
del = d[ip1] - d[i];
midpt = del / Two;
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - midpt;
}
psi = Zero;
for (j = 0; j < i - 1; j++) {
psi += z[j] * z[j] / delta[j];
}
phi = Zero;
for (j = n; j >= i + 2; j--) {
phi += z[j] * z[j] / delta[j];
}
c = rhoinv + psi + phi;
w = c + z[i] * z[i] / delta[i] + z[ip1] * z[ip1] / delta[ip1];
if (w > Zero) {
//d(i)< the ith eigenvalue < (d(i)+d(i+1))/2
//We choose d(i) as origin.
orgati = MTRUE;
a = c * del + z[i] * z[i] + z[ip1] * z[ip1];
b = z[i] * z[i] * del;
if (a > Zero) {
tau = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
} else {
tau = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
}
dltlb = Zero;
dltub = midpt;
} else {
//(d(i)+d(i+1))/2 <= the ith eigenvalue < d(i+1)
//We choose d(i+1) as origin.
orgati = MFALSE;
a = c * del - z[i] * z[i] - z[ip1] * z[ip1];
b = z[ip1] * z[ip1] * del;
if (a < Zero) {
tau = b * Two / (a - sqrt(abs(a * a + b * Four * c)));
} else {
tau = -(a + sqrt(abs(a * a + b * Four * c))) / (c * Two);
}
dltlb = -midpt;
dltub = Zero;
}
if (orgati) {
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[i] - tau;
}
} else {
for (j = 0; j < n; j++) {
delta[j] = d[j] - d[ip1] - tau;
}
}
if (orgati) {
ii = i;
} else {
ii = i + 1;
}
iim1 = ii - 1;
iip1 = ii + 1;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
w = rhoinv + phi + psi;
//W is the value of the secular function with
//its ii-th element removed.
swtch3 = MFALSE;
if (orgati) {
if (w < Zero) {
swtch3 = MTRUE;
}
} else {
if (w > Zero) {
swtch3 = MTRUE;
}
}
if (ii == 1 || ii == n) {
swtch3 = MFALSE;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w += temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau) * dw;
//Test for convergence
if (abs(w) <= eps * erretm) {
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
++niter;
if (!swtch3) {
if (orgati) {
c = w - delta[ip1] * dw - (d[i] - d[ip1]) * (z[i] / delta[i] * z[i] / delta[i]);
} else {
c = w - delta[i] * dw - (d[ip1] - d[i]) * (z[ip1] / delta[ip1] * z[ip1] / delta[ip1]);
}
a = (delta[i] + delta[ip1]) * w - delta[i] * delta[ip1] * dw;
b = delta[i] * delta[ip1] * w;
if (c == Zero) {
if (a == Zero) {
if (orgati) {
a = z[i] * z[i] + delta[ip1] * delta[ip1] * (dpsi + dphi);
} else {
a = z[ip1] * z[ip1] + delta[i] * delta[i] * (dpsi + dphi);
}
}
eta = b / a;
} else if (a <= Zero) {
eta = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
}
} else {
/* Interpolation using THREE most relevant poles */
temp = rhoinv + psi + phi;
if (orgati) {
temp1 = z[iim1] / delta[iim1];
temp1 *= temp1;
c = temp - delta[iip1] * (dpsi + dphi) - (d[iim1] - d[iip1]) * temp1;
zz[0] = z[iim1] * z[iim1];
zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi);
} else {
temp1 = z[iip1] / delta[iip1];
temp1 *= temp1;
c = temp - delta[iim1] * (dpsi + dphi) - (d[iip1] - d[iim1]) * temp1;
zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1));
zz[2] = z[iip1] * z[iip1];
}
zz[1] = z[ii] * z[ii];
Rlaed6(niter, orgati, c, &delta[iim1], zz, &w, &eta, info);
if (*info != 0) {
goto L250;
}
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta >= Zero) {
eta = -w / dw;
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
prew = w;
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w = rhoinv + phi + psi + temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau + eta) * dw;
swtch = MFALSE;
if (orgati) {
if (-w > abs(prew) / Ten) {
swtch = MTRUE;
}
} else {
if (w > abs(prew) / Ten) {
swtch = MTRUE;
}
}
tau += eta;
//Main loop to update the values of the array DELTA
iter = niter + 1;
for (niter = iter; niter <= 30; ++niter) {
//Test for convergence
if (abs(w) <= eps * erretm) {
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
goto L250;
}
if (w <= Zero) {
dltlb = max(dltlb, tau);
} else {
dltub = min(dltub, tau);
}
//Calculate the new step
if (!swtch3) {
if (!swtch) {
if (orgati) {
c = w - delta[ip1] * dw - (d[i] - d[ip1]) * ((z[i] / delta[i]) * (z[i] / delta[i]));
} else {
c = w - delta[i] * dw - (d[ip1] - d[i]) * ((z[ip1] / delta[ip1]) * (z[ip1] / delta[ip1]));
}
} else {
temp = z[ii] / delta[ii];
if (orgati) {
dpsi += temp * temp;
} else {
dphi += temp * temp;
}
c = w - delta[i] * dpsi - delta[ip1] * dphi;
}
a = (delta[i] + delta[ip1]) * w - delta[i] * delta[ip1]
* dw;
b = delta[i] * delta[ip1] * w;
if (c == Zero) {
if (a == Zero) {
if (!swtch) {
if (orgati) {
a = z[i] * z[i] + delta[ip1] * delta[ip1] * (dpsi + dphi);
} else {
a = z[ip1] * z[ip1] + delta[i] * delta[i] * (dpsi + dphi);
}
} else {
a = delta[i] * delta[i] * dpsi + delta[ip1]
* delta[ip1] * dphi;
}
}
eta = b / a;
} else if (a <= Zero) {
eta = (a - sqrt(abs(a * a - b * Four * c))) / (c * Two);
} else {
eta = b * Two / (a + sqrt(abs(a * a - b * Four * c)));
}
} else {
//Interpolation using THREE most relevant poles
temp = rhoinv + psi + phi;
if (swtch) {
c = temp - delta[iim1] * dpsi - delta[iip1] * dphi;
zz[0] = delta[iim1] * delta[iim1] * dpsi;
zz[2] = delta[iip1] * delta[iip1] * dphi;
} else {
if (orgati) {
temp1 = z[iim1] / delta[iim1];
temp1 *= temp1;
c = temp - delta[iip1] * (dpsi + dphi) - (d[iim1]
- d[iip1]) * temp1;
zz[0] = z[iim1] * z[iim1];
zz[2] = delta[iip1] * delta[iip1] * (dpsi - temp1 + dphi);
} else {
temp1 = z[iip1] / delta[iip1];
temp1 *= temp1;
c = temp - delta[iim1] * (dpsi + dphi) - (d[iip1]
- d[iim1]) * temp1;
zz[0] = delta[iim1] * delta[iim1] * (dpsi + (dphi - temp1));
zz[2] = z[iip1] * z[iip1];
}
}
Rlaed6(niter, orgati, c, &delta[iim1], zz, &w, &eta, info);
if (*info != 0) {
goto L250;
}
}
/* Note, eta should be positive if w is negative, and */
/* eta should be negative otherwise. However, */
/* if for some reason caused by roundoff, eta*w > 0, */
/* we simply use one Newton step instead. This way */
/* will guarantee eta*w < Zero */
if (w * eta >= Zero) {
eta = -w / dw;
}
temp = tau + eta;
if (temp > dltub || temp < dltlb) {
if (w < Zero) {
eta = (dltub - tau) / Two;
} else {
eta = (dltlb - tau) / Two;
}
}
for (j = 0; j < n; j++) {
delta[j] -= eta;
}
tau += eta;
prew = w;
//Evaluate PSI and the derivative DPSI
dpsi = Zero;
psi = Zero;
erretm = Zero;
for (j = 0; j < iim1; j++) {
temp = z[j] / delta[j];
psi += z[j] * temp;
dpsi += temp * temp;
erretm += psi;
}
erretm = abs(erretm);
//Evaluate PHI and the derivative DPHI
dphi = Zero;
phi = Zero;
for (j = n; j >= iip1; j--) {
temp = z[j] / delta[j];
phi += z[j] * temp;
dphi += temp * temp;
erretm += phi;
}
temp = z[ii] / delta[ii];
dw = dpsi + dphi + temp * temp;
temp = z[ii] * temp;
w = rhoinv + phi + psi + temp;
erretm = (phi - psi) * Eight + erretm + rhoinv * Two + abs(temp) * Three + abs(tau) * dw;
if (w * prew > Zero && abs(w) > abs(prew) / Ten) {
swtch = !swtch;
}
}
//Return with INFO = 1, NITER = MAXIT and not converged
*info = 1;
if (orgati) {
*dlam = d[i] + tau;
} else {
*dlam = d[ip1] + tau;
}
}
L250:
return;
}
| 18,848 | 8,896 |
// MadronaLib: a C++ framework for DSP applications.
// Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com
// Distributed under the MIT license: http://madrona-labs.mit-license.org/
#include "MLReporter.h"
// --------------------------------------------------------------------------------
#pragma mark param viewing
MLPropertyView::MLPropertyView(MLWidget* w, MLSymbol a) :
mpWidget(w),
mAttr(a)
{
}
MLPropertyView::~MLPropertyView()
{
}
void MLPropertyView::view(const MLProperty& p) const
{
mpWidget->setPropertyImmediate(mAttr, p);
/*
// with Widget properties we can remove switch! TODO
switch(p.getType())
{
case MLProperty::kUndefinedProperty:
break;
case MLProperty::kFloatProperty:
mpWidget->setAttribute(mAttr, p.getFloatValue());
break;
case MLProperty::kStringProperty:
mpWidget->setStringAttribute(mAttr, *p.getStringValue());
break;
case MLProperty::kSignalProperty:
mpWidget->setSignalAttribute(mAttr, *p.getSignalValue());
break;
}
*/
}
// --------------------------------------------------------------------------------
#pragma mark MLReporter
MLReporter::MLReporter(MLPropertySet* m) :
MLPropertyListener(m)
{
}
MLReporter::~MLReporter()
{
}
// ----------------------------------------------------------------
// parameter viewing
// add a parameter view.
// when param p changes, attribute attr of Widget w will be set to the param's value.
//
void MLReporter::addPropertyViewToMap(MLSymbol p, MLWidget* w, MLSymbol attr)
{
mPropertyViewsMap[p].push_back(MLPropertyViewPtr(new MLPropertyView(w, attr)));
}
void MLReporter::doPropertyChangeAction(MLSymbol prop, const MLProperty& newVal)
{
// do we have viewers for this parameter?
MLPropertyViewListMap::iterator look = mPropertyViewsMap.find(prop);
if (look != mPropertyViewsMap.end())
{
// run viewers
MLPropertyViewList viewers = look->second;
for(MLPropertyViewList::iterator vit = viewers.begin(); vit != viewers.end(); vit++)
{
MLPropertyViewPtr pv = (*vit);
const MLPropertyView& v = (*pv);
v.view(newVal);
}
}
}
| 2,098 | 714 |
/*
* Copyright (C) 2020 Louis Hobson <louis-hobson@hotmail.co.uk>. All Rights Reserved.
*
* Distributed under MIT licence as a part of the Chess C++ library.
* For details, see: https://github.com/louishobson/Chess/blob/master/LICENSE
*
* src/chess/chessboard_eval.cpp
*
* Implementation of evaluation methods in include/chess/chessboard.h
*
*/
/* INCLUDES */
#include <louischessx/chessboard.h>
/* BOARD EVALUATION */
/** @name get_check_info
*
* @brief Get information about the check state of a color's king
* @param pc: The color who's king we will look at
* @return check_info_t
*/
chess::chessboard::check_info_t chess::chessboard::get_check_info ( pcolor pc ) const chess_validate_throw
{
/* SETUP */
/* The output check info */
check_info_t check_info;
/* Get the other color */
const pcolor npc = other_color ( pc );
/* Get the friendly and opposing pieces */
const bitboard friendly = bb ( pc );
const bitboard opposing = bb ( npc );
/* Get the king and position of the colored king */
const bitboard king = bb ( pc, ptype::king );
const int king_pos = king.trailing_zeros ();
/* Get the positions of the opposing straight and diagonal pieces */
const bitboard op_straight = bb ( npc, ptype::queen ) | bb ( npc, ptype::rook );
const bitboard op_diagonal = bb ( npc, ptype::queen ) | bb ( npc, ptype::bishop );
/* Get the primary propagator.
* Primary propagator of not opposing means that spans will overlook friendly pieces.
* The secondary propagator will be universe.
*/
const bitboard pp = ~opposing;
const bitboard sp = ~bitboard {};
/* KING, KNIGHTS AND PAWNS */
/* Throw if kings are adjacent (this should never occur) */
#if CHESS_VALIDATE
if ( bitboard::king_attack_lookup ( king_pos ) & bb ( npc, ptype::king ) ) throw std::runtime_error { "Adjacent king found in check_info ()." };
#endif
/* Add checking knights */
check_info.check_vectors |= bitboard::knight_attack_lookup ( king_pos ) & bb ( npc, ptype::knight );
/* Switch depending on pc and add checking pawns */
if ( pc == pcolor::white )
check_info.check_vectors |= king.pawn_any_attack_n () & bb ( pcolor::black, ptype::pawn );
else
check_info.check_vectors |= king.pawn_any_attack_s () & bb ( pcolor::white, ptype::pawn );
/* SLIDING PIECES */
/* Iterate through the straight compass to see if those sliding pieces could be attacking */
if ( bitboard::straight_attack_lookup ( king_pos ) & op_straight )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), king_pos ) & op_straight )
{
/* Span the king in the current direction */
const bitboard king_span = king.rook_attack ( dir, pp, sp );
/* Get the checking and blocking pieces */
const bitboard checking = king_span & op_straight;
const bitboard blocking = king_span & friendly;
/* Add check info */
check_info.check_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_empty () );
check_info.pin_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_singleton () );
}
}
/* Iterate through the diagonal compass to see if those sliding pieces could be attacking */
if ( bitboard::diagonal_attack_lookup ( king_pos ) & op_diagonal )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), king_pos ) & op_diagonal )
{
/* Span the king in the current direction */
const bitboard king_span = king.bishop_attack ( dir, pp, sp );
/* Get the checking and blocking pieces */
const bitboard checking = king_span & op_diagonal;
const bitboard blocking = king_span & friendly;
/* Add check info */
check_info.check_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_empty () );
check_info.pin_vectors |= king_span.only_if ( checking.is_nonempty () & blocking.is_singleton () );
}
}
/* SET REMAINING VARIABLES AND RETURN */
/* Get the check count */
check_info.check_count = ( check_info.check_vectors & bb ( npc ) ).popcount ();
/* Set the check vectors along straight and diagonal paths */
check_info.straight_check_vectors = check_info.check_vectors & bitboard::straight_attack_lookup ( king_pos );
check_info.diagonal_check_vectors = check_info.check_vectors & bitboard::diagonal_attack_lookup ( king_pos );
/* Set the pin vectors along straight and diagonal paths */
check_info.straight_pin_vectors = check_info.pin_vectors & bitboard::straight_attack_lookup ( king_pos );
check_info.diagonal_pin_vectors = check_info.pin_vectors & bitboard::diagonal_attack_lookup ( king_pos );
/* Set check_vectors_dep_check_count */
check_info.check_vectors_dep_check_count = check_info.check_vectors.all_if ( check_info.check_count == 0 ).only_if ( check_info.check_count < 2 );
/* Return the info */
return check_info;
}
/** @name is_protected
*
* @brief Returns true if the board position is protected by the player specified.
* There is no restriction on what piece is at the position, since any piece in the position is ignored.
* @param pc: The color who is defending.
* @param pos: The position of the cell to check the defence of.
* @return boolean
*/
bool chess::chessboard::is_protected ( pcolor pc, int pos ) const chess_validate_throw
{
/* SETUP */
/* Get a bitboard from pos */
const bitboard pos_bb = singleton_bitboard ( pos );
/* Get the positions of the friendly straight and diagonal pieces */
const bitboard fr_straight = bb ( pc, ptype::queen ) | bb ( pc, ptype::rook );
const bitboard fr_diagonal = bb ( pc, ptype::queen ) | bb ( pc, ptype::bishop );
/* Get the propagators.
* Primary propagator of not non-occupied will mean the span will stop at the first piece.
* The secondary propagator of friendly pieces means the span will include a friendly piece if found.
*/
const bitboard pp = ~bb ();
const bitboard sp = bb ( pc );
/* Get the adjacent open cells. These are the cells which don't contain an enemy piece or a friendly pawn, knight or king (and protection from a sliding piece could be blocked) */
const bitboard adj_open_cells = bitboard::king_attack_lookup ( pos ) & ~bb ( other_color ( pc ) ) & ~bb ( pc, ptype::pawn ) & ~bb ( pc, ptype::knight ) & ~bb ( pc, ptype::king );
/* KING, KNIGHTS AND PAWNS */
/* Look for an adjacent king */
if ( bitboard::king_attack_lookup ( pos ) & bb ( pc, ptype::king ) ) return true;
/* Look for defending knights */
if ( bitboard::knight_attack_lookup ( pos ) & bb ( pc, ptype::knight ) ) return true;
/* Switch depending on pc and look for defending pawns */
if ( pc == pcolor::white )
{ if ( pos_bb.pawn_any_attack_s () & bb ( pcolor::white, ptype::pawn ) ) return true; }
else
{ if ( pos_bb.pawn_any_attack_n () & bb ( pcolor::black, ptype::pawn ) ) return true; }
/* SLIDING PIECES */
/* Iterate through the straight compass to see if those sliding pieces could be defending */
if ( bitboard::straight_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::straight_attack_lookup ( pos ).has_common ( fr_straight ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_straight ) )
if ( pos_bb.rook_attack ( dir, pp, sp ) & fr_straight ) return true;
}
/* Iterate through the diagonal compass to see if those sliding pieces could be defending */
if ( bitboard::diagonal_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::diagonal_attack_lookup ( pos ).has_common ( fr_diagonal ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_diagonal ) )
if ( pos_bb.bishop_attack ( dir, pp, sp ) & fr_diagonal ) return true;
}
/* Return false */
return false;
}
/** @name get_least_valuable_attacker
*
* @brief Takes a color and position and finds the least valuable piece attacking that color.
* @param pc: The color attacking.
* @param pos: The position being attacked.
* @return A pair of ptype and position, no_piece and -1 if no attacker is found.
*/
std::pair<chess::ptype, int> chess::chessboard::get_least_valuable_attacker ( pcolor pc, int pos ) const chess_validate_throw
{
/* SETUP */
/* Get the check info */
const check_info_t check_info = get_check_info ( pc );
/* If pos is not part of check_vectors_dep_check_count, then no move will leave the king not in check, so no move is possible */
if ( !check_info.check_vectors_dep_check_count.test ( pos ) ) return { ptype::no_piece, 0 };
/* Get a bitboard from pos */
const bitboard pos_bb = singleton_bitboard ( pos );
/* Get the positions of the friendly straight and diagonal pieces. Disregard straight pieces on diagonal pin vectors and vice versa. */
const bitboard fr_straight = ( bb ( pc, ptype::queen ) | bb ( pc, ptype::rook ) ) & ~check_info.diagonal_pin_vectors;
const bitboard fr_diagonal = ( bb ( pc, ptype::queen ) | bb ( pc, ptype::bishop ) ) & ~check_info.straight_pin_vectors;
/* Get the propagators.
* Primary propagator of not non-occupied will mean the span will stop at the first piece.
* The secondary propagator of friendly pieces means the span will include a friendly piece if found.
*/
const bitboard pp = ~bb ();
const bitboard sp = bb ( pc );
/* Get the adjacent open cells. These are the cells which don't contain an enemy piece or a friendly pawn, knight or king (and protection from a sliding piece could be blocked) */
const bitboard adj_open_cells = bitboard::king_attack_lookup ( pos ) & ~bb ( other_color ( pc ) ) & ~bb ( pc, ptype::pawn ) & ~bb ( pc, ptype::knight ) & ~bb ( pc, ptype::king );
/* PAWNS */
{
/* Switch depending on pc and look for attacking pawns */
bitboard attackers = ( pc == pcolor::white ? pos_bb.pawn_any_attack_s () : pos_bb.pawn_any_attack_n () ) & bb ( pc, ptype::pawn );
/* Remove pawns on straight pin vectors */
attackers &= ~check_info.straight_pin_vectors;
/* Remove the pawns on diagonal pin vectors, if they move off of their pin vector */
attackers &= ~( attackers & check_info.diagonal_pin_vectors ).only_if_not ( check_info.diagonal_pin_vectors.test ( pos ) );
/* If there are any pawns left, return one of them */
if ( attackers ) return { ptype::pawn, attackers.trailing_zeros () };
}
/* KNIGHTS */
{
/* Get the attacking knights */
bitboard attackers = bitboard::knight_attack_lookup ( pos ) & bb ( pc, ptype::knight );
/* Remove those which are on pin vectors */
attackers &= ~check_info.pin_vectors;
/* If there are any knights left, return one of them */
if ( attackers ) return { ptype::knight, attackers.trailing_zeros () };
}
/* SLIDING PIECES */
/* If an attacking queen is found, the rest of the directions must be checked for lower value pieces.
* Hence keep a variable storing the position of a queen, if found.
*/
int attacking_queen_pos = -1;
/* Iterate through diagonal sliding pieces first, since this way finding a bishop or rook can cause immediate return */
/* Iterate through the diagonal compass to see if those sliding pieces could be defending */
if ( bitboard::diagonal_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::diagonal_attack_lookup ( pos ).has_common ( fr_diagonal ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const diagonal_compass dir : diagonal_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_diagonal ) )
{
/* Get the attacker */
bitboard attacker = pos_bb.bishop_attack ( dir, pp, sp ) & fr_diagonal;
/* Get if there is an attacker, and it does not move off of a pin vector */
if ( attacker && !( attacker.contains ( check_info.diagonal_pin_vectors ) && !check_info.diagonal_pin_vectors.test ( pos ) ) )
{
/* Get the position */
const int attacker_pos = attacker.trailing_zeros ();
/* If is a bishop, return now, else set attacking_queen_pos */
if ( bb ( pc, ptype::bishop ).test ( attacker_pos ) ) return { ptype::bishop, attacker_pos }; else attacking_queen_pos = attacker_pos;
}
}
}
/* Iterate through the straight compass to see if those sliding pieces could be attacking */
if ( bitboard::straight_attack_lookup ( pos ).has_common ( adj_open_cells ) & bitboard::straight_attack_lookup ( pos ).has_common ( fr_straight ) )
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( const straight_compass dir : straight_compass_array )
{
/* Only continue if this is a possibly valid direction, then return if is protected */
if ( bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( adj_open_cells ) & bitboard::omnidir_attack_lookup ( static_cast<compass> ( dir ), pos ).has_common ( fr_straight ) )
{
/* Get the attackers */
bitboard attacker = pos_bb.rook_attack ( dir, pp, sp ) & fr_straight;
/* Get if there is an attacker, and it does not move off of a pin vector */
if ( attacker && !( attacker.contains ( check_info.straight_pin_vectors ) && !check_info.straight_pin_vectors.test ( pos ) ) )
{
/* Get the position */
const int attacker_pos = attacker.trailing_zeros ();
/* If is a rook, return now, else set attacking_queen_pos */
if ( bb ( pc, ptype::rook ).test ( attacker_pos ) ) return { ptype::rook, attacker_pos }; else attacking_queen_pos = attacker_pos;
}
}
}
/* If an attacking queen was found, return that */
if ( attacking_queen_pos != -1 ) return { ptype::queen, attacking_queen_pos };
/* KING */
/* Get if there is an adjacent king */
if ( bitboard::king_attack_lookup ( pos ) & bb ( pc, ptype::king ) )
{
/* If pos is not protected by the other color, return the king as attacking */
if ( !is_protected ( other_color ( pc ), pos ) ) return { ptype::king, bb ( pc, ptype::king ).trailing_zeros () };
}
/* NO PIECE */
/* Return no_piece */
return { ptype::no_piece, -1 };
}
/** @name static_exchange_evaluation
*
* @brief Takes a color and position, and returns the possible material gain from the color attacking that position.
* @param pc: The color attacking.
* @param attacked_pos: The position being attacked.
* @param attacked_pt: The piece type to assume that's occupying pos. If no_piece, will be calculated.
* @param attacker_pos: The position of the first piece to attack attacked_pos.
* @param attacker_pt: The piece type that's first attacking attacked_pos. If no_piece, will be set to the least valuable attacker.
* @param prev_gain: A the gain from previous calls. Used internally, should be 0 initially.
* @return An integer, 0 meaning no matierial gain, +/- meaning material gain or loss respectively.
*/
int chess::chessboard::static_exchange_evaluation ( pcolor pc, int attacked_pos, ptype attacked_pt, int attacker_pos, ptype attacker_pt, int prev_gain ) chess_validate_throw
{
/* Create an array of material values for each ptype */
constexpr std::array<int, 7> material_values { 100, 400, 400, 600, 1100, 10000, 0 };
/* Get the attacked type, if required. Return prev_gain if there is no attacked piece. */
if ( attacked_pt == ptype::no_piece ) attacked_pt = find_type ( other_color ( pc ), attacked_pos );
if ( attacked_pt == ptype::no_piece ) return prev_gain;
/* Get the speculative gain */
const int spec_gain = prev_gain + material_values [ cast_penum ( attacked_pt ) ];
/* Possibly cutoff */
if ( std::max ( prev_gain, spec_gain ) < 0 ) return prev_gain;
/* Get the least value piece of this color attacking pos.
* If attacker_pos is set, then find the piece type at that position. Otherwise chose the least valuable attacker.
* Return prev_gain if there is no such piece.
*/
if ( attacker_pt == ptype::no_piece ) if ( attacked_pos != -1 ) attacker_pt = find_type ( pc, attacker_pos ); else
std::tie ( attacker_pt, attacker_pos ) = get_least_valuable_attacker ( pc, attacked_pos );
if ( attacker_pt == ptype::no_piece ) return prev_gain;
/* Make the capture */
get_bb ( pc ).reset ( attacker_pos );
get_bb ( pc, attacker_pt ).reset ( attacker_pos );
get_bb ( pc ).set ( attacked_pos );
get_bb ( pc, attacker_pt ).set ( attacked_pos );
get_bb ( other_color ( pc ) ).reset ( attacked_pos );
get_bb ( other_color ( pc ), attacked_pt ).reset ( attacked_pos );
/* Get the gain from see */
const int gain = std::max ( prev_gain, -static_exchange_evaluation ( other_color ( pc ), attacked_pos, attacker_pt, -1, ptype::no_piece, -spec_gain ) );
/* Unmake the capture */
get_bb ( other_color ( pc ) ).set ( attacked_pos );
get_bb ( other_color ( pc ), attacked_pt ).set ( attacked_pos );
get_bb ( pc ).reset ( attacked_pos );
get_bb ( pc, attacker_pt ).reset ( attacked_pos );
get_bb ( pc ).set ( attacker_pos );
get_bb ( pc, attacker_pt ).set ( attacker_pos );
/* Return the gain */
return gain;
}
/** @name evaluate
*
* @brief Symmetrically evaluate the board state.
* Note that although is non-const, a call to this function will leave the board unmodified.
* @param pc: The color who's move it is next
* @return Integer value, positive for pc, negative for not pc
*/
int chess::chessboard::evaluate ( pcolor pc )
{
/* TERMINOLOGY */
/* Here, a piece refers to any chessman, including pawns and kings.
* Restricted pieces, or restrictives, do not include pawns or kings.
*
* It's important to note the difference between general attacks and legal attacks.
*
* An attack is any position a piece could end up in and potentially capture, regardless of if A) it leaves the king in check, or B) if a friendly piece is in the attack set.
* Legal attacks must be currently possible moves, including A) not leaving the king in check, and B) not attacking friendly pieces, and C) pawns not attacking empty cells.
* Note that a pawn push is not an attack, since a pawn cannot capture by pushing.
*
* A capture is a legal attack on an enemy piece.
* A restricted capture is a legal attack on a restricted enemy piece.
*
* Mobility is the number of distinct strictly legal moves. If a mobility is zero, that means that color is in checkmate.
*/
/* CONSTANTS */
/* Masks */
constexpr bitboard white_center { 0x0000181818000000 }, black_center { 0x0000001818180000 };
constexpr bitboard white_bishop_initial_cells { 0x0000000000000024 }, black_bishop_initial_cells { 0x2400000000000000 };
constexpr bitboard white_knight_initial_cells { 0x0000000000000042 }, black_knight_initial_cells { 0x4200000000000000 };
/* Material values */
constexpr int QUEEN { 1100 }; // 19
constexpr int ROOK { 600 }; // 10
constexpr int BISHOP { 400 }; // 7
constexpr int KNIGHT { 400 }; // 7
constexpr int PAWN { 100 }; // 2
/* Pawns */
constexpr int PAWN_GENERAL_ATTACKS { 1 }; // For every generally attacked cell
constexpr int CENTER_PAWNS { 20 }; // For every pawn
constexpr int PAWN_CENTER_GENERAL_ATTACKS { 10 }; // For every generally attacked cell (in the center)
constexpr int ISOLATED_PAWNS { -10 }; // For every pawn
constexpr int ISOLATED_PAWNS_ON_SEMIOPEN_FILES { -10 }; // For every pawn
constexpr int DOUBLED_PAWNS { -5 }; // Tripled pawns counts as -10 etc.
constexpr int PAWN_GENERAL_ATTACKS_ADJ_OP_KING { 20 }; // For every generally attacked cell
constexpr int PHALANGA { 20 }; // Tripple pawn counts as 40 etc.
constexpr int BLOCKED_PASSED_PAWNS { -15 }; // For each blocked passed pawn
constexpr int STRONG_SQUARES { 20 }; // For each strong square (one attacked by a friendly pawn and not an enemy pawn)
constexpr int BACKWARD_PAWNS { 10 }; // For each pawn behind a strong square (see above)
constexpr int PASSED_PAWNS_DISTANCE { 5 }; // For each passed pawn, for every square away from the 1st rank (since may be queened)
constexpr int LEGAL_ATTACKS_ON_PASSED_PAWN_TRAJECTORIES { 5 }; // For each attack
/* Sliding pieces */
constexpr int STRAIGHT_PIECES_ON_7TH_RANK { 30 }; // For each piece
constexpr int DOUBLE_BISHOP { 20 }; // If true
constexpr int STRAIGHT_PIECES_ON_OPEN_FILE { 35 }; // For each piece
constexpr int STRAIGHT_PIECES_ON_SEMIOPEN_FILE { 25 }; // For each piece
constexpr int STRAIGHT_PIECE_LEGAL_ATTACKS_ON_OPEN_FILES { 10 }; // For every legal attack
constexpr int STRAIGHT_PIECE_LEGAL_ATTACKS_ON_SEMIOPEN_FILES { 5 }; // For every legal attack
constexpr int STRAIGHT_PIECES_BEHIND_PASSED_PAWNS { 20 }; // For every piece
constexpr int DIAGONAL_PIECE_RESTRICTED_CAPTURES { 15 }; // For every restricted capture on enemy pieces (not including pawns or kings)
constexpr int RESTRICTIVES_LEGALLY_ATTACKED_BY_DIAGONAL_PIECES { 15 }; // For every restrictive, white and black (pieces not including pawns or kings)
/* Knights */
constexpr int CENTER_KNIGHTS { 20 }; // For every knight
/* Bishops and knights */
constexpr int BISHOP_OR_KNIGHT_INITIAL_CELL { -15 }; // For every bishop/knight
constexpr int DIAGONAL_OR_KNIGHT_CAPTURE_ON_STRAIGHT_PIECES { 10 }; // For every capture
constexpr int BISHOP_OR_KNIGHT_ON_STRONG_SQUARE { 20 }; // For each piece
/* Mobility and king queen mobility, for every move */
constexpr int MOBILITY { 1 }; // For every legal move
constexpr int KING_QUEEN_MOBILITY { -2 }; // For every non-capture attack, pretending the king is a queen
/* Castling */
constexpr int CASTLE_MADE { 30 }; // If true
constexpr int CASTLE_LOST { -60 }; // If true
/* Other values */
constexpr int KNIGHT_AND_QUEEN_EXIST { 10 }; // If true
constexpr int CENTER_LEGAL_ATTACKS_BY_RESTRICTIVES { 10 }; // For every attack (not including pawns or kings)
constexpr int PINNED_PIECES { -20 }; // For each (friendly) piece
/* Non-symmetrical values */
constexpr int CHECKMATE { 10000 }; // If on the enemy, -10000 if on self
constexpr int KINGS_IN_OPPOSITION { 15 }; // If the kings are one off adjacent
/* SETUP */
/* Get the check info */
const check_info_t white_check_info = get_check_info ( pcolor::white );
const check_info_t black_check_info = get_check_info ( pcolor::black );
/* Get king positions */
const int white_king_pos = bb ( pcolor::white, ptype::king ).trailing_zeros ();
const int black_king_pos = bb ( pcolor::black, ptype::king ).trailing_zeros ();
/* Get the king spans */
const bitboard white_king_span = bitboard::king_attack_lookup ( white_king_pos );
const bitboard black_king_span = bitboard::king_attack_lookup ( black_king_pos );
/* Set legalize_attacks. This is the intersection of not friendly pieces, not the enemy king, and check_vectors_dep_check_count. */
const bitboard white_legalize_attacks = ~bb ( pcolor::white ) & ~bb ( pcolor::black, ptype::king ) & white_check_info.check_vectors_dep_check_count;
const bitboard black_legalize_attacks = ~bb ( pcolor::black ) & ~bb ( pcolor::white, ptype::king ) & black_check_info.check_vectors_dep_check_count;
/* Get the restrictives */
const bitboard white_restrictives = bb ( pcolor::white, ptype::bishop ) | bb ( pcolor::white, ptype::rook ) | bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::knight );
const bitboard black_restrictives = bb ( pcolor::black, ptype::bishop ) | bb ( pcolor::black, ptype::rook ) | bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::knight );
const bitboard restrictives = white_restrictives | black_restrictives;
/* Set the primary propagator such that all empty cells are set */
const bitboard pp = ~bb ();
/* Get the white pawn rear span */
const bitboard white_pawn_rear_span = bb ( pcolor::white, ptype::pawn ).span ( compass::s );
const bitboard black_pawn_rear_span = bb ( pcolor::black, ptype::pawn ).span ( compass::n );
/* Get the pawn file fills (from the rear span and forwards fill) */
const bitboard white_pawn_file_fill = white_pawn_rear_span | bb ( pcolor::white, ptype::pawn ).fill ( compass::n );
const bitboard black_pawn_file_fill = black_pawn_rear_span | bb ( pcolor::black, ptype::pawn ).fill ( compass::s );
/* Get the open and semiopen files. White semiopen files contain no white pawns. */
const bitboard open_files = ~( white_pawn_file_fill | black_pawn_file_fill );
const bitboard white_semiopen_files = ~white_pawn_file_fill & black_pawn_file_fill;
const bitboard black_semiopen_files = ~black_pawn_file_fill & white_pawn_file_fill;
/* Get the passed pawns */
const bitboard white_passed_pawns = bb ( pcolor::white, ptype::pawn ) & ~white_pawn_rear_span & black_semiopen_files & black_semiopen_files.shift ( compass::e ) & black_semiopen_files.shift ( compass::w );
const bitboard black_passed_pawns = bb ( pcolor::black, ptype::pawn ) & ~black_pawn_rear_span & white_semiopen_files & white_semiopen_files.shift ( compass::e ) & white_semiopen_files.shift ( compass::w );
/* Get the cells behind passed pawns.
* This is the span between the passed pawns and the next piece back, including the next piece back but not the pawn.
*/
const bitboard white_behind_passed_pawns = white_passed_pawns.span ( compass::s, pp, ~bitboard {} );
const bitboard black_behind_passed_pawns = black_passed_pawns.span ( compass::n, pp, ~bitboard {} );
/* Get the cells in front of passed pawns.
* This is the span between the passed pawns and the opposite end of the board, not including the pawn.
*/
const bitboard white_passed_pawn_trajectories = white_passed_pawns.span ( compass::n );
const bitboard black_passed_pawn_trajectories = black_passed_pawns.span ( compass::s );
/* ACCUMULATORS */
/* The value of the evaluation function */
int value = 0;
/* Mobilities */
int white_mobility = 0, black_mobility = 0;
/* Partial defence unions. Gives cells which are protected by friendly pieces.
* This is found from the union of all general attacks and can be used to determine opposing king's possible moves.
* However, pinned sliding pieces' general attacks are not included in this union (due to complexity to calculate), hence 'partial'.
*/
bitboard white_partial_defence_union, black_partial_defence_union;
/* Accumulate the difference between white and black's straight piece legal attacks on open and semiopen files */
int straight_legal_attacks_open_diff = 0, straight_legal_attacks_semiopen_diff = 0;
/* Accumulate the difference between white and black's attacks the center by restrictives */
int center_legal_attacks_by_restrictives_diff = 0;
/* Accumulate the difference between white and black's number of restricted captures by diagonal pieces */
int diagonal_restricted_captures_diff = 0;
/* Accumulate the restricted pieces attacked by diagonal pieces */
bitboard restrictives_legally_attacked_by_white_diagonal_pieces, restrictives_legally_attacked_by_black_diagonal_pieces;
/* Accumulate bishop or knight captures on enemy straight pieces */
int diagonal_or_knight_captures_on_straight_diff = 0;
/* Accumulate attacks on passed pawn trajectories */
int legal_attacks_on_passed_pawn_trajectories_diff = 0;
/* NON-PINNED SLIDING PIECES */
/* Deal with non-pinned sliding pieces of both colors in one go.
* If in double check, check_vectors_dep_check_count will remove all attacks the attacks.
*/
/* Scope new bitboards */
{
/* Set straight and diagonal pieces */
const bitboard white_straight_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) & ~white_check_info.pin_vectors;
const bitboard white_diagonal_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::bishop ) ) & ~white_check_info.pin_vectors;
const bitboard black_straight_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) & ~black_check_info.pin_vectors;
const bitboard black_diagonal_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::bishop ) ) & ~black_check_info.pin_vectors;
/* Start compasses */
straight_compass straight_dir;
diagonal_compass diagonal_dir;
/* Iterate through the compass to get all queen, rook and bishop attacks */
#pragma clang loop unroll ( full )
#pragma GCC unroll 4
for ( int i = 0; i < 4; ++i )
{
/* Get the compasses */
straight_dir = straight_compass_array [ i ];
diagonal_dir = diagonal_compass_array [ i ];
/* Apply all shifts to get straight and diagonal general attacks (note that sp is universe to get general attacks)
* This allows us to union to the defence set first.
*/
bitboard white_straight_attacks = white_straight_pieces.rook_attack ( straight_dir, pp, ~bitboard {} );
bitboard white_diagonal_attacks = white_diagonal_pieces.bishop_attack ( diagonal_dir, pp, ~bitboard {} );
bitboard black_straight_attacks = black_straight_pieces.rook_attack ( straight_dir, pp, ~bitboard {} );
bitboard black_diagonal_attacks = black_diagonal_pieces.bishop_attack ( diagonal_dir, pp, ~bitboard {} );
/* Union defence */
white_partial_defence_union |= white_straight_attacks | white_diagonal_attacks;
black_partial_defence_union |= black_straight_attacks | black_diagonal_attacks;
/* Legalize the attacks */
white_straight_attacks &= white_legalize_attacks;
white_diagonal_attacks &= white_legalize_attacks;
black_straight_attacks &= black_legalize_attacks;
black_diagonal_attacks &= black_legalize_attacks;
/* Sum mobility */
white_mobility += white_straight_attacks.popcount () + white_diagonal_attacks.popcount ();
black_mobility += black_straight_attacks.popcount () + black_diagonal_attacks.popcount ();
/* Sum rook attacks on open files */
straight_legal_attacks_open_diff += ( white_straight_attacks & open_files ).popcount ();
straight_legal_attacks_open_diff -= ( black_straight_attacks & open_files ).popcount ();
/* Sum rook attacks on semiopen files */
straight_legal_attacks_semiopen_diff += ( white_straight_attacks & white_semiopen_files ).popcount ();
straight_legal_attacks_semiopen_diff -= ( black_straight_attacks & black_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( white_straight_attacks & white_center ).popcount () + ( white_diagonal_attacks & white_center ).popcount ();
center_legal_attacks_by_restrictives_diff -= ( black_straight_attacks & black_center ).popcount () + ( black_diagonal_attacks & black_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_white_diagonal_pieces |= restrictives & white_diagonal_attacks;
restrictives_legally_attacked_by_black_diagonal_pieces |= restrictives & black_diagonal_attacks;
/* Sum the restricted captures by diagonal pieces */
diagonal_restricted_captures_diff += ( white_diagonal_attacks & black_restrictives ).popcount ();
diagonal_restricted_captures_diff -= ( black_diagonal_attacks & white_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff += ( white_diagonal_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
diagonal_or_knight_captures_on_straight_diff -= ( black_diagonal_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( white_straight_attacks & black_passed_pawn_trajectories ).popcount () + ( white_diagonal_attacks & black_passed_pawn_trajectories ).popcount ();
legal_attacks_on_passed_pawn_trajectories_diff -= ( black_straight_attacks & white_passed_pawn_trajectories ).popcount () + ( black_diagonal_attacks & white_passed_pawn_trajectories ).popcount ();
}
}
/* PINNED SLIDING PIECES */
/* Pinned pieces are handelled separately for each color.
* Only if that color is not in check will they be considered.
* The flood spans must be calculated separately for straight and diagonal, since otherwise the flood could spill onto adjacent pin vectors.
*/
/* White pinned pieces */
if ( white_check_info.pin_vectors.is_nonempty () & white_check_info.check_count == 0 )
{
/* Get the straight and diagonal pinned pieces which can move.
* Hence the straight pinned pieces are all on straight pin vectors, and diagonal pinned pieces are all on diagonal pin vectors.
*/
const bitboard straight_pinned_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) & white_check_info.straight_pin_vectors;
const bitboard diagonal_pinned_pieces = ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::bishop ) ) & white_check_info.diagonal_pin_vectors;
/* Initially set pinned attacks to empty */
bitboard straight_pinned_attacks, diagonal_pinned_attacks;
/* Flood span straight and diagonal (but only if there are pieces to flood) */
if ( straight_pinned_pieces ) straight_pinned_attacks = straight_pinned_pieces.straight_flood_span ( white_check_info.straight_pin_vectors );
if ( diagonal_pinned_pieces ) diagonal_pinned_attacks = diagonal_pinned_pieces.diagonal_flood_span ( white_check_info.diagonal_pin_vectors );
/* Get the union of pinned attacks */
const bitboard pinned_attacks = straight_pinned_attacks | diagonal_pinned_attacks;
/* Only continue if there were appropriate pinned attacks */
if ( pinned_attacks )
{
/* Union defence (at this point the defence union becomes partial) */
white_partial_defence_union |= pinned_attacks | bb ( pcolor::white, ptype::king );
/* Sum mobility */
white_mobility += pinned_attacks.popcount ();
/* Sum rook attacks on open and semiopen files */
straight_legal_attacks_open_diff += ( straight_pinned_attacks & open_files ).popcount ();
straight_legal_attacks_semiopen_diff += ( straight_pinned_attacks & white_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( pinned_attacks & white_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_white_diagonal_pieces |= restrictives & diagonal_pinned_attacks;
/* Get the number of diagonal restricted captures */
diagonal_restricted_captures_diff += ( diagonal_pinned_attacks & black_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff += ( diagonal_pinned_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( pinned_attacks & black_passed_pawn_trajectories ).popcount ();
}
}
/* Black pinned pieces */
if ( black_check_info.pin_vectors.is_nonempty () & black_check_info.check_count == 0 )
{
/* Get the straight and diagonal pinned pieces which can move.
* Hence the straight pinned pieces are all on straight pin vectors, and diagonal pinned pieces are all on diagonal pin vectors.
*/
const bitboard straight_pinned_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) & black_check_info.straight_pin_vectors;
const bitboard diagonal_pinned_pieces = ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::bishop ) ) & black_check_info.diagonal_pin_vectors;
/* Initially set pinned attacks to empty */
bitboard straight_pinned_attacks, diagonal_pinned_attacks;
/* Flood span straight and diagonal (but only if there are pieces to flood) */
if ( straight_pinned_pieces ) straight_pinned_attacks = straight_pinned_pieces.straight_flood_span ( black_check_info.straight_pin_vectors );
if ( diagonal_pinned_pieces ) diagonal_pinned_attacks = diagonal_pinned_pieces.diagonal_flood_span ( black_check_info.diagonal_pin_vectors );
/* Get the union of pinned attacks */
const bitboard pinned_attacks = straight_pinned_attacks | diagonal_pinned_attacks;
/* Only continue if there were appropriate pinned attacks */
if ( pinned_attacks )
{
/* Union defence (at this point the defence union becomes partial) */
black_partial_defence_union |= pinned_attacks | bb ( pcolor::black, ptype::king );
/* Sum mobility */
black_mobility += pinned_attacks.popcount ();
/* Sum rook attacks on open and semiopen files */
straight_legal_attacks_open_diff -= ( straight_pinned_attacks & open_files ).popcount ();
straight_legal_attacks_semiopen_diff -= ( straight_pinned_attacks & black_semiopen_files ).popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff -= ( pinned_attacks & black_center ).popcount ();
/* Union restrictives attacked by diagonal pieces */
restrictives_legally_attacked_by_black_diagonal_pieces |= restrictives & diagonal_pinned_attacks;
/* Get the number of diagonal restricted captures */
diagonal_restricted_captures_diff -= ( diagonal_pinned_attacks & white_restrictives ).popcount ();
/* Sum the legal captures on enemy straight pieces by diagonal pieces */
diagonal_or_knight_captures_on_straight_diff -= ( diagonal_pinned_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff -= ( pinned_attacks & white_passed_pawn_trajectories ).popcount ();
}
}
/* GENERAL SLIDING PIECES */
/* Scope new bitboards */
{
/* Get straight pieces */
const bitboard white_straight_pieces = bb ( pcolor::white, ptype::rook ) | bb ( pcolor::white, ptype::queen );
const bitboard black_straight_pieces = bb ( pcolor::black, ptype::rook ) | bb ( pcolor::black, ptype::queen );
/* Incorperate the material cost into value */
value += BISHOP * ( bb ( pcolor::white, ptype::bishop ).popcount () - bb ( pcolor::black, ptype::bishop ).popcount () );
value += ROOK * ( bb ( pcolor::white, ptype::rook ).popcount () - bb ( pcolor::black, ptype::rook ).popcount () );
value += QUEEN * ( bb ( pcolor::white, ptype::queen ).popcount () - bb ( pcolor::black, ptype::queen ).popcount () );
/* Incorporate straight pieces on 7th (or 2nd) rank into value */
{
const bitboard white_straight_pieces_7th_rank = white_straight_pieces & bitboard { bitboard::masks::rank_7 };
const bitboard black_straight_pieces_2nd_rank = black_straight_pieces & bitboard { bitboard::masks::rank_2 };
value += STRAIGHT_PIECES_ON_7TH_RANK * ( white_straight_pieces_7th_rank.popcount () - black_straight_pieces_2nd_rank.popcount () );
}
/* Incorporate bishops on initial cells into value */
{
const bitboard white_initial_bishops = bb ( pcolor::white, ptype::bishop ) & white_bishop_initial_cells;
const bitboard black_initial_bishops = bb ( pcolor::black, ptype::bishop ) & black_bishop_initial_cells;
value += BISHOP_OR_KNIGHT_INITIAL_CELL * ( white_initial_bishops.popcount () - black_initial_bishops.popcount () );
}
/* Incorporate double bishops into value */
value += DOUBLE_BISHOP * ( ( bb ( pcolor::white, ptype::bishop ).popcount () == 2 ) - ( bb ( pcolor::black, ptype::bishop ).popcount () == 2 ) );
/* Incorporate straight pieces and attacks on open/semiopen files into value */
value += STRAIGHT_PIECES_ON_OPEN_FILE * ( ( white_straight_pieces & open_files ).popcount () - ( black_straight_pieces & open_files ).popcount () );
value += STRAIGHT_PIECES_ON_SEMIOPEN_FILE * ( ( white_straight_pieces & white_semiopen_files ).popcount () - ( black_straight_pieces & black_semiopen_files ).popcount () );
value += STRAIGHT_PIECE_LEGAL_ATTACKS_ON_OPEN_FILES * straight_legal_attacks_open_diff;
value += STRAIGHT_PIECE_LEGAL_ATTACKS_ON_SEMIOPEN_FILES * straight_legal_attacks_semiopen_diff;
/* Incorporate straight pieces behind passed pawns into value */
value += STRAIGHT_PIECES_BEHIND_PASSED_PAWNS * ( ( white_straight_pieces & white_behind_passed_pawns ).popcount () - ( black_straight_pieces & black_behind_passed_pawns ).popcount () );
/* Incorporate restrictives attacked by diagonal pieces */
value += RESTRICTIVES_LEGALLY_ATTACKED_BY_DIAGONAL_PIECES * ( restrictives_legally_attacked_by_white_diagonal_pieces.popcount () - restrictives_legally_attacked_by_black_diagonal_pieces.popcount () );
/* Incorporate diagonal pieces restricted captures into value */
value += DIAGONAL_PIECE_RESTRICTED_CAPTURES * diagonal_restricted_captures_diff;
}
/* KNIGHTS */
/* Each color is considered separately in loops */
/* Scope new bitboards */
{
/* Iterate through white knights to get attacks.
* If in double check, white_check_info.check_vectors_dep_check_count will remove all moves.
*/
for ( bitboard white_knights = bb ( pcolor::white, ptype::knight ); white_knights; )
{
/* Get the position of the next knight and its general attacks */
const int pos = white_knights.trailing_zeros (); white_knights.reset ( pos );
bitboard knight_attacks = bitboard::knight_attack_lookup ( pos );
/* Union defence */
white_partial_defence_union |= knight_attacks;
/* Find legal knight attacks. Note that a pinned knight cannot move along its pin vector, hence cannot move at all. */
knight_attacks = knight_attacks.only_if ( !white_check_info.pin_vectors.test ( pos ) ) & white_legalize_attacks;
/* Sum mobility */
white_mobility += knight_attacks.popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff += ( knight_attacks & white_center ).popcount ();
/* Sum the legal captures on enemy straight pieces by knights */
diagonal_or_knight_captures_on_straight_diff += ( knight_attacks & ( bb ( pcolor::black, ptype::queen ) | bb ( pcolor::black, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( knight_attacks & black_passed_pawn_trajectories ).popcount ();
}
/* Iterate through black knights to get attacks */
for ( bitboard black_knights = bb ( pcolor::black, ptype::knight ); black_knights; )
{
/* Get the position of the next knight and its general attacks */
const int pos = black_knights.trailing_zeros (); black_knights.reset ( pos );
bitboard knight_attacks = bitboard::knight_attack_lookup ( pos );
/* Union defence */
black_partial_defence_union |= knight_attacks;
/* Find legal knight attacks. Note that a pinned knight cannot move along its pin vector, hence cannot move at all. */
knight_attacks = knight_attacks.only_if ( !black_check_info.pin_vectors.test ( pos ) ) & black_legalize_attacks;
/* Sum mobility */
black_mobility += knight_attacks.popcount ();
/* Sum attacks on the center */
center_legal_attacks_by_restrictives_diff -= ( knight_attacks & black_center ).popcount ();
/* Sum the legal captures on enemy straight pieces by knights */
diagonal_or_knight_captures_on_straight_diff -= ( knight_attacks & ( bb ( pcolor::white, ptype::queen ) | bb ( pcolor::white, ptype::rook ) ) ).popcount ();
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff -= ( knight_attacks & white_passed_pawn_trajectories ).popcount ();
}
/* Incorperate the number of knights into value */
value += KNIGHT * ( bb ( pcolor::white, ptype::knight ).popcount () - bb ( pcolor::black, ptype::knight ).popcount () );
/* Incorporate knights on initial cells into value */
{
const bitboard white_initial_knights = bb ( pcolor::white, ptype::knight ) & white_knight_initial_cells;
const bitboard black_initial_knights = bb ( pcolor::black, ptype::knight ) & black_knight_initial_cells;
value += BISHOP_OR_KNIGHT_INITIAL_CELL * ( white_initial_knights.popcount () - black_initial_knights.popcount () );
}
/* Incorporate knights in the venter into value */
{
const bitboard white_center_knights = bb ( pcolor::white, ptype::knight ) & white_center;
const bitboard black_center_knights = bb ( pcolor::black, ptype::knight ) & black_center;
value += CENTER_KNIGHTS * ( white_center_knights.popcount () - black_center_knights.popcount () );
}
}
/* PAWN MOVES */
/* We can handle both colors, pinned and non-pinned pawns simultaneously, since pawn moves are more simple than sliding pieces and knights.
* Non-pinned pawns can have their moves calculated normally, but pinned pawns must first be checked as to whether they will move along their pin vector.
* There is no if-statement for double check, only check_vectors_dep_check_count is used to mask out all moves if in double check.
* This is because double check is quite unlikely, and pawn move calculations are quite cheap anyway.
*/
/* Scope the new bitboards */
{
/* Get the non-pinned pawns */
const bitboard white_non_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & ~white_check_info.pin_vectors;
const bitboard black_non_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & ~black_check_info.pin_vectors;
/* Get the straight and diagonal pinned pawns */
const bitboard white_straight_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & white_check_info.straight_pin_vectors;
const bitboard white_diagonal_pinned_pawns = bb ( pcolor::white, ptype::pawn ) & white_check_info.diagonal_pin_vectors;
const bitboard black_straight_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & black_check_info.straight_pin_vectors;
const bitboard black_diagonal_pinned_pawns = bb ( pcolor::black, ptype::pawn ) & black_check_info.diagonal_pin_vectors;
/* Calculations for pawn pushes.
* Non-pinned pawns can push without restriction.
* Pinned pawns can push only if they started and ended within a straight pin vector.
* If in check, ensure that the movements protected the king.
*/
const bitboard white_pawn_pushes = ( white_non_pinned_pawns.pawn_push_n ( pp ) | ( white_straight_pinned_pawns.pawn_push_n ( pp ) & white_check_info.straight_pin_vectors ) ) & white_check_info.check_vectors_dep_check_count;
const bitboard black_pawn_pushes = ( black_non_pinned_pawns.pawn_push_s ( pp ) | ( black_straight_pinned_pawns.pawn_push_s ( pp ) & black_check_info.straight_pin_vectors ) ) & black_check_info.check_vectors_dep_check_count;
/* Get general pawn attacks */
const bitboard white_pawn_attacks = bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::ne ) | bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::nw );
const bitboard black_pawn_attacks = bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::se ) | bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::sw );
/* Get the strong squares.
* These are the squares attacked by a friendly pawn, but not by an enemy pawn.
*/
const bitboard white_strong_squares = white_pawn_attacks & ~black_pawn_attacks;
const bitboard black_strong_squares = black_pawn_attacks & ~white_pawn_attacks;
/* Get pawn captures (legal pawn attacks).
* Non-pinned pawns can attack without restriction.
* Pinned pawns can attack only if they started and ended within a diagonal pin vector.
* If in check, ensure that the movements protected the king.
* En passant will be added later
*/
bitboard white_pawn_captures_e = ( white_non_pinned_pawns.pawn_attack ( diagonal_compass::ne ) | ( white_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::ne ) & white_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::black ) & white_legalize_attacks;
bitboard white_pawn_captures_w = ( white_non_pinned_pawns.pawn_attack ( diagonal_compass::nw ) | ( white_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::nw ) & white_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::black ) & white_legalize_attacks;
bitboard black_pawn_captures_e = ( black_non_pinned_pawns.pawn_attack ( diagonal_compass::se ) | ( black_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::se ) & black_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::white ) & black_legalize_attacks;
bitboard black_pawn_captures_w = ( black_non_pinned_pawns.pawn_attack ( diagonal_compass::sw ) | ( black_diagonal_pinned_pawns.pawn_attack ( diagonal_compass::sw ) & black_check_info.diagonal_pin_vectors ) ) & bb ( pcolor::white ) & black_legalize_attacks;
/* Save the en passant target square */
const int en_passant_target = aux_info.en_passant_target;
/* Add white en passant captures if they don't lead to check */
if ( bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::ne ).only_if ( aux_info.en_passant_color == pcolor::white ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::white, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target - 9, en_passant_target } );
if ( !is_in_check ( pc ) ) white_pawn_captures_e.set ( en_passant_target );
unmake_move_internal ();
} if ( bb ( pcolor::white, ptype::pawn ).pawn_attack ( diagonal_compass::nw ).only_if ( aux_info.en_passant_color == pcolor::white ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::white, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target - 7, en_passant_target } );
if ( !is_in_check ( pc ) ) white_pawn_captures_w.set ( en_passant_target );
unmake_move_internal ();
}
/* Add black en passant captures if they don't lead to check */
if ( bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::se ).only_if ( aux_info.en_passant_color == pcolor::black ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::black, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target + 7, en_passant_target } );
if ( !is_in_check ( pc ) ) black_pawn_captures_e.set ( en_passant_target );
unmake_move_internal ();
} if ( bb ( pcolor::black, ptype::pawn ).pawn_attack ( diagonal_compass::sw ).only_if ( aux_info.en_passant_color == pcolor::black ).test ( en_passant_target ) )
{
make_move_internal ( move_t { pcolor::black, ptype::pawn, ptype::pawn, ptype::no_piece, en_passant_target + 9, en_passant_target } );
if ( !is_in_check ( pc ) ) black_pawn_captures_w.set ( en_passant_target );
unmake_move_internal ();
}
/* Union defence */
white_partial_defence_union |= white_pawn_attacks;
black_partial_defence_union |= black_pawn_attacks;
/* Sum mobility */
white_mobility += white_pawn_pushes.popcount () + white_pawn_captures_e.popcount () + white_pawn_captures_w.popcount ();
black_mobility += black_pawn_pushes.popcount () + black_pawn_captures_e.popcount () + black_pawn_captures_w.popcount ();
/* Incorporate the number of pawns into value */
value += PAWN * ( bb ( pcolor::white, ptype::pawn ).popcount () - bb ( pcolor::black, ptype::pawn ).popcount () );
/* Incorporate the number of cells generally attacked by pawns into value */
value += PAWN_GENERAL_ATTACKS * ( white_pawn_attacks.popcount () - black_pawn_attacks.popcount () );
/* Incorporate strong squares into value */
value += STRONG_SQUARES * ( white_strong_squares.popcount () - black_strong_squares.popcount () );
/* Sum the legal attacks on passed pawn trajectories.
* Use pawn general attacks, since legal captures require there to be a piece present.
*/
legal_attacks_on_passed_pawn_trajectories_diff += ( white_pawn_attacks & black_passed_pawn_trajectories ).popcount () - ( black_pawn_attacks & white_passed_pawn_trajectories ).popcount ();
/* Incorperate the number of pawns in the center to value */
{
const bitboard white_center_pawns = bb ( pcolor::white, ptype::pawn ) & white_center;
const bitboard black_center_pawns = bb ( pcolor::black, ptype::pawn ) & black_center;
value += CENTER_PAWNS * ( white_center_pawns.popcount () - black_center_pawns.popcount () );
}
/* Incororate the number of center cells generally attacked by pawns into value */
{
const bitboard white_center_defence = white_pawn_attacks & white_center;
const bitboard black_center_defence = black_pawn_attacks & black_center;
value += PAWN_CENTER_GENERAL_ATTACKS * ( white_center_defence.popcount () - black_center_defence.popcount () );
}
/* Incorporate isolated pawns, and those on semiopen files, into value */
{
const bitboard white_isolated_pawns = bb ( pcolor::white, ptype::pawn ) & ~( white_pawn_file_fill.shift ( compass::e ) | white_pawn_file_fill.shift ( compass::w ) );
const bitboard black_isolated_pawns = bb ( pcolor::black, ptype::pawn ) & ~( black_pawn_file_fill.shift ( compass::e ) | black_pawn_file_fill.shift ( compass::w ) );
value += ISOLATED_PAWNS * ( white_isolated_pawns.popcount () - black_isolated_pawns.popcount () );
value += ISOLATED_PAWNS_ON_SEMIOPEN_FILES * ( ( white_isolated_pawns & white_semiopen_files ).popcount () - ( black_isolated_pawns & black_semiopen_files ).popcount () );
}
/* Incorporate the number of doubled pawns into value */
{
const bitboard white_doubled_pawns = bb ( pcolor::white, ptype::pawn ) & white_pawn_rear_span;
const bitboard black_doubled_pawns = bb ( pcolor::black, ptype::pawn ) & black_pawn_rear_span;
value += DOUBLED_PAWNS * ( white_doubled_pawns.popcount () - black_doubled_pawns.popcount () );
}
/* Incorporate the number of cells adjacent to enemy king, which are generally attacked by pawns, into value */
{
const bitboard white_pawn_defence_adj_op_king = white_pawn_attacks & black_king_span;
const bitboard black_pawn_defence_adj_op_king = black_pawn_attacks & white_king_span;
value += PAWN_GENERAL_ATTACKS_ADJ_OP_KING * ( white_pawn_defence_adj_op_king.popcount () - black_pawn_defence_adj_op_king.popcount () );
}
/* Incorporate phalanga into value */
{
const bitboard white_phalanga = bb ( pcolor::white, ptype::pawn ) & bb ( pcolor::white, ptype::pawn ).shift ( compass::e );
const bitboard black_phalanga = bb ( pcolor::black, ptype::pawn ) & bb ( pcolor::black, ptype::pawn ).shift ( compass::e );
value += PHALANGA * ( white_phalanga.popcount () - black_phalanga.popcount () );
}
/* Incorporate blocked passed pawns into value */
{
const bitboard white_blocked_passed_pawns = white_behind_passed_pawns.shift ( compass::n ).shift ( compass::n ) & bb ( pcolor::black );
const bitboard black_blocked_passed_pawns = black_behind_passed_pawns.shift ( compass::s ).shift ( compass::s ) & bb ( pcolor::white );
value += BLOCKED_PASSED_PAWNS * ( white_blocked_passed_pawns.popcount () - black_blocked_passed_pawns.popcount () );
}
/* Incorporate backwards pawns into value */
{
const bitboard white_backward_pawns = white_strong_squares.shift ( compass::s ) & bb ( pcolor::white, ptype::pawn );
const bitboard black_backward_pawns = black_strong_squares.shift ( compass::n ) & bb ( pcolor::black, ptype::pawn );
value += BACKWARD_PAWNS * ( white_backward_pawns.popcount () - black_backward_pawns.popcount () );
}
/* Incorporate bishops or knights on strong squares into value */
{
const bitboard white_bishop_or_knight_strong_squares = white_strong_squares & ( bb ( pcolor::white, ptype::bishop ) | bb ( pcolor::white, ptype::knight ) );
const bitboard black_bishop_or_knight_strong_squares = black_strong_squares & ( bb ( pcolor::black, ptype::bishop ) | bb ( pcolor::black, ptype::knight ) );
value += BISHOP_OR_KNIGHT_ON_STRONG_SQUARE * ( white_bishop_or_knight_strong_squares.popcount () - black_bishop_or_knight_strong_squares.popcount () );
}
/* Incorporate passed pawns into value */
{
const bitboard white_passed_pawns_distance = white_passed_pawns.fill ( compass::s );
const bitboard black_passed_pawns_distance = black_passed_pawns.fill ( compass::n );
value += PASSED_PAWNS_DISTANCE * ( white_passed_pawns_distance.popcount () - black_passed_pawns_distance.popcount () );
}
}
/* KING ATTACKS */
/* Use the king position to look for possible attacks.
* As well as using the partial defence union, check any left over king moves for check.
*/
/* Scope the new bitboards */
{
/* Get all the king legal attacks (into empty space or an opposing piece).
* The empty space must not be protected by the opponent, and the kings must not be left adjacent.
* Note that some illegal attacks may be included here, if there are any opposing pinned sliding pieces.
*/
bitboard white_king_attacks = white_king_span & ~black_king_span & ~bb ( pcolor::white ) & ~black_partial_defence_union;
bitboard black_king_attacks = black_king_span & ~white_king_span & ~bb ( pcolor::black ) & ~white_partial_defence_union;
/* Validate the remaining white king moves */
if ( white_king_attacks )
{
/* Temporarily unset the king */
get_bb ( pcolor::white ).reset ( white_king_pos );
get_bb ( pcolor::white, ptype::king ).reset ( white_king_pos );
/* Loop through the white king attacks to validate they don't lead to check */
for ( bitboard white_king_attacks_temp = white_king_attacks; white_king_attacks_temp; )
{
/* Get the position of the next king attack then use the position to determine if it is defended by the opponent */
int pos = white_king_attacks_temp.trailing_zeros ();
white_king_attacks.reset_if ( pos, is_protected ( pcolor::black, pos ) );
white_king_attacks_temp.reset ( pos );
}
/* Reset the king */
get_bb ( pcolor::white ).set ( white_king_pos );
get_bb ( pcolor::white, ptype::king ).set ( white_king_pos );
}
/* Validate the remaining black king moves */
if ( black_king_attacks )
{
/* Temporarily unset the king */
get_bb ( pcolor::black ).reset ( black_king_pos );
get_bb ( pcolor::black, ptype::king ).reset ( black_king_pos );
/* Loop through the white king attacks to validate they don't lead to check */
for ( bitboard black_king_attacks_temp = black_king_attacks; black_king_attacks_temp; )
{
/* Get the position of the next king attack then use the position to determine if it is defended by the opponent */
int pos = black_king_attacks_temp.trailing_zeros ();
black_king_attacks.reset_if ( pos, is_protected ( pcolor::white, pos ) );
black_king_attacks_temp.reset ( pos );
}
/* Reset the king */
get_bb ( pcolor::black ).set ( black_king_pos );
get_bb ( pcolor::black, ptype::king ).set ( black_king_pos );
}
/* Calculate king queen fill. Flood fill using pp and queen attack lookup as a propagator. */
const bitboard white_king_queen_fill = bb ( pcolor::white, ptype::king ).straight_flood_fill ( bitboard::straight_attack_lookup ( white_king_pos ) & pp )
| bb ( pcolor::white, ptype::king ).diagonal_flood_fill ( bitboard::diagonal_attack_lookup ( white_king_pos ) & pp );
const bitboard black_king_queen_fill = bb ( pcolor::black, ptype::king ).straight_flood_fill ( bitboard::straight_attack_lookup ( black_king_pos ) & pp )
| bb ( pcolor::black, ptype::king ).diagonal_flood_fill ( bitboard::diagonal_attack_lookup ( black_king_pos ) & pp );
/* Sum mobility */
white_mobility += white_king_attacks.popcount () + can_kingside_castle ( pcolor::white, white_check_info ) + can_queenside_castle ( pcolor::white, white_check_info );
black_mobility += black_king_attacks.popcount () + can_kingside_castle ( pcolor::black, black_check_info ) + can_queenside_castle ( pcolor::black, black_check_info );
/* Incorporate the king queen mobility into value.
* It does not matter that we are using the fills instead of spans, since the fact both the fills include their kings will cancel out.
*/
value += KING_QUEEN_MOBILITY * ( white_king_queen_fill.popcount () - black_king_queen_fill.popcount () );
/* Sum the legal attacks on passed pawn trajectories */
legal_attacks_on_passed_pawn_trajectories_diff += ( white_king_span & black_passed_pawn_trajectories ).popcount () - ( black_king_span & white_passed_pawn_trajectories ).popcount ();
}
/* CHECKMATE AND STALEMATE */
/* If one color has no mobility and the other does, return maxima/minima or 0, depending on check count */
if ( ( white_mobility == 0 ) & ( black_mobility != 0 ) ) if ( white_check_info.check_count ) return ( pc == pcolor::white ? -CHECKMATE : CHECKMATE ); else return 0;
if ( ( black_mobility == 0 ) & ( white_mobility != 0 ) ) if ( black_check_info.check_count ) return ( pc == pcolor::white ? CHECKMATE : -CHECKMATE ); else return 0;
/* If neither color has any mobility, return 0 */
if ( white_mobility == 0 && black_mobility == 0 ) return 0;
/* FINISH ADDING TO VALUE */
/* Mobility */
value += MOBILITY * ( white_mobility - black_mobility );
/* Attacks by restrictives on center */
value += CENTER_LEGAL_ATTACKS_BY_RESTRICTIVES * center_legal_attacks_by_restrictives_diff;
/* Captures on straight pieces by diagonal pieces and knights */
value += DIAGONAL_OR_KNIGHT_CAPTURE_ON_STRAIGHT_PIECES * diagonal_or_knight_captures_on_straight_diff;
/* Knight and queen exist */
{
const bool white_knight_and_queen_exist = bb ( pcolor::white, ptype::knight ).is_nonempty () & bb ( pcolor::white, ptype::queen ).is_nonempty ();
const bool black_knight_and_queen_exist = bb ( pcolor::black, ptype::knight ).is_nonempty () & bb ( pcolor::black, ptype::queen ).is_nonempty ();
value += KNIGHT_AND_QUEEN_EXIST * ( white_knight_and_queen_exist - black_knight_and_queen_exist );
}
/* Castling */
value += CASTLE_MADE * ( castle_made ( pcolor::white ) - castle_made ( pcolor::black ) );
value += CASTLE_LOST * ( castle_lost ( pcolor::white ) - castle_lost ( pcolor::black ) );
/* Pinned pieces */
{
const bitboard white_pinned_pieces = white_check_info.pin_vectors & bb ( pcolor::white );
const bitboard black_pinned_pieces = black_check_info.pin_vectors & bb ( pcolor::black );
value += PINNED_PIECES * ( white_pinned_pieces.popcount () - black_pinned_pieces.popcount () );
}
/* Attacks on passed pawn trajectories */
value += LEGAL_ATTACKS_ON_PASSED_PAWN_TRAJECTORIES * legal_attacks_on_passed_pawn_trajectories_diff;
/* Kings in opposition */
value += KINGS_IN_OPPOSITION * ( white_king_span & black_king_span ).is_nonempty () * ( pc == pcolor::white ? +1 : -1 );
/* Return the value */
return ( pc == pcolor::white ? value : -value );
} | 68,739 | 21,843 |
/*
* LevelIO.cpp
*
* Created on: Dec 1, 2010
* Author: rgreen
*/
#include "LevelIO.h"
#include <batterytech/platform/platformgeneral.h>
#include <batterytech/Logger.h>
#include "../gameobject/GameObjectFactory.h"
#include <batterytech/util/TextFileUtil.h>
#include <string.h>
LevelIO::LevelIO(GameContext *context) {
this->context = context;
}
LevelIO::~LevelIO() {
context = NULL;
}
void LevelIO::getDataDirPath(char* path) {
_platform_get_external_storage_dir_name(path, 255);
strcat(path, _platform_get_path_separator());
strcat(path, "demo-app-data");
}
void LevelIO::checkDataDir() {
logmsg("External Storage Directory:");
char dir[255];
getDataDirPath(dir);
logmsg(dir);
if (!_platform_path_exists(dir)) {
logmsg("Path does not exist. Attempting to create");
if (!_platform_path_create(dir)) {
logmsg("Unable to create dir!");
}
} else {
logmsg("Path exists.");
}
if (_platform_path_can_read(dir)) {
logmsg("Can read from dir.");
}
if (_platform_path_can_write(dir)) {
logmsg("Can write to dir.");
}
logmsg(dir);
}
| 1,125 | 443 |
#include <iostream>
#include <regex>
#include <string>
#include <list>
#define CPPHTTPLIB_OPENSSL_SUPPORT
#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 20
#define CPPHTTPLIB_READ_TIMEOUT_SECOND 20
#define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 20
#include "httplib.h"
#include <vm/vm.h>
#include <bot/bot.h>
#include <game.h>
#include <types.h>
#include <plot.h>
using namespace std;
bool https;
string serverUrl;
string serverName;
int serverPort;
string apiKey;
string playerKeyStr;
bool localMode;
std::shared_ptr<Plot> plot;
bool parseArgv(int argc, char**argv) {
const std::regex urlRegexp("(http|https)://([^/:]+)(:\\d+)?/?");
const string serverUrl = argv[1];
if (argc == 3) {
// subbmission
localMode = false;
cerr << "Submission mode" << endl;
playerKeyStr = argv[2];
} else if (argc == 4) {
// local bot test
localMode = true;
cerr << "local mode" << endl;
apiKey = argv[2];
playerKeyStr = argv[3];
}
std::smatch urlMatches;
if (!std::regex_search(serverUrl, urlMatches, urlRegexp)) {
std::cout << "Bad server URL" << std::endl;
return false;
}
string protocol = urlMatches[1];
https = protocol == "https";
serverName = urlMatches[2];
if (urlMatches[3] == "") {
serverPort = https ? 443 : 80;
} else {
serverPort = std::stoi(urlMatches[3].str().substr(1));
}
cout << "ServerURL: " << serverUrl << endl;
cout << "ServerPort: " << serverPort << endl;
cout << "ServerName: " << serverName << "; APIKey: " << apiKey << std::endl;
cout << "PlayerKey: " << playerKeyStr << endl;
return true;
}
string post(const string&path, const string& body) {
shared_ptr<httplib::Client> pclient;
if (https) {
pclient.reset((httplib::Client*) new httplib::SSLClient(serverName, serverPort));
} else {
pclient.reset(new httplib::Client(serverName, serverPort));
}
string pathWithKey = path;
if (apiKey != "") {
pathWithKey += "?apiKey=" + apiKey;
}
std::cout << "PathWithKey: " << pathWithKey << endl;
std::cout << "body: " << body << std::endl;
const std::shared_ptr<httplib::Response> serverResponse =
pclient->Post(pathWithKey.c_str(), body.c_str(), "text/plain");
if (!serverResponse) {
std::cout << "Unexpected server response:\nNo response from server" << std::endl;
exit(1);
}
if (serverResponse->status != 200) {
std::cout << "Unexpected server response:\nHTTP code: " << serverResponse->status
<< "\nResponse body: " << serverResponse->body << std::endl;
exit(1);
return "";
}
std::cout << "Server response: " << serverResponse->body << std::endl;
return serverResponse->body;
}
std::string sendData(const std::string& path, const std::string& payload) {
return post(path, payload);
}
void printNum(bint num) {
cout << num << endl;
cout << numToStr(num) << endl;
}
void printSexp(const string& str) {
cout << "Input: " << str << endl;
Sexp sexp = parse(nullptr, str);
cout << "Parsed: " << sexp << endl;
cout << "Eval: " << eval(sexp) << endl;
}
void printMod(const string& str) {
cout << "Input: " << str << endl;
Sexp sexp = parse(nullptr, str);
cout << "Parsed: " << sexp << endl;
auto e = eval(sexp);
cout << "Eval: " << e << endl;
cout << "Mod-str: " << e->mod() << endl;
}
int runTest() {
/*
printNum(1);
printNum(7);
printNum(8);
printNum(508);
printNum(65537);
printNum(bint("8704918670857764736"));
// From blog.
printNum(decode("110110000111011111100001001111110101000000"));
// From blog.
printNum(decode("110110000111011111100001001111110100110000"));
// Response for "1101000"
printNum(decode("110110000111011111100001001110011010000100"));
// Response
cerr << decode("1101000") << endl;
*/
printSexp("ap ap add 1 2");
printSexp("ap ap ap cons 1 2 add");
printSexp("ap ap ap c add 1 2");
printSexp("ap ap ap b inc dec 3");
printSexp("ap ap ap s add inc 1");
printSexp("ap ap ap s mul ap add 1 6");
printSexp("ap ap t 1 5");
printSexp("ap ap t t i");
printSexp("ap ap t t ap inc 5");
printSexp("ap ap t ap inc 5 t");
printSexp("ap car ap ap cons 3 1");
printSexp("ap car i"); // t
printSexp("ap ap eq 3 3"); // t
printSexp("ap ap eq 3 2"); // f
printSexp("ap ap t 42 ap inc 42");
printSexp("ap ap f 42 0");
printMod("ap mod 0");
printMod("ap mod 1");
printMod("ap mod -1");
printMod("ap mod 2");
printMod("ap mod -2");
printMod("ap mod 256");
printMod("ap mod -256");
printSexp("ap ap ap cons 2 1 add");
printSexp("ap car ap ap cons t f");
printSexp("ap car i");
printSexp("ap cdr i");
printSexp("ap isnil nil");
printSexp("ap isnil ap ap cons 1 2");
printSexp("ap ap lt -19 -20");
printSexp("ap ap div 4 2");
printSexp("ap ap div 4 3");
printSexp("ap ap div 4 5");
printSexp("ap ap div 6 -2");
printSexp("ap ap div -5 3");
printSexp("ap ap div -5 -3");
// mod
printSexp("ap mod nil");
printSexp("ap mod ap ap cons nil nil");
printSexp("ap mod ap ap cons 0 nil");
printSexp("ap mod ap ap cons 1 2");
printSexp("ap mod ap ap cons 1 ap ap cons 2 nil");
printSexp("ap dem ap mod nil");
printSexp("ap dem ap mod ap ap cons nil nil");
printSexp("ap dem ap mod ap ap cons 0 nil");
printSexp("ap dem ap mod ap ap cons 1 2");
printSexp("ap dem ap mod ap ap cons 1 ap ap cons 2 nil");
printSexp("ap dem ap mod ap ap cons 1 ap ap cons 2 nil");
return 0;
}
void visualizeGame(GameResponse game) {
if (!plot) {
return;
}
plot->clear();
int earthSize = 16;
plot->startDraw();
for (int y = -earthSize; y <= earthSize; y++) {
for (int x = -earthSize; x <= earthSize; x++) {
plot->draw(x, y);
}
}
plot->endDraw();
plot->startDraw();
for (const Ship& s : game.ships()) {
auto pos = s.position();
plot->draw((int)pos.x, (int)pos.y);
}
plot->endDraw();
plot->flush();
}
int runLocal(const string& path) {
plot.reset(new Plot());
int x = 0;
int y = 0;
Sexp state = nil();
VM vm(path);
list<pair<int, int>> bootstrap = {
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{8, 4},
{2, -8},
{3, 6},
{0, -14},
{-4, 10},
{9, -3 },
{-4, 10},
{1, 4 }
};
bool gprof = false;
#ifdef GPROF
gprof = true;
#endif
while (true) {
plot->clear();
cout << "x: " << x << ", y: " << y << endl;
//auto vec0 =
//Sexp p = vm.protocol("galaxy");
Sexp p = vm.interact("galaxy", state, Vec(num(x), num(y)));
// Sexp p = vm.function(1141);
cout << "Start evaluating: " << str(p) << endl;
Sexp result = eval(p);
cout << "p = " << result << endl;
state = call(Car(), result);
plot->flush();
if (!bootstrap.empty()) {
auto it = bootstrap.begin();;
x = it->first;
y = it->second;
bootstrap.pop_front();
} else {
if (gprof) {
cout << "quitting for gprof." << endl;
return 0;
}
cout << "listening" << endl;
string response = plot->read();
cout << "from plotter: " << response << endl;
istringstream iss(response);
string cmd;
iss >> cmd >> x >> y;
}
}
return 0;
}
Sexp joinGame(Sexp playerKey) {
cout << "Join: " << playerKey << endl;
Sexp joinRequest = List(num(2), playerKey, NIL);
cout << "Join Request: " << joinRequest << endl;
// send it to aliens and get the GameResponse
Sexp gameResponse = call(SEND, joinRequest);
cout << "Join respones: " << gameResponse << endl;
return gameResponse;
}
Sexp startGame(Sexp playerKey, Sexp gameState) {
GameResponse game(gameState);
int fuel = 300; // OK: 300, NG: 500
int snd = 1;
int third = 1; // larger one consumes fewer fuel.
int forth = 1;
if (!localMode || game.role() == 0) {
/*
snd = 10;
third = 7; // OK: 10
forth = 5; // OK: 10
*/
snd = 10;
third = 11; // OK: 11, NG: 16
forth = 5; // OK: 10
}
if (eval(game.staticGameInfo())->isNil()) {
fuel = 100;
snd = 8;
third = 16;
forth = 32;
}
// make valid START request using the provided playerKey and gameResponse returned from JOIN
Sexp startParam = List(num(fuel),
num(snd),
num(third),
num(forth));
Sexp startRequest = List(num(3), playerKey, startParam);
cout << "Start Request: " << startRequest << endl;
// send it to aliens and get the updated GameResponse
Sexp startResponse = call(SEND, startRequest);
cout << "Start response: " << startResponse << endl;
return startResponse;
}
int runBot() {
cout << "Run bot" << endl;
cout << "player key:" << playerKeyStr << endl;
Sexp playerKey = num(bint(playerKeyStr));
Sexp gameResponse = joinGame(playerKey);
if (!checkGame(gameResponse)) {
cout << "Failed to join game." << endl;
return 0;
}
Sexp info = GameResponse(gameResponse).staticGameInfo();
cout << "***" << endl;
cout << "Static Game Info: " << info << endl;
cout << "***" << endl;
gameResponse = startGame(playerKey, gameResponse);
if (!checkGame(gameResponse)) {
cout << "Failed to start game: " << gameResponse << endl;
return 0;
}
cout << "Game Response: " << gameResponse << endl;
if (apiKey != "" && GameResponse(gameResponse).role() == 0) {
// local test.
cout << "Enable plotter" << endl;
plot.reset(new Plot());
}
Bot bot(playerKey);
while (true) {
GameResponse game(gameResponse);
visualizeGame(game);
Sexp info = game.staticGameInfo();
Sexp state = game.gameState();
cout << "OK: " << game.ok() << endl;
cout << "Tick: " << game.gameTick() << endl;
cout << "?State: " << nth(state, 1) << endl;
for (const Ship& s : game.ships()) {
cout << " " << s.toString() << endl;
}
if (!game.ok()) {
cerr << "Fail?" << endl;
cerr << " stage: " << game.gameState() << endl;
break;
}
if (game.gameStage() != 1) {
cerr << "Finished" << endl;
break;
}
Sexp cmd = bot.command(game);
Sexp commandRequest = List(num(4), playerKey, List(cmd));
gameResponse = call(SEND, commandRequest);
cout << "game respones: " << gameResponse << endl;
}
return 0;
}
int communicate() {
post("/aliens/send", modImpl(num(0)));
return 0;
}
int main(int argc, char* argv[]) {
const string galaxy = "../data/galaxy.txt";
if (argc < 3) {
cerr << argv[0] << "<server> <key>" << endl;
return 1;
}
/*
cout << "eval..." << endl;
cout << "mod: " << modNum( bint("3167558396624468277")) << endl;
cout << "mod-old: " << modNumOld(bint("3167558396624468277")) << endl;
cout << "dem: " << dem(modNum( bint("3167558396624468277"))) << endl;
cout << "dem-old: " << dem(modNumOld(bint("3167558396624468277"))) << endl;
cout << "mod: " << modNum( bint("16")) << endl;
cout << "mod-old: " << modNumOld(bint("16")) << endl;
cout << "dem: " << dem(modNum( bint("16"))) << endl;
cout << "dem-old: " << dem(modNumOld(bint("16"))) << endl;
cout << "mod: " << modNum( bint("147")) << endl;
cout << "mod-old: " << modNumOld(bint("147")) << endl;
cout << "dem: " << dem(modNum( bint("147"))) << endl;
cout << "dem-old: " << dem(modNumOld(bint("147"))) << endl;
*/
parseArgv(argc, argv);
if (argc == 3) {
return runBot();
}
if (playerKeyStr == "galaxy") {
return runLocal(galaxy);
}
return runBot();
}
| 11,477 | 4,571 |
#ifndef QUADMATERIAL_HPP_
#define QUADMATERIAL_HPP_
#include "textures/BitmapTexture.hpp"
#include "bsdfs/Bsdf.hpp"
#include "math/Box.hpp"
#include "math/Vec.hpp"
#include <memory>
namespace Tungsten {
namespace MinecraftLoader {
struct QuadMaterial
{
std::shared_ptr<Bsdf> bsdf;
std::shared_ptr<Bsdf> emitterBsdf;
Box2f opaqueBounds;
Box2f emitterOpaqueBounds;
std::shared_ptr<BitmapTexture> emission;
float primaryScale, secondaryScale;
float sampleWeight;
};
}
}
#endif /* QUADMATERIAL_HPP_ */
| 536 | 215 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <stdlib.h>
#include "callee_in_c.h"
void call_set_field_three_Ok(int* p) {
struct s x;
x.a = 5;
set_field_three(&x);
if (x.a == 5) {
free(p);
*p = 3;
}
}
| 371 | 152 |
/* Copyright (c) 2021. kms1212(Minsu Kwon)
This file is part of OpenFSL.
OpenFSL and its source code is published over BSD 3-Clause License.
See the BSD-3-Clause for more details.
<https://raw.githubusercontent.com/kms1212/OpenFSL/main/LICENSE>
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <codecvt>
#include <bitset>
#include "openfsl/fslutils.h"
#include "openfsl/fileblockdevice.h"
#include "openfsl/sector.h"
#include "openfsl/fat32/fs_fat32.h"
int readCount = 0;
int writeCount = 0;
size_t split(const std::string &txt, std::vector<std::string>* strs, char ch);
void hexdump(uint8_t* p, size_t offset, size_t len);
std::fstream disk;
int main(int argc, char** argv) {
if (argc != 3) {
std::cout << "usage: " << argv[0] << " [image_file] [test_name]";
return 1;
}
std::string imageFileName = std::string(argv[1]);
std::string testName = std::string(argv[2]);
disk.open(imageFileName, std::ios::in | std::ios::out | std::ios::binary);
openfsl::FileBlockDevice bd;
std::cout << "Reading image file parameter...\n";
std::fstream diskInfo;
diskInfo.open(imageFileName + ".info", std::ios::in);
if (!diskInfo.fail()) {
std::string line;
openfsl::BlockDevice::DiskParameter parameter;
while (getline(diskInfo, line)) {
std::cout << line << "\n";
std::vector<std::string> value;
split(line, &value, ' ');
if (value[0] == "SectorPerTrack") {
parameter.sectorPerTrack = stoi(value[1]);
} else if (value[0] == "HeadPerCylinder") {
parameter.headPerCylinder = stoi(value[1]);
} else if (value[0] == "BytesPerSector") {
parameter.bytesPerSector = stoi(value[1]);
}
}
bd.setDiskParameter(parameter);
diskInfo.close();
} else {
std::cout << "Fail to read disk parameter file. ";
std::cout << "Default values are will be used.\n";
}
bd.initialize(imageFileName, openfsl::FileBlockDevice::OpenMode::RW);
openfsl::FAT32 fat32(&bd, "", "\\/");
error_t result = fat32.initialize();
if (result) {
disk.close();
return result;
}
fat32.enableCache(512);
/////////////////////////////////////////////
// CHDIR TEST
/////////////////////////////////////////////
std::cout << "===========================\n";
std::cout << " CHDIR TEST\n";
std::cout << "===========================\n";
std::vector<std::string> chdirChecklist; // Checklist
chdirChecklist.push_back("::/.");
chdirChecklist.push_back("::/..");
chdirChecklist.push_back("::/directory1");
chdirChecklist.push_back("subdir1");
chdirChecklist.push_back("::");
chdirChecklist.push_back("directory1/subdir2");
chdirChecklist.push_back("../..");
chdirChecklist.push_back("directory9");
for (size_t i = 0; i < chdirChecklist.size(); i++) {
fat32.changeDirectory(chdirChecklist.at(i));
std::cout << "chdir(\"" << chdirChecklist.at(i) << "\") -> "
<< fat32.getPath() << "\n";
}
/////////////////////////////////////////////
// GETDIRLIST TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " GETDIRLIST TEST\n";
std::cout << "===========================\n";
std::vector<std::string> listDirChecklistDir; // Checklist directories
std::vector<std::vector<std::string>> listDirChecklist; // Checklist
std::vector<std::string> listDirChecklistChilds; // Checklist childs list
listDirChecklistDir.push_back("::"); // Directory ::
listDirChecklistChilds.push_back("DIRECTORY1");
listDirChecklistChilds.push_back("DIRECTORY2");
listDirChecklistChilds.push_back("DIRECTORY3");
listDirChecklistChilds.push_back("DIRECTORY4");
listDirChecklistChilds.push_back("DIRECTORY5");
listDirChecklistChilds.push_back("DIRECTORY6");
listDirChecklistChilds.push_back("DIRECTORY7");
listDirChecklistChilds.push_back("DIRECTORY8");
listDirChecklistChilds.push_back("FILE1.TXT");
listDirChecklistChilds.push_back("FILE2.TXT");
listDirChecklistChilds.push_back("FILE3.TXT");
listDirChecklistChilds.push_back("FILE4.TXT");
listDirChecklistChilds.push_back("FILE5.TXT");
listDirChecklistChilds.push_back("FILE6.TXT");
listDirChecklistChilds.push_back("FILE7.TXT");
listDirChecklistChilds.push_back("FILE8.TXT");
listDirChecklistChilds.push_back("LFNFILENAME1.TXT");
listDirChecklistChilds.push_back("LFNFILENAME2.TXT");
listDirChecklistChilds.push_back("LFNFILENAME3.TXT");
listDirChecklistChilds.push_back("LFNFILENAME4.TXT");
listDirChecklistChilds.push_back("DIRECTORY9");
listDirChecklist.push_back(listDirChecklistChilds);
listDirChecklistChilds.clear();
listDirChecklistDir.push_back("::/directory1"); // Directory ::/directory1
listDirChecklistChilds.push_back(".");
listDirChecklistChilds.push_back("..");
listDirChecklistChilds.push_back("SUBDIR1");
listDirChecklistChilds.push_back("SUBDIR2");
listDirChecklistChilds.push_back("SUBDIR3");
listDirChecklistChilds.push_back("SUBDIR4");
listDirChecklist.push_back(listDirChecklistChilds);
for (size_t j = 0; j < listDirChecklist.size(); j++) {
int result_temp;
fat32.changeDirectory(listDirChecklistDir.at(j));
std::vector<openfsl::FAT32::FileInfo> buf;
fat32.listDirectory(&buf);
result_temp = buf.size() != listDirChecklist.at(j).size();
result += result_temp;
std::cout << "(dirList.size() = " << buf.size()
<< ") != (dirChild.size() = " << listDirChecklist.at(j).size()
<< ") Returns : " << result_temp << "\n";
std::string filename;
for (uint32_t i = 0; i < buf.size(); i++) {
std::cout << buf[i].fileName << ": ";
filename = buf[i].fileName;
for (auto& c : filename) c = static_cast<char>(toupper(c));
if (find(listDirChecklist.at(j).begin(),
listDirChecklist.at(j).end(), filename) ==
listDirChecklist.at(j).end()) {
std::cout << "not found\n";
result++;
} else {
std::cout << "found\n";
}
}
}
/////////////////////////////////////////////
// GETFILEINFORMATION TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " GETFILEINFORMATION TEST\n";
std::cout << "===========================\n";
std::vector<std::string> finfoChecklist; // Checklist
finfoChecklist.push_back("::/file1.txt");
finfoChecklist.push_back("::/file2.txt");
finfoChecklist.push_back("::/file3.txt");
finfoChecklist.push_back("::/file4.txt");
finfoChecklist.push_back("::/file5.txt");
finfoChecklist.push_back("::/file6.txt");
finfoChecklist.push_back("::/file7.txt");
finfoChecklist.push_back("::/file8.txt");
finfoChecklist.push_back("::/lfnfilename1.txt");
finfoChecklist.push_back("::/lfnfilename2.txt");
finfoChecklist.push_back("::/lfnfilename3.txt");
finfoChecklist.push_back("::/lfnfilename4.txt");
for (size_t i = 0; i < finfoChecklist.size(); i++) {
std::pair<error_t, openfsl::FAT32::FileInfo> fileInfo =
fat32.getEntryInfo(finfoChecklist.at(i));
if (fileInfo.first) {
result++;
break;
}
std::cout << "getFileInformation(\"" << finfoChecklist.at(i)
<< "\") Returns : \n";
std::cout << " File Name: " << fileInfo.second.fileName << "\n";
std::cout << " File Created Time: "
<< fileInfo.second.fileCreateTime.time_month << "/"
<< fileInfo.second.fileCreateTime.time_day << "/"
<< fileInfo.second.fileCreateTime.time_year << " "
<< fileInfo.second.fileCreateTime.time_hour << ":"
<< fileInfo.second.fileCreateTime.time_min << ":"
<< fileInfo.second.fileCreateTime.time_sec << "."
<< fileInfo.second.fileCreateTime.time_millis << "\n";
std::cout << " File Access Time: "
<< fileInfo.second.fileAccessTime.time_month << "/"
<< fileInfo.second.fileAccessTime.time_day << "/"
<< fileInfo.second.fileAccessTime.time_year << " "
<< fileInfo.second.fileAccessTime.time_hour << ":"
<< fileInfo.second.fileAccessTime.time_min << ":"
<< fileInfo.second.fileAccessTime.time_sec << "."
<< fileInfo.second.fileAccessTime.time_millis << "\n";
std::cout << " File Mod Time: "
<< fileInfo.second.fileModTime.time_month << "/"
<< fileInfo.second.fileModTime.time_day << "/"
<< fileInfo.second.fileModTime.time_year << " "
<< fileInfo.second.fileModTime.time_hour << ":"
<< fileInfo.second.fileModTime.time_min << ":"
<< fileInfo.second.fileModTime.time_sec << "."
<< fileInfo.second.fileModTime.time_millis << "\n";
std::cout << " File Location: " << fileInfo.second.fileLocation << "\n";
std::cout << " File Size: " << fileInfo.second.fileSize << "\n";
std::stringstream ss;
ss << std::hex << (unsigned int)fileInfo.second.fileAttr;
std::cout << " File Attribute: 0x" << ss.str() << "\n";
}
/////////////////////////////////////////////
// FILE TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " FILE TEST\n";
std::cout << "===========================\n";
std::vector<std::string> fileChecklist; // Checklist
fileChecklist.push_back("::/file1.txt");
fileChecklist.push_back("::/file2.txt");
fileChecklist.push_back("::/file3.txt");
fileChecklist.push_back("::/file4.txt");
fileChecklist.push_back("::/file5.txt");
fileChecklist.push_back("::/file6.txt");
fileChecklist.push_back("::/file7.txt");
fileChecklist.push_back("::/file8.txt");
fileChecklist.push_back("::/lfnfilename1.txt");
fileChecklist.push_back("::/lfnfilename2.txt");
fileChecklist.push_back("::/lfnfilename3.txt");
fileChecklist.push_back("::/lfnfilename4.txt");
for (size_t i = 0; i < fileChecklist.size(); i++) {
std::cout << "Filename: " << finfoChecklist.at(i) << "\n";
openfsl::FAT32::FILE file(&fat32);
if (file.open(fileChecklist.at(i), openfsl::FSL_OpenMode::Read)) {
result++;
continue;
}
std::cout << "openFile(\"" << finfoChecklist.at(i) << "\")\n";
file.seekg(0, openfsl::FSL_SeekMode::SeekEnd);
size_t fileSize = file.tellg();
file.seekg(0, openfsl::FSL_SeekMode::SeekSet);
char* buf = new char[fileSize + 1]();
memset(buf, 0, fileSize + 1);
file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize);
buf[fileSize] = 0;
std::string buf_s(buf);
std::string comp_s("Hello, World!\nOpenFSL\n");
std::cout << "file.read() :\n";
std::cout << " Read: \n<" << buf_s << ">\n";
hexdump(reinterpret_cast<uint8_t*>(buf), 0, fileSize);
std::cout << "\n";
if (buf_s != comp_s) {
result++;
}
// Try to read file with seek
memset(buf, 0, fileSize + 1);
file.seekg(14, openfsl::FSL_SeekMode::SeekSet);
file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize - 14);
buf_s = std::string(buf);
comp_s = "OpenFSL\n";
std::cout << "file.seek(14) file.read() :\n";
std::cout << " Read: \n<" << buf_s << ">\n";
hexdump(reinterpret_cast<uint8_t*>(buf), 0, fileSize - 14);
if (buf_s != comp_s) {
result++;
}
// Try to read more than the size of file.
memset(buf, 0, fileSize + 1);
file.seekg(14, openfsl::FSL_SeekMode::SeekSet);
size_t ret = file.read(reinterpret_cast<uint8_t*>(buf), 1, fileSize);
if (ret != fileSize - 14)
result++;
std::cout << "file.seek(14) file.read() :\n";
std::cout << " Returned: " << ret << "\n";
file.close();
std::cout << "------------------------------\n";
}
/////////////////////////////////////////////
// MAKE DIRECTORY TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " MAKE DIRECTORY TEST\n";
std::cout << "===========================\n";
std::vector<std::string> mkDirChecklist; // Checklist
fileChecklist.push_back("::/mkdirtest1");
fileChecklist.push_back("::/mkdirtest2");
fileChecklist.push_back("::/SFNMKDIR.1");
fileChecklist.push_back("::/SFNMKDIR.2");
for (std::string dirname : mkDirChecklist) {
result += fat32.makeDirectory(dirname);
result += fat32.changeDirectory(dirname);
result += fat32.changeDirectory("..");
}
/////////////////////////////////////////////
// REMOVE DIRECTORY TEST
/////////////////////////////////////////////
std::cout << "\n\n";
std::cout << "===========================\n";
std::cout << " REMOVE DIRECTORY TEST\n";
std::cout << "===========================\n";
std::vector<std::string> rmDirChecklist; // Checklist
fileChecklist.push_back("::/mkdirtest1");
fileChecklist.push_back("::/mkdirtest2");
fileChecklist.push_back("::/SFNMKDIR.1");
fileChecklist.push_back("::/SFNMKDIR.2");
for (std::string dirname : rmDirChecklist) {
result += fat32.remove(dirname,
openfsl::FAT32::FileAttribute::Directory);
if (!fat32.changeDirectory(dirname))
result++;
}
std::cout << "Total read count: " << readCount << std::endl;
std::cout << "Total write count: " << writeCount << std::endl;
disk.close();
return result;
}
size_t split(const std::string &txt,
std::vector<std::string>* strs, char ch) {
std::string temp = txt;
size_t pos = temp.find(ch);
size_t initialPos = 0;
strs->clear();
// Decompose statement
while (pos != std::string::npos) {
if (temp.at(pos - 1) != '\\') {
strs->push_back(temp.substr(initialPos, pos - initialPos));
initialPos = pos + 1;
} else {
temp.erase(temp.begin() + pos - 1);
}
pos = temp.find(ch, pos + 1);
}
// Add the last one
strs->push_back(temp.substr(initialPos,
std::min(pos, temp.size()) - initialPos + 1));
return strs->size();
}
void hexdump(uint8_t* p, size_t offset, size_t len) {
std::ios init(nullptr);
init.copyfmt(std::cout);
size_t address = 0;
size_t row = 0;
std::cout << std::hex << std::setfill('0');
while (1) {
if (address >= len) break;
size_t nread = ((len - address) > 16) ? 16 : (len - address);
// Show the address
std::cout << std::setw(8) << address + offset;
// Show the hex codes
for (size_t i = 0; i < 16; i++) {
if (i % 8 == 0) std::cout << ' ';
if (i < nread)
std::cout << ' ' << std::setw(2)
<< static_cast<int>(p[16 * row + i + offset]);
else
std::cout << " ";
}
// Show printable characters
std::cout << " ";
for (size_t i = 0; i < nread; i++) {
uint8_t ch = p[16 * row + i + offset];
if (ch < 32 || ch > 125) std::cout << '.';
else
std::cout << ch;
}
std::cout << "\n";
address += 16;
row++;
}
std::cout.copyfmt(init);
}
| 16,129 | 5,462 |
#pragma once
#include "file.hpp"
#include "types.hpp"
namespace gold {
struct texture : public file {
protected:
static object& getPrototype();
public:
texture();
texture(file copy);
texture(path fpath);
texture(binary data);
var load(list args = {});
var bind(list args);
};
} // namespace gold | 320 | 117 |
#ifndef isnp_facility_component_SpallationTargetMessenger_hh
#define isnp_facility_component_SpallationTargetMessenger_hh
#include <memory>
#include <G4UImessenger.hh>
#include <G4UIdirectory.hh>
#include <G4UIcmdWithABool.hh>
#include <G4UIcmdWith3VectorAndUnit.hh>
#include "isnp/facility/component/SpallationTarget.hh"
namespace isnp {
namespace facility {
namespace component {
class SpallationTargetMessenger: public G4UImessenger {
public:
SpallationTargetMessenger(SpallationTarget& component);
~SpallationTargetMessenger() override;
G4String GetCurrentValue(G4UIcommand* command) override;
void SetNewValue(G4UIcommand*, G4String) override;
private:
SpallationTarget& component;
std::unique_ptr<G4UIdirectory> const directory;
std::unique_ptr<G4UIcmdWithABool> const hasCoolerCmd;
std::unique_ptr<G4UIcmdWith3VectorAndUnit> const rotationCmd, positionCmd;
};
}
}
}
#endif // isnp_facility_component_SpallationTargetMessenger_hh
| 959 | 348 |
#include <RayTracer/render.h>
int main(int, char**) {
render Render;
Render.init();
Render.process();
return 0;
}
| 136 | 53 |
//Example two, deleting a std::map
#include<iostream>
#include"memory_utils.h"
using namespace std;
class Test
{
public:
int id;
Test(int x)
{
this->id=x;
cout<<"Hello world! My name is Test "<<id<<endl;
}
~Test()
{
cout<<"Good bye friend... My name is Test "<<id<<endl;
}
};
void init_map(map<int, Test*>& ts, int n)
{
static int x=0;
for(int i=0; i<n; i++)
{
x++;
ts.insert(make_pair(i, new Test(x)));
}
}
int main()
{
map<int, Test*> t1;
map<int, Test*> t2;
map<int, Test*> t3;
cout<<"Initializing the t1..."<<endl;
init_map(t1, 5);
cout<<"Initializing the t2..."<<endl;
init_map(t2, 5);
cout<<"Initializing the t3..."<<endl;
init_map(t3, 5);
cout<<"Deleting map with a struct..."<<endl;
DeleteContainer dc;
dc(t1);
cout<<"Deleting with function..."<<endl;
_DeleteContainer(t2);
cout<<"Deleting with a for_each..."<<endl;
for_each(t3.begin(), t3.end(), DeleteMapObject());
return 0;
};
| 895 | 380 |
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "Graphics/Buffer/IGraphicsBuffer.h"
#include "Graphics/Render/Render.h"
#include "Graphics/State/ArrayBufferRenderState.h"
#include "Graphics/State/ElementArrayBufferRenderState.h"
#include "Graphics/State/RenderStateMachine.h"
#include "Graphics/Render/Render.h"
#include "Core/Log/Log.h"
#include "Rendering/RenderingStatics.h"
MEDUSA_BEGIN;
IGraphicsBuffer::IGraphicsBuffer(GraphicsBufferType bufferType,GraphicsBufferUsage usageType,GraphicsDataType dataType,uint componentCount,bool isNormlized/*=false*/)
:mUsageType(usageType),
mDataType(dataType),mComponentCount(componentCount),mIsNormlized(isNormlized)
{
mIsDataLoaded=false;
mBufferSize=0;
if (bufferType==GraphicsBufferType::Array)
{
mRenderState=new ArrayBufferRenderState();
}
else
{
mRenderState=new ElementArrayBufferRenderState();
}
}
IGraphicsBuffer::~IGraphicsBuffer(void)
{
DeleteObject();
SAFE_RELEASE(mRenderState);
}
bool IGraphicsBuffer::Initialize()
{
//GenObjcet();
return true;
}
bool IGraphicsBuffer::Uninitialize()
{
//DeleteObjcet();
return true;
}
void IGraphicsBuffer::GenObject()
{
if (mRenderState->Buffer() == 0)
{
uint buffer = Render::Instance().GenBuffer();
RenderingStatics::Instance().IncreaseBuffer();
mRenderState->SetBuffer(buffer);
}
}
void IGraphicsBuffer::DeleteObject()
{
if (mRenderState->Buffer() != 0)
{
Render::Instance().DeleteBuffer(mRenderState->Buffer());
RenderingStatics::Instance().DecreaseBuffer();
mRenderState->SetBuffer(0);
}
}
void IGraphicsBuffer::Bind( bool val )
{
if (val)
{
GenObject();
RenderStateMachine::Instance().Push(mRenderState);
//Render::Instance().BindBuffer(GetType(),renderState.GetBuffer());
}
else
{
RenderStateMachine::Instance().Pop(mRenderState);
//Render::Instance().BindBuffer(GetType(),0);
}
}
void IGraphicsBuffer::LoadBufferData( size_t size,void* data)
{
Render::Instance().LoadBufferData(GetType(),static_cast<uint>(size),data,UsageType());
RenderingStatics::Instance().CountGPUUploadSize(size);
mIsDataLoaded=true;
mBufferSize=size;
}
void IGraphicsBuffer::ModifyBufferSubData( size_t offset, size_t size, const void* data )
{
Log::AssertFormat(offset+size<=mBufferSize,"offset:{}+size:{}={} > buffer size:{}",(uint)offset,(uint)size,(uint)(offset+size),(uint)mBufferSize);
GenObject();
Render::Instance().ModifyBufferSubData(GetType(),static_cast<uint>(offset),static_cast<uint>(size),data);
RenderingStatics::Instance().CountGPUUploadSize(size);
}
void IGraphicsBuffer::SetDirtyRange( size_t minIndex,size_t maxIndex,size_t maxLimit )
{
mDirtyRange.ExpandRange(minIndex,maxIndex);
mDirtyRange.ShrinkMax(maxLimit);
}
void IGraphicsBuffer::LimitDirtyRange(size_t maxLimit)
{
mDirtyRange.ExpandMin(maxLimit);
mDirtyRange.ShrinkMax((uint)maxLimit);
}
void IGraphicsBuffer::CleanDirty()
{
mDirtyRange.Reset();
}
void IGraphicsBuffer::Apply()
{
Bind(true);
RETURN_IF_FALSE(IsDirty());
UpdateBufferData();
CleanDirty();
}
void IGraphicsBuffer::Restore()
{
Bind(false);
}
void IGraphicsBuffer::DrawArray( GraphicsDrawMode drawMode/*=GraphicsDrawMode::Triangles*/ ) const
{
DrawArray(drawMode,0,Count());
}
void IGraphicsBuffer::DrawArray( GraphicsDrawMode drawMode,int first,uint count ) const
{
Render::Instance().DrawArrays(drawMode,first,count);
}
void IGraphicsBuffer::DrawElements( GraphicsDrawMode drawMode/*=GraphicsDrawMode::Triangles*/ ) const
{
DrawElements(drawMode,Count(),mDataType,nullptr);
}
void IGraphicsBuffer::DrawElements( GraphicsDrawMode drawMode,uint count,GraphicsDataType dataType,const void* indices ) const
{
Render::Instance().DrawIndices(drawMode,count,dataType,indices);
}
MEDUSA_END; | 4,024 | 1,389 |
/*********************************************************************
** Author: Wei-Chien Hsu
** Date: 04/24/18
** Description: A class called Person that has two data members
- a string variable called name and a double variable called age.
It should have a constructor that takes two values and uses them to
initialize the data members.
It should have get methods for both data members (getName and getAge),
but doesn't need any set methods.
*********************************************************************/
#ifndef PERSON_HPP
#define PERSON_HPP
#include <string>
class Person {
private:
std::string name;
double age;
public:
Person();
Person(std::string, double);
std::string getName();
double getAge();
};
#endif | 869 | 215 |
#include "SelVertexCmd.h"
namespace ofx {
namespace piMapper {
SelVertexCmd::SelVertexCmd(SurfaceManager * sm, int i){
_surfaceManager = sm;
_newVertexIndex = i;
}
void SelVertexCmd::exec(){
_prevVertexIndex = _surfaceManager->getSelectedVertexIndex();
_surfaceManager->selectVertex(_newVertexIndex);
}
void SelVertexCmd::undo(){
ofLogNotice("SelVertexCmd", "undo");
_surfaceManager->selectVertex(_prevVertexIndex);
}
} // namespace piMapper
} // namespace ofx
| 473 | 160 |
#include <unistd.h>
#include <ctime>
#include <vector>
#include "sireen/file_utility.hpp"
#include "sireen/image_feature_extract.hpp"
/*
* Main
*/
int main(int argc, char * argv[]) {
/*********************************************
* Step 0 - optget to receive input option
*********************************************/
char result_buf[256]= "res/llc/caltech101.txt";
char codebook_buf[256]= "res/codebooks/caltech101/cbcaltech101.txt";
char image_dir_buf[256]= "res/images/caltech101";
/* CHECK THE INPUT OPTIONS */
//initialize the arg options
int opt;
while ((opt = getopt(argc, argv, "r:c:i:")) != -1) {
switch (opt) {
case 'r':
sprintf(result_buf, "%s", optarg);
break;
case 'c':
sprintf(codebook_buf, "%s", optarg);
break;
case 'i':
sprintf(image_dir_buf, "%s", optarg);
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [options]\n", argv[0]);
fprintf(stderr, " -i :PATH to image directory\n");
fprintf(stderr, " -r :PATH to result\n");
fprintf(stderr, " -c :PATH to codebook\n");
return -1;
}
}
/* CHECK END */
/*--------------------------------------------
* Path
--------------------------------------------*/
string result_path = string(result_buf);
string image_dir = string(image_dir_buf);
string codebook_path = string(codebook_buf);
/*--------------------------------------------
* PARAMETERS
--------------------------------------------*/
const int CB_SIZE = 500;
/*--------------------------------------------
* VARIABLE READ & WRITE CACHE
--------------------------------------------*/
FILE * outfile;
float *codebook = new float[128 * CB_SIZE];
//counter for reading lines;
unsigned int done=0;
// Initiation
ImageCoder icoder;
/*********************************************
* Step 1 - Loading & Check everything
*********************************************/
// 1. codebook validation
if (access(codebook_path.c_str(), 0)){
cerr << "codebook not found!" << endl;
return -1;
}
char delim[2] = ",";
futil::file_to_pointer(codebook_path.c_str(), codebook,delim);
if (codebook == NULL) {
cerr << "codebook error!" << endl;
return -1;
}
// 1. write file validation
outfile = fopen(result_path.c_str(), "wt+");
//if no file, error report
if ( NULL == outfile) {
cerr << "result file initialize problem!" << endl;
return -1;
}
vector<string> all_images;
string imgfile;
string llcstr;
futil::get_files_in_dir(all_images,image_dir);
/*********************************************
* Step 2 - Traverse the image directory
*********************************************/
clock_t start = clock();
for(unsigned int n = 0; n < all_images.size(); ++n)
{
// load image source to Mat format(opencv2.4.9)
// using the simple llcDescripter interface from
// ImageCoder
imgfile = all_images[n];
try
{
Mat src_image = imread(imgfile,0);
if(!src_image.data)
{
cout << "\tinvalid source image! --> " << imgfile << endl;
continue;
}
llcstr = icoder.llc_sift(src_image, codebook, CB_SIZE, 5);
// cout << llcstr << endl;
}
catch(...)
{
cout << "\tbroken image! --> " << imgfile << endl;
continue;
}
/*********************************************
* Step 4 - write result to file
*********************************************/
// correct file
fprintf(outfile, "%s\t", imgfile.c_str());
fprintf(outfile, "%s\n", llcstr.c_str());
// succeed count
done++;
// print info
if(done % 10== 0){
cout << "\t" << done << " Processed..." << endl;
}
}
cout << "\t" << done << " Processed...(done)"
<< " <Elasped Time: " << float(clock() -start)/CLOCKS_PER_SEC
<< "s>"<< endl;
delete codebook;
fclose(outfile);
}
| 4,323 | 1,342 |
///////////////////////////////////////////////////////////////////////////////
///
/// \file StringUtility.cpp
///
///
/// Authors: Chris Peters
/// Copyright 2013, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Zero
{
//---------------------------------------------------------------------- Strings
bool CaseInsensitiveStringLess(StringParam a, StringParam b)
{
StringRange achars = a.All();
StringRange bchars = b.All();
while(!achars.Empty() && !bchars.Empty())
{
Rune aChar = UTF8::ToLower(achars.Front());
Rune bChar = UTF8::ToLower(bchars.Front());
if(aChar < bChar)
return true;
if(aChar > bChar)
return false;
achars.PopFront();
bchars.PopFront();
}
if(achars.Empty() && !bchars.Empty())
return true;
return false;
}
Pair<StringRange,StringRange> SplitOnLast(StringRange input, Rune delimiter)
{
//With empty just return empty String
if(input.Empty())
return Pair<StringRange,StringRange>(input, input);
size_t numRunes = input.ComputeRuneCount();
StringRange lastOf = input.FindLastOf(delimiter);
// Delim found return string and empty
if(lastOf.Empty())
return Pair<StringRange,StringRange>(input, StringRange());
if(lastOf.SizeInBytes() == 0)
return Pair<StringRange, StringRange>(StringRange(), input.SubString(input.Begin(), input.End()));
if(lastOf.SizeInBytes() == numRunes - 1)
return Pair<StringRange, StringRange>(input.SubString(input.Begin(), input.End()), StringRange());
return Pair<StringRange, StringRange>(input.SubString(input.Begin(), lastOf.End()), input.SubString(lastOf.Begin() + 1, lastOf.End()));
}
Pair<StringRange,StringRange> SplitOnFirst(StringRange input, Rune delimiter)
{
StringTokenRange tokenRange(input, delimiter);
StringRange left = tokenRange.Front();
StringRange right = StringRange(left.End(), input.End());
return Pair<StringRange, StringRange>(left, right);
}
StringRange StripBeforeLast(StringRange input, Rune delimiter)
{
Pair<StringRange, StringRange> split = SplitOnLast(input, delimiter);
// If the delimiter was not found the second will be empty
if(split.second.Empty())
return input;
else
return split.second;
}
String JoinStrings(const Array<String>& strings, StringParam delimiter)
{
StringBuilder builder;
for (size_t i = 0; i < strings.Size(); ++i)
{
const String& string = strings[i];
builder.Append(string);
bool isNotLast = (i + 1 != strings.Size());
if (isNotLast)
{
builder.Append(delimiter);
}
}
return builder.ToString();
}
char OnlyAlphaNumeric(char c)
{
if (!isalnum(c))
return '_';
else
return c;
}
//******************************************************************************
// Recursive helper for global string Permute below
static void PermuteRecursive(char *src, size_t start, size_t end, Array<String>& perms)
{
// finished a permutation, add it to the list
if (start == end)
{
perms.PushBack(src);
return;
}
for (size_t i = start; i < end; ++i)
{
// swap to get new head
Swap(src[start], src[i]);
// permute
PermuteRecursive(src, start + 1, end, perms);
// backtrack
Swap(src[start], src[i]);
}
}
//******************************************************************************
void Permute(StringParam src, Array<String>& perms)
{
// convert to std string which is char writable
size_t srclen = src.SizeInBytes();
// create a temp buffer on the stack to manipulate src
char *buf = (char *)alloca(srclen + 1);
memset(buf, 0, srclen + 1);
// recursively calculate permutations
PermuteRecursive(buf, 0, srclen, perms);
}
//******************************************************************************
void SuperPermute(StringParam src, Array<String>& perms)
{
// convert to std string which is char writable
size_t srclen = src.SizeInBytes();
const char *csrc = src.c_str();
// create a temp buffer on the stack to manipulate src
char *buf = (char *)alloca(srclen + 1);
memset(buf, 0, srclen + 1);
// push the individual elements of the source
StringRange srcRange = src;
for (; !srcRange.Empty(); srcRange.PopFront())
perms.PushBack(String(srcRange.Front()));
for (uint l = 1; l < srclen; ++l)
{
for (uint i = 0; i + l < srclen; ++i)
{
// initialize buffer
memcpy(buf, csrc + i, l);
for (uint j = i + l; j < srclen; ++j)
{
buf[l] = csrc[j];
PermuteRecursive(buf, 0, l + 1, perms);
buf[l] = '\0';
}
}
}
}
}//namespace Zero
| 4,854 | 1,599 |
/** Derived from DTGeometryAnalyzer by Nicola Amapane
*
* \author M. Maggi - INFN Bari
*/
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "Geometry/GEMGeometry/interface/ME0Geometry.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "Geometry/GEMGeometry/interface/ME0EtaPartitionSpecs.h"
#include "Geometry/CommonTopologies/interface/StripTopology.h"
#include "DataFormats/Math/interface/deltaPhi.h"
#include <memory>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <iomanip>
#include <set>
class ME0GeometryAnalyzer10EtaPart : public edm::one::EDAnalyzer<>
{
public:
ME0GeometryAnalyzer10EtaPart( const edm::ParameterSet& pset);
~ME0GeometryAnalyzer10EtaPart() override;
void beginJob() override {}
void analyze(edm::Event const& iEvent, edm::EventSetup const&) override;
void endJob() override {}
private:
const std::string& myName() { return myName_;}
const int dashedLineWidth_;
const std::string dashedLine_;
const std::string myName_;
std::ofstream ofos;
};
using namespace std;
ME0GeometryAnalyzer10EtaPart::ME0GeometryAnalyzer10EtaPart( const edm::ParameterSet& /*iConfig*/ )
: dashedLineWidth_(104), dashedLine_( string(dashedLineWidth_, '-') ),
myName_( "ME0GeometryAnalyzer10EtaPart" )
{
ofos.open("ME0testOutput10EtaPart.out");
ofos <<"======================== Opening output file"<< endl;
}
ME0GeometryAnalyzer10EtaPart::~ME0GeometryAnalyzer10EtaPart()
{
ofos.close();
ofos <<"======================== Closing output file"<< endl;
}
void
ME0GeometryAnalyzer10EtaPart::analyze( const edm::Event& /*iEvent*/, const edm::EventSetup& iSetup )
{
edm::ESHandle<ME0Geometry> pDD;
iSetup.get<MuonGeometryRecord>().get(pDD);
ofos << myName() << ": Analyzer..." << endl;
ofos << "start " << dashedLine_ << endl;
ofos << " Geometry node for ME0Geom is " << &(*pDD) << endl;
ofos << " detTypes \t" <<pDD->detTypes().size() << endl;
ofos << " GeomDetUnit \t" <<pDD->detUnits().size() << endl;
ofos << " GeomDet \t" <<pDD->dets().size() << endl;
ofos << " GeomDetUnit DetIds\t" <<pDD->detUnitIds().size() << endl;
ofos << " eta partitions \t" <<pDD->etaPartitions().size() << endl;
ofos << " layers \t" <<pDD->layers().size() << endl;
ofos << " chambers \t" <<pDD->chambers().size() << endl;
// ofos << " regions \t" <<pDD->regions().size() << endl;
// checking uniqueness of roll detIds
bool flagNonUniqueRollID = false;
bool flagNonUniqueRollRawID = false;
int nstrips = 0;
int npads = 0;
for (auto roll1 : pDD->etaPartitions()){
nstrips += roll1->nstrips();
npads += roll1->npads();
for (auto roll2 : pDD->etaPartitions()){
if (roll1 != roll2){
if (roll1->id() == roll2->id()) flagNonUniqueRollID = true;
if (roll1->id().rawId() == roll2->id().rawId()) flagNonUniqueRollRawID = true;
}
}
}
if (flagNonUniqueRollID or flagNonUniqueRollRawID)
ofos << " -- WARNING: non unique roll Ids!!!" << endl;
// checking uniqueness of layer detIds
bool flagNonUniqueLaID = false;
bool flagNonUniqueLaRawID = false;
for (auto la1 : pDD->layers()){
for (auto la2 : pDD->layers()){
if (la1 != la2){
if (la1->id() == la2->id()) flagNonUniqueLaID = true;
if (la1->id().rawId() == la2->id().rawId()) flagNonUniqueLaRawID = true;
}
}
}
if (flagNonUniqueLaID or flagNonUniqueLaRawID)
ofos << " -- WARNING: non unique layer Ids!!!" << endl;
// checking uniqueness of chamber detIds
bool flagNonUniqueChID = false;
bool flagNonUniqueChRawID = false;
for (auto ch1 : pDD->chambers()){
for (auto ch2 : pDD->chambers()){
if (ch1 != ch2){
if (ch1->id() == ch2->id()) flagNonUniqueChID = true;
if (ch1->id().rawId() == ch2->id().rawId()) flagNonUniqueChRawID = true;
}
}
}
if (flagNonUniqueChID or flagNonUniqueChRawID)
ofos << " -- WARNING: non unique chamber Ids!!!" << endl;
// print out number of strips and pads
ofos << " total number of strips\t"<<nstrips << endl;
ofos << " total number of pads \t"<<npads << endl;
ofos << myName() << ": Begin iteration over geometry..." << endl;
ofos << "iter " << dashedLine_ << endl;
ofos << myName() << "Begin ME0Geometry TEST" << endl;
/*
* possible checklist for an eta partition:
* base_bottom, base_top, height, strips, pads
* cx, cy, cz, ceta, cphi
* tx, ty, tz, teta, tphi
* bx, by, bz, beta, bphi
* pitch center, pitch bottom, pitch top
* deta, dphi
* gap thicess
* sum of all dx + gap = chamber height
*/
int i = 1;
for (auto ch : pDD->chambers()){
ME0DetId chId(ch->id());
int nLayers(ch->nLayers());
ofos << "\tME0Chamber " << i << ", ME0DetId = " << chId.rawId() << ", " << chId << " has " << nLayers << " layers." << endl;
int j = 1;
for (auto la : ch->layers()){
ME0DetId laId(la->id());
int nRolls(la->nEtaPartitions());
ofos << "\t\tME0Layer " << j << ", ME0DetId = " << laId.rawId() << ", " << laId << " has " << nRolls << " eta partitions." << endl;
int k = 1;
auto& rolls(la->etaPartitions());
for (auto roll : rolls){
// for (auto roll : pDD->etaPartitions()){
ME0DetId rId(roll->id());
ofos<<"\t\t\tME0EtaPartition " << k << " , ME0DetId = " << rId.rawId() << ", " << rId << endl;
const BoundPlane& bSurface(roll->surface());
const StripTopology* topology(&(roll->specificTopology()));
// base_bottom, base_top, height, strips, pads (all half length)
auto& parameters(roll->specs()->parameters());
float bottomEdge(parameters[0]);
float topEdge(parameters[1]);
float height(parameters[2]);
float nStrips(parameters[3]);
float nPads(parameters[4]);
LocalPoint lCentre( 0., 0., 0. );
GlobalPoint gCentre(bSurface.toGlobal(lCentre));
LocalPoint lTop( 0., height, 0.);
GlobalPoint gTop(bSurface.toGlobal(lTop));
LocalPoint lBottom( 0., -height, 0.);
GlobalPoint gBottom(bSurface.toGlobal(lBottom));
// gx, gy, gz, geta, gphi (center)
double cx(gCentre.x());
double cy(gCentre.y());
double cz(gCentre.z());
double ceta(gCentre.eta());
int cphi(static_cast<int>(gCentre.phi().degrees()));
if (cphi < 0) cphi += 360;
double tx(gTop.x());
double ty(gTop.y());
double tz(gTop.z());
double teta(gTop.eta());
int tphi(static_cast<int>(gTop.phi().degrees()));
if (tphi < 0) tphi += 360;
double bx(gBottom.x());
double by(gBottom.y());
double bz(gBottom.z());
double beta(gBottom.eta());
int bphi(static_cast<int>(gBottom.phi().degrees()));
if (bphi < 0) bphi += 360;
// pitch bottom, pitch top, pitch centre
float pitch(roll->pitch());
float topPitch(roll->localPitch(lTop));
float bottomPitch(roll->localPitch(lBottom));
// Type - should be GHA0[1-nRolls]
string type(roll->type().name());
// print info about edges
LocalPoint lEdge1(topology->localPosition(0.));
LocalPoint lEdgeN(topology->localPosition((float)nStrips));
double cstrip1(roll->toGlobal(lEdge1).phi().degrees());
double cstripN(roll->toGlobal(lEdgeN).phi().degrees());
double dphi(cstripN - cstrip1);
if (dphi < 0.) dphi += 360.;
double deta(abs(beta - teta));
const bool printDetails(true);
if (printDetails)
ofos << "\t\t\t\tType: " << type << endl
<< "\t\t\t\tDimensions[cm]: b = " << bottomEdge*2 << ", B = " << topEdge*2 << ", H = " << height*2 << endl
<< "\t\t\t\tnStrips = " << nStrips << ", nPads = " << nPads << endl
<< "\t\t\t\ttop(x,y,z)[cm] = (" << tx << ", " << ty << ", " << tz << "), top (eta,phi) = (" << teta << ", " << tphi << ")" << endl
<< "\t\t\t\tcenter(x,y,z) = (" << cx << ", " << cy << ", " << cz << "), center(eta,phi) = (" << ceta << ", " << cphi << ")" << endl
<< "\t\t\t\tbottom(x,y,z) = (" << bx << ", " << by << ", " << bz << "), bottom(eta,phi) = (" << beta << ", " << bphi << ")" << endl
<< "\t\t\t\tpitch (top,center,bottom) = " << topPitch << " " << pitch << " " << bottomPitch << ", dEta = " << deta << ", dPhi = " << dphi << endl
<< "\t\t\t\tlocal pos at strip 1 " << lEdge1 << " strip N " << lEdgeN << endl;
++k;
} ++j;
} ++i;
}
ofos << dashedLine_ << " end" << endl;
}
//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(ME0GeometryAnalyzer10EtaPart);
| 8,745 | 3,396 |
#include "player.h"
#include "raylib.h"
#include <iostream>
bool player::moveTo(const Vector2 & dest)
{
std::cout << "player moving" << std::endl;
return false;
}
void player::takeDamage(int damage)
{
if (health >= 0)
{
health -= damage;
death = false;
}
else
{
death = true;
}
}
player::player(const std::string & fileName)
{
std::cout << "Creating sprite!" << std::endl;
mySprite = LoadTexture(fileName.c_str());
}
player::player()
{
}
player::~player()
{
std::cout << "Destroying sprite!" << std::endl;
UnloadTexture(mySprite);
}
void player::draw(Color h)
{
DrawTexture(mySprite, 375, 225, h);
}
| 628 | 265 |
#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
int main() {
fastio;
int C, n, a, b, c, i;
long long m = 0;
cin >> C >> n;
for (i = 1; i <= n; ++i) {
cin >> a >> b >> c;
if (m < a) {
break;
}
m += b - a;
if (m > C) {
break;
}
if (c > 0 && m != C) {
break;
}
}
cout << (i == n + 1 && m == 0 ? "possible" : "impossible");
return 0;
} | 527 | 214 |
#include <iostream>
#include "../srrg_data_structures/platform.h"
#include "srrg_geometry/geometry3d.h"
using namespace srrg2_core;
int32_t main() {
//ds check events
JointEventPtr event_t0(new JointEvent(0, "j0", 0));
JointEventPtr event_t1(new JointEvent(1, "j0", 100));
JointEventPtr event_t2(new JointEvent(2, "j0", 103));
if (event_t0 < event_t1) {
std::cerr << "event t=0 is earlier than event t=1" << std::endl;
} else {
std::cerr << "event t=1 is earlier than event t=0" << std::endl;
}
if (event_t2 > event_t1) {
std::cerr << "event t=2 is older than event t=1" << std::endl;
} else {
std::cerr << "event t=1 is older than event t=2" << std::endl;
}
std::cerr << "copying event_t1 into event_t3: fields" << std::endl;
JointEventPtr event_t3 = event_t1;
std::cerr << "event_t3: " << event_t3->timeSeconds() << " = " << event_t1->timeSeconds() << std::endl;
std::cerr << "event_t3: " << event_t3->position() << " = " << event_t1->position() << std::endl;
std::cerr << "copying event_t2 into event_t3: fields" << std::endl;
event_t3 = event_t2;
std::cerr << "event_t3: " << event_t3->timeSeconds() << " = " << event_t2->timeSeconds() << std::endl;
std::cerr << "event_t3: " << event_t3->position() << " = " << event_t2->position() << std::endl;
LinkWithJointPrismatic* prismatic_joint = new LinkWithJointPrismatic("jp0", Vector3f(1, 0, 0));
prismatic_joint->addEvent(event_t0);
prismatic_joint->addEvent(event_t1);
prismatic_joint->addEvent(event_t2);
std::cerr << "number of events in joint jp0: " << prismatic_joint->numberOfEvents() << std::endl;
std::cerr << "sampling" << std::endl;
prismatic_joint->sample(0);
std::cerr << "sampled distance (LinkWithJointPrismatic) at t=0s: " << prismatic_joint->sampledPosition() << std::endl;
prismatic_joint->sample(1.5);
std::cerr << "sampled distance (LinkWithJointPrismatic) at t=1.5s: " << prismatic_joint->sampledPosition() << std::endl;
prismatic_joint->sample(0.5);
std::cerr << "sampled distance (LinkWithJointPrismatic) at t=0.5s: " << prismatic_joint->sampledPosition() << std::endl;
LinkWithJointRotational* rotational_joint = new LinkWithJointRotational("jr0", Vector3f(0, 0, 1));
JointEventPtr event_rotational_t0(new JointEvent(0, "jr0", 0));
JointEventPtr event_rotational_t1(new JointEvent(1, "jr0", 1));
rotational_joint->addEvent(event_rotational_t0);
rotational_joint->addEvent(event_rotational_t1);
std::cerr << "number of events in joint jp0: " << rotational_joint->numberOfEvents() << std::endl;
rotational_joint->sample(0.5);
std::cerr << "sampled orientation (LinkWithJointRotational) at t=0.5s: "
<< rotational_joint->sampledPosition().w()
<< " " << rotational_joint->sampledPosition().x()
<< " " << rotational_joint->sampledPosition().y()
<< " " << rotational_joint->sampledPosition().z()
<< std::endl;
rotational_joint->sample(0.75);
std::cerr << "sampled orientation (LinkWithJointRotational) at t=0.75s: "
<< rotational_joint->sampledPosition().w()
<< " " << rotational_joint->sampledPosition().x()
<< " " << rotational_joint->sampledPosition().y()
<< " " << rotational_joint->sampledPosition().z()
<< std::endl;
delete prismatic_joint;
delete rotational_joint;
return 0;
}
| 3,386 | 1,271 |
// This file generated by ngrestcg
// For more information, please visit: https://github.com/loentar/ngrest
#include "user_manage.h"
#include "random_user.h"
#include "db_sqlite_user.h"
#include "Base64.h"
#include "picosha2.h"
#include <hiredis/hiredis.h>
register_resp user_manage::proc_register(const register_req &text)
{
register_resp ret;
std::string reg_name;
std::string hash_pwd;
picosha2::hash256_hex_string(text.reg_password, hash_pwd);
if (true == Base64::Decode(text.reg_name, ®_name))
{
auto db_ret = db_sqlite_insert_user(text.reg_number, hash_pwd, reg_name);
if (0 == db_ret)
ret = "success";
else if (1 == db_ret)
ret = "exit";
else
ret = "fail";
}
return ret;
}
login_resp user_manage::proc_login(const login_req& text)
{
login_resp ret = {"fail", ""};
std::string hash_pwd;
picosha2::hash256_hex_string(text.login_pwd, hash_pwd);
if (db_sqlite_query_user(text.login_id, hash_pwd))
{
auto ssid = db_sqlite_logon_user(text.login_id);
if (ssid.length() == 32)
{
ret.status = "success";
ret.ssid = ssid;
}
}
return ret;
}
hello_resp user_manage::proc_get_hello()
{
hello_resp ret = {"hello mvc"};
return ret;
}
login_random_resp user_manage::proc_login_random()
{
login_random_resp ret;
auto random_user_ssid = RandomUserGenerat();
if (random_user_ssid.length() >= 0)
{
ret.status = "success";
ret.type = "response";
ret.ssid = random_user_ssid;
}
return ret;
}
std::string get_string_from_redis(redisContext *_predis, std::string _command)
{
std::string ret = "";
auto preply = redisCommand(_predis, _command.c_str());
if (NULL != preply)
{
redisReply *stdreply = (redisReply *)preply;
if (REDIS_REPLY_STRING == stdreply->type)
{
ret.assign(stdreply->str, stdreply->len);
}
freeReplyObject(preply);
}
return ret;
}
get_user_info_resp user_manage::proc_get_user_info(std::string ssid)
{
get_user_info_resp ret = {"fail", "", ""};
redisContext *predis = redisConnect("localhost", 6379);
if (NULL != predis)
{
std::string command;
command = std::string("HGET user_ssid:") + ssid + " name";
Base64::Encode(get_string_from_redis(predis, command), &ret.name) ;
command = std::string("HGET user_ssid:") + ssid + " cash";
ret.cash = get_string_from_redis(predis, command);
if (ret.name.length() > 0 && ret.cash.length() > 0)
{
ret.status = "success";
}
redisFree(predis);
}
return ret;
}
std::string user_manage::proc_logoff(std::string ssid)
{
std::string ret = "fail";
redisContext *predis = redisConnect("localhost", 6379);
if (NULL != predis)
{
auto user_id = get_string_from_redis(predis, std::string("HGET user_ssid:") + ssid + " id");
freeReplyObject(redisCommand(predis, "DEL user_ssid:%s", ssid.c_str()));
freeReplyObject(redisCommand(predis, "DEL id:%s", user_id.c_str()));
redisFree(predis);
ret = "success";
}
return ret;
} | 3,259 | 1,196 |
// | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Ignasi de Pouplana
//
// Application includes
#include "custom_processes/automatic_dt_process.hpp"
namespace Kratos
{
/// this function is designed for being called at the beginning of the computations
/// right after reading the model and the groups
void AutomaticDTProcess::ExecuteBeforeSolutionLoop()
{
KRATOS_TRY;
ModelPart::ElementsContainerType& rElements = mrModelPart.GetCommunicator().LocalMesh().Elements();
const int NElems = static_cast<int>(rElements.size());
ModelPart::ElementsContainerType::ptr_iterator ptr_itElem_begin = rElements.ptr_begin();
// Find smallest particle
double min_radius = std::numeric_limits<double>::infinity();
SphericContinuumParticle* pSmallestDemElem = dynamic_cast<SphericContinuumParticle*>(ptr_itElem_begin->get());
for (int i = 0; i < NElems; i++) {
ModelPart::ElementsContainerType::ptr_iterator ptr_itElem = ptr_itElem_begin + i;
Element* p_element = ptr_itElem->get();
SphericContinuumParticle* pDemElem = dynamic_cast<SphericContinuumParticle*>(p_element);
const double radius = pDemElem->GetRadius();
if (radius < min_radius) {
pSmallestDemElem = pDemElem;
min_radius = radius;
}
}
// Calculate stiffness of the smallest particle with itself
double initial_dist = 2.0*min_radius;
double myYoung = pSmallestDemElem->GetYoung();
double myPoisson = pSmallestDemElem->GetPoisson();
double calculation_area = 0.0;
double kn_el = 0.0;
double kt_el = 0.0;
DEMContinuumConstitutiveLaw::Pointer NewContinuumConstitutiveLaw = pSmallestDemElem->GetProperties()[DEM_CONTINUUM_CONSTITUTIVE_LAW_POINTER]->Clone();
NewContinuumConstitutiveLaw->CalculateContactArea(min_radius, min_radius, calculation_area);
NewContinuumConstitutiveLaw->CalculateElasticConstants(kn_el, kt_el, initial_dist, myYoung, myPoisson, calculation_area, pSmallestDemElem, pSmallestDemElem);
// Calculate mass of the smallest particle
const double particle_density = pSmallestDemElem->GetDensity();
const double particle_volume = pSmallestDemElem->CalculateVolume();
const double min_mass = particle_volume * particle_density;
// Calculate critical delta time
const double critical_delta_time = std::sqrt(min_mass/kn_el);
mrModelPart.GetProcessInfo().SetValue(DELTA_TIME,mCorrectionFactor*critical_delta_time);
KRATOS_INFO("Automatic DT process") << "Calculated critical time step: " << critical_delta_time << " seconds." << std::endl;
KRATOS_INFO("Automatic DT process") << "Using a correction factor of: " << mCorrectionFactor << ", the resulting time step is: " << mCorrectionFactor*critical_delta_time << " seconds." << std::endl;
KRATOS_CATCH("");
}
///------------------------------------------------------------------------------------
} // namespace Kratos.
| 3,339 | 1,045 |
/**********************************************************************/
/** Microsoft Windows NT **/
/** Copyright(c) Microsoft Corp., 1991 **/
/**********************************************************************/
/*
bltdlgxp.hxx
Expandable dialog class declaration.
This class represents a standard BLT DIALOG_WINDOW which can
be expanded once to reveal new controls. All other operations
are common between EXPANDABLE_DIALOG and DIALOG_WINDOW.
To construct, provide the control ID of two controls: a "boundary"
static text control (SLT) and an "expand" button.
The "boundary" control is declared in the resource file as 2x2
units in size, containing no text, and has only the WS_CHILD style.
Its location marks the lower right corner of the reduced (initial)
size of the dialog. Controls lower and/or to the right of this
boundary "point" are disabled until the dialog is expanded.
The "expand" button is a normal two-state button which usually has
a title like "Options >>" to indicate that it changes the dialog.
EXPANDABLE_DIALOG handles the state transition entirely, and the
"expand" button is permanently disabled after the transition. In
other words, it's a one way street.
The virtual method OnExpand() is called when expansion takes place;
this can be overridden to initialize controls which have been
heretofor invisible. It's usually necessary to override the default
version of OnExpand() to set focus on whichever control you want,
since the control which had focus (the expand button) is now disabled.
There is one optional parameter to the constructor. It specifies a
distance, in dialog units. If the ShowArea() member finds that the
"boundary" control is within this distance of the real (.RC file)
border of the dialog, it will use the original border. This prevents
small (3-10 unit) errors caused by the inability to place a control
immediately against the dialog border.
FILE HISTORY:
DavidHov 11/1/91 Created
*/
#ifndef _BLTDLGXP_HXX_
#define _BLTDLGXP_HXX_
/*************************************************************************
NAME: EXPANDABLE_DIALOG
SYNOPSIS: A dialog whose initial state is small, and then expands
to reveal more controls. Two controls are special:
a "boundary" control which demarcates the
limits of the smaller initial state, and
an "expand" button which causes the dialog
to grow to its full size; the button is then
permanently disabled.
About the "cPxBoundary" parameter: if the distance from
the end of the boundary control to the edge of the dialog
is LESS than this value, the size of the original dialog
will be used for that dimension.
INTERFACE:
EXPANDABLE_DIALOG() -- constructor
~EXPANDABLE_DIALOG() -- destructor
Process() -- run the dialog
OnExpand() -- optional virtual routine
called when the dialog is
expanded. Default routine
just sets focus on OK button.
PARENT: DIALOG_WINDOW
USES: PUSH_BUTTON, SLT
CAVEATS: The expansion process is one-way; that is, the dialog
cannot be shrunk. The controlling button is permanently
disabled after the expansion.
NOTES:
HISTORY:
DavidHov 10/30/91 Created
**************************************************************************/
DLL_CLASS EXPANDABLE_DIALOG ;
#define EXP_MIN_USE_BOUNDARY 20
DLL_CLASS EXPANDABLE_DIALOG : public DIALOG_WINDOW
{
public:
EXPANDABLE_DIALOG
( const TCHAR * pszResourceName,
HWND hwndOwner,
CID cidBoundary,
CID cidExpandButn,
INT cPxBoundary = EXP_MIN_USE_BOUNDARY ) ;
~ EXPANDABLE_DIALOG () ;
// Overloaded 'Process' members for reducing initial dialog extent
APIERR Process ( UINT * pnRetVal = NULL ) ;
APIERR Process ( BOOL * pfRetVal ) ;
protected:
PUSH_BUTTON _butnExpand ; // The button which bloats
SLT _sltBoundary ; // The "point" marker
BOOL OnCommand ( const CONTROL_EVENT & event ) ;
// Virtual called when dialog is to be expanded.
virtual VOID OnExpand () ;
VOID ShowArea ( BOOL fFull ) ; // Change dialog size
private:
XYDIMENSION _xyOriginal ; // Original dlg box dimensions
INT _cPxBoundary ; // Limit to force original boundary
BOOL _fExpanded ; // Dialog is expanded
};
#endif // _BLTDLGXP_HXX_
| 4,593 | 1,516 |
#pragma once
#include "Maths/Vector3.hpp"
#include "Graphics/Buffers/Buffer.hpp"
#include "Resources/Resource.hpp"
namespace acid {
template<typename Base>
class ModelFactory {
public:
using TCreateReturn = std::shared_ptr<Base>;
using TCreateMethodNode = std::function<TCreateReturn(const Node &)>;
using TRegistryMapNode = std::unordered_map<std::string, TCreateMethodNode>;
using TCreateMethodFilename = std::function<TCreateReturn(const std::filesystem::path &)>;
using TRegistryMapFilename = std::unordered_map<std::string, TCreateMethodFilename>;
virtual ~ModelFactory() = default;
/**
* Creates a new model, or finds one with the same values.
* @param node The node to decode values from.
* @return The model with the requested values.
*/
static TCreateReturn Create(const Node &node) {
auto typeName = node["type"].Get<std::string>();
auto it = RegistryNode().find(typeName);
return it == RegistryNode().end() ? nullptr : it->second(node);
}
/**
* Creates a new model, or finds one with the same values.
* @param filename The file to load the model from.
* @return The model loaded from the filename.
*/
static TCreateReturn Create(const std::filesystem::path &filename) {
auto fileExt = filename.extension().string();
auto it = RegistryFilename().find(fileExt);
return it == RegistryFilename().end() ? nullptr : it->second(filename);
}
static TRegistryMapNode &RegistryNode() {
static TRegistryMapNode impl;
return impl;
}
static TRegistryMapFilename &RegistryFilename() {
static TRegistryMapFilename impl;
return impl;
}
/**
* A class used to help register subclasses of Model to the factory.
* Your subclass should have a static Create function taking a Node, or path.
* @tparam T The type that will extend Model.
*/
template<typename T>
class Registrar : public Base {
protected:
template<int Dummy = 0>
static bool Register(const std::string &typeName) {
Registrar::name = typeName;
ModelFactory::RegistryNode()[typeName] = [](const Node &node) -> TCreateReturn {
return T::Create(node);
};
return true;
}
template<int Dummy = 0>
static bool Register(const std::string &typeName, const std::string &extension) {
Register(typeName);
ModelFactory::RegistryFilename()[extension] = [](const std::filesystem::path &filename) -> TCreateReturn {
return T::Create(filename);
};
return true;
}
const Node &Load(const Node &node) override {
return node >> *dynamic_cast<T *>(this);
}
Node &Write(Node &node) const override {
node["type"].Set(name);
return node << *dynamic_cast<const T *>(this);
}
inline static std::string name;
};
friend const Node &operator>>(const Node &node, Base &base) {
return base.Load(node);
}
friend Node &operator<<(Node &node, const Base &base) {
return base.Write(node);
}
protected:
virtual const Node &Load(const Node &node) { return node; }
virtual Node &Write(Node &node) const { return node; }
};
/**
* @brief Resource that represents a model vertex and index buffer.
*/
class ACID_EXPORT Model : public ModelFactory<Model>, public Resource {
public:
/**
* Creates a new empty model.
*/
Model() = default;
/**
* Creates a new model.
* @tparam T The vertex type.
* @param vertices The model vertices.
* @param indices The model indices.
*/
template<typename T>
explicit Model(const std::vector<T> &vertices, const std::vector<uint32_t> &indices = {}) :
Model() {
Initialize(vertices, indices);
}
bool CmdRender(const CommandBuffer &commandBuffer, uint32_t instances = 1) const;
template<typename T>
std::vector<T> GetVertices(std::size_t offset = 0) const;
template<typename T>
void SetVertices(const std::vector<T> &vertices);
std::vector<uint32_t> GetIndices(std::size_t offset = 0) const;
void SetIndices(const std::vector<uint32_t> &indices);
std::vector<float> GetPointCloud() const;
const Vector3f &GetMinExtents() const { return m_minExtents; }
const Vector3f &GetMaxExtents() const { return m_maxExtents; }
float GetWidth() const { return m_maxExtents.m_x - m_minExtents.m_x; }
float GetHeight() const { return m_maxExtents.m_y - m_minExtents.m_y; }
float GetDepth() const { return m_maxExtents.m_z - m_minExtents.m_z; }
float GetRadius() const { return m_radius; }
const Buffer *GetVertexBuffer() const { return m_vertexBuffer.get(); }
const Buffer *GetIndexBuffer() const { return m_indexBuffer.get(); }
uint32_t GetVertexCount() const { return m_vertexCount; }
uint32_t GetIndexCount() const { return m_indexCount; }
static VkIndexType GetIndexType() { return VK_INDEX_TYPE_UINT32; }
protected:
template<typename T>
void Initialize(const std::vector<T> &vertices, const std::vector<uint32_t> &indices = {});
private:
std::unique_ptr<Buffer> m_vertexBuffer;
std::unique_ptr<Buffer> m_indexBuffer;
uint32_t m_vertexCount = 0;
uint32_t m_indexCount = 0;
Vector3f m_minExtents;
Vector3f m_maxExtents;
float m_radius = 0.0f;
};
}
#include "Model.inl"
| 5,015 | 1,723 |
/*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced
under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National
Laboratory (LANL), which is operated by Los Alamos National Security, LLC for
the U.S. Department of Energy. The U.S. Government has rights to use,
reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS
ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
to produce derivative works, such modified software should be clearly marked,
so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos
National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL
SECURITY, LLC 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 "GraphTraverser.hh"
#include "Mat.hh"
#include "Global.hh"
#include "TychoMesh.hh"
#include "Comm.hh"
#include "Timer.hh"
#include <vector>
#include <set>
#include <queue>
#include <utility>
#include <omp.h>
#include <limits.h>
#include <string.h>
using namespace std;
/*
Tuple class
*/
namespace {
class Tuple
{
private:
UINT c_cell;
UINT c_angle;
UINT c_priority;
public:
Tuple(UINT cell, UINT angle, UINT priority)
: c_cell(cell), c_angle(angle), c_priority(priority) {}
UINT getCell() const { return c_cell; }
UINT getAngle() const { return c_angle; }
// Comparison operator to determine relative priorities
// Needed for priority_queue
bool operator<(const Tuple &rhs) const
{
return c_priority < rhs.c_priority;
}
};}
/*
splitPacket
Packet is (global side, angle, data)
*/
static
void splitPacket(char *packet, UINT &globalSide, UINT &angle, char **data)
{
memcpy(&globalSide, packet, sizeof(UINT));
packet += sizeof(UINT);
memcpy(&angle, packet, sizeof(UINT));
packet += sizeof(UINT);
*data = packet;
}
/*
createPacket
Packet is (global side, angle, data)
*/
static
void createPacket(vector<char> &packet, UINT globalSide, UINT angle,
UINT dataSize, const char *data)
{
packet.resize(2 * sizeof(UINT) + dataSize);
char *p = packet.data();
memcpy(p, &globalSide, sizeof(UINT));
p += sizeof(UINT);
memcpy(p, &angle, sizeof(UINT));
p += sizeof(UINT);
memcpy(p, data, dataSize);
}
/*
isIncoming
Determines whether data is incoming to the cell
depending on sweep direction.
*/
static
bool isIncoming(UINT angle, UINT cell, UINT face, Direction direction)
{
if (direction == Direction_Forward)
return g_tychoMesh->isIncoming(angle, cell, face);
else if (direction == Direction_Backward)
return g_tychoMesh->isOutgoing(angle, cell, face);
// Should never get here
Assert(false);
return false;
}
/*
angleGroupIndex
Gets angle groups for angle index.
e.g. 20 angles numbered 0...19 with 3 threads.
Split into 3 angle chunks of size 7,7,6: 0...6 7...13 14...19
If angle in 0...6, return 0
If angle in 7...13, return 1
If angle in 14...19, return 2
*/
UINT angleGroupIndex(UINT angle)
{
UINT numAngles = g_nAngles;
UINT chunkSize = numAngles / g_nThreads;
UINT numChunksBigger = numAngles % g_nThreads;
UINT lowIndex = 0;
// Find angleGroup
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
UINT nextLowIndex = lowIndex + chunkSize;
if (angleGroup < numChunksBigger)
nextLowIndex++;
if (angle < nextLowIndex)
return angleGroup;
lowIndex = nextLowIndex;
}
// Should never get here
Assert(false);
return 0;
}
/*
sendData2Sided
Implements two-sided MPI for sending data.
*/
void GraphTraverser::sendData2Sided(
const vector<vector<char>> &sendBuffers) const
{
vector<MPI_Request> mpiSendRequests;
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
// Send the data
for (UINT index = 0; index < numAdjRanks; index++) {
const vector<char> &sendBuffer = sendBuffers[index];
if (sendBuffer.size() > 0) {
MPI_Request request;
const int adjRank = c_adjRankIndexToRank[index];
const int tag = 0;
mpiError = MPI_Isend(const_cast<char*>(sendBuffer.data()),
sendBuffer.size(),
MPI_BYTE, adjRank, tag,
MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
}
}
// Make sure all sends are done
if (mpiSendRequests.size() > 0) {
mpiError = MPI_Waitall(mpiSendRequests.size(), mpiSendRequests.data(),
MPI_STATUSES_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
/*
recvData2Sided
Implements two-sided MPI for receiving data.
*/
void GraphTraverser::recvData2Sided(vector<char> &dataPackets) const
{
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
for (UINT index = 0; index < numAdjRanks; index++) {
const int adjRank = c_adjRankIndexToRank[index];
const int tag = 0;
int flag = 0;
MPI_Status mpiStatus;
int recvCount;
// Probe for new message
mpiError = MPI_Iprobe(adjRank, tag, MPI_COMM_WORLD, &flag, &mpiStatus);
Insist(mpiError == MPI_SUCCESS, "");
mpiError = MPI_Get_count(&mpiStatus, MPI_BYTE, &recvCount);
Insist(mpiError == MPI_SUCCESS, "");
// Recv message if there is one
if (flag) {
UINT originalSize = dataPackets.size();
dataPackets.resize(originalSize + recvCount);
mpiError = MPI_Recv(&dataPackets[originalSize], recvCount,
MPI_BYTE, adjRank, tag, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
}
/*
sendAndRecvData()
The algorithm is
- Irecv data size for all adjacent ranks
- ISend data size and then data (if any)
- Wait on recv of data size, then blocking recv for data if there is any.
Data is sent in two steps to each adjacent rank.
First is the number of bytes of data that will be sent.
Second is the raw data in bytes.
The tag for the first send is 0.
The tag for the second send is 1.
The raw data is made of data packets containing:
globalSide, angle, and data to send.
The data can have different meanings depending on the TraverseData
subclass.
When done traversing local graph, you want to stop all communication.
This is done by setting killComm to true.
To mark killing communication, sendSize is set to UINT64_MAX.
In this event, commDark[rank] is set to true on the receiving rank
so we no longer look for communication from this rank.
*/
void GraphTraverser::sendAndRecvData(const vector<vector<char>> &sendBuffers,
vector<char> &dataPackets,
vector<bool> &commDark,
const bool killComm) const
{
// Check input
Assert(c_adjRankIndexToRank.size() == sendBuffers.size());
Assert(c_adjRankIndexToRank.size() == commDark.size());
// Variables
UINT numAdjRanks = c_adjRankIndexToRank.size();
int mpiError;
vector<UINT> recvSizes(numAdjRanks);
vector<UINT> sendSizes(numAdjRanks);
vector<MPI_Request> mpiRecvRequests(numAdjRanks);
vector<MPI_Request> mpiSendRequests;
UINT numRecv = numAdjRanks;
// Setup recv of data size
for (UINT index = 0; index < numAdjRanks; index++) {
// No recv if adjRank is no longer communicating
if (commDark[index]) {
mpiRecvRequests[index] = MPI_REQUEST_NULL;
numRecv--;
continue;
}
// Irecv data size
int numDataToRecv = 1;
int adjRank = c_adjRankIndexToRank[index];
int tag0 = 0;
mpiError = MPI_Irecv(&recvSizes[index], numDataToRecv, MPI_UINT64_T,
adjRank, tag0, MPI_COMM_WORLD,
&mpiRecvRequests[index]);
Insist(mpiError == MPI_SUCCESS, "");
}
// Send data size and data
for (UINT index = 0; index < numAdjRanks; index++) {
// Don't send if adjRank is no longer communicating
if (commDark[index])
continue;
const vector<char> &sendBuffer = sendBuffers[index];
int numDataToSend = 1;
int adjRank = c_adjRankIndexToRank[index];
int tag0 = 0;
int tag1 = 1;
// Send data size
MPI_Request request;
sendSizes[index] = sendBuffer.size();
if (killComm)
sendSizes[index] = UINT64_MAX;
mpiError = MPI_Isend(&sendSizes[index], numDataToSend, MPI_UINT64_T,
adjRank, tag0, MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
// Send data
if (sendSizes[index] > 0 && sendSizes[index] != UINT64_MAX) {
MPI_Request request;
Assert(sendBuffer.size() < INT_MAX);
mpiError = MPI_Isend(const_cast<char*>(sendBuffer.data()),
sendBuffer.size(),
MPI_BYTE, adjRank, tag1,
MPI_COMM_WORLD, &request);
Insist(mpiError == MPI_SUCCESS, "");
mpiSendRequests.push_back(request);
}
}
// Recv data size and data
for (UINT numWaits = 0; numWaits < numRecv; numWaits++) {
// Wait for a data size to arrive
int index;
mpiError = MPI_Waitany(mpiRecvRequests.size(), mpiRecvRequests.data(),
&index, MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
// Recv data
if (recvSizes[index] > 0 && recvSizes[index] != UINT64_MAX) {
int adjRank = c_adjRankIndexToRank[index];
int tag1 = 1;
UINT originalSize = dataPackets.size();
dataPackets.resize(originalSize + recvSizes[index]);
mpiError = MPI_Recv(&dataPackets[originalSize], recvSizes[index],
MPI_BYTE, adjRank, tag1, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
// Stop communication with this rank
if (recvSizes[index] == UINT64_MAX) {
commDark[index] = true;
}
}
// Make sure all sends are done
if (mpiSendRequests.size() > 0) {
mpiError = MPI_Waitall(mpiSendRequests.size(), mpiSendRequests.data(),
MPI_STATUSES_IGNORE);
Insist(mpiError == MPI_SUCCESS, "");
}
}
/*
GraphTraverser
If doComm is true, graph traversal is global.
If doComm is false, each mesh partition is traversed locally with no
consideration for boundaries between partitions.
*/
GraphTraverser::GraphTraverser(Direction direction, bool doComm,
UINT dataSizeInBytes)
: c_direction(direction), c_doComm(doComm),
c_dataSizeInBytes(dataSizeInBytes)
{
// Get adjacent ranks
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT face = 0; face < g_nFacePerCell; face++) {
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK &&
c_adjRankToRankIndex.count(adjRank) == 0)
{
UINT rankIndex = c_adjRankIndexToRank.size();
c_adjRankToRankIndex.insert(make_pair(adjRank, rankIndex));
c_adjRankIndexToRank.push_back(adjRank);
}
}}
// Calc num dependencies for each (cell, angle) pair
c_initNumDependencies.resize(g_nAngles, g_nCells);
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
c_initNumDependencies(angle, cell) = 0;
for (UINT face = 0; face < g_nFacePerCell; face++) {
bool incoming = isIncoming(angle, cell, face, c_direction);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
if (c_doComm && incoming && adjRank != TychoMesh::BAD_RANK) {
c_initNumDependencies(angle, cell)++;
}
else if (!c_doComm && incoming && adjCell != TychoMesh::BOUNDARY_FACE) {
c_initNumDependencies(angle, cell)++;
}
}
}}
}
/*
traverse
Traverses g_tychoMesh.
*/
void GraphTraverser::traverse(const UINT maxComputePerStep,
TraverseData &traverseData)
{
vector<priority_queue<Tuple>> canCompute(g_nThreads);
Mat2<UINT> numDependencies(g_nAngles, g_nCells);
UINT numCellAnglePairsToCalculate = g_nAngles * g_nCells;
Mat2<vector<char>> sendBuffers;
vector<vector<char>> sendBuffers1;
vector<bool> commDark;
Timer totalTimer;
Timer setupTimer;
Timer commTimer;
Timer sendTimer;
Timer recvTimer;
// Start total timer
totalTimer.start();
setupTimer.start();
// Calc num dependencies for each (cell, angle) pair
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
numDependencies(angle, cell) = c_initNumDependencies(angle, cell);
}}
// Set size of sendBuffers and commDark
UINT numAdjRanks = c_adjRankIndexToRank.size();
sendBuffers.resize(g_nThreads, numAdjRanks);
sendBuffers1.resize(numAdjRanks);
commDark.resize(numAdjRanks, false);
// Initialize canCompute queue
for (UINT cell = 0; cell < g_nCells; cell++) {
for (UINT angle = 0; angle < g_nAngles; angle++) {
if (numDependencies(angle, cell) == 0) {
UINT priority = traverseData.getPriority(cell, angle);
UINT angleGroup = angleGroupIndex(angle);
canCompute[angleGroup].push(Tuple(cell, angle, priority));
}
}}
// End setup timer
setupTimer.stop();
// Traverse the graph
while (numCellAnglePairsToCalculate > 0) {
// Do local traversal
#pragma omp parallel
{
UINT stepsTaken = 0;
UINT angleGroup = omp_get_thread_num();
while (canCompute[angleGroup].size() > 0 &&
stepsTaken < maxComputePerStep)
{
// Get cell/angle pair to compute
Tuple cellAnglePair = canCompute[angleGroup].top();
canCompute[angleGroup].pop();
UINT cell = cellAnglePair.getCell();
UINT angle = cellAnglePair.getAngle();
stepsTaken++;
#pragma omp atomic
numCellAnglePairsToCalculate--;
// Get boundary type and adjacent cell/side data for each face
BoundaryType bdryType[g_nFacePerCell];
UINT adjCellsSides[g_nFacePerCell];
bool isOutgoingWrtDirection[g_nFacePerCell];
for (UINT face = 0; face < g_nFacePerCell; face++) {
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
adjCellsSides[face] = adjCell;
if (g_tychoMesh->isOutgoing(angle, cell, face)) {
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_OutIntBdry;
adjCellsSides[face] =
g_tychoMesh->getSide(cell, face);
}
else if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank == TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_OutExtBdry;
}
else {
bdryType[face] = BoundaryType_OutInt;
}
if (c_direction == Direction_Forward) {
isOutgoingWrtDirection[face] = true;
}
else {
isOutgoingWrtDirection[face] = false;
}
}
else {
if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank != TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_InIntBdry;
adjCellsSides[face] =
g_tychoMesh->getSide(cell, face);
}
else if (adjCell == TychoMesh::BOUNDARY_FACE &&
adjRank == TychoMesh::BAD_RANK)
{
bdryType[face] = BoundaryType_InExtBdry;
}
else {
bdryType[face] = BoundaryType_InInt;
}
if (c_direction == Direction_Forward) {
isOutgoingWrtDirection[face] = false;
}
else {
isOutgoingWrtDirection[face] = true;
}
}
}
// Update data for this cell-angle pair
traverseData.update(cell, angle, adjCellsSides, bdryType);
// Update dependency for children
for (UINT face = 0; face < g_nFacePerCell; face++) {
if (isOutgoingWrtDirection[face]) {
UINT adjCell = g_tychoMesh->getAdjCell(cell, face);
UINT adjRank = g_tychoMesh->getAdjRank(cell, face);
if (adjCell != TychoMesh::BOUNDARY_FACE) {
numDependencies(angle, adjCell)--;
if (numDependencies(angle, adjCell) == 0) {
UINT priority =
traverseData.getPriority(adjCell, angle);
Tuple tuple(adjCell, angle, priority);
canCompute[angleGroup].push(tuple);
}
}
else if (c_doComm && adjRank != TychoMesh::BAD_RANK) {
UINT rankIndex = c_adjRankToRankIndex.at(adjRank);
UINT side = g_tychoMesh->getSide(cell, face);
UINT globalSide = g_tychoMesh->getLGSide(side);
vector<char> packet;
createPacket(packet, globalSide, angle,
c_dataSizeInBytes,
traverseData.getData(cell, face, angle));
sendBuffers(angleGroup, rankIndex).insert(
sendBuffers(angleGroup, rankIndex).end(),
packet.begin(), packet.end());
}
}
}
}
}
// Put together sendBuffers from different angleGroups
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers1[rankIndex].insert(
sendBuffers1[rankIndex].end(),
sendBuffers(angleGroup, rankIndex).begin(),
sendBuffers(angleGroup, rankIndex).end());
}}
// Do communication
commTimer.start();
if (c_doComm) {
// Send/Recv
UINT packetSizeInBytes = 2 * sizeof(UINT) + c_dataSizeInBytes;
vector<char> dataPackets;
if (g_mpiType == MPIType_TychoTwoSided) {
const bool killComm = false;
sendAndRecvData(sendBuffers1, dataPackets, commDark, killComm);
}
else if (g_mpiType == MPIType_CapsaicinTwoSided) {
sendTimer.start();
sendData2Sided(sendBuffers1);
sendTimer.stop();
recvTimer.start();
recvData2Sided(dataPackets);
recvTimer.stop();
}
else {
Insist(false, "MPI type not recognized.");
}
// Clear send buffers for next iteration
for (UINT angleGroup = 0; angleGroup < g_nThreads; angleGroup++) {
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers(angleGroup, rankIndex).clear();
}}
for (UINT rankIndex = 0; rankIndex < numAdjRanks; rankIndex++) {
sendBuffers1[rankIndex].clear();
}
// Unpack packets
UINT numPackets = dataPackets.size() / packetSizeInBytes;
Assert(dataPackets.size() % packetSizeInBytes == 0);
for (UINT i = 0; i < numPackets; i++) {
char *packet = &dataPackets[i * packetSizeInBytes];
UINT globalSide;
UINT angle;
char *packetData;
splitPacket(packet, globalSide, angle, &packetData);
UINT localSide = g_tychoMesh->getGLSide(globalSide);
traverseData.setSideData(localSide, angle, packetData);
UINT cell = g_tychoMesh->getSideCell(localSide);
numDependencies(angle, cell)--;
if (numDependencies(angle, cell) == 0) {
UINT priority = traverseData.getPriority(cell, angle);
Tuple tuple(cell, angle, priority);
canCompute[angleGroupIndex(angle)].push(tuple);
}
}
}
commTimer.stop();
}
// Send kill comm signal to adjacent ranks
if (g_mpiType == MPIType_TychoTwoSided) {
commTimer.start();
if (c_doComm) {
vector<char> dataPackets;
const bool killComm = true;
sendAndRecvData(sendBuffers1, dataPackets, commDark, killComm);
}
commTimer.stop();
}
// Print times
totalTimer.stop();
double totalTime = totalTimer.wall_clock();
Comm::gmax(totalTime);
double setupTime = setupTimer.wall_clock();
Comm::gmax(setupTime);
double commTime = commTimer.sum_wall_clock();
Comm::gmax(commTime);
double sendTime = sendTimer.sum_wall_clock();
Comm::gmax(sendTime);
double recvTime = recvTimer.sum_wall_clock();
Comm::gmax(recvTime);
if (Comm::rank() == 0) {
printf(" Traverse Timer (comm): %fs\n", commTime);
printf(" Traverse Timer (send): %fs\n", sendTime);
printf(" Traverse Timer (recv): %fs\n", recvTime);
printf(" Traverse Timer (setup): %fs\n", setupTime);
printf(" Traverse Timer (total): %fs\n", totalTime);
}
}
| 26,239 | 8,032 |
// This code is put in the public domain by Andrei Alexandrescu
// See http://www.reddit.com/r/programming/comments/14m1tc/andrei_alexandrescu_systematic_error_handling_in/c7etk47
// Some edits by Alexander Kondratskiy.
#ifndef EXPECTED_HPP_TN6DJT51
#define EXPECTED_HPP_TN6DJT51
#include <stdexcept>
#include <algorithm>
template <class T>
class Expected {
union {
std::exception_ptr spam;
T ham;
};
bool gotHam;
Expected() {
// used by fromException below
}
public:
Expected(const T& rhs) : ham(rhs), gotHam(true) {}
Expected(T&& rhs) : ham(std::move(rhs)), gotHam(true) {}
Expected(const Expected& rhs) : gotHam(rhs.gotHam) {
if (gotHam) new(&ham) T(rhs.ham);
else new(&spam) std::exception_ptr(rhs.spam);
}
Expected(Expected&& rhs) : gotHam(rhs.gotHam) {
if (gotHam) new(&ham) T(std::move(rhs.ham));
else new(&spam) std::exception_ptr(std::move(rhs.spam));
}
void swap(Expected& rhs) {
if (gotHam) {
if (rhs.gotHam) {
using std::swap;
swap(ham, rhs.ham);
} else {
auto t = std::move(rhs.spam);
new(&rhs.ham) T(std::move(ham));
new(&spam) std::exception_ptr(t);
std::swap(gotHam, rhs.gotHam);
}
} else {
if (rhs.gotHam) {
rhs.swap(*this);
} else {
spam.swap(rhs.spam);
std::swap(gotHam, rhs.gotHam);
}
}
}
Expected& operator=(Expected<T> rhs) {
swap(rhs);
return *this;
}
~Expected() {
//using std::exception_ptr;
if (gotHam) ham.~T();
else spam.~exception_ptr();
}
static Expected<T> fromException(std::exception_ptr p) {
Expected<T> result;
result.gotHam = false;
new(&result.spam) std::exception_ptr(std::move(p));
return result;
}
template <class E>
static Expected<T> fromException(const E& exception) {
if (typeid(exception) != typeid(E)) {
throw std::invalid_argument(
"Expected<T>::fromException: slicing detected.");
}
return fromException(std::make_exception_ptr(exception));
}
static Expected<T> fromException() {
return fromException(std::current_exception());
}
template <class U>
static Expected<T> transferException(Expected<U> const& other) {
if (other.valid()) {
throw std::invalid_argument(
"Expected<T>::transferException: other Expected<U> does not contain an exception.");
}
return fromException(other.spam);
}
bool valid() const {
return gotHam;
}
/**
* implicit conversion may throw if spam
*/
operator T&() {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
T& get() {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
const T& get() const {
if (!gotHam) std::rethrow_exception(spam);
return ham;
}
template <class E>
bool hasException() const {
try {
if (!gotHam) std::rethrow_exception(spam);
} catch (const E& object) {
return true;
} catch (...) {
}
return false;
}
template <class F>
static Expected fromCode(F fun) {
try {
return Expected(fun());
} catch (...) {
return fromException();
}
}
};
// TODO: clean this up
template <>
class Expected<void> {
std::exception_ptr spam;
bool gotHam;
public:
Expected() : gotHam(true) { }
void swap(Expected& rhs) {
if (gotHam) {
if (!rhs.gotHam) {
auto t = std::move(rhs.spam);
new(&spam) std::exception_ptr(t);
std::swap(gotHam, rhs.gotHam);
}
} else {
if (rhs.gotHam) {
rhs.swap(*this);
} else {
spam.swap(rhs.spam);
std::swap(gotHam, rhs.gotHam);
}
}
}
Expected& operator=(Expected<void> rhs) {
swap(rhs);
return *this;
}
~Expected() {
//using std::exception_ptr;
if (!gotHam) spam.~exception_ptr();
}
static Expected<void> fromException(std::exception_ptr p) {
Expected<void> result;
result.gotHam = false;
new(&result.spam) std::exception_ptr(std::move(p));
return result;
}
template <class E>
static Expected<void> fromException(const E& exception) {
if (typeid(exception) != typeid(E)) {
throw std::invalid_argument(
"Expected<void>::fromException: slicing detected.");
}
return fromException(std::make_exception_ptr(exception));
}
static Expected<void> fromException() {
return fromException(std::current_exception());
}
bool valid() const {
return gotHam;
}
/**
* implicit conversion may throw if spam
*/
operator void() {
if (!gotHam) std::rethrow_exception(spam);
}
void get() const {
if (!gotHam) std::rethrow_exception(spam);
}
template <class E>
bool hasException() const {
try {
if (!gotHam) std::rethrow_exception(spam);
} catch (const E& object) {
return true;
} catch (...) {
}
return false;
}
template <class F>
static Expected fromCode(F fun) {
try {
fun();
return Expected();
} catch (...) {
return fromException();
}
}
};
#endif /* end of include guard: EXPECTED_HPP_TN6DJT51 */
| 5,131 | 1,890 |
#include<bits/stdc++.h>
using namespace std;
/*
problem is similar as finding first occurrence
because array is binary and sorted so,
if we find first occurrence of 1, then subtract it from
last index to find count.
*/
int count1s(int a[], int n)//time comp. O(logn)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == 0)
{
low = mid + 1;
}
else
{
if (mid == 0 or a[mid - 1] != a[mid])
{
return (n - mid);
}
else
{
high = mid - 1;
}
}
}
return 0;
}
int main()
{
int a[] = {0, 0, 0, 0, 1, 1, 1};
int n = sizeof(a) / sizeof(int);
cout << count1s(a, n);
return 0;
} | 666 | 326 |
#include <iostream>
using namespace std;
enum Status {Unchecked, Checking, IsHappy, NotHappy };
const int HIGHEST = 1000;
Status numbers[HIGHEST];
inline int nextNum(int num)
{
int ret = 0;
while (num)
{
ret += (num % 10) * (num % 10);
num /= 10;
}
return ret;
}
bool isHappy(int num)
{
num = nextNum(num);
if (numbers[num] == Unchecked)
{
numbers[num] = Checking;
bool is = isHappy(num);
numbers[num] = (is ? IsHappy : NotHappy);
}
else if (numbers[num] == Checking)
return false;
return numbers[num] == IsHappy;
}
int main()
{
for (int i = 0; i < HIGHEST; ++i)
numbers[i] = Unchecked;
numbers[1] = IsHappy;
int T;
cin >> T;
for (int t = 1; t <= T; ++t)
{
int num;
cin >> num;
if (isHappy(num))
cout << "Case #" << t << ": " << num << " is a Happy number.\n";
else
cout << "Case #" << t << ": " << num << " is an Unhappy number.\n";
}
}
| 1,040 | 400 |
/**
* @file tests/bin2llvmir/utils/tests/simplifycfg_tests.cpp
* @brief Tests for the @c CFGSimplifyPass pass.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*
* This is checking that LLVM's -simplifycfg is behaving as expected.
* If this fails, something in LLVM changed and we need to react, because
* otherwise it will start to screw up our code.
*/
#include "../lib/Transforms/Scalar/SimplifyCFGPass.cpp"
#include "retdec/bin2llvmir/optimizations/unreachable_funcs/unreachable_funcs.h"
#include "bin2llvmir/utils/llvmir_tests.h"
using namespace ::testing;
using namespace llvm;
namespace retdec {
namespace bin2llvmir {
namespace tests {
/**
* @brief Tests for the @c UnreachableFuncs pass.
*/
class CFGSimplifyPassTests: public LlvmIrTests
{
protected:
void runOnModule()
{
LlvmIrTests::runOnModule<CFGSimplifyPass>();
}
};
TEST_F(CFGSimplifyPassTests, unreachableBasicBlocksKeep)
{
parseInput(R"(
; Instructions in unreachable BBs are *NOT* removed if metadata named
; 'llvmToAsmGlobalVariableName' exits.
@llvm2asm = global i64 0
define void @fnc() {
store volatile i64 123, i64* @llvm2asm, !asm !1
ret void
store volatile i64 456, i64* @llvm2asm, !asm !2
ret void
store volatile i64 789, i64* @llvm2asm, !asm !3
ret void
}
!llvmToAsmGlobalVariableName = !{!0}
!0 = !{!"llvm2asm"}
!1 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
!2 = !{!"name", i64 456, i64 10, !"asm", !"annotation"}
!3 = !{!"name", i64 789, i64 10, !"asm", !"annotation"}
)");
runOnModule();
std::string exp = R"(
@llvm2asm = global i64 0
define void @fnc() {
; 7b
store volatile i64 123, i64* @llvm2asm, !asm !1
ret void
; No predecessors!
; 1c8
store volatile i64 456, i64* @llvm2asm, !asm !2
ret void
; No predecessors!
; 315
store volatile i64 789, i64* @llvm2asm, !asm !3
ret void
}
!llvmToAsmGlobalVariableName = !{!0}
!0 = !{!"llvm2asm"}
!1 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
!2 = !{!"name", i64 456, i64 10, !"asm", !"annotation"}
!3 = !{!"name", i64 789, i64 10, !"asm", !"annotation"}
)";
checkModuleAgainstExpectedIr(exp);
}
TEST_F(CFGSimplifyPassTests, unreachableBasicBlocksRemove)
{
parseInput(R"(
; Instructions in unreachable BBs are removed if metadata named
; 'llvmToAsmGlobalVariableName' does not exit.
@llvm2asm = global i64 0
define void @fnc() {
store volatile i64 123, i64* @llvm2asm, !asm !0
ret void
store volatile i64 456, i64* @llvm2asm, !asm !1
ret void
store volatile i64 789, i64* @llvm2asm, !asm !2
ret void
}
!0 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
!1 = !{!"name", i64 456, i64 10, !"asm", !"annotation"}
!2 = !{!"name", i64 789, i64 10, !"asm", !"annotation"}
)");
runOnModule();
std::string exp = R"(
@llvm2asm = global i64 0
define void @fnc() {
; 7b
store volatile i64 123, i64* @llvm2asm, !asm !0
ret void
}
!0 = !{!"name", i64 123, i64 10, !"asm", !"annotation"}
)";
checkModuleAgainstExpectedIr(exp);
}
} // namespace tests
} // namespace bin2llvmir
} // namespace retdec
| 3,183 | 1,541 |
// ============================================================================
//
// = LIBRARY
// ULib - c++ library
//
// = FILENAME
// error_simulation.cpp
//
// = AUTHOR
// Stefano Casazza
//
// ============================================================================
/*
#define DEBUG_DEBUG
*/
#include <ulib/base/utility.h>
#include <ulib/debug/error_simulation.h>
bool USimulationError::flag_init;
char* USimulationError::file_mem;
uint32_t USimulationError::file_size;
union uuvararg USimulationError::var_arg;
/**
* #if defined(HAVE_STRTOF) && !defined(strtof)
* extern "C" { float strtof(const char* nptr, char** endptr); }
* #endif
* #if defined(HAVE_STRTOLD) && !defined(strtold)
* extern "C" { long double strtold(const char* nptr, char** endptr); }
* #endif
*/
void USimulationError::init()
{
U_INTERNAL_TRACE("USimulationError::init()")
int fd = 0;
char* env = getenv("USIMERR");
char file[MAX_FILENAME_LEN];
if ( env &&
*env)
{
flag_init = true;
// format: <file_error_simulation>
// error.sim
(void) sscanf(env, "%254s", file);
fd = open(file, O_RDONLY | O_BINARY, 0666);
if (fd != -1)
{
struct stat st;
if (fstat(fd, &st) == 0)
{
file_size = st.st_size;
if (file_size)
{
file_mem = (char*) mmap(0, file_size, PROT_READ, MAP_SHARED, fd, 0);
if (file_mem == MAP_FAILED) file_size = 0;
}
}
(void) close(fd);
}
}
if (fd <= 0)
{
U_MESSAGE("SIMERR%W<%Woff%W>%W", YELLOW, RED, YELLOW, RESET);
}
else
{
U_MESSAGE("SIMERR%W<%Won%W>: File<%W%s%W>%W", YELLOW, GREEN, YELLOW, CYAN, file, YELLOW, RESET);
}
}
void* USimulationError::checkForMatch(const char* call_name)
{
U_INTERNAL_TRACE("USimulationError::checkForMatch(%s)", call_name);
if (flag_init &&
file_size)
{
const char* ptr = call_name;
while (*ptr && *ptr != '(') ++ptr;
if (*ptr == '(')
{
int len = ptr - call_name;
char* limit = file_mem + file_size - len;
char* file_ptr = file_mem;
// format: <classname>::method <random range> <return type> <return value> <errno value>
// ::lstat 10 i -1 13
bool match = false;
for (; file_ptr <= limit; ++file_ptr)
{
while (u__isspace(*file_ptr)) ++file_ptr;
if (*file_ptr != '#')
{
while (u__isspace(*file_ptr)) ++file_ptr;
U_INTERNAL_PRINT("file_ptr = %.*s", len, file_ptr);
if (u__isspace(file_ptr[len]) &&
memcmp(file_ptr, call_name, len) == 0)
{
match = true;
file_ptr += len;
// manage random testing
uint32_t range = (uint32_t) strtol(file_ptr, &file_ptr, 10);
if (range > 0) match = (u_get_num_random(range) == (range / 2));
break;
}
}
while (*file_ptr != '\n') ++file_ptr;
}
if (match)
{
while (u__isspace(*file_ptr)) ++file_ptr;
char type = *file_ptr++;
switch (type)
{
case 'p': // pointer
{
var_arg.p = (void*) strtol(file_ptr, &file_ptr, 16);
}
break;
case 'l': // long
{
var_arg.l = strtol(file_ptr, &file_ptr, 10);
}
break;
case 'L': // long long
{
# ifdef HAVE_STRTOULL
var_arg.ll = (long long) strtoull(file_ptr, &file_ptr, 10);
# endif
}
break;
case 'f': // float
{
# ifdef HAVE_STRTOF
var_arg.f = strtof(file_ptr, &file_ptr);
# endif
}
break;
case 'd': // double
{
var_arg.d = strtod(file_ptr, &file_ptr);
}
break;
case 'D': // long double
{
# ifdef HAVE_STRTOLD
var_arg.ld = strtold(file_ptr, &file_ptr);
# endif
}
break;
case 'i': // word-size (int)
default:
{
var_arg.i = (int) strtol(file_ptr, &file_ptr, 10);
}
break;
}
errno = atoi(file_ptr);
U_INTERNAL_PRINT("errno = %d var_arg = %d", errno, var_arg.i);
return &var_arg;
}
}
}
return 0;
}
| 5,060 | 1,680 |
/**
* Copyright (c) 2040 Dark Energy Processor
*
* 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.
*/
// STL
#include <map>
#include <string>
#include <vector>
// Lua
extern "C" {
#include "lua.h"
#include "lauxlib.h"
}
// lovewrap
#include "LOVEWrap.h"
#include "Scene.h"
// Current scene
lovewrap::Scene *currentScene = nullptr;
static int loveLoad(lua_State *L)
{
// args
std::vector<std::string> args;
int argLen = lua_objlen(L, 1);
for (int i = 1; i <= argLen; i++)
{
lua_pushinteger(L, (lua_Integer) i);
lua_rawget(L, 1);
size_t strSize;
const char *str = lua_tolstring(L, -1, &strSize);
args.push_back(std::string(str, strSize));
lua_pop(L, 1);
}
currentScene->load(args);
return 0;
}
static int loveUpdate(lua_State *L)
{
currentScene->update(luaL_checknumber(L, 1));
return 0;
}
static int loveDraw(lua_State *L)
{
currentScene->draw();
return 0;
}
static int loveQuit(lua_State *L)
{
lua_pushboolean(L, (int) currentScene->quit());
return 1;
}
typedef void(*EventHandlerFunc)(const std::vector<love::Variant> &);
inline ptrdiff_t getIntegerFromVariant(const std::vector<love::Variant> &arg, size_t index)
{
if (index > arg.size())
throw love::Exception("index %u is out of range", (uint32_t) index);
const love::Variant &var = arg[index - 1];
if (var.getType() != love::Variant::NUMBER)
throw love::Exception("index %u is not a number", (uint32_t) index);
return var.getData().number;
}
inline bool getBooleanFromVariant(const std::vector<love::Variant> &arg, size_t index, bool implicitConversion = false)
{
if (index > arg.size())
throw love::Exception("index %u is out of range", (uint32_t) index);
const love::Variant &var = arg[index - 1];
const love::Variant::Data &data = var.getData();
love::Variant::Type varType = var.getType();
if (implicitConversion)
{
if (varType == love::Variant::BOOLEAN)
return data.boolean;
else if (varType == love::Variant::NUMBER)
return abs(data.number) <= 0.000001;
else if (varType == love::Variant::NIL)
return false;
else
throw love::Exception("index %u is not a boolean", (uint32_t) index);
}
else if (varType != var.BOOLEAN)
throw love::Exception("index %u is not a boolean", (uint32_t) index);
return var.getData().boolean;
}
inline std::string getStringFromVariant(const std::vector<love::Variant> &arg, size_t index)
{
if (index > arg.size())
throw love::Exception("index %u is out of range", (uint32_t) index);
const love::Variant &var = arg[index - 1];
const love::Variant::Data &data = var.getData();
love::Variant::Type varType = var.getType();
switch(varType)
{
case love::Variant::SMALLSTRING:
{
return std::string(data.smallstring.str, data.smallstring.len);
}
case love::Variant::STRING:
{
return std::string(data.string->str, data.string->len);
}
default:
throw love::Exception("index %u is not a string", (uint32_t) index);
}
}
template<typename T> inline T getConstantFromVariant(
const std::vector<love::Variant> &arg,
size_t index,
bool (*func)(const char*, T&)
)
{
std::string str = getStringFromVariant(arg, index);
T outVal;
if (func(str.c_str(), outVal))
return outVal;
else
throw love::Exception("index %u invalid constant value '%s'", (uint32_t) index, str.c_str());
}
static void loveEventKeyPressed(const std::vector<love::Variant> &arg)
{
using namespace love::keyboard;
currentScene->keyPressed(
getConstantFromVariant<Keyboard::Key>(arg, 1, &Keyboard::getConstant),
getConstantFromVariant<Keyboard::Scancode>(arg, 2, &Keyboard::getConstant),
getBooleanFromVariant(arg, 3)
);
}
static void loveEventKeyReleased(const std::vector<love::Variant> &arg)
{
using namespace love::keyboard;
currentScene->keyReleased(
getConstantFromVariant<Keyboard::Key>(arg, 1, &Keyboard::getConstant),
getConstantFromVariant<Keyboard::Scancode>(arg, 2, &Keyboard::getConstant)
);
}
static int loveGameLoop(lua_State *L)
{
static bool eventHandlerInitialized = false;
static std::map<std::string, EventHandlerFunc> eventHandler;
if (!eventHandlerInitialized)
{
eventHandler["keypressed"] = &loveEventKeyPressed;
eventHandler["keyreleased"] = &loveEventKeyReleased;
eventHandlerInitialized = true;
}
double dt = 0;
if (lovewrap::event::isLoaded())
{
auto inst = lovewrap::event::getInstance();
love::event::Message *msg = nullptr;
inst->pump();
while (inst->poll(msg))
{
if (msg->name.compare("quit") == 0 && currentScene->quit() == false)
{
if (msg->args.size() > 0)
msg->args[0].toLua(L);
else
lua_pushinteger(L, 0);
return 1;
}
else
{
auto iter = eventHandler.find(msg->name);
if (iter != eventHandler.end())
{
try
{
iter->second(msg->args);
}
catch (love::Exception &e)
{
fprintf(stderr, "Exception '%s': %s\n", msg->name.c_str(), e.what());
return luaL_error(L, "%s", e.what());
}
}
else
fprintf(stderr, "Missing event handler: %s\n", msg->name.c_str());
}
}
}
if (lovewrap::timer::isLoaded())
dt = lovewrap::timer::step();
try
{
currentScene->update(dt);
}
catch (love::Exception &e)
{
lua_pushstring(L, e.what());
lua_error(L);
}
if (lovewrap::graphics::isLoaded() && lovewrap::graphics::isActive())
{
lovewrap::graphics::origin();
lovewrap::graphics::clear(lovewrap::graphics::getBackgroundColor());
try
{
currentScene->draw();
}
catch (love::Exception &e)
{
lua_pushstring(L, e.what());
lua_error(L);
}
lua_gc(L, LUA_GCCOLLECT, 0);
lovewrap::graphics::present();
}
return 0;
}
static int loveRun(lua_State *L)
{
// args
std::vector<std::string> args;
lua_getglobal(L, "arg");
int argLen = lua_objlen(L, 1);
size_t strSize;
const char *str = nullptr;
// index -2 = argv[0]
lua_pushinteger(L, -2);
lua_rawget(L, 1);
str = lua_tolstring(L, -1, &strSize);
args.push_back(std::string(str, strSize));
for (int i = 1; i <= argLen; i++)
{
lua_pushinteger(L, (lua_Integer) i);
lua_rawget(L, 1);
str = lua_tolstring(L, -1, &strSize);
if (str != nullptr)
args.push_back(std::string(str, strSize));
lua_pop(L, 1);
}
lua_pop(L, 1);
try
{
currentScene->load(args);
}
catch (love::Exception &e)
{
lua_pushstring(L, e.what());
lua_error(L);
}
lua_pushcfunction(L, &loveGameLoop);
return 1;
}
int baseMain(lua_State *L)
{
lua_getglobal(L, "love");
// love.load
lua_pushcfunction(L, &loveLoad);
lua_setfield(L, -2, "load");
// love.update
lua_pushcfunction(L, &loveUpdate);
lua_setfield(L, -2, "update");
// love.draw
lua_pushcfunction(L, &loveDraw);
lua_setfield(L, -2, "draw");
// love.quit
lua_pushcfunction(L, &loveQuit);
lua_setfield(L, -2, "quit");
// love.run
lua_pushcfunction(L, &loveRun);
lua_setfield(L, -2, "run");
lua_pop(L, 1);
lua_pushboolean(L, 1);
return 1;
}
namespace lovewrap
{
lua_CFunction initializeScene(Scene *scene)
{
currentScene = scene;
return &baseMain;
}
Scene::Scene() {}
Scene::~Scene() {}
void Scene::load(std::vector<std::string>) {}
void Scene::update(double) {}
void Scene::draw() {}
bool Scene::quit() {return false;}
void Scene::visible(bool) {}
void Scene::focus(bool) {}
void Scene::resize(int, int) {}
void Scene::keyPressed(love::keyboard::Keyboard::Key, love::keyboard::Keyboard::Scancode, bool) {}
void Scene::keyReleased(love::keyboard::Keyboard::Key, love::keyboard::Keyboard::Scancode) {}
void Scene::textInput(std::string) {}
void Scene::mousePressed(int, int, int, bool) {}
void Scene::mouseReleased(int, int, int, bool) {}
void Scene::mouseMoved(int, int, int, int, bool) {}
void Scene::mouseFocus(bool) {}
}
| 8,457 | 3,372 |
#include "pch.hpp"
#include "logger.hpp"
bool Logger::is_using_custom_color = false;
Logger::COLOR Logger::global_foregronnd_color = COLOR::BRIGHT_WHITE_FOREGROUND;
void Logger::log_info(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::BRIGHT_WHITE_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[INFO]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_warn(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::YELLOW_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[WARN]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_error(string message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::RED_FOREGROUND);
printf(string("\n" + get_date_time_string() + "[ERROR]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_info(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::BRIGHT_WHITE_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[INFO]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_warn(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::YELLOW_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[WARN]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_error(wstring message)
{
if (!is_using_custom_color) set_console_color_internal(COLOR::RED_FOREGROUND);
wprintf(wstring(L"\n" + get_date_time_wstring() + L"[ERROR]: " + message).c_str());
if (!is_using_custom_color) set_console_color_internal(global_foregronnd_color);
}
void Logger::log_nl(int amount)
{
if (amount < 1) amount = 1;
for (int i = 0; i < amount; i++) printf("\n");
}
void Logger::log_divide()
{
string divide = "";
for (int i = 0; i < get_console_buffer_width() - 1; i++) divide += "-";
printf(string("\n" + divide).c_str());
}
void Logger::set_global_foreground_color(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
global_foregronnd_color = color;
}
/*
void Logger::set_global_background_color(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
*/
void Logger::set_console_color(COLOR color)
{
is_using_custom_color = true;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
void Logger::clear_console_color()
{
is_using_custom_color = false;
}
void Logger::set_console_color_internal(COLOR color)
{
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(console, (unsigned short)color);
}
void Logger::flush_log_buffer()
{
COORD tl = { 0,0 };
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &s);
DWORD written = 0;
DWORD cells = s.dwSize.X * s.dwSize.Y;
FillConsoleOutputCharacter(console, ' ', cells, tl, &written);
FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
SetConsoleCursorPosition(console, tl);
}
void Logger::log_last_error()
{
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
string message(messageBuffer, size);
LocalFree(messageBuffer);
Logger::log_error(message);
}
void Logger::wait()
{
char c;
cin >> std::noskipws;
while (cin >> c) cout << c << std::endl;
}
string Logger::get_date_time_string()
{
time_t now = cr::system_clock::to_time_t(cr::system_clock::now());
tm current_time{};
localtime_s(¤t_time, &now);
string year = to_string(1900 + current_time.tm_year);
string month = current_time.tm_mon > 8 ? to_string(1 + current_time.tm_mon) : "0" + to_string(1 + current_time.tm_mon);
string day = current_time.tm_mday > 8 ? to_string(1 + current_time.tm_mday) : "0" + to_string(1 + current_time.tm_mday);
string hour = current_time.tm_hour != 60 ? current_time.tm_hour > 8 ? to_string(1 + current_time.tm_hour) : "0" + to_string(1 + current_time.tm_hour) : "00";
string minute = current_time.tm_min != 60 ? current_time.tm_min > 8 ? to_string(1 + current_time.tm_min) : "0" + to_string(1 + current_time.tm_min) : "00";
string second = current_time.tm_sec != 60 ? current_time.tm_sec > 8 ? to_string(1 + current_time.tm_sec) : "0" + to_string(1 + current_time.tm_sec) : "00";
string millisecond = to_string((cr::duration_cast<cr::milliseconds>(cr::system_clock::now().time_since_epoch())).count()).substr(10);
return "[" + year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second + "." + millisecond + "]";
}
wstring Logger::get_date_time_wstring()
{
return string_to_wstring_copy(get_date_time_string());
}
int Logger::get_console_buffer_width()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
} | 5,393 | 2,081 |
/**
* (c) 2019 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include <array>
#include <tuple>
#include <gtest/gtest.h>
#include <mega/base64.h>
#include <mega/filesystem.h>
#include <mega/utils.h>
#include "megafs.h"
TEST(utils, hashCombine_integer)
{
size_t hash = 0;
mega::hashCombine(hash, 42);
#ifdef _WIN32
// MSVC's std::hash gives different values than that of gcc/clang
ASSERT_EQ(sizeof(hash) == 4 ? 286246808ul : 10203658983813110072ull, hash);
#else
ASSERT_EQ(2654435811ull, hash);
#endif
}
TEST(CharacterSet, IterateUtf8)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator("abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'a');
EXPECT_EQ(it.get(), 'b');
EXPECT_EQ(it.get(), 'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator("q\xf0\x90\x80\x80r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), 'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), 'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), '\0');
}
}
TEST(CharacterSet, IterateUtf16)
{
using mega::unicodeCodepointIterator;
// Single code-unit.
{
auto it = unicodeCodepointIterator(L"abc");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'a');
EXPECT_EQ(it.get(), L'b');
EXPECT_EQ(it.get(), L'c');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
// Multiple code-unit.
{
auto it = unicodeCodepointIterator(L"q\xd800\xdc00r");
EXPECT_FALSE(it.end());
EXPECT_EQ(it.get(), L'q');
EXPECT_EQ(it.get(), 0x10000);
EXPECT_EQ(it.get(), L'r');
EXPECT_TRUE(it.end());
EXPECT_EQ(it.get(), L'\0');
}
}
using namespace mega;
using namespace std;
// Disambiguate between Microsoft's FileSystemType.
using ::mega::FileSystemType;
class ComparatorTest
: public ::testing::Test
{
public:
ComparatorTest()
: mFSAccess()
{
}
template<typename T, typename U>
int compare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, false);
}
template<typename T, typename U>
int ciCompare(const T& lhs, const U& rhs) const
{
return compareUtf(lhs, true, rhs, true, true);
}
LocalPath fromPath(const string& s)
{
return LocalPath::fromPath(s, mFSAccess);
}
template<typename T, typename U>
int fsCompare(const T& lhs, const U& rhs, const FileSystemType type) const
{
const auto caseInsensitive = isCaseInsensitive(type);
return compareUtf(lhs, true, rhs, true, caseInsensitive);
}
private:
FSACCESS_CLASS mFSAccess;
}; // ComparatorTest
TEST_F(ComparatorTest, CompareLocalPaths)
{
LocalPath lhs;
LocalPath rhs;
// Case insensitive
{
// Make sure basic characters are uppercased.
lhs = fromPath("abc");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("ABCD");
EXPECT_LT(ciCompare(lhs, rhs), 0);
EXPECT_GT(ciCompare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("A0B");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Make sure decoded characters are uppercased.
lhs = fromPath("%61%62%63");
rhs = fromPath("ABC");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = fromPath("A%qB%");
EXPECT_EQ(ciCompare(lhs, rhs), 0);
EXPECT_EQ(ciCompare(rhs, lhs), 0);
}
// Case sensitive
{
// Basic comparison.
lhs = fromPath("abc");
EXPECT_EQ(compare(lhs, lhs), 0);
// Make sure characters are not uppercased.
rhs = fromPath("ABC");
EXPECT_NE(compare(lhs, rhs), 0);
EXPECT_NE(compare(rhs, lhs), 0);
// Make sure comparison invariants are not violated.
lhs = fromPath("abc");
rhs = fromPath("abcd");
EXPECT_LT(compare(lhs, rhs), 0);
EXPECT_GT(compare(rhs, lhs), 0);
// Make sure escapes are decoded.
lhs = fromPath("a%30b");
rhs = fromPath("a0b");
EXPECT_EQ(compare(lhs, rhs), 0);
EXPECT_EQ(compare(rhs, lhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
EXPECT_EQ(compare(lhs, lhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = fromPath("A%070B1C");
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = fromPath("a%070b1c");
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST_F(ComparatorTest, CompareLocalPathAgainstString)
{
LocalPath lhs;
string rhs;
// Case insensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invariants.
lhs = fromPath("abc");
rhs = "abcd";
EXPECT_LT(ciCompare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(ciCompare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "A0b1C";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Escapes are uppercased.
lhs = fromPath("%61%62%63");
rhs = "ABC";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
// Invalid escapes are left as-is.
lhs = fromPath("a%qb%");
rhs = "A%QB%";
EXPECT_EQ(ciCompare(lhs, rhs), 0);
}
// Case sensitive
{
// Simple comparison.
lhs = fromPath("abc");
rhs = "abc";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invariants.
rhs = "abcd";
EXPECT_LT(compare(lhs, rhs), 0);
lhs = fromPath("abcd");
rhs = "abc";
EXPECT_GT(compare(lhs, rhs), 0);
// All local escapes are decoded.
lhs = fromPath("a%30b%31c");
rhs = "a0b1c";
EXPECT_EQ(compare(lhs, rhs), 0);
// Invalid escapes left as-is.
lhs = fromPath("a%qb%r");
rhs = "a%qb%r";
EXPECT_EQ(compare(lhs, rhs), 0);
}
// Filesystem-specific
{
lhs = fromPath("a\7%30b%31c");
rhs = "A%070B1C";
// exFAT, FAT32, NTFS and UNKNOWN are case-insensitive.
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXFAT), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_FAT32), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_NTFS), 0);
EXPECT_EQ(fsCompare(lhs, rhs, FS_UNKNOWN), 0);
#ifndef _WIN32
// Everything else is case-sensitive.
EXPECT_NE(fsCompare(lhs, rhs, FS_EXT), 0);
rhs = "a%070b1c";
EXPECT_EQ(fsCompare(lhs, rhs, FS_EXT), 0);
#endif // ! _WIN32
}
}
TEST(Conversion, HexVal)
{
// Decimal [0-9]
for (int i = 0x30; i < 0x3a; ++i)
{
EXPECT_EQ(hexval(i), i - 0x30);
}
// Lowercase hexadecimal [a-f]
for (int i = 0x41; i < 0x47; ++i)
{
EXPECT_EQ(hexval(i), i - 0x37);
}
// Uppercase hexadeimcal [A-F]
for (int i = 0x61; i < 0x67; ++i)
{
EXPECT_EQ(hexval(i), i - 0x57);
}
}
TEST(URLCodec, Unescape)
{
string input = "a%4a%4Bc";
string output;
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "aJKc");
}
TEST(URLCodec, UnescapeInvalidEscape)
{
string input;
string output;
// First character is invalid.
input = "a%qbc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%qbc");
// Second character is invalid.
input = "a%bqc";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%bqc");
}
TEST(URLCodec, UnescapeShortEscape)
{
string input;
string output;
// No hex digits.
input = "a%";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%");
// Single hex digit.
input = "a%a";
URLCodec::unescape(&input, &output);
EXPECT_EQ(output, "a%a");
}
| 9,294 | 3,726 |
#define DEBUG 0
#if DEBUG == 1
#define DEBUG_SCREEN_DESCRIPTOR 1
#define DEBUG_GLOBAL_COLOR_TABLE 1
#define DEBUG_PROCESSING_PLAIN_TEXT_EXT 1
#define DEBUG_PROCESSING_GRAPHIC_CONTROL_EXT 1
#define DEBUG_PROCESSING_APP_EXT 1
#define DEBUG_PROCESSING_COMMENT_EXT 1
#define DEBUG_PROCESSING_FILE_TERM 1
#define DEBUG_PROCESSING_TABLE_IMAGE_DESC 1
#define DEBUG_PROCESSING_TBI_DESC_START 1
#define DEBUG_PROCESSING_TBI_DESC_INTERLACED 1
#define DEBUG_PROCESSING_TBI_DESC_LOCAL_COLOR_TABLE 1
#define DEBUG_PROCESSING_TBI_DESC_LZWCODESIZE 1
#define DEBUG_PROCESSING_TBI_DESC_DATABLOCKSIZE 1
#define DEBUG_PROCESSING_TBI_DESC_LZWIMAGEDATA_OVERFLOW 1
#define DEBUG_PROCESSING_TBI_DESC_LZWIMAGEDATA_SIZE 1
#define DEBUG_PARSING_DATA 1
#define DEBUG_DECOMPRESS_AND_DISPLAY 1
#define DEBUG_WAIT_FOR_KEY_PRESS 0
#endif
#include <Arduino.h>
#include <SD.h>
#include "GIFDecoder.h"
File file;
const int WIDTH = 32;
const int HEIGHT = 32;
// maximum bounds of the decoded GIF (dimensions of imageData buffer)
// Error codes
#define ERROR_NONE 0
#define ERROR_FILEOPEN -1
#define ERROR_FILENOTGIF -2
#define ERROR_BADGIFFORMAT -3
#define ERROR_UNKNOWNCONTROLEXT -4
#define GIFHDRTAGNORM "GIF87a" // tag in valid GIF file
#define GIFHDRTAGNORM1 "GIF89a" // tag in valid GIF file
#define GIFHDRSIZE 6
// Global GIF specific definitions
#define COLORTBLFLAG 0x80
#define INTERLACEFLAG 0x40
#define TRANSPARENTFLAG 0x01
#define NO_TRANSPARENT_INDEX -1
// Disposal methods
#define DISPOSAL_NONE 0
#define DISPOSAL_LEAVE 1
#define DISPOSAL_BACKGROUND 2
#define DISPOSAL_RESTORE 3
// Logical screen descriptor attributes
int lsdWidth;
int lsdHeight;
int lsdPackedField;
int lsdAspectRatio;
int lsdBackgroundIndex;
// Table based image attributes
int tbiImageX;
int tbiImageY;
int tbiWidth;
int tbiHeight;
int tbiPackedBits;
boolean tbiInterlaced;
int frameDelay;
int transparentColorIndex;
int prevBackgroundIndex;
int prevDisposalMethod;
int disposalMethod;
int lzwCodeSize;
boolean keyFrame;
int rectX;
int rectY;
int rectWidth;
int rectHeight;
unsigned long nextFrameTime_ms;
int colorCount;
rgb24 palette[256];
char tempBuffer[260];
// Buffer image data is decoded into
byte imageData[WIDTH * HEIGHT];
// Backup image data buffer for saving portions of image disposal method == 3
byte imageDataBU[WIDTH * HEIGHT];
callback screenClearCallback;
callback updateScreenCallback;
pixel_callback drawPixelCallback;
callback startDrawingCallback;
void setStartDrawingCallback(callback f) {
startDrawingCallback = f;
}
void setUpdateScreenCallback(callback f) {
updateScreenCallback = f;
}
void setDrawPixelCallback(pixel_callback f) {
drawPixelCallback = f;
}
void setScreenClearCallback(callback f) {
screenClearCallback = f;
}
// Backup the read stream by n bytes
void backUpStream(int n) {
file.seek(file.position() - n);
}
// Read a file byte
int readByte() {
int b = file.read();
if (b == -1) {
Serial.println("Read error or EOF occurred");
}
return b;
}
// Read a file word
int readWord() {
int b0 = readByte();
int b1 = readByte();
return (b1 << 8) | b0;
}
// Read the specified number of bytes into the specified buffer
int readIntoBuffer(void *buffer, int numberOfBytes) {
int result = file.read(buffer, numberOfBytes);
if (result == -1) {
Serial.println("Read error or EOF occurred");
}
return result;
}
// Fill a portion of imageData buffer with a color index
void fillImageDataRect(byte colorIndex, int x, int y, int width, int height) {
int yOffset;
for (int yy = y; yy < height + y; yy++) {
yOffset = yy * WIDTH;
for (int xx = x; xx < width + x; xx++) {
imageData[yOffset + xx] = colorIndex;
}
}
}
// Fill entire imageData buffer with a color index
void fillImageData(byte colorIndex) {
memset(imageData, colorIndex, sizeof(imageData));
}
// Copy image data in rect from a src to a dst
void copyImageDataRect(byte *dst, byte *src, int x, int y, int width, int height) {
int yOffset, offset;
for (int yy = y; yy < height + y; yy++) {
yOffset = yy * WIDTH;
for (int xx = x; xx < width + x; xx++) {
offset = yOffset + xx;
dst[offset] = src[offset];
}
}
}
// Make sure the file is a Gif file
boolean parseGifHeader() {
char buffer[10];
readIntoBuffer(buffer, GIFHDRSIZE);
if ((strncmp(buffer, GIFHDRTAGNORM, GIFHDRSIZE) != 0) &&
(strncmp(buffer, GIFHDRTAGNORM1, GIFHDRSIZE) != 0)) {
return false;
}
else {
return true;
}
}
// Parse the logical screen descriptor
void parseLogicalScreenDescriptor() {
lsdWidth = readWord();
lsdHeight = readWord();
lsdPackedField = readByte();
lsdBackgroundIndex = readByte();
lsdAspectRatio = readByte();
#if DEBUG == 1 && DEBUG_SCREEN_DESCRIPTOR == 1
Serial.print("lsdWidth: ");
Serial.println(lsdWidth);
Serial.print("lsdHeight: ");
Serial.println(lsdHeight);
Serial.print("lsdPackedField: ");
Serial.println(lsdPackedField, HEX);
Serial.print("lsdBackgroundIndex: ");
Serial.println(lsdBackgroundIndex);
Serial.print("lsdAspectRatio: ");
Serial.println(lsdAspectRatio);
#endif
}
// Parse the global color table
void parseGlobalColorTable() {
// Does a global color table exist?
if (lsdPackedField & COLORTBLFLAG) {
// A GCT was present determine how many colors it contains
colorCount = 1 << ((lsdPackedField & 7) + 1);
#if DEBUG == 1 && DEBUG_GLOBAL_COLOR_TABLE == 1
Serial.print("Global color table with ");
Serial.print(colorCount);
Serial.println(" colors present");
#endif
// Read color values into the palette array
int colorTableBytes = sizeof(rgb24) * colorCount;
readIntoBuffer(palette, colorTableBytes);
}
}
// Parse plain text extension and dispose of it
void parsePlainTextExtension() {
#if DEBUG == 1 && DEBUG_PROCESSING_PLAIN_TEXT_EXT == 1
Serial.println("\nProcessing Plain Text Extension");
#endif
// Read plain text header length
byte len = readByte();
// Consume plain text header data
readIntoBuffer(tempBuffer, len);
// Consume the plain text data in blocks
len = readByte();
while (len != 0) {
readIntoBuffer(tempBuffer, len);
len = readByte();
}
}
// Parse a graphic control extension
void parseGraphicControlExtension() {
#if DEBUG == 1 && DEBUG_PROCESSING_GRAPHIC_CONTROL_EXT == 1
Serial.println("\nProcessing Graphic Control Extension");
#endif
int len = readByte(); // Check length
if (len != 4) {
Serial.println("Bad graphic control extension");
}
int packedBits = readByte();
frameDelay = readWord();
transparentColorIndex = readByte();
if ((packedBits & TRANSPARENTFLAG) == 0) {
// Indicate no transparent index
transparentColorIndex = NO_TRANSPARENT_INDEX;
}
disposalMethod = (packedBits >> 2) & 7;
if (disposalMethod > 3) {
disposalMethod = 0;
Serial.println("Invalid disposal value");
}
readByte(); // Toss block end
#if DEBUG == 1 && DEBUG_PROCESSING_GRAPHIC_CONTROL_EXT == 1
Serial.print("PacketBits: ");
Serial.println(packedBits, HEX);
Serial.print("Frame delay: ");
Serial.println(frameDelay);
Serial.print("transparentColorIndex: ");
Serial.println(transparentColorIndex);
Serial.print("disposalMethod: ");
Serial.println(disposalMethod);
#endif
}
// Parse application extension
void parseApplicationExtension() {
memset(tempBuffer, 0, sizeof(tempBuffer));
#if DEBUG == 1 && DEBUG_PROCESSING_APP_EXT == 1
Serial.println("\nProcessing Application Extension");
#endif
// Read block length
byte len = readByte();
// Read app data
readIntoBuffer(tempBuffer, len);
#if DEBUG == 1 && DEBUG_PROCESSING_APP_EXT == 1
// Conditionally display the application extension string
if (strlen(tempBuffer) != 0) {
Serial.print("Application Extension: ");
Serial.println(tempBuffer);
}
#endif
// Consume any additional app data
len = readByte();
while (len != 0) {
readIntoBuffer(tempBuffer, len);
len = readByte();
}
}
// Parse comment extension
void parseCommentExtension() {
#if DEBUG == 1 && DEBUG_PROCESSING_COMMENT_EXT == 1
Serial.println("\nProcessing Comment Extension");
#endif
// Read block length
byte len = readByte();
while (len != 0) {
// Clear buffer
memset(tempBuffer, 0, sizeof(tempBuffer));
// Read len bytes into buffer
readIntoBuffer(tempBuffer, len);
#if DEBUG == 1 && DEBUG_PROCESSING_COMMENT_EXT == 1
// Display the comment extension string
if (strlen(tempBuffer) != 0) {
Serial.print("Comment Extension: ");
Serial.println(tempBuffer);
}
#endif
// Read the new block length
len = readByte();
}
}
// Parse file terminator
int parseGIFFileTerminator() {
#if DEBUG == 1 && DEBUG_PROCESSING_FILE_TERM == 1
Serial.println("\nProcessing file terminator");
#endif
byte b = readByte();
if (b != 0x3B) {
#if DEBUG == 1 && DEBUG_PROCESSING_FILE_TERM == 1
Serial.print("Terminator byte: ");
Serial.println(b, HEX);
#endif
Serial.println("Bad GIF file format - Bad terminator");
return ERROR_BADGIFFORMAT;
}
else {
return ERROR_NONE;
}
}
// Parse table based image data
void parseTableBasedImage() {
#if DEBUG == 1 && DEBUG_PROCESSING_TBI_DESC_START == 1
Serial.println("\nProcessing Table Based Image Descriptor");
#endif
// Parse image descriptor
tbiImageX = readWord();
tbiImageY = readWord();
tbiWidth = readWord();
tbiHeight = readWord();
tbiPackedBits = readByte();
#if DEBUG == 1
Serial.print("tbiImageX: ");
Serial.println(tbiImageX);
Serial.print("tbiImageY: ");
Serial.println(tbiImageY);
Serial.print("tbiWidth: ");
Serial.println(tbiWidth);
Serial.print("tbiHeight: ");
Serial.println(tbiHeight);
Serial.print("PackedBits: ");
Serial.println(tbiPackedBits, HEX);
#endif
// Is this image interlaced ?
tbiInterlaced = ((tbiPackedBits & INTERLACEFLAG) != 0);
#if DEBUG == 1 && DEBUG_PROCESSING_TBI_DESC_INTERLACED == 1
Serial.print("Image interlaced: ");
Serial.println((tbiInterlaced != 0) ? "Yes" : "No");
#endif
// Does this image have a local color table ?
boolean localColorTable = ((tbiPackedBits & COLORTBLFLAG) != 0);
if (localColorTable) {
int colorBits = ((tbiPackedBits & 7) + 1);
colorCount = 1 << colorBits;
#if DEBUG == 1 && DEBUG_PROCESSING_TBI_DESC_LOCAL_COLOR_TABLE == 1
Serial.print("Local color table with ");
Serial.print(colorCount);
Serial.println(" colors present");
#endif
// Read colors into palette
int colorTableBytes = sizeof(rgb24) * colorCount;
readIntoBuffer(palette, colorTableBytes);
}
// One time initialization of imageData before first frame
if (keyFrame) {
if (transparentColorIndex == NO_TRANSPARENT_INDEX) {
fillImageData(lsdBackgroundIndex);
}
else {
fillImageData(transparentColorIndex);
}
keyFrame = false;
rectX = 0;
rectY = 0;
rectWidth = WIDTH;
rectHeight = HEIGHT;
}
// Don't clear matrix screen for these disposal methods
if ((prevDisposalMethod != DISPOSAL_NONE) && (prevDisposalMethod != DISPOSAL_LEAVE)) {
if(screenClearCallback)
(*screenClearCallback)();
}
// Process previous disposal method
if (prevDisposalMethod == DISPOSAL_BACKGROUND) {
// Fill portion of imageData with previous background color
fillImageDataRect(prevBackgroundIndex, rectX, rectY, rectWidth, rectHeight);
}
else if (prevDisposalMethod == DISPOSAL_RESTORE) {
copyImageDataRect(imageData, imageDataBU, rectX, rectY, rectWidth, rectHeight);
}
// Save disposal method for this frame for next time
prevDisposalMethod = disposalMethod;
if (disposalMethod != DISPOSAL_NONE) {
// Save dimensions of this frame
rectX = tbiImageX;
rectY = tbiImageY;
rectWidth = tbiWidth;
rectHeight = tbiHeight;
if (disposalMethod == DISPOSAL_BACKGROUND) {
if (transparentColorIndex != NO_TRANSPARENT_INDEX) {
prevBackgroundIndex = transparentColorIndex;
}
else {
prevBackgroundIndex = lsdBackgroundIndex;
}
}
else if (disposalMethod == DISPOSAL_RESTORE) {
copyImageDataRect(imageDataBU, imageData, rectX, rectY, rectWidth, rectHeight);
}
}
// Read the min LZW code size
lzwCodeSize = readByte();
#if DEBUG == 1 && DEBUG_PROCESSING_TBI_DESC_LZWCODESIZE == 1
Serial.print("LzwCodeSize: ");
Serial.println(lzwCodeSize);
Serial.println("File Position Before: ");
Serial.println(file.position());
#endif
unsigned long filePositionBefore = file.position();
// Gather the lzw image data
// NOTE: the dataBlockSize byte is left in the data as the lzw decoder needs it
int offset = 0;
int dataBlockSize = readByte();
while (dataBlockSize != 0) {
#if DEBUG == 1 && DEBUG_PROCESSING_TBI_DESC_DATABLOCKSIZE == 1
Serial.print("dataBlockSize: ");
Serial.println(dataBlockSize);
#endif
backUpStream(1);
dataBlockSize++;
file.seek(file.position() + dataBlockSize);
offset += dataBlockSize;
dataBlockSize = readByte();
}
#if DEBUG == 1 && DEBUG_PROCESSING_TBI_DESC_LZWIMAGEDATA_SIZE == 1
Serial.print("total lzwImageData Size: ");
Serial.println(offset);
Serial.println("File Position Test: ");
Serial.println(file.position());
#endif
// this is the position where GIF decoding needs to pick up after decompressing frame
unsigned long filePositionAfter = file.position();
file.seek(filePositionBefore);
// Process the animation frame for display
// Initialize the LZW decoder for this frame
lzw_decode_init(lzwCodeSize, readIntoBuffer);
lzw_setTempBuffer((byte*)tempBuffer);
// Make sure there is at least some delay between frames
if (frameDelay < 1) {
frameDelay = 1;
}
// Decompress LZW data and display the frame
decompressAndDisplayFrame(filePositionAfter);
// Graphic control extension is for a single frame
transparentColorIndex = NO_TRANSPARENT_INDEX;
disposalMethod = DISPOSAL_NONE;
}
// Parse gif data
int parseData() {
#if DEBUG == 1 && DEBUG_PARSING_DATA == 1
Serial.println("\nParsing Data Block");
#endif
boolean done = false;
while (! done) {
#if DEBUG == 1 && DEBUG_WAIT_FOR_KEY_PRESS == 1
Serial.println("\nPress Key For Next");
while(Serial.read() <= 0);
#endif
// Determine what kind of data to process
byte b = readByte();
if (b == 0x2c) {
// Parse table based image
#if DEBUG == 1 && DEBUG_PARSING_DATA == 1
Serial.println("\nParsing Table Based");
#endif
parseTableBasedImage();
}
else if (b == 0x21) {
// Parse extension
b = readByte();
#if DEBUG == 1 && DEBUG_PARSING_DATA == 1
Serial.println("\nParsing Extension");
#endif
// Determine which kind of extension to parse
switch (b) {
case 0x01:
// Plain test extension
parsePlainTextExtension();
break;
case 0xf9:
// Graphic control extension
parseGraphicControlExtension();
break;
case 0xfe:
// Comment extension
parseCommentExtension();
break;
case 0xff:
// Application extension
parseApplicationExtension();
break;
default:
Serial.print("Unknown control extension: ");
Serial.println(b, HEX);
return ERROR_UNKNOWNCONTROLEXT;
}
}
else {
#if DEBUG == 1 && DEBUG_PARSING_DATA == 1
Serial.println("\nParsing Done");
#endif
done = true;
// Push unprocessed byte back into the stream for later processing
backUpStream(1);
}
}
return ERROR_NONE;
}
// Attempt to parse the gif file
int processGIFFile(const char *pathname) {
// Initialize variables
keyFrame = true;
prevDisposalMethod = DISPOSAL_NONE;
transparentColorIndex = NO_TRANSPARENT_INDEX;
Serial.print("Pathname: ");
Serial.println(pathname);
if(file)
file.close();
// Attempt to open the file for reading
file = SD.open(pathname);
if (!file) {
Serial.println("Error opening GIF file");
return ERROR_FILEOPEN;
}
// Validate the header
if (! parseGifHeader()) {
Serial.println("Not a GIF file");
file.close();
return ERROR_FILENOTGIF;
}
// If we get here we have a gif file to process
// Parse the logical screen descriptor
parseLogicalScreenDescriptor();
// Parse the global color table
parseGlobalColorTable();
// Parse gif data
int result = parseData();
if (result != ERROR_NONE) {
Serial.println("Error: ");
Serial.println(result);
Serial.println(" occurred during parsing of data");
file.close();
return result;
}
// Parse the gif file terminator
result = parseGIFFileTerminator();
file.close();
Serial.println("Success");
return result;
}
// Decompress LZW data and display animation frame
void decompressAndDisplayFrame(unsigned long filePositionAfter) {
// Each pixel of image is 8 bits and is an index into the palette
// How the image is decoded depends upon whether it is interlaced or not
// Decode the interlaced LZW data into the image buffer
if (tbiInterlaced) {
// Decode every 8th line starting at line 0
for (int line = tbiImageY + 0; line < tbiHeight + tbiImageY; line += 8) {
lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);
}
// Decode every 8th line starting at line 4
for (int line = tbiImageY + 4; line < tbiHeight + tbiImageY; line += 8) {
lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);
}
// Decode every 4th line starting at line 2
for (int line = tbiImageY + 2; line < tbiHeight + tbiImageY; line += 4) {
lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);
}
// Decode every 2nd line starting at line 1
for (int line = tbiImageY + 1; line < tbiHeight + tbiImageY; line += 2) {
lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);
}
}
else {
// Decode the non interlaced LZW data into the image data buffer
for (int line = tbiImageY; line < tbiHeight + tbiImageY; line++) {
lzw_decode(imageData + (line * WIDTH) + tbiImageX, tbiWidth);
}
}
#if DEBUG == 1 && DEBUG_DECOMPRESS_AND_DISPLAY == 1
Serial.println("File Position After: ");
Serial.println(file.position());
#endif
#if DEBUG == 1 && DEBUG_WAIT_FOR_KEY_PRESS == 1
Serial.println("\nPress Key For Next");
while(Serial.read() <= 0);
#endif
// LZW doesn't parse through all the data, manually set position
file.seek(filePositionAfter);
// Optional callback can be used to get drawing routines ready
if(startDrawingCallback)
(*startDrawingCallback)();
// Image data is decompressed, now display portion of image affected by frame
int yOffset, pixel;
for (int y = tbiImageY; y < tbiHeight + tbiImageY; y++) {
yOffset = y * WIDTH;
for (int x = tbiImageX; x < tbiWidth + tbiImageX; x++) {
// Get the next pixel
pixel = imageData[yOffset + x];
// Check pixel transparency
if (pixel == transparentColorIndex) {
continue;
}
// Pixel not transparent so get color from palette and draw the pixel
if(drawPixelCallback)
(*drawPixelCallback)(x, y, palette[pixel].red, palette[pixel].green, palette[pixel].blue);
}
}
// Make animation frame visible
// swapBuffers() call can take up to 1/framerate seconds to return (it waits until a buffer copy is complete)
// note the time before calling
// wait until time to display next frame
while(nextFrameTime_ms > millis());
// calculate time to display next frame
nextFrameTime_ms = millis() + (10 * frameDelay);
if(updateScreenCallback)
(*updateScreenCallback)();
}
| 21,355 | 6,707 |
#ifndef PACWOMAN_PACWOMAN_HPP
#define PACWOMAN_PACWOMAN_HPP
#include "Animator.hpp"
#include "Character.hpp"
class PacWoman : public Character
{
public:
PacWoman(sf::Texture& texture);
void die();
bool isDying() const;
bool isDead() const;
void update(sf::Time delta);
private:
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
bool m_isDying;
bool m_isDead;
sf::Sprite m_visual;
Animator m_runAnimator;
Animator m_dieAnimator;
};
#endif // PACWOMAN_PACWOMAN_HPP
| 511 | 225 |
#define _CRT_SECURE_NO_WARNINGS
#include <unicorn/unicorn.h>
#include <engextcpp.hpp>
#include <windows.h>
#include <TlHelp32.h>
#include <stdio.h>
#include <list>
#include <memory>
#include <strsafe.h>
#include <interface.h>
#include <engine.h>
#include <capstone.h>
#include <engine_linker.h>
#include <helper.h>
#include <emulator.h>
static void hook_code(uc_engine *uc, uint64_t address, uint32_t size, void *user_data)
{
dprintf("run %I64x\n", address);
}
static void hook_unmap_memory(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data)
{
if (type == UC_MEM_WRITE_UNMAPPED || type == UC_MEM_READ_UNMAPPED)
{
dprintf("unmaped memory.. %I64x\n", address);
}
}
static void hook_fetch_memory(uc_engine *uc, uc_mem_type type, uint64_t address, int size, int64_t value, void *user_data)
{
if (type == UC_MEM_FETCH_UNMAPPED)
{
dprintf("fetch memory.. %I64x\n", address);
}
}
unsigned long long __stdcall alignment(unsigned long long region_size, unsigned long image_aligin)
{
unsigned long mod = region_size % image_aligin;
region_size -= mod;
return region_size + image_aligin;
}
//
//
//
uc_engine *_uc = nullptr;
bool __stdcall query(unsigned long long address, unsigned long long *base, unsigned long long *size)
{
uc_mem_region *um = nullptr;
uint32_t count = 0;
if (uc_mem_regions(_uc, &um, &count) != 0)
return false;
std::shared_ptr<void> uc_memory_closer(um, free);
for (unsigned int i = 0; i < count; ++i)
{
if (address >= um[i].begin && address <= um[i].end)
{
*base = um[i].begin;
*size = um[i].end - um[i].begin;
return true;
}
}
return false;
}
void set_global_descriptor(SegmentDescriptor *desc, uint32_t base, uint32_t limit, uint8_t is_code)
{
desc->descriptor = 0;
desc->base_low = base & 0xffff;
desc->base_mid = (base >> 16) & 0xff;
desc->base_hi = base >> 24;
if (limit > 0xfffff)
{
limit >>= 12;
desc->granularity = 1;
}
desc->limit_low = limit & 0xffff;
desc->limit_hi = limit >> 16;
desc->dpl = 3;
desc->present = 1;
desc->db = 1;
desc->type = is_code ? 0xb : 3;
desc->system = 1;
}
bool __stdcall read_x86_cpu_context(cpu_context_type *context)
{
int x86_register[] = { UC_X86_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long *read_register = nullptr;
void **read_ptr = nullptr;
read_register = (unsigned long *)malloc(sizeof(unsigned long)*size);
if (!read_register)
return false;
std::shared_ptr<void> read_register_closer(read_register, free);
memset(read_register, 0, sizeof(unsigned long)*size);
read_ptr = (void **)malloc(sizeof(void **)*size);
if (!read_ptr)
return false;
std::shared_ptr<void> read_ptr_closer(read_ptr, free);
memset(read_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
read_ptr[i] = &read_register[i];
if (uc_reg_read_batch(_uc, x86_register, read_ptr, size) != 0)
return false;
context->rax = read_register[PR_RAX];
context->rbx = read_register[PR_RBX];
context->rcx = read_register[PR_RCX];
context->rdx = read_register[PR_RDX];
context->rsi = read_register[PR_RSI];
context->rdi = read_register[PR_RDI];
context->rsp = read_register[PR_RSP];
context->rbp = read_register[PR_RBP];
context->rip = read_register[PR_RIP];
context->xmm0 = read_register[PR_XMM0];
context->xmm1 = read_register[PR_XMM1];
context->xmm2 = read_register[PR_XMM2];
context->xmm3 = read_register[PR_XMM3];
context->xmm4 = read_register[PR_XMM4];
context->xmm5 = read_register[PR_XMM5];
context->xmm6 = read_register[PR_XMM6];
context->xmm7 = read_register[PR_XMM7];
context->ymm0 = read_register[PR_YMM0];
context->ymm1 = read_register[PR_YMM1];
context->ymm2 = read_register[PR_YMM2];
context->ymm3 = read_register[PR_YMM3];
context->ymm4 = read_register[PR_YMM4];
context->ymm5 = read_register[PR_YMM5];
context->ymm6 = read_register[PR_YMM6];
context->ymm7 = read_register[PR_YMM7];
context->efl = read_register[PR_EFLAGS];
context->cs = (unsigned short)read_register[PR_REG_CS];
context->ds = (unsigned short)read_register[PR_REG_DS];
context->es = (unsigned short)read_register[PR_REG_ES];
context->fs = (unsigned short)read_register[PR_REG_FS];
context->gs = (unsigned short)read_register[PR_REG_GS];
context->ss = (unsigned short)read_register[PR_REG_SS];
return true;
}
bool __stdcall write_x86_cpu_context(cpu_context_type context)
{
int x86_register[] = { UC_X86_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long *write_register = nullptr;
void **write_ptr = nullptr;
write_register = (unsigned long *)malloc(sizeof(unsigned long)*size);
if (!write_register)
return false;
std::shared_ptr<void> write_register_closer(write_register, free);
memset(write_register, 0, sizeof(unsigned long)*size);
write_ptr = (void **)malloc(sizeof(void **)*size);
if (!write_ptr)
return false;
std::shared_ptr<void> write_ptr_closer(write_ptr, free);
memset(write_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
write_ptr[i] = &write_register[i];
write_register[PR_RAX] = (unsigned long)context.rax;
write_register[PR_RBX] = (unsigned long)context.rbx;
write_register[PR_RCX] = (unsigned long)context.rcx;
write_register[PR_RDX] = (unsigned long)context.rdx;
write_register[PR_RSI] = (unsigned long)context.rsi;
write_register[PR_RDI] = (unsigned long)context.rdi;
write_register[PR_RSP] = (unsigned long)context.rsp;
write_register[PR_RBP] = (unsigned long)context.rbp;
write_register[PR_RIP] = (unsigned long)context.rip;
write_register[PR_EFLAGS] = (unsigned long)context.efl;
write_register[PR_XMM0] = (unsigned long)context.xmm0;
write_register[PR_XMM1] = (unsigned long)context.xmm1;
write_register[PR_XMM2] = (unsigned long)context.xmm2;
write_register[PR_XMM3] = (unsigned long)context.xmm3;
write_register[PR_XMM4] = (unsigned long)context.xmm4;
write_register[PR_XMM5] = (unsigned long)context.xmm5;
write_register[PR_XMM6] = (unsigned long)context.xmm6;
write_register[PR_XMM7] = (unsigned long)context.xmm7;
write_register[PR_YMM0] = (unsigned long)context.ymm0;
write_register[PR_YMM1] = (unsigned long)context.ymm1;
write_register[PR_YMM2] = (unsigned long)context.ymm2;
write_register[PR_YMM3] = (unsigned long)context.ymm3;
write_register[PR_YMM4] = (unsigned long)context.ymm4;
write_register[PR_YMM5] = (unsigned long)context.ymm5;
write_register[PR_YMM6] = (unsigned long)context.ymm6;
write_register[PR_YMM7] = (unsigned long)context.ymm7;
write_register[PR_REG_CS] = context.cs;
write_register[PR_REG_DS] = context.ds;
write_register[PR_REG_ES] = context.es;
write_register[PR_REG_FS] = context.fs;
write_register[PR_REG_GS] = context.gs;
write_register[PR_REG_SS] = context.ss;
if (uc_reg_write_batch(_uc, x86_register, write_ptr, size) != 0)
return false;
return true;
}
bool __stdcall write_x64_cpu_context(cpu_context_type context)
{
#ifdef _WIN64
int x86_register[] = { UC_X64_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long long *write_register = nullptr;
void **write_ptr = nullptr;
write_register = (unsigned long long *)malloc(sizeof(unsigned long long)*size);
if (!write_register)
return false;
std::shared_ptr<void> write_register_closer(write_register, free);
memset(write_register, 0, sizeof(unsigned long long)*size);
write_ptr = (void **)malloc(sizeof(void **)*size);
if (!write_ptr)
return false;
std::shared_ptr<void> write_ptr_closer(write_ptr, free);
memset(write_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
write_ptr[i] = &write_register[i];
write_register[PR_RAX] = context.rax;
write_register[PR_RBX] = context.rbx;
write_register[PR_RCX] = context.rcx;
write_register[PR_RDX] = context.rdx;
write_register[PR_RSI] = context.rsi;
write_register[PR_RDI] = context.rdi;
write_register[PR_RSP] = context.rsp;
write_register[PR_RBP] = context.rbp;
write_register[PR_RIP] = context.rip;
write_register[PR_R8] = context.r8;
write_register[PR_R9] = context.r9;
write_register[PR_R10] = context.r10;
write_register[PR_R11] = context.r11;
write_register[PR_R12] = context.r12;
write_register[PR_R13] = context.r13;
write_register[PR_R14] = context.r14;
write_register[PR_R15] = context.r15;
write_register[PR_EFLAGS] = (unsigned long)context.efl;
write_register[PR_XMM0] = context.xmm0;
write_register[PR_XMM1] = context.xmm1;
write_register[PR_XMM2] = context.xmm2;
write_register[PR_XMM3] = context.xmm3;
write_register[PR_XMM4] = context.xmm4;
write_register[PR_XMM5] = context.xmm5;
write_register[PR_XMM6] = context.xmm6;
write_register[PR_XMM7] = context.xmm7;
write_register[PR_XMM8] = context.xmm8;
write_register[PR_XMM9] = context.xmm9;
write_register[PR_XMM10] = context.xmm10;
write_register[PR_XMM11] = context.xmm11;
write_register[PR_XMM12] = context.xmm12;
write_register[PR_XMM13] = context.xmm13;
write_register[PR_XMM14] = context.xmm14;
write_register[PR_XMM15] = context.xmm15;
write_register[PR_YMM0] = context.ymm0;
write_register[PR_YMM1] = context.ymm1;
write_register[PR_YMM2] = context.ymm2;
write_register[PR_YMM3] = context.ymm3;
write_register[PR_YMM4] = context.ymm4;
write_register[PR_YMM5] = context.ymm5;
write_register[PR_YMM6] = context.ymm6;
write_register[PR_YMM7] = context.ymm7;
write_register[PR_YMM8] = context.ymm8;
write_register[PR_YMM9] = context.ymm9;
write_register[PR_YMM10] = context.ymm10;
write_register[PR_YMM11] = context.ymm11;
write_register[PR_YMM12] = context.ymm12;
write_register[PR_YMM13] = context.ymm13;
write_register[PR_YMM14] = context.ymm14;
write_register[PR_YMM15] = context.ymm15;
write_register[PR_REG_CS] = context.cs;
write_register[PR_REG_DS] = context.ds;
write_register[PR_REG_ES] = context.es;
write_register[PR_REG_FS] = context.fs;
write_register[PR_REG_GS] = context.gs;
write_register[PR_REG_SS] = context.ss;
if (uc_reg_write_batch(_uc, x86_register, write_ptr, size) != 0)
return false;
#endif
return true;
}
bool __stdcall read_x64_cpu_context(cpu_context_type *context)
{
#ifdef _WIN64
int x86_register[] = { UC_X64_REGISTER_SET };
int size = sizeof(x86_register) / sizeof(int);
unsigned long long *read_register = nullptr;
void **read_ptr = nullptr;
read_register = (unsigned long long *)malloc(sizeof(unsigned long long)*size);
if (!read_register)
return false;
std::shared_ptr<void> read_register_closer(read_register, free);
memset(read_register, 0, sizeof(unsigned long long)*size);
read_ptr = (void **)malloc(sizeof(void **)*size);
if (!read_ptr)
return false;
std::shared_ptr<void> read_ptr_closer(read_ptr, free);
memset(read_ptr, 0, sizeof(void **)*size);
for (int i = 0; i < size; ++i)
read_ptr[i] = &read_register[i];
if (uc_reg_read_batch(_uc, x86_register, read_ptr, size) != 0)
return false;
context->rax = read_register[PR_RAX];
context->rbx = read_register[PR_RBX];
context->rcx = read_register[PR_RCX];
context->rdx = read_register[PR_RDX];
context->rsi = read_register[PR_RSI];
context->rdi = read_register[PR_RDI];
context->rsp = read_register[PR_RSP];
context->rbp = read_register[PR_RBP];
context->rip = read_register[PR_RIP];
context->r8 = read_register[PR_R8];
context->r9 = read_register[PR_R9];
context->r10 = read_register[PR_R10];
context->r11 = read_register[PR_R11];
context->r12 = read_register[PR_R12];
context->r13 = read_register[PR_R13];
context->r14 = read_register[PR_R14];
context->r15 = read_register[PR_R15];
context->efl = (unsigned long)read_register[PR_EFLAGS];
context->xmm0 = read_register[PR_XMM0];
context->xmm1 = read_register[PR_XMM1];
context->xmm2 = read_register[PR_XMM2];
context->xmm3 = read_register[PR_XMM3];
context->xmm4 = read_register[PR_XMM4];
context->xmm5 = read_register[PR_XMM5];
context->xmm6 = read_register[PR_XMM6];
context->xmm7 = read_register[PR_XMM7];
context->xmm8 = read_register[PR_XMM8];
context->xmm9 = read_register[PR_XMM9];
context->xmm10 = read_register[PR_XMM10];
context->xmm11 = read_register[PR_XMM11];
context->xmm12 = read_register[PR_XMM12];
context->xmm13 = read_register[PR_XMM13];
context->xmm14 = read_register[PR_XMM14];
context->xmm15 = read_register[PR_XMM15];
context->ymm0 = read_register[PR_YMM0];
context->ymm1 = read_register[PR_YMM1];
context->ymm2 = read_register[PR_YMM2];
context->ymm3 = read_register[PR_YMM3];
context->ymm4 = read_register[PR_YMM4];
context->ymm5 = read_register[PR_YMM5];
context->ymm6 = read_register[PR_YMM6];
context->ymm7 = read_register[PR_YMM7];
context->ymm8 = read_register[PR_YMM8];
context->ymm9 = read_register[PR_YMM9];
context->ymm10 = read_register[PR_YMM10];
context->ymm11 = read_register[PR_YMM11];
context->ymm12 = read_register[PR_YMM12];
context->ymm13 = read_register[PR_YMM13];
context->ymm14 = read_register[PR_YMM14];
context->ymm15 = read_register[PR_YMM15];
context->cs = (unsigned short)read_register[PR_REG_CS];
context->ds = (unsigned short)read_register[PR_REG_DS];
context->es = (unsigned short)read_register[PR_REG_ES];
context->fs = (unsigned short)read_register[PR_REG_FS];
context->gs = (unsigned short)read_register[PR_REG_GS];
context->ss = (unsigned short)read_register[PR_REG_SS];
#endif
return true;
}
void __stdcall print_reg_64(unsigned long long c, unsigned long long b)
{
if (c != b)
g_Ext->Dml("<b><col fg=\"changed\">%0*I64x</col></b>", 16, c);
else
dprintf("%0*I64x", 16, c);
}
void __stdcall print_reg_32(unsigned long long c, unsigned long long b)
{
if (c != b)
g_Ext->Dml("<b><col fg=\"changed\">%08x</col></b>", c);
else
dprintf("%08x", c);
}
void __stdcall view_cpu_context()
{
cpu_context_type context;
#ifdef _WIN64
read_x64_cpu_context(&context);
dprintf(" rax=%0*I64x rbx=%0*I64x rcx=%0*I64x rdx=%0*I64x rsi=%0*I64x rdi=%0*I64x\n", 16, context.rax, 16, context.rbx, 16, context.rcx, 16, context.rdx, 16, context.rsi, 16, context.rdi);
dprintf(" rip=%0*I64x rsp=%0*I64x rbp=%0*I64x efl=%0*I64x\n", 16, context.rip, 16, context.rsp, 16, context.rbp, context.efl);
dprintf(" r8=%0*I64x r9=%0*I64x r10=%0*I64x r11=%0*I64x r12=%0*I64x r13=%0*I64x r14=%0*I64x r15=%0*I64x\n", 16, context.r8, 16, context.r9, 16, context.r10, 16, context.r11, 16, context.r12, 16, context.r13, 16, context.r14, 16, context.r15);
dprintf(" cs=%x ds=%x es=%x fs=%x gs=%x %ss\n", context.cs, context.ds, context.es, context.fs, context.gs, context.ss);
#else
read_x86_cpu_context(&context);
dprintf(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n", (unsigned long)context.rax, (unsigned long)context.rbx, (unsigned long)context.rcx, (unsigned long)context.rdx, (unsigned long)context.rsi, (unsigned long)context.rdi);
dprintf(" eip=%08x esp=%08x ebp=%08x efl=%08x\n", (unsigned long)context.rip, (unsigned long)context.rsp, (unsigned long)context.rbp, (unsigned long)context.efl);
dprintf(" cs=%x ds=%x es=%x fs=%x gs=%x %ss\n", context.cs, context.ds, context.es, context.fs, context.gs, context.ss);
#endif
dprintf("\n");
char str[1024] = { 0, };
Disasm(&context.rip, str, false);
dprintf(" %s", str);
dprintf("\n");
}
bool __stdcall create_global_descriptor_table(cpu_context_type context, unsigned long mode)
{
SegmentDescriptor global_descriptor[31];
memset(global_descriptor, 0, sizeof(global_descriptor));
context.ss = 0x88; // rpl = 0
context.gs = 0x63;
set_global_descriptor(&global_descriptor[0x33 >> 3], 0, 0xfffff000, 1); // 64 code
set_global_descriptor(&global_descriptor[context.cs >> 3], 0, 0xfffff000, 1);
set_global_descriptor(&global_descriptor[context.ds >> 3], 0, 0xfffff000, 0);
set_global_descriptor(&global_descriptor[context.fs >> 3], 0, 0xfff, 0);
set_global_descriptor(&global_descriptor[context.gs >> 3], 0, 0xfffff000, 0);
set_global_descriptor(&global_descriptor[context.ss >> 3], 0, 0xfffff000, 0);
global_descriptor[context.ss >> 3].dpl = 0; // dpl = 0, cpl = 0
unsigned long long gdt_base = 0xc0000000;
uc_x86_mmr gdtr;
gdtr.base = gdt_base;
gdtr.limit = (sizeof(SegmentDescriptor) * 31) - 1;
if (uc_reg_write(_uc, UC_X86_REG_GDTR, &gdtr) != 0)
return false;
if (uc_mem_map(_uc, gdt_base, (size_t)0x10000, UC_PROT_ALL) == 0)
{
if (uc_mem_write(_uc, gdt_base, global_descriptor, sizeof(global_descriptor)) == 0)
{
#ifdef _WIN64
write_x64_cpu_context(context);
#else
write_x86_cpu_context(context);
#endif
}
}
return true;
}
//
//
//
EXT_CLASS_COMMAND(WindbgEngine, open, "", "{bit;ed,o;bit;;}")
{
if (!HasArg("bit"))
{
return;
}
if (_uc)
{
uc_close(_uc);
}
uc_mode mode;
unsigned long long bit = GetArgU64("bit", false);
if (bit == 0x32)
{
mode = UC_MODE_32;
}
else if (bit == 0x64)
{
mode = UC_MODE_64;
}
else
{
dprintf("unsupported mode\n");
return;
}
if (uc_open(UC_ARCH_X86, mode, &_uc) == 0)
{
cpu_context_type context;
engine_linker linker;
linker.get_thread_context(&context);
cpu_context_type segment_context = { 0, };
segment_context.cs = context.cs;
segment_context.ds = context.ds;
segment_context.es = context.es;
segment_context.fs = 0x88;
segment_context.gs = 0x63;
if (create_global_descriptor_table(segment_context, mode))
{
dprintf("emulator:: open success\n");
view_cpu_context();
}
}
}
EXT_CLASS_COMMAND(WindbgEngine, alloc, "", "{em;ed,o;em;;}" "{size;ed,o;size;;}" "{copy;b,o;copy;;}")
{
if (!HasArg("em") || !HasArg("size"))
{
return;
}
unsigned long long em = GetArgU64("em", false);
unsigned long long size = GetArgU64("size", false);
unsigned long long base = alignment(em, 0x1000) - 0x1000;
unsigned long long base_size = alignment(size, 0x1000);
if (uc_mem_map(_uc, base, (size_t)base_size, UC_PROT_ALL) == 0)
{
dprintf("emulator:: alloc success\n");
dprintf(" [-] %I64x-%I64x\n", base, base+base_size);
if (HasArg("copy"))
{
unsigned char *dump = (unsigned char *)malloc((size_t)size);
if (!dump)
{
dprintf("emulator:: copy fail\n");
}
std::shared_ptr<void> dump_closer(dump, free);
engine_linker linker;
unsigned long readn = linker.read_virtual_memory(em, dump, (unsigned long)size);
if (uc_mem_write(_uc, em, dump, readn) == 0)
{
dprintf("emulator:: copy success\n");
}
}
}
else
{
dprintf("emulator:: copy fail\n");
}
}
EXT_CLASS_COMMAND(WindbgEngine, write, "", "{em;ed,o;em;;}" "{hex;x,o;hex;;}")
{
if (!HasArg("em") || !HasArg("hex"))
{
return;
}
unsigned long long em = GetArgU64("em", false);
PCSTR hex = GetArgStr("hex", true);
size_t size_of_hex = strlen(hex);
unsigned char *hex_dump = (unsigned char *)malloc(size_of_hex);
if (!hex_dump)
{
return;
}
std::shared_ptr<void> pattern_closer(hex_dump, free);
memset(hex_dump, 0, size_of_hex);
unsigned long long j = 0;
for (unsigned long long i = 0; i < size_of_hex; ++i)
{
if (hex[i] != ' ')
{
char *end = nullptr;
hex_dump[j++] = (unsigned char)strtol(&hex[i], &end, 16);
i = end - hex;
}
}
if (uc_mem_write(_uc, em, hex_dump, size_of_hex) == 0)
{
dprintf("emulator:: write success\n");
}
}
EXT_CLASS_COMMAND(WindbgEngine, read, "", "{em;ed,o;em;;}" "{size;ed,o;size;;}")
{
if (!HasArg("em") || !HasArg("size"))
{
return;
}
unsigned long long em = GetArgU64("em", false);
unsigned long long size = GetArgU64("size", false);
unsigned char *dump = (unsigned char *)malloc((size_t)size);
if (!dump)
return;
std::shared_ptr<void> dump_closer(dump, free);
memset(dump, 0, (size_t)size);
if (uc_mem_read(_uc, em, dump, (size_t)size) != 0)
{
dprintf("emulator:: read fail\n");
return;
}
unsigned int i = 0, j = 0;
for (i; i < size; ++i)
{
if (i == 0)
{
dprintf("%08x ", em);
}
else if (i % 16 == 0)
{
/*-- ascii --*/
for (j; j < i; ++j)
{
if (helper::is_ascii(dump, (size_t)size))
dprintf("%c", dump[j]);
else
dprintf(".");
}
/*-- next line --*/
dprintf("\n");
em += 16;
dprintf("%08x ", em);
}
dprintf("%02x ", dump[i]);
}
if (i % 16)
{
for (unsigned k = 0; k < i % 16; ++i)
dprintf(" ");
}
for (j; j < i; ++j)
{
if (helper::is_ascii(dump, (size_t)size))
dprintf("%c", dump[j]);
else
dprintf(".");
}
dprintf("\n");
}
EXT_CLASS_COMMAND(WindbgEngine, query, "", "{em;ed,o;em;;}")
{
if (!HasArg("em"))
return;
unsigned long long em = GetArgU64("em", false);
unsigned long long base = 0;
unsigned long long size = 0;
if (::query(em, &base, &size))
{
dprintf(" %I64x-%I64x\n", base, base + size + 1);
}
}
EXT_CLASS_COMMAND(WindbgEngine, trace, "", "{em;ed,o;em;;}" "{step;ed,o;step;;}")
{
if (!HasArg("em") || !HasArg("step"))
return;
cpu_context_type backup;
read_x86_cpu_context(&backup);
unsigned long long em = GetArgU64("em", false);
unsigned long long step = GetArgU64("step", false);
unsigned long long base = 0;
unsigned long long size = 0;
if (::query(em, &base, &size))
{
dprintf(" %I64x:: %I64x-%I64x\n", em, base, base + size + 1);
}
else
{
dprintf(" %I64x:: not found emulator memory..\n");
}
uc_err err = uc_emu_start(_uc, em, em+size, 0, (size_t)step);
if (err)
{
dprintf("emulator:: %d\n", err);
}
else
{
cpu_context_type context;
#ifdef _WIN64
read_x64_cpu_context(&context);
#else
read_x86_cpu_context(&context);
#endif
#ifdef _WIN64
view_cpu_context();
#else
view_cpu_context();
#endif
}
}
EXT_CLASS_COMMAND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ed,o;ymm14;;}" "{ymm15;ed,o;ymm15;;}"
"{view;b,o;view;;}")
{
if (HasArg("view"))
{
view_cpu_context();
}
else
{
cpu_context_type context;
#ifdef _WIN64
read_x64_cpu_context(&context);
#else
read_x86_cpu_context(&context);
#endif
if (HasArg("rax"))
context.rax = GetArgU64("rax", false);
if(HasArg("rbx"))
context.rbx = GetArgU64("rbx", false);
if (HasArg("rcx"))
context.rcx = GetArgU64("rcx", false);
if (HasArg("rdx"))
context.rdx = GetArgU64("rdx", false);
if (HasArg("rdi"))
context.rdi = GetArgU64("rdi", false);
if (HasArg("rsi"))
context.rsi = GetArgU64("rsi", false);
if (HasArg("rbp"))
context.rbp = GetArgU64("rbp", false);
if (HasArg("rsp"))
context.rsp = GetArgU64("rsp", false);
if (HasArg("rip"))
context.rsp = GetArgU64("rip", false);
if (HasArg("r8"))
context.r8 = GetArgU64("r8", false);
if (HasArg("r9"))
context.r9 = GetArgU64("r9", false);
if (HasArg("r10"))
context.r10 = GetArgU64("r10", false);
if (HasArg("r11"))
context.r11 = GetArgU64("r11", false);
if (HasArg("r12"))
context.r12 = GetArgU64("r12", false);
if (HasArg("r13"))
context.r13 = GetArgU64("r13", false);
if (HasArg("r14"))
context.r14 = GetArgU64("r14", false);
if (HasArg("r15"))
context.r15 = GetArgU64("r15", false);
if (HasArg("xmm0"))
context.xmm0 = GetArgU64("xmm0", false);
if (HasArg("xmm1"))
context.xmm1 = GetArgU64("xmm1", false);
if (HasArg("xmm2"))
context.xmm2 = GetArgU64("xmm2", false);
if (HasArg("xmm3"))
context.xmm3 = GetArgU64("xmm3", false);
if (HasArg("xmm4"))
context.xmm4 = GetArgU64("xmm4", false);
if (HasArg("xmm5"))
context.xmm5 = GetArgU64("xmm5", false);
if (HasArg("xmm6"))
context.xmm6 = GetArgU64("xmm6", false);
if (HasArg("xmm7"))
context.xmm7 = GetArgU64("xmm7", false);
if (HasArg("xmm8"))
context.xmm8 = GetArgU64("xmm8", false);
if (HasArg("xmm9"))
context.xmm9 = GetArgU64("xmm9", false);
if (HasArg("xmm10"))
context.xmm10 = GetArgU64("xmm10", false);
if (HasArg("xmm11"))
context.xmm11 = GetArgU64("xmm11", false);
if (HasArg("xmm12"))
context.xmm12 = GetArgU64("xmm12", false);
if (HasArg("xmm13"))
context.xmm13 = GetArgU64("xmm13", false);
if (HasArg("xmm14"))
context.xmm14 = GetArgU64("xmm14", false);
if (HasArg("xmm15"))
context.xmm15 = GetArgU64("xmm15", false);
if (HasArg("ymm0"))
context.ymm0 = GetArgU64("ymm0", false);
if (HasArg("ymm1"))
context.ymm1 = GetArgU64("ymm1", false);
if (HasArg("ymm2"))
context.ymm2 = GetArgU64("ymm2", false);
if (HasArg("ymm3"))
context.ymm3 = GetArgU64("ymm3", false);
if (HasArg("ymm4"))
context.ymm4 = GetArgU64("ymm4", false);
if (HasArg("ymm5"))
context.ymm5 = GetArgU64("ymm5", false);
if (HasArg("ymm6"))
context.ymm6 = GetArgU64("ymm6", false);
if (HasArg("ymm7"))
context.ymm7 = GetArgU64("ymm7", false);
if (HasArg("ymm8"))
context.ymm8 = GetArgU64("ymm8", false);
if (HasArg("ymm9"))
context.ymm9 = GetArgU64("ymm9", false);
if (HasArg("ymm10"))
context.ymm10 = GetArgU64("ymm10", false);
if (HasArg("ymm11"))
context.ymm11 = GetArgU64("ymm11", false);
if (HasArg("ymm12"))
context.ymm12 = GetArgU64("ymm12", false);
if (HasArg("ymm13"))
context.ymm13 = GetArgU64("ymm13", false);
if (HasArg("ymm14"))
context.ymm14 = GetArgU64("ymm14", false);
if (HasArg("ymm15"))
context.ymm15 = GetArgU64("ymm15", false);
if (HasArg("copy"))
{
engine_linker linker;
cpu_context_type current_context = { 0, };
if (linker.get_thread_context(¤t_context))
{
context.rax = current_context.rax;
context.rbx = current_context.rbx;
context.rcx = current_context.rcx;
context.rdx = current_context.rdx;
context.rdi = current_context.rdi;
context.rsi = current_context.rsi;
context.rsp = current_context.rsp;
context.rbp = current_context.rbp;
context.rip = current_context.rip;
context.efl = current_context.efl;
context.r8 = current_context.r8;
context.r9 = current_context.r9;
context.r10 = current_context.r10;
context.r11 = current_context.r11;
context.r12 = current_context.r12;
context.r13 = current_context.r13;
context.r14 = current_context.r14;
context.r15 = current_context.r15;
}
}
#ifdef _WIN64
write_x64_cpu_context(context);
#else
write_x86_cpu_context(context);
#endif
view_cpu_context();
}
}
| 27,082 | 12,643 |
#include "includes.h"
#define OBF_BEGIN try { obf::next_step __crv = obf::next_step::ns_done; std::shared_ptr<obf::base_rvholder> __rvlocal;
// Data
static LPDIRECT3D9 g_pD3D = NULL;
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS g_d3dpp = {};
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void ResetDevice();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool frameRounding = true;
float GUI_Color[4] = { 1.000f, 0.137f, 1.000f, 1.000f };
bool otherBG = true;
namespace features {
int window_key = 45; // insert
bool hideWindow = false;
}
namespace helpers {
// Keymap
const char* keys[256] = {
"",
"",
"",
"",
"",
"MOUSE4",
"MOUSE5",
"",
"BACKSPACE",
"TAB",
"",
"",
"CLEAR",
"ENTER",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"SPACE",
"PGUP",
"PGDOWN",
"END",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"INSERT",
"DELETE",
"",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"",
"",
"",
"",
"",
"",
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"",
"",
"",
"",
"",
"NUM0",
"NUM1",
"NUM2",
"NUM3",
"NUM4",
"NUM5",
"NUM6",
"NUM7",
"NUM8",
"NUM9",
"MULTIPLY",
"ADD",
"SEPARATOR",
"SUBTRACT",
"DECIMAL",
"DIVIDE",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"F13",
"F14",
"F15",
"F16",
"F17",
"F18",
"F19",
"F20",
"F21",
"F22",
"F23",
"F24",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"LSHIFT",
"RSHIFT",
"LCONTROL",
"RCONTROL",
"LMENU",
"RMENU",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"COMMA",
"MINUS",
"PERIOD",
"SLASH",
"TILDA",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"[",
"|",
"]",
"QUOTE",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
};
//
// Gets current key down and returns it
//
int getKeybind()
{
int i = 0;
int n = 0;
while (n == 0) {
for (i = 3; i < 256; i++)
{
if (GetAsyncKeyState((i)))
{
if (i < 256) {
if (!(*keys[i] == 0)) {
n = 1;
return i;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
//
// check if the key is down.
//
bool keyCheck(int key)
{
for (int t = 3; t < 256; t++)
{
if (GetAsyncKeyState(t))
{
if ((keys[key] == keys[t]) & (keys[key] != 0 & keys[t] != 0))
{
return true;
//std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
}
return false;
}
static auto generate_random_float = [](float min, float max) {
float random = ((float)rand()) / (float)RAND_MAX;
float diff = max - min;
float r = random * diff;
return min + r;
};
//
// Implement this as a thread
// takes in a key and a reference to a bool to toggle on or off
// if they key you put in is true it toggles the bool you passed in.
//
void checkThread(int key, bool& toggle)
{
auto future = std::async(helpers::keyCheck, key);
if (future.get()) {
toggle = !toggle;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
}
// Side Panel State
int sidePanel = 0;
// Main code
int main(int, char**)
{
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T(" "), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T(" "), WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 100, 100, 500, 335, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.Fonts->AddFontFromMemoryCompressedTTF(Ubuntu_Light_compressed_data, Ubuntu_Light_compressed_size, 20);
io.Fonts->AddFontFromMemoryCompressedTTF(Ubuntu_Regular_compressed_data, Ubuntu_Regular_compressed_size, 18);
std::thread clickerThread(features::clickerThread);
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX9_Init(g_pd3dDevice);
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX9_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
if (!features::hideWindow) {
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
::ShowWindow(GetConsoleWindow(), SW_HIDE);
}
else {
// Show the window
::ShowWindow(hwnd, SW_HIDE);
::ShowWindow(GetConsoleWindow(), SW_HIDE);
}
{
// press the - on Visual Studio to Ignore
{
ImColor mainColor = ImColor(GUI_Color[0], GUI_Color[1], GUI_Color[2], GUI_Color[3]);
ImColor bodyColor = ImColor(int(24), int(24), int(24), 255);
ImColor fontColor = ImColor(int(255), int(255), int(255), 255);
ImGuiStyle& style = ImGui::GetStyle();
ImVec4 mainColorHovered = ImVec4(mainColor.Value.x + 0.1f, mainColor.Value.y + 0.1f, mainColor.Value.z + 0.1f, mainColor.Value.w);
ImVec4 mainColorActive = ImVec4(mainColor.Value.x + 0.2f, mainColor.Value.y + 0.2f, mainColor.Value.z + 0.2f, mainColor.Value.w);
ImVec4 menubarColor = ImVec4(bodyColor.Value.x, bodyColor.Value.y, bodyColor.Value.z, bodyColor.Value.w - 0.8f);
ImVec4 frameBgColor = ImVec4(bodyColor.Value.x + 0.1f, bodyColor.Value.y + 0.1f, bodyColor.Value.z + 0.1f, bodyColor.Value.w + .1f);
ImVec4 tooltipBgColor = ImVec4(bodyColor.Value.x, bodyColor.Value.y, bodyColor.Value.z, bodyColor.Value.w + .05f);
style.Alpha = 1.0f;
style.WindowPadding = ImVec2(8, 8);
style.WindowMinSize = ImVec2(32, 32);
style.WindowRounding = 0.0f;
style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
style.ChildRounding = 0.0f;
style.FramePadding = ImVec2(4, 3);
style.FrameRounding = 0.0f;
style.ItemSpacing = ImVec2(4, 3);
style.ItemInnerSpacing = ImVec2(4, 4);
style.TouchExtraPadding = ImVec2(0, 0);
style.IndentSpacing = 21.0f;
style.ColumnsMinSpacing = 3.0f;
style.ScrollbarSize = 8.f;
style.ScrollbarRounding = 0.0f;
style.GrabMinSize = 1.0f;
style.GrabRounding = 0.0f;
style.ButtonTextAlign = ImVec2(0.5f, 0.5f);
style.DisplayWindowPadding = ImVec2(22, 22);
style.DisplaySafeAreaPadding = ImVec2(4, 4);
style.AntiAliasedLines = true;
style.CurveTessellationTol = 1.25f;
style.Colors[ImGuiCol_Text] = fontColor;
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = bodyColor;
style.Colors[ImGuiCol_ChildBg] = ImVec4(.0f, .0f, .0f, .0f);
style.Colors[ImGuiCol_PopupBg] = tooltipBgColor;
style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f);
style.Colors[ImGuiCol_FrameBg] = frameBgColor;
style.Colors[ImGuiCol_FrameBgHovered] = mainColorHovered;
style.Colors[ImGuiCol_FrameBgActive] = mainColorActive;
style.Colors[ImGuiCol_TitleBg] = mainColor;
style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f);
style.Colors[ImGuiCol_TitleBgActive] = mainColor;
style.Colors[ImGuiCol_MenuBarBg] = menubarColor;
style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(frameBgColor.x + .05f, frameBgColor.y + .05f, frameBgColor.z + .05f, frameBgColor.w);
style.Colors[ImGuiCol_ScrollbarGrab] = mainColor;
style.Colors[ImGuiCol_ScrollbarGrabHovered] = mainColorHovered;
style.Colors[ImGuiCol_ScrollbarGrabActive] = mainColorActive;
style.Colors[ImGuiCol_CheckMark] = mainColor;
style.Colors[ImGuiCol_SliderGrab] = mainColorHovered;
style.Colors[ImGuiCol_SliderGrabActive] = mainColorActive;
style.Colors[ImGuiCol_Button] = mainColor;
style.Colors[ImGuiCol_ButtonHovered] = mainColorHovered;
style.Colors[ImGuiCol_ButtonActive] = mainColorActive;
style.Colors[ImGuiCol_Header] = mainColor;
style.Colors[ImGuiCol_HeaderHovered] = mainColorHovered;
style.Colors[ImGuiCol_HeaderActive] = mainColorActive;
style.Colors[ImGuiCol_ResizeGrip] = mainColor;
style.Colors[ImGuiCol_ResizeGripHovered] = mainColorHovered;
style.Colors[ImGuiCol_ResizeGripActive] = mainColorActive;
style.Colors[ImGuiCol_PlotLines] = mainColor;
style.Colors[ImGuiCol_PlotLinesHovered] = mainColorHovered;
style.Colors[ImGuiCol_PlotHistogram] = mainColor;
style.Colors[ImGuiCol_PlotHistogramHovered] = mainColorHovered;
style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f);
}
// check if the keys down for keybinds
helpers::checkThread(features::left_key, features::CLICKER_TOGGLED);
helpers::checkThread(features::right_key, features::rCLICKER_TOGGLED);
helpers::checkThread(features::window_key, features::hideWindow);
// check for frame rounding
if (frameRounding) {
ImGui::GetStyle().FrameRounding = 4.0f;
ImGui::GetStyle().GrabRounding = 3.0f;
}
else { // we do da java
ImGui::GetStyle().FrameRounding = 0.0f;
ImGui::GetStyle().GrabRounding = 0.0f;
}
// Actuall stuff
// Setup tings
ImGui::Begin(xorstr_(" "), NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoInputs);
ImGui::SetWindowSize({ 500, 0 });
ImGui::SetWindowPos({ 0, 0 });
ImGui::End();
// Left Shit
ImGui::Begin(xorstr_("SidePanel"), NULL, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDecoration); {
ImGui::SetWindowPos({ -5, -5 });
ImGui::SetWindowSize({ 125, 515 });
ImGui::Text(xorstr_("Vega - Clicker"));
if (ImGui::Button(xorstr_("Clicker"), { 100, 50 })) sidePanel = 0;
if (ImGui::Button(xorstr_("Misc"), { 100, 50 })) sidePanel = 1;
//if (ImGui::Button(xorstr_("Config"), { 100, 50 })) sidePanel = 2;
if (ImGui::Button(xorstr_("Settings"), { 100, 50 })) sidePanel = 3;
ImGui::End();
}
// For drawing the gui
ImGui::Begin(xorstr_("Canvas"), NULL, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDecoration); {
ImGui::SetWindowPos({ 115, 5 });
ImGui::SetWindowSize({ 450, 350 });
if (sidePanel == 0) {
// Left
ImGui::Checkbox(xorstr_("Left Toggle"), &features::CLICKER_TOGGLED); ImGui::SameLine(); if (ImGui::Button(xorstr_("Left Bind"))) { features::left_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::left_key]);
// drag clicker not done
//if (!features::lDrag) {
// ImGui::SliderFloat(xorstr_("L CPS"), &features::CPS, 10.0f, 20.0f, "%.1f");
// ImGui::Checkbox(xorstr_("Extra Rand"), &features::lExtraRand); ImGui::SameLine();
//}
// ImGui::Checkbox(xorstr_("Drag Click"), &features::lDrag);
ImGui::SliderFloat(xorstr_("L CPS"), &features::CPS, 10.0f, 20.0f, "%.1f");
ImGui::Checkbox(xorstr_("Extra Rand"), &features::lExtraRand);
ImGui::NewLine();
// Right
ImGui::Checkbox(xorstr_("Right Toggle"), &features::rCLICKER_TOGGLED); ImGui::SameLine(); if (ImGui::Button(xorstr_("Right Bind"))) { features::right_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::right_key]);
ImGui::SliderFloat(xorstr_("R CPS"), &features::rCPS, 10.0f, 20.0f, "%.1f");
ImGui::Checkbox(xorstr_("Extra Rand "), &features::rExtraRand);
}
if (sidePanel == 1) {
ImGui::Checkbox(xorstr_("Block Hit"), &features::BLOCKHIT); ImGui::SameLine(); ImGui::BulletText(xorstr_("Note: This is only for Left Click"));
ImGui::SliderInt(xorstr_(" "), &features::BLOCK_CHANCE, 1, 25, "%d Chance");
}
if (sidePanel == 2) {
ImGui::Text(xorstr_("NOTHING YET - Configs"));
}
// Settings Tab
if (sidePanel == 3) {
ImGui::ColorEdit4(xorstr_(" "), GUI_Color, ImGuiColorEditFlags_NoBorder | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoPicker);
ImGui::Checkbox(xorstr_("Other Background"), &otherBG); ImGui::SameLine(); ImGui::Checkbox(xorstr_("Rounding"), &frameRounding);
ImGui::Text(xorstr_("Application average %.3f ms/frame (%.1f FPS)"),
1000.0 / double(ImGui::GetIO().Framerate), double(ImGui::GetIO().Framerate));
ImGui::Text(xorstr_("Hide Window: ")); ImGui::SameLine();
if (ImGui::Button(xorstr_("Bind"))) { features::window_key = helpers::getKeybind(); }
ImGui::SameLine(); ImGui::Text(helpers::keys[features::window_key]);
ImGui::NewLine();
ImGui::Text(xorstr_("Vega - Clicker V2.5\nLGBTQHIV+-123456789 Edition"));
}
ImGui::End();
}
ImGui::Begin(xorstr_("DrawList"), NULL, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs);
ImGui::SetWindowPos({ 0, 0 });
ImGui::SetWindowSize({ 800, 800 });
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DrawList->AddLine({ 107, 0 }, { 107, 400 }, ImGui::GetColorU32(ImVec4{ GUI_Color[0], GUI_Color[1], GUI_Color[2], GUI_Color[3] }), 3);
ImGui::End();
}
// Rendering (dont touch)
ImGui::EndFrame();
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
D3DCOLOR clear_col_dx;
if (otherBG) clear_col_dx = D3DCOLOR_RGBA((int)(12), (int)(22), (int)(28), (int)(255));
else clear_col_dx = D3DCOLOR_RGBA((int)(27), (int)(22), (int)(22), (int)(255));
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
if (g_pd3dDevice->BeginScene() >= 0)
{
ImGui::Render();
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
g_pd3dDevice->EndScene();
}
HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
// Handle loss of D3D9 device
if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
ResetDevice();
}
clickerThread.detach();
ImGui_ImplDX9_Shutdown();
ImGui_ImplWin32_Shutdown();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
return false;
// Create the D3DDevice
ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
g_d3dpp.Windowed = TRUE;
g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
g_d3dpp.EnableAutoDepthStencil = TRUE;
g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync
//g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate
if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
return false;
return true;
}
void CleanupDeviceD3D()
{
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; }
}
void ResetDevice()
{
ImGui_ImplDX9_InvalidateDeviceObjects();
HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
if (hr == D3DERR_INVALIDCALL)
IM_ASSERT(0);
ImGui_ImplDX9_CreateDeviceObjects();
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
g_d3dpp.BackBufferWidth = LOWORD(lParam);
g_d3dpp.BackBufferHeight = HIWORD(lParam);
ResetDevice();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
#define OBF_END } catch(std::shared_ptr<obf::base_rvholder>& r) { return *r; } catch (...) {throw;}
| 20,947 | 7,634 |
#include "Affichage4DigitsBase.h"
#include "OptimiserEntreesSorties.h"
static const byte valeurSegments[] = {
// Segements ABCDEFGP
0b11111100, // 0 '0' AAA
0b01100000, // 1 '1' F B
0b11011010, // 2 '2' F B
0b11110010, // 3 '3' GGG
0b01100110, // 4 '4' E C
0b10110110, // 5 '5' E C
0b10111110, // 6 '6' DDD P
0b11100000, // 7 '7'
0b11111110, // 8 '8'
0b11110110, // 9 '9'
0b11101110, // 10 'A'
0b00111110, // 11 'b'
0b10011100, // 12 'C'
0b01111010, // 13 'd'
0b10011110, // 14 'E'
0b10001110, // 15 'F'
0b00000010, // 16 '-'
0b00000000, // 17 ' '
0b10000000, // 18 '¨' Trop grand
0b00010000, // 19 '_' Trop petit
};
static const int nombreConfigurations = sizeof(valeurSegments);
static const int blanc = 17;
static const int tropGrand = 18;
static const int tropPetit = 19;
static const int moins = 16;
Affichage4DigitsBase::Affichage4DigitsBase(const int &p_pinD1, const int &p_pinD2, const int &p_pinD3, const int &p_pinD4, const bool &p_cathodeCommune)
: m_pinD{p_pinD1, p_pinD2, p_pinD3, p_pinD4}
{
if (p_cathodeCommune)
{
this->m_digitOff = HIGH;
this->m_digitOn = LOW;
this->m_segmentOff = LOW;
this->m_segmentOn = HIGH;
}
else
{
this->m_digitOff = LOW;
this->m_digitOn = HIGH;
this->m_segmentOff = HIGH;
this->m_segmentOn = LOW;
}
for (size_t digitIndex = 0; digitIndex < 4; digitIndex++)
{
pinMode(this->m_pinD[digitIndex], OUTPUT);
}
}
const byte valeurSegmentTropGrand = valeurSegments[tropGrand];
const byte valeurSegmentTropPetit = valeurSegments[tropPetit];
const byte valeurSegmentBlanc = valeurSegments[blanc];
const byte valeurSegmentMoins = valeurSegments[moins];
// Affichage des 4 digits en 4 cycle d'appel et utilisation d'une cache
// Idées cache et afficher digit / digit prises de la très bonne vidéo de Cyrob : https://www.youtube.com/watch?v=CS4t0j1yzH0
void Affichage4DigitsBase::Afficher(const int &p_valeur, const int &p_base) const
{
if (p_valeur != this->m_valeurCache || p_base != this->m_baseCache)
{
this->m_valeurCache = p_valeur;
this->m_baseCache = p_base;
if (p_base == DEC && p_valeur > 9999)
{
this->m_cache[0] = valeurSegmentTropGrand;
this->m_cache[1] = valeurSegmentTropGrand;
this->m_cache[2] = valeurSegmentTropGrand;
this->m_cache[3] = valeurSegmentTropGrand;
}
else if (p_base == DEC && p_valeur < -999)
{
this->m_cache[0] = valeurSegmentTropPetit;
this->m_cache[1] = valeurSegmentTropPetit;
this->m_cache[2] = valeurSegmentTropPetit;
this->m_cache[3] = valeurSegmentTropPetit;
}
else
{
switch (p_base)
{
case HEX:
this->m_cache[0] = valeurSegments[(byte)(p_valeur >> 12 & 0x0F)];
this->m_cache[1] = valeurSegments[(byte)((p_valeur >> 8) & 0x0F)];
this->m_cache[2] = valeurSegments[(byte)((p_valeur >> 4) & 0x0F)];
this->m_cache[3] = valeurSegments[(byte)(p_valeur & 0x0F)];
break;
case DEC: // par défault décimale. Autres bases non gérées.
default:
{
int valeur = p_valeur < 0 ? -p_valeur : p_valeur;
int index = 3;
while (valeur != 0 && index >= 0)
{
this->m_cache[index] = valeurSegments[valeur % 10];
valeur /= 10;
--index;
}
while (index >= 0)
{
this->m_cache[index] = valeurSegmentBlanc;
--index;
}
if (p_valeur < 0)
{
this->m_cache[0] = valeurSegmentMoins;
}
}
break;
}
}
}
}
void Affichage4DigitsBase::Executer() const
{
monDigitalWrite(this->m_pinD[this->m_digitCourant], this->m_digitOff);
++this->m_digitCourant;
#if !OPTIMISE_MODULO
this->m_digitCourant %= 4;
#else
if (this->m_digitCourant > 3)
{
this->m_digitCourant = 0;
}
#endif
this->EnvoyerValeur(this->m_cache[this->m_digitCourant]);
monDigitalWrite(this->m_pinD[this->m_digitCourant], this->m_digitOn);
}
| 4,555 | 1,877 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "JniConstants.h"
// by cmjo
//#include <stdlib.h>
#include "xi/xi_process.h"
// by jshwang
//#define LOGE printf
#if 0
jclass JniConstants::bidiRunClass;
jclass JniConstants::bigDecimalClass;
jclass JniConstants::booleanClass;
jclass JniConstants::byteClass;
jclass JniConstants::byteArrayClass;
jclass JniConstants::charsetICUClass;
jclass JniConstants::constructorClass;
jclass JniConstants::datagramPacketClass;
jclass JniConstants::deflaterClass;
jclass JniConstants::doubleClass;
jclass JniConstants::fieldClass;
jclass JniConstants::fieldPositionIteratorClass;
jclass JniConstants::multicastGroupRequestClass;
jclass JniConstants::inetAddressClass;
jclass JniConstants::inflaterClass;
jclass JniConstants::integerClass;
jclass JniConstants::interfaceAddressClass;
jclass JniConstants::localeDataClass;
jclass JniConstants::longClass;
jclass JniConstants::methodClass;
jclass JniConstants::parsePositionClass;
jclass JniConstants::patternSyntaxExceptionClass;
jclass JniConstants::realToStringClass;
jclass JniConstants::socketClass;
jclass JniConstants::socketImplClass;
jclass JniConstants::stringClass;
//jclass JniConstants::vmRuntimeClass;
static jclass findClass(JNIEnv* env, const char* name) {
jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(env->FindClass(name)));
if (result == NULL) {
log_error(XDLOG, "failed to find class '%s'\n", name);
xi_proc_abort();
}
return result;
}
#endif // 0
void JniConstants::init(JNIEnv*) {
#if 0
bidiRunClass = findClass(env, "org/apache/harmony/text/BidiRun");
bigDecimalClass = findClass(env, "java/math/BigDecimal");
booleanClass = findClass(env, "java/lang/Boolean");
byteClass = findClass(env, "java/lang/Byte");
byteArrayClass = findClass(env, "[B");
charsetICUClass = findClass(env, "com/ibm/icu4jni/charset/CharsetICU");
constructorClass = findClass(env, "java/lang/reflect/Constructor");
datagramPacketClass = findClass(env, "java/net/DatagramPacket");
deflaterClass = findClass(env, "java/util/zip/Deflater");
doubleClass = findClass(env, "java/lang/Double");
fieldClass = findClass(env, "java/lang/reflect/Field");
fieldPositionIteratorClass = findClass(env, "com/ibm/icu4jni/text/NativeDecimalFormat$FieldPositionIterator");
inetAddressClass = findClass(env, "java/net/InetAddress");
inflaterClass = findClass(env, "java/util/zip/Inflater");
integerClass = findClass(env, "java/lang/Integer");
interfaceAddressClass = findClass(env, "java/net/InterfaceAddress");
localeDataClass = findClass(env, "com/ibm/icu4jni/util/LocaleData");
longClass = findClass(env, "java/lang/Long");
methodClass = findClass(env, "java/lang/reflect/Method");
multicastGroupRequestClass = findClass(env, "java/net/MulticastGroupRequest");
parsePositionClass = findClass(env, "java/text/ParsePosition");
patternSyntaxExceptionClass = findClass(env, "java/util/regex/PatternSyntaxException");
realToStringClass = findClass(env, "java/lang/RealToString");
socketClass = findClass(env, "java/net/Socket");
socketImplClass = findClass(env, "java/net/SocketImpl");
stringClass = findClass(env, "java/lang/String");
// vmRuntimeClass = findClass(env, "dalvik/system/VMRuntime");
#else
// deflaterClass = findClass(env, "java/util/zip/Deflater");
// inflaterClass = findClass(env, "java/util/zip/Inflater");
// stringClass = findClass(env, "java/lang/String");
// charsetICUClass = findClass(env, "com/ibm/icu4jni/charset/CharsetICU");
#endif
}
| 4,169 | 1,323 |
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#ifndef ITL_ASYNC_EXECUTOR_INCLUDE
#define ITL_ASYNC_EXECUTOR_INCLUDE
#include <thread>
#include <boost/numeric/itl/iteration/interruptible_iteration.hpp>
namespace itl {
template <typename Solver>
class async_executor
{
public:
async_executor(const Solver& solver) : my_solver(solver), my_iter(), my_thread() {}
/// Solve linear system approximately as specified by \p iter
template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
void start_solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
{
my_iter.set_iter(iter);
// my_thread= std::thread(&Solver::solve, &my_solver, b, x, my_iter);
my_thread= std::thread([this, &x, &b]() { my_solver.solve(x, b, my_iter);});
}
/// Solve linear system approximately as specified by \p iter
template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >
int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const
{
start_solve(x, b, iter);
return wait();
}
/// Perform one iteration on linear system
template < typename HilbertSpaceX, typename HilbertSpaceB >
int solve(HilbertSpaceX& x, const HilbertSpaceB& b) const
{
itl::basic_iteration<double> iter(x, 1, 0, 0);
return solve(x, b, iter);
}
int wait()
{
my_thread.join();
return my_iter.error_code();
}
bool is_finished() const { return !my_thread.joinable(); }
int interrupt() { my_iter.interrupt(); return wait(); }
private:
Solver my_solver;
mutable interruptible_iteration my_iter;
mutable std::thread my_thread;
};
template <typename Solver>
inline async_executor<Solver> make_async_executor(const Solver& solver)
{
return async_executor<Solver>(solver);
}
} // namespace itl
#endif // ITL_ASYNC_EXECUTOR_INCLUDE
| 2,372 | 787 |
#include "C_CALCUL.h"
C_CALCUL::C_CALCUL(TypeDeProjet type)
{
switch (type)
{
case C_CALCUL::TypeDeProjet::ORGANIC:
TypeProjetInt = 0;
break;
case C_CALCUL::TypeDeProjet::DETACHED:
TypeProjetInt = 1;
break;
case C_CALCUL::TypeDeProjet::EMBEDDED:
TypeProjetInt = 2;
break;
default:
TypeProjetInt = 0;
break;
}
}
void C_CALCUL::setKLOC(float KLOC)
{
this->KLOC = KLOC;
}
void C_CALCUL::setEAF(float EAF)
{
this->EAF = EAF;
}
float C_CALCUL::calcul_E()
{
float E;
E = organic_A * (pow(KLOC,organic_B)) * EAF;
/*
switch (TypeProjetInt)
{
case 0:
// E = organic_A * (KLOC ^ organic_B) * EAF;
break;
case 1:
break;
case 2:
break;
default:
// E = organic_A * (KLOC ^ organic_B) * EAF;
break;
}
*/
return E;
}
float C_CALCUL::calcul_D(float E)
{
float D;
D = 2.5 * (pow(E, orgnic_C));
return D;
}
float C_CALCUL::calcul_P(float E, float D)
{
float P;
P = E / D;
return P;
}
| 927 | 502 |
/*
* ShapeSweepUtils.cpp
* nlivarot
*
* Created by fred on Wed Jun 18 2003.
*
*/
#include "Shape.h"
#include "MyMath.h"
SweepEvent::SweepEvent()
{
MakeNew(NULL,NULL,0,0,0,0);
}
SweepEvent::~SweepEvent(void)
{
MakeDelete();
}
void
SweepEvent::MakeNew(SweepTree* iLeft,SweepTree* iRight,float px,float py,float itl,float itr)
{
ind=-1;
posx=px;
posy=py;
tl=itl;
tr=itr;
leftSweep=iLeft;
rightSweep=iRight;
leftSweep->rightEvt=this;
rightSweep->leftEvt=this;
}
void
SweepEvent::MakeDelete(void)
{
if ( leftSweep ) {
if ( leftSweep->src->aretes[leftSweep->bord].st < leftSweep->src->aretes[leftSweep->bord].en ) {
leftSweep->src->pData[leftSweep->src->aretes[leftSweep->bord].en].pending--;
} else {
leftSweep->src->pData[leftSweep->src->aretes[leftSweep->bord].st].pending--;
}
leftSweep->rightEvt=NULL;
}
if ( rightSweep ) {
if ( rightSweep->src->aretes[rightSweep->bord].st < rightSweep->src->aretes[rightSweep->bord].en ) {
rightSweep->src->pData[rightSweep->src->aretes[rightSweep->bord].en].pending--;
} else {
rightSweep->src->pData[rightSweep->src->aretes[rightSweep->bord].st].pending--;
}
rightSweep->leftEvt=NULL;
}
leftSweep=rightSweep=NULL;
}
void SweepEvent::CreateQueue(SweepEventQueue &queue,int size)
{
queue.nbEvt=0;
queue.maxEvt=size;
queue.events=(SweepEvent*)malloc(queue.maxEvt*sizeof(SweepEvent));
queue.inds=(int*)malloc(queue.maxEvt*sizeof(int));
}
void SweepEvent::DestroyQueue(SweepEventQueue &queue)
{
if ( queue.events ) free(queue.events);
if ( queue.inds ) free(queue.inds);
queue.nbEvt=queue.maxEvt=0;
queue.inds=NULL;
queue.events=NULL;
}
SweepEvent* SweepEvent::AddInQueue(SweepTree* iLeft,SweepTree* iRight,float px,float py,float itl,float itr,SweepEventQueue &queue)
{
if ( queue.nbEvt >= queue.maxEvt ) return NULL;
int n=queue.nbEvt++;
queue.events[n].MakeNew(iLeft,iRight,px,py,itl,itr);
if ( iLeft->src->aretes[iLeft->bord].st < iLeft->src->aretes[iLeft->bord].en ) {
iLeft->src->pData[iLeft->src->aretes[iLeft->bord].en].pending++;
} else {
iLeft->src->pData[iLeft->src->aretes[iLeft->bord].st].pending++;
}
if ( iRight->src->aretes[iRight->bord].st < iRight->src->aretes[iRight->bord].en ) {
iRight->src->pData[iRight->src->aretes[iRight->bord].en].pending++;
} else {
iRight->src->pData[iRight->src->aretes[iRight->bord].st].pending++;
}
queue.events[n].ind=n;
queue.inds[n]=n;
int curInd=n;
while ( curInd > 0 ) {
int half=(curInd-1)/2;
int no=queue.inds[half];
if ( py < queue.events[no].posy || ( py == queue.events[no].posy && px < queue.events[no].posx ) ) {
queue.events[n].ind=half;
queue.events[no].ind=curInd;
queue.inds[half]=n;
queue.inds[curInd]=no;
} else {
break;
}
curInd=half;
}
return queue.events+n;
}
void SweepEvent::SupprFromQueue(SweepEventQueue &queue)
{
if ( queue.nbEvt <= 1 ) {
MakeDelete();
queue.nbEvt=0;
return;
}
int n=ind;
int to=queue.inds[n];
MakeDelete();
queue.events[--queue.nbEvt].Relocate(queue,to);
int moveInd=queue.nbEvt;
if ( moveInd == n ) return;
to=queue.inds[moveInd];
queue.events[to].ind=n;
queue.inds[n]=to;
int curInd=n;
float px=queue.events[to].posx;
float py=queue.events[to].posy;
bool didClimb=false;
while ( curInd > 0 ) {
int half=(curInd-1)/2;
int no=queue.inds[half];
if ( py < queue.events[no].posy || ( py == queue.events[no].posy && px < queue.events[no].posx ) ) {
queue.events[to].ind=half;
queue.events[no].ind=curInd;
queue.inds[half]=to;
queue.inds[curInd]=no;
didClimb=true;
} else {
break;
}
curInd=half;
}
if ( didClimb ) return;
while ( 2*curInd+1 < queue.nbEvt ) {
int son1=2*curInd+1;
int son2=son1+1;
int no1=queue.inds[son1];
int no2=queue.inds[son2];
if ( son2 < queue.nbEvt ) {
if ( py > queue.events[no1].posy || ( py == queue.events[no1].posy && px > queue.events[no1].posx ) ) {
if ( queue.events[no2].posy > queue.events[no1].posy || ( queue.events[no2].posy == queue.events[no1].posy && queue.events[no2].posx > queue.events[no1].posx ) ) {
queue.events[to].ind=son1;
queue.events[no1].ind=curInd;
queue.inds[son1]=to;
queue.inds[curInd]=no1;
curInd=son1;
} else {
queue.events[to].ind=son2;
queue.events[no2].ind=curInd;
queue.inds[son2]=to;
queue.inds[curInd]=no2;
curInd=son2;
}
} else {
if ( py > queue.events[no2].posy || ( py == queue.events[no2].posy && px > queue.events[no2].posx ) ) {
queue.events[to].ind=son2;
queue.events[no2].ind=curInd;
queue.inds[son2]=to;
queue.inds[curInd]=no2;
curInd=son2;
} else {
break;
}
}
} else {
if ( py > queue.events[no1].posy || ( py == queue.events[no1].posy && px > queue.events[no1].posx ) ) {
queue.events[to].ind=son1;
queue.events[no1].ind=curInd;
queue.inds[son1]=to;
queue.inds[curInd]=no1;
}
break;
}
}
}
bool SweepEvent::PeekInQueue(SweepTree* &iLeft,SweepTree* &iRight,float &px,float &py,float &itl,float &itr,SweepEventQueue &queue)
{
if ( queue.nbEvt <= 0 ) return false;
iLeft=queue.events[queue.inds[0]].leftSweep;
iRight=queue.events[queue.inds[0]].rightSweep;
px=queue.events[queue.inds[0]].posx;
py=queue.events[queue.inds[0]].posy;
itl=queue.events[queue.inds[0]].tl;
itr=queue.events[queue.inds[0]].tr;
return true;
}
bool SweepEvent::ExtractFromQueue(SweepTree* &iLeft,SweepTree* &iRight,float &px,float &py,float &itl,float &itr,SweepEventQueue &queue)
{
if ( queue.nbEvt <= 0 ) return false;
iLeft=queue.events[queue.inds[0]].leftSweep;
iRight=queue.events[queue.inds[0]].rightSweep;
px=queue.events[queue.inds[0]].posx;
py=queue.events[queue.inds[0]].posy;
itl=queue.events[queue.inds[0]].tl;
itr=queue.events[queue.inds[0]].tr;
queue.events[queue.inds[0]].SupprFromQueue(queue);
return true;
}
void SweepEvent::Relocate(SweepEventQueue &queue,int to)
{
if ( queue.inds[ind] == to ) return; // j'y suis deja
queue.events[to].posx=posx;
queue.events[to].posy=posy;
queue.events[to].tl=tl;
queue.events[to].tr=tr;
queue.events[to].leftSweep=leftSweep;
queue.events[to].rightSweep=rightSweep;
leftSweep->rightEvt=queue.events+to;
rightSweep->leftEvt=queue.events+to;
queue.events[to].ind=ind;
queue.inds[ind]=to;
}
/*
*
*/
SweepTree::SweepTree(void)
{
src=NULL;
bord=-1;
startPoint=-1;
leftEvt=rightEvt=NULL;
sens=true;
// invDirLength=1;
}
SweepTree::~SweepTree(void)
{
MakeDelete();
}
void
SweepTree::MakeNew(Shape* iSrc,int iBord,int iWeight,int iStartPoint)
{
AVLTree::MakeNew();
ConvertTo(iSrc,iBord,iWeight,iStartPoint);
}
void
SweepTree::ConvertTo(Shape* iSrc,int iBord,int iWeight,int iStartPoint)
{
src=iSrc;
bord=iBord;
leftEvt=rightEvt=NULL;
startPoint=iStartPoint;
if ( src->aretes[bord].st < src->aretes[bord].en ) {
if ( iWeight >= 0 ) sens=true; else sens=false;
} else {
if ( iWeight >= 0 ) sens=false; else sens=true;
}
// invDirLength=src->eData[bord].isqlength;
// invDirLength=1/sqrt(src->aretes[bord].dx*src->aretes[bord].dx+src->aretes[bord].dy*src->aretes[bord].dy);
}
void
SweepTree::MakeDelete(void)
{
if ( leftEvt ) {
leftEvt->rightSweep=NULL;
}
if ( rightEvt ) {
rightEvt->leftSweep=NULL;
}
leftEvt=rightEvt=NULL;
AVLTree::MakeDelete();
}
void SweepTree::CreateList(SweepTreeList &list,int size)
{
list.nbTree=0;
list.maxTree=size;
list.trees=(SweepTree*)malloc(list.maxTree*sizeof(SweepTree));
list.racine=NULL;
}
void SweepTree::DestroyList(SweepTreeList &list)
{
if ( list.trees ) free(list.trees);
list.trees=NULL;
list.nbTree=list.maxTree=0;
list.racine=NULL;
}
SweepTree* SweepTree::AddInList(Shape* iSrc,int iBord,int iWeight,int iStartPoint,SweepTreeList &list,Shape* iDst)
{
if ( list.nbTree >= list.maxTree ) return NULL;
int n=list.nbTree++;
list.trees[n].MakeNew(iSrc,iBord,iWeight,iStartPoint);
return list.trees+n;
}
int SweepTree::Find(float px,float py,SweepTree* newOne,SweepTree* &insertL,SweepTree* &insertR,bool sweepSens)
{
vec2d bOrig,bNorm;
bOrig.x=src->pData[src->aretes[bord].st].rx;
bOrig.y=src->pData[src->aretes[bord].st].ry;
bNorm.x=src->eData[bord].rdx;
bNorm.y=src->eData[bord].rdy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
RotCCW(bNorm);
vec2d diff;
diff.x=px-bOrig.x;
diff.y=py-bOrig.y;
double y=0;
// if ( startPoint == newOne->startPoint ) {
// y=0;
// } else {
y=Cross(bNorm,diff);
// }
// y*=invDirLength;
if ( fabs(y) < 0.000001 ) {
// prendre en compte les directions
vec2d nNorm;
nNorm.x=newOne->src->eData[newOne->bord].rdx;
nNorm.y=newOne->src->eData[newOne->bord].rdy;
if ( newOne->src->aretes[newOne->bord].st > newOne->src->aretes[newOne->bord].en ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
RotCCW(nNorm);
if ( sweepSens ) {
y=Dot(bNorm,nNorm);
} else {
y=Dot(nNorm,bNorm);
}
if ( y == 0 ) {
y=Cross(bNorm,nNorm);
if ( y == 0 ) {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
return found_exact;
}
}
}
if ( y < 0 ) {
if ( sonL ) {
return (static_cast <SweepTree*> (sonL))->Find(px,py,newOne,insertL,insertR,sweepSens);
} else {
insertR=this;
insertL=static_cast <SweepTree*> (leftElem);
if ( insertL ) {
return found_between;
} else {
return found_on_left;
}
}
} else {
if ( sonR ) {
return (static_cast <SweepTree*> (sonR))->Find(px,py,newOne,insertL,insertR,sweepSens);
} else {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
if ( insertR ) {
return found_between;
} else {
return found_on_right;
}
}
}
return not_found;
}
int SweepTree::Find(float px,float py,SweepTree* &insertL,SweepTree* &insertR)
{
vec2d bOrig,bNorm;
bOrig.x=src->pData[src->aretes[bord].st].rx;
bOrig.y=src->pData[src->aretes[bord].st].ry;
bNorm.x=src->eData[bord].rdx;
bNorm.y=src->eData[bord].rdy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
RotCCW(bNorm);
vec2d diff;
diff.x=px-bOrig.x;
diff.y=py-bOrig.y;
double y=0;
y=Cross(bNorm,diff);
if ( fabs(y) < 0.000001 ) {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
return found_exact;
}
if ( y < 0 ) {
if ( sonL ) {
return (static_cast <SweepTree*> (sonL))->Find(px,py,insertL,insertR);
} else {
insertR=this;
insertL=static_cast <SweepTree*> (leftElem);
if ( insertL ) {
return found_between;
} else {
return found_on_left;
}
}
} else {
if ( sonR ) {
return (static_cast <SweepTree*> (sonR))->Find(px,py,insertL,insertR);
} else {
insertL=this;
insertR=static_cast <SweepTree*> (rightElem);
if ( insertR ) {
return found_between;
} else {
return found_on_right;
}
}
}
return not_found;
}
void SweepTree::RemoveEvents(SweepEventQueue &queue)
{
RemoveEvent(queue,true);
RemoveEvent(queue,false);
}
void SweepTree::RemoveEvent(SweepEventQueue &queue,bool onLeft)
{
if ( onLeft ) {
if ( leftEvt ) {
leftEvt->SupprFromQueue(queue);
// leftEvt->MakeDelete(); // fait dans SupprFromQueue
}
leftEvt=NULL;
} else {
if ( rightEvt ) {
rightEvt->SupprFromQueue(queue);
// rightEvt->MakeDelete(); // fait dans SupprFromQueue
}
rightEvt=NULL;
}
}
int SweepTree::Remove(SweepTreeList &list,SweepEventQueue &queue,bool rebalance)
{
RemoveEvents(queue);
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Remove(tempR,rebalance);
list.racine=static_cast <SweepTree*> (tempR);
MakeDelete();
if ( list.nbTree <= 1 ) {
list.nbTree=0;
list.racine=NULL;
} else {
if ( list.racine == list.trees+(list.nbTree-1) ) list.racine=this;
list.trees[--list.nbTree].Relocate(this);
}
return err;
}
int SweepTree::Insert(SweepTreeList &list,SweepEventQueue &queue,Shape* iDst,int iAtPoint,bool rebalance,bool sweepSens)
{
if ( list.racine == NULL ) {
list.racine=this;
return avl_no_err;
}
SweepTree* insertL=NULL;
SweepTree* insertR=NULL;
int insertion=list.racine->Find(iDst->pts[iAtPoint].x,iDst->pts[iAtPoint].y,this,insertL,insertR,sweepSens);
if ( insertion == found_on_left ) {
} else if ( insertion == found_on_right ) {
} else if ( insertion == found_exact ) {
if ( insertR ) insertR->RemoveEvent(queue,true);
if ( insertL ) insertL->RemoveEvent(queue,false);
// insertL->startPoint=startPoint;
} else if ( insertion == found_between ) {
insertR->RemoveEvent(queue,true);
insertL->RemoveEvent(queue,false);
}
// if ( insertL ) cout << insertL->bord; else cout << "-1";
// cout << " < ";
// cout << bord;
// cout << " < ";
// if ( insertR ) cout << insertR->bord; else cout << "-1";
// cout << endl;
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Insert(tempR,insertion,static_cast <AVLTree*> (insertL),static_cast <AVLTree*> (insertR),rebalance);
list.racine=static_cast <SweepTree*> (tempR);
return err;
}
int SweepTree::InsertAt(SweepTreeList &list,SweepEventQueue &queue,Shape* iDst,SweepTree* insNode,int fromPt,bool rebalance,bool sweepSens)
{
if ( list.racine == NULL ) {
list.racine=this;
return avl_no_err;
}
vec2 fromP;
fromP.x=src->pData[fromPt].rx;
fromP.y=src->pData[fromPt].ry;
vec2d nNorm;
nNorm.x=src->aretes[bord].dx;
nNorm.y=src->aretes[bord].dy;
if ( src->aretes[bord].st > src->aretes[bord].en ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
if ( sweepSens == false ) {
nNorm.x=-nNorm.x;
nNorm.y=-nNorm.y;
}
vec2d bNorm;
bNorm.x=insNode->src->aretes[insNode->bord].dx;
bNorm.y=insNode->src->aretes[insNode->bord].dy;
if ( insNode->src->aretes[insNode->bord].st > insNode->src->aretes[insNode->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
SweepTree* insertL=NULL;
SweepTree* insertR=NULL;
double ang=Dot(bNorm,nNorm);
if ( ang == 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
} else if ( ang > 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
while ( insertL ) {
if ( insertL->src == src ) {
if ( insertL->src->aretes[insertL->bord].st != fromPt && insertL->src->aretes[insertL->bord].en != fromPt ) {
break;
}
} else {
int ils=insertL->src->aretes[insertL->bord].st;
int ile=insertL->src->aretes[insertL->bord].en;
if ( ( insertL->src->pData[ils].rx != fromP.x || insertL->src->pData[ils].ry != fromP.y ) &&
( insertL->src->pData[ile].rx != fromP.x || insertL->src->pData[ile].ry != fromP.y ) ) {
break;
}
}
bNorm.x=insertL->src->aretes[insertL->bord].dx;
bNorm.y=insertL->src->aretes[insertL->bord].dy;
if ( insertL->src->aretes[insertL->bord].st > insertL->src->aretes[insertL->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
ang=Dot(bNorm,nNorm);
if ( ang <= 0 ) {
break;
}
insertR=insertL;
insertL=static_cast <SweepTree*> (insertR->leftElem);
}
} else if ( ang < 0 ) {
insertL=insNode;
insertR=static_cast <SweepTree*> (insNode->rightElem);
while ( insertR ) {
if ( insertR->src == src ) {
if ( insertR->src->aretes[insertR->bord].st != fromPt && insertR->src->aretes[insertR->bord].en != fromPt ) {
break;
}
} else {
int ils=insertR->src->aretes[insertR->bord].st;
int ile=insertR->src->aretes[insertR->bord].en;
if ( ( insertR->src->pData[ils].rx != fromP.x || insertR->src->pData[ils].ry != fromP.y ) &&
( insertR->src->pData[ile].rx != fromP.x || insertR->src->pData[ile].ry != fromP.y ) ) {
break;
}
}
bNorm.x=insertR->src->aretes[insertR->bord].dx;
bNorm.y=insertR->src->aretes[insertR->bord].dy;
if ( insertR->src->aretes[insertR->bord].st > insertR->src->aretes[insertR->bord].en ) {
bNorm.x=-bNorm.x;
bNorm.y=-bNorm.y;
}
ang=Dot(bNorm,nNorm);
if ( ang > 0 ) {
break;
}
insertL=insertR;
insertR=static_cast <SweepTree*> (insertL->rightElem);
}
}
int insertion=found_between;
if ( insertL == NULL ) insertion=found_on_left;
if ( insertR == NULL ) insertion=found_on_right;
if ( insertion == found_on_left ) {
} else if ( insertion == found_on_right ) {
} else if ( insertion == found_exact ) {
if ( insertR ) insertR->RemoveEvent(queue,true);
if ( insertL ) insertL->RemoveEvent(queue,false);
// insertL->startPoint=startPoint;
} else if ( insertion == found_between ) {
insertR->RemoveEvent(queue,true);
insertL->RemoveEvent(queue,false);
}
// if ( insertL ) cout << insertL->bord; else cout << "-1";
// cout << " < ";
// cout << bord;
// cout << " < ";
// if ( insertR ) cout << insertR->bord; else cout << "-1";
// cout << endl;
AVLTree* tempR=static_cast <AVLTree*>(list.racine);
int err=AVLTree::Insert(tempR,insertion,static_cast <AVLTree*> (insertL),static_cast <AVLTree*> (insertR),rebalance);
list.racine=static_cast <SweepTree*> (tempR);
return err;
}
void SweepTree::Relocate(SweepTree* to)
{
if ( this == to ) return;
AVLTree::Relocate(to);
to->src=src;
to->bord=bord;
to->sens=sens;
to->leftEvt=leftEvt;
to->rightEvt=rightEvt;
to->startPoint=startPoint;
if ( src->swsData ) src->swsData[bord].misc=to;
if ( src->swrData ) src->swrData[bord].misc=to;
if ( leftEvt ) leftEvt->rightSweep=to;
if ( rightEvt ) rightEvt->leftSweep=to;
}
void SweepTree::SwapWithRight(SweepTreeList &list,SweepEventQueue &queue)
{
SweepTree* tL=this;
SweepTree* tR=static_cast <SweepTree*> (rightElem);
tL->src->swsData[tL->bord].misc=tR;
tR->src->swsData[tR->bord].misc=tL;
{Shape* swap=tL->src;tL->src=tR->src;tR->src=swap;}
{int swap=tL->bord;tL->bord=tR->bord;tR->bord=swap;}
{int swap=tL->startPoint;tL->startPoint=tR->startPoint;tR->startPoint=swap;}
// {float swap=tL->invDirLength;tL->invDirLength=tR->invDirLength;tR->invDirLength=swap;}
{bool swap=tL->sens;tL->sens=tR->sens;tR->sens=swap;}
}
void SweepTree::Avance(Shape* dstPts,int curPoint,Shape* a,Shape* b)
{
return;
/* if ( curPoint != startPoint ) {
int nb=-1;
if ( sens ) {
// nb=dstPts->AddEdge(startPoint,curPoint);
} else {
// nb=dstPts->AddEdge(curPoint,startPoint);
}
if ( nb >= 0 ) {
dstPts->swsData[nb].misc=(void*)((src==b)?1:0);
int wp=waitingPoint;
dstPts->eData[nb].firstLinkedPoint=waitingPoint;
waitingPoint=-1;
while ( wp >= 0 ) {
dstPts->pData[wp].edgeOnLeft=nb;
wp=dstPts->pData[wp].nextLinkedPoint;
}
}
startPoint=curPoint;
}*/
}
| 18,644 | 8,843 |
#include <array>
#include <chrono>
#include <functional>
#include <iostream>
#include <random>
#include <type_traits>
using namespace std;
using namespace std::chrono;
// define class
#define DERIVE(base, derived, num) \
class derived : public base { \
int derived_##member; \
\
public: \
static inline constexpr int tid = num; \
derived() : derived_##member(0) {} \
int m() const { return derived_##member; } \
int derived##_proc() const { return num; }; \
bool is_a(int t) const override { return t == tid || base::is_a(t); } \
};
class root {
public:
virtual ~root() {}
virtual bool is_a(int t) const { return false; }
};
DERIVE(root, vertebrate, __LINE__)
DERIVE(vertebrate, fish, __LINE__)
DERIVE(fish, amphibian, __LINE__)
DERIVE(fish, shark, __LINE__)
DERIVE(fish, tuna, __LINE__)
DERIVE(amphibian, reptile, __LINE__)
DERIVE(amphibian, newt, __LINE__)
DERIVE(amphibian, frog, __LINE__)
DERIVE(reptile, mammal, __LINE__)
DERIVE(reptile, crocodile, __LINE__)
DERIVE(reptile, snake, __LINE__)
DERIVE(mammal, monkey, __LINE__)
DERIVE(monkey, aye_aye, __LINE__)
DERIVE(monkey, tamarin, __LINE__)
DERIVE(monkey, hominidae, __LINE__)
DERIVE(hominidae, gorilla, __LINE__)
DERIVE(hominidae, human, __LINE__)
DERIVE(mammal, whale, __LINE__)
DERIVE(whale, blue_whale, __LINE__)
DERIVE(whale, narwhal, __LINE__)
DERIVE(whale, sperm_whale, __LINE__)
DERIVE(reptile, bird, __LINE__)
DERIVE(bird, penguin, __LINE__)
DERIVE(penguin, king_penguin, __LINE__)
DERIVE(penguin, magellanic_penguin, __LINE__)
DERIVE(penguin, galapagos_penguin, __LINE__)
DERIVE(bird, sparrow, __LINE__)
constexpr size_t COUNT = 1'000'000;
std::function<root *()> newAnimals[] = {
[]() -> root * { return new shark(); },
[]() -> root * { return new tuna(); },
[]() -> root * { return new newt(); },
[]() -> root * { return new frog(); },
[]() -> root * { return new crocodile(); },
[]() -> root * { return new snake(); },
[]() -> root * { return new aye_aye(); },
[]() -> root * { return new tamarin(); },
[]() -> root * { return new gorilla(); },
[]() -> root * { return new human(); },
[]() -> root * { return new blue_whale(); },
[]() -> root * { return new narwhal(); },
[]() -> root * { return new sperm_whale(); },
[]() -> root * { return new king_penguin(); },
[]() -> root * { return new magellanic_penguin(); },
[]() -> root * { return new galapagos_penguin(); },
[]() -> root * { return new sparrow(); },
};
constexpr size_t newAnimalsCount = sizeof(newAnimals) / sizeof(*newAnimals);
int dynamic_run(std::array<root *, COUNT> const &m) {
int sum = 0;
for (auto const &e : m) {
if (auto p = dynamic_cast<mammal const *>(e)) {
sum += p->mammal_proc();
}
if (auto p = dynamic_cast<bird const *>(e)) {
sum += p->bird_proc();
}
}
return sum;
}
template <typename cast> //
inline cast animal_cast(root *p) {
if (p->is_a(std::remove_pointer<cast>::type::tid)) {
return static_cast<cast>(p);
}
return nullptr;
}
template <typename cast> //
inline cast animal_cast(root const *p) {
if (p->is_a(std::remove_pointer<cast>::type::tid)) {
return static_cast<cast>(p);
}
return nullptr;
}
int static_run(std::array<root *, COUNT> const &m) {
int sum = 0;
for (auto const &e : m) {
if (auto p = animal_cast<mammal const *>(e)) {
sum += p->mammal_proc();
}
if (auto p = animal_cast<bird const *>(e)) {
sum += p->bird_proc();
}
}
return sum;
}
void run(char const *title, decltype(dynamic_run) runner,
std::array<root *, COUNT> const &m, bool production) {
auto start = high_resolution_clock::now();
auto r = runner(m);
auto end = high_resolution_clock::now();
if (production) {
std::cout << title
<< "\n"
" res="
<< r
<< "\n"
" "
<< duration_cast<microseconds>(end - start).count() * 1e-3
<< "ms\n";
}
}
void test(int num) {
std::array<root *, COUNT> m = {0};
std::mt19937_64 rng(num);
std::uniform_int_distribution<size_t> dist(0, newAnimalsCount - 1);
for (auto &e : m) {
e = newAnimals[dist(rng)]();
}
for (int i = 0; i < 3; ++i) {
run("dynamic_cast", dynamic_run, m, 2 <= i);
run("animal_cast", static_run, m, 2 <= i);
}
}
int main(int argc, char const *argv[]) {
test(argc < 2 ? 0 : std::atoi(argv[1]));
}
| 4,873 | 1,711 |
/*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/rtp_dependency_descriptor_reader.h"
#include <memory>
#include <utility>
#include <vector>
#include "rtc_base/bit_buffer.h"
#include "rtc_base/checks.h"
namespace webrtc {
namespace {
constexpr int kMaxTemporalId = 7;
constexpr int kMaxSpatialId = 3;
constexpr int kMaxTemplates = 63;
constexpr int kMaxTemplateId = kMaxTemplates - 1;
constexpr int kExtendedFieldsIndicator = kMaxTemplates;
} // namespace
RtpDependencyDescriptorReader::RtpDependencyDescriptorReader(
rtc::ArrayView<const uint8_t> raw_data,
const FrameDependencyStructure* structure,
DependencyDescriptor* descriptor)
: descriptor_(descriptor), buffer_(raw_data.data(), raw_data.size()) {
RTC_DCHECK(descriptor);
ReadMandatoryFields();
if (frame_dependency_template_id_ == kExtendedFieldsIndicator)
ReadExtendedFields();
structure_ = descriptor->attached_structure
? descriptor->attached_structure.get()
: structure;
if (structure_ == nullptr || parsing_failed_) {
parsing_failed_ = true;
return;
}
if (active_decode_targets_present_flag_) {
descriptor->active_decode_targets_bitmask =
ReadBits(structure_->num_decode_targets);
}
ReadFrameDependencyDefinition();
}
uint32_t RtpDependencyDescriptorReader::ReadBits(size_t bit_count) {
uint32_t value = 0;
if (!buffer_.ReadBits(&value, bit_count))
parsing_failed_ = true;
return value;
}
uint32_t RtpDependencyDescriptorReader::ReadNonSymmetric(size_t num_values) {
uint32_t value = 0;
if (!buffer_.ReadNonSymmetric(&value, num_values))
parsing_failed_ = true;
return value;
}
void RtpDependencyDescriptorReader::ReadTemplateDependencyStructure() {
descriptor_->attached_structure =
std::make_unique<FrameDependencyStructure>();
descriptor_->attached_structure->structure_id = ReadBits(6);
if (descriptor_->attached_structure->structure_id ==
kExtendedFieldsIndicator) {
parsing_failed_ = true;
return;
}
descriptor_->attached_structure->num_decode_targets = ReadBits(5) + 1;
ReadTemplateLayers();
ReadTemplateDtis();
ReadTemplateFdiffs();
ReadTemplateChains();
uint32_t has_resolutions = ReadBits(1);
if (has_resolutions)
ReadResolutions();
}
void RtpDependencyDescriptorReader::ReadTemplateLayers() {
enum NextLayerIdc : uint32_t {
kSameLayer = 0,
kNextTemporalLayer = 1,
kNextSpatialLayer = 2,
kNoMoreTemplates = 3,
};
std::vector<FrameDependencyTemplate> templates;
int temporal_id = 0;
int spatial_id = 0;
NextLayerIdc next_layer_idc;
do {
if (templates.size() == kMaxTemplates) {
parsing_failed_ = true;
break;
}
templates.emplace_back();
FrameDependencyTemplate& last_template = templates.back();
last_template.temporal_id = temporal_id;
last_template.spatial_id = spatial_id;
next_layer_idc = static_cast<NextLayerIdc>(ReadBits(2));
if (next_layer_idc == kNextTemporalLayer) {
temporal_id++;
if (temporal_id > kMaxTemporalId) {
parsing_failed_ = true;
break;
}
} else if (next_layer_idc == kNextSpatialLayer) {
temporal_id = 0;
spatial_id++;
if (spatial_id > kMaxSpatialId) {
parsing_failed_ = true;
break;
}
}
} while (next_layer_idc != kNoMoreTemplates && !parsing_failed_);
descriptor_->attached_structure->templates = std::move(templates);
}
void RtpDependencyDescriptorReader::ReadTemplateDtis() {
FrameDependencyStructure* structure = descriptor_->attached_structure.get();
for (FrameDependencyTemplate& current_template : structure->templates) {
current_template.decode_target_indications.resize(
structure->num_decode_targets);
for (int i = 0; i < structure->num_decode_targets; ++i) {
current_template.decode_target_indications[i] =
static_cast<DecodeTargetIndication>(ReadBits(2));
}
}
}
void RtpDependencyDescriptorReader::ReadTemplateFdiffs() {
for (FrameDependencyTemplate& current_template :
descriptor_->attached_structure->templates) {
for (uint32_t fdiff_follows = ReadBits(1); fdiff_follows;
fdiff_follows = ReadBits(1)) {
uint32_t fdiff_minus_one = ReadBits(4);
current_template.frame_diffs.push_back(fdiff_minus_one + 1);
}
}
}
void RtpDependencyDescriptorReader::ReadTemplateChains() {
FrameDependencyStructure* structure = descriptor_->attached_structure.get();
structure->num_chains = ReadNonSymmetric(structure->num_decode_targets + 1);
if (structure->num_chains == 0)
return;
for (int i = 0; i < structure->num_decode_targets; ++i) {
uint32_t protected_by_chain = ReadNonSymmetric(structure->num_chains + 1);
structure->decode_target_protected_by_chain.push_back(protected_by_chain);
}
for (FrameDependencyTemplate& frame_template : structure->templates) {
for (int chain_id = 0; chain_id < structure->num_chains; ++chain_id) {
frame_template.chain_diffs.push_back(ReadBits(4));
}
}
}
void RtpDependencyDescriptorReader::ReadResolutions() {
FrameDependencyStructure* structure = descriptor_->attached_structure.get();
// The way templates are bitpacked, they are always ordered by spatial_id.
int spatial_layers = structure->templates.back().spatial_id + 1;
structure->resolutions.reserve(spatial_layers);
for (int sid = 0; sid < spatial_layers; ++sid) {
uint16_t width_minus_1 = ReadBits(16);
uint16_t height_minus_1 = ReadBits(16);
structure->resolutions.emplace_back(width_minus_1 + 1, height_minus_1 + 1);
}
}
void RtpDependencyDescriptorReader::ReadMandatoryFields() {
descriptor_->first_packet_in_frame = ReadBits(1);
descriptor_->last_packet_in_frame = ReadBits(1);
frame_dependency_template_id_ = ReadBits(6);
descriptor_->frame_number = ReadBits(16);
}
void RtpDependencyDescriptorReader::ReadExtendedFields() {
frame_dependency_template_id_ = ReadBits(6);
if (frame_dependency_template_id_ == kExtendedFieldsIndicator) {
parsing_failed_ = true;
return;
}
bool template_dependency_structure_present_flag = ReadBits(1);
active_decode_targets_present_flag_ = ReadBits(1);
custom_dtis_flag_ = ReadBits(1);
custom_fdiffs_flag_ = ReadBits(1);
custom_chains_flag_ = ReadBits(1);
if (template_dependency_structure_present_flag) {
ReadTemplateDependencyStructure();
RTC_DCHECK(descriptor_->attached_structure);
descriptor_->active_decode_targets_bitmask =
(uint64_t{1} << descriptor_->attached_structure->num_decode_targets) -
1;
}
}
void RtpDependencyDescriptorReader::ReadFrameDependencyDefinition() {
size_t template_index = (frame_dependency_template_id_ +
(kMaxTemplateId + 1) - structure_->structure_id) %
(kMaxTemplateId + 1);
if (template_index >= structure_->templates.size()) {
parsing_failed_ = true;
return;
}
// Copy all the fields from the matching template
descriptor_->frame_dependencies = structure_->templates[template_index];
if (custom_dtis_flag_)
ReadFrameDtis();
if (custom_fdiffs_flag_)
ReadFrameFdiffs();
if (custom_chains_flag_)
ReadFrameChains();
if (structure_->resolutions.empty()) {
descriptor_->resolution = absl::nullopt;
} else {
// Format guarantees that if there were resolutions in the last structure,
// then each spatial layer got one.
RTC_DCHECK_LE(descriptor_->frame_dependencies.spatial_id,
structure_->resolutions.size());
descriptor_->resolution =
structure_->resolutions[descriptor_->frame_dependencies.spatial_id];
}
}
void RtpDependencyDescriptorReader::ReadFrameDtis() {
RTC_DCHECK_EQ(
descriptor_->frame_dependencies.decode_target_indications.size(),
structure_->num_decode_targets);
for (auto& dti : descriptor_->frame_dependencies.decode_target_indications) {
dti = static_cast<DecodeTargetIndication>(ReadBits(2));
}
}
void RtpDependencyDescriptorReader::ReadFrameFdiffs() {
descriptor_->frame_dependencies.frame_diffs.clear();
for (uint32_t next_fdiff_size = ReadBits(2); next_fdiff_size > 0;
next_fdiff_size = ReadBits(2)) {
uint32_t fdiff_minus_one = ReadBits(4 * next_fdiff_size);
descriptor_->frame_dependencies.frame_diffs.push_back(fdiff_minus_one + 1);
}
}
void RtpDependencyDescriptorReader::ReadFrameChains() {
RTC_DCHECK_EQ(descriptor_->frame_dependencies.chain_diffs.size(),
structure_->num_chains);
for (auto& chain_diff : descriptor_->frame_dependencies.chain_diffs) {
chain_diff = ReadBits(8);
}
}
} // namespace webrtc
| 9,058 | 3,040 |
#include <boost/python.hpp>
#include <Python.h>
#include <pracmln/mln.h>
#include <iostream>
/*******************************************************************************
* Defines
******************************************************************************/
#define MODULE_MLN "pracmln.mln"
#define MODULE_METHODS "pracmln.mln.methods"
#define MODULE_DATABASE "pracmln.mln.database"
#define MODULE_QUERY "pracmln.mlnquery"
#define NAME_CW_PREDS "cw_preds"
#define NAME_MAX_STEPS "maxsteps"
#define NAME_NUM_CHAINS "chains"
#define NAME_MULTI_CPU "multicore"
#define NAME_VERBOSE "verbose"
#define NAME_MERGE_DBS "mergeDBs"
#define CHECK_INITIALIZED() if(!initialized) throw "MLN is not initiazied!"
using namespace boost;
const std::string logics_array[] = {"FirstOrderLogic", "FuzzyLogic"};
const std::string grammars_array[] = {"StandardGrammar", "PRACGrammar"};
const std::vector<std::string> logics(logics_array, logics_array + sizeof(logics_array) / sizeof(logics_array[0]));
const std::vector<std::string> grammars(grammars_array, grammars_array + sizeof(grammars_array) / sizeof(grammars_array[0]));
/*******************************************************************************
* Utility
******************************************************************************/
template<typename T>
std::vector<T> listToVector(python::list list)
{
std::vector<T> vec;
vec.resize(python::len(list));
for(size_t i = 0; i < vec.size(); ++i)
{
vec[i] = python::extract<T>(list[i]);
}
return vec;
}
template<typename T>
python::list vectorToList(const std::vector<T> &vec)
{
python::list list;
for(size_t i = 0; i < vec.size(); ++i)
{
list.append(vec[i]);
}
return list;
}
/*******************************************************************************
* Internal struct
******************************************************************************/
struct MLN::Internal
{
python::object module_mln;
python::dict dict_mln;
python::object module_methods;
python::dict dict_methods;
python::object module_database;
python::dict dict_database;
python::object module_query;
python::dict dict_query;
python::object mlnObj;
python::object mln;
python::object mlnQueryObj;
python::object mlnQuery;
python::object db;
python::object method;
python::list query;
python::dict settings;
};
/*******************************************************************************
* Initialize
******************************************************************************/
MLN::MLN() : internal(NULL), method(0), logic(0), grammar(0), initialized(false), dbIsFile(false), updateDB(false), updateMLN(false)
{
if(!Py_IsInitialized())
{
Py_Initialize();
}
}
MLN::~MLN()
{
if(internal)
{
delete internal;
}
}
bool MLN::initialize()
{
if(initialized)
{
return true;
}
try
{
if(!internal)
{
internal = new Internal();
}
internal->module_mln = python::import(MODULE_MLN);
internal->dict_mln = python::extract<python::dict>(internal->module_mln.attr("__dict__"));
internal->module_methods = python::import(MODULE_METHODS);
internal->dict_methods = python::extract<python::dict>(internal->module_methods.attr("__dict__"));
internal->module_database = python::import(MODULE_DATABASE);
internal->dict_database = python::extract<python::dict>(internal->module_database.attr("__dict__"));
internal->module_query = python::import(MODULE_QUERY);
internal->dict_query = python::extract<python::dict>(internal->module_query.attr("__dict__"));
this->methods = listToVector<std::string>(python::extract<python::list>(internal->dict_methods["InferenceMethods"].attr("ids")()));
initialized = true;
setMethod(this->methods[2]);
internal->settings[NAME_CW_PREDS] = python::list();
internal->settings[NAME_MULTI_CPU] = false;
internal->settings[NAME_VERBOSE] = false;
internal->settings[NAME_MERGE_DBS] = false;
}
catch(python::error_already_set)
{
PyErr_Print();
initialized = false;
return false;
}
return true;
}
std::vector<std::string> MLN::getMethods() const
{
CHECK_INITIALIZED();
return methods;
}
std::vector<std::string> MLN::getLogics() const
{
CHECK_INITIALIZED();
return logics;
}
std::vector<std::string> MLN::getGrammars() const
{
CHECK_INITIALIZED();
return grammars;
}
/*******************************************************************************
* General
******************************************************************************/
bool MLN::setMethod(const std::string &method)
{
CHECK_INITIALIZED();
const size_t oldValue = this->method;
if(isInOptions(method, methods, this->method))
{
if(oldValue != this->method)
{
internal->method = internal->dict_methods["InferenceMethods"].attr("clazz")(this->methods[this->method]);
}
return true;
}
return false;
}
bool MLN::setLogic(const std::string &logic)
{
CHECK_INITIALIZED();
const size_t oldValue = this->logic;
if(isInOptions(logic, logics, this->logic))
{
updateMLN = updateMLN || this->logic != oldValue;
updateDB = updateMLN;
return true;
}
return false;
}
bool MLN::setGrammar(const std::string &grammar)
{
CHECK_INITIALIZED();
const size_t oldValue = this->grammar;
if(isInOptions(grammar, grammars, this->grammar))
{
updateMLN = updateMLN || this->grammar == oldValue;
updateDB = updateMLN;
return true;
}
return false;
}
void MLN::setMLN(const std::string &mln)
{
CHECK_INITIALIZED();
updateMLN = true;
updateDB = true;
this->mln = mln;
}
void MLN::setDB(const std::string &db, const bool isFile)
{
CHECK_INITIALIZED();
this->db = db;
dbIsFile = isFile;
updateDB = true;
}
void MLN::setQuery(const std::vector<std::string> &query)
{
CHECK_INITIALIZED();
internal->query = vectorToList(query);
}
std::string MLN::getMethod() const
{
CHECK_INITIALIZED();
return methods[method];
}
std::string MLN::getLogic() const
{
CHECK_INITIALIZED();
return logics[logic];
}
std::string MLN::getGrammar() const
{
CHECK_INITIALIZED();
return grammars[grammar];
}
std::string MLN::getMLN() const
{
CHECK_INITIALIZED();
return mln;
}
std::string MLN::getDB() const
{
CHECK_INITIALIZED();
return db;
}
std::vector<std::string> MLN::getQuery() const
{
CHECK_INITIALIZED();
return listToVector<std::string>(internal->query);
}
/*******************************************************************************
* Settings
******************************************************************************/
void MLN::setCWPreds(const std::vector<std::string> &cwPreds)
{
CHECK_INITIALIZED();
internal->settings[NAME_CW_PREDS] = vectorToList(cwPreds);
}
void MLN::setMaxSteps(const int value)
{
CHECK_INITIALIZED();
if(value > 0)
{
internal->settings[NAME_MAX_STEPS] = value;
}
else
{
internal->settings[NAME_MAX_STEPS].del();
}
}
void MLN::setNumChains(const int value)
{
CHECK_INITIALIZED();
if(value > 0)
{
internal->settings[NAME_NUM_CHAINS] = value;
}
else
{
internal->settings[NAME_NUM_CHAINS].del();
}
}
void MLN::setUseMultiCPU(const bool enable)
{
CHECK_INITIALIZED();
internal->settings[NAME_MULTI_CPU] = enable;
}
std::vector<std::string> MLN::getCWPreds() const
{
CHECK_INITIALIZED();
return listToVector<std::string>(python::extract<python::list>(internal->settings[NAME_CW_PREDS]));
}
int MLN::getMaxSteps() const
{
CHECK_INITIALIZED();
if(internal->settings.has_key(NAME_MAX_STEPS))
{
return python::extract<int>(internal->settings[NAME_MAX_STEPS]);
}
return -1;
}
int MLN::getNumChains() const
{
CHECK_INITIALIZED();
if(internal->settings.has_key(NAME_NUM_CHAINS))
{
return python::extract<int>(internal->settings[NAME_NUM_CHAINS]);
}
return -1;
}
bool MLN::getUseMultiCPU() const
{
CHECK_INITIALIZED();
return python::extract<bool>(internal->settings[NAME_MULTI_CPU]);
}
/*******************************************************************************
* Methods
******************************************************************************/
bool MLN::infer(std::vector<std::string> &results, std::vector<double> &probabilities)
{
CHECK_INITIALIZED();
try
{
if(!init())
{
return false;
}
//the empty config file
boost::python::list arguments;
//the actual config -> for now here, but consider making this a class member
boost::python::dict settings;
settings["mln"] = internal->mln;
settings["db"] = internal->db;
settings["method"] = internal->method;
settings["cw_preds"] = internal->settings[NAME_CW_PREDS];
settings["queries"] = internal->query;
internal->mlnQueryObj = internal->dict_query["MLNQuery"](*boost::python::tuple(arguments), **settings);
python::object resObj = internal->mlnQueryObj.attr("run")();
resObj.attr("write")();
python::dict resObjDict = python::extract<python::dict>(resObj.attr("results"));
python::list keys = resObjDict.keys();
results.resize(python::len(keys));
probabilities.resize(results.size());
for(size_t i = 0; i < results.size(); ++i)
{
results[i] = python::extract<std::string>(keys[i]);
}
std::sort(results.begin(), results.end());
for(size_t i = 0; i < results.size(); ++i)
{
probabilities[i] = python::extract<double>(resObjDict[results[i]]);
}
}
catch(python::error_already_set)
{
PyErr_Print();
return false;
}
return true;
}
/*******************************************************************************
* Private
******************************************************************************/
bool MLN::init()
{
try
{
if(updateMLN)
{
internal->mlnObj = internal->dict_mln["MLN"];
internal->mln = internal->mlnObj.attr("load")(mln, logics[logic], grammars[grammar]);
}
if(updateDB)
{
python::list dbs;
if(dbIsFile)
{
dbs = python::extract<python::list>(internal->dict_database["Database.load"](internal->mln, db));
}
else
{
dbs = python::extract<python::list>(internal->dict_database["parse_db"](internal->mln, db));
}
internal->db = dbs[0];
}
updateMLN = false;
updateDB = false;
}
catch(python::error_already_set)
{
PyErr_Print();
return false;
}
return true;
}
bool MLN::isInOptions(const std::string &option, const std::vector<std::string> &options, size_t &value) const
{
for(size_t i = 0; i < options.size(); ++i)
{
if(option == options[i])
{
value = i;
return true;
}
}
return false;
}
| 10,704 | 3,611 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "checksumstd.hxx"
#ifdef _IA64_
extern "C" {
void __lfetch( INT Level,void const *Address );
#pragma intrinsic( __lfetch )
}
#define MD_LFHINT_NONE 0x00
#define MD_LFHINT_NT1 0x01
#define MD_LFHINT_NT2 0x02
#define MD_LFHINT_NTA 0x03
#endif
typedef ULONG( *PFNCHECKSUMOLDFORMAT )( const unsigned char * const, const ULONG );
ULONG ChecksumSelectOldFormat( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormatSlowly( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormat64Bit( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormatSSE( const unsigned char * const pb, const ULONG cb );
ULONG ChecksumOldFormatSSE2( const unsigned char * const pb, const ULONG cb );
static PFNCHECKSUMOLDFORMAT pfnChecksumOldFormat = ChecksumSelectOldFormat;
ULONG ChecksumOldFormat( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormat;
Unused( pfn );
return pfnChecksumOldFormat( pb, cb );
}
typedef XECHECKSUM( *PFNCHECKSUMNEWFORMAT )( const unsigned char * const, const ULONG, const ULONG, BOOL );
XECHECKSUM ChecksumSelectNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
enum ChecksumParityMaskFunc
{
ParityMaskFuncDefault = 0,
ParityMaskFuncPopcnt,
};
XECHECKSUM ChecksumNewFormatSlowly( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
XECHECKSUM ChecksumNewFormat64Bit( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
XECHECKSUM ChecksumNewFormatSSE( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
template <ChecksumParityMaskFunc TParityMaskFunc> XECHECKSUM ChecksumNewFormatSSE2( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue);
XECHECKSUM ChecksumNewFormatAVX( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock = fTrue );
PFNCHECKSUMNEWFORMAT pfnChecksumNewFormat = ChecksumSelectNewFormat;
XECHECKSUM ChecksumNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
{
PFNCHECKSUMNEWFORMAT pfn = ChecksumNewFormat;
Unused( pfn );
return pfnChecksumNewFormat( pb, cb, pgno, fHeaderBlock );
}
ULONG ChecksumSelectOldFormat( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumSelectOldFormat;
#if defined _X86_ && defined _CHPE_X86_ARM64_
pfn = ChecksumOldFormatSlowly;
#else
if( FSSEInstructionsAvailable() )
{
if( FSSE2InstructionsAvailable() )
{
pfn = ChecksumOldFormatSSE2;
}
else
{
pfn = ChecksumOldFormatSSE;
}
}
else if( sizeof( void * ) == sizeof( ULONG ) * 2 )
{
pfn = ChecksumOldFormat64Bit;
}
else
{
pfn = ChecksumOldFormatSlowly;
}
#endif
pfnChecksumOldFormat = pfn;
return (*pfn)( pb, cb );
}
ULONG ChecksumOldFormatSlowly( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormatSlowly;
Unused( pfn );
const ULONG * pdw = (ULONG *)pb;
const INT cDWords = 8;
const INT cbStep = cDWords * sizeof( ULONG );
__int64 cbT = cb;
Assert( 0 == ( cbT % cbStep ) );
ULONG dwChecksum = 0x89abcdef ^ pdw[0];
while ( ( cbT -= cbStep ) >= 0 )
{
dwChecksum ^= pdw[0]
^ pdw[1]
^ pdw[2]
^ pdw[3]
^ pdw[4]
^ pdw[5]
^ pdw[6]
^ pdw[7];
pdw += cDWords;
}
return dwChecksum;
}
ULONG ChecksumOldFormat64Bit( const unsigned char * const pb, const ULONG cb )
{
PFNCHECKSUMOLDFORMAT pfn = ChecksumOldFormat64Bit;
Unused( pfn );
const unsigned __int64* pqw = (unsigned __int64 *)pb;
unsigned __int64 qwChecksum = 0;
const INT cQWords = 4;
const INT cbStep = cQWords * sizeof( unsigned __int64 );
__int64 cbT = cb;
Assert( 0 == ( cbT % cbStep ) );
qwChecksum ^= pqw[0] & 0x00000000FFFFFFFF;
while ( ( cbT -= cbStep ) >= 0 )
{
#ifdef _IA64_
__lfetch( MD_LFHINT_NTA, (unsigned char *)(pqw + 4) );
#endif
qwChecksum ^= pqw[0];
qwChecksum ^= pqw[1];
qwChecksum ^= pqw[2];
qwChecksum ^= pqw[3];
pqw += cQWords;
}
const unsigned __int64 qwUpper = ( qwChecksum >> ( sizeof( ULONG ) * 8 ) );
const unsigned __int64 qwLower = qwChecksum & 0x00000000FFFFFFFF;
qwChecksum = qwUpper ^ qwLower;
const ULONG ulChecksum = static_cast<ULONG>( qwChecksum ) ^ 0x89abcdef;
return ulChecksum;
}
XECHECKSUM ChecksumSelectNewFormat( const unsigned char * const pb, const ULONG cb, const ULONG pgno, BOOL fHeaderBlock )
{
PFNCHECKSUMNEWFORMAT pfn = ChecksumSelectNewFormat;
#if defined _X86_ && defined _CHPE_X86_ARM64_
pfn = ChecksumNewFormatSlowly;
#else
if( FAVXEnabled() && FPopcntAvailable() )
{
pfn = ChecksumNewFormatAVX;
}
else if( FSSEInstructionsAvailable() )
{
if( FSSE2InstructionsAvailable() )
{
if( FPopcntAvailable() )
{
pfn = ChecksumNewFormatSSE2<ParityMaskFuncPopcnt>;
}
else
{
pfn = ChecksumNewFormatSSE2<ParityMaskFuncDefault>;
}
}
else
{
pfn = ChecksumNewFormatSSE;
}
}
else if( sizeof( DWORD_PTR ) == sizeof( ULONG ) * 2 )
{
pfn = ChecksumNewFormat64Bit;
}
else
{
pfn = ChecksumNewFormatSlowly;
}
#endif
pfnChecksumNewFormat = pfn;
return (*pfn)( pb, cb, pgno, fHeaderBlock );
}
ULONG DwECCChecksumFromXEChecksum( const XECHECKSUM checksum )
{
return (ULONG)( checksum >> 32 );
}
ULONG DwXORChecksumFromXEChecksum( const XECHECKSUM checksum )
{
return (ULONG)( checksum & 0xffffffff );
}
INT CbitSet( const ULONG dw )
{
INT cbit = 0;
for( INT ibit = 0; ibit < 32; ++ibit )
{
if( dw & ( 1 << ibit ) )
{
++cbit;
}
}
return cbit;
}
BOOL FECCErrorIsCorrectable( const UINT cb, const XECHECKSUM xeChecksumExpected, const XECHECKSUM xeChecksumActual )
{
Assert( xeChecksumActual != xeChecksumExpected );
const DWORD dwECCChecksumExpected = DwECCChecksumFromXEChecksum( xeChecksumExpected );
const DWORD dwECCChecksumActual = DwECCChecksumFromXEChecksum( xeChecksumActual );
if ( FECCErrorIsCorrectable( cb, dwECCChecksumExpected, dwECCChecksumActual ) )
{
const ULONG dwXor = DwXORChecksumFromXEChecksum( xeChecksumActual ) ^ DwXORChecksumFromXEChecksum( xeChecksumExpected );
if ( 1 == CbitSet( dwXor ) )
{
return fTrue;
}
}
return fFalse;
}
UINT IbitCorrupted( const UINT cb, const XECHECKSUM xeChecksumExpected, const XECHECKSUM xeChecksumActual )
{
Assert( xeChecksumExpected != xeChecksumActual );
Assert( FECCErrorIsCorrectable( cb, xeChecksumExpected, xeChecksumActual ) );
const DWORD dwECCChecksumExpected = DwECCChecksumFromXEChecksum( xeChecksumExpected );
const DWORD dwECCChecksumActual = DwECCChecksumFromXEChecksum( xeChecksumActual );
Assert( dwECCChecksumExpected != dwECCChecksumActual );
return IbitCorrupted( cb, dwECCChecksumExpected, dwECCChecksumActual );
}
BOOL FECCErrorIsCorrectable( const UINT cb, const ULONG dwECCChecksumExpected, const ULONG dwECCChecksumActual )
{
const ULONG dwEcc = dwECCChecksumActual ^ dwECCChecksumExpected;
const ULONG ulMask = ( ( cb << 3 ) - 1 );
const ULONG ulX = ( ( dwEcc >> 16 ) ^ dwEcc ) & ulMask;
return ulMask == ulX;
}
UINT IbitCorrupted( const UINT cb, const ULONG dwECCChecksumExpected, const ULONG dwECCChecksumActual )
{
const ULONG dwEcc = dwECCChecksumActual ^ dwECCChecksumExpected;
if ( dwEcc == 0 )
{
return ulMax;
}
const UINT ibitCorrupted = (UINT)( dwEcc & 0xffff );
const UINT ibCorrupted = ibitCorrupted / 8;
if ( ibCorrupted >= cb )
{
return ulMax;
}
return ibitCorrupted;
}
| 8,457 | 3,156 |
/******************************************************************************
* Copyright 2017-2018 Baidu Robotic Vision 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 "timer.h"
#include <glog/logging.h>
#ifndef __DEVELOPMENT_DEBUG_MODE__
#define __HELPER_TIMER_NO_DEBUG__
#endif
namespace XP {
ScopedMicrosecondTimer::ScopedMicrosecondTimer(const std::string& text_id,
int vlog_level)
: text_id_(text_id),
vlog_level_(vlog_level),
t_start_(std::chrono::steady_clock::now()) {}
ScopedMicrosecondTimer::~ScopedMicrosecondTimer() {
#ifndef __HELPER_TIMER_NO_DEBUG__
VLOG(vlog_level_) << "ScopedTimer " << text_id_ << "=["
<< std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t_start_)
.count()
<< "] microseconds";
#endif
}
ScopedLoopProfilingTimer::ScopedLoopProfilingTimer(const std::string& text_id,
int vlog_level)
: text_id_(text_id),
vlog_level_(vlog_level),
t_start_(std::chrono::steady_clock::now()) {}
ScopedLoopProfilingTimer::~ScopedLoopProfilingTimer() {
using namespace std::chrono;
// print timing info even if in release mode
if (VLOG_IS_ON(vlog_level_)) {
VLOG(vlog_level_)
<< "ScopedLoopProfilingTimer " << text_id_ << " start_end=["
<< duration_cast<microseconds>(t_start_.time_since_epoch()).count()
<< " "
<< duration_cast<microseconds>(steady_clock::now().time_since_epoch())
.count()
<< "]";
}
}
MicrosecondTimer::MicrosecondTimer(const std::string& text_id, int vlog_level)
: has_ended_(false), text_id_(text_id), vlog_level_(vlog_level) {
t_start_ = std::chrono::steady_clock::now();
}
MicrosecondTimer::MicrosecondTimer()
: has_ended_(false), text_id_(""), vlog_level_(99) {
t_start_ = std::chrono::steady_clock::now();
}
int MicrosecondTimer::end() {
CHECK(!has_ended_);
has_ended_ = true;
int micro_sec_passed = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t_start_)
.count();
#ifndef __HELPER_TIMER_NO_DEBUG__
VLOG(vlog_level_) << "Timer " << text_id_ << "=[" << micro_sec_passed
<< "] microseconds";
#endif
return micro_sec_passed;
}
MicrosecondTimer::~MicrosecondTimer() {
if (!has_ended_) {
VLOG(vlog_level_) << "MicrosecondTimer " << text_id_ << " is not used";
}
}
} // namespace XP
| 3,235 | 1,055 |
#include "WktGeometry.h"
#include "Engine.h"
#include <gis/Box.h>
#include <macgyver/Exception.h>
#include <ogr_geometry.h>
namespace SmartMet
{
namespace Engine
{
namespace Geonames
{
namespace
{
// ----------------------------------------------------------------------
/*!
* \brief Get location name from location:radius
*/
// ----------------------------------------------------------------------
std::string get_name_base(const std::string& theName)
{
try
{
std::string place = theName;
// remove radius if exists
if (place.find(':') != std::string::npos)
place = place.substr(0, place.find(':'));
return place;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
std::unique_ptr<OGRGeometry> get_ogr_geometry(const std::string wktString, double radius /*= 0.0*/)
{
std::unique_ptr<OGRGeometry> ret;
std::string wkt = get_name_base(wktString);
OGRGeometry* geom = Fmi::OGR::createFromWkt(wkt, 4326);
if (geom)
{
if (radius > 0.0)
{
std::unique_ptr<OGRGeometry> poly;
poly.reset(Fmi::OGR::expandGeometry(geom, radius * 1000));
OGRGeometryFactory::destroyGeometry(geom);
geom = poly.release();
}
ret.reset(geom);
}
return ret;
}
std::list<const OGRGeometry*> get_geometry_list(const OGRGeometry* geom)
{
std::list<const OGRGeometry*> ret;
switch (geom->getGeometryType())
{
case wkbMultiPoint:
{
// OGRMultiPoint geometry -> extract OGRPoints
const auto* mpGeom = static_cast<const OGRMultiPoint*>(geom);
int numGeoms = mpGeom->getNumGeometries();
for (int i = 0; i < numGeoms; i++)
ret.push_back(mpGeom->getGeometryRef(i));
}
break;
case wkbMultiLineString:
{
// OGRMultiLineString geometry -> extract OGRLineStrings
const auto* mlsGeom = static_cast<const OGRMultiLineString*>(geom);
int numGeoms = mlsGeom->getNumGeometries();
for (int i = 0; i < numGeoms; i++)
ret.push_back(mlsGeom->getGeometryRef(i));
}
break;
case wkbMultiPolygon:
{
// OGRMultiLineString geometry -> extract OGRLineStrings
const auto* mpolGeom = static_cast<const OGRMultiPolygon*>(geom);
int numGeoms = mpolGeom->getNumGeometries();
for (int i = 0; i < numGeoms; i++)
ret.push_back(mpolGeom->getGeometryRef(i));
}
break;
case wkbPoint:
case wkbLineString:
case wkbPolygon:
ret.push_back(geom);
break;
default:
// no other geometries are supported
break;
}
return ret;
}
NFmiSvgPath get_svg_path(const OGRGeometry& geom)
{
try
{
NFmiSvgPath ret;
// Get SVG-path
Fmi::Box box = Fmi::Box::identity();
std::string svgString = Fmi::OGR::exportToSvg(geom, box, 6);
svgString.insert(0, " \"\n");
svgString.append(" \"\n");
std::stringstream svgStringStream(svgString);
ret.Read(svgStringStream);
return ret;
}
catch (...)
{
throw Fmi::Exception(BCP, "Failed to create NFmiSvgPath from OGRGeometry");
}
}
bool is_multi_geometry(const OGRGeometry& geom)
{
bool ret = false;
switch (geom.getGeometryType())
{
case wkbMultiPoint:
case wkbMultiLineString:
case wkbMultiPolygon:
{
ret = true;
}
break;
default:
break;
}
return ret;
}
} // namespace
// ----------------------------------------------------------------------
/*!
* \brief Initialize the WktGeometry object
*/
// ----------------------------------------------------------------------
void WktGeometry::init(const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
try
{
// Create OGRGeometry
geometryFromWkt(loc->name, loc->radius);
// Get SVG-path
svgPathsFromGeometry();
// Get locations from OGRGeometry; OGRMulti* geometries may contain many locations
locationsFromGeometry(loc, language, geoengine);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create OGRGeometry from wkt-string
*/
// ----------------------------------------------------------------------
void WktGeometry::geometryFromWkt(const std::string& wktString, double radius)
{
if (wktString.find(" as") != std::string::npos)
itsName = wktString.substr(wktString.find(" as") + 3);
else
{
itsName = wktString;
if (itsName.size() > 60)
{
itsName = wktString.substr(0, 30);
itsName += " ...";
}
}
itsGeom = get_ogr_geometry(wktString, radius).release();
}
// ----------------------------------------------------------------------
/*!
* \brief Create NFmiSvgPath object(s) from OGRGeometry
*/
// ----------------------------------------------------------------------
void WktGeometry::svgPathsFromGeometry()
{
itsSvgPath = get_svg_path(*itsGeom);
if (is_multi_geometry(*itsGeom))
{
std::list<const OGRGeometry*> glist = get_geometry_list(itsGeom);
for (const auto* g : glist)
itsSvgPaths.push_back(get_svg_path(*g));
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create Spine::LocationPtr objects from OGRGeometry
*/
// ----------------------------------------------------------------------
void WktGeometry::locationsFromGeometry(const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
itsLocation = locationFromGeometry(itsGeom, loc, language, geoengine);
if (is_multi_geometry(*itsGeom))
{
std::list<const OGRGeometry*> glist = get_geometry_list(itsGeom);
for (const auto* g : glist)
itsLocations.push_back(locationFromGeometry(g, loc, language, geoengine));
}
}
// ----------------------------------------------------------------------
/*!
* \brief Create Spine::LocationPtr OGRGeometry
*/
// ----------------------------------------------------------------------
Spine::LocationPtr WktGeometry::locationFromGeometry(
const OGRGeometry* geom,
const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
OGREnvelope envelope;
geom->getEnvelope(&envelope);
double top = envelope.MaxY;
double bottom = envelope.MinY;
double left = envelope.MinX;
double right = envelope.MaxX;
double lon = (right + left) / 2.0;
double lat = (top + bottom) / 2.0;
Spine::LocationPtr geoloc = geoengine.lonlatSearch(lon, lat, language);
std::unique_ptr<Spine::Location> tmp(new Spine::Location(geoloc->geoid,
"", // tloc.tag,
geoloc->iso2,
geoloc->municipality,
geoloc->area,
geoloc->feature,
geoloc->country,
geoloc->longitude,
geoloc->latitude,
geoloc->timezone,
geoloc->population,
geoloc->elevation));
tmp->radius = loc->radius;
tmp->type = loc->type;
tmp->name = itsName;
OGRwkbGeometryType type = geom->getGeometryType();
switch (type)
{
case wkbPoint:
{
tmp->type = Spine::Location::CoordinatePoint;
}
break;
case wkbPolygon:
case wkbMultiPolygon:
{
tmp->type = Spine::Location::Area;
}
break;
case wkbLineString:
case wkbMultiLineString:
case wkbMultiPoint:
{
// LINESTRING, MULTILINESTRING and MULTIPOINT are handled in a similar fashion
tmp->type = Spine::Location::Path;
}
break;
default:
break;
};
Spine::LocationPtr ret(tmp.release());
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Initialize the WktGeometry object
*/
// ----------------------------------------------------------------------
WktGeometry::WktGeometry(const Spine::LocationPtr loc,
const std::string& language,
const SmartMet::Engine::Geonames::Engine& geoengine)
{
init(loc, language, geoengine);
}
// ----------------------------------------------------------------------
/*!
* \brief Destroy OGRGeometry object
*/
// ----------------------------------------------------------------------
WktGeometry::~WktGeometry()
{
if (itsGeom)
{
OGRGeometryFactory::destroyGeometry(itsGeom);
itsGeom = nullptr;
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get Spine::LocationPtr
*/
// ----------------------------------------------------------------------
Spine::LocationPtr WktGeometry::getLocation() const
{
return itsLocation;
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of Spine::LocationPtr objects
*
* For multipart geometry this returns list of Spine::LocationPtr objects,
* that has been created from geometiry primitives inside multipart geometry.
*
* For geometry primitives this returns empty list.
*/
// ----------------------------------------------------------------------
Spine::LocationList WktGeometry::getLocations() const
{
return itsLocations;
}
// ----------------------------------------------------------------------
/*!
* \brief Get NFmiSvgPath object
*/
// ----------------------------------------------------------------------
NFmiSvgPath WktGeometry::getSvgPath() const
{
return itsSvgPath;
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of NFmiSvgPath objects
*
* For multipart geometry this returns list of NFmiSvgPath objects,
* that has been created from geometiry primitives inside multipart geometry.
*
* For geometry primitives this returns empty list.
*/
// ----------------------------------------------------------------------
std::list<NFmiSvgPath> WktGeometry::getSvgPaths() const
{
return itsSvgPaths;
}
// ----------------------------------------------------------------------
/*!
* \brief Get OGRGeometry object
*/
// ----------------------------------------------------------------------
const OGRGeometry* WktGeometry::getGeometry() const
{
return itsGeom;
}
// ----------------------------------------------------------------------
/*!
* \brief Get name of geometry
*/
// ----------------------------------------------------------------------
const std::string& WktGeometry::getName() const
{
return itsName;
}
// ----------------------------------------------------------------------
/*!
* \brief Adds new geometry into container
*/
// ----------------------------------------------------------------------
void WktGeometries::addWktGeometry(const std::string& id, WktGeometryPtr wktGeometry)
{
itsWktGeometries.insert(std::make_pair(id, wktGeometry));
}
Spine::LocationPtr WktGeometries::getLocation(const std::string& id) const
{
Spine::LocationPtr ret = nullptr;
if (itsWktGeometries.find(id) != itsWktGeometries.end())
{
WktGeometryPtr wktGeom = itsWktGeometries.at(id);
ret = wktGeom->getLocation();
}
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of Spine::LocationPtr objects of specified geometry
*/
// ----------------------------------------------------------------------
Spine::LocationList WktGeometries::getLocations(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getLocations();
return Spine::LocationList();
}
// ----------------------------------------------------------------------
/*!
* \brief Get NFmiSvgPath object of specified geometry
*/
// ----------------------------------------------------------------------
NFmiSvgPath WktGeometries::getSvgPath(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getSvgPath();
return NFmiSvgPath();
}
// ----------------------------------------------------------------------
/*!
* \brief Get list of NFmiSvgPath objects of specified geometry
*/
// ----------------------------------------------------------------------
std::list<NFmiSvgPath> WktGeometries::getSvgPaths(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getSvgPaths();
return std::list<NFmiSvgPath>();
}
// ----------------------------------------------------------------------
/*!
* \brief Get OGRGeometry object of specified geometry
*/
// ----------------------------------------------------------------------
const OGRGeometry* WktGeometries::getGeometry(const std::string& id) const
{
const OGRGeometry* ret = nullptr;
if (itsWktGeometries.find(id) != itsWktGeometries.end())
{
WktGeometryPtr wktGeom = itsWktGeometries.at(id);
ret = wktGeom->getGeometry();
}
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Get name of specified geometry
*/
// ----------------------------------------------------------------------
std::string WktGeometries::getName(const std::string& id) const
{
if (itsWktGeometries.find(id) != itsWktGeometries.end())
return itsWktGeometries.at(id)->getName();
return std::string();
}
} // namespace Geonames
} // namespace Engine
} // namespace SmartMet
| 13,996 | 4,144 |
#include "Environment.h"
#include <cstdlib>
// create environment
Environment environment;
int xpos = environment.getW()/2 - 50;
int ypos = environment.getH()/2 - 50;
int xvel = 0;
int yvel = 0;
int xtarget = 0;
int ytarget = 0;
drawRects() {
// render black square
environment.setRenderColor(0x00, 0x00, 0x00, 0xFF);
environment.drawRectangle(xpos, ypos, 100, 100);
// render green square
environment.setRenderColor(0x00, 200, 0x00, 0xFF);
environment.drawRectangle(xtarget - 5, ytarget - 5, 10, 10);
}
int chooseRandomX() {
return rand() % environment.getW();
}
int chooseRandomY() {
return rand() % environment.getH();
}
changeRectVel() {
// if left, go right
if (xpos < xtarget) {
xvel = 1;
}
// if right, go left
if (xpos > xtarget) {
xvel = -1;
}
// if up, go down
if (ypos < ytarget) {
yvel = 1;
}
// if down, go up
if (ypos > ytarget) {
yvel = -1;
}
// if reached, stop
if (xpos == xtarget) {
xvel = 0;
}
if (ypos == ytarget) {
yvel = 0;
}
if (xpos == xtarget && ypos == ytarget) {
xtarget = chooseRandomX();
ytarget = chooseRandomY();
}
}
changeRectPos() {
xpos += xvel;
ypos += yvel;
}
int main(int argc, char* args[]) {
// set title
environment.setTitle("Environment Test 5");
// set width and height of the screen
environment.setScreenWidth(700);
environment.setScreenHeight(700);
// initialize
environment.init();
// load media
environment.loadMedia();
// main loop
while (environment.isRunning()) {
while (environment.pollEvent() != 0) {
if (environment.getEvent()->type == SDL_QUIT) {
environment.setRunning(false);
}
}
// clear environment
environment.setRenderColor(0xFF, 0xFF, 0xFF, 0XFF);
environment.clear();
// draw rectangle
drawRects();
// change velocity
changeRectVel();
// change x and y
changeRectPos();
// present environment
environment.present();
}
// clean up environment
environment.cleanUp();
} | 1,972 | 838 |
#include <Foundation/FoundationPCH.h>
#include <Foundation/Logging/Log.h>
#include <Foundation/Profiling/Profiling.h>
#include <Foundation/Threading/Implementation/TaskGroup.h>
#include <Foundation/Threading/Implementation/TaskSystemState.h>
#include <Foundation/Threading/Implementation/TaskWorkerThread.h>
#include <Foundation/Threading/Lock.h>
#include <Foundation/Threading/TaskSystem.h>
ezTaskGroupID ezTaskSystem::CreateTaskGroup(ezTaskPriority::Enum Priority, ezOnTaskGroupFinishedCallback callback)
{
EZ_LOCK(s_TaskSystemMutex);
ezUInt32 i = 0;
// this search could be speed up with a stack of free groups
for (; i < s_State->m_TaskGroups.GetCount(); ++i)
{
if (!s_State->m_TaskGroups[i].m_bInUse)
{
goto foundtaskgroup;
}
}
// no free group found, create a new one
s_State->m_TaskGroups.ExpandAndGetRef();
s_State->m_TaskGroups[i].m_uiTaskGroupIndex = static_cast<ezUInt16>(i);
foundtaskgroup:
s_State->m_TaskGroups[i].Reuse(Priority, callback);
ezTaskGroupID id;
id.m_pTaskGroup = &s_State->m_TaskGroups[i];
id.m_uiGroupCounter = s_State->m_TaskGroups[i].m_uiGroupCounter;
return id;
}
void ezTaskSystem::AddTaskToGroup(ezTaskGroupID groupID, const ezSharedPtr<ezTask>& pTask)
{
EZ_ASSERT_DEBUG(pTask != nullptr, "Cannot add nullptr tasks.");
EZ_ASSERT_DEV(pTask->IsTaskFinished(), "The given task is not finished! Cannot reuse a task before it is done.");
EZ_ASSERT_DEBUG(!pTask->m_sTaskName.IsEmpty(), "Every task should have a name");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
pTask->Reset();
pTask->m_BelongsToGroup = groupID;
groupID.m_pTaskGroup->m_Tasks.PushBack(pTask);
}
void ezTaskSystem::AddTaskGroupDependency(ezTaskGroupID groupID, ezTaskGroupID DependsOn)
{
EZ_ASSERT_DEBUG(DependsOn.IsValid(), "Invalid dependency");
EZ_ASSERT_DEBUG(groupID.m_pTaskGroup != DependsOn.m_pTaskGroup || groupID.m_uiGroupCounter != DependsOn.m_uiGroupCounter, "Group cannot depend on itselfs");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
groupID.m_pTaskGroup->m_DependsOnGroups.PushBack(DependsOn);
}
void ezTaskSystem::AddTaskGroupDependencyBatch(ezArrayPtr<const ezTaskGroupDependency> batch)
{
#if EZ_ENABLED(EZ_COMPILE_FOR_DEBUG)
// lock here once to reduce the overhead of ezTaskGroup::DebugCheckTaskGroup inside AddTaskGroupDependency
EZ_LOCK(s_TaskSystemMutex);
#endif
for (const ezTaskGroupDependency& dep : batch)
{
AddTaskGroupDependency(dep.m_TaskGroup, dep.m_DependsOn);
}
}
void ezTaskSystem::StartTaskGroup(ezTaskGroupID groupID)
{
EZ_ASSERT_DEV(s_ThreadState->m_Workers[ezWorkerThreadType::ShortTasks].GetCount() > 0, "No worker threads started.");
ezTaskGroup::DebugCheckTaskGroup(groupID, s_TaskSystemMutex);
ezInt32 iActiveDependencies = 0;
{
EZ_LOCK(s_TaskSystemMutex);
ezTaskGroup& tg = *groupID.m_pTaskGroup;
tg.m_bStartedByUser = true;
for (ezUInt32 i = 0; i < tg.m_DependsOnGroups.GetCount(); ++i)
{
if (!IsTaskGroupFinished(tg.m_DependsOnGroups[i]))
{
ezTaskGroup& Dependency = *tg.m_DependsOnGroups[i].m_pTaskGroup;
// add this task group to the list of dependencies, such that when that group finishes, this task group can get woken up
Dependency.m_OthersDependingOnMe.PushBack(groupID);
// count how many other groups need to finish before this task group can be executed
++iActiveDependencies;
}
}
if (iActiveDependencies != 0)
{
// atomic integers are quite slow, so do not use them in the loop, where they are not yet needed
tg.m_iNumActiveDependencies = iActiveDependencies;
}
}
if (iActiveDependencies == 0)
{
ScheduleGroupTasks(groupID.m_pTaskGroup, false);
}
}
void ezTaskSystem::StartTaskGroupBatch(ezArrayPtr<const ezTaskGroupID> batch)
{
EZ_LOCK(s_TaskSystemMutex);
for (const ezTaskGroupID& group : batch)
{
StartTaskGroup(group);
}
}
bool ezTaskSystem::IsTaskGroupFinished(ezTaskGroupID Group)
{
// if the counters differ, the task group has been reused since the GroupID was created, so that group has finished
return (Group.m_pTaskGroup == nullptr) || (Group.m_pTaskGroup->m_uiGroupCounter != Group.m_uiGroupCounter);
}
void ezTaskSystem::ScheduleGroupTasks(ezTaskGroup* pGroup, bool bHighPriority)
{
if (pGroup->m_Tasks.IsEmpty())
{
pGroup->m_iNumRemainingTasks = 1;
// "finish" one task -> will finish the task group and kick off dependent groups
TaskHasFinished(nullptr, pGroup);
return;
}
ezInt32 iRemainingTasks = 0;
// add all the tasks to the task list, so that they will be processed
{
EZ_LOCK(s_TaskSystemMutex);
// store how many tasks from this groups still need to be processed
for (auto pTask : pGroup->m_Tasks)
{
iRemainingTasks += ezMath::Max(1u, pTask->m_uiMultiplicity);
pTask->m_iRemainingRuns = ezMath::Max(1u, pTask->m_uiMultiplicity);
}
pGroup->m_iNumRemainingTasks = iRemainingTasks;
for (ezUInt32 task = 0; task < pGroup->m_Tasks.GetCount(); ++task)
{
auto& pTask = pGroup->m_Tasks[task];
for (ezUInt32 mult = 0; mult < ezMath::Max(1u, pTask->m_uiMultiplicity); ++mult)
{
TaskData td;
td.m_pBelongsToGroup = pGroup;
td.m_pTask = pTask;
td.m_pTask->m_bTaskIsScheduled = true;
td.m_uiInvocation = mult;
if (bHighPriority)
s_State->m_Tasks[pGroup->m_Priority].PushFront(td);
else
s_State->m_Tasks[pGroup->m_Priority].PushBack(td);
}
}
// send the proper thread signal, to make sure one of the correct worker threads is awake
switch (pGroup->m_Priority)
{
case ezTaskPriority::EarlyThisFrame:
case ezTaskPriority::ThisFrame:
case ezTaskPriority::LateThisFrame:
case ezTaskPriority::EarlyNextFrame:
case ezTaskPriority::NextFrame:
case ezTaskPriority::LateNextFrame:
case ezTaskPriority::In2Frames:
case ezTaskPriority::In3Frames:
case ezTaskPriority::In4Frames:
case ezTaskPriority::In5Frames:
case ezTaskPriority::In6Frames:
case ezTaskPriority::In7Frames:
case ezTaskPriority::In8Frames:
case ezTaskPriority::In9Frames:
{
WakeUpThreads(ezWorkerThreadType::ShortTasks, iRemainingTasks);
break;
}
case ezTaskPriority::LongRunning:
case ezTaskPriority::LongRunningHighPriority:
{
WakeUpThreads(ezWorkerThreadType::LongTasks, iRemainingTasks);
break;
}
case ezTaskPriority::FileAccess:
case ezTaskPriority::FileAccessHighPriority:
{
WakeUpThreads(ezWorkerThreadType::FileAccess, iRemainingTasks);
break;
}
case ezTaskPriority::SomeFrameMainThread:
case ezTaskPriority::ThisFrameMainThread:
case ezTaskPriority::ENUM_COUNT:
// nothing to do for these enum values
break;
}
}
}
void ezTaskSystem::DependencyHasFinished(ezTaskGroup* pGroup)
{
// remove one dependency from the group
if (pGroup->m_iNumActiveDependencies.Decrement() == 0)
{
// if there are no remaining dependencies, kick off all tasks in this group
ScheduleGroupTasks(pGroup, true);
}
}
ezResult ezTaskSystem::CancelGroup(ezTaskGroupID Group, ezOnTaskRunning::Enum OnTaskRunning)
{
if (ezTaskSystem::IsTaskGroupFinished(Group))
return EZ_SUCCESS;
EZ_PROFILE_SCOPE("CancelGroup");
EZ_LOCK(s_TaskSystemMutex);
ezResult res = EZ_SUCCESS;
auto TasksCopy = Group.m_pTaskGroup->m_Tasks;
// first cancel ALL the tasks in the group, without waiting for anything
for (ezUInt32 task = 0; task < TasksCopy.GetCount(); ++task)
{
if (CancelTask(TasksCopy[task], ezOnTaskRunning::ReturnWithoutBlocking) == EZ_FAILURE)
{
res = EZ_FAILURE;
}
}
// if all tasks could be removed without problems, we do not need to try it again with blocking
if (OnTaskRunning == ezOnTaskRunning::WaitTillFinished && res == EZ_FAILURE)
{
// now cancel the tasks in the group again, this time wait for those that are already running
for (ezUInt32 task = 0; task < TasksCopy.GetCount(); ++task)
{
CancelTask(TasksCopy[task], ezOnTaskRunning::WaitTillFinished).IgnoreResult();
}
}
return res;
}
void ezTaskSystem::WaitForGroup(ezTaskGroupID Group)
{
EZ_PROFILE_SCOPE("WaitForGroup");
EZ_ASSERT_DEV(tl_TaskWorkerInfo.m_bAllowNestedTasks, "The executing task '{}' is flagged to never wait for other tasks but does so anyway. Remove the flag or remove the wait-dependency.", tl_TaskWorkerInfo.m_szTaskName);
const auto ThreadTaskType = tl_TaskWorkerInfo.m_WorkerType;
const bool bAllowSleep = ThreadTaskType != ezWorkerThreadType::MainThread;
while (!ezTaskSystem::IsTaskGroupFinished(Group))
{
if (!HelpExecutingTasks(Group))
{
if (bAllowSleep)
{
const ezWorkerThreadType::Enum typeToWakeUp = (ThreadTaskType == ezWorkerThreadType::Unknown) ? ezWorkerThreadType::ShortTasks : ThreadTaskType;
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Blocked) == (int)ezTaskWorkerState::Active, "Corrupt worker state");
}
WakeUpThreads(typeToWakeUp, 1);
Group.m_pTaskGroup->WaitForFinish(Group);
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Active) == (int)ezTaskWorkerState::Blocked, "Corrupt worker state");
}
break;
}
else
{
ezThreadUtils::YieldTimeSlice();
}
}
}
}
void ezTaskSystem::WaitForCondition(ezDelegate<bool()> condition)
{
EZ_PROFILE_SCOPE("WaitForCondition");
EZ_ASSERT_DEV(tl_TaskWorkerInfo.m_bAllowNestedTasks, "The executing task '{}' is flagged to never wait for other tasks but does so anyway. Remove the flag or remove the wait-dependency.", tl_TaskWorkerInfo.m_szTaskName);
const auto ThreadTaskType = tl_TaskWorkerInfo.m_WorkerType;
const bool bAllowSleep = ThreadTaskType != ezWorkerThreadType::MainThread;
while (!condition())
{
if (!HelpExecutingTasks(ezTaskGroupID()))
{
if (bAllowSleep)
{
const ezWorkerThreadType::Enum typeToWakeUp = (ThreadTaskType == ezWorkerThreadType::Unknown) ? ezWorkerThreadType::ShortTasks : ThreadTaskType;
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Blocked) == (int)ezTaskWorkerState::Active, "Corrupt worker state");
}
WakeUpThreads(typeToWakeUp, 1);
while (!condition())
{
// TODO: busy loop for now
ezThreadUtils::YieldTimeSlice();
}
if (tl_TaskWorkerInfo.m_pWorkerState)
{
EZ_VERIFY(tl_TaskWorkerInfo.m_pWorkerState->Set((int)ezTaskWorkerState::Active) == (int)ezTaskWorkerState::Blocked, "Corrupt worker state");
}
break;
}
else
{
ezThreadUtils::YieldTimeSlice();
}
}
}
}
EZ_STATICLINK_FILE(Foundation, Foundation_Threading_Implementation_TaskSystemGroups);
| 11,216 | 3,801 |
/*
* @lc app=leetcode id=155 lang=cpp
*
* [155] Min Stack
*
* https://leetcode.com/problems/min-stack/description/
*
* algorithms
* Easy (35.38%)
* Total Accepted: 269.9K
* Total Submissions: 756.8K
* Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]'
*
*
* Design a stack that supports push, pop, top, and retrieving the minimum
* element in constant time.
*
*
* push(x) -- Push element x onto stack.
*
*
* pop() -- Removes the element on top of the stack.
*
*
* top() -- Get the top element.
*
*
* getMin() -- Retrieve the minimum element in the stack.
*
*
*
*
* Example:
*
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> Returns -3.
* minStack.pop();
* minStack.top(); --> Returns 0.
* minStack.getMin(); --> Returns -2.
*
*
*/
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (x <= min_) {
s_.push(min_);
min_ = x;
}
s_.push(x);
}
void pop() {
if (s_.top() == min_) {
s_.pop();
min_ = s_.top();
s_.pop();
}
else {
s_.pop();
}
}
int top() {
return s_.top();
}
int getMin() {
return min_;
}
private:
stack<int> s_;
int min_ = INT_MAX;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
| 1,565 | 647 |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "HierarchicalRig.h"
#include "Engine/SkeletalMesh.h"
#include "AnimationRuntime.h"
#include "AnimationCoreLibrary.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SkeletalMeshComponent.h"
#define LOCTEXT_NAMESPACE "HierarchicalRig"
UHierarchicalRig::UHierarchicalRig()
{
}
#if WITH_EDITOR
void UHierarchicalRig::SetConstraints(const TArray<FTransformConstraint>& InConstraints)
{
Constraints = InConstraints;
}
void UHierarchicalRig::BuildHierarchyFromSkeletalMesh(USkeletalMesh* SkeletalMesh)
{
const TArray<FMeshBoneInfo>& MeshBoneInfos = SkeletalMesh->RefSkeleton.GetRawRefBoneInfo();
const TArray<FTransform>& LocalTransforms = SkeletalMesh->RefSkeleton.GetRefBonePose();
check(MeshBoneInfos.Num() == LocalTransforms.Num());
// clear hierarchy - is this necessary? Maybe not, but it makes it simpler for not handling duplicated names and so on
Hierarchy.Empty();
TArray<FTransform> GlobalTransforms;
FAnimationRuntime::FillUpComponentSpaceTransforms(SkeletalMesh->RefSkeleton, LocalTransforms, GlobalTransforms);
const int32 BoneCount = MeshBoneInfos.Num();
for (int32 BoneIndex = 0; BoneIndex < BoneCount; ++BoneIndex)
{
const FMeshBoneInfo& MeshBoneInfo = MeshBoneInfos[BoneIndex];
const FTransform& LocalTransform = LocalTransforms[BoneIndex];
const FTransform& GlobalTransform = GlobalTransforms[BoneIndex];
FName ParentName;
FConstraintNodeData NodeData;
if (MeshBoneInfo.ParentIndex != INDEX_NONE)
{
ParentName = MeshBoneInfos[MeshBoneInfo.ParentIndex].Name;
const FTransform& GlobalParentTransform = GlobalTransforms[MeshBoneInfo.ParentIndex];
NodeData.RelativeParent = GlobalTransform.GetRelativeTransform(GlobalParentTransform);
}
else
{
NodeData.RelativeParent = GlobalTransform;
}
Hierarchy.Add(MeshBoneInfo.Name, ParentName, GlobalTransform, NodeData);
}
}
#endif // WITH_EDITOR
FTransform UHierarchicalRig::GetLocalTransform(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName);
}
FVector UHierarchicalRig::GetLocalLocation(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName).GetLocation();
}
FRotator UHierarchicalRig::GetLocalRotation(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName).GetRotation().Rotator();
}
FVector UHierarchicalRig::GetLocalScale(FName NodeName) const
{
return Hierarchy.GetLocalTransformByName(NodeName).GetScale3D();
}
FTransform UHierarchicalRig::GetGlobalTransform(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName);
}
FTransform UHierarchicalRig::GetMappedGlobalTransform(FName NodeName) const
{
FTransform GlobalTransform = GetGlobalTransform(NodeName);
ApplyMappingTransform(NodeName, GlobalTransform);
return GlobalTransform;
}
FTransform UHierarchicalRig::GetMappedLocalTransform(FName NodeName) const
{
// should recalculate since mapping is happening in component space
const FAnimationHierarchy& CacheHiearchy = GetHierarchy();
int32 NodeIndex = CacheHiearchy.GetNodeIndex(NodeName);
if (CacheHiearchy.IsValidIndex(NodeIndex))
{
FTransform GlobalTransform = CacheHiearchy.GetGlobalTransform(NodeIndex);
ApplyMappingTransform(NodeName, GlobalTransform);
int32 ParentIndex = CacheHiearchy.GetParentIndex(NodeIndex);
if (CacheHiearchy.IsValidIndex(ParentIndex))
{
FTransform ParentGlobalTransform = CacheHiearchy.GetGlobalTransform(ParentIndex);
ApplyMappingTransform(CacheHiearchy.GetNodeName(ParentIndex), ParentGlobalTransform);
GlobalTransform = GlobalTransform.GetRelativeTransform(ParentGlobalTransform);
}
GlobalTransform.NormalizeRotation();
return GlobalTransform;
}
return FTransform::Identity;
}
FVector UHierarchicalRig::GetGlobalLocation(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName).GetLocation();
}
FRotator UHierarchicalRig::GetGlobalRotation(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName).GetRotation().Rotator();
}
FVector UHierarchicalRig::GetGlobalScale(FName NodeName) const
{
return Hierarchy.GetGlobalTransformByName(NodeName).GetScale3D();
}
void UHierarchicalRig::SetLocalTransform(FName NodeName, const FTransform& Transform)
{
Hierarchy.SetLocalTransformByName(NodeName, Transform);
}
void UHierarchicalRig::SetGlobalTransform(FName NodeName, const FTransform& Transform)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (Hierarchy.IsValidIndex(NodeIndex))
{
const FTransform& OldTransform = Hierarchy.GetGlobalTransform(NodeIndex);
if (!OldTransform.Equals(Transform))
{
Hierarchy.SetGlobalTransform(NodeIndex, Transform);
}
// we still have to call evaluate node to update all dependency even if this node didn't change
// because constraints might have to update
EvaluateNode(NodeName);
}
}
void UHierarchicalRig::SetMappedGlobalTransform(FName NodeName, const FTransform& Transform)
{
FTransform NewTransform = Transform;
NewTransform.NormalizeRotation();
ApplyInverseMappingTransform(NodeName, NewTransform);
SetGlobalTransform(NodeName, NewTransform);
}
void UHierarchicalRig::SetMappedLocalTransform(FName NodeName, const FTransform& Transform)
{
// should recalculate since mapping is happening in component space
const FAnimationHierarchy& CacheHiearchy = GetHierarchy();
int32 NodeIndex = CacheHiearchy.GetNodeIndex(NodeName);
if (CacheHiearchy.IsValidIndex(NodeIndex))
{
FTransform GlobalTransform;
int32 ParentIndex = CacheHiearchy.GetParentIndex(NodeIndex);
if (CacheHiearchy.IsValidIndex(ParentIndex))
{
FTransform ParentGlobalTransform = CacheHiearchy.GetGlobalTransform(ParentIndex);
ApplyMappingTransform(CacheHiearchy.GetNodeName(ParentIndex), ParentGlobalTransform);
// have to apply to mapped transform
GlobalTransform = Transform * ParentGlobalTransform;
}
else
{
GlobalTransform = Transform;
}
// inverse mapping transform
ApplyInverseMappingTransform(NodeName, GlobalTransform);
SetGlobalTransform(NodeName, GlobalTransform);
}
}
void UHierarchicalRig::ApplyMappingTransform(FName NodeName, FTransform& InOutTransform) const
{
if (NodeMappingContainer)
{
const FNodeMap* NodeMapping = NodeMappingContainer->GetNodeMapping(NodeName);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform * InOutTransform;
}
else
{
// get node data
// @todo: do it here or create mapping for manually. Creating mapping will be more efficient
const int32 Index = Hierarchy.GetNodeIndex(NodeName);
if (Index != INDEX_NONE)
{
const FConstraintNodeData* UserData = static_cast<const FConstraintNodeData*> (Hierarchy.GetUserDataImpl(Index));
if (UserData->LinkedNode != NAME_None)
{
NodeMapping = NodeMappingContainer->GetNodeMapping(UserData->LinkedNode);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform * InOutTransform;
}
}
}
}
}
}
void UHierarchicalRig::ApplyInverseMappingTransform(FName NodeName, FTransform& InOutTransform) const
{
if (NodeMappingContainer)
{
const FNodeMap* NodeMapping = NodeMappingContainer->GetNodeMapping(NodeName);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform.GetRelativeTransformReverse(InOutTransform);
}
else
{
// get node data
// @todo: do it here or create mapping for manually. Creating mapping will be more efficient
const int32 Index = Hierarchy.GetNodeIndex(NodeName);
if (Index != INDEX_NONE)
{
const FConstraintNodeData* UserData = static_cast<const FConstraintNodeData*> (Hierarchy.GetUserDataImpl(Index));
if (UserData->LinkedNode != NAME_None)
{
NodeMapping = NodeMappingContainer->GetNodeMapping(UserData->LinkedNode);
if (NodeMapping)
{
InOutTransform = NodeMapping->SourceToTargetTransform.GetRelativeTransformReverse(InOutTransform);
}
}
}
}
}
}
#if WITH_EDITOR
FText UHierarchicalRig::GetCategory() const
{
return LOCTEXT("HierarchicalRigCategory", "Animation|ControlRigs");
}
FText UHierarchicalRig::GetTooltipText() const
{
return LOCTEXT("HierarchicalRigTooltip", "Handles hierarchical (node based) data, constraints etc.");
}
#endif
void UHierarchicalRig::GetTickDependencies(TArray<FTickPrerequisite, TInlineAllocator<1>>& OutTickPrerequisites)
{
if (SkeletalMeshComponent.IsValid())
{
OutTickPrerequisites.Add(FTickPrerequisite(SkeletalMeshComponent.Get(), SkeletalMeshComponent->PrimaryComponentTick));
}
}
void UHierarchicalRig::Initialize()
{
Super::Initialize();
// Initialize any manipulators we have
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator)
{
#if WITH_EDITOR
TGuardValue<bool> ScopeGuard(Manipulator->bNotifyListeners, false);
#endif
Manipulator->Initialize(this);
if (Hierarchy.Contains(Manipulator->Name))
{
if (Manipulator->bInLocalSpace)
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedLocalTransform(Manipulator->Name), this);
}
else
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedGlobalTransform(Manipulator->Name), this);
}
}
}
}
Sort();
}
AActor* UHierarchicalRig::GetHostingActor() const
{
if (SkeletalMeshComponent.Get())
{
return SkeletalMeshComponent->GetOwner();
}
return Super::GetHostingActor();
}
void UHierarchicalRig::BindToObject(UObject* InObject)
{
// If we are binding to an actor, find the first skeletal mesh component
if (AActor* Actor = Cast<AActor>(InObject))
{
if (USkeletalMeshComponent* Component = Actor->FindComponentByClass<USkeletalMeshComponent>())
{
SkeletalMeshComponent = Component;
}
}
else if (USkeletalMeshComponent* Component = Cast<USkeletalMeshComponent>(InObject))
{
SkeletalMeshComponent = Component;
}
}
void UHierarchicalRig::UnbindFromObject()
{
SkeletalMeshComponent = nullptr;
}
bool UHierarchicalRig::IsBoundToObject(UObject* InObject) const
{
if (AActor* Actor = Cast<AActor>(InObject))
{
if (USkeletalMeshComponent* Component = Actor->FindComponentByClass<USkeletalMeshComponent>())
{
return SkeletalMeshComponent.Get() == Component;
}
}
else if (USkeletalMeshComponent* Component = Cast<USkeletalMeshComponent>(InObject))
{
return SkeletalMeshComponent.Get() == Component;
}
return false;
}
UObject* UHierarchicalRig::GetBoundObject() const
{
return SkeletalMeshComponent.Get();
}
void UHierarchicalRig::PreEvaluate()
{
Super::PreEvaluate();
// @todo: sequencer will need this -
// Propagate manipulators to nodes
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator)
{
if (Manipulator->bInLocalSpace)
{
SetMappedLocalTransform(Manipulator->Name, Manipulator->GetTransform(this));
}
else
{
SetMappedGlobalTransform(Manipulator->Name, Manipulator->GetTransform(this));
}
}
}
}
void UHierarchicalRig::Evaluate()
{
Super::Evaluate();
}
// we don't really have to update nodes as they're updated by manipulator anyway if input
// but I'm leaving here as a function just in case in the future this came up again
void UHierarchicalRig::UpdateNodes()
{
// Calculate each node
for (const FName& NodeName : SortedNodes)
{
const FTransform& GlobalTransfrom = GetGlobalTransform(NodeName);
SetGlobalTransform(NodeName, GlobalTransfrom);
}
}
void UHierarchicalRig::PostEvaluate()
{
Super::PostEvaluate();
UpdateManipulatorToNode(false);
}
void UHierarchicalRig::UpdateManipulatorToNode(bool bNotifyListeners)
{
// Propagate back to manipulators after evaluation
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator)
{
#if WITH_EDITOR
TGuardValue<bool> ScopeGuard(Manipulator->bNotifyListeners, bNotifyListeners);
#endif
if (Manipulator->bInLocalSpace)
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedLocalTransform(Manipulator->Name), this);
}
else
{
// do not add node in initialize, that is only for editor purpose and to serialize
Manipulator->SetTransform(GetMappedGlobalTransform(Manipulator->Name), this);
}
}
}
}
#if WITH_EDITOR
void UHierarchicalRig::AddNode(FName NodeName, FName ParentName, const FTransform& GlobalTransform, FName LinkedNode /*= NAME_None*/)
{
FConstraintNodeData NewNodeData;
NewNodeData.LinkedNode = LinkedNode;
if (ParentName != NAME_None)
{
FTransform ParentTransform = Hierarchy.GetGlobalTransformByName(ParentName);
NewNodeData.RelativeParent = GlobalTransform.GetRelativeTransform(ParentTransform);
}
else
{
NewNodeData.RelativeParent = GlobalTransform;
}
Hierarchy.Add(NodeName, ParentName, GlobalTransform, NewNodeData);
}
void UHierarchicalRig::SetParent(FName NodeName, FName NewParentName)
{
if (Hierarchy.Contains(NodeName) && (NewParentName == NAME_None || Hierarchy.Contains(NewParentName)))
{
const int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
check(NodeIndex != INDEX_NONE);
const FTransform NodeTransform = Hierarchy.GetGlobalTransform(NodeIndex);
Hierarchy.SetParentName(NodeIndex, NewParentName);
FConstraintNodeData& MyNodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
if (NewParentName != NAME_None)
{
FTransform ParentTransform = Hierarchy.GetGlobalTransformByName(NewParentName);
MyNodeData.RelativeParent = NodeTransform.GetRelativeTransform(ParentTransform);
}
else
{
MyNodeData.RelativeParent = NodeTransform;
}
}
}
void UHierarchicalRig::DeleteConstraint(FName NodeName, FName TargetNode)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (Hierarchy.IsValidIndex(NodeIndex))
{
FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
NodeData.DeleteConstraint(TargetNode);
}
}
void UHierarchicalRig::DeleteNode(FName NodeName)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (Hierarchy.IsValidIndex(NodeIndex))
{
TArray<FName> Children = Hierarchy.GetChildren(NodeIndex);
FName ParentName = Hierarchy.GetParentName(NodeIndex);
int32 ParentIndex = Hierarchy.GetNodeIndex(ParentName);
FTransform ParentTransform = (ParentIndex != INDEX_NONE)? Hierarchy.GetGlobalTransform(ParentIndex) : FTransform::Identity;
// now reparent the children
for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex)
{
int32 ChildNodeIndex = Hierarchy.GetNodeIndex(Children[ChildIndex]);
Hierarchy.SetParentName(ChildNodeIndex, ParentName);
// when delete, we have to re-adjust relative transform
FTransform ChildTransform = Hierarchy.GetGlobalTransform(ChildNodeIndex);
FConstraintNodeData& ChildNodeData = Hierarchy.GetNodeData<FConstraintNodeData>(ChildNodeIndex);
ChildNodeData.RelativeParent = ChildTransform.GetRelativeTransform(ParentTransform);
}
Hierarchy.Remove(NodeName);
}
}
FNodeChain UHierarchicalRig::MakeNodeChain(FName RootNode, FName EndNode)
{
FNodeChain NodeChain;
// walk up hierarchy towards root from end to start
FName BoneName = EndNode;
while (BoneName != RootNode)
{
// we hit the root, so clear the bone chain - we have an invalid chain
if (BoneName == NAME_None)
{
NodeChain.Nodes.Reset();
break;
}
NodeChain.Nodes.EmplaceAt(0, BoneName);
int32 NodeIndex = Hierarchy.GetNodeIndex(BoneName);
if (NodeIndex == INDEX_NONE)
{
NodeChain.Nodes.Reset();
break;
}
BoneName = Hierarchy.GetParentName(NodeIndex);
}
return NodeChain;
}
UControlManipulator* UHierarchicalRig::AddManipulator(TSubclassOf<UControlManipulator> ManipulatorClass, FText DisplayName, FName NodeName, FName PropertyToManipulate, EIKSpaceMode KinematicSpace, bool bUsesTranslation, bool bUsesRotation, bool bUsesScale, bool bInLocalSpace)
{
// make sure manipulator doesn't exists already
for (int32 ManipulatorIndex = 0; ManipulatorIndex < Manipulators.Num(); ++ManipulatorIndex)
{
if (UControlManipulator* Manipulator = Manipulators[ManipulatorIndex])
{
if (Manipulator->Name == NodeName)
{
// same name exists, failed, return
return Manipulator;
}
}
}
UControlManipulator* NewManipulator = NewObject<UControlManipulator>(this, ManipulatorClass.Get(), NAME_None, RF_Public | RF_Transactional | RF_ArchetypeObject);
NewManipulator->DisplayName = DisplayName;
NewManipulator->Name = NodeName;
NewManipulator->PropertyToManipulate = PropertyToManipulate;
NewManipulator->KinematicSpace = KinematicSpace;
NewManipulator->bUsesTranslation = bUsesTranslation;
NewManipulator->bUsesRotation = bUsesRotation;
NewManipulator->bUsesScale = bUsesScale;
NewManipulator->bInLocalSpace = bInLocalSpace;
Manipulators.Add(NewManipulator);
return NewManipulator;
}
void UHierarchicalRig::UpdateConstraints()
{
if (Constraints.Num() > 0)
{
for (const FTransformConstraint& Constraint : Constraints)
{
AddConstraint(Constraint);
}
}
}
#endif // WITH_EDITOR
void UHierarchicalRig::AddConstraint(const FTransformConstraint& TransformConstraint)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(TransformConstraint.SourceNode);
int32 ConstraintNodeIndex = Hierarchy.GetNodeIndex(TransformConstraint.TargetNode);
if (NodeIndex != INDEX_NONE && ConstraintNodeIndex != INDEX_NONE)
{
FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
NodeData.AddConstraint(TransformConstraint);
// recalculate main offset for all constraint
if (TransformConstraint.bMaintainOffset)
{
int32 ParentIndex = Hierarchy.GetParentIndex(NodeIndex);
FTransform ParentTransform = (ParentIndex != INDEX_NONE) ? Hierarchy.GetGlobalTransform(ParentIndex) : FTransform::Identity;
FTransform LocalTransform = Hierarchy.GetLocalTransform(NodeIndex);
FTransform TargetTransform = ResolveConstraints(LocalTransform, ParentTransform, NodeData);
NodeData.ConstraintOffset.SaveInverseOffset(LocalTransform, TargetTransform, TransformConstraint.Operator);
}
else
{
NodeData.ConstraintOffset.Reset();
}
}
}
static int32& EnsureNodeExists(TMap<FName, int32>& InGraph, FName Name)
{
int32* Value = InGraph.Find(Name);
if (!Value)
{
Value = &InGraph.Add(Name);
*Value = 0;
}
return *Value;
}
static void IncreaseEdgeCount(TMap<FName, int32>& InGraph, FName Name)
{
int32& EdgeCount = EnsureNodeExists(InGraph, Name);
++EdgeCount;
}
void UHierarchicalRig::AddDependenciesRecursive(int32 OriginalNodeIndex, int32 NodeIndex)
{
const FName& NodeName = Hierarchy.GetNodeName(NodeIndex);
TArray<FName> Neighbors;
GetDependentArray(NodeName, Neighbors);
for (const FName& Neighbor : Neighbors)
{
int32 NeighborNodeIndex = Hierarchy.GetNodeIndex(Neighbor);
if (NeighborNodeIndex != INDEX_NONE)
{
TArray<int32>& NodeDependencies = DependencyGraph[NeighborNodeIndex];
NodeDependencies.AddUnique(OriginalNodeIndex);
AddDependenciesRecursive(OriginalNodeIndex, NeighborNodeIndex);
}
}
}
void UHierarchicalRig::CreateSortedNodes()
{
// Comparison Operator for Sorting.
struct FSortDependencyGraph
{
private:
TArray<int32>* SortedNodeIndices;
public:
FSortDependencyGraph(TArray<int32>* InSortedNodeIndices)
: SortedNodeIndices(InSortedNodeIndices)
{
}
FORCEINLINE bool operator()(const int32& A, const int32& B) const
{
return SortedNodeIndices->Find(A) > SortedNodeIndices->Find(B);
}
};
SortedNodes.Reset();
// name to incoming edge
TMap<FName, int32> Graph;
// calculate incoming edges
for (int32 NodeIndex = 0; NodeIndex < Hierarchy.GetNum(); ++NodeIndex)
{
const FName& NodeName = Hierarchy.GetNodeName(NodeIndex);
EnsureNodeExists(Graph, NodeName);
TArray<FName> Neighbors;
GetDependentArray(NodeName, Neighbors);
// @todo: can include itself?
for (int32 NeighborsIndex = 0; NeighborsIndex < Neighbors.Num(); ++NeighborsIndex)
{
IncreaseEdgeCount(Graph, Neighbors[NeighborsIndex]);
}
}
// do run Kahn
TArray<FName> SortingQueue;
TArray<int32> SortedNodeIndices;
// first remove 0 in-degree vertices
for (const TPair<FName, int32>& GraphPair : Graph)
{
if (GraphPair.Value == 0)
{
SortingQueue.Add(GraphPair.Key);
}
}
// if sorting queue is same as node count, that means nothing is dependent
if (SortingQueue.Num() == Hierarchy.GetNum())
{
SortedNodes = SortingQueue;
}
else
{
while (SortingQueue.Num() != 0)
{
FName Name = SortingQueue[0];
// move the element
SortingQueue.Remove(Name);
SortedNodes.Add(Name);
SortedNodeIndices.Add(Hierarchy.GetNodeIndex(Name));
TArray<FName> Neighbors;
GetDependentArray(Name, Neighbors);
for (int32 NeighborsIndex = 0; NeighborsIndex < Neighbors.Num(); ++NeighborsIndex)
{
int32* EdgeCount = Graph.Find(Neighbors[NeighborsIndex]);
--(*EdgeCount);
if (*EdgeCount == 0)
{
SortingQueue.Add(Neighbors[NeighborsIndex]);
}
}
}
DependencyGraph.Reset();
if (SortedNodes.Num() == Hierarchy.GetNum())
{
// If the sorted node count is different to the hierarchy we have a cycle, so we dont regenerate the graph in that case
// Now generate a path through the DAG for each node to evaluate
DependencyGraph.SetNum(Hierarchy.GetNum());
for (int32 NodeIndex = 0; NodeIndex < Hierarchy.GetNum(); ++NodeIndex)
{
AddDependenciesRecursive(NodeIndex, NodeIndex);
}
// after this, we should sort using SortedNodes.
for (int32 NodeIndex = 0; NodeIndex < Hierarchy.GetNum(); ++NodeIndex)
{
DependencyGraph[NodeIndex].Sort(FSortDependencyGraph(&SortedNodeIndices));
}
}
}
}
void UHierarchicalRig::ApplyConstraint(const FName& NodeName)
{
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (NodeIndex != INDEX_NONE)
{
FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
if (NodeData.DoesHaveConstraint())
{
FTransform LocalTransform = Hierarchy.GetLocalTransform(NodeIndex);
int32 ParentIndex = Hierarchy.GetParentIndex(NodeIndex);
FTransform ParentTransform = (ParentIndex != INDEX_NONE)? Hierarchy.GetGlobalTransform(ParentIndex) : FTransform::Identity;
FTransform ConstraintTransform = ResolveConstraints(LocalTransform, ParentTransform, NodeData);
NodeData.ConstraintOffset.ApplyInverseOffset(ConstraintTransform, LocalTransform);
Hierarchy.SetGlobalTransform(NodeIndex, LocalTransform * ParentTransform);
}
}
}
void UHierarchicalRig::EvaluateNode(const FName& NodeName)
{
// constraints have to update when current transform changes - I think that should happen before here
ApplyConstraint(NodeName);
int32 NodeIndex = Hierarchy.GetNodeIndex(NodeName);
if (NodeIndex != INDEX_NONE && NodeIndex < DependencyGraph.Num())
{
for(int32 ChildNodeIndex : DependencyGraph[NodeIndex])
{
FName ChildNodeName = Hierarchy.GetNodeName(ChildNodeIndex);
int32 ParentIndex = Hierarchy.GetParentIndex(ChildNodeIndex);
if (ParentIndex != INDEX_NONE)
{
FTransform ParentTransform = Hierarchy.GetGlobalTransform(ParentIndex);
// Note we don't call SetGlobalTransform here as the local transform has not changed,
// so we dont want to introduce error
Hierarchy.GetTransforms()[ChildNodeIndex] = Hierarchy.GetLocalTransform(ChildNodeIndex) * ParentTransform;
}
ApplyConstraint(ChildNodeName);
}
}
}
void UHierarchicalRig::GetDependentArray(const FName& Name, TArray<FName>& OutList) const
{
int32 NodeIndex = Hierarchy.GetNodeIndex(Name);
OutList.Reset();
if (NodeIndex != INDEX_NONE)
{
FName ParentName = Hierarchy.GetParentName(NodeIndex);
if (ParentName != NAME_None)
{
OutList.AddUnique(ParentName);
}
const FConstraintNodeData& NodeData = Hierarchy.GetNodeData<FConstraintNodeData>(NodeIndex);
const TArray<FTransformConstraint>& NodeConstraints = NodeData.GetConstraints();
for (int32 ConstraintsIndex = 0; ConstraintsIndex < NodeConstraints.Num(); ++ConstraintsIndex)
{
if (NodeConstraints[ConstraintsIndex].TargetNode != NAME_None)
{
OutList.AddUnique(NodeConstraints[ConstraintsIndex].TargetNode);
}
}
}
}
FTransform UHierarchicalRig::ResolveConstraints(const FTransform& LocalTransform, const FTransform& ParentTransform, const FConstraintNodeData& NodeData)
{
FTransform CurrentLocalTransform = LocalTransform;
FGetGlobalTransform OnGetGlobalTransform;
OnGetGlobalTransform.BindUObject(this, &UHierarchicalRig::GetGlobalTransform);
return AnimationCore::SolveConstraints(CurrentLocalTransform, ParentTransform, NodeData.GetConstraints(), OnGetGlobalTransform);
}
void UHierarchicalRig::Sort()
{
CreateSortedNodes();
}
UControlManipulator* UHierarchicalRig::FindManipulator(const FName& Name)
{
for (UControlManipulator* Manipulator : Manipulators)
{
if (Manipulator && Manipulator->Name == Name)
{
return Manipulator;
}
}
return nullptr;
}
void UHierarchicalRig::GetMappableNodeData(TArray<FName>& OutNames, TArray<FTransform>& OutTransforms) const
{
OutNames.Reset();
OutTransforms.Reset();
// now add all nodes
TArray<FNodeObject> Nodes = Hierarchy.GetNodes();
const TArray<FTransform>& Transforms = Hierarchy.GetTransforms();
for (int32 Index = 0; Index < Nodes.Num(); ++Index)
{
const FConstraintNodeData* UserData = static_cast<const FConstraintNodeData*> (Hierarchy.GetUserDataImpl(Index));
// if no node is linked, we only allow them to map, so add them
if (UserData->LinkedNode == NAME_None)
{
OutNames.Add(Nodes[Index].Name);
OutTransforms.Add(Transforms[Index]);
}
}
}
bool UHierarchicalRig::RenameNode(const FName& CurrentNodeName, const FName& NewNodeName)
{
if (Hierarchy.Contains(NewNodeName))
{
// the name is already used
return false;
}
if (Hierarchy.Contains(CurrentNodeName))
{
const int32 NodeIndex = Hierarchy.GetNodeIndex(CurrentNodeName);
Hierarchy.SetNodeName(NodeIndex, NewNodeName);
// now updates Constraints as well as data Constraints
for (int32 Index = 0; Index < Hierarchy.UserData.Num(); ++Index)
{
FConstraintNodeData& ConstraintNodeData = Hierarchy.UserData[Index];
if (ConstraintNodeData.LinkedNode == CurrentNodeName)
{
ConstraintNodeData.LinkedNode = NewNodeName;
}
FTransformConstraint* Constraint = ConstraintNodeData.FindConstraint(CurrentNodeName);
if (Constraint)
{
Constraint->TargetNode = NewNodeName;
}
}
for (int32 Index = 0; Index < Constraints.Num(); ++Index)
{
FTransformConstraint& Constraint = Constraints[Index];
if (Constraint.SourceNode == CurrentNodeName)
{
Constraint.SourceNode = NewNodeName;
}
if (Constraint.TargetNode == CurrentNodeName)
{
Constraint.TargetNode = NewNodeName;
}
}
for (int32 Index = 0; Index < Manipulators.Num(); ++Index)
{
UControlManipulator* Manipulator = Manipulators[Index];
if (Manipulator)
{
if (Manipulator->Name == CurrentNodeName)
{
Manipulator->Name = NewNodeName;
}
}
}
return true;
}
return false;
}
void UHierarchicalRig::Setup()
{
//Initialize();
}
#undef LOCTEXT_NAMESPACE | 27,066 | 9,609 |
#include <iostream>
#include <cassert>
#include <cmath>
#include <cfloat>
#include "vapor/LayeredGrid.h"
using namespace std;
using namespace VAPoR;
LayeredGrid::LayeredGrid(
const size_t bs[3],
const size_t min[3],
const size_t max[3],
const double extents[6],
const bool periodic[3],
float ** blks,
float ** coords,
int varying_dim
) : RegularGrid(bs,min,max,extents,periodic,blks) {
//
// Shallow copy blocks
//
size_t nblocks = RegularGrid::GetNumBlks();
_coords = new float*[nblocks];
for (int i=0; i<nblocks; i++) {
_coords[i] = coords[i];
}
_varying_dim = varying_dim;
if (_varying_dim < 0 || _varying_dim > 2) _varying_dim = 2;
//
// Periodic, varying dimensions are not supported
//
if (periodic[_varying_dim]) SetPeriodic(periodic);
_GetUserExtents(_extents);
RegularGrid::_SetExtents(_extents);
}
LayeredGrid::LayeredGrid(
const size_t bs[3],
const size_t min[3],
const size_t max[3],
const double extents[6],
const bool periodic[3],
float ** blks,
float ** coords,
int varying_dim,
float missing_value
) : RegularGrid(bs,min,max,extents,periodic,blks, missing_value) {
//
// Shallow copy blocks
//
size_t nblocks = RegularGrid::GetNumBlks();
_coords = new float*[nblocks];
for (int i=0; i<nblocks; i++) {
_coords[i] = coords[i];
}
_varying_dim = varying_dim;
if (_varying_dim < 0 || _varying_dim > 2) _varying_dim = 2;
assert(periodic[_varying_dim] == false);
_GetUserExtents(_extents);
RegularGrid::_SetExtents(_extents);
}
LayeredGrid::~LayeredGrid() {
if (_coords) delete [] _coords;
}
void LayeredGrid::GetBoundingBox(
const size_t min[3],
const size_t max[3],
double extents[6]
) const {
size_t mymin[] = {min[0],min[1],min[2]};
size_t mymax[] = {max[0],max[1],max[2]};
//
// Don't stop until we find valid extents. When missing values
// are present it's possible that the missing value dimension has
// an entire plane of missing values
//
bool done = false;
while (! done) {
done = true;
_GetBoundingBox(mymin, mymax, extents);
if (_varying_dim == 0) {
if (extents[0] == FLT_MAX && mymin[0]<mymax[0]) {
mymin[0] = mymin[0]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[0]>mymin[0]) {
mymax[0] = mymax[0]-1;
done = false;
}
}
else if (_varying_dim == 1) {
if (extents[1] == FLT_MAX && mymin[1]<mymax[1]) {
mymin[1] = mymin[1]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[1]>mymin[1]) {
mymax[1] = mymax[1]-1;
done = false;
}
}
else if (_varying_dim == 2) {
if (extents[2] == FLT_MAX && mymin[2]<mymax[2]) {
mymin[2] = mymin[2]+1;
done = false;
}
if (extents[5] == -FLT_MAX && mymax[2]>mymin[2]) {
mymax[2] = mymax[2]-1;
done = false;
}
}
}
}
void LayeredGrid::_GetBoundingBox(
const size_t min[3],
const size_t max[3],
double extents[6]
) const {
// Get extents of non-varying dimension. Values returned for
// varying dimension are coordinates for first and last grid
// point, respectively, which in general are not the extents
// of the bounding box.
//
RegularGrid::GetUserCoordinates(
min[0], min[1], min[2], &(extents[0]), &(extents[1]), &(extents[2])
);
RegularGrid::GetUserCoordinates(
max[0], max[1], max[2], &(extents[3]), &(extents[4]), &(extents[5])
);
// Initialize min and max coordinates of varying dimension with
// coordinates of "first" and "last" grid point. Coordinates of
// varying dimension are stored as values of a scalar function
// sampling the coordinate space.
//
float mincoord = FLT_MAX;
float maxcoord = -FLT_MAX;
float mv = GetMissingValue();
assert(_varying_dim >= 0 && _varying_dim <= 2);
bool flip = (
_AccessIJK(_coords, 0, 0, min[_varying_dim]) >
_AccessIJK(_coords, 0, 0, max[_varying_dim])
);
// Now find the extreme values of the varying dimension's coordinates
//
if (_varying_dim == 0) { // I plane
// Find min coordinate in first plane
//
for (int k = min[2]; k<=max[2]; k++) {
for (int j = min[1]; j<=max[1]; j++) {
float v = _AccessIJK(_coords, min[0],j,k);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
// Find max coordinate in last plane
//
for (int k = min[2]; k<=max[2]; k++) {
for (int j = min[1]; j<=max[1]; j++) {
float v = _AccessIJK(_coords, max[0],j,k);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
else if (_varying_dim == 1) { // J plane
for (int k = min[2]; k<=max[2]; k++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,min[1],k);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
for (int k = min[2]; k<=max[2]; k++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,max[1],k);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
else { // _varying_dim == 2 (K plane)
for (int j = min[1]; j<=max[1]; j++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,j,min[2]);
if (v == mv) continue;
if (! flip) {
if (v<mincoord) mincoord = v;
} else {
if (v>mincoord) mincoord = v;
}
}
}
for (int j = min[1]; j<=max[1]; j++) {
for (int i = min[0]; i<=max[0]; i++) {
float v = _AccessIJK(_coords, i,j,max[2]);
if (v == mv) continue;
if (! flip) {
if (v>maxcoord) maxcoord = v;
} else {
if (v<maxcoord) maxcoord = v;
}
}
}
}
extents[_varying_dim] = mincoord;
extents[_varying_dim+3] = maxcoord;
}
void LayeredGrid::GetEnclosingRegion(
const double minu[3], const double maxu[3],
size_t min[3], size_t max[3]
) const {
assert (_varying_dim == 2); // Only z varying dim currently supported
//
// Get coords for non-varying dimension
//
RegularGrid::GetEnclosingRegion(minu, maxu, min, max);
// we have the correct results
// for X and Y dimensions, but the Z levels may not be completely
// contained in the box. We need to verify and possibly expand
// the min and max Z values.
//
size_t dims[3];
GetDimensions(dims);
bool done;
double z;
if (maxu[2] >= minu[2]) {
//
// first do max, then min
//
done = false;
for (int k=0; k<dims[2] && ! done; k++) {
done = true;
max[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z < maxu[2]) {
done = false;
}
}
}
}
done = false;
for (int k = dims[2]-1; k>=0 && ! done; k--) {
done = true;
min[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z > minu[2]) {
done = false;
}
}
}
}
}
else {
//
// first do max, then min
//
done = false;
for (int k=0; k<dims[2] && ! done; k++) {
done = true;
max[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z > maxu[2]) {
done = false;
}
}
}
}
done = false;
for (int k = dims[2]-1; k>=0 && ! done; k--) {
done = true;
min[2] = k;
for (int j = min[1]; j<=max[1] && done; j++) {
for (int i = min[0]; i<=max[0] && done; i++) {
z = _AccessIJK(_coords, i, j, k); // get Z coordinate
if (z < maxu[2]) {
done = false;
}
}
}
}
}
}
float LayeredGrid::GetValue(double x, double y, double z) const {
_ClampCoord(x,y,z);
if (! InsideGrid(x,y,z)) return(GetMissingValue());
size_t dims[3];
GetDimensions(dims);
// Get the indecies of the cell containing the point
//
size_t i0, j0, k0;
size_t i1, j1, k1;
GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// Get user coordinates of cell containing point
//
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
//
// Calculate interpolation weights. We always interpolate along
// the varying dimension last (the kwgt)
//
double iwgt, jwgt, kwgt;
if (_varying_dim == 0) {
// We have to interpolate coordinate of varying dimension
//
x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
x1 = _interpolateVaryingCoord(i1,j0,k0,x,y,z);
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
if (x1!=x0) kwgt = fabs((x-x0) / (x1-x0));
else kwgt = 0.0;
}
else if (_varying_dim == 1) {
y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
y1 = _interpolateVaryingCoord(i0,j1,k0,x,y,z);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
if (y1!=y0) kwgt = fabs((y-y0) / (y1-y0));
else kwgt = 0.0;
}
else {
z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
z1 = _interpolateVaryingCoord(i0,j0,k1,x,y,z);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
if (z1!=z0) kwgt = fabs((z-z0) / (z1-z0));
else kwgt = 0.0;
}
if (GetInterpolationOrder() == 0) {
if (iwgt>0.5) i0++;
if (jwgt>0.5) j0++;
if (kwgt>0.5) k0++;
return(AccessIJK(i0,j0,k0));
}
//
// perform tri-linear interpolation
//
double p0,p1,p2,p3,p4,p5,p6,p7;
p0 = AccessIJK(i0,j0,k0);
if (p0 == GetMissingValue()) return (GetMissingValue());
if (iwgt!=0.0) {
p1 = AccessIJK(i1,j0,k0);
if (p1 == GetMissingValue()) return (GetMissingValue());
}
else p1 = 0.0;
if (jwgt!=0.0) {
p2 = AccessIJK(i0,j1,k0);
if (p2 == GetMissingValue()) return (GetMissingValue());
}
else p2 = 0.0;
if (iwgt!=0.0 && jwgt!=0.0) {
p3 = AccessIJK(i1,j1,k0);
if (p3 == GetMissingValue()) return (GetMissingValue());
}
else p3 = 0.0;
if (kwgt!=0.0) {
p4 = AccessIJK(i0,j0,k1);
if (p4 == GetMissingValue()) return (GetMissingValue());
}
else p4 = 0.0;
if (kwgt!=0.0 && iwgt!=0.0) {
p5 = AccessIJK(i1,j0,k1);
if (p5 == GetMissingValue()) return (GetMissingValue());
}
else p5 = 0.0;
if (kwgt!=0.0 && jwgt!=0.0) {
p6 = AccessIJK(i0,j1,k1);
if (p6 == GetMissingValue()) return (GetMissingValue());
}
else p6 = 0.0;
if (kwgt!=0.0 && iwgt!=0.0 && jwgt!=0.0) {
p7 = AccessIJK(i1,j1,k1);
if (p7 == GetMissingValue()) return (GetMissingValue());
}
else p7 = 0.0;
double c0 = p0+iwgt*(p1-p0) + jwgt*((p2+iwgt*(p3-p2))-(p0+iwgt*(p1-p0)));
double c1 = p4+iwgt*(p5-p4) + jwgt*((p6+iwgt*(p7-p6))-(p4+iwgt*(p5-p4)));
return(c0+kwgt*(c1-c0));
}
void LayeredGrid::_GetUserExtents(double extents[6]) const {
size_t dims[3];
GetDimensions(dims);
size_t min[3] = {0,0,0};
size_t max[3] = {dims[0]-1, dims[1]-1, dims[2]-1};
LayeredGrid::GetBoundingBox(min, max, extents);
}
int LayeredGrid::GetUserCoordinates(
size_t i, size_t j, size_t k,
double *x, double *y, double *z
) const {
// First get coordinates of non-varying dimensions
// The varying dimension coordinate returned is ignored
//
int rc = RegularGrid::GetUserCoordinates(i,j,k,x,y,z);
if (rc<0) return(rc);
// Now get coordinates of varying dimension
//
if (_varying_dim == 0) {
*x = _GetVaryingCoord(i,j,k);
}
else if (_varying_dim == 1) {
*y = _GetVaryingCoord(i,j,k);
}
else {
*z = _GetVaryingCoord(i,j,k);
}
return(0);
}
void LayeredGrid::GetIJKIndex(
double x, double y, double z,
size_t *i, size_t *j, size_t *k
) const {
// First get ijk index of non-varying dimensions
// N.B. index returned for varying dimension is bogus
//
RegularGrid::GetIJKIndex(x,y,z, i,j,k);
size_t dims[3];
GetDimensions(dims);
// At this point the ijk indecies are correct for the non-varying
// dimensions. We only need to find the index for the varying dimension
//
if (_varying_dim == 0) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (i0 == dims[0]-1) { // on boundary
*i = i0;
return;
}
double x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double x1 = _interpolateVaryingCoord(i0+1,j0,k0,x,y,z);
if (fabs(x-x0) < fabs(x-x1)) {
*i = i0;
}
else {
*i = i0+1;
}
}
else if (_varying_dim == 1) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (j0 == dims[1]-1) { // on boundary
*j = j0;
return;
}
double y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double y1 = _interpolateVaryingCoord(i0,j0+1,k0,x,y,z);
if (fabs(y-y0) < fabs(y-y1)) {
*j = j0;
}
else {
*j = j0+1;
}
}
else if (_varying_dim == 2) {
size_t i0, j0, k0;
LayeredGrid::GetIJKIndexFloor(x,y,z,&i0, &j0, &k0);
if (k0 == dims[2]-1) { // on boundary
*k = k0;
return;
}
double z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double z1 = _interpolateVaryingCoord(i0,j0,k0+1,x,y,z);
if (fabs(z-z0) < fabs(z-z1)) {
*k = k0;
}
else {
*k = k0+1;
}
}
}
void LayeredGrid::GetIJKIndexFloor(
double x, double y, double z,
size_t *i, size_t *j, size_t *k
) const {
// First get ijk index of non-varying dimensions
// N.B. index returned for varying dimension is bogus
//
size_t i0, j0, k0;
RegularGrid::GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
size_t dims[3];
GetDimensions(dims);
size_t i1, j1, k1;
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// At this point the ijk indecies are correct for the non-varying
// dimensions. We only need to find the index for the varying dimension
//
if (_varying_dim == 0) {
*j = j0; *k = k0;
i0 = 0;
i1 = dims[0]-1;
double x0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double x1 = _interpolateVaryingCoord(i1,j0,k0,x,y,z);
// see if point is outside grid or on boundary
//
if ((x-x0) * (x-x1) >= 0.0) {
if (x0<=x1) {
if (x<=x0) *i = 0;
else if (x>=x1) *i = dims[0]-1;
}
else {
if (x>=x0) *i = 0;
else if (x<=x1) *i = dims[0]-1;
}
return;
}
//
// X-coord of point must be between x0 and x1
//
while (i1-i0 > 1) {
x1 = _interpolateVaryingCoord((i0+i1)>>1,j0,k0,x,y,z);
if (x1 == x) { // pathological case
//*i = (i0+i1)>>1;
i0 = (i0+i1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between x0 and x1
//
if ((x-x0) * (x-x1) <= 0.0) {
i1 = (i0+i1)>>1;
}
else {
i0 = (i0+i1)>>1;
x0 = x1;
}
}
*i = i0;
}
else if (_varying_dim == 1) {
*i = i0; *k = k0;
// Now search for the closest point
//
j0 = 0;
j1 = dims[1]-1;
double y0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double y1 = _interpolateVaryingCoord(i0,j1,k0,x,y,z);
// see if point is outside grid or on boundary
//
if ((y-y0) * (y-y1) >= 0.0) {
if (y0<=y1) {
if (y<=y0) *j = 0;
else if (y>=y1) *j = dims[1]-1;
}
else {
if (y>=y0) *j = 0;
else if (y<=y1) *j = dims[1]-1;
}
return;
}
//
// Y-coord of point must be between y0 and y1
//
while (j1-j0 > 1) {
y1 = _interpolateVaryingCoord(i0,(j0+j1)>>1,k0,x,y,z);
if (y1 == y) { // pathological case
//*j = (j0+j1)>>1;
j0 = (j0+j1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between y0 and y1
//
if ((y-y0) * (y-y1) <= 0.0) {
j1 = (j0+j1)>>1;
}
else {
j0 = (j0+j1)>>1;
y0 = y1;
}
}
*j = j0;
}
else { // _varying_dim == 2
*i = i0; *j = j0;
// Now search for the closest point
//
k0 = 0;
k1 = dims[2]-1;
double z0 = _interpolateVaryingCoord(i0,j0,k0,x,y,z);
double z1 = _interpolateVaryingCoord(i0,j0,k1,x,y,z);
// see if point is outside grid or on boundary
//
if ((z-z0) * (z-z1) >= 0.0) {
if (z0<=z1) {
if (z<=z0) *k = 0;
else if (z>=z1) *k = dims[2]-1;
}
else {
if (z>=z0) *k = 0;
else if (z<=z1) *k = dims[2]-1;
}
return;
}
//
// Z-coord of point must be between z0 and z1
//
while (k1-k0 > 1) {
z1 = _interpolateVaryingCoord(i0,j0,(k0+k1)>>1,x,y,z);
if (z1 == z) { // pathological case
//*k = (k0+k1)>>1;
k0 = (k0+k1)>>1;
break;
}
// if the signs of differences change then the coordinate
// is between z0 and z1
//
if ((z-z0) * (z-z1) <= 0.0) {
k1 = (k0+k1)>>1;
}
else {
k0 = (k0+k1)>>1;
z0 = z1;
}
}
*k = k0;
}
}
int LayeredGrid::Reshape(
const size_t min[3],
const size_t max[3],
const bool periodic[3]
) {
int rc = RegularGrid::Reshape(min,max,periodic);
if (rc<0) return(-1);
_GetUserExtents(_extents);
return(0);
}
void LayeredGrid::SetPeriodic(const bool periodic[3]) {
bool pvec[3];
for (int i=0; i<3; i++) pvec[i] = periodic[i];
pvec[_varying_dim] = false;
RegularGrid::SetPeriodic(pvec);
}
bool LayeredGrid::InsideGrid(double x, double y, double z) const {
// Clamp coordinates on periodic boundaries to reside within the
// grid extents (vary-dimensions can not have periodic boundaries)
//
_ClampCoord(x,y,z);
// Do a quick check to see if the point is completely outside of
// the grid bounds.
//
double extents[6];
GetUserExtents(extents);
if (extents[0] < extents[3]) {
if (x<extents[0] || x>extents[3]) return (false);
}
else {
if (x>extents[0] || x<extents[3]) return (false);
}
if (extents[1] < extents[4]) {
if (y<extents[1] || y>extents[4]) return (false);
}
else {
if (y>extents[1] || y<extents[4]) return (false);
}
if (extents[2] < extents[5]) {
if (z<extents[2] || z>extents[5]) return (false);
}
else {
if (z>extents[2] || z<extents[5]) return (false);
}
// If we get to here the point's non-varying dimension coordinates
// must be inside the grid. It is only the varying dimension
// coordinates that we need to check
//
// Get the indecies of the cell containing the point
// Only the indecies for the non-varying dimensions are correctly
// returned by GetIJKIndexFloor()
//
size_t dims[3];
GetDimensions(dims);
size_t i0, j0, k0;
size_t i1, j1, k1;
RegularGrid::GetIJKIndexFloor(x,y,z, &i0,&j0,&k0);
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
//
// See if the varying dimension coordinate of the point is
// completely above or below all of the corner points in the first (last)
// cell in the column of cells containing the point
//
double t00, t01, t10, t11; // varying dimension coord of "top" cell
double b00, b01, b10, b11; // varying dimension coord of "bottom" cell
double vc; // varying coordinate value
if (_varying_dim == 0) {
t00 = _GetVaryingCoord( dims[0]-1, j0, k0);
t01 = _GetVaryingCoord( dims[0]-1, j1, k0);
t10 = _GetVaryingCoord( dims[0]-1, j0, k1);
t11 = _GetVaryingCoord( dims[0]-1, j1, k1);
b00 = _GetVaryingCoord( 0, j0, k0);
b01 = _GetVaryingCoord( 0, j1, k0);
b10 = _GetVaryingCoord( 0, j0, k1);
b11 = _GetVaryingCoord( 0, j1, k1);
vc = x;
}
else if (_varying_dim == 1) {
t00 = _GetVaryingCoord( i0, dims[1]-1, k0);
t01 = _GetVaryingCoord( i1, dims[1]-1, k0);
t10 = _GetVaryingCoord( i0, dims[1]-1, k1);
t11 = _GetVaryingCoord( i1, dims[1]-1, k1);
b00 = _GetVaryingCoord( i0, 0, k0);
b01 = _GetVaryingCoord( i1, 0, k0);
b10 = _GetVaryingCoord( i0, 0, k1);
b11 = _GetVaryingCoord( i1, 0, k1);
vc = y;
}
else { // _varying_dim == 2
t00 = _GetVaryingCoord( i0, j0, dims[2]-1);
t01 = _GetVaryingCoord( i1, j0, dims[2]-1);
t10 = _GetVaryingCoord( i0, j1, dims[2]-1);
t11 = _GetVaryingCoord( i1, j1, dims[2]-1);
b00 = _GetVaryingCoord( i0, j0, 0);
b01 = _GetVaryingCoord( i1, j0, 0);
b10 = _GetVaryingCoord( i0, j1, 0);
b11 = _GetVaryingCoord( i1, j1, 0);
vc = z;
}
if (b00<t00) {
// If coordinate is between all of the cell's top and bottom
// coordinates the point must be in the grid
//
if (b00<vc && b01<vc && b10<vc && b11<vc &&
t00>vc && t01>vc && t10>vc && t11>vc) {
return(true);
}
//
// if coordinate is above or below all corner points
// the input point must be outside the grid
//
if (b00>vc && b01>vc && b10>vc && b11>vc) return(false);
if (t00<vc && t01<vc && t10<vc && t11<vc) return(false);
}
else {
if (b00>vc && b01>vc && b10>vc && b11>vc &&
t00<vc && t01<vc && t10<vc && t11<vc) {
return(true);
}
if (b00<vc && b01<vc && b10<vc && b11<vc) return(false);
if (t00>vc && t01>vc && t10>vc && t11>vc) return(false);
}
// If we get this far the point is either inside or outside of a
// boundary cell on the varying dimension. Need to interpolate
// the varying coordinate of the cell
// Varying dimesion coordinate value returned by GetUserCoordinates
// is not valid
//
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
double iwgt, jwgt;
if (_varying_dim == 0) {
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else if (_varying_dim == 1) {
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else {
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
}
double t = t00+iwgt*(t01-t00) + jwgt*((t10+iwgt*(t11-t10))-(t00+iwgt*(t01-t00)));
double b = b00+iwgt*(b01-b00) + jwgt*((b10+iwgt*(b11-b10))-(b00+iwgt*(b01-b00)));
if (b<t) {
if (vc<b || vc>t) return(false);
}
else {
if (vc>b || vc<t) return(false);
}
return(true);
}
void LayeredGrid::GetMinCellExtents(double *x, double *y, double *z) const {
//
// Get X and Y dimension minimums
//
RegularGrid::GetMinCellExtents(x,y,z);
size_t dims[3];
GetDimensions(dims);
if (dims[2] < 2) return;
double tmp;
*z = fabs(_extents[5] - _extents[3]);
for (int k=0; k<dims[2]-1; k++) {
for (int j=0; j<dims[1]; j++) {
for (int i=0; i<dims[0]; i++) {
float z0 = _GetVaryingCoord(i,j,k);
float z1 = _GetVaryingCoord(i,j,k+1);
tmp = fabs(z1-z0);
if (tmp<*z) *z = tmp;
}
}
}
}
double LayeredGrid::_GetVaryingCoord(size_t i, size_t j, size_t k) const {
double mv = GetMissingValue();
double c = _AccessIJK(_coords, i, j, k);
if (c != mv) return (c);
assert (c != mv);
size_t dims[3];
GetDimensions(dims);
//
// Varying coordinate for i,j,k is missing. Look along varying dimension
// axis for first grid point with non-missing value. First search
// below, then above. If no valid coordinate is found, use the
// grid minimum extent
//
if (_varying_dim == 0) {
size_t ii = i;
while (ii>0 && (c=_AccessIJK(_coords,ii-1,j,k)) == mv) ii--;
if (c!=mv) return (c);
ii = i;
while (ii<dims[0]-1 && (c=_AccessIJK(_coords,ii+1,j,k)) == mv) ii++;
if (c!=mv) return (c);
return(_extents[0]);
} else if (_varying_dim == 1) {
size_t jj = j;
while (jj>0 && (c=_AccessIJK(_coords,i,jj-1,k)) == mv) jj--;
if (c!=mv) return (c);
jj = j;
while (jj<dims[1]-1 && (c=_AccessIJK(_coords,i, jj+1,k)) == mv) jj++;
if (c!=mv) return (c);
return(_extents[1]);
} else if (_varying_dim == 2) {
size_t kk = k;
while (kk>0 && (c=_AccessIJK(_coords,i,j,kk-1)) == mv) kk--;
if (c!=mv) return (c);
kk = k;
while (kk<dims[2]-1 && (c=_AccessIJK(_coords,i,j,kk+1)) == mv) kk++;
if (c!=mv) return (c);
return(_extents[2]);
}
return(0.0);
}
double LayeredGrid::_interpolateVaryingCoord(
size_t i0, size_t j0, size_t k0,
double x, double y, double z) const {
// varying dimension coord at corner grid points of cell face
//
double c00, c01, c10, c11;
size_t dims[3];
GetDimensions(dims);
size_t i1, j1, k1;
if (i0 == dims[0]-1) i1 = i0;
else i1 = i0+1;
if (j0 == dims[1]-1) j1 = j0;
else j1 = j0+1;
if (k0 == dims[2]-1) k1 = k0;
else k1 = k0+1;
// Coordinates of grid points for non-varying dimensions
double x0, y0, z0, x1, y1, z1;
RegularGrid::GetUserCoordinates(i0,j0,k0, &x0, &y0, &z0);
RegularGrid::GetUserCoordinates(i1,j1,k1, &x1, &y1, &z1);
double iwgt, jwgt;
if (_varying_dim == 0) {
// Now get user coordinates of vary-dimension grid point
// N.B. Could just call LayeredGrid:GetUserCoordinates() for
// each of the four points but this is more efficient
//
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i0, j1, k0);
c10 = _AccessIJK(_coords, i0, j0, k1);
c11 = _AccessIJK(_coords, i0, j1, k1);
if (y1!=y0) iwgt = fabs((y-y0) / (y1-y0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else if (_varying_dim == 1) {
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i1, j0, k0);
c10 = _AccessIJK(_coords, i0, j0, k1);
c11 = _AccessIJK(_coords, i1, j0, k1);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (z1!=z0) jwgt = fabs((z-z0) / (z1-z0));
else jwgt = 0.0;
}
else { // _varying_dim == 2
c00 = _AccessIJK(_coords, i0, j0, k0);
c01 = _AccessIJK(_coords, i1, j0, k0);
c10 = _AccessIJK(_coords, i0, j1, k0);
c11 = _AccessIJK(_coords, i1, j1, k0);
if (x1!=x0) iwgt = fabs((x-x0) / (x1-x0));
else iwgt = 0.0;
if (y1!=y0) jwgt = fabs((y-y0) / (y1-y0));
else jwgt = 0.0;
}
double c = c00+iwgt*(c01-c00) + jwgt*((c10+iwgt*(c11-c10))-(c00+iwgt*(c01-c00)));
return(c);
}
| 25,801 | 13,382 |
#include "kernel.h"
/// <summary>
/// Compiler definitions.
/// </summary>
void __stack_chk_fail(void)
{
}
void* __dso_handle = (void*) &__dso_handle;
void* __cxa_atexit = (void*) &__cxa_atexit;
/// <summary>
/// The function called by the bootloader when it leaves boot services.
/// </summary>
extern "C" void KernelMain(BootLoaderInfo* BootInfo)
{
InitGDT();
//Runtime services setup.
UEFI::Init(BootInfo->RT);
//Heap setup.
PageAllocator::Init(BootInfo->MemoryMap, BootInfo->ScreenBuffer);
PageTableManager::Init(BootInfo->ScreenBuffer);
Heap::Init();
//Renderer setup.
STL::SetFonts(BootInfo->PSFFonts, BootInfo->FontAmount);
Renderer::Init(BootInfo->ScreenBuffer);
//Interrupt setup.
PIT::SetFrequency(100);
RTC::Update();
IDT::SetupInterrupts();
//AHCI setup.
ACPI::Init(BootInfo->RSDP);
PCI::Init();
AHCI::Init();
ProcessHandler::Loop();
while(true)
{
asm("HLT");
}
}
| 911 | 356 |
#ifndef GUI_ABILITY_HPP_INCLUDED
#define GUI_ABILITY_HPP_INCLUDED
/**
* Contains all the information about an ability, for the GUI part. For
* example the icone to use, the activate callback (it can execute the
* ability directly, or change the LeftClick structure, which only involves
* the GUI)
*/
#include <gui/screen/left_click.hpp>
#include <functional>
class GuiAbility
{
public:
GuiAbility() = default;
~GuiAbility() = default;
LeftClick left_click;
std::function<void()> callback;
private:
GuiAbility(const GuiAbility&) = delete;
GuiAbility(GuiAbility&&) = delete;
GuiAbility& operator=(const GuiAbility&) = delete;
GuiAbility& operator=(GuiAbility&&) = delete;
};
#endif /* GUI_ABILITY_HPP_INCLUDED */
| 738 | 265 |
#pragma once
#include <mutex>
#include <thread>
typedef void (*die_handler_func)(int);
struct MutexStore {
public:
std::mutex podman, podman_sched, podman_sock;
MutexStore(die_handler_func die_handler);
};
extern MutexStore mutex;
| 243 | 98 |
#include <iostream>
#include <cmath>
#include "isPrime.hpp"
using namespace std;
int main() {
long int sum = 0;
for(int i = 2; i < 2000000; i++) {
if(isPrime(i) == true)
sum += i;
}
cout << sum << endl;
}
| 246 | 104 |
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2014 Pivotal, Inc.
//
// @filename:
// CDXLScalarBitmapIndexProbe.cpp
//
// @doc:
// Class for representing DXL bitmap index probe operators
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#include "naucrates/dxl/operators/CDXLIndexDescr.h"
#include "naucrates/dxl/operators/CDXLNode.h"
#include "naucrates/dxl/operators/CDXLScalarBitmapIndexProbe.h"
#include "naucrates/dxl/operators/CDXLTableDescr.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
#include "naucrates/dxl/xml/dxltokens.h"
using namespace gpdxl;
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::CDXLScalarBitmapIndexProbe
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CDXLScalarBitmapIndexProbe::CDXLScalarBitmapIndexProbe
(
IMemoryPool *pmp,
CDXLIndexDescr *pdxlid
)
:
CDXLScalar(pmp),
m_pdxlid(pdxlid)
{
GPOS_ASSERT(NULL != m_pdxlid);
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::~CDXLScalarBitmapIndexProbe
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CDXLScalarBitmapIndexProbe::~CDXLScalarBitmapIndexProbe()
{
m_pdxlid->Release();
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::PstrOpName
//
// @doc:
// Operator name
//
//---------------------------------------------------------------------------
const CWStringConst *
CDXLScalarBitmapIndexProbe::PstrOpName() const
{
return CDXLTokens::PstrToken(EdxltokenScalarBitmapIndexProbe);
}
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::SerializeToDXL
//
// @doc:
// Serialize operator in DXL format
//
//---------------------------------------------------------------------------
void
CDXLScalarBitmapIndexProbe::SerializeToDXL
(
CXMLSerializer *pxmlser,
const CDXLNode *pdxln
)
const
{
const CWStringConst *pstrElemName = PstrOpName();
pxmlser->OpenElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
// serialize children
pdxln->SerializeChildrenToDXL(pxmlser);
// serialize index descriptor
m_pdxlid->SerializeToDXL(pxmlser);
pxmlser->CloseElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName);
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CDXLScalarBitmapIndexProbe::AssertValid
//
// @doc:
// Checks whether operator node is well-structured
//
//---------------------------------------------------------------------------
void
CDXLScalarBitmapIndexProbe::AssertValid
(
const CDXLNode *pdxln,
BOOL fValidateChildren
)
const
{
// bitmap index probe has 1 child: the index condition list
GPOS_ASSERT(1 == pdxln->UlArity());
if (fValidateChildren)
{
CDXLNode *pdxlnIndexCondList = (*pdxln)[0];
GPOS_ASSERT(EdxlopScalarIndexCondList == pdxlnIndexCondList->Pdxlop()->Edxlop());
pdxlnIndexCondList->Pdxlop()->AssertValid(pdxlnIndexCondList, fValidateChildren);
}
// assert validity of index descriptor
GPOS_ASSERT(NULL != m_pdxlid->Pmdname());
GPOS_ASSERT(m_pdxlid->Pmdname()->Pstr()->FValid());
}
#endif // GPOS_DEBUG
// EOF
| 3,520 | 1,205 |
/*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ui/HdrCapabilities.h>
#include <binder/Parcel.h>
namespace android {
status_t HdrCapabilities::writeToParcel(Parcel* parcel) const
{
status_t result = parcel->writeInt32Vector(mSupportedHdrTypes);
if (result != OK) {
return result;
}
result = parcel->writeFloat(mMaxLuminance);
if (result != OK) {
return result;
}
result = parcel->writeFloat(mMaxAverageLuminance);
if (result != OK) {
return result;
}
result = parcel->writeFloat(mMinLuminance);
return result;
}
status_t HdrCapabilities::readFromParcel(const Parcel* parcel)
{
status_t result = parcel->readInt32Vector(&mSupportedHdrTypes);
if (result != OK) {
return result;
}
result = parcel->readFloat(&mMaxLuminance);
if (result != OK) {
return result;
}
result = parcel->readFloat(&mMaxAverageLuminance);
if (result != OK) {
return result;
}
result = parcel->readFloat(&mMinLuminance);
return result;
}
} // namespace android
| 1,651 | 522 |
#include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vi arr(n);
int acc = 0, flag = 0;
for(int i=1; i<=n; ++i){
cin >> arr[i-1];
if(arr[i-1] == i)
flag = 0;
else if(!flag){
flag = 1;
acc++;
}
}
if(acc == 0)
cout << 0 << endl;
else if(acc == 1)
cout << 1 << endl;
else
cout << 2 << endl;
}
return 0;
}
| 578 | 206 |
// Copyright (C) <2021> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#include "InternalClient.h"
#include "RawTransport.h"
namespace owt_base {
DEFINE_LOGGER(InternalClient, "owt.InternalClient");
InternalClient::InternalClient(
const std::string& streamId,
const std::string& protocol,
Listener* listener)
: m_client(new TransportClient(this))
, m_streamId(streamId)
, m_ready(false)
, m_listener(listener)
{
}
InternalClient::InternalClient(
const std::string& streamId,
const std::string& protocol,
const std::string& ip,
unsigned int port,
Listener* listener)
: InternalClient(streamId, protocol, listener)
{
if (!TransportSecret::getPassphrase().empty()) {
m_client->enableSecure();
}
m_client->createConnection(ip, port);
}
InternalClient::~InternalClient()
{
m_client->close();
m_client.reset();
}
void InternalClient::connect(const std::string& ip, unsigned int port)
{
m_client->createConnection(ip, port);
}
void InternalClient::onFeedback(const FeedbackMsg& msg)
{
if (!m_ready && msg.cmd != INIT_STREAM_ID) {
return;
}
ELOG_DEBUG("onFeedback ");
uint8_t sendBuffer[512];
sendBuffer[0] = TDT_FEEDBACK_MSG;
memcpy(&sendBuffer[1],
reinterpret_cast<uint8_t*>(const_cast<FeedbackMsg*>(&msg)),
sizeof(FeedbackMsg));
m_client->sendData((uint8_t*)sendBuffer, sizeof(FeedbackMsg) + 1);
}
void InternalClient::onConnected()
{
ELOG_DEBUG("On Connected %s", m_streamId.c_str());
if (m_listener) {
m_listener->onConnected();
}
if (!m_streamId.empty()) {
FeedbackMsg msg(VIDEO_FEEDBACK, INIT_STREAM_ID);
if (m_streamId.length() > 128) {
ELOG_WARN("Too long streamId:%s, will be resized",
m_streamId.c_str());
m_streamId.resize(128);
}
memcpy(&msg.buffer.data[0], m_streamId.c_str(), m_streamId.length());
msg.buffer.len = m_streamId.length();
onFeedback(msg);
}
m_ready = true;
}
void InternalClient::onData(uint8_t* buf, uint32_t len)
{
Frame* frame = nullptr;
MetaData* metadata = nullptr;
if (len <= 1) {
ELOG_DEBUG("Skip onData len: %u", (unsigned int)len);
return;
}
switch ((char) buf[0]) {
case TDT_MEDIA_FRAME:
frame = reinterpret_cast<Frame*>(buf + 1);
frame->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(Frame));
deliverFrame(*frame);
break;
case TDT_MEDIA_METADATA:
metadata = reinterpret_cast<MetaData*>(buf + 1);
metadata->payload = reinterpret_cast<uint8_t*>(buf + 1 + sizeof(MetaData));
deliverMetaData(*metadata);
break;
default:
break;
}
}
void InternalClient::onDisconnected()
{
if (m_listener) {
m_listener->onDisconnected();
}
}
} /* namespace owt_base */
| 2,969 | 1,030 |
// Copyright (c) 2019 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/matrix2x2.h>
#include <jet/point_hash_grid_searcher2.h>
#include <jet/samplers.h>
#include <jet/surface_to_implicit2.h>
#include <jet/triangle_point_generator.h>
#include <jet/volume_particle_emitter2.h>
using namespace jet;
static const size_t kDefaultHashGridResolution = 64;
VolumeParticleEmitter2::VolumeParticleEmitter2(
const ImplicitSurface2Ptr& implicitSurface, const BoundingBox2D& maxRegion,
double spacing, const Vector2D& initialVel, const Vector2D& linearVel,
double angularVel, size_t maxNumberOfParticles, double jitter,
bool isOneShot, bool allowOverlapping, uint32_t seed)
: _rng(seed),
_implicitSurface(implicitSurface),
_bounds(maxRegion),
_spacing(spacing),
_initialVel(initialVel),
_linearVel(linearVel),
_angularVel(angularVel),
_maxNumberOfParticles(maxNumberOfParticles),
_jitter(jitter),
_isOneShot(isOneShot),
_allowOverlapping(allowOverlapping) {
_pointsGen = std::make_shared<TrianglePointGenerator>();
}
void VolumeParticleEmitter2::onUpdate(double currentTimeInSeconds,
double timeIntervalInSeconds) {
UNUSED_VARIABLE(currentTimeInSeconds);
UNUSED_VARIABLE(timeIntervalInSeconds);
auto particles = target();
if (particles == nullptr) {
return;
}
if (!isEnabled()) {
return;
}
Array1<Vector2D> newPositions;
Array1<Vector2D> newVelocities;
emit(particles, &newPositions, &newVelocities);
particles->addParticles(newPositions, newVelocities);
if (_isOneShot) {
setIsEnabled(false);
}
}
void VolumeParticleEmitter2::emit(const ParticleSystemData2Ptr& particles,
Array1<Vector2D>* newPositions,
Array1<Vector2D>* newVelocities) {
if (!_implicitSurface) {
return;
}
_implicitSurface->updateQueryEngine();
BoundingBox2D region = _bounds;
if (_implicitSurface->isBounded()) {
BoundingBox2D surfaceBBox = _implicitSurface->boundingBox();
region.lowerCorner = max(region.lowerCorner, surfaceBBox.lowerCorner);
region.upperCorner = min(region.upperCorner, surfaceBBox.upperCorner);
}
// Reserving more space for jittering
const double j = jitter();
const double maxJitterDist = 0.5 * j * _spacing;
size_t numNewParticles = 0;
if (_allowOverlapping || _isOneShot) {
_pointsGen->forEachPoint(region, _spacing, [&](const Vector2D& point) {
double newAngleInRadian = (random() - 0.5) * kTwoPiD;
Matrix2x2D rotationMatrix =
Matrix2x2D::makeRotationMatrix(newAngleInRadian);
Vector2D randomDir = rotationMatrix * Vector2D();
Vector2D offset = maxJitterDist * randomDir;
Vector2D candidate = point + offset;
if (_implicitSurface->signedDistance(candidate) <= 0.0) {
if (_numberOfEmittedParticles < _maxNumberOfParticles) {
newPositions->append(candidate);
++_numberOfEmittedParticles;
++numNewParticles;
} else {
return false;
}
}
return true;
});
} else {
// Use serial hash grid searcher for continuous update.
PointHashGridSearcher2 neighborSearcher(
Size2(kDefaultHashGridResolution, kDefaultHashGridResolution),
2.0 * _spacing);
if (!_allowOverlapping) {
neighborSearcher.build(particles->positions());
}
_pointsGen->forEachPoint(region, _spacing, [&](const Vector2D& point) {
double newAngleInRadian = (random() - 0.5) * kTwoPiD;
Matrix2x2D rotationMatrix =
Matrix2x2D::makeRotationMatrix(newAngleInRadian);
Vector2D randomDir = rotationMatrix * Vector2D();
Vector2D offset = maxJitterDist * randomDir;
Vector2D candidate = point + offset;
if (_implicitSurface->isInside(candidate) &&
(!_allowOverlapping &&
!neighborSearcher.hasNearbyPoint(candidate, _spacing))) {
if (_numberOfEmittedParticles < _maxNumberOfParticles) {
newPositions->append(candidate);
neighborSearcher.add(candidate);
++_numberOfEmittedParticles;
++numNewParticles;
} else {
return false;
}
}
return true;
});
}
JET_INFO << "Number of newly generated particles: " << numNewParticles;
JET_INFO << "Number of total generated particles: "
<< _numberOfEmittedParticles;
newVelocities->resize(newPositions->size());
newVelocities->parallelForEachIndex([&](size_t i) {
(*newVelocities)[i] = velocityAt((*newPositions)[i]);
});
}
void VolumeParticleEmitter2::setPointGenerator(
const PointGenerator2Ptr& newPointsGen) {
_pointsGen = newPointsGen;
}
const ImplicitSurface2Ptr& VolumeParticleEmitter2::surface() const {
return _implicitSurface;
}
void VolumeParticleEmitter2::setSurface(const ImplicitSurface2Ptr& newSurface) {
_implicitSurface = newSurface;
}
const BoundingBox2D& VolumeParticleEmitter2::maxRegion() const {
return _bounds;
}
void VolumeParticleEmitter2::setMaxRegion(const BoundingBox2D& newMaxRegion) {
_bounds = newMaxRegion;
}
double VolumeParticleEmitter2::jitter() const { return _jitter; }
void VolumeParticleEmitter2::setJitter(double newJitter) {
_jitter = clamp(newJitter, 0.0, 1.0);
}
bool VolumeParticleEmitter2::isOneShot() const { return _isOneShot; }
void VolumeParticleEmitter2::setIsOneShot(bool newValue) {
_isOneShot = newValue;
}
bool VolumeParticleEmitter2::allowOverlapping() const {
return _allowOverlapping;
}
void VolumeParticleEmitter2::setAllowOverlapping(bool newValue) {
_allowOverlapping = newValue;
}
size_t VolumeParticleEmitter2::maxNumberOfParticles() const {
return _maxNumberOfParticles;
}
void VolumeParticleEmitter2::setMaxNumberOfParticles(
size_t newMaxNumberOfParticles) {
_maxNumberOfParticles = newMaxNumberOfParticles;
}
double VolumeParticleEmitter2::spacing() const { return _spacing; }
void VolumeParticleEmitter2::setSpacing(double newSpacing) {
_spacing = newSpacing;
}
Vector2D VolumeParticleEmitter2::initialVelocity() const { return _initialVel; }
void VolumeParticleEmitter2::setInitialVelocity(const Vector2D& newInitialVel) {
_initialVel = newInitialVel;
}
Vector2D VolumeParticleEmitter2::linearVelocity() const { return _linearVel; }
void VolumeParticleEmitter2::setLinearVelocity(const Vector2D& newLinearVel) {
_linearVel = newLinearVel;
}
double VolumeParticleEmitter2::angularVelocity() const { return _angularVel; }
void VolumeParticleEmitter2::setAngularVelocity(double newAngularVel) {
_angularVel = newAngularVel;
}
double VolumeParticleEmitter2::random() {
std::uniform_real_distribution<> d(0.0, 1.0);
return d(_rng);
}
Vector2D VolumeParticleEmitter2::velocityAt(const Vector2D& point) const {
Vector2D r = point - _implicitSurface->transform.translation();
return _linearVel + _angularVel * Vector2D(-r.y, r.x) + _initialVel;
}
VolumeParticleEmitter2::Builder VolumeParticleEmitter2::builder() {
return Builder();
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withImplicitSurface(
const ImplicitSurface2Ptr& implicitSurface) {
_implicitSurface = implicitSurface;
if (!_isBoundSet) {
_bounds = _implicitSurface->boundingBox();
}
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withSurface(
const Surface2Ptr& surface) {
_implicitSurface = std::make_shared<SurfaceToImplicit2>(surface);
if (!_isBoundSet) {
_bounds = surface->boundingBox();
}
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withMaxRegion(
const BoundingBox2D& bounds) {
_bounds = bounds;
_isBoundSet = true;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withSpacing(
double spacing) {
_spacing = spacing;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withInitialVelocity(
const Vector2D& initialVel) {
_initialVel = initialVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withLinearVelocity(const Vector2D& linearVel) {
_linearVel = linearVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withAngularVelocity(double angularVel) {
_angularVel = angularVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withMaxNumberOfParticles(
size_t maxNumberOfParticles) {
_maxNumberOfParticles = maxNumberOfParticles;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withJitter(
double jitter) {
_jitter = jitter;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::withIsOneShot(
bool isOneShot) {
_isOneShot = isOneShot;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withAllowOverlapping(bool allowOverlapping) {
_allowOverlapping = allowOverlapping;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::withRandomSeed(uint32_t seed) {
_seed = seed;
return *this;
}
VolumeParticleEmitter2 VolumeParticleEmitter2::Builder::build() const {
return VolumeParticleEmitter2(_implicitSurface, _bounds, _spacing,
_initialVel, _linearVel, _angularVel,
_maxNumberOfParticles, _jitter, _isOneShot,
_allowOverlapping, _seed);
}
VolumeParticleEmitter2Ptr VolumeParticleEmitter2::Builder::makeShared() const {
return std::shared_ptr<VolumeParticleEmitter2>(
new VolumeParticleEmitter2(_implicitSurface, _bounds, _spacing,
_initialVel, _linearVel, _angularVel,
_maxNumberOfParticles, _jitter, _isOneShot,
_allowOverlapping),
[](VolumeParticleEmitter2* obj) { delete obj; });
}
| 10,699 | 3,436 |
#include "tabbarform.h"
TabBarForm::TabBarForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::TabBarForm)
{
ui->setupUi(this);
}
TabBarForm::~TabBarForm()
{
delete ui;
}
| 188 | 80 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: ShowHideAnimationController
class ShowHideAnimationController;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::ShowHideAnimationController);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::ShowHideAnimationController*, "", "ShowHideAnimationController");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: ShowHideAnimationController
// [TokenAttribute] Offset: FFFFFFFF
class ShowHideAnimationController : public ::UnityEngine::MonoBehaviour {
public:
// Nested type: ::GlobalNamespace::ShowHideAnimationController::$DeactivateSelfAfterDelayCoroutine$d__9
class $DeactivateSelfAfterDelayCoroutine$d__9;
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public UnityEngine.Animator _animator
// Size: 0x8
// Offset: 0x18
::UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(::UnityEngine::Animator*) == 0x8);
// public System.Boolean _deactivateSelfAfterDelay
// Size: 0x1
// Offset: 0x20
bool deactivateSelfAfterDelay;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: deactivateSelfAfterDelay and: deactivationDelay
char __padding1[0x3] = {};
// public System.Single _deactivationDelay
// Size: 0x4
// Offset: 0x24
float deactivationDelay;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Boolean _show
// Size: 0x1
// Offset: 0x28
bool show;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: show and: showAnimatorParam
char __padding3[0x3] = {};
// private System.Int32 _showAnimatorParam
// Size: 0x4
// Offset: 0x2C
int showAnimatorParam;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: public UnityEngine.Animator _animator
::UnityEngine::Animator*& dyn__animator();
// Get instance field reference: public System.Boolean _deactivateSelfAfterDelay
bool& dyn__deactivateSelfAfterDelay();
// Get instance field reference: public System.Single _deactivationDelay
float& dyn__deactivationDelay();
// Get instance field reference: private System.Boolean _show
bool& dyn__show();
// Get instance field reference: private System.Int32 _showAnimatorParam
int& dyn__showAnimatorParam();
// public System.Boolean get_Show()
// Offset: 0x29D63D4
bool get_Show();
// public System.Void set_Show(System.Boolean value)
// Offset: 0x29D6274
void set_Show(bool value);
// protected System.Void Awake()
// Offset: 0x29D63DC
void Awake();
// private System.Collections.IEnumerator DeactivateSelfAfterDelayCoroutine(System.Single delay)
// Offset: 0x29D6458
::System::Collections::IEnumerator* DeactivateSelfAfterDelayCoroutine(float delay);
// public System.Void .ctor()
// Offset: 0x29D6504
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ShowHideAnimationController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::ShowHideAnimationController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ShowHideAnimationController*, creationType>()));
}
}; // ShowHideAnimationController
#pragma pack(pop)
static check_size<sizeof(ShowHideAnimationController), 44 + sizeof(int)> __GlobalNamespace_ShowHideAnimationControllerSizeCheck;
static_assert(sizeof(ShowHideAnimationController) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::get_Show
// Il2CppName: get_Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::ShowHideAnimationController::*)()>(&GlobalNamespace::ShowHideAnimationController::get_Show)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "get_Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::set_Show
// Il2CppName: set_Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ShowHideAnimationController::*)(bool)>(&GlobalNamespace::ShowHideAnimationController::set_Show)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "set_Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ShowHideAnimationController::*)()>(&GlobalNamespace::ShowHideAnimationController::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::DeactivateSelfAfterDelayCoroutine
// Il2CppName: DeactivateSelfAfterDelayCoroutine
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (GlobalNamespace::ShowHideAnimationController::*)(float)>(&GlobalNamespace::ShowHideAnimationController::DeactivateSelfAfterDelayCoroutine)> {
static const MethodInfo* get() {
static auto* delay = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ShowHideAnimationController*), "DeactivateSelfAfterDelayCoroutine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{delay});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ShowHideAnimationController::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 8,199 | 2,593 |
#include <iostream>
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "HelperTest.h"
#include "MagmaDevice.h"
#include "mbmagma.h"
using namespace MagmaBinding;
#include "GSVTests.h"
#include "SVDTests.h"
#include "LSSTests.h"
#include "EIGENTests.h"
#include "MatrixTest.h"
int main(int argc, char** argv)
{
mv2sgemm_test_magma_col_01();
mv2sgemm_test_magma_row_01();
mv2sgemm_test_magma_row();
mv2sgemm_test_magma_col();
mv2sgemm_test_lapack_col_01();
mv2sgemm_test_lapack_row_01();
mv2sgemm_test_lapack_row();
mv2sgemm_test_lapack_col();
mv2dgemm_test_magma_col_01();
mv2dgemm_test_magma_row_01();
mv2dgemm_test_magma_row();
mv2dgemm_test_magma_col();
mv2dgemm_test_lapack_col_01();
mv2dgemm_test_lapack_row_01();
mv2dgemm_test_lapack_row();
mv2dgemm_test_lapack_col();
mbv2getdevice_arch();
//EIGEN
mv2sgeevs_cpu_test();
mv2sgeevs_test();
mv2sgeev_cpu_test();
mv2sgeev_test();
mv2dgeevs_cpu_test();
mv2dgeevs_test();
mv2dgeev_cpu_test();
mv2dgeev_test();
//LSS
mv2sgels_cpu_test();
mv2sgels_test();
mv2sgels_gpu_test();
mv2dgels_cpu_test();
mv2dgels_test();
mv2dgels_gpu_test();
//GSV tests
mv2dgesv_cpu_test();
mv2dgesv_test();
mv2dgesv_gpu_test();
mv2sgesv_cpu_test();
mv2sgesv_test();
mv2sgesv_gpu_test();
//SVD
mv2sgesvd_cpu_test();
mv2sgesvds_cpu_test();
mv2sgesvds_test();
mv2sgesvd_test();
mv2dgesvd_cpu_test();
mv2dgesvds_cpu_test();
mv2dgesvds_test();
mv2dgesvd_test();
return 0;
}
| 1,525 | 791 |
#include "TicTacToeGame.hpp"
void TicTacToeGame::setup()
{
createBoard();
createText();
m_board.clear();
m_crntPlayer = CellValue::Cross; // todo: set this randomly
}
void TicTacToeGame::createText()
{
m_textEntities.clear();
m_headingText = std::make_shared<sf::Text>();
m_headingText->setFont(shared::font);
m_headingText->setCharacterSize(m_topBarHeight - 15);
m_headingText->setFillColor(m_textColor);
// m_drawables.push_back(m_headingText);
}
void TicTacToeGame::createBoard()
{
m_board = TicTacToeBoard();
}
void TicTacToeGame::update()
{
calcBoardSize();
switch (m_gamePhase)
{
case Playing:
drawCellBorders();
drawCells();
updateText();
break;
case ShowingWinner:
drawCellBorders();
drawCells();
updateText();
if (! m_showWinnerTimer.running) m_showWinnerTimer.start();
if (m_showWinnerTimer.isFinished()) gameManager->queueLoadScene("TitleScreen");
break;
}
}
void TicTacToeGame::handleEvent(sf::Event& event)
{
if (event.type == sf::Event::MouseButtonPressed)
{
switch (m_gamePhase)
{
case Playing:
setCellContents(event);
break;
}
}
}
void TicTacToeGame::updateText()
{
// Yes this is a big and convoluted nested switch-case
// But I couldn't find a way to put this into a table lookup because of the differing
// data types
std::string headingTextContent = "Error: no text supplied for this heading";
switch (m_gamePhase)
{
case Playing:
switch (m_crntPlayer)
{
case CellValue::Nought:
headingTextContent = "Noughts turn";
break;
case CellValue::Cross:
headingTextContent = "Crosses turn";
break;
}
break;
case ShowingWinner:
switch (m_winner)
{
case Winner::Nought:
headingTextContent = "Noughts wins";
break;
case Winner::Cross:
headingTextContent = "Crosses wins";
break;
case Winner::Draw:
headingTextContent = "Draw";
break;
}
break;
}
m_headingText->setString(headingTextContent);
miniengine::utils::centerAlignText(*m_headingText);
m_headingText->setPosition(gameManager->width / 2, m_topBarHeight / 2);
}
void TicTacToeGame::calcBoardSize()
{
int availableHeight = gameManager->height - m_topBarHeight - m_bottomBarHeight;
m_boardSize = std::min(availableHeight, gameManager->width) - m_windowPadding * 2;
m_cellSize = m_boardSize / 3;
m_boardLeft = std::max(gameManager->width - m_boardSize, 1) / 2;
m_boardTop = std::max(gameManager->height - m_boardSize, 1) / 2;
}
void TicTacToeGame::drawCellBorders()
{
sf::RectangleShape rectangle;
rectangle.setFillColor(m_cellBorderColor);
int cellBorderWidth = m_cellBorderWidthProportion * m_boardSize;
rectangle.setSize(sf::Vector2f(m_boardSize, cellBorderWidth));
rectangle.setOrigin(m_boardSize / 2, cellBorderWidth / 2);
// Do the horizontal borders
for (int y = 1; y < BOARD_SIZE; y ++)
{
rectangle.setPosition(m_boardLeft + m_boardSize / 2,
m_boardTop + y * m_cellSize);
gameManager->window.draw(rectangle);
}
// Do the vertical borders
rectangle.setRotation(90);
for (int x = 1; x < BOARD_SIZE; x ++)
{
rectangle.setPosition(m_boardLeft + x * m_cellSize,
m_boardTop + m_boardSize / 2);
gameManager->window.draw(rectangle);
}
}
void TicTacToeGame::drawCells()
{
int cellPadding = m_cellPaddingProportion * m_cellSize;
NoughtGraphic nought((m_cellSize - cellPadding) / 2);
CrossGraphic cross((m_cellSize - cellPadding) / 2);
for (int x = 0; x < BOARD_SIZE; x ++)
{
for (int y = 0; y < BOARD_SIZE; y ++)
{
int xPos = x * m_cellSize + m_cellSize / 2 + m_boardLeft;
int yPos = y * m_cellSize + m_cellSize / 2 + m_boardTop;
if (m_board.getCell(x, y) == CellValue::Nought)
nought.draw(xPos, yPos, gameManager->window, m_backgroundColor);
else if (m_board.getCell(x, y) == CellValue::Cross)
cross.draw(xPos, yPos, gameManager->window);
}
}
}
void TicTacToeGame::setCellContents(sf::Event event)
{
// First calculate board pos of click
int xCoord = (event.mouseButton.x - m_boardLeft) / m_cellSize;
int yCoord = (event.mouseButton.y - m_boardTop) / m_cellSize;
// If click is on board, do game logic
if (xCoord >= 0 && xCoord < BOARD_SIZE &&
yCoord >= 0 && yCoord < BOARD_SIZE)
{
if (m_board.getCell(xCoord, yCoord) == CellValue::Empty)
{
m_board.setCell(xCoord, yCoord, m_crntPlayer);
m_winner = m_board.findWinner();
if (m_winner == Winner::GameNotFinished)
{
if (m_crntPlayer == CellValue::Nought) m_crntPlayer = CellValue::Cross;
else m_crntPlayer = CellValue::Nought;
}
else
{
m_gamePhase = ShowingWinner;
}
}
}
}
| 5,252 | 1,769 |
#include "mvAppItemState.h"
#include <imgui.h>
#include "mvAppItem.h"
#include "mvApp.h"
#include "mvPyObject.h"
namespace Marvel {
void mvAppItemState::reset()
{
_hovered = false;
_active = false;
_focused = false;
_leftclicked = false;
_rightclicked = false;
_middleclicked = false;
_visible = false;
_edited = false;
_activated = false;
_deactivated = false;
_deactivatedAfterEdit = false;
_toggledOpen = false;
}
void mvAppItemState::update()
{
_lastFrameUpdate = mvApp::s_frame;
_hovered = ImGui::IsItemHovered();
_active = ImGui::IsItemActive();
_focused = ImGui::IsItemFocused();
_leftclicked = ImGui::IsItemClicked();
_rightclicked = ImGui::IsItemClicked(1);
_middleclicked = ImGui::IsItemClicked(2);
_visible = ImGui::IsItemVisible();
_edited = ImGui::IsItemEdited();
_activated = ImGui::IsItemActivated();
_deactivated = ImGui::IsItemDeactivated();
_deactivatedAfterEdit = ImGui::IsItemDeactivatedAfterEdit();
_toggledOpen = ImGui::IsItemToggledOpen();
_rectMin = { ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y };
_rectMax = { ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y };
_rectSize = { ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y };
_contextRegionAvail = { ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y };
}
void mvAppItemState::getState(PyObject* dict)
{
if (dict == nullptr)
return;
bool valid = _lastFrameUpdate == mvApp::s_frame;
PyDict_SetItemString(dict, "ok", mvPyObject(ToPyBool(_ok)));
PyDict_SetItemString(dict, "pos", mvPyObject(ToPyPairII(_pos.x, _pos.y)));
if(_applicableState & MV_STATE_HOVER) PyDict_SetItemString(dict, "hovered", mvPyObject(ToPyBool(valid ? _hovered : false)));
if(_applicableState & MV_STATE_ACTIVE) PyDict_SetItemString(dict, "active", mvPyObject(ToPyBool(valid ? _active : false)));
if(_applicableState & MV_STATE_FOCUSED) PyDict_SetItemString(dict, "focused", mvPyObject(ToPyBool(valid ? _focused : false)));
if (_applicableState & MV_STATE_CLICKED)
{
PyDict_SetItemString(dict, "clicked", mvPyObject(ToPyBool(valid ? _leftclicked || _rightclicked || _middleclicked : false)));
PyDict_SetItemString(dict, "left_clicked", mvPyObject(ToPyBool(valid ? _leftclicked : false)));
PyDict_SetItemString(dict, "right_clicked", mvPyObject(ToPyBool(valid ? _rightclicked : false)));
PyDict_SetItemString(dict, "middle_clicked", mvPyObject(ToPyBool(valid ? _middleclicked : false)));
}
if(_applicableState & MV_STATE_VISIBLE) PyDict_SetItemString(dict, "visible", mvPyObject(ToPyBool(valid ? _visible : false)));
if(_applicableState & MV_STATE_EDITED) PyDict_SetItemString(dict, "edited", mvPyObject(ToPyBool(valid ? _edited : false)));
if(_applicableState & MV_STATE_ACTIVATED) PyDict_SetItemString(dict, "activated", mvPyObject(ToPyBool(valid ? _activated : false)));
if(_applicableState & MV_STATE_DEACTIVATED) PyDict_SetItemString(dict, "deactivated", mvPyObject(ToPyBool(valid ? _deactivated : false)));
if(_applicableState & MV_STATE_DEACTIVATEDAE) PyDict_SetItemString(dict, "deactivated_after_edit", mvPyObject(ToPyBool(valid ? _deactivatedAfterEdit : false)));
if(_applicableState & MV_STATE_TOGGLED_OPEN) PyDict_SetItemString(dict, "toggled_open", mvPyObject(ToPyBool(valid ? _toggledOpen : false)));
if(_applicableState & MV_STATE_RECT_MIN) PyDict_SetItemString(dict, "rect_min", mvPyObject(ToPyPairII(_rectMin.x, _rectMin.y)));
if(_applicableState & MV_STATE_RECT_MAX) PyDict_SetItemString(dict, "rect_max", mvPyObject(ToPyPairII(_rectMax.x, _rectMax.y)));
if(_applicableState & MV_STATE_RECT_SIZE) PyDict_SetItemString(dict, "rect_size", mvPyObject(ToPyPairII(_rectSize.x, _rectSize.y)));
if(_applicableState & MV_STATE_CONT_AVAIL) PyDict_SetItemString(dict, "content_region_avail", mvPyObject(ToPyPairII(_contextRegionAvail.x, _contextRegionAvail.y)));
}
bool mvAppItemState::isItemHovered(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _hovered;
}
bool mvAppItemState::isItemActive(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _active;
}
bool mvAppItemState::isItemFocused(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _focused;
}
bool mvAppItemState::isItemLeftClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _leftclicked;
}
bool mvAppItemState::isItemRightClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _rightclicked;
}
bool mvAppItemState::isItemMiddleClicked(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _middleclicked;
}
bool mvAppItemState::isItemVisible(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _visible;
}
bool mvAppItemState::isItemEdited(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _edited;
}
bool mvAppItemState::isItemActivated(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _activated;
}
bool mvAppItemState::isItemDeactivated(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _deactivated;
}
bool mvAppItemState::isItemDeactivatedAfterEdit(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _deactivatedAfterEdit;
}
bool mvAppItemState::isItemToogledOpen(int frameDelay) const
{
if (_lastFrameUpdate + frameDelay != mvApp::s_frame)
return false;
return _toggledOpen;
}
bool mvAppItemState::isOk() const
{
return _ok;
}
mvVec2 mvAppItemState::getItemRectMin() const
{
return _rectMin;
}
mvVec2 mvAppItemState::getItemRectMax() const
{
return _rectMax;
}
mvVec2 mvAppItemState::getItemRectSize() const
{
return _rectSize;
}
mvVec2 mvAppItemState::getItemPos() const
{
return _pos;
}
mvVec2 mvAppItemState::getContextRegionAvail() const
{
return _contextRegionAvail;
}
} | 7,122 | 2,349 |
/******************************************************************************
Helper methods, including configuration management.
Author: Noah Strong
Project: Crab Tracker
Created: 2018-02-19
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "config.h"
/******************************************************************************
CONFIGURATION FUNCTIONS AND VARIABLES
Configuration works as follows: on program startup, the initalize() function
should be called. This will look for and load the `.conf` file whose location
is specificed in CONFIG.H (generally `/etc/crab-tracker.conf`). The .conf file
will be parsed and any key/value pairs whose keys we expect to see will be
read in and saved. The keys we "expect to see" are those that are listed in the
entries[] array below. Initially, entries[] contains the default values for all
parameters we expect to come across; unless new values for those parameters are
found in the .conf file, those values will be used.
******************************************************************************/
/* Basically a key/value store for configuration options */
struct config_entry{
const char* param;
int value;
int isset;
};
/* An exhaustive set of all configuration options. Default values given here */
config_entry entries[] = { {"DISPLAY_PINGS", 1, 0},
{"DISPLAY_RAW_SPI", 0, 0},
{"R_USER", 1, 0},
{"HPHONE_DIST_CM", 300, 0}};
int num_entries = sizeof(entries) / sizeof(config_entry);
/**
* "Public" way for getting a configuration. Looks through entries and returns
* (via an out param) the value of that config option.
* @param param The name of the parameter to look for
* @param result The value of the parameter, if found [OUT PARAM]
* @return 1 if param was found, else 0
*/
int get_param(char* param, int* result){
for(int i=0; i<num_entries; i++){
if(!strcmp(param, entries[i].param)){
*result = entries[i].value;
return 1;
}
}
return 0;
}
/* Rather than include math.h, here's a quick integer min() */
int min(int a, int b){ return a > b ? b : a; }
/**
* Loads the .conf file on the machine and then stores the values of any known
* configuration parameters.
* @return 0 if config loaded successfully, else 1.
*/
int initialize_util(){
printf("Loading configuration... ");
FILE* fp;
char* line = NULL;
char buf[120];
size_t linecap = 0;
ssize_t len;
int n, m, n_found = 0, int_param = 0;
/* Load the `.conf` file, if it exists */
fp = fopen(CONFIG_FILE_PATH, "r");
if (fp == NULL){
perror("fopen");
fprintf(stderr, "Unable to load configuration file\n");
return 1;
}
/* Now we go through every line in the config file */
while ((len = getline(&line, &linecap, fp)) != -1) {
for(int i=0; i<len; i++){
/* Strip out comments (denoted by a hash (#)) */
if(line[i] == '#'){ line[i] = '\0'; i=len; };
}
/* See if any of our parameters are found in this line */
for(int j=0; j<num_entries; j++){
/* Set `buf = entries[j].param + " %d";` */
m = min(strlen(entries[j].param), 115);
strncpy(buf, entries[j].param, m);
strcpy(&buf[m], " %d\0");
n = sscanf(line, buf, &int_param);
if(n > 0){
/* Found the parameter! Store it */
n_found++;
entries[j].value = int_param;
entries[j].isset = 1;
j = num_entries; /* Break out of loop early */
}
}
}
/* Clean up! */
fclose(fp);
if (line) free(line);
printf("successfully read %d configuration parameters\n", n_found);
return 0;
}
/******************************************************************************
DISPLAY AND OTHER HELPER FUNCTIONS
These are mostly simple helper functions, such as binary print functions.
******************************************************************************/
/**
* Print a 32-bit number as binary.
* Written by Zach McGrew (WWU Comptuer Science Graduate Student)
* @param number The number to print
*/
void print_bin(int32_t number) {
uint32_t bit_set = (uint32_t) 1 << 31;
int32_t bit_pos;
for (bit_pos = 31; bit_pos >= 0; --bit_pos, bit_set >>= 1) {
printf("%c", ((uint32_t)number & bit_set ? '1' : '0'));
}
}
/**
* Print an 8-bit unsigned integer in binary to stdout.
* @param number The number (UNSIGNED) to print
*/
void print_bin_8(uint8_t number){
uint8_t bit_set = (uint8_t) 1 << 7;
int bit_pos;
for(bit_pos = 7; bit_pos >= 0; --bit_pos){
printf("%c", ((uint8_t)number & bit_set ? '1' : '0'));
bit_set >>= 1;
}
}
/**
* Print a long unsigned integer in binary to stdout.
* @param number The number (UNSIGNED) to print
*/
void print_bin_ulong(unsigned long number){
unsigned long bit_set = (unsigned long) 1 << 31;
int bit_pos;
for(bit_pos = 31; bit_pos >= 0; --bit_pos){
printf("%c", (number & bit_set ? '1' : '0'));
bit_set >>= 1;
}
}
| 5,366 | 1,682 |
/* Common logging functionality.
author: andreasl
*/
#pragma once
#include <ostream>
namespace barn {
namespace bbm {
/* Severity levels for logging.*/
enum Severity {
INFO,
WARN,
ERROR
};
/* Write a log message to console.*/
std::ostream& log(const Severity level);
} // namespace bbm
} // namespace barn
| 324 | 103 |
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: WSQ - Grayscale Image Compression
FILE: UTIL.C
AUTHORS: Craig Watson
Michael Garris
DATE: 11/24/1999
UPDATED: 02/24/2005 by MDG
Contains gernal routines responsible for supporting WSQ
image compression.
ROUTINES:
#cat: conv_img_2_flt_ret - Converts an image's unsigned character pixels
#cat: to floating point values in the range +/- 128.0.
#cat: Returns on error.
#cat: conv_img_2_flt - Converts an image's unsigned character pixels
#cat: to floating point values in the range +/- 128.0.
#cat: conv_img_2_uchar - Converts an image's floating point pixels
#cat: unsigned character pixels.
#cat: variance - Calculates the variances within image subbands.
#cat:
#cat: quantize - Quantizes the image's wavelet subbands.
#cat:
#cat: quant_block_sizes - Quantizes an image's subband block.
#cat:
#cat: unquantize - Unquantizes an image's wavelet subbands.
#cat:
#cat: wsq_decompose - Computes the wavelet decomposition of an input image.
#cat:
#cat: get_lets - Compute the wavelet subband decomposition for the image.
#cat:
#cat: wsq_reconstruct - Reconstructs a lossy floating point pixmap from
#cat: a WSQ compressed datastream.
#cat: join_lets - Reconstruct the image from the wavelet subbands.
#cat:
#cat: int_sign - Get the sign of the sythesis filter coefficients.
#cat:
#cat: image_size - Computes the size in bytes of a WSQ compressed image
#cat: file, including headers, tables, and parameters.
#cat: init_wsq_decoder_resources - Initializes memory resources used by the
#cat: WSQ decoder
#cat: free_wsq_decoder_resources - Deallocates memory resources used by the
#cat: WSQ decoder
***********************************************************************/
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <wsq.h>
#include <defs.h>
#include <dataio.h>
/******************************************************************/
/* The routines in this file do numerous things */
/* related to the WSQ algorithm such as: */
/* converting the image data from unsigned char */
/* to float and integer to unsigned char, */
/* splitting the image into the subbands as well */
/* the rejoining process, subband variance */
/* calculations, and quantization. */
/******************************************************************/
/******************************************************************/
/* This routine converts the unsigned char data to float. In the */
/* process it shifts and scales the data so the values range from */
/* +/- 128.0 This function returns on error. */
/******************************************************************/
int conv_img_2_flt_ret(
float *fip, /* output float image data */
float *m_shift, /* shifting parameter */
float *r_scale, /* scaling parameter */
unsigned char *data, /* input unsigned char data */
const int num_pix) /* num pixels in image */
{
int cnt; /* pixel cnt */
unsigned int sum, overflow; /* sum of pixel values */
float mean; /* mean pixel value */
int low, high; /* low/high pixel values */
float low_diff, high_diff; /* new low/high pixels values shifting */
sum = 0;
overflow = 0;
low = 255;
high = 0;
for(cnt = 0; cnt < num_pix; cnt++) {
if(data[cnt] > high)
high = data[cnt];
if(data[cnt] < low)
low = data[cnt];
sum += data[cnt];
if(sum < overflow) {
fprintf(stderr, "ERROR: conv_img_2_flt: overflow at %d\n", cnt);
return(-91);
}
overflow = sum;
}
mean = (float) sum / (float)num_pix;
*m_shift = mean;
low_diff = *m_shift - low;
high_diff = high - *m_shift;
if(low_diff >= high_diff)
*r_scale = low_diff;
else
*r_scale = high_diff;
*r_scale /= (float)128.0;
for(cnt = 0; cnt < num_pix; cnt++) {
fip[cnt] = ((float)data[cnt] - *m_shift) / *r_scale;
}
return(0);
}
/******************************************************************/
/* This routine converts the unsigned char data to float. In the */
/* process it shifts and scales the data so the values range from */
/* +/- 128.0 */
/******************************************************************/
void conv_img_2_flt(
float *fip, /* output float image data */
float *m_shift, /* shifting parameter */
float *r_scale, /* scaling parameter */
unsigned char *data, /* input unsigned char data */
const int num_pix) /* num pixels in image */
{
int cnt; /* pixel cnt */
unsigned int sum, overflow; /* sum of pixel values */
float mean; /* mean pixel value */
int low, high; /* low/high pixel values */
float low_diff, high_diff; /* new low/high pixels values shifting */
sum = 0;
overflow = 0;
low = 255;
high = 0;
for(cnt = 0; cnt < num_pix; cnt++) {
if(data[cnt] > high)
high = data[cnt];
if(data[cnt] < low)
low = data[cnt];
sum += data[cnt];
if(sum < overflow) {
fprintf(stderr, "ERROR: conv_img_2_flt: overflow at pixel %d\n", cnt);
exit(-1);
}
overflow = sum;
}
mean = (float) sum / (float)num_pix;
*m_shift = mean;
low_diff = *m_shift - low;
high_diff = high - *m_shift;
if(low_diff >= high_diff)
*r_scale = low_diff;
else
*r_scale = high_diff;
*r_scale /= (float)128.0;
for(cnt = 0; cnt < num_pix; cnt++) {
fip[cnt] = ((float)data[cnt] - *m_shift) / *r_scale;
}
}
/*********************************************************/
/* Routine to convert image from float to unsigned char. */
/*********************************************************/
void conv_img_2_uchar(
unsigned char *data, /* uchar image pointer */
float *img, /* image pointer */
const int width, /* image width */
const int height, /* image height */
const float m_shift, /* shifting parameter */
const float r_scale) /* scaling parameter */
{
int r, c; /* row/column counters */
float img_tmp; /* temp image data store */
for (r = 0; r < height; r++) {
for (c = 0; c < width; c++) {
img_tmp = (*img * r_scale) + m_shift;
img_tmp += 0.5;
if (img_tmp < 0.0)
*data = 0; /* neg pix poss after quantization */
else if (img_tmp > 255.0)
*data = 255;
else
*data = (unsigned char)img_tmp;
++img;
++data;
}
}
}
/**********************************************************/
/* This routine calculates the variances of the subbands. */
/**********************************************************/
void variance(
QUANT_VALS *quant_vals, /* quantization parameters */
Q_TREE q_tree[], /* quantization "tree" */
const int q_treelen, /* length of q_tree */
float *fip, /* image pointer */
const int width, /* image width */
const int height) /* image height */
{
float *fp; /* temp image pointer */
int cvr; /* subband counter */
int lenx = 0, leny = 0; /* dimensions of area to calculate variance */
int skipx, skipy; /* pixels to skip to get to area for
variance calculation */
int row, col; /* dimension counters */
float ssq; /* sum of squares */
float sum2; /* variance calculation parameter */
float sum_pix; /* sum of pixels */
float vsum; /* variance sum for subbands 0-3 */
vsum = 0.0;
for(cvr = 0; cvr < 4; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
skipx = q_tree[cvr].lenx / 8;
skipy = (9 * q_tree[cvr].leny)/32;
lenx = (3 * q_tree[cvr].lenx)/4;
leny = (7 * q_tree[cvr].leny)/16;
fp += (skipy * width) + skipx;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
vsum += quant_vals->var[cvr];
}
if(vsum < 20000.0) {
for(cvr = 0; cvr < NUM_SUBBANDS; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
lenx = q_tree[cvr].lenx;
leny = q_tree[cvr].leny;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
}
}
else {
for(cvr = 4; cvr < NUM_SUBBANDS; cvr++) {
fp = fip + (q_tree[cvr].y * width) + q_tree[cvr].x;
ssq = 0.0;
sum_pix = 0.0;
skipx = q_tree[cvr].lenx / 8;
skipy = (9 * q_tree[cvr].leny)/32;
lenx = (3 * q_tree[cvr].lenx)/4;
leny = (7 * q_tree[cvr].leny)/16;
fp += (skipy * width) + skipx;
for(row = 0; row < leny; row++, fp += (width - lenx)) {
for(col = 0; col < lenx; col++) {
sum_pix += *fp;
ssq += *fp * *fp;
fp++;
}
}
sum2 = (sum_pix * sum_pix)/(lenx * leny);
quant_vals->var[cvr] = (float)((ssq - sum2)/((lenx * leny)-1.0));
}
}
}
/************************************************/
/* This routine quantizes the wavelet subbands. */
/************************************************/
int quantize(
short **osip, /* quantized output */
int *ocmp_siz, /* size of quantized output */
QUANT_VALS *quant_vals, /* quantization parameters */
Q_TREE q_tree[], /* quantization "tree" */
const int q_treelen, /* size of q_tree */
float *fip, /* floating point image pointer */
const int width, /* image width */
const int height) /* image height */
{
int i; /* temp counter */
int j; /* interation index */
float *fptr; /* temp image pointer */
short *sip, *sptr; /* pointers to quantized image */
int row, col; /* temp image characteristic parameters */
int cnt; /* subband counter */
float zbin; /* zero bin size */
float A[NUM_SUBBANDS]; /* subband "weights" for quantization */
float m[NUM_SUBBANDS]; /* subband size to image size ratios */
/* (reciprocal of FBI spec for 'm') */
float m1, m2, m3; /* reciprocal constants for 'm' */
float sigma[NUM_SUBBANDS]; /* square root of subband variances */
int K0[NUM_SUBBANDS]; /* initial list of subbands w/variance >= thresh */
int K1[NUM_SUBBANDS]; /* working list of subbands */
int *K, *nK; /* pointers to sets of subbands */
int NP[NUM_SUBBANDS]; /* current subbounds with nonpositive bit rates. */
int K0len; /* number of subbands in K0 */
int Klen, nKlen; /* number of subbands in other subband lists */
int NPlen; /* number of subbands flagged in NP */
float S; /* current frac of subbands w/positive bit rate */
float q; /* current proportionality constant */
float P; /* product of 'q/Q' ratios */
/* Set up 'A' table. */
for(cnt = 0; cnt < STRT_SUBBAND_3; cnt++)
A[cnt] = 1.0;
A[cnt++ /*52*/] = 1.32;
A[cnt++ /*53*/] = 1.08;
A[cnt++ /*54*/] = 1.42;
A[cnt++ /*55*/] = 1.08;
A[cnt++ /*56*/] = 1.32;
A[cnt++ /*57*/] = 1.42;
A[cnt++ /*58*/] = 1.08;
A[cnt++ /*59*/] = 1.08;
for(cnt = 0; cnt < MAX_SUBBANDS; cnt++) {
quant_vals->qbss[cnt] = 0.0;
quant_vals->qzbs[cnt] = 0.0;
}
/* Set up 'Q1' (prime) table. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(quant_vals->var[cnt] < VARIANCE_THRESH)
quant_vals->qbss[cnt] = 0.0;
else
/* NOTE: q has been taken out of the denominator in the next */
/* 2 formulas from the original code. */
if(cnt < STRT_SIZE_REGION_2 /*4*/)
quant_vals->qbss[cnt] = 1.0;
else
quant_vals->qbss[cnt] = 10.0 / (A[cnt] *
(float)log(quant_vals->var[cnt]));
}
/* Set up output buffer. */
if((sip = (short *) calloc(width*height, sizeof(short))) == NULL) {
fprintf(stderr,"ERROR : quantize : calloc : sip\n");
return(-90);
}
sptr = sip;
/* Set up 'm' table (these values are the reciprocal of 'm' in */
/* the FBI spec). */
m1 = 1.0/1024.0;
m2 = 1.0/256.0;
m3 = 1.0/16.0;
for(cnt = 0; cnt < STRT_SIZE_REGION_2; cnt++)
m[cnt] = m1;
for(cnt = STRT_SIZE_REGION_2; cnt < STRT_SIZE_REGION_3; cnt++)
m[cnt] = m2;
for(cnt = STRT_SIZE_REGION_3; cnt < NUM_SUBBANDS; cnt++)
m[cnt] = m3;
j = 0;
/* Initialize 'K0' and 'K1' lists. */
K0len = 0;
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++){
if(quant_vals->var[cnt] >= VARIANCE_THRESH){
K0[K0len] = cnt;
K1[K0len++] = cnt;
/* Compute square root of subband variance. */
sigma[cnt] = sqrt(quant_vals->var[cnt]);
}
}
K = K1;
Klen = K0len;
while(1){
/* Compute new 'S' */
S = 0.0;
for(i = 0; i < Klen; i++){
/* Remeber 'm' is the reciprocal of spec. */
S += m[K[i]];
}
/* Compute product 'P' */
P = 1.0;
for(i = 0; i < Klen; i++){
/* Remeber 'm' is the reciprocal of spec. */
P *= pow((sigma[K[i]] / quant_vals->qbss[K[i]]), m[K[i]]);
}
/* Compute new 'q' */
q = (pow(2.0f,(float)((quant_vals->r/S)-1.0))/2.5) / pow(P, (float)(1.0/S));
/* Flag subbands with non-positive bitrate. */
memset(NP, 0, NUM_SUBBANDS * sizeof(int));
NPlen = 0;
for(i = 0; i < Klen; i++){
if((quant_vals->qbss[K[i]] / q) >= (5.0*sigma[K[i]])){
NP[K[i]] = TRUE;
NPlen++;
}
}
/* If list of subbands with non-positive bitrate is empty ... */
if(NPlen == 0){
/* Then we are done, so break from while loop. */
break;
}
/* Assign new subband set to previous set K minus subbands in set NP. */
nK = K1;
nKlen = 0;
for(i = 0; i < Klen; i++){
if(!NP[K[i]])
nK[nKlen++] = K[i];
}
/* Assign new set as K. */
K = nK;
Klen = nKlen;
/* Bump iteration counter. */
j++;
}
/* Flag subbands that are in set 'K0' (the very first set). */
nK = K1;
memset(nK, 0, NUM_SUBBANDS * sizeof(int));
for(i = 0; i < K0len; i++){
nK[K0[i]] = TRUE;
}
/* Set 'Q' values. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(nK[cnt])
quant_vals->qbss[cnt] /= q;
else
quant_vals->qbss[cnt] = 0.0;
quant_vals->qzbs[cnt] = 1.2 * quant_vals->qbss[cnt];
}
/* Now ready to compute and store bin widths for subbands. */
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
fptr = fip + (q_tree[cnt].y * width) + q_tree[cnt].x;
if(quant_vals->qbss[cnt] != 0.0) {
zbin = quant_vals->qzbs[cnt] / 2.0;
for(row = 0;
row < q_tree[cnt].leny;
row++, fptr += width - q_tree[cnt].lenx){
for(col = 0; col < q_tree[cnt].lenx; col++) {
if(-zbin <= *fptr && *fptr <= zbin)
*sptr = 0;
else if(*fptr > 0.0)
*sptr = (short)(((*fptr-zbin)/quant_vals->qbss[cnt]) + 1.0);
else
*sptr = (short)(((*fptr+zbin)/quant_vals->qbss[cnt]) - 1.0);
sptr++;
fptr++;
}
}
}
else if(debug > 0)
fprintf(stderr, "%d -> %3.6f\n", cnt, quant_vals->qbss[cnt]);
}
*osip = sip;
*ocmp_siz = sptr - sip;
return(0);
}
/************************************************************************/
/* Compute quantized WSQ subband block sizes. */
/************************************************************************/
void quant_block_sizes(int *oqsize1, int *oqsize2, int *oqsize3,
QUANT_VALS *quant_vals,
W_TREE w_tree[], const int w_treelen,
Q_TREE q_tree[], const int q_treelen)
{
int qsize1, qsize2, qsize3;
int node;
/* Compute temporary sizes of 3 WSQ subband blocks. */
qsize1 = w_tree[14].lenx * w_tree[14].leny;
qsize2 = (w_tree[5].leny * w_tree[1].lenx) +
(w_tree[4].lenx * w_tree[4].leny);
qsize3 = (w_tree[2].lenx * w_tree[2].leny) +
(w_tree[3].lenx * w_tree[3].leny);
/* Adjust size of quantized WSQ subband blocks. */
for (node = 0; node < STRT_SUBBAND_2; node++)
if(quant_vals->qbss[node] == 0.0)
qsize1 -= (q_tree[node].lenx * q_tree[node].leny);
for (node = STRT_SUBBAND_2; node < STRT_SUBBAND_3; node++)
if(quant_vals->qbss[node] == 0.0)
qsize2 -= (q_tree[node].lenx * q_tree[node].leny);
for (node = STRT_SUBBAND_3; node < STRT_SUBBAND_DEL; node++)
if(quant_vals->qbss[node] == 0.0)
qsize3 -= (q_tree[node].lenx * q_tree[node].leny);
*oqsize1 = qsize1;
*oqsize2 = qsize2;
*oqsize3 = qsize3;
}
/*************************************/
/* Routine to unquantize image data. */
/*************************************/
int unquantize(
float **ofip, /* floating point image pointer */
const DQT_TABLE *dqt_table, /* quantization table structure */
Q_TREE q_tree[], /* quantization table structure */
const int q_treelen, /* size of q_tree */
short *sip, /* quantized image pointer */
const int width, /* image width */
const int height) /* image height */
{
float *fip; /* floating point image */
int row, col; /* cover counter and row/column counters */
float C; /* quantizer bin center */
float *fptr; /* image pointers */
short *sptr;
int cnt; /* subband counter */
if((fip = (float *) calloc(width*height, sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : unquantize : calloc : fip\n");
return(-91);
}
if(dqt_table->dqt_def != 1) {
fprintf(stderr,
"ERROR: unquantize : quantization table parameters not defined!\n");
return(-92);
}
sptr = sip;
C = dqt_table->bin_center;
for(cnt = 0; cnt < NUM_SUBBANDS; cnt++) {
if(dqt_table->q_bin[cnt] == 0.0)
continue;
fptr = fip + (q_tree[cnt].y * width) + q_tree[cnt].x;
for(row = 0;
row < q_tree[cnt].leny;
row++, fptr += width - q_tree[cnt].lenx){
for(col = 0; col < q_tree[cnt].lenx; col++) {
if(*sptr == 0)
*fptr = 0.0;
else if(*sptr > 0)
*fptr = (dqt_table->q_bin[cnt] * ((float)*sptr - C))
+ (dqt_table->z_bin[cnt] / 2.0);
else if(*sptr < 0)
*fptr = (dqt_table->q_bin[cnt] * ((float)*sptr + C))
- (dqt_table->z_bin[cnt] / 2.0);
else {
fprintf(stderr,
"ERROR : unquantize : invalid quantization pixel value\n");
return(-93);
}
fptr++;
sptr++;
}
}
}
*ofip = fip;
return(0);
}
/************************************************************************/
/* WSQ decompose the image. NOTE: this routine modifies and returns */
/* the results in "fdata". */
/************************************************************************/
int wsq_decompose(float *fdata, const int width, const int height,
W_TREE w_tree[], const int w_treelen,
float *hifilt, const int hisz,
float *lofilt, const int losz)
{
int num_pix, node;
float *fdata1, *fdata_bse;
num_pix = width * height;
/* Allocate temporary floating point pixmap. */
if((fdata1 = (float *) malloc(num_pix*sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : wsq_decompose : malloc : fdata1\n");
return(-94);
}
/* Compute the Wavelet image decomposition. */
for(node = 0; node < w_treelen; node++) {
fdata_bse = fdata + (w_tree[node].y * width) + w_tree[node].x;
get_lets(fdata1, fdata_bse, w_tree[node].leny, w_tree[node].lenx,
width, 1, hifilt, hisz, lofilt, losz, w_tree[node].inv_rw);
get_lets(fdata_bse, fdata1, w_tree[node].lenx, w_tree[node].leny,
1, width, hifilt, hisz, lofilt, losz, w_tree[node].inv_cl);
}
free(fdata1);
return(0);
}
/************************************************************/
/************************************************************/
void get_lets(
float *ne, /* image pointers for creating subband splits */
float *old,
const int len1, /* temporary length parameters */
const int len2,
const int pitch, /* pitch gives next row_col to filter */
const int stride, /* stride gives next pixel to filter */
float *hi,
const int hsz, /* NEW */
float *lo, /* filter coefficients */
const int lsz, /* NEW */
const int inv) /* spectral inversion? */
{
float *lopass, *hipass; /* pointers of where to put lopass
and hipass filter outputs */
float *p0,*p1; /* pointers to image pixels used */
int pix, rw_cl; /* pixel counter and row/column counter */
int i, da_ev; /* even or odd row/column of pixels */
int fi_ev;
int loc, hoc, nstr, pstr;
int llen, hlen;
int lpxstr, lspxstr;
float *lpx, *lspx;
int hpxstr, hspxstr;
float *hpx, *hspx;
int olle, ohle;
int olre, ohre;
int lle, lle2;
int lre, lre2;
int hle, hle2;
int hre, hre2;
da_ev = len2 % 2;
fi_ev = lsz % 2;
if(fi_ev) {
loc = (lsz-1)/2;
hoc = (hsz-1)/2 - 1;
olle = 0;
ohle = 0;
olre = 0;
ohre = 0;
}
else {
loc = lsz/2 - 2;
hoc = hsz/2 - 2;
olle = 1;
ohle = 1;
olre = 1;
ohre = 1;
if(loc == -1) {
loc = 0;
olle = 0;
}
if(hoc == -1) {
hoc = 0;
ohle = 0;
}
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
pstr = stride;
nstr = -pstr;
if(da_ev) {
llen = (len2+1)/2;
hlen = llen - 1;
}
else {
llen = len2/2;
hlen = llen;
}
for(rw_cl = 0; rw_cl < len1; rw_cl++) {
if(inv) {
hipass = ne + rw_cl * pitch;
lopass = hipass + hlen * stride;
}
else {
lopass = ne + rw_cl * pitch;
hipass = lopass + llen * stride;
}
p0 = old + rw_cl * pitch;
p1 = p0 + (len2-1) * stride;
lspx = p0 + (loc * stride);
lspxstr = nstr;
lle2 = olle;
lre2 = olre;
hspx = p0 + (hoc * stride);
hspxstr = nstr;
hle2 = ohle;
hre2 = ohre;
for(pix = 0; pix < hlen; pix++) {
lpxstr = lspxstr;
lpx = lspx;
lle = lle2;
lre = lre2;
*lopass = *lpx * lo[0];
for(i = 1; i < lsz; i++) {
if(lpx == p0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == p1){
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*lopass += *lpx * lo[i];
}
lopass += stride;
hpxstr = hspxstr;
hpx = hspx;
hle = hle2;
hre = hre2;
*hipass = *hpx * hi[0];
for(i = 1; i < hsz; i++) {
if(hpx == p0){
if(hle) {
hpxstr = 0;
hle = 0;
}
else
hpxstr = pstr;
}
if(hpx == p1){
if(hre) {
hpxstr = 0;
hre = 0;
}
else
hpxstr = nstr;
}
hpx += hpxstr;
*hipass += *hpx * hi[i];
}
hipass += stride;
for(i = 0; i < 2; i++) {
if(lspx == p0){
if(lle2) {
lspxstr = 0;
lle2 = 0;
}
else
lspxstr = pstr;
}
lspx += lspxstr;
if(hspx == p0){
if(hle2) {
hspxstr = 0;
hle2 = 0;
}
else
hspxstr = pstr;
}
hspx += hspxstr;
}
}
if(da_ev) {
lpxstr = lspxstr;
lpx = lspx;
lle = lle2;
lre = lre2;
*lopass = *lpx * lo[0];
for(i = 1; i < lsz; i++) {
if(lpx == p0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == p1){
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*lopass += *lpx * lo[i];
}
lopass += stride;
}
}
if(!fi_ev) {
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
}
/************************************************************************/
/* WSQ reconstructs the image. NOTE: this routine modifies and returns */
/* the results in "fdata". */
/************************************************************************/
int wsq_reconstruct(float *fdata, const int width, const int height,
W_TREE w_tree[], const int w_treelen,
const DTT_TABLE *dtt_table)
{
int num_pix, node;
float *fdata1, *fdata_bse;
if(dtt_table->lodef != 1) {
fprintf(stderr,
"ERROR: wsq_reconstruct : Lopass filter coefficients not defined\n");
return(-95);
}
if(dtt_table->hidef != 1) {
fprintf(stderr,
"ERROR: wsq_reconstruct : Hipass filter coefficients not defined\n");
return(-96);
}
num_pix = width * height;
/* Allocate temporary floating point pixmap. */
if((fdata1 = (float *) malloc(num_pix*sizeof(float))) == NULL) {
fprintf(stderr,"ERROR : wsq_reconstruct : malloc : fdata1\n");
return(-97);
}
/* Reconstruct floating point pixmap from wavelet subband data. */
for (node = w_treelen - 1; node >= 0; node--) {
fdata_bse = fdata + (w_tree[node].y * width) + w_tree[node].x;
join_lets(fdata1, fdata_bse, w_tree[node].lenx, w_tree[node].leny,
1, width,
dtt_table->hifilt, dtt_table->hisz,
dtt_table->lofilt, dtt_table->losz,
w_tree[node].inv_cl);
join_lets(fdata_bse, fdata1, w_tree[node].leny, w_tree[node].lenx,
width, 1,
dtt_table->hifilt, dtt_table->hisz,
dtt_table->lofilt, dtt_table->losz,
w_tree[node].inv_rw);
}
free(fdata1);
return(0);
}
/****************************************************************/
void join_lets(
float *ne, /* image pointers for creating subband splits */
float *old,
const int len1, /* temporary length parameters */
const int len2,
const int pitch, /* pitch gives next row_col to filter */
const int stride, /* stride gives next pixel to filter */
float *hi,
const int hsz, /* NEW */
float *lo, /* filter coefficients */
const int lsz, /* NEW */
const int inv) /* spectral inversion? */
{
float *lp0, *lp1;
float *hp0, *hp1;
float *lopass, *hipass; /* lo/hi pass image pointers */
float *limg, *himg;
int pix, cl_rw; /* pixel counter and column/row counter */
int i, da_ev; /* if "scanline" is even or odd and */
int loc, hoc;
int hlen, llen;
int nstr, pstr;
int tap;
int fi_ev;
int olle, ohle, olre, ohre;
int lle, lle2, lre, lre2;
int hle, hle2, hre, hre2;
float *lpx, *lspx;
int lpxstr, lspxstr;
int lstap, lotap;
float *hpx, *hspx;
int hpxstr, hspxstr;
int hstap, hotap;
int asym, fhre = 0, ofhre;
float ssfac, osfac, sfac;
da_ev = len2 % 2;
fi_ev = lsz % 2;
pstr = stride;
nstr = -pstr;
if(da_ev) {
llen = (len2+1)/2;
hlen = llen - 1;
}
else {
llen = len2/2;
hlen = llen;
}
if(fi_ev) {
asym = 0;
ssfac = 1.0;
ofhre = 0;
loc = (lsz-1)/4;
hoc = (hsz+1)/4 - 1;
lotap = ((lsz-1)/2) % 2;
hotap = ((hsz+1)/2) % 2;
if(da_ev) {
olle = 0;
olre = 0;
ohle = 1;
ohre = 1;
}
else {
olle = 0;
olre = 1;
ohle = 1;
ohre = 0;
}
}
else {
asym = 1;
ssfac = -1.0;
ofhre = 2;
loc = lsz/4 - 1;
hoc = hsz/4 - 1;
lotap = (lsz/2) % 2;
hotap = (hsz/2) % 2;
if(da_ev) {
olle = 1;
olre = 0;
ohle = 1;
ohre = 1;
}
else {
olle = 1;
olre = 1;
ohle = 1;
ohre = 1;
}
if(loc == -1) {
loc = 0;
olle = 0;
}
if(hoc == -1) {
hoc = 0;
ohle = 0;
}
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
for (cl_rw = 0; cl_rw < len1; cl_rw++) {
limg = ne + cl_rw * pitch;
himg = limg;
*himg = 0.0;
*(himg + stride) = 0.0;
if(inv) {
hipass = old + cl_rw * pitch;
lopass = hipass + stride * hlen;
}
else {
lopass = old + cl_rw * pitch;
hipass = lopass + stride * llen;
}
lp0 = lopass;
lp1 = lp0 + (llen-1) * stride;
lspx = lp0 + (loc * stride);
lspxstr = nstr;
lstap = lotap;
lle2 = olle;
lre2 = olre;
hp0 = hipass;
hp1 = hp0 + (hlen-1) * stride;
hspx = hp0 + (hoc * stride);
hspxstr = nstr;
hstap = hotap;
hle2 = ohle;
hre2 = ohre;
osfac = ssfac;
for(pix = 0; pix < hlen; pix++) {
for(tap = lstap; tap >=0; tap--) {
lle = lle2;
lre = lre2;
lpx = lspx;
lpxstr = lspxstr;
*limg = *lpx * lo[tap];
for(i = tap+2; i < lsz; i += 2) {
if(lpx == lp0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == lp1) {
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*limg += *lpx * lo[i];
}
limg += stride;
}
if(lspx == lp0){
if(lle2) {
lspxstr = 0;
lle2 = 0;
}
else
lspxstr = pstr;
}
lspx += lspxstr;
lstap = 1;
for(tap = hstap; tap >=0; tap--) {
hle = hle2;
hre = hre2;
hpx = hspx;
hpxstr = hspxstr;
fhre = ofhre;
sfac = osfac;
for(i = tap; i < hsz; i += 2) {
if(hpx == hp0) {
if(hle) {
hpxstr = 0;
hle = 0;
}
else {
hpxstr = pstr;
sfac = 1.0;
}
}
if(hpx == hp1) {
if(hre) {
hpxstr = 0;
hre = 0;
if(asym && da_ev) {
hre = 1;
fhre--;
sfac = (float)fhre;
if(sfac == 0.0)
hre = 0;
}
}
else {
hpxstr = nstr;
if(asym)
sfac = -1.0;
}
}
*himg += *hpx * hi[i] * sfac;
hpx += hpxstr;
}
himg += stride;
}
if(hspx == hp0) {
if(hle2) {
hspxstr = 0;
hle2 = 0;
}
else {
hspxstr = pstr;
osfac = 1.0;
}
}
hspx += hspxstr;
hstap = 1;
}
if(da_ev)
if(lotap)
lstap = 1;
else
lstap = 0;
else
if(lotap)
lstap = 2;
else
lstap = 1;
for(tap = 1; tap >= lstap; tap--) {
lle = lle2;
lre = lre2;
lpx = lspx;
lpxstr = lspxstr;
*limg = *lpx * lo[tap];
for(i = tap+2; i < lsz; i += 2) {
if(lpx == lp0){
if(lle) {
lpxstr = 0;
lle = 0;
}
else
lpxstr = pstr;
}
if(lpx == lp1) {
if(lre) {
lpxstr = 0;
lre = 0;
}
else
lpxstr = nstr;
}
lpx += lpxstr;
*limg += *lpx * lo[i];
}
limg += stride;
}
if(da_ev) {
if(hotap)
hstap = 1;
else
hstap = 0;
if(hsz == 2) {
hspx -= hspxstr;
fhre = 1;
}
}
else
if(hotap)
hstap = 2;
else
hstap = 1;
for(tap = 1; tap >= hstap; tap--) {
hle = hle2;
hre = hre2;
hpx = hspx;
hpxstr = hspxstr;
sfac = osfac;
if(hsz != 2)
fhre = ofhre;
for(i = tap; i < hsz; i += 2) {
if(hpx == hp0) {
if(hle) {
hpxstr = 0;
hle = 0;
}
else {
hpxstr = pstr;
sfac = 1.0;
}
}
if(hpx == hp1) {
if(hre) {
hpxstr = 0;
hre = 0;
if(asym && da_ev) {
hre = 1;
fhre--;
sfac = (float)fhre;
if(sfac == 0.0)
hre = 0;
}
}
else {
hpxstr = nstr;
if(asym)
sfac = -1.0;
}
}
*himg += *hpx * hi[i] * sfac;
hpx += hpxstr;
}
himg += stride;
}
}
if(!fi_ev)
for(i = 0; i < hsz; i++)
hi[i] *= -1.0;
}
/*****************************************************/
/* Routine to execute an integer sign determination */
/*****************************************************/
int int_sign(
const int power) /* "sign" power */
{
int cnt, num = -1; /* counter and sign return value */
if(power == 0)
return 1;
for(cnt = 1; cnt < power; cnt++)
num *= -1;
return num;
}
/*************************************************************/
/* Computes size of compressed image file including headers, */
/* tables, and parameters. */
/*************************************************************/
int image_size(
const int blocklen, /* length of the compressed blocks */
short *huffbits1, /* huffman table parameters */
short *huffbits2)
{
int tot_size, cnt;
tot_size = blocklen; /* size of three compressed blocks */
tot_size += 58; /* size of transform table */
tot_size += 389; /* size of quantization table */
tot_size += 17; /* size of frame header */
tot_size += 3; /* size of block 1 */
tot_size += 3; /* size of block 2 */
tot_size += 3; /* size of block 3 */
tot_size += 3; /* size hufftable variable and hufftable number */
tot_size += 16; /* size of huffbits1 */
for(cnt = 1; cnt < 16; cnt ++)
tot_size += huffbits1[cnt]; /* size of huffvalues1 */
tot_size += 3; /* size hufftable variable and hufftable number */
tot_size += 16; /* size of huffbits1 */
for(cnt = 1; cnt < 16; cnt ++)
tot_size += huffbits2[cnt]; /* size of huffvalues2 */
tot_size += 20; /* SOI,SOF,SOB(3),DTT,DQT,DHT(2),EOI */
return tot_size;
}
/*************************************************************/
/* Added by MDG on 02-24-05 */
/* Initializes memory used by the WSQ decoder. */
/*************************************************************/
void init_wsq_decoder_resources()
{
/* Added 02-24-05 by MDG */
/* Init dymanically allocated members to NULL */
/* for proper memory management in: */
/* read_transform_table() */
/* getc_transform_table() */
/* free_wsq_resources() */
dtt_table.lofilt = (float *)NULL;
dtt_table.hifilt = (float *)NULL;
}
/*************************************************************/
/* Added by MDG on 02-24-05 */
/* Deallocates memory used by the WSQ decoder. */
/*************************************************************/
void free_wsq_decoder_resources()
{
if(dtt_table.lofilt != (float *)NULL){
free(dtt_table.lofilt);
dtt_table.lofilt = (float *)NULL;
}
if(dtt_table.hifilt != (float *)NULL){
free(dtt_table.hifilt);
dtt_table.hifilt = (float *)NULL;
}
}
/************************************************************************
#cat: delete_comments_wsq - Deletes all comments in a WSQ compressed file.
*************************************************************************/
/*****************************************************************/
int delete_comments_wsq(unsigned char **ocdata, int *oclen,
unsigned char *idata, const int ilen)
{
int ret, nlen, nalloc, stp;
unsigned short marker, length;
unsigned char m1, m2, *ndata, *cbufptr, *ebufptr;
nalloc = ilen;
/* Initialize current filled length to 0. */
nlen = 0;
/* Allocate new compressed byte stream. */
if((ndata = (unsigned char *)malloc(nalloc * sizeof(unsigned char)))
== (unsigned char *)NULL){
fprintf(stderr, "ERROR : delete_comments_wsq : malloc : ndata\n");
return(-2);
}
cbufptr = idata;
ebufptr = idata + ilen;
/* Parse SOI */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/* Copy SOI */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
/* Read Next Marker */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
while(marker != EOI_WSQ) {
if(marker != COM_WSQ) {
/* Copy Marker and Data */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = getc_ushort(&length, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/*
printf("Copying Marker %04X and Data (Length = %d)\n", marker, length);
*/
if((ret = putc_ushort(length, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = putc_bytes(cbufptr, length-2, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
cbufptr += (length-2);
if(marker == SOB_WSQ) {
stp = 0;
while(!stp) {
if((ret = getc_byte(&m1, &cbufptr, ebufptr))) {
free(ndata);
return(ret);
}
if(m1 == 0xFF) {
if((ret = getc_byte(&m2, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
if(m2 == 0x00) {
if((ret = putc_byte(m1, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
if((ret = putc_byte(m2, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
}
else {
cbufptr -= 2;
stp = 1;
}
}
else {
if((ret = putc_byte(m1, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
}
}
}
}
else {
/* Don't Copy Comments. Print to stdout. */
if((ret = getc_ushort(&length, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/*
printf("COMMENT (Length %d):\n", length-2);
for(i = 0; i < length-2; i++)
printf("%c", *(cbufptr+i));
printf("\n");
*/
cbufptr += length-2;
}
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
}
/* Copy EOI Marker */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
*ocdata = ndata;
*oclen = nlen;
return(0);
}
| 45,832 | 15,778 |
//===- WordLineDriver.hh --------------------------------------------------===//
//
// The CIM Hardware Simulator Project
//
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#pragma once
#include "types.hh"
#include "CrossBarArray.hh"
namespace cimHW {
class WordLineDriver {
public:
WordLineDriver(const unsigned maxWordlines, const unsigned integerLen, const unsigned fractionLen) noexcept;
void setInput(const VectorXnum &inputVector, const unsigned OUSize);
CrossBarArray::WordLineVector getNextWordLine();
virtual RowVectorXui quantize2TwoComplement(const numType x) const;
void reset();
private:
// basic property of a wordline driver
const unsigned m_maxWordlines;
const unsigned m_integerLen;
const unsigned m_fractionLen;
const unsigned m_nBits;
// internal cursor
unsigned m_wordlines;
unsigned m_bitsIndex;
unsigned m_OUSize;
unsigned m_OUIndex;
MatrixXuiRowMajor m_buffer;
};
} // namespace cimHW
| 1,291 | 325 |
/**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX SQL_ENG
#include "sql/engine/px/exchange/ob_px_repart_transmit.h"
#include "sql/dtl/ob_dtl_channel_group.h"
#include "sql/dtl/ob_dtl_rpc_channel.h"
#include "sql/executor/ob_range_hash_key_getter.h"
#include "sql/executor/ob_slice_calc.h"
using namespace oceanbase::common;
using namespace oceanbase::sql;
using namespace oceanbase::share::schema;
OB_SERIALIZE_MEMBER((ObPxRepartTransmitInput, ObPxTransmitInput));
//////////////////////////////////////////
ObPxRepartTransmit::ObPxRepartTransmitCtx::ObPxRepartTransmitCtx(ObExecContext& ctx)
: ObPxTransmit::ObPxTransmitCtx(ctx)
{}
ObPxRepartTransmit::ObPxRepartTransmitCtx::~ObPxRepartTransmitCtx()
{}
//////////////////////////////////////////
ObPxRepartTransmit::ObPxRepartTransmit(common::ObIAllocator& alloc) : ObPxTransmit(alloc)
{}
ObPxRepartTransmit::~ObPxRepartTransmit()
{}
int ObPxRepartTransmit::inner_open(ObExecContext& exec_ctx) const
{
int ret = OB_SUCCESS;
LOG_TRACE("Inner open px fifo transmit", "op_id", get_id());
if (OB_FAIL(ObPxTransmit::inner_open(exec_ctx))) {
LOG_WARN("initialize operator context failed", K(ret));
}
return ret;
}
int ObPxRepartTransmit::do_transmit(ObExecContext& exec_ctx) const
{
int ret = OB_SUCCESS;
ObPhysicalPlanCtx* phy_plan_ctx = NULL;
ObPxRepartTransmitInput* trans_input = NULL;
ObPxRepartTransmitCtx* transmit_ctx = NULL;
if (OB_ISNULL(phy_plan_ctx = GET_PHY_PLAN_CTX(exec_ctx)) ||
OB_ISNULL(trans_input = GET_PHY_OP_INPUT(ObPxRepartTransmitInput, exec_ctx, get_id())) ||
OB_ISNULL(transmit_ctx = GET_PHY_OPERATOR_CTX(ObPxRepartTransmitCtx, exec_ctx, get_id()))) {
LOG_ERROR("fail to op ctx", "op_id", get_id(), "op_type", get_type(), KP(trans_input), KP(transmit_ctx), K(ret));
} else if (!is_repart_exchange()) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("expect repart repartition", K(ret));
} else if (OB_INVALID_ID == repartition_table_id_) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("repartition table id should be set for repart transmit op", K(ret));
} else {
ObSchemaGetterGuard schema_guard;
const ObTableSchema* table_schema = NULL;
if (OB_FAIL(GCTX.schema_service_->get_tenant_schema_guard(
exec_ctx.get_my_session()->get_effective_tenant_id(), schema_guard))) {
LOG_WARN("faile to get schema guard", K(ret));
} else if (OB_FAIL(schema_guard.get_table_schema(repartition_table_id_, table_schema))) {
LOG_WARN("faile to get table schema", K(ret), K_(repartition_table_id));
} else if (OB_ISNULL(table_schema)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("table schema is null. repart sharding requires a table in dfo", K_(repartition_table_id), K(ret));
} else if (OB_FAIL(
trans_input->get_part_ch_map(transmit_ctx->part_ch_info_, phy_plan_ctx->get_timeout_timestamp()))) {
LOG_WARN("fail to get channel affinity map", K(ret));
} else {
if (get_dist_method() == ObPQDistributeMethod::PARTITION_RANDOM) {
// pkey random
ObRepartRandomSliceIdxCalc repart_slice_calc(exec_ctx,
*table_schema,
&repart_func_,
&repart_sub_func_,
&repart_columns_,
&repart_sub_columns_,
unmatch_row_dist_method_,
transmit_ctx->part_ch_info_,
repartition_type_);
if (OB_FAIL(do_repart_transmit(exec_ctx, repart_slice_calc))) {
LOG_WARN("failed to do repart transmit for pkey random", K(ret));
}
} else if (ObPQDistributeMethod::PARTITION_HASH == get_dist_method()) {
// pkey hash
ObSlaveMapPkeyHashIdxCalc repart_slice_calc(exec_ctx,
*table_schema,
&repart_func_,
&repart_sub_func_,
&repart_columns_,
&repart_sub_columns_,
unmatch_row_dist_method_,
transmit_ctx->task_channels_.count(),
transmit_ctx->part_ch_info_,
transmit_ctx->expr_ctx_,
hash_dist_columns_,
dist_exprs_,
repartition_type_);
if (OB_FAIL(do_repart_transmit(exec_ctx, repart_slice_calc))) {
LOG_WARN("failed to do repart transmit for pkey random", K(ret));
}
} else {
// pkey
ObAffinitizedRepartSliceIdxCalc repart_slice_calc(exec_ctx,
*table_schema,
&repart_func_,
&repart_sub_func_,
&repart_columns_,
&repart_sub_columns_,
unmatch_row_dist_method_,
transmit_ctx->task_channels_.count(),
transmit_ctx->part_ch_info_,
repartition_type_);
if (OB_FAIL(do_repart_transmit(exec_ctx, repart_slice_calc))) {
LOG_WARN("failed to do repart transmit for pkey", K(ret));
}
}
}
}
return ret;
}
int ObPxRepartTransmit::do_repart_transmit(ObExecContext& exec_ctx, ObRepartSliceIdxCalc& repart_slice_calc) const
{
int ret = OB_SUCCESS;
ObPxRepartTransmitCtx* transmit_ctx = NULL;
if (OB_ISNULL(transmit_ctx = GET_PHY_OPERATOR_CTX(ObPxRepartTransmitCtx, exec_ctx, get_id()))) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("transmit_ctx is null", K(ret));
}
if (OB_SUCC(ret)) {
// init the ObRepartSliceIdxCalc cache map
if (OB_FAIL(repart_slice_calc.init_partition_cache_map())) {
LOG_WARN("failed to repart_slice_calc init partiiton cache map", K(ret));
} else if (OB_FAIL(repart_slice_calc.init())) {
LOG_WARN("failed to init repart slice calc", K(ret));
} else if (OB_FAIL(send_rows(exec_ctx, *transmit_ctx, repart_slice_calc))) {
LOG_WARN("failed to send rows", K(ret));
}
}
int tmp_ret = OB_SUCCESS;
if (OB_SUCCESS != (tmp_ret = repart_slice_calc.destroy())) {
LOG_WARN("failed to destroy", K(tmp_ret));
if (OB_SUCC(ret)) {
ret = tmp_ret;
}
}
return ret;
}
int ObPxRepartTransmit::inner_close(ObExecContext& exec_ctx) const
{
return ObPxTransmit::inner_close(exec_ctx);
}
int ObPxRepartTransmit::init_op_ctx(ObExecContext& ctx) const
{
int ret = OB_SUCCESS;
ObPhyOperatorCtx* op_ctx = NULL;
if (OB_FAIL(CREATE_PHY_OPERATOR_CTX(ObPxRepartTransmitCtx, ctx, get_id(), get_type(), op_ctx))) {
LOG_WARN("fail to create phy op ctx", K(ret), K(get_id()), K(get_type()));
} else if (OB_ISNULL(op_ctx)) {
ret = OB_ERR_UNEXPECTED;
LOG_WARN("op ctx is NULL", K(ret));
} else if (OB_FAIL(init_cur_row(*op_ctx, has_partition_id_column_idx()))) {
LOG_WARN("fail to int cur row", K(ret));
}
return ret;
}
int ObPxRepartTransmit::create_operator_input(ObExecContext& ctx) const
{
int ret = OB_SUCCESS;
ObIPhyOperatorInput* input = NULL;
if (OB_FAIL(CREATE_PHY_OP_INPUT(ObPxRepartTransmitInput, ctx, get_id(), get_type(), input))) {
LOG_WARN("fail to create phy op input", K(ret), K(get_id()), K(get_type()));
}
UNUSED(input);
return ret;
}
int ObPxRepartTransmit::add_compute(ObColumnExpression* expr)
{
return ObPhyOperator::add_compute(expr);
}
| 7,518 | 2,798 |
/** \file
* \brief Implementation of class MaximumCPlanarSubgraph
*
* \author Karsten Klein
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/basic/basic.h>
#include <ogdf/cluster/MaximumCPlanarSubgraph.h>
#include <ogdf/cluster/CconnectClusterPlanar.h>
#include <ogdf/basic/simple_graph_alg.h>
#ifdef OGDF_CPLANAR_DEBUG_OUTPUT
#include <ogdf/fileformats/GraphIO.h>
#endif
using namespace abacus;
namespace ogdf {
using namespace cluster_planarity;
Module::ReturnType MaximumCPlanarSubgraph::doCall(const ClusterGraph &G,
const EdgeArray<int> *pCost,
List<edge> &delEdges,
List<NodePair> &addedEdges)
{
#ifdef OGDF_DEBUG
std::cout << "Creating new Masterproblem for clustergraph with " << G.constGraph().numberOfNodes() << " nodes\n";
#endif
MaxCPlanarMaster* cplanMaster = new MaxCPlanarMaster(G, pCost,
m_heuristicLevel,
m_heuristicRuns,
m_heuristicOEdgeBound,
m_heuristicNPermLists,
m_kuratowskiIterations,
m_subdivisions,
m_kSupportGraphs,
m_kuratowskiHigh,
m_kuratowskiLow,
m_perturbation,
m_branchingGap,
m_time.c_str(),
m_pricing,
m_checkCPlanar,
m_numAddVariables,
m_strongConstraintViolation,
m_strongVariableViolation);
cplanMaster->setPortaFile(m_portaOutput);
cplanMaster->useDefaultCutPool() = m_defaultCutPool;
#ifdef OGDF_DEBUG
std::cout << "Starting Optimization\n";
#endif
Master::STATUS status;
try {
status = cplanMaster->optimize();
}
catch (...)
{
#ifdef OGDF_DEBUG
std::cout << "ABACUS Optimization failed...\n";
#endif
}
m_totalTime = getDoubleTime(*cplanMaster->totalTime());
m_heurTime = getDoubleTime(*cplanMaster->improveTime());
m_sepTime = getDoubleTime(*cplanMaster->separationTime());
m_lpTime = getDoubleTime(*cplanMaster->lpTime());
m_lpSolverTime = getDoubleTime(*cplanMaster->lpSolverTime());
m_totalWTime = getDoubleTime(*cplanMaster->totalCowTime());
m_numKCons = cplanMaster->addedKConstraints();
m_numCCons = cplanMaster->addedCConstraints();
m_numLPs = cplanMaster->nLp();
m_numBCs = cplanMaster->nSub();
m_numSubSelected = cplanMaster->nSubSelected();
m_numVars = cplanMaster->nMaxVars()-cplanMaster->getNumInactiveVars();
#ifdef OGDF_DEBUG
m_solByHeuristic = cplanMaster->m_solByHeuristic;
#endif
#ifdef OGDF_DEBUG
if(cplanMaster->pricing())
Logger::slout() << "Pricing was ON\n";
Logger::slout() << "ABACUS returned with status '" << Master::STATUS_[status] << "'" << std::endl;
#endif
NodePairs allEdges;
cplanMaster->getDeletedEdges(delEdges);
cplanMaster->getConnectionOptimalSolutionEdges(addedEdges);
cplanMaster->getAllOptimalSolutionEdges(allEdges);
#ifdef OGDF_DEBUG
int delE = delEdges.size();
int addE = addedEdges.size();
std::cout << delE << " Number of deleted edges, " << addE << " Number of added edges " << allEdges.size() << " gesamt" << std::endl;
#endif
if (m_portaOutput)
{
writeFeasible(getPortaFileName(), *cplanMaster, status);
}
delete cplanMaster;
switch (status) {
case Master::Optimal: return Module::ReturnType::Optimal; break;
case Master::Error: return Module::ReturnType::Error; break;
default: break;
}
return Module::ReturnType::Error;
}
//returns list of all clusters in subtree at c in bottom up order
void MaximumCPlanarSubgraph::getBottomUpClusterList(const cluster c, List< cluster > & theList)
{
for(cluster cc : c->children) {
getBottomUpClusterList(cc, theList);
}
theList.pushBack(c);
}
//outputs the set of feasible solutions
void MaximumCPlanarSubgraph::writeFeasible(const char *filename,
MaxCPlanarMaster &master,
MaxCPlanarMaster::STATUS &status)
{
const ClusterGraph& CG = *(master.getClusterGraph());
const Graph& G = CG.constGraph();
//first compute the nodepairs that are potential candidates to connect
//chunks in a cluster
//potential connection edges
NodeArray< NodeArray<bool> > potConn(G);
for(node v : G.nodes)
{
potConn[v].init(G, false);
}
//we perform a bottom up cluster tree traversal
List< cluster > clist;
getBottomUpClusterList(CG.rootCluster(), clist);
//could use postordertraversal instead
NodePairs connPairs; //holds all connection node pairs
//counts the number of potential connectivity edges
//int potCount = 0; //equal to number of true values in potConn
//we run through the clusters and check connected components
//we consider all possible edges connecting CCs in a cluster,
//even if they may be connected by edges in a child cluster
//(to get the set of all feasible solutions)
for (cluster c : clist)
{
//we compute the subgraph induced by vertices in c
GraphCopy gcopy;
gcopy.createEmpty(G);
List<node> clusterNodes;
//would be more efficient if we would just merge the childrens' vertices
//and add c's
c->getClusterNodes(clusterNodes);
NodeArray<bool> activeNodes(G, false); //true for all cluster nodes
EdgeArray<edge> copyEdge(G); //holds the edge copy
for (node v : clusterNodes) {
activeNodes[v] = true;
}
gcopy.initByActiveNodes(clusterNodes, activeNodes, copyEdge);
//gcopy now represents the cluster induced subgraph
//we compute the connected components and store all nodepairs
//that connect two of them
NodeArray<int> component(gcopy);
connectedComponents(gcopy, component);
//now we run over all vertices and compare the component
//number of adjacent vertices. If they differ, we found a
//potential connection edge. We do not care if we find them twice.
for(node v : gcopy.nodes)
{
for(node w : gcopy.nodes)
{
if (component[v] != component[w])
{
std::cout << "Indizes: " << v->index() << ":" << w->index() << "\n";
node vg = gcopy.original(v);
node wg = gcopy.original(w);
bool newConn = !((vg->index() < wg->index()) ? potConn[vg][wg] : potConn[wg][vg]);
if (newConn)
{
NodePair np;
np.source = vg;
np.target = wg;
connPairs.pushBack(np);
if (vg->index() < wg->index())
potConn[vg][wg] = true;
else
potConn[wg][vg] = true;
}
}
}
}
}
std::cout << "Potentielle Verbindungskanten: "<< connPairs.size()<<"\n";
//we run through our candidates and save them in an array
//that can be used for dynamic graph updates
int i = 0;
struct connStruct {
bool connected;
node v1, v2;
edge e;
};
connStruct *cons = new connStruct[connPairs.size()];
for(const NodePair &np : connPairs)
{
connStruct cs;
cs.connected = false;
cs.v1 = np.source;
cs.v2 = np.target;
cs.e = nullptr;
cons[i] = cs;
i++;
}
// WARNING: this is extremely slow for graphs with a large number of cluster
// chunks now we test all possible connection edge combinations for c-planarity
Graph G2;
NodeArray<node> origNodes(CG.constGraph());
ClusterArray<cluster> origCluster(CG);
EdgeArray<edge> origEdges(CG.constGraph());
ClusterGraph testCopy(CG, G2, origCluster, origNodes, origEdges);
std::ofstream os(filename);
// Output dimension of the LP (number of variables)
os << "DIM = " << connPairs.size() << "\n";
os << "COMMENT\n";
switch (status) {
case Master::Optimal:
os << "Optimal \n\n"; break;
case Master::Error:
os << "Error \n\n"; break;
default:
os << "unknown \n\n";
}
for (i = 0; i < connPairs.size(); i++)
{
os << "Var " << i << ": " << origNodes[cons[i].v1]->index() << "->" << origNodes[cons[i].v2] << "\n";
}
os << "CONV_SECTION\n";
#ifdef OGDF_CPLANAR_DEBUG_OUTPUT
int writeCount = 0; //debug
#endif
if (connPairs.size() > 0)
while (true)
{
//we create the next test configuration by incrementing the edge selection array
//we create the corresponding graph dynamically on the fly
i = 0;
while (i < connPairs.size() && cons[i].connected)
{
cons[i].connected = false;
OGDF_ASSERT(cons[i].e != nullptr);
G2.delEdge(cons[i].e);
i++;
}
if (i >= connPairs.size()) break;
#if 0
std::cout<<"v1graph: "<<&(*(cons[i].v1->graphOf()))<<"\n";
std::cout<<"origNodesgraph: "<<&(*(origNodes.graphOf()))<<"\n";
#endif
cons[i].connected = true; //i.e., (false) will never be a feasible solution
cons[i].e = G2.newEdge(origNodes[cons[i].v1], origNodes[cons[i].v2]);
//and test it for c-planarity
CconnectClusterPlanar CCCP;
bool cplanar = CCCP.call(testCopy);
//c-planar graphs define a feasible solution
if (cplanar)
{
std::cout << "Feasible solution found\n";
for (int j = 0; j < connPairs.size(); j++)
{
char ch = (cons[j].connected ? '1' : '0');
std::cout << ch;
os << ch << " ";
}
std::cout << "\n";
os << "\n";
#ifdef OGDF_CPLANAR_DEBUG_OUTPUT
string fn = "cGraph";
fn += to_string(writeCount++) + ".gml";
GraphIO::writeGML(testCopy, fn);
#endif
}
}
delete[] cons;
os << "\nEND" <<"\n";
os.close();
#if 0
return;
#endif
os.open(getIeqFileName());
os << "DIM = " << m_numVars << "\n";
// Output the status as a comment
os << "COMMENT\n";
switch (status) {
case Master::Optimal:
os << "Optimal \n\n"; break;
case Master::Error:
os << "Error \n\n"; break;
default:
os << "unknown \n\n";
}
// In case 0 is not a valid solution, some PORTA functions need
//a valid solution in the ieq file
os << "VALID\n";
os << "\nLOWER_BOUNDS\n";
for (i = 0; i < m_numVars; i++) os << "0 ";
os << "\n";
os << "\nHIGHER_BOUNDS\n";
for (i = 0; i < m_numVars; i++) os << "1 ";
os << "\n";
os << "\nINEQUALITIES_SECTION\n";
//we first read the standard constraint that are written
//into a text file by the optimization master
std::ifstream isf(master.getStdConstraintsFileName());
if (!isf)
{
std::cerr << "Could not open optimization master's standard constraint file\n";
os << "#No standard constraints read\n";
}
else
{
char* fileLine = new char[maxConLength()];
while (isf.getline(fileLine, maxConLength()))
{
//skip commment lines
if (fileLine[0] == '#') continue;
int count = 1;
std::istringstream iss(fileLine);
char d;
bool rhs = false;
while (iss >> d)
{
if ( rhs || ( (d == '<') || (d == '>') || (d == '=') ) )
{
os << d;
rhs = true;
}
else
{
if (d != '0')
{
os <<"+"<< d <<"x"<<count;
}
count++;
}
}
os <<"\n";
}
delete[] fileLine;
}
//now we read the cut pools from the master
if (master.useDefaultCutPool())
{
os << "#No cut constraints read from master\n";
#if 0
StandardPool<Constraint, Variable> *connCon = master.cutPool();
#endif
}
else
{
StandardPool<Constraint, Variable> *connCon = master.getCutConnPool();
StandardPool<Constraint, Variable> *kuraCon = master.getCutKuraPool();
StandardPool<Variable, Constraint> *stdVar = master.varPool();
OGDF_ASSERT(connCon != nullptr);
OGDF_ASSERT(kuraCon != nullptr);
std::cout << connCon->number() << " Constraints im MasterConnpool \n";
std::cout << kuraCon->number() << " Constraints im MasterKurapool \n";
std::cout << connCon->size() << " Größe ConnPool"<<"\n";
outputCons(os, connCon, stdVar);
outputCons(os, kuraCon, stdVar);
}
os << "\nEND" <<"\n";
os.close();
std::cout << "Cutting is set: "<<master.cutting()<<"\n";
#if 0
std::cout <<"Bounds for the variables:\n";
Sub &theSub = *(master.firstSub());
for ( i = 0; i < theSub.nVar(); i++)
{
std::cout << i << ": " << theSub.lBound(i) << " - " << theSub.uBound(i) << "\n";
}
#endif
#if 0
// OLD CRAP
std::cout << "Constraints: \n";
StandardPool< Constraint, Variable > *spool = master.conPool();
StandardPool< Constraint, Variable > *cpool = master.cutPool();
std::cout << spool->size() << " Constraints im Masterpool \n";
std::cout << cpool->size() << " Constraints im Mastercutpool \n";
std::cout << "ConPool Constraints \n";
for ( i = 0; i < spool->size(); i++)
{
PoolSlot< Constraint, Variable > * sloty = spool->slot(i);
Constraint *mycon = sloty->conVar();
switch (mycon->sense()->sense())
{
case CSense::Less: std::cout << "<" << "\n"; break;
case CSense::Greater: std::cout << ">" << "\n"; break;
case CSense::Equal: std::cout << "=" << "\n"; break;
default: std::cout << "Inequality sense doesn't make any sense \n"; break;
}
}
std::cout << "CutPool Constraints \n";
for ( i = 0; i < cpool->size(); i++)
{
PoolSlot< Constraint, Variable > * sloty = cpool->slot(i);
Constraint *mycon = sloty->conVar();
switch (mycon->sense()->sense())
{
case CSense::Less: std::cout << "<" << "\n"; break;
case CSense::Greater: std::cout << ">" << "\n"; break;
case CSense::Equal: std::cout << "=" << "\n"; break;
default: std::cout << "Inequality sense doesn't make any sense \n"; break;
}
}
for ( i = 0; i < theSub.nCon(); i++)
{
Constraint &theCon = *(theSub.constraint(i));
for ( i = 0; i < theSub.nVar(); i++)
{
double c = theCon.coeff(theSub.variable(i));
if (c != 0)
std::cout << c;
else std::cout << " ";
}
switch (theCon.sense()->sense())
{
case CSense::Less: std::cout << "<" << "\n"; break;
case CSense::Greater: std::cout << ">" << "\n"; break;
case CSense::Equal: std::cout << "=" << "\n"; break;
default: std::cout << "doesn't make any sense \n"; break;
}
float fl;
while(!(std::cin >> fl))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
}
#endif
}
void MaximumCPlanarSubgraph::outputCons(std::ofstream &os,
StandardPool<Constraint, Variable> *connCon,
StandardPool<Variable, Constraint> *stdVar)
{
int i;
for ( i = 0; i < connCon->number(); i++)
{
PoolSlot< Constraint, Variable > * sloty = connCon->slot(i);
Constraint *mycon = sloty->conVar();
OGDF_ASSERT(mycon != nullptr);
int count;
for (count = 0; count < stdVar->size(); count++)
{
PoolSlot< Variable, Constraint > * slotv = stdVar->slot(count);
Variable *myvar = slotv->conVar();
double d = mycon->coeff(myvar);
if (d != 0.0) //precision!
{
os <<"+"<< d <<"x"<<count+1;
}
}
switch (mycon->sense()->sense())
{
case CSense::Less: os << " <= "; break;
case CSense::Greater: os << " >= "; break;
case CSense::Equal: os << " = "; break;
default:
os << "Inequality sense doesn't make any sense \n";
std::cerr << "Inequality sense unknown \n";
break;
}
os << mycon->rhs();
os << "\n";
}
}
}
| 15,216 | 6,016 |
/*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include <algorithm>
#include "messagebox.h"
#include "schedule_list.h"
#include "line_management_gui.h"
#include "components/gui_convoiinfo.h"
#include "components/gui_divider.h"
#include "line_item.h"
#include "simwin.h"
#include "../simcolor.h"
#include "../simdepot.h"
#include "../simhalt.h"
#include "../simworld.h"
#include "../simevent.h"
#include "../display/simgraph.h"
#include "../simskin.h"
#include "../simconvoi.h"
#include "../vehicle/vehicle.h"
#include "../simlinemgmt.h"
#include "../simmenu.h"
#include "../utils/simstring.h"
#include "../player/simplay.h"
#include "../gui/line_class_manager.h"
#include "../bauer/vehikelbauer.h"
#include "../dataobj/schedule.h"
#include "../dataobj/translator.h"
#include "../dataobj/livery_scheme.h"
#include "../dataobj/environment.h"
#include "../boden/wege/kanal.h"
#include "../boden/wege/maglev.h"
#include "../boden/wege/monorail.h"
#include "../boden/wege/narrowgauge.h"
#include "../boden/wege/runway.h"
#include "../boden/wege/schiene.h"
#include "../boden/wege/strasse.h"
#include "../unicode.h"
#include "minimap.h"
#include "halt_info.h"
uint16 schedule_list_gui_t::livery_scheme_index = 0;
static const char *cost_type[MAX_LINE_COST] =
{
"Free Capacity",
"Transported",
"Distance",
"Average speed",
// "Maxspeed",
"Comfort",
"Revenue",
"Operation",
"Refunds",
"Road toll",
"Profit",
"Convoys",
"Departures",
"Scheduled"
};
const uint8 cost_type_color[MAX_LINE_COST] =
{
COL_FREE_CAPACITY,
COL_TRANSPORTED,
COL_DISTANCE,
COL_AVERAGE_SPEED,
COL_COMFORT,
COL_REVENUE,
COL_OPERATION,
COL_CAR_OWNERSHIP,
COL_TOLL,
COL_PROFIT,
COL_VEHICLE_ASSETS,
//COL_COUNVOI_COUNT,
COL_MAXSPEED,
COL_LILAC
};
static uint32 bFilterStates = 0;
static uint8 tabs_to_lineindex[8];
static uint8 max_idx=0;
static uint8 statistic[MAX_LINE_COST]={
LINE_CAPACITY, LINE_TRANSPORTED_GOODS, LINE_DISTANCE, LINE_AVERAGE_SPEED, LINE_COMFORT, LINE_REVENUE, LINE_OPERATIONS, LINE_REFUNDS, LINE_WAYTOLL, LINE_PROFIT, LINE_CONVOIS, LINE_DEPARTURES, LINE_DEPARTURES_SCHEDULED
//std LINE_CAPACITY, LINE_TRANSPORTED_GOODS, LINE_REVENUE, LINE_OPERATIONS, LINE_PROFIT, LINE_CONVOIS, LINE_DISTANCE, LINE_MAXSPEED, LINE_WAYTOLL
};
static uint8 statistic_type[MAX_LINE_COST]={
STANDARD, STANDARD, STANDARD, STANDARD, STANDARD, MONEY, MONEY, MONEY, MONEY, MONEY, STANDARD, STANDARD, STANDARD
//std STANDARD, STANDARD, MONEY, MONEY, MONEY, STANDARD, STANDARD, STANDARD, MONEY
};
static const char * line_alert_helptexts[5] =
{
"line_nothing_moved",
"line_missing_scheduled_slots",
"line_has_obsolete_vehicles",
"line_overcrowded",
"line_has_upgradeable_vehicles"
};
enum sort_modes_t { SORT_BY_NAME=0, SORT_BY_ID, SORT_BY_PROFIT, SORT_BY_TRANSPORTED, SORT_BY_CONVOIS, SORT_BY_DISTANCE, MAX_SORT_MODES };
static uint8 current_sort_mode = 0;
#define LINE_NAME_COLUMN_WIDTH ((D_BUTTON_WIDTH*3)+11+4)
#define SCL_HEIGHT (min(L_DEFAULT_WINDOW_HEIGHT/2+D_TAB_HEADER_HEIGHT,(15*LINESPACE)))
#define L_DEFAULT_WINDOW_HEIGHT max(305, 24*LINESPACE)
/// selected convoy tab
static uint8 selected_convoy_tab = 0;
/// selected line tab per player
static uint8 selected_tab[MAX_PLAYER_COUNT] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/// selected line per tab (static)
linehandle_t schedule_list_gui_t::selected_line[MAX_PLAYER_COUNT][simline_t::MAX_LINE_TYPE];
// selected convoy list display mode
static uint8 selected_cnvlist_mode[MAX_PLAYER_COUNT] = {0};
// sort stuff
schedule_list_gui_t::sort_mode_t schedule_list_gui_t::sortby = by_name;
static uint8 default_sortmode = 0;
bool schedule_list_gui_t::sortreverse = false;
const char *schedule_list_gui_t::sort_text[SORT_MODES] = {
"cl_btn_sort_name",
"cl_btn_sort_schedule",
"cl_btn_sort_income",
"cl_btn_sort_loading_lvl",
"cl_btn_sort_max_speed",
"cl_btn_sort_power",
"cl_btn_sort_value",
"cl_btn_sort_age",
"cl_btn_sort_range"
};
gui_line_waiting_status_t::gui_line_waiting_status_t(linehandle_t line_)
{
line = line_;
set_table_layout(1, 0);
set_spacing(scr_size(1, 0));
init();
}
void gui_line_waiting_status_t::init()
{
remove_all();
if (line.is_bound()) {
schedule = line->get_schedule();
if( !schedule->get_count() ) return; // nothing to show
uint8 cols; // table cols
cols = line->get_goods_catg_index().get_count()+show_name+1;
add_table(cols, 0);
{
// header
new_component<gui_empty_t>();
if (show_name) {
new_component<gui_label_t>("stations");
}
for (uint8 catg_index = 0; catg_index < goods_manager_t::get_max_catg_index(); catg_index++) {
if (line->get_goods_catg_index().is_contained(catg_index) ) {
add_table(2,1);
{
new_component<gui_image_t>(goods_manager_t::get_info_catg_index(catg_index)->get_catg_symbol(), 0, ALIGN_NONE, true);
new_component<gui_label_t>(goods_manager_t::get_info_catg_index(catg_index)->get_catg_name());
}
end_table();
}
}
// border
new_component<gui_empty_t>();
for (uint8 i = 1; i < cols; ++i) {
new_component<gui_border_t>();
}
uint8 entry_idx = 0;
FORX(minivec_tpl<schedule_entry_t>, const& i, schedule->entries, ++entry_idx) {
halthandle_t const halt = haltestelle_t::get_halt(i.pos, line->get_owner());
if( !halt.is_bound() ) { continue; }
const bool is_interchange = (halt->registered_lines.get_count() + halt->registered_convoys.get_count()) > 1;
new_component<gui_schedule_entry_number_t>(entry_idx, halt->get_owner()->get_player_color1(),
is_interchange ? gui_schedule_entry_number_t::number_style::interchange : gui_schedule_entry_number_t::number_style::halt,
scr_size(D_ENTRY_NO_WIDTH, max(D_POS_BUTTON_HEIGHT, D_ENTRY_NO_HEIGHT)),
halt->get_basis_pos3d()
);
if (show_name) {
gui_label_buf_t *lb = new_component<gui_label_buf_t>();
lb->buf().append(halt->get_name());
lb->update();
}
for (uint8 catg_index = 0; catg_index < goods_manager_t::get_max_catg_index(); catg_index++) {
if (line->get_goods_catg_index().is_contained(catg_index)) {
new_component<gui_halt_waiting_catg_t>(halt, catg_index);
}
}
}
}
end_table();
}
}
void gui_line_waiting_status_t::draw(scr_coord offset)
{
if (line.is_bound()) {
if (!line->get_schedule()->matches(world(), schedule)) {
init();
}
}
set_size(get_size());
gui_aligned_container_t::draw(offset);
}
schedule_list_gui_t::schedule_list_gui_t(player_t *player_) :
gui_frame_t(translator::translate("Line Management"), player_),
player(player_),
scrolly_convois(&cont),
cont_haltlist(linehandle_t()),
scrolly_haltestellen(&cont_tab_haltlist, true, true),
scroll_times_history(&cont_times_history, true, true),
scrolly_line_info(&cont_line_info, true, true),
scl(gui_scrolled_list_t::listskin, line_scrollitem_t::compare),
lbl_filter("Line Filter"),
cont_line_capacity_by_catg(linehandle_t(), convoihandle_t()),
convoy_infos(),
halt_entry_origin(-1), halt_entry_dest(-1),
routebar_middle(player_->get_player_color1(), gui_colored_route_bar_t::downward)
{
selection = -1;
schedule_filter[0] = 0;
old_schedule_filter[0] = 0;
last_schedule = NULL;
old_player = NULL;
line_goods_catg_count = 0;
origin_halt = halthandle_t();
destination_halt = halthandle_t();
// init scrolled list
scl.set_pos(scr_coord(0,1));
scl.set_size(scr_size(LINE_NAME_COLUMN_WIDTH-11-4, SCL_HEIGHT-18));
scl.set_highlight_color(color_idx_to_rgb(player->get_player_color1()+1));
scl.add_listener(this);
// tab panel
tabs.set_pos(scr_coord(11,5));
tabs.set_size(scr_size(LINE_NAME_COLUMN_WIDTH-11-4, SCL_HEIGHT));
tabs.add_tab(&scl, translator::translate("All"));
max_idx = 0;
tabs_to_lineindex[max_idx++] = simline_t::line;
// now add all specific tabs
if(maglev_t::default_maglev) {
tabs.add_tab(&scl, translator::translate("Maglev"), skinverwaltung_t::maglevhaltsymbol, translator::translate("Maglev"));
tabs_to_lineindex[max_idx++] = simline_t::maglevline;
}
if(monorail_t::default_monorail) {
tabs.add_tab(&scl, translator::translate("Monorail"), skinverwaltung_t::monorailhaltsymbol, translator::translate("Monorail"));
tabs_to_lineindex[max_idx++] = simline_t::monorailline;
}
if(schiene_t::default_schiene) {
tabs.add_tab(&scl, translator::translate("Train"), skinverwaltung_t::zughaltsymbol, translator::translate("Train"));
tabs_to_lineindex[max_idx++] = simline_t::trainline;
}
if(narrowgauge_t::default_narrowgauge) {
tabs.add_tab(&scl, translator::translate("Narrowgauge"), skinverwaltung_t::narrowgaugehaltsymbol, translator::translate("Narrowgauge"));
tabs_to_lineindex[max_idx++] = simline_t::narrowgaugeline;
}
if (!vehicle_builder_t::get_info(tram_wt).empty()) {
tabs.add_tab(&scl, translator::translate("Tram"), skinverwaltung_t::tramhaltsymbol, translator::translate("Tram"));
tabs_to_lineindex[max_idx++] = simline_t::tramline;
}
if(strasse_t::default_strasse) {
tabs.add_tab(&scl, translator::translate("Truck"), skinverwaltung_t::autohaltsymbol, translator::translate("Truck"));
tabs_to_lineindex[max_idx++] = simline_t::truckline;
}
if (!vehicle_builder_t::get_info(water_wt).empty()) {
tabs.add_tab(&scl, translator::translate("Ship"), skinverwaltung_t::schiffshaltsymbol, translator::translate("Ship"));
tabs_to_lineindex[max_idx++] = simline_t::shipline;
}
if(runway_t::default_runway) {
tabs.add_tab(&scl, translator::translate("Air"), skinverwaltung_t::airhaltsymbol, translator::translate("Air"));
tabs_to_lineindex[max_idx++] = simline_t::airline;
}
tabs.add_listener(this);
add_component(&tabs);
// editable line name
inp_name.add_listener(this);
inp_name.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH+23, D_MARGIN_TOP));
inp_name.set_visible(false);
add_component(&inp_name);
// sort button on convoy list, define this first to prevent overlapping
sortedby.set_pos(scr_coord(BUTTON1_X, 2));
sortedby.set_size(scr_size(D_BUTTON_WIDTH*1.5, D_BUTTON_HEIGHT));
sortedby.set_max_size(scr_size(D_BUTTON_WIDTH * 1.5, LINESPACE * 8));
for (int i = 0; i < SORT_MODES; i++) {
sortedby.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate(sort_text[i]), SYSCOL_TEXT);
}
sortedby.set_selection(default_sortmode);
sortedby.add_listener(this);
cont_convoys.add_component(&sortedby);
// convoi list
cont.set_size(scr_size(200, 80));
cont.set_pos(scr_coord(D_H_SPACE, D_V_SPACE));
scrolly_convois.set_pos(scr_coord(0, D_BUTTON_HEIGHT+D_H_SPACE));
scrolly_convois.set_show_scroll_y(true);
scrolly_convois.set_scroll_amount_y(40);
scrolly_convois.set_visible(false);
cont_convoys.add_component(&scrolly_convois);
scrolly_line_info.set_visible(false);
cont_line_info.set_table_layout(1,0);
cont_line_info.add_table(2,0)->set_spacing(scr_size(D_H_SPACE, 0));
{
cont_line_info.add_component(&halt_entry_origin);
cont_line_info.add_component(&lb_line_origin);
cont_line_info.add_component(&routebar_middle);
cont_line_info.new_component<gui_empty_t>();
cont_line_info.add_component(&halt_entry_dest);
cont_line_info.add_component(&lb_line_destination);
}
cont_line_info.end_table();
cont_line_info.add_table(3,1);
{
cont_line_info.add_component(&lb_travel_distance);
if (skinverwaltung_t::service_frequency) {
cont_line_info.new_component<gui_image_t>(skinverwaltung_t::service_frequency->get_image_id(0), 0, ALIGN_NONE, true)->set_tooltip(translator::translate("Service frequency"));
}
else {
cont_line_info.new_component<gui_label_t>("Service frequency");
}
cont_line_info.add_component(&lb_service_frequency);
}
cont_line_info.end_table();
cont_line_info.add_table(2,1);
{
cont_line_info.add_component(&lb_convoy_count);
bt_withdraw_line.init(button_t::box_state, "Withdraw All", scr_coord(0, 0), scr_size(D_BUTTON_WIDTH+18,D_BUTTON_HEIGHT));
bt_withdraw_line.set_tooltip("Convoi is sold when all wagons are empty.");
if (skinverwaltung_t::alerts) {
bt_withdraw_line.set_image(skinverwaltung_t::alerts->get_image_id(2));
}
bt_withdraw_line.add_listener(this);
cont_line_info.add_component(&bt_withdraw_line);
}
cont_line_info.end_table();
cont_line_info.new_component<gui_divider_t>();
cont_line_info.add_component(&cont_line_capacity_by_catg);
scrolly_line_info.set_pos(scr_coord(0, 8 + SCL_HEIGHT + D_BUTTON_HEIGHT + D_BUTTON_HEIGHT + 2));
add_component(&scrolly_line_info);
// filter lines by
lbl_filter.set_pos( scr_coord( 11, 7+SCL_HEIGHT+2 ) );
add_component(&lbl_filter);
inp_filter.set_pos( scr_coord( 11+D_BUTTON_WIDTH, 7+SCL_HEIGHT ) );
inp_filter.set_size( scr_size( D_BUTTON_WIDTH*2- D_BUTTON_HEIGHT *3, D_EDIT_HEIGHT ) );
inp_filter.set_text( schedule_filter, lengthof(schedule_filter) );
// inp_filter.set_tooltip("Only show lines containing");
inp_filter.add_listener(this);
add_component(&inp_filter);
filter_btn_all_pas.init(button_t::roundbox_state, NULL, scr_coord(inp_filter.get_pos() + scr_coord(inp_filter.get_size().w, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_pas.set_image(skinverwaltung_t::passengers->get_image_id(0));
filter_btn_all_pas.set_tooltip("filter_pas_line");
filter_btn_all_pas.pressed = line_type_flags & (1 << simline_t::all_pas);
add_component(&filter_btn_all_pas);
filter_btn_all_pas.add_listener(this);
filter_btn_all_mails.init(button_t::roundbox_state, NULL, scr_coord(filter_btn_all_pas.get_pos() + scr_coord(D_BUTTON_HEIGHT, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_mails.set_image(skinverwaltung_t::mail->get_image_id(0));
filter_btn_all_mails.set_tooltip("filter_mail_line");
filter_btn_all_mails.pressed = line_type_flags & (1 << simline_t::all_mail);
filter_btn_all_mails.add_listener(this);
add_component(&filter_btn_all_mails);
filter_btn_all_freights.init(button_t::roundbox_state, NULL, scr_coord(filter_btn_all_mails.get_pos() + scr_coord(D_BUTTON_HEIGHT, 0)), scr_size(D_BUTTON_HEIGHT, D_BUTTON_HEIGHT));
filter_btn_all_freights.set_image(skinverwaltung_t::goods->get_image_id(0));
filter_btn_all_freights.set_tooltip("filter_freight_line");
filter_btn_all_freights.pressed = line_type_flags & (1 << simline_t::all_freight);
filter_btn_all_freights.add_listener(this);
add_component(&filter_btn_all_freights);
// normal buttons edit new remove
bt_new_line.init(button_t::roundbox, "New Line", scr_coord(11, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_new_line.add_listener(this);
add_component(&bt_new_line);
bt_edit_line.init(button_t::roundbox, "Update Line", scr_coord(11+D_BUTTON_WIDTH, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_edit_line.set_tooltip("Modify the selected line");
bt_edit_line.add_listener(this);
bt_edit_line.disable();
add_component(&bt_edit_line);
bt_delete_line.init(button_t::roundbox, "Delete Line", scr_coord(11+2*D_BUTTON_WIDTH, 8+SCL_HEIGHT+D_BUTTON_HEIGHT ), D_BUTTON_SIZE);
bt_delete_line.set_tooltip("Delete the selected line (if without associated convois).");
bt_delete_line.add_listener(this);
bt_delete_line.disable();
add_component(&bt_delete_line);
int offset_y = D_MARGIN_TOP + D_BUTTON_HEIGHT*2;
bt_line_class_manager.init(button_t::roundbox_state, "line_class_manager", scr_coord(LINE_NAME_COLUMN_WIDTH, offset_y), D_BUTTON_SIZE);
bt_line_class_manager.set_tooltip("change_the_classes_for_the_entire_line");
bt_line_class_manager.set_visible(false);
bt_line_class_manager.add_listener(this);
add_component(&bt_line_class_manager);
offset_y += D_BUTTON_HEIGHT;
// Select livery
livery_selector.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH, offset_y));
livery_selector.set_focusable(false);
livery_selector.set_size(scr_size(D_BUTTON_WIDTH*1.5, D_BUTTON_HEIGHT));
livery_selector.set_max_size(scr_size(D_BUTTON_WIDTH - 8, LINESPACE * 8 + 2 + 16));
livery_selector.set_highlight_color(1);
livery_selector.clear_elements();
livery_selector.add_listener(this);
add_component(&livery_selector);
// sort asc/desc switching button
sort_order.set_typ(button_t::sortarrow_state); // NOTE: This dialog is not yet auto-aligned, so we need to pre-set the typ to calculate the size
sort_order.init(button_t::sortarrow_state, "", scr_coord(BUTTON1_X + D_BUTTON_WIDTH * 1.5 + D_H_SPACE, 2), sort_order.get_min_size());
sort_order.set_tooltip(translator::translate("cl_btn_sort_order"));
sort_order.add_listener(this);
sort_order.pressed = sortreverse;
cont_convoys.add_component(&sort_order);
bt_mode_convois.init(button_t::roundbox, gui_convoy_formation_t::cnvlist_mode_button_texts[selected_cnvlist_mode[player->get_player_nr()]], scr_coord(BUTTON3_X, 2), scr_size(D_BUTTON_WIDTH+15, D_BUTTON_HEIGHT));
bt_mode_convois.add_listener(this);
cont_convoys.add_component(&bt_mode_convois);
info_tabs.add_tab(&cont_convoys, translator::translate("Convoys"));
offset_y += D_BUTTON_HEIGHT;
// right tabs
info_tabs.set_pos(scr_coord(LINE_NAME_COLUMN_WIDTH-4, offset_y));
info_tabs.add_listener(this);
info_tabs.set_size(scr_size(get_windowsize().w- LINE_NAME_COLUMN_WIDTH+4+D_MARGIN_RIGHT, get_windowsize().h-offset_y));
add_component(&info_tabs);
//CHART
chart.set_dimension(12, 1000);
chart.set_pos( scr_coord(68, LINESPACE) );
chart.set_seed(0);
chart.set_background(SYSCOL_CHART_BACKGROUND);
chart.set_ltr(env_t::left_to_right_graphs);
cont_charts.add_component(&chart);
// add filter buttons
for (int i=0; i<MAX_LINE_COST; i++) {
filterButtons[i].init(button_t::box_state,cost_type[i],scr_coord(0,0), D_BUTTON_SIZE);
filterButtons[i].add_listener(this);
filterButtons[i].background_color = color_idx_to_rgb(cost_type_color[i]);
cont_charts.add_component(filterButtons + i);
}
info_tabs.add_tab(&cont_charts, translator::translate("Chart"));
info_tabs.set_active_tab_index(selected_convoy_tab);
cont_times_history.set_table_layout(1,0);
info_tabs.add_tab(&scroll_times_history, translator::translate("times_history"));
cont_tab_haltlist.set_table_layout(1,0);
bt_show_halt_name.init(button_t::square_state, "show station names");
bt_show_halt_name.set_tooltip("helptxt_show_station_name");
bt_show_halt_name.pressed=true;
bt_show_halt_name.add_listener(this);
cont_tab_haltlist.add_component(&bt_show_halt_name);
cont_tab_haltlist.add_component(&cont_haltlist);
info_tabs.add_tab(&scrolly_haltestellen, translator::translate("waiting_status"));
// recover last selected line
int index = 0;
for( uint i=0; i<max_idx; i++ ) {
if( tabs_to_lineindex[i] == selected_tab[player->get_player_nr()] ) {
line = selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]];
// check owner here: selected_line[][] is not reset between games, so line could have another player as owner
if (line.is_bound() && line->get_owner() != player) {
line = linehandle_t();
}
index = i;
break;
}
}
selected_tab[player->get_player_nr()] = tabs_to_lineindex[index]; // reset if previous selected tab is not there anymore
tabs.set_active_tab_index(index);
if(index>0) {
bt_new_line.enable();
}
else {
bt_new_line.disable();
}
update_lineinfo( line );
// resize button
set_min_windowsize(scr_size(LINE_NAME_COLUMN_WIDTH + D_BUTTON_WIDTH*3 + D_MARGIN_LEFT*2, L_DEFAULT_WINDOW_HEIGHT));
set_resizemode(diagonal_resize);
resize(scr_coord(0,0));
resize(scr_coord(D_BUTTON_WIDTH, LINESPACE*3+D_V_SPACE)); // suitable for 4 buttons horizontally and 5 convoys vertically
build_line_list(index);
}
schedule_list_gui_t::~schedule_list_gui_t()
{
delete last_schedule;
// change line name if necessary
rename_line();
}
/**
* Mouse clicks are hereby reported to the GUI-Components
*/
bool schedule_list_gui_t::infowin_event(const event_t *ev)
{
if(ev->ev_class == INFOWIN) {
if(ev->ev_code == WIN_CLOSE) {
// hide schedule on minimap (may not current, but for safe)
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
else if( (ev->ev_code==WIN_OPEN || ev->ev_code==WIN_TOP) && line.is_bound() ) {
if( line->count_convoys()>0 ) {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( line->get_convoy(0) );
}
else {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
}
}
return gui_frame_t::infowin_event(ev);
}
bool schedule_list_gui_t::action_triggered( gui_action_creator_t *comp, value_t v )
{
if(comp == &bt_edit_line) {
if(line.is_bound()) {
create_win( new line_management_gui_t(line, player), w_info, (ptrdiff_t)line.get_rep() );
}
}
else if(comp == &bt_new_line) {
// create typed line
assert( tabs.get_active_tab_index() > 0 && tabs.get_active_tab_index()<max_idx );
// update line schedule via tool!
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
int type = tabs_to_lineindex[tabs.get_active_tab_index()];
buf.printf( "c,0,%i,0,0|%i|", type, type );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
depot_t::update_all_win();
}
else if(comp == &bt_delete_line) {
if(line.is_bound()) {
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "d,%i", line.get_id() );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
depot_t::update_all_win();
}
}
else if(comp == &bt_withdraw_line) {
bt_withdraw_line.pressed ^= 1;
if (line.is_bound()) {
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "w,%i,%i", line.get_id(), bt_withdraw_line.pressed );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
}
}
else if (comp == &bt_line_class_manager)
{
create_win(20, 20, new line_class_manager_t(line), w_info, magic_line_class_manager + line.get_id());
return true;
}
else if (comp == &sortedby) {
int tmp = sortedby.get_selection();
if (tmp >= 0 && tmp < sortedby.count_elements())
{
sortedby.set_selection(tmp);
set_sortierung((sort_mode_t)tmp);
}
else {
sortedby.set_selection(0);
set_sortierung(by_name);
}
default_sortmode = (uint8)tmp;
update_lineinfo(line);
}
else if (comp == &sort_order) {
set_reverse(!get_reverse());
update_lineinfo(line);
sort_order.pressed = sortreverse;
}
else if (comp == &bt_mode_convois) {
selected_cnvlist_mode[player->get_player_nr()] = (selected_cnvlist_mode[player->get_player_nr()] + 1) % gui_convoy_formation_t::CONVOY_OVERVIEW_MODES;
bt_mode_convois.set_text(gui_convoy_formation_t::cnvlist_mode_button_texts[selected_cnvlist_mode[player->get_player_nr()]]);
update_lineinfo(line);
}
else if(comp == &livery_selector)
{
sint32 livery_selection = livery_selector.get_selection();
if(livery_selection < 0)
{
livery_selector.set_selection(0);
livery_selection = 0;
}
livery_scheme_index = livery_scheme_indices.empty()? 0 : livery_scheme_indices[livery_selection];
if (line.is_bound())
{
tool_t *tmp_tool = create_tool( TOOL_CHANGE_LINE | SIMPLE_TOOL );
cbuffer_t buf;
buf.printf( "V,%i,%i", line.get_id(), livery_scheme_index );
tmp_tool->set_default_param(buf);
welt->set_tool( tmp_tool, player );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
}
}
else if (comp == &tabs) {
int const tab = tabs.get_active_tab_index();
uint8 old_selected_tab = selected_tab[player->get_player_nr()];
selected_tab[player->get_player_nr()] = tabs_to_lineindex[tab];
if( old_selected_tab == simline_t::line && selected_line[player->get_player_nr()][0].is_bound() && selected_line[player->get_player_nr()][0]->get_linetype() == selected_tab[player->get_player_nr()] ) {
// switching from general to same waytype tab while line is seletced => use current line instead
selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] = selected_line[player->get_player_nr()][0];
}
update_lineinfo( selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] );
build_line_list(tab);
if (tab>0) {
bt_new_line.enable( (welt->get_active_player() == player || player == welt->get_player(1)) && !welt->get_active_player()->is_locked() );
}
else {
bt_new_line.disable();
}
}
else if(comp == &info_tabs){
selected_convoy_tab = (uint8)info_tabs.get_active_tab_index();
if (selected_convoy_tab == 3) {
cont_haltlist.init();
}
}
else if (comp == &scl) {
if( line_scrollitem_t *li=(line_scrollitem_t *)scl.get_element(v.i) ) {
update_lineinfo( li->get_line() );
}
else {
// no valid line
update_lineinfo(linehandle_t());
}
selected_line[player->get_player_nr()][selected_tab[player->get_player_nr()]] = line;
selected_line[player->get_player_nr()][0] = line; // keep these the same in overview
}
else if (comp == &inp_filter) {
if( strcmp(old_schedule_filter,schedule_filter) ) {
build_line_list(tabs.get_active_tab_index());
strcpy(old_schedule_filter,schedule_filter);
}
}
else if (comp == &inp_name) {
rename_line();
}
else if (comp == &filter_btn_all_pas) {
line_type_flags ^= (1 << simline_t::all_pas);
filter_btn_all_pas.pressed = line_type_flags & (1 << simline_t::all_pas);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &filter_btn_all_mails) {
line_type_flags ^= (1 << simline_t::all_mail);
filter_btn_all_mails.pressed = line_type_flags & (1 << simline_t::all_mail);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &filter_btn_all_freights) {
line_type_flags ^= (1 << simline_t::all_freight);
filter_btn_all_freights.pressed = line_type_flags & (1 << simline_t::all_freight);
build_line_list(tabs.get_active_tab_index());
}
else if (comp == &bt_show_halt_name) {
bt_show_halt_name.pressed = !bt_show_halt_name.pressed;
cont_haltlist.set_show_name( bt_show_halt_name.pressed );
}
else {
if (line.is_bound()) {
for ( int i = 0; i<MAX_LINE_COST; i++) {
if (comp == &filterButtons[i]) {
bFilterStates ^= (1 << i);
if(bFilterStates & (1 << i)) {
chart.show_curve(i);
}
else {
chart.hide_curve(i);
}
break;
}
}
}
}
return true;
}
void schedule_list_gui_t::reset_line_name()
{
// change text input of selected line
if (line.is_bound()) {
tstrncpy(old_line_name, line->get_name(), sizeof(old_line_name));
tstrncpy(line_name, line->get_name(), sizeof(line_name));
inp_name.set_text(line_name, sizeof(line_name));
}
}
void schedule_list_gui_t::rename_line()
{
if (line.is_bound()
&& ((player == welt->get_active_player() && !welt->get_active_player()->is_locked()) || welt->get_active_player() == welt->get_public_player())) {
const char *t = inp_name.get_text();
// only change if old name and current name are the same
// otherwise some unintended undo if renaming would occur
if( t && t[0] && strcmp(t, line->get_name()) && strcmp(old_line_name, line->get_name())==0) {
// text changed => call tool
cbuffer_t buf;
buf.printf( "l%u,%s", line.get_id(), t );
tool_t *tmp_tool = create_tool( TOOL_RENAME | SIMPLE_TOOL );
tmp_tool->set_default_param( buf );
welt->set_tool( tmp_tool, line->get_owner() );
// since init always returns false, it is safe to delete immediately
delete tmp_tool;
// do not trigger this command again
tstrncpy(old_line_name, t, sizeof(old_line_name));
}
}
}
void schedule_list_gui_t::draw(scr_coord pos, scr_size size)
{
if( old_line_count != player->simlinemgmt.get_line_count() ) {
show_lineinfo( line );
}
if( old_player != welt->get_active_player() ) {
// deativate buttons, if not curretn player
old_player = welt->get_active_player();
const bool activate = (old_player == player || old_player == welt->get_player( 1 )) && !welt->get_active_player()->is_locked();
bt_delete_line.enable( activate );
bt_edit_line.enable( activate );
bt_new_line.enable( activate && tabs.get_active_tab_index() > 0);
bt_withdraw_line.set_visible( activate );
livery_selector.enable( activate );
}
// if search string changed, update line selection
if( strcmp( old_schedule_filter, schedule_filter ) ) {
build_line_list(tabs.get_active_tab_index());
strcpy( old_schedule_filter, schedule_filter );
}
gui_frame_t::draw(pos, size);
if( line.is_bound() ) {
if( (!line->get_schedule()->empty() && !line->get_schedule()->matches( welt, last_schedule )) || last_vehicle_count != line->count_convoys() || line->get_goods_catg_index().get_count() != line_goods_catg_count ) {
update_lineinfo( line );
}
// line type symbol
display_color_img(line->get_linetype_symbol(), pos.x + LINE_NAME_COLUMN_WIDTH -23, pos.y + D_TITLEBAR_HEIGHT + D_MARGIN_TOP - 42 + FIXED_SYMBOL_YOFF, 0, false, false);
PUSH_CLIP( pos.x + 1, pos.y + D_TITLEBAR_HEIGHT, size.w - 2, size.h - D_TITLEBAR_HEIGHT);
display(pos);
POP_CLIP();
}
for (int i = 0; i < MAX_LINE_COST; i++) {
filterButtons[i].pressed = ((bFilterStates & (1 << i)) != 0);
}
}
#define GOODS_SYMBOL_CELL_WIDTH 14 // TODO: This will be used in common with halt detail in the future
void schedule_list_gui_t::display(scr_coord pos)
{
uint32 icnv = line->count_convoys();
cbuffer_t buf;
char ctmp[128];
int top = D_TITLEBAR_HEIGHT + D_MARGIN_TOP + D_EDIT_HEIGHT + D_V_SPACE;
int left = LINE_NAME_COLUMN_WIDTH;
sint64 profit = line->get_finance_history(0,LINE_PROFIT);
uint32 line_total_vehicle_count=0;
for (uint32 i = 0; i<icnv; i++) {
convoihandle_t const cnv = line->get_convoy(i);
// we do not want to count the capacity of depot convois
if (!cnv->in_depot()) {
line_total_vehicle_count += cnv->get_vehicle_count();
}
}
if (last_schedule != line->get_schedule() && origin_halt.is_bound()) {
uint8 halt_symbol_style = gui_schedule_entry_number_t::halt;
lb_line_origin.buf().append(origin_halt->get_name());
if ((origin_halt->registered_lines.get_count() + origin_halt->registered_convoys.get_count()) > 1) {
halt_symbol_style = gui_schedule_entry_number_t::interchange;
}
halt_entry_origin.init(halt_entry_idx[0], origin_halt->get_owner()->get_player_color1(), halt_symbol_style, origin_halt->get_basis_pos3d());
if (destination_halt.is_bound()) {
halt_symbol_style = gui_schedule_entry_number_t::halt;
if ((destination_halt->registered_lines.get_count() + destination_halt->registered_convoys.get_count()) > 1) {
halt_symbol_style = gui_schedule_entry_number_t::interchange;
}
halt_entry_dest.init(halt_entry_idx[1], destination_halt->get_owner()->get_player_color1(), halt_symbol_style, destination_halt->get_basis_pos3d());
if (line->get_schedule()->is_mirrored()) {
routebar_middle.set_line_style(gui_colored_route_bar_t::doubled);
}
else {
routebar_middle.set_line_style(gui_colored_route_bar_t::downward);
}
lb_line_destination.buf().append(destination_halt->get_name());
lb_travel_distance.buf().printf("%s: %.1fkm ", translator::translate("travel_distance"), (float)(line->get_travel_distance()*world()->get_settings().get_meters_per_tile()/1000.0));
lb_travel_distance.update();
}
}
lb_line_origin.update();
lb_line_destination.update();
// convoy count
if (line->get_convoys().get_count()>1) {
lb_convoy_count.buf().printf(translator::translate("%d convois"), icnv);
}
else {
lb_convoy_count.buf().append(line->get_convoys().get_count() == 1 ? translator::translate("1 convoi") : translator::translate("no convois"));
}
if (icnv && line_total_vehicle_count>1) {
lb_convoy_count.buf().printf(translator::translate(", %d vehicles"), line_total_vehicle_count);
}
lb_convoy_count.update();
// Display service frequency
const sint64 service_frequency = line->get_service_frequency();
if(service_frequency)
{
char as_clock[32];
welt->sprintf_ticks(as_clock, sizeof(as_clock), service_frequency);
lb_service_frequency.buf().printf(" %s", as_clock);
lb_service_frequency.set_color(line->get_state() & simline_t::line_missing_scheduled_slots ? color_idx_to_rgb(COL_DARK_TURQUOISE) : SYSCOL_TEXT);
lb_service_frequency.set_tooltip(line->get_state() & simline_t::line_missing_scheduled_slots ? translator::translate(line_alert_helptexts[1]) : "");
}
else {
lb_service_frequency.buf().append("--:--");
}
lb_service_frequency.update();
int len2 = display_proportional_clip_rgb(pos.x+LINE_NAME_COLUMN_WIDTH, pos.y+top, translator::translate("Gewinn"), ALIGN_LEFT, SYSCOL_TEXT, true );
money_to_string(ctmp, profit/100.0);
len2 += display_proportional_clip_rgb(pos.x+LINE_NAME_COLUMN_WIDTH+len2+5, pos.y+top, ctmp, ALIGN_LEFT, profit>=0?MONEY_PLUS:MONEY_MINUS, true );
bt_line_class_manager.disable();
for (unsigned convoy = 0; convoy < line->count_convoys(); convoy++)
{
convoihandle_t cnv = line->get_convoy(convoy);
for (unsigned veh = 0; veh < cnv->get_vehicle_count(); veh++)
{
vehicle_t* v = cnv->get_vehicle(veh);
if (v->get_cargo_type()->get_catg_index() == goods_manager_t::INDEX_PAS || v->get_cargo_type()->get_catg_index() == goods_manager_t::INDEX_MAIL)
{
bt_line_class_manager.enable( (welt->get_active_player() == player || player == welt->get_player(1)) && !welt->get_active_player()->is_locked() );
}
}
}
top += D_BUTTON_HEIGHT + LINESPACE + 1;
left = LINE_NAME_COLUMN_WIDTH + D_BUTTON_WIDTH*1.5 + D_V_SPACE;
buf.clear();
// show the state of the line, if interresting
if (line->get_state() & simline_t::line_nothing_moved) {
if (skinverwaltung_t::alerts) {
display_color_img_with_tooltip(skinverwaltung_t::alerts->get_image_id(2), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[0]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else {
buf.append(translator::translate(line_alert_helptexts[0]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_has_upgradeable_vehicles) {
if (skinverwaltung_t::upgradable) {
display_color_img_with_tooltip(skinverwaltung_t::upgradable->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[4]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len() && line->get_state_color() == COL_PURPLE) {
buf.append(translator::translate(line_alert_helptexts[4]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_has_obsolete_vehicles) {
if (skinverwaltung_t::alerts) {
display_color_img_with_tooltip(skinverwaltung_t::alerts->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[2]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len()) {
buf.append(translator::translate(line_alert_helptexts[2]));
}
}
if (line->count_convoys() && line->get_state() & simline_t::line_overcrowded) {
if (skinverwaltung_t::pax_evaluation_icons) {
display_color_img_with_tooltip(skinverwaltung_t::pax_evaluation_icons->get_image_id(1), pos.x + left, pos.y + top + FIXED_SYMBOL_YOFF, 0, false, false, translator::translate(line_alert_helptexts[3]));
left += GOODS_SYMBOL_CELL_WIDTH;
}
else if (!buf.len() && line->get_state_color() == COL_DARK_PURPLE) {
buf.append(translator::translate(line_alert_helptexts[3]));
}
}
if (buf.len() > 0) {
display_proportional_clip_rgb(pos.x + left, pos.y + top, buf, ALIGN_LEFT, line->get_state_color(), true);
}
cont_line_info.set_size(cont_line_info.get_size());
}
void schedule_list_gui_t::set_windowsize(scr_size size)
{
gui_frame_t::set_windowsize(size);
int rest_width = get_windowsize().w-LINE_NAME_COLUMN_WIDTH;
int button_per_row=max(1,rest_width/(D_BUTTON_WIDTH+D_H_SPACE));
int button_rows= MAX_LINE_COST/button_per_row + ((MAX_LINE_COST%button_per_row)!=0);
scrolly_line_info.set_size( scr_size(LINE_NAME_COLUMN_WIDTH-4, get_client_windowsize().h - scrolly_line_info.get_pos().y-1) );
info_tabs.set_size( scr_size(rest_width+2, get_windowsize().h-info_tabs.get_pos().y-D_TITLEBAR_HEIGHT-1) );
scrolly_convois.set_size( scr_size(info_tabs.get_size().w+1, info_tabs.get_size().h - scrolly_convois.get_pos().y - D_H_SPACE-1) );
chart.set_size(scr_size(rest_width-68-D_MARGIN_RIGHT, SCL_HEIGHT-14-(button_rows*(D_BUTTON_HEIGHT+D_H_SPACE))));
inp_name.set_size(scr_size(rest_width - 31, D_EDIT_HEIGHT));
int y=SCL_HEIGHT-(button_rows*(D_BUTTON_HEIGHT+D_H_SPACE))+18;
for (int i=0; i<MAX_LINE_COST; i++) {
filterButtons[i].set_pos( scr_coord((i%button_per_row)*(D_BUTTON_WIDTH+D_H_SPACE)+D_H_SPACE, y+(i/button_per_row)*(D_BUTTON_HEIGHT+D_H_SPACE)) );
}
}
void schedule_list_gui_t::build_line_list(int selected_tab)
{
sint32 sel = -1;
scl.clear_elements();
player->simlinemgmt.get_lines(tabs_to_lineindex[selected_tab], &lines, get_filter_type_bits(), true);
FOR(vector_tpl<linehandle_t>, const l, lines) {
// search name
if( utf8caseutf8(l->get_name(), schedule_filter) ) {
scl.new_component<line_scrollitem_t>(l);
if ( line == l ) {
sel = scl.get_count() - 1;
}
}
}
scl.set_selection( sel );
line_scrollitem_t::sort_mode = (line_scrollitem_t::sort_modes_t)current_sort_mode;
scl.sort( 0 );
scl.set_size(scl.get_size());
old_line_count = player->simlinemgmt.get_line_count();
}
/* hides show components */
void schedule_list_gui_t::update_lineinfo(linehandle_t new_line)
{
// change line name if necessary
if (line.is_bound()) {
rename_line();
}
if(new_line.is_bound()) {
const bool activate = (old_player == player || old_player == welt->get_player(1)) && !welt->get_active_player()->is_locked();
// ok, this line is visible
scrolly_convois.set_visible(true);
scrolly_haltestellen.set_visible(true);
scrolly_line_info.set_visible(new_line->get_schedule()->get_count()>0);
inp_name.set_visible(true);
livery_selector.set_visible(true);
cont_line_capacity_by_catg.set_line(new_line);
cont_times_history.set_visible(true);
cont_times_history.remove_all();
cont_times_history.new_component<gui_times_history_t>(new_line, convoihandle_t(), false);
if (!new_line->get_schedule()->is_mirrored()) {
cont_times_history.new_component<gui_times_history_t>(new_line, convoihandle_t(), true);
}
cont_haltlist.set_visible(true);
cont_haltlist.set_line(new_line);
resize(scr_size(0,0));
livery_selector.set_visible(true);
// fill container with info of line's convoys
// we do it here, since this list needs only to be
// refreshed when the user selects a new line
line_convoys.clear();
line_convoys = new_line->get_convoys();
sort_list();
uint32 i, icnv = 0;
line_goods_catg_count = new_line->get_goods_catg_index().get_count();
icnv = new_line->count_convoys();
// display convoys of line
cont.remove_all();
while (!convoy_infos.empty()) {
delete convoy_infos.pop_back();
}
convoy_infos.resize(icnv);
scr_coord_val ypos = 0;
for(i = 0; i<icnv; i++ ) {
gui_convoiinfo_t* const cinfo = new gui_convoiinfo_t(line_convoys.get_element(i), false);
cinfo->set_pos(scr_coord(0, ypos-D_MARGIN_TOP));
scr_size csize = cinfo->get_min_size();
cinfo->set_size(scr_size(400, csize.h-D_MARGINS_Y));
cinfo->set_mode(selected_cnvlist_mode[player->get_player_nr()]);
cinfo->set_switchable_label(sortby);
convoy_infos.append(cinfo);
cont.add_component(cinfo);
ypos += csize.h - D_MARGIN_TOP-D_V_SPACE*2;
}
cont.set_size(scr_size(600, ypos));
bt_delete_line.disable();
bt_withdraw_line.set_visible(false);
if( icnv>0 ) {
bt_withdraw_line.set_visible(true);
}
else {
bt_delete_line.enable( activate );
}
bt_edit_line.enable( activate );
bt_withdraw_line.pressed = new_line->get_withdraw();
bt_withdraw_line.background_color = color_idx_to_rgb( bt_withdraw_line.pressed ? COL_DARK_YELLOW-1 : COL_YELLOW );
bt_withdraw_line.text_color = color_idx_to_rgb(bt_withdraw_line.pressed ? COL_WHITE : COL_BLACK);
livery_selector.set_focusable(true);
livery_selector.clear_elements();
livery_scheme_indices.clear();
if( icnv>0 ) {
// build available livery schemes list for this line
if (new_line->count_convoys()) {
const uint16 month_now = welt->get_timeline_year_month();
vector_tpl<livery_scheme_t*>* schemes = welt->get_settings().get_livery_schemes();
ITERATE_PTR(schemes, i)
{
bool found = false;
livery_scheme_t* scheme = schemes->get_element(i);
if (scheme->is_available(month_now))
{
for (uint32 j = 0; j < new_line->count_convoys(); j++)
{
convoihandle_t const cnv_in_line = new_line->get_convoy(j);
for (int k = 0; k < cnv_in_line->get_vehicle_count(); k++) {
const vehicle_desc_t *desc = cnv_in_line->get_vehicle(k)->get_desc();
if (desc->get_livery_count()) {
const char* test_livery = scheme->get_latest_available_livery(month_now, desc);
if (test_livery) {
if (scheme->is_contained(test_livery, month_now)) {
livery_selector.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate(scheme->get_name()), SYSCOL_TEXT);
livery_scheme_indices.append(i);
found = true;
break;
}
}
}
}
if (found) {
livery_selector.set_selection(livery_scheme_indices.index_of(i));
break;
}
}
}
}
}
}
if(livery_scheme_indices.empty()) {
livery_selector.new_component<gui_scrolled_list_t::const_text_scrollitem_t>(translator::translate("No livery"), SYSCOL_TEXT);
livery_selector.set_selection(0);
}
uint8 entry_idx = 0;
halt_entry_idx[0] = 255;
halt_entry_idx[1] = 255;
origin_halt = halthandle_t();
destination_halt = halthandle_t();
FORX(minivec_tpl<schedule_entry_t>, const& i, new_line->get_schedule()->entries, ++entry_idx) {
halthandle_t const halt = haltestelle_t::get_halt(i.pos, player);
if (halt.is_bound()) {
if (halt_entry_idx[0] == 255) {
halt_entry_idx[0] = entry_idx;
origin_halt = halt;
}
else {
halt_entry_idx[1] = entry_idx;
destination_halt = halt;
}
}
}
// chart
chart.remove_curves();
for(i=0; i<MAX_LINE_COST; i++) {
chart.add_curve(color_idx_to_rgb(cost_type_color[i]), new_line->get_finance_history(), MAX_LINE_COST, statistic[i], MAX_MONTHS, statistic_type[i], filterButtons[i].pressed, true, statistic_type[i]*2 );
if (bFilterStates & (1 << i)) {
chart.show_curve(i);
}
}
chart.set_visible(true);
// has this line a single running convoi?
if( new_line.is_bound() && new_line->count_convoys() > 0 ) {
// set this schedule as current to show on minimap if possible
minimap_t::get_instance()->set_selected_cnv( new_line->get_convoy(0) );
}
else {
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
}
delete last_schedule;
last_schedule = new_line->get_schedule()->copy();
last_vehicle_count = new_line->count_convoys();
}
else if( inp_name.is_visible() ) {
// previously a line was visible
// thus the need to hide everything
line_convoys.clear();
cont.remove_all();
cont_times_history.remove_all();
cont_line_capacity_by_catg.set_line(linehandle_t());
scrolly_convois.set_visible(false);
scrolly_haltestellen.set_visible(false);
livery_selector.set_visible(false);
scrolly_line_info.set_visible(false);
inp_name.set_visible(false);
cont_times_history.set_visible(false);
cont_haltlist.set_visible(false);
scl.set_selection(-1);
bt_delete_line.disable();
bt_edit_line.disable();
for(int i=0; i<MAX_LINE_COST; i++) {
chart.hide_curve(i);
}
chart.set_visible(true);
// hide schedule on minimap (may not current, but for safe)
minimap_t::get_instance()->set_selected_cnv( convoihandle_t() );
delete last_schedule;
last_schedule = NULL;
last_vehicle_count = 0;
}
line = new_line;
bt_line_class_manager.set_visible(line.is_bound());
reset_line_name();
}
void schedule_list_gui_t::show_lineinfo(linehandle_t line)
{
update_lineinfo(line);
if( line.is_bound() ) {
// rebuilding line list will also show selection
for( uint8 i=0; i<max_idx; i++ ) {
if( tabs_to_lineindex[i]==line->get_linetype() ) {
tabs.set_active_tab_index( i );
build_line_list( i );
break;
}
}
}
}
bool schedule_list_gui_t::compare_convois(convoihandle_t const cnv1, convoihandle_t const cnv2)
{
sint32 cmp = 0;
switch (sortby) {
default:
case by_name:
cmp = strcmp(cnv1->get_internal_name(), cnv2->get_internal_name());
break;
case by_schedule:
cmp = cnv1->get_schedule()->get_current_stop() - cnv2->get_schedule()->get_current_stop();
break;
case by_profit:
cmp = sgn(cnv1->get_jahresgewinn() - cnv2->get_jahresgewinn());
break;
case by_loading_lvl:
cmp = cnv1->get_loading_level() - cnv2->get_loading_level();
break;
case by_max_speed:
cmp = cnv1->get_min_top_speed() - cnv2->get_min_top_speed();
break;
case by_power:
cmp = cnv1->get_sum_power() - cnv2->get_sum_power();
break;
case by_age:
cmp = cnv1->get_average_age() - cnv2->get_average_age();
break;
case by_value:
cmp = sgn(cnv1->get_purchase_cost() - cnv2->get_purchase_cost());
break;
}
return sortreverse ? cmp > 0 : cmp < 0;
}
// sort the line convoy list
void schedule_list_gui_t::sort_list()
{
if (!line_convoys.get_count()) {
return;
}
std::sort(line_convoys.begin(), line_convoys.end(), compare_convois);
}
void schedule_list_gui_t::update_data(linehandle_t changed_line)
{
if (changed_line.is_bound()) {
const uint16 i = tabs.get_active_tab_index();
if (tabs_to_lineindex[i] == simline_t::line || tabs_to_lineindex[i] == changed_line->get_linetype()) {
// rebuilds the line list, but does not change selection
build_line_list(i);
}
// change text input of selected line
if (changed_line.get_id() == line.get_id()) {
reset_line_name();
}
}
}
uint32 schedule_list_gui_t::get_rdwr_id()
{
return magic_line_management_t+player->get_player_nr();
}
void schedule_list_gui_t::rdwr( loadsave_t *file )
{
scr_size size;
sint32 cont_xoff, cont_yoff, halt_xoff, halt_yoff;
if( file->is_saving() ) {
size = get_windowsize();
cont_xoff = scrolly_convois.get_scroll_x();
cont_yoff = scrolly_convois.get_scroll_y();
halt_xoff = scrolly_haltestellen.get_scroll_x();
halt_yoff = scrolly_haltestellen.get_scroll_y();
}
size.rdwr( file );
simline_t::rdwr_linehandle_t(file, line);
int chart_records = line_cost_t::MAX_LINE_COST;
if( file->is_version_less(112, 8) ) {
chart_records = 8;
}
else if (file->get_extended_version() < 14 || (file->get_extended_version() == 14 && file->get_extended_revision() < 25)) {
chart_records = 12;
}
for (int i=0; i<chart_records; i++) {
bool b = filterButtons[i].pressed;
file->rdwr_bool( b );
filterButtons[i].pressed = b;
}
file->rdwr_long( cont_xoff );
file->rdwr_long( cont_yoff );
file->rdwr_long( halt_xoff );
file->rdwr_long( halt_yoff );
// open dialogue
if( file->is_loading() ) {
show_lineinfo( line );
set_windowsize( size );
resize( scr_coord(0,0) );
scrolly_convois.set_scroll_position( cont_xoff, cont_yoff );
scrolly_haltestellen.set_scroll_position( halt_xoff, halt_yoff );
}
}
| 47,571 | 20,648 |