hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58978d72f770e83000d1e64da5889556715c6722 | 1,438 | cpp | C++ | WxHook/HookPort/NativeAPI_NTDLL.cpp | ac-km/MicroMsg | 62532e184ae2fdc34ba0f711bcc4487e4d591676 | [
"MIT"
] | 2 | 2020-03-03T09:50:34.000Z | 2020-04-06T13:41:01.000Z | WxHook/HookPort/NativeAPI_NTDLL.cpp | ac-km/MicroMsg | 62532e184ae2fdc34ba0f711bcc4487e4d591676 | [
"MIT"
] | null | null | null | WxHook/HookPort/NativeAPI_NTDLL.cpp | ac-km/MicroMsg | 62532e184ae2fdc34ba0f711bcc4487e4d591676 | [
"MIT"
] | 3 | 2019-11-20T05:52:59.000Z | 2020-03-03T09:50:33.000Z | #include <windows.h>
#include <ntsecapi.h>
#include "NativeAPI_NTDLL.h"
//
//NativeAPI_NTDLL Functions
//
NTSTATUS
NTAPI
RtlInitUnicodeString(
PUNICODE_STRING DestinationString,
PCWSTR SourceString
)
{
NTSTATUS ret = NULL;
typedef NTSTATUS (WINAPI *lpAddFun)(PUNICODE_STRING,PCWSTR);
HINSTANCE hDll = GetModuleHandleW( L"ntdll.dll" );
lpAddFun addFun = (lpAddFun)GetProcAddress(hDll,"RtlInitUnicodeString");
if( addFun != NULL )
{
ret = addFun(DestinationString,SourceString);
}
return ret;
}
NTSTATUS
NTAPI
RtlFreeUnicodeString(
IN PUNICODE_STRING UnicodeString
)
{
NTSTATUS ret = NULL;
typedef NTSTATUS (WINAPI *lpAddFun)(PUNICODE_STRING);
HINSTANCE hDll = GetModuleHandleW( L"ntdll.dll" );
lpAddFun addFun = (lpAddFun)GetProcAddress(hDll,"RtlFreeUnicodeString");
if( addFun != NULL )
{
ret = addFun(UnicodeString);
}
return ret;
}
NTSTATUS
NTAPI
RtlDosPathNameToNtPathName_U(
IN PCWSTR DosPathName,
OUT PUNICODE_STRING NtPathName,
OUT PCWSTR *NtFileNamePart,
OUT CURDIR *DirectoryInfo
)
{
NTSTATUS ret = NULL;
typedef NTSTATUS (WINAPI *lpAddFun)(PCWSTR,PUNICODE_STRING,PCWSTR *,CURDIR *);
HINSTANCE hDll = GetModuleHandleW( L"ntdll.dll" );
lpAddFun addFun = (lpAddFun)GetProcAddress(hDll,"RtlDosPathNameToNtPathName_U");
if( addFun != NULL )
{
ret = addFun(DosPathName,NtPathName,NtFileNamePart,DirectoryInfo);
}
return ret;
} | 22.46875 | 82 | 0.723227 | ac-km |
589aca653d9e9089414bc18f7f96e6cf51a7e013 | 3,083 | cpp | C++ | src/interface/c_fortran/wrapResourceManager.cpp | nanzifan/Umpire-edit | 990895b527bef0716aaa0fbb0c0f2017e8e15882 | [
"MIT"
] | null | null | null | src/interface/c_fortran/wrapResourceManager.cpp | nanzifan/Umpire-edit | 990895b527bef0716aaa0fbb0c0f2017e8e15882 | [
"MIT"
] | null | null | null | src/interface/c_fortran/wrapResourceManager.cpp | nanzifan/Umpire-edit | 990895b527bef0716aaa0fbb0c0f2017e8e15882 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory
//
// Created by David Beckingsale, david@llnl.gov
// LLNL-CODE-747640
//
// All rights reserved.
//
// This file is part of Umpire.
//
// For details, see https://github.com/LLNL/Umpire
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
// wrapResourceManager.cpp
// This is generated code, do not edit
// wrapResourceManager.cpp
#include "wrapResourceManager.h"
#include <string>
#include "umpire/ResourceManager.hpp"
namespace umpire {
// splicer begin class.ResourceManager.CXX_definitions
// splicer end class.ResourceManager.CXX_definitions
extern "C" {
// splicer begin class.ResourceManager.C_definitions
// splicer end class.ResourceManager.C_definitions
UMPIRE_resourcemanager * UMPIRE_resourcemanager_get()
{
// splicer begin class.ResourceManager.method.get
auto& SH_rv = ResourceManager::getInstance(); return static_cast<UMPIRE_resourcemanager *>(static_cast<void *>(&SH_rv));
// splicer end class.ResourceManager.method.get
}
UMPIRE_allocator * UMPIRE_resourcemanager_get_allocator(UMPIRE_resourcemanager * self, const char * space)
{
// splicer begin class.ResourceManager.method.get_allocator
ResourceManager *SH_this = static_cast<ResourceManager *>(static_cast<void *>(self));
const std::string SH_space(space);
Allocator * SH_rv = new Allocator(SH_this->getAllocator(SH_space));
UMPIRE_allocator * XSH_rv = static_cast<UMPIRE_allocator *>(static_cast<void *>(SH_rv));
return XSH_rv;
// splicer end class.ResourceManager.method.get_allocator
}
UMPIRE_allocator * UMPIRE_resourcemanager_get_allocator_bufferify(UMPIRE_resourcemanager * self, const char * space, int Lspace)
{
// splicer begin class.ResourceManager.method.get_allocator_bufferify
ResourceManager *SH_this = static_cast<ResourceManager *>(static_cast<void *>(self));
const std::string SH_space(space, Lspace);
Allocator * SH_rv = new Allocator(SH_this->getAllocator(SH_space));
UMPIRE_allocator * XSH_rv = static_cast<UMPIRE_allocator *>(static_cast<void *>(SH_rv));
return XSH_rv;
// splicer end class.ResourceManager.method.get_allocator_bufferify
}
void UMPIRE_resourcemanager_copy(UMPIRE_resourcemanager * self, void * src_ptr, void * dst_ptr)
{
// splicer begin class.ResourceManager.method.copy
ResourceManager *SH_this = static_cast<ResourceManager *>(static_cast<void *>(self));
SH_this->copy(src_ptr, dst_ptr);
return;
// splicer end class.ResourceManager.method.copy
}
void UMPIRE_resourcemanager_deallocate(UMPIRE_resourcemanager * self, void * ptr)
{
// splicer begin class.ResourceManager.method.deallocate
ResourceManager *SH_this = static_cast<ResourceManager *>(static_cast<void *>(self));
SH_this->deallocate(ptr);
return;
// splicer end class.ResourceManager.method.deallocate
}
} // extern "C"
} // namespace umpire
| 37.597561 | 128 | 0.73143 | nanzifan |
589d44e3c6dfb3803e28c630ed848845cafbf452 | 8,543 | cc | C++ | src/drivers/devices/cuda/flowunit/normalize_v2/normalize_flowunit_test.cc | fujl/modelbox | 390541a87318bb6f8a37163668b439e5387f5d9a | [
"Apache-2.0"
] | 1 | 2021-12-16T06:53:00.000Z | 2021-12-16T06:53:00.000Z | src/drivers/devices/cuda/flowunit/normalize_v2/normalize_flowunit_test.cc | fujl/modelbox | 390541a87318bb6f8a37163668b439e5387f5d9a | [
"Apache-2.0"
] | null | null | null | src/drivers/devices/cuda/flowunit/normalize_v2/normalize_flowunit_test.cc | fujl/modelbox | 390541a87318bb6f8a37163668b439e5387f5d9a | [
"Apache-2.0"
] | 1 | 2021-12-03T06:19:09.000Z | 2021-12-03T06:19:09.000Z | /*
* Copyright 2021 The Modelbox Project 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 <securec.h>
#include <functional>
#include <future>
#include <opencv2/opencv.hpp>
#include <random>
#include <thread>
#include <cuda_runtime.h>
#include "modelbox/base/log.h"
#include "modelbox/base/utils.h"
#include "modelbox/buffer.h"
#include "driver_flow_test.h"
#include "flowunit_mockflowunit/flowunit_mockflowunit.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::_;
namespace modelbox {
class NormalizeV2FlowUnitTest : public testing::Test {
public:
NormalizeV2FlowUnitTest()
: driver_flow_(std::make_shared<DriverFlowTest>()) {}
protected:
virtual void SetUp() {
int count = 0;
cudaGetDeviceCount(&count);
if (count <= 0) {
MBLOG_INFO << "no cuda device, skip test suit";
GTEST_SKIP();
}
auto ret = AddMockFlowUnit();
EXPECT_EQ(ret, STATUS_OK);
};
virtual void TearDown() { driver_flow_->Clear(); };
std::shared_ptr<DriverFlowTest> GetDriverFlow();
private:
Status AddMockFlowUnit();
std::shared_ptr<DriverFlowTest> driver_flow_;
};
std::shared_ptr<DriverFlowTest> NormalizeV2FlowUnitTest::GetDriverFlow() {
return driver_flow_;
}
Status NormalizeV2FlowUnitTest::AddMockFlowUnit() {
auto ctl_ = driver_flow_->GetMockFlowCtl();
{
MockFlowUnitDriverDesc desc_flowunit;
desc_flowunit.SetClass("DRIVER-FLOWUNIT");
desc_flowunit.SetType("cpu");
desc_flowunit.SetName("copy");
desc_flowunit.SetDescription("just copy data flowunit on CPU");
desc_flowunit.SetVersion("1.0.0");
std::string file_path_flowunit =
std::string(TEST_DRIVER_DIR) + "/libmodelbox-unit-cpu-copy.so";
desc_flowunit.SetFilePath(file_path_flowunit);
auto mock_flowunit = std::make_shared<MockFlowUnit>();
auto mock_flowunit_desc = std::make_shared<FlowUnitDesc>();
mock_flowunit_desc->SetFlowUnitName("copy");
mock_flowunit_desc->AddFlowUnitInput(modelbox::FlowUnitInput("input"));
mock_flowunit_desc->AddFlowUnitOutput(modelbox::FlowUnitOutput("output"));
mock_flowunit_desc->SetFlowType(modelbox::NORMAL);
mock_flowunit->SetFlowUnitDesc(mock_flowunit_desc);
std::weak_ptr<MockFlowUnit> mock_flowunit_wp;
mock_flowunit_wp = mock_flowunit;
EXPECT_CALL(*mock_flowunit, Open(_))
.WillRepeatedly(testing::Invoke(
[=](const std::shared_ptr<modelbox::Configuration>& flow_option) {
return modelbox::STATUS_OK;
}));
EXPECT_CALL(*mock_flowunit, DataPre(_))
.WillRepeatedly(
testing::Invoke([&](std::shared_ptr<DataContext> data_ctx) {
return modelbox::STATUS_OK;
}));
EXPECT_CALL(*mock_flowunit, DataPost(_))
.WillRepeatedly(
testing::Invoke([&](std::shared_ptr<DataContext> data_ctx) {
return modelbox::STATUS_OK;
}));
EXPECT_CALL(*mock_flowunit,
Process(testing::An<std::shared_ptr<modelbox::DataContext>>()))
.WillRepeatedly(
testing::Invoke([=](std::shared_ptr<DataContext> op_ctx) {
auto input = op_ctx->Input("input");
auto output = op_ctx->Output("output");
for (size_t i = 0; i < input->Size(); ++i) {
output->PushBack(input->At(i));
}
return modelbox::STATUS_OK;
}));
EXPECT_CALL(*mock_flowunit, Close()).WillRepeatedly(testing::Invoke([=]() {
return modelbox::STATUS_OK;
}));
desc_flowunit.SetMockFlowUnit(mock_flowunit);
ctl_->AddMockDriverFlowUnit("copy", "cpu", desc_flowunit,
std::string(TEST_DRIVER_DIR));
}
return STATUS_OK;
}
TEST_F(NormalizeV2FlowUnitTest, NormalizeV2Test) {
const std::string test_lib_dir = TEST_DRIVER_DIR;
std::string toml_content = R"(
[driver]
skip-default=true
dir=[")" + test_lib_dir + "\"]\n " +
R"([graph]
graphconf = '''digraph demo {
input1[type=input]
normalize_v2[type=flowunit, flowunit=image_preprocess, device=cuda, deviceid=0, label="<in_image> | <out_data>", output_layout="hwc", mean="0.0, 0.0, 0.0", standard_deviation_inverse="1.0, 1.0, 1.0"]
normalize_v2_chw[type=flowunit, flowunit=image_preprocess, device=cuda, deviceid=0, label="<in_image> | <out_data>", output_layout="chw", mean="0.0, 0.0, 0.0", standard_deviation_inverse="1.0, 1.0, 1.0"]
copy[type=flowunit, flowunit=copy, device=cpu, deviceid=0, label="<input> | <output>"]
copy_chw[type=flowunit, flowunit=copy, device=cpu, deviceid=0, label="<input> | <output>"]
output_hwc[type=output]
output_chw[type=output]
input1 -> normalize_v2:in_image
input1 -> normalize_v2_chw:in_image
normalize_v2:out_data -> copy:input
normalize_v2_chw:out_data -> copy_chw:input
copy:output -> output_hwc
copy_chw:output -> output_chw
}'''
format = "graphviz"
)";
auto driver_flow = GetDriverFlow();
auto ret = driver_flow->BuildAndRun("InitUnit", toml_content, -1);
auto flow = driver_flow->GetFlow();
auto ext_data = flow->CreateExternalDataMap();
{
std::string gimg_path = std::string(TEST_ASSETS) + "/test.jpg";
cv::Mat bgr_img = cv::imread(gimg_path.c_str());
cv::Mat bgr_img_float, bgr_img_float_chw;
bgr_img.convertTo(bgr_img_float, CV_32FC3);
bgr_img.convertTo(bgr_img_float_chw, CV_32FC3);
int height = bgr_img_float.rows;
int width = bgr_img_float.cols;
int channel = bgr_img_float.channels();
for (int c = 0; c < channel; ++c) {
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
int dstIdx = c * height * width + h * width + w;
int srcIdx = h * width * channel + w * channel + c;
*((float*)((void*)bgr_img_float_chw.data) + dstIdx) =
*(((float*)((void*)bgr_img_float.data)) + srcIdx);
}
}
}
std::vector<std::string> output_name({"output_hwc", "output_chw"});
std::vector<cv::Mat> opencv_out_check({bgr_img_float, bgr_img_float_chw});
auto color_bl = ext_data->CreateBufferList();
size_t img_size = bgr_img.total() * bgr_img.elemSize();
color_bl->BuildFromHost({img_size}, bgr_img.data, img_size);
// HWC
color_bl->Set("shape", std::vector<size_t>(
{static_cast<size_t>(bgr_img.rows),
static_cast<size_t>(bgr_img.cols),
static_cast<size_t>(bgr_img.channels())}));
color_bl->Set("layout", std::string("hwc"));
color_bl->Set("type", ModelBoxDataType::MODELBOX_UINT8);
color_bl->Set("pix_fmt", "bgr");
auto status = ext_data->Send("input1", color_bl);
EXPECT_EQ(status, STATUS_OK);
OutputBufferList map_buffer_list;
status = ext_data->Recv(map_buffer_list);
EXPECT_EQ(status, STATUS_OK);
for (size_t j = 0; j < output_name.size(); j++) {
auto buffer_list = map_buffer_list[output_name[j]];
EXPECT_EQ(buffer_list->Size(), 1);
EXPECT_EQ(buffer_list->GetBytes(),
opencv_out_check[j].total() * opencv_out_check[j].elemSize());
ModelBoxDataType type = MODELBOX_TYPE_INVALID;
buffer_list->At(0)->Get("type", type);
EXPECT_EQ(type, ModelBoxDataType::MODELBOX_FLOAT);
auto* opencv_data = (float*)opencv_out_check[j].data;
const auto* out_data = (float*)(buffer_list->ConstBufferData(0));
size_t count = buffer_list->GetBytes() / sizeof(float);
for (size_t k = 0; k < count; ++k) {
EXPECT_TRUE(*(out_data + k) - *(opencv_data + k) < 0.00000001);
EXPECT_TRUE(*(opencv_data + k) - *(out_data + k) < 0.00000001);
}
}
}
MBLOG_INFO << "Send Shutdown";
auto status = ext_data->Shutdown();
EXPECT_EQ(status, STATUS_OK);
flow->Wait(1000);
} // namespace modelbox
} // namespace modelbox | 36.046414 | 213 | 0.648484 | fujl |
58a271f9275e3f6b982ab216d7fa657c2b9ff260 | 6,113 | cpp | C++ | android-31/android/net/sip/SipManager.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/net/sip/SipManager.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/net/sip/SipManager.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../app/PendingIntent.hpp"
#include "../../content/Context.hpp"
#include "../../content/Intent.hpp"
#include "./SipAudioCall.hpp"
#include "./SipAudioCall_Listener.hpp"
#include "./SipProfile.hpp"
#include "./SipSession.hpp"
#include "./SipSession_Listener.hpp"
#include "../../../JString.hpp"
#include "./SipManager.hpp"
namespace android::net::sip
{
// Fields
JString SipManager::EXTRA_CALL_ID()
{
return getStaticObjectField(
"android.net.sip.SipManager",
"EXTRA_CALL_ID",
"Ljava/lang/String;"
);
}
JString SipManager::EXTRA_OFFER_SD()
{
return getStaticObjectField(
"android.net.sip.SipManager",
"EXTRA_OFFER_SD",
"Ljava/lang/String;"
);
}
jint SipManager::INCOMING_CALL_RESULT_CODE()
{
return getStaticField<jint>(
"android.net.sip.SipManager",
"INCOMING_CALL_RESULT_CODE"
);
}
// QJniObject forward
SipManager::SipManager(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
JString SipManager::getCallId(android::content::Intent arg0)
{
return callStaticObjectMethod(
"android.net.sip.SipManager",
"getCallId",
"(Landroid/content/Intent;)Ljava/lang/String;",
arg0.object()
);
}
JString SipManager::getOfferSessionDescription(android::content::Intent arg0)
{
return callStaticObjectMethod(
"android.net.sip.SipManager",
"getOfferSessionDescription",
"(Landroid/content/Intent;)Ljava/lang/String;",
arg0.object()
);
}
jboolean SipManager::isApiSupported(android::content::Context arg0)
{
return callStaticMethod<jboolean>(
"android.net.sip.SipManager",
"isApiSupported",
"(Landroid/content/Context;)Z",
arg0.object()
);
}
jboolean SipManager::isIncomingCallIntent(android::content::Intent arg0)
{
return callStaticMethod<jboolean>(
"android.net.sip.SipManager",
"isIncomingCallIntent",
"(Landroid/content/Intent;)Z",
arg0.object()
);
}
jboolean SipManager::isSipWifiOnly(android::content::Context arg0)
{
return callStaticMethod<jboolean>(
"android.net.sip.SipManager",
"isSipWifiOnly",
"(Landroid/content/Context;)Z",
arg0.object()
);
}
jboolean SipManager::isVoipSupported(android::content::Context arg0)
{
return callStaticMethod<jboolean>(
"android.net.sip.SipManager",
"isVoipSupported",
"(Landroid/content/Context;)Z",
arg0.object()
);
}
android::net::sip::SipManager SipManager::newInstance(android::content::Context arg0)
{
return callStaticObjectMethod(
"android.net.sip.SipManager",
"newInstance",
"(Landroid/content/Context;)Landroid/net/sip/SipManager;",
arg0.object()
);
}
void SipManager::close(JString arg0) const
{
callMethod<void>(
"close",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
android::net::sip::SipSession SipManager::createSipSession(android::net::sip::SipProfile arg0, android::net::sip::SipSession_Listener arg1) const
{
return callObjectMethod(
"createSipSession",
"(Landroid/net/sip/SipProfile;Landroid/net/sip/SipSession$Listener;)Landroid/net/sip/SipSession;",
arg0.object(),
arg1.object()
);
}
android::net::sip::SipSession SipManager::getSessionFor(android::content::Intent arg0) const
{
return callObjectMethod(
"getSessionFor",
"(Landroid/content/Intent;)Landroid/net/sip/SipSession;",
arg0.object()
);
}
jboolean SipManager::isOpened(JString arg0) const
{
return callMethod<jboolean>(
"isOpened",
"(Ljava/lang/String;)Z",
arg0.object<jstring>()
);
}
jboolean SipManager::isRegistered(JString arg0) const
{
return callMethod<jboolean>(
"isRegistered",
"(Ljava/lang/String;)Z",
arg0.object<jstring>()
);
}
android::net::sip::SipAudioCall SipManager::makeAudioCall(android::net::sip::SipProfile arg0, android::net::sip::SipProfile arg1, android::net::sip::SipAudioCall_Listener arg2, jint arg3) const
{
return callObjectMethod(
"makeAudioCall",
"(Landroid/net/sip/SipProfile;Landroid/net/sip/SipProfile;Landroid/net/sip/SipAudioCall$Listener;I)Landroid/net/sip/SipAudioCall;",
arg0.object(),
arg1.object(),
arg2.object(),
arg3
);
}
android::net::sip::SipAudioCall SipManager::makeAudioCall(JString arg0, JString arg1, android::net::sip::SipAudioCall_Listener arg2, jint arg3) const
{
return callObjectMethod(
"makeAudioCall",
"(Ljava/lang/String;Ljava/lang/String;Landroid/net/sip/SipAudioCall$Listener;I)Landroid/net/sip/SipAudioCall;",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object(),
arg3
);
}
void SipManager::open(android::net::sip::SipProfile arg0) const
{
callMethod<void>(
"open",
"(Landroid/net/sip/SipProfile;)V",
arg0.object()
);
}
void SipManager::open(android::net::sip::SipProfile arg0, android::app::PendingIntent arg1, JObject arg2) const
{
callMethod<void>(
"open",
"(Landroid/net/sip/SipProfile;Landroid/app/PendingIntent;Landroid/net/sip/SipRegistrationListener;)V",
arg0.object(),
arg1.object(),
arg2.object()
);
}
void SipManager::register_(android::net::sip::SipProfile arg0, jint arg1, JObject arg2) const
{
callMethod<void>(
"register",
"(Landroid/net/sip/SipProfile;ILandroid/net/sip/SipRegistrationListener;)V",
arg0.object(),
arg1,
arg2.object()
);
}
void SipManager::setRegistrationListener(JString arg0, JObject arg1) const
{
callMethod<void>(
"setRegistrationListener",
"(Ljava/lang/String;Landroid/net/sip/SipRegistrationListener;)V",
arg0.object<jstring>(),
arg1.object()
);
}
android::net::sip::SipAudioCall SipManager::takeAudioCall(android::content::Intent arg0, android::net::sip::SipAudioCall_Listener arg1) const
{
return callObjectMethod(
"takeAudioCall",
"(Landroid/content/Intent;Landroid/net/sip/SipAudioCall$Listener;)Landroid/net/sip/SipAudioCall;",
arg0.object(),
arg1.object()
);
}
void SipManager::unregister(android::net::sip::SipProfile arg0, JObject arg1) const
{
callMethod<void>(
"unregister",
"(Landroid/net/sip/SipProfile;Landroid/net/sip/SipRegistrationListener;)V",
arg0.object(),
arg1.object()
);
}
} // namespace android::net::sip
| 26.811404 | 194 | 0.707836 | YJBeetle |
58a5a73b37d63a3a39785b2a41d16047d83472c5 | 5,646 | hh | C++ | dune/gdt/local/fluxes/interfaces.hh | TiKeil/dune-gdt | 25c8b987cc07a4b8b966c1a07ea21b78dba7852f | [
"BSD-2-Clause"
] | null | null | null | dune/gdt/local/fluxes/interfaces.hh | TiKeil/dune-gdt | 25c8b987cc07a4b8b966c1a07ea21b78dba7852f | [
"BSD-2-Clause"
] | null | null | null | dune/gdt/local/fluxes/interfaces.hh | TiKeil/dune-gdt | 25c8b987cc07a4b8b966c1a07ea21b78dba7852f | [
"BSD-2-Clause"
] | null | null | null | // This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2016 - 2017)
// Rene Milk (2016 - 2018)
// Tobias Leibner (2016 - 2017)
#ifndef DUNE_GDT_LOCAL_FLUXES_INTERFACES_HH
#define DUNE_GDT_LOCAL_FLUXES_INTERFACES_HH
#include <dune/grid/yaspgrid.hh>
#include <dune/xt/common/crtp.hh>
#include <dune/xt/grid/boundaryinfo/types.hh>
#include <dune/xt/functions/interfaces.hh>
namespace Dune {
namespace GDT {
template <class Traits>
class LocalNumericalCouplingFluxInterface
: public XT::Common::CRTPInterface<LocalNumericalCouplingFluxInterface<Traits>, Traits>
{
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::EntityType EntityType;
public:
LocalfunctionTupleType local_functions(const EntityType& entity) const
{
CHECK_CRTP(this->as_imp().local_functions(entity))
return this->as_imp().local_functions(entity);
}
template <class E, class D, size_t d, class R, size_t r, size_t rC, class IntersectionType>
auto evaluate(const LocalfunctionTupleType& local_functions_tuple_entity,
const LocalfunctionTupleType& local_functions_tuple_neighbor,
const XT::Functions::LocalfunctionInterface<E, D, d, R, r, rC>& local_source_entity,
const XT::Functions::LocalfunctionInterface<E, D, d, R, r, rC>& local_source_neighbor,
const IntersectionType& intersection,
const Dune::FieldVector<D, d - 1>& x_intersection) const ->
typename XT::Functions::LocalfunctionSetInterface<E, D, d, R, r, rC>::RangeType
{
CHECK_CRTP(this->as_imp().evaluate(local_functions_tuple_entity,
local_functions_tuple_neighbor,
local_source_entity,
local_source_neighbor,
intersection,
x_intersection));
this->as_imp().evaluate(local_functions_tuple_entity,
local_functions_tuple_neighbor,
local_source_entity,
local_source_neighbor,
intersection,
x_intersection);
}
}; // class LocalNumericalCouplingFluxInterface
template <class Traits>
class LocalNumericalBoundaryFluxInterface
: public XT::Common::CRTPInterface<LocalNumericalBoundaryFluxInterface<Traits>, Traits>
{
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::BoundaryValueType BoundaryValueType;
typedef typename Traits::DomainFieldType DomainFieldType;
typedef typename Traits::RangeFieldType RangeFieldType;
typedef typename Traits::AnalyticalFluxType AnalyticalFluxType;
typedef typename Traits::RangeType RangeType;
typedef typename Traits::DomainType DomainType;
static const size_t dimDomain = Traits::dimDomain;
static const size_t dimRange = Traits::dimRange;
public:
LocalNumericalBoundaryFluxInterface(const BoundaryValueType& boundary_values)
: boundary_values_(boundary_values)
{
}
LocalfunctionTupleType local_functions(const EntityType& entity) const
{
CHECK_CRTP(this->as_imp().local_functions(entity));
return this->as_imp().local_functions(entity);
}
template <class E, class D, size_t d, class R, size_t r, size_t rC, class IntersectionType>
auto evaluate(const LocalfunctionTupleType& local_functions_tuple,
const XT::Functions::LocalfunctionInterface<E, D, d, R, r, rC>& local_source_entity,
const IntersectionType& intersection,
const Dune::FieldVector<D, d - 1>& x_intersection) const ->
typename XT::Functions::LocalfunctionSetInterface<E, D, d, R, r, rC>::RangeType
{
CHECK_CRTP(this->as_imp().evaluate(local_functions_tuple, local_source_entity, intersection, x_intersection))
return this->as_imp().evaluate(local_functions_tuple, local_source_entity, intersection, x_intersection);
}
protected:
// returns u_i, u_j and x_in_inside_coords
template <class IntersectionType, size_t boundary_value_pos>
std::tuple<RangeType, RangeType, DomainType> get_values(
const LocalfunctionTupleType& local_functions_tuple,
const XT::Functions::LocalfunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1>&
local_source_entity,
const IntersectionType& intersection,
const Dune::FieldVector<DomainFieldType, dimDomain - 1>& x_in_intersection_coords) const
{
std::tuple<RangeType, RangeType, DomainType> ret;
auto& u_i = std::get<0>(ret);
auto& u_j = std::get<1>(ret);
auto& x_in_inside_coords = std::get<2>(ret);
x_in_inside_coords = intersection.geometryInInside().global(x_in_intersection_coords);
u_i = local_source_entity.evaluate(x_in_inside_coords);
u_j = std::get<boundary_value_pos>(local_functions_tuple)->evaluate(intersection, x_in_inside_coords, u_i);
return ret;
}
const BoundaryValueType& boundary_values_;
}; // class LocalNumericalBoundaryFluxInterface
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_FLUXES_INTERFACES_HH
| 42.451128 | 119 | 0.712894 | TiKeil |
58a690aac4e2789ffa80ba900995aa0f238ec038 | 5,397 | cp | C++ | Sources_Common/i18n/IDN/CPunyCode.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Sources_Common/i18n/IDN/CPunyCode.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Sources_Common/i18n/IDN/CPunyCode.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// Source for CPunyCode class
#include "CPunyCode.h"
#include "cdustring.h"
#include <strstream>
using namespace idn;
// base36 tables
static char basis_36[] =
"abcdefghijklmnopqrstuvwxyz0123456789";
static signed char index_36[128] =
{
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
26,27,28,29, 30,31,32,33, 34,35,-1,-1, -1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1
};
#define CHAR36(c) (((c) < 0 || (c) > 127) ? -1 : index_36[(c)])
// punycode constants from RFC3492
const int cBase = 36;
const int cTmin = 1;
const int cTmax = 26;
const int cSkew = 38;
const int cDamp = 700;
const int cInitialBias = 72;
const unsigned long cInitialN = 128;
const char* cPrefix = "xn--";
const char cDelimiter = '-';
// Encode : punycode encode
//
// str : data to encode (input format is utf8)
void CPunyCode::Encode(cdstring& str)
{
// See whether any non-ascii chars exist
bool non_ascii = false;
const char* p = str.c_str();
while(*p)
{
if (*(unsigned char*)p++ > 0x7F)
{
non_ascii = true;
break;
}
}
// Just exit if nothing to do
if (!non_ascii)
return;
// Get unicode version of string
cdustring ustr(str);
int ulen = ustr.length();
// Write the prefix
ostrstream sout;
sout << cPrefix;
unsigned long n = cInitialN;
unsigned long delta = 0;
int bias = cInitialBias;
// Write out each basic char
int b = 0;
const unichar_t* up = ustr.c_str();
while(*up)
{
if (*up < 0x0080)
{
b++;
sout.put(*up);
}
up++;
}
// Write out delimiter if some basic chars found
if (b > 0)
sout.put(cDelimiter);
int h = b;
while(h < ulen)
{
// Find smallest code point >= n and its pos
unsigned long m = 0xFFFF;
int mpos = -1;
for(unsigned long ctr = 0; ctr < ulen; ctr++)
{
if ((ustr[ctr] >= n) && (ustr[ctr] < m))
{
m = ustr[ctr];
mpos = ctr;
}
}
delta += (m - n) * (h + 1);
n = m;
// Encode all instances of m in the input string
for(unsigned long ctr = 0; ctr < ulen; ctr++)
{
if (ustr[ctr] < n)
delta++;
else if (ustr[ctr] == n)
{
unsigned long q = delta;
for(int k = cBase - bias; true; k += cBase)
{
int t = (k <= cTmin) ? cTmin : ((k >= cTmax) ? cTmax : k);
if (q < t)
break;
unsigned long digit = t + ((q - t) % (cBase - t));
if (digit < cBase)
sout.put(basis_36[digit]);
q = (q - t) / (cBase - t);
}
if (q < cBase)
sout.put(basis_36[q]);
bias = Adapt(delta, h + 1, h == b);
delta = 0;
h++;
}
}
delta++;
n++;
}
sout << ends;
str.steal(sout.str());
}
// Decode : punycode decode
//
// str : c-str to decode (output is utf8)
void CPunyCode::Decode(cdstring& str)
{
// Just exit if prefix is not present
if (!str.compare_start(cPrefix))
return;
// Grab chars up to delimiter
cdstring::size_type pos = str.rfind(cDelimiter);
// Must have valid delimiter
if (pos < 4)
return;
// Split string into basic and encoded parts
cdstring basic;
cdstring encoded;
if (pos == cdstring::npos)
{
// Use entire string as encoded
encoded.assign(str, 4);
}
else
{
// Split at pos
basic.assign(str, 4, pos - 4);
encoded.assign(str, pos + 1);
}
cdustring ubasic(basic);
int n = cInitialN;
int i = 0;
int bias = cInitialBias;
const char* input = encoded.c_str();
while(*input)
{
int oldi = i;
int w = 1;
int len1 = ubasic.length() + 1;
if (!ReadChar(&input, bias, i))
return;
bias = Adapt(i - oldi, len1, oldi == 0);
// Get <n, i> value
n += i / len1;
i = i % len1;
// Do char insert
cdustring temp(ubasic, 0, i);
temp.append((unichar_t) n);
temp.append(ubasic, i, cdustring::npos);
ubasic = temp;
i++;
}
str = ubasic.ToUTF8();
}
bool CPunyCode::ReadChar(const char** input, int bias, int& output)
{
int i = 0;
int w = 1;
for(int k = cBase - bias; true; k += cBase)
{
int digit = CHAR36(**input);
(*input)++;
if (digit == -1)
return false;
i += digit * w;
int t = (k < cTmin) ? cTmin : ((k > cTmax) ? cTmax : k);
if (digit < t)
break;
w *= (cBase - t);
}
output += i;
return true;
}
int CPunyCode::Adapt(int delta, int numpoints, bool firsttime)
{
delta /= firsttime ? cDamp : 2;
delta += delta / numpoints;
int k = 0;
while(delta > ((cBase - cTmin) * cTmax) / 2)
{
delta /= (cBase - cTmin);
k += cBase;
}
return k + ((cBase - cTmin + 1) * delta) / (delta + cSkew);
}
| 20.213483 | 76 | 0.575505 | mulberry-mail |
58a8f8ad0061350194ddbfd0437593a3d27eedd6 | 2,164 | cpp | C++ | tool_kits/ui_component/ui_kit/gui/plugins/session/session_plugin_icon.cpp | stephenzhj/NIM_PC_Demo | 0d2933955e079afa5c9e4df196ee017fad6c79af | [
"BSD-2-Clause",
"OpenSSL"
] | 161 | 2016-01-24T13:55:15.000Z | 2021-06-01T03:48:56.000Z | tool_kits/ui_component/ui_kit/gui/plugins/session/session_plugin_icon.cpp | stephenzhj/NIM_PC_Demo | 0d2933955e079afa5c9e4df196ee017fad6c79af | [
"BSD-2-Clause",
"OpenSSL"
] | 49 | 2016-01-24T14:06:52.000Z | 2021-06-01T07:14:53.000Z | tool_kits/ui_component/ui_kit/gui/plugins/session/session_plugin_icon.cpp | xiejiulong/NIM_PC_Demo | 47f74270b200bb365035209c9734723f1cb7efea | [
"BSD-2-Clause",
"OpenSSL"
] | 140 | 2016-02-22T09:42:07.000Z | 2021-05-26T01:15:12.000Z | #include "stdafx.h"
#include "stdafx.h"
#include "session_plugin_icon.h"
#include "export\nim_ui_session_list_manager.h"
#include "gui\main\control\custom_button_box.h"
#include "module\session\session_manager.h"
using namespace nim_comp;
SessionPluginIcon::SessionPluginIcon() :
real_option_(nullptr), label_unread_(nullptr), box_unread_(nullptr)
{
}
SessionPluginIcon::~SessionPluginIcon()
{
}
ui::Control* SessionPluginIcon::CreateControl(const std::wstring& pstrClass)
{
if (pstrClass == L"CustomButtonBox")
{
return new nim_comp::CustomButtonBox;
}
return NULL;
}
void SessionPluginIcon::DoInit()
{
real_option_ = dynamic_cast<ui::OptionBox*>(FindSubControl(L"op_ctrl"));
label_unread_ = dynamic_cast<ui::Label*>(FindSubControl(L"label_unread"));
box_unread_ = dynamic_cast<nim_comp::CustomButtonBox*>(FindSubControl(L"box_unread"));
box_unread_->AttachClick([this](ui::EventArgs* param){
nim::Session::SetAllUnreadCountZeroAsync([this](nim::NIMResCode rescode, const nim::SessionData& data, int total_unread_counts){
if (rescode != nim::kNIMResSuccess)
{
QLOG_APP(L"SetAllUnreadCountZeroAsync::OnChangeCallback Error! {0}, uid:{1}, unread_count: {2}") << rescode << data.id_ << total_unread_counts;
assert(0);
return;
}
if (data.command_ == nim::kNIMSessionCommandUpdate)
{
nim_comp::SessionManager::GetInstance()->ResetUnread(data.id_);
}
});
nim::MsgLog::ReadAllAsync(nim::MsgLog::DBFunctionCallback());
return true;
});
AttachSelect([this](ui::EventArgs* param){
real_option_->Selected(true, false);
return true;
});
AttachUnSelect([this](ui::EventArgs* param){
real_option_->Selected(false, false);
return true;
});
}
ui::OptionBox* SessionPluginIcon::GetPluginIconAction()
{
return real_option_;
}
void SessionPluginIcon::OnSessionListAttached()
{
nim_ui::SessionListManager::GetInstance()->RegUnreadCountChange([this](int unread_count){
if (unread_count > 0)
{
label_unread_->SetText(unread_count > 99 ? nbase::StringPrintf(L"99+") : nbase::StringPrintf(L"%d", unread_count));
box_unread_->SetVisible(true);
}
else
{
box_unread_->SetVisible(false);
}
});
} | 28.853333 | 147 | 0.733826 | stephenzhj |
58aa5d0fd55d1241d7f626d7bd9b5bd178de4535 | 3,713 | cpp | C++ | cpu_general/test.cpp | 111116/shfft | e7ad335ddb36ee60b251b74c6a4c707a009bef7d | [
"MIT"
] | 12 | 2021-12-15T14:19:06.000Z | 2022-03-08T07:31:12.000Z | cpu_general/test.cpp | 111116/shfft | e7ad335ddb36ee60b251b74c6a4c707a009bef7d | [
"MIT"
] | 2 | 2021-12-15T14:17:55.000Z | 2021-12-15T14:18:23.000Z | cpu_general/test.cpp | 111116/shfft | e7ad335ddb36ee60b251b74c6a4c707a009bef7d | [
"MIT"
] | 1 | 2021-12-31T16:26:31.000Z | 2021-12-31T16:26:31.000Z | // Note: performance of this demo may be sub-optimal.
// This program is a demonstration of computing SH products
// with arbitary k value, using the divide-and-conquer strategy. To obtain
// better performance, order of computation may be arranged with care,
// especially for small fixed k value.
#include <iostream>
#include <cmath>
#include <vector>
#include "lib/consolelog.hpp"
#include "fourierseries.hpp"
#include "fastmul.hpp"
#include "sh.hpp"
#include "precompute_sh2fs.hpp"
#include "precompute_fs2sh.hpp"
#include "readgamma.hpp"
typedef FourierSeries<float> FS;
FS sh2fs(const SH& sh)
{
int n = sh.n;
FS fs = FS::zeros(sh.n);
for (int l=0; l<n; ++l)
for (int m=-l; m<=l; ++m) {
int i = SHIndex(l,m);
for (int a=-n+1; a<n; ++a) {
fs.at(a,-m) += sh.a[i] * coeff_sh2fs[i*4*n + a+n-1];
fs.at(a, m) += sh.a[i] * coeff_sh2fs[i*4*n + a+n-1 + 2*n];
}
}
return fs;
}
SH fs2sh(int n, int k, const FS& fs)
{
SH sh(n);
for (int l=0; l<n; ++l)
for (int m=-l; m<=l; ++m) {
int i = SHIndex(l,m);
int b = -std::abs(m);
for (int a=-(k*n-k); a<=0; ++a) {
auto t = coeff_fs2sh[i * k*n -a];
auto x = fs.at(a,b);
sh.a[i] += t.real() * x.real() - t.imag() * x.imag();
}
}
return sh;
}
using std::vector;
SH reference_prod(vector<SH> inputs)
{
// checks
int n_elem = inputs.size();
if (n_elem == 0) throw "bad k";
int n = inputs[0].n;
if (n==0) throw "bad n";
for (auto s: inputs)
if (s.n != n)
throw "input of varying order unsupported";
if (sizeof(inputs[0].a.back()) != sizeof(float))
throw "bad data type";
// compute reference
int N = (n-1)*((n_elem+1)/2)+1;
auto gamma = readGamma(N);
float A[N*N], B[N*N], C[N*N];
memset(A, 0, N*N*sizeof(float));
memcpy(A, inputs[0].a.data(), n*n*sizeof(float));
memset(B, 0, N*N*sizeof(float));
for (int i=1; i<inputs.size(); ++i) {
memcpy(B, inputs[i].a.data(), n*n*sizeof(float));
memset(C, 0, N*N*sizeof(float));
for (auto e: gamma)
C[e.c] += e.val * A[e.a] * B[e.b];
memcpy(A, C, N*N*sizeof(float));
}
SH ref(n);
memcpy(ref.a.data(), A, n*n*sizeof(float));
return ref;
}
int main()
{
// n: order of SH (i.e. n^2 coefficients each SH)
// Result is (k-1) SH functions multiplied, reprojected onto n-th SH basis.
int n=4, k=7;
// Note: n and k can be assigned arbitarily at runtime.
// Here we demonstrate runtime precomputation.
// Performance of this demo may be suboptimal.
console.log("n=", n);
console.log("k=", k);
precompute_sh2fs(n);
// Note: if k is too large (i.e. product of many terms is required),
// it's usually reasonable to truncate intermediate results
// to avoid precomputing a very large conversion for the final result.
precompute_fs2sh(n,k);
// generate random multiplicands
vector<SH> inputs;
for (int i=0; i<k-1; ++i) {
SH sh(n);
for (int l=0; l<n; ++l)
for (int m=-l; m<=l; m++) {
sh.at(l,m) = (float)rand()/RAND_MAX-0.5;
}
inputs.push_back(sh);
}
// run our algorithm
// step 1. convert to Fourier series
vector<FS> fs;
for (auto s: inputs)
fs.push_back(sh2fs(s));
// step 2. compute product of Fourier series
FS prod = prod_divide_and_conquer(fs);
// step 3. convert back to SH
SH res = fs2sh(n,k,prod);
// check correctness
SH ref = reference_prod(inputs);
console.log("err:", (ref-res).magnitude() / ref.magnitude());
}
| 29.007813 | 80 | 0.558039 | 111116 |
58aae1e3dd9a3c5d980b8936222a6f4c642cf688 | 3,596 | hpp | C++ | Server/include/rhio_server/ServerPub.hpp | ipab-slmc/RhIO | 45f5440a745d5ae9b256335a78ded799d3a02d4d | [
"MIT"
] | null | null | null | Server/include/rhio_server/ServerPub.hpp | ipab-slmc/RhIO | 45f5440a745d5ae9b256335a78ded799d3a02d4d | [
"MIT"
] | 1 | 2018-12-11T18:36:07.000Z | 2018-12-11T18:36:07.000Z | Server/include/rhio_server/ServerPub.hpp | ipab-slmc/RhIO | 45f5440a745d5ae9b256335a78ded799d3a02d4d | [
"MIT"
] | null | null | null | #ifndef RHIO_SERVERPUB_HPP
#define RHIO_SERVERPUB_HPP
#include <string>
#include <list>
#include <mutex>
#include <zmq.hpp>
#include "RhIO.hpp"
#include "rhio_common/LockFreeDoubleQueue.hpp"
namespace RhIO {
/**
* ServerPub
*
* Implement Streaming publisher
* using ZMQ network library
*/
class ServerPub
{
public:
/**
* Initialization with the bind
* endpoint string
*/
ServerPub(std::string endpoint = "");
/**
* Append to publish buffer value for type
* Bool, Int, Float, Str with given absolute
* name and timestamp
*/
void publishBool(const std::string& name,
bool val, int64_t timestamp);
void publishInt(const std::string& name,
int64_t val, int64_t timestamp);
void publishFloat(const std::string& name,
double val, int64_t timestamp);
void publishStr(const std::string& name,
const std::string& val, int64_t timestamp);
/**
* Append to publish buffer stream
* given absolute name, string and timestamp
*/
void publishStream(const std::string& name,
const std::string& val, int64_t timestamp);
/**
* Append to publish buffer frame
* given absolute name, timestamp,
* frame data and size.
* The data is immediatly copied.
*/
void publishFrame(const std::string& name,
size_t width, size_t height,
unsigned char* data, size_t size,
int64_t timestamp);
/**
* Switch values buffer and publish to Client
* all registered values in former writing buffer.
*/
void sendToClient();
private:
/**
* Structure for typed values
* to publish
*/
template <typename T>
struct PubValue {
std::string name;
T value;
int64_t timestamp;
};
/**
* Typedef for typed values
*/
typedef PubValue<bool> PubValBool;
typedef PubValue<int64_t> PubValInt;
typedef PubValue<double> PubValFloat;
typedef PubValue<std::string> PubValStr;
/**
* ZMQ context
*/
zmq::context_t _context;
/**
* ZMQ socket
*/
zmq::socket_t _socket;
/**
* Lock free double buffer for RT publish
* of bool, int, float and str values and streams
*/
LockFreeDoubleQueue<PubValBool> _bufferBool;
LockFreeDoubleQueue<PubValInt> _bufferInt;
LockFreeDoubleQueue<PubValFloat> _bufferFloat;
LockFreeDoubleQueue<PubValStr> _bufferStr;
LockFreeDoubleQueue<PubValStr> _bufferStream;
/**
* If true, the external writing buffer
* is the 1 and the outputing network buffer is the 2.
* If false, the external writing buffer
* is the 2 and the outputing network buffer is the 1.
*/
bool _isWritingTo1;
/**
* First double buffer for frame publishing
*/
std::list<zmq::message_t> _queue1Frame;
/**
* Second double buffer for frame publishing
*/
std::list<zmq::message_t> _queue2Frame;
/**
* Mutex protecting access to frame double buffer
*/
std::mutex _mutexQueueFrame;
/**
* Swap double buffer for publishing values
*/
void swapBuffer();
};
}
#endif
| 25.503546 | 62 | 0.562848 | ipab-slmc |
58b406c67517d4d944aa8b8653a8a4367537a192 | 526 | hpp | C++ | experimental/Pomdog.Experimental/Particle2D/BeamBranching.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Particle2D/BeamBranching.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | experimental/Pomdog.Experimental/Particle2D/BeamBranching.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_BEAMBRANCHING_1888F4E0_HPP
#define POMDOG_BEAMBRANCHING_1888F4E0_HPP
#include <cstdint>
#include <random>
namespace Pomdog {
class BeamBranching {
public:
std::uniform_real_distribution<float> SpreadRange {-5.0f, 5.0f};
float BranchingRate = 0.7f;
float InheritThickness = 0.7f;
std::uint8_t MaxBranches = 0;
};
} // namespace Pomdog
#endif // POMDOG_BEAMBRANCHING_1888F4E0_HPP
| 20.230769 | 70 | 0.750951 | bis83 |
58b50d96f4c43fbb3d948a9cdb59b2cd755b1e3d | 44,327 | cxx | C++ | osprey/crayf90/sgi/cwh_expr.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/crayf90/sgi/cwh_expr.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/crayf90/sgi/cwh_expr.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2006. QLogic Corporation. All Rights Reserved.
*/
/*
* Copyright 2004, 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
/* ====================================================================
* ====================================================================
*
* Module: cwh_expr
* $Revision: 1.5 $
* $Date: 04/12/21 14:57:32-08:00 $
* $Author: bos@eng-25.internal.keyresearch.com $
* $Source:
*
* Revision history:
* dd-mmm-95 - Original Version
*
* Description: contains routines for expressions and conversions.
* Entry points from PDGCS layer are those for
* unary & binary operations eg:
* fei_plus,fei_bneg, fei_max..
*
* The Cray IR doesn't contain explicit conversions
* so each operand is checked, and OPC_CVRTLs sprinkled
* around. Small operands - I1,U2 etc are also converted
* to the minumun WH sizes I4,U4.
*
* The source of operands is the expression stack, via
* the routine cwh_expr_operand. Usually that's where
* the result goes too.
*
* ====================================================================
* ====================================================================
*/
static const char *source_file = __FILE__;
#ifdef _KEEP_RCS_ID
static char *rcs_id = "$Source: /home/bos/bk/kpro64-pending/crayf90/sgi/SCCS/s.cwh_expr.cxx $ $Revision: 1.5 $";
#endif /* _KEEP_RCS_ID */
/* sgi includes */
#include "defs.h"
#include "glob.h"
#include "stab.h"
#include "strtab.h"
#include "errors.h"
#include "config_targ.h"
#include "targ_const.h"
#include "wn.h"
#include "wn_util.h"
#include "const.h"
#include "f90_utils.h"
#include "sgi_cmd_line.h"
/* Cray includes */
#include "i_cvrt.h"
/* conversion includes */
#include "cwh_defines.h"
#include "cwh_addr.h"
#include "cwh_expr.h"
#include "cwh_block.h"
#include "cwh_types.h"
#include "cwh_preg.h"
#include "cwh_stab.h"
#include "cwh_auxst.h"
#include "cwh_stmt.h"
#include "cwh_stk.h"
#include "cwh_expr.h"
#include "cwh_intrin.h"
#include "cwh_preg.h"
static void cwh_expr_binop(OPERATOR op, TY_IDX result_ty) ;
static void cwh_expr_unop(OPERATOR op,TY_IDX result_ty) ;
static WN * cwh_expr_compare_char(OPERATOR op, TY_IDX ty) ;
/*================================================================
*
* cwh_expr_extract_arrayexp
*
* Pulls an ARRAYEXP off the top of wn. If *arrayexp is non-null,
* delete the ARRAYEXP. IF *arrayexp is NULL, return the ARRAYEXP in it.
* If arrayexp == 1, then delete the arrayexp.
*
*================================================================
*/
extern WN *
cwh_expr_extract_arrayexp(WN *wn, WN **arrayexp)
{
WN * ae;
INT i;
if (Full_arrayexp) {
if (WNOPR(wn) == OPR_ARRAYEXP && arrayexp != NULL) {
ae = wn;
wn = WN_kid0(wn);
/* Check to see if we should delete it */
if (arrayexp != DELETE_ARRAYEXP_WN && *arrayexp == NULL) {
*arrayexp = ae;
} else {
for (i = 1; i < WN_kid_count(ae); i++) {
WN_DELETE_Tree(WN_kid(ae,i));
}
WN_Delete(ae);
}
}
}
return (wn);
}
/*================================================================
*
* cwh_expr_restore_arrayexp
*
* Puts an ARRAYEXP back on top of wn. If arrayexp is non-null,
* put it on top of the expression.
*
*================================================================
*/
extern WN *
cwh_expr_restore_arrayexp(WN *wn, WN *arrayexp)
{
OPCODE opc;
if (Full_arrayexp && arrayexp) {
WN_kid0(arrayexp) = wn;
opc = cwh_make_typed_opcode(OPR_ARRAYEXP,WN_rtype(wn),MTYPE_V);
WN_set_opcode(arrayexp,opc);
return (arrayexp);
} else {
return (wn);
}
}
/*================================================================
*
* cwh_wrap_cvtl
*
* Wrap a CVTL around an expressions for small types
*
*==================================================================
*/
extern WN *
cwh_wrap_cvtl(WN * wn, TYPE_ID ty)
{
return F90_wrap_cvtl(wn,ty);
}
/*================================================================
*
* cwh_convert_to_ty
*
* Convert a node to a new type. Needed because we don't
* have explicit converts in the trees from the Cray IR. It's also
* a useful routine to have around.
*
*================================================================
*/
extern WN *
cwh_convert_to_ty(WN * wn, TYPE_ID ty)
{
TYPE_ID old_ty,real_ty,new_real_ty;
OPCODE cvt_op;
OPCODE realpart,imagpart;
WN *r;
WN *ri,*rr;
old_ty = WNRTY(wn);
if (old_ty == ty) return (wn);
if (old_ty == MTYPE_I1 || old_ty == MTYPE_I2) {
/* treat as it it were an I4 */
old_ty = MTYPE_I4;
}
r = wn;
cvt_op = OPCODE_UNKNOWN;
/* Special case for TAS nodes */
if (WNOPR(wn) == OPR_TAS) {
WN_set_opcode(wn,OPCODE_make_op(OPR_TAS,ty,MTYPE_V));
return (wn);
}
if (MTYPE_is_complex(old_ty)) {
real_ty = Mtype_complex_to_real(old_ty);
realpart = OPCODE_make_op(OPR_REALPART,real_ty,MTYPE_V);
imagpart = OPCODE_make_op(OPR_IMAGPART,real_ty,MTYPE_V);
/* complex to non-complex */
if (!MTYPE_is_complex(ty)) {
r = WN_CreateExp1(realpart,r);
r = cwh_convert_to_ty(r,ty);
} else { /* complex to complex */
new_real_ty = Mtype_complex_to_real(ty);
rr = WN_CreateExp1(realpart,WN_COPY_Tree(r));
rr = cwh_convert_to_ty(rr,new_real_ty);
ri = WN_CreateExp1(imagpart,r);
ri = cwh_convert_to_ty(ri,new_real_ty);
r = WN_CreateExp2(OPCODE_make_op(OPR_COMPLEX,ty,MTYPE_V),rr,ri);
}
return (r);
} else if (MTYPE_is_complex(ty)) {
real_ty = Mtype_complex_to_real(ty);
cvt_op = OPCODE_make_op(OPR_COMPLEX,ty,MTYPE_V);
r = cwh_convert_to_ty(r,real_ty);
r = WN_CreateExp2(cvt_op,r,Make_Zerocon(real_ty));
return (r);
}
if (ty == MTYPE_I1 || ty == MTYPE_I2) {
/* First convert to I4, then do a CVTL */
r = cwh_convert_to_ty(wn,MTYPE_I4);
r = cwh_wrap_cvtl(r,ty);
return (r);
}
if (ty == MTYPE_U1 || ty == MTYPE_U2) {
/* First convert to I4, then do a CVTL */
r = cwh_convert_to_ty(wn,MTYPE_U4);
r = cwh_wrap_cvtl(r,ty);
return (r);
}
if (MTYPE_is_float(ty)) {
/* Converts to float */
cvt_op = OPCODE_make_op(OPR_CVT,ty,old_ty);
} else if (MTYPE_is_float(old_ty)) {
/* Converts from float to integer */
cvt_op = OPCODE_make_op(OPR_TRUNC,ty,old_ty);
} else {
/* Integral to integral */
if (MTYPE_size_reg(ty) != MTYPE_size_reg(old_ty)) {
cvt_op = OPCODE_make_op(OPR_CVT,ty,old_ty);
}
}
/* See if there is a single op to do the conversion */
if (cvt_op != 0) {
r = WN_CreateExp1(cvt_op,r);
}
return (r);
}
/*===============================================
*
* cwh_get_highest_type
*
* Utility routine for type conversions, etc.
*
* Takes two operands, and converts them so that both
* are of the "greater" (in the fortran sense) type.
*
*===============================================
*/
extern TYPE_ID
cwh_get_highest_type(WN *lhs, WN *rhs)
{
TYPE_ID t1,t2,r;
t1 = WN_rtype(lhs);
t2 = WN_rtype(rhs);
/* Types are the same, nothing to do */
if (t1 == t2) return (t1);
if (MTYPE_is_complex(t1) && !MTYPE_is_complex(t2)) {
t1 = Mtype_complex_to_real(t1);
if (MTYPE_type_order(t2) > MTYPE_type_order(t1)) {
r = t2;
} else {
r = t1;
}
/* Convert r to complex */
switch (r) {
case MTYPE_F4: r = MTYPE_C4; break;
case MTYPE_F8: r = MTYPE_C8; break;
case MTYPE_FQ: r = MTYPE_CQ; break;
}
} else if (MTYPE_is_complex(t2) && !MTYPE_is_complex(t1)) {
t2 = Mtype_complex_to_real(t2);
if (MTYPE_type_order(t2) > MTYPE_type_order(t1)) {
r = t2;
} else {
r = t1;
}
/* Convert r to complex */
switch (r) {
case MTYPE_F4: r = MTYPE_C4; break;
case MTYPE_F8: r = MTYPE_C8; break;
case MTYPE_FQ: r = MTYPE_CQ; break;
}
} else {
/* No complexes, return the greatest in type order */
if (MTYPE_type_order(t2) > MTYPE_type_order(t1)) {
r = t2;
} else {
r = t1;
}
}
return (r);
}
/*===============================================
*
* cwh_get_typed_operand
*
* Utility routine for type conversions, etc.
*
* Pops an operand from the stack and converts
* it to type ty if necessary.
*
* arrexp is treated as it is for cwh_expr_operand
*
*===============================================
*/
extern WN *
cwh_get_typed_operand(TYPE_ID ty, WN **arrexp)
{
WN *r;
r = cwh_expr_operand(arrexp);
r = cwh_convert_to_ty(r,ty);
return (r);
}
/*===============================================
*
* cwh_make_typed_opcode
*
* Build an opcode from a type, also checking
* for small types and converting them to 32 bits.
*
*===============================================
*/
extern OPCODE
cwh_make_typed_opcode(OPERATOR op, TYPE_ID ty1, TYPE_ID ty2)
{
OPCODE opc;
TYPE_ID ti ;
switch (ty1) {
case MTYPE_B:
case MTYPE_I1:
case MTYPE_I2:
ti = MTYPE_I4;
break ;
case MTYPE_U1:
case MTYPE_U2:
ti = MTYPE_U4;
break ;
default:
ti = ty1;
break;
}
opc = OPCODE_make_op(op,ti,ty2);
return (opc);
}
/*===============================================
*
* cwh_expr_binop
*
* Apply the binop to the two operands at the
* top of the stack and push the result. Conversions
* are added to lhs & rhs if required.
*
*===============================================
*/
static void
cwh_expr_binop(OPERATOR op,TY_IDX result_ty)
{
WN *rhs ;
WN *lhs ;
WN *wn ;
TYPE_ID bt ;
OPCODE opc ;
TYPE_ID ot;
WN *ae=NULL;
rhs = cwh_expr_operand(&ae);
lhs = cwh_expr_operand(&ae);
ot = cwh_get_highest_type(rhs,lhs);
if (result_ty) {
bt = TY_mtype(result_ty) ;
} else {
bt = ot;
}
opc = cwh_make_typed_opcode(op, ot, MTYPE_V);
lhs = cwh_convert_to_ty(lhs,ot);
rhs = cwh_convert_to_ty(rhs,ot);
wn = WN_CreateExp2 ( opc, lhs, rhs) ;
/* Need to insert a CVTL on top of the small ops */
wn = cwh_wrap_cvtl(wn,bt);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,result_ty) ;
}
/*===============================================
*
* cwh_expr_binop_shift
*
* Apply the binop to the two operands at the
* top of the stack and push the result. The
* shifts yield integer results and can be applied
* to float operands.
*
*===============================================
*/
static void
cwh_expr_binop_shift(OPERATOR op, TY_IDX result_ty)
{
WN *arg ;
WN *shft ;
WN *wn ;
WN *temp ;
WN *ae=NULL;
TYPE_ID bt ;
TYPE_ID ret_t;
TYPE_ID br ;
TYPE_ID ba ;
OPCODE opc ;
INT bitlen;
INT reslen;
br = TY_mtype(result_ty) ;
ret_t = br;
reslen = MTYPE_size_best(br);
shft = cwh_expr_operand(&ae);
arg = cwh_expr_operand(&ae);
bt = WNRTY(arg);
bitlen = MTYPE_size_best(bt);
if (reslen < 32 && op == OPR_LSHR) {
/* Need to clear out the upper bits */
arg = WN_Band(bt,arg,WN_Intconst(bt,(1<<reslen)-1));
}
if (bitlen <= MTYPE_size_best(MTYPE_U4))
ba = MTYPE_I4 ;
else
ba = MTYPE_I8 ;
if (reslen > 32) {
br = MTYPE_I8;
} else {
br = MTYPE_I4;
}
if (!MTYPE_is_integral(bt))
arg = WN_Tas(ba,Be_Type_Tbl(bt),arg) ;
opc = cwh_make_typed_opcode(op, br, MTYPE_V);
if (op == OPR_ASHR) {
/* shift is MIN(shift,reslen-1) */
if (ARCH_mask_shift_counts) {
temp = WN_GT(br,WN_COPY_Tree(shft),WN_Intconst(br,reslen-1));
temp = cwh_convert_to_ty(temp,br);
temp = WN_Neg(br,temp);
shft = WN_Bior(br,temp,shft);
}
wn = WN_CreateExp2 (opc, arg, shft);
} else {
if (ARCH_mask_shift_counts) {
/* shift is (arg op shift ) & -(shift<reslen) */
temp = WN_LT(br,WN_COPY_Tree(shft),WN_Intconst(br,reslen));
temp = cwh_convert_to_ty(temp,br);
temp = WN_Neg(br,temp);
wn = WN_CreateExp2 (opc, arg, shft);
wn = WN_Band(br,wn,temp);
} else {
wn = WN_CreateExp2 (opc, arg, shft);
}
}
wn = cwh_wrap_cvtl(wn,ret_t);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,result_ty);
}
/*===============================================
*
* cwh_expr_compare
*
* Apply the compare binop to the two operands at the
* top of the stack and push the result. Convert
* both operands 'highest' type before selecting
* operator.
*
* Character operations are diverted to create
* the correct intrinsic.
*
*===============================================
*/
extern void
cwh_expr_compare(OPERATOR op,TY_IDX ty)
{
WN *rhs ;
WN *lhs ;
WN *wn ;
WN *ae=NULL;
TYPE_ID bt ;
OPCODE opc ;
if (cwh_stk_get_class() == STR_item)
wn = cwh_expr_compare_char(op,ty);
else {
rhs = cwh_expr_operand(&ae);
lhs = cwh_expr_operand(&ae);
bt = cwh_get_highest_type(rhs,lhs);
opc = cwh_make_typed_opcode(op, MTYPE_I4, Mtype_comparison(bt));
lhs = cwh_convert_to_ty(lhs,bt);
rhs = cwh_convert_to_ty(rhs,bt);
wn = WN_CreateExp2 ( opc, lhs, rhs) ;
wn = cwh_expr_restore_arrayexp(wn,ae);
}
cwh_stk_push_typed(wn,WN_item,ty);
}
/*===============================================
*
* cwh_expr_compare_char
*
* Convert the compare binop into an intrinsic OP
* and return the WN of the op. Assumes two
* STR_items are TOS.
*
*===============================================
*/
static WN *
cwh_expr_compare_char(OPERATOR op, TY_IDX ty)
{
WN * ar[4];
WN * sz[4];
BOOL va[4];
WN * wn ;
#ifdef KEY /* Bug 10177 */
INTRINSIC intr = INTRN_CLTEXPR;
#else /* KEY Bug 10177 */
INTRINSIC intr;
#endif /* KEY Bug 10177 */
cwh_stk_pop_STR();
ar[3] = cwh_expr_operand(NULL);
ar[1] = cwh_expr_address(f_NONE);
sz[3] = NULL;
sz[1] = WN_COPY_Tree(ar[3]);
va[3] = TRUE;
va[1] = FALSE;
cwh_stk_pop_STR();
ar[2] = cwh_expr_operand(NULL);
ar[0] = cwh_expr_address(f_NONE);
sz[2] = NULL;
sz[0] = WN_COPY_Tree(ar[2]);
va[2] = TRUE;
va[0] = FALSE;
switch(op) {
case OPR_LT:
intr = INTRN_CLTEXPR;
break ;
case OPR_LE:
intr = INTRN_CLEEXPR;
break ;
case OPR_GE:
intr = INTRN_CGEEXPR;
break ;
case OPR_GT:
intr = INTRN_CGTEXPR;
break ;
case OPR_EQ:
intr = INTRN_CEQEXPR;
break ;
case OPR_NE:
intr = INTRN_CNEEXPR;
break ;
default:
DevAssert((0),("Missing char comp"));
}
wn = cwh_intrin_op(intr,4,ar,sz,va,TY_mtype(ty));
wn = F90_Wrap_ARREXP(wn);
return (wn);
}
/*===============================================
*
* cwh_expr_compare_logical
*
* Logical WN comparisons don't have a type
* so just pop the items, stick the operator
* on top and push the result.
*
*===============================================
*/
static void
cwh_expr_compare_logical(OPCODE opc,TY_IDX ty)
{
WN * rhs;
WN * lhs;
WN * wn ;
WN *ae=NULL;
rhs = cwh_expr_operand(&ae);
lhs = cwh_expr_operand(&ae);
wn = WN_CreateExp2 ( opc, lhs, rhs) ;
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,ty);
}
/*===============================================
*
* cwh_expr_compare_bitwise
*
* Bitwise WN comparisons for all types. Convert
* bits to integer type (if they aren't already)
* using TAS operate & push the result.
* The result type should be either I8 or I4.
*
*===============================================
*/
static void
cwh_expr_compare_bitwise(OPERATOR op,TY_IDX ty)
{
WN * rhs;
WN * lhs;
WN * wn ;
TY_IDX ta ;
TYPE_ID bt;
TYPE_ID br;
TYPE_ID ba;
TYPE_ID rhs_t,lhs_t;
OPCODE opc;
WN *ae=NULL;
bt = br = TY_mtype(ty);
if (bt == MTYPE_U4) br = MTYPE_I4 ;
if (bt == MTYPE_U8) br = MTYPE_I8 ;
rhs = cwh_expr_operand(&ae) ;
lhs = cwh_expr_operand(&ae) ;
rhs_t = WN_rtype(rhs);
lhs_t = WN_rtype(lhs);
ta = cwh_types_scalar_TY(cwh_types_WN_TY(rhs,FALSE));
ba = TY_mtype(ta);
if (!MTYPE_is_integral(rhs_t)) {
rhs = WN_Tas(br,ta,rhs) ;
}
if (!MTYPE_is_integral(lhs_t)) {
lhs = WN_Tas(br,ta,lhs) ;
}
opc = cwh_make_typed_opcode(op,br,MTYPE_V);
wn = WN_CreateExp2 ( opc, lhs, rhs) ;
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
/*===============================================
*
* fei_lneg
*
* .not. processing - similar to cwh_expr_unop,
* except result doesn't have a type.
*
*===============================================
*/
extern void
fei_lneg(TYPE result)
{
WN * lhs;
WN * wn ;
WN *ae=NULL;
lhs = cwh_expr_operand(&ae);
wn = WN_CreateExp1(OPC_I4LNOT, lhs) ;
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,(INTPTR)cast_to_TY(t_TY(result)));
}
/*===============================================
*
* cwh_expr_unop
*
* Apply the unop to the operand at the
* top of the stack and push the result.
* The operand is converted to the type
* of the result.
*
*===============================================
*/
static void
cwh_expr_unop(OPERATOR op,TY_IDX result_ty)
{
WN *lhs ;
WN *wn ;
WN *ae=NULL;
TYPE_ID bt ;
OPCODE opc ;
bt = TY_mtype(result_ty) ;
opc = cwh_make_typed_opcode(op, bt, MTYPE_V);
lhs = cwh_get_typed_operand(bt,&ae);
wn = WN_CreateExp1 ( opc, lhs) ;
wn = cwh_wrap_cvtl(wn,bt);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
/*===================================================
*
* cwh_expr_bincalc
*
* Given a binary op, and two WNs create the WN of
* the result. Used by address calculations, only.
* The type of the result is the type of the first
* argument.
*
====================================================
*/
extern WN *
cwh_expr_bincalc(OPERATOR op, WN * wn1, WN * wn2)
{
TYPE_ID bt ;
bt = cwh_get_highest_type(wn1,wn2);
wn1 = cwh_convert_to_ty(wn1,bt);
wn2 = cwh_convert_to_ty(wn2,bt);
return WN_CreateExp2 (OPCODE_make_op(op,bt,MTYPE_V),
wn1,
wn2) ;
}
/*===============================================
*
* cwh_expr_operand
*
* Pop the top of the stack and make it
* into an operand. If it's a WN, then it may be a
* constant or expression, and it's just returned,
* unless an OPC_ARRAY or OPC_ARRSECTION when
* a load is added. An ST requires a load. A FLD
* loads from its offset.
*
* if arrexp is non-null, and the returned node is an
* ARRAYEXP node, *arrexp is set to the ARRAYEXP node, and
* the first child if the ARRAYEXP is returned.
*===============================================
*/
extern WN *
cwh_expr_operand(WN **arrexp)
{
WN * wn ;
ST * st ;
TY_IDX ts ;
FLD_det det;
ts = cwh_stk_get_TY();
switch(cwh_stk_get_class()) {
case WN_item:
case WN_item_whole_array:
wn = cwh_stk_pop_WN();
if (wn == NULL)
return(wn);
if (cwh_addr_is_array(wn)) {
wn = cwh_addr_load_WN(wn,0,ts);
} else if (cwh_addr_is_section(wn)) {
wn = cwh_addr_load_WN(wn,0,ts);
if (Full_arrayexp) {
wn = F90_Wrap_ARREXP(wn);
}
}
wn = cwh_expr_extract_arrayexp(wn,arrexp);
break ;
case ADDR_item:
wn = cwh_stk_pop_ADDR();
break ;
case DEREF_item:
wn = cwh_stk_pop_DEREF();
wn = cwh_addr_load_WN(wn,0,0);
break ;
case ST_item:
case ST_item_whole_array:
st = cwh_stk_pop_ST();
wn = cwh_addr_load_ST(st,0,0);
break ;
case FLD_item:
det = cwh_addr_offset();
if (cwh_stk_get_class() == ST_item || cwh_stk_get_class() == ST_item_whole_array) {
st = cwh_stk_pop_ST();
wn = cwh_addr_load_ST(st,det.off,det.type);
} else {
wn = cwh_stk_pop_WHIRL();
wn = cwh_expr_extract_arrayexp(wn,DELETE_ARRAYEXP_WN);
wn = cwh_addr_load_WN(wn,det.off,det.type);
if (Full_arrayexp) {
wn = F90_Wrap_ARREXP(wn);
}
wn = cwh_expr_extract_arrayexp(wn,arrexp);
}
break ;
case PCONST_item:
st = (ST *) cwh_stk_pop_PCONST();
wn = cwh_addr_address_ST(st);
break;
default:
DevAssert((0),("Bad operand"));
}
return (wn);
}
/*===============================================
*
* cwh_expr_address
*
* Makes an address of the top of the stack and
* returns it. A STR_item has its length thrown
* away. A WN constant gets an LDA, otherwise its
* assumed an WN is an address. An INTCONST is
* entered into the symbol table & an expression
* may be saved. An address on the stack may be NULL
* if the dope vector routines have already processed it.
* FLD items are similar to WN_items, but get an
* ADD of the offset to the component. The TY of
* the FLD is thrown away.
*
* Sets ST_addr bits depending of setting of flag
*
*===============================================
*/
extern WN *
cwh_expr_address(FLAG flag)
{
WN * wn ;
ST * st ;
FLD_det det ;
switch(cwh_stk_get_class()) {
case WN_item:
case WN_item_whole_array:
case ADDR_item:
case DEREF_item:
wn = cwh_stk_pop_WHIRL();
if (wn) {
if (flag) {
st = cwh_addr_WN_ST(wn);
cwh_expr_set_flags(st, flag);
}
}
break;
case ST_item:
case ST_item_whole_array:
st = cwh_stk_pop_ST();
wn = cwh_addr_address_ST(st);
if (flag)
cwh_expr_set_flags(st, flag);
break;
case STR_item:
cwh_stk_pop_STR();
WN_Delete(cwh_expr_operand(NULL)); /* Get rid of the length */
wn = cwh_expr_address(flag);
break;
case FLD_item:
det = cwh_addr_offset();
if (cwh_stk_get_class() == ST_item ||
cwh_stk_get_class() == ST_item_whole_array) {
st = cwh_stk_pop_ST();
wn = cwh_addr_address_ST(st,det.off,det.type);
if (flag)
cwh_expr_set_flags(st, flag);
} else {
wn = cwh_expr_address(flag);
wn = cwh_expr_bincalc(OPR_ADD,wn,WN_Intconst(Pointer_Mtype,det.off));
}
break ;
default:
DevAssert((0),("Odd address"));
}
return (wn);
}
/*===============================================
*
* fei_<binop>
*
* Use common binary op routine - one of
* cwh_expr_binop,cwh_expr_compare,
* cwh_expr_binop_shift
* cwh_expr_compare_logical
* cwh_expr_compare_bitwise
*===============================================
*/
#define binop_routine(name,opr) \
extern void name (TYPE type) \
{ \
cwh_expr_binop(opr,cast_to_TY(t_TY(type))); \
}
#define binop_shift_routine(name,opr) \
extern void name (TYPE type) \
{ \
cwh_expr_binop_shift(opr,cast_to_TY(t_TY(type))); \
}
#define compare_routine(name,opr) \
extern void name (TYPE type) \
{ \
cwh_expr_compare(opr,cast_to_TY(t_TY(type))); \
}
#define compare_logical(name,opr_l,opr_c) \
extern void name (TYPE type) \
{ \
cwh_expr_compare_logical(FTN_Short_Circuit_On ? opr_c : opr_l,cast_to_TY(t_TY(type))); \
}
#define compare_bitwise(name,opr) \
extern void name (TYPE type) \
{ \
cwh_expr_compare_bitwise(opr,cast_to_TY(t_TY(type))); \
}
binop_routine(fei_plus,OPR_ADD)
binop_routine(fei_minus,OPR_SUB)
binop_routine(fei_mult,OPR_MPY)
binop_routine(fei_div,OPR_DIV)
compare_routine(fei_gt,OPR_GT)
compare_routine(fei_ge,OPR_GE)
compare_routine(fei_lt,OPR_LT)
compare_routine(fei_le,OPR_LE)
compare_routine(fei_eq,OPR_EQ)
compare_routine(fei_ne,OPR_NE)
compare_bitwise(fei_and,OPR_BAND)
compare_bitwise(fei_xor,OPR_BXOR)
compare_logical(fei_land ,OPC_I4LAND, OPC_I4CAND)
compare_routine(fei_leqv ,OPR_EQ)
compare_logical(fei_lor ,OPC_I4LIOR, OPC_I4CIOR)
binop_shift_routine(fei_lshift ,OPR_SHL)
binop_shift_routine(fei_rshift ,OPR_LSHR)
binop_shift_routine(fei_ashift ,OPR_ASHR)
compare_routine(fei_lxor ,OPR_NE)
compare_bitwise(fei_or ,OPR_BIOR)
/* Bitwise equivalence */
extern void
fei_eqv(TYPE type)
{
fei_xor(type);
fei_bneg(type);
}
/*===============================================
*
* fei_islg
*
* != comparison, implemented as is less than or
* greater than comparison.
*
*===============================================
*/
extern void
fei_islg(TYPE type)
{
WN *arg1, *arg2, *r1, *r2;
arg1 = cwh_expr_operand(NULL);
arg2 = cwh_expr_operand(NULL);
cwh_stk_push(WN_COPY_Tree(arg2),WN_item);
cwh_stk_push(WN_COPY_Tree(arg1),WN_item);
cwh_expr_compare(OPR_LT,0);
r1 = cwh_expr_operand(NULL);
cwh_stk_push(arg2,WN_item);
cwh_stk_push(arg1,WN_item);
cwh_expr_compare(OPR_GT,0);
r2 = cwh_expr_operand(NULL);
cwh_stk_push(r1,WN_item);
cwh_stk_push(r2,WN_item);
fei_lor(type);
}
extern void
fei_multiply_high(TYPE type)
{
/* Can't use cwh_expr_binop, since we need UNSIGNED multiply */
WN *rhs ;
WN *lhs ;
WN *wn ;
OPCODE opc ;
TYPE_ID ot;
WN *ae=NULL;
rhs = cwh_expr_operand(&ae);
lhs = cwh_expr_operand(&ae);
ot = cwh_get_highest_type(rhs,lhs);
if (ot == MTYPE_I8) {
opc = OPC_U8HIGHMPY;
ot = MTYPE_U8;
} else {
opc = OPC_U4HIGHMPY;
ot = MTYPE_U4;
}
lhs = cwh_convert_to_ty(lhs,ot);
rhs = cwh_convert_to_ty(rhs,ot);
wn = WN_CreateExp2 ( opc, lhs, rhs) ;
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
/*===============================================
*
* fei_<unop>
*
* Use common unary op routine
*
*===============================================
*/
#define unop_routine(name,opr) \
extern void name (TYPE type) \
{ \
cwh_expr_unop(opr,cast_to_TY(t_TY(type))); \
}
/*===============================================
*
* fei_imag
*
* Get the imaginary part
*
*===============================================
*/
extern void
fei_imag(TYPE type)
{
WN *rhs, *wn;
TY_IDX ty;
TYPE_ID t,rt;
WN *ae=NULL;
ty = cast_to_TY(t_TY(type));
t = TY_mtype(ty) ;
rhs = cwh_expr_operand(&ae);
rt = Mtype_complex_to_real(WN_rtype(rhs));
wn = WN_CreateExp1(cwh_make_typed_opcode(OPR_IMAGPART,rt,MTYPE_V),rhs);
wn = cwh_convert_to_ty(wn,t);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
/*===============================================
*
* fei_bneg
*
* Bitwise NOT on top of stack
*
*===============================================
*/
extern void
fei_bneg(TYPE type)
{
WN *lhs ;
WN *wn ;
WN *ae=NULL;
TYPE_ID bt, lhs_t ;
OPCODE opc ;
TY_IDX ta, result_ty;
result_ty = cast_to_TY(t_TY(type));
bt = TY_mtype(result_ty) ;
if (MTYPE_is_unsigned(bt)) {
bt = MTYPE_complement(bt);
}
lhs = cwh_expr_operand(&ae) ;
lhs_t = WN_rtype(lhs);
ta = cwh_types_scalar_TY(cwh_types_WN_TY(lhs,FALSE));
if (!MTYPE_is_integral(lhs_t)) {
lhs = WN_Tas(bt,ta,lhs) ;
}
opc = cwh_make_typed_opcode(OPR_BNOT, bt, MTYPE_V);
wn = WN_CreateExp1 ( opc, lhs) ;
wn = cwh_wrap_cvtl(wn,bt);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,Be_Type_Tbl(bt));
}
unop_routine(fei_uminus,OPR_NEG)
/*===============================================
*
* fei_paren
*
* If type is integer/logical ignore, as WHIRL
* doesn't have an suitable operator code. Otherwise
* use the unary operator routine.
*
*===============================================
*/
extern void
fei_paren(TYPE type)
{
TY_IDX ty ;
TYPE_ID t;
ty = cast_to_TY(t_TY(type));
ty = cwh_types_scalar_TY(ty);
t = TY_mtype(ty);
if (MTYPE_is_float(t) || MTYPE_is_complex(t)) {
cwh_expr_unop(OPR_PAREN,ty);
}
}
/*===============================================
*
* fei_max/min
*
* create max/min via common binop routine.
*
*===============================================
*/
extern void
fei_max(INT count, TYPE type)
{
INT i;
for (i = 1; i < count; i++) {
cwh_expr_binop(OPR_MAX,cast_to_TY(t_TY(type)));
}
}
extern void
fei_min(INT count, TYPE type)
{
INT i;
for (i = 1; i < count; i++) {
cwh_expr_binop(OPR_MIN,cast_to_TY(t_TY(type)));
}
}
/*===============================================
*
* fei_select
*
* Implement the MERGE intrinsic. The mask is
* TOS, then T items, F items and the destination.
*
* Generally a select is issued, and pushed onto
* the stack so the result can be used, eg: by
* fei_store. If it's an aggregate - a character
* or derived type, then the MERGE intrinsic op
* is used.
*
* This also implements the CVM... intrinsics
*
*===============================================
*/
extern void
#ifdef KEY /* Bug 10410 */
fei_select(TYPE type, int cselect)
#else /* KEY Bug 10410 */
fei_select(TYPE type)
#endif /* KEY Bug 10410 */
{
WN *t_case,*f_case,*condition;
WN * wn;
TY_IDX ty;
WN *strlen;
WN *addr;
TYPE_ID bt;
TYPE_ID rt;
WN *args[3];
WN *ae=NULL;
ty = cast_to_TY(t_TY(type));
condition = cwh_expr_operand(&ae);
if (TY_is_character(ty)) {
cwh_stk_pop_STR();
strlen = cwh_expr_operand(NULL);
addr = cwh_expr_address(f_NONE);
f_case = cwh_addr_mload(addr,0,ty,strlen);
cwh_stk_pop_STR();
strlen = cwh_expr_operand(NULL);
addr = cwh_expr_address(f_NONE);
t_case = cwh_addr_mload(addr,0,ty,strlen);
} else {
f_case = cwh_expr_operand(&ae);
t_case = cwh_expr_operand(&ae);
}
bt = WN_rtype(t_case);
if (bt == MTYPE_M) {
/* character,derived type - build an intrinsic_op */
args[0] = cwh_intrin_wrap_value_parm(condition);
args[1] = cwh_intrin_wrap_value_parm(t_case);
args[2] = cwh_intrin_wrap_value_parm(f_case);
if (TY_is_character(ty)) {
wn = WN_Create_Intrinsic(OPC_U4INTRINSIC_OP,INTRN_MERGE,3,args);
cwh_stk_push_STR(WN_COPY_Tree(strlen),wn,ty,WN_item);
} else {
wn = WN_Create_Intrinsic(OPC_MINTRINSIC_OP,INTRN_MERGE,3,args);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
} else {
/*
* In order to handle the CVMGT intrinsic and its ilk, we check the base types
* of the TRUE and FALSE cases and wrap them with TAS as necessary.
*/
rt = TY_mtype(ty);
if (MTYPE_is_integral(rt)) {
if (!MTYPE_is_integral(WNRTY(t_case))) {
t_case = WN_Tas(rt,Be_Type_Tbl(WNRTY(t_case)),t_case) ;
}
if (!MTYPE_is_integral(WNRTY(f_case))) {
f_case = WN_Tas(rt,Be_Type_Tbl(WNRTY(f_case)),f_case) ;
}
}
#ifdef KEY /* Bug 10410 */
wn = WN_CreateExp3(
cwh_make_typed_opcode((cselect ? OPR_CSELECT : OPR_SELECT),rt,MTYPE_V),
condition,t_case,f_case);
#else /* KEY Bug 10410 */
wn = WN_CreateExp3(cwh_make_typed_opcode(OPR_SELECT,rt,MTYPE_V),condition,t_case,f_case);
#endif /* KEY Bug 10410 */
wn = cwh_wrap_cvtl(wn,rt);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,Be_Type_Tbl(rt));
}
}
/*=============================================
*
* fei_cvtop
*
* Convert TOS to the given type.
*
*=============================================
*/
extern void
fei_cvtop(TYPE type)
{
WN *wn ;
TYPE_ID bt ;
TYPE_ID ot ;
WN *addr;
TY_IDX ty;
WN *ival;
WN *icall;
WN *ae=NULL;
ty = cast_to_TY(t_TY(type));
/* Check for converts to TYPELESS, for which we just use a TAS */
if (type.basic_type == T_ypeless) {
wn = cwh_expr_operand(&ae);
ot = WNRTY(wn) ;
if (!MTYPE_is_integral(ot)) {
wn = WN_Tas(TY_mtype(ty),Be_Type_Tbl(ot),wn) ;
}
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,ty);
} else if (TY_is_character(ty)) {
ival = cwh_intrin_wrap_value_parm(cwh_expr_operand(&ae));
icall = WN_Create_Intrinsic(OPC_U4INTRINSIC_OP,INTRN_CHAR,1,&ival);
icall = cwh_expr_restore_arrayexp(icall,ae);
cwh_stk_push_STR(WN_Intconst(MTYPE_I4,1),icall,ty,WN_item);
} else {
bt = TY_mtype(ty);
if (cwh_stk_get_class() == STR_item) {
cwh_stk_pop_STR();
WN_Delete(cwh_expr_operand(NULL)); /* Get rid of the length */
addr = cwh_expr_address(f_NONE);
if (WN_opcode(addr) == OPC_U4INTRINSIC_OP &&
WN_intrinsic(addr) == INTRN_CHAR) {
addr = cwh_expr_dispose_of_char(addr);
/* ichar(char(x)) ==> x & 255 */
wn = WN_Band(MTYPE_I4,addr,WN_Intconst(MTYPE_I4,255));
wn = F90_Wrap_ARREXP(wn);
} else {
wn = cwh_addr_load_WN(addr,0,Be_Type_Tbl(MTYPE_U1));
wn = WN_Band(MTYPE_I4,wn,WN_Intconst(MTYPE_I4,255));
/* Convert to bt */
wn = cwh_convert_to_ty(wn,bt);
}
} else {
wn = cwh_get_typed_operand(bt,&ae);
}
if (WNOPR(wn) == OPR_INTCONST) {
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,ty);
} else {
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,ty);
}
} /* Non-character */
}
/*=============================================
*
* fei_len
*
* Used to establish the length of a DUMMY argument
* or to implement the LEN function applied
* to a character expression.
*
* TOS is an ST if the length of a DUMMY or
* a STR_item if it's a character expression.
* In both cases we push the length. For a
* dummy we have to look up the value in the
* list of arguments associated with the
* current entry point (dummy args are
* processed in the preamble).
*
* An ST may also occur for a CHARACTER pointer.
*
*=============================================
*/
extern void
fei_len(TYPE type)
{
ST * st ;
ST * ln ;
WN * wn ;
switch(cwh_stk_get_class()) {
case ST_item:
case ST_item_whole_array:
st = cwh_stk_pop_ST();
ln = cwh_auxst_find_dummy_len(st);
if (ln == NULL) {
if (ST_sclass(st) == SCLASS_FORMAL)
Fatal_Error ("Unsupported LEN on character dummy : %s",ST_name(st));
else
Fatal_Error ("No LEN type parameter: %s", ST_name(st));
}
cwh_stk_push(ln,ST_item);
break;
case STR_item:
cwh_stk_pop_STR();
wn = cwh_expr_operand(NULL);
cwh_stk_pop_whatever();
cwh_stk_push(wn,WN_item);
break;
default:
DevAssert((0),("Odd LEN"));
}
}
/*=============================================
*
* fei_null_expr
*
* push a null WN onto the stack.
*
*=============================================
*/
extern void
fei_null_expr (void)
{
WN *null_wn = NULL;
cwh_stk_push(null_wn,WN_item);
}
/*
* Generate a mask of len bits of type TY
* valid for 0<= len <= 64
*/
extern
WN * cwh_generate_bitmask(WN *len, TYPE_ID ty)
{
WN *mask;
if (MTYPE_size_reg(ty) != 64 || !ARCH_mask_shift_counts) {
/* Optimization: we use 64 bit shift */
mask = WN_Intconst(MTYPE_I8,1);
} else {
/* Need to be a little more clever */
mask = WN_NE(ty,WN_Intconst(MTYPE_I8,64),WN_COPY_Tree(len));
mask = cwh_convert_to_ty(mask,MTYPE_I8);
}
mask = WN_Shl(MTYPE_I8,mask,len);
mask = cwh_expr_bincalc(OPR_SUB,mask,WN_Intconst(MTYPE_I8,1));
mask = cwh_convert_to_ty(mask,ty);
return (mask);
}
/*=============================================
*
* fei_mask
*
* push a bitmask on the stack.
* MASK(I) is
* set leftmost I bits if I < bitlen. This is -1 << (bitlen - I)
* set rightmost 2*bitlen-I bits if I >= bitlen
*
*=============================================
*/
extern void
fei_mask (TYPE type)
{
#ifdef KEY /* Bug 10177 */
WN *wn = 0;
WN *arg,*t1,*t2;
#else /* KEY Bug 10177 */
WN *wn,*arg,*t1,*t2;
#endif /* KEY Bug 10177 */
TYPE_ID t;
WN *ae=NULL;
t = TY_mtype(cast_to_TY(t_TY(type)));
arg = cwh_expr_operand(&ae);
switch (t) {
case MTYPE_U1:
case MTYPE_I1:
/* we can use a neat little trick for this */
wn = WN_CreateExp2(OPC_I4LSHR,WN_Intconst(MTYPE_I4,0xff00LL),arg);
wn = cwh_convert_to_ty(wn,MTYPE_I1);
break;
case MTYPE_U2:
case MTYPE_I2:
/* we can use a neat little trick for this */
wn = WN_CreateExp2(OPC_I4LSHR,WN_Intconst(MTYPE_U4,0xffff0000LL),arg);
wn = cwh_convert_to_ty(wn,MTYPE_I2);
break;
case MTYPE_U4:
case MTYPE_I4:
/* we can use a neat little trick for this */
wn = WN_CreateExp2(OPC_I8LSHR,WN_Intconst(MTYPE_I8,0xffffffff00000000LL),arg);
wn = cwh_convert_to_ty(wn,MTYPE_I4);
break;
case MTYPE_U8:
case MTYPE_I8:
/* Uglier code:
* ~(-1 >> arg) if arg < 64
* bitmask (128 - arg) if arg >= 64
*/
t1 = cwh_expr_bincalc(OPR_LSHR,WN_Intconst(MTYPE_I8,-1),WN_COPY_Tree(arg));
t1 = WN_CreateExp1(OPC_I8BNOT,t1);
t2 = cwh_expr_bincalc(OPR_SUB,WN_Intconst(MTYPE_I8,128),WN_COPY_Tree(arg));
t2 = cwh_generate_bitmask(t2,MTYPE_I8);
wn = WN_CreateExp2(OPC_I4I8LT,arg,WN_Intconst(t,64));
wn = WN_CreateExp3(OPC_I8SELECT,wn,t1,t2);
}
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push_typed(wn,WN_item,Be_Type_Tbl(t));
}
/*=============================================
*
* fei_mbits
*
* CSMG(x1, x2, x3)
*
* Bit by bit selective merge. (x1 AND x3) OR (x2 AND NOT x3)
*
* x1, x2, x3 are all the same length objects (the FE assures this)
*
*
*=============================================
*/
extern void
fei_mbits (TYPE type)
{
WN *wn,*a1,*a2,*mask;
WN *ae=NULL;
mask = cwh_expr_operand(&ae);
a2 = cwh_expr_operand(&ae);
a1 = cwh_expr_operand(&ae);
cwh_stk_push(a1,WN_item);
cwh_stk_push(WN_COPY_Tree(mask),WN_item);
fei_and(type); /* Stack contains a1 & mask */
cwh_stk_push(mask,WN_item);
fei_bneg(type); /* Stack contains NOT mask */
cwh_stk_push(a2,WN_item);
fei_and(type);
fei_or(type);
wn = cwh_expr_operand(NULL);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
/*=============================================
*
* fei_new_binop_cshift
*
* Implement a circular left-shift. May be applied
* to types other than integers, so convert operand
* via TAS if required.
*
*=============================================
*/
extern void
fei_new_binop_cshift (TYPE type)
{
WN *wn,*shift,*arg;
WN *t1;
WN *ae=NULL;
INT64 bitlen;
TYPE_ID bt ;
TYPE_ID br ;
shift = cwh_expr_operand(&ae);
arg = cwh_expr_operand(&ae);
bt = WNRTY(arg);
bitlen = MTYPE_size_best(bt);
if (bitlen <= MTYPE_size_best(MTYPE_U4))
br = MTYPE_I4 ;
else
br = MTYPE_I8 ;
if (!MTYPE_is_integral(bt))
arg = WN_Tas(br,Be_Type_Tbl(bt),arg) ;
t1 = cwh_expr_bincalc(OPR_SUB,WN_Intconst(MTYPE_I4,bitlen),WN_COPY_Tree(shift));
t1 = cwh_expr_bincalc(OPR_LSHR,WN_COPY_Tree(arg),t1);
wn = cwh_expr_bincalc(OPR_SHL,arg,shift);
wn = cwh_expr_bincalc(OPR_BIOR,wn,t1);
wn = cwh_wrap_cvtl(wn,bt);
wn = cwh_expr_restore_arrayexp(wn,ae);
cwh_stk_push(wn,WN_item);
}
/*=============================================
*
* cwh_expr_temp
*
* Return the address of a temp. If e_sz is
* NULL or constant the temp depends on the TY,
* and a temp is generated, otherwise an alloca
* is issued and a preg returned with the address.
*
* If an array valued temp is needed, then the TY
* should reflect this. e_sz is intepreted as the
* size of an element, so if TY_size == 0, the
* element size can stand in.
*
* If the temp is created within a parallel region
* it should be marked as LOCAL in the pragma list
*
* Flag is PASSED/SAVED etc - typical for an address
*
*=============================================
*/
extern WN *
cwh_expr_temp(TY_IDX ty, WN * e_sz, FLAG flag)
{
ST * st ;
TY_IDX tp ;
WN * wr ;
WN * nl[1] ;
WN * wn[1] ;
BOOL va[1] ;
WN *free_stmt;
PREG_det det;
if (e_sz == NULL && TY_size(ty) != 0) {
st = cwh_stab_temp_ST(ty,TY_name(ty));
cwh_expr_set_flags(st,flag);
wr = cwh_addr_address_ST(st);
} else if (WNOPR(e_sz) == OPR_INTCONST && TY_size(ty) != 0) {
st = cwh_stab_temp_ST(ty,TY_name(ty));
cwh_expr_set_flags(st,flag);
wr = cwh_addr_address_ST(st);
} else {
DevAssert((e_sz!=NULL),("NULL element size in cwh_expr_temp"));
if (TY_kind(ty) == KIND_ARRAY)
wn[0] = cwh_types_size_WN(ty,e_sz);
else
wn[0] = e_sz ;
nl[0] = NULL;
va[0] = TRUE;
/* pregs are assumed LOCAL by the MP lowerer */
det = cwh_preg_next_preg(Pointer_Mtype,"concat_temp",NULL);
wr = cwh_intrin_op(INTRN_F90_STACKTEMPALLOC,1,wn,nl,va,Pointer_Mtype);
tp = cwh_types_make_pointer_type(ty, FALSE);
cwh_addr_store_ST(det.preg_st,det.preg,tp,wr);
wr = cwh_addr_load_ST(det.preg_st,det.preg,tp);
/* Add call to free temp to defer list, set flags so it won't be moved before alloc */
wn[0] = cwh_intrin_wrap_value_parm(WN_COPY_Tree(wr));
free_stmt = WN_Create_Intrinsic(OPC_VINTRINSIC_CALL,INTRN_F90_STACKTEMPFREE,1,wn);
WN_Set_Call_Non_Parm_Ref(free_stmt);
WN_Set_Call_Non_Parm_Mod(free_stmt);
cwh_block_append_given_id(free_stmt,Defer_Block,FALSE);
}
return(wr);
}
/*===============================================
*
* cwh_expr_temp_set_pragma
*
* If a temp is created within a parallel region
* it may require a LOCAL pragma to be set in
* the parallel region.
*
*===============================================
*/
extern void
cwh_expr_temp_set_pragma(ST *st)
{
cwh_block_add_to_enclosing_regions(WN_PRAGMA_LOCAL,st);
}
/*===============================================
*
* cwh_expr_str_operand
*
* Assumes stack top contains an STR_item; pops the
* string marker and then returns the address and the
* length of the string in the argument passed to the
* routine.
*
*===============================================
*/
extern void
cwh_expr_str_operand(W_node expr[2])
{
WN * wn;
cwh_stk_pop_STR();
wn = cwh_expr_operand(NULL);
W_ty(expr[0]) = cwh_types_WN_TY(wn,FALSE);
W_wn(expr[0]) = wn;
W_ty(expr[1]) = cwh_stk_get_TY();
W_wn(expr[1]) = cwh_expr_address(f_NONE);
}
/*===============================================
*
* cwh_expr_set_flags
*
* set the requested flags on an ST. In 7.3, the
* addr_passed flag is removed & the information
* computed by wopt.
*
*===============================================
*/
extern void
cwh_expr_set_flags(ST *st, FLAG flag)
{
if (st != NULL)
if ((ST_class(st) == CLASS_VAR) ||
(ST_class(st) == CLASS_FUNC)) {
if (flag & f_T_SAVED) Set_ST_addr_saved(st);
}
}
/*===============================================
*
* cwh_expr_dispose_of_char
*
* The CHAR intrinsic is converted to temp and
* address of temp in the f90 lowerer. In some
* circumstances we want the value immediately.
*
* Take the intrinsic op and PARM off the top,
* and return the value. There may be an ARRAYEXP
* in the way, as it would have a ARRAY argumnet
* to the intrinsic.
*
*===============================================
*/
extern WN *
cwh_expr_dispose_of_char(WN * src)
{
WN * wn;
WN * wn1;
if (WN_operator(src) == OPR_ARRAYEXP) {
wn = WN_kid0(src);
wn1 = cwh_expr_dispose_of_char(wn);
if (wn != wn1)
WN_kid0(src) = wn1;
} else if (WN_operator(src) == OPR_INTRINSIC_OP &&
WN_intrinsic(src) == INTRN_CHAR) {
wn = WN_kid0(src);
WN_Delete(src);
src = WN_kid0(wn);
WN_Delete(wn);
}
return src;
}
| 23.59074 | 112 | 0.588332 | sharugupta |
58b5fcf7ca64b4c3bbabc5434907d73f32c6a9bb | 492 | hpp | C++ | libs/font/include/sge/font/optional_index_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/font/include/sge/font/optional_index_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/font/include/sge/font/optional_index_fwd.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_FONT_OPTIONAL_INDEX_FWD_HPP_INCLUDED
#define SGE_FONT_OPTIONAL_INDEX_FWD_HPP_INCLUDED
#include <sge/font/index.hpp>
#include <fcppt/optional/object_fwd.hpp>
namespace sge::font
{
using optional_index = fcppt::optional::object<sge::font::index>;
}
#endif
| 24.6 | 65 | 0.745935 | cpreh |
58b8ad1d9513b8852205252eea4a7c3e4389899b | 79,884 | cpp | C++ | src/game/client/tf/vgui/tf_clientscoreboard.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/client/tf/vgui/tf_clientscoreboard.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/client/tf/vgui/tf_clientscoreboard.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include <tier1/fmtstr.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/ImagePanel.h>
#include <vgui_controls/RichText.h>
#include <vgui_controls/Frame.h>
#include <vgui/IScheme.h>
#include <vgui/ILocalize.h>
#include <vgui/ISurface.h>
#include <vgui/IVGui.h>
#include <vgui_controls/SectionedListPanel.h>
#include <vgui_controls/ImageList.h>
#include <game/client/iviewport.h>
#include <KeyValues.h>
#include <filesystem.h>
#include "IGameUIFuncs.h" // for key bindings
#include "VGuiMatSurface/IMatSystemSurface.h"
#include "tf_controls.h"
#include "tf_shareddefs.h"
#include "tf_playermodelpanel.h"
#include "tf_clientscoreboard.h"
#include "c_playerresource.h"
#include "c_tf_playerresource.h"
#include "c_tf_team.h"
#include "c_tf_player.h"
#include "vgui_avatarimage.h"
#include "tf_gamerules.h"
#include "econ_item_description.h"
#include "vgui_controls/MenuItem.h"
#include "vgui/IInput.h"
#include "voice_status.h"
#include "vgui_controls/ScrollBarSlider.h"
#include "econ/econ_trading.h"
#include "in_buttons.h"
#include "tf_mapinfo.h"
#if defined ( _X360 )
#include "engine/imatchmaking.h"
#endif
#if defined( REPLAY_ENABLED )
#include "replay/ireplaysystem.h"
#include "replay/ienginereplay.h"
#endif
#include "econ_item_system.h"
#include "tf_mann_vs_machine_stats.h"
#include "player_vs_environment/c_tf_upgrades.h"
#include "tf_badge_panel.h"
#include "report_player_dialog.h"
using namespace vgui;
#define SCOREBOARD_MAX_LIST_ENTRIES 12
ConVar tf_scoreboard_mouse_mode( "tf_scoreboard_mouse_mode", "0", FCVAR_ARCHIVE );
void cc_scoreboard_convar_changed( IConVar *pConVar, const char *pOldString, float flOldValue )
{
CTFClientScoreBoardDialog *pScoreboard = dynamic_cast< CTFClientScoreBoardDialog *>( gViewPortInterface->FindPanelByName( PANEL_SCOREBOARD ) );
if ( pScoreboard )
{
pScoreboard->Reset();
}
}
ConVar tf_scoreboard_ping_as_text( "tf_scoreboard_ping_as_text", "0", FCVAR_ARCHIVE, "Show ping values as text in the scoreboard.", cc_scoreboard_convar_changed );
ConVar tf_scoreboard_alt_class_icons( "tf_scoreboard_alt_class_icons", "0", FCVAR_ARCHIVE, "Show alternate class icons in the scoreboard." );
extern bool IsInCommentaryMode( void );
extern bool DuelMiniGame_GetStats( C_TFPlayer **ppPlayer, uint32 &unMyScore, uint32 &unOpponentScore );
extern void AddSubKeyNamed( KeyValues *pKeys, const char *pszName );
extern ConVar cl_hud_playerclass_use_playermodel;
extern ConVar mp_tournament;
//......................................................
enum
{
PING_LOW,
PING_MED,
PING_HIGH,
PING_VERY_HIGH,
PING_BOT_RED,
PING_BOT_BLUE,
PING_MAX_TYPES
};
static const char *pszPingIcons[SCOREBOARD_PING_ICONS] = {
"../hud/scoreboard_ping_low",
"../hud/scoreboard_ping_med",
"../hud/scoreboard_ping_high",
"../hud/scoreboard_ping_very_high",
"../hud/scoreboard_ping_bot_red",
"../hud/scoreboard_ping_bot_blue",
};
static const char *pszPingIconsDead[SCOREBOARD_PING_ICONS] = {
"../hud/scoreboard_ping_low_d",
"../hud/scoreboard_ping_med_d",
"../hud/scoreboard_ping_high_d",
"../hud/scoreboard_ping_very_high_d",
"../hud/scoreboard_ping_bot_red_d",
"../hud/scoreboard_ping_bot_blue_d",
};
COMPILE_TIME_ASSERT( SCOREBOARD_PING_ICONS == PING_MAX_TYPES );
//......................................................
static const char *pszDominationIcons[SCOREBOARD_DOMINATION_ICONS] = {
"",
"../hud/leaderboard_dom1",
"../hud/leaderboard_dom2",
"../hud/leaderboard_dom3",
"../hud/leaderboard_dom4",
"../hud/leaderboard_dom5",
"../hud/leaderboard_dom6",
"../hud/leaderboard_dom7",
"../hud/leaderboard_dom8",
"../hud/leaderboard_dom9",
"../hud/leaderboard_dom10",
"../hud/leaderboard_dom11",
"../hud/leaderboard_dom12",
"../hud/leaderboard_dom13",
"../hud/leaderboard_dom14",
"../hud/leaderboard_dom15",
"../hud/leaderboard_dom16",
};
static const char *pszDominationIconsDead[SCOREBOARD_DOMINATION_ICONS] = {
"",
"../hud/leaderboard_dom1_d",
"../hud/leaderboard_dom2_d",
"../hud/leaderboard_dom3_d",
"../hud/leaderboard_dom4_d",
"../hud/leaderboard_dom5_d",
"../hud/leaderboard_dom6_d",
"../hud/leaderboard_dom7_d",
"../hud/leaderboard_dom8_d",
"../hud/leaderboard_dom9_d",
"../hud/leaderboard_dom10_d",
"../hud/leaderboard_dom11_d",
"../hud/leaderboard_dom12_d",
"../hud/leaderboard_dom13_d",
"../hud/leaderboard_dom14_d",
"../hud/leaderboard_dom15_d",
"../hud/leaderboard_dom16_d",
};
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CTFClientScoreBoardDialog::CTFClientScoreBoardDialog( IViewPort *pViewPort ) : CClientScoreBoardDialog( pViewPort )
{
SetProportional( true );
SetKeyBoardInputEnabled( false );
SetScheme( "ClientScheme" );
m_pPlayerListBlue = new SectionedListPanel( this, "BluePlayerList" );
m_pPlayerListRed = new SectionedListPanel( this, "RedPlayerList" );
m_pLabelPlayerName = new CExLabel( this, "PlayerNameLabel", "" );
m_pImagePanelHorizLine = new ImagePanel( this, "HorizontalLine" );
m_pClassImage = new CTFClassImage( this, "ClassImage" );
m_pPlayerModelPanel = new CTFPlayerModelPanel( this, "classmodelpanel" );
m_pPlayerModelPanel->SetDoFlexes(false);
m_pLocalPlayerStatsPanel = new vgui::EditablePanel( this, "LocalPlayerStatsPanel" );
m_pLocalPlayerDuelStatsPanel = new vgui::EditablePanel( this, "LocalPlayerDuelStatsPanel" );
m_duelPanelLocalPlayer.m_pPanel = new vgui::EditablePanel( m_pLocalPlayerDuelStatsPanel, "LocalPlayerData" );
m_duelPanelOpponent.m_pPanel = new vgui::EditablePanel( m_pLocalPlayerDuelStatsPanel, "OpponentData" );
m_pRedTeamName = new CExLabel( this, "RedTeamLabel", "" );
m_pBlueTeamName = new CExLabel( this, "BlueTeamLabel", "" );
m_pRedLeaderAvatarImage = new CAvatarImagePanel( this, "RedLeaderAvatar" );
m_pRedLeaderAvatarBG = new EditablePanel( this, "RedLeaderAvatarBG" );
m_pRedTeamImage = new ImagePanel( this, "RedTeamImage" );
m_pBlueLeaderAvatarImage = new CAvatarImagePanel( this, "BlueLeaderAvatar" );
m_pBlueLeaderAvatarBG = new EditablePanel( this, "BlueLeaderAvatarBG" );
m_pBlueTeamImage = new ImagePanel( this, "BlueTeamImage" );
m_pServerTimeLeftValue = NULL;
m_pFontTimeLeftNumbers = vgui::INVALID_FONT;
m_pFontTimeLeftString = vgui::INVALID_FONT;
m_pMvMScoreboard = new CTFHudMannVsMachineScoreboard( this, "MvMScoreboard" );
m_pRightClickMenu = NULL;
m_iImageDominated = 0;
m_iImageDominatedDead = 0;
m_iImageNemesis = 0;
m_iImageNemesisDead = 0;
m_iImageStreak = 0;
m_iImageStreakDead = 0;
m_iTextureCamera = -1;
m_bIsPVEMode = false;
// m_bDisplayLevel = false;
m_bMouseActivated = true;
Q_memset( m_iImageClass, NULL, sizeof( m_iImageClass ) );
Q_memset( m_iImageClassAlt, NULL, sizeof( m_iImageClassAlt ) );
Q_memset( m_iImageDom, NULL, sizeof( m_iImageDom ) );
Q_memset( m_iImageDomDead, NULL, sizeof( m_iImageDomDead ) );
ListenForGameEvent( "server_spawn" );
#ifdef STAGING_ONLY
// ListenForGameEvent( "bountymode_toggled" );
#endif
SetDialogVariable( "server", "" );
SetVisible( false );
m_nPlayerModelPanelIndex = -1;
m_bRedScrollBarVisible = false;
m_bBlueScrollBarVisible = false;
m_nExtraSpace = 0;
m_hSelectedPlayer = NULL;
m_bUsePlayerModel = false;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CTFClientScoreBoardDialog::~CTFClientScoreBoardDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::PerformLayout()
{
BaseClass::PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdatePlayerModel()
{
if ( !m_pPlayerModelPanel->IsVisible() )
return;
if ( m_nPlayerModelPanelIndex == -1 )
{
m_nPlayerModelPanelIndex = GetLocalPlayerIndex();
}
C_TFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( m_nPlayerModelPanelIndex ) );
if ( !pPlayer )
return;
int nClass = pPlayer->GetPlayerClass()->GetClassIndex();
int nTeam = pPlayer->GetTeamNumber();
int nItemSlot = ( pPlayer->IsAlive() && pPlayer->GetActiveTFWeapon() ) ? pPlayer->GetActiveTFWeapon()->GetAttributeContainer()->GetItem()->GetStaticData()->GetLoadoutSlot( nClass ) : LOADOUT_POSITION_PRIMARY;;
CEconItemView *pWeapon = NULL;
CTFWeaponBase *pEnt = dynamic_cast<CTFWeaponBase*>( pPlayer->GetEntityForLoadoutSlot( nItemSlot ) );
if ( pEnt )
{
pWeapon = pEnt->GetAttributeContainer()->GetItem();
}
bool bIsRobot = false;
int iRobot = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER( pPlayer, iRobot, appear_as_mvm_robot );
bIsRobot = iRobot ? true : false;
m_pPlayerModelPanel->ClearCarriedItems();
m_pPlayerModelPanel->SetToPlayerClass( nClass, bIsRobot );
m_pPlayerModelPanel->SetTeam( nTeam );
if ( pWeapon )
{
m_pPlayerModelPanel->AddCarriedItem( pWeapon );
}
for ( int wbl = pPlayer->GetNumWearables() - 1; wbl >= 0; wbl-- )
{
C_TFWearable *pItem = dynamic_cast<C_TFWearable*>( pPlayer->GetWearable( wbl ) );
if ( !pItem )
continue;
if ( pItem->IsViewModelWearable() )
continue;
if ( pItem->IsDisguiseWearable() )
continue;
CAttributeContainer *pCont = pItem->GetAttributeContainer();
CEconItemView *pEconItemView = pCont ? pCont->GetItem() : NULL;
if ( pEconItemView && pEconItemView->IsValid() )
{
m_pPlayerModelPanel->AddCarriedItem( pEconItemView );
}
}
m_pPlayerModelPanel->HoldItemInSlot( nItemSlot );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
KeyValues *pConditions = NULL;
if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() )
{
pConditions = new KeyValues( "conditions" );
AddSubKeyNamed( pConditions, "if_mvm" );
}
LoadControlSettings( "Resource/UI/Scoreboard.res", NULL, NULL, pConditions );
m_hScoreFontDefault = pScheme->GetFont( "Default", true );
m_hScoreFontSmallest = pScheme->GetFont( "ScoreboardSmallest", true );
if ( pConditions )
{
pConditions->deleteThis();
}
if ( m_pImageList )
{
m_iImageDominated = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_dominated", true ) );
m_iImageDominatedDead = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_dominated_d", true ) );
m_iImageNemesis = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_nemesis", true ) );
m_iImageNemesisDead = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_nemesis_d", true ) );
m_iImageStreak = m_pImageList->AddImage( scheme()->GetImage( "../hud/scoreboard_streak", true ) );
m_iImageStreakDead = m_pImageList->AddImage( scheme()->GetImage( "../hud/scoreboard_streak_d", true ) );
for(int i = 1 ; i < SCOREBOARD_DOMINATION_ICONS ; i++)
{
m_iImageDom[i] = m_pImageList->AddImage( scheme()->GetImage( pszDominationIcons[i], true ) );
m_iImageDomDead[i] = m_pImageList->AddImage( scheme()->GetImage( pszDominationIconsDead[i], true ) );
}
for( int i = 1 ; i < SCOREBOARD_CLASS_ICONS ; i++ )
{
m_iImageClass[i] = m_pImageList->AddImage( scheme()->GetImage( g_pszClassIcons[i], true ) );
m_iImageClassAlt[i] = m_pImageList->AddImage( scheme()->GetImage( g_pszClassIconsAlt[i], true ) );
}
for ( int i = 0; i < SCOREBOARD_PING_ICONS; i++ )
{
m_iImagePing[i] = m_pImageList->AddImage( scheme()->GetImage( pszPingIcons[i], true ) );
m_iImagePingDead[i] = m_pImageList->AddImage( scheme()->GetImage( pszPingIconsDead[i], true ) );
}
// resize the images to our resolution
for (int i = 1 ; i < m_pImageList->GetImageCount(); i++ )
{
int wide = 13, tall = 13;
m_pImageList->GetImage(i)->SetSize(scheme()->GetProportionalScaledValueEx( GetScheme(), wide ), scheme()->GetProportionalScaledValueEx( GetScheme(),tall ) );
}
}
SetPlayerListImages( m_pPlayerListBlue );
SetPlayerListImages( m_pPlayerListRed );
SetBgColor( Color( 0, 0, 0, 0) );
SetBorder( NULL );
SetVisible( false );
m_duelPanelLocalPlayer.m_pAvatar = dynamic_cast< CAvatarImagePanel *>( m_duelPanelLocalPlayer.m_pPanel->FindChildByName("AvatarImage") );
m_duelPanelLocalPlayer.m_pPlayerNameLabel = dynamic_cast< CExLabel *>( m_duelPanelLocalPlayer.m_pPanel->FindChildByName("AvatarTextLabel") );
m_duelPanelOpponent.m_pAvatar = dynamic_cast< CAvatarImagePanel *>( m_duelPanelOpponent.m_pPanel->FindChildByName("AvatarImage") );
m_duelPanelOpponent.m_pPlayerNameLabel = dynamic_cast< CExLabel *>( m_duelPanelOpponent.m_pPanel->FindChildByName("AvatarTextLabel") );
if ( m_pLocalPlayerStatsPanel )
{
m_pKillsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Kills" ) );
m_pDeathsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Deaths" ) );
m_pAssistLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Assists" ) );
m_pDestructionLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Destruction" ) );
m_pCapturesLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Captures" ) );
m_pDefensesLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Defenses" ) );
m_pDominationsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Domination" ) );
m_pRevengeLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Revenge" ) );
m_pHealingLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Healing" ) );
m_pInvulnsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Invuln" ) );
m_pTeleportsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Teleports" ) );
m_pHeadshotsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Headshots" ) );
m_pBackstabsLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Backstabs" ) );
m_pBonusLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Bonus" ) );
m_pSupportLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Support" ) );
m_pDamageLabel = dynamic_cast< CExLabel* >( m_pLocalPlayerStatsPanel->FindChildByName( "Damage" ) );
}
m_pServerTimeLeftValue = dynamic_cast< CExLabel* >( FindChildByName( "ServerTimeLeftValue" ) );
m_pFontTimeLeftNumbers = pScheme->GetFont( "ScoreboardMediumSmall", true );
m_pFontTimeLeftString = pScheme->GetFont( "ScoreboardVerySmall", true );
Reset();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::ShowPanel( bool bShow )
{
if ( bShow )
{
if ( TFGameRules() && TFGameRules()->ShowMatchSummary() )
return;
}
// Catch the case where we call ShowPanel before ApplySchemeSettings, eg when
// going from windowed <-> fullscreen
if ( m_pImageList == NULL )
{
InvalidateLayout( true, true );
}
bool bIsPVEMode = TFGameRules() && TFGameRules()->IsPVEModeActive();
if ( m_bIsPVEMode != bIsPVEMode )
{
m_bIsPVEMode = bIsPVEMode;
InvalidateLayout( true, true );
}
// Don't show in commentary mode
if ( IsInCommentaryMode() )
{
bShow = false;
}
if ( IsVisible() == bShow )
{
return;
}
int iRenderGroup = gHUD.LookupRenderGroupIndexByName( "global" );
if ( bShow )
{
SetVisible( true );
MoveToFront();
InitializeInputScheme();
gHUD.LockRenderGroup( iRenderGroup );
// Clear the selected item, this forces the default to the local player
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
pList->ClearSelection();
}
if ( tf_scoreboard_mouse_mode.GetInt() == 2 )
m_bMouseActivated = false;
UpdateServerTimeLeft();
m_nPlayerModelPanelIndex = -1;
m_hSelectedPlayer = NULL;
UpdatePlayerModel();
}
else
{
SetVisible( false );
if ( m_pRightClickMenu )
{
delete m_pRightClickMenu;
m_pRightClickMenu = NULL;
}
gHUD.UnlockRenderGroup( iRenderGroup );
m_bMouseActivated = false;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::OnCommand( const char *command )
{
if ( V_stristr( command, "report_player" ) )
{
engine->ClientCmd( command );
}
else if ( !V_strcmp( command, "muteplayer" ) )
{
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( !pIssueKeyValues )
return;
int playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
if ( playerIndex > 0 && playerIndex <= MAX_PLAYERS && GetClientVoiceMgr() )
{
// Toggle
GetClientVoiceMgr()->SetPlayerBlockedState( playerIndex, ( GetClientVoiceMgr()->IsPlayerBlocked( playerIndex ) ? false : true ) );
}
}
}
}
else if ( !V_strcmp( command, "specplayer" ) )
{
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( !pIssueKeyValues )
return;
int playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
if ( playerIndex > 0 && playerIndex <= MAX_PLAYERS )
{
engine->ClientCmd_Unrestricted( VarArgs( "spec_player %d\n", playerIndex ) );
}
}
}
}
else if ( !V_strcmp( command, "friendadd" ) )
{
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( !pIssueKeyValues )
return;
int playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
CBasePlayer *pTarget = UTIL_PlayerByIndex( playerIndex );
if ( pTarget && !( pTarget->IsBot() || pTarget->IsHLTV() ) )
{
CSteamID steamID;
if ( pTarget->GetSteamID( &steamID ) && steamapicontext && steamapicontext->SteamFriends() )
{
steamapicontext->SteamFriends()->ActivateGameOverlayToUser( "friendadd", steamID );
}
}
}
}
}
else if ( !V_strcmp( command, "jointrade" ) )
{
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( !pIssueKeyValues )
return;
int playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
CBasePlayer *pTarget = UTIL_PlayerByIndex( playerIndex );
if ( pTarget && !( pTarget->IsBot() || pTarget->IsHLTV() ) )
{
// Prevent large UI popup during a match
if ( pTarget->GetTeamNumber() >= FIRST_GAME_TEAM )
{
if ( TFGameRules() && TFGameRules()->UsePlayerReadyStatusMode() && TFGameRules()->State_Get() == GR_STATE_RND_RUNNING )
return;
}
Trading_RequestTrade( playerIndex );
}
}
}
}
else if ( !V_strcmp( command, "profile" ) )
{
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( !pIssueKeyValues )
return;
int playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
CBasePlayer *pTarget = UTIL_PlayerByIndex( playerIndex );
if ( pTarget && !( pTarget->IsBot() || pTarget->IsHLTV() ) )
{
CSteamID steamID;
if ( pTarget->GetSteamID( &steamID ) && steamapicontext && steamapicontext->SteamFriends() )
{
steamapicontext->SteamFriends()->ActivateGameOverlayToUser( "steamid", steamID );
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::OnItemSelected( vgui::Panel *panel )
{
if ( panel == m_pPlayerListBlue || panel == m_pPlayerListRed )
{
// There can be only one... selection
if ( panel == m_pPlayerListBlue && m_pPlayerListBlue->GetSelectedItem() >= 0 && m_pPlayerListRed->GetSelectedItem() >= 0 )
{
m_pPlayerListRed->ClearSelection();
}
else if ( panel == m_pPlayerListRed && m_pPlayerListRed->GetSelectedItem() >= 0 && m_pPlayerListBlue->GetSelectedItem() >= 0 )
{
m_pPlayerListBlue->ClearSelection();
}
if ( vgui::input()->IsMouseDown( MOUSE_RIGHT ) )
{
OnScoreBoardMouseRightRelease();
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::OnItemContextMenu( vgui::Panel *panel )
{
if ( panel == m_pPlayerListBlue || panel == m_pPlayerListRed )
{
if ( vgui::input()->IsMouseDown( MOUSE_RIGHT ) )
{
OnScoreBoardMouseRightRelease();
}
}
}
void CTFClientScoreBoardDialog::OnReportPlayer( KeyValues *pData )
{
int playerIndex = pData->GetInt( "playerIndex" );
int nReason = pData->GetInt( "reason" );
CSteamID steamID = GetSteamIDForPlayerIndex( playerIndex );
ReportPlayerAccount( steamID, nReason );
}
//-----------------------------------------------------------------------------
// Purpose: Figure out where to put the camera view
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::GetCameraUnderlayBounds( int *pX, int *pY, int *pWide, int *pTall )
{
GetBounds( *pX, *pY, *pWide, *pTall );
// inset these b*pY a bit
*pX += 15;
*pY += 25;
*pWide -= 30;
*pTall -= 40;
}
void CTFClientScoreBoardDialog::OnScoreBoardMouseRightRelease( void )
{
if ( !IsVisible() )
return;
C_TFPlayer *pLocalTFPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalTFPlayer )
return;
SectionedListPanel *pList = GetSelectedPlayerList();
if ( !pList )
return;
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem < 0 )
return;
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( !pIssueKeyValues )
return;
int playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
if ( GetLocalPlayerIndex() == playerIndex )
return;
if ( m_pRightClickMenu )
delete m_pRightClickMenu;
const char *pszContextMenuBorder = "DarkComboBoxBorder";
const char *pszContextMenuFont = "HudFontMediumSecondary";
m_pRightClickMenu = new Menu( pList, "RightClickMenu" );
m_pRightClickMenu->SetKeyBoardInputEnabled( false );
m_pRightClickMenu->SetBorder( scheme()->GetIScheme( GetScheme() )->GetBorder( pszContextMenuBorder ) );
m_pRightClickMenu->SetFgColor( Color( 0, 0, 255, 255 ) );
m_pRightClickMenu->SetPaintBackgroundEnabled( true );
m_pRightClickMenu->SetPaintBackgroundType( 0 );
m_pRightClickMenu->SetFont( scheme()->GetIScheme( GetScheme() )->GetFont( pszContextMenuFont ) );
bool bFakeClient = ( g_TF_PR->IsFakePlayer( playerIndex ) );
bool bTournamentGame = ( g_TF_PR->GetTeam( playerIndex ) >= FIRST_GAME_TEAM && TFGameRules() && TFGameRules()->UsePlayerReadyStatusMode() && TFGameRules()->State_Get() == GR_STATE_RND_RUNNING );
MenuBuilder contextMenuBuilder( m_pRightClickMenu, this );
// Report
if ( !bFakeClient && engine->GetLocalPlayer() != playerIndex )
{
Menu *pReportSubMenu = new Menu( this, "ReportSubMenu" );
pReportSubMenu->SetBorder( scheme()->GetIScheme( GetScheme() )->GetBorder( pszContextMenuBorder ) );
pReportSubMenu->SetFont( scheme()->GetIScheme( GetScheme() )->GetFont( pszContextMenuFont ) );
contextMenuBuilder.AddCascadingMenuItem( "#TF_ScoreBoard_Context_Report", pReportSubMenu, "report" );
for ( int iReason=CMsgGC_ReportPlayer_EReason_kReason_INVALID+1; iReason<CMsgGC_ReportPlayer_EReason_kReason_COUNT; ++iReason )
{
CFmtStr name( "#TF_ScoreBoard_Context_Report_Reason%d", iReason );
KeyValues *pReport = new KeyValues( "ReportPlayer" );
pReport->SetInt( "playerIndex", playerIndex );
pReport->SetInt( "reason", iReason );
pReportSubMenu->AddMenuItem( name, pReport, this );
}
}
// Mute
if ( !bFakeClient && GetClientVoiceMgr() )
{
const char *pszString = GetClientVoiceMgr()->IsPlayerBlocked( playerIndex ) ? "#TF_ScoreBoard_Context_UnMute" : "#TF_ScoreBoard_Context_Mute";
contextMenuBuilder.AddMenuItem( pszString, "muteplayer", "mute" );
}
// Spectate
if ( g_TF_PR->IsAlive( playerIndex ) && ( !pLocalTFPlayer->IsAlive() || pLocalTFPlayer->GetTeamNumber() == TEAM_SPECTATOR ) )
{
contextMenuBuilder.AddMenuItem( "#TF_ScoreBoard_Context_Spec", "specplayer", "spectate" );
}
// Add Friend
if ( !bFakeClient )
{
CSteamID steamID;
C_TFPlayer *pTFTarget = ToTFPlayer( UTIL_PlayerByIndex( playerIndex ) );
if ( pTFTarget && pTFTarget->GetSteamID( &steamID ) )
{
if ( steamapicontext && steamapicontext->SteamFriends() && steamapicontext->SteamFriends()->GetFriendRelationship( steamID ) == k_EFriendRelationshipNone )
{
contextMenuBuilder.AddMenuItem( "#TF_ScoreBoard_Context_Friend", "friendadd", "friend" );
}
}
}
// Trade
if ( !bFakeClient && !bTournamentGame )
{
contextMenuBuilder.AddMenuItem( "#TF_ScoreBoard_Context_Trade", "jointrade", "trade" );
}
// Profile
if ( !bFakeClient )
{
contextMenuBuilder.AddMenuItem( "#TF_ScoreBoard_Context_Profile", "profile", "profile" );
}
int x, y;
vgui::input()->GetCursorPosition( x, y );
m_pRightClickMenu->SetPos( x, y );
m_pRightClickMenu->SetVisible( true );
m_pRightClickMenu->AddActionSignalTarget( this );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTFClientScoreBoardDialog::UseMouseMode( void )
{
return tf_scoreboard_mouse_mode.GetInt() == 1 || ( tf_scoreboard_mouse_mode.GetInt() == 2 && m_bMouseActivated );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::InitializeInputScheme( void )
{
if ( !IsVisible() )
return;
if ( !m_pPlayerListBlue || !m_pPlayerListRed )
return;
MakePopup( false, UseMouseMode() );
SetKeyBoardInputEnabled( false );
SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListBlue->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListBlue->AddActionSignalTarget( this );
m_pPlayerListBlue->SetClickable( UseMouseMode() );
m_pPlayerListRed->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListRed->AddActionSignalTarget( this );
m_pPlayerListRed->SetClickable( UseMouseMode() );
if ( m_pPlayerListBlue->GetScrollBar() &&
m_pPlayerListBlue->GetScrollBar()->GetButton( 0 ) &&
m_pPlayerListBlue->GetScrollBar()->GetButton( 1 ) &&
m_pPlayerListBlue->GetScrollBar()->GetSlider() )
{
m_pPlayerListBlue->SetVerticalScrollbar( UseMouseMode() );
m_pPlayerListBlue->GetScrollBar()->GetButton( 0 )->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListBlue->GetScrollBar()->GetButton( 1 )->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListBlue->GetScrollBar()->GetSlider()->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListBlue->GetScrollBar()->SetMouseInputEnabled( UseMouseMode() );
}
if ( m_pPlayerListRed->GetScrollBar() &&
m_pPlayerListRed->GetScrollBar()->GetButton( 0 ) &&
m_pPlayerListRed->GetScrollBar()->GetButton( 1 ) &&
m_pPlayerListRed->GetScrollBar()->GetSlider() )
{
m_pPlayerListRed->SetVerticalScrollbar( UseMouseMode() );
m_pPlayerListRed->GetScrollBar()->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListRed->GetScrollBar()->GetButton( 0 )->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListRed->GetScrollBar()->GetButton( 1 )->SetMouseInputEnabled( UseMouseMode() );
m_pPlayerListRed->GetScrollBar()->GetSlider()->SetMouseInputEnabled( UseMouseMode() );
}
}
//-----------------------------------------------------------------------------
// Purpose: Resets the scoreboard panel
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::Reset()
{
if ( !m_bIsPVEMode )
{
InitPlayerList( m_pPlayerListBlue );
InitPlayerList( m_pPlayerListRed );
}
m_pPlayerListBlue->SetVisible( !m_bIsPVEMode );
m_pPlayerListRed->SetVisible( !m_bIsPVEMode );
}
//-----------------------------------------------------------------------------
// Purpose: Inits the player list in a list panel
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::InitPlayerList( SectionedListPanel *pPlayerList )
{
pPlayerList->SetVerticalScrollbar( UseMouseMode() );
pPlayerList->RemoveAll();
pPlayerList->RemoveAllSections();
pPlayerList->AddSection( 0, "Players", TFPlayerSortFunc );
pPlayerList->SetSectionAlwaysVisible( 0, true );
pPlayerList->SetSectionFgColor( 0, Color( 255, 255, 255, 255 ) );
pPlayerList->SetBgColor( Color( 0, 0, 0, 0 ) );
pPlayerList->SetBorder( NULL );
pPlayerList->AddColumnToSection( 0, "medal", "", SectionedListPanel::COLUMN_IMAGE | SectionedListPanel::COLUMN_CENTER, m_iMedalWidth );
// Avatars are always displayed at 32x32 regardless of resolution
if ( ShowAvatars() )
{
pPlayerList->AddColumnToSection( 0, "avatar", "", SectionedListPanel::COLUMN_IMAGE | SectionedListPanel::COLUMN_RIGHT, m_iAvatarWidth );
pPlayerList->AddColumnToSection( 0, "spacer", "", 0, m_iSpacerWidth );
}
// the player avatar is always a fixed size, so as we change resolutions we need to vary the size of the name column to adjust the total width of all the columns
m_nExtraSpace = pPlayerList->GetWide() - m_iMedalWidth - m_iAvatarWidth - m_iSpacerWidth - m_iNameWidth - m_iKillstreakWidth - m_iKillstreakImageWidth - m_iNemesisWidth - m_iNemesisWidth - m_iScoreWidth - m_iClassWidth - m_iPingWidth - m_iSpacerWidth - ( 2 * SectionedListPanel::COLUMN_DATA_INDENT ); // the SectionedListPanel will indent the columns on either end by SectionedListPanel::COLUMN_DATA_INDENT
pPlayerList->AddColumnToSection( 0, "name", "#TF_Scoreboard_Name", 0, m_iNameWidth + m_nExtraSpace );
pPlayerList->AddColumnToSection( 0, "killstreak", "", SectionedListPanel::COLUMN_RIGHT, m_iKillstreakWidth );
pPlayerList->AddColumnToSection( 0, "killstreak_image", "", SectionedListPanel::COLUMN_IMAGE, m_iKillstreakImageWidth );
pPlayerList->AddColumnToSection( 0, "dominating", "", SectionedListPanel::COLUMN_IMAGE | SectionedListPanel::COLUMN_CENTER, m_iNemesisWidth );
pPlayerList->AddColumnToSection( 0, "nemesis", "", SectionedListPanel::COLUMN_IMAGE | SectionedListPanel::COLUMN_CENTER, m_iNemesisWidth );
pPlayerList->AddColumnToSection( 0, "score", "#TF_Scoreboard_Score", SectionedListPanel::COLUMN_RIGHT, m_iScoreWidth );
pPlayerList->AddColumnToSection( 0, "class", "", SectionedListPanel::COLUMN_IMAGE | SectionedListPanel::COLUMN_RIGHT, m_iClassWidth );
if ( tf_scoreboard_ping_as_text.GetBool() )
{
pPlayerList->AddColumnToSection( 0, "ping", "#TF_Scoreboard_Ping", SectionedListPanel::COLUMN_RIGHT, m_iPingWidth );
}
else
{
pPlayerList->AddColumnToSection( 0, "ping", "", SectionedListPanel::COLUMN_IMAGE | SectionedListPanel::COLUMN_RIGHT, m_iPingWidth );
}
#ifdef STAGING_ONLY
// if ( m_bDisplayLevel )
// {
// pPlayerList->AddColumnToSection( 0, "level", "#TF_ScoreBoard_LevelLabel", SectionedListPanel::COLUMN_RIGHT, m_iPingWidth );
// }
#endif // STAGING_ONLY
}
//-----------------------------------------------------------------------------
// Purpose: Builds the image list to use in the player list
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::SetPlayerListImages( vgui::SectionedListPanel *pPlayerList )
{
pPlayerList->SetImageList( m_pImageList, false );
pPlayerList->SetVisible( true );
}
//-----------------------------------------------------------------------------
// Purpose: Updates the dialog
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::Update()
{
// MvM
if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() )
{
m_pMvMScoreboard->OnTick();
}
UpdateTeamInfo();
UpdatePlayerList();
UpdateSpectatorList();
UpdateArenaWaitingToPlayList();
UpdatePlayerDetails();
MoveToCenterOfScreen();
UpdateServerTimeLeft();
AdjustForVisibleScrollbar();
UpdateBadgePanels( m_pRedBadgePanels, m_pPlayerListRed );
UpdateBadgePanels( m_pBlueBadgePanels, m_pPlayerListBlue );
float flNextUpdate = 1.0f;
if ( UseMouseMode() )
{
if ( ( m_pPlayerListRed && m_pPlayerListRed->GetScrollBar() && m_pPlayerListRed->GetScrollBar()->IsVisible() ) ||
( m_pPlayerListBlue && m_pPlayerListBlue->GetScrollBar() && m_pPlayerListBlue->GetScrollBar()->IsVisible() ) )
{
// we need a much faster update rate for MouseMode() so the MedalList can update when the scrollbar is quickly moved
// we're listening for the ScrollBarSliderMoved message but it still doesn't keep up with dragging the mouse around
flNextUpdate = 0.02f;
}
else
{
flNextUpdate = 0.15f;
}
}
m_fNextUpdateTime = gpGlobals->curtime + flNextUpdate;
}
//-----------------------------------------------------------------------------
// Purpose: Updates information about teams
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdateTeamInfo()
{
// update the team sections in the scoreboard
for ( int teamIndex = TF_TEAM_RED; teamIndex <= TF_TEAM_BLUE; teamIndex++ )
{
C_TFTeam *team = GetGlobalTFTeam( teamIndex );
if ( team )
{
// choose dialog variables to set depending on team
const char *pDialogVarTeamScore = "";
const char *pDialogVarTeamPlayerCount = "";
const char *pDialogVarTeamName = "";
switch ( teamIndex )
{
case TF_TEAM_RED:
pDialogVarTeamScore = "redteamscore";
pDialogVarTeamPlayerCount = "redteamplayercount";
pDialogVarTeamName = "redteamname";
break;
case TF_TEAM_BLUE:
pDialogVarTeamScore = "blueteamscore";
pDialogVarTeamPlayerCount = "blueteamplayercount";
pDialogVarTeamName = "blueteamname";
break;
default:
Assert( false );
break;
}
// update # of players on each team
wchar_t string1[1024];
wchar_t wNumPlayers[6];
_snwprintf( wNumPlayers, ARRAYSIZE( wNumPlayers ), L"%i", team->Get_Number_Players() );
if ( team->Get_Number_Players() == 1 )
{
g_pVGuiLocalize->ConstructString_safe( string1, g_pVGuiLocalize->Find( "#TF_ScoreBoard_Player" ), 1, wNumPlayers );
}
else
{
g_pVGuiLocalize->ConstructString_safe( string1, g_pVGuiLocalize->Find( "#TF_ScoreBoard_Players" ), 1, wNumPlayers );
}
// set # of players for team in dialog
SetDialogVariable( pDialogVarTeamPlayerCount, string1 );
// set team score in dialog
SetDialogVariable( pDialogVarTeamScore, team->Get_Score() );
// set the team name
SetDialogVariable( pDialogVarTeamName, team->Get_Localized_Name() );
}
}
bool bMvM = TFGameRules() && TFGameRules()->IsMannVsMachineMode();
bool bTournament = mp_tournament.GetBool() && !bMvM;
if ( m_pRedTeamName->IsVisible() != bTournament )
{
m_pRedTeamName->SetVisible( bTournament );
}
if ( m_pBlueTeamName->IsVisible() != bTournament )
{
m_pBlueTeamName->SetVisible( bTournament );
}
bool bShowAvatars = g_TF_PR && g_TF_PR->HasPremadeParties();
if ( bShowAvatars )
{
m_pRedLeaderAvatarImage->SetPlayer( GetSteamIDForPlayerIndex( g_TF_PR->GetPartyLeaderRedTeamIndex() ), k_EAvatarSize64x64 );
m_pRedLeaderAvatarImage->SetShouldDrawFriendIcon( false );
m_pBlueLeaderAvatarImage->SetPlayer( GetSteamIDForPlayerIndex( g_TF_PR->GetPartyLeaderBlueTeamIndex() ), k_EAvatarSize64x64 );
m_pBlueLeaderAvatarImage->SetShouldDrawFriendIcon( false );
}
m_pRedLeaderAvatarImage->SetVisible( bShowAvatars );
m_pRedLeaderAvatarBG->SetVisible( bShowAvatars );
m_pRedTeamImage->SetVisible( !bShowAvatars && !bMvM );
m_pBlueLeaderAvatarImage->SetVisible( bShowAvatars );
m_pBlueLeaderAvatarBG->SetVisible( bShowAvatars );
m_pBlueTeamImage->SetVisible( !bShowAvatars && !bMvM );
}
bool AreEnemyTeams( int iTeam1, int iTeam2 )
{
if ( iTeam1 == TF_TEAM_RED && iTeam2 == TF_TEAM_BLUE )
return true;
if ( iTeam1 == TF_TEAM_BLUE && iTeam2 == TF_TEAM_RED )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::AdjustForVisibleScrollbar( void )
{
if ( m_pPlayerListRed && m_pPlayerListRed->GetScrollBar() && ( m_bRedScrollBarVisible != m_pPlayerListRed->GetScrollBar()->IsVisible() ) )
{
m_bRedScrollBarVisible = m_pPlayerListRed->GetScrollBar()->IsVisible();
int iScrollBarWidth = m_bRedScrollBarVisible ? m_pPlayerListRed->GetScrollBar()->GetWide() : 0;
m_pPlayerListRed->SetColumnWidthBySection( 0, "name", m_iNameWidth + m_nExtraSpace - iScrollBarWidth );
}
if ( m_pPlayerListBlue && m_pPlayerListBlue->GetScrollBar() && ( m_bBlueScrollBarVisible != m_pPlayerListBlue->GetScrollBar()->IsVisible() ) )
{
m_bBlueScrollBarVisible = m_pPlayerListBlue->GetScrollBar()->IsVisible();
int iScrollBarWidth = m_bBlueScrollBarVisible ? m_pPlayerListBlue->GetScrollBar()->GetWide() : 0;
m_pPlayerListBlue->SetColumnWidthBySection( 0, "name", m_iNameWidth + m_nExtraSpace - iScrollBarWidth );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdateBadgePanels( CUtlVector<CTFBadgePanel*> &pBadgePanels, vgui::SectionedListPanel *pPlayerList )
{
int iNumPanels = 0;
const IMatchGroupDescription *pMatchDesc = TFGameRules() ? GetMatchGroupDescription( TFGameRules()->GetCurrentMatchGroup() ) : NULL;
const IProgressionDesc *pProgressionDesc = pMatchDesc ? pMatchDesc->m_pProgressionDesc : NULL;
if ( pProgressionDesc && pPlayerList )
{
if ( TFGameRules()->IsMatchTypeCasual() )
{
int parentTall = pPlayerList->GetTall();
CTFBadgePanel *pPanel = NULL;
for ( int i = 0; i < pPlayerList->GetItemCount(); i++ )
{
KeyValues *pKeyValues = pPlayerList->GetItemData( i );
if ( !pKeyValues )
continue;
int iPlayerIndex = pKeyValues->GetInt( "playerIndex" );
const CSteamID steamID = GetSteamIDForPlayerIndex( iPlayerIndex );
if ( steamID.IsValid() )
{
if ( iNumPanels >= pBadgePanels.Count() )
{
pPanel = new CTFBadgePanel( this, "BadgePanel" );
pPanel->MakeReadyForUse();
pPanel->SetVisible( true );
pPanel->SetZPos( 9999 );
pBadgePanels.AddToTail( pPanel );
}
else
{
pPanel = pBadgePanels[iNumPanels];
}
int x, y, wide, tall;
pPlayerList->GetMaxCellBounds( i, 0, x, y, wide, tall );
if ( y + tall > parentTall )
continue;
if ( !pPanel->IsVisible() )
{
pPanel->SetVisible( true );
}
int xParent, yParent;
pPlayerList->GetPos( xParent, yParent );
int nPanelXPos, nPanelYPos, nPanelWide, nPanelTall;
pPanel->GetBounds( nPanelXPos, nPanelYPos, nPanelWide, nPanelTall );
if ( ( nPanelXPos != xParent + x )
|| ( nPanelYPos != yParent + y )
|| ( nPanelWide != wide )
|| ( nPanelTall != tall ) )
{
pPanel->SetBounds( xParent + x, yParent + y, wide, tall );
pPanel->InvalidateLayout( true, true );
}
pPanel->SetupBadge( pProgressionDesc, steamID );
iNumPanels++;
}
}
}
}
// hide any unused images
for ( int i = iNumPanels; i < pBadgePanels.Count(); i++ )
{
if ( pBadgePanels[i]->IsVisible() )
{
pBadgePanels[i]->SetVisible( false );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Updates the player list
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdatePlayerList()
{
int iSelectedPlayerIndex = GetLocalPlayerIndex();
// Save off which player we had selected
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int itemID = pList->GetSelectedItem();
if ( itemID >= 0 )
{
KeyValues *pInfo = pList->GetItemData( itemID );
if ( pInfo )
{
iSelectedPlayerIndex = pInfo->GetInt( "playerIndex" );
}
}
}
m_pPlayerListRed->ClearSelection();
m_pPlayerListBlue->ClearSelection();
m_pPlayerListRed->RemoveAll();
m_pPlayerListBlue->RemoveAll();
if ( !g_TF_PR )
return;
C_TFPlayer *pLocalTFPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalTFPlayer )
return;
int localteam = pLocalTFPlayer->GetTeamNumber();
if ( pLocalTFPlayer->m_bIsCoaching && pLocalTFPlayer->m_hStudent )
{
localteam = pLocalTFPlayer->m_hStudent->GetTeamNumber();
}
bool bMadeSelection = false;
for ( int playerIndex = 1; playerIndex <= MAX_PLAYERS; playerIndex++ )
{
if ( g_PR->IsConnected( playerIndex ) || g_PR->IsValid( playerIndex ) )
{
SectionedListPanel *pPlayerList = NULL;
int nTeam = g_PR->GetTeam( playerIndex );
switch ( nTeam )
{
case TF_TEAM_BLUE:
pPlayerList = m_pPlayerListBlue;
break;
case TF_TEAM_RED:
pPlayerList = m_pPlayerListRed;
break;
}
if ( !pPlayerList )
continue;
MM_PlayerConnectionState_t eConnectionState = g_TF_PR->GetPlayerConnectionState( playerIndex );
const wchar_t *pwszFormat = NULL;
if ( eConnectionState == MM_DISCONNECTED )
{
pwszFormat = g_pVGuiLocalize->Find( "#TF_MM_PlayerLostConnection" );
}
else if ( ( eConnectionState == MM_CONNECTING ) || ( eConnectionState == MM_LOADING ) )
{
pwszFormat = g_pVGuiLocalize->Find( "#TF_MM_PlayerConnecting" );
}
if ( pwszFormat )
{
KeyValues *pKV = new KeyValues( "data" );
pKV->SetInt( "playerIndex", playerIndex );
pKV->SetInt( "connected", 1 );
// HOLY CHEESEBALL BUSY INDICATOR
const wchar_t *pwszEllipses = &L"....."[4 - ( (unsigned)Plat_FloatTime() % 5U )];
wchar_t wszLocalized[512];
g_pVGuiLocalize->ConstructString_safe( wszLocalized, pwszFormat, 1, pwszEllipses );
pKV->SetWString( "name", wszLocalized );
int itemID = pPlayerList->AddItem( 0, pKV );
pPlayerList->SetItemFgColor( itemID, ( eConnectionState == MM_DISCONNECTED ) ? Color( 208, 147, 7, 255 ) : Color( 76, 107, 34, 255 ) );
pPlayerList->SetItemBgColor( itemID, Color( 0, 0, 0, 80 ) );
pPlayerList->SetItemFont( itemID, m_hScoreFontSmallest );
pKV->deleteThis();
continue;
}
int iActiveDominations = g_TF_PR->GetActiveDominations( playerIndex );
// Debug getting some bogus counts here.
if ( iActiveDominations < 0 )
{
Assert( iActiveDominations >= 0 );
iActiveDominations = 0;
}
else if ( iActiveDominations >= MAX_PLAYERS )
{
Assert( iActiveDominations < MAX_PLAYERS );
iActiveDominations = MAX_PLAYERS - 1;
}
// Now limit based on the number of images we have
if ( iActiveDominations >= SCOREBOARD_DOMINATION_ICONS )
{
iActiveDominations = SCOREBOARD_DOMINATION_ICONS - 1;
}
bool bDominating;
if ( iActiveDominations > 0 )
{
bDominating = true;
}
else
{
bDominating = false;
}
bool bAlive = g_TF_PR->IsAlive( playerIndex );
int iDominationIndex = ( bDominating ? ( m_iImageDom[iActiveDominations] ) : 0 );
if ( !bAlive )
{
iDominationIndex = ( bDominating ? ( m_iImageDomDead[iActiveDominations] ) : 0 );
}
KeyValues *pKeyValues = new KeyValues( "data" );
pKeyValues->SetInt( "playerIndex", playerIndex );
pKeyValues->SetString( "name", g_TF_PR->GetPlayerName( playerIndex ) );
pKeyValues->SetInt( "dominating", iDominationIndex );
pKeyValues->SetInt( "score", g_TF_PR->GetTotalScore( playerIndex ) );
pKeyValues->SetInt( "connected", 2 );
C_TFPlayer *pTFPlayer = ToTFPlayer( UTIL_PlayerByIndex( playerIndex ) );
if ( pTFPlayer && pTFPlayer->GetActiveTFWeapon() )
{
int nCount = g_TF_PR->GetStreak( playerIndex, CTFPlayerShared::kTFStreak_Kills );
if ( nCount )
{
pKeyValues->SetInt( "killstreak_image", bAlive ? m_iImageStreak : m_iImageStreakDead );
pKeyValues->SetInt( "killstreak", nCount );
}
else
{
pKeyValues->SetInt( "killstreak_image", 0 );
pKeyValues->SetString( "killstreak", "" );
}
}
// check for bots first, so malicious server operators can't fake a ping and stuff their server with bots that look like players
if ( g_PR->IsFakePlayer( playerIndex ) )
{
if ( tf_scoreboard_ping_as_text.GetBool() )
{
pKeyValues->SetString( "ping", "#TF_Scoreboard_Bot" );
}
else
{
int iIndex = ( nTeam == TF_TEAM_RED ) ? PING_BOT_RED : PING_BOT_BLUE;
pKeyValues->SetInt( "ping", bAlive ? m_iImagePing[iIndex] : m_iImagePingDead[iIndex] );
}
}
else
{
int nPing = g_PR->GetPing( playerIndex );
if ( nPing < 1 )
{
if ( tf_scoreboard_ping_as_text.GetBool() )
{
pKeyValues->SetString( "ping", "" );
}
else
{
pKeyValues->SetInt( "ping", 0 );
}
}
else
{
if ( tf_scoreboard_ping_as_text.GetBool() )
{
pKeyValues->SetInt( "ping", nPing );
}
else
{
int iIndex = PING_VERY_HIGH;
if ( nPing < 125 )
{
iIndex = PING_LOW;
}
else if ( nPing < 200 )
{
iIndex = PING_MED;
}
else if ( nPing < 275 )
{
iIndex = PING_HIGH;
}
pKeyValues->SetInt( "ping", bAlive ? m_iImagePing[iIndex] : m_iImagePingDead[iIndex] );
}
}
}
if ( TFGameRules() && TFGameRules()->IsHolidayActive( kHoliday_Halloween ) && TFGameRules()->ArePlayersInHell() )
{
bAlive &= pTFPlayer && !pTFPlayer->m_Shared.InCond( TF_COND_HALLOWEEN_GHOST_MODE );
}
// are they a Spy that's feigning death? mark them as dead in the scoreboard...
if ( g_TF_PR->GetPlayerClass( playerIndex ) == TF_CLASS_SPY )
{
if ( pTFPlayer && pTFPlayer->m_Shared.InCond( TF_COND_FEIGN_DEATH ) )
{
bAlive = false;
}
}
// can only see class information if we're on the same team
if ( !AreEnemyTeams( g_PR->GetTeam( playerIndex ), localteam ) && !( localteam == TEAM_UNASSIGNED ) )
{
// class name
if ( g_PR->IsConnected( playerIndex ) )
{
int iClass = g_TF_PR->GetPlayerClass( playerIndex );
if ( GetLocalPlayerIndex() == playerIndex && !bAlive )
{
// If this is local player and he is dead, show desired class (which he will spawn as) rather than current class.
int iDesiredClass = pLocalTFPlayer->m_Shared.GetDesiredPlayerClassIndex();
// use desired class unless it's random -- if random, his future class is not decided until moment of spawn
if ( TF_CLASS_RANDOM != iDesiredClass )
{
iClass = iDesiredClass;
}
}
else
{
// for non-local players, show the current class
iClass = g_TF_PR->GetPlayerClass( playerIndex );
}
if ( iClass >= TF_FIRST_NORMAL_CLASS && iClass <= TF_LAST_NORMAL_CLASS )
{
if ( bAlive )
{
pKeyValues->SetInt( "class", tf_scoreboard_alt_class_icons.GetBool() ? m_iImageClassAlt[iClass] : m_iImageClass[iClass] );
}
else
{
pKeyValues->SetInt( "class", tf_scoreboard_alt_class_icons.GetBool() ? m_iImageClassAlt[iClass + 9] : m_iImageClass[iClass + 9] ); // +9 is to jump ahead to the darker dead icons
}
}
else
{
pKeyValues->SetInt( "class", 0 );
}
}
}
else
{
if ( pTFPlayer && pTFPlayer->m_Shared.IsPlayerDominated( pLocalTFPlayer->entindex() ) )
{
// if local player is dominated by this player, show a nemesis icon
pKeyValues->SetInt( "nemesis", bAlive ? m_iImageNemesis : m_iImageNemesisDead );
}
else if ( pLocalTFPlayer->m_Shared.IsPlayerDominated( playerIndex ) )
{
// if this player is dominated by the local player, show the domination icon
pKeyValues->SetInt( "nemesis", bAlive ? m_iImageDominated : m_iImageDominatedDead );
}
}
#ifdef STAGING_ONLY
// if ( m_bDisplayLevel )
// {
// pKeyValues->SetInt( "level", g_TF_PR->GetPlayerLevel( playerIndex ) );
// }
#endif // STAGING_ONLY
UpdatePlayerAvatar( playerIndex, pKeyValues );
// the medal column is just a place holder for the images that are displayed later
pKeyValues->SetInt( "medal", 0 );
int itemID = pPlayerList->AddItem( 0, pKeyValues );
Color clr = g_PR->GetTeamColor( nTeam );
// change color based off alive or dead status. Also slightly different if its local player since the name is highlighted.
if ( !bAlive )
{
if ( nTeam == TF_TEAM_RED )
{
if ( GetLocalPlayerIndex() != playerIndex )
{
clr = Color( 135, 83, 83, 255 );
}
else
{
clr = Color( 182, 75, 75, 255 );
}
}
else
{
if ( GetLocalPlayerIndex() != playerIndex )
{
clr = Color( 81, 97, 129, 255 );
}
else
{
clr = Color( 123, 153, 187, 255 );
}
}
}
pPlayerList->SetItemFgColor( itemID, clr );
pPlayerList->SetItemBgColor( itemID, Color( 0, 0, 0, 80 ) );
pPlayerList->SetItemFont( itemID, m_hScoreFontDefault );
if ( iSelectedPlayerIndex == playerIndex )
{
bMadeSelection = true;
pPlayerList->SetSelectedItem( itemID );
}
pKeyValues->deleteThis();
}
else
{
MM_PlayerConnectionState_t eConnectionState = g_TF_PR->GetPlayerConnectionState( playerIndex );
if ( eConnectionState == MM_WAITING_FOR_PLAYER )
{
SectionedListPanel *pPlayerList = NULL;
int nTeam = g_PR->GetTeam( playerIndex );
switch ( nTeam )
{
case TF_TEAM_BLUE:
pPlayerList = m_pPlayerListBlue;
break;
case TF_TEAM_RED:
pPlayerList = m_pPlayerListRed;
break;
}
if ( pPlayerList )
{
const wchar_t *pwszFormat = g_pVGuiLocalize->Find( "#TF_MM_LookingForPlayer" );
if ( pwszFormat )
{
KeyValues *pKV = new KeyValues( "data" );
pKV->SetInt( "playerIndex", playerIndex );
pKV->SetInt( "connected", 0 );
// HOLY CHEESEBALL BUSY INDICATOR
const wchar_t *pwszEllipses = &L"....."[4 - ( (unsigned)Plat_FloatTime() % 5U )];
wchar_t wszLocalized[512];
g_pVGuiLocalize->ConstructString_safe( wszLocalized, pwszFormat, 1, pwszEllipses );
pKV->SetWString( "name", wszLocalized );
int itemID = pPlayerList->AddItem( 0, pKV );
pPlayerList->SetItemFgColor( itemID, Color( 120, 120, 120, 255 ) );
pPlayerList->SetItemBgColor( itemID, Color( 0, 0, 0, 80 ) );
pPlayerList->SetItemFont( itemID, m_hScoreFontSmallest );
pKV->deleteThis();
}
}
}
}
}
// If we're on spectator, find a default selection
#ifdef _X360
if ( !bMadeSelection )
{
if ( m_pPlayerListBlue->GetItemCount() > 0 )
{
m_pPlayerListBlue->SetSelectedItem( 0 );
}
else if ( m_pPlayerListRed->GetItemCount() > 0 )
{
m_pPlayerListRed->SetSelectedItem( 0 );
}
}
#endif
// force the lists to PerformLayout() now so we can update our medal images after we return
m_pPlayerListRed->InvalidateLayout( true );
m_pPlayerListBlue->InvalidateLayout( true );
}
//-----------------------------------------------------------------------------
// Purpose: Updates the spectator list
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdateSpectatorList()
{
char szCoachList[512] = "" ;
int nCoaches = 0;
char szSpectatorList[512] = "" ;
int nSpectators = 0;
for( int playerIndex = 1 ; playerIndex <= MAX_PLAYERS; playerIndex++ )
{
if ( ShouldShowAsSpectator( playerIndex ) )
{
C_TFPlayer *pPlayer = (C_TFPlayer*)UTIL_PlayerByIndex( playerIndex );
if ( pPlayer && pPlayer->m_bIsCoaching && pPlayer->m_hStudent )
{
if ( nCoaches > 0 )
{
Q_strncat( szCoachList, ", ", ARRAYSIZE( szCoachList ) );
}
Q_strncat( szCoachList, g_PR->GetPlayerName( playerIndex ), ARRAYSIZE( szCoachList ) );
nCoaches++;
}
else
{
if ( nSpectators > 0 )
{
Q_strncat( szSpectatorList, ", ", ARRAYSIZE( szSpectatorList ) );
}
Q_strncat( szSpectatorList, g_PR->GetPlayerName( playerIndex ), ARRAYSIZE( szSpectatorList ) );
nSpectators++;
}
}
}
wchar_t wzText[512] = L"";
if ( nCoaches > 0 )
{
const char *pchFormat = ( 1 == nCoaches ? "#ScoreBoard_Coach" : "#ScoreBoard_Coaches" );
wchar_t wzCount[16];
wchar_t wzList[1024];
_snwprintf( wzCount, ARRAYSIZE( wzCount ), L"%i", nCoaches );
g_pVGuiLocalize->ConvertANSIToUnicode( szCoachList, wzList, sizeof( wzList ) );
g_pVGuiLocalize->ConstructString_safe( wzText, g_pVGuiLocalize->Find( pchFormat), 2, wzCount, wzList );
}
if ( nSpectators > 0 )
{
const char *pchFormat = ( 1 == nSpectators ? "#ScoreBoard_Spectator" : "#ScoreBoard_Spectators" );
wchar_t wzSpectatorText[512] = L"";
wchar_t wzSpectatorCount[16];
wchar_t wzSpectatorList[1024];
_snwprintf( wzSpectatorCount, ARRAYSIZE( wzSpectatorCount ), L"%i", nSpectators );
g_pVGuiLocalize->ConvertANSIToUnicode( szSpectatorList, wzSpectatorList, sizeof( wzSpectatorList ) );
g_pVGuiLocalize->ConstructString_safe( wzSpectatorText, g_pVGuiLocalize->Find( pchFormat), 2, wzSpectatorCount, wzSpectatorList );
if ( nCoaches > 0 )
{
V_wcscat_safe( wzText, L". " );
}
V_wcscat_safe( wzText, wzSpectatorText );
}
SetDialogVariable( "spectators", wzText );
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether the specified player index is an arena spectator
//-----------------------------------------------------------------------------
bool CTFClientScoreBoardDialog::ShouldShowAsArenaWaitingToPlay( int iPlayerIndex )
{
if ( !g_TF_PR )
return false;
// see if player is connected
if ( g_TF_PR->IsConnected( iPlayerIndex ) )
{
if ( g_TF_PR->IsArenaSpectator( iPlayerIndex ) == true )
return false;
if ( g_TF_PR->GetPlayerClass( iPlayerIndex ) == TF_CLASS_UNDEFINED )
return false;
if ( g_TF_PR->GetTeam( iPlayerIndex ) > LAST_SHARED_TEAM )
return false;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Updates the spectator list
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdateArenaWaitingToPlayList()
{
char szSpectatorList[512] = "" ;
wchar_t wzSpectators[512] = L"";
if ( TFGameRules() && TFGameRules()->IsInArenaMode() == true )
{
int nSpectators = 0;
for( int playerIndex = 1 ; playerIndex <= MAX_PLAYERS; playerIndex++ )
{
if ( ShouldShowAsArenaWaitingToPlay( playerIndex ) )
{
if ( nSpectators > 0 )
{
Q_strncat( szSpectatorList, ", ", ARRAYSIZE( szSpectatorList ) );
}
Q_strncat( szSpectatorList, g_PR->GetPlayerName( playerIndex ), ARRAYSIZE( szSpectatorList ) );
nSpectators++;
}
}
if ( nSpectators > 0 )
{
const char *pchFormat = ( 1 == nSpectators ? "#TF_Arena_ScoreBoard_Spectator" : "#TF_Arena_ScoreBoard_Spectators" );
wchar_t wzSpectatorCount[16];
wchar_t wzSpectatorList[1024];
_snwprintf( wzSpectatorCount, ARRAYSIZE( wzSpectatorCount ), L"%i", nSpectators );
g_pVGuiLocalize->ConvertANSIToUnicode( szSpectatorList, wzSpectatorList, sizeof( wzSpectatorList ) );
g_pVGuiLocalize->ConstructString_safe( wzSpectators, g_pVGuiLocalize->Find( pchFormat), 2, wzSpectatorCount, wzSpectatorList );
}
}
SetDialogVariable( "waitingtoplay", wzSpectators );
}
static void PopulateDuelPanel( CTFClientScoreBoardDialog::duel_panel_t &duelPanel, C_TFPlayer *pPlayer, int unScore )
{
CSteamID steamID;
if ( duelPanel.m_pAvatar && pPlayer->GetSteamID( &steamID ) )
{
duelPanel.m_pAvatar->SetVisible( true );
duelPanel.m_pAvatar->SetShouldDrawFriendIcon( false );
duelPanel.m_pAvatar->SetPlayer( steamID, k_EAvatarSize64x64 );
}
if ( duelPanel.m_pPlayerNameLabel && g_TF_PR != NULL )
{
duelPanel.m_pPanel->SetDialogVariable( "playername", g_TF_PR->GetPlayerName( pPlayer->entindex() ) );
Color clr = g_PR->GetTeamColor( g_PR->GetTeam( pPlayer->entindex() ) );
duelPanel.m_pPlayerNameLabel->SetFgColor( clr );
}
duelPanel.m_pPanel->SetDialogVariable( "score", unScore );
}
//-----------------------------------------------------------------------------
// Purpose: Updates details about a player
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdatePlayerDetails()
{
ClearPlayerDetails();
// by default, hide these, especially for source tv
m_pLocalPlayerStatsPanel->SetVisible( false );
m_pLocalPlayerDuelStatsPanel->SetVisible( false );
if ( !g_TF_PR )
return;
// Default is local player
C_TFPlayer *pSelectedPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pSelectedPlayer )
return;
int playerIndex = pSelectedPlayer->entindex();
// Change to selected player when using mouse mode
if ( UseMouseMode() )
{
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pIssueKeyValues = pList->GetItemData( iSelectedItem );
if ( pIssueKeyValues )
{
playerIndex = pIssueKeyValues->GetInt( "playerIndex", 0 );
pSelectedPlayer = ToTFPlayer( UTIL_PlayerByIndex( playerIndex ) );
if ( !pSelectedPlayer || !playerIndex )
return;
}
}
}
}
// Make sure the selected player is still connected.
if ( !g_TF_PR->IsConnected( playerIndex ) )
return;
#if defined( REPLAY_ENABLED )
if ( engine->IsHLTV() || g_pEngineClientReplay->IsPlayingReplayDemo() )
#else
if ( engine->IsHLTV() )
#endif
{
SetDialogVariable( "playername", g_TF_PR->GetPlayerName( playerIndex ) );
return;
}
uint32 unMyScore, unOpponentScore;
C_TFPlayer *pDuelingPartner = NULL;
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( pSelectedPlayer == pLocalPlayer && DuelMiniGame_GetStats( &pDuelingPartner, unMyScore, unOpponentScore ) )
{
PopulateDuelPanel( m_duelPanelLocalPlayer, pLocalPlayer, unMyScore );
PopulateDuelPanel( m_duelPanelOpponent, pDuelingPartner, unOpponentScore );
if ( m_pLocalPlayerStatsPanel->IsVisible() == true )
{
m_pLocalPlayerStatsPanel->SetVisible( false );
}
if ( m_pLocalPlayerDuelStatsPanel->IsVisible() == false )
{
m_pLocalPlayerDuelStatsPanel->SetVisible( true );
}
}
else
{
if ( m_pLocalPlayerStatsPanel->IsVisible() == false )
{
m_pLocalPlayerStatsPanel->SetVisible( true );
}
if ( m_pLocalPlayerDuelStatsPanel->IsVisible() == true )
{
m_pLocalPlayerDuelStatsPanel->SetVisible( false );
}
Color cGreen = Color( 0, 255, 0, 255 );
Color cWhite = Color( 255, 255, 255, 255 );
m_pLocalPlayerStatsPanel->SetDialogVariable( "kills", g_TF_PR->GetPlayerScore( playerIndex ) );
if ( m_pKillsLabel )
{
m_pKillsLabel->SetFgColor( g_TF_PR->GetPlayerScore( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "deaths", g_TF_PR->GetDeaths( playerIndex ) );
if ( m_pDeathsLabel )
{
m_pDeathsLabel->SetFgColor( g_TF_PR->GetDeaths( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "assists", pSelectedPlayer->m_Shared.GetKillAssists( playerIndex ) );
if ( m_pAssistLabel )
{
m_pAssistLabel->SetFgColor( pSelectedPlayer->m_Shared.GetKillAssists( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "destruction", pSelectedPlayer->m_Shared.GetBuildingsDestroyed( playerIndex ) );
if ( m_pDestructionLabel )
{
m_pDestructionLabel->SetFgColor( pSelectedPlayer->m_Shared.GetBuildingsDestroyed( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "captures", pSelectedPlayer->m_Shared.GetCaptures( playerIndex ) );
if ( m_pCapturesLabel )
{
m_pCapturesLabel->SetFgColor( pSelectedPlayer->m_Shared.GetCaptures( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "defenses", pSelectedPlayer->m_Shared.GetDefenses( playerIndex ) );
if ( m_pDefensesLabel )
{
m_pDefensesLabel->SetFgColor( pSelectedPlayer->m_Shared.GetDefenses( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "dominations", pSelectedPlayer->m_Shared.GetDominations( playerIndex ) );
if ( m_pDominationsLabel )
{
m_pDominationsLabel->SetFgColor( pSelectedPlayer->m_Shared.GetDominations( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "revenge", pSelectedPlayer->m_Shared.GetRevenge( playerIndex ) );
if ( m_pRevengeLabel )
{
m_pRevengeLabel->SetFgColor( pSelectedPlayer->m_Shared.GetRevenge( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "healing", pSelectedPlayer->m_Shared.GetHealPoints( playerIndex ) );
if ( m_pHealingLabel )
{
m_pHealingLabel->SetFgColor( pSelectedPlayer->m_Shared.GetHealPoints( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "invulns", pSelectedPlayer->m_Shared.GetInvulns( playerIndex ) );
if ( m_pInvulnsLabel )
{
m_pInvulnsLabel->SetFgColor( pSelectedPlayer->m_Shared.GetInvulns( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "teleports", pSelectedPlayer->m_Shared.GetTeleports( playerIndex ) );
if ( m_pTeleportsLabel )
{
m_pTeleportsLabel->SetFgColor( pSelectedPlayer->m_Shared.GetTeleports( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "headshots", pSelectedPlayer->m_Shared.GetHeadshots( playerIndex ) );
if ( m_pHeadshotsLabel )
{
m_pHeadshotsLabel->SetFgColor( pSelectedPlayer->m_Shared.GetHeadshots( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "backstabs", pSelectedPlayer->m_Shared.GetBackstabs( playerIndex ) );
if ( m_pBackstabsLabel )
{
m_pBackstabsLabel->SetFgColor( pSelectedPlayer->m_Shared.GetBackstabs( playerIndex ) ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "bonus", pSelectedPlayer->m_Shared.GetBonusPoints( playerIndex ) );
if ( m_pBonusLabel )
{
m_pBonusLabel->SetFgColor( pSelectedPlayer->m_Shared.GetBonusPoints( playerIndex ) ? cGreen : cWhite );
}
int nSupport = TFGameRules() ? TFGameRules()->CalcPlayerSupportScore( NULL, playerIndex ) : 0;
m_pLocalPlayerStatsPanel->SetDialogVariable( "support", nSupport );
if ( m_pSupportLabel )
{
m_pSupportLabel->SetFgColor( nSupport ? cGreen : cWhite );
}
m_pLocalPlayerStatsPanel->SetDialogVariable( "damage", g_TF_PR->GetDamage( playerIndex ) );
if ( m_pDamageLabel )
{
m_pDamageLabel->SetFgColor( g_TF_PR->GetDamage( playerIndex ) ? cGreen : cWhite );
}
}
SetDialogVariable( "playername", g_TF_PR->GetPlayerName( playerIndex ) );
Color clr = g_PR->GetTeamColor( g_PR->GetTeam( playerIndex ) );
m_pLabelPlayerName->SetFgColor( clr );
m_pImagePanelHorizLine->SetFillColor( clr );
// update our image if our selected player or mode of display has changed
if ( ( m_hSelectedPlayer != pSelectedPlayer ) || ( m_bUsePlayerModel != cl_hud_playerclass_use_playermodel.GetBool() ) )
{
m_hSelectedPlayer = pSelectedPlayer;
m_bUsePlayerModel = cl_hud_playerclass_use_playermodel.GetBool();
int iClass = pSelectedPlayer->m_Shared.GetDesiredPlayerClassIndex();
int iTeam = pSelectedPlayer->GetTeamNumber();
if ( ( pLocalPlayer->InSameTeam( pSelectedPlayer ) || pLocalPlayer->GetTeamNumber() < FIRST_GAME_TEAM ) &&
iTeam >= FIRST_GAME_TEAM && iClass >= TF_FIRST_NORMAL_CLASS && iClass <= TF_LAST_NORMAL_CLASS )
{
if ( cl_hud_playerclass_use_playermodel.GetBool() )
{
if ( !m_pPlayerModelPanel->IsVisible() )
{
m_pPlayerModelPanel->SetVisible( true );
}
if ( m_pClassImage->IsVisible() )
{
m_pClassImage->SetVisible( false );
}
m_nPlayerModelPanelIndex = pSelectedPlayer->entindex();
UpdatePlayerModel();
}
else
{
if ( m_pPlayerModelPanel->IsVisible() )
{
m_pPlayerModelPanel->SetVisible( false );
}
if ( !m_pClassImage->IsVisible() )
{
m_pClassImage->SetVisible( true );
}
m_pClassImage->SetClass( iTeam, iClass, 0 );
}
}
else
{
if ( m_pPlayerModelPanel->IsVisible() )
{
m_pPlayerModelPanel->SetVisible( false );
}
if ( m_pClassImage->IsVisible() )
{
m_pClassImage->SetVisible( false );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Updates Server Time Left
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::UpdateServerTimeLeft()
{
wchar_t wzServerTimeHrsLeft[128];
wchar_t wzServerTimeMinLeft[128];
wchar_t wzServerTimeSecLeft[128];
wchar_t wzServerTimeLeft[128];
int iTimeLeft = 0;
int iHours = 0;
int iMinutes = 0;
int iSeconds = 0;
int iServerTimeLimit = mp_timelimit.GetInt() * 60;
if ( iServerTimeLimit == 0 )
{
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_NoTimeLimit" ), 0 );
SetDialogVariable( "servertimeleft", wzServerTimeLeft );
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_NoTimeLimitNew" ), 0 );
SetDialogVariable( "servertime", wzServerTimeLeft );
if ( m_pServerTimeLeftValue && m_pServerTimeLeftValue->IsVisible() && ( m_pFontTimeLeftString != vgui::INVALID_FONT ) )
{
m_pServerTimeLeftValue->SetFont( m_pFontTimeLeftString );
m_pServerTimeLeftValue->InvalidateLayout();
}
return;
}
iTimeLeft = TFGameRules() ? TFGameRules()->GetTimeLeft() : 0;
if ( iTimeLeft < 0 )
{
iTimeLeft = 0;
}
if ( iTimeLeft == 0 )
{
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_ChangeOnRoundEnd" ), 0 );
SetDialogVariable( "servertimeleft", wzServerTimeLeft );
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_ChangeOnRoundEndNew" ), 0 );
SetDialogVariable( "servertime", wzServerTimeLeft );
if ( m_pServerTimeLeftValue && m_pServerTimeLeftValue->IsVisible() && ( m_pFontTimeLeftString != vgui::INVALID_FONT ) )
{
m_pServerTimeLeftValue->SetFont( m_pFontTimeLeftString );
m_pServerTimeLeftValue->InvalidateLayout();
}
return;
}
iHours = iTimeLeft / 3600;
iMinutes = ( iTimeLeft % 3600 ) / 60;
iSeconds = ( iTimeLeft % 60 );
_snwprintf( wzServerTimeHrsLeft, ARRAYSIZE( wzServerTimeHrsLeft ), L"%i", iHours );
_snwprintf( wzServerTimeMinLeft, ARRAYSIZE( wzServerTimeMinLeft ), L"%02i", iMinutes );
_snwprintf( wzServerTimeSecLeft, ARRAYSIZE( wzServerTimeSecLeft ), L"%02i", iSeconds );
if ( m_pServerTimeLeftValue && m_pServerTimeLeftValue->IsVisible() && ( m_pFontTimeLeftNumbers != vgui::INVALID_FONT ) )
{
m_pServerTimeLeftValue->SetFont( m_pFontTimeLeftNumbers );
m_pServerTimeLeftValue->InvalidateLayout();
}
if ( iHours == 0 )
{
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_TimeLeftNoHours" ), 2, wzServerTimeMinLeft, wzServerTimeSecLeft );
SetDialogVariable( "servertimeleft", wzServerTimeLeft );
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_TimeLeftNoHoursNew" ), 2, wzServerTimeMinLeft, wzServerTimeSecLeft );
SetDialogVariable( "servertime", wzServerTimeLeft );
return;
}
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_TimeLeft" ), 3, wzServerTimeHrsLeft, wzServerTimeMinLeft, wzServerTimeSecLeft );
SetDialogVariable( "servertimeleft", wzServerTimeLeft );
g_pVGuiLocalize->ConstructString_safe( wzServerTimeLeft, g_pVGuiLocalize->Find( "#Scoreboard_TimeLeftNew" ), 3, wzServerTimeHrsLeft, wzServerTimeMinLeft, wzServerTimeSecLeft );
SetDialogVariable( "servertime", wzServerTimeLeft );
}
//-----------------------------------------------------------------------------
// Purpose: Clears score details
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::ClearPlayerDetails()
{
// HLTV has no game stats
#if defined( REPLAY_ENABLED )
bool bVisible = !engine->IsHLTV() && !g_pEngineClientReplay->IsPlayingReplayDemo();
#else
bool bVisible = !engine->IsHLTV();
#endif
SetDialogVariable( "kills", "" );
SetControlVisible( "KillsLabel", bVisible );
SetDialogVariable( "deaths", "" );
SetControlVisible( "DeathsLabel", bVisible );
SetDialogVariable( "captures", "" );
SetControlVisible( "CapturesLabel", bVisible );
SetDialogVariable( "defenses", "" );
SetControlVisible( "DefensesLabel", bVisible );
SetDialogVariable( "dominations", "" );
SetControlVisible( "DominationLabel", bVisible );
SetDialogVariable( "revenge", "" );
SetControlVisible( "RevengeLabel", bVisible );
SetDialogVariable( "assists", "" );
SetControlVisible( "AssistsLabel", bVisible );
SetDialogVariable( "destruction", "" );
SetControlVisible( "DestructionLabel", bVisible );
SetDialogVariable( "healing", "" );
SetControlVisible( "HealingLabel", bVisible );
SetDialogVariable( "invulns", "" );
SetControlVisible( "InvulnLabel", bVisible );
SetDialogVariable( "teleports", "" );
SetControlVisible( "TeleportsLabel", bVisible );
SetDialogVariable( "headshots", "" );
SetControlVisible( "HeadshotsLabel", bVisible );
SetDialogVariable( "backstabs", "" );
SetControlVisible( "BackstabsLabel", bVisible );
SetDialogVariable( "bonus", "" );
SetControlVisible( "BonusLabel", bVisible );
SetDialogVariable( "support", "" );
SetControlVisible( "SupportLabel", bVisible );
SetDialogVariable( "damage", "" );
SetControlVisible( "DamageLabel", bVisible );
SetDialogVariable( "playername", "" );
// SetDialogVariable( "playerscore", "" );
}
//-----------------------------------------------------------------------------
// Purpose: Used for sorting players
//-----------------------------------------------------------------------------
bool CTFClientScoreBoardDialog::TFPlayerSortFunc( vgui::SectionedListPanel *list, int itemID1, int itemID2 )
{
KeyValues *it1 = list->GetItemData(itemID1);
KeyValues *it2 = list->GetItemData(itemID2);
Assert(it1 && it2);
// first compare score
int v1 = it1->GetInt("score");
int v2 = it2->GetInt("score");
if (v1 > v2)
return true;
else if (v1 < v2)
return false;
// sort by connected status next ( 0 is looking for player, 1 is disconnected/connecting/loading, 2 is fully connected )
int connected1 = it1->GetInt( "connected" );
int connected2 = it2->GetInt( "connected" );
if ( ( connected1 != 2 ) || ( connected2 != 2 ) )
return ( connected1 > connected2 );
// if score is the same, use player index to get deterministic sort
int iPlayerIndex1 = it1->GetInt( "playerIndex" );
int iPlayerIndex2 = it2->GetInt( "playerIndex" );
return ( iPlayerIndex1 > iPlayerIndex2 );
}
//-----------------------------------------------------------------------------
// Purpose: Returns a localized string of form "1 point", "2 points", etc for specified # of points
//-----------------------------------------------------------------------------
const wchar_t *GetPointsString( int iPoints )
{
wchar_t wzScoreVal[128];
static wchar_t wzScore[128];
_snwprintf( wzScoreVal, ARRAYSIZE( wzScoreVal ), L"%i", iPoints );
if ( 1 == iPoints )
{
g_pVGuiLocalize->ConstructString_safe( wzScore, g_pVGuiLocalize->Find( "#TF_ScoreBoard_Point" ), 1, wzScoreVal );
}
else
{
g_pVGuiLocalize->ConstructString_safe( wzScore, g_pVGuiLocalize->Find( "#TF_ScoreBoard_Points" ), 1, wzScoreVal );
}
return wzScore;
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether the specified player index is a spectator
//-----------------------------------------------------------------------------
bool CTFClientScoreBoardDialog::ShouldShowAsSpectator( int iPlayerIndex )
{
if ( !g_TF_PR )
return false;
// see if player is connected
if ( g_TF_PR->IsConnected( iPlayerIndex ) )
{
// either spectating or unassigned team should show in spectator list
int iTeam = g_TF_PR->GetTeam( iPlayerIndex );
if ( TFGameRules() )
{
if ( TFGameRules()->IsInArenaMode() )
{
if ( g_TF_PR->IsArenaSpectator( iPlayerIndex ) )
return true;
return false;
}
else if ( TFGameRules()->IsMannVsMachineMode() )
{
if ( g_TF_PR->IsFakePlayer( iPlayerIndex ) )
return false;
}
}
if ( TEAM_SPECTATOR == iTeam || TEAM_UNASSIGNED == iTeam )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Event handler
//-----------------------------------------------------------------------------
void CTFClientScoreBoardDialog::FireGameEvent( IGameEvent *event )
{
const char *type = event->GetName();
if ( FStrEq( type, "server_spawn" ) )
{
// set server name in scoreboard
const char *hostname = event->GetString( "hostname" );
wchar_t wzHostName[256];
wchar_t wzServerLabel[256];
g_pVGuiLocalize->ConvertANSIToUnicode( hostname, wzHostName, sizeof( wzHostName ) );
g_pVGuiLocalize->ConstructString_safe( wzServerLabel, g_pVGuiLocalize->Find( "#Scoreboard_Server" ), 1, wzHostName );
SetDialogVariable( "server", wzServerLabel );
const char *pMapName = event->GetString( "mapname" );
SetDialogVariable( "mapname", GetMapDisplayName( pMapName ) );
// m_pLocalPlayerStatsPanel->SetDialogVariable( "gametype", g_pVGuiLocalize->Find( GetMapType( pMapName ) ) );
}
#ifdef STAGING_ONLY
// else if ( FStrEq( type, "bountymode_toggled" ) )
// {
// m_bDisplayLevel = event->GetBool( "active" );
// InvalidateLayout( true, true );
// }
#endif
if ( IsVisible() )
{
Update();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
SectionedListPanel *CTFClientScoreBoardDialog::GetSelectedPlayerList( void )
{
SectionedListPanel *pList = NULL;
// navigation
if ( m_pPlayerListBlue->GetSelectedItem() >= 0 )
{
pList = m_pPlayerListBlue;
}
else if ( m_pPlayerListRed->GetSelectedItem() >= 0 )
{
pList = m_pPlayerListRed;
}
return pList;
}
//-----------------------------------------------------------------------------
// Purpose: Event handler
//-----------------------------------------------------------------------------
int CTFClientScoreBoardDialog::HudElementKeyInput( int down, ButtonCode_t keynum, const char *pszCurrentBinding )
{
if ( !IsVisible() )
return 1;
if ( !down )
{
return 1;
}
if ( tf_scoreboard_mouse_mode.GetInt() == 2 )
{
if ( !m_bMouseActivated && ( keynum == MOUSE_LEFT || keynum == MOUSE_RIGHT ) )
{
m_bMouseActivated = true;
InitializeInputScheme();
return 0;
}
}
#if defined ( _X360 )
SectionedListPanel *pList = GetSelectedPlayerList();
switch( keynum )
{
case KEY_XBUTTON_UP:
{
if ( pList )
{
pList->MoveSelectionUp();
}
}
return 0;
case KEY_XBUTTON_DOWN:
{
if ( pList )
{
pList->MoveSelectionDown();
}
}
return 0;
case KEY_XBUTTON_RIGHT:
{
if ( m_pPlayerListRed->GetItemCount() == 0 )
return 0;
// move to the red list
// get the row we're in now
int iSelectedBlueItem = m_pPlayerListBlue->GetSelectedItem();
m_pPlayerListBlue->ClearSelection();
if ( iSelectedBlueItem >= 0 )
{
int row = m_pPlayerListBlue->GetRowFromItemID( iSelectedBlueItem );
if ( row >= 0 )
{
int iNewItem = m_pPlayerListRed->GetItemIDFromRow( row );
if ( iNewItem >= 0 )
{
m_pPlayerListRed->SetSelectedItem( iNewItem );
}
else
{
// we have fewer items. Select the last one
int iLastRow = m_pPlayerListRed->GetItemCount()-1;
iNewItem = m_pPlayerListRed->GetItemIDFromRow( iLastRow );
if ( iNewItem >= 0 )
{
m_pPlayerListRed->SetSelectedItem( iNewItem );
}
}
}
}
}
return 0;
case KEY_XBUTTON_LEFT:
{
if ( m_pPlayerListBlue->GetItemCount() == 0 )
return 0;
// move to the blue list
// get the row we're in now
int iSelectedRedItem = m_pPlayerListRed->GetSelectedItem();
if ( iSelectedRedItem < 0 )
iSelectedRedItem = 0;
m_pPlayerListRed->ClearSelection();
if ( iSelectedRedItem >= 0 )
{
int row = m_pPlayerListRed->GetRowFromItemID( iSelectedRedItem );
if ( row >= 0 )
{
int iNewItem = m_pPlayerListBlue->GetItemIDFromRow( row );
if ( iNewItem >= 0 )
{
m_pPlayerListBlue->SetSelectedItem( iNewItem );
}
else
{
// we have fewer items. Select the last one
int iLastRow = m_pPlayerListBlue->GetItemCount()-1;
iNewItem = m_pPlayerListBlue->GetItemIDFromRow( iLastRow );
if ( iNewItem >= 0 )
{
m_pPlayerListBlue->SetSelectedItem( iNewItem );
}
}
}
}
}
return 0;
case KEY_XBUTTON_B:
{
ShowPanel( false );
}
return 0;
case KEY_XBUTTON_A: // Show GamerCard for the selected player
{
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pInfo = pList->GetItemData( iSelectedItem );
DevMsg( 1, "XShowGamerCardUI for player '%s'\n", pInfo->GetString( "name" ) );
uint64 xuid = matchmaking->PlayerIdToXuid( pInfo->GetInt( "playerIndex" ) );
XShowGamerCardUI( XBX_GetPrimaryUserId(), xuid );
}
}
}
return 0;
case KEY_XBUTTON_X: // Show player review for the selected player
{
if ( pList )
{
int iSelectedItem = pList->GetSelectedItem();
if ( iSelectedItem >= 0 )
{
KeyValues *pInfo = pList->GetItemData( iSelectedItem );
DevMsg( 1, "XShowPlayerReviewUI for player '%s'\n", pInfo->GetString( "name" ) );
uint64 xuid = matchmaking->PlayerIdToXuid( pInfo->GetInt( "playerIndex" ) );
XShowPlayerReviewUI( XBX_GetPrimaryUserId(), xuid );
}
}
}
return 0;
default:
break;
}
#endif //_X360
return 1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool ShouldScoreBoardHandleKeyInput( int down, ButtonCode_t keynum, const char *pszCurrentBinding )
{
// We're only looking for specific mouse input
if ( keynum == MOUSE_LEFT || keynum == MOUSE_RIGHT )
{
CTFClientScoreBoardDialog *pScoreBoard = dynamic_cast< CTFClientScoreBoardDialog* >( gViewPortInterface->FindPanelByName( PANEL_SCOREBOARD ) );
if ( pScoreBoard )
{
return !pScoreBoard->HudElementKeyInput( down, keynum, pszCurrentBinding );
}
}
return false;
}
| 33.009917 | 408 | 0.658592 | cstom4994 |
58bf9c0faf5c6679a7b619279cd3def888b27bbb | 442 | hpp | C++ | libs/libvodka/include/vodka/utility/move.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | 1 | 2022-02-11T21:25:53.000Z | 2022-02-11T21:25:53.000Z | libs/libvodka/include/vodka/utility/move.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | 15 | 2021-08-21T13:41:29.000Z | 2022-03-08T14:13:43.000Z | libs/libvodka/include/vodka/utility/move.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | null | null | null | // License: The Unlicense (https://unlicense.org)
#pragma once
#ifndef TYBL_VODKA_UTILITY_MOVE_HPP
#define TYBL_VODKA_UTILITY_MOVE_HPP
#include "vodka/type_traits/remove_reference.hpp" // remove_reference
namespace tybl::vodka {
template <typename T>
constexpr auto
move(T&& obj) noexcept -> remove_reference_t<T>&& {
return static_cast<remove_reference_t<T>&&>(obj);
}
} // namespace tybl::vodka
#endif // TYBL_VODKA_UTILITY_MOVE_HPP
| 23.263158 | 69 | 0.773756 | tybl |
58c10b2a6f5f78dcad4464b1c0cc84317440f2ec | 264 | cpp | C++ | src/main.cpp | darkwood101/snake_game | 8d768ae8fd7b461f3a82c697f375de711ef7269a | [
"MIT"
] | null | null | null | src/main.cpp | darkwood101/snake_game | 8d768ae8fd7b461f3a82c697f375de711ef7269a | [
"MIT"
] | 3 | 2020-12-14T17:16:32.000Z | 2020-12-25T23:43:30.000Z | src/main.cpp | darkwood101/snake_game | 8d768ae8fd7b461f3a82c697f375de711ef7269a | [
"MIT"
] | 1 | 2021-04-24T05:33:32.000Z | 2021-04-24T05:33:32.000Z | #include "globals.hpp"
#include "game.hpp"
int main(int argc, char* argv[]) {
(void) argc; (void) argv;
Game game;
if (game.startScreen() == globals::userExit) return 0;
if (game.run() == globals::playerDead) game.gameOverScreen();
return 0;
} | 26.4 | 65 | 0.632576 | darkwood101 |
58c7409d3cbfbaf7452b8a22729bce7c026dc7a9 | 18,344 | cpp | C++ | src/search_cautious.cpp | ThetaOmega01/tetris_ai_runner | 4a73124c861382f5722eacbe0c7b59289b3bc8ac | [
"MIT"
] | 25 | 2015-01-06T06:08:36.000Z | 2021-12-07T13:04:13.000Z | src/search_cautious.cpp | ThetaOmega01/tetris_ai_runner | 4a73124c861382f5722eacbe0c7b59289b3bc8ac | [
"MIT"
] | null | null | null | src/search_cautious.cpp | ThetaOmega01/tetris_ai_runner | 4a73124c861382f5722eacbe0c7b59289b3bc8ac | [
"MIT"
] | 15 | 2015-01-06T07:25:02.000Z | 2022-01-10T07:00:11.000Z |
#include "search_cautious.h"
using namespace m_tetris;
namespace search_cautious
{
void Search::init(m_tetris::TetrisContext const *context, Config const *config)
{
config_ = config;
node_mark_.init(context->node_max());
node_mark_filtered_.init(context->node_max());
}
std::vector<char> Search::make_path(TetrisNode const *node, TetrisNode const *land_point, TetrisMap const &map)
{
if(node->index_filtered == land_point->index_filtered)
{
return std::vector<char>();
}
const size_t index = land_point->index_filtered;
auto build_path = [](TetrisNode const *node, decltype(node_mark_) &node_mark)->std::vector < char >
{
std::vector<char> path;
while(true)
{
auto result = node_mark.get(node);
node = result.first;
if(node == nullptr)
{
break;
}
path.push_back(result.second);
}
std::reverse(path.begin(), path.end());
return path;
};
node_mark_.clear();
node_search_.clear();
node_search_.push_back(node);
node_mark_.set(node, nullptr, '\0');
size_t cache_index = 0;
if(node->drop(map) != node)
{
do
{
for(size_t max_index = node_search_.size(); cache_index < max_index; ++cache_index)
{
TetrisNode const *node = node_search_[cache_index];
if(node->drop(map)->index_filtered == index)
{
return build_path(node, node_mark_);
}
//l
if(node->move_left && node_mark_.set(node->move_left, node, 'l') && node->move_left->check(map))
{
if(node->move_left->drop(map)->index_filtered == index)
{
return build_path(node->move_left, node_mark_);
}
else
{
node_search_.push_back(node->move_left);
}
}
//r
if(node->move_right && node_mark_.set(node->move_right, node, 'r') && node->move_right->check(map))
{
if(node->move_right->drop(map)->index_filtered == index)
{
return build_path(node->move_right, node_mark_);
}
else
{
node_search_.push_back(node->move_right);
}
}
//L
if(node->move_left && node->move_left->check(map))
{
TetrisNode const *node_L = node->move_left;
while(node_L->move_left && node_L->move_left->check(map))
{
node_L = node_L->move_left;
}
if(node_mark_.set(node_L, node, 'L'))
{
if(node_L->drop(map)->index_filtered == index)
{
return build_path(node_L, node_mark_);
}
else
{
node_search_.push_back(node_L);
}
}
}
//R
if(node->move_right && node->move_right->check(map))
{
TetrisNode const *node_R = node->move_right;
while(node_R->move_right && node_R->move_right->check(map))
{
node_R = node_R->move_right;
}
if(node_mark_.set(node_R, node, 'R'))
{
if(node_R->drop(map)->index_filtered == index)
{
return build_path(node_R, node_mark_);
}
else
{
node_search_.push_back(node_R);
}
}
}
//x
if(node->rotate_opposite && node_mark_.set(node->rotate_opposite, node, 'x') && node->rotate_opposite->check(map))
{
if(node->rotate_opposite->drop(map)->index_filtered == index)
{
return build_path(node->rotate_opposite, node_mark_);
}
else
{
node_search_.push_back(node->rotate_opposite);
}
}
//z
if(node->rotate_counterclockwise && node_mark_.set(node->rotate_counterclockwise, node, 'z') && node->rotate_counterclockwise->check(map))
{
if(node->rotate_counterclockwise->drop(map)->index_filtered == index)
{
return build_path(node->rotate_counterclockwise, node_mark_);
}
else
{
node_search_.push_back(node->rotate_counterclockwise);
}
}
//c
if(node->rotate_clockwise && node_mark_.set(node->rotate_clockwise, node, 'c') && node->rotate_clockwise->check(map))
{
if(node->rotate_clockwise->drop(map)->index_filtered == index)
{
return build_path(node->rotate_clockwise, node_mark_);
}
else
{
node_search_.push_back(node->rotate_clockwise);
}
}
}
}
while(node_search_.size() > cache_index);
node_mark_.clear();
node_search_.clear();
node_search_.push_back(node);
node_mark_.set(node, nullptr, '\0');
cache_index = 0;
}
do
{
for(size_t max_index = node_search_.size(); cache_index < max_index; ++cache_index)
{
TetrisNode const *node = node_search_[cache_index];
//l
if(node->move_left && node_mark_.set(node->move_left, node, 'l') && node->move_left->check(map))
{
if(node->move_left->index_filtered == index)
{
return build_path(node->move_left, node_mark_);
}
else
{
node_search_.push_back(node->move_left);
}
}
//r
if(node->move_right && node_mark_.set(node->move_right, node, 'r') && node->move_right->check(map))
{
if(node->move_right->index_filtered == index)
{
return build_path(node->move_right, node_mark_);
}
else
{
node_search_.push_back(node->move_right);
}
}
//L
if(node->move_left && node->move_left->check(map))
{
TetrisNode const *node_L = node->move_left;
while(node_L->move_left && node_L->move_left->check(map))
{
node_L = node_L->move_left;
}
if(node_mark_.set(node_L, node, 'L'))
{
if(node_L->index_filtered == index)
{
return build_path(node_L, node_mark_);
}
else
{
node_search_.push_back(node_L);
}
}
}
//R
if(node->move_right && node->move_right->check(map))
{
TetrisNode const *node_R = node->move_right;
while(node_R->move_right && node_R->move_right->check(map))
{
node_R = node_R->move_right;
}
if(node_mark_.set(node_R, node, 'R'))
{
if(node_R->index_filtered == index)
{
return build_path(node_R, node_mark_);
}
else
{
node_search_.push_back(node_R);
}
}
}
//x
for(TetrisNode const *wall_kick_node : node->wall_kick_opposite)
{
if(wall_kick_node)
{
if(wall_kick_node->check(map))
{
if(node_mark_.set(wall_kick_node, node, 'x'))
{
if(wall_kick_node->index_filtered == index)
{
return build_path(wall_kick_node, node_mark_);
}
else
{
node_search_.push_back(wall_kick_node);
}
}
break;
}
}
else
{
break;
}
}
//z
for(TetrisNode const *wall_kick_node : node->wall_kick_counterclockwise)
{
if(wall_kick_node)
{
if(wall_kick_node->check(map))
{
if(node_mark_.set(wall_kick_node, node, 'z'))
{
if(wall_kick_node->index_filtered == index)
{
return build_path(wall_kick_node, node_mark_);
}
else
{
node_search_.push_back(wall_kick_node);
}
}
break;
}
}
else
{
break;
}
}
//c
for(TetrisNode const *wall_kick_node : node->wall_kick_clockwise)
{
if(wall_kick_node)
{
if(wall_kick_node->check(map))
{
if(node_mark_.set(wall_kick_node, node, 'c'))
{
if(wall_kick_node->index_filtered == index)
{
return build_path(wall_kick_node, node_mark_);
}
else
{
node_search_.push_back(wall_kick_node);
}
}
break;
}
}
else
{
break;
}
}
if(config_->fast_move_down)
{
//D
TetrisNode const *node_D = node->drop(map);
if(node_mark_.set(node_D, node, 'D'))
{
if(node_D->index_filtered == index)
{
return build_path(node_D, node_mark_);
}
else
{
node_search_.push_back(node_D);
}
}
}
else
{
//d
if(node->move_down && node_mark_.set(node->move_down, node, 'd') && node->move_down->check(map))
{
if(node->move_down->index_filtered == index)
{
return build_path(node->move_down, node_mark_);
}
else
{
node_search_.push_back(node->move_down);
}
//D
TetrisNode const *node_D = node->drop(map);
if(node_mark_.set(node_D, node, 'D'))
{
if(node_D->index_filtered == index)
{
return build_path(node_D, node_mark_);
}
else
{
node_search_.push_back(node_D);
}
}
}
}
}
}
while(node_search_.size() > cache_index);
return std::vector<char>();
}
std::vector<TetrisNode const *> const *Search::search(TetrisMap const &map, TetrisNode const *node, size_t depth)
{
land_point_cache_.clear();
if(!node->check(map))
{
return &land_point_cache_;
}
node_mark_.clear();
node_mark_filtered_.clear();
node_search_.clear();
node_search_.push_back(node);
node_mark_.mark(node);
size_t cache_index = 0;
do
{
for(size_t max_index = node_search_.size(); cache_index < max_index; ++cache_index)
{
node = node_search_[cache_index];
if(!node->move_down || !node->move_down->check(map))
{
if(node_mark_filtered_.mark(node))
{
land_point_cache_.push_back(node);
}
}
//x
for(TetrisNode const *wall_kick_node : node->wall_kick_opposite)
{
if(wall_kick_node)
{
if(wall_kick_node->check(map))
{
if(node_mark_.mark(wall_kick_node))
{
node_search_.push_back(wall_kick_node);
}
break;
}
}
else
{
break;
}
}
//z
for(TetrisNode const *wall_kick_node : node->wall_kick_counterclockwise)
{
if(wall_kick_node)
{
if(wall_kick_node->check(map))
{
if(node_mark_.mark(wall_kick_node))
{
node_search_.push_back(wall_kick_node);
}
break;
}
}
else
{
break;
}
}
//c
for(TetrisNode const *wall_kick_node : node->wall_kick_clockwise)
{
if(wall_kick_node)
{
if(wall_kick_node->check(map))
{
if(node_mark_.mark(wall_kick_node))
{
node_search_.push_back(wall_kick_node);
}
break;
}
}
else
{
break;
}
}
//l
if(node->move_left && node_mark_.mark(node->move_left) && node->move_left->check(map))
{
node_search_.push_back(node->move_left);
}
//r
if(node->move_right && node_mark_.mark(node->move_right) && node->move_right->check(map))
{
node_search_.push_back(node->move_right);
}
if(config_->fast_move_down)
{
//D
TetrisNode const *node_drop = node->drop(map);
if(node_mark_.mark(node_drop))
{
node_search_.push_back(node_drop);
}
}
else
{
//d
if(node->move_down && node_mark_.mark(node->move_down) && node->move_down->check(map))
{
node_search_.push_back(node->move_down);
}
}
}
}
while(node_search_.size() > cache_index);
return &land_point_cache_;
}
} | 38.700422 | 158 | 0.350469 | ThetaOmega01 |
58c7484f769d1e830beba56d5229665ca57f2c95 | 3,609 | hpp | C++ | libraries/client/lib.hpp | utevo/Multiprocess-filesystem | 38ce2c53bd18a8946c1d01c071e5d1c0b6c1f348 | [
"MIT"
] | null | null | null | libraries/client/lib.hpp | utevo/Multiprocess-filesystem | 38ce2c53bd18a8946c1d01c071e5d1c0b6c1f348 | [
"MIT"
] | null | null | null | libraries/client/lib.hpp | utevo/Multiprocess-filesystem | 38ce2c53bd18a8946c1d01c071e5d1c0b6c1f348 | [
"MIT"
] | null | null | null | #ifndef CLIENT_LIB_HPP
#define CLIENT_LIB_HPP
#include <map>
#include "../core/utils.hpp"
#include "../core/sync.hpp"
#include "Handler.h"
extern int test_client_lib(int x);
class MFSClient {
public:
int error;
MFSClient();
void mfs_mount(const char *path);
int mfs_open(const char *name, int mode);
int mfs_creat(const char *name, int mode);
int mfs_close(int fd);
int mfs_read(int fd, char *buf, int len);
int mfs_write(int fd, const char *buf, int len);
int mfs_lseek(int fd, int whence, int offset);
int mfs_unlink(const char *name);
//TODO w ostatecznej wersji zwraca tylko vector<string>
std::vector<std::pair<uint32_t, std::string>> mfs_ls(const char *name);
int mfs_mkdir(const char *name);
int mfs_rmdir(char *name);
//private:
int openAndSeek(const int& offset = 0) const;
int getLowestDescriptor() const;
std::vector<u_int32_t> getAllTakenBlocksInInode(const Inode &inode);
u_int32_t blocksToWrite(const u_int32_t& fileOffset, const u_int32_t& length) const;
Inode getInodeByIndex(u_int32_t index);
//returns the block number from the sequence of saved blocks of the file
uint32_t getBlockInFileByNumber(u_int32_t inode_idx, const Inode& inode, u_int32_t blockNumberInFile);
uint32_t getBlockInFileByNumberIndirect(int disk_fd, u_int32_t inode_idx, const Inode &inode, u_int32_t blockNumberInFile);
bool CheckIfInodeExists(const std::string& name, const u_int32_t& directoryInode);
u_int32_t getInode(std::string path);
u_int32_t getInodeFromDirectoryByName(const int& disk_fd, const std::string& filename, const u_int32_t& directoryInode);
void addInodeToDirectory(const u_int32_t& directoryInodeIndex, const u_int32_t& inodeIndex, const std::string& name);
void removeInodeFromDirectory(const u_int32_t& directoryInodeIndex, const u_int32_t& inodeToDelete);
void directoryFill(int disk_fd, const u_int32_t& directoryInodeIndex,
const u_int32_t& inodeToChange, const u_int32_t &newInode, const std::string& name);
void writeInodeAndName(int disk_fd, const u_int32_t& directoryInodeIndex,
const u_int32_t& newInodeIndex, const std::string& name);
void makeRoot(); //creates root directory
u_int32_t getAndTakeUpFirstFreeInode(); //return inode number
//TODO think about: get n blocks by one call and return vector?
u_int32_t getAndTakeUpFirstFreeBlock(); //returns block number
u_int32_t getFirstFreeBitmapIndex(int disk_fd, u_int32_t offset, u_int32_t sizeInBlocks, u_int32_t amount) const;
void freeInode(unsigned long index);
void freeBlock(unsigned long index);
void freeBitmapIndex(int disk_fd, u_int32_t offset, unsigned long index) const;
void clearBlock(u_int32_t index);
void clearInode(u_int32_t index);
void clearIndirectBlocks(int disk, int index);
//functor when operation fails, e.g. unlock sync
void readFromDisk(int disk_fd, void *buf, size_t size, std::function<void()> functor);
void writeToDisk(int disk_fd, const void *buf, size_t size, std::function<void()> functor);
void lseekOnDisk(int disk_fd, off_t offset, int whence, std::function<void()> functor);
u_int32_t blockSize;
u_int32_t inodeSize;
//number of blocks for each objects
u_int32_t inodes;
u_int32_t inodesBitmap;
u_int32_t blocks;
u_int32_t allocationBitmap;
//offsets in bytes
u_int32_t inodesBitmapOffset;
u_int32_t inodesOffset;
u_int32_t allocationBitmapOffset;
u_int32_t blocksOffset;
std::string disk_path;
//key - file descriptor, value - open file structure
std::map<u_int32_t, OpenFile> open_files;
MockSyncClient sync_client;
};
#endif
| 35.732673 | 125 | 0.764755 | utevo |
58ce019d6e71da6563dfd3d198eae2342bfbdd2a | 309 | hpp | C++ | include/pathfinding/MovementRequestState.hpp | icebreakersentertainment/ice_engine | 52a8313bc266c053366bdf554b5dc27a54ddcb25 | [
"MIT"
] | null | null | null | include/pathfinding/MovementRequestState.hpp | icebreakersentertainment/ice_engine | 52a8313bc266c053366bdf554b5dc27a54ddcb25 | [
"MIT"
] | null | null | null | include/pathfinding/MovementRequestState.hpp | icebreakersentertainment/ice_engine | 52a8313bc266c053366bdf554b5dc27a54ddcb25 | [
"MIT"
] | 1 | 2019-06-11T03:41:48.000Z | 2019-06-11T03:41:48.000Z | #ifndef MOVEMENTREQUESTSTATE_H_
#define MOVEMENTREQUESTSTATE_H_
#include "Types.hpp"
namespace ice_engine
{
namespace pathfinding
{
enum MovementRequestState : uint32
{
NONE = 0,
FAILED,
VALID,
REQUESTING,
WAITING_FOR_QUEUE,
WAITING_FOR_PATH,
VELOCITY,
};
}
}
#endif /* MOVEMENTREQUESTSTATE_H_ */
| 11.884615 | 36 | 0.76699 | icebreakersentertainment |
58cf8d113bd949ed2e1863a0645a6b3ab46dccc6 | 738 | cpp | C++ | luogu/P1085.cpp | StableAgOH/solution-codes | 1fde9424a40f989570e05d7340ddd5497a0d390d | [
"CC0-1.0"
] | null | null | null | luogu/P1085.cpp | StableAgOH/solution-codes | 1fde9424a40f989570e05d7340ddd5497a0d390d | [
"CC0-1.0"
] | null | null | null | luogu/P1085.cpp | StableAgOH/solution-codes | 1fde9424a40f989570e05d7340ddd5497a0d390d | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <ctime>
using namespace std;
//==========================================
const int maxn = 1e5+5;
signed main(signed argc, char const *argv[])
{
#ifdef LOCAL
freopen("in.in", "r", stdin);
freopen("out.out", "w", stdout);
clock_t c1 = clock();
#endif
ios::sync_with_stdio(false);
cin.tie(nullptr);
//======================================
int mxh=0, mxd=0;
for(int i=1;i<=7;i++)
{
int x,y;
cin>>x>>y;
if(x+y>8&&x+y>mxh)
{
mxh = x+y;
mxd = i;
}
}
cout<<mxd<<endl;
//======================================
#ifdef LOCAL
cerr << "Time Used:" << clock() - c1 << "ms" << endl;
#endif
return 0;
}
| 21.705882 | 57 | 0.411924 | StableAgOH |
58d3740afaf64e9fefab4abc7aeaa106a53e7660 | 5,914 | cpp | C++ | Examples/DNSResolver/main.cpp | NUS-SNL/PcapPlusPlus | 79ce861c373e7f4e029552fe8df52f2663c879f0 | [
"Unlicense"
] | 1,856 | 2015-01-08T21:43:04.000Z | 2022-03-30T05:36:25.000Z | Examples/DNSResolver/main.cpp | NUS-SNL/PcapPlusPlus | 79ce861c373e7f4e029552fe8df52f2663c879f0 | [
"Unlicense"
] | 604 | 2015-01-05T22:31:11.000Z | 2022-03-31T16:22:39.000Z | Examples/DNSResolver/main.cpp | NUS-SNL/PcapPlusPlus | 79ce861c373e7f4e029552fe8df52f2663c879f0 | [
"Unlicense"
] | 537 | 2015-06-27T09:14:39.000Z | 2022-03-25T15:35:30.000Z | #include <stdlib.h>
#include <iostream>
#include "PcapPlusPlusVersion.h"
#include "PcapLiveDevice.h"
#include "PcapLiveDeviceList.h"
#include "NetworkUtils.h"
#include "SystemUtils.h"
#include <getopt.h>
#define EXIT_WITH_ERROR(reason) do { \
printUsage(); \
std::cout << std::endl << "ERROR: " << reason << std::endl << std::endl; \
exit(1); \
} while(0)
static struct option DNSResolverOptions[] =
{
{"interface", required_argument, 0, 'i'},
{"hostname", required_argument, 0, 's'},
{"dns-server", required_argument, 0, 'd'},
{"gateway", required_argument, 0, 'g'},
{"timeout", optional_argument, 0, 't'},
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{"list", no_argument, 0, 'l'},
{0, 0, 0, 0}
};
/**
* Print application usage
*/
void printUsage()
{
std::cout << std::endl
<< "Usage:" << std::endl
<< "------" << std::endl
<< pcpp::AppName::get() << " [-hvl] [-t timeout] [-d dns_server] [-g gateway] [-i interface] -s hostname" << std::endl
<< std::endl
<< "Options:" << std::endl
<< std::endl
<< " -h : Displays this help message and exits" << std::endl
<< " -v : Displays the current version and exists" << std::endl
<< " -l : Print the list of interfaces and exists" << std::endl
<< " -s hostname : Hostname to resolve" << std::endl
<< " -i interface : Use the specified interface. Can be interface name (e.g eth0) or interface IPv4 address. If not set" << std::endl
<< " one of the interfaces that has a default gateway will be used" << std::endl
<< " -d dns_server: IPv4 address of DNS server to send the DNS request to. If not set the DNS request will be sent to the gateway" << std::endl
<< " -g gateway : IPv4 address of the gateway to send the DNS request to. If not set the default gateway will be chosen" << std::endl
<< " -t timeout : How long to wait for a reply (in seconds). Default timeout is 5 seconds" << std::endl
<< std::endl;
}
/**
* Print application version
*/
void printAppVersion()
{
std::cout
<< pcpp::AppName::get() << " " << pcpp::getPcapPlusPlusVersionFull() << std::endl
<< "Built: " << pcpp::getBuildDateTime() << std::endl
<< "Built from: " << pcpp::getGitInfo() << std::endl;
exit(0);
}
/**
* Go over all interfaces and output their names
*/
void listInterfaces()
{
const std::vector<pcpp::PcapLiveDevice*>& devList = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDevicesList();
std::cout << std::endl << "Network interfaces:" << std::endl;
for (std::vector<pcpp::PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++)
{
std::cout << " -> Name: '" << (*iter)->getName() << "' IP address: " << (*iter)->getIPv4Address().toString() << std::endl;
}
exit(0);
}
/**
* main method of the application
*/
int main(int argc, char* argv[])
{
pcpp::AppName::init(argc, argv);
std::string hostname;
bool hostnameProvided = false;
std::string interfaceNameOrIP;
bool interfaceNameOrIPProvided = false;
pcpp::IPv4Address dnsServerIP;
pcpp::IPv4Address gatewayIP;
int timeoutSec = -1;
int optionIndex = 0;
int opt = 0;
while((opt = getopt_long(argc, argv, "i:d:g:s:t:hvl", DNSResolverOptions, &optionIndex)) != -1)
{
switch (opt)
{
case 0:
{
break;
}
case 'h':
{
printUsage();
exit(0);
}
case 'v':
{
printAppVersion();
break;
}
case 'l':
{
listInterfaces();
exit(0);
}
case 'i':
{
interfaceNameOrIP = optarg;
interfaceNameOrIPProvided = true;
break;
}
case 'd':
{
dnsServerIP = pcpp::IPv4Address(static_cast<char const *>(optarg));
break;
}
case 'g':
{
gatewayIP = pcpp::IPv4Address(static_cast<char const *>(optarg));
break;
}
case 's':
{
hostname = optarg;
hostnameProvided = true;
break;
}
case 't':
{
timeoutSec = atoi(optarg);
break;
}
default:
{
printUsage();
exit(1);
}
}
}
// make sure that hostname is provided
if (!hostnameProvided)
EXIT_WITH_ERROR("Hostname not provided");
// find the interface to send the DNS request from
pcpp::PcapLiveDevice* dev = NULL;
// if interface name or IP was provided - find the device accordingly
if (interfaceNameOrIPProvided)
{
dev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIpOrName(interfaceNameOrIP);
if (dev == NULL)
EXIT_WITH_ERROR("Couldn't find interface by provided IP address or name");
}
// if interface name or IP was not provided - find a device that has a default gateway
else
{
const std::vector<pcpp::PcapLiveDevice*>& devList = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDevicesList();
for (std::vector<pcpp::PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++)
{
if ((*iter)->getDefaultGateway().isValid())
{
dev = *iter;
break;
}
}
if (dev == NULL)
EXIT_WITH_ERROR("Couldn't find an interface with a default gateway");
}
std::cout << "Using interface '" << dev->getIPv4Address() << "'" << std::endl;
// find the IPv4 address for provided hostname
double responseTime = 0;
uint32_t dnsTTL = 0;
pcpp::IPv4Address resultIP = pcpp::NetworkUtils::getInstance().getIPv4Address(hostname, dev, responseTime, dnsTTL, timeoutSec, dnsServerIP, gatewayIP);
// print resolved IPv4 address if found
if (!resultIP.isValid())
std::cout << std::endl << "Could not resolve hostname [" << hostname << "]" << std::endl;
else
std::cout << std::endl << "IP address of [" << hostname << "] is: " << resultIP << " DNS-TTL=" << dnsTTL << " time=" << (int)responseTime << "ms" << std::endl;
}
| 28.432692 | 164 | 0.603652 | NUS-SNL |
58d8a79da13c5ec0220aaac699c146ab9d5c75cb | 31,289 | cpp | C++ | fpdfsdk/src/pdfwindow/PWL_Edit.cpp | chenjian-rits/pdfium | aafeff816e22c1333c17d8a0eb4fe8927c28142d | [
"BSD-3-Clause"
] | 44 | 2016-03-10T11:51:17.000Z | 2022-03-07T07:46:09.000Z | fpdfsdk/src/pdfwindow/PWL_Edit.cpp | chenjian-rits/pdfium | aafeff816e22c1333c17d8a0eb4fe8927c28142d | [
"BSD-3-Clause"
] | 3 | 2015-09-04T14:35:49.000Z | 2019-10-29T19:00:30.000Z | fpdfsdk/src/pdfwindow/PWL_Edit.cpp | chenjian-rits/pdfium | aafeff816e22c1333c17d8a0eb4fe8927c28142d | [
"BSD-3-Clause"
] | 40 | 2016-04-15T01:49:35.000Z | 2022-02-25T01:36:34.000Z | // Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "../../../core/include/fxcrt/fx_safe_types.h"
#include "../../../core/include/fxcrt/fx_xml.h"
#include "../../include/pdfwindow/PDFWindow.h"
#include "../../include/pdfwindow/PWL_Caret.h"
#include "../../include/pdfwindow/PWL_Edit.h"
#include "../../include/pdfwindow/PWL_EditCtrl.h"
#include "../../include/pdfwindow/PWL_FontMap.h"
#include "../../include/pdfwindow/PWL_ScrollBar.h"
#include "../../include/pdfwindow/PWL_Utils.h"
#include "../../include/pdfwindow/PWL_Wnd.h"
/* ---------------------------- CPWL_Edit ------------------------------ */
CPWL_Edit::CPWL_Edit() : m_pFillerNotify(NULL),
m_pSpellCheck(NULL),
m_bFocus(FALSE)
{
m_pFormFiller = NULL;
}
CPWL_Edit::~CPWL_Edit()
{
ASSERT(m_bFocus == FALSE);
}
CFX_ByteString CPWL_Edit::GetClassName() const
{
return PWL_CLASSNAME_EDIT;
}
void CPWL_Edit::OnDestroy()
{
}
void CPWL_Edit::SetText(const FX_WCHAR* csText)
{
CFX_WideString swText = csText;
if (HasFlag(PES_RICH))
{
CFX_ByteString sValue = CFX_ByteString::FromUnicode(swText);
if (CXML_Element * pXML = CXML_Element::Parse(sValue.c_str(), sValue.GetLength()))
{
int32_t nCount = pXML->CountChildren();
FX_BOOL bFirst = TRUE;
swText.Empty();
for (int32_t i=0; i<nCount; i++)
{
if (CXML_Element * pSubElement = pXML->GetElement(i))
{
CFX_ByteString tag=pSubElement->GetTagName();
if (tag.EqualNoCase("p"))
{
int nChild = pSubElement->CountChildren();
CFX_WideString swSection;
for(int32_t j=0; j<nChild; j++)
{
swSection += pSubElement->GetContent(j);
}
if (bFirst)bFirst = FALSE;
else
swText += FWL_VKEY_Return;
swText += swSection;
}
}
}
delete pXML;
}
}
m_pEdit->SetText(swText.c_str());
}
void CPWL_Edit::RePosChildWnd()
{
if (CPWL_ScrollBar * pVSB = GetVScrollBar()) {
CPDF_Rect rcWindow = m_rcOldWindow;
CPDF_Rect rcVScroll = CPDF_Rect(rcWindow.right,
rcWindow.bottom,
rcWindow.right + PWL_SCROLLBAR_WIDTH,
rcWindow.top);
pVSB->Move(rcVScroll, TRUE, FALSE);
}
if (m_pEditCaret && !HasFlag(PES_TEXTOVERFLOW))
m_pEditCaret->SetClipRect(CPWL_Utils::InflateRect(GetClientRect(),1.0f)); //+1 for caret beside border
CPWL_EditCtrl::RePosChildWnd();
}
CPDF_Rect CPWL_Edit::GetClientRect() const
{
CPDF_Rect rcClient = CPWL_Utils::DeflateRect(GetWindowRect(),(FX_FLOAT)(GetBorderWidth()+GetInnerBorderWidth()));
if (CPWL_ScrollBar * pVSB = GetVScrollBar())
{
if (pVSB->IsVisible())
{
rcClient.right -= PWL_SCROLLBAR_WIDTH;
}
}
return rcClient;
}
void CPWL_Edit::SetAlignFormatH(PWL_EDIT_ALIGNFORMAT_H nFormat, FX_BOOL bPaint/* = TRUE*/)
{
m_pEdit->SetAlignmentH((int32_t)nFormat, bPaint);
}
void CPWL_Edit::SetAlignFormatV(PWL_EDIT_ALIGNFORMAT_V nFormat, FX_BOOL bPaint/* = TRUE*/)
{
m_pEdit->SetAlignmentV((int32_t)nFormat, bPaint);
}
FX_BOOL CPWL_Edit::CanSelectAll() const
{
return GetSelectWordRange() != m_pEdit->GetWholeWordRange();
}
FX_BOOL CPWL_Edit::CanClear() const
{
return !IsReadOnly() && m_pEdit->IsSelected();
}
FX_BOOL CPWL_Edit::CanCopy() const
{
return !HasFlag(PES_PASSWORD) && !HasFlag(PES_NOREAD) && m_pEdit->IsSelected();
}
FX_BOOL CPWL_Edit::CanCut() const
{
return CanCopy() && !IsReadOnly();
}
FX_BOOL CPWL_Edit::CanPaste() const
{
if (IsReadOnly()) return FALSE;
CFX_WideString swClipboard;
if (IFX_SystemHandler* pSH = GetSystemHandler())
swClipboard = pSH->GetClipboardText(GetAttachedHWnd());
return !swClipboard.IsEmpty();
}
void CPWL_Edit::CopyText()
{
if (!CanCopy()) return;
CFX_WideString str = m_pEdit->GetSelText();
if (IFX_SystemHandler* pSH = GetSystemHandler())
pSH->SetClipboardText(GetAttachedHWnd(), str);
}
void CPWL_Edit::PasteText()
{
if (!CanPaste()) return;
CFX_WideString swClipboard;
if (IFX_SystemHandler* pSH = GetSystemHandler())
swClipboard = pSH->GetClipboardText(GetAttachedHWnd());
if (m_pFillerNotify)
{
FX_BOOL bRC = TRUE;
FX_BOOL bExit = FALSE;
CFX_WideString strChangeEx;
int nSelStart = 0;
int nSelEnd = 0;
GetSel(nSelStart, nSelEnd);
m_pFillerNotify->OnBeforeKeyStroke(TRUE, GetAttachedData(), 0 , swClipboard, strChangeEx, nSelStart, nSelEnd, TRUE, bRC, bExit, 0);
if (!bRC) return;
if (bExit) return;
}
if (swClipboard.GetLength() > 0)
{
Clear();
InsertText(swClipboard.c_str());
}
if (m_pFillerNotify)
{
FX_BOOL bExit = FALSE;
m_pFillerNotify->OnAfterKeyStroke(TRUE, GetAttachedData(), bExit,0);
if (bExit) return;
}
}
void CPWL_Edit::CutText()
{
if (!CanCut()) return;
CFX_WideString str = m_pEdit->GetSelText();
if (IFX_SystemHandler* pSH = GetSystemHandler())
pSH->SetClipboardText(GetAttachedHWnd(), str);
m_pEdit->Clear();
}
void CPWL_Edit::OnCreated()
{
CPWL_EditCtrl::OnCreated();
if (CPWL_ScrollBar * pScroll = GetVScrollBar())
{
pScroll->RemoveFlag(PWS_AUTOTRANSPARENT);
pScroll->SetTransparency(255);
}
SetParamByFlag();
m_rcOldWindow = GetWindowRect();
m_pEdit->SetOprNotify(this);
m_pEdit->EnableOprNotify(TRUE);
}
void CPWL_Edit::SetParamByFlag()
{
if (HasFlag(PES_RIGHT))
{
m_pEdit->SetAlignmentH(2, FALSE);
}
else if (HasFlag(PES_MIDDLE))
{
m_pEdit->SetAlignmentH(1, FALSE);
}
else
{
m_pEdit->SetAlignmentH(0, FALSE);
}
if (HasFlag(PES_BOTTOM))
{
m_pEdit->SetAlignmentV(2, FALSE);
}
else if (HasFlag(PES_CENTER))
{
m_pEdit->SetAlignmentV(1, FALSE);
}
else
{
m_pEdit->SetAlignmentV(0, FALSE);
}
if (HasFlag(PES_PASSWORD))
{
m_pEdit->SetPasswordChar('*', FALSE);
}
m_pEdit->SetMultiLine(HasFlag(PES_MULTILINE), FALSE);
m_pEdit->SetAutoReturn(HasFlag(PES_AUTORETURN), FALSE);
m_pEdit->SetAutoFontSize(HasFlag(PWS_AUTOFONTSIZE), FALSE);
m_pEdit->SetAutoScroll(HasFlag(PES_AUTOSCROLL), FALSE);
m_pEdit->EnableUndo(HasFlag(PES_UNDO));
if (HasFlag(PES_TEXTOVERFLOW))
{
SetClipRect(CPDF_Rect(0.0f,0.0f,0.0f,0.0f));
m_pEdit->SetTextOverflow(TRUE, FALSE);
}
else
{
if (m_pEditCaret)
{
m_pEditCaret->SetClipRect(CPWL_Utils::InflateRect(GetClientRect(),1.0f)); //+1 for caret beside border
}
}
if (HasFlag(PES_SPELLCHECK))
{
m_pSpellCheck = GetCreationParam().pSpellCheck;
}
}
void CPWL_Edit::GetThisAppearanceStream(CFX_ByteTextBuf & sAppStream)
{
CPWL_Wnd::GetThisAppearanceStream(sAppStream);
CPDF_Rect rcClient = GetClientRect();
CFX_ByteTextBuf sLine;
int32_t nCharArray = m_pEdit->GetCharArray();
if (nCharArray > 0)
{
switch (GetBorderStyle())
{
case PBS_SOLID:
{
sLine << "q\n" << GetBorderWidth() << " w\n"
<< CPWL_Utils::GetColorAppStream(GetBorderColor(),FALSE) << " 2 J 0 j\n";
for (int32_t i=1;i<nCharArray;i++)
{
sLine << rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*i << " "
<< rcClient.bottom << " m\n"
<< rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*i << " "
<< rcClient.top << " l S\n";
}
sLine << "Q\n";
}
break;
case PBS_DASH:
{
sLine << "q\n" << GetBorderWidth() << " w\n"
<< CPWL_Utils::GetColorAppStream(GetBorderColor(),FALSE) << " 2 J 0 j\n"
<< "[" << GetBorderDash().nDash << " "
<< GetBorderDash().nGap << "] "
<< GetBorderDash().nPhase << " d\n";
for (int32_t i=1;i<nCharArray;i++)
{
sLine << rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*i << " "
<< rcClient.bottom << " m\n"
<< rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*i << " "
<< rcClient.top << " l S\n";
}
sLine << "Q\n";
}
break;
}
}
sAppStream << sLine;
CFX_ByteTextBuf sText;
CPDF_Point ptOffset = CPDF_Point(0.0f,0.0f);
CPVT_WordRange wrWhole = m_pEdit->GetWholeWordRange();
CPVT_WordRange wrSelect = GetSelectWordRange();
CPVT_WordRange wrVisible = (HasFlag(PES_TEXTOVERFLOW) ? wrWhole : m_pEdit->GetVisibleWordRange());
CPVT_WordRange wrSelBefore(wrWhole.BeginPos,wrSelect.BeginPos);
CPVT_WordRange wrSelAfter(wrSelect.EndPos,wrWhole.EndPos);
CPVT_WordRange wrTemp = CPWL_Utils::OverlapWordRange(GetSelectWordRange(),wrVisible);
CFX_ByteString sEditSel = CPWL_Utils::GetEditSelAppStream(m_pEdit, ptOffset,
&wrTemp);
if (sEditSel.GetLength() > 0)
sText << CPWL_Utils::GetColorAppStream(PWL_DEFAULT_SELBACKCOLOR) << sEditSel ;
wrTemp = CPWL_Utils::OverlapWordRange(wrVisible,wrSelBefore);
CFX_ByteString sEditBefore = CPWL_Utils::GetEditAppStream(m_pEdit, ptOffset,
&wrTemp, !HasFlag(PES_CHARARRAY), m_pEdit->GetPasswordChar());
if (sEditBefore.GetLength() > 0)
sText << "BT\n" << CPWL_Utils::GetColorAppStream(GetTextColor()) << sEditBefore << "ET\n";
wrTemp = CPWL_Utils::OverlapWordRange(wrVisible,wrSelect);
CFX_ByteString sEditMid = CPWL_Utils::GetEditAppStream(m_pEdit, ptOffset,
&wrTemp, !HasFlag(PES_CHARARRAY), m_pEdit->GetPasswordChar());
if (sEditMid.GetLength() > 0)
sText << "BT\n" << CPWL_Utils::GetColorAppStream(CPWL_Color(COLORTYPE_GRAY,1)) << sEditMid << "ET\n";
wrTemp = CPWL_Utils::OverlapWordRange(wrVisible,wrSelAfter);
CFX_ByteString sEditAfter = CPWL_Utils::GetEditAppStream(m_pEdit, ptOffset,
&wrTemp, !HasFlag(PES_CHARARRAY), m_pEdit->GetPasswordChar());
if (sEditAfter.GetLength() > 0)
sText << "BT\n" << CPWL_Utils::GetColorAppStream(GetTextColor()) << sEditAfter<< "ET\n";
if (HasFlag(PES_SPELLCHECK))
{
CFX_ByteString sSpellCheck = CPWL_Utils::GetSpellCheckAppStream(m_pEdit, m_pSpellCheck, ptOffset, &wrVisible);
if (sSpellCheck.GetLength() > 0)
sText << CPWL_Utils::GetColorAppStream(CPWL_Color(COLORTYPE_RGB,1,0,0),FALSE) << sSpellCheck;
}
if (sText.GetLength() > 0)
{
CPDF_Rect rcClient = GetClientRect();
sAppStream << "q\n/Tx BMC\n";
if (!HasFlag(PES_TEXTOVERFLOW))
sAppStream << rcClient.left << " " << rcClient.bottom << " "
<< rcClient.right - rcClient.left << " " << rcClient.top - rcClient.bottom << " re W n\n";
sAppStream << sText;
sAppStream << "EMC\nQ\n";
}
}
void CPWL_Edit::DrawThisAppearance(CFX_RenderDevice* pDevice, CPDF_Matrix* pUser2Device)
{
CPWL_Wnd::DrawThisAppearance(pDevice,pUser2Device);
CPDF_Rect rcClient = GetClientRect();
CFX_ByteTextBuf sLine;
int32_t nCharArray = m_pEdit->GetCharArray();
FX_SAFE_INT32 nCharArraySafe = nCharArray;
nCharArraySafe -= 1;
nCharArraySafe *= 2;
if (nCharArray > 0 && nCharArraySafe.IsValid())
{
switch (GetBorderStyle())
{
case PBS_SOLID:
{
CFX_GraphStateData gsd;
gsd.m_LineWidth = (FX_FLOAT)GetBorderWidth();
CFX_PathData path;
path.SetPointCount(nCharArraySafe.ValueOrDie());
for (int32_t i=0; i<nCharArray-1; i++)
{
path.SetPoint(i*2, rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*(i+1),
rcClient.bottom, FXPT_MOVETO);
path.SetPoint(i*2+1, rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*(i+1),
rcClient.top, FXPT_LINETO);
}
if (path.GetPointCount() > 0)
pDevice->DrawPath(&path, pUser2Device, &gsd,0,
CPWL_Utils::PWLColorToFXColor(GetBorderColor(),255), FXFILL_ALTERNATE);
}
break;
case PBS_DASH:
{
CFX_GraphStateData gsd;
gsd.m_LineWidth = (FX_FLOAT)GetBorderWidth();
gsd.SetDashCount(2);
gsd.m_DashArray[0] = (FX_FLOAT)GetBorderDash().nDash;
gsd.m_DashArray[1] = (FX_FLOAT)GetBorderDash().nGap;
gsd.m_DashPhase = (FX_FLOAT)GetBorderDash().nPhase;
CFX_PathData path;
path.SetPointCount(nCharArraySafe.ValueOrDie());
for (int32_t i=0; i<nCharArray-1; i++)
{
path.SetPoint(i*2, rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*(i+1),
rcClient.bottom, FXPT_MOVETO);
path.SetPoint(i*2+1, rcClient.left + ((rcClient.right - rcClient.left)/nCharArray)*(i+1),
rcClient.top, FXPT_LINETO);
}
if (path.GetPointCount() > 0)
pDevice->DrawPath(&path, pUser2Device, &gsd,0,
CPWL_Utils::PWLColorToFXColor(GetBorderColor(),255), FXFILL_ALTERNATE);
}
break;
}
}
CPDF_Rect rcClip;
CPVT_WordRange wrRange = m_pEdit->GetVisibleWordRange();
CPVT_WordRange* pRange = NULL;
if (!HasFlag(PES_TEXTOVERFLOW))
{
rcClip = GetClientRect();
pRange = &wrRange;
}
IFX_SystemHandler* pSysHandler = GetSystemHandler();
IFX_Edit::DrawEdit(pDevice,pUser2Device,m_pEdit,
CPWL_Utils::PWLColorToFXColor(GetTextColor(), GetTransparency()),
CPWL_Utils::PWLColorToFXColor(GetTextStrokeColor(), GetTransparency()),
rcClip,CPDF_Point(0.0f,0.0f),pRange, pSysHandler, m_pFormFiller);
if (HasFlag(PES_SPELLCHECK))
{
CPWL_Utils::DrawEditSpellCheck(pDevice,pUser2Device,m_pEdit,rcClip,
CPDF_Point(0.0f,0.0f),pRange, GetCreationParam().pSpellCheck);
}
}
FX_BOOL CPWL_Edit::OnLButtonDown(const CPDF_Point & point, FX_DWORD nFlag)
{
CPWL_Wnd::OnLButtonDown(point,nFlag);
if (HasFlag(PES_TEXTOVERFLOW) || ClientHitTest(point))
{
if (m_bMouseDown)
InvalidateRect();
m_bMouseDown = TRUE;
SetCapture();
m_pEdit->OnMouseDown(point,IsSHIFTpressed(nFlag),IsCTRLpressed(nFlag));
}
return TRUE;
}
FX_BOOL CPWL_Edit::OnLButtonDblClk(const CPDF_Point & point, FX_DWORD nFlag)
{
CPWL_Wnd::OnLButtonDblClk(point, nFlag);
if (HasFlag(PES_TEXTOVERFLOW) || ClientHitTest(point))
{
m_pEdit->SelectAll();
}
return TRUE;
}
#define WM_PWLEDIT_UNDO 0x01
#define WM_PWLEDIT_REDO 0x02
#define WM_PWLEDIT_CUT 0x03
#define WM_PWLEDIT_COPY 0x04
#define WM_PWLEDIT_PASTE 0x05
#define WM_PWLEDIT_DELETE 0x06
#define WM_PWLEDIT_SELECTALL 0x07
#define WM_PWLEDIT_SUGGEST 0x08
FX_BOOL CPWL_Edit::OnRButtonUp(const CPDF_Point & point, FX_DWORD nFlag)
{
if (m_bMouseDown) return FALSE;
CPWL_Wnd::OnRButtonUp(point, nFlag);
if (!HasFlag(PES_TEXTOVERFLOW) && !ClientHitTest(point)) return TRUE;
IFX_SystemHandler* pSH = GetSystemHandler();
if (!pSH) return FALSE;
SetFocus();
CPVT_WordRange wrLatin = GetLatinWordsRange(point);
CFX_WideString swLatin = m_pEdit->GetRangeText(wrLatin);
FX_HMENU hPopup = pSH->CreatePopupMenu();
if (!hPopup) return FALSE;
CFX_ByteStringArray sSuggestWords;
CPDF_Point ptPopup = point;
if (!IsReadOnly())
{
if (HasFlag(PES_SPELLCHECK) && !swLatin.IsEmpty())
{
if (m_pSpellCheck)
{
CFX_ByteString sLatin = CFX_ByteString::FromUnicode(swLatin);
if (!m_pSpellCheck->CheckWord(sLatin))
{
m_pSpellCheck->SuggestWords(sLatin,sSuggestWords);
int32_t nSuggest = sSuggestWords.GetSize();
for (int32_t nWord=0; nWord<nSuggest; nWord++)
{
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_SUGGEST+nWord, sSuggestWords[nWord].UTF8Decode());
}
if (nSuggest > 0)
pSH->AppendMenuItem(hPopup, 0, L"");
ptPopup = GetWordRightBottomPoint(wrLatin.EndPos);
}
}
}
}
IPWL_Provider* pProvider = GetProvider();
if (HasFlag(PES_UNDO))
{
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_UNDO,
pProvider ? pProvider->LoadPopupMenuString(0) : L"&Undo");
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_REDO,
pProvider ? pProvider->LoadPopupMenuString(1) : L"&Redo");
pSH->AppendMenuItem(hPopup, 0, L"");
if (!m_pEdit->CanUndo())
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_UNDO, FALSE);
if (!m_pEdit->CanRedo())
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_REDO, FALSE);
}
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_CUT,
pProvider ? pProvider->LoadPopupMenuString(2) : L"Cu&t");
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_COPY,
pProvider ? pProvider->LoadPopupMenuString(3) : L"&Copy");
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_PASTE,
pProvider ? pProvider->LoadPopupMenuString(4) : L"&Paste");
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_DELETE,
pProvider ? pProvider->LoadPopupMenuString(5) : L"&Delete");
CFX_WideString swText = pSH->GetClipboardText(GetAttachedHWnd());
if (swText.IsEmpty())
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_PASTE, FALSE);
if (!m_pEdit->IsSelected())
{
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_CUT, FALSE);
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_COPY, FALSE);
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_DELETE, FALSE);
}
if (IsReadOnly())
{
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_CUT, FALSE);
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_DELETE, FALSE);
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_PASTE, FALSE);
}
if (HasFlag(PES_PASSWORD))
{
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_CUT, FALSE);
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_COPY, FALSE);
}
if (HasFlag(PES_NOREAD))
{
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_CUT, FALSE);
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_COPY, FALSE);
}
pSH->AppendMenuItem(hPopup, 0, L"");
pSH->AppendMenuItem(hPopup, WM_PWLEDIT_SELECTALL,
pProvider ? pProvider->LoadPopupMenuString(6) : L"&Select All");
if (m_pEdit->GetTotalWords() == 0)
{
pSH->EnableMenuItem(hPopup, WM_PWLEDIT_SELECTALL, FALSE);
}
int32_t x, y;
PWLtoWnd(ptPopup, x, y);
pSH->ClientToScreen(GetAttachedHWnd(), x, y);
pSH->SetCursor(FXCT_ARROW);
int32_t nCmd = pSH->TrackPopupMenu(hPopup,
x,
y,
GetAttachedHWnd());
switch (nCmd)
{
case WM_PWLEDIT_UNDO:
Undo();
break;
case WM_PWLEDIT_REDO:
Redo();
break;
case WM_PWLEDIT_CUT:
CutText();
break;
case WM_PWLEDIT_COPY:
CopyText();
break;
case WM_PWLEDIT_PASTE:
PasteText();
break;
case WM_PWLEDIT_DELETE:
Clear();
break;
case WM_PWLEDIT_SELECTALL:
SelectAll();
break;
case WM_PWLEDIT_SUGGEST + 0:
SetSel(m_pEdit->WordPlaceToWordIndex(wrLatin.BeginPos),m_pEdit->WordPlaceToWordIndex(wrLatin.EndPos));
ReplaceSel(sSuggestWords[0].UTF8Decode().c_str());
break;
case WM_PWLEDIT_SUGGEST + 1:
SetSel(m_pEdit->WordPlaceToWordIndex(wrLatin.BeginPos),m_pEdit->WordPlaceToWordIndex(wrLatin.EndPos));
ReplaceSel(sSuggestWords[1].UTF8Decode().c_str());
break;
case WM_PWLEDIT_SUGGEST + 2:
SetSel(m_pEdit->WordPlaceToWordIndex(wrLatin.BeginPos),m_pEdit->WordPlaceToWordIndex(wrLatin.EndPos));
ReplaceSel(sSuggestWords[2].UTF8Decode().c_str());
break;
case WM_PWLEDIT_SUGGEST + 3:
SetSel(m_pEdit->WordPlaceToWordIndex(wrLatin.BeginPos),m_pEdit->WordPlaceToWordIndex(wrLatin.EndPos));
ReplaceSel(sSuggestWords[3].UTF8Decode().c_str());
break;
case WM_PWLEDIT_SUGGEST + 4:
SetSel(m_pEdit->WordPlaceToWordIndex(wrLatin.BeginPos),m_pEdit->WordPlaceToWordIndex(wrLatin.EndPos));
ReplaceSel(sSuggestWords[4].UTF8Decode().c_str());
break;
default:
break;
}
pSH->DestroyMenu(hPopup);
return TRUE;
}
void CPWL_Edit::OnSetFocus()
{
SetEditCaret(TRUE);
if (!IsReadOnly())
{
if (IPWL_FocusHandler* pFocusHandler = GetFocusHandler())
pFocusHandler->OnSetFocus(this);
}
m_bFocus = TRUE;
}
void CPWL_Edit::OnKillFocus()
{
ShowVScrollBar(FALSE);
m_pEdit->SelectNone();
SetCaret(FALSE, CPDF_Point(0.0f,0.0f), CPDF_Point(0.0f,0.0f));
SetCharSet(0);
if (!IsReadOnly())
{
if (IPWL_FocusHandler* pFocusHandler = GetFocusHandler())
pFocusHandler->OnKillFocus(this);
}
m_bFocus = FALSE;
}
void CPWL_Edit::SetHorzScale(int32_t nHorzScale, FX_BOOL bPaint/* = TRUE*/)
{
m_pEdit->SetHorzScale(nHorzScale, bPaint);
}
void CPWL_Edit::SetCharSpace(FX_FLOAT fCharSpace, FX_BOOL bPaint/* = TRUE*/)
{
m_pEdit->SetCharSpace(fCharSpace, bPaint);
}
void CPWL_Edit::SetLineLeading(FX_FLOAT fLineLeading, FX_BOOL bPaint/* = TRUE*/)
{
m_pEdit->SetLineLeading(fLineLeading, bPaint);
}
CFX_ByteString CPWL_Edit::GetSelectAppearanceStream(const CPDF_Point & ptOffset) const
{
CPVT_WordRange wr = GetSelectWordRange();
return CPWL_Utils::GetEditSelAppStream(m_pEdit,ptOffset,&wr);
}
CPVT_WordRange CPWL_Edit::GetSelectWordRange() const
{
if (m_pEdit->IsSelected())
{
int32_t nStart = -1;
int32_t nEnd = -1;
m_pEdit->GetSel(nStart, nEnd);
CPVT_WordPlace wpStart = m_pEdit->WordIndexToWordPlace(nStart);
CPVT_WordPlace wpEnd = m_pEdit->WordIndexToWordPlace(nEnd);
return CPVT_WordRange(wpStart,wpEnd);
}
return CPVT_WordRange();
}
CFX_ByteString CPWL_Edit::GetTextAppearanceStream(const CPDF_Point & ptOffset) const
{
CFX_ByteTextBuf sRet;
CFX_ByteString sEdit = CPWL_Utils::GetEditAppStream(m_pEdit,ptOffset);
if (sEdit.GetLength() > 0)
{
sRet << "BT\n" << CPWL_Utils::GetColorAppStream(GetTextColor()) << sEdit << "ET\n";
}
return sRet.GetByteString();
}
CFX_ByteString CPWL_Edit::GetCaretAppearanceStream(const CPDF_Point & ptOffset) const
{
if (m_pEditCaret)
return m_pEditCaret->GetCaretAppearanceStream(ptOffset);
return CFX_ByteString();
}
CPDF_Point CPWL_Edit::GetWordRightBottomPoint(const CPVT_WordPlace& wpWord)
{
CPDF_Point pt(0.0f, 0.0f);
if (IFX_Edit_Iterator * pIterator = m_pEdit->GetIterator())
{
CPVT_WordPlace wpOld = pIterator->GetAt();
pIterator->SetAt(wpWord);
CPVT_Word word;
if (pIterator->GetWord(word))
{
pt = CPDF_Point(word.ptWord.x + word.fWidth, word.ptWord.y + word.fDescent);
}
pIterator->SetAt(wpOld);
}
return pt;
}
FX_BOOL CPWL_Edit::IsTextFull() const
{
return m_pEdit->IsTextFull();
}
FX_FLOAT CPWL_Edit::GetCharArrayAutoFontSize(CPDF_Font* pFont, const CPDF_Rect& rcPlate, int32_t nCharArray)
{
if (pFont && !pFont->IsStandardFont())
{
FX_RECT rcBBox;
pFont->GetFontBBox(rcBBox);
CPDF_Rect rcCell = rcPlate;
FX_FLOAT xdiv = rcCell.Width() / nCharArray * 1000.0f / rcBBox.Width();
FX_FLOAT ydiv = - rcCell.Height() * 1000.0f / rcBBox.Height();
return xdiv < ydiv ? xdiv : ydiv;
}
return 0.0f;
}
void CPWL_Edit::SetCharArray(int32_t nCharArray)
{
if (HasFlag(PES_CHARARRAY) && nCharArray > 0)
{
m_pEdit->SetCharArray(nCharArray);
m_pEdit->SetTextOverflow(TRUE);
if (HasFlag(PWS_AUTOFONTSIZE))
{
if (IFX_Edit_FontMap* pFontMap = GetFontMap())
{
FX_FLOAT fFontSize = GetCharArrayAutoFontSize(pFontMap->GetPDFFont(0), GetClientRect(), nCharArray);
if (fFontSize > 0.0f)
{
m_pEdit->SetAutoFontSize(FALSE);
m_pEdit->SetFontSize(fFontSize);
}
}
}
}
}
void CPWL_Edit::SetLimitChar(int32_t nLimitChar)
{
m_pEdit->SetLimitChar(nLimitChar);
}
void CPWL_Edit::ReplaceSel(const FX_WCHAR* csText)
{
m_pEdit->Clear();
m_pEdit->InsertText(csText);
}
CPDF_Rect CPWL_Edit::GetFocusRect() const
{
return CPDF_Rect();
}
void CPWL_Edit::ShowVScrollBar(FX_BOOL bShow)
{
if (CPWL_ScrollBar * pScroll = GetVScrollBar())
{
if (bShow)
{
if (!pScroll->IsVisible())
{
pScroll->SetVisible(TRUE);
CPDF_Rect rcWindow = GetWindowRect();
m_rcOldWindow = rcWindow;
rcWindow.right += PWL_SCROLLBAR_WIDTH;
Move(rcWindow, TRUE, TRUE);
}
}
else
{
if (pScroll->IsVisible())
{
pScroll->SetVisible(FALSE);
Move(m_rcOldWindow, TRUE, TRUE);
}
}
}
}
FX_BOOL CPWL_Edit::IsVScrollBarVisible() const
{
if (CPWL_ScrollBar * pScroll = GetVScrollBar())
{
return pScroll->IsVisible();
}
return FALSE;
}
void CPWL_Edit::EnableSpellCheck(FX_BOOL bEnabled)
{
if (bEnabled)
AddFlag(PES_SPELLCHECK);
else
RemoveFlag(PES_SPELLCHECK);
}
FX_BOOL CPWL_Edit::OnKeyDown(FX_WORD nChar, FX_DWORD nFlag)
{
if (m_bMouseDown) return TRUE;
if (nChar == FWL_VKEY_Delete)
{
if (m_pFillerNotify)
{
FX_BOOL bRC = TRUE;
FX_BOOL bExit = FALSE;
CFX_WideString strChange;
CFX_WideString strChangeEx;
int nSelStart = 0;
int nSelEnd = 0;
GetSel(nSelStart, nSelEnd);
if (nSelStart == nSelEnd)
nSelEnd = nSelStart + 1;
m_pFillerNotify->OnBeforeKeyStroke(TRUE, GetAttachedData(), FWL_VKEY_Delete, strChange, strChangeEx, nSelStart, nSelEnd, TRUE, bRC, bExit, nFlag);
if (!bRC) return FALSE;
if (bExit) return FALSE;
}
}
FX_BOOL bRet = CPWL_EditCtrl::OnKeyDown(nChar, nFlag);
if (nChar == FWL_VKEY_Delete)
{
if (m_pFillerNotify)
{
FX_BOOL bExit = FALSE;
m_pFillerNotify->OnAfterKeyStroke(TRUE, GetAttachedData(), bExit,nFlag);
if (bExit) return FALSE;
}
}
//In case of implementation swallow the OnKeyDown event.
if(IsProceedtoOnChar(nChar, nFlag))
return TRUE;
return bRet;
}
/**
*In case of implementation swallow the OnKeyDown event.
*If the event is swallowed, implementation may do other unexpected things, which is not the control means to do.
*/
FX_BOOL CPWL_Edit::IsProceedtoOnChar(FX_WORD nKeyCode, FX_DWORD nFlag)
{
FX_BOOL bCtrl = IsCTRLpressed(nFlag);
FX_BOOL bAlt = IsALTpressed(nFlag);
if(bCtrl && !bAlt)
{
//hot keys for edit control.
switch(nKeyCode)
{
case 'C':
case 'V':
case 'X':
case 'A':
case 'Z':
return TRUE;
default:
break;
}
}
//control characters.
switch(nKeyCode)
{
case FWL_VKEY_Escape:
case FWL_VKEY_Back:
case FWL_VKEY_Return:
case FWL_VKEY_Space:
return TRUE;
default:
break;
}
return FALSE;
}
FX_BOOL CPWL_Edit::OnChar(FX_WORD nChar, FX_DWORD nFlag)
{
if (m_bMouseDown) return TRUE;
FX_BOOL bRC = TRUE;
FX_BOOL bExit = FALSE;
FX_BOOL bCtrl = IsCTRLpressed(nFlag);
if (!bCtrl)
{
if (m_pFillerNotify)
{
CFX_WideString swChange;
int32_t nKeyCode;
int nSelStart = 0;
int nSelEnd = 0;
GetSel(nSelStart, nSelEnd);
switch (nChar)
{
case FWL_VKEY_Back:
nKeyCode = nChar;
if (nSelStart == nSelEnd)
nSelStart = nSelEnd - 1;
break;
case FWL_VKEY_Return:
nKeyCode = nChar;
break;
default:
nKeyCode = 0;
swChange += nChar;
break;
}
CFX_WideString strChangeEx;
m_pFillerNotify->OnBeforeKeyStroke(TRUE, GetAttachedData(), nKeyCode, swChange, strChangeEx, nSelStart, nSelEnd, TRUE, bRC, bExit, nFlag);
}
}
if (!bRC) return TRUE;
if (bExit) return FALSE;
if (IFX_Edit_FontMap * pFontMap = GetFontMap())
{
int32_t nOldCharSet = GetCharSet();
int32_t nNewCharSet = pFontMap->CharSetFromUnicode(nChar, DEFAULT_CHARSET);
if(nOldCharSet != nNewCharSet)
{
SetCharSet(nNewCharSet);
}
}
FX_BOOL bRet = CPWL_EditCtrl::OnChar(nChar,nFlag);
if (!bCtrl)
{
if (m_pFillerNotify)
{
m_pFillerNotify->OnAfterKeyStroke(TRUE, GetAttachedData(), bExit,nFlag);
if (bExit) return FALSE;
}
}
return bRet;
}
FX_BOOL CPWL_Edit::OnMouseWheel(short zDelta, const CPDF_Point & point, FX_DWORD nFlag)
{
if (HasFlag(PES_MULTILINE))
{
CPDF_Point ptScroll = GetScrollPos();
if (zDelta > 0)
{
ptScroll.y += GetFontSize();
}
else
{
ptScroll.y -= GetFontSize();
}
SetScrollPos(ptScroll);
return TRUE;
}
return FALSE;
}
void CPWL_Edit::OnInsertReturn(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
if (HasFlag(PES_SPELLCHECK))
{
m_pEdit->RefreshWordRange(CombineWordRange(GetLatinWordsRange(oldplace),GetLatinWordsRange(place)));
}
if (m_pEditNotify)
{
m_pEditNotify->OnInsertReturn(place, oldplace);
}
}
void CPWL_Edit::OnBackSpace(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
if (HasFlag(PES_SPELLCHECK))
{
m_pEdit->RefreshWordRange(CombineWordRange(GetLatinWordsRange(oldplace),GetLatinWordsRange(place)));
}
if (m_pEditNotify)
{
m_pEditNotify->OnBackSpace(place, oldplace);
}
}
void CPWL_Edit::OnDelete(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
if (HasFlag(PES_SPELLCHECK))
{
m_pEdit->RefreshWordRange(CombineWordRange(GetLatinWordsRange(oldplace),GetLatinWordsRange(place)));
}
if (m_pEditNotify)
{
m_pEditNotify->OnDelete(place, oldplace);
}
}
void CPWL_Edit::OnClear(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
if (HasFlag(PES_SPELLCHECK))
{
m_pEdit->RefreshWordRange(CombineWordRange(GetLatinWordsRange(oldplace),GetLatinWordsRange(place)));
}
if (m_pEditNotify)
{
m_pEditNotify->OnClear(place, oldplace);
}
}
void CPWL_Edit::OnInsertWord(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
if (HasFlag(PES_SPELLCHECK))
{
m_pEdit->RefreshWordRange(CombineWordRange(GetLatinWordsRange(oldplace),GetLatinWordsRange(place)));
}
if (m_pEditNotify)
{
m_pEditNotify->OnInsertWord(place, oldplace);
}
}
void CPWL_Edit::OnSetText(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
}
void CPWL_Edit::OnInsertText(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace)
{
if (HasFlag(PES_SPELLCHECK))
{
m_pEdit->RefreshWordRange(CombineWordRange(GetLatinWordsRange(oldplace),GetLatinWordsRange(place)));
}
if (m_pEditNotify)
{
m_pEditNotify->OnInsertText(place, oldplace);
}
}
void CPWL_Edit::OnAddUndo(IFX_Edit_UndoItem* pUndoItem)
{
if (m_pEditNotify)
{
m_pEditNotify->OnAddUndo(this);
}
}
CPVT_WordRange CPWL_Edit::CombineWordRange(const CPVT_WordRange& wr1, const CPVT_WordRange& wr2)
{
CPVT_WordRange wrRet;
if (wr1.BeginPos.WordCmp(wr2.BeginPos) < 0)
{
wrRet.BeginPos = wr1.BeginPos;
}
else
{
wrRet.BeginPos = wr2.BeginPos;
}
if (wr1.EndPos.WordCmp(wr2.EndPos) < 0)
{
wrRet.EndPos = wr2.EndPos;
}
else
{
wrRet.EndPos = wr1.EndPos;
}
return wrRet;
}
CPVT_WordRange CPWL_Edit::GetLatinWordsRange(const CPDF_Point& point) const
{
return GetSameWordsRange(m_pEdit->SearchWordPlace(point), TRUE, FALSE);
}
CPVT_WordRange CPWL_Edit::GetLatinWordsRange(const CPVT_WordPlace & place) const
{
return GetSameWordsRange(place, TRUE, FALSE);
}
CPVT_WordRange CPWL_Edit::GetArabicWordsRange(const CPVT_WordPlace & place) const
{
return GetSameWordsRange(place, FALSE, TRUE);
}
#define PWL_ISARABICWORD(word) ((word >= 0x0600 && word <= 0x06FF) || (word >= 0xFB50 && word <= 0xFEFC))
CPVT_WordRange CPWL_Edit::GetSameWordsRange(const CPVT_WordPlace & place, FX_BOOL bLatin, FX_BOOL bArabic) const
{
CPVT_WordRange range;
if (IFX_Edit_Iterator* pIterator = m_pEdit->GetIterator())
{
CPVT_Word wordinfo;
CPVT_WordPlace wpStart(place),wpEnd(place);
pIterator->SetAt(place);
if (bLatin)
{
while (pIterator->NextWord())
{
if (pIterator->GetWord(wordinfo) && FX_EDIT_ISLATINWORD(wordinfo.Word))
{
wpEnd = pIterator->GetAt();
continue;
}
else
break;
};
}
else if (bArabic)
{
while (pIterator->NextWord())
{
if (pIterator->GetWord(wordinfo) && PWL_ISARABICWORD(wordinfo.Word))
{
wpEnd = pIterator->GetAt();
continue;
}
else
break;
};
}
pIterator->SetAt(place);
if (bLatin)
{
do
{
if (pIterator->GetWord(wordinfo) && FX_EDIT_ISLATINWORD(wordinfo.Word))
{
continue;
}
else
{
wpStart = pIterator->GetAt();
break;
}
}
while (pIterator->PrevWord());
}
else if (bArabic)
{
do
{
if (pIterator->GetWord(wordinfo) && PWL_ISARABICWORD(wordinfo.Word))
{
continue;
}
else
{
wpStart = pIterator->GetAt();
break;
}
}
while (pIterator->PrevWord());
}
range.Set(wpStart,wpEnd);
}
return range;
}
void CPWL_Edit::AjustArabicWords(const CPVT_WordRange& wr)
{
}
void CPWL_Edit::GeneratePageObjects(CPDF_PageObjects* pPageObjects,
const CPDF_Point& ptOffset, CFX_ArrayTemplate<CPDF_TextObject*>& ObjArray)
{
IFX_Edit::GeneratePageObjects(pPageObjects, m_pEdit, ptOffset, NULL, CPWL_Utils::PWLColorToFXColor(GetTextColor(),GetTransparency()), ObjArray);
}
void CPWL_Edit::GeneratePageObjects(CPDF_PageObjects* pPageObjects,
const CPDF_Point& ptOffset)
{
CFX_ArrayTemplate<CPDF_TextObject*> ObjArray;
IFX_Edit::GeneratePageObjects(pPageObjects, m_pEdit, ptOffset, NULL, CPWL_Utils::PWLColorToFXColor(GetTextColor(),GetTransparency()), ObjArray);
}
| 23.739757 | 149 | 0.704561 | chenjian-rits |
58d8f647e41f93976a4ff62938e18e0ab2c85b31 | 1,711 | hh | C++ | src/mmutil_python_index.hh | YPARK/mmutil | 21729fc50ac4cefff58c1b71e8c5740d2045b111 | [
"MIT"
] | null | null | null | src/mmutil_python_index.hh | YPARK/mmutil | 21729fc50ac4cefff58c1b71e8c5740d2045b111 | [
"MIT"
] | null | null | null | src/mmutil_python_index.hh | YPARK/mmutil | 21729fc50ac4cefff58c1b71e8c5740d2045b111 | [
"MIT"
] | null | null | null | #include "mmutil.hh"
#include "mmutil_util.hh"
#include "mmutil_index.hh"
#include "utils/bgzstream.hh"
#include "mmutil_python.hh"
#ifndef MMUTIL_PYTHON_INDEX_HH_
#define MMUTIL_PYTHON_INDEX_HH_
const char *_build_index_desc =
"Build an auxiliary column indexing file for fast access for .mtx.gz\n"
"\n"
"[Input]\n"
"\n"
"mtx_file : .mtx.gz file\n"
"idx_file : .mtx.gz.index file (optional)\n"
"\n";
static PyObject *
mmutil_build_index(PyObject *self, PyObject *args, PyObject *keywords)
{
static const char *kwlist[] = { "mtx_file", "idx_file", NULL };
char *mtx_file;
char *_idx_file;
if (!PyArg_ParseTupleAndKeywords(args,
keywords, // keywords
"s|s", // format
const_cast<char **>(kwlist), //
&mtx_file, // .mtx.gz
&_idx_file // .index
)) {
return NULL;
}
if (!file_exists(mtx_file)) {
PyErr_SetString(PyExc_TypeError, ".mtx file does not exist");
return NULL;
}
using namespace mmutil::index;
std::string idx_file;
if (!_idx_file) {
idx_file = std::string(mtx_file) + ".index";
} else {
idx_file = std::string(_idx_file);
}
if (!is_file_bgz(mtx_file)) {
convert_bgzip(mtx_file);
} else {
TLOG("This file is bgzipped: " << mtx_file);
}
Py_CHECK(build_mmutil_index(mtx_file, idx_file));
PyObject *ret = PyDict_New();
return ret;
}
#endif
| 26.323077 | 77 | 0.524255 | YPARK |
58dc9e2f02a5eb6ac3d530df7916882663e0b1e7 | 3,333 | cpp | C++ | def/Seasonal/Animation_Seasonal_Weather.cpp | MikaylaFischler/dorm-leds | d5edd7b1d8ba1bc76e13c2ee37cb4f9b1d272d9b | [
"MIT"
] | 2 | 2018-10-03T05:40:00.000Z | 2018-12-07T00:39:03.000Z | def/Seasonal/Animation_Seasonal_Weather.cpp | MikaylaFischler/dorm-leds | d5edd7b1d8ba1bc76e13c2ee37cb4f9b1d272d9b | [
"MIT"
] | 5 | 2017-09-02T03:57:24.000Z | 2018-01-14T17:52:15.000Z | def/Seasonal/Animation_Seasonal_Weather.cpp | MikaylaFischler/dorm-leds | d5edd7b1d8ba1bc76e13c2ee37cb4f9b1d272d9b | [
"MIT"
] | null | null | null | #include "Animation_Seasonal.hpp"
/* ~~~~~ PRECIPITATION ~~~~~ */
void Animation_Seasonal_Indiv_Weather::precipitation_init(int update_rate) {
Animation_Seasonal_Indiv::init();
this->update_rate = update_rate;
i = 0;
randomized_spacing = false;
left_spacing = 0;
right_spacing = 0;
}
void Animation_Seasonal_Indiv_Weather::precipitation_step(int min_spacing, int max_spacing, long unsigned int color) {
if (!randomized_spacing) {
// randomize spacing
left_spacing = random(min_spacing, max_spacing);
right_spacing = random(min_spacing, max_spacing);
randomized_spacing = true;
}
// precipitation fall
// set each right pixel
for (uint16_t x = WINDOW_BOTTOM_RIGHT; x <= WINDOW_TOP_RIGHT; x++) {
int rel_index = x - WINDOW_BOTTOM_RIGHT;
if (rel_index % right_spacing == (1000 - i) % right_spacing) {
npsm[this->id]->setPixelColor(x, color);
} else {
npsm[this->id]->setPixelColor(x, COLOR_OFF);
}
}
// set each left pixel
for (uint16_t x = WINDOW_TOP_LEFT; x <= WINDOW_BOTTOM_LEFT; x++){
int rel_index = x - WINDOW_TOP_LEFT;
if (rel_index % left_spacing == i % left_spacing) {
npsm[this->id]->setPixelColor(x, color);
} else {
npsm[this->id]->setPixelColor(x, COLOR_OFF);
}
}
npsm[this->id]->show();
if (randomized_spacing) {
i++;
if (i == 800) {
// 40 for a loop one direction, 80 for a full forwards and backwards
i = 0;
randomized_spacing = false;
this->current_exec++;
}
}
}
/* ~~~~~ RAIN ~~~~~ */
/* ~~~ Animation Seasonal Individual Weather: Randomized Window Light Rain */
void Animation_Seasonal_Indiv_Weather_WindowLightRain::init() {
precipitation_init(50);
this->name = F("Light Rain");
}
void Animation_Seasonal_Indiv_Weather_WindowLightRain::step() {
precipitation_step(7, 10, COLOR_RAINY_BLUE);
}
/* ~~~ Animation Seasonal Individual Weather: Randomized Window Rain */
void Animation_Seasonal_Indiv_Weather_WindowRain::init() {
precipitation_init(40);
this->name = F("Rain");
}
void Animation_Seasonal_Indiv_Weather_WindowRain::step() {
precipitation_step(5, 8, COLOR_RAINY_BLUE);
}
/* ~~~ Animation Seasonal Individual Weather: Randomized Heavy Window Rain */
void Animation_Seasonal_Indiv_Weather_WindowHeavyRain::init() {
precipitation_init(40);
this->name = F("Heavy Rain");
}
void Animation_Seasonal_Indiv_Weather_WindowHeavyRain::step() {
precipitation_step(4, 6, COLOR_RAINY_BLUE);
}
/* ~~~~~ SNOW ~~~~~ */
/* ~~~ Animation Seasonal Individual Weather: Randomized Light Snow */
void Animation_Seasonal_Indiv_Weather_WindowLightSnow::init() {
precipitation_init(90);
this->name = F("Light Snow");
}
void Animation_Seasonal_Indiv_Weather_WindowLightSnow::step() {
precipitation_step(7, 10, COLOR_DIM_WHITE);
}
/* ~~~ Animation Seasonal Individual Weather: Randomized Snow */
void Animation_Seasonal_Indiv_Weather_WindowSnow::init() {
precipitation_init(80);
this->name = F("Snow");
}
void Animation_Seasonal_Indiv_Weather_WindowSnow::step() {
precipitation_step(4, 8, COLOR_DIM_WHITE);
}
/* ~~~ Animation Seasonal Individual Weather: Randomized Heavy Snow */
void Animation_Seasonal_Indiv_Weather_WindowHeavySnow::init() {
precipitation_init(60);
this->name = F("Heavy Snow");
}
void Animation_Seasonal_Indiv_Weather_WindowHeavySnow::step() {
precipitation_step(3, 5, COLOR_DIM_WHITE);
}
| 25.837209 | 118 | 0.727573 | MikaylaFischler |
58dd5d4a09ae227d7352ac02427355dc04625df2 | 2,439 | cpp | C++ | Dynamic Programming/221. Maximal Square/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 1 | 2021-11-19T19:58:33.000Z | 2021-11-19T19:58:33.000Z | Dynamic Programming/221. Maximal Square/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | null | null | null | Dynamic Programming/221. Maximal Square/main.cpp | Minecodecraft/LeetCode-Minecode | 185fd6efe88d8ffcad94e581915c41502a0361a0 | [
"MIT"
] | 2 | 2021-11-26T12:47:27.000Z | 2022-01-13T16:14:46.000Z | //
// main.cpp
// 221. Maximal Square
//
// Created by 边俊林 on 2019/8/26.
// Copyright © 2019 Minecode.Link. All rights reserved.
//
/* ------------------------------------------------------ *\
https://leetcode.com/problems/maximal-square/
\* ------------------------------------------------------ */
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/// Solution:
//
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.size() == 0) return 0;
vector<vector<int>> dp (matrix.size(), vector<int> (matrix[0].size(), 0));
vector<vector<int>> top (matrix.size(), vector<int> (matrix[0].size(), 0));
vector<vector<int>> left (matrix.size(), vector<int> (matrix[0].size(), 0));
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (i == 0)
top[i][j] = matrix[i][j] == '1' ? 1 : 0;
else
top[i][j] = matrix[i][j] == '1' ? top[i-1][j]+1 : 0;
if (j == 0)
left[i][j] = matrix[i][j] == '1' ? 1 : 0;
else
left[i][j] = matrix[i][j] == '1' ? left[i][j-1]+1 : 0;
}
}
int maxx = 0;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (matrix[i][j] == '0') continue;
dp[i][j] = 1;
if (i > 0 && j > 0)
dp[i][j] = min(dp[i-1][j-1] + 1, min(left[i][j], top[i][j]));
maxx = max(maxx, dp[i][j]);
}
}
return maxx * maxx;
}
};
int main() {
Solution sol = Solution();
vector<string> strs = {
"10100", "10111", "11111", "10010"
};
// vector<string> strs = {"0"};
// vector<string> strs = {
// "0001",
// "1101",
// "1111",
// "0111",
// "0111"
// };
vector<vector<char>> matrix (strs.size());
for (int i = 0; i < strs.size(); ++i) {
for (int j = 0; j < strs[i].length(); ++j) {
matrix[i].push_back(strs[i][j]);
}
}
int res = sol.maximalSquare(matrix);
cout << res << endl;
return 0;
}
| 27.715909 | 84 | 0.430914 | Minecodecraft |
58ddff17a3b61750e7e6cdf7a6fe63d82c45eea8 | 1,721 | cpp | C++ | tests/pipeline_compiler/Test_ComputeLocalSize1.cpp | ayberkgerey5/FrameGraphx | cefc587529305ffdba35a4faa06a9e7c10accbe2 | [
"BSD-2-Clause"
] | 362 | 2018-10-14T04:03:50.000Z | 2022-03-26T23:45:06.000Z | tests/pipeline_compiler/Test_ComputeLocalSize1.cpp | loopunit/FrameGraph | 1359143284a135542ace8b851db78521f2800cc3 | [
"BSD-2-Clause"
] | 18 | 2019-05-25T13:43:53.000Z | 2021-03-22T18:12:18.000Z | tests/pipeline_compiler/Test_ComputeLocalSize1.cpp | loopunit/FrameGraph | 1359143284a135542ace8b851db78521f2800cc3 | [
"BSD-2-Clause"
] | 39 | 2019-03-04T05:47:11.000Z | 2022-02-04T14:32:39.000Z | // Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE'
#include "Utils.h"
extern void Test_ComputeLocalSize1 (VPipelineCompiler* compiler)
{
ComputePipelineDesc ppln;
ppln.AddShader( EShaderLangFormat::GLSL_450, "main", R"#(
#pragma shader_stage(compute)
#extension GL_ARB_separate_shader_objects : enable
layout (constant_id = 2) const float SCALE = 0.5f;
layout (local_size_x=8, local_size_y=8, local_size_z=1) in;
layout (local_size_x_id = 0, local_size_y_id = 1) in;
layout(binding=0, rgba8) writeonly uniform image2D un_OutImage;
layout(binding=1, std140) readonly buffer un_SSBO
{
vec4 ssb_data;
};
const float uv_scale = 0.1f;
void main ()
{
vec2 uv = vec2(gl_GlobalInvocationID.xy) / vec2((gl_WorkGroupSize * gl_NumWorkGroups).xy) * (uv_scale + SCALE);
vec4 fragColor = vec4(sin(uv.x), cos(uv.y), 1.0, ssb_data.r);
imageStore( un_OutImage, ivec2(gl_GlobalInvocationID.xy), fragColor );
}
)#" );
TEST( compiler->Compile( INOUT ppln, EShaderLangFormat::SPIRV_100 ));
auto ds = FindDescriptorSet( ppln, DescriptorSetID("0") );
TEST( ds );
TEST( TestImageUniform( *ds, UniformID("un_OutImage"), EImageSampler::Float2D | EImageSampler(EPixelFormat::RGBA8_UNorm), EShaderAccess::WriteOnly, 0, EShaderStages::Compute ));
TEST( TestStorageBuffer( *ds, UniformID("un_SSBO"), 16_b, 0_b, EShaderAccess::ReadOnly, 1, EShaderStages::Compute ));
TEST(All( ppln._defaultLocalGroupSize == uint3(8, 8, 1) ));
TEST( ppln._localSizeSpec.x == 0 );
TEST( ppln._localSizeSpec.y == 1 );
TEST( ppln._localSizeSpec.z == UMax );
TEST( ppln._shader.specConstants.size() == 1 );
TEST( TestSpecializationConstant( ppln._shader, SpecializationID("SCALE"), 2 ));
TEST_PASSED();
}
| 30.192982 | 178 | 0.732132 | ayberkgerey5 |
58e7898083ebd61cc89744be82a0b8e97f4bc4cc | 2,133 | cpp | C++ | src/reflection/runner.cpp | maxdebayser/SelfPortra | f2817e19d4e00d7a18075b8d876fc710390821eb | [
"MIT"
] | 5 | 2015-03-27T15:57:19.000Z | 2021-02-07T23:42:45.000Z | src/reflection/runner.cpp | maxdebayser/SelfPortra | f2817e19d4e00d7a18075b8d876fc710390821eb | [
"MIT"
] | null | null | null | src/reflection/runner.cpp | maxdebayser/SelfPortra | f2817e19d4e00d7a18075b8d876fc710390821eb | [
"MIT"
] | 2 | 2015-04-27T04:19:42.000Z | 2016-11-25T18:36:59.000Z | /* Generated file, do not edit */
#ifndef CXXTEST_RUNNING
#define CXXTEST_RUNNING
#endif
#define _CXXTEST_HAVE_STD
#define _CXXTEST_HAVE_EH
#include <cxxtest/TestListener.h>
#include <cxxtest/TestTracker.h>
#include <cxxtest/TestRunner.h>
#include <cxxtest/RealDescriptions.h>
#include <cxxtest/TestMain.h>
#include <cxxtest/ErrorPrinter.h>
int main( int argc, char *argv[] ) {
int status;
CxxTest::ErrorPrinter tmp;
status = CxxTest::Main<CxxTest::ErrorPrinter>( tmp, argc, argv );
return status;
}
bool suite_VariantTestSuite_init = false;
#include "variant_test.h"
static VariantTestSuite suite_VariantTestSuite;
static CxxTest::List Tests_VariantTestSuite = { 0, 0 };
CxxTest::StaticSuiteDescription suiteDescription_VariantTestSuite( "variant_test.h", 7, "VariantTestSuite", suite_VariantTestSuite, Tests_VariantTestSuite );
static class TestDescription_suite_VariantTestSuite_testInvalid : public CxxTest::RealTestDescription {
public:
TestDescription_suite_VariantTestSuite_testInvalid() : CxxTest::RealTestDescription( Tests_VariantTestSuite, suiteDescription_VariantTestSuite, 11, "testInvalid" ) {}
void runTest() { suite_VariantTestSuite.testInvalid(); }
} testDescription_suite_VariantTestSuite_testInvalid;
static class TestDescription_suite_VariantTestSuite_testValue : public CxxTest::RealTestDescription {
public:
TestDescription_suite_VariantTestSuite_testValue() : CxxTest::RealTestDescription( Tests_VariantTestSuite, suiteDescription_VariantTestSuite, 12, "testValue" ) {}
void runTest() { suite_VariantTestSuite.testValue(); }
} testDescription_suite_VariantTestSuite_testValue;
static class TestDescription_suite_VariantTestSuite_testConversions : public CxxTest::RealTestDescription {
public:
TestDescription_suite_VariantTestSuite_testConversions() : CxxTest::RealTestDescription( Tests_VariantTestSuite, suiteDescription_VariantTestSuite, 13, "testConversions" ) {}
void runTest() { suite_VariantTestSuite.testConversions(); }
} testDescription_suite_VariantTestSuite_testConversions;
#include <cxxtest/Root.cpp>
const char* CxxTest::RealWorldDescription::_worldName = "cxxtest";
| 42.66 | 175 | 0.823722 | maxdebayser |
58e9c2fcacff9332941bf3737d1989210f27160a | 9,005 | cpp | C++ | camera/QCamera2/HAL3/test/QCameraHAL3VideoTest.cpp | derp-sdm660-common/device_asus_sdm660-common | f3106f346f4362859ab24d73428131ff916741e0 | [
"Apache-2.0"
] | 2 | 2021-06-12T11:18:28.000Z | 2021-06-22T20:53:12.000Z | camera/QCamera2/HAL3/test/QCameraHAL3VideoTest.cpp | derp-sdm660-common/device_asus_sdm660-common | f3106f346f4362859ab24d73428131ff916741e0 | [
"Apache-2.0"
] | null | null | null | camera/QCamera2/HAL3/test/QCameraHAL3VideoTest.cpp | derp-sdm660-common/device_asus_sdm660-common | f3106f346f4362859ab24d73428131ff916741e0 | [
"Apache-2.0"
] | 5 | 2020-09-29T14:15:31.000Z | 2021-11-06T23:21:39.000Z | /* Copyright (c) 2016, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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 "QCameraHAL3VideoTest.h"
#include "QCameraHAL3MainTestContext.h"
namespace qcamera {
extern hal3_camera_lib_test *CamObj_handle;
buffer_thread_t Video_thread;
int video_req_sent;
extern pthread_cond_t mRequestAppCond;
extern int test_case_end;
extern bool thread_exit;
extern std::list<uint32_t> VideoQueue;
int video_buffer_allocated;
extern pthread_mutex_t TestAppLock, mCaptureRequestLock;
extern int snapshot_buffer;
QCameraHAL3VideoTest::QCameraHAL3VideoTest(int camid) :
QCameraHAL3Test(0),
mVideoHandle(NULL),
mCaptureHandle(NULL),
mVideoStream(NULL),
mCameraId(camid),
binning_mode(0)
{
}
void QCameraHAL3VideoTest::initTest(hal3_camera_lib_test *handle,
int testcase, int camid, int w, int h)
{
int i;
CamObj_handle = handle; thread_exit = 0;
test_case_end = 0;
LOGD("\n buffer thread created for testcase %d %d and %d ",testcase, w, h);
configureVideoStream(&(handle->test_obj), camid, w, h);
LOGD("\n video stream configured");
constructDefaultRequest(&(handle->test_obj), camid);
LOGD("pipeline_depth is %d", mPipelineDepthVideo);
mVideoHandle = new native_handle_t *[mPipelineDepthVideo];
for (i = 0; i < mPipelineDepthVideo; i++) {
mVideoHandle[i] = new native_handle_t;
}
for (i = 0, video_req_sent = 1; i < mPipelineDepthVideo; i++, video_req_sent++) {
vidoeAllocateBuffers(width, height, i);
VideoQueue.push_back(i);
}
LOGD(" Request Number is : %d ",mRequest.frame_number);
mRequest.frame_number = 0;
videoProcessThreadCreate(handle);
}
void QCameraHAL3VideoTest::snapshotCaptureRequest(hal3_camera_lib_test *handle,
int testcase, int camid, int w, int h)
{
LOGD("Requested Capture Sizes for testcase:%d are :%d X %d",testcase, w, h);
captureRequestRepeat(handle, camid, MENU_START_CAPTURE);
pthread_mutex_unlock(&mCaptureRequestLock);
}
void QCameraHAL3VideoTest::configureVideoStream(hal3_camera_test_obj_t *my_test_obj,
int camid, int w, int h)
{
camera3_device_t *device_handle = my_test_obj->device;
mVideoStream = new camera3_stream_t;
memset(mVideoStream, 0, sizeof(camera3_stream_t));
mVideoStream = initStream(CAMERA3_STREAM_OUTPUT, camid, w, h, FLAGS_VIDEO_ENCODER,
HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, HAL3_DATASPACE_UNKNOWN);
mVideoConfig = configureStream(CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE, 1);
mVideoConfig.streams[0] = mVideoStream;
device_handle->ops->configure_streams(my_test_obj->device, &(mVideoConfig));
mPipelineDepthVideo = mVideoConfig.streams[0]->max_buffers;
video_buffer_allocated = mPipelineDepthVideo;
}
void QCameraHAL3VideoTest::constructDefaultRequest(
hal3_camera_test_obj_t *my_test_obj, int camid)
{
camera3_device_t *device_handle = my_test_obj->device;
LOGD("Camera ID : %d",camid);
mMetaDataPtr[0] = device_handle->ops->construct_default_request_settings(
my_test_obj->device, CAMERA3_TEMPLATE_VIDEO_RECORD);
mMetaDataPtr[1] = device_handle->ops->construct_default_request_settings(my_test_obj->device,
CAMERA3_TEMPLATE_STILL_CAPTURE);
}
void QCameraHAL3VideoTest::captureRequestRepeat(
hal3_camera_lib_test *my_hal3test_obj, int camid, int testcase)
{
int num1, num2;
int binning_mode_changed;
hal3_camera_test_obj_t *my_test_obj = &(my_hal3test_obj->test_obj);
camera3_device_t *device_handle = my_test_obj->device;
if (testcase == MENU_START_VIDEO) {
if (VideoQueue.empty()) {
LOGE("no Video buffer for CamID : %d", camid);
}
else {
if (test_case_end == 0) {
LOGD(" Request Number is : %d ", mRequest.frame_number);
pthread_mutex_lock(&mCaptureRequestLock);
num2 = VideoQueue.front();
VideoQueue.pop_front();
num1 = mRequest.frame_number;
binning_mode_changed = get_binning_mode(binning_mode);
if (num1 < 1) {
(mRequest).settings = mMetaDataPtr[0];
}
else if(binning_mode_changed == 1) {
hal3app_video_settings = mMetaDataPtr[0];
hal3app_video_settings.update(QCAMERA3_BINNING_CORRECTION_MODE,
&binning_mode, 1);
(mRequest).settings = hal3app_video_settings.release();
}
else {
(mRequest).settings = NULL;
}
(mRequest).input_buffer = NULL;
(mRequest).num_output_buffers = 1;
mVideoStreamBuffs.stream = mVideoStream;
mVideoStreamBuffs.status = 0;
mVideoStreamBuffs.buffer =
(const native_handle_t**)&mVideoHandle[num2];
mVideoStreamBuffs.release_fence = -1;
mVideoStreamBuffs.acquire_fence = -1;
(mRequest).output_buffers = &(mVideoStreamBuffs);
LOGD("Calling HAL3APP repeat capture request %d and %d and free buffer :%d "
, num1, num2, VideoQueue.size());
device_handle->ops->process_capture_request(my_test_obj->device, &(mRequest));
(mRequest.frame_number)++;
pthread_mutex_unlock(&mCaptureRequestLock);
}
}
}
else {
snapshot_buffer = mRequest.frame_number;
(mRequest).settings = mMetaDataPtr[1];
mSnapshotStreamBuffs = hal3appGetStreamBuffs(mSnapshotStream);
mSnapshotStreamBuffs.buffer = (const native_handle_t**)&mCaptureHandle;
mRequest = hal3appGetRequestSettings(&mSnapshotStreamBuffs, 1);
LOGD("Calling snap HAL3APP repeat capture request repeat %d ", snapshot_buffer);
device_handle->ops->process_capture_request(my_test_obj->device, &(mRequest));
(mRequest.frame_number)++;
}
}
void QCameraHAL3VideoTest::videoTestEnd(
hal3_camera_lib_test *my_hal3test_obj, int camid)
{
test_case_end = 1;
hal3_camera_test_obj_t *my_test_obj = &(my_hal3test_obj->test_obj);
camera3_device_t *device_handle = my_test_obj->device;
device_handle->ops->flush(my_test_obj->device);
LOGD("%s Closing Camera %d", __func__, camid);
ioctl(mVideoMeminfo.ion_fd, ION_IOC_FREE, &mVideoMeminfo.ion_handle);
close(mVideoMeminfo.ion_fd);
mVideoMeminfo.ion_fd = -1;
LOGD("%s Closing thread", __func__);
thread_exit = 1;
}
void QCameraHAL3VideoTest::vidoeAllocateBuffers(int height, int width, int num)
{
mVideoHandle[num] = allocateBuffers(width, height, &mVideoMeminfo);
}
void QCameraHAL3VideoTest::snapshotAllocateBuffers(int width, int height)
{
mCaptureHandle = allocateBuffers(width, height, &mCaptureMemInfo);
}
int QCameraHAL3VideoTest::get_binning_mode(int32_t binning_mode)
{
static int prev_binning;
if(binning_mode == prev_binning)
return 0;
else {
ALOGE("setting binning mode in video:%d", binning_mode);
prev_binning = binning_mode;
return 1;
}
}
bool QCameraHAL3VideoTest::videoProcessThreadCreate(
hal3_camera_lib_test *handle) {
if(handle == NULL) {
LOGD("Camera Hanle is NULL");
}
processThreadCreate(this, MENU_START_VIDEO);
return 1;
}
QCameraHAL3VideoTest::~QCameraHAL3VideoTest()
{
}
}
| 38.319149 | 97 | 0.687396 | derp-sdm660-common |
58ec3ab0db0df64cc3e6121ec015507661a09c8b | 2,043 | cpp | C++ | cs224/prog1/bridgesim.cpp | sankalpgambhir/fall2021 | 955bbe47e547860219920e8090076b2b4bdc3a58 | [
"WTFPL"
] | null | null | null | cs224/prog1/bridgesim.cpp | sankalpgambhir/fall2021 | 955bbe47e547860219920e8090076b2b4bdc3a58 | [
"WTFPL"
] | null | null | null | cs224/prog1/bridgesim.cpp | sankalpgambhir/fall2021 | 955bbe47e547860219920e8090076b2b4bdc3a58 | [
"WTFPL"
] | null | null | null | // bridgesim.cpp
// function definitions for the network
#include "bridgesim.h"
// construction
// constructor
Network::Network(std::ostream& inlog = std::clog)
: log (inlog){
// initialise nodes
for(int i = 0; i < 26; i++){
nodes.emplace_back(i);
}
return;
}
// access and modification
// add a new bridge to network
Bridge* Network::add_bridge(int id){
bridges.emplace_back(id, &log);
return &(bridges.back());
}
Node* Network::get_node(int id){
return &(nodes.at(id));
}
void Network::add_connection(Bridge* b, int node_id){
auto* n = this->get_node(node_id);
b->add_connection(n);
n->add_connection(b);
return;
}
// output and control
// sort individual bridges
void Network::sort(){
for(auto &b: bridges){
b.sort();
}
// sort all bridges
std::sort(bridges.begin(), bridges.end(), [](const Bridge& a, const Bridge& b){
return a.get_id() < b.get_id();
});
// nodes were generated sorted
return;
}
// run actual STP algorithm
void Network::run_stp(){
// set universal time
Bridge::currtime = 0;
for(auto &b : bridges){
b.broadcast_root();
}
Bridge::currtime++;
while(!check_same_root()){
for(auto i = bridges.rbegin(); i < bridges.rend(); i++){
i->process_buffer();
}
Bridge::currtime++;
}
// run once more for NP
for(auto i = bridges.rbegin(); i < bridges.rend(); i++){
i->process_buffer();
}
Bridge::currtime++;
return;
}
bool Network::check_same_root(){
bool same = true;
int root = bridges.front().get_root();
for(auto &b : bridges){
if(b.get_root() != root){
same = false;
break;
}
}
return same;
}
void Network::print_connections(std::ostream& out){
for(auto &b: bridges){
out << b.print_connections() << std::endl;
}
return;
}
| 19.273585 | 83 | 0.545277 | sankalpgambhir |
58ed0421a1ccc3bfbdb42b9991f4c83d4bcb0ca7 | 1,255 | cpp | C++ | Upsolving/URI/2486.cpp | rodrigoAMF7/Notebook---Maratonas | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | 4 | 2019-01-25T21:22:55.000Z | 2019-03-20T18:04:01.000Z | Upsolving/URI/2486.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | Upsolving/URI/2486.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3F3F3F3F3FLL
#define DINF (double)1e+30
#define forn(i, n) for ( int i = 0; i < (n); ++i )
#define forxn(i, x, n) for ( int i = (x); i < (n); ++i )
#define forr(i, a, b) for ( int i = (a); i <= (b); ++i )
#define ford(i, a, b) for ( int i = (a); i >= (b); −−i )
using namespace std;
int main(){
int t;
int resultado;
while(true){
cin >> t;
if(t == 0) break;
resultado = 0;
forn(i, t){
int n;
string alimento;
cin >> n;
getline(cin, alimento);
if(alimento == " suco de laranja")
resultado+=120*n;
else if(alimento == " morango fresco")
resultado+=85*n;
else if(alimento == " mamao")
resultado+=85*n;
else if(alimento == " goiaba vermelha")
resultado+=70*n;
else if(alimento == " manga")
resultado+=56*n;
else if(alimento == " laranja")
resultado+=50*n;
else if(alimento == " brocolis")
resultado+=34*n;
}
if(resultado >= 110 && resultado <= 130)
cout << resultado << " mg" << endl;
else{
if(resultado > 130){
resultado -= 130;
cout << "Menos " << resultado << " mg" << endl;
}else{
resultado -= 110;
cout << "Mais " << resultado*-1 << " mg" << endl;
}
}
}
return 0;
} | 22.017544 | 56 | 0.549004 | rodrigoAMF7 |
58edd9fc431c5f3b2bc5c43bfe51090b6d2f78dd | 4,446 | cpp | C++ | src/timelineDecoder/TimelineCaptureCommandHandler.cpp | muthukumaravel7/armnn | 879ec231203df5b0a94462c0b247dc7d8d8a7a44 | [
"MIT"
] | null | null | null | src/timelineDecoder/TimelineCaptureCommandHandler.cpp | muthukumaravel7/armnn | 879ec231203df5b0a94462c0b247dc7d8d8a7a44 | [
"MIT"
] | null | null | null | src/timelineDecoder/TimelineCaptureCommandHandler.cpp | muthukumaravel7/armnn | 879ec231203df5b0a94462c0b247dc7d8d8a7a44 | [
"MIT"
] | null | null | null | //
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "TimelineCaptureCommandHandler.hpp"
#include <string>
#include <armnn/Logging.hpp>
namespace armnn
{
namespace timelinedecoder
{
//Array of member functions, the array index matches the decl_id
const TimelineCaptureCommandHandler::ReadFunction TimelineCaptureCommandHandler::m_ReadFunctions[]
{
&TimelineCaptureCommandHandler::ReadLabel, // Label decl_id = 0
&TimelineCaptureCommandHandler::ReadEntity, // Entity decl_id = 1
&TimelineCaptureCommandHandler::ReadEventClass, // EventClass decl_id = 2
&TimelineCaptureCommandHandler::ReadRelationship, // Relationship decl_id = 3
&TimelineCaptureCommandHandler::ReadEvent // Event decl_id = 4
};
void TimelineCaptureCommandHandler::ParseData(const armnn::profiling::Packet& packet)
{
uint32_t offset = 0;
m_PacketLength = packet.GetLength();
// We are expecting TimelineDirectoryCaptureCommandHandler to set the thread id size
// if it not set in the constructor
if (m_ThreadIdSize == 0)
{
ARMNN_LOG(error) << "TimelineCaptureCommandHandler: m_ThreadIdSize has not been set";
return;
}
if (packet.GetLength() < 8)
{
return;
}
const unsigned char* data = reinterpret_cast<const unsigned char*>(packet.GetData());
uint32_t declId = 0;
while ( offset < m_PacketLength )
{
declId = profiling::ReadUint32(data, offset);
offset += uint32_t_size;
(this->*m_ReadFunctions[declId])(data, offset);
}
}
void TimelineCaptureCommandHandler::ReadLabel(const unsigned char* data, uint32_t& offset)
{
ITimelineDecoder::Label label;
label.m_Guid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
uint32_t nameLength = profiling::ReadUint32(data, offset);
offset += uint32_t_size;
uint32_t i = 0;
// nameLength - 1 to account for null operator \0
for ( i = 0; i < nameLength - 1; ++i )
{
label.m_Name += static_cast<char>(profiling::ReadUint8(data, offset + i));
}
// Shift offset past nameLength
uint32_t uint32WordAmount = (nameLength / uint32_t_size) + (nameLength % uint32_t_size != 0 ? 1 : 0);
offset += uint32WordAmount * uint32_t_size;
m_TimelineDecoder.CreateLabel(label);
}
void TimelineCaptureCommandHandler::ReadEntity(const unsigned char* data, uint32_t& offset)
{
ITimelineDecoder::Entity entity;
entity.m_Guid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
m_TimelineDecoder.CreateEntity(entity);
}
void TimelineCaptureCommandHandler::ReadEventClass(const unsigned char* data, uint32_t& offset)
{
ITimelineDecoder::EventClass eventClass;
eventClass.m_Guid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
m_TimelineDecoder.CreateEventClass(eventClass);
}
void TimelineCaptureCommandHandler::ReadRelationship(const unsigned char* data, uint32_t& offset)
{
ITimelineDecoder::Relationship relationship;
relationship.m_RelationshipType =
static_cast<ITimelineDecoder::RelationshipType>(profiling::ReadUint32(data, offset));
offset += uint32_t_size;
relationship.m_Guid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
relationship.m_HeadGuid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
relationship.m_TailGuid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
m_TimelineDecoder.CreateRelationship(relationship);
}
void TimelineCaptureCommandHandler::ReadEvent(const unsigned char* data, uint32_t& offset)
{
ITimelineDecoder::Event event;
event.m_TimeStamp = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
if ( m_ThreadIdSize == 4 )
{
event.m_ThreadId = profiling::ReadUint32(data, offset);
}
else if ( m_ThreadIdSize == 8 )
{
event.m_ThreadId = profiling::ReadUint64(data, offset);
}
offset += m_ThreadIdSize;
event.m_Guid = profiling::ReadUint64(data, offset);
offset += uint64_t_size;
m_TimelineDecoder.CreateEvent(event);
}
void TimelineCaptureCommandHandler::SetThreadIdSize(uint32_t size)
{
m_ThreadIdSize = size;
}
void TimelineCaptureCommandHandler::operator()(const profiling::Packet& packet)
{
ParseData(packet);
}
} //namespace gatordmock
} //namespace armnn
| 29.838926 | 105 | 0.710301 | muthukumaravel7 |
58f14bf464dd9ce725b30a2ae86fe65f6f636d1f | 1,678 | cpp | C++ | mod.cpp | johnb432/TFAR-ACE-Setter-Extended | dc91aac52eab33411d575a4a2447306f6ac5defe | [
"MIT"
] | null | null | null | mod.cpp | johnb432/TFAR-ACE-Setter-Extended | dc91aac52eab33411d575a4a2447306f6ac5defe | [
"MIT"
] | null | null | null | mod.cpp | johnb432/TFAR-ACE-Setter-Extended | dc91aac52eab33411d575a4a2447306f6ac5defe | [
"MIT"
] | null | null | null | // Name
name = "TFAR - ACE Radio Setter - Extended";
// Author
author = "johnb43";
// Tool tip on mouse hover
tooltip = "TFAR - ACE Radio Setter - Extended";
// Tool tip displayed when the mouse is left over, in the main menu
tooltipOwned = "TFAR - ACE Radio Setter - Extended";
// Hide the extension name
hideName = 0;
// Hide the extension menu
hidePicture = 0;
// Button name
actionName = "Github";
// Website URL, that can accessed from the expansions menu
action = "https://github.com/johnb432/ACE-TFAR-Setter-Extended";
// Description of the mod
description = "A simple quality of life mod for the Arma 3 TFAR Addon. Allows you to save multiple radio configurations and reload them at any point in the future.";
// Overview text, displayed from the extension menu
overview = "A simple quality of life mod for the Arma 3 TFAR Addon. Allows you to save multiple radio configurations and reload them at any point in the future.";
// Picture displayed from the expansions menu/ Optimal size is 2048x1024, other sizes work too; https://community.bistudio.com/wiki/ImageToPAA
picture = "\x\tfar_ace_extended\addons\main\ui\logo_ace_tfar_setter_extended.paa";
// Logo displayed in the main menu
logo = "\x\tfar_ace_extended\addons\main\ui\logo_ace_tfar_setter_extended.paa";
// When the mouse is over, in the main menu
logoOver = "\x\tfar_ace_extended\addons\main\ui\logo_ace_tfar_setter_extended.paa";
// Display next to the item added by the mod
logoSmall = "\x\tfar_ace_extended\addons\main\ui\logo_ace_tfar_setter_extended.paa";
// Overview picture, displayed from the extension menu
overviewPicture = "\x\tfar_ace_extended\addons\main\ui\logo_ace_tfar_setter_extended.paa";
| 54.129032 | 165 | 0.771752 | johnb432 |
58f555ed05a6cb6a088a791bcbcd5b13fd13c733 | 7,056 | cpp | C++ | src/lic.cpp | rubenvanstaden/Magix | 0b45955d98a57b15b021e3d2e99698972f874a2d | [
"CECILL-B"
] | null | null | null | src/lic.cpp | rubenvanstaden/Magix | 0b45955d98a57b15b021e3d2e99698972f874a2d | [
"CECILL-B"
] | null | null | null | src/lic.cpp | rubenvanstaden/Magix | 0b45955d98a57b15b021e3d2e99698972f874a2d | [
"CECILL-B"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include "sys.h"
#include <time.h>
#include "grid.h"
#include <armadillo>
using namespace std;
double compute_convolution_normal(System *sys, double *pNoise, Node *C) {
double sum = 0;
for (int i = 1; i < 2 * sys->len; i++) {
int samp_y = (C[i].x + C[i - 1].x) * 0.5;
int samp_x = (C[i].y + C[i - 1].y) * 0.5;
if (samp_x < 0)
samp_x = 0;
if (samp_y < 0)
samp_y = 0;
if (samp_x > sys->NGrid)
samp_x = sys->NGrid - 1;
if (samp_y > sys->NGrid)
samp_y = sys->NGrid - 1;
int pic_loc = samp_y * sys->NGrid + samp_x;
sum = sum + pNoise[pic_loc];
}
sum = sum / (2 * sys->len + 1);
return sum;
}
double compute_convolution_high(System *sys, double *pNoise, Node *C) {
double sum = 0;
double filter[3][3] = {
0, 1 / 2, 0,
1 / 2, 1.5, 1 / 2,
0, 1 / 2, 0
};
for (int i = 1; i < 2 * sys->len; i++) {
int samp_x = (C[i].x + C[i - 1].x) * 0.5;
int samp_y = (C[i].y + C[i - 1].y) * 0.5;
if (samp_x < 0)
samp_x = 0;
if (samp_y < 0)
samp_y = 0;
if (samp_x > sys->NGrid)
samp_x = sys->NGrid - 1;
if (samp_y > sys->NGrid)
samp_y = sys->NGrid - 1;
for (int r = 0; r < 3; r++) {
for (int s = 0; s < 3; s++) {
int n = (samp_x - 3 / 2 + r + sys->NGrid) % sys->NGrid;
int m = (samp_y - 3 / 2 + s + sys->NGrid) % sys->NGrid;
int pic_loc = n * sys->NGrid + m;
sum = sum + (pNoise[pic_loc] * filter[r][s]);
}
}
}
sum = sum / (2 * sys->len + 1);
return sum;
}
void synthesize_vectors(System *sys, Grid *grid, double **vect_x, double **vect_y) {
for (int j = 0; j < sys->NGrid; j++) {
for (int i = 0; i < sys->NGrid; i++) {
vect_x[j][i] = grid->Hy(j,i);
vect_y[j][i] = grid->Hz(j,i);
}
}
}
void normalize_vectors(System *sys, double **vect_x, double **vect_y) {
for (int j = 0; j < sys->NGrid; j++) {
for (int i = 0; i < sys->NGrid; i++) {
double mag = sqrtf(vect_x[j][i] * vect_x[j][i] + vect_y[j][i] * vect_y[j][i]);
if (mag > 0.0) {
vect_x[j][i] = vect_x[j][i] / mag;
vect_y[j][i] = vect_y[j][i] / mag;
}
else {
vect_x[j][i] = 0;
vect_y[j][i] = 0;
}
}
}
}
void white_noise(System *sys, double *pNoise) {
int pic_loc;
for (int j = 0; j < sys->NGrid; j++) {
for (int i = 0; i < sys->NGrid; i++) {
int r = rand();
pic_loc = j * sys->NGrid + i;
r = ((r & 255) + ((r & 255) >> 8)) & 255;
pNoise[pic_loc] = (unsigned char) r;
}
}
}
void compute_integral_curve(System *sys, Node *p, Node *C, double **vect_x, double **vect_y) {
double x = p->x + 0.5;
double y = p->y + 0.5;
int s;
int index = 0;
C[index].x = x;
C[index].y = y;
double segLen = 0;
double vctr_x = 0;
double vctr_y = 0;
// positive calculations
for (s = 0; s < sys->len; s++) {
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > sys->NGrid)
x = sys->NGrid - 1;
if (y > sys->NGrid)
y = sys->NGrid - 1;
vctr_x = vect_x[(int) x][(int) y];
vctr_y = vect_y[(int) x][(int) y];
segLen += 0.1;
x = x + segLen * vctr_x;
y = y + segLen * vctr_y;
C[index].x = x;
C[index].y = y;
index++;
}
x = p->x + 0.5;
y = p->y + 0.5;
segLen = 0;
// negative calculations
for (s = 0; s < sys->len; s++) {
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > sys->NGrid)
x = sys->NGrid - 1;
if (y > sys->NGrid)
y = sys->NGrid - 1;
vctr_x = vect_x[(int) x][(int) y];
vctr_y = vect_y[(int) x][(int) y];
segLen += 0.1;
x = x - segLen * vctr_x;
y = y - segLen * vctr_y;
C[index].x = x;
C[index].y = y;
index++;
}
}
void lic(System *sys, Grid *grid) {
grid->ix.reshape(sys->NGrid, sys->NGrid);
grid->iy.reshape(sys->NGrid, sys->NGrid);
grid->iz.reshape(sys->NGrid, sys->NGrid);
sys->len = 20;
std::cout << "\n--- LIC algorithm started ---" << std::endl;
clock_t begin, end;
double time_spent;
begin = clock();
Node *p = (Node *) calloc(1, sizeof(Node));
Node *C = (Node *) calloc(2 * sys->len, sizeof(Node));
double *pNoise = (double *) malloc(sizeof(double) * sys->NGrid * sys->NGrid);
double *pNoise_double = (double *) malloc(sizeof(double) * sys->NGrid * sys->NGrid);
double **vect_x = (double **) calloc(sys->NGrid, sizeof(double *));
double **vect_y = (double **) calloc(sys->NGrid, sizeof(double *));
for (int i = 0; i < sys->NGrid; i++)
vect_x[i] = (double *) calloc(sys->NGrid, sizeof(double));
for (int i = 0; i < sys->NGrid; i++)
vect_y[i] = (double *) calloc(sys->NGrid, sizeof(double));
synthesize_vectors(sys, grid, vect_x, vect_y);
normalize_vectors(sys, vect_x, vect_y);
white_noise(sys, pNoise);
for (int j = 0; j < sys->NGrid; j++) {
for (int i = 0; i < sys->NGrid; i++) {
p->x = j;
p->y = i;
compute_integral_curve(sys, p, C, vect_x, vect_y);
double sum = compute_convolution_normal(sys, pNoise, C);
if (sum < 100)
sum = 0;
if (sum > 150)
sum = 255;
pNoise_double[j * sys->NGrid + i] = sum;
}
}
for (int j = 0; j < sys->NGrid; j++) {
for (int i = 0; i < sys->NGrid; i++) {
p->x = j;
p->y = i;
compute_integral_curve(sys, p, C, vect_x, vect_y);
double sum = compute_convolution_high(sys, pNoise_double, C);
if (sum < 0)
sum = 0;
if (sum > 255)
sum = 255;
grid->ix(j,i) = sum;
}
}
arma::mat magVect(sys->NGrid, sys->NGrid);
for (int j = 0; j < sys->NGrid; j++) {
for (int i = 0; i < sys->NGrid; i++) {
double mag_x = grid->Hx(j,i) * grid->Hx(j,i);
double mag_y = grid->Hy(j,i) * grid->Hy(j,i);
double mag_z = grid->Hz(j,i) * grid->Hz(j,i);
double mag = sqrtf(mag_x + mag_y + mag_z);
if (mag > 0)
magVect(j,i) = mag;
}
}
for (int j = 0; j < sys->NGrid; j++)
for (int i = 0; i < sys->NGrid; i++)
grid->iy(j,i) = magVect(j,i);
end = clock();
time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
printf("LIC End\n");
printf("Time Spend: %lf\n", time_spent);
}
| 24.5 | 94 | 0.447279 | rubenvanstaden |
58f86bb53b9367be29ef0d369222fdb5611a35c9 | 177 | cpp | C++ | src/solutions/48.cpp | bshankar/euler | c866a661a94d15d3744c74d85149534efac2ca23 | [
"MIT"
] | null | null | null | src/solutions/48.cpp | bshankar/euler | c866a661a94d15d3744c74d85149534efac2ca23 | [
"MIT"
] | null | null | null | src/solutions/48.cpp | bshankar/euler | c866a661a94d15d3744c74d85149534efac2ca23 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
typedef short s;
typedef unsigned short us;
typedef unsigned int ui;
typedef unsigned long ul;
using namespace std;
int main() {
}
| 12.642857 | 26 | 0.723164 | bshankar |
58f881a44f05bfdbed968b962659ca2ac3563922 | 3,580 | cpp | C++ | sources/lowlevelcom/transport_i2c.cpp | lukier/misccpp | bf557404be271b83310d636ce8ac9f5747e50fc7 | [
"BSD-3-Clause"
] | 1 | 2017-06-01T09:18:19.000Z | 2017-06-01T09:18:19.000Z | sources/lowlevelcom/transport_i2c.cpp | lukier/misccpp | bf557404be271b83310d636ce8ac9f5747e50fc7 | [
"BSD-3-Clause"
] | null | null | null | sources/lowlevelcom/transport_i2c.cpp | lukier/misccpp | bf557404be271b83310d636ce8ac9f5747e50fc7 | [
"BSD-3-Clause"
] | null | null | null | /**
* ****************************************************************************
* Copyright (c) 2017, Robert Lukierski.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ****************************************************************************
* Linux i2c-dev based transport.
* ****************************************************************************
*/
#include <string>
#include <chrono>
#include <stdexcept>
#include <cstring>
#include <misccpp/drivers/DevI2C.hpp>
#include <misccpp/lowlevelcom/transport/transport_i2c.hpp>
template<bool MultiChannel>
llc::transport::I2CIO<MultiChannel>::I2CIO(const char* port, bool addr10b) : tx_i2c_addr(0), pimpl(new drivers::DevI2C())
{
pimpl->open(port, (addr10b == true ? drivers::DevI2C::AddressSupport::bits10 : drivers::DevI2C::AddressSupport::bits7));
}
template<bool MultiChannel>
llc::transport::I2CIO<MultiChannel>::~I2CIO()
{
}
template<bool MultiChannel>
llc::Error llc::transport::I2CIO<MultiChannel>::receiveImpl(message_t& msg_out, const int timeout_ms)
{
// msg_out must contain info (length) beforehand for packet based IO
if(!msg_out) { return Error::OutOfMemory; }
if(!pimpl->setSlaveAddress(tx_i2c_addr))
{
return Error::HardwareError;
}
msg_out.setNodeID(tx_i2c_addr);
if(!pimpl->read(msg_out.buf.get(), message_t::PrefixRequired + msg_out.len, std::chrono::milliseconds(timeout_ms)))
{
return Error::HardwareError;
}
tx_i2c_addr = 0;
return Error::OK;
}
template<bool MultiChannel>
llc::Error llc::transport::I2CIO<MultiChannel>::transmitImpl(const message_t& msg_out, const int timeout_ms)
{
tx_i2c_addr = msg_out.getNodeID();
if(!pimpl->setSlaveAddress(tx_i2c_addr))
{
return Error::HardwareError;
}
if(!pimpl->write(msg_out.buf.get(), message_t::PrefixRequired + msg_out.len, std::chrono::milliseconds(timeout_ms)))
{
return Error::HardwareError;
}
return Error::OK;
}
template class llc::transport::I2CIO<true>;
template class llc::transport::I2CIO<false>;
| 35.8 | 124 | 0.681285 | lukier |
58f8c273b4f96a22b5a617c1d24dc3dfaa5c22b5 | 567 | cpp | C++ | cph/examples/uart_async.cpp | Loggi-pro/cph-lib | 4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67 | [
"MIT"
] | null | null | null | cph/examples/uart_async.cpp | Loggi-pro/cph-lib | 4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67 | [
"MIT"
] | null | null | null | cph/examples/uart_async.cpp | Loggi-pro/cph-lib | 4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67 | [
"MIT"
] | null | null | null | #include <cph/basic_usart.h>
#include <void/interrupt.h>
typedef cph::UsartAsync<cph::Usart0> Usart;
extern "C" {
VOID_ISR(CPH_INT_USART0_RXC) {
Usart::Hardware::IntRxHandler();
}
VOID_ISR(CPH_INT_USART0_TXE) {
Usart::Hardware::IntTxEmptyHandler();
}
}
int main(void) {
Usart::init<19200>();
Usart::setOnReceive([](const uint8_t& value) {
Usart::writeByte(value + 1);
});
vd::EnableInterrupts();
while (true) {
typename Usart::Flags::Error e = Usart::getError();
if (e != Usart::Flags::NoError) {
Usart::writeByte(e);
}
}
return 0;
} | 17.181818 | 53 | 0.663139 | Loggi-pro |
58ff6618024fd9b8cd7c72bcae3120514be8512d | 7,775 | cpp | C++ | source/sema/overload_resolution.cpp | stryku/cmakesl | e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326 | [
"BSD-3-Clause"
] | 51 | 2019-05-06T01:33:34.000Z | 2021-11-17T11:44:54.000Z | source/sema/overload_resolution.cpp | stryku/cmakesl | e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326 | [
"BSD-3-Clause"
] | 191 | 2019-05-06T18:31:24.000Z | 2020-06-19T06:48:06.000Z | source/sema/overload_resolution.cpp | stryku/cmakesl | e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326 | [
"BSD-3-Clause"
] | 3 | 2019-10-12T21:03:29.000Z | 2020-06-19T06:22:25.000Z | #include "sema/overload_resolution.hpp"
#include "common/overloaded.hpp"
#include "errors/error.hpp"
#include "errors/errors_observer.hpp"
#include "overload_resolution.hpp"
#include "sema/failed_initialization_errors_reporters.hpp"
#include "sema/sema_function.hpp"
#include "sema/sema_nodes.hpp"
#include "sema/variable_initialization_checker.hpp"
#include <algorithm>
#include <functional>
namespace cmsl::sema {
overload_resolution::overload_resolution(errors::errors_observer& errs,
lexer::token call_token)
: m_errs{ errs }
, m_call_token{ call_token }
{
}
const sema_function* overload_resolution::choose(
const function_lookup_result_t& functions,
const std::vector<std::unique_ptr<expression_node>>& call_parameters) const
{
if (functions.empty()) {
const auto line_info =
m_call_token.source().line(m_call_token.src_range().begin.line);
const auto err = errors::error{ m_call_token.source().path(),
line_info.line,
line_info.start_pos,
'\'' + std::string{ m_call_token.str() } +
"\' function not found",
errors::error_type::error,
m_call_token.src_range() };
m_errs.notify_error(err);
return nullptr;
}
const auto call_params_wrappers = to_vector_of_wrappers(call_parameters);
for (const auto& scoped_functions : functions) {
// Todo: is it even possible to have empty vector here?
if (scoped_functions.empty()) {
continue;
}
return choose_from_scope(scoped_functions, call_params_wrappers);
}
return nullptr;
}
const sema_function* overload_resolution::choose(
const single_scope_function_lookup_result_t& functions,
const std::vector<std::unique_ptr<expression_node>>& call_parameters) const
{
const auto param_wrappers = to_vector_of_wrappers(call_parameters);
return choose_from_scope(functions, param_wrappers);
}
const sema_function* overload_resolution::choose(
const single_scope_function_lookup_result_t& functions,
const expression_node& call_parameter) const
{
const auto param_wrappers = to_vector_of_wrappers(call_parameter);
return choose_from_scope(functions, param_wrappers);
}
const sema_function* overload_resolution::choose_from_scope(
const single_scope_function_lookup_result_t& functions,
const std::vector<std::reference_wrapper<const expression_node>>&
call_parameters) const
{
std::vector<function_match_result> results;
for (const auto function : functions) {
auto result = params_match(*function, call_parameters);
if (std::holds_alternative<match_result::ok>(result)) {
return function;
}
results.emplace_back(
function_match_result{ *function, std::move(result) });
}
// At this point we know that there is no good function to call.
raise_error(results, call_parameters);
return nullptr;
}
overload_resolution::match_result_variant_t overload_resolution::params_match(
const sema_function& function,
const std::vector<std::reference_wrapper<const expression_node>>&
call_parameters) const
{
const auto& signature = function.signature();
if (signature.params.size() != call_parameters.size()) {
return match_result::wrong_parameters_count{
static_cast<unsigned>(signature.params.size()),
static_cast<unsigned>(call_parameters.size())
};
}
std::vector<
match_result::params_initialization_failed::param_initialization_info>
initialization_failed_info;
for (auto i = 0u; i < call_parameters.size(); ++i) {
const auto& declared_param_type = signature.params[i].ty;
variable_initialization_checker checker;
const auto init_issues =
checker.check(declared_param_type, call_parameters[i].get());
if (init_issues.empty()) {
continue;
}
auto param_init_failed_info =
match_result::params_initialization_failed::param_initialization_info{
i, init_issues
};
initialization_failed_info.emplace_back(std::move(param_init_failed_info));
}
if (!initialization_failed_info.empty()) {
return match_result::params_initialization_failed{ std::move(
initialization_failed_info) };
}
return match_result::ok{};
}
overload_resolution::error_notes_reporter::error_notes_reporter(
cmsl::errors::errors_observer& errs,
const cmsl::sema::sema_function& function, const lexer::token& call_token,
const std::vector<std::reference_wrapper<const expression_node>>&
call_parameters)
: m_errs{ errs }
, m_function{ function }
, m_call_token{ call_token }
, m_call_parameters{ call_parameters }
{
}
void overload_resolution::error_notes_reporter::operator()(
const overload_resolution::match_result::wrong_parameters_count& result)
const
{
auto err = create_note_basics();
err.message += "Wrong parameters count passed. Expected " +
std::to_string(result.expected) + ", got " + std::to_string(result.got);
m_errs.notify_error(err);
}
void overload_resolution::error_notes_reporter::operator()(
const overload_resolution::match_result::params_initialization_failed&
result) const
{
for (const auto& info : result.info) {
for (const auto& call_issue : info.issues) {
const auto& param_expr = m_call_parameters[info.position].get();
function_call_parameters_failed_initializations_errors_reporter reporter{
m_errs, m_function, info.position, param_expr, m_call_token
};
std::visit(reporter, call_issue);
}
}
// Todo: would be nice to create notes about expected and got types, with
// expressions indication.
}
errors::error overload_resolution::error_notes_reporter::create_note_basics()
const
{
errors::error err;
const auto function_name = m_function.signature().name;
const auto line_info =
function_name.source().line(function_name.src_range().begin.line);
err.line_snippet = line_info.line;
err.line_start_pos = line_info.start_pos;
err.source_path = function_name.source().path();
err.range = function_name.src_range();
err.type = errors::error_type::note;
err.message = "candidate \'" + std::string{ function_name.str() } + "\'. ";
return err;
}
void overload_resolution::raise_error(
const std::vector<overload_resolution::function_match_result>& match_results,
const std::vector<std::reference_wrapper<const expression_node>>&
call_parameters) const
{
{
const auto line_info =
m_call_token.source().line(m_call_token.src_range().begin.line);
const auto err = errors::error{
m_call_token.source().path(), line_info.line,
line_info.start_pos, "No matching function for call",
errors::error_type::error, m_call_token.src_range()
};
m_errs.notify_error(err);
}
for (const auto& result : match_results) {
const auto reporter =
error_notes_reporter{ m_errs, result.function, m_call_token,
call_parameters };
std::visit(reporter, result.params_match_result);
}
}
std::vector<std::reference_wrapper<const expression_node>>
overload_resolution::to_vector_of_wrappers(
const std::vector<std::unique_ptr<expression_node>>& params) const
{
std::vector<std::reference_wrapper<const expression_node>> result;
std::transform(
std::cbegin(params), std::cend(params), std::back_inserter(result),
[](const auto& param) -> std::reference_wrapper<const expression_node> {
return *param;
});
return result;
}
std::vector<std::reference_wrapper<const expression_node>>
overload_resolution::to_vector_of_wrappers(const expression_node& param) const
{
return { std::ref(param) };
}
}
| 31.734694 | 79 | 0.715498 | stryku |
450020d8ab50f1587afd6c825baa15c4feb3be48 | 278 | cpp | C++ | src/gameworld/gameworld/global/randactivity/impl/randactivitysinglecharge.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/gameworld/gameworld/global/randactivity/impl/randactivitysinglecharge.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/gameworld/gameworld/global/randactivity/impl/randactivitysinglecharge.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #include "randactivitysinglecharge.hpp"
RandActivitySingleCharge::RandActivitySingleCharge(RandActivityManager *rand_activity_manager)
: RandActivity(rand_activity_manager, RAND_ACTIVITY_TYPE_SINGLE_CHARGE)
{
}
RandActivitySingleCharge::~RandActivitySingleCharge()
{
}
| 15.444444 | 94 | 0.845324 | mage-game |
45044bc7a1972b638fa351a36004ec18579eb82a | 4,812 | cc | C++ | Simulation/OMNeT++/inet/src/inet/common/geometry/common/CoordinateSystem.cc | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | 1 | 2017-03-13T15:51:22.000Z | 2017-03-13T15:51:22.000Z | Simulation/OMNeT++/inet/src/inet/common/geometry/common/CoordinateSystem.cc | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | null | null | null | Simulation/OMNeT++/inet/src/inet/common/geometry/common/CoordinateSystem.cc | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | null | null | null | //
// Copyright (C) 2013 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/common/geometry/common/CoordinateSystem.h"
#ifdef WITH_OSG
#include <osgEarthUtil/ObjectLocator>
#endif
namespace inet {
const GeoCoord GeoCoord::NIL = GeoCoord(NaN, NaN, NaN);
Define_Module(SimpleGeographicCoordinateSystem);
void SimpleGeographicCoordinateSystem::initialize(int stage)
{
if (stage == INITSTAGE_LOCAL) {
playgroundLatitude = par("playgroundLatitude");
playgroundLongitude = par("playgroundLongitude");
playgroundAltitude = par("playgroundAltitude");
}
}
Coord SimpleGeographicCoordinateSystem::computePlaygroundCoordinate(const GeoCoord& geographicCoordinate) const
{
double playgroundX = (geographicCoordinate.longitude - playgroundLongitude) * cos(fabs(playgroundLatitude / 180 * M_PI)) * metersPerDegree;
double playgroundY = (playgroundLatitude - geographicCoordinate.latitude) * metersPerDegree;
return Coord(playgroundX, playgroundY, geographicCoordinate.altitude + playgroundAltitude);
}
GeoCoord SimpleGeographicCoordinateSystem::computeGeographicCoordinate(const Coord& playgroundCoordinate) const
{
double geograpicLatitude = playgroundLatitude - playgroundCoordinate.y / metersPerDegree;
double geograpicLongitude = playgroundLongitude + playgroundCoordinate.x / metersPerDegree / cos(fabs(playgroundLatitude / 180 * M_PI));
return GeoCoord(geograpicLatitude, geograpicLongitude, playgroundCoordinate.z - playgroundAltitude);
}
#ifdef WITH_OSG
Define_Module(OsgGeographicCoordinateSystem);
void OsgGeographicCoordinateSystem::initialize(int stage)
{
if (stage == INITSTAGE_LOCAL) {
auto mapScene = getParentModule()->getOsgCanvas()->getScene();
mapNode = osgEarth::MapNode::findMapNode(mapScene);
if (mapNode == nullptr)
throw cRuntimeError("Count not find map node in the scene");
double playgroundLatitude = par("playgroundLatitude");
double playgroundLongitude = par("playgroundLongitude");
double playgroundAltitude = par("playgroundAltitude");
double playgroundHeading = par("playgroundHeading");
double playgroundElevation = par("playgroundElevation");
double playgroundBank = par("playgroundBank");
playgroundPosition = GeoCoord(playgroundLatitude, playgroundLongitude, playgroundAltitude);
playgroundOrientation = EulerAngles(playgroundHeading, playgroundElevation, playgroundBank);
auto locatorNode = new osgEarth::Util::ObjectLocatorNode(mapNode->getMap());
locatorNode->getLocator()->setPosition(osg::Vec3d(playgroundLongitude, playgroundLatitude, playgroundAltitude));
locatorNode->getLocator()->setOrientation(osg::Vec3d(playgroundHeading, playgroundElevation, playgroundBank));
locatorNode->getLocator()->getLocatorMatrix(locatorMatrix);
inverseLocatorMatrix.invert(locatorMatrix);
delete locatorNode;
}
}
Coord OsgGeographicCoordinateSystem::computePlaygroundCoordinate(const GeoCoord& geographicCoordinate) const
{
auto mapSrs = mapNode->getMapSRS();
osg::Vec3d ecefCoordinate;
mapSrs->getGeographicSRS()->transform(osg::Vec3d(geographicCoordinate.longitude, geographicCoordinate.latitude, geographicCoordinate.altitude), mapSrs->getECEF(), ecefCoordinate);
auto playgroundCoordinate = osg::Vec4d(ecefCoordinate.x(), ecefCoordinate.y(), ecefCoordinate.z(), 1.0) * inverseLocatorMatrix;
return Coord(playgroundCoordinate.x(), playgroundCoordinate.y(), playgroundCoordinate.z());
}
GeoCoord OsgGeographicCoordinateSystem::computeGeographicCoordinate(const Coord& playgroundCoordinate) const
{
auto ecefCoordinate = osg::Vec4d(playgroundCoordinate.x, playgroundCoordinate.y, playgroundCoordinate.z, 1.0) * locatorMatrix;
auto mapSrs = mapNode->getMapSRS();
osg::Vec3d geographicCoordinate;
mapSrs->getECEF()->transform(osg::Vec3d(ecefCoordinate.x(), ecefCoordinate.y(), ecefCoordinate.z()), mapSrs->getGeographicSRS(), geographicCoordinate);
return GeoCoord(geographicCoordinate.y(), geographicCoordinate.x(), geographicCoordinate.z());
}
#endif // WITH_OSG
} // namespace inet
| 46.718447 | 183 | 0.764131 | StarStuffSteve |
450b166cf90e2b1949aefc914880034459f7f1fe | 643 | cpp | C++ | mp_intro/cs225/HSLAPixel.cpp | keelimepi/CS225 | a98871095cc2d488c646a72acd2c28aceb2b3ae7 | [
"AFL-1.1"
] | null | null | null | mp_intro/cs225/HSLAPixel.cpp | keelimepi/CS225 | a98871095cc2d488c646a72acd2c28aceb2b3ae7 | [
"AFL-1.1"
] | null | null | null | mp_intro/cs225/HSLAPixel.cpp | keelimepi/CS225 | a98871095cc2d488c646a72acd2c28aceb2b3ae7 | [
"AFL-1.1"
] | null | null | null | /**
* @file HSLAPixel.cpp
* Implementation of the HSLAPixel class for use in with the PNG library.
*
* @author CS 225: Data Structures
* @version 2018r1-lab1
*/
#include "HSLAPixel.h"
#include <cmath>
#include <iostream>
using namespace std;
namespace cs225 {
HSLAPixel::HSLAPixel(){
h = 0;
l = 1;
s = 0;
a = 1;
}
HSLAPixel::HSLAPixel(double hue, double saturation, double luminance){
h = hue;
l = luminance;
s = saturation;
a = 1;
}
HSLAPixel::HSLAPixel (double hue, double saturation, double luminance, double alpha){
h = hue;
l = luminance;
s = saturation;
a = alpha;
}
}
| 18.911765 | 87 | 0.625194 | keelimepi |
45130662f9cba5a329e71c7b0d40202f24cf49e4 | 1,227 | hpp | C++ | source/plc/include/document/BINARY_ARITHMETIC_OP.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | source/plc/include/document/BINARY_ARITHMETIC_OP.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | source/plc/include/document/BINARY_ARITHMETIC_OP.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | // This file was generated using Parlex's cpp_generator
#ifndef INCLUDED_BINARY_ARITHMETIC_OP_HPP
#define INCLUDED_BINARY_ARITHMETIC_OP_HPP
#include <optional>
#include <variant>
#include <vector>
#include "erased.hpp"
#include "parlex/detail/abstract_syntax_tree.hpp"
#include "parlex/detail/builtins.hpp"
#include "parlex/detail/document.hpp"
#include "plange_grammar.hpp"
namespace plc {
struct ADDITION;
struct ADD_SUB;
struct DIVISION;
struct EXPONENTIATION;
struct INTEGER_DIVISION;
struct MODULATION;
struct MULTIPLICATIVE_OP;
struct SHIFTL;
struct SHIFTR;
struct SUBTRACTION;
typedef std::variant<
erased<ADD_SUB>,
erased<ADDITION>,
erased<DIVISION>,
erased<EXPONENTIATION>,
erased<INTEGER_DIVISION>,
erased<MODULATION>,
erased<MULTIPLICATIVE_OP>,
erased<SHIFTL>,
erased<SHIFTR>,
erased<SUBTRACTION>
> BINARY_ARITHMETIC_OP_base;
struct BINARY_ARITHMETIC_OP: BINARY_ARITHMETIC_OP_base {
static BINARY_ARITHMETIC_OP build(parlex::detail::ast_node const & n);
explicit BINARY_ARITHMETIC_OP(BINARY_ARITHMETIC_OP_base const & value) : BINARY_ARITHMETIC_OP_base(value) {}
static parlex::detail::state_machine const & state_machine();
};
} // namespace plc
#endif //INCLUDED_BINARY_ARITHMETIC_OP_HPP
| 22.722222 | 109 | 0.804401 | dlin172 |
451627b81473489b5c8e9bf72a7fd7d0ddc69ae6 | 155 | cpp | C++ | Source/VRCode/VRCodeGameModeBase.cpp | sclark39/UE-Virtual-Reality-Code-Sample | a4c6a4b414cf0649c445e0ba53778ea8a776820c | [
"MIT"
] | 32 | 2017-05-03T05:33:31.000Z | 2020-11-07T17:46:13.000Z | Source/VRCode/VRCodeGameModeBase.cpp | sclark39/UE-Virtual-Reality-Code-Sample | a4c6a4b414cf0649c445e0ba53778ea8a776820c | [
"MIT"
] | 7 | 2017-05-03T17:26:54.000Z | 2018-03-25T23:02:02.000Z | Source/VRCode/VRCodeGameModeBase.cpp | sclark39/UE-Virtual-Reality-Code-Sample | a4c6a4b414cf0649c445e0ba53778ea8a776820c | [
"MIT"
] | 9 | 2017-05-03T06:12:58.000Z | 2022-01-22T18:00:35.000Z | /*
* Author: Skyler Clark (@sclark39)
* Website: http://skylerclark.com
* License: MIT License
*/
#include "VRCode.h"
#include "VRCodeGameModeBase.h"
| 11.923077 | 34 | 0.690323 | sclark39 |
93251fe2f445ac805be3454f514f7283cb729983 | 8,551 | cpp | C++ | lib/src/MOLAMRTimeDependent/AMRLevelConsFactory.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | null | null | null | lib/src/MOLAMRTimeDependent/AMRLevelConsFactory.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | null | null | null | lib/src/MOLAMRTimeDependent/AMRLevelConsFactory.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 1 | 2021-04-13T19:06:43.000Z | 2021-04-13T19:06:43.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include "AMRLevel.H"
#include "AMRLevelCons.H"
#include "AMRLevelConsFactory.H"
#include "NamespaceHeader.H"
AMRLevelConsFactory::AMRLevelConsFactory()
{
setDefaultValues();
}
//////////////////////////////////////////////////////////////////////////////
// Virtual constructor
AMRLevel* AMRLevelConsFactory::new_amrlevel() const
{
// Make sure everything is defined
CH_assert(isDefined());
// Create a new AMRLevelCons
AMRLevelCons* amrConsPtr = new AMRLevelCons();
// Set up new object
transferSettings(amrConsPtr);
// Return it
return (static_cast <AMRLevel*> (amrConsPtr));
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::transferSettings(AMRLevelCons* a_newPtr) const
{
CH_assert(a_newPtr != NULL);
a_newPtr->CFL(m_cfl);
a_newPtr->spaceOrder(m_spaceOrder);
a_newPtr->limitFaceValues(m_limitFaceValues);
a_newPtr->highOrderLimiter(m_highOrderLimiter);
a_newPtr->useFlattening(m_useFlattening);
a_newPtr->initialAverage(m_initialAverage);
a_newPtr->noPPM(m_noPPM);
a_newPtr->doDeconvolution(m_doDeconvolution);
a_newPtr->doFaceDeconvolution(m_doFaceDeconvolution);
a_newPtr->useArtificialViscosity(m_useArtificialViscosity);
a_newPtr->artificialViscosity(m_artificialViscosity);
a_newPtr->useArtVisc(m_useArtVisc);
a_newPtr->ratioArtVisc(m_ratioArtVisc);
a_newPtr->forwardEuler(m_forwardEuler);
a_newPtr->enforceMinVal(m_enforceMinVal, m_minVal);
a_newPtr->domainLength(m_domainLength);
a_newPtr->refinementThreshold(m_refineThresh);
a_newPtr->refinementIsScaled(m_refinementIsScaled);
a_newPtr->tagPressure(m_tagPressure);
a_newPtr->tagVorticity(m_tagVorticity);
a_newPtr->tagBufferSize(m_tagBufferSize);
a_newPtr->initialDtMultiplier(m_initialDtMultiplier);
a_newPtr->verbosity(m_verbosity);
a_newPtr->molPhysics(m_molPhysics);
}
//////////////////////////////////////////////////////////////////////////////
AMRLevelConsFactory::~AMRLevelConsFactory()
{
if (m_molPhysics != NULL)
{
delete m_molPhysics;
m_molPhysics = NULL;
}
}
//////////////////////////////////////////////////////////////////////////////
// CFL number
void AMRLevelConsFactory::CFL(Real a_cfl)
{
m_cfl = a_cfl;
m_cflSet = true;
}
//////////////////////////////////////////////////////////////////////////////
// spatial order of accuracy
void AMRLevelConsFactory::spaceOrder(int a_spaceOrder)
{
m_spaceOrder = a_spaceOrder;
}
//////////////////////////////////////////////////////////////////////////////
// if true, limit face values in advection
// spatial order of accuracy
void AMRLevelConsFactory::limitFaceValues(bool a_limitFaceValues)
{
m_limitFaceValues = a_limitFaceValues;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::highOrderLimiter(bool a_highOrderLimiter)
{
m_highOrderLimiter = a_highOrderLimiter;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::initialAverage(bool a_initialAverage)
{
m_initialAverage = a_initialAverage;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::useFlattening(bool a_useFlattening)
{
m_useFlattening = a_useFlattening;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::noPPM(bool a_noPPM)
{
m_noPPM = a_noPPM;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::doDeconvolution(bool a_doDeconvolution)
{
m_doDeconvolution = a_doDeconvolution;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::doFaceDeconvolution(bool a_doFaceDeconvolution)
{
m_doFaceDeconvolution = a_doFaceDeconvolution;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::useArtificialViscosity(bool a_useArtificialViscosity)
{
m_useArtificialViscosity = a_useArtificialViscosity;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::artificialViscosity(Real a_artificialViscosity)
{
m_artificialViscosity = a_artificialViscosity;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::useArtVisc(bool a_useArtVisc)
{
m_useArtVisc = a_useArtVisc;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::ratioArtVisc(Real a_ratioArtVisc)
{
m_ratioArtVisc = a_ratioArtVisc;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::forwardEuler(bool a_forwardEuler)
{
m_forwardEuler = a_forwardEuler;
}
//////////////////////////////////////////////////////////////////////////////
/// sets whether to enforce a min value in advection, along with value
void AMRLevelConsFactory::enforceMinVal(bool a_enforceMinVal, Real a_minVal)
{
m_enforceMinVal = a_enforceMinVal;
if (m_enforceMinVal) m_minVal = a_minVal;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::verbosity(const int& a_verbosity)
{
m_verbosity = a_verbosity;
}
//////////////////////////////////////////////////////////////////////////////
// Physical dimension of the longest side of the domain
void AMRLevelConsFactory::domainLength(Real a_domainLength)
{
m_domainLength = a_domainLength;
m_domainLengthSet = true;
}
//////////////////////////////////////////////////////////////////////////////
// Refinement threshold
void AMRLevelConsFactory::refinementThreshold(Real a_refineThresh)
{
m_refineThresh = a_refineThresh;
m_refineThreshSet = true;
}
//////////////////////////////////////////////////////////////////////////////
// Set whether refinement threshold is scaled with dx
void AMRLevelConsFactory::refinementIsScaled(bool a_refinementIsScaled)
{
m_refinementIsScaled = a_refinementIsScaled;
}
//////////////////////////////////////////////////////////////////////////////
// Set whether to tag on pressure instead of on density
void AMRLevelConsFactory::tagPressure(bool a_tagPressure)
{
m_tagPressure = a_tagPressure;
}
//////////////////////////////////////////////////////////////////////////////
// Set whether to tag on vorticity instead of on density
void AMRLevelConsFactory::tagVorticity(bool a_tagVorticity)
{
m_tagVorticity = a_tagVorticity;
}
//////////////////////////////////////////////////////////////////////////////
// Tag buffer size
void AMRLevelConsFactory::tagBufferSize(int a_tagBufferSize)
{
m_tagBufferSize = a_tagBufferSize;
m_tagBufferSizeSet = true;
}
//////////////////////////////////////////////////////////////////////////////
void AMRLevelConsFactory::molPhysics(const MOLPhysics* const a_molPhysics)
{
m_molPhysics = a_molPhysics->new_molPhysics();
}
//////////////////////////////////////////////////////////////////////////////
// Initial dt multiplier
void AMRLevelConsFactory::initialDtMultiplier(Real a_initialDtMultiplier)
{
m_initialDtMultiplier = a_initialDtMultiplier;
m_initialDtMultiplierSet = true;
}
//////////////////////////////////////////////////////////////////////////////
// Check that everything is defined
bool AMRLevelConsFactory::isDefined() const
{
return (m_cflSet &&
m_domainLengthSet &&
m_refineThreshSet &&
m_tagBufferSizeSet &&
m_initialDtMultiplierSet);
}
//////////////////////////////////////////////////////////////////////////////
// Some default values
void AMRLevelConsFactory::setDefaultValues()
{
CFL(0.8);
spaceOrder(4);
limitFaceValues(false);
highOrderLimiter(true);
initialAverage(false);
useFlattening(false);
useArtVisc(false);
noPPM(false);
doDeconvolution(true);
doFaceDeconvolution(true);
useArtificialViscosity(false);
artificialViscosity(0.);
ratioArtVisc(0.);
forwardEuler(false);
enforceMinVal(false, -1);
domainLength(1.0);
refinementThreshold(0.2);
refinementIsScaled(false);
tagPressure(false);
tagVorticity(false);
tagBufferSize(2);
initialDtMultiplier(0.1);
m_verbosity = 0;
m_molPhysics = NULL;
}
#include "NamespaceFooter.H"
| 27.407051 | 79 | 0.561689 | rmrsk |
932a023700420b9dde9e593e73469422d9f64e43 | 13,732 | cpp | C++ | src/ORB_feature.cpp | Bonoy0328/robot_description | 288af718fecf7122e35eb0cb8fead15fa72ca5e3 | [
"Apache-2.0"
] | null | null | null | src/ORB_feature.cpp | Bonoy0328/robot_description | 288af718fecf7122e35eb0cb8fead15fa72ca5e3 | [
"Apache-2.0"
] | null | null | null | src/ORB_feature.cpp | Bonoy0328/robot_description | 288af718fecf7122e35eb0cb8fead15fa72ca5e3 | [
"Apache-2.0"
] | null | null | null | #include "ros/ros.h"
// 话题同步处理
#include "message_filters/subscriber.h"
#include "message_filters/synchronizer.h"
#include "message_filters/sync_policies/approximate_time.h"
// opencv接口
#include "cv_bridge/cv_bridge.h"
#include "image_transport/image_transport.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include <opencv2/calib3d/calib3d.hpp>
//ros消息类型头文件
#include "sensor_msgs/Image.h"
#include "sensor_msgs/image_encodings.h"
//系统指令头文件
#include <boost/thread/thread.hpp>
#include <boost/foreach.hpp>
// pcl点云库
#include <pcl/io/pcd_io.h>
#include "pcl_ros/point_cloud.h"
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_types.h>
#include <pcl/PCLPointCloud2.h>
#include <pcl/conversions.h>
#include <pcl_ros/transforms.h>
//内部时钟
#include <chrono>
#include "sensor_msgs/Imu.h"
#include "eigen3/Eigen/Core"
#include <sophus/se3.hpp>
#include <iostream>
//g2o
#include <g2o/core/base_vertex.h>
#include <g2o/core/base_unary_edge.h>
#include <g2o/core/block_solver.h>
#include <g2o/core/optimization_algorithm_gauss_newton.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include <g2o/solvers/dense/linear_solver_dense.h>
using namespace std;
using namespace cv;
sensor_msgs::Image image_;
cv::Mat cvColorImgMat;
cv::Mat cvColorImgMat2;
pcl::PCLPointCloud2 pcl_pc2;
pcl::PCLPointCloud2 pcl_pc2l;
uint8_t flag=0;
long int cnt = 0;
typedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;
typedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;
/// vertex and edges used in g2o ba
class VertexPose : public g2o::BaseVertex<6, Sophus::SE3d> {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
virtual void setToOriginImpl() override {
_estimate = Sophus::SE3d();
}
/// left multiplication on SE3
virtual void oplusImpl(const double *update) override {
Eigen::Matrix<double, 6, 1> update_eigen;
update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];
_estimate = Sophus::SE3d::exp(update_eigen) * _estimate;
}
virtual bool read(istream &in) override {}
virtual bool write(ostream &out) const override {}
};
/// g2o edge
class EdgeProjectXYZRGBDPoseOnly : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPose> {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
EdgeProjectXYZRGBDPoseOnly(const Eigen::Vector3d &point) : _point(point) {}
virtual void computeError() override {
const VertexPose *pose = static_cast<const VertexPose *> ( _vertices[0] );
_error = _measurement - pose->estimate() * _point;
}
virtual void linearizeOplus() override {
VertexPose *pose = static_cast<VertexPose *>(_vertices[0]);
Sophus::SE3d T = pose->estimate();
Eigen::Vector3d xyz_trans = T * _point;
_jacobianOplusXi.block<3, 3>(0, 0) = -Eigen::Matrix3d::Identity();
_jacobianOplusXi.block<3, 3>(0, 3) = Sophus::SO3d::hat(xyz_trans);
}
bool read(istream &in) {}
bool write(ostream &out) const {}
protected:
Eigen::Vector3d _point;
};
void pose_estimation_3d3d(const vector<Point3f> &pts1,
const vector<Point3f> &pts2,
Mat &R, Mat &t) {
Point3f p1, p2; // center of mass
int N = pts1.size();
for (int i = 0; i < N; i++) {
p1 += pts1[i];
p2 += pts2[i];
}
p1 = Point3f(Vec3f(p1) / N);
p2 = Point3f(Vec3f(p2) / N);
vector<Point3f> q1(N), q2(N); // remove the center
for (int i = 0; i < N; i++) {
q1[i] = pts1[i] - p1;
q2[i] = pts2[i] - p2;
}
// compute q1*q2^T
Eigen::Matrix3d W = Eigen::Matrix3d::Zero();
for (int i = 0; i < N; i++) {
W += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();
}
cout << "W=" << W << endl;
// SVD on W
Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::Matrix3d U = svd.matrixU();
Eigen::Matrix3d V = svd.matrixV();
cout << "U=" << U << endl;
cout << "V=" << V << endl;
Eigen::Matrix3d R_ = U * (V.transpose());
if (R_.determinant() < 0) {
R_ = -R_;
}
Eigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);
// convert to cv::Mat
R = (Mat_<double>(3, 3) <<
R_(0, 0), R_(0, 1), R_(0, 2),
R_(1, 0), R_(1, 1), R_(1, 2),
R_(2, 0), R_(2, 1), R_(2, 2)
);
t = (Mat_<double>(3, 1) << t_(0, 0), t_(1, 0), t_(2, 0));
}
void bundleAdjustmentGaussNewton(const VecVector3d &points_3d,const VecVector2d &points_2d,const cv::Mat &K,Sophus::SE3d &pose) {
typedef Eigen::Matrix<double,6,1> Vector6d;
const int iterations = 10;
double cost = 0,lastCost = 0;
double fx = K.at<double>(0,0);
double fy = K.at<double>(1,1);
double cx = K.at<double>(0,2);
double cy = K.at<double>(1,2);
for(int iter = 0;iter < iterations; iter++){
Eigen::Matrix<double,6,6> H = Eigen::Matrix<double,6,6>::Zero();
Vector6d b = Vector6d::Zero();
cost = 0;
//compute cost
for(int i = 0;i < points_3d.size(); i++){
Eigen::Vector3d pc = pose * points_3d[i];
double inv_z = 1.0 / pc[2];
double inv_z2 = inv_z * inv_z;
Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx,fy * pc[1] / pc[2] + cy);
Eigen::Vector2d e = points_2d[i] - proj;
cost+=e.squaredNorm();
Eigen::Matrix<double,2,6> J;
J << -fx * inv_z,
0,
fx * pc[0] * inv_z2,
fx * pc[0] * pc[1] * inv_z2,
-fx - fx * pc[0] * pc[0] * inv_z2,
fx * pc[1] * inv_z,
0,
-fy * inv_z,
fy * pc[1] * inv_z2,
fy + fy * pc[1] * pc[1] * inv_z2,
-fy * pc[0] * pc[1] * inv_z2,
-fy * pc[0] * inv_z;
H += J.transpose() * J;
b += -J.transpose() * e;
}
Vector6d dx;
dx = H.ldlt().solve(b);
if(isnan(dx[0])){
std::cout << "result is nan!" << std::endl;
break;
}
if(iter > 0 && cost >= lastCost){
// cost increase, update is not good
std::cout << "cost: " << cost << ", last cost: " << lastCost << std::endl;
break;
}
//update estimation
pose = Sophus::SE3d::exp(dx) * pose;
lastCost = cost;
std::cout << "iteration " << iter << " cost=" << std::setprecision(12) << cost << std::endl;
if(dx.norm() < 1e-6){
break;
}
}
std::cout << "pose by g-n \n" << pose.matrix() <<std::endl;
}
void callback(const sensor_msgs::ImuConstPtr& imu,const sensor_msgs::PointCloud2ConstPtr& point){
std::cout <<"this is quternion" << imu-> orientation.x << std::endl;
cv_bridge::CvImagePtr cvImagePtr;
pcl_conversions::toPCL(*point,pcl_pc2);
pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud);
ROS_INFO("Cloud:width = %d,height = %d",point->width,point->height);
try{
pcl::toROSMsg(*point,image_);
}catch(std::runtime_error e){
ROS_ERROR_STREAM("Error in converting cloud to image message: " << e.what());
}
try{
cvImagePtr = cv_bridge::toCvCopy(image_,sensor_msgs::image_encodings::BGR8);
}catch(cv_bridge::Exception e){
ROS_ERROR_STREAM("Cv_bridge Exception:" << e.what());
return;
}
cvColorImgMat = cvImagePtr->image;
if(flag==0){//如果是第一次进入,则和第一帧解算相同
// pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud_last);
cvColorImgMat2 = cvImagePtr->image;
flag =2;
}else{
// pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(pcl_pc2l,*temp_cloud_last);
}
std::vector<cv::KeyPoint> keypoints,keypoints2;
cv::Mat descriptors,descriptors2;
cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();
cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();
cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create("BruteForce-Hamming");
std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
detector->detect(cvColorImgMat,keypoints);
detector->detect(cvColorImgMat2,keypoints2);
descriptor->compute(cvColorImgMat,keypoints,descriptors);
descriptor->compute(cvColorImgMat2,keypoints2,descriptors2);
std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
ROS_INFO("extract ORB cost = %f seconds",time_used.count());
// cvColorImgMat2 = cvColorImgMat;
// cv::Mat outimg,outimg2;
// cv::drawKeypoints(cvColorImgMat,keypoints,outimg,cv::Scalar::all(-1),cv::DrawMatchesFlags::DEFAULT);
// cv::drawKeypoints(cvColorImgMat2,keypoints2,outimg2,cv::Scalar::all(-1),cv::DrawMatchesFlags::DEFAULT);
// cv::imshow("colorview",outimg2);
// cv::imshow("ORB feature",outimg);
//match
std::vector<cv::DMatch> matches;
t1 = std::chrono::steady_clock::now();
try
{
matcher->match(descriptors,descriptors2,matches);
}
catch(const cv::Exception& e)
{
ROS_INFO(e.what());
}
t2 = std::chrono::steady_clock::now();
time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
ROS_INFO("match ORB cost %f seconds",time_used.count());
//choise better match
auto min_max = std::minmax_element(matches.begin(),matches.end(),
[](const cv::DMatch &m1,const cv::DMatch &m2){return m1.distance < m2.distance;});
double min_dist = min_max.first->distance;
double max_dist = min_max.second->distance;
std::vector<cv::DMatch> good_matches;
for (int i = 0; i < descriptors.rows; i++){
if(matches[i].distance <= std::max(2 * min_dist,30.0))
good_matches.push_back(matches[i]);
}
//获取3D点
cv::Point3f d;
std::vector<cv::Point3f> pts_3d,pts_3d_last;
std::vector<cv::Point2f> pts_2d,pts_2d_last;
BOOST_FOREACH(cv::DMatch m,good_matches){
d.x = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].x;
d.y = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].y;
d.z = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].z;
if(isnan(d.x)||isnan(d.y)||isnan(d.z))
continue;
pts_3d.push_back(d);
pts_2d.push_back(keypoints[m.queryIdx].pt);
// ROS_INFO("%f %f %f",d.x,d.y,d.z);
// ROS_INFO("%d %d",int(keypoints[m.queryIdx].pt.x),int(keypoints[m.queryIdx].pt.y));
}
std::cout << "3d-2s pairs: " << pts_3d.size() << std::endl;
cv::Mat K = (cv::Mat_<double>(3, 3) << 525.0, 0, 319.5, 0, 525.0, 239.5, 0, 0, 1);
//Opencv 解位姿
// t1 = std::chrono::steady_clock::now();
// cv::Mat r, t;
// cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t,false,CV_ITERATIVE); // 调用OpenCV 的 PnP 求解,可选择EPNP,DLS等方法
// cv::Mat R;
// cv::Rodrigues(r, R); // r为旋转向量形式,用Rodrigues公式转换为矩阵
// t2 = std::chrono::steady_clock::now();
// time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
// std::cout << "solve pnp in opencv cost time: " << time_used.count() << " seconds." << std::endl;
// std::cout << "R=" << std::endl << R << std::endl;
// std::cout << "t=" << std::endl << t << std::endl;
//gaussNewton 解位姿
VecVector3d pts_3d_eigen;
VecVector2d pts_2d_eigen;
for (size_t i = 0; i < pts_3d.size(); ++i) {
pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));
pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));
}
std::cout << "calling bundle adjustment by gauss newton " << std::endl;
Sophus::SE3d pose_gn;
t1 = std::chrono::steady_clock::now();
bundleAdjustmentGaussNewton(pts_3d_eigen,pts_2d_eigen,K,pose_gn);
t2 = std::chrono::steady_clock::now();
time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << "solve pnp by gauss newton cost time: " << time_used.count() << " seconds." << std::endl;
//保存上一帧的数据
pcl_pc2l = pcl_pc2;
cvColorImgMat2 = cvColorImgMat;
//draw the answer
cv::Mat img_match;
cv::Mat img_goodmatch;
cv::drawMatches(cvColorImgMat,keypoints,cvColorImgMat2,keypoints2,good_matches,img_goodmatch);
cv::imshow("good matches",img_goodmatch);
// cv::imshow("grayview",cvGrayImgMat);
cv::waitKey(5);
}
int main(int argc, char *argv[])
{
ros::init(argc,argv,"grayView");
ros::NodeHandle nh_;
message_filters::Subscriber<sensor_msgs::Imu> sub(nh_,"/imu_data",1);
message_filters::Subscriber<sensor_msgs::PointCloud2> sub2(nh_,"/camera/depth_registered/points",1);
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Imu,sensor_msgs::PointCloud2> MySync;
message_filters::Synchronizer<MySync> sync(MySync(10),sub,sub2);
sync.registerCallback(boost::bind(&callback,_1,_2));
// cv::namedWindow("colorview",cv::WINDOW_NORMAL);
// cv::moveWindow("colorview",100,100);
// cv::namedWindow("grayview",cv::WINDOW_NORMAL);
// cv::moveWindow("grayview",600,100);
ros::spin();
return 0;
}
| 37.519126 | 129 | 0.627585 | Bonoy0328 |
932bed2ac49b9b94d4292ffefbac823692b46436 | 12,561 | cpp | C++ | src/core/ItemModelLeftovers_forFuture.cpp | varunamachi/tanyatu | ce055e0fb0b688054fe19ef39b09a6ca655e2457 | [
"MIT"
] | 1 | 2018-01-07T18:11:04.000Z | 2018-01-07T18:11:04.000Z | src/core/ItemModelLeftovers_forFuture.cpp | varunamachi/tanyatu | ce055e0fb0b688054fe19ef39b09a6ca655e2457 | [
"MIT"
] | null | null | null | src/core/ItemModelLeftovers_forFuture.cpp | varunamachi/tanyatu | ce055e0fb0b688054fe19ef39b09a6ca655e2457 | [
"MIT"
] | null | null | null | // __START__( IAudioLibrary )
int StandardAudioLibrary::rowCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return m_itemList->size();
}
int StandardAudioLibrary::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return 5;
}
QVariant StandardAudioLibrary::data( const QModelIndex &index, int role ) const
{
if( ! index.isValid() || index.row() >= m_tracks.size() ) {
return QVariant();
}
if ( role == Qt::TextAlignmentRole ) {
return int ( Qt::AlignLeft | Qt::AlignVCenter );
}
else if ( role == Qt::DisplayRole ) {
Model::StoredAudio *source = m_itemList->at( index.row() );
switch( index.column() ) {
case 0: return source->id();
case 1: return source->title();
case 2: return source->artist();
case 3: return source->album();
case 4: return int( source->rating() );
}
}
else if( role == Qt::ToolTipRole ) {
Model::StoredAudio *source = m_itemList->at( index.row() );
QString tooltip = QString() +
tr( "Title : <b>" ) + source->title() + "</b><br>" +
tr( "Artist : <b>" ) + source->artist() + "</b><br>" +
tr( "Album : <b>" ) + source->album() + "</b>" ;
return tooltip;
}
//??
else if( role == Qt::SizeHintRole ) {
return QSize( 0, 18 );
}
return QVariant();
}
QVariant StandardAudioLibrary::headerData( int section,
Qt::Orientation orientation,
int role ) const
{
Q_UNUSED( orientation )
if ( role == Qt::TextAlignmentRole ) {
return int( Qt::AlignLeft | Qt::AlignVCenter );
}
else if ( role == Qt::DisplayRole ) {
switch( section ) {
case 0: return tr( "Id" );
case 1: return tr( "Title" );
case 2: return tr( "Artist" );
case 3: return tr( "Album" );
case 4: return tr( "Rating" );
}
}
return QVariant();
}
QModelIndex StandardAudioLibrary::index( int row, int column,
const QModelIndex &parent ) const
{
Q_UNUSED( parent )
return createIndex(row, column);
}
QModelIndex StandardAudioLibrary::parent( const QModelIndex &child ) const
{
Q_UNUSED( child )
return QModelIndex();
}
bool StandardAudioLibrary::hasChildren( const QModelIndex &parent ) const
{
if(! parent.isValid()) {
return true;
}
return false;
}
Qt::ItemFlags StandardAudioLibrary::flags( const QModelIndex &index ) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags( index );
if( index.column() == 4 ) {
return flags |= Qt::ItemIsEditable;
}
return flags;
}
bool StandardAudioLibrary::setData( const QModelIndex &index,
const QVariant &value,
int role )
{
Q_UNUSED( role );
if( index.column() == 4 ) {
Model::StoredAudio *item = m_itemList->at( index.row() );
setRating( item->id(), Utils::getRatingFromInt( value.toInt() ));
return true;
}
return false;
}
// __END__( IAudioLibrary )
//__START__( IHistoryManager )
int StdHistoryManager::rowCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent )
return m_history.size();
}
int StdHistoryManager::columnCount(const QModelIndex &parent) const
{
Q_UNUSED( parent );
return 5;
}
QVariant StdHistoryManager::data(const QModelIndex &index, int role) const
{
if( ! index.isValid() || index.row() >= m_history.size() ) {
return QVariant();
}
if( role == Qt::DisplayRole ) {
QPair< QString, QDateTime > *history = m_history.at( index.row() );
Model::StoredAudio *track = T::get()->audioLib()->item(
history->first );
switch( index.column() ) {
case 0: return track->id();
case 1: return track->title();
case 2: return track->artist();
case 3: return track->album();
case 4: return history->second.toString();
}
}
else if( role == Qt::TextAlignmentRole ) {
return int( Qt::AlignLeft | Qt::AlignVCenter );
}
else if( role == Qt::SizeHintRole ) {
return QSize( 0, 18 );
}
else if( role == Qt::FontRole ) {
return QFont( "Droid Sans", 9 );
}
return QVariant();
}
QVariant StdHistoryManager::headerData(
int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED( orientation );
if( role == Qt::DisplayRole ) {
switch( section ) {
case 0: return tr("id");
case 1: return tr("Title");
case 2: return tr("Artist");
case 3: return tr("Album");
case 4: return tr("Time");
}
}
return QVariant();
}
QModelIndex StdHistoryManager::index(
int row, int column, const QModelIndex &parent) const
{
Q_UNUSED( parent )
return createIndex( row, column );
}
QModelIndex StdHistoryManager::parent(const QModelIndex &child) const
{
Q_UNUSED( child );
return QModelIndex();
}
bool StdHistoryManager::hasChildren(const QModelIndex &parent) const
{
if( ! parent.isValid() ) {
return true;
}
return false;
}
//__END__( IHistoryManager )
//__START__( IPlaylistManager )
int StdPlaylistManager::rowCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return m_itemList->size();
}
int StdPlaylistManager::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return 4;
}
QVariant StdPlaylistManager::data(
const QModelIndex &index, int role ) const
{
if( ! index.isValid()
|| m_itemList->isEmpty()
|| index.row() >= m_itemList->size() ) {
return QVariant();
}
if ( role == Qt::TextAlignmentRole ) {
return int ( Qt::AlignLeft | Qt::AlignVCenter );
}
else if ( role == Qt::DisplayRole ) {
Model::SavedPlaylist *plist = m_itemList->at( index.row() );
switch( index.column() ) {
case 0: return plist->name();
case 1: return numTracksIn( plist->name() );
case 2: return plist->playCount();
case 3: return plist->rating();
}
}
//?? Settings???
else if( role == Qt::SizeHintRole ) {
return QSize( 0, 18 );
}
else if( role == Qt::FontRole ) {
return QFont( "Droid Sans", 9 );
}
return QVariant();
}
QVariant StdPlaylistManager::headerData( int section,
Qt::Orientation orientation,
int role ) const
{
Q_UNUSED( orientation )
if ( role == Qt::TextAlignmentRole ) {
return int( Qt::AlignLeft | Qt::AlignVCenter );
}
else if ( role == Qt::DisplayRole ) {
switch( section ) {
case 0: return tr( "Name" );
case 1: return tr( "Tracks" );
case 2: return tr( "Played" );
case 3: return tr( "Rating" );
}
}
return QVariant();
}
QModelIndex StdPlaylistManager::index( int row, int column,
const QModelIndex &parent ) const
{
Q_UNUSED( parent )
return createIndex(row, column);
}
QModelIndex StdPlaylistManager::parent( const QModelIndex &child ) const
{
Q_UNUSED( child )
return QModelIndex();
}
bool StdPlaylistManager::hasChildren( const QModelIndex &parent ) const
{
if(! parent.isValid()) {
return true;
}
return false;
}
Qt::ItemFlags StdPlaylistManager::flags( const QModelIndex &index ) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags( index );
if( index.column() == 3 ) {
return flags |= Qt::ItemIsEditable;
}
return flags;
}
bool StdPlaylistManager::setData( const QModelIndex &index,
const QVariant &value,
int role )
{
Q_UNUSED( role );
if( index.column() == 3 ) {
Model::SavedPlaylist *plist = m_itemList->at( index.row() );
ratePlaylist( plist->name() , Utils::getRatingFromInt( value.toInt() ));
return true;
}
return false;
}
void StdPlaylistManager::loadPlaylist( const QString playlistName )
{
if( ! m_playlistToTrackIds.contains( playlistName ) ) {
QList< QString > *list = new QList< QString >();
if( T::get()->dataRetriever()->getPlaylistContent( playlistName,
*list )) {
m_playlistToTrackIds.insert( playlistName, list );
}
}
}
//__END__( IPlaylistManager )
//__START__( IPlayQueue )
int StdPlayQueue::rowCount( const QModelIndex& ) const {
return m_items.size();
}
int StdPlayQueue::columnCount( const QModelIndex& ) const {
return 2;
}
QVariant StdPlayQueue::data( const QModelIndex &index, int role ) const {
if ( ! index.isValid() || index.row() >= m_items.size() ) {
return QVariant();
}
if ( role == Qt::TextAlignmentRole ) {
if( index.column() == 0 ) {
return int (Qt::AlignLeft | Qt::AlignVCenter);
}
else {
return int (Qt::AlignRight | Qt::AlignVCenter);
}
}
//These are for the settings to decide... but for now this what we have
else if( role == Qt::SizeHintRole ) {
return QSize( 0, 16 );
}
else if( role == Qt::FontRole ) {
return QFont("Droid Sans", 8);
}
else {
Data::MediaItem *item = m_items[ index.row() ];
item->type();
if( item && item->type() == Data::Media_LocalAudio
|| item->type() == Data::Media_StoredAudio ) {
Data::AudioTrack *audioTrack = dynamic_cast<Data::AudioTrack *>
( item );
if ( role == Qt::DisplayRole ) {
switch( index.column() ) {
case 0: return audioTrack->title() +
( audioTrack->artist().isEmpty()
? "" :
( " - " + audioTrack->artist() ));
case 1: return Utils::getStringTime( audioTrack->duration() );
}
}
else if( role == Qt::ToolTipRole ) {
Data::AudioTrack *audioTrack =
dynamic_cast<Data::AudioTrack *>(
m_items.at( index.row() ) );
QString tooltip = QString() +
"Title : <b>"+ audioTrack->title() +"</b><br>"+
"Artist : <b>"+ audioTrack->artist() +"</b><br>"+
"Album : <b>"+ audioTrack->album() +"</b>";
return tooltip;
}
}
else if( item && item->type() == Data::Media_LocalVideo
|| item->type() == Data::Media_StoredVideo ) {
Data::VideoTrack *videoTrack = dynamic_cast< Data::VideoTrack *>(
item );
if ( role == Qt::DisplayRole ) {
switch( index.column() ) {
case 0: return videoTrack->name();
case 1: return Utils::getStringTime( videoTrack->duration() );
}
}
else if( role == Qt::ToolTipRole ) {
Data::AudioTrack *track = dynamic_cast< Data::AudioTrack *>(
m_items.at( index.row() ) );
QString tooltip = QString() +
"Title: <b>"+ videoTrack->name() +"</b><br>"+
"Path : <b>"+ track->url().toString() +"</b>";
return tooltip;
}
}
}
return QVariant();
}
QVariant StdPlayQueue::headerData( int section,
Qt::Orientation orientation,
int role ) const {
Q_UNUSED( role );
if( orientation == Qt::Horizontal ) {
switch( section ) {
case 0: return tr( "Track" );
case 1: return tr( "Len" );
}
}
else {
return "";
}
return QVariant();
}
QModelIndex StdPlayQueue::parent( const QModelIndex & ) const {
return QModelIndex();
}
bool StdPlayQueue::hasChildren( const QModelIndex &parent ) const {
if( ! parent.isValid() ) {
return true;
}
return false;
}
QModelIndex StdPlayQueue::index( int row, int column,
const QModelIndex & ) const {
return createIndex(row, column);
}
//__END__( IPlayQueue )
| 27.667401 | 80 | 0.537616 | varunamachi |
932d4d99a4ff68d871ba1aa7c6a279d610f38b9f | 5,956 | cpp | C++ | cpp/src/tests/nvgraph_plugin/nvgraph_gdf_louvain.cpp | rgsl888prabhu/cugraph | e030a2fe22ad308fba05d6146765a3c9aa865e5b | [
"Apache-2.0"
] | null | null | null | cpp/src/tests/nvgraph_plugin/nvgraph_gdf_louvain.cpp | rgsl888prabhu/cugraph | e030a2fe22ad308fba05d6146765a3c9aa865e5b | [
"Apache-2.0"
] | null | null | null | cpp/src/tests/nvgraph_plugin/nvgraph_gdf_louvain.cpp | rgsl888prabhu/cugraph | e030a2fe22ad308fba05d6146765a3c9aa865e5b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*
*/
#include <gtest/gtest.h>
#include <nvgraph/nvgraph.h>
#include <cugraph.h>
#include <algorithm>
#include "test_utils.h"
#include <rmm_utils.h>
TEST(nvgraph_louvain, success)
{
gdf_graph G;
std::vector<int> off_h = {0, 16, 25, 35, 41, 44, 48, 52, 56, 61, 63, 66, 67, 69, 74, 76, 78, 80, 82, 84, 87, 89, 91, 93, 98, 101, 104, 106, 110, 113, 117, 121, 127, 139, 156};
std::vector<int> ind_h = {1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31, 0, 2, 3, 7, 13, 17, 19, 21, 30, 0, 1, 3, 7, 8, 9, 13, 27, 28, 32, 0, 1, 2, 7, 12, 13, 0, 6, 10, 0,
6, 10, 16, 0, 4, 5, 16, 0, 1, 2, 3, 0, 2, 30, 32, 33, 2, 33, 0, 4, 5, 0, 0, 3, 0, 1, 2, 3, 33, 32, 33, 32, 33, 5, 6, 0, 1, 32, 33, 0, 1, 33, 32, 33, 0, 1, 32, 33, 25, 27, 29, 32, 33,
25, 27, 31, 23, 24, 31, 29, 33, 2, 23, 24, 33, 2, 31, 33, 23, 26, 32, 33, 1, 8, 32, 33, 0, 24, 25, 28, 32, 33, 2, 8, 14, 15, 18, 20, 22, 23, 29, 30, 31, 33, 8, 9, 13, 14, 15,
18, 19, 20, 22, 23, 26, 27, 28, 29, 30, 31, 32};
std::vector<float> w_h = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
gdf_column col_off, col_ind, col_w;
create_gdf_column(off_h,&col_off);
create_gdf_column(ind_h,&col_ind);
create_gdf_column(w_h ,&col_w);
ASSERT_EQ(gdf_adj_list_view(&G, &col_off, &col_ind, &col_w), GDF_SUCCESS);
if (!(G.adjList))
ASSERT_EQ(gdf_add_adj_list(&G), GDF_SUCCESS);
int no_vertex = off_h.size()-1;
int weighted = 0; //false
int has_init_cluster = 0; //false
float modularity = 0.0;
int num_level = 40;
int* best_cluster_vec = NULL;
cudaStream_t stream{nullptr};
ALLOC_TRY((void**)&best_cluster_vec, sizeof(int) * no_vertex, stream);
ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, nvgraphLouvain (CUDA_R_32I, CUDA_R_32F, no_vertex, ind_h.size(),
G.adjList->offsets->data, G.adjList->indices->data, G.adjList->edge_data->data, weighted, has_init_cluster, nullptr,
(void*) &modularity, (void*) best_cluster_vec, (void *)(&num_level)));
std::vector<int> cluster_id (34, -1);
cudaMemcpy ((void*) &(cluster_id[0]), best_cluster_vec, sizeof(int)*34, cudaMemcpyDeviceToHost);
int max = *max_element (cluster_id.begin(), cluster_id.end());
int min = *min_element (cluster_id.begin(), cluster_id.end());
ASSERT_EQ((min >= 0), 1);
ASSERT_EQ((modularity >= 0.402777), 1);
//printf ("max is %d and min is %d \n", max, min);
//printf ("Modularity is %f \n", modularity);
ALLOC_FREE_TRY (best_cluster_vec, stream);
}
TEST(nvgraph_louvain_grmat, success)
{
gdf_graph G;
gdf_column col_src, col_dest, col_weights;
size_t vertices = 0, edges = 0;
char argv[1024] = "grmat --rmat_scale=23 --rmat_edgefactor=16 --device=0 --normalized --quiet ";
col_src.data = nullptr;
col_src.dtype = GDF_INT32;
col_src.valid = nullptr;
col_dest.data = nullptr;
col_dest.dtype = GDF_INT32;
col_dest.valid = nullptr;
col_weights.data = nullptr;
col_weights.dtype = GDF_FLOAT32;
col_weights.valid = nullptr;
col_src.null_count = 0;
col_dest.null_count = 0;
col_weights.null_count = 0;
ASSERT_EQ(gdf_grmat_gen(argv, vertices, edges, &col_src, &col_dest, nullptr), GDF_SUCCESS);
cudaStream_t stream{nullptr};
ALLOC_TRY ((void**)&col_weights.data, sizeof(int) * edges, stream);
col_weights.size = edges;
std::vector<float> w_h (edges, (float)1.0);
cudaMemcpy (col_weights.data, (void*) &(w_h[0]), sizeof(float)*edges, cudaMemcpyHostToDevice);
ASSERT_EQ(gdf_edge_list_view(&G, &col_src, &col_dest, &col_weights), GDF_SUCCESS);
if (!(G.adjList))
{
ASSERT_EQ(gdf_add_adj_list(&G), GDF_SUCCESS);
}
int weighted = 1; //false
int has_init_cluster = 0; //false
float modularity = 0.0;
int num_level = 0;
int* best_cluster_vec = NULL;
ALLOC_TRY ((void**)&best_cluster_vec, sizeof(int) * vertices, stream);
ASSERT_EQ(NVGRAPH_STATUS_SUCCESS, nvgraphLouvain (CUDA_R_32I, CUDA_R_32F, vertices, edges, G.adjList->offsets->data, G.adjList->indices->data, G.adjList->edge_data->data, weighted, has_init_cluster, nullptr, (void*) &modularity, (void*) best_cluster_vec, (void *)(&num_level)));
std::vector<int> cluster_id (vertices, -1);
cudaMemcpy ((void*) &(cluster_id[0]), best_cluster_vec, sizeof(int)*vertices, cudaMemcpyDeviceToHost);
int max = *max_element (cluster_id.begin(), cluster_id.end());
int min = *min_element (cluster_id.begin(), cluster_id.end());
ASSERT_EQ((min >= 0), 1);
ASSERT_EQ((modularity >= 0.002875), 1);
ALLOC_FREE_TRY (best_cluster_vec, stream);
ALLOC_FREE_TRY(col_src.data, stream);
ALLOC_FREE_TRY(col_dest.data, stream);
ALLOC_FREE_TRY(col_weights.data, stream);
}
int main(int argc, char **argv) {
srand(42);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 42.542857 | 280 | 0.62861 | rgsl888prabhu |
932f81318ce3f932974860c14b7dc9a2e378e310 | 979 | cpp | C++ | server/Common/Packets/GCExchangeSynchLock.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 3 | 2018-06-19T21:37:38.000Z | 2021-07-31T21:51:40.000Z | server/Common/Packets/GCExchangeSynchLock.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | null | null | null | server/Common/Packets/GCExchangeSynchLock.cpp | viticm/web-pap | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | [
"BSD-3-Clause"
] | 13 | 2015-01-30T17:45:06.000Z | 2022-01-06T02:29:34.000Z | #include "stdafx.h"
// GCExchangeSynchLock.cpp
//
/////////////////////////////////////////////////////
#include "GCExchangeSynchLock.h"
BOOL GCExchangeSynchLock::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_IsBoth), sizeof(BYTE));
iStream.Read( (CHAR*)(&m_IsMyself), sizeof(BYTE));
iStream.Read( (CHAR*)(&m_IsLocked), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
BOOL GCExchangeSynchLock::Write( SocketOutputStream& oStream )const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_IsBoth), sizeof(BYTE));
oStream.Write( (CHAR*)(&m_IsMyself), sizeof(BYTE));
oStream.Write( (CHAR*)(&m_IsLocked), sizeof(BYTE));
return TRUE ;
__LEAVE_FUNCTION
return FALSE ;
}
UINT GCExchangeSynchLock::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return GCExchangeSynchLockHandler::Execute( this, pPlayer ) ;
__LEAVE_FUNCTION
return FALSE ;
}
| 19.979592 | 69 | 0.636364 | viticm |
9333a36a47e1f07b434bdf818712e6c7d76e51a8 | 970 | cpp | C++ | DECypher_app/file_io.cpp | RealKC/HN_DECutils | d4baa7c66b4ad4810a18858ff45d8d5c4f6b94fb | [
"MIT"
] | null | null | null | DECypher_app/file_io.cpp | RealKC/HN_DECutils | d4baa7c66b4ad4810a18858ff45d8d5c4f6b94fb | [
"MIT"
] | 1 | 2019-02-09T19:28:00.000Z | 2019-02-09T19:29:35.000Z | DECypher_app/file_io.cpp | RealKC/HN_DECutils | d4baa7c66b4ad4810a18858ff45d8d5c4f6b94fb | [
"MIT"
] | 1 | 2019-02-06T19:22:05.000Z | 2019-02-06T19:22:05.000Z | #include <numeric>
#include <string>
#include "file_io.hpp"
namespace DECypher
{
// This function was created using a bunch of stackoverflow posts
// Please help improve it
// Some of the SO posts I used are
// https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c
// https://stackoverflow.com/questions/10712117/how-to-count-the-characters-in-a-text-file
std::string readWholeFile(std::string_view pathToFile)
{
std::string ret;
std::ifstream file(std::string(pathToFile), std::ios::in | std::ios::binary | std::ios::ate);
// opens file directly at the end
if (file.is_open()) {
ret.reserve(static_cast<std::size_t>(file.gcount()));
file.seekg(0, std::ios::beg);
file.read(ret.data(), ret.capacity()); // this will work as of C++17
file.close();
return ret;
} else {
//TODO: throw an exception when I stop being lazy
}
}
} // DECypher
| 28.529412 | 111 | 0.66701 | RealKC |
9335ba90bd5153ac4ee7261ae3a47225aeb4653b | 1,237 | hpp | C++ | Pods/Realm/include/core/realm/util/misc_errors.hpp | Jethro87/DevSwitch | 0ff977fb0e1225b58304e2b46ddb129abc5b9fbe | [
"MIT"
] | 1,562 | 2020-08-19T00:30:37.000Z | 2022-03-31T15:15:22.000Z | Pods/Realm/include/core/realm/util/misc_errors.hpp | Jethro87/DevSwitch | 0ff977fb0e1225b58304e2b46ddb129abc5b9fbe | [
"MIT"
] | 2,265 | 2016-09-27T13:01:26.000Z | 2022-03-31T17:55:37.000Z | Pods/Realm/include/core/realm/util/misc_errors.hpp | Jethro87/DevSwitch | 0ff977fb0e1225b58304e2b46ddb129abc5b9fbe | [
"MIT"
] | 330 | 2015-04-18T07:35:28.000Z | 2022-01-05T07:26:10.000Z | /*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#ifndef REALM_UTIL_MISC_ERRORS_HPP
#define REALM_UTIL_MISC_ERRORS_HPP
#include <system_error>
namespace realm {
namespace util {
namespace error {
enum misc_errors {
unknown = 1,
};
std::error_code make_error_code(misc_errors);
} // namespace error
} // namespace util
} // namespace realm
namespace std {
template <>
class is_error_code_enum<realm::util::error::misc_errors> {
public:
static const bool value = true;
};
} // namespace std
#endif // REALM_UTIL_MISC_ERRORS_HPP
| 24.74 | 76 | 0.650768 | Jethro87 |
93378fb8ae4fb83dff0f6d027a152ecdb2d0a69e | 279 | hpp | C++ | APairOfSquares.hpp | ThePythonator/A-Pair-Of-Squares-32blit | d49866575c8b2a619ed0db07d09a538c10f76a4b | [
"MIT"
] | null | null | null | APairOfSquares.hpp | ThePythonator/A-Pair-Of-Squares-32blit | d49866575c8b2a619ed0db07d09a538c10f76a4b | [
"MIT"
] | null | null | null | APairOfSquares.hpp | ThePythonator/A-Pair-Of-Squares-32blit | d49866575c8b2a619ed0db07d09a538c10f76a4b | [
"MIT"
] | null | null | null | #pragma once
#include "engine/api.hpp"
//#include "engine/engine.hpp"
//#include "engine/input.hpp"
//#include "engine/save.hpp"
//#include "engine/version.hpp"
//#include "graphics/sprite.hpp"
//#include "graphics/color.hpp"
#include "Game.hpp"
//#include "InputManager.hpp"
| 19.928571 | 32 | 0.709677 | ThePythonator |
933a87887f64e5c02346fa3b08f4a88c3599d938 | 17,961 | cpp | C++ | engine/source/core/memory/details/memory.cpp | JasonYui/PolarisEngine | 5c96b8171fb1e7d07e6a68058664467940af4558 | [
"MIT"
] | null | null | null | engine/source/core/memory/details/memory.cpp | JasonYui/PolarisEngine | 5c96b8171fb1e7d07e6a68058664467940af4558 | [
"MIT"
] | null | null | null | engine/source/core/memory/details/memory.cpp | JasonYui/PolarisEngine | 5c96b8171fb1e7d07e6a68058664467940af4558 | [
"MIT"
] | null | null | null | //#include "precompiled_core.hpp"
#include "core_minimal_private.hpp"
#include "memory/memory.hpp"
#include "memory/malloc_interface.hpp"
#include "math/limit.hpp"
namespace Engine
{
IMalloc* GMalloc = nullptr;
void* Memory::Malloc(size_t size)
{
return Malloc(size, PlatformMemory::GetDefaultAlignment());
}
void* Memory::Malloc(size_t size, uint32 alignment)
{
IMalloc* gMalloc = GetGMalloc();
return gMalloc->Malloc(size, alignment);
}
void Memory::Free(void* ptr)
{
IMalloc* gMalloc = GetGMalloc();
gMalloc->Free(ptr);
}
void* Memory::Realloc(void* ptr, size_t newSize, uint32 alignment)
{
IMalloc* gMalloc = GetGMalloc();
return gMalloc->Realloc(ptr, newSize, alignment);
}
void Memory::Memcpy(void* dest, void* src, size_t size)
{
PlatformMemory::Memcpy(dest, src, size);
}
void Memory::Memmove(void* dest, void* src, size_t size)
{
PlatformMemory::Memmove(dest, src, size);
}
void Memory::Memset(void* dest, uint8 byte, size_t size)
{
PlatformMemory::Memset(dest, byte, size);
}
bool Memory::Memcmp(void* lBuffer, void* rBuffer, size_t size)
{
return PlatformMemory::Memcmp(lBuffer, rBuffer, size);
}
void Memory::MemmoveBits(uint32* startDest, int32 destOffset, uint32* startSrc, int32 srcOffset, uint32 bitCount)
{
if (bitCount <= 0)
{
return;
}
NormalizeOffset(startDest, destOffset);
NormalizeOffset(startSrc, srcOffset);
const uint32 uintBits = 32;
// If the Dest words are aligned with the Source Words, use the aligned version of MemmoveBits which requires fewer masking instructions.
// This also allows us to reduce complexity by not needing to handle the aligned case in the rest of this function.
const int32 DeltaOffset = destOffset - srcOffset;
if (DeltaOffset == 0)
{
//MemmoveBitsWordOrderAlignedInternal(startDest, startSrc, destOffset, bitCount);
const int32 endOffset = (destOffset + bitCount - 1) % uintBits + 1;
const uint32 startMask = MAX_UINT32 << destOffset;
const uint32 endMask = MAX_UINT32 >> (uintBits - endOffset);
// Calculate Start and Final Pointers
const uint32 offsetToLastWord = (destOffset + bitCount - 1) / MAX_UINT32;
uint32* const finalDest = startDest + offsetToLastWord;
const uint32* const finalSource = startSrc + offsetToLastWord;
// If the end word is the start word, use special handling to apply both the start mask and the end mask
if (offsetToLastWord == 0)
{
uint32 combinedMask = startMask & endMask;
*startDest = (*startDest & ~combinedMask) | (*startSrc & combinedMask);
return;
}
// If the Dest range and Source range overlap, we need to dest the words of dest in the same order as the direction from deststart to sourcestart, so that words are read from the destrange before being overwritten
// If Dest is less than Source, this is handled by forward iteration, which is the default since it is better for cache coherency
// If Source is less than Dest AND they overlap, we need to iterate backwards
const bool bRequiresBackward = (startSrc < startDest) & (startDest <= finalSource);
if (!bRequiresBackward)
{
*startDest = (*startDest & ~startMask) | (*startSrc & startMask);
uint32* currentDest = startDest + 1;
const uint32* CurrentSource = startSrc + 1;
while (currentDest < finalDest)
{
*currentDest++ = *CurrentSource++;
}
*finalDest = (*finalSource & endMask) | (*finalDest & ~endMask);
}
else
{
*finalDest = (*finalSource & endMask) | (*finalDest & ~endMask);
uint32* currentDest = finalDest - 1;
const uint32* currentSource = finalSource - 1;
while (currentDest > startDest)
{
*currentDest-- = *currentSource--;
}
*startDest = (*startDest & ~startMask) | (*startSrc & startMask);
}
return;
}
// Work out shifts for which bits of each source word are in each of the two dest words it overlaps
const uint32 firstBitInLowerDestWord = (DeltaOffset >= 0) ? DeltaOffset : DeltaOffset + uintBits;
const uint32 upShiftToLowerDestWord = firstBitInLowerDestWord; // The shift up distance to align with the dest positions of the lower dest word is equal to the position of the first bit in that word. We copy it to this variable name to make it easier to understand why we're using it as the shift
const uint32 downShiftToUpperDestWord = uintBits - firstBitInLowerDestWord; // The shift down distance to align with the upper dest word is the additive inverse of the shift-up distance
// Calculate Starting and Ending DestMasks
const uint32 endDestOffset = (destOffset + bitCount - 1) % uintBits + 1;
const uint32 startDestMask = destOffset == 0 ? MAX_UINT32 : (MAX_UINT32 << destOffset);
const uint32 endDestMask = MAX_UINT32 >> (uintBits - endDestOffset);
// Calculate Final Pointers
uint32* const finalDest = startDest + (destOffset + bitCount - 1) / uintBits;
const uint32* const finalSource = startSrc + (srcOffset + bitCount - 1) / uintBits;
// If the end word is the start word, use special handling to apply both the start mask and the end mask
if (startDest == finalDest)
{
uint32 combinedDestMask = startDestMask & endDestMask;
// Read the bits from the lower and upper source word of the dest word, if they are in the source range
// Note we are not allowed to try reading from any word that does not overlap the source range because it could pointing to inaccessible memory.
if (srcOffset < destOffset)
{
// The beginning of the first source word is past the beginning of the dest word, so it is the upper source word of the dest word
// It must therefore also be the last source word.
// Shift it up to the offset of the dest word.
const uint32 destBitsFromUpperSourceWord = *(startSrc) << upShiftToLowerDestWord;
*startDest = (*startDest & ~combinedDestMask) | (destBitsFromUpperSourceWord & combinedDestMask);
}
else if (startSrc == finalSource)
{
// The beginning of the first source word is before the beginning of the dest word, so it is the lower source word of the dest word
// But the write range ends at or before the end of the source word, so we only have a single source word
// Shift it down to the offset of the dest word
const uint32 destBitsFromLowerSourceWord = ((*startSrc) >> downShiftToUpperDestWord);
*startDest = (*startDest & ~combinedDestMask) | (destBitsFromLowerSourceWord & combinedDestMask);
}
else
{
// The beginning of the first source word is before the beginning of the dest word, so it is the lower source word of the dest word
// The write range ends after the end of the source word, so we also have an upper source word - finalSource is the upper source word of the destword
// Shift startSrc down and finalSource up
const uint32 destBitsFromLowerSourceWord = ((*startSrc) >> downShiftToUpperDestWord);
const uint32 destBitsFromUpperSourceWord = *(finalSource) << upShiftToLowerDestWord;
*startDest = (*startDest & ~combinedDestMask) | ((destBitsFromLowerSourceWord | destBitsFromUpperSourceWord) & combinedDestMask);
}
return;
}
// If the Dest range and Source range overlap, we need to dest the words of dest in the same order as the direction from deststart to sourcestart, so that words are read from the destrange before being overwritten
// If Dest is less than Source, this is handled by forward enumeration, which is the default since it is better for cache coherency
// If Source is less than Dest AND they overlap, we need to enumerate backwards
const bool bRequiresBackward = (startSrc < startDest) & (startDest <= finalSource);
if (!bRequiresBackward)
{
uint32* currentDest = startDest;
const uint32* currentSource = startSrc;
uint32 destBitsFromLowerSourceWord;
uint32 destBitsFromUpperSourceWord;
uint32 nextDestBitsFromLowerSourceWord;
// Write the first Dest word, handling whether the first source word is the lower source word or the upper source word and handling startDestMask
if (srcOffset < destOffset)
{
// The beginning of the first source word is past the beginning of the dest word, so it is the upper source word of the dest word, and we don't have bits from the lower source word
// Note we are not allowed to try reading from any word that does not overlap the source range because it could pointing to inaccessible memory, so we don't try to read the bits from currentSource-1
destBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord;
nextDestBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord; // Must read this before writing currentDest to handle overlap
*currentDest = (*currentDest & ~(startDestMask)) | (destBitsFromUpperSourceWord & startDestMask);
}
else
{
// The first source word is the lower source word of the first dest word
destBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord;
++currentSource;
destBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord;
nextDestBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord; // Must read this before writing currentDest to handle overlap
*currentDest = (*currentDest & ~(startDestMask)) | ((destBitsFromLowerSourceWord | destBitsFromUpperSourceWord) & startDestMask);
}
// Establish the loop invariant: we have written all dest before currentDest, currentSource is the lower source word of currentDest, and destBitsFromLowerSourceWord has been read
// Note that reading all bits from currentSource before writing any dest words it touches is necessary if the source range and dest range overlap and the source words are within one word of their dest words
++currentDest;
// currentSource remains unchanged; it is the lower source word of the new currentDest
destBitsFromLowerSourceWord = nextDestBitsFromLowerSourceWord;
while (currentDest != finalDest)
{
++currentSource;
destBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord;
nextDestBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord; // Must read this before writing currentDest to handle overlap
*currentDest = destBitsFromLowerSourceWord | destBitsFromUpperSourceWord;
++currentDest;
destBitsFromLowerSourceWord = nextDestBitsFromLowerSourceWord;
}
// Write the final Dest word, handling whether the last source word is the lower source word or the upper source word and handling endmask
if (endDestOffset <= firstBitInLowerDestWord)
{
// The last dest word ends before the bits touched by its upper source word, so the current lower source word is the last source word
// Note we are not allowed to try reading from any word that does not overlap the source range because it could pointing to inaccessible memory, so we don't try to read the bits from currentSource+1
destBitsFromUpperSourceWord = 0;
}
else
{
// The last source word is the upper source word of the last dest word; increment one last time and read the UpperSourceWord bits
++currentSource;
destBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord;
}
*currentDest = ((destBitsFromLowerSourceWord | destBitsFromUpperSourceWord) & endDestMask) | (*currentDest & ~(endDestMask));
}
else
{
uint32* currentDest = finalDest;
const uint32* currentSource = finalSource;
uint32 destBitsFromLowerSourceWord;
uint32 destBitsFromUpperSourceWord;
uint32 nextDestBitsFromUpperSourceWord;
// Write the final Dest word, handling whether the last source word is the lower source word or the upper source word and handling endmask
if (endDestOffset <= firstBitInLowerDestWord)
{
// The last dest word ends before the bits touched by its upper source word, so the final source word is the lower source word for the final dest word, and we don't have any bits from the upper source word
// Note we are not allowed to try reading from any word that does not overlap the source range because it could pointing to inaccessible memory, so we don't try to read the bits from currentSource+1
destBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord;
nextDestBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord; // Must read this before writing currentDest to handle overlap
*currentDest = (destBitsFromLowerSourceWord & endDestMask) | (*currentDest & ~(endDestMask));
}
else
{
// The last source word is the upper source word of the last dest word
destBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord;
--currentSource;
destBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord;
nextDestBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord; // Must read this before writing currentDest to handle overlap
*currentDest = ((destBitsFromLowerSourceWord | destBitsFromUpperSourceWord) & endDestMask) | (*currentDest & ~(endDestMask));
}
// Establish the loop invariant: we have written all dest before currentDest, currentSource is the lower source word of currentDest, and destBitsFromLowerSourceWord has been read
// Note that reading all bits from currentSource before writing any dest words it touches is necessary if the source range and dest range overlap and the source words are within one word of their dest words
--currentDest;
// currentSource remains unchanged; it is the upper source word of the new currentDest
destBitsFromUpperSourceWord = nextDestBitsFromUpperSourceWord;
while (currentDest != startDest)
{
--currentSource;
destBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord;
nextDestBitsFromUpperSourceWord = *(currentSource) << upShiftToLowerDestWord; // Must read this before writing currentDest to handle overlap
*currentDest = destBitsFromLowerSourceWord | destBitsFromUpperSourceWord;
--currentDest;
destBitsFromUpperSourceWord = nextDestBitsFromUpperSourceWord;
}
// Write the first Dest word, handling whether the first source word is the lower source word or the upper source word and handling startDestMask
if (srcOffset < destOffset)
{
// The beginning of the first source word is past the beginning of the dest word, so it is the upper source word of the dest word, and we've already read its bits above
// Note we are not allowed to try reading from any word that does not overlap the source range because it could pointing to inaccessible memory, so we don't try to read the bits from currentSource-1
destBitsFromLowerSourceWord = 0;
}
else
{
// The first source word is the lower source word of the first dest word; decrement one last time and read the LowerSourceWord bits
--currentSource;
destBitsFromLowerSourceWord = *(currentSource) >> downShiftToUpperDestWord;
}
*currentDest = (*currentDest & ~(startDestMask)) | ((destBitsFromLowerSourceWord | destBitsFromUpperSourceWord) & startDestMask);
}
}
void Memory::Shutdown()
{
if (GMalloc != nullptr)
{
delete GMalloc;
GMalloc = nullptr;
}
}
void Memory::NormalizeOffset(uint32* data, int32& offset)
{
const uint32 uintBits = 32;
if ((offset < 0) | (uintBits <= offset))
{
data += (offset / uintBits);
offset = offset % uintBits;
if (offset < 0)
{
--data;
offset += uintBits;
}
}
}
IMalloc* Memory::GetGMalloc()
{
if (GMalloc == nullptr)
{
GMalloc = PlatformMemory::GetDefaultMalloc();
}
PL_ASSERT(GMalloc);
return GMalloc;
}
} | 55.953271 | 304 | 0.641668 | JasonYui |
933e7c8d7b43f911ce23c789087716dc49a63d19 | 2,276 | cpp | C++ | Tree/ConstructBinaryTreeFromPreorderAndInorderTraversal/ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | 2 | 2015-08-28T03:52:05.000Z | 2015-09-03T09:54:40.000Z | Tree/ConstructBinaryTreeFromPreorderAndInorderTraversal/ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | Tree/ConstructBinaryTreeFromPreorderAndInorderTraversal/ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | // Source : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
// Author : Yijing Bai
// Date : 2016-01-01
/**********************************************************************************
*
* Given preorder and inorder traversal of a tree, construct the binary tree.
*
* Note:
* You may assume that duplicates do not exist in the tree.
*
*
*
*
*
*
*
*
**********************************************************************************/
#include <vector>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* buildTreeHelper(vector<int>& preorder, vector<int>& inorder, int pre_start, int pre_end,
int in_start, int in_end) {
if (pre_end < pre_start || in_end < in_start) {
return NULL;
}
int root_val = preorder[pre_start];
TreeNode* root = new TreeNode(root_val);
int in_left_start = in_start, in_left_end, in_right_start, in_right_end = in_end;
for (int i = in_start; i <= in_end; i++) {
if (root_val == inorder[i]) {
in_left_end = i - 1;
in_right_start = i + 1;
break;
}
}
int pre_left_start = pre_start + 1, pre_left_end = pre_left_start + (in_left_end - in_left_start),
pre_right_start = pre_left_end + 1, pre_right_end = pre_end;
root->left = buildTreeHelper(preorder, inorder, pre_left_start, pre_left_end, in_left_start, in_left_end);
root->right = buildTreeHelper(preorder, inorder, pre_right_start, pre_right_end, in_right_start, in_right_end);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildTreeHelper(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
};
int main() {
vector<int> pre;
vector<int> in;
pre.push_back(1);
pre.push_back(2);
pre.push_back(3);
pre.push_back(4);
pre.push_back(5);
in.push_back(2);
in.push_back(1);
in.push_back(4);
in.push_back(3);
in.push_back(5);
Solution s;
TreeNode* root = s.buildTree(pre, in);
}
| 26.16092 | 119 | 0.585677 | yijingbai |
93410172157ce99aa4b604bb0640d9811cf8ae6a | 1,516 | cc | C++ | build/x86/cpu/DummyChecker.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/cpu/DummyChecker.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/cpu/DummyChecker.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_DummyChecker[] = {
120,156,181,80,77,75,196,48,16,157,180,107,209,197,131,7,
127,128,39,169,66,27,191,122,16,68,196,21,188,137,180,122,
112,47,161,38,217,166,216,116,75,63,96,123,214,255,173,51,
237,22,253,3,14,201,227,101,50,153,247,50,18,182,225,226,
190,59,2,104,174,144,40,92,12,10,128,23,98,14,20,12,
44,131,37,3,166,92,208,12,86,12,212,12,190,0,62,1,
222,150,14,168,29,72,124,15,31,230,223,24,62,67,214,18,
156,142,116,142,176,48,90,126,232,122,241,252,218,238,227,241,
161,179,182,223,230,228,228,129,138,239,201,195,33,18,13,36,
136,250,212,31,197,93,136,19,223,193,139,152,96,40,145,85,
199,21,53,18,114,236,20,26,227,207,72,113,23,65,136,50,
181,90,136,65,94,8,187,86,93,65,199,161,160,175,244,144,
151,155,141,48,58,85,186,246,201,193,47,52,143,8,220,150,
45,55,217,170,225,137,73,107,157,24,93,242,76,219,40,88,
215,121,150,151,65,211,166,239,133,14,46,206,206,163,224,58,
184,228,77,45,57,153,250,251,187,176,234,7,199,39,212,148,
180,61,230,177,39,159,230,221,238,33,216,40,172,210,58,181,
77,204,166,207,253,163,149,97,50,55,227,44,110,143,39,75,
115,118,224,252,0,137,239,113,253,
};
EmbeddedPython embedded_m5_objects_DummyChecker(
"m5/objects/DummyChecker.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/src/cpu/DummyChecker.py",
"m5.objects.DummyChecker",
data_m5_objects_DummyChecker,
297,
522);
} // anonymous namespace
| 42.111111 | 78 | 0.677441 | billionshang |
9344e65bdf387620b1774ab4f4974511557a71c9 | 1,473 | cpp | C++ | Codeforces/1000~1999/1196/F.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | 6 | 2018-12-30T06:16:54.000Z | 2022-03-23T08:03:33.000Z | Codeforces/1000~1999/1196/F.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | null | null | null | Codeforces/1000~1999/1196/F.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <unordered_map>
typedef long long ll;
typedef std::pair<int, int> pii;
const int N = 2e3 + 32, M = 1e6 + 64;
struct ed {
int x, y, z;
bool operator<(const ed& r) const { return z < r.z; }
} e2[M << 1];
struct edge {
int to, next, w;
} e[M << 1];
int head[N], cnt;
void addedge(int x, int y, int z) {
e[++cnt] = (edge){y, head[x], z}, head[x] = cnt;
e[++cnt] = (edge){x, head[y], z}, head[y] = cnt;
}
std::unordered_map<int, int> mp;
int id(int x) {
if (!mp.count(x)) return mp[x] = mp.size() + 1;
return mp[x];
}
ll dis[N], a[M];
void dijspfa(int s) {
memset(dis, 0x3f, sizeof dis);
std::priority_queue<pii> pq;
for (pq.push(pii(0, s)), dis[s] = 0; !pq.empty();) {
int x = pq.top().second, y = -pq.top().first;
pq.pop();
if (dis[x] < y) continue;
for (int i = head[x], nx; i; i = e[i].next)
if (dis[nx = e[i].to] > dis[x] + e[i].w) {
dis[nx] = dis[x] + e[i].w;
pq.push(pii(-dis[nx], nx));
}
}
}
int n, m, k, u, v, t;
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= m; i++) scanf("%d%d%d", &e2[i].x, &e2[i].y, &e2[i].z);
std::sort(e2 + 1, e2 + m + 1);
for (int i = 1; i <= std::min(m, k); i++) {
u = id(e2[i].x), v = id(e2[i].y);
addedge(u, v, e2[i].z);
}
n = mp.size();
for (int i = 1; i <= n; i++) {
dijspfa(i);
for (int j = i + 1; j <= n; j++) a[++t] = dis[j];
}
std::sort(a + 1, a + t + 1);
printf("%lld", a[k]);
} | 23.380952 | 76 | 0.508486 | tiger0132 |
9346b731299c8033c88f03cf38fff58aec75ceb8 | 4,074 | cpp | C++ | geometry/StarOBJ.cpp | sunglab/StarEngine | fa14be7c74ef09d4ffbc2c31b5790befd414f2d6 | [
"MIT",
"Unlicense"
] | 32 | 2016-12-29T22:32:40.000Z | 2021-07-09T01:59:19.000Z | geometry/StarOBJ.cpp | sunglab/StarEngine | fa14be7c74ef09d4ffbc2c31b5790befd414f2d6 | [
"MIT",
"Unlicense"
] | 1 | 2018-03-15T09:09:16.000Z | 2019-02-12T02:13:55.000Z | geometry/StarOBJ.cpp | sunglab/StarEngine | fa14be7c74ef09d4ffbc2c31b5790befd414f2d6 | [
"MIT",
"Unlicense"
] | 11 | 2016-12-29T22:36:30.000Z | 2022-01-25T11:30:22.000Z | //
// StarOBJ.cpp
//
// Created by Sungwoo Choi on 7/30/15.
// Copyright (c) 2015 SungLab. All rights reserved.
//
#include "StarOBJ.h"
//
//#include <boost/tokenizer.hpp>
#include <string>
#include "../StarMain.h"
using namespace std;
//using namespace boost;
StarOBJ::StarOBJ(const string& path, vector<Vec3>& position, vector<Vec2>& texcoord,vector<Vec3>& normal, vector<unsigned short>& index):filepath(path)
{
string line;
unsigned int v=0, vt=0, vn=0, lines=0;
unsigned short offset = 0;
ifstream objfile(path.c_str());
if(!objfile)
starLOG("File is not open\n");
else
while (std::getline(objfile,line))
{
istringstream lineSS(line);
string lineType;
lineSS >> lineType;
// vertex
if( lineType == "v" )
{
v++;
float x = 0 ,y = 0,z = 0;
lineSS >> x >> y >> z ;
temp_position.push_back( Vec3( x, y, z));
}
// texture
else if( lineType == "vt" )
{
vt++;
float u = 0, v = 0;
lineSS >> u >> v ;
temp_texcoord.push_back(Vec2( u, v ));
}
// normal
else if( lineType == "vn" )
{
vn++;
float x = 0, y = 0, z = 0;
lineSS >> x >> y >> z;
// temp_normal.push_back(Vec3( x, y, z ).normalize());
temp_normal.push_back(Normalize(Vec3( x, y, z )));
}
else if( lineType == "f" )
{
string i,j,k,l;
// string m,n,o;
lineSS >> i >> j >> k >> l;
parseFace(i,index);
parseFace(j,index);
parseFace(k,index);
if(l.size())
{
parseFace(i,index);
parseFace(k,index);
parseFace(l,index);
}
}
}
if(vn)
offset++;
if(vt)
offset++;
for(vector<unsigned short>::iterator itr=index.begin(); itr!=index.end();itr++)
position.push_back(temp_position[*itr]);
if((offset==1) && vt)
{
for(vector<unsigned short>::iterator itr=temp_index.begin(); itr!=temp_index.end();itr++)
texcoord.push_back(temp_texcoord[*itr]);
}
else if((offset==1) && vn)
{
for(vector<unsigned short>::iterator itr=temp_index.begin(); itr!=temp_index.end();itr++)
{
normal.push_back(temp_normal[*itr]);
}
}
else if(offset==2)
{
int i = 0;
for(vector<unsigned short>::iterator itr=temp_index.begin(); itr!=temp_index.end();itr++,i++)
{
if((i%2))
normal.push_back(temp_normal[*itr]);
else
texcoord.push_back(temp_texcoord[*itr]);
}
}
else
{
}
starLOG("\nv = %d vn = %d vt = %d f = %d offset = %d lines = %d\n", position.size(), normal.size(), texcoord.size(), index.size(),offset, lines);
starLOG("v = %d vn = %d vt = %d f = %d offset = %d lines = %d\n", position.size(), temp_normal.size(), temp_texcoord.size(), temp_index.size(),offset, lines);
}
void StarOBJ::parseFace(const string& faces, vector<unsigned short>& idx)
{
// without boost
// boost::char_separator<char> sep("/");
// boost::tokenizer<boost::char_separator<char> > tokens(faces, sep);
// for(tokenizer<boost::char_separator<char> >::iterator itridx=tokens.begin(); itridx!=tokens.end();itridx++)
// {
// if(itridx==tokens.begin())
// idx.push_back(std::stoi((*itridx))-1);
// else
// temp_index.push_back(std::stoi(*itridx)-1);
// }
}
unsigned int StarOBJ::getVertexCount() const
{
return vertexCount;
}
unsigned int StarOBJ::getNormalCount() const
{
return normalCount;
}
| 28.096552 | 162 | 0.485027 | sunglab |
93482637ad784c79b112e7afa699eba44519fa07 | 916 | cpp | C++ | GeoWars/Battery.cpp | ShaunKarran/PEESSP-Game1 | 997e53580aff680263fe15152f1dd8ea0538d663 | [
"MIT"
] | null | null | null | GeoWars/Battery.cpp | ShaunKarran/PEESSP-Game1 | 997e53580aff680263fe15152f1dd8ea0538d663 | [
"MIT"
] | null | null | null | GeoWars/Battery.cpp | ShaunKarran/PEESSP-Game1 | 997e53580aff680263fe15152f1dd8ea0538d663 | [
"MIT"
] | null | null | null | #include <WProgram.h>
#include "Battery.h"
#include "sprites.h"
Battery::Battery()
{
this->pin = A3;
lcd = new LCD_HY28B(LCD_RST, LCD_BL_CTRL);
}
Battery::Battery(uint8_t pin)
{
this->pin = pin;
}
double Battery::MilliVoltage()
{
uint16_t analogResult = analogRead(pin);
double voltage = ((analogResult * VREF) / (1 << ADC_RES)); // Scale result to correct voltage.
return voltage * V_DIV; // Compensate for voltage divider on battery voltage.
}
uint8_t Battery::Percentage()
{
double voltage = MilliVoltage();
uint8_t percentage = ((voltage - V_MIN) * 100) / V_RANGE;
return (percentage < 100) ? percentage : 100;
}
void Battery::Show_Level()
{
uint8_t percentage = Percentage();
if (percentage > 80)
{
lcd->Draw_Sprite(sprite_battery_full, 300, 0);
}
else if (percentage > 40)
{
lcd->Draw_Sprite(sprite_battery_mid, 300, 0);
}
else
{
lcd->Draw_Sprite(sprite_battery_low, 300, 0);
}
}
| 19.913043 | 95 | 0.689956 | ShaunKarran |
934a8508a5f8aed0ed69b449660d306725483f5b | 2,615 | cpp | C++ | Source/moja.flint/src/operationstockublas.cpp | moja-global/flint | 2c65c5808d908247ce8ee4d9f87f11c7dd57794e | [
"BSL-1.0"
] | null | null | null | Source/moja.flint/src/operationstockublas.cpp | moja-global/flint | 2c65c5808d908247ce8ee4d9f87f11c7dd57794e | [
"BSL-1.0"
] | 1 | 2020-07-12T11:30:00.000Z | 2020-07-18T14:50:16.000Z | Source/moja.flint/src/operationstockublas.cpp | moja-global/flint | 2c65c5808d908247ce8ee4d9f87f11c7dd57794e | [
"BSL-1.0"
] | null | null | null | #include "moja/flint/operationstockublas.h"
#include "moja/flint/ipool.h"
#include "moja/flint/operationmanagerublas.h"
#include "moja/flint/operationresultublas.h"
namespace moja {
namespace flint {
// --------------------------------------------------------------------------------------------
StockOperationUblas::StockOperationUblas(OperationManagerUblas* manager, moja_ublas_vector& pools, double timeScale,
/*moja_ublas_identity& I, */ const ModuleMetaData* metaData)
: IOperation(metaData),
_manager(manager),
_timeScale(timeScale),
_pools(pools),
/*_I(I), */ _matrix(manager->_poolCount, manager->_poolCount, manager->_poolCount) /*, _matrix(I)*/ {
_hasChange = false;
}
StockOperationUblas::StockOperationUblas(OperationManagerUblas* manager, moja_ublas_vector& pools, double timeScale,
const ModuleMetaData* metaData, DynamicVar& dataPackage)
: IOperation(metaData, dataPackage),
_manager(manager),
_timeScale(timeScale),
_pools(pools),
/*_I(I), */ _matrix(manager->_poolCount, manager->_poolCount, manager->_poolCount) /*, _matrix(I)*/ {
_hasChange = false;
}
// --------------------------------------------------------------------------------------------
StockOperationUblas* StockOperationUblas::addTransfer(const IPool* source, const IPool* sink, double value) {
// Ublas allows a zero value to be inserted in a sparse matrix
if (FloatCmp::equalTo(value, 0.0)) return this;
_matrix(source->idx(), sink->idx()) += value;
_hasChange = true;
return this;
}
// --------------------------------------------------------------------------------------------
std::shared_ptr<IOperationResult> StockOperationUblas::computeOperation(ITiming& _timing) {
// if (!_hasChange)
// return nullptr;
auto result = std::make_shared<OperationResultUblas>(*this);
if (!_hasChange) return result;
if (_timing.isFullStep()) {
result->_fluxes = _matrix;
} else {
result->_fluxes = _matrix * _timeScale;
}
return result;
}
// --------------------------------------------------------------------------------------------
OperationTransferType StockOperationUblas::transferType() const { return OperationTransferType::Stock; }
// --------------------------------------------------------------------------------------------
void StockOperationUblas::submitOperation() { _manager->submitOperation(this); }
} // namespace flint
} // namespace moja
| 36.830986 | 117 | 0.547228 | moja-global |
93590b3d613fd2490653ab134b87763d07a653e9 | 594 | hpp | C++ | Glitter/Headers/SpriteRenderer.hpp | haolly/Breakout | 19606c2c0308d87833c40e87b62fa350d716660f | [
"MIT",
"Unlicense"
] | null | null | null | Glitter/Headers/SpriteRenderer.hpp | haolly/Breakout | 19606c2c0308d87833c40e87b62fa350d716660f | [
"MIT",
"Unlicense"
] | null | null | null | Glitter/Headers/SpriteRenderer.hpp | haolly/Breakout | 19606c2c0308d87833c40e87b62fa350d716660f | [
"MIT",
"Unlicense"
] | null | null | null | //
// Created by liuhao on 2018/9/28.
//
#ifndef GLITTER_SPRITERENDERER_HPP
#define GLITTER_SPRITERENDERER_HPP
#include <glm/vec2.hpp>
#include <glad/glad.h>
#include <glm/vec3.hpp>
#include "Shader.hpp"
#include "Texture2D.hpp"
class SpriteRenderer
{
public:
SpriteRenderer(const Shader& shader);
~SpriteRenderer();
void DrawSprite(const Texture2D& texture, glm::vec2 position, glm::vec2 size = glm::vec2(10, 10), GLfloat rotate = 0.0f,
glm::vec3 color = glm::vec3(1.0f));
private:
Shader shader;
GLuint quadVAO;
void initRenderData();
};
#endif //GLITTER_SPRITERENDERER_HPP
| 18 | 121 | 0.73064 | haolly |
935a6f0307f5d876da5cac3610ac2d33a5638f9b | 4,200 | hpp | C++ | stdlib/Core/Int.hpp | Oj18/Ethereal | 16a0a167693c27615e5c63044f1c38b5c8d863b2 | [
"BSD-3-Clause"
] | null | null | null | stdlib/Core/Int.hpp | Oj18/Ethereal | 16a0a167693c27615e5c63044f1c38b5c8d863b2 | [
"BSD-3-Clause"
] | null | null | null | stdlib/Core/Int.hpp | Oj18/Ethereal | 16a0a167693c27615e5c63044f1c38b5c8d863b2 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2019, Electrux
All rights reserved.
Using the BSD 3-Clause license for the project,
main LICENSE file resides in project's root directory.
Please read that file and understand the license terms
before using or altering the project.
*/
#ifndef VM_MODULES_CORE_INT_HPP
#define VM_MODULES_CORE_INT_HPP
#include "../../src/VM/Core.hpp"
#define DECL_FUNC_ALLOC__INT( name, oper, ret_type ) \
var_base_t * name( vm_state_t & vm, func_call_data_t & fcd ) \
{ \
auto & lhs = AS_INT( fcd.args[ 1 ] )->get(); \
auto & rhs = AS_INT( fcd.args[ 0 ] )->get(); \
return new ret_type( lhs oper rhs ); \
}
#define DECL_FUNC_BOOL__INT( name, oper ) \
var_base_t * name( vm_state_t & vm, func_call_data_t & fcd ) \
{ \
auto & lhs = AS_INT( fcd.args[ 1 ] )->get(); \
auto & rhs = AS_INT( fcd.args[ 0 ] )->get(); \
return TRUE_FALSE( lhs oper rhs ); \
}
#define DECL_FUNC_ASSN__INT( name, oper ) \
var_base_t * name( vm_state_t & vm, func_call_data_t & fcd ) \
{ /* lhs = 0 because Right to Left associativity */ \
auto & lhs = AS_INT( fcd.args[ 0 ] )->get(); \
auto & rhs = AS_INT( fcd.args[ 1 ] )->get(); \
lhs oper rhs; \
return fcd.args[ 0 ]; \
}
#define DECL_FUNC_BIT__INT( name, oper ) \
var_base_t * name( vm_state_t & vm, func_call_data_t & fcd ) \
{ /* lhs = 0 because Right to Left associativity */ \
auto & lhs = AS_INT( fcd.args[ 0 ] )->get(); \
auto & rhs = AS_INT( fcd.args[ 1 ] )->get(); \
return new var_int_t( lhs oper rhs ); \
}
DECL_FUNC_ALLOC__INT( add, +, var_int_t )
DECL_FUNC_ALLOC__INT( sub, -, var_int_t )
DECL_FUNC_ALLOC__INT( mul, *, var_int_t )
DECL_FUNC_ALLOC__INT( div, /, var_int_t )
DECL_FUNC_ALLOC__INT( mod, %, var_int_t )
DECL_FUNC_ASSN__INT( add_assn, += )
DECL_FUNC_ASSN__INT( sub_assn, -= )
DECL_FUNC_ASSN__INT( mul_assn, *= )
DECL_FUNC_ASSN__INT( div_assn, /= )
DECL_FUNC_ASSN__INT( mod_assn, %= )
DECL_FUNC_BOOL__INT( eqi, == )
DECL_FUNC_BOOL__INT( nei, != )
DECL_FUNC_BOOL__INT( lti, < )
DECL_FUNC_BOOL__INT( lei, <= )
DECL_FUNC_BOOL__INT( gti, > )
DECL_FUNC_BOOL__INT( gei, >= )
DECL_FUNC_BIT__INT( andi, & )
DECL_FUNC_BIT__INT( ori, | )
var_base_t * power( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & lhs = AS_INT( fcd.args[ 1 ] )->get();
mpz_class & rhs = AS_INT( fcd.args[ 0 ] )->get();
var_int_t * res = new var_int_t( "0" );
mpz_pow_ui( res->get().get_mpz_t(), lhs.get_mpz_t(), rhs.get_ui() );
return res;
}
var_base_t * lshift( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & lhs = AS_INT( fcd.args[ 1 ] )->get();
mpz_class & rhs = AS_INT( fcd.args[ 0 ] )->get();
var_int_t * res = new var_int_t( "0" );
mpz_mul_2exp( res->get().get_mpz_t(), lhs.get_mpz_t(), rhs.get_ui() );
return res;
}
var_base_t * rshift( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & lhs = AS_INT( fcd.args[ 1 ] )->get();
mpz_class & rhs = AS_INT( fcd.args[ 0 ] )->get();
var_int_t * res = new var_int_t( "0" );
mpz_div_2exp( res->get().get_mpz_t(), lhs.get_mpz_t(), rhs.get_ui() );
return res;
}
var_base_t * lshift_assn( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & lhs = AS_INT( fcd.args[ 0 ] )->get();
mpz_class & rhs = AS_INT( fcd.args[ 1 ] )->get();
mpz_mul_2exp( lhs.get_mpz_t(), lhs.get_mpz_t(), rhs.get_ui() );
return fcd.args[ 0 ];
}
var_base_t * rshift_assn( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & lhs = AS_INT( fcd.args[ 0 ] )->get();
mpz_class & rhs = AS_INT( fcd.args[ 1 ] )->get();
mpz_div_2exp( lhs.get_mpz_t(), lhs.get_mpz_t(), rhs.get_ui() );
return fcd.args[ 0 ];
}
var_base_t * unary_sub( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & num = AS_INT( fcd.args[ 0 ] )->get();
return new var_int_t( -num );
}
var_base_t * not_oper( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & num = AS_INT( fcd.args[ 0 ] )->get();
return TRUE_FALSE( !num );
}
var_base_t * not_oper_bitwise( vm_state_t & vm, func_call_data_t & fcd )
{
mpz_class & num = AS_INT( fcd.args[ 0 ] )->get();
return new var_int_t( ~num );
}
var_base_t * num( vm_state_t & vm, func_call_data_t & fcd )
{
return new var_int_t( fcd.args[ 0 ]->to_int() );
}
#endif // VM_MODULES_CORE_INT_HPP | 30.882353 | 72 | 0.651667 | Oj18 |
935d1dfaeaef0f40aa62f8c4ea3ca163b1c2c8e8 | 272 | cpp | C++ | examples/hello_world.cpp | ClausKlein/observer | 1d6957385ba912d190a792dbb031b762e419d785 | [
"MIT"
] | 8 | 2018-03-23T14:29:17.000Z | 2021-12-26T01:18:22.000Z | examples/hello_world.cpp | ClausKlein/observer | 1d6957385ba912d190a792dbb031b762e419d785 | [
"MIT"
] | 1 | 2020-04-11T07:52:47.000Z | 2020-04-11T07:52:47.000Z | examples/hello_world.cpp | ClausKlein/observer | 1d6957385ba912d190a792dbb031b762e419d785 | [
"MIT"
] | 5 | 2018-03-23T14:29:22.000Z | 2022-02-27T16:46:47.000Z | #include <observer.h>
#include <iostream>
void hello_world()
{
std::cout << "Hello World!" << std::endl;
}
int main( int /* argc */, char * /* argv */[] )
{
pg::subject<> s;
auto connection = pg::connect( s, hello_world );
s.notify();
return 0;
}
| 14.315789 | 52 | 0.555147 | ClausKlein |
93635f37e2b52d57bc97b81c1d568b7fbd156630 | 17,426 | hpp | C++ | Library/Private/Galleon/Galleon/LongTermContainer.hpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | 3 | 2021-06-02T05:06:48.000Z | 2022-01-26T09:39:44.000Z | Library/Private/Galleon/Galleon/LongTermContainer.hpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | null | null | null | Library/Private/Galleon/Galleon/LongTermContainer.hpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cassert>
#include <API/Common/Cursor.hpp>
#include <API/Common/Shortcuts.hpp>
#include <Galleon/ContainerBase.hpp>
#include <RecordCollection/Collection.hpp>
#include <RecordCollection/LinearRepresentation.hpp>
#include <RecordCollection/PointRepresentation.hpp>
#include <RecordCollection/VolumetricRepresentation.hpp>
namespace Emergence::Galleon
{
/// \brief Storage for objects that are created and destroyed rarely.
/// \details Prepared queries for this container use RecordCollection to provide fast parametrized lookups.
class LongTermContainer final : public ContainerBase
{
public:
/// \brief Prepared query, used to start insertion transactions.
class InsertQuery final
{
public:
class Cursor final
{
public:
Cursor (const Cursor &_other) = delete;
Cursor (Cursor &&_other) noexcept = default;
/// \invariant Previously allocated object must be initialized before cursor destruction.
~Cursor () noexcept = default;
/// \return Pointer to memory, allocated for the new object.
/// \invariant Previously allocated object must be initialized before next call.
void *operator++ () noexcept;
/// Assigning cursors looks counter intuitive.
EMERGENCE_DELETE_ASSIGNMENT (Cursor);
private:
friend class InsertQuery;
explicit Cursor (Handling::Handle<LongTermContainer> _container) noexcept;
Handling::Handle<LongTermContainer> container;
RecordCollection::Collection::Allocator allocator;
};
InsertQuery (const InsertQuery &_other) noexcept = default;
InsertQuery (InsertQuery &&_other) noexcept = default;
~InsertQuery () noexcept = default;
[[nodiscard]] Cursor Execute () const noexcept;
[[nodiscard]] Handling::Handle<LongTermContainer> GetContainer () const noexcept;
/// Assigning prepared queries looks counter intuitive.
EMERGENCE_DELETE_ASSIGNMENT (InsertQuery);
private:
friend class LongTermContainer;
explicit InsertQuery (Handling::Handle<LongTermContainer> _container) noexcept;
Handling::Handle<LongTermContainer> container;
};
template <typename Representation>
class RepresentationQueryBase
{
public:
RepresentationQueryBase (const RepresentationQueryBase &_other) noexcept = default;
RepresentationQueryBase (RepresentationQueryBase &&_other) noexcept = default;
~RepresentationQueryBase () noexcept;
[[nodiscard]] Handling::Handle<LongTermContainer> GetContainer () const noexcept;
/// Assigning prepared queries looks counter intuitive.
EMERGENCE_DELETE_ASSIGNMENT (RepresentationQueryBase);
protected:
/// VisualizationDriver for Warehouse service should be able to directly access ::representation.
friend class VisualizationDriver;
RepresentationQueryBase (Handling::Handle<LongTermContainer> _container,
Representation _representation) noexcept;
Handling::Handle<LongTermContainer> container;
Representation representation;
};
/// \brief Prepared query, used to gain thread safe readonly access to objects that match criteria:
/// each key field value is equal to according value in given values sequence.
class FetchValueQuery final : public RepresentationQueryBase<RecordCollection::PointRepresentation>
{
public:
/// \warning There is no guaranteed order of objects. Therefore object order should be considered random.
using Cursor = RecordCollection::PointRepresentation::ReadCursor;
Cursor Execute (RecordCollection::PointRepresentation::Point _values) noexcept;
[[nodiscard]] RecordCollection::PointRepresentation::KeyFieldIterator KeyFieldBegin () const noexcept;
[[nodiscard]] RecordCollection::PointRepresentation::KeyFieldIterator KeyFieldEnd () const noexcept;
private:
friend class LongTermContainer;
FetchValueQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::PointRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain readwrite access to objects that match criteria:
/// each key field value is equal to according value in given values sequence.
class ModifyValueQuery final : public RepresentationQueryBase<RecordCollection::PointRepresentation>
{
public:
/// \warning There is no guaranteed order of objects. Therefore object order should be considered random.
using Cursor = RecordCollection::PointRepresentation::EditCursor;
Cursor Execute (RecordCollection::PointRepresentation::Point _values) noexcept;
[[nodiscard]] RecordCollection::PointRepresentation::KeyFieldIterator KeyFieldBegin () const noexcept;
[[nodiscard]] RecordCollection::PointRepresentation::KeyFieldIterator KeyFieldEnd () const noexcept;
private:
friend class LongTermContainer;
ModifyValueQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::PointRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain thread safe readonly access to objects that match criteria:
/// given min max interval contains key field value.
class FetchAscendingRangeQuery final : public RepresentationQueryBase<RecordCollection::LinearRepresentation>
{
public:
using Cursor = RecordCollection::LinearRepresentation::AscendingReadCursor;
Cursor Execute (RecordCollection::LinearRepresentation::KeyFieldValue _min,
RecordCollection::LinearRepresentation::KeyFieldValue _max) noexcept;
[[nodiscard]] StandardLayout::Field GetKeyField () const noexcept;
private:
friend class LongTermContainer;
FetchAscendingRangeQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::LinearRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain readwrite access to objects that match criteria:
//// given min max interval contains key field value.
class ModifyAscendingRangeQuery final : public RepresentationQueryBase<RecordCollection::LinearRepresentation>
{
public:
using Cursor = RecordCollection::LinearRepresentation::AscendingEditCursor;
Cursor Execute (RecordCollection::LinearRepresentation::KeyFieldValue _min,
RecordCollection::LinearRepresentation::KeyFieldValue _max) noexcept;
[[nodiscard]] StandardLayout::Field GetKeyField () const noexcept;
private:
friend class LongTermContainer;
ModifyAscendingRangeQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::LinearRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain thread safe readonly access to objects that match criteria:
/// given min max interval contains key field value.
class FetchDescendingRangeQuery final : public RepresentationQueryBase<RecordCollection::LinearRepresentation>
{
public:
using Cursor = RecordCollection::LinearRepresentation::DescendingReadCursor;
Cursor Execute (RecordCollection::LinearRepresentation::KeyFieldValue _min,
RecordCollection::LinearRepresentation::KeyFieldValue _max) noexcept;
[[nodiscard]] StandardLayout::Field GetKeyField () const noexcept;
private:
friend class LongTermContainer;
FetchDescendingRangeQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::LinearRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain readwrite access to objects that match criteria:
//// given min max interval contains key field value.
class ModifyDescendingRangeQuery final : public RepresentationQueryBase<RecordCollection::LinearRepresentation>
{
public:
/// \details Objects are sorted in descending order on key field value.
using Cursor = RecordCollection::LinearRepresentation::DescendingEditCursor;
Cursor Execute (RecordCollection::LinearRepresentation::KeyFieldValue _min,
RecordCollection::LinearRepresentation::KeyFieldValue _max) noexcept;
[[nodiscard]] StandardLayout::Field GetKeyField () const noexcept;
private:
friend class LongTermContainer;
ModifyDescendingRangeQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::LinearRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain thread safe readonly access to objects that match criteria:
//// shape, described by values of object key dimensions, intersects with given shape.
class FetchShapeIntersectionQuery final : public RepresentationQueryBase<RecordCollection::VolumetricRepresentation>
{
public:
/// \warning There is no guaranteed order of objects. Therefore object order should be considered random.
using Cursor = RecordCollection::VolumetricRepresentation::ShapeIntersectionReadCursor;
Cursor Execute (RecordCollection::VolumetricRepresentation::Shape _shape) noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionBegin () const noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionEnd () const noexcept;
private:
friend class LongTermContainer;
FetchShapeIntersectionQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::VolumetricRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain readwrite access to objects that match criteria:
//// shape, described by values of object key dimensions, intersects with given shape.
class ModifyShapeIntersectionQuery final
: public RepresentationQueryBase<RecordCollection::VolumetricRepresentation>
{
public:
/// \warning There is no guaranteed order of objects. Therefore object order should be considered random.
using Cursor = RecordCollection::VolumetricRepresentation::ShapeIntersectionEditCursor;
Cursor Execute (RecordCollection::VolumetricRepresentation::Shape _shape) noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionBegin () const noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionEnd () const noexcept;
private:
friend class LongTermContainer;
ModifyShapeIntersectionQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::VolumetricRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain thread safe readonly access to objects that match criteria:
//// shape, described by values of object key dimensions, intersects with given ray and distance
/// from intersection point to ray origin is less or equal to given max distance.
class FetchRayIntersectionQuery final : public RepresentationQueryBase<RecordCollection::VolumetricRepresentation>
{
public:
/// \warning There is no guaranteed order of objects. Therefore object order should be considered random.
using Cursor = RecordCollection::VolumetricRepresentation::RayIntersectionReadCursor;
Cursor Execute (RecordCollection::VolumetricRepresentation::Ray _ray, float _maxDistance) noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionBegin () const noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionEnd () const noexcept;
private:
friend class LongTermContainer;
FetchRayIntersectionQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::VolumetricRepresentation _representation) noexcept;
};
/// \brief Prepared query, used to gain readwrite access to objects that match criteria:
//// shape, described by values of object key dimensions, intersects with given ray and distance
/// from intersection point to ray origin is less or equal to given max distance.
class ModifyRayIntersectionQuery final : public RepresentationQueryBase<RecordCollection::VolumetricRepresentation>
{
public:
/// \warning There is no guaranteed order of objects. Therefore object order should be considered random.
using Cursor = RecordCollection::VolumetricRepresentation::RayIntersectionEditCursor;
Cursor Execute (RecordCollection::VolumetricRepresentation::Ray _ray, float _maxDistance) noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionBegin () const noexcept;
[[nodiscard]] RecordCollection::VolumetricRepresentation::DimensionIterator DimensionEnd () const noexcept;
private:
friend class LongTermContainer;
ModifyRayIntersectionQuery (Handling::Handle<LongTermContainer> _container,
RecordCollection::VolumetricRepresentation _representation) noexcept;
};
LongTermContainer (const LongTermContainer &_other) = delete;
LongTermContainer (LongTermContainer &&_other) = delete;
InsertQuery Insert () noexcept;
FetchValueQuery FetchValue (const std::vector<StandardLayout::FieldId> &_keyFields) noexcept;
ModifyValueQuery ModifyValue (const std::vector<StandardLayout::FieldId> &_keyFields) noexcept;
FetchAscendingRangeQuery FetchAscendingRange (StandardLayout::FieldId _keyField) noexcept;
ModifyAscendingRangeQuery ModifyAscendingRange (StandardLayout::FieldId _keyField) noexcept;
FetchDescendingRangeQuery FetchDescendingRange (StandardLayout::FieldId _keyField) noexcept;
ModifyDescendingRangeQuery ModifyDescendingRange (StandardLayout::FieldId _keyField) noexcept;
FetchShapeIntersectionQuery FetchShapeIntersection (
const std::vector<RecordCollection::Collection::DimensionDescriptor> &_dimensions) noexcept;
ModifyShapeIntersectionQuery ModifyShapeIntersection (
const std::vector<RecordCollection::Collection::DimensionDescriptor> &_dimensions) noexcept;
FetchRayIntersectionQuery FetchRayIntersection (
const std::vector<RecordCollection::Collection::DimensionDescriptor> &_dimensions) noexcept;
ModifyRayIntersectionQuery ModifyRayIntersection (
const std::vector<RecordCollection::Collection::DimensionDescriptor> &_dimensions) noexcept;
EMERGENCE_DELETE_ASSIGNMENT (LongTermContainer);
private:
/// CargoDeck constructs containers.
friend class CargoDeck;
/// Only handles have right to destruct containers.
template <typename>
friend class Handling::Handle;
/// VisualizationDriver for Warehouse service should be able to directly access ::collection.
friend class VisualizationDriver;
explicit LongTermContainer (CargoDeck *_deck, StandardLayout::Mapping _typeMapping) noexcept;
~LongTermContainer () noexcept;
RecordCollection::LinearRepresentation AcquireLinearRepresentation (StandardLayout::FieldId _keyField) noexcept;
// TODO: Value reordering for value queries is not supported. Therefore preparing query for fields A B C and
// C B A will result on creation of two separate representations. Think about fixing this problem.
// There is same problem with volumetric query dimension reordering.
RecordCollection::PointRepresentation AcquirePointRepresentation (
const std::vector<StandardLayout::FieldId> &_keyFields) noexcept;
RecordCollection::VolumetricRepresentation AcquireVolumetricRepresentation (
const std::vector<RecordCollection::Collection::DimensionDescriptor> &_dimensions) noexcept;
RecordCollection::Collection collection;
};
template <typename Representation>
LongTermContainer::RepresentationQueryBase<Representation>::~RepresentationQueryBase<Representation> () noexcept
{
// If prepared query was moved out, representation call will result in undefined behaviour.
// Therefore, we should check container reference first. It will be null of query was moved out.
if (container && representation.CanBeDropped ())
{
representation.Drop ();
}
}
template <typename Representation>
Handling::Handle<LongTermContainer> LongTermContainer::RepresentationQueryBase<Representation>::GetContainer ()
const noexcept
{
assert (container);
return container;
}
template <typename Representation>
LongTermContainer::RepresentationQueryBase<Representation>::RepresentationQueryBase (
Handling::Handle<LongTermContainer> _container, Representation _representation) noexcept
: container (std::move (_container)),
representation (std::move (_representation))
{
assert (container);
}
} // namespace Emergence::Galleon
| 44.116456 | 120 | 0.732067 | KonstantinTomashevich |
936400196798f8b11e80880018d5739eeb3932b8 | 1,595 | cpp | C++ | src/Cube.cpp | Jaclav/wolf3d | d98574acf9e4e389258450bdc20ed216369558dd | [
"MIT"
] | null | null | null | src/Cube.cpp | Jaclav/wolf3d | d98574acf9e4e389258450bdc20ed216369558dd | [
"MIT"
] | null | null | null | src/Cube.cpp | Jaclav/wolf3d | d98574acf9e4e389258450bdc20ed216369558dd | [
"MIT"
] | null | null | null | #include "Cube.hpp"
#include <iostream>
Cube::Cube() {
glGenBuffers(1, &pointsVbo);
glBindBuffer(GL_ARRAY_BUFFER, pointsVbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
glGenBuffers(1, &texturePositionVbo);
glBindBuffer(GL_ARRAY_BUFFER, texturePositionVbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(texturePosition), &texturePosition, GL_STATIC_DRAW);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, pointsVbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, texturePositionVbo);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(1);
assert(mShader.loadFromFile("rsc/shaders/block.vert", "rsc/shaders/block.frag"));
setTexture("rsc/notFound.png");
}
Cube::Cube(glm::vec3 position) : Cube() {
setPosition(position);
}
void Cube::draw(glm::mat4 transformation) {
sf::Shader::bind(&mShader);
mShader.setUniform("transformation", sf::Glsl::Mat4(glm::value_ptr(glm::translate(transformation, position))));
glBindVertexArray(vao);
//TODO: don't draw not displayed walls
glDrawArrays(GL_TRIANGLES, 0, sizeof(points) / 3);
}
void Cube::setPosition(glm::vec3 position) {
Cube::position = position;
}
void Cube::setTexture(std::string path, bool smooth) {
if(!mTexture.loadFromFile(path)) {
assert(mTexture.loadFromFile("rsc/notFound.png"));
}
mTexture.setSmooth(smooth);
mShader.setUniform("texture", mTexture);
} | 30.673077 | 115 | 0.717241 | Jaclav |
93677059cc90285eb713a62b8a2f3d9d8a826715 | 321 | hpp | C++ | include/PiObjectRepresentation.hpp | echo-Mike/SARW-UEFITreeBuilder | e4ab988b1dedf6dce20341ff80f3c6bbdc83e7e6 | [
"MIT"
] | null | null | null | include/PiObjectRepresentation.hpp | echo-Mike/SARW-UEFITreeBuilder | e4ab988b1dedf6dce20341ff80f3c6bbdc83e7e6 | [
"MIT"
] | null | null | null | include/PiObjectRepresentation.hpp | echo-Mike/SARW-UEFITreeBuilder | e4ab988b1dedf6dce20341ff80f3c6bbdc83e7e6 | [
"MIT"
] | null | null | null | #pragma once
#ifndef PI_OBJECT_REPRESENTATION_HPP__
#define PI_OBJECT_REPRESENTATION_HPP__ "0.0.0@PiObjectRepresentation.hpp"
/// PROJECT
#include "PiObject.hpp"
#include "PiSimpleObjects.hpp"
#include "PiComplexObject.hpp"
#include "PiSectionObject.hpp"
#include "PiFileObject.hpp"
#include "PiVolumeObject.hpp"
#endif | 24.692308 | 73 | 0.813084 | echo-Mike |
937120a50d327941bd2deb2848a2af52ffc6d4f0 | 5,080 | cpp | C++ | app/Limits.cpp | SantoshKesani/ackermann-controller | afee2cd94884c6b392643f83c0e9bda11dd37acd | [
"MIT"
] | null | null | null | app/Limits.cpp | SantoshKesani/ackermann-controller | afee2cd94884c6b392643f83c0e9bda11dd37acd | [
"MIT"
] | 5 | 2020-10-24T12:22:22.000Z | 2020-11-10T21:29:35.000Z | app/Limits.cpp | SantoshKesani/ackermann-controller | afee2cd94884c6b392643f83c0e9bda11dd37acd | [
"MIT"
] | 4 | 2020-09-29T23:06:12.000Z | 2021-11-19T23:33:14.000Z | /**
* @file Limits.cpp
*
* @author Spencer Elyard
* @author Daniel M. Sahu
* @author Santosh Kesani
*
* @copyright [2020]
*/
#include <Limits.hpp>
#include <cmath>
namespace ackermann {
Limits::Limits(const std::shared_ptr<const Params>& params)
: params_(params) {
}
double Limits::throttleToSpeed(double throttle) const {
double speed_calc;
if (throttle > params_->throttle_max)
throttle = params_->throttle_max;
if (throttle < params_->throttle_min)
throttle = params_->throttle_min;
if (throttle <= 0)
speed_calc = 0;
else
speed_calc = throttle * params_->velocity_max;
return speed_calc;
}
double Limits::speedToThrottle(double speed) const {
double throttle_calc;
if (speed > params_->velocity_max)
speed = params_->velocity_max;
if (speed < params_->velocity_min)
speed = params_->velocity_min;
if (speed <= 0)
throttle_calc = 0;
else
throttle_calc = speed / params_->velocity_max;
return throttle_calc;
}
double Limits::shortestArcToTurn(double current_heading,
double desired_heading) const {
double heading_command = (desired_heading - current_heading);
if (heading_command > M_PI)
heading_command -= 2*M_PI;
if (heading_command < -M_PI)
heading_command += 2*M_PI;
return heading_command;
}
double Limits::boundHeading(const double heading) const {
double temp_heading = heading;
if (temp_heading < -M_PI)
while (temp_heading < -M_PI)
temp_heading += 2*M_PI;
if (temp_heading >= M_PI)
while (temp_heading > M_PI)
temp_heading -= 2*M_PI;
return temp_heading;
}
void Limits::limit(const double current_speed,
const double current_steering,
const double current_steering_vel,
double& desired_throttle,
double& desired_steering,
double& desired_steering_vel,
double dt) const {
// BEGIN THROTTLE LIMITATION SECTION
// limit current_throttle to [min,max]
if (desired_throttle > params_->throttle_max)
desired_throttle = params_->throttle_max;
if (desired_throttle < params_->throttle_min)
desired_throttle = params_->throttle_min;
// scale throttle to velocity commanded
double new_velocity = throttleToSpeed(desired_throttle);
if (new_velocity > params_->velocity_max) {
new_velocity = params_->velocity_max;
desired_throttle = speedToThrottle(new_velocity);
}
if (new_velocity < params_->velocity_min) {
new_velocity = params_->velocity_min;
desired_throttle = speedToThrottle(new_velocity);
}
// scale previous throttle to velocity & calculate commanded acceleration
double desired_acceleration = (new_velocity - current_speed) / dt;
// limit acceleration
if (desired_acceleration > params_->acceleration_max) {
desired_acceleration = params_->acceleration_max;
new_velocity = current_speed + desired_acceleration * dt;
desired_throttle = speedToThrottle(new_velocity);
}
if (desired_acceleration < params_->acceleration_min) {
desired_acceleration = params_->acceleration_min;
new_velocity = current_speed + desired_acceleration * dt;
desired_throttle = speedToThrottle(new_velocity);
}
// END THROTTLE LIMITATION SECTION
// BEGIN STEERING LIMITATION SECTION
// limit heading my max angle
if (desired_steering > params_->max_steering_angle) {
desired_steering = params_->max_steering_angle;
}
if (desired_steering < -params_->max_steering_angle) {
desired_steering = -params_->max_steering_angle;
}
// limit heading by max angle rate of change (angular velocity)
desired_steering_vel = (desired_steering - current_steering) / dt;
if (desired_steering_vel > params_->angular_velocity_max) {
desired_steering_vel = params_->angular_velocity_max;
desired_steering = current_steering + desired_steering_vel*dt;
}
if (desired_steering_vel < params_->angular_velocity_min) {
desired_steering_vel = params_->angular_velocity_min;
desired_steering = current_steering + desired_steering_vel*dt;
}
// limit heading by max angle rate of change rate of change (angular accel)
double steering_accel = (desired_steering_vel - current_steering_vel) / dt;
if (steering_accel > params_->angular_acceleration_max) {
steering_accel = params_->angular_acceleration_max;
desired_steering_vel = current_steering_vel + steering_accel*dt;
desired_steering = current_steering
+ (current_steering_vel*dt)
+ .5*steering_accel*dt*dt;
}
if (steering_accel < params_->angular_acceleration_min) {
steering_accel = params_->angular_acceleration_min;
desired_steering_vel = current_steering_vel + steering_accel*dt;
desired_steering = current_steering
+ (current_steering_vel*dt)
+ .5*steering_accel*dt*dt;
}
}
} // namespace ackermann
| 33.202614 | 79 | 0.691339 | SantoshKesani |
937d07668508428b61878833cc6dc1e955ebd21c | 26,094 | cc | C++ | src/util/tbl/_tt.cc | mansour2014/ATSP2K_plus | 30842b9f086d1e497aeb778e2a352d1e8e520ec3 | [
"BSD-4-Clause-UC"
] | 1 | 2019-07-21T14:03:39.000Z | 2019-07-21T14:03:39.000Z | src/util/tbl/_tt.cc | mzmansour/ATSP2K_plus | 30842b9f086d1e497aeb778e2a352d1e8e520ec3 | [
"BSD-4-Clause-UC"
] | null | null | null | src/util/tbl/_tt.cc | mzmansour/ATSP2K_plus | 30842b9f086d1e497aeb778e2a352d1e8e520ec3 | [
"BSD-4-Clause-UC"
] | null | null | null | #include "_tt.hh"
#include "_prn.hh"
#include "_inp.hh"
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <fstream>
#include <map>
#include <strstream>
#include <cstring>
#include <iomanip>
#include <iterator>
#include <algorithm>
#include <functional>
#include <cmath>
#include <sstream>
#include <ctime>
using namespace std;
//----------------------------------------------------
//----- non-members included in namespace transition
//----- also some of them called from members
//----------------------------------------------------
void Dt::fZ(double& ZZ, double& dRZ) {
double zmu = 0;
if (ZZ == 1) zmu = 1;
else if ( ZZ > 10) {zmu = 2 * ZZ + 1 + (ZZ - 11)/2;}
else if (!(int(ZZ)%2) || (ZZ == 7)) {zmu = 2 * ZZ;}
else {zmu = 2 * ZZ + 1;}
dRZ = RZN/(1+RZD/zmu);
}
// compare if term tb duplicates ta
bool Dt::Un_t (LCI ta, LCI tb) {
return (((*ta)->config == (*tb)->config) &&
((*ta)->term == (*tb)->term) &&
((*ta)->J == (*tb)->J));
}
void Dt::ETable_jini::set_ZNEL() {
Print_table::_Z_ = int(Z);
Print_table::_NEL_ = NEL;
Print_table::_RZ_ = RZ;
}
void Dt::set_tr_type(string& s) {
*Print_table::_tr_type_ = s;
}
void Dt::conv_J(string& B, const int j) {
string S;
std::ostringstream ost(S);
if (j%2) {
if (j > 10) ost << j << "/2";
else ost << " " << j << "/2";
}
else {
if (j >= 20) ost << " " << j/2;
else ost << " " << j/2;
}
B = ost.str();
}
//---------------------------------------------------------------
//------- comparing two transitions using initial-final energies
//---------------------------------------------------------------
class Dt::Comp_lsjLU {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
//return true if ta < tb
if(ta->ef == tb->ef) return ta->ei <= tb->ei;
return ta->ef <= tb->ef;
}
};
class Dt::Comp_lsjUL {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
//return true if ta < tb
if(ta->ei == tb->ei) return ta->ef <= tb->ef;
return ta->ei < tb->ei;
}
};
class Dt::Comp_mp {
public:
bool operator()(const JTR_mp* ta, const JTR_mp* tb) const {
//if(ta->E_low != tb->E_low) return ta->E_low >= tb->E_low;
//if(ta->E_high != tb->E_high) return ta->E_low >= tb->E_high;
return ta->E_tr >= tb->E_tr;
}
};
class Dt::Comp_lsjE {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
// if(ta->te == tb->te) return ta->te <= tb->te;
if(ta->tr_type != tb->tr_type)
return ta->tr_type <= tb->tr_type;
return ta->te <= tb->te;
}
};
class Dt::Comp_lsjgF {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
if(ta->_f_ik == tb->_f_ik) return ta->te <= tb->te;
return ta->_f_ik > tb->_f_ik;
}
};
class Dt::Comp_lsjSL {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
if(ta->_sL == tb->_sL) return ta->te <= tb->te;
return ta->_sL > tb->_sL;
}
};
class Dt::Comp_lsjWL {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
if(ta->angs_v == tb->angs_v) return ta->angs_v <= tb->angs_v;
return ta->angs_v <= tb->angs_v;
}
};
//--------------------------------------------------------------
//----- operator for sorting lsj tbl within the final term
//--------------------------------------------------------------
class Dt::Comp_lsj_int {
public:
bool operator()(const JTR_tr* ta, const JTR_tr* tb) const {
//return true if ta < tb
if(ta->cf == tb->cf) return ta->ef <= tb->ef;
return ta->ei < tb->ei;
}
};
//----------------------------------------------------
// ----member functions of Dt::Level--
//---------------------------------------------------
Dt::Level::Level(std::string sc = "", int jj = 0,
double d1 = 0, double d2 = 0, double d3 = 0,
double d4 = 0, double d5 = 0, double d6 = 0) :
tmp(sc), J(jj), totalE(d1), lev(d2), lifetime(d3),
Ssms(d4), g_J(d5), g_JLS(d6), config_rep(" "),
term_rep(" "), unph(true) , Splitting(0) { mk_term(); }
void mk_term();
Dt::JTR_tr::JTR_tr(double& d1, double& d2, double& d3, string& s1,
string& s2, int& i1, int& i2, double& d4, double& d5, string& s3,
double& d6, double& d7, double& d8, double& d9, double& d10,
double& d11, double& ge) :
ei(d1), ef(d2), te(d3), ci(s1), cf(s2), ji(i1), jf(i2), angs_v(d4),
angs_a(d5), tr_type(s3), _sL(d6), _sV(d7), _gfL(d8), _gfV(d9),
_akiL(d10), _akiV(d11), GE_read(ge) {
int jj = (d1 <= d2) ? i1 : i2;
_f_ik = _gfL/(1*jj + 1);
lev_i = 0;
lev_f = 0;
}
void Dt::Level::mk_term() {
int ss = tmp.size();
if (ss < 2) return;
if (isdigit(tmp[ss-1]) || tmp[ss-1] == '*') {
ss--;
config = tmp.substr(0, ss - 3);
term = tmp.substr(ss - 2, 3);
} else {
config = tmp.substr(0, ss - 3);
term = tmp.substr(ss - 2, 2);
}
}
// ---->>>member functions of Dt::JTR_tr<<<-----
// void get_terms(); // not implemented
//----------------------------------------------------------
// --- member functions of Abstract Dt::Base_table
//--------------------------------------------------------
// sort the energies from low :->Dt::Base_table::sort_e()
void Dt::Base_table::sort_e() {
std::cout << "...sorting energies: ...\n\n";
// sort(lv.begin(),lv.end(),Comp());
lv.sort(Comp());
LCI p = lv.begin();
if (p == lv.end()) return;
(*p)->config_rep = (*p)->config;
(*p)->term_rep = (*p)->term;
string C(" ");
string T(" ");
string curr_C(" ");
string curr_T(" ");
for( ; p != lv.end(); p++) {
bool NC = false;
if (curr_T != (*p)->term) {
curr_C = (*p)->config;
curr_T = (*p)->term;
(*p)->config_rep = curr_C;
(*p)->term_rep = curr_T;
NC = true;
}
else (*p)->config_rep = " ";
if (!NC) {
if (curr_T != (*p)->term) {
curr_T = (*p)->term;
(*p)->term_rep = curr_T;
}
else (*p)->term_rep = " ";
}
// if (curr_SLC != (*pi)->Lconf_tex) {
// curr_SLC = (*pi)->Lconf_tex;
// sLC = curr_SLC;
// } else { sLC = ""; }
// if ( ++ptmp != lv.end()) {
// if ((*ptmp)->term != (*p)->term) {
// (*ptmp)->term_rep = (*ptmp)->term;
// }
// if ((*ptmp)->config != (*p)->config) {
// (*ptmp)->config_rep = (*ptmp)->config;
// (*ptmp)->term_rep = (*ptmp)->term;
// }
// (*ptmp)->term_rep = (*ptmp)->term;
// (*ptmp)->config_rep = (*ptmp)->config;
// }
}
}
// sort levels according to terms and check for duplicates
// :->Dt::Base_table::sort_t()
void Dt::Base_table::sort_t() {
std::cout << "...arranging terms: ...\n\n";
LI p1 = lv.begin();
LI p2 = lv.begin();
LI ptmp = lv.begin();
while (p1 != lv.end()) {
p1 = ptmp;
p2 = ++ptmp;
if (p2 == lv.end()) break;
while (p2 != lv.end()) {
if (Un_t(p1, p2)) {
// (*p2)->config_rep = "dupl. . . . . . . . . . . .->";
// (*p2)->term_rep = (*p2)->term;
(*p2)->unph = false;
if ((*ptmp)->unph) {
lv.insert(ptmp,(*p2));
p2 = lv.erase(p2);
} else if(++p2 != lv.end()) {}
} else if(++p2 != lv.end()) {}
}
}
//@@@@@@@@@@@@@2
string C(" ");
string T(" ");
string curr_C(" ");
string curr_T(" ");
for( LI p = lv.begin(); p != lv.end(); p++) {
bool NC = false;
if (curr_C != (*p)->config) {
curr_C = (*p)->config;
curr_T = (*p)->term;
(*p)->config_rep = curr_C;
(*p)->term_rep = curr_T;
NC = true;
}
else (*p)->config_rep = " ";
if (!NC) {
if (curr_T != (*p)->term) {
curr_T = (*p)->term;
(*p)->term_rep = curr_T;
}
else (*p)->term_rep = " ";
}
}
//@@@@@@@@@@@@@@@
}
void Dt::Base_table::rep_TC() {
for (LI pl = lv.begin(); pl != lv.end(); pl++) {
if (!((*pl)->unph)) {
(*pl)->config_rep = "dupl. . . . . . . . . . . .->";
(*pl)->term_rep = (*pl)->term;
}
}
}
// :->remove unphysical levels using CpRmTbLv
void Dt::Base_table::LV_rm_unph() {
lv.remove_if(CpRmTbLv());
// splitt();
}
// After sorting compute splitting, and sort
void Dt::Base_table::splitt(){
LI spb = lv.begin();
LI spe = lv.begin();
LI sptmp = lv.begin();
while(spb != lv.end()) {
spb = sptmp;
do {
if (++sptmp == lv.end()) break;
if (((*sptmp)->config == (*spb)->config) &&
((*sptmp)->term == (*spb)->term)) (*sptmp)->term_rep = " ";
}
while((((*sptmp)->config == (*spb)->config) &&
((*sptmp)->term == (*spb)->term)) && (sptmp != lv.end()));
spe = sptmp;
if(++spe == lv.end() || sptmp == lv.end()) break;
else {
while (spe != lv.end()) {
if (((*spe)->config == (*spb)->config) &&
((*spe)->term == (*spb)->term)) {
(*spe)->term_rep = " ";
lv.insert(sptmp,(*spe));
spe = lv.erase(spe);
} else if(++spe != lv.end()) {}
}
}
}
//@@@@@@@@@@@@@2
string C(" ");
string T(" ");
string curr_C(" ");
string curr_T(" ");
for( LI p = lv.begin(); p != lv.end(); p++) {
bool NC = false;
if (curr_C != (*p)->config) {
curr_C = (*p)->config;
curr_T = (*p)->term;
(*p)->config_rep = curr_C;
(*p)->term_rep = curr_T;
NC = true;
}
else (*p)->config_rep = " ";
if (!NC) {
if (curr_T != (*p)->term) {
curr_T = (*p)->term;
(*p)->term_rep = curr_T;
}
else (*p)->term_rep = " ";
}
}
//@@@@@@@@@@@@@@@
// end sort, compute splitting
LI pa = lv.begin();
LI pb = lv.begin();
while (pa != lv.end()) {
while(++pb != lv.end()) {
if ((*pb)->config==(*pa)->config && (*pa)->term==(*pb)->term)
{(*pb)->Splitting = (*pb)->lev - (*pa)->lev;}
else break;
}
pa = pb;
}
}
// This function does: 1. removes unphysical, 2. sorts *.lsj files,
// 3.sorts again for terms, 4.computes lifetimes 5. prints the trasnitions.
// remove unphysical
void Dt::Base_table::JTR_rmv() {
int A = lsj.size();
cout << lsj.size() << " lsj transitions initially\n";
for(JCI jp = lsj.begin(); jp != lsj.end(); jp++) {
(*jp)->unph = JTR_unph(jp);
}
// remove all lsj not present in table levels
lsj.remove_if(CmpRmJTR());
cout << "...sorting .lsj transitions\n" << endl;
JTR_sortLSJ();
JCI jr;
cout << "...checking .lsj for duplicates" << endl;
// jr = unique(lsj.begin(),lsj.end(),RmvDupl()); //remove any duplicate .lsj
lsj.erase(unique(lsj.begin(),lsj.end(),RmvDupl()),lsj.end());
cout << lsj.size() << " transitions after removing of "
<< A - lsj.size() << " duplicated transitions\n";
if (lsj.size() == 0 )
cerr << " There are 0 transitions, exit(1)\n", exit(1);
// sort the list of lsj
cout << "\nEnter a number to sort the transitions by:\n";
cout << " 1. Transition energies.\n";
cout << " 2. Lower-Upper.\n";
cout << " 3. Upper-Lower.\n";
cout << " 4. f value.\n";
cout << " 5. Line strength.\n";
cout << " 6. Wavelength(air).\n";
int s;
cin >> s;
switch (s) {
case 1:
JTR_sortE();
JTR_sortT();
break;
case 2:
JTR_sortELU();
JTR_sortT();
break;
case 3:
JTR_sortEUL();
JTR_sortT();
break;
case 4:
JTR_sortgF();
JTR_sortT();
break;
case 5:
JTR_sortSL();
JTR_sortT();
break;
case 6:
JTR_sortWL();
JTR_sortT();
break;
default:
JTR_sortE();
JTR_sortT();
}
JTR_sortELU();
JTR_multiplet();
}
void Dt::Base_table::JTR_multiplet() {
cout << " ...arranging by multiplets\n";
JCI jt = lsj.begin();
double E_ground (0);
if (Base_table::E_min)
E_ground = Base_table::E_min;
else
E_ground = (*jt)->ef;
for(JCI jp = lsj.begin(); jp != lsj.end(); jp++) {
bool ins = false;
for(JMP jm = jmp.begin(); jm != jmp.end(); jm++) {
if((*jp)->cf == (*jm)->C_low + '_' + (*jm)->T_low &&
(*jp)->ci == (*jm)->C_high + '_' + (*jm)->T_high ) ins = true;
if (ins) (*jm)->MP_add(*jp);
if (ins) break;
}
if (!ins) { // insert a new multiplet
JTR_mp* A = new JTR_mp(jp);
//cout << (*jp)->cf << (*jp)->tf << (*jp)->ci << (*jp)->ti << endl;
A->MP_add(*jp);
jmp.push_back(A);
}
}
Level_MP lmp(E_ground,this->lv);
for(JMP jm = jmp.begin(); jm != jmp.end(); jm++) {
(*jm)->lsjm.sort(Comp_lsjE());
(*jm)->MP_computeE(E_ground,lmp);
(*jm)->MP_compute_Aki();
// cout << (*jm)->C_low<<"_"<<(*jm)->T_low
// <<"-"<<(*jm)->C_high<<"_"<<(*jm)->T_high<<endl;
// cout << (*jm)->lsjm.size() << "=(*jm)->lsjm.size()\n";
}
}
class Dt::MP_Lev_comp {
public:
bool operator()(const Dt::JTR_mp::lev_map a,
const Dt::JTR_mp::lev_map b) const {
if (a.E != b.E) return a.E > b.E;
else return a.j2 < b.j2;
}
};
void Dt::JTR_mp::MP_add(JTR_tr* j) {
JTR_mkterms(T_low,C_low,j->cf);
JTR_mkterms(T_high,C_high,j->ci);
lsjm.push_back(j);
}
Dt::Level_MP::Level_MP(double E_ground,std::list<Level*>& lv) {
map<const char,int> Map_LS;
Map_LS['S'] = 0;
Map_LS['P'] = 1;
Map_LS['D'] = 2;
Map_LS['F'] = 3;
Map_LS['G'] = 4;
Map_LS['H'] = 5;
Map_LS['I'] = 6;
typedef map<string,int>::iterator SSI;
map<string,int>m_g;
for (LCI p = lv.begin(); p != lv.end(); p++) {
int _IT_U = int((*p)->term[0] - 48);
int _L_U = int(Map_LS[(*p)->term[1]]);
int gg = _IT_U*(2*_L_U+1);
string C = (*p)->config + "_" + (*p)->term;
lev_MPG[C] = gg;
int jj = (*p)->J;
m_g[C] += jj+1;
double Z(Print_table::_Z_);
double RZ(0);
fZ(Z,RZ);
double E = ((*p)->totalE-E_ground)*RZ*2*(jj+1)/gg;
lev_MPE[C] += E;
}
for (SSI p = lev_MPG.begin(); p != lev_MPG.end(); p++) {
string C = (*p).first;
if (m_g[C] != lev_MPG[C]) lev_MPG[C] = 0;
}
}
void Dt::JTR_mp::MP_computeE(double E_ground, Level_MP& lmp) {
string SH = C_high+"_"+T_high;
string SL = C_low+"_"+T_low;
MP_gk = lmp.lev_MPG[SH];
MP_gi = lmp.lev_MPG[SL];
E_low = lmp.lev_MPE[SL];
E_high = lmp.lev_MPE[SH];
E_tr = E_high - E_low;
MP_WL = 1e8/E_tr;
}
void Dt::JTR_mp::MP_compute_Aki() {
bool e1 = false;
for (JCI p = lsjm.begin(); p != lsjm.end(); p++) {
double a1, a2, a3;
a1 = (*p)->_akiL;
a2 = 1e8/(*p)->te;
a3 = (*p)->_f_ik;
double a4((*p)->ji+1);
double a5((*p)->jf+1);
double a6 = pow(a2,3);
if ((*p)->tr_type == "E1") {
MP_AKI += a1*a4*a6;
MP_f_ik += a2*a3*a5;
MP_S += (*p)->_sL;
e1 = true;
}
}
if (e1) MP_AKI /= (MP_gk*pow(MP_WL,3));
if (e1) MP_f_ik /= (MP_WL*MP_gi);
// cout << "::" << MP_AKI << "::" << MP_f_ik << "::" << MP_S <<"::"<< endl;
}
void Dt::Base_table::JTR_sortMP() {
jmp.sort(Comp_MP());
}
// a function comparing the levels, used in sorting *.lsj
bool Dt::Base_table::JTR_unph(JCI& jp) {
for (LCI pi = lv.begin(); pi != lv.end(); pi++) {
if(fabs((*pi)->totalE - (*jp)->ei) < 1e-8) {
for(LCI pf = lv.begin(); pf != lv.end(); pf++)
if(fabs((*pf)->totalE - (*jp)->ef) < 1e-8) return true;
}
}
for (LCI pi = lv.begin(); pi != lv.end(); pi++) {
if(fabs((*pi)->totalE - (*jp)->ei) < 1e-7) {
for(LCI pf = lv.begin(); pf != lv.end(); pf++)
if(fabs((*pf)->totalE - (*jp)->ef) < 1e-7) {
return true;
}
}
}
return false;
}
// all energies from *.lsj are sorted form low->high
void Dt::Base_table::JTR_sortE() {
lsj.sort(Comp_lsjE());
}
void Dt::Base_table::JTR_sortELU() {
lsj.sort(Comp_lsjLU());
}
void Dt::Base_table::JTR_sortEUL() {
lsj.sort(Comp_lsjUL());
}
void Dt::Base_table::JTR_sortWL() {
lsj.sort(Comp_lsjWL());
}
void Dt::Base_table::JTR_sortgF() {
lsj.sort(Comp_lsjgF());
}
void Dt::Base_table::JTR_sortSL() {
lsj.sort(Comp_lsjSL());
}
void Dt::Base_table::JTR_sortLSJ() {
lsj.sort(Comp_LSJ());
}
// more specialized sorting on sections of the *.lsj (alike)
void Dt::Base_table::JTR_sortT() {
JI jp = lsj.begin();
JI ji = lsj.begin();
while(jp != lsj.end()) {
for(ji = jp; ji != lsj.end(); ++ji) {
if ((*ji)->ci != (*jp)->ci) {
// cout << "< >" << jp << endl;
// cout << "<" <<++i << ">" << ji << endl;
break;
}
}
// jp: begining of the section
//->ji: end
//-------------------------------------
JI pb = jp;
JI pe = jp;
JI ptmp = jp;
while(pb != ji) {
pb = ptmp;
do {if (++ptmp == ji) break;}
while (((*ptmp)->cf == (*pb)->cf) && ptmp != ji);
pe = ptmp;
if(++pe == ji || ptmp == ji) break;
else {
while (pe != ji) {
if ((*pe)->cf == (*pb)->cf) {
if ((*pe)->te > (*pb)->te) lsj.insert(pb,(*pe));
else lsj.insert(ptmp,(*pe));
lsj.erase(pe);
pe = ptmp;
} else if(++pe != ji) {}
}
}
}
//--------------------------------------
// = -> advance to the next section
jp = ji;
}
}
// Computing the lifetimes
void Dt::Base_table::JTR_lifetimes() {
// map<double,double> lt;
typedef map<double,double>::const_iterator MCI;
cout << " ...Computing Liefetimes...\n" << endl;
typedef map<string,map<int,map<double,double> > >MMM;
MMM mmm;
for (JCI jb = lsj.begin(); jb != lsj.end(); jb++) {
mmm[(*jb)->ci][(*jb)->ji][(*jb)->ei] += (*jb)->_akiL;
//cout << (*jb)->ci << (*jb)->ji << (*jb)->ei << " == " << (*jb)->_akiL << endl;
}
for (LI lp = lv.begin(); lp != lv.end(); lp++) {
string _c = (*lp)->config + "_" + (*lp)->term;
int _j = (*lp)->J;
double _e = (*lp)->totalE;
double _e_lev = mmm[_c][_j].begin()->first;
double tr = mmm[_c][_j].begin()->second;
//cout << _c << _j << _e <<"::"<<_e_lev<< " == " << tr << endl;
if (tr && fabs(_e - _e_lev) < 10e-8) {
double _ti = 1/tr;
(*lp)->lifetime = _ti;
}
}
}
// separate terms, caled from JTR_print
void Dt::JTR_mkterms(string& term_i, string& config_i, string& sc_i) {
int szi = sc_i.size();
if (isdigit(sc_i[szi-1]) || sc_i[szi-1] == '*') {
szi--;
config_i = sc_i.substr(0,szi - 3);
term_i = sc_i.substr(szi - 2, 4);
} else {
config_i = sc_i.substr(0,szi - 3);
term_i = sc_i.substr(szi - 2, 3);
}
}
//##############################################
//##############################################
// printout .lsj.bin file
// not implemented for now
void Dt::Base_table::CpLT() {}
//----------------------------------------------------
// --- member functions of Dt::ETable_lsjini--
//----------------------------------------------------
Dt::ETable_lsjini::ETable_lsjini(const std::string& ss) :
file_name(ss), E_min(0) {
Base_table::E_min = 0;
// read *.lsj file
read_lsj(ss);
// compute levels
get_lev();
std::cout << "\n... " << file_name
<< " reading OK...\n";
// sort for energies
sort_e();
// sort terms
sort_t();
// set conf. and term representations;
rep_TC();
// compute RZ constant
fZ(Z,RZ);
// set global _Z_ _NEL_
// set_ZNEL();
comp_lev();
splitt();
print_lev(std::cout);
splitt();
// print_lev(std::cout,false);
}
class Dt::Lev_map_comp {
public:
bool operator()(const tmp_lv* a, const tmp_lv* b) const {
if (a->e != b->e) return a->e > b->e;
else {
if (a->s != b->s) return a->s > b->s;
else return a->i < b->i;
}
}
};
void Dt::ETable_lsjini::get_lev() {
//map all levels found in *.lsj onto an array of energies
map<tmp_lv*,Level*,Lev_map_comp> mpE;
list<Level*> lv_del;
for(JI jp = lsj.begin(); jp != lsj.end(); jp++) {
// for initial state:
double E = (*jp)->ei;
int J = (*jp)->ji;
string cs = (*jp)->ci;
Level* ni = new Level(cs,J,E);
lv_del.push_back(ni);
// for the final state
E = (*jp)->ef;
J = (*jp)->jf;
cs = (*jp)->cf;
Level* nf = new Level(cs,J,E);
lv_del.push_back(nf);
}
for (LI lp = lv_del.begin(); lp != lv_del.end(); lp++) {
//double E = (*lp)->totalE;
tmp_lv* E = new tmp_lv;
E->e = (*lp)->totalE;
E->i = (*lp)->J;
E->s = (*lp)->config + "_" + (*lp)->term;
mpE[E] = *lp;
}
typedef map<tmp_lv*,Level*,Lev_map_comp>::const_iterator MCI;
for (MCI mp = mpE.begin(); mp != mpE.end(); mp++) {
Level* lp = new Level(mp->second);
lv.push_back(lp);
}
}
void Dt::ETable_lsjini::comp_lev() {
LI p = lv.begin();
if (!Base_table::E_min) E_min = (*p)->totalE;
else E_min = Base_table::E_min;
for (p = lv.begin(); p != lv.end(); p++)
(*p)->lev = ((*p)->totalE - E_min) * 2 * RZ;
}
void Dt::ETable_lsjini::fZ(double& ZZ, double& RZ) {
ZZ = Print_table::_Z_;
NEL = Print_table::_NEL_;
Base_table::fZ(Z,RZ);
set_ZNEL();
}
void Dt::ETable_lsjini::set_ZNEL() {
Print_table::_RZ_ = RZ;
}
//----------------------------------------------------
// --- member functions of Dt::ETable_jini --
//----------------------------------------------------
// copy constructor -
Dt::ETable_jini::ETable_jini(const ETable_jini& t)
: RZ(t.RZ), Z(t.Z), dE(t.dE), NEL(t.NEL), iJ(t.iJ) ,
file_name(t.file_name) {}
// construct table of transitions from file.j
// the constructor does it all for levels
Dt::ETable_jini::ETable_jini(const std::string& ss) :
file_name(ss), E_min(0) {
std::cout << "\n...reading " << file_name << "...\n\n";
get_lev();
std::cout << "\n... " << file_name
<< " reading OK...\n\n";
sort_e();
sort_t();
rep_TC();
// set global _Z_ _NEL_
fZ(Z,RZ);
// set_ZNEL();
comp_lev();
splitt();
print_lev(std::cout);
read_lsj(ss);
}
// static integer counting how many levels are initially,
// used to specify what to remove
int Dt::ETable_jini::n_lev = 0;
// this function starts reading the *.j file, calls other members
void Dt::ETable_jini::get_lev() {
std::ifstream j_in(file_name.c_str());
std::string sw1("_123456789_123456789_123456789_123456789");
std::string sw2("_123456789_123456789_123456789_123456789");
std::cout << setw(80) << sw1 + sw2 << endl;
const int sz = buf;
static char t_read[sz];
while(j_in.getline(t_read,sz)) {
string test_end(t_read);
bool end_j(false);
string::size_type szt_e = test_end.find("END");
string::size_type szt_s = test_end.find("*");
if (szt_s > 2) szt_s = string::npos;
if (szt_e != string::npos || szt_s != string::npos) end_j = true;
if (end_j) { j_in.getline(t_read,sz); }
if (read_a(t_read))
for (int i = 0; i < 3; i++) j_in.getline(t_read,sz);
else { j_in.getline(t_read,sz); j_in.getline(t_read,sz); }
int nr = read_b(t_read);
for (int i = 0; i < nr; i++) {
j_in.getline(t_read,sz);
read_c(t_read);
j_in.getline(t_read,sz);
read_d(t_read);
int ii = ncfg/7;
int ad = ii * 78;
j_in.seekg(ad, std::ios::cur);
if(ncfg%7) { j_in.getline(t_read,sz); }
}
}
}
// read the line with Z=...
bool Dt::ETable_jini::read_a(const char* p) {
char p1[8], p2[4], p3[6], p4[8], a[2];
static char rd[buf];
for (int i = 0; i < buf; i++) rd[i] = p[i];
std::istrstream in(rd);
in >> p1 >> p2 >> a >> Z >> p3 >> a >> NEL >> p4 >> a >> ncfg;
if (p[10] == 'Z') return true;
return false;
}
// read the line with J, etc
int Dt::ETable_jini::read_b(char* p) {
static char rd[buf];
for (int i = 0; i < buf; i++){rd[i] = p[i];}
int nJ(0);
char p1[7], p2[9], a[2];
std::istrstream in(rd);
in >> p1 >> a >> iJ >> p2 >> a >> nJ;
cout << "\n\n Labels for 2J = " << iJ << "\n";
return nJ;
}
//read the line with Ssms, g_JTR, etc
void Dt::ETable_jini::read_c(char* p) {
static char rd[buf];
for (int i = 0; i < buf; i++) rd[i] = p[i];
char p1[6], p2[6], p3[6];
std::istrstream in(rd);
in >> p1 >> dSsms >> p2 >> dg_J >> p3 >> dg_JLS;
}
//read the line with the energy and configuration
std::string getOdd(std::string& conf);
void Dt::ETable_jini::read_d(char* p) {
n_lev++;
static char rd[buf];
for (int i = 0; i < buf; i++) rd[i] = p[i];
std::string configuration;
int nn;
std::istrstream in(rd);
in >> nn >> dE >> configuration;
configuration = getOdd(configuration);
if (dE < E_min) E_min = dE;
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios_base::left);
cout.precision(8);
cout << " " << setw(30) << configuration << dE << endl;
Level* nu = new Level(configuration,iJ,dE,0,0,dSsms,dg_J,dg_JLS);
lv.push_back(nu);
// std::cout << nu << endl;
}
void Dt::Base_table::fZ(double& ZZ, double& dRZ) {
// using namespace Dt;
double zmu = 0;
if (ZZ == 1) zmu = 1;
else if ( ZZ > 10) {zmu = 2 * ZZ + 1 + (ZZ - 11)/2;}
else if (!(int(ZZ)%2) || (ZZ == 7)) {zmu = 2 * ZZ;}
else {zmu = 2 * ZZ + 1;}
dRZ = RZN/(1+RZD/zmu);
}
// compute RZ as funcion of Z
void Dt::ETable_jini::fZ(double& ZZ, double& RZ) {
// using namespace Dt;
Base_table::fZ(Z,RZ);
set_ZNEL();
}
// compute levels using the factor RZ and energy diff
void Dt::ETable_jini::comp_lev() {
for (LI p = lv.begin(); p != lv.end(); p++)
(*p)->lev = ((*p)->totalE - E_min) * 2 * RZ;
}
| 27.554382 | 80 | 0.484058 | mansour2014 |
937f946d739cf99e35e03d6d5b2597457a9ddf41 | 6,266 | cc | C++ | dcmdata/libsrc/dcvrds.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 10 | 2016-07-03T12:16:58.000Z | 2021-12-18T06:15:50.000Z | dcmdata/libsrc/dcvrds.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 1 | 2020-04-30T07:55:55.000Z | 2020-04-30T07:55:55.000Z | dcmdata/libsrc/dcvrds.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 9 | 2017-02-09T02:16:39.000Z | 2021-01-06T02:49:24.000Z | /*
*
* Copyright (C) 1994-2011, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Gerd Ehlers, Andreas Barth
*
* Purpose: Implementation of class DcmDecimalString
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dcvrds.h"
#include "dcmtk/ofstd/ofstring.h"
#include "dcmtk/ofstd/ofstd.h"
#define MAX_DS_LENGTH 16
// ********************************
DcmDecimalString::DcmDecimalString(const DcmTag &tag,
const Uint32 len)
: DcmByteString(tag, len)
{
setMaxLength(MAX_DS_LENGTH);
setNonSignificantChars(" \\");
}
DcmDecimalString::DcmDecimalString(const DcmDecimalString &old)
: DcmByteString(old)
{
}
DcmDecimalString::~DcmDecimalString()
{
}
DcmDecimalString &DcmDecimalString::operator=(const DcmDecimalString &obj)
{
DcmByteString::operator=(obj);
return *this;
}
OFCondition DcmDecimalString::copyFrom(const DcmObject& rhs)
{
if (this != &rhs)
{
if (rhs.ident() != ident()) return EC_IllegalCall;
*this = OFstatic_cast(const DcmDecimalString &, rhs);
}
return EC_Normal;
}
// ********************************
DcmEVR DcmDecimalString::ident() const
{
return EVR_DS;
}
OFCondition DcmDecimalString::checkValue(const OFString &vm,
const OFBool /*oldFormat*/)
{
OFString strVal;
/* get "raw value" without any modifications (if possible) */
OFCondition l_error = getStringValue(strVal);
if (l_error.good())
l_error = DcmDecimalString::checkStringValue(strVal, vm);
return l_error;
}
// ********************************
OFCondition DcmDecimalString::getFloat64(Float64 &doubleVal,
const unsigned long pos)
{
/* get decimal string value */
OFString str;
OFCondition l_error = getOFString(str, pos, OFTrue /*normalize*/);
if (l_error.good())
{
OFBool success = OFFalse;
/* convert string to float value */
doubleVal = OFStandard::atof(str.c_str(), &success);
if (!success)
l_error = EC_CorruptedData;
}
return l_error;
}
OFCondition DcmDecimalString::getFloat64Vector(OFVector<Float64> &doubleVals)
{
/* get stored value */
char *strVal = NULL;
Uint32 strLen = 0;
OFCondition l_error = getString(strVal, strLen);
/* clear result variable */
doubleVals.clear();
if (l_error.good() && (strVal != NULL))
{
/* determine number of stored values */
const unsigned long vm = getVM();
if (vm > 0)
{
Float64 doubleVal;
OFString doubleStr;
char *p = strVal;
OFBool success = OFFalse;
/* avoid memory re-allocations by specifying the expected size */
doubleVals.reserve(vm);
/* iterate over the string value and search for delimiters */
for (Uint32 i = 0; i <= strLen; i++)
{
if ((i == strLen) || (*p == '\\'))
{
/* extract single value and convert it to floating point */
doubleStr.assign(strVal, p - strVal);
doubleVal = OFStandard::atof(doubleStr.c_str(), &success);
if (success)
{
/* store floating point value in result variable */
doubleVals.push_back(doubleVal);
strVal = p + 1;
}
else
{
l_error = EC_CorruptedData;
break;
}
}
++p;
}
}
}
return l_error;
}
// ********************************
OFCondition DcmDecimalString::getOFString(OFString &stringVal,
const unsigned long pos,
OFBool normalize)
{
/* call inherited method */
OFCondition l_error = DcmByteString::getOFString(stringVal, pos);
/* normalize string if required */
if (l_error.good() && normalize)
normalizeString(stringVal, !MULTIPART, DELETE_LEADING, DELETE_TRAILING);
return l_error;
}
// ********************************
OFCondition DcmDecimalString::writeXML(STD_NAMESPACE ostream &out,
const size_t flags)
{
if (flags & DCMTypes::XF_useNativeModel)
{
/* for the Native DICOM Model output, we do not need any specific DS handling */
return DcmElement::writeXML(out, flags);
} else {
/* XML start tag: <element tag="gggg,eeee" vr="XX" ...> */
writeXMLStartTag(out, flags);
/* write element value (if loaded) */
if (valueLoaded())
{
/* get string data (without normalization) */
char *value = NULL;
Uint32 length = 0;
getString(value, length);
if ((value != NULL) && (length > 0))
{
/* explicitly convert to OFString because of possible NULL bytes */
OFString stringVal(value, length);
const OFBool convertNonASCII = (flags & DCMTypes::XF_convertNonASCII) > 0;
/* check whether conversion to XML markup string is required */
if (OFStandard::checkForMarkupConversion(stringVal, convertNonASCII))
OFStandard::convertToMarkupStream(out, stringVal, convertNonASCII);
else
out << value;
}
}
/* XML end tag: </element> */
writeXMLEndTag(out, flags);
/* always report success */
return EC_Normal;
}
}
// ********************************
OFCondition DcmDecimalString::checkStringValue(const OFString &value,
const OFString &vm)
{
return DcmByteString::checkStringValue(value, vm, "ds", 6, MAX_DS_LENGTH);
}
| 27.482456 | 97 | 0.544845 | trice-imaging |
938170688cde2d88af3a3a9d0769ed1b138ce018 | 21,382 | hpp | C++ | src/search/tb2solver.hpp | Pierre-Mont/toulbar2 | 623b92d593eab2dc1e21df9f853c28cc84626ed6 | [
"MIT"
] | null | null | null | src/search/tb2solver.hpp | Pierre-Mont/toulbar2 | 623b92d593eab2dc1e21df9f853c28cc84626ed6 | [
"MIT"
] | null | null | null | src/search/tb2solver.hpp | Pierre-Mont/toulbar2 | 623b92d593eab2dc1e21df9f853c28cc84626ed6 | [
"MIT"
] | null | null | null | /** \file tb2solver.hpp
* \brief Generic solver.
*
*/
#ifndef TB2SOLVER_HPP_
#define TB2SOLVER_HPP_
#include "toulbar2lib.hpp"
#include "utils/tb2store.hpp"
template <class T>
class DLink;
template <class T>
class BTList;
class NeighborhoodStructure;
class RandomNeighborhoodChoice;
class ClustersNeighborhoodStructure;
class RandomClusterChoice;
class ParallelRandomClusterChoice;
const double epsilon = 1e-6; // 1./100001.
class Solver : public WeightedCSPSolver {
public:
class OpenNode {
private:
#ifdef OPENMPI
friend class serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& cost; // node lower bound
ar& first; // pointer of type intptr_t = ptrdiff_t based on signed integer type
ar& last; // means the "last" choice point in CPStore = vector<ChoicePoint> is at the adr (last-1)
}
#endif
Cost cost; // global lower bound associated to the open node
public:
ptrdiff_t first; // first position in the list of choice points corresponding to a branch in order to reconstruct the open node
ptrdiff_t last; // last position (excluded) in the list of choice points corresponding to a branch in order to reconstruct the open node
OpenNode() {} // default constructor added to avoid boost/serialization/access.hpp:130:9: error
OpenNode(Cost cost_, ptrdiff_t first_, ptrdiff_t last_)
: cost(cost_)
, first(first_)
, last(last_)
{
}
bool operator<(const OpenNode& right) const { return (cost > right.cost) || (cost == right.cost && ((last - first) < (right.last - right.first) || ((last - first) == (right.last - right.first) && last >= right.last))); } // reverse order to get the open node with first, the smallest lower bound, and next, the deepest depth, and next, the oldest time-stamp
Cost getCost(Cost delta = MIN_COST) const { return MAX(MIN_COST, cost - delta); }
};
class CPStore;
class OpenList FINAL : public std::priority_queue<OpenNode> {
private:
Cost clb; // current cluster lower bound built from closed nodes (independent of any soft arc consistency cost moves)
Cost cub; // current cluster upper bound (independent of any soft arc consistency cost moves)
public:
OpenList(Cost lb, Cost ub)
: clb(lb)
, cub(ub)
{
}
OpenList()
: clb(MAX_COST)
, cub(MAX_COST)
{
} /// \warning use also this method to clear an open list
void init()
{
clb = MAX_COST;
cub = MAX_COST;
}
bool finished() const
{
assert(clb <= cub);
return (empty() || CUT(top().getCost(), clb));
}
Cost getLb(Cost delta = MIN_COST) const { return MIN(MAX(MIN_COST, clb - delta), (empty() ? MAX_COST : top().getCost(delta))); }
Cost getClosedNodesLb(Cost delta = MIN_COST) const { return MAX(MIN_COST, clb - delta); }
void setClosedNodesLb(Cost lb, Cost delta = MIN_COST)
{
clb = MAX(MIN_COST, lb + delta);
assert(clb <= cub);
}
void updateClosedNodesLb(Cost lb, Cost delta = MIN_COST) { clb = MIN(clb, MAX(MIN_COST, lb + delta)); }
Cost getUb(Cost delta = MIN_COST) const { return MAX(MIN_COST, cub - delta); }
void setUb(Cost ub, Cost delta = MIN_COST) { cub = MAX(MIN_COST, ub + delta); }
void updateUb(Cost ub, Cost delta = MIN_COST)
{
Cost tmpub = MAX(MIN_COST, ub + delta);
cub = MIN(cub, tmpub);
clb = MIN(clb, tmpub);
}
size_type capacity() const { return c.capacity(); }
priority_queue::container_type::iterator begin() { return c.begin(); }
priority_queue::container_type::iterator end() { return c.end(); }
};
class SolutionTrie {
public:
class TrieNode {
public:
TrieNode(size_t w = 0);
~TrieNode();
vector<vector<TrieNode*>> insertSolution(const vector<Value>& sol, unsigned int pos, vector<vector<TrieNode*>> nodesAtPos);
vector<TrieNode*> sons;
vector<vector<TrieNode*>> insertNode(Value v, unsigned int pos, vector<vector<TrieNode*>> nodesAtPos);
bool present(Value v);
void printTrie(vector<Value>& sol);
static size_t nbSolutions;
static vector<size_t> widths;
};
SolutionTrie(){};
~SolutionTrie(){};
void init(const vector<Variable*>& vv);
void insertSolution(const vector<Value>& sol);
void printTrie();
size_t getNbSolutions() { return root.nbSolutions; };
vector<vector<TrieNode*>> getNodesAtPos() { return nodesAtPos; };
private:
TrieNode root;
vector<vector<TrieNode*>> nodesAtPos;
};
Mdd computeMDD(SolutionTrie* solTrie, Cost cost);
ostream& printLayers(ostream& os, Mdd mdd);
typedef enum {
CP_ASSIGN = 0,
CP_REMOVE = 1,
CP_INCREASE = 2,
CP_DECREASE = 3,
CP_REMOVE_RANGE = 4,
CP_MAX
} ChoicePointOp;
static const string CPOperation[CP_MAX]; // for pretty print
struct ChoicePoint {
private:
#ifdef OPENMPI
friend class serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& op;
ar& varIndex;
ar& value;
ar& reverse;
}
#endif
public:
ChoicePointOp op; // choice point operation
int varIndex; // variable wcsp's index
Value value; // variable's value
bool reverse; // true if the choice point corresponds to the last right branch of an open node
ChoicePoint() {} // default constructor added to avoid boost/serialization/access.hpp:130:9: error
ChoicePoint(ChoicePointOp op_, int var_, Value val_, bool rev_)
: op(op_)
, varIndex(var_)
, value(val_)
, reverse(rev_)
{
}
};
class CPStore FINAL : public vector<ChoicePoint> {
public:
ptrdiff_t start; // beginning of the current branch
ptrdiff_t stop; // deepest saved branch end (should be free at this position)
StoreCost index; // current branch depth (should be free at this position)
CPStore()
: start(0)
, stop(0)
, index(0)
{
}
void addChoicePoint(ChoicePointOp op, int varIndex, Value value, bool reverse);
void store()
{
start = stop;
index = start;
}
};
#ifdef OPENMPI
/**
* \brief class to send/receive work to/from workers in the form of an object i.e. a message in MPI's semantic //
*
*/
class Work {
private:
friend class serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& hbfs;
ar& nbNodes;
ar& nbBacktracks;
ar& nbDEE;
ar& nbRecomputationNodes;
ar& lb;
ar& ub;
ar& open;
ar& cp;
ar& sol;
}
public:
bool hbfs; // false if master cp/open memory is out
Long nbNodes;
Long nbBacktracks;
Long nbDEE;
Long nbRecomputationNodes;
Cost lb; // best lower bound known by the master or found by the worker
Cost ub; // best current solution a.k.a incumbent solution
vector<OpenNode> open; // priority queue which will contain the node(s) to eXchange between the processes
vector<ChoicePoint> cp; // vector of choice points
vector<Value> sol;
Work()
: hbfs(true)
, nbNodes(0)
, nbBacktracks(0)
, nbDEE(0)
, nbRecomputationNodes(0)
, lb(MIN_COST)
, ub(MAX_COST)
{
} // dummy message when stopping
/**
* @brief constructor used by the master
*/
Work(const CPStore& cpMaster_, OpenList& openMaster_, const Cost lbMaster_, const Cost ubMaster_, vector<Value>& sol_)
: hbfs(true)
, nbNodes(0)
, nbBacktracks(0)
, nbDEE(0)
, nbRecomputationNodes(0)
, lb(lbMaster_)
, ub(ubMaster_)
{
open.push_back(openMaster_.top());
openMaster_.pop(); // pop up directly the open queue!!
for (ptrdiff_t i = open[0].first; i < open[0].last; i++) { // create a sequence of decisions
assert(i >= 0 && (size_t)i < cpMaster_.size());
assert(i < cpMaster_.stop);
cp.push_back(cpMaster_[i]);
assert(cp.back().op >= 0 && cp.back().op < CP_MAX);
}
if (sol_.size() > 0) {
// sol.swap(sol_); //after the swap sol_ in the worker is an empty vector
sol = sol_;
}
}
/**
* @brief constructor used by the worker
*/
Work(CPStore& cpWorker_, OpenList& openWorker_, const Long nbNodes_, const Long nbBacktracks_, const Long nbDEE_, const Long nbRecomputationNodes_, const Cost lbWorker_, const Cost ubWorker_, vector<Value>& sol_)
: hbfs(true)
, nbNodes(nbNodes_)
, nbBacktracks(nbBacktracks_)
, nbDEE(nbDEE_)
, nbRecomputationNodes(nbRecomputationNodes_)
, lb(lbWorker_)
, ub(ubWorker_)
{
ptrdiff_t cpmax = 0; // stop collecting choice points if unused. however, we must start collecting choice points at position 0 to be consistent with stored node.first and node.last even if they are not used.
while (!openWorker_.empty()) // fill-in local vector of open nodes
{
OpenNode node = openWorker_.top();
assert(node.first >= 0);
assert(node.first <= node.last);
assert(node.last <= cpWorker_.stop);
cpmax = MAX(cpmax, node.last);
open.push_back(node);
openWorker_.pop(); // pop up directly the open queue!!
}
if (!ToulBar2::burst) {
openWorker_.init(); // clb=cub=MAX_COST method added to init openList attributes
// because emptying an openList is not enough we have to initialize its attributes
}
if (open.size() > 0) {
assert(cpmax <= cpWorker_.stop);
for (ptrdiff_t i = 0; i < cpmax; i++) {
assert((size_t)i < cpWorker_.size());
cp.push_back(cpWorker_[i]);
assert(cp.back().op >= 0 && cp.back().op < CP_MAX);
}
}
if (!ToulBar2::burst)
cpWorker_.clear(); // size = 0 added to put new cp out of the while(1)
// cpWorker_.shrink_to_fit(); // to win space we shrink the vector: capacity=0 //TODO: test if it speeds-up things or not
if (sol_.size() > 0) {
// sol.swap(sol_); //after the swap sol_ in the worker is an empty vector
sol = sol_;
}
}
friend ostream& operator<<(ostream& os, Work& work)
{
os << "[lb: " << work.lb << ", ub: " << work.ub << ", nbvars: " << work.sol.size() << ", nodes: " << work.open.size() << ", choices: " << work.cp.size() << "]";
return os;
}
};
#endif
void addChoicePoint(ChoicePointOp op, int varIndex, Value value, bool reverse);
void addOpenNode(CPStore& cp, OpenList& open, Cost lb, Cost delta = MIN_COST); ///< \param delta cost moved out from the cluster by soft arc consistency
void restore(CPStore& cp, OpenNode node);
char opSymbol(const CPStore& cp, const ptrdiff_t idx, OpenNode nd);
void epsDumpSubProblems(CPStore& cp, OpenList& open);
protected:
friend class NeighborhoodStructure;
friend class RandomNeighborhoodChoice;
friend class ClustersNeighborhoodStructure;
friend class RandomClusterChoice;
friend class ParallelRandomClusterChoice;
friend class VACExtension;
Long nbNodes;
Long nbBacktracks;
Long nbBacktracksLimit;
WeightedCSP* wcsp;
vector<DLink<Value>*> allVars;
BTList<Value>* unassignedVars;
int lastConflictVar;
void* searchSize;
BigInteger nbSol;
Long nbSGoods; //number of #good which created
Long nbSGoodsUse; //number of #good which used
map<int, BigInteger> ubSol; // upper bound of solution number
double timeDeconnect; // time for the disconnection
int tailleSep;
CPStore* cp; // choice point cache for open nodes (except BTD)
OpenList* open; // list of open nodes (except BTD)
Long hbfsLimit; // limit on number of backtracks for hybrid search (except BTD)
Long nbHybrid;
Long nbHybridContinue;
Long nbHybridNew;
Long nbRecomputationNodes;
//only for pretty print of optimality gap information
Cost initialLowerBound;
Cost globalLowerBound;
Cost globalUpperBound;
int initialDepth;
void initGap(Cost newlb, Cost newub);
void showGap(Cost newlb, Cost newub);
Cost prevDivSolutionCost;
SolutionTrie solTrie;
// Heuristics and search methods
/// \warning hidden feature: do not branch on variable indexes from ToulBar2::nbDecisionVars to the last variable
void initVarHeuristic();
int getVarMinDomainDivMaxWeightedDegreeLastConflictRandomized();
int getVarMinDomainDivMaxWeightedDegreeLastConflict();
int getVarMinDomainDivMaxWeightedDegreeRandomized();
int getVarMinDomainDivMaxWeightedDegree();
int getVarMinDomainDivMaxDegreeLastConflictRandomized();
int getVarMinDomainDivMaxDegreeLastConflict();
int getVarMinDomainDivMaxDegreeRandomized();
int getVarMinDomainDivMaxDegree();
int getNextUnassignedVar();
int getMostUrgent();
void Manage_Freedom(Cluster* cluster);
double nbChoices;
double nbForcedChoices;
double nbForcedChoiceChange;
double nbChoiceChange;
double nbReadOnly;
int solveDepth;
void increase(int varIndex, Value value, bool reverse = false);
void decrease(int varIndex, Value value, bool reverse = false);
void assign(int varIndex, Value value, bool reverse = false);
void remove(int varIndex, Value value, bool reverse = false);
void remove(int varIndex, ValueCost* array, int first, int last, bool reverse = false);
void conflict() {}
void enforceUb();
void singletonConsistency();
void binaryChoicePoint(int xIndex, Value value, Cost lb = MIN_COST);
void binaryChoicePointLDS(int xIndex, Value value, int discrepancy);
void narySortedChoicePoint(int xIndex, Cost lb = MIN_COST);
void narySortedChoicePointLDS(int xIndex, int discrepancy);
Value postponeRule(int varIndex);
void scheduleOrPostpone(int varIndex);
int getVarMinDomainDivMaxWeightedDegreeLastConflictRandomized(Cluster* cluster);
int getVarMinDomainDivMaxWeightedDegreeLastConflict(Cluster* cluster);
int getVarMinDomainDivMaxWeightedDegreeRandomized(Cluster* cluster);
int getVarMinDomainDivMaxWeightedDegree(Cluster* cluster);
int getVarMinDomainDivMaxDegreeLastConflictRandomized(Cluster* cluster);
int getVarMinDomainDivMaxDegreeLastConflict(Cluster* cluster);
int getVarMinDomainDivMaxDegreeRandomized(Cluster* cluster);
int getVarMinDomainDivMaxDegree(Cluster* cluster);
int getNextUnassignedVar(Cluster* cluster);
pair<Cost, Cost> binaryChoicePoint(Cluster* cluster, Cost lbgood, Cost cub, int varIndex, Value value);
pair<Cost, Cost> recursiveSolve(Cluster* cluster, Cost lbgood, Cost cub);
pair<Cost, Cost> hybridSolve(Cluster* root, Cost clb, Cost cub);
#ifdef OPENMPI
double hbfsWaitingTime;
Long initWorkerNbNodes;
Long initWorkerNbBacktracks;
Long initWorkerNbDEE;
Long initWorkerNbRecomputationNodes;
mpi::communicator world;
queue<int> idleQ; //MASTER ONLY container with the rank of the free workers
std::unordered_map<int, OpenNode> activeWork; //MASTER ONLY map the rank i of a worker with an open node currently explored by the worker
std::unordered_map<int, Cost> bestsolWork; //MASTER ONLY map the rank i of a worker with the cost of the best solution sent by the master
inline bool MPI_interrupted()
{
if (world.iprobe(mpi::any_source, DIETAG))
return true;
else
return false;
}
pair<Cost, Cost> hybridSolveMaster(Cluster* root, Cost clb, Cost cub);
pair<Cost, Cost> hybridSolveWorker(Cluster* root, Cost clb, Cost cub);
#endif
pair<Cost, Cost> russianDollSearch(Cluster* c, Cost cub);
BigInteger binaryChoicePointSBTD(Cluster* cluster, int varIndex, Value value);
BigInteger sharpBTD(Cluster* cluster);
void approximate(BigInteger& nbsol, TreeDecomposition* td);
public:
Solver(Cost initUpperBound);
virtual ~Solver();
Cost read_wcsp(const char* fileName);
void read_random(int n, int m, vector<int>& p, int seed, bool forceSubModular = false, string globalname = "");
Long getNbNodes() const FINAL { return nbNodes; }
Long getNbBacktracks() const FINAL { return nbBacktracks; }
set<int> getUnassignedVars() const;
unsigned int numberOfUnassignedVariables() const; // faster than its WCSP linear-time counterpart, but it is valid only during search (otherwise returns -1)
void updateVarHeuristic(); /// \brief to be called if DAC order has been changed after preprocessing (initVarHeuristic call)
virtual bool solve(bool first = true);
// internal methods called by solve, for advanced programmers only!!!
void beginSolve(Cost ub);
Cost preprocessing(Cost ub);
void recursiveSolve(Cost lb = MIN_COST);
void recursiveSolveLDS(int discrepancy);
pair<Cost, Cost> hybridSolve() { return hybridSolve(NULL, wcsp->getLb(), wcsp->getUb()); }
void endSolve(bool isSolution, Cost cost, bool isComplete);
// end of internal solve methods
Cost narycsp(string cmd, vector<Value>& solution);
bool solve_symmax2sat(int n, int m, int* posx, int* posy, double* cost, int* sol);
void dump_wcsp(const char* fileName, bool original = true, ProblemFormat format = WCSP_FORMAT);
void read_solution(const char* fileName, bool updateValueHeuristic = true);
void parse_solution(const char* certificate, bool updateValueHeuristic = true);
virtual void newSolution();
const vector<Value> getSolution() { return wcsp->getSolution(); }
Double getSolutionValue() const { return wcsp->getSolutionValue(); }
Cost getSolutionCost() const { return wcsp->getSolutionCost(); }
Cost getSolution(vector<Value>& solution) const
{
Cost cost = MAX_COST;
solution = wcsp->getSolution(&cost);
return cost;
}
vector<pair<Double, vector<Value>>> getSolutions() const { return wcsp->getSolutions(); }
friend void setvalue(int wcspId, int varIndex, Value value, void* solver);
WeightedCSP* getWCSP() FINAL { return wcsp; }
};
#ifdef OPENMPI
BOOST_IS_MPI_DATATYPE(Solver::OpenNode)
BOOST_IS_BITWISE_SERIALIZABLE(Solver::OpenNode) // only for simple datatypes with no pointer or any varying size objects (vectors, etc.)
BOOST_CLASS_IMPLEMENTATION(Solver::OpenNode, serialization::object_serializable)
BOOST_CLASS_TRACKING(Solver::OpenNode, serialization::track_never)
BOOST_IS_MPI_DATATYPE(Solver::ChoicePoint)
BOOST_IS_BITWISE_SERIALIZABLE(Solver::ChoicePoint)
BOOST_CLASS_IMPLEMENTATION(Solver::ChoicePoint, serialization::object_serializable)
BOOST_CLASS_TRACKING(Solver::ChoicePoint, serialization::track_never)
BOOST_CLASS_IMPLEMENTATION(Solver::Work, serialization::object_serializable)
BOOST_CLASS_TRACKING(Solver::Work, serialization::track_never)
#endif
class SolverOut : public std::exception {
public:
SolverOut()
{
ToulBar2::limited = true;
if (ToulBar2::verbose >= 2)
cout << SolverOut::what() << endl;
}
virtual const char* what() const throw() { return "... some solver limit was reached!"; }
};
class NbBacktracksOut : public SolverOut {
public:
const char* what() const throw() FINAL { return "... limit on the number of backtracks reached!"; }
};
class NbSolutionsOut : public SolverOut {
public:
const char* what() const throw() FINAL { return "... limit on the number of solutions reached!"; }
};
class DivSolutionOut : public SolverOut {
public:
const char* what() const throw() FINAL { return "... optimal diverse solution found!"; }
};
class TimeOut : public SolverOut {
public:
const char* what() const throw() FINAL { return "... time limit reached!"; }
};
int solveSymMax2SAT(int n, int m, int* posx, int* posy, double* cost, int* sol);
extern "C" int solvesymmax2sat_(int* n, int* m, int* posx, int* posy, double* cost, int* sol);
#endif /*TB2SOLVER_HPP_*/
/* Local Variables: */
/* c-basic-offset: 4 */
/* tab-width: 4 */
/* indent-tabs-mode: nil */
/* c-default-style: "k&r" */
/* End: */
| 37.710758 | 365 | 0.637592 | Pierre-Mont |
9383fb7c456ca6b9e333b347b17c8d78ea68ba56 | 629 | cpp | C++ | TargetFileReader.cpp | pderocco/digital-chroma-toolkit | 7db00bff7baa28b08a1b929c67c40e97c2b5b121 | [
"MIT"
] | null | null | null | TargetFileReader.cpp | pderocco/digital-chroma-toolkit | 7db00bff7baa28b08a1b929c67c40e97c2b5b121 | [
"MIT"
] | null | null | null | TargetFileReader.cpp | pderocco/digital-chroma-toolkit | 7db00bff7baa28b08a1b929c67c40e97c2b5b121 | [
"MIT"
] | null | null | null | // TargetFileReader.cpp
#include <QByteArray>
#include <QResource>
#include "TargetFileReader.h"
QVariant TargetFileReader::read(QString p) {
QResource f(p);
// If no resource, return null.
if (!f.isValid())
return QVariant();
// Create array large enough for Sysex header, file contents, EOX.
int n = f.size();
QByteArray a(n + 6, 0);
// Fill in header, read file, fill in EOX.
char* d = a.data();
d[0] = char(0xF0);
d[1] = 0;
d[2] = 0;
d[3] = 0x14;
d[4] = 'D';
memcpy(&d[5], f.data(), n);
d[n + 5] = char(0xF7);
// Return array.
return a;
}
| 20.290323 | 70 | 0.556439 | pderocco |
93883b79554159839da6b0573079798ea537c072 | 3,204 | cpp | C++ | developments/kernel/test/utkernel/one_shot_timer_test.cpp | kokabe2/surfes | 7c93fc08e74973cef53cf4a5859767201d457134 | [
"MIT"
] | null | null | null | developments/kernel/test/utkernel/one_shot_timer_test.cpp | kokabe2/surfes | 7c93fc08e74973cef53cf4a5859767201d457134 | [
"MIT"
] | null | null | null | developments/kernel/test/utkernel/one_shot_timer_test.cpp | kokabe2/surfes | 7c93fc08e74973cef53cf4a5859767201d457134 | [
"MIT"
] | null | null | null | // Copyright(c) 2019 Ken Okabe
// This software is released under the MIT License, see LICENSE.
#include "gtest/gtest.h"
extern "C" {
#include "impl/fake_alarmhandler.h"
#include "one_shot_timer.h"
}
namespace {
const int kDummyParameter = 1234;
void* given_parameter;
bool was_ran;
void FakeFunction(void* parameter) {
was_ran = true;
given_parameter = parameter;
}
} // namespace
class OneShotTimerTest : public ::testing::Test {
protected:
Timer instance;
virtual void SetUp() {
fake_alarmhandler_init();
instance = OneShotTimer_Create(FakeFunction, 10, (void*)&kDummyParameter);
was_ran = false;
given_parameter = NULL;
}
virtual void TearDown() { Timer_Destroy(&instance); }
};
TEST_F(OneShotTimerTest, Create) {
EXPECT_TRUE(instance != NULL);
EXPECT_EQ(TA_HLNG, fake_alarmhandler_getAttribute(0));
EXPECT_TRUE(fake_alarmhandler_isActive(0));
EXPECT_EQ(10, fake_alarmhandler_getLeftTime(0));
}
TEST_F(OneShotTimerTest, CreateWithNullFunction) {
EXPECT_EQ(NULL, OneShotTimer_Create(NULL, 10, (void*)&kDummyParameter));
}
TEST_F(OneShotTimerTest, CreateWithTimeLessThanZero) {
EXPECT_EQ(NULL,
OneShotTimer_Create(FakeFunction, -1, (void*)&kDummyParameter));
}
TEST_F(OneShotTimerTest, RunScheduledFunction) {
EXPECT_FALSE(was_ran);
fake_alarmhandler_countdown(0, 20);
EXPECT_TRUE(was_ran);
EXPECT_EQ((void*)&kDummyParameter, given_parameter);
EXPECT_FALSE(fake_alarmhandler_isActive(0));
EXPECT_EQ(0, fake_alarmhandler_getLeftTime(0));
}
TEST_F(OneShotTimerTest, Destroy) {
EXPECT_TRUE(fake_alarmhandler_isCreated(0));
Timer_Destroy(&instance);
EXPECT_EQ(NULL, instance);
EXPECT_FALSE(fake_alarmhandler_isCreated(0));
}
TEST_F(OneShotTimerTest, DestroyAfterDestroy) {
Timer_Destroy(&instance);
Timer_Destroy(&instance);
SUCCEED();
}
TEST_F(OneShotTimerTest, DestroyWithNull) {
Timer_Destroy(NULL);
SUCCEED();
}
TEST_F(OneShotTimerTest, Pause) {
Timer_Pause(instance);
fake_alarmhandler_countdown(0, 20);
EXPECT_FALSE(was_ran);
EXPECT_FALSE(fake_alarmhandler_isActive(0));
EXPECT_EQ(0, fake_alarmhandler_getLeftTime(0));
}
TEST_F(OneShotTimerTest, PauseWithNull) {
Timer_Pause(NULL);
SUCCEED();
}
TEST_F(OneShotTimerTest, Resume) {
fake_alarmhandler_countdown(0, 5);
Timer_Pause(instance);
Timer_Resume(instance);
EXPECT_FALSE(was_ran);
EXPECT_TRUE(fake_alarmhandler_isActive(0));
EXPECT_EQ(5, fake_alarmhandler_getLeftTime(0));
}
TEST_F(OneShotTimerTest, ResumeWhenNotPauseed) {
fake_alarmhandler_countdown(0, 5);
Timer_Resume(instance);
EXPECT_FALSE(was_ran);
EXPECT_TRUE(fake_alarmhandler_isActive(0));
EXPECT_EQ(5, fake_alarmhandler_getLeftTime(0));
}
TEST_F(OneShotTimerTest, ResumeAfterStopped) {
fake_alarmhandler_countdown(0, 20);
was_ran = false;
Timer_Resume(instance);
EXPECT_FALSE(was_ran);
EXPECT_FALSE(fake_alarmhandler_isActive(0));
EXPECT_EQ(0, fake_alarmhandler_getLeftTime(0));
}
TEST_F(OneShotTimerTest, ResumeWithNull) {
Timer_Pause(instance);
Timer_Resume(NULL);
SUCCEED();
}
| 23.733333 | 79 | 0.726592 | kokabe2 |
938ced3bc6080f3dfacb6333f27bed33084423ba | 6,333 | cpp | C++ | src/Core/Serialization/Deserializer.cpp | JijaLoqie/MxEngine | b82dbeefac416c15d44bf134058f668eb071078e | [
"BSD-3-Clause"
] | null | null | null | src/Core/Serialization/Deserializer.cpp | JijaLoqie/MxEngine | b82dbeefac416c15d44bf134058f668eb071078e | [
"BSD-3-Clause"
] | null | null | null | src/Core/Serialization/Deserializer.cpp | JijaLoqie/MxEngine | b82dbeefac416c15d44bf134058f668eb071078e | [
"BSD-3-Clause"
] | null | null | null | // Copyright(c) 2019 - 2020, #Momo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and /or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Serialization.h"
#include "Utilities/STL/MxMap.h"
#include "Utilities/Logging/Logger.h"
#include "Core/Runtime/ResourceReflection.h"
#include "Core/Runtime/HandleMappings.h"
namespace MxEngine
{
rttr::variant VisitDeserialize(const JsonFile& json, const rttr::variant& property, HandleMappings& mappings);
template<typename T>
rttr::variant DeserializeGeneric(const JsonFile& json, const rttr::type& type)
{
return json.empty() ? rttr::variant{ } : rttr::variant{ json.get<T>() };
}
rttr::variant DeserializeSequentialContainer(const JsonFile& json, const rttr::variant& property, HandleMappings& mappings)
{
auto view = property.create_sequential_view();
if (view.is_dynamic())
{
view.clear();
view.set_size(json.size());
}
size_t size = Min(view.get_size(), json.size());
for (size_t index = 0; index < size; index++)
{
auto element = view.get_value(index);
auto result = VisitDeserialize(json[index], element.extract_wrapped_value(), mappings);
view.set_value(index, result);
}
return property;
}
rttr::variant DeserializeEnumeration(const JsonFile& json, const rttr::variant& property, HandleMappings& mappings)
{
return json.empty() ? rttr::variant{ } : property.get_type().get_enumeration().name_to_value(json.get<MxString>().c_str());
}
rttr::variant Deserialize(const JsonFile& json, const rttr::variant& property, HandleMappings& mappings)
{
if (IsHandle(property))
{
size_t handleId = json;
return GetHandleById(property.get_type(), handleId, mappings);
}
else
{
Deserialize(json, rttr::instance{ property }, mappings);
return property;
}
}
rttr::variant VisitDeserialize(const JsonFile& json, const rttr::variant& property, HandleMappings& mappings)
{
#define VISITOR_DESERIALIZE_ENTRY(TYPE) { rttr::type::get<TYPE>(), DeserializeGeneric<TYPE> }
using DeserializeCallback = rttr::variant(*)(const JsonFile&, const rttr::type&);
static MxMap<rttr::type, DeserializeCallback> visitor = {
VISITOR_DESERIALIZE_ENTRY(bool),
VISITOR_DESERIALIZE_ENTRY(MxString),
VISITOR_DESERIALIZE_ENTRY(float),
VISITOR_DESERIALIZE_ENTRY(int),
VISITOR_DESERIALIZE_ENTRY(unsigned int),
VISITOR_DESERIALIZE_ENTRY(size_t),
VISITOR_DESERIALIZE_ENTRY(Quaternion),
VISITOR_DESERIALIZE_ENTRY(Vector2),
VISITOR_DESERIALIZE_ENTRY(Vector3),
VISITOR_DESERIALIZE_ENTRY(Vector4),
};
auto type = property.get_type();
if (visitor.find(type) != visitor.end())
{
return visitor[type](json, type);
}
else if (type.is_sequential_container())
{
return DeserializeSequentialContainer(json, property, mappings);
}
else if (type.is_enumeration())
{
return DeserializeEnumeration(json, property, mappings);
}
else
{
return Deserialize(json, property, mappings);
}
}
void Deserialize(const JsonFile& json, rttr::instance object, HandleMappings& mappings)
{
auto type = object.get_type();
for (auto property : type.get_properties())
{
ReflectionMeta propertyMeta(property);
if ((propertyMeta.Flags & MetaInfo::SERIALIZABLE) == 0) continue;
const char* propertyName = property.get_name().cbegin();
if (propertyMeta.Serialization.CustomDeserialize != nullptr)
{
propertyMeta.Serialization.CustomDeserialize(json[propertyName], object, mappings);
}
else
{
if (json.contains(propertyName))
{
auto result = VisitDeserialize(json[propertyName], property.get_value(object), mappings);
if (result.is_valid())
{
property.set_value(object, result);
}
}
}
}
if (type.get_properties().empty())
{
MXLOG_WARNING("MxEngine::Serializer", "no properties for type: " + MxString(object.get_type().get_name().cbegin()));
}
}
void DeserializeComponentImpl(const JsonFile& json, rttr::instance object, rttr::variant handle, HandleMappings& mappings)
{
size_t jsonHandleId = json["id"];
mappings.TypeToProjection[handle.get_type()][jsonHandleId] = handle;
Deserialize(json, object, mappings);
}
} | 39.58125 | 131 | 0.647718 | JijaLoqie |
938e06315aa64c257b95429338443a2ff93dcca5 | 20,395 | cc | C++ | examples/bouncingBall/src/bouncingBallBenchmark.cc | ju6ge/rbdl-orb | 321e20e80e2859a3a2ab43629c7c26c1020cb6f6 | [
"Zlib"
] | 12 | 2020-04-30T19:32:18.000Z | 2021-07-13T11:30:23.000Z | examples/bouncingBall/src/bouncingBallBenchmark.cc | ju6ge/rbdl-orb | 321e20e80e2859a3a2ab43629c7c26c1020cb6f6 | [
"Zlib"
] | 2 | 2020-06-04T23:16:07.000Z | 2022-03-19T23:37:28.000Z | examples/bouncingBall/src/bouncingBallBenchmark.cc | ju6ge/rbdl-orb | 321e20e80e2859a3a2ab43629c7c26c1020cb6f6 | [
"Zlib"
] | 10 | 2020-02-01T20:38:18.000Z | 2021-06-01T22:28:24.000Z | /*====================================================================
bouncingBallBenchmark.cc
Copyright (c) 2019 Matthew Millard <matthew.millard@iwr.uni-heidelberg.de>
Licensed under the zlib license. See LICENSE for more details.
*///=================================================================
#include <string>
#include <iostream>
#include <stdio.h>
#include <rbdl/rbdl.h>
#include <rbdl/addons/luamodel/luamodel.h>
#include <rbdl/addons/geometry/geometry.h>
#include "csvtools.h"
#include "ContactToolkit.h"
#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>
#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>
#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>
#include <boost/numeric/odeint/stepper/generation/make_controlled.hpp>
//using namespace std;
using namespace boost::numeric::odeint;
using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;
//====================================================================
// Boost stuff
//====================================================================
typedef std::vector< double > state_type;
typedef runge_kutta_cash_karp54< state_type > error_stepper_type;
typedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;
class rbdlToBoost {
public:
rbdlToBoost(Model* model,
std::string &ballName,
double ballRadius,
Vector3d &pointOnPlane,
Vector3d &planeNormal,
double stiffness,
double exponent,
double damping,
double staticFrictionSpeed,
double staticFrictionCoefficient,
double dynamicFrictionSpeed,
double dynamicFrictionCoefficient,
double viscousFrictionSlope,
unsigned int numberOfWorkTermsInState
):model(model),r(ballRadius),r0P0(pointOnPlane),
eN0(planeNormal),k(stiffness),p(exponent),beta(damping),
staticFrictionSpeed(staticFrictionSpeed),
staticFrictionCoefficient(staticFrictionCoefficient),
dynamicFrictionSpeed(dynamicFrictionSpeed),
dynamicFrictionCoefficient(dynamicFrictionCoefficient),
viscousFrictionSlope(viscousFrictionSlope),
numberOfWorkTermsInState(numberOfWorkTermsInState)
{
q = VectorNd::Zero(model->dof_count);
qd = VectorNd::Zero(model->dof_count);
qdd = VectorNd::Zero(model->dof_count);
tau = VectorNd::Zero(model->dof_count);
fext.resize(model->mBodies.size());
for(unsigned int i=0; i<fext.size();++i){
fext[i]=SpatialVector::Zero();
}
ballId = model->GetBodyId(ballName.c_str());
fK0n = Vector3dZero;
tK0n = Vector3dZero;
fK0t = Vector3dZero;
tK0t = Vector3dZero;
//1a. The regularized friction model is created and printed to file
ContactToolkit::createRegularizedFrictionCoefficientCurve(
staticFrictionSpeed, staticFrictionCoefficient,
dynamicFrictionSpeed,dynamicFrictionCoefficient,
viscousFrictionSlope,"mu",frictionCoefficientCurve);
frictionCoefficientCurve.printCurveToCSVFile("../output/",
"frictionCoefficientCurve",0,dynamicFrictionSpeed*2);
printf("Wrote: ../output/frictionCoefficentCurve.csv\n");
//Set the velocity at which the relaxed method is used to compute
//the direction vector of the tangential velocity of the contact
//point
veps = staticFrictionSpeed/100.0;
//If veps is too small, we really might have problems
assert(veps > std::sqrt(std::numeric_limits<double>::epsilon()));
}
//1b. The state derivative for this model is called by Boost whenever the
// code for the 'operator()' function is called
void operator() (const state_type &x,
state_type &dxdt,
const double t){
//1c. The state x is split into generalized positions (q), generalized
// velocities (qdd). Here tau is set to 0 because we are not
// applying any generlized forces: the ball contact/friction forces
// are applied as external forces
//q
int j = 0;
for(unsigned int i=0; i<model->q_size; i++){
q[i] = double(x[j]);
j++;
}
//qd
for(unsigned int i=0; i<model->qdot_size; i++){
qd[i] = double(x[j]);
j++;
}
//tau = 0
for(unsigned int i=0; i<model->qdot_size; i++){
tau[i] = 0;
}
//2a. To evaluate the contact forces we must see if the ball is interpenetrating
// the ground. Outside of FEA modelling it is common to allow (non deforming)
// geometry to intepenetrate and to use the interpenetration to compute
// contact forces. Here we go with the simplest option and map the
// depth of penetration to a contact force.
r0B0 = CalcBodyToBaseCoordinates(*model,q,ballId,Vector3dZero,true);
ContactToolkit::calcSpherePlaneContactPointPosition(r0B0,r,eN0,r0K0);
//if the contact point is in the sphere compute contact data
z = (r0K0-r0P0).dot(eN0);
dz=0.; //this is zero until contact is made
if( z < 0. ){
//2b. If the sphere is in contact with the plane, we must get the position and
//velocity of the contact point.
//Get the point of contact resolved in the coordinates of the ball
EB0 = CalcBodyWorldOrientation(*model,q,ballId,true);
rBKB = EB0*(r0K0-r0B0);
//Get the velocity of the point of contact
v0K0 = CalcPointVelocity(*model,q,qd,ballId,rBKB,true);
//Evaluate Hunt-Crossley Contact forces
dz = (v0K0).dot(eN0); //assuming the plane is fixed.
//2c. Now we can evaluate the contact forces using a Hunt-Crossley contact model
// This is a popular contact model because it is numerically well behaved.
// See the comments in ContactToolkit.h above the function definition
// for calcHuntCrossleyContactForce for further details.
ContactToolkit::calcHuntCrossleyContactForce(z,dz,k,p,beta,hcInfo);
//2d. To apply this contact force as an external force in RBDL, we must first
// transform it into a spatial wrench that is resolved in the Root frame.
// Here we turn the scalar contact force into a vector, and then evaluate
// the torque that this force vector produces about the Root frame
fK0n = hcInfo.force*eN0;
tK0n = VectorCrossMatrix(r0K0)*fK0n;
//2e. Now we can use the tangential velocity of the contact point of the ball
// to evaluate the coefficient of friction, and then the friction forces
v0K0t = v0K0 - dz*eN0;
ContactToolkit::calcTangentialVelocityDirection(v0K0t,veps,eT0);
mu = frictionCoefficientCurve.calcValue(v0K0t.norm());
//2f. As with the contact model we evaluate the force the friction model applies
// to the ball and also the torque it generates about the ROOT frame
fK0t = -mu*hcInfo.force*eT0;
tK0t = VectorCrossMatrix(r0K0)*fK0t;
//2g. The total wrench generated by the contact and friction models is applied to
// the entry in the vector fext that corresponds to the ball.
fext[ballId][0] = tK0n[0] + tK0t[0];
fext[ballId][1] = tK0n[1] + tK0t[1];
fext[ballId][2] = tK0n[2] + tK0t[2];
fext[ballId][3] = fK0n[0] + fK0t[0];
fext[ballId][4] = fK0n[1] + fK0t[1];
fext[ballId][5] = fK0n[2] + fK0t[2];
}else{
//zero the entry of fext associated with the ball.
fext[ballId]=SpatialVector::Zero();
hcInfo.force = 0.;
hcInfo.springForce = 0.;
hcInfo.dampingForce = 0.;
fK0n = Vector3dZero;
tK0n = Vector3dZero;
fK0t = Vector3dZero;
tK0t = Vector3dZero;
}
//3a. Now the generalized accelerations of the ball can be computed
ForwardDynamics(*model,q,qd,tau,qdd,&fext);
//3b. The state derivative dxdt is now formed using qd, and qdd. The
// derivatives of the work done by the contact and friction models
// is also stored so that we can track the system energy of the
// system through the simulation
j = 0;
for(unsigned int i = 0; i < model->q_size; i++){
dxdt[j] = double(qd[i]);
j++;
}
for(unsigned int i = 0; i < model->qdot_size; i++){
dxdt[j] = double(qdd[i]);
j++;
}
dworkN = hcInfo.force*dz;
dxdt[j] = dworkN;
j++;
dxdt[j] = fK0t.dot(v0K0t);
j++;
assert((numberOfWorkTermsInState
+ model->q_size
+ model->qdot_size) == j);
}
/*
Ascii Vector Notation:
rBKB
r: vector
B: from the origin of the Ball frame
K: to the contact point K
B: expressed in the coordinates of the ball frame.
EB0:
E: rotation matrix
B: to Frame B
0: from Frame 0
eN0:
e: unit vector
N: Normal direction
0: expressed in the coordinates of the root frame (0)
fK0
f: force
K: At point K
0: expressed in the coordinates of the root frame
tK0
t: torque
K: At point K
0: expressed in the coordinates of the root frame
*/
//Multibody Variables
Model* model;
VectorNd q, qd, qdd, tau;
//Normal-Contact Model Working Variables
unsigned int ballId;
double z, dz; //pentration depth and velocity
HuntCrossleyContactInfo hcInfo;
std::vector< SpatialVector > fext;
double dworkN, dworkT; //Work in the normal and tangential directions
double mu; //Friction coefficient
Matrix3d EB0; //Orientation of the ball expressed in the Root frame
Vector3d r0B0; //Position of the ball
Vector3d rBKB; //B : ball.
Vector3d r0K0; //K : contact point
Vector3d v0K0; //velocity of the contact point
Vector3d v0K0t; //tangential velocity of the contact point
Vector3d r0P0; //Origin of the plane
Vector3d eN0; //Normal of the plane
Vector3d eT0; //Tangental direction of the plane: in 2d this isn't necessary
//here we compute it to show how this is done in a
//numerically stable way in 3d.
Vector3d fK0n, tK0n; //contact force and moment
Vector3d fK0t, tK0t; //tangential friction force and moment
//Normal Contact-Model Parameters
double r; //ball radius
double k; //stiffness
double p; //exponential power on the spring compression
double beta; //damping
//Friction Model Parameters: see ContactToolkit
// createRegularizedFrictionCoefficientCurve for details
double staticFrictionSpeed;
double staticFrictionCoefficient;
double dynamicFrictionSpeed;
double dynamicFrictionCoefficient;
double viscousFrictionSlope;
double veps; //Velocity at which the relaxed method is used to compute
//the direction vector of the tangential velocity
RigidBodyDynamics::Addons::Geometry
::SmoothSegmentedFunction frictionCoefficientCurve;
unsigned int numberOfWorkTermsInState;
};
struct pushBackStateAndTime
{
std::vector< state_type >& states;
std::vector< double >& times;
pushBackStateAndTime( std::vector< state_type > &states ,
std::vector< double > × )
: states( states ) , times( times ) { }
void operator()( const state_type &x , double t )
{
states.push_back( x );
times.push_back( t );
}
};
void f(const state_type &x, state_type &dxdt, const double t);
/* Problem Constants */
int main (int argc, char* argv[]) {
rbdl_check_api_version (RBDL_API_VERSION);
RigidBodyDynamics::Model model;
std::string fileName("../model/ballPlaneContact.lua");
std::string ballName("Ball");
//0a. ballPlaneContact.lua model is read in
if (!Addons::LuaModelReadFromFile(fileName.c_str(),&model)){
std::cerr << "Error loading LuaModel: " << fileName << std::endl;
abort();
}
//0b. Contact and friction parameters are set (more on these later)
double radius = 0.5;
Vector3d pointOnPlane = Vector3d(0.,0.,0.);
Vector3d planeNormal = Vector3d(0.,0.,1.);
//Hunt-Crossley contact terms. See
// ContactToolkit::calcHuntCrossleyContactForce for details
double exponent = 2.0; //The spring force will increase with the deflection squared.
double stiffness = 9.81/pow(0.01,2.); //The ball will settle to 1cm penetration
double damping = 0.1; //lightly damped
//Friction model terms. See
// ContactToolkit::createRegularizedFrictionCoefficientCurve for details
double staticFrictionSpeed = 0.001;
double staticFrictionCoefficient = 0.8;
double dynamicFrictionSpeed = 0.01;
double dynamicFrictionCoeffient = 0.6;
double viscousFrictionSlope = 0.1;
unsigned int numWorkTermsInState = 2; //1 normal work term
//1 friction term
VectorNd q, qd, x, tau;
q.resize(model.dof_count);
qd.resize(model.dof_count);
tau.resize(model.dof_count);
x.resize(model.dof_count*2);
q.setZero();
qd.setZero();
x.setZero();
tau.setZero();
q[1] = 1.; //ball starts 1m off the ground
qd[0]= 1.;
for(unsigned int i=0; i<q.rows();++i){
x[i] =q[i];
x[i+q.rows()] = qd[i];
}
//0c. An object that Boost can integrate is instantiated:
rbdlToBoost rbdlModel(&model,
ballName,
radius,
pointOnPlane,
planeNormal,
stiffness,
exponent,
damping,
staticFrictionSpeed,
staticFrictionCoefficient,
dynamicFrictionSpeed,
dynamicFrictionCoeffient,
viscousFrictionSlope,
numWorkTermsInState);
//4a. The model state is initialized
state_type xState(x.size()+numWorkTermsInState);
state_type dxState(x.size()+numWorkTermsInState);
for(unsigned int i=0; i<x.size(); ++i){
xState[i] = x[i];
}
//4b. This model is integrated forward in time from t0 to t1 and is evaluated
// at npts between these time points
double t;
double t0 = 0;
double t1 = 1.0;
unsigned int npts = 100;
double absTolVal = 1e-8;
double relTolVal = 1e-8;
double dt = (t1-t0)/(npts-1);
double ke,pe,w =0;
unsigned int k=0;
std::vector<std::vector< double > > matrixData, matrixForceData;
std::vector<std::vector< double > > matrixErrorData;
std::vector< double > rowData(model.dof_count+1);
std::vector< double > rowForceData(10);
std::vector< double > rowErrorData(2);
double a_x = 1.0 , a_dxdt = 1.0;
controlled_stepper_type
controlled_stepper(
default_error_checker< double ,
range_algebra ,
default_operations >
( absTolVal , relTolVal , a_x , a_dxdt ) );
double tp = 0;
rowData[0] = 0;
for(unsigned int z=0; z < model.dof_count; z++){
rowData[z+1] = xState[z];
}
matrixData.push_back(rowData);
SpatialVector fA0 = SpatialVector::Zero();
for(unsigned int i=0; i<rowForceData.size();++i){
rowForceData[i]=0.;
}
matrixForceData.push_back(rowForceData);
double kepe0 = 0;
double th,dth;
// , , , , , , ,
printf("Columns below:\n");
printf(" t, theta, d/dt theta, ke, pe, w, ke+pe-w-kepe0\n");
for(unsigned int i=0; i<= npts; ++i){
t = t0 + dt*i;
integrate_adaptive(
controlled_stepper ,
rbdlModel , xState , tp , t , (t-tp)/10 );
tp = t;
//4c. At each time point the q's, qd's, and the work done on the ball by the
// contact & friction model is saved
for(unsigned int j=0; j<x.rows();++j){
x[j] = xState[j];
}
k=0;
for(unsigned int j=0; j<model.q_size;++j){
q[j] = xState[k];
++k;
}
for(unsigned int j=0; j<model.qdot_size;++j){
qd[j] = xState[k];
++k;
}
w = 0.;
for(unsigned int j=0; j<numWorkTermsInState;++j){
w += xState[k];
++k;
}
//4d. The q's, qd's, and work terms are used to numerically evaluate the system
// energy of the ball less the work done on it: ke+pe-w, where
// ke is kinetic energy, pe is potential energy, and w is work.
pe = Utils::CalcPotentialEnergy(model,
q,true);
ke = Utils::CalcKineticEnergy(model,
q,
qd,true);
rowData[0] = t;
for(unsigned int z=0; z < model.dof_count; z++){
rowData[z+1] = xState[z];
}
matrixData.push_back(rowData);
//4e. This is evaluated relative to the system energy of the ball at the
// beginning of the simulation. If the integrator were perfect the sum of
// ke+pe-w-kepe0 would be numerically zero. Because numerical integration is
// not perfect this quantity (printed to screen) will drift over time.
// You can see this if you adjust the absolute and relative tolerances
// (set between 4b and 4c) on the integrator and re-run the simulations.
// drift will be larger with looser integration tolerances.
if(i==0) kepe0 = (ke+pe-w);
rowErrorData[0] = t;
rowErrorData[1] = (ke + pe -w) - kepe0;
matrixErrorData.push_back(rowErrorData);
printf("%e, %e, %e, %e, %e, %e, %e\n",
t, q[2],qd[2],ke,
pe,w,(ke+pe-w-kepe0));
//Make sure the model state is up to date.
rbdlModel(xState,dxState,tp);
//4f. Here we grab quantities that we would like to save
rowForceData[0] = t;
//contact point location
rowForceData[1] = rbdlModel.r0K0[0];
rowForceData[2] = rbdlModel.r0K0[1];
rowForceData[3] = rbdlModel.r0K0[2];
//force at the contact point
rowForceData[4] = rbdlModel.fK0n[0] + rbdlModel.fK0t[0];
rowForceData[5] = rbdlModel.fK0n[1] + rbdlModel.fK0t[1];
rowForceData[6] = rbdlModel.fK0n[2] + rbdlModel.fK0t[2];
//moment at the contact point
rowForceData[7] = 0.;//This contact model generates no contact moments
rowForceData[8] = 0.;//This contact model generates no contact moments
rowForceData[9] = 0.;//This contact model generates no contact moments
matrixForceData.push_back(rowForceData);
bool here=true;
}
printf("Columns above:\n");
printf(" t, theta, d/dt theta, ke, pe, w, ke+pe-w-kepe0\n");
//5a. Finally we write the simulation data to file
std::cout << std::endl;
std::string emptyHeader("");
std::string fileNameOut("../output/animation.csv");
printMatrixToFile(matrixData,emptyHeader,fileNameOut);
printf("Wrote: ../output/animation.csv (meshup animation file)\n");
fileNameOut.assign("../output/animationForces.ff");
printMatrixToFile(matrixForceData,emptyHeader,fileNameOut);
printf("Wrote: ../output/animationForces.ff (meshup force file)\n");
fileNameOut = "../output/kepe.csv";
std::string header("time,systemEnergy,");
printMatrixToFile(matrixErrorData,header,fileNameOut);
printf("Wrote: ../output/kepe.csv (simulation data)\n");
return 0;
}
| 36.419643 | 113 | 0.593185 | ju6ge |
93982c8aa16d2f59d5f1c59b1462e37374ae75c9 | 856 | hpp | C++ | include/Awl/boost/detail/win/timers.hpp | Yalir/Awl | 92ef5996d8933bf92ceb37357d8cd2b169cb788e | [
"BSL-1.0"
] | 4 | 2016-07-01T02:33:28.000Z | 2020-03-03T17:52:54.000Z | include/Awl/boost/detail/win/timers.hpp | Yalir/Awl | 92ef5996d8933bf92ceb37357d8cd2b169cb788e | [
"BSL-1.0"
] | null | null | null | include/Awl/boost/detail/win/timers.hpp | Yalir/Awl | 92ef5996d8933bf92ceb37357d8cd2b169cb788e | [
"BSL-1.0"
] | null | null | null | // timers.hpp --------------------------------------------------------------//
// Copyright 2010 Vicente J. Botet Escriba
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef BOOST_DETAIL_WIN_TIMERS_HPP
#define BOOST_DETAIL_WIN_TIMERS_HPP
#include <Awl/boost/detail/win/basic_types.hpp>
namespace boost
{
namespace detail
{
namespace win32
{
#if defined( BOOST_USE_WINDOWS_H )
using ::QueryPerformanceCounter;
using ::QueryPerformanceFrequency;
#else
extern "C" {
__declspec(dllimport) BOOL_ WINAPI
QueryPerformanceCounter(
LARGE_INTEGER_ *lpPerformanceCount
);
__declspec(dllimport) BOOL_ WINAPI
QueryPerformanceFrequency(
LARGE_INTEGER_ *lpFrequency
);
}
#endif
}
}
}
#endif // BOOST_DETAIL_WIN_TIMERS_HPP
| 20.380952 | 80 | 0.663551 | Yalir |
939933fe1d61326c92c882ddf2e5eb8729613421 | 24,568 | cpp | C++ | tests/messaging/test_send_object.cpp | yumilceh/libqi | f094bcad506bcfd5a8dcfa7688cbcce864b0765b | [
"BSD-3-Clause"
] | null | null | null | tests/messaging/test_send_object.cpp | yumilceh/libqi | f094bcad506bcfd5a8dcfa7688cbcce864b0765b | [
"BSD-3-Clause"
] | null | null | null | tests/messaging/test_send_object.cpp | yumilceh/libqi | f094bcad506bcfd5a8dcfa7688cbcce864b0765b | [
"BSD-3-Clause"
] | null | null | null | /*
**
** Copyright (C) 2018 Softbank Robotics Europe
*/
#include <gtest/gtest.h>
#include <qi/application.hpp>
#include <qi/anyobject.hpp>
#include <qi/session.hpp>
#include <qi/signalspy.hpp>
#include <qi/anymodule.hpp>
#include <testsession/testsessionpair.hpp>
#include <qi/testutils/testutils.hpp>
#include <condition_variable>
#include <thread>
#include <chrono>
qiLogCategory("test");
static const int timeoutMs = 300;
static const qi::Duration timeout = qi::MilliSeconds(timeoutMs);
void test_service(const qi::AnyObject &o)
{
ASSERT_TRUE(o);
int res = o.call<int>("testMethod", 12);
ASSERT_EQ(13, res);
}
TEST(SendObject, pass_obj)
{
TestSessionPair p;
qi::SessionPtr s = p.server();
s->loadService("naoqi.testanymodule.test");
qi::AnyObject o = s->service("test").value();
qiLogInfo() << "check first service" << std::endl;
test_service(o);
qi::AnyObject o2 = o.call<qi::AnyObject>("make_other_object");
s->registerService("test_bis", o2);
std::cout << "check second service" << std::endl;
test_service(o2);
qi::AnyObject o3 = s->service("test_bis").value();
test_service(o3);
s->close();
}
TEST(SendObject, load_received_obj)
{
TestSessionPair p;
qi::SessionPtr s = p.server();
s->loadService("naoqi.testanymodule.test");
qi::AnyObject o = s->service("test").value();
test_service(o);
s->registerService("test_bis", o);
qi::AnyObject o2 = s->service("test_bis").value();
test_service(o2);
s->close();
}
TEST(SendObject, unregister_obj)
{
TestSessionPair p;
qi::SessionPtr s = p.server();
int index = s->loadService("naoqi.testanymodule.test").value();
qi::AnyObject o = s->service("test").value();
test_service(o);
s->unregisterService(index).wait();
ASSERT_ANY_THROW(s->service("test"));
s->close();
}
class SubObjectToPing
{
public:
void subping() { qiLogInfo() << "subping !"; }
};
QI_REGISTER_OBJECT(SubObjectToPing, subping)
class ObjectToPing
{
public:
ObjectToPing() { propToPing.set(boost::make_shared<SubObjectToPing>()); }
void ping() { qiLogInfo() << "ping !" << std::endl; }
qi::Property<qi::AnyObject> propToPing;
};
QI_REGISTER_OBJECT(ObjectToPing, ping, propToPing)
class ObjectEmitter
{
public:
ObjectEmitter()
{
object.set(boost::make_shared<ObjectToPing>());
}
void emitObject(qi::AnyObject o) { QI_EMIT onTruc(o); }
qi::AnyObject identity(qi::AnyObject o) {return o;}
void receiveObject(qi::AnyObject o)
{
auto gettingProperty = o.property<void>("propToPing");
auto state = gettingProperty.waitFor(timeout);
std::stringstream errorMessage;
errorMessage << "Unexpected state";
if (state == qi::FutureState_FinishedWithError)
errorMessage << ", error: " << gettingProperty.error();
else
errorMessage << ": " << state;
EXPECT_EQ(qi::FutureState_FinishedWithValue, state) << errorMessage.str();
}
std::vector<qi::AnyObject> identities(const std::vector<qi::AnyObject>& objects)
{
return objects;
}
std::vector<qi::AnyObject> generateObjects()
{
return std::vector<qi::AnyObject>{boost::make_shared<ObjectToPing>()};
}
qi::Signal<qi::AnyObject> onTruc;
qi::Property<qi::AnyObject> object;
qi::Property<std::vector<qi::AnyObject>> vectorOfObjects;
};
QI_REGISTER_OBJECT(ObjectEmitter, emitObject, identity, identities, generateObjects,
receiveObject, onTruc, vectorOfObjects, object)
TEST(SendObject, pass_obj_made_from_module)
{
qi::AnyModule testModule = qi::import("naoqi.testanymodule");
auto obj = testModule.call<qi::AnyObject>("test");
auto obj2 = obj;
ASSERT_EQ(obj, obj2);
ASSERT_EQ(1, obj.call<int>("testMethod", 0)); // just checking, in case of
TestSessionPair p;
p.server()->registerService("plop", boost::make_shared<ObjectEmitter>());
qi::AnyObject remotePlop = p.client()->service("plop").value();
qi::Promise<void> receivingObject;
auto signalLink = remotePlop.connect(
"onTruc", boost::function<void(qi::AnyObject)>([=](qi::AnyObject o) mutable
{
ASSERT_EQ(o, obj);
ASSERT_EQ(1, o.call<int>("testMethod", 0)); // this is the real test
receivingObject.setValue(0);
})).value();
remotePlop.async<void>("emitObject", obj);
ASSERT_EQ(qi::FutureState_FinishedWithValue, receivingObject.future().waitFor(timeout));
// If the test failed and the onTruc signal has not been triggered before the
// end of the timeout, it could still be called during the test destruction.
// Disconnect the callback to make sure it is not called after receivingObject
// Promise has been destroyed.
remotePlop.disconnect(signalLink);
}
class ObjectEmitterFactory
{
public:
qi::AnyObject makeObjectEmitter() { return boost::make_shared<ObjectEmitter>(); }
};
QI_REGISTER_OBJECT(ObjectEmitterFactory, makeObjectEmitter)
TEST(SendObject, pass_obj_made_from_module_to_an_obj_made_from_service)
{
qi::AnyModule testModule = qi::import("naoqi.testanymodule");
auto obj = testModule.call<qi::AnyObject>("test");
ASSERT_EQ(1, obj.call<int>("testMethod", 0)); // just checking, in case of
TestSessionPair p;
p.server()->registerService("EmitterFactory", boost::make_shared<ObjectEmitterFactory>());
qi::AnyObject emitterFactory = p.client()->service("EmitterFactory").value();
auto emitter = emitterFactory.call<qi::AnyObject>("makeObjectEmitter");
qi::Promise<void> receivingObject;
emitter.connect("onTruc", boost::function<void(qi::AnyObject)>([=](qi::AnyObject o) mutable
{
ASSERT_EQ(o, obj);
int i = o.call<int>("testMethod", 0);
ASSERT_EQ(1, i); // this is the real test
receivingObject.setValue(0);
}));
emitter.async<void>("emitObject", obj);
ASSERT_EQ(qi::FutureState_FinishedWithValue, receivingObject.future().waitFor(timeout));
}
TEST(SendObject, emitter_from_factory_transmits_objects_through_property_then_receive_object)
{
TestSessionPair p;
p.server()->registerService("EmitterFactory", boost::make_shared<ObjectEmitterFactory>());
qi::AnyObject emitterFactory = p.client()->service("EmitterFactory").value();
auto emitter = emitterFactory.call<qi::AnyObject>("makeObjectEmitter");
// create vector
std::vector<qi::AnyObject> vecObj{
boost::make_shared<ObjectToPing>(), boost::make_shared<ObjectToPing>()
};
emitter.setProperty<std::vector<qi::AnyObject>>("vectorOfObjects", vecObj);
auto vectorOfObjectsReceived = emitter.property<std::vector<qi::AnyObject>>("vectorOfObjects").value();
auto objectToReceive = vectorOfObjectsReceived[0];
auto receiving = emitter.async<void>("receiveObject", objectToReceive);
ASSERT_EQ(qi::FutureState_FinishedWithValue, receiving.wait(timeoutMs));
}
TEST(SendObject, emitter_from_factory_transmits_objects_through_property_then_ping_property)
{
TestSessionPair p;
p.server()->registerService("EmitterFactory", boost::make_shared<ObjectEmitterFactory>());
qi::AnyObject emitterFactory = p.client()->service("EmitterFactory").value();
auto emitter = emitterFactory.call<qi::AnyObject>("makeObjectEmitter");
// create vector
std::vector<qi::AnyObject> vecObj{
boost::make_shared<ObjectToPing>(), boost::make_shared<ObjectToPing>()
};
emitter.setProperty<std::vector<qi::AnyObject>>("vectorOfObjects", vecObj);
auto vectorOfObjectsReceived = emitter.property<std::vector<qi::AnyObject>>("vectorOfObjects").value();
auto objectToPing = vectorOfObjectsReceived[0];
ASSERT_EQ(qi::FutureState_FinishedWithValue, objectToPing.property<void>("propToPing").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_transmits_objects_through_property_then_ping_property)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
// create vector
std::vector<qi::AnyObject> vecObj{
boost::make_shared<ObjectToPing>(), boost::make_shared<ObjectToPing>()
};
emitter.setProperty<std::vector<qi::AnyObject>>("vectorOfObjects", vecObj);
auto vectorOfObjectsReceived = emitter.property<std::vector<qi::AnyObject>>("vectorOfObjects").value();
auto objectToPing = vectorOfObjectsReceived[0];
ASSERT_EQ(qi::FutureState_FinishedWithValue, objectToPing.property<void>("propToPing").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_identities_then_ping_property)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
// create vector
std::vector<qi::AnyObject> vecObj{
boost::make_shared<ObjectToPing>(), boost::make_shared<ObjectToPing>()
};
auto sameObjects = emitter.call<std::vector<qi::AnyObject>>("identities", vecObj);
ASSERT_EQ(qi::FutureState_FinishedWithValue, sameObjects[0].property<void>("propToPing").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_identities_then_ping)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
// create vector
std::vector<qi::AnyObject> vecObj{
boost::make_shared<ObjectToPing>(), boost::make_shared<ObjectToPing>()
};
auto sameObjects = emitter.call<std::vector<qi::AnyObject>>("identities", vecObj);
ASSERT_EQ(qi::FutureState_FinishedWithValue, sameObjects[0].async<void>("ping").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_generate_objects_then_ping)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
auto objects = emitter.call<std::vector<qi::AnyObject>>("generateObjects");
ASSERT_EQ(qi::FutureState_FinishedWithValue, objects[0].async<void>("ping").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_identity_then_ping)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
qi::AnyObject object{boost::make_shared<ObjectToPing>()};
auto sameObject = emitter.call<qi::AnyObject>("identity", object);
ASSERT_EQ(qi::FutureState_FinishedWithValue, sameObject.async<void>("ping").wait(timeoutMs));
}
TEST(SendObject, emitter_from_factory_transmits_single_object_through_property_then_receive_object)
{
TestSessionPair p;
p.server()->registerService("EmitterFactory", boost::make_shared<ObjectEmitterFactory>());
qi::AnyObject emitterFactory = p.client()->service("EmitterFactory").value();
auto emitter = emitterFactory.call<qi::AnyObject>("makeObjectEmitter");
// create vector
qi::AnyObject objToPing = boost::make_shared<ObjectToPing>();
emitter.setProperty<qi::AnyObject>("object", objToPing);
auto objectStored = emitter.property<qi::AnyObject>("object").value();
auto receiving = emitter.async<void>("receiveObject", objectStored);
ASSERT_EQ(qi::FutureState_FinishedWithValue, receiving.wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_transmits_single_object_through_property_then_ping_property)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
qi::AnyObject objToPing = boost::make_shared<ObjectToPing>();
emitter.setProperty<qi::AnyObject>("object", objToPing);
auto objectStored = emitter.property<qi::AnyObject>("object").value();
ASSERT_EQ(qi::FutureState_FinishedWithValue, objectStored.property<void>("propToPing").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_transmits_single_object_through_property_then_ping)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
qi::AnyObject objToPing = boost::make_shared<ObjectToPing>();
emitter.setProperty<qi::AnyObject>("object", objToPing);
auto objectStored = emitter.property<qi::AnyObject>("object").value();
ASSERT_EQ(qi::FutureState_FinishedWithValue, objectStored.async<void>("ping").wait(timeoutMs));
}
TEST(SendObject, object_emitter_service_provides_single_object_through_property_then_ping)
{
TestSessionPair p;
p.server()->registerService("ObjectEmitter", boost::make_shared<ObjectEmitter>());
qi::AnyObject emitter = p.client()->service("ObjectEmitter").value();
auto objectStored = emitter.property<qi::AnyObject>("object").value();
ASSERT_EQ(qi::FutureState_FinishedWithValue, objectStored.async<void>("ping").wait(timeoutMs));
}
class Human
{
public:
void pingMe(const qi::AnyObject& humanToPing) {std::string oName = humanToPing.call<std::string>("ping");}
std::string ping()
{
qiLogInfo() << "Ping !";
return "human";
}
void nameMe(const std::string& newName) {name.set(newName);}
qi::Property<std::string> name;
};
QI_REGISTER_OBJECT(Human, pingMe, ping, nameMe, name)
class Actuation
{
public:
Actuation() { humanProperty.set(boost::make_shared<Human>()); }
qi::AnyObject getHomeMadeHuman() { return boost::make_shared<Human>(); }
void set(const qi::AnyObject& humanToSet) {_human = humanToSet;}
qi::AnyObject get() const {return _human;}
private:
qi::AnyObject _human;
public:
void emitHumanProperty()
{
humanProperty.set(boost::make_shared<Human>());
}
qi::Property<qi::AnyObject> humanProperty;
};
QI_REGISTER_OBJECT(Actuation, set, get, getHomeMadeHuman, emitHumanProperty, humanProperty)
TEST(SendObject, reuse_object_taken_from_connect)
{
TestSessionPair p;
p.server()->registerService("Actuation", boost::make_shared<Actuation>());
qi::AnyObject actuation = p.client()->service("Actuation").value();
qi::Promise<bool> pinged;
actuation.connect("humanProperty",
boost::function<void(qi::AnyObject)>([&](qi::AnyObject human)
{
auto homeMadeHuman = actuation.call<qi::AnyObject>("getHomeMadeHuman");
human.call<void>("pingMe", homeMadeHuman);
pinged.setValue(true);
}));
actuation.call<void>("emitHumanProperty");
ASSERT_EQ(qi::FutureState_FinishedWithValue, pinged.future().waitFor(qi::MilliSeconds(2000)));
}
// Check that we can connect to a property exposed on an object retrieved in a property callback
TEST(SendObject, connect_to_object_taken_from_connect)
{
TestSessionPair p;
p.server()->registerService("Actuation", boost::make_shared<Actuation>());
qi::AnyObject actuation = p.client()->service("Actuation").value();
qi::Promise<bool> pinged;
qi::Promise<bool> named;
actuation.connect("humanProperty",
boost::function<void(qi::AnyObject)>([=](qi::AnyObject human) mutable
{
// explicitly capture human in the lambda to keep it alive
human.connect("name",
boost::function<void(const std::string&)>([named, human](const std::string&) mutable
{
named.setValue(true);
}));
human.call<void>("nameMe", "(´・ω・`)");
pinged.setValue(true);
}));
actuation.call<void>("emitHumanProperty");
ASSERT_EQ(qi::FutureState_FinishedWithValue, pinged.future().waitFor(qi::MilliSeconds(2000)));
ASSERT_EQ(qi::FutureState_FinishedWithValue, named.future().waitFor(qi::MilliSeconds(2000)));
}
TEST(SendObject, make_frame)
{
TestSessionPair p;
p.server()->registerService("Actuation", boost::make_shared<Actuation>());
qi::AnyObject actuation = p.client()->service("Actuation").value();
actuation.call<void>("set", boost::make_shared<Human>());
auto humanReceived = actuation.call<qi::AnyObject>("get");
auto homeMadeHuman = actuation.call<qi::AnyObject>("getHomeMadeHuman");
humanReceived.call<void>("ping"); // <-- this one doesn't hang
homeMadeHuman.call<void>("pingMe", humanReceived); // <-- this one doesn't hang
humanReceived.call<void>("pingMe", homeMadeHuman); // <-- this one hangs infinitely
humanReceived.call<void>("pingMe", humanReceived); // <-- this one hangs infinitely
}
class Cookie
{
public:
Cookie(bool withTaste) : taste(withTaste) {}
bool eat()
{
eaten();
qiLogInfo() << "Too late, you ate me";
return true;
}
bool eatRival(qi::AnyObject other)
{
qiLogInfo() << "I am bigger than the other cookie";
return other.call<bool>("eat");
}
qi::Property<bool> taste;
qi::Signal<void> eaten;
};
class CookieBox
{
public:
qi::AnyObject makeCookie(bool withTaste)
{
std::weak_ptr<Token> token{ _token };
return boost::shared_ptr<Cookie>{
new Cookie{withTaste},
[this,token](Cookie* cookie) {
qiLogInfo() << "Cookie destruction";
delete cookie;
if (auto cookieBox = token.lock())
{
QI_EMIT cookieLost();
}
else
{
qiLogWarning() << "CookieBox have been destroyed before all Cookies instances destruction!";
}
}
};
}
void give(qi::AnyObject c)
{
cookie = c;
}
qi::AnyObject take()
{
return cookie;
}
qi::Signal<void> cookieLost;
private:
qi::AnyObject cookie;
struct Token {};
std::shared_ptr<Token> _token{ std::make_shared<Token>() };
};
struct CookieMonster
{
void feed(qi::AnyObject cookie)
{
cookie.call<bool>("eat");
qiLogInfo() << "Cookiiiiie!!! Om nom nom nom...";
}
};
struct CookieMonsterFeeder
{
void feedMonster(qi::AnyObject cookie, qi::AnyObject cookieMonster)
{
cookieMonster.call<void>("feed", cookie);
}
};
QI_REGISTER_OBJECT(Cookie, eat, eatRival, taste, eaten)
QI_REGISTER_OBJECT(CookieBox, makeCookie, give, take)
QI_REGISTER_OBJECT(CookieMonster, feed)
QI_REGISTER_OBJECT(CookieMonsterFeeder, feedMonster)
TEST(SendObject, give_and_take_object_function)
{
TestSessionPair p;
p.server()->registerService("CookieBox", boost::make_shared<CookieBox>());
qi::AnyObject cookieBoxProxy = p.client()->service("CookieBox").value();
qi::AnyObject cookie = cookieBoxProxy.call<qi::AnyObject>("makeCookie", true);
cookieBoxProxy.call<void>("give", cookie);
qi::AnyObject takenCookie = cookieBoxProxy.call<qi::AnyObject>("take");
EXPECT_TRUE(takenCookie.call<bool>("eat"));
EXPECT_EQ(cookie, takenCookie);
}
TEST(SendObject, give_and_take_object_property)
{
TestSessionPair p;
p.server()->registerService("CookieBox", boost::make_shared<CookieBox>());
qi::AnyObject cookieBoxProxy = p.client()->service("CookieBox").value();
qi::AnyObject cookie = cookieBoxProxy.call<qi::AnyObject>("makeCookie", true);
cookieBoxProxy.call<void>("give", cookie);
qi::AnyObject takenCookie = cookieBoxProxy.call<qi::AnyObject>("take");
EXPECT_TRUE(takenCookie.property<bool>("taste").value(timeoutMs));
EXPECT_EQ(cookie, takenCookie);
}
TEST(SendObject, give_and_take_object_signal)
{
TestSessionPair p;
p.server()->registerService("CookieBox", boost::make_shared<CookieBox>());
qi::AnyObject cookieBoxProxy = p.client()->service("CookieBox").value();
qi::AnyObject cookie = cookieBoxProxy.call<qi::AnyObject>("makeCookie", true);
cookieBoxProxy.call<void>("give", cookie);
qi::AnyObject takenCookie = cookieBoxProxy.call<qi::AnyObject>("take");
EXPECT_EQ(cookie, takenCookie);
qi::Promise<bool> eaten;
auto connecting =
takenCookie.connect("eaten", boost::function<void()>([&eaten]
{
eaten.setValue(true);
})).async();
EXPECT_EQ(qi::FutureState_FinishedWithValue, connecting.waitFor(timeout));
auto eating = takenCookie.async<bool>("eat");
EXPECT_TRUE(eating.value(timeoutMs));
EXPECT_TRUE(eaten.future().value(timeoutMs));
}
TEST(SendObject, two_client_objects_call_each_other_on_service_side)
{
TestSessionPair p;
auto cookieFeeder = boost::make_shared<CookieMonsterFeeder>();
p.server()->registerService("CookieMonsterFeeder", cookieFeeder);
qi::AnyObject cookieTransmitterRemote = p.client()->service("CookieMonsterFeeder").value();
auto transmitting = cookieTransmitterRemote.async<void>(
"feedMonster", boost::make_shared<Cookie>(false), boost::make_shared<CookieMonster>());
ASSERT_EQ(qi::FutureState_FinishedWithValue, transmitting.wait(timeoutMs));
}
TEST(SendObject, object_referenced_by_remote_only_is_destroyed_on_disconnection)
{
TestSessionPair p;
auto cookieBox = boost::make_shared<CookieBox>();
p.server()->registerService("CookieBox", cookieBox);
qi::AnyObject cookieBoxRemote = p.client()->service("CookieBox").value();
qiLogInfo() << "Getting a cookie!";
auto cookie = cookieBoxRemote.call<qi::AnyObject>("makeCookie", true);
QI_UNUSED(cookie);
qi::SignalSpy cookieLostSpy{cookieBox->cookieLost};
qiLogInfo() << "Closing the session.";
p.client()->close();
// in this case, the references are only counted using the shared pointers
if (p.mode() == TestMode::Mode_Direct)
ASSERT_FALSE(cookieLostSpy.waitUntil(1, timeout).value());
// In every other case, a remote object intervenes
else
ASSERT_TRUE(cookieLostSpy.waitUntil(1, timeout).value());
}
TEST(SendObject, object_referenced_by_remote_only_is_destroyed_on_unreference)
{
TestSessionPair p;
auto cookieBox = boost::make_shared<CookieBox>();
p.server()->registerService("CookieBox", cookieBox);
qi::AnyObject cookieBoxRemote = p.client()->service("CookieBox").value();
auto cookie = cookieBoxRemote.call<qi::AnyObject>("makeCookie", true);
qi::SignalSpy cookieLostSpy{cookieBox->cookieLost};
cookie.reset();
ASSERT_TRUE(cookieLostSpy.waitUntil(1, timeout).value());
}
TEST(SendObject, eat_yourself)
{
TestSessionPair p;
auto cookieBox = boost::make_shared<CookieBox>();
p.server()->registerService("CookieBox", cookieBox);
qi::AnyObject cookieBoxRemote = p.client()->service("CookieBox").value();
auto cookie = cookieBoxRemote.call<qi::AnyObject>("makeCookie", true);
auto otherCookie = cookieBoxRemote.call<qi::AnyObject>("makeCookie", true);
auto eatOther = cookie.async<bool>("eatRival", otherCookie);
eatOther.value();
// ^^^ This works
auto eatYourself = cookie.async<bool>("eatRival", cookie);
eatYourself.value();
// ^^^ This timeouts because cookie.eat() is never called inside of eatRival.
}
class FocusOwner
{
public:
FocusOwner() {}
void doNothing() {}
};
QI_REGISTER_OBJECT(FocusOwner, doNothing)
class Focus
{
std::condition_variable& _var;
std::atomic_bool& _sessionClosed;
std::mutex _mutex;
public:
boost::weak_ptr<FocusOwner> focusOwner;
qi::Promise<void> focusPromise;
Focus(std::condition_variable& var,
std::atomic_bool& closed) : _var(var), _sessionClosed(closed) {}
qi::Object<FocusOwner> take()
{
std::unique_lock<std::mutex> lock(_mutex);
_var.wait(lock, [this]() { return _sessionClosed.load() == true; });
auto fo = boost::make_shared<FocusOwner>();
focusOwner = fo;
focusPromise.setValue(nullptr);
return fo;
}
};
QI_REGISTER_OBJECT(Focus, take)
TEST(SendObject, sendOnClosedConnection)
{
if(TestMode::getTestMode() == TestMode::Mode_Direct)
return; // in direct mode the future will hold the object
std::condition_variable var;
std::atomic_bool closed{false};
auto focus = boost::make_shared<Focus>(var, closed);
TestSessionPair p;
p.server()->registerService("Focus", focus);
qi::AnyObject focusService = p.client()->service("Focus").value();
auto future = focusService.async<qi::AnyObject>("take");
p.client()->close().wait();
closed.store(true);
var.notify_all();
focus->focusPromise.future().wait();
// at this point the focus object should be thrown away by qi::messaging
// hypothesis: it takes no longer that 2 seconds
int i = 0;
while (!focus->focusOwner.expired() && i < 2000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++i;
}
ASSERT_TRUE(focus->focusOwner.expired());
}
struct ObjectWithObjProp
{
qi::Property<qi::Object<Cookie>> prop;
};
QI_REGISTER_OBJECT(ObjectWithObjProp, prop);
TEST(SendObject, PropertySetWithNullObjectNotifiesSubscribers)
{
static const auto serviceName = testing::UnitTest::GetInstance()->current_test_info()->test_case_name();
TestSessionPair p;
auto server = p.server();
auto obj = boost::make_shared<ObjectWithObjProp>();
server->registerService(serviceName, obj);
qi::AnyObject clientObj = p.client()->service(serviceName).value();
qi::Promise<bool> prom;
clientObj.connect("prop", [=](qi::Object<Cookie> obj) mutable {
prom.setValue(static_cast<bool>(obj));
}).value();
obj->prop.set(qi::Object<Cookie>{});
auto fut = prom.future();
ASSERT_TRUE(test::finishesWithValue(fut));
ASSERT_FALSE(fut.value());
}
| 32.540397 | 108 | 0.721263 | yumilceh |
939d069d5d40282f777481d328cac8fb2eee70f3 | 827 | cpp | C++ | URI/URI-CPP/BEGINNER/1038.cpp | tareqmahmud/Competitive-Programming | ad5e53300d70280bccbd5046ca01278fb246f314 | [
"MIT"
] | 2 | 2020-11-19T19:03:28.000Z | 2021-01-04T19:52:11.000Z | URI/URI-CPP/BEGINNER/1038.cpp | tareqmahmud/Competitive-Programming | ad5e53300d70280bccbd5046ca01278fb246f314 | [
"MIT"
] | null | null | null | URI/URI-CPP/BEGINNER/1038.cpp | tareqmahmud/Competitive-Programming | ad5e53300d70280bccbd5046ca01278fb246f314 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main(void){
// Initialize variable
int productCode, productQuantity;
double actualPrice;
// Take input
cin >> productCode >> productQuantity;
// Calculate price based on productCode and productQuantity
switch(productCode){
case 1:
actualPrice = 4.00 * productQuantity;
break;
case 2:
actualPrice = 4.50 * productQuantity;
break;
case 3:
actualPrice = 5.00 * productQuantity;
break;
case 4:
actualPrice = 2.00 * productQuantity;
break;
case 5:
actualPrice = 1.50 * productQuantity;
break;
}
// Ouput that Calculate value
printf("Total: R$ %.2lf\n", actualPrice);
return 0;
} | 22.972222 | 63 | 0.561064 | tareqmahmud |
4d34c3e96a5c8614d3935fac0161f39a84657dc3 | 23,249 | cpp | C++ | software/atmega328p_u1/ev-charge-control/src/mon.cpp | greenenergyprojects/electro-vehicle-charger-met16 | cf8c274da60ee8c340915f377c3b352e3ed3e552 | [
"MIT"
] | 1 | 2022-03-18T18:49:50.000Z | 2022-03-18T18:49:50.000Z | software/atmega328p_u1/ev-charge-control/src/mon.cpp | greenenergyprojects/electro-vehicle-charger-met16 | cf8c274da60ee8c340915f377c3b352e3ed3e552 | [
"MIT"
] | null | null | null | software/atmega328p_u1/ev-charge-control/src/mon.cpp | greenenergyprojects/electro-vehicle-charger-met16 | cf8c274da60ee8c340915f377c3b352e3ed3e552 | [
"MIT"
] | null | null | null | #include "global.h"
#include "mon.hpp"
#include "sys.hpp"
#include "app.hpp"
#ifdef GLOBAL_MONITOR
namespace u1_mon {
// declarations and definitions
int8_t cmd_info (uint8_t argc, const char **argv);
int8_t cmd_test (uint8_t argc, const char **argv);
int8_t cmd_set (uint8_t argc, const char **argv);
int8_t cmd_pwm (uint8_t argc, const char **argv);
int8_t cmd_eep (uint8_t argc, const char **argv);
int8_t cmd_trim (uint8_t argc, const char **argv);
int8_t cmd_log (uint8_t argc, const char **argv);
const char LINE_WELCOME[] PROGMEM = "Line-Mode: CTRL-X, CTRL-Y, CTRL-C, Return \n\r";
const char PMEM_CMD_INFO[] PROGMEM = "info\0Application infos\0info";
const char PMEM_CMD_TEST[] PROGMEM = "test\0commando for test\0test";
const char PMEM_CMD_SET[] PROGMEM = "set\0set function/port\0set {k1|k2|f|v|i|t} {0|1|value}";
const char PMEM_CMD_PWM[] PROGMEM = "pwm\0set PWM duty cycle for CP/port\0pwm {0-100}";
const char PMEM_CMD_EEP[] PROGMEM = "eep\0eeprom ...\0eep [c/r/w] [hex-address] [number|value]";
const char PMEM_CMD_TRIM[] PROGMEM = "trim\0trim table\0trim [reset]";
const char PMEM_CMD_LOG[] PROGMEM = "log\0log\0log [clear]";
const char HEADER_1[] PROGMEM = "L1 | Up-Time | A0 A1 A2 A6 A7 A8 | Temp | VCP | CP | STATUS";
const char HEADER_2[] PROGMEM = "L2 | Voltage\n | +/- TH ADC MIN MAX VPP | PERIOD | FREQU | VAC | ";
const char HEADER_3[] PROGMEM = "L3 | Current (s + -)\n | +/- TH ADC MIN MAX IPP | DPH | SIM | CURR";
const char HEADER_4[] PROGMEM = "L4 | Power (s + -)\n | FREQU | VAC | CURR | DPH | S | P | Q |";
const struct u1_sys::MonCmdInfo PMEMSTR_CMDS[] PROGMEM = {
{ PMEM_CMD_INFO, cmd_info }
, { PMEM_CMD_TEST, cmd_test }
, { PMEM_CMD_SET, cmd_set }
, { PMEM_CMD_PWM, cmd_pwm }
, { PMEM_CMD_EEP, cmd_eep }
, { PMEM_CMD_TRIM, cmd_trim }
, { PMEM_CMD_LOG, cmd_log }
};
// definitions and declarations
struct Mon mon;
void startupLog ();
// ------------------------------------------------------------------------
void init () {
memset((void *)&mon, 0, sizeof(mon));
// startupLog();
}
void main () {
}
uint8_t getCmdCount () {
return sizeof(PMEMSTR_CMDS) / sizeof(struct u1_sys::MonCmdInfo);
}
// --------------------------------------------------------
// Monitor commands of the application
// --------------------------------------------------------
int8_t cmd_info (uint8_t argc, const char **argv) {
return 0;
}
int8_t cmd_test (uint8_t argc, const char **argv) {
return 0;
}
int8_t cmd_set (uint8_t argc, const char **argv) {
if (argc > 1 && argc < 4 && argv[1][1] == 0) {
int v = 0;
if (argc == 3) {
if (sscanf(argv[2], "%d", &v) != 1) { return -2; }
}
switch (argv[1][0]) {
case 'f': u1_app::app.sim.f = v; return 0;
case 'v': u1_app::app.sim.v = v; return 0;
case 'i': u1_app::app.sim.i = v; return 0;
case 't': u1_app::app.sim.t = v; return 0;
}
}
if (argc != 3 || argv[2][1] != 0) { return -1; }
uint8_t v = argv[2][0] - '0';
if (strcmp("k1", argv[1]) == 0) {
DDRC |= (1 << PC4); // PC4 - K1
if (v) {
PORTC |= (1 << PC4);
} else {
PORTC &= ~(1 << PC4);
}
return 0;
} else if (strcmp("k2", argv[1]) == 0 ) {
DDRC |= (1 << PC5); // PC5 - K2
if (v) {
PORTC |= (1 << PC5);
} else {
PORTC &= ~(1 << PC5);
}
return 0;
}
return -10;
}
int8_t cmd_pwm (uint8_t argc, const char **argv) {
if (argc != 2) { return -1; }
int v;
if (sscanf(argv[1], "%d", &v) != 1) { return -2; }
if (v < 0 || v > 100) { return -3; }
if (v == 0) {
u1_sys::enablePWM(0);
} else if (v == 100) {
u1_sys::enablePWM(1);
OCR0A = 255; // CP is 12V without PWM
} else {
u1_sys::enablePWM(1);
OCR0A = (255 * v) / 100;
}
return 0;
}
int8_t cmd_eep (uint8_t argc, const char **argv) {
uint8_t *pAddr = 0;
uint16_t number = 32;
char type = 'r';
if (argc > 1) {
if (argv[1][1] != 0) { return -1; }
type = argv[1][0];
if (type == 'c' && argc == 2) {
clearLogTable();
return 0;
}
if (type != 'r' && type != 'w') { return -2; }
if (type == 'w' && argc != 4) { return -3; }
}
if (argc > 2) {
int a;
if (sscanf(argv[2], "%d", &a) != 1) { return -4; }
if (a < 0 || a > 1023) { return - 5; }
pAddr = (uint8_t *)a;
}
if (argc > 3) {
int n;
if (sscanf(argv[3], "%d", &n) != 1) { return -6; }
if (type == 'w') {
if (n < 0 || n > 0xff) { return -7; }
} else if (n < 1 || n > 1024) {
return - 8;
}
number = n;
}
if (argc > 4) {
return -8;
}
if (type == 'w') {
eeprom_write_byte(pAddr, number);
eeprom_busy_wait();
number = 1;
}
while ((uint16_t)pAddr < 1024 && number > 0) {
uint8_t b = eeprom_read_byte(pAddr);
printf(" %04x: %02x\n", (uint16_t)pAddr, b);
pAddr++; number--;
}
printf("\n");
// ueeprom_read_byte (const uint8_t *__p) __ATTR_PURE__;
return 0;
}
void printTrim (struct u1_app::Trim *p) {
printf(" magic: %08lx\n", p->magic);
printf(" startCnt: %u\n", p->startCnt);
printf(" vcpK: %d\n", p->vcpK);
printf(" vcpD: %d\n", p->vcpD);
printf(" currK: %d\n", p->currK);
printf(" tempK: %d\n", p->tempK);
printf(" tempOffs: %d\n\n", p->tempOffs);
}
int8_t cmd_trim (uint8_t argc, const char **argv) {
if (argc == 2) {
if (strcmp(argv[1], "clear") == 0) {
uint8_t *p = 0;
for (uint8_t i = 0; i < sizeof(u1_app::app.trim); i++) {
eeprom_write_byte(p++, 0xff);
eeprom_busy_wait();
}
} else if (strcmp(argv[1], "reset") == 0) {
u1_app::initTrim(0);
eeprom_update_block(&u1_app::app.trim, (void *)0, sizeof(u1_app::app.trim));
eeprom_busy_wait();
} else {
return -1;
}
printf("OK\n\n");
}
printf("EE2:\n");
struct u1_app::Trim t;
uint8_t *p = (uint8_t *)&t;
for (uint8_t i = 0; i < sizeof(t); i++) {
*(p++) = eeprom_read_byte((uint8_t *)(uint16_t)i);
}
printTrim(&t);
printf("TRIM:\n");
printTrim(&u1_app::app.trim);
printf("\n");
return 0;
}
// ***********************************************************************
// log functions
// ***********************************************************************
int16_t findLogDescriptorIndex (uint32_t time) {
u1_app::clearLogHistory();
int16_t rv = -1;
uint32_t rvTimeDiff = 0xffffffff;
uint8_t index = 0;
plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index;
struct LogDescriptor d;
while (index < EEP_LOG_DESCRIPTORS) {
eeprom_busy_wait();
eeprom_read_block(&d, p, sizeof (d));
uint8_t typ = d.typ & 0x0f;
if (typ != 0x0f) {
uint32_t diff = d.time > time ? d.time - time : time - d.time;
if (diff < rvTimeDiff) {
rvTimeDiff = diff;
rv = index;
}
u1_app::addLogCharging(typ, d.time, index);
}
index++;
p += sizeof(struct LogDescriptor);
}
return rv;
}
int16_t findNewestLogDescriptorIndex () {
return findLogDescriptorIndex(0xffffffff);
}
int16_t findOldestLogDescriptorIndex () {
return findLogDescriptorIndex(0);
}
uint8_t saveLog (uint8_t typ, void *pData, uint8_t size) {
if (typ >= 0x0f) {
return 0xff; // error
}
struct LogDescriptor d;
d.typ = 0x0f;
pushSREGAndCli(); {
uint16_t tHigh = (u1_app::app.trim.startCnt << 1) | ((u1_app::app.clock.hrs >> 4) & 0x01);
uint16_t tLow = ((u1_app::app.clock.hrs & 0x0f) << 12) | ((u1_app::app.clock.min & 0x3f) << 6) | (u1_app::app.clock.sec & 0x3f);
d.time = (((uint32_t)tHigh) << 16) | tLow;
} popSREG();
uint8_t index = 0;
plogtable_t p = (plogtable_t)EEP_LOG_START;
plogtable_t pTo = (plogtable_t)EEP_LOG_SLOTS_START;
uint8_t lastTyp = typ;
if (mon.log.index < EEP_LOG_DESCRIPTORS) {
index = mon.log.index;
p += index * sizeof (struct LogDescriptor);
pTo += index * EEP_LOG_SLOT_SIZE;
lastTyp = mon.log.lastTyp == 0 ? 0xff : mon.log.lastTyp;
}
uint8_t rv;
int16_t bytes = size;
uint8_t slotCnt = 0;
do {
if (lastTyp != typ || slotCnt > 0) {
index++;
p += sizeof (struct LogDescriptor);
pTo += EEP_LOG_SLOT_SIZE;
if (index >= EEP_LOG_DESCRIPTORS) {
p = (plogtable_t)EEP_LOG_START;
pTo = (plogtable_t)EEP_LOG_SLOTS_START;
index = 0;
}
}
if (slotCnt == 0) {
rv = index;
}
d.typ = (d.typ & 0x0f) | (slotCnt++ << 4);
eeprom_busy_wait();
eeprom_update_block(&d, p, sizeof(d));
uint8_t l = bytes < EEP_LOG_SLOT_SIZE ? bytes : EEP_LOG_SLOT_SIZE;
eeprom_busy_wait();
if (pData != NULL && size > 0) {
eeprom_update_block(pData, pTo, l);
bytes -= EEP_LOG_SLOT_SIZE;
pData = ((uint8_t *)pData) + l;
}
} while (bytes > 0 && slotCnt < 16);
index = rv;
p = (plogtable_t)EEP_LOG_START + index * sizeof (struct LogDescriptor);
d.typ = typ;
uint8_t slot = 0;
while (slotCnt-- > 0) {
d.typ = (d.typ & 0x0f) | (slot << 4);
eeprom_busy_wait();
eeprom_write_byte(p, *((uint8_t *)&d));
p += sizeof (struct LogDescriptor);
mon.log.index = index++;
slot++;
if (index >= EEP_LOG_DESCRIPTORS) {
p = (plogtable_t)EEP_LOG_START;
index = 0;
}
}
mon.log.lastTyp = typ;
u1_app::addLogCharging(typ, d.time, rv);
return rv;
}
void readLogData (uint8_t index, uint8_t *pDest, uint8_t destSize) {
if (index >= EEP_LOG_DESCRIPTORS) {
return;
}
eeprom_busy_wait();
plogtable_t pFrom = (plogtable_t)EEP_LOG_SLOTS_START + EEP_LOG_SLOT_SIZE * index;
eeprom_read_block(pDest, pFrom, destSize);
}
void startupLog () {
int16_t startIndex = findNewestLogDescriptorIndex();
mon.log.index = startIndex < 0 ? EEP_LOG_DESCRIPTORS : startIndex + 1;
if (mon.log.index >= EEP_LOG_DESCRIPTORS) {
mon.log.index = 0;
}
mon.log.lastTyp = 0xff;
saveLog(LOG_TYPE_SYSTEMSTART, NULL, 0);
}
int8_t cmd_log (uint8_t argc, const char **argv) {
if (argc == 2 && strcmp("clear", argv[1]) == 0) {
clearLogTable();
return 0;
}
if (argc > 1) { return -1; }
struct LogDescriptor d;
int16_t startIndex = findOldestLogDescriptorIndex();
uint8_t cnt = 0;
if (startIndex >= 0) {
uint8_t index = (uint8_t)startIndex;
plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index;
struct LogDescriptor d;
do {
eeprom_busy_wait();
eeprom_read_block(&d, p, sizeof (d));
if ((d.typ & 0x0f) != 0x0f) {
cnt++;
uint8_t typ = d.typ & 0x0f;
uint8_t subIndex = d.typ >> 4;
uint16_t startupCnt = d.time >> 17;
uint8_t hrs = (d.time >> 12) & 0x1f;
uint8_t min = (d.time >> 6) & 0x3f;
uint8_t sec = d.time & 0x3f;
printf(" %2d(%01x/%01x) %5d-%02d:%02d:%02d -> ", index, typ, subIndex, startupCnt, hrs, min, sec);
uint8_t slot[EEP_LOG_SLOT_SIZE];
eeprom_busy_wait();
eeprom_read_block(&slot, (plogtable_t)EEP_LOG_SLOTS_START + index * EEP_LOG_SLOT_SIZE, sizeof (slot));
switch (d.typ) {
case LOG_TYPE_SYSTEMSTART: {
printf("system start");
break;
}
case LOG_TYPE_STARTCHARGE: {
struct LogDataStartCharge *pData = (struct LogDataStartCharge *)&slot;
printf("start charge maxAmps=%u", pData->maxAmps);
break;
}
case LOG_TYPE_CHARGING: case LOG_TYPE_STOPCHARGING: {
struct LogDataCharging *pData = (struct LogDataCharging *)&slot;
uint8_t e = pData->energyKwhX256 >> 8;
uint8_t nk = ((pData->energyKwhX256 & 0xff) * 100 + 128) / 256;
if (d.typ == LOG_TYPE_STOPCHARGING) {
printf("stop ");
}
printf("charge %u:%02u, E=%u.%02ukWh", pData->chgTimeHours, pData->chgTimeMinutes, e, nk);
break;
}
default: {
printf("? (");
for (uint8_t i = 0; i < sizeof slot; i++) {
printf(" %02x", slot[i]);
}
printf(")");
break;
}
}
printf("\n");
}
index++;
p += sizeof(struct LogDescriptor);
if (index >= EEP_LOG_DESCRIPTORS) {
index = 0;
p = (plogtable_t)EEP_LOG_START;
}
} while (index != startIndex);
}
printf("%d valid log records\n", cnt);
printf("\nLog history:\n");
for (uint8_t i = 0; i < (sizeof (u1_app::app.logChargingHistory) / sizeof (u1_app::app.logChargingHistory[0])); i++) {
struct u1_app::LogChargingHistory *p= &(u1_app::app.logChargingHistory[i]);
printf(" %u: typ=%u time=%04x%04x ", i, p->typ, (uint16_t)(p->time >> 16), (uint16_t)(p->time));
printf("= %u-%u:%02u:%02u -> ", (uint16_t)(p->time >> 17), (uint16_t)((p->time >> 12) & 0x1f), (uint16_t)((p->time >> 6) & 0x3f), (uint16_t)(p->time & 0x3f));
printf(" %u:%02umin", p->data.chgTimeHours, p->data.chgTimeMinutes);
printf(" %u.%02ukWh", p->data.energyKwhX256 >> 8, ((p->data.energyKwhX256 & 0xff) * 100 + 128) / 256);
printf("\n");
}
return 0;
}
// --------------------------------------------------------
// Monitor-Line for continues output
// --------------------------------------------------------
int8_t printLineHeader (uint8_t lineIndex) {
if (lineIndex==0) {
u1_sys::printString_P(LINE_WELCOME);
}
switch (lineIndex) {
case 0: u1_sys::printString_P(HEADER_1); return 75;
case 1: u1_sys::printString_P(HEADER_2); return 60;
case 2: u1_sys::printString_P(HEADER_3); return 50;
case 3: u1_sys::printString_P(HEADER_4); return 75;
default: return -1; // this line index is not valid
}
}
int8_t printLine (uint8_t lineIndex, char keyPressed) {
// handle keypressed
switch (lineIndex) {
case 2: case 3: {
uint8_t k = u1_app::app.sim.currentAdcK;
if (keyPressed == 's') {
if (k == 0) {
// enable current simulation
// current adc taken from voltage sensor
k = 32;
} else {
// disable current simulation
// current adc taken from current sensor
k = 0;
}
}
if (k > 0) {
// adjust current adc simulation amplitude
if (keyPressed =='+') {
k = (k < 0xff) ? k + 1 : k;
} else if (keyPressed == '-') {
k = (k < 0xff) ? k - 1 : k;
}
}
u1_app::app.sim.currentAdcK = k;
break;
}
}
// create line output
printf("%02d | ", (int)u1_sys::getSw1Value());
switch (lineIndex) {
case 0: { // line L1
struct u1_app::Adc *p = &(u1_app::app.adc);
printf("%3d:%02d:%02d ", u1_app::app.clock.hrs, u1_app::app.clock.min, u1_app::app.clock.sec);
printf("| %02x %02x %02x %02x %02x %02x ", p->adc0, p->adc1, p->adc2, p->adc6, p->adc7, p->adc8);
printf("| %c%3dC ", u1_app::app.sim.t > 0 ? 'S' : ' ', (int)u1_app::app.temp);
printf("| %2d.%1dV ", u1_app::app.vcpX16 >> 4, ((u1_app::app.vcpX16 & 0x0f) * 10) / 16 );
uint16_t cpPwmX256 = ((uint16_t)OCR0A) * 100;
printf ("| %3d.%1d%% ", cpPwmX256 >> 8, ((cpPwmX256 & 0xff) * 10) / 256 );
printf("| ");
switch (u1_app::app.state) {
case u1_app::Init: printf("Init"); break;
case u1_app::Test: printf("Test"); break;
case u1_app::Start: printf("Start"); break;
case u1_app::NotConnected: printf("NotConnected"); break;
case u1_app::Connected: printf("Connected"); break;
case u1_app::EVReady: printf("EVReady"); break;
case u1_app::Charging: printf("Charging"); break;
default: printf("? (%d)", u1_app::app.state);
}
return 10;
}
case 1: { // line L2
struct u1_app::AdcVoltage *p = &(u1_app::app.adc.voltage);
printf("%3d %02x %02x %02x %02x %02x ", p->area, p->th, u1_app::app.adc.adc1, p->min, p->max, p->peakToPeak);
printf("| %02x %04x ", p->period, p->periodEwma);
uint16_t frequX256 = u1_app::app.frequX256 + 13; // 0.05*256 = 12.8 -> 13
printf("| %c%2u.%1uHz ", u1_app::app.sim.f > 0 ? 'S' : ' ', frequX256 / 256, ((frequX256 & 0xff) * 10) / 256);
uint16_t vphX256 = u1_app::app.vphX256 + 13; // 0.05*256 = 12.8 -> 13
printf("| %c%3u.%1uV ", u1_app::app.sim.v > 0 ? 'S' : ' ', vphX256 / 256, ((vphX256 & 0xff) * 10) / 256);
return 4;
}
case 2: { // line L3
struct u1_app::AdcSine *p = &(u1_app::app.adc.current.sine);
printf("%3d %02x %02x %02x %02x %03x ", u1_app::app.adc.current.tmp.area, p->th, u1_app::app.adc.adc0, p->min, p->max, p->peakToPeak);
printf("| %3d ", u1_app::app.adc.phAngX100us);
printf("| %3d ", u1_app::app.sim.currentAdcK);
uint16_t currX256 = u1_app::app.currX256 + 13; // 0.05*256 = 12.8 -> 13
printf("| %c%2u.%1uA ", u1_app::app.sim.i > 0 || u1_app::app.sim.currentAdcK > 0 ? 'S' : ' ', currX256 / 256, ((currX256 & 0xff) * 10) / 256);
return 4;
}
case 3: { // line L4
struct u1_app::AdcVoltage *pv = &(u1_app::app.adc.voltage);
struct u1_app::AdcSine *pc = &(u1_app::app.adc.current.sine);
uint16_t frequX256 = u1_app::app.frequX256 + 13; // 0.05*256 = 12.8 -> 13
printf("%c%2u.%1uHz ", u1_app::app.sim.f > 0 || u1_app::app.sim.currentAdcK > 0 ? 'S' : ' ', frequX256 / 256, ((frequX256 & 0xff) * 10) / 256);
uint16_t vphX256 = u1_app::app.vphX256 + 13; // 0.05*256 = 12.8 -> 13
printf("| %c%3u.%1uV ", u1_app::app.sim.v > 0 ? 'S' : ' ', vphX256 / 256, ((vphX256 & 0xff) * 10) / 256);
uint16_t currX256 = u1_app::app.currX256 + 13; // 0.05*256 = 12.8 -> 13
printf("| %c%2u.%1uA ", u1_app::app.sim.i > 0 ? 'S' : ' ', currX256 / 256, ((currX256 & 0xff) * 10) / 256);
printf("| %3d ", u1_app::app.adc.phAngX100us);
cli();
int16_t s = u1_app::app.apparantPower;
int16_t p = u1_app::app.activePower;
int16_t q = u1_app::app.reactivePower;
uint32_t e = u1_app::app.energyKwhX256;
sei();
printf("| %4dVA ", s);
printf("| %5dW ", p);
printf("| %5dvar ", q);
printf("| %ld.%02dkWh", e / 256, ((uint8_t)e) * 100 / 256);
return 2;
}
case 4: {
for (int i = 0; i < 6; i++) {
printf(" %04x", u1_app::app.debug.u16[i] );
}
return 2;
}
default: return -1;
}
}
// --------------------------------------------------------
// Log functions
// --------------------------------------------------------
void clearEEP (plogtable_t pStartAddr, uint16_t size) {
while (size-- > 0 && (uint16_t)pStartAddr <= E2END) {
eeprom_busy_wait();
eeprom_write_byte(pStartAddr++, 0xff);
}
eeprom_busy_wait();
}
void clearTrim () {
clearEEP(0, sizeof(struct u1_app::Trim));
}
void clearLogTable () {
clearEEP((plogtable_t)EEP_LOG_START, E2END + 1 - EEP_LOG_START);
mon.log.index = 0xff;
mon.log.lastTyp = 0x0f;
}
}
#endif // GLOBAL_MONITOR
| 38.491722 | 174 | 0.44832 | greenenergyprojects |
4d3584bbd966987ad0514c516250619669ad0f0a | 17,740 | cpp | C++ | Medusa/Medusa/Resource/Font/BMPFont.cpp | tony2u/Medusa | d4ac8181a693bc796681880e09aac3fdba9aaaaf | [
"MIT"
] | 143 | 2015-11-18T01:06:03.000Z | 2022-03-30T03:08:54.000Z | Medusa/Medusa/Resource/Font/BMPFont.cpp | tony2u/Medusa | d4ac8181a693bc796681880e09aac3fdba9aaaaf | [
"MIT"
] | 1 | 2019-10-23T13:00:40.000Z | 2019-10-23T13:00:40.000Z | Medusa/Medusa/Resource/Font/BMPFont.cpp | tony2u/Medusa | d4ac8181a693bc796681880e09aac3fdba9aaaaf | [
"MIT"
] | 45 | 2015-11-18T01:17:59.000Z | 2022-03-05T12:29:45.000Z | // 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 "BMPFont.h"
#include "Resource/Material/MaterialFactory.h"
#include "Core/IO/File.h"
#include "Resource/ResourceNames.h"
#include "Resource/Image/PVRImage.h"
#include "Resource/Material/IMaterial.h"
#include "Resource/Texture/ITexture.h"
#include "Core/IO/FileSystem.h"
#include "Resource/TextureAtlas/TextureAtlasPage.h"
#include "Resource/TextureAtlas/TextureAtlas.h"
#include "Resource/TextureAtlas/TextureAtlasRegion.h"
MEDUSA_BEGIN;
BMPFont::BMPFont(const FontId& fontId) :IFont(fontId)
{
}
BMPFont::~BMPFont(void)
{
}
Share<BMPFont> BMPFont::CreateFromPVR(const FontId& fontId)
{
TextureAtlasPage* page = new TextureAtlasPage(fontId.ToRef());
auto texture = page->LoadTexture();
auto image = texture->Image();
RETURN_NULL_IF_NULL(image);
auto pvrImage = image.CastPtr<PVRImage>();
PVRImageMetaDataBlock* headerMetaBlock = pvrImage->GetMetaBlock((uint)PVRVersionIdentifier::PVR3, (uint)PVRFontMetaBlockKey::Header);
PVRFontHeader* fontHeader = (PVRFontHeader*)headerMetaBlock->Data;
if (fontHeader->Version != 1) //default is 1 in pvr font
{
return nullptr;
}
Share<BMPFont> resultFont = new BMPFont(fontId);
resultFont->SetAscender(fontHeader->Ascent);
resultFont->SetLineHeight(fontHeader->LineSpace);
resultFont->SetTotalCharCount(fontHeader->NumCharacters);
if (fontId.Size() == 0)
{
resultFont->SetOriginalSize(fontHeader->SpaceWidth);
}
PVRImageMetaDataBlock* charListMetaBlock = pvrImage->GetMetaBlock((uint)PVRVersionIdentifier::PVR3, (uint)PVRFontMetaBlockKey::CharList);
PVRImageMetaDataBlock* yOffsetMetaBlock = pvrImage->GetMetaBlock((uint)PVRVersionIdentifier::PVR3, (uint)PVRFontMetaBlockKey::YOffset);
PVRImageMetaDataBlock* metricsMetaBlock = pvrImage->GetMetaBlock((uint)PVRVersionIdentifier::PVR3, (uint)PVRFontMetaBlockKey::Metrics);
PVRImageMetaDataBlock* kerningMetaBlock = pvrImage->GetMetaBlock((uint)PVRVersionIdentifier::PVR3, (uint)PVRFontMetaBlockKey::Kerning);
PVRImageMetaDataBlock* rectMetaBlock = pvrImage->GetMetaBlock((uint)PVRVersionIdentifier::PVR3, (uint)PVRFontMetaBlockKey::Rects);
bool hasSpace = false;
FOR_EACH_SIZE(i, (uint)fontHeader->NumCharacters)
{
FontChar* fontChar = new FontChar();
fontChar->Id = (wchar_t)((int*)charListMetaBlock->Data)[i];
fontChar->HBearing.Y = ((int*)yOffsetMetaBlock->Data)[i];
fontChar->HBearing.X = ((short*)metricsMetaBlock->Data)[i];
fontChar->HAdvance = ((short*)metricsMetaBlock->Data)[i + 1];
TextureAtlasRegion* region = new TextureAtlasRegion();
region->SetId(fontChar->Id);
region->SetTextureRect(((Rect2U*)rectMetaBlock->Data)[i]);
page->AddRegion(region);
fontChar->SetRegion(region);
resultFont->AddChar(fontChar);
if (fontChar->Id == ' ')
{
resultFont->SetSpaceFontChar(fontChar);
hasSpace = true;
}
}
resultFont->Atlas()->AddPage(page);
if (!hasSpace)
{
FontChar* fontChar =new FontChar();
fontChar->Id = ' ';
fontChar->HAdvance = fontHeader->SpaceWidth;
resultFont->AddChar(fontChar);
resultFont->SetSpaceFontChar(fontChar);
}
FOR_EACH_SIZE(i, (uint)fontHeader->NumKerningPairs)
{
FontKerning* pair = new FontKerning();
*pair = ((FontKerning*)kerningMetaBlock->Data)[i];
resultFont->AddKerning(pair);
}
return resultFont;
}
Share<BMPFont> BMPFont::CreateFromBMPBinary(const FontId& fontId, const IStream& stream)
{
int version = stream.ReadChar();
if (version != 3)
{
Log::FormatError("Invalid fnt binary file format version:{}. Must be 3!", version);
return nullptr;
}
//1.read info line
stream.ReadChar();
/*uint infoBlockSize=*/stream.Read<uint>();
ushort fontSize = stream.Read<ushort>();
byte infoBitField = (byte)stream.ReadChar();
bool isBold = (infoBitField & 8) != 0;
bool isItalic = (infoBitField & 4) != 0;
/*bool isUnicode=(infoBitField&2)!=0;*/
/*bool isFixedHeight=(infoBitField&16)!=0;*/
/*bool isSmooth=(infoBitField&1)!=0;*/
/*byte charSet=(byte)*/stream.ReadChar();
/*ushort stretchHeight=*/stream.Read<ushort>();
/*byte isAtiAlias=(byte)*/stream.ReadChar();
Padding4I padding;
padding.Up = stream.ReadChar();
padding.Right = stream.ReadChar();
padding.Down = stream.ReadChar();
padding.Left = stream.ReadChar();
Point2I spacing;
spacing.X = stream.ReadChar();
spacing.Y = stream.ReadChar();
byte outLineThickness = (byte)stream.ReadChar();
HeapString faceName = stream.ReadString();
std::unique_ptr<BMPFont> bmpFont(new BMPFont(fontId));
bmpFont->SetOriginalSize(fontSize);
bmpFont->SetIsBold(isBold);
bmpFont->SetIsItalic(isItalic);
bmpFont->SetPadding(padding);
bmpFont->SetSpacing(spacing);
bmpFont->SetOutlineThickness(outLineThickness);
//read common line
stream.ReadChar();
/*uint commonBlockSize=*/stream.Read<uint>();
ushort lineHeight = stream.Read<ushort>();
int baseHeight = stream.Read<ushort>();
Size2U textureSize;
textureSize.Width = stream.Read<ushort>();
textureSize.Height = stream.Read<ushort>();
uint pageCount = stream.Read<ushort>();
byte commonBitField = (byte)stream.ReadChar();
int isPacked = (commonBitField & 128) != 0;
int channelA = stream.ReadChar();
int channelR = stream.ReadChar();
int channelG = stream.ReadChar();
int channelB = stream.ReadChar();
bmpFont->SetLineHeight(lineHeight);
bmpFont->SetAscender(baseHeight);
bmpFont->SetDescender(lineHeight - baseHeight);
bmpFont->SetImageSize(textureSize);
bmpFont->SetIsPacked(isPacked == 1);
bmpFont->SetChannel(Color4B((byte)channelR, (byte)channelG, (byte)channelB, (byte)channelA).To4F());
//read page lines
stream.ReadChar();
/*uint pageBlockSize=*/stream.Read<uint>();
FOR_EACH_UINT32(i, pageCount)
{
HeapString pageFileName = stream.ReadString();
TextureAtlasPage* page = new TextureAtlasPage(pageFileName);
page->SetTexcoordUpSide(false);
page->SetId(i);
auto texture = page->LoadTexture();
if (texture == nullptr)
{
Log::FormatError("Failed to read texture:{}", pageFileName.c_str());
return nullptr;
}
bmpFont->Atlas()->AddPage(page);
}
//read chars
stream.ReadChar();
uint charBlockSize = stream.Read<uint>();
uint charCount = charBlockSize / 20;
bmpFont->SetTotalCharCount(charCount);
//read all char line
int pageId;
bool hasSpace = false;
FOR_EACH_SIZE(i, charCount)
{
FontChar* fontChar = new FontChar();
TextureAtlasRegion* region = new TextureAtlasRegion();
fontChar->Id = (wchar_t)stream.Read<uint>();
region->SetId(fontChar->Id);
Rect2U textureRect;
textureRect.Origin.X = stream.Read<ushort>();
textureRect.Origin.Y = stream.Read<ushort>();
textureRect.Size.Width = stream.Read<ushort>();
textureRect.Size.Height = stream.Read<ushort>();
region->SetTextureRect(textureRect);
fontChar->HBearing.X = stream.Read<short>();
fontChar->HBearing.Y = stream.Read<short>();
fontChar->HAdvance = stream.Read<short>();
pageId = stream.ReadChar();
fontChar->Channel = stream.ReadChar();
TextureAtlasPage* page= bmpFont->Atlas()->FindPage(pageId);
if (page == nullptr)
{
Log::FormatError("Failed to find page id:{}", pageId);
return nullptr;
}
page->AddRegion(region);
fontChar->SetRegion(region);
fontChar->HBearing.Y = (int)(bmpFont->Ascender() - fontChar->HBearing.Y);
bmpFont->AddChar(fontChar);
if (fontChar->Id == ' ')
{
bmpFont->SetSpaceFontChar(fontChar);
hasSpace = true;
}
}
if (!hasSpace)
{
FontChar* fontChar = new FontChar();
fontChar->Id = ' ';
fontChar->HAdvance = (ushort)bmpFont->Size() / 2;
bmpFont->AddChar(fontChar);
bmpFont->SetSpaceFontChar(fontChar);
}
int kerningBlockId = stream.ReadChar();
if (kerningBlockId != -1)
{
//still have kerning pairs
uint kerningBlockSize = stream.Read<uint>();
uint kerningCount = kerningBlockSize / 10;
FOR_EACH_SIZE(i, kerningCount)
{
FontKerning* kerning = new FontKerning();
kerning->First = stream.Read<uint>();
kerning->Second = stream.Read<uint>();
kerning->Offset = stream.Read<short>();
bmpFont->AddKerning(kerning);
}
}
Share<BMPFont> resultFont = bmpFont.release();
return resultFont;
}
Share<BMPFont> BMPFont::CreateFromBMPText(const FontId& fontId, const IStream& stream)
{
List<HeapString> outLines;
stream.ReadAllLinesTo(outLines);
RETURN_NULL_IF_EMPTY(outLines);
uint lineIndex = 0;
//1.read info line
StringRef infoLine = outLines[lineIndex++];
int fontSize = 0;
int isBold = 0;
int isItalic = 0;
int isUnicode = 0;
int stretchHeight = 0;
int isSmooth = 0;
int isAtiAlias = 0;
Padding4I padding = Padding4I::Zero;
Point2I spacing = Point2I::Zero;
int outLineThickness = 0;
StringRef faceNameStr;
bool isSuccess = StringParser::TryReadKeyValue(infoLine, "info face", "=\"", "\" ", faceNameStr);
isSuccess = StringParser::TryReadKeyValue(infoLine, "size", '=', ' ', fontSize);
isSuccess = StringParser::TryReadKeyValue(infoLine, "bold", '=', ' ', isBold);
isSuccess = StringParser::TryReadKeyValue(infoLine, "bold", '=', ' ', isBold);
isSuccess = StringParser::TryReadKeyValue(infoLine, "unicode", '=', ' ', isUnicode);
isSuccess = StringParser::TryReadKeyValue(infoLine, "stretchH", '=', ' ', stretchHeight);
isSuccess = StringParser::TryReadKeyValue(infoLine, "smooth", '=', ' ', isSmooth);
isSuccess = StringParser::TryReadKeyValue(infoLine, "aa", '=', ' ', isAtiAlias);
int paddingBuffer[4];
isSuccess = StringParser::TryReadKeyValues(infoLine, "padding", '=', ',', ' ', paddingBuffer);
padding.Up = paddingBuffer[0];
padding.Down = paddingBuffer[1];
padding.Left = paddingBuffer[2];
padding.Right = paddingBuffer[3];
isSuccess = StringParser::TryReadKeyValues(infoLine, "spacing", '=', ',', ' ', spacing.Buffer);
isSuccess = StringParser::TryReadKeyValue(infoLine, "outline", '=', ' ', outLineThickness);
std::unique_ptr<BMPFont> bmpFont(new BMPFont(fontId));
bmpFont->SetOriginalSize(fontSize);
bmpFont->SetIsBold(isBold == 1);
bmpFont->SetIsItalic(isItalic == 1);
bmpFont->SetPadding(padding);
bmpFont->SetSpacing(spacing);
bmpFont->SetOutlineThickness(outLineThickness);
//read common line
StringRef commonLine = outLines[lineIndex++];
int lineHeight=0;
int baseHeight=0;
Size2U textureSize=Size2U::Zero;
uint pageCount=0;
int isPacked=0;
int channelR=0;
int channelG=0;
int channelB=0;
int channelA=0;
isSuccess = StringParser::TryReadKeyValue(commonLine, "lineheight", '=', ' ', lineHeight);
isSuccess = StringParser::TryReadKeyValue(commonLine, "base", '=', ' ', baseHeight);
isSuccess = StringParser::TryReadKeyValue(commonLine, "scaleW", '=', ' ', textureSize.Width);
isSuccess = StringParser::TryReadKeyValue(commonLine, "scaleH", '=', ' ', textureSize.Height);
isSuccess = StringParser::TryReadKeyValue(commonLine, "pages", '=', ' ', pageCount);
isSuccess = StringParser::TryReadKeyValue(commonLine, "packed", '=', ' ', isPacked);
isSuccess = StringParser::TryReadKeyValue(commonLine, "alphaChnl", '=', ' ', channelA);
isSuccess = StringParser::TryReadKeyValue(commonLine, "redChnl", '=', ' ', channelR);
isSuccess = StringParser::TryReadKeyValue(commonLine, "greenChnl", '=', ' ', channelG);
isSuccess = StringParser::TryReadKeyValue(commonLine, "blueChnl", '=', ' ', channelB);
bmpFont->SetLineHeight(lineHeight);
if (baseHeight==0)
{
baseHeight = lineHeight;
}
bmpFont->SetAscender(baseHeight);
bmpFont->SetDescender(lineHeight - baseHeight);
bmpFont->SetImageSize(textureSize);
bmpFont->SetIsPacked(isPacked == 1);
bmpFont->SetChannel(Color4B((byte)channelB, (byte)channelG, (byte)channelB, (byte)channelA).To4F());
//read page lines
HeapString pageFileName;
FOR_EACH_SIZE(i, pageCount)
{
StringRef pageLine = outLines[lineIndex++];
int pageId=0;
isSuccess = StringParser::TryReadKeyValue(pageLine, "id", '=', ' ', pageId);
isSuccess = StringParser::TryReadKeyValue(pageLine, "file", "=\"", "\"\n", pageFileName);
pageFileName.RemoveLast();
TextureAtlasPage* page = new TextureAtlasPage(pageFileName);
page->SetTexcoordUpSide(false);
page->SetId(pageId);
auto texture = page->LoadTexture();
if (texture == nullptr)
{
Log::FormatError("Failed to read material:{}", pageFileName.c_str());
return nullptr;
}
bmpFont->Atlas()->AddPage(page);
}
//read char count line
StringRef charCountLine = outLines[lineIndex++];
uint charCount;
isSuccess = StringParser::TryReadKeyValue(charCountLine, "count", '=', ' ', charCount);
bmpFont->SetTotalCharCount(charCount);
//read all char line
int pageId=0;
bool hasSpace = false;
FOR_EACH_SIZE(i, charCount)
{
FontChar* fontChar = new FontChar();
TextureAtlasRegion* region = new TextureAtlasRegion();
fontChar->SetRegion(region);
Rect2U textureRect;
StringRef charLine = outLines[lineIndex++];
isSuccess = StringParser::TryReadKeyValue(charLine, "id", '=', ' ', fontChar->Id);
isSuccess = StringParser::TryReadKeyValue(charLine, "x", '=', ' ', textureRect.Origin.X);
isSuccess = StringParser::TryReadKeyValue(charLine, "y", '=', ' ', textureRect.Origin.Y);
isSuccess = StringParser::TryReadKeyValue(charLine, "width", '=', ' ', textureRect.Size.Width);
isSuccess = StringParser::TryReadKeyValue(charLine, "height", '=', ' ', textureRect.Size.Height);
isSuccess = StringParser::TryReadKeyValue(charLine, "xoffset", '=', ' ', fontChar->HBearing.X);
isSuccess = StringParser::TryReadKeyValue(charLine, "yoffset", '=', ' ', fontChar->HBearing.Y);
isSuccess = StringParser::TryReadKeyValue(charLine, "xadvance", '=', ' ', fontChar->HAdvance);
pageId = 0;
isSuccess = StringParser::TryReadKeyValue(charLine, "page", '=', ' ', pageId);
isSuccess = StringParser::TryReadKeyValue(charLine, "chnl", '=', ' ', fontChar->Channel);
region->SetId(fontChar->Id);
region->SetTextureRect(textureRect);
auto* page= bmpFont->Atlas()->FindPage(pageId);
if (page == nullptr)
{
Log::FormatError("Failed to find page id:{}", pageId);
return nullptr;
}
page->AddRegion(region);
fontChar->HBearing.Y = (int)(bmpFont->Ascender() - fontChar->HBearing.Y);
bmpFont->AddChar(fontChar);
if (fontChar->Id == ' ')
{
bmpFont->SetSpaceFontChar(fontChar);
hasSpace = true;
}
}
if (!hasSpace)
{
FontChar* fontChar = new FontChar();
fontChar->Id = ' ';
fontChar->HAdvance = (ushort)bmpFont->Size() / 2;
bmpFont->AddChar(fontChar);
bmpFont->SetSpaceFontChar(fontChar);
}
if (lineIndex < outLines.Count())
{
//still have kerning pairs
//read kerning count line
StringRef kerningCountLine = outLines[lineIndex++];
uint kerningCount=0;
isSuccess = StringParser::TryReadKeyValue(kerningCountLine, "count", '=', ' ', kerningCount);
FOR_EACH_SIZE(i, kerningCount)
{
FontKerning* kerning = new FontKerning();
StringRef kerningLine = outLines[lineIndex++];
//read kerning line
isSuccess = StringParser::TryReadKeyValue(kerningLine, "first", '=', ' ', kerning->First);
isSuccess = StringParser::TryReadKeyValue(kerningLine, "second", '=', ' ', kerning->Second);
isSuccess = StringParser::TryReadKeyValue(kerningLine, "amount", '=', ' ', kerning->Offset);
bmpFont->AddKerning(kerning);
}
}
if (lineIndex != outLines.Count())
{
Log::Error("Failed to parse all lines.");
return nullptr;
}
Share<BMPFont> resultFont = bmpFont.release();
return resultFont;
}
Share<BMPFont> BMPFont::CreateFromSingleTexture(const FontId& fontId, wchar_t firstChar /*= L'0'*/)
{
TextureAtlasPage* page = new TextureAtlasPage(fontId.Name);
page->SetTexcoordUpSide(false);
auto texture = page->LoadTexture();
if (page == nullptr)
{
Log::FormatError("Failed to read font material:{}", fontId.Name.c_str());
return nullptr;
}
Size2U textureSize = texture->Size();
uint fontSize = fontId.Size();;
std::unique_ptr<BMPFont> bmpFont(new BMPFont(fontId));
bmpFont->SetLineHeight(textureSize.Height);
bmpFont->SetAscender(textureSize.Height);
bmpFont->SetDescender(0);
bmpFont->SetImageSize(textureSize);
bmpFont->Atlas()->AddPage(page);
uint charCount = textureSize.Width / fontSize;
bmpFont->SetTotalCharCount(charCount);
//read all char line
bool hasSpace = false;
uint charWidth = fontSize;
FOR_EACH_UINT32(i, charCount)
{
FontChar* fontChar = new FontChar();
TextureAtlasRegion* region = new TextureAtlasRegion();
fontChar->SetRegion(region);
Rect2U textureRect;
fontChar->Id = firstChar++;
textureRect.Origin.X = i*charWidth;
textureRect.Origin.Y = 0;
textureRect.Size.Width = charWidth;
textureRect.Size.Height = textureSize.Height;
fontChar->HAdvance = (ushort)charWidth;
fontChar->HBearing.Y = (int)(bmpFont->Ascender());
region->SetTextureRect(textureRect);
page->AddRegion(region);
bmpFont->AddChar(fontChar);
if (fontChar->Id == ' ')
{
bmpFont->SetSpaceFontChar(fontChar);
hasSpace = true;
}
}
if (!hasSpace)
{
FontChar* fontChar = new FontChar();
fontChar->Id = ' ';
fontChar->HAdvance = (ushort)bmpFont->Size() / 2;
bmpFont->AddChar(fontChar);
bmpFont->SetSpaceFontChar(fontChar);
}
Share<BMPFont> resultFont = bmpFont.release();
return resultFont;
}
MEDUSA_END; | 31.122807 | 139 | 0.689797 | tony2u |
4d361a898955248f0ce9f06edbe87b5c8b1355e8 | 2,782 | cpp | C++ | KsiazkaAdresowa.cpp | pieterkycia/KsiazkaAdresowaObiektowo | 05e4bf8c2114d69d15a6cc3372cb808c147080f0 | [
"Unlicense"
] | null | null | null | KsiazkaAdresowa.cpp | pieterkycia/KsiazkaAdresowaObiektowo | 05e4bf8c2114d69d15a6cc3372cb808c147080f0 | [
"Unlicense"
] | null | null | null | KsiazkaAdresowa.cpp | pieterkycia/KsiazkaAdresowaObiektowo | 05e4bf8c2114d69d15a6cc3372cb808c147080f0 | [
"Unlicense"
] | null | null | null | #include "KsiazkaAdresowa.h"
void KsiazkaAdresowa::rejestracjaUzytkownika() {
uzytkownikMenedzer.rejestracjaUzytkownika();
}
void KsiazkaAdresowa::logowanieUzytkownika() {
uzytkownikMenedzer.logowanieUzytkownika();
if (czyUzytkownikJestZalogowany())
adresatMenedzer = new AdresatMenedzer(NAZWA_PLIKU_Z_ADRESATAMI, uzytkownikMenedzer.pobierzIdZalogowanegoUzytkownika());
}
void KsiazkaAdresowa::zmianaHaslaZalogowanegoUzytkownika() {
uzytkownikMenedzer.zmianaHaslaZalogowanegoUzytkownika();
}
void KsiazkaAdresowa::wylogowanieUzytkownika() {
uzytkownikMenedzer.wylogowanieUzytkownika();
delete adresatMenedzer;
adresatMenedzer = NULL;
}
void KsiazkaAdresowa::wyswietlWszystkichUzytkownikow() {
uzytkownikMenedzer.wyswietlWszystkichUzytkownikow();
}
bool KsiazkaAdresowa::czyUzytkownikJestZalogowany() {
if (uzytkownikMenedzer.pobierzIdZalogowanegoUzytkownika() > 0)
return true;
else
return false;
}
void KsiazkaAdresowa::dodajAdresata() {
adresatMenedzer -> dodajAdresata();
}
void KsiazkaAdresowa::wyszukajAdresatowPoImieniu() {
adresatMenedzer -> wyszukajAdresatowPoImieniu();
}
void KsiazkaAdresowa::wyszukajAdresatowPoNazwisku() {
adresatMenedzer -> wyszukajAdresatowPoNazwisku();
}
void KsiazkaAdresowa::wyswietlWszystkichAdresatow() {
adresatMenedzer -> wyswietlWszystkichAdresatow();
}
void KsiazkaAdresowa::usunAdresata() {
adresatMenedzer -> usunAdresata();
}
void KsiazkaAdresowa::edytujAdresata() {
adresatMenedzer -> edytujAdresata();
}
char KsiazkaAdresowa::wybierzOpcjeZMenuGlownego() {
char wybor;
system("cls");
cout << " >>> MENU GLOWNE <<<" << endl;
cout << "---------------------------" << endl;
cout << "1. Rejestracja" << endl;
cout << "2. Logowanie" << endl;
cout << "3. Wyswietl wszystkich uzytkownikow" << endl;
cout << "9. Koniec programu" << endl;
cout << "---------------------------" << endl;
cout << "Twoj wybor: ";
wybor = MetodyPomocnicze::wczytajZnak();
return wybor;
}
char KsiazkaAdresowa::wybierzOpcjeZMenuUzytkownika() {
char wybor;
system("cls");
cout << " >>> MENU UZYTKOWNIKA <<<" << endl;
cout << "---------------------------" << endl;
cout << "1. Dodaj adresata" << endl;
cout << "2. Wyszukaj po imieniu" << endl;
cout << "3. Wyszukaj po nazwisku" << endl;
cout << "4. Wyswietl adresatow" << endl;
cout << "5. Usun adresata" << endl;
cout << "6. Edytuj adresata" << endl;
cout << "---------------------------" << endl;
cout << "7. Zmien haslo" << endl;
cout << "8. Wyloguj sie" << endl;
cout << "---------------------------" << endl;
cout << "Twoj wybor: ";
wybor = MetodyPomocnicze::wczytajZnak();
return wybor;
}
| 28.979167 | 127 | 0.650252 | pieterkycia |
4d39049392f857e813ce0056dad91c2c022f496f | 3,183 | cpp | C++ | src/ms-gui/main.cpp | Arisien/minesweeper | 5b4eab7800fde35d73ad8b004a0f89b0dbacc2f9 | [
"MIT"
] | 3 | 2020-08-31T20:23:42.000Z | 2021-06-26T21:26:16.000Z | src/ms-gui/main.cpp | Arisien/minesweeper | 5b4eab7800fde35d73ad8b004a0f89b0dbacc2f9 | [
"MIT"
] | 1 | 2021-04-27T07:54:02.000Z | 2021-04-27T07:54:02.000Z | src/ms-gui/main.cpp | Arisien/minesweeper | 5b4eab7800fde35d73ad8b004a0f89b0dbacc2f9 | [
"MIT"
] | null | null | null | /*
* ms-gui.cpp
*
* This is a GUI implementation of Minesweeper. SFML is used for the graphics.
*
* Author: Arisien @ 26.6.2021
*
*/
#include <SFML/Graphics.hpp>
#include <ctime>
#include "../minesweeper.hpp"
using namespace Minesweeper;
class GuiGame: public Game {
public:
sf::RenderWindow app;
sf::Texture texture;
sf::Sprite sprite;
int bar_size = 52;
int width, height;
GuiGame (int h, int w, int m) : Game {h,w,m} {
app.create(sf::VideoMode(32*field.width, 32*field.height), "Minesweeper++");
texture.loadFromFile("./sprites.png");
sprite = sf::Sprite(texture);
width = 32 * w;
height = bar_size + 32 * h;
}
Input input () {
sf::Vector2i pos = sf::Mouse::getPosition(app);
int x = pos.x / 32;
int y = (pos.y - bar_size) / 32;
sf::Event event;
while (app.pollEvent(event))
{
if (event.type == sf::Event::Closed){
return Input(I_QUIT);
}
if (event.type == sf::Event::MouseButtonReleased) {
if (event.key.code == sf::Mouse::Left) {
if (pos.x >= width/2 - 26 && pos.x <= width/2 + 26 && pos.y >= 0 && pos.y <= 52) return Input(I_RESET);
else return Input(I_PLOT, x, y , false);
}
else if (event.key.code == sf::Mouse::Right) {
return Input(I_PLOT, x, y, true);
}
}
}
return Input(I_NONE);
}
void render () {
//Draw Flag Count
int fc = field.flags;
int max = (width/2 - 26)/26 - 1;
if (max > 2) max = 2;
for (int i = max; i >= 0; i--) {
sprite.setTextureRect(sf::IntRect((fc%10) * 26, 32, 26, 46));
sprite.setPosition(i*26, 3);
app.draw(sprite);
fc /= 10;
}
//Draw Face
sprite.setTextureRect(sf::IntRect(field.state*52, 78, 52, 52));
sprite.setPosition(width/2 - 26, 0);
app.draw(sprite);
//Draw Time
int elapsed;
if (start_time == stop_time) elapsed = time(0) - start_time;
else elapsed = stop_time - start_time;
for (int i = 0; i <= max; i++) {
sprite.setTextureRect(sf::IntRect((elapsed%10) * 26, 32, 26, 46));
sprite.setPosition(width - ((i+1)*26), 3);
app.draw(sprite);
elapsed /= 10;
}
//Draw Field
for (int i = 0; i < field.height; i++) {
for (int j = 0; j < field.width; j++) {
Tile tile = field.tiles[i][j];
int xPos = 0;
if (tile.flagged) {
xPos = 11*32; //11th sprite - FLAG
}
else if (tile.visible) {
xPos = tile.value*32; //nth sprite - VALUE
}
else {
xPos = 10*32; //10th sprite - EMPTY
}
sprite.setTextureRect(sf::IntRect(xPos, 0, 32, 32));
sprite.setPosition(j*32, bar_size + i*32);
app.draw(sprite);
}
}
app.display();
}
};
int main (int argc, char *argv[]) {
if (argc != 4) {
std::cout << "Usage: " << argv[0] << " [height] [width] [mines]\n";
return 0;
}
int height = std::stoi(argv[1]);
int width = std::stoi(argv[2]);
int mines = std::stoi(argv[3]);
GuiGame game(height, width, mines);
game.start();
return 0;
}
| 20.14557 | 109 | 0.531574 | Arisien |
4d3ad678d0f7ce53b040d0bec76d3ccc55404c10 | 28,816 | cpp | C++ | src/core/resolution_statistics.cpp | ngrigorieff/cisTEM_downstream_ng | 8cf890cc5d8d9eec874e9d7897da51ed0419251c | [
"BSD-3-Clause"
] | 7 | 2020-09-09T10:59:59.000Z | 2020-11-19T15:26:53.000Z | src/core/resolution_statistics.cpp | ngrigorieff/cisTEM_downstream_ng | 8cf890cc5d8d9eec874e9d7897da51ed0419251c | [
"BSD-3-Clause"
] | 85 | 2020-09-11T15:07:02.000Z | 2021-02-08T20:38:13.000Z | src/core/resolution_statistics.cpp | ngrigorieff/cisTEM_downstream_ng | 8cf890cc5d8d9eec874e9d7897da51ed0419251c | [
"BSD-3-Clause"
] | 6 | 2021-03-26T13:04:10.000Z | 2021-11-18T19:28:16.000Z | #include "core_headers.h"
ResolutionStatistics::ResolutionStatistics()
{
pixel_size = 0.0;
number_of_bins = -1;
number_of_bins_extended = 0;
}
ResolutionStatistics::ResolutionStatistics(float wanted_pixel_size, int box_size)
{
Init(wanted_pixel_size, box_size);
}
ResolutionStatistics::ResolutionStatistics( const ResolutionStatistics &other_statistics) // copy constructor
{
MyDebugPrint("Warning: copying a resolution statistics object");
*this = other_statistics;
//DEBUG_ABORT;
}
ResolutionStatistics & ResolutionStatistics::operator = (const ResolutionStatistics &other_statistics)
{
*this = &other_statistics;
return *this;
}
ResolutionStatistics & ResolutionStatistics::operator = (const ResolutionStatistics *other_statistics)
{
// Check for self assignment
if(this != other_statistics)
{
//MyDebugAssertTrue(other_statistics->number_of_bins >= 0, "Other statistics not initialized");
FSC = other_statistics->FSC;
part_FSC = other_statistics->part_FSC;
part_SSNR = other_statistics->part_SSNR;
rec_SSNR = other_statistics->rec_SSNR;
pixel_size = other_statistics->pixel_size;
number_of_bins = other_statistics->number_of_bins;
number_of_bins_extended = other_statistics->number_of_bins_extended;
}
return *this;
}
void ResolutionStatistics::ResampleFrom(ResolutionStatistics &other_statistics, int wanted_number_of_bins)
{
MyDebugAssertTrue(other_statistics.number_of_bins > 0 || wanted_number_of_bins > 0, "Other statistics not initialized");
int extended = int(wanted_number_of_bins * sqrtf(3.0)) + 1;
if (wanted_number_of_bins == 0) extended = number_of_bins_extended;
if (other_statistics.FSC.number_of_points > 0) FSC.ResampleCurve(&other_statistics.FSC, extended);
if (other_statistics.part_FSC.number_of_points > 0) part_FSC.ResampleCurve(&other_statistics.part_FSC, extended);
if (other_statistics.part_SSNR.number_of_points > 0) part_SSNR.ResampleCurve(&other_statistics.part_SSNR, extended);
if (other_statistics.rec_SSNR.number_of_points > 0) rec_SSNR.ResampleCurve(&other_statistics.rec_SSNR, extended);
}
void ResolutionStatistics::CopyFrom(ResolutionStatistics &other_statistics, int wanted_number_of_bins)
{
MyDebugAssertTrue(other_statistics.number_of_bins > 0 || wanted_number_of_bins > 0, "Other statistics not initialized");
// MyDebugAssertTrue(other_statistics.number_of_bins > wanted_number_of_bins, "Other statistics has more bins than requested");
int i;
int number_of_bins2 = 2 * (number_of_bins - 1);
float resolution;
int extended = int(wanted_number_of_bins * sqrtf(3.0)) + 1;
if (wanted_number_of_bins == 0) extended = number_of_bins_extended;
FSC.ClearData();
part_FSC.ClearData();
part_SSNR.ClearData();
rec_SSNR.ClearData();
for (i = 0; i < std::min(extended,number_of_bins_extended); i++)
{
if (i > 0)
{
resolution = pixel_size / float(i) * float(number_of_bins2);
}
else
{
resolution = 0.0;
}
if (other_statistics.FSC.number_of_points > 0) FSC.AddPoint(resolution, other_statistics.FSC.data_y[i]);
if (other_statistics.part_FSC.number_of_points > 0) part_FSC.AddPoint(resolution, other_statistics.part_FSC.data_y[i]);
if (other_statistics.part_SSNR.number_of_points > 0) part_SSNR.AddPoint(resolution, other_statistics.part_SSNR.data_y[i]);
if (other_statistics.rec_SSNR.number_of_points > 0) rec_SSNR.AddPoint(resolution, other_statistics.rec_SSNR.data_y[i]);
}
for (i = std::min(extended,number_of_bins_extended); i < extended; i++)
{
if (i > 0)
{
resolution = pixel_size / float(i) * float(number_of_bins2);
}
else
{
resolution = 0.0;
}
if (other_statistics.FSC.number_of_points > 0) FSC.AddPoint(resolution, 0.0);
if (other_statistics.part_FSC.number_of_points > 0) part_FSC.AddPoint(resolution, 0.0);
if (other_statistics.part_SSNR.number_of_points > 0) part_SSNR.AddPoint(resolution, 0.0);
if (other_statistics.rec_SSNR.number_of_points > 0) rec_SSNR.AddPoint(resolution, 0.0);
}
}
void ResolutionStatistics::CopyParticleSSNR(ResolutionStatistics &other_statistics, int wanted_number_of_bins)
{
MyDebugAssertTrue(other_statistics.number_of_bins > 0 || wanted_number_of_bins > 0, "Other statistics not initialized");
// MyDebugAssertTrue(other_statistics.number_of_bins > wanted_number_of_bins, "Other statistics has more bins than requested");
int i;
int number_of_bins2 = 2 * (number_of_bins - 1);
float resolution;
int extended = int(wanted_number_of_bins * sqrtf(3.0)) + 1;
if (wanted_number_of_bins == 0) extended = number_of_bins_extended;
part_SSNR.ClearData();
for (i = 0; i < std::min(extended,number_of_bins_extended); i++)
{
if (i > 0)
{
resolution = pixel_size / float(i) * float(number_of_bins2);
}
else
{
resolution = 0.0;
}
if (other_statistics.part_SSNR.number_of_points > 0) part_SSNR.AddPoint(resolution, other_statistics.part_SSNR.data_y[i]);
}
for (i = std::min(extended,number_of_bins_extended); i < extended; i++)
{
if (i > 0)
{
resolution = pixel_size / float(i) * float(number_of_bins2);
}
else
{
resolution = 0.0;
}
if (other_statistics.part_SSNR.number_of_points > 0) part_SSNR.AddPoint(resolution, 0.0);
}
}
void ResolutionStatistics::ResampleParticleSSNR(ResolutionStatistics &other_statistics, int wanted_number_of_bins)
{
MyDebugAssertTrue(other_statistics.number_of_bins > 0 || wanted_number_of_bins > 0, "Other statistics not initialized");
int extended = int(wanted_number_of_bins * sqrtf(3.0)) + 1;
if (wanted_number_of_bins == 0) extended = number_of_bins_extended;
if (other_statistics.part_SSNR.number_of_points > 0)
{
part_SSNR.ResampleCurve(&other_statistics.part_SSNR, extended);
part_SSNR.MultiplyByConstant(float(extended) / float(other_statistics.number_of_bins_extended));
}
}
float ResolutionStatistics::ReturnEstimatedResolution(bool use_part_fsc)
{
float estimated_resolution = 0.0f;
if (use_part_fsc == true)
{
for (int counter = 1; counter < part_FSC.number_of_points; counter++)
{
if (part_FSC.data_y[counter] < 0.143)
{
estimated_resolution = (part_FSC.data_x[counter - 1] + part_FSC.data_x[counter]) / 2.0;
break;
}
}
}
else
{
for (int counter = 1; counter < FSC.number_of_points; counter++)
{
if (FSC.data_y[counter] < 0.143)
{
estimated_resolution = (FSC.data_x[counter - 1] + FSC.data_x[counter]) / 2.0;
break;
}
}
}
if (estimated_resolution < 2.0f * pixel_size) estimated_resolution = 2.0f * pixel_size;
return estimated_resolution;
}
float ResolutionStatistics::Return0p8Resolution(bool use_part_fsc)
{
float estimated_resolution = 0.0f;
if (use_part_fsc == true)
{
for (int counter = 1; counter < part_FSC.number_of_points; counter++)
{
if (part_FSC.data_y[counter] < 0.8)
{
estimated_resolution = (part_FSC.data_x[counter - 1] + part_FSC.data_x[counter]) / 2.0;
break;
}
}
}
else
{
for (int counter = 1; counter < FSC.number_of_points; counter++)
{
if (FSC.data_y[counter] < 0.8)
{
estimated_resolution = (FSC.data_x[counter - 1] + FSC.data_x[counter]) / 2.0;
break;
}
}
}
if (estimated_resolution < 2.0f * pixel_size) estimated_resolution = 2.0f * pixel_size;
return estimated_resolution;
}
float ResolutionStatistics::Return0p5Resolution(bool use_part_fsc)
{
float estimated_resolution = 0.0f;
if (use_part_fsc == true)
{
for (int counter = 1; counter < part_FSC.number_of_points; counter++)
{
if (part_FSC.data_y[counter] < 0.5)
{
estimated_resolution = (part_FSC.data_x[counter - 1] + part_FSC.data_x[counter]) / 2.0;
break;
}
}
}
else
{
for (int counter = 1; counter < FSC.number_of_points; counter++)
{
if (FSC.data_y[counter] < 0.5)
{
estimated_resolution = (FSC.data_x[counter - 1] + FSC.data_x[counter]) / 2.0;
break;
}
}
}
if (estimated_resolution < 2.0f * pixel_size) estimated_resolution = 2.0f * pixel_size;
return estimated_resolution;
}
float ResolutionStatistics::ReturnResolutionNShellsAfter(float wanted_resolution, int number_of_shells)
{
int resolution_shell = -1;
for (int counter = 1; counter < FSC.number_of_points; counter++)
{
if (FSC.data_x[counter] < wanted_resolution)
{
resolution_shell = counter;
break;
}
}
if (resolution_shell == -1) return 0;
else
{
resolution_shell += number_of_shells;
if (resolution_shell >= FSC.number_of_points) return pixel_size * 2.0;
else return FSC.data_x[resolution_shell];
}
}
int ResolutionStatistics::ReturnResolutionShellNumber(float wanted_resolution)
{
int resolution_shell = -1;
for (int counter = 1; counter < FSC.number_of_points; counter++)
{
if (FSC.data_x[counter] < wanted_resolution)
{
resolution_shell = counter;
break;
}
}
return resolution_shell;
}
float ResolutionStatistics::ReturnResolutionNShellsBefore(float wanted_resolution, int number_of_shells)
{
int resolution_shell = -1;
for (int counter = FSC.number_of_points - 1; counter >= 1; counter--)
{
if (FSC.data_x[counter] > wanted_resolution)
{
resolution_shell = counter;
break;
}
}
if (resolution_shell == -1) return 0;
else
{
resolution_shell -= number_of_shells;
if (resolution_shell < 1) return 0;
else return FSC.data_x[resolution_shell];
}
}
void ResolutionStatistics::Init(float wanted_pixel_size, int box_size)
{
pixel_size = wanted_pixel_size;
number_of_bins = box_size / 2 + 1;
number_of_bins_extended = int(number_of_bins * sqrtf(3.0)) + 1;
FSC.ClearData();
part_FSC.ClearData();
part_SSNR.ClearData();
rec_SSNR.ClearData();
}
void ResolutionStatistics::NormalizeVolumeWithParticleSSNR(Image &reconstructed_volume)
{
// MyDebugAssertTrue(reconstructed_volume.is_in_real_space == false, "reconstructed_volume not in Fourier space");
MyDebugAssertTrue(number_of_bins_extended == int((reconstructed_volume.logical_x_dimension / 2 + 1) * sqrtf(3.0)) + 1, "reconstructed_volume not compatible with resolution statistics");
MyDebugAssertTrue(part_SSNR.number_of_points > 0, "part_SSNR curve not calculated");
float ssq_in;
float ssq_out;
bool need_fft;
Curve temp_curve;
part_SSNR.SquareRoot();
need_fft = reconstructed_volume.is_in_real_space;
if (need_fft) reconstructed_volume.ForwardFFT();
ssq_in = reconstructed_volume.ReturnSumOfSquares();
reconstructed_volume.Whiten(0.5);
reconstructed_volume.MultiplyByWeightsCurve(part_SSNR);
ssq_out = reconstructed_volume.ReturnSumOfSquares();
reconstructed_volume.MultiplyByConstant(sqrtf(ssq_in / ssq_out));
if (need_fft) reconstructed_volume.BackwardFFT();
// If part_SSNR is used after this, it needs to be squared again
// part_SSNR.Square();
}
void ResolutionStatistics::CalculateFSC(Image &reconstructed_volume_1, Image &reconstructed_volume_2, bool smooth_curve)
{
MyDebugAssertTrue(reconstructed_volume_1.is_in_real_space == false, "reconstructed_volume_1 not in Fourier space");
MyDebugAssertTrue(reconstructed_volume_2.is_in_real_space == false, "reconstructed_volume_2 not in Fourier space");
MyDebugAssertTrue(reconstructed_volume_1.HasSameDimensionsAs(&reconstructed_volume_2), "reconstructions do not have equal size");
int i, j, k;
int yi, zi;
float bin;
int ibin;
int window = myroundint(20.0 / pixel_size);
double difference;
double current_sum1;
double current_sum2;
float x, y, z;
float frequency;
float frequency_squared;
if (number_of_bins <= 1 ) number_of_bins = reconstructed_volume_1.ReturnSmallestLogicalDimension() / 2 + 1;
int number_of_bins2 = 2 * (number_of_bins - 1);
// Extend table to include corners in 3D Fourier space
if (reconstructed_volume_1.logical_z_dimension == 1) number_of_bins_extended = int(number_of_bins * sqrtf(2.0)) + 1;
else number_of_bins_extended = int(number_of_bins * sqrtf(3.0)) + 1;
double *sum1 = new double[number_of_bins_extended];
double *sum2 = new double[number_of_bins_extended];
double *cross_terms = new double[number_of_bins_extended];
double *non_zero_count = new double[number_of_bins_extended];
double temp_double;
float temp_float;
long pixel_counter = 0;
std::complex<double> temp_c;
FSC.ClearData();
ZeroDoubleArray(sum1, number_of_bins_extended);
ZeroDoubleArray(sum2, number_of_bins_extended);
ZeroDoubleArray(cross_terms, number_of_bins_extended);
ZeroDoubleArray(non_zero_count, number_of_bins_extended);
for (k = 0; k <= reconstructed_volume_1.physical_upper_bound_complex_z; k++)
{
zi = reconstructed_volume_1.ReturnFourierLogicalCoordGivenPhysicalCoord_Z(k);
z = powf(zi * reconstructed_volume_1.fourier_voxel_size_z, 2);
for (j = 0; j <= reconstructed_volume_1.physical_upper_bound_complex_y; j++)
{
yi = reconstructed_volume_1.ReturnFourierLogicalCoordGivenPhysicalCoord_Y(j);
y = powf(yi * reconstructed_volume_1.fourier_voxel_size_y, 2);
for (i = 0; i <= reconstructed_volume_1.physical_upper_bound_complex_x; i++)
{
x = powf(i * reconstructed_volume_1.fourier_voxel_size_x, 2);
frequency_squared = x + y + z;
// if (frequency_squared <= 0.25)
// {
temp_c = real(reconstructed_volume_1.complex_values[pixel_counter] * conj(reconstructed_volume_2.complex_values[pixel_counter])) + I * 0.0f;
if (temp_c != 0.0)
{
if ((i != 0) || (i == 0 && zi > 0) || (i == 0 && yi > 0 && zi == 0))
{
// compute radius, in units of physical Fourier pixels
bin = sqrtf(frequency_squared) * number_of_bins2;
ibin = int(bin);
difference = bin - float(ibin);
//bin = int(sqrtf(frequency_squared) * number_of_bins2);
if ((i == 0 && yi != 0) || pixel_counter == 0)
{
current_sum1 = real(reconstructed_volume_1.complex_values[pixel_counter] * conj(reconstructed_volume_1.complex_values[pixel_counter])) * 0.25;
current_sum2 = real(reconstructed_volume_2.complex_values[pixel_counter] * conj(reconstructed_volume_2.complex_values[pixel_counter])) * 0.25;
sum1[ibin] += current_sum1 * (1 - difference);
sum1[ibin + 1] += current_sum1 * difference;
sum2[ibin] += current_sum2 * (1 - difference);
sum2[ibin + 1] += current_sum2 * difference;
cross_terms[ibin] += real(temp_c) * (1 - difference) * 0.25;
cross_terms[ibin + 1] += real(temp_c) * difference * 0.25;
non_zero_count[ibin] += 1 - difference * 0.25;
non_zero_count[ibin + 1] += difference * 0.25;
}
else
{
//sum1[bin] += real(reconstructed_volume_1.complex_values[pixel_counter] * conj(reconstructed_volume_1.complex_values[pixel_counter]));
//sum2[bin] += real(reconstructed_volume_2.complex_values[pixel_counter] * conj(reconstructed_volume_2.complex_values[pixel_counter]));
//cross_terms[bin] += crealf(temp_c);
//non_zero_count[bin] += 1;
current_sum1 = real(reconstructed_volume_1.complex_values[pixel_counter] * conj(reconstructed_volume_1.complex_values[pixel_counter]));
current_sum2 = real(reconstructed_volume_2.complex_values[pixel_counter] * conj(reconstructed_volume_2.complex_values[pixel_counter]));
sum1[ibin] += current_sum1 * (1 - difference);
sum1[ibin + 1] += current_sum1 * difference;
sum2[ibin] += current_sum2 * (1 - difference);
sum2[ibin + 1] += current_sum2 * difference;
cross_terms[ibin] += real(temp_c) * (1 - difference);
cross_terms[ibin + 1] += real(temp_c) * difference;
non_zero_count[ibin] += 1 - difference;
non_zero_count[ibin + 1] += difference;
}
}
}
// }
pixel_counter++;
}
}
}
for (i = 0; i < number_of_bins_extended; i++)
{
temp_double = sum1[i] * sum2[i];
if (i > 0)
{
temp_float = pixel_size / float(i) * float(number_of_bins2);
}
else
{
temp_float = 0.0;
}
if (temp_double != 0.0)
{
// if (i < 8 || non_zero_count[i] > 440)
// {
FSC.AddPoint(temp_float, float(cross_terms[i] / sqrtf(temp_double)));
// }
// else
// {
// FSC.AddPoint(pixel_size / float(i) * float(number_of_bins2), 0.0);
// }
}
else
{
FSC.AddPoint(temp_float, 0.0);
}
}
if (smooth_curve)
{
if (window > number_of_bins_extended / 10) window = number_of_bins_extended / 10;
if (window < 5) window = 5;
if (IsOdd(window) == false) window++;
FSC.data_y[0] = FSC.data_y[1];
FSC.FitSavitzkyGolayToData(window, 3);
for (i = 0; i < number_of_bins_extended; i++)
{
// wxPrintf("FSC,fit = %i %g %g\n", i, FSC.data_y[i], FSC.savitzky_golay_fit[i]);
// if (FSC.data_y[i] < 0.8) FSC.data_y[i] = FSC.savitzky_golay_fit[i];
// Make a smooth transition between original FSC curve and smoothed curve
// else FSC.data_y[i] = FSC.data_y[i] * (1.0 - (1.0 - FSC.data_y[i]) / 0.2) + FSC.savitzky_golay_fit[i] * (1.0 - FSC.data_y[i]) / 0.2;
// Make a smooth transition between original FSC curve and smoothed curve
// if (FSC.data_y[i] < 0.5) FSC.data_y[i] = FSC.data_y[i] * (1.0 - fabsf(1.0 - FSC.data_y[i])) + FSC.savitzky_golay_fit[i] * fabsf(1.0 - FSC.data_y[i]);
FSC.data_y[i] = FSC.data_y[i] * (1.0 - (1.0 - fabsf(FSC.data_y[i]))) + FSC.savitzky_golay_fit[i] * (1.0 - fabsf(FSC.data_y[i]));
if (FSC.data_y[i] > 1.0) FSC.data_y[i] = 1.0;
if (FSC.data_y[i] < -1.0) FSC.data_y[i] = -1.0;
}
}
delete [] sum1;
delete [] sum2;
delete [] cross_terms;
delete [] non_zero_count;
}
void ResolutionStatistics::CalculateParticleFSCandSSNR(float mask_volume_in_voxels, float molecular_mass_kDa)
{
MyDebugAssertTrue(FSC.number_of_points > 0, "FSC curve must be calculated first");
int i;
part_FSC.ClearData();
rec_SSNR.ClearData();
float volume_fraction = kDa_to_Angstrom3(molecular_mass_kDa) / powf(pixel_size,3) / mask_volume_in_voxels;
for (i = 0; i < number_of_bins_extended; i++)
{
part_FSC.AddPoint(FSC.data_x[i], FSC.data_y[i] / volume_fraction / (1.0f + (1.0f / volume_fraction - 1.0f) * fabsf(FSC.data_y[i])));
}
for (i = 0; i < number_of_bins_extended; i++)
{
if (part_FSC.data_y[i] > 0.0)
{
rec_SSNR.AddPoint(FSC.data_x[i], fabsf(2.0f * part_FSC.data_y[i] / (1.00001f - part_FSC.data_y[i])));
}
else
{
rec_SSNR.AddPoint(FSC.data_x[i],0.0f);
}
}
}
void ResolutionStatistics::CalculateParticleSSNR(Image &image_reconstruction, float *ctf_reconstruction, float mask_volume_fraction)
{
MyDebugAssertTrue(FSC.number_of_points > 0, "FSC curve must be calculated first");
MyDebugAssertTrue(mask_volume_fraction > 0.0, "mask_volume_fraction invalid");
part_SSNR.ClearData();
int i, j, k;
int yi, zi;
int bin;
int number_of_bins2;
float x, y, z;
float frequency;
float frequency_squared;
// float pssnr_scaling_factor = mask_volume_fraction / average_occupancy * 100.0;
// float pssnr_scaling_factor = 1.0 / mask_volume_fraction;
double *sum_double = new double[number_of_bins_extended];
long *sum_int = new long[number_of_bins_extended];
long pixel_counter = 0;
ZeroDoubleArray(sum_double, number_of_bins_extended);
ZeroLongArray(sum_int, number_of_bins_extended);
number_of_bins2 = 2 * (number_of_bins - 1);
for (k = 0; k <= image_reconstruction.physical_upper_bound_complex_z; k++)
{
zi = image_reconstruction.ReturnFourierLogicalCoordGivenPhysicalCoord_Z(k);
z = powf(zi * image_reconstruction.fourier_voxel_size_z, 2);
for (j = 0; j <= image_reconstruction.physical_upper_bound_complex_y; j++)
{
yi = image_reconstruction.ReturnFourierLogicalCoordGivenPhysicalCoord_Y(j);
y = powf(yi * image_reconstruction.fourier_voxel_size_y, 2);
for (i = 0; i <= image_reconstruction.physical_upper_bound_complex_x; i++)
{
x = powf(i * image_reconstruction.fourier_voxel_size_x, 2);
frequency_squared = x + y + z;
// if (frequency_squared <= 0.25)
// {
if (ctf_reconstruction[pixel_counter] != 0.0)
{
if ((i != 0) || (i == 0 && zi > 0) || (i == 0 && yi > 0 && zi == 0))
{
// compute radius, in units of physical Fourier pixels
bin = int(sqrtf(frequency_squared) * number_of_bins2);
if ((i == 0 && yi != 0) || pixel_counter == 0)
{
sum_double[bin] += ctf_reconstruction[pixel_counter] * 0.5;
}
else
{
sum_double[bin] += ctf_reconstruction[pixel_counter];
}
sum_int[bin] += 1;
}
}
// }
pixel_counter++;
}
}
}
for (i = 0; i < number_of_bins_extended; i++)
{
if (sum_double[i] > 0.0 && i > 0)
{
// part_SSNR.AddPoint(pixel_size / float(i) * float(number_of_bins2), float(sum_double[i]) / float(sum_int[i]) / 0.5);
// part_SSNR.AddPoint(pixel_size / float(i) * float(number_of_bins2), float(sum_double[i]) / float(sum_int[i]) / 0.25 / 10000 * i);
// Average sum of CTF^2 from N 2D images contributing to a 3D voxel = float(sum_double[i]) / float(sum_int[i]) = N * 0.5 / 2i
// The factor of 0.5 is due to the average value for CTF^2.
// The factor of 1 / 2 is due to the average weight in the trilinear interpolation
// Divide volume SSNR by float(sum_double[i]) / float(sum_int[i])
// Factor of 8.0 is due to 8-point trilinear interpolation
// wxPrintf("i = %i, fsc, sum_int, sum_double, ratio = %g %g %g %g\n", i, FSC.data_y[i], float(sum_int[i]), float(sum_double[i]), float(sum_int[i]) / float(sum_double[i]));
// part_SSNR.AddPoint(pixel_size / float(i) * float(number_of_bins2), 8.0 * 4.0 * mask_volume_fraction * fabsf(2.0 * fabsf(FSC.data_y[i]) / (1.00001 - fabsf(FSC.data_y[i])) * float(sum_int[i]) / float(sum_double[i])));
part_SSNR.AddPoint(pixel_size / float(i) * float(number_of_bins2), mask_volume_fraction * fabsf(2.0f * fabsf(FSC.data_y[i]) / (1.00001f - fabsf(FSC.data_y[i])) * float(sum_int[i]) / float(sum_double[i])));
// wxPrintf("x = %g, y = %g\n", FSC.data_x[i], FSC.data_y[i]);
}
else
if (i > 0)
{
part_SSNR.AddPoint(pixel_size / float(i) * float(number_of_bins2), 0.0f);
}
else
{
// part_SSNR.AddPoint(pixel_size * powf(float(number_of_bins2), 2), 0.0);
part_SSNR.AddPoint(0.0f, 0.0f);
}
}
// Set value at i = 0 to 8 * value at i = 1 to allow reconstructions with non-zero offset
part_SSNR.data_y[0] = 8.0f * part_SSNR.data_y[1];
delete [] sum_double;
delete [] sum_int;
// wxPrintf("number_of_bins = %i, number_of_bins_extended = %i, ssnr = %i\n", number_of_bins, number_of_bins_extended, part_SSNR.number_of_points);
}
void ResolutionStatistics::RestrainParticleSSNR(float low_resolution_limit)
{
int i;
float adjustment_factor = -FLT_MAX;
float reciprocal_resolution_limit = 0.0f;
if (low_resolution_limit > 0.0f) reciprocal_resolution_limit = 1.0f / low_resolution_limit;
Curve temp_curve;
temp_curve = part_SSNR;
// part_SSNR x-axis is in A, need 1/A for fit
for (i = 0; i < temp_curve.number_of_points; i++) {if (temp_curve.data_x[i] != 0.0f) temp_curve.data_x[i] = 1.0f / temp_curve.data_x[i];}
// temp_curve.FitGaussianToData(reciprocal_resolution_limit, FLT_MAX, true);
temp_curve.FitGaussianToData(reciprocal_resolution_limit);
for (i = 0; i < part_SSNR.number_of_points; i++)
{
if (temp_curve.data_x[i] >= reciprocal_resolution_limit)
{
// Set adjustment factor for the first time
if (adjustment_factor < -FLT_MAX * 0.5f && temp_curve.gaussian_fit[i] > 0.0f) adjustment_factor = part_SSNR.data_y[i] / powf(temp_curve.gaussian_fit[i], 2);
// Square Gaussian for additional down-weighting of high frequencies to counter over-fitting
// Only do this if adjustment_factor was set to a reasonable value
if (adjustment_factor >= -FLT_MAX * 0.5f) part_SSNR.data_y[i] = adjustment_factor * powf(temp_curve.gaussian_fit[i], 2);
}
}
}
void ResolutionStatistics::ZeroToResolution(float resolution_limit)
{
MyDebugAssertTrue(number_of_bins > 0, "Statistics not initialized");
int number_of_bins2 = 2 * (number_of_bins - 1);
int index;
if (resolution_limit > 0.0)
{
index = int(pixel_size / resolution_limit * float(number_of_bins2));
FSC.ZeroAfterIndex(index);
part_FSC.ZeroAfterIndex(index);
part_SSNR.ZeroAfterIndex(index);
rec_SSNR.ZeroAfterIndex(index);
}
}
void ResolutionStatistics::PrintStatistics()
{
MyDebugAssertTrue(FSC.number_of_points > 0, "Resolution statistics have not been fully calculated");
wxPrintf("\nC Sqrt Sqrt \n");
wxPrintf("C NO. RESOL RING_RAD FSC Part_FSC Part_SSNR Rec_SSNR\n");
for (int i = 1; i < number_of_bins; i++)
{
wxPrintf("%5i%8.2f%10.4f%10.4f%10.4f%10.4f%10.4f\n",i + 1, FSC.data_x[i], pixel_size / FSC.data_x[i],
FSC.data_y[i], part_FSC.data_y[i],
sqrtf(part_SSNR.data_y[i]), sqrtf(rec_SSNR.data_y[i]));
}
}
void ResolutionStatistics::WriteStatisticsToFloatArray(float *float_array, int wanted_class) // this is a hack for pre-embo course rush, but i predict it will last for a long time after...
{
float_array[0] = FSC.number_of_points;
float_array[1] = wanted_class;
int position_counter = 2;
for (int i = 0; i < FSC.number_of_points; i++)
{
float_array[position_counter] = FSC.data_x[i];
position_counter++;
float_array[position_counter] = FSC.data_y[i];
position_counter++;
float_array[position_counter] = part_FSC.data_y[i];
position_counter++;
float_array[position_counter] = part_SSNR.data_y[i];
position_counter++;
float_array[position_counter] = rec_SSNR.data_y[i];
position_counter++;
}
}
void ResolutionStatistics::WriteStatisticsToFile(NumericTextFile &output_statistics_file, float pssnr_division_factor)
{
MyDebugAssertTrue(FSC.number_of_points > 0, "Resolution statistics have not been fully calculated");
float temp_float[7];
// NumericTextFile output_statistics_file(output_file, OPEN_TO_WRITE, 7);
output_statistics_file.WriteCommentLine("C SHELL RESOLUTION RING_RADIUS FSC Part_FSC Part_SSNR^0.5 Rec_SSNR^0.5");
for (int i = 1; i < number_of_bins; i++)
{
temp_float[0] = float(i+1);
temp_float[1] = FSC.data_x[i];
temp_float[2] = pixel_size / FSC.data_x[i];
temp_float[3] = FSC.data_y[i];
temp_float[4] = part_FSC.data_y[i];
temp_float[5] = sqrtf(part_SSNR.data_y[i] / pssnr_division_factor);
temp_float[6] = sqrtf(rec_SSNR.data_y[i]);
output_statistics_file.WriteLine(temp_float);
}
}
void ResolutionStatistics::ReadStatisticsFromFile(wxString input_file)
{
int i;
float temp_float[10];
float resolution;
int number_of_bins2 = 2 * (number_of_bins - 1);
if (! DoesFileExist(input_file))
{
MyPrintWithDetails("Error: Statistics file not found\n");
DEBUG_ABORT;
}
NumericTextFile my_statistics(input_file, OPEN_TO_READ);
FSC.ClearData();
part_FSC.ClearData();
part_SSNR.ClearData();
rec_SSNR.ClearData();
FSC.AddPoint(0.0, 1.0);
part_FSC.AddPoint(0.0, 1.0);
part_SSNR.AddPoint(0.0, 1000.0);
rec_SSNR.AddPoint(0.0, 1000.0);
for (i = 1; i <= my_statistics.number_of_lines; i++)
{
my_statistics.ReadLine(temp_float);
resolution = pixel_size / float(i) * float(number_of_bins2);
if (fabsf(resolution - temp_float[1]) > 0.1)
{
MyPrintWithDetails("Statistics file not compatible with input reconstruction\n");
DEBUG_ABORT;
}
FSC.AddPoint(temp_float[1], temp_float[3]);
part_FSC.AddPoint(temp_float[1], temp_float[4]);
part_SSNR.AddPoint(temp_float[1], powf(temp_float[5],2));
rec_SSNR.AddPoint(temp_float[1], powf(temp_float[6],2));
}
for (i = my_statistics.number_of_lines + 1; i <= number_of_bins_extended; i++)
{
resolution = pixel_size / float(i) * float(number_of_bins2);
FSC.AddPoint(resolution, 0.0);
part_FSC.AddPoint(resolution, 0.0);
part_SSNR.AddPoint(resolution, 0.0);
rec_SSNR.AddPoint(resolution, 0.0);
}
}
void ResolutionStatistics::GenerateDefaultStatistics(float molecular_mass_in_kDa)
{
int i;
float resolution;
float ssnr;
float fsc;
// float particle_diameter = 2.0 * powf(3.0 * kDa_to_Angstrom3(molecular_mass_in_kDa) / 4.0 / PI / powf(pixel_size,3) ,1.0 / 3.0);
float particle_diameter = 2.0 * powf(3.0 * kDa_to_Angstrom3(molecular_mass_in_kDa) / 4.0 / PI,1.0 / 3.0);
int number_of_bins2 = 2 * (number_of_bins - 1);
int number_of_bins_extended = int((number_of_bins2 / 2 + 1) * sqrtf(3.0)) + 1;
FSC.ClearData();
part_FSC.ClearData();
part_SSNR.ClearData();
rec_SSNR.ClearData();
FSC.AddPoint(0.0, 1.0);
part_FSC.AddPoint(0.0, 1.0);
part_SSNR.AddPoint(0.0, 1000.0);
rec_SSNR.AddPoint(0.0, 1000.0);
for (i = 1; i <= number_of_bins_extended; i++)
{
resolution = pixel_size / float(i) * float(number_of_bins2);
// Approximate formula derived from part_SSNR curve for VSV-L
ssnr = powf(molecular_mass_in_kDa,1.5) / 2200.0 * (800.0 * expf(-3.5 * particle_diameter / resolution) + expf(-25.0 / resolution));
fsc = ssnr / (2.0 + ssnr);
FSC.AddPoint(resolution, fsc);
part_FSC.AddPoint(resolution, fsc);
part_SSNR.AddPoint(resolution, ssnr);
// wxPrintf("i = %i, res = %g, sqrt(pssnr) = %g\n", i, resolution, sqrtf(ssnr));
rec_SSNR.AddPoint(resolution, ssnr);
}
}
| 33.742389 | 220 | 0.710543 | ngrigorieff |
4d3b353b10cac4ae699c60d62bc1e2301a2ce0b6 | 11,752 | cpp | C++ | test_conformance/gles/main.cpp | svenvh/OpenCL-CTS | 509172b7805aca2514081e259b6f26cb74a3445a | [
"Apache-2.0"
] | null | null | null | test_conformance/gles/main.cpp | svenvh/OpenCL-CTS | 509172b7805aca2514081e259b6f26cb74a3445a | [
"Apache-2.0"
] | null | null | null | test_conformance/gles/main.cpp | svenvh/OpenCL-CTS | 509172b7805aca2514081e259b6f26cb74a3445a | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2017 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <stdlib.h>
#if !defined(_WIN32)
#include <stdbool.h>
#endif
#include <math.h>
#include <string.h>
#if !defined (__APPLE__)
#include <CL/cl.h>
#endif
#include "procs.h"
#include "../../test_common/gles/setup.h"
#include "../../test_common/harness/testHarness.h"
#if !defined(_WIN32)
#include <unistd.h>
#endif
static cl_context sCurrentContext = NULL;
#define TEST_FN_REDIRECT( fn ) ADD_TEST( redirect_##fn )
#define TEST_FN_REDIRECTOR( fn ) \
int test_redirect_##fn(cl_device_id device, cl_context context, cl_command_queue queue, int numElements ) \
{ \
int error; \
clCommandQueueWrapper realQueue = clCreateCommandQueue( sCurrentContext, device, 0, &error ); \
test_error( error, "Unable to create command queue" ); \
return test_##fn( device, sCurrentContext, realQueue, numElements ); \
}
TEST_FN_REDIRECTOR( buffers )
TEST_FN_REDIRECTOR( buffers_getinfo )
TEST_FN_REDIRECTOR( images_read )
TEST_FN_REDIRECTOR( images_2D_getinfo )
TEST_FN_REDIRECTOR( images_read_cube )
TEST_FN_REDIRECTOR( images_cube_getinfo )
TEST_FN_REDIRECTOR( images_read_3D )
TEST_FN_REDIRECTOR( images_3D_getinfo )
TEST_FN_REDIRECTOR( images_write )
TEST_FN_REDIRECTOR( images_write_cube )
TEST_FN_REDIRECTOR( renderbuffer_read )
TEST_FN_REDIRECTOR( renderbuffer_write )
TEST_FN_REDIRECTOR( renderbuffer_getinfo )
#ifndef GL_ES_VERSION_2_0
TEST_FN_REDIRECTOR( test_fence_sync )
#endif
test_definition test_list[] = {
TEST_FN_REDIRECT( buffers ),
TEST_FN_REDIRECT( buffers_getinfo ),
TEST_FN_REDIRECT( images_read ),
TEST_FN_REDIRECT( images_2D_getinfo ),
TEST_FN_REDIRECT( images_read_cube ),
TEST_FN_REDIRECT( images_cube_getinfo ),
TEST_FN_REDIRECT( images_read_3D ),
TEST_FN_REDIRECT( images_3D_getinfo ),
TEST_FN_REDIRECT( images_write ),
TEST_FN_REDIRECT( images_write_cube ),
TEST_FN_REDIRECT( renderbuffer_read ),
TEST_FN_REDIRECT( renderbuffer_write ),
TEST_FN_REDIRECT( renderbuffer_getinfo )
};
#ifndef GL_ES_VERSION_2_0
test_definition test_list32[] = {
TEST_FN_REDIRECT( fence_sync )
};
#endif
const int test_num = ARRAY_SIZE( test_list );
const int test_num32 = ARRAY_SIZE( test_list32 );
int main(int argc, const char *argv[])
{
int error = 0;
cl_platform_id platform_id = NULL;
/* To keep it simple, use a static allocation of 32 argv pointers.
argc is not expected to go beyond 32 */
const char* argv_tmp[32] = {0};
int argc_tmp = 0;
test_start();
cl_device_type requestedDeviceType = CL_DEVICE_TYPE_DEFAULT;
for(int z = 1; z < argc; ++z)
{//for
if(strcmp( argv[ z ], "-list" ) == 0 )
{
log_info( "Available 2.x tests:\n" );
for( int i = 0; i < test_num; i++ )
log_info( "\t%s\n", test_list[i].name );
log_info( "Available 3.2 tests:\n" );
for( int i = 0; i < test_num32; i++ )
log_info( "\t%s\n", test_list32[i].name );
log_info( "Note: Any 3.2 test names must follow 2.1 test names on the command line." );
log_info( "Use environment variables to specify desired device." );
test_finish();
return 0;
}
/* support requested device type */
if(!strcmp(argv[z], "CL_DEVICE_TYPE_GPU"))
{
printf("Requested device type is CL_DEVICE_TYPE_GPU\n");
requestedDeviceType = CL_DEVICE_TYPE_GPU;
}
else
if(!strcmp(argv[z], "CL_DEVICE_TYPE_CPU"))
{
printf("Requested device type is CL_DEVICE_TYPE_CPU\n");
log_info("Invalid CL device type. GL tests can only run on a GPU device.\n");
test_finish();
return 0;
}
}//for
// Check to see if any 2.x or 3.2 test names were specified on the command line.
unsigned first_32_testname = 0;
for (int j=1; (j<argc) && (!first_32_testname); ++j)
for (int i = 0; i < test_num32; ++i)
if (strcmp(test_list32[i].name, argv[j]) == 0 ) {
first_32_testname = j;
break;
}
// Create the environment for the test.
GLEnvironment *glEnv = GLEnvironment::Instance();
// Check if any devices of the requested type support CL/GL interop.
int supported = glEnv->SupportsCLGLInterop( requestedDeviceType );
if( supported == 0 ) {
log_info("Test not run because GL-CL interop is not supported for any devices of the requested type.\n");
test_finish();
error = 0;
goto cleanup;
} else if ( supported == -1 ) {
log_error("Failed to determine if CL-GL interop is supported.\n");
test_finish();
error = -1;
goto cleanup;
}
// OpenGL tests for non-3.2 ////////////////////////////////////////////////////////
if ((argc == 1) || (first_32_testname != 1)) {
// At least one device supports CL-GL interop, so init the test.
if( glEnv->Init( &argc, (char **)argv, CL_FALSE ) ) {
log_error("Failed to initialize the GL environment for this test.\n");
test_finish();
error = -1;
goto cleanup;
}
// Create a context to use and then grab a device (or devices) from it
sCurrentContext = glEnv->CreateCLContext();
if( sCurrentContext == NULL )
{
log_error( "ERROR: Unable to obtain CL context from GL\n" );
test_finish();
error = -1;
goto cleanup;
}
size_t numDevices = 0;
cl_device_id deviceIDs[ 16 ];
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, 0, NULL, &numDevices);
if( error != CL_SUCCESS )
{
print_error( error, "Unable to get device count from context" );
test_finish();
error = -1;
goto cleanup;
}
numDevices /= sizeof(cl_device_id);
if (numDevices < 1) {
log_error("No devices found.\n");
test_finish();
error = -1;
goto cleanup;
}
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, sizeof( deviceIDs ), deviceIDs, NULL);
if( error != CL_SUCCESS ) {
print_error( error, "Unable to get device list from context" );
test_finish();
error = -1;
goto cleanup;
}
// Execute tests.
int argc_ = (first_32_testname) ? first_32_testname : argc;
for( size_t i = 0; i < numDevices; i++ ) {
log_info( "\nTesting OpenGL 2.x\n" );
if( printDeviceHeader( deviceIDs[ i ] ) != CL_SUCCESS ) {
test_finish();
error = -1;
goto cleanup;
}
error = clGetDeviceInfo(deviceIDs[ i ],
CL_DEVICE_PLATFORM,
sizeof(platform_id),
&platform_id,
NULL);
if(error)
{
goto cleanup;
}
error = init_clgl_ext(platform_id);
if (error < 0)
{
goto cleanup;
}
/* parseAndCallCommandLineTests considers every command line argument
as a test name. This results in the test failing because of considering
args such as 'CL_DEVICE_TYPE_GPU' as test names unless
the actual test name happens to be the first argument.
Instead of changing the behaviour of parseAndCallCommandLineTests
modify the arguments passed to it so as to not affect other tests.
*/
int w = 1;
argc_tmp= argc_;
for(int k = 1; k < argc; k++)
{
if( (strcmp(argv[k], "full") == 0) ||
(strcmp(argv[k], "CL_DEVICE_TYPE_CPU") == 0) ||
(strcmp(argv[k], "CL_DEVICE_TYPE_GPU") == 0))
{
argc_tmp--;
continue;
}
else
{
argv_tmp[w++] = argv[k];
}
}
// Note: don't use the entire harness, because we have a different way of obtaining the device (via the context)
error = parseAndCallCommandLineTests( argc_tmp, argv_tmp, deviceIDs[i], test_num, test_list, true, 0, 1024 );
if( error != 0 )
break;
}
// Clean-up.
// We move this to a common cleanup step to make sure that things will be released properly before the test exit
goto cleanup;
// clReleaseContext( sCurrentContext );
// delete glEnv;
}
// OpenGL 3.2 tests. ////////////////////////////////////////////////////////
if ((argc==1) || first_32_testname) {
// At least one device supports CL-GL interop, so init the test.
if( glEnv->Init( &argc, (char **)argv, CL_TRUE ) ) {
log_error("Failed to initialize the GL environment for this test.\n");
test_finish();
error = -1;
goto cleanup;
}
// Create a context to use and then grab a device (or devices) from it
sCurrentContext = glEnv->CreateCLContext();
if( sCurrentContext == NULL ) {
log_error( "ERROR: Unable to obtain CL context from GL\n" );
test_finish();
error = -1;
goto cleanup;
}
size_t numDevices = 0;
cl_device_id deviceIDs[ 16 ];
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, 0, NULL, &numDevices);
if( error != CL_SUCCESS ) {
print_error( error, "Unable to get device count from context" );
test_finish();
error = -1;
goto cleanup;
}
numDevices /= sizeof(cl_device_id);
if (numDevices < 1) {
log_error("No devices found.\n");
test_finish();
error = -1;
goto cleanup;
}
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, sizeof( deviceIDs ), deviceIDs, NULL);
if( error != CL_SUCCESS ) {
print_error( error, "Unable to get device list from context" );
test_finish();
error = -1;
goto cleanup;
}
int argc_ = (first_32_testname) ? 1 + (argc - first_32_testname) : argc;
const char** argv_ = (first_32_testname) ? &argv[first_32_testname-1] : argv;
// Execute the tests.
for( size_t i = 0; i < numDevices; i++ ) {
log_info( "\nTesting OpenGL 3.2\n" );
if( printDeviceHeader( deviceIDs[ i ] ) != CL_SUCCESS ) {
test_finish();
error = -1;
goto cleanup;
}
#ifdef GL_ES_VERSION_2_0
log_info("Cannot test OpenGL 3.2! This test was built for OpenGL ES 2.0\n");
test_finish();
error = -1;
goto cleanup;
#else
// Note: don't use the entire harness, because we have a different way of obtaining the device (via the context)
error = parseAndCallCommandLineTests( argc_, argv_, deviceIDs[ i ], test_num32, test_list32, true, 0, 1024 );
if( error != 0 )
break;
#endif
}
// Converge on a common cleanup to make sure that things will be released properly before the test exit
goto cleanup;
}
// cleanup CL/GL/EGL environment properly when the test exit.
// This change does not affect any functionality of the test
// Intentional falling through
cleanup:
// Always make sure that OpenCL context is released properly when the test exit
if(sCurrentContext)
{
clReleaseContext( sCurrentContext );
sCurrentContext = NULL;
}
// Cleanup EGL
glEnv->terminate_egl_display();
delete glEnv;
return error;
}
| 31.007916 | 120 | 0.624319 | svenvh |
4d3d4268156b9cb81dba38fd3e56fa62af60cc7d | 626 | cpp | C++ | roguelike/health_drop.cpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | roguelike/health_drop.cpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | roguelike/health_drop.cpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | #include "health_drop.hpp"
#include "utils.hpp"
#include "game_manager.hpp"
#include "player.hpp"
HealthDrop::HealthDrop(GameManager *_manager, GameEntity *parent, sf::Vector2f pos, float powerLevel) : Collectible(_manager, parent, pos) {
health = powerLevel * 20;
}
void HealthDrop::draw(sf::RenderTarget &renderer) const {
sf::RectangleShape rect(getSize());
rect.setFillColor(sf::Color::Red);
rect.setPosition(getTotalPosition());
rect.setOrigin(rect.getSize() / 2.0f);
renderer.draw(rect);
}
void HealthDrop::getCollected() {
manager->getPlayer()->receiveHealth(health);
setAlive(false);
} | 28.454545 | 141 | 0.717252 | LoginLEE |
4d40dd82435dbcd8527a4bc65cc46bbe618dd4db | 18,387 | hpp | C++ | tutorials/SkipGram/text8.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | tutorials/SkipGram/text8.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | tutorials/SkipGram/text8.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <algorithm>
#include <cstring>
#include <string.h>
#include <time.h> //난수 생성위해 추가!
#include "../../WICWIU_src/Tensor.hpp"
#include "../../WICWIU_src/DataLoader.hpp"
#include "Langs.hpp"
//여기에 선언해주는 숫자는!!! 이제 파일에 있는 단어의 개수임!!!
//text8꺼 다시 확인해보고 사용하기!
//#define NUMOFVOCAB 71293 //text8에서 중복 없는 단어의 개수!(vocab size) // eos sos +2 해주면 71293개! //eos만 해주면 +1 71292
#define NUMOFVOCAB 253856 //text8에서 중복 없는 단어의 개수!(vocab size) // eos sos +2 해주면 71293개! //eos만 해주면 +1 71292
//#define NUMOFVOCAB 4181 //shakespear.txt 에서 중복 없는 단어의 개수!(vocab size) // eos, sos 추가 안하면 4179 // eos sos +2 해주면 4181개!
//매우중요!!! 단어개수가!!!.... 이게 결국 0부터 시작하면 4180개 이고.... 1부터 시작하면 4181개인거임....
//#define NUMOFVOCAB 2515 //Subtext8.txt
//#define NUMOFVOCAB 15036 //Subtext8-2.txt
//#define NUMOFVOCAB 1289 //debug.txt
#define NUMOFWORD 17005207 //text8에서 단어의 개수!
//#define NUMOFWORD 27655 //shakespeare.txt에서 단어의 개수!
//#define NUMOFWORD 9967 //subtext8.txt에서 단어의 개수!
//#define NUMOFWORD 142395 //subtext8-2.txt에서 단어의 개수!
//#define NUMOFWORD 4278 //debug.txt
using namespace std;
enum OPTION {
ONEHOT,
CBOWMODE,
SKIPGRAM,
ACCURACY
};
void MakeOneHotVector(int* onehotvector, int vocab_size, int index){
for(int i=0; i<vocab_size; i++){
if(i==index)
onehotvector[i] = 1;
else
onehotvector[i] = 0;
}
}
void Eliminate(char *str, char ch){
int length = strlen(str);
for(int i=0; i<length; i++){
if(str[i] == ch)
{
for(int j=i; j<length; j++)
str[j] = str[j+1]; //+1로 처리해주기 때문에 NULL까지 옮겨줌!!!
}
}
}
void replace(char *str, char tar, char repl){
int length = strlen(str);
for(int i=0; i<length; i++){
if(str[i] == tar)
str[i] = repl;
}
}
template<typename DTYPE>
class text8 : public Dataset<DTYPE> {
private:
Langs langs;
//textData에 있던 변수들!!!
string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!
char* TextData; //파일에서 읽어오기!
string* wordTextData; //strtok를 사용하면 원래 data가 바뀌어서 추가한거!
int vocab_size; //반복없는 단어의 개수
int text_length; // 이거는 char 개수... //나중에 fastText에서 필요할 수도 있을거 같아서 남겨둠!!!
int word_num; //단어의 개수
//각 단어가 몇 번 나왔는지는 없음...! 이거 배열을 하나 더 만들어서 가능할듯!!! -> sampling 할때 필요!
int* wordFrequency; //이걸.... 음.... vocab size를 미리 받아서 하는걸로 할까.... 아니면... 음... 우찌하면 좋을라나...
OPTION option;
//word2vec.hpp에 있던 거!!!
DTYPE **m_aaInput;
DTYPE **m_aaLabel;
int m_numOfInput; //input data의 개수!!!
int m_window; //window size -> 홀수가 기본이겠지!
int m_negative;
int m_dimOfInput;
int m_dimOfLabel;
public:
text8(string File_Path, int window, int negative, OPTION pOption, string lang1, string lang2) : langs(File_Path, lang1, lang2) {
vocab = NULL;
TextData = NULL;
wordTextData = NULL;
vocab_size = 0;
text_length = 0;
word_num=0;
option = pOption;
//word2vec.hpp에 있던거!
m_aaInput = NULL;
m_aaLabel = NULL;
m_numOfInput = 0;
m_window = 0;
m_negative = 0;
m_dimOfInput = 0;
m_dimOfLabel = 0;
Alloc(File_Path, window, negative);
}
virtual ~text8() {
Delete();
}
//왜 굳이 virtual인거지?
void Alloc(string pTextPath, int window, int negative);
void Delete();
void FileReader(string pFile_Path);
void MakeVocab();
//SKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAM
void MakeSkipGramInputData();
void MakeSkipGramLabelData();
//SKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAMSKIPGRAM
//ACCURACYACCURACYACCURACYACCURACYACCURACYACCURACYACCURACY
void MakeAccuracyData();
//ACCURACYACCURACYACCURACYACCURACYACCURACYACCURACYACCURACY
int word2index(string str);
string index2word(int index);
int GetTextLength();
int GetWordNum();
string* GetVocab();
int GetVocabSize();
int GetInputDim();
int GetLabelDim();
virtual std::vector<Tensor<DTYPE> *>* GetData(int idx);
virtual int GetLength();
};
template<typename DTYPE> void text8<DTYPE>::Alloc(string File_Path, int window, int negative) {
vocab = new string[NUMOFVOCAB]; //원래는 NUMOFWORD+2 였음! 이거 문제가 아님!!!
wordTextData = new string[NUMOFWORD];
//subsampling 때문에 추가됨!
wordFrequency = new int[NUMOFVOCAB];
m_window = window;
m_negative = negative;
if(option == SKIPGRAM){
std::cout<<"skipgram alloc 호출!"<<'\n';
m_numOfInput = NUMOFWORD * (m_window - 1); //sos eos 추가
m_dimOfInput = m_negative + 2; //center word와 context neighbor word 2개 추가!
m_dimOfLabel = m_negative + 1; //positive sample 추가
}
else if(option == ACCURACY){
std::cout<<"accuracy alloc 호출!"<<'\n';
m_numOfInput = NUMOFWORD / 4;
m_dimOfInput = 3;
m_dimOfLabel = 1;
}
m_aaInput = new DTYPE *[m_numOfInput];
m_aaLabel = new DTYPE *[m_numOfInput];
FileReader(File_Path);
//여기서부터-----------------------------------------------
//make_vocab
MakeVocab();
if(option == SKIPGRAM){
MakeSkipGramInputData();
// MakeSkipGramLabelData();
}
else if(option == ACCURACY){
MakeAccuracyData();
}
//여기까지 alloc함수에서 호출하지 말고 다른곳에서 호출하도록 만들자!!!
}
template<typename DTYPE> void text8<DTYPE>::Delete() {
delete []vocab;
delete []TextData;
}
template<typename DTYPE> void text8<DTYPE>::FileReader(string pFile_Path) {
std::cout<<"FileReader"<<'\n';
ifstream fin;
fin.open(pFile_Path);
if(fin.is_open()){
//파일 사이즈 구하기
fin.seekg(0, ios::end);
text_length = fin.tellg();
fin.tellg();
fin.seekg(0, ios::beg); //포인터를 다시 시작위치로 바꿈
//cout<<"@@@@@@@@@@@@@@@@@ Print Text Length = "<<text_length <<" @@@@@@@@@@@@@@@@@@@@@"<<endl;
//파일 길이만큼 할당
TextData = new char[text_length];
//파일 읽기
fin.read(TextData, text_length);
cout<<"@@@@@@@@@@@@@@@@@ Print Text Last 100 @@@@@@@@@@@@@@@@@@@@@"<<endl;
for(int i=text_length-100 ; i<=text_length ; i++)
cout<<TextData[i];
cout<<endl;
//*************************************************************************이거 text8에 대해서는 필요 없어서 실행 시키지 않기!!!
//소문자로 변환
// for(int i=0; i<text_length; i++){
// TextData[i] = tolower(TextData[i]);
// }
// std::cout<<"제거 전 text 길이 : "<<text_length<<'\n';
// std::cout<< strlen(TextData)<<'\n';
//빈공간 다 없애고 sp만 남기기
//*************************************************************************이거 text8에 대해서는 필요 없어서 실행 시키지 않기!!!
// Eliminate(TextData, '\n');
// Eliminate(TextData, ':');
// Eliminate(TextData, ',');
// Eliminate(TextData, '.');
// Eliminate(TextData, ';');
// Eliminate(TextData, '?');
// Eliminate(TextData, '!');
// replace(TextData, '\r', ' ');
}
text_length = strlen(TextData); //strlen원리가 NULL를 찾을 때 까지여서 마지막에 NULL이 자동으로 추가된거 같음!
fin.close();
}
template<typename DTYPE> void text8<DTYPE>::MakeVocab(){
std::cout<<"---------------------Makevocab------------------"<<'\n';
int flag = 0;
char* token = strtok(TextData, " "); //단어 하나씩 가져오기 위한 변수
int word_count =0;
while(token != NULL){
//wordTextData[NUMOFWORD-4] = token;
wordTextData[word_count] = token; //301291
//std::cout<<"word count : "<<word_count<<" "<<token<<'\n';
//std::cout<<word_count<<'\n';
if(word_count%100000==0)
std::cout<<word_count<<'\n';
//중복확인하기
for(int i=0; i<vocab_size; i++){
if(vocab[i] == token){
flag = 1;
wordFrequency[i]++;
break;
// std::cout<<"중복된 단어 : "<<token<<'\n';
}
}
//중복이 아니라면
if(flag == 0){
vocab[vocab_size] = token;
wordFrequency[vocab_size] = 1;
vocab_size++;
}
token = strtok(NULL, " "); // 이건 왜 있는건지 확인@@@@@@@@@@@
//단어 개수
word_count++;
flag = 0;
}
//SOS하고 EOS 추가하려면 여기서!!! 그리고 vocab수하고 파일에 있는 단어수도 증가시키기???
//sos : "<s>" eos : "<\s>"
// std::cout<<index2word(vocab_size-1)<<" "<<index2word(vocab_size)<<"???"<<'\n';
wordFrequency[vocab_size] = 1;
vocab[vocab_size++] = "<s>";
wordFrequency[vocab_size] = 1;
//매우 중요!!! 여기서 ++해주는 이유는!!! 이제 모든 index 접근을.... <=가 아닌 <로 for문을 만들어서... 문제가 생김!! 이 문제는 단순히 text8에서만의 문제가 아니라!!! 다른 operator에서도 이제 접근할 때 for문에서 <로 해서 이제 문제가 생김!!! 마지막 <e>이거 때문에!!!
vocab[vocab_size++] = "<e>";
//count를 사용해서 subsampling을 하기위해!!! 굳이 sort를 할 필요가 없다고 생각함!!! 결과에 영향 없을 듯!
//sort(vocab, vocab+vocab_size-1);
word_num = word_count;
std::cout<<"파일에 있는 단어의 개수(중복 포함) : "<<word_num<<'\n';
std::cout<<"파일에 있는 단어의 개수(중복 미포함) : "<<vocab_size<<'\n';
// std::cout<<index2word(vocab_size-2)<<" : "<<wordFrequency[vocab_size-2]<<" "<<index2word(vocab_size-1)<<" : "<<wordFrequency[vocab_size-1]<<'\n';
// std::cout<<word2index("<s>")<<" "<<word2index("<e>")<<'\n';
// std::cout<<"work : "<<wordFrequency[word2index("work")]<<'\n';
for(int i=0 ; i<vocab_size ; i++)
cout<<vocab[i]<<" ";
cout<<endl;
}
//일단 subsampling of frequent words - 이거는 일단 제외하고 하겠음!!
// center context non-context non-context
template<typename DTYPE> void text8<DTYPE>::MakeSkipGramInputData(){
//subsampling때문에 추가
unsigned long long next_random = 1; // 출력은 %lld임!
float sample = 1e-4;
//여기까지 subsamling때문에 추가
//이게 시간이 오래걸리지 않을까?....
std::cout<<"------------------------------MakeskipgramInputdata---------------------"<<'\n';
srand(time(NULL)); //이 함수는 main에서 한번만 호출하면 됨!!!! 이거 그래서 수정 필요!!!
int offsetIndex = 0;
int index = 0;
//context에 해당하는 index에 접근하기 위한 offset
int contextOffset[m_window-1];
for(int i=0; i<m_window/2; i++){
contextOffset[index++] = i+1;
contextOffset[index++] = -(i+1);
}
int centerIndex = 0;
int nonContextIndex = 0;
for (int i = 0; i < m_numOfInput; i++) {
//min count에 못 미치면 그냥 pass!!!
//wordFrequency[word2index(wordTextData[nonContextIndex]
m_aaInput[i] = new DTYPE[m_dimOfInput];
//center word
m_aaInput[i][0] = (DTYPE)word2index(wordTextData[centerIndex]);
//context word + sos + eos = positive sample
if(centerIndex+contextOffset[offsetIndex] < 0){ // vocab index가 0보다 작으면 안되기 때문.. 그럴경우 <sos>로 저장
m_aaInput[i][1] = (DTYPE)word2index("<s>"); // int를 float로 강제 형변환
} else if(centerIndex+contextOffset[offsetIndex] >= word_num){ // 왜 word_num? 중복 포함하면 안되지않나?
m_aaInput[i][1] = (DTYPE)word2index("<e>"); // 아무튼 vocab index보다 크면 <eos>로 저장
} else{
m_aaInput[i][1] = (DTYPE)word2index(wordTextData[ centerIndex+contextOffset[offsetIndex] ]); // 그냥 맞는 인덱스값 저장
}
//non-context word = negative sample
//일단은 negative sample에만 subsampling 적용하기! -> pytorch는 그렇게함!!
for (int d = 2; d < m_dimOfInput; d++) {
nonContextIndex = rand()%word_num;
//sub sampling 추가해보기!!!
//next_random값 !!!! 중요!!! 이거 dataset에 따라 값을 바꿔줄 필요가 있음!!! data가 작아지면 값이 전체적으로 작아져서 무한loop에 들어감!!!
//이거 근데 로직이 이상한게..... 한번 안되면 계속 안되는거 아닌가....???
// next_random = 1;
// float ran = (sqrt(wordFrequency[word2index(wordTextData[nonContextIndex])] / (sample * word_num)) + 1) * (sample * word_num) / wordFrequency[word2index(wordTextData[nonContextIndex])]; //여기서 ran설정...
// next_random = (unsigned long long)25214903917 + 11;
// //std::cout<<wordFrequency[word2index(wordTextData[nonContextIndex])]<<" "<<ran<<" "<<(next_random & 0xFFFF) / (float)65536<<'\n';
// if (ran < (next_random & 0xFFFF) / (float)65536 ){ //ran은 여기서만 사용....
// d--;
// continue;
// }
//center와 겹치지 않도록!!!
if(nonContextIndex == centerIndex){
d--;
// std::cout<<"center와 겹침!"<<'\n';
continue;
}
//context에 대한 처리 추가!
m_aaInput[i][d] = (DTYPE)word2index(wordTextData[nonContextIndex]);
for(int j=0; j<m_window-1; j++){
if(nonContextIndex==centerIndex+contextOffset[j]){
// std::cout<<"centext와 겹침!"<<'\n';
d--;
}
}
}
// std::cout<<'\n'<<'\n';
offsetIndex++;
if(offsetIndex == m_window-1){
centerIndex++;
offsetIndex = 0;
}
//이제 입력 확인해보기!
// for(int j=0; j<m_dimOfInput; j++)
// std::cout<<index2word(m_aaInput[i][j])<<" ";
// std::cout<<'\n';
}
}
//이 함수 굳이 필요는 없음.... 필요 없을듯??? 일단 수정한 곳에서는 필요없음!!!
//사용안함!!! 일단 호출은 안하도록 한다!
template<typename DTYPE> void text8<DTYPE>::MakeSkipGramLabelData(){
for (int i = 0; i < m_numOfInput; i++) {
m_aaLabel[i] = new DTYPE[1];
//positive sample
m_aaLabel[i][0] = (DTYPE)0; //positive sample은 항상 맨 처음
}
}
//ACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAY
// m_numOfInput = NUMOFWORD / 4;
// 이거 index로 했는지 확인하기!!! 그리고 없는 단어는 pass하도록!!!
template<typename DTYPE> void text8<DTYPE>::MakeAccuracyData(){
int index = 0;
int w0 = 0, w1 = 0, w2 = 0, w3 = 0;
for (int i = 0; i < m_numOfInput; i++) {
m_aaInput[i] = new DTYPE[m_dimOfInput];
m_aaLabel[i] = new DTYPE[m_dimOfLabel];
w0 = word2index(wordTextData[index++]);
w1 = word2index(wordTextData[index++]);
w2 = word2index(wordTextData[index++]);
w3 = word2index(wordTextData[index++]);
//std::cout<<w0<<index2word(w0)<<" "<<w1<<index2word(w1)<<" "<<w2<<index2word(w2)<<" "<<w3<<index2word(w3)<<'\n';
//word2index에 없는 단어는 pass하기!
//-1인 경우 pass하고 data 개수 줄이기!
if(w0 == -1 || w1 == -1 || w2 == -1 || w3 == -1 ){
m_numOfInput--;
//std::cout<<"없는 단어!"<<'\n';
continue;
}
//값 넣기
m_aaInput[i][0] = w0;
m_aaInput[i][1] = w1;
m_aaInput[i][2] = w2;
m_aaLabel[i][0] = w3;
}
std::cout<<"최종 m_numOfInput 개수 : "<<m_numOfInput<<'\n';
}
//ACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAYACCURAY
template<typename DTYPE> int text8<DTYPE>::word2index(string str){
for(int index=0; index<vocab_size; index++){
if(vocab[index]==str){
return index;
}
}
return -1;
}
template<typename DTYPE> string text8<DTYPE>::index2word(int index){
return vocab[index];
}
//이거는 필요한지 모르겠음....
template<typename DTYPE> int text8<DTYPE>::GetTextLength(){
return text_length;
}
template<typename DTYPE> int text8<DTYPE>::GetWordNum(){
return word_num;
}
template<typename DTYPE> string* text8<DTYPE>::GetVocab(){
return vocab;
}
template<typename DTYPE> int text8<DTYPE>::GetVocabSize(){
return vocab_size;
}
template<typename DTYPE> int text8<DTYPE>::GetInputDim(){
return m_dimOfInput;
}
template<typename DTYPE> int text8<DTYPE>::GetLabelDim(){
return m_dimOfLabel;
}
template<typename DTYPE> std::vector<Tensor<DTYPE> *> *text8<DTYPE>::GetData(int idx) {
std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL);
Tensor<DTYPE> *input = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfInput);
Tensor<DTYPE> *label = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfLabel);
for (int i = 0; i < m_dimOfInput; i++) {
//이거는 전체 단어의 개수 안 맞춰주면 이렇게 됨!!!
if(m_aaInput[idx][i]==-1)
std::cout<<'\n'<<"****************************************************************************************음수존재..."<<'\n';
(*input)[i] = m_aaInput[idx][i];
}
//(*label)[ (int)m_aaLabel[idx][0] ] = 1.f;
(*label)[0] = 1.f;
result->push_back(input);
result->push_back(label);
return result;
}
template<typename DTYPE> int text8<DTYPE>::GetLength() {
return m_numOfInput;
}
| 31.270408 | 256 | 0.494589 | ChanhyoLee |
4d44a810d2e1f8fb7c4869d423eb3f937472fe57 | 1,641 | cpp | C++ | Source/modio/Private/BlueprintCallbackProxies/CallbackProxy_GetUserModfiles.cpp | Turupawn/UE4Plugin | f01de1609aedb95f7733924f64bd59a4770bf2d1 | [
"MIT"
] | 3 | 2020-01-15T02:05:12.000Z | 2021-08-30T08:14:29.000Z | Source/modio/Private/BlueprintCallbackProxies/CallbackProxy_GetUserModfiles.cpp | Turupawn/UE4Plugin | f01de1609aedb95f7733924f64bd59a4770bf2d1 | [
"MIT"
] | null | null | null | Source/modio/Private/BlueprintCallbackProxies/CallbackProxy_GetUserModfiles.cpp | Turupawn/UE4Plugin | f01de1609aedb95f7733924f64bd59a4770bf2d1 | [
"MIT"
] | 2 | 2020-06-29T23:40:08.000Z | 2021-03-05T07:47:27.000Z | // Copyright 2019 modio. All Rights Reserved.
// Released under MIT.
#include "BlueprintCallbackProxies/CallbackProxy_GetUserModfiles.h"
#include "ModioUE4Utility.h"
#include "ModioSubsystem.h"
#include "Engine/Engine.h"
UCallbackProxy_GetUserModfiles::UCallbackProxy_GetUserModfiles(const FObjectInitializer &ObjectInitializer)
: Super(ObjectInitializer)
{
}
UCallbackProxy_GetUserModfiles *UCallbackProxy_GetUserModfiles::GetUserModfiles(UObject *WorldContext, int32 Limit, int32 Offset)
{
UCallbackProxy_GetUserModfiles *Proxy = NewObject<UCallbackProxy_GetUserModfiles>();
Proxy->SetFlags(RF_StrongRefOnFrame);
Proxy->Limit = Limit;
Proxy->Offset = Offset;
Proxy->WorldContextObject = WorldContext;
return Proxy;
}
void UCallbackProxy_GetUserModfiles::Activate()
{
UWorld* World = GEngine->GetWorldFromContextObject( WorldContextObject, EGetWorldErrorMode::LogAndReturnNull );
FModioSubsystemPtr Modio = FModioSubsystem::Get( World );
if( Modio.IsValid() )
{
Modio->GetUserModfiles( this->Limit, this->Offset, FModioModfileArrayDelegate::CreateUObject( this, &UCallbackProxy_GetUserModfiles::OnGetUserModfilesDelegate ) );
}
else
{
// @todonow: Make something more pretty than this
FModioResponse Response;
TArray<FModioModfile> Modfiles;
OnFailure.Broadcast( Response, Modfiles );
}
}
void UCallbackProxy_GetUserModfiles::OnGetUserModfilesDelegate(FModioResponse Response, const TArray<FModioModfile> &Modfiles)
{
if (Response.Code >= 200 && Response.Code < 300)
{
OnSuccess.Broadcast(Response, Modfiles);
}
else
{
OnFailure.Broadcast(Response, Modfiles);
}
} | 32.176471 | 167 | 0.776356 | Turupawn |
4d46c66cfac159216b85c05ecc73e0c9a3e756f1 | 1,820 | cpp | C++ | Graph/Adjacency-matrix/Graph.cpp | shoukailiang/PAT | 30b766e52da7b978bb174cefa03c72ab23ce7ee0 | [
"MIT"
] | 1 | 2019-08-16T14:00:29.000Z | 2019-08-16T14:00:29.000Z | Graph/Adjacency-matrix/Graph.cpp | shoukailiang/PAT | 30b766e52da7b978bb174cefa03c72ab23ce7ee0 | [
"MIT"
] | null | null | null | Graph/Adjacency-matrix/Graph.cpp | shoukailiang/PAT | 30b766e52da7b978bb174cefa03c72ab23ce7ee0 | [
"MIT"
] | null | null | null | //
// Created by liang on 2019/10/21.
//
#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 100
typedef int weightType;
typedef int Vertex;
typedef int DataType;
typedef struct GNode *ptrToGNode;
struct GNode{ // 图
int Nv; // 顶点数
int Ne; // 边数
weightType G[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum]; // 存顶点的数据
};
typedef ptrToGNode MGraph;
typedef struct ENode *ptrToENode;
struct ENode{ // 边
Vertex V1,V2; // 有向边<V1,V2>
weightType Weight; // 权重
};
typedef ptrToENode Edge;
// 初始化图
MGraph Create(int VertexNum){
Vertex v,w;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for(v=0;v<VertexNum;v++)
for(w=0;w<VertexNum;w++)
Graph->G[v][w] = 0;
return Graph;
}
// 插入边
MGraph Insert(MGraph Graph,Edge E){
// 插入边 <V1,V2>
Graph->G[E->V1][E->V2] = E->Weight;
// 如果是无向图,还需要插入边 <V2,V1>
Graph->G[E->V2][E->V1] = E->Weight;
}
// 建图
MGraph BuildGraph(){
MGraph Graph;
Edge E;
Vertex V;
int Nv,i;
scanf("%d",&Nv); // 读入顶点数
Graph = Create(Nv);
scanf("%d",&(Graph->Ne)); // 读入边数
if(Graph->Ne != 0){
E = (Edge)malloc(sizeof(struct ENode));
for(i=0;i<Graph->Ne;i++){
scanf("%d %d %d",&E->V1,&E->V2,&E->Weight); // 读入每个边的数据
Insert(Graph,E);
}
}
return Graph;
}
/**
#include<stdio.h>
#include<stdlib.h>
#define MAXN 100
int G[MAXN][MAXN],Nv,Ne;
void BuildGraph(){
int i,j,v1,v2,w;
scanf("%d",&Nv);
// 初始化图
for(i=0;i<Nv;i++)
for(j=0;j<Nv;j++)
G[i][j] = 0;
scanf("%d",&Ne);
// 插入边
for(i=0;i<Ne;i++){
scanf("%d %d %d",&v1,&v2,&w);
G[v1][v2] = w;
G[v2][v1] = w;
}
}
// 遍历图
void print(){
int i,j;
for(i=0;i<Nv;i++){
for(j=0;j<Nv;j++)
printf("%d ",G[i][j]);
printf("\n");
}
}
int main(){
BuildGraph();
print();
return 0;
}
**/ | 17.009346 | 62 | 0.575824 | shoukailiang |
4d4cc791580f546ceb05392ed4c78cacb156015b | 329 | cpp | C++ | monisai_2/problem_6.cpp | Leon-Francis/AlgorithmPractice | bfff066da64ebbb00ecd33d94ebbe5bcc382867c | [
"MIT"
] | 1 | 2020-10-07T12:03:12.000Z | 2020-10-07T12:03:12.000Z | monisai_2/problem_6.cpp | Leon-Francis/AlgorithmPractice | bfff066da64ebbb00ecd33d94ebbe5bcc382867c | [
"MIT"
] | null | null | null | monisai_2/problem_6.cpp | Leon-Francis/AlgorithmPractice | bfff066da64ebbb00ecd33d94ebbe5bcc382867c | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
string str;
cin >> str;
for (int i = 0; i < str.length(); i++)
{
str[i] = str[i] + 3;
if (str[i] > 'z')
{
str[i] = str[i] - 26;
}
}
cout << str;
return 0;
}
| 17.315789 | 42 | 0.443769 | Leon-Francis |
4d4f62afb9cbcc3ed6e602da11ec3e35162ef5db | 24,793 | cp | C++ | Plug-ins/GPG/sources/GPGTest.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Plug-ins/GPG/sources/GPGTest.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Plug-ins/GPG/sources/GPGTest.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// GPGTest.cp
// Test application for GPG plugin testing
#include "CSecurityPluginDLL.h"
#include <iostream.h>
#include <string.h>
#if __dest_os == __mac_os
#include "FullPath.h"
#endif
extern "C"
{
long MulberryPluginEntry(long, void*, long);
typedef long (*MulberryPluginEntryPtr)(long, void*, long);
}
bool Callback(CSecurityPluginDLL::ESecurityPluginCallback type, void* data);
void TestSignData(long refCon);
void TestEncryptData(long refCon);
void TestEncryptSignData(long refCon);
void TestVerifyData(long refCon);
void TestDecryptData(long refCon);
void TestSignFile(long refCon);
void TestEncryptFile(long refCon);
void TestEncryptSignFile(long refCon);
void TestDecryptFile(long refCon);
const char* in_file = "input";
const char* out_file = "output";
#if __dest_os == __mac_os
#define lendl "\n"
#define lendl_len 1
#elif __dest_os == __win32_os
#define lendl "\r\n"
#define lendl_len 2
#elif __dest_os == __linux_os || __dest_os == __mac_os_x
#define lendl "\n"
#define lendl_len 1
#endif
#if __dest_os == __mac_os
static OSErr FindApplicationDirectory(short *theVRefNum, long *theParID);
static OSErr FindApplicationDirectory(short *theVRefNum, long *theParID)
{
OSErr theErr;
ProcessSerialNumber thePSN;
ProcessInfoRec theInfo;
FSSpec theSpec;
thePSN.highLongOfPSN = 0;
thePSN.lowLongOfPSN = kCurrentProcess;
theInfo.processInfoLength = sizeof(theInfo);
theInfo.processName = NULL;
theInfo.processAppSpec = &theSpec;
/* Find the application FSSpec */
theErr = GetProcessInformation(&thePSN, &theInfo);
if (theErr == noErr)
{
/* Return the folder which contains the application */
*theVRefNum = theSpec.vRefNum;
*theParID = theSpec.parID;
}
return theErr;
}
static OSErr CreateBundleFromFSSpec(FSSpec *theSpec, CFBundleRef *theBundle);
static OSErr CreateBundleFromFSSpec(FSSpec *theSpec, CFBundleRef *theBundle)
{
OSErr theErr;
FSRef theRef;
CFURLRef thePluginDirURL;
CFURLRef theBundleURL;
/* Turn the FSSpec pointing to the Bundle into a FSRef */
theErr = FSpMakeFSRef(theSpec, &theRef);
/* Turn the FSRef into a CFURL */
thePluginDirURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault, &theRef);
if (thePluginDirURL == NULL)
return -1;
theBundleURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, thePluginDirURL, CFSTR("GPG.bundle"), false);
CFRelease(thePluginDirURL);
if (theBundleURL != NULL)
{
/* Turn the CFURL into a bundle reference */
*theBundle = CFBundleCreate(kCFAllocatorSystemDefault, theBundleURL);
CFRelease(theBundleURL);
}
return theErr;
}
static OSErr LoadFunction(CFBundleRef* theBundle, MulberryPluginEntryPtr* theFnPtr);
static OSErr LoadFunction(CFBundleRef* theBundle, MulberryPluginEntryPtr* theFnPtr)
{
OSErr theErr;
Boolean isLoaded;
short theVRefNum;
long theParID;
FSSpec theSpec;
/* Start with no bundle */
*theBundle = NULL;
/* This returns the directory which contains the application */
theErr = FindApplicationDirectory(&theVRefNum, &theParID);
/* Create the FSSpec pointing to the Bundle */
if (theErr == noErr)
theErr = FSMakeFSSpec(theVRefNum, theParID, "\p", &theSpec);
/* Create a bundle reference based on a FSSpec */
if (theErr == noErr)
theErr = CreateBundleFromFSSpec(&theSpec, theBundle);
if ((theErr == noErr) && (*theBundle != NULL))
{
CFShow(*theBundle);
isLoaded = CFBundleLoadExecutable(*theBundle);
if (isLoaded)
{
/* Lookup the function in the bundle by name */
*theFnPtr = (MulberryPluginEntryPtr) CFBundleGetFunctionPointerForName(*theBundle, CFSTR("MulberryPluginEntry"));
//*theFnPtr = (MulberryPluginEntryPtr) CFBundleGetFunctionPointerForName(*theBundle, CFSTR("SayHello"));
}
}
return theErr;
}
static OSErr UnloadFunction(CFBundleRef* theBundle, MulberryPluginEntryPtr* theFnPtr);
static OSErr UnloadFunction(CFBundleRef* theBundle, MulberryPluginEntryPtr* theFnPtr)
{
/* Call the function if it was found */
if (*theFnPtr != NULL)
{
/* Dispose of the function pointer to the bundled Mach-O routine */
//DisposePtr((Ptr) *theFnPtr);
}
CFShow(*theBundle);
CFBundleUnloadExecutable(*theBundle);
CFShow(*theBundle);
CFRelease(*theBundle);
return noErr;
}
#endif
static long LoggingCallback(const char* text);
long LoggingCallback(const char* text)
{
const char* p = text;
unsigned long l = 0;
while(*p++) l++;
return 0;
}
#if __dest_os == __mac_os
static MulberryPluginEntryPtr theFnPtr = NULL;
#else
static MulberryPluginEntryPtr theFnPtr = MulberryPluginEntry;
#endif
int main()
{
long code;
long refCon = 0;
cout << "GPGTest: Application Startup" << endl;
cout << "GPGTest: Contsruct and Initialise" << endl;
#if __dest_os == __mac_os
CFBundleRef theBundle;
LoadFunction(&theBundle, &theFnPtr);
#endif
refCon = (*theFnPtr)(CSecurityPluginDLL::ePluginConstruct, NULL, refCon);
long err = (*theFnPtr)(CSecurityPluginDLL::ePluginInitialise, NULL, refCon);
(*theFnPtr)(CPluginDLL::ePluginSetLoggingCallback, (void*) LoggingCallback, refCon);
(*theFnPtr)(CSecurityPluginDLL::eSecuritySetCallback, (void*) Callback, refCon);
//TestSignData(refCon);
//TestEncryptData(refCon);
//TestEncryptSignData(refCon);
//TestSignFile(refCon);
TestEncryptFile(refCon);
//TestEncryptSignFile(refCon);
//TestVerifyData(refCon);
//TestDecryptData(refCon);
cout << "GPGTest: Terminate and Destruct" << endl;
err = (*theFnPtr)(CSecurityPluginDLL::ePluginTerminate, NULL, refCon);
err = (*theFnPtr)(CSecurityPluginDLL::ePluginDestroy, NULL, refCon);
#if __dest_os == __mac_os
UnloadFunction(&theBundle, &theFnPtr);
#endif
cout << "GPGTest: Application Shutdown" << endl;
}
bool Callback(CSecurityPluginDLL::ESecurityPluginCallback type, void* data)
{
switch(type)
{
case CSecurityPluginDLL::eCallbackPassphrase:
{
CSecurityPluginDLL::SCallbackPassphrase* context = reinterpret_cast<CSecurityPluginDLL::SCallbackPassphrase*>(data);
::strcpy(context->passphrase, "how much is that mulberry");
context->chosen = 0;
return true;
}
default:
return false;
}
}
void TestSignData(long refCon)
{
cout << "GPGTest: Sign data" << endl;
CSecurityPluginDLL::SSignData sign;
char* out = NULL;
unsigned long out_len = 0L;
sign.mInputData = "Content-Type: text/plain" lendl lendl "test" lendl;
sign.mKey = "daboo@cyrusoft.com";
sign.mOutputData = &out;
sign.mOutputDataLength = &out_len;
sign.mUseMIME = true;
cout << " DATA: " << sign.mInputData << endl;
cout << " KEY: " << sign.mKey << endl;
long err = (*theFnPtr)(CSecurityPluginDLL::eSecuritySignData, &sign, refCon);
if (!err)
{
cout << " FAILED" << endl;
return;
}
cout << " SIGNED: " << endl;
{
char* p = out;
long len = out_len;
while(len--)
if (*p == '\r')
*p++ = ' ';
else
p++;
}
cout.write(out, out_len);
cout << endl;
cout << "GPGTest: Dispose Data" << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDisposeData, (void*) *sign.mOutputData, refCon);
}
void TestEncryptData(long refCon)
{
cout << "GPGTest: Encrypt data" << endl;
const char* keys[10];
keys[0] = "daboo@cyrusoft.com";
keys[1] = NULL;
CSecurityPluginDLL::SEncryptData encrypt;
char* out = NULL;
unsigned long out_len = 0L;
encrypt.mInputData = "Testing PGP";
encrypt.mKeys = keys;
encrypt.mOutputData = &out;
encrypt.mOutputDataLength = &out_len;
encrypt.mUseMIME = true;
cout << " DATA: " << encrypt.mInputData<< endl;
cout << " KEY: " << *encrypt.mKeys << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityEncryptData, &encrypt, refCon);
cout << " ENCRYPTED: " << endl;
{
char* p = out;
long len = out_len;
while(len--)
if (*p == '\r')
*p++ = ' ';
else
p++;
}
cout.write(out, out_len);
cout << endl;
cout << "GPGTest: Dispose Data" << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDisposeData, (void*) *encrypt.mOutputData, refCon);
}
void TestEncryptSignData(long refCon)
{
cout << "GPGTest: Encrypt-sign data" << endl;
const char* keys[10];
keys[0] = "daboo@cyrusoft.com";
keys[1] = NULL;
CSecurityPluginDLL::SEncryptSignData esign;
char* out = NULL;
unsigned long out_len = 0L;
esign.mInputData = "Testing PGP";
esign.mKeys = keys;
esign.mSignKey = "daboo@cyrusoft.com";
esign.mOutputData = &out;
esign.mOutputDataLength = &out_len;
esign.mUseMIME = true;
cout << " DATA: " << esign.mInputData<< endl;
cout << " KEY: " << *esign.mKeys << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityEncryptSignData, &esign, refCon);
cout << " ENCRYPTED-SIGNED: " << endl;
{
char* p = out;
long len = out_len;
while(len--)
if (*p == '\r')
*p++ = ' ';
else
p++;
}
cout.write(out, out_len);
cout << endl;
cout << "GPGTest: Dispose Data" << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDisposeData, (void*) *esign.mOutputData, refCon);
}
const char* cWholeSignature =
"-----BEGIN PGP SIGNED MESSAGE-----" lendl
"Hash: SHA1" lendl
lendl
"test" lendl
lendl
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: PGP for Personal Privacy 5.5" lendl
lendl
"iQA/AwUBN4ItnCK4BGrbmMvFEQINhQCg51/6qAOfaQygGY1DYzXVFGm8ZK4AoOw/" lendl
"CM3QrMdHsHY0AGQ338JBUROI" lendl
"=wdX/" lendl
"-----END PGP SIGNATURE-----" lendl;
const char* cSeparateSignature =
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: PGP for Personal Privacy 5.5" lendl
lendl
"iQA/AwUBN4ItnCK4BGrbmMvFEQINhQCg51/6qAOfaQygGY1DYzXVFGm8ZK4AoOw/" lendl
"CM3QrMdHsHY0AGQ338JBUROI" lendl
"=wdX/" lendl
"-----END PGP SIGNATURE-----" lendl;
const char* cSeparateData =
"test" lendl;
const char* cOpenWhole1 =
"From daboo@cyrusoft.com Tue Jul 06 12:36:07 1999 -0400" lendl
"Date: Tue, 06 Jul 1999 12:36:07 -0400" lendl
"From: Cyrus Daboo <daboo@cyrusoft.com>" lendl
"To: Cyrus Daboo <daboo@cyrusoft.com>" lendl
"Subject: test" lendl
"Message-ID: <497881.3140253366@sardis.cyrusoft.com>" lendl
"Originator-Info: login-id=daboo; server=imap.cyrusoft.com:431" lendl
"X-Mailer: Mulberry (MacOS) [2.0.0a3, s/n S1-000001]" lendl
"MIME-Version: 1.0" lendl
"Content-Type: Multipart/signed; micalg=pgp-sha1;" lendl
" protocol=\"application/pgp-signature\";" lendl
" Boundary=\"==========00503649==========\"" lendl
lendl
"--==========00503649==========" lendl
"Content-Type: text/plain; charset=us-ascii" lendl
"Content-Transfer-Encoding: 7bit" lendl
"Content-Disposition: inline" lendl
lendl
"This test " lendl
" " lendl
"--==========00503649==========" lendl
"Content-Type: application/pgp-signature" lendl
"Content-Transfer-Encoding: 7bit" lendl
lendl
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: Mulberry PGP Plugin v1.4b2" lendl
"Comment: processed by Mulberry PGP Plugin" lendl
lendl
"iQA/AwUBN4IwdyK4BGrbmMvFEQJooQCfTCX+nxc2IqhWp/uPhRo7G7i0jhoAnAmT" lendl
"vcsUkQVu1SZEoulB7c8h9f/R" lendl
"=dEzG" lendl
"-----END PGP SIGNATURE-----" lendl
lendl
"--==========00503649==========--" lendl;
const char* cOpenSignature1 =
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: Mulberry PGP Plugin v1.4b2" lendl
"Comment: processed by Mulberry PGP Plugin" lendl
lendl
"iQA/AwUBN4IwdyK4BGrbmMvFEQJooQCfTCX+nxc2IqhWp/uPhRo7G7i0jhoAnAmT" lendl
"vcsUkQVu1SZEoulB7c8h9f/R" lendl
"=dEzG" lendl
"-----END PGP SIGNATURE-----" lendl;
const char* cOpenData1 =
"Content-Type: text/plain; charset=us-ascii" lendl
"Content-Transfer-Encoding: 7bit" lendl
"Content-Disposition: inline" lendl
lendl
"This test" lendl;
const char* cOpenWhole2 =
"From daboo@cyrusoft.com Tue Jul 06 12:36:15 1999 -0400" lendl
"Date: Tue, 06 Jul 1999 12:36:15 -0400" lendl
"From: Cyrus Daboo <daboo@cyrusoft.com>" lendl
"To: Cyrus Daboo <daboo@cyrusoft.com>" lendl
"Subject: test" lendl
"Message-ID: <498381.3140253375@sardis.cyrusoft.com>" lendl
"Originator-Info: login-id=daboo; server=imap.cyrusoft.com:431" lendl
"X-Mailer: Mulberry (MacOS) [2.0.0a3, s/n S1-000001]" lendl
"MIME-Version: 1.0" lendl
"Content-Type: multipart/signed; micalg=pgp-sha1;" lendl
" protocol=\"application/pgp-signature\";" lendl
" boundary=\"==========00508501==========\"" lendl
lendl
"--==========00508501==========" lendl
"Content-Type: text/plain; charset=us-ascii" lendl
"Content-Transfer-Encoding: 7bit" lendl
"Content-Disposition: inline" lendl
lendl
"This test " lendl
lendl
"--==========00508501==========" lendl
"Content-Type: application/pgp-signature" lendl
"Content-Transfer-Encoding: 7bit" lendl
lendl
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: Mulberry PGP Plugin v1.4b2" lendl
"Comment: processed by Mulberry PGP Plugin" lendl
lendl
"iQA/AwUBN4IwfyK4BGrbmMvFEQIboACg5yZtGb7LOkgwS8+l/tgNkVq/28IAnR/g" lendl
"0a4z5sRexybzwCFOhDvd94lr" lendl
"=+JO5" lendl
"-----END PGP SIGNATURE-----" lendl
lendl
"--==========00508501==========--" lendl;
const char* cOpenSignature2 =
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: Mulberry PGP Plugin v1.4b2" lendl
"Comment: processed by Mulberry PGP Plugin" lendl
lendl
"iQA/AwUBN4IwfyK4BGrbmMvFEQIboACg5yZtGb7LOkgwS8+l/tgNkVq/28IAnR/g" lendl
"0a4z5sRexybzwCFOhDvd94lr" lendl
"=+JO5" lendl
"-----END PGP SIGNATURE-----" lendl;
const char* cOpenData2 =
"Content-Type: text/plain; charset=us-ascii" lendl
"Content-Transfer-Encoding: 7bit" lendl
"Content-Disposition: inline" lendl
lendl
"This test " lendl;
const char* cOpenWhole3 =
"From steve@execmail.com Tue Mar 02 22:58:55 1999 -0500" lendl
"Return-Path: <steve@execmail.com>" lendl
"Received: from demo.esys.ca (demo.esys.ca [207.167.22.130])" lendl
" by darius.cyrusoft.com (8.8.5/8.8.5) with ESMTP id WAA08886" lendl
" for <daboo@cyrusoft.com>; Tue, 2 Mar 1999 22:58:53 -0500 (EST)" lendl
"Received: from galileo.esys.ca (dhcp198-58.esys.ca [198.161.92.58])" lendl
" by demo.esys.ca (2.0.4/SMS 2.0.4-beta-5) with ESMTP id MAA11654" lendl
" for <daboo@cyrusoft.com>; Wed, 3 Mar 1999 12:08:20 -0700" lendl
"From: Steve Hole <steve@execmail.com>" lendl
"Date: Tue, 2 Mar 1999 21:01:23 -0700" lendl
"To: Cyrus Daboo <daboo@cyrusoft.com>" lendl
"Subject: Signed only message" lendl
"Message-ID: <EXECMAIL.990302210123.P@galileo.execmail.com>" lendl
"Priority: NORMAL" lendl
"X-Mailer: Execmail for Win32 Version 5.0 pc5 Build (37)" lendl
"MIME-Version: 1.0" lendl
"Content-Type: Multipart/signed; boundary=\"Part9903022101.Q\"; protocol=\"application/pgp-signature\"; micalg=\"pgp-sha1\"" lendl
lendl
lendl
"--Part9903022101.Q" lendl
"Content-Type: Text/Plain; charset=\"us-ascii\"; name=\"ipm.txt\"" lendl
"Content-Disposition: inline; filename=\"ipm.txt\"" lendl
lendl
"Here is a singed only message." lendl
lendl
"--- " lendl
"Steve Hole " lendl
"Execmail Inc." lendl
"Mailto:Steve.Hole@execmail.com " lendl
"Phone: 780-424-4922" lendl
lendl
lendl
"--Part9903022101.Q" lendl
"Content-Type: Application/pgp-signature" lendl
lendl
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: PGPsdk version 1.5.2 (C) 1997-1998 Network Associates, Inc. and its affiliated companies." lendl
lendl
"iQA/AwUBNty0GNi5Jj9Fn5KMEQI8XACgnzgWI71xJRCYDj0UkLHjgGTUuHcAnAmj" lendl
"rcRM6c9uFQmxTobe6rHUN8nE" lendl
"=9fS1" lendl
"-----END PGP SIGNATURE-----" lendl
lendl
"--Part9903022101.Q--" lendl;
const char* cOpenSignature3 =
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: PGPsdk version 1.5.2 (C) 1997-1998 Network Associates, Inc. and its affiliated companies." lendl
lendl
"iQA/AwUBNty0GNi5Jj9Fn5KMEQI8XACgnzgWI71xJRCYDj0UkLHjgGTUuHcAnAmj" lendl
"rcRM6c9uFQmxTobe6rHUN8nE" lendl
"=9fS1" lendl
"-----END PGP SIGNATURE-----" lendl;
const char* cOpenData3 =
"Content-Type: Text/Plain; charset=\"us-ascii\"; name=\"ipm.txt\"" lendl
"Content-Disposition: inline; filename=\"ipm.txt\"" lendl
lendl
"Here is a singed only message." lendl
lendl
"--- " lendl
"Steve Hole " lendl
"Execmail Inc." lendl
"Mailto:Steve.Hole@execmail.com " lendl
"Phone: 780-424-4922" lendl
lendl;
const char* cOpenData4 = "Content-Type: text/plain; charset=us-ascii\rContent-Transfer-Encoding: 7bit\rContent-Disposition: inline\r\rThis test\r";
const char* cOpenSignature4 = "-----BEGIN PGP SIGNATURE-----\rVersion: Mulberry PGP Plugin v1.4b2\rComment: processed by Mulberry PGP Plugin\r\riQA/AwUBN4IwdyK4BGrbmMvFEQJooQCfTCX+nxc2IqhWp/uPhRo7G7i0jhoAnAmT\rvcsUkQVu1SZEoulB7c8h9f/R\r=dEzG\r-----END PGP SIGNATURE-----\r";
const char* cOpenData5 =
"Content-Type: multipart/mixed; boundary=\"==========01106357==========\"" lendl
lendl
"--==========01106357==========" lendl
"Content-Type: text/plain; charset=us-ascii" lendl
"Content-Transfer-Encoding: 7bit" lendl
"Content-Disposition: inline" lendl
lendl
lendl
lendl
"--" lendl
"Cyrus" lendl
"--==========01106357==========" lendl
"Content-Type: application/octet-stream; name=Unnamed part #1_2" lendl
"Content-Transfer-Encoding: base64" lendl
"Content-Disposition: attachment; filename=Unnamed part #1_2; size=334" lendl
lendl
"LS0tLS1CRUdJTiBQR1AgUFVCTElDIEtFWSBCTE9DSy0tLS0tDVZlcnNpb246IDIuNi4yDQ1tUUNO" lendl
"QXkvR1N1MEFBQUVFQU1QQUlTZkY4VHBtdW9WcGdsN0lEUmh5L3RSN3BsbVJCeFhxTzVjR21RbVhx" lendl
"RlhmDWF6eC8zemo5YXdiNDVWdTdQMWNHQjVWQzJRaWNCMUhBSEdKWGdQL3BQYWlaYTVNaW94a1FC" lendl
"ZnZlelRpNDRyc0UNS3Bnc1piVUR4R1FZWjJvVnMzYkV0RHZUa05idzlvMkJoU0xobUh6RWZxb0Rm" lendl
"aGNDZzVFbGtNa01lempOQUFVUg10QjVVYUc5dFlYTWdWMkZuYm1WeUlEeG9iMjUxY3l0QVkyMTFM" lendl
"bVZrZFQ0PQ09cFdyQQ0tLS0tLUVORCBQR1AgUFVCTElDIEtFWSBCTE9DSy0tLS0tDQ==" lendl
lendl
"--==========01106357==========--" lendl;
const char* cOpenSignature5 =
"Content-Type: application/pgp-signature; name=\"temp00000009.c\"" lendl
"Content-Transfer-Encoding: 7bit" lendl
"Content-Disposition: attachment; filename=\"temp00000009.c\"; size=233" lendl
lendl
"-----BEGIN PGP SIGNATURE-----" lendl
"Version: Mulberry PGP Plugin v1.4b2" lendl
"Comment: processed by Mulberry PGP Plugin" lendl
lendl
"iQA/AwUBN4JXuyK4BGrbmMvFEQKu7wCfR6QROxKTbr6zO/sAl8NKof9C55wAoLs6" lendl
"xcP6nZWSyZNn6hVc5pWVeu5T" lendl
"=OVtJ" lendl
"-----END PGP SIGNATURE-----" lendl;
const char* cEncrypted =
"-----BEGIN PGP MESSAGE-----" lendl
"Version: PGP for Personal Privacy 5.5" lendl
lendl
"qANQR1DBwU4DK66LjGUXow4QB/4lbeEnioNpMj2gVkzC+uej3IZ3TVMEpSIJfy7I" lendl
"16jZhKYDYP8nLFYnMpfB0C7HRY/iNpiWRdX+++bTvwXDEWL1rt4/+cdOjxZgQnAT" lendl
"B/TXsNgTmP2JhsYf9137AjlPXzz3ZKADyI6wwvI2a9x+6dNS3kspfeKaPvA5/lWF" lendl
"hmi5t0Eo83g+7NAIjDG09mC8H7oKW1O7j9LA9CRum4glkrtej9YuZzYSIFPIJX/L" lendl
"7IG5ccHkcF4hc0EOSLEDN4GLl8wbthWb6qgvj8dCg4ygh/Am6FxIkLvGlGbKjH7Q" lendl
"bE3tqXXC3ej0o3GH/wa6Mw7pjCKuTkFNDNbD+C4L2UItK2WUB/40Q8s5X06h4IZI" lendl
"quDirvsUaBdAmPgcYCYDG66fSJI/3C7ezEfarUHRroGxMUOd3Jg1A/yYjSHLq1Kj" lendl
"AzU5dnOI3TjFCGw5JOo0nrzFfY3hxh8gGRq+hieIITk9/SIRJvs8F2cKPS4Tg4mV" lendl
"EryoOvk3jA2z2KQCa7ipZGjbZawH5UK7yEWPc8pPzIAOjJw/Am6SKZzGlNamJRQv" lendl
"DSCP6Vm4SXkQudDJmNBZLI9bSy+tLL66buVG0KN+tdLTCL41UuBV9tYlI27I8drc" lendl
"Gj3/i2YAeT+w68GFHjWKY1OTaXRxKoC1J/3aXH8fCLL+DN2gOE53086ruCYbtTds" lendl
"oVM63TQCySNfMnnLSi4kgorUh6RQH4Wgf6H30XLjFkwSRXEDhbHKpbM4nw==" lendl
"=k3Ig" lendl
"-----END PGP MESSAGE-----" lendl;
void TestVerifyData(long refCon)
{
cout << "GPGTest: Verify data" << endl;
CSecurityPluginDLL::SDecryptVerifyData verify;
char* out = NULL;
unsigned long out_len = 0L;
bool result = false;
bool did_sig = false;
verify.mInputData = cOpenData5;
verify.mInputSignature = cOpenSignature5;
verify.mOutputData = &out;
verify.mOutputDataLength = &out_len;
verify.mSuccess = &result;
verify.mDidSig = &did_sig;
cout << " DATA:" << endl << verify.mInputData << endl;
if (verify.mInputSignature)
cout << " SIGNATURE:" << endl << verify.mInputSignature << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDecryptVerifyData, &verify, refCon);
if (result)
{
cout << " VERIFIED:" << endl;
{
char* p = out;
long len = out_len;
while(len--)
if (*p == '\r')
*p++ = '\n';
else
p++;
}
cout.write(out, out_len);
cout << endl;
}
else
cout << " VERIFY FAILED" << endl;
cout << "GPGTest: Dispose Data" << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDisposeData, (void*) *verify.mOutputData, refCon);
}
void TestDecryptData(long refCon)
{
cout << "GPGTest: Decrypt data" << endl;
CSecurityPluginDLL::SDecryptVerifyData decrypt;
char* out = NULL;
unsigned long out_len = 0L;
bool result = false;
bool did_sig = false;
decrypt.mInputData = cEncrypted;
decrypt.mInputSignature = NULL;
decrypt.mOutputData = &out;
decrypt.mOutputDataLength = &out_len;
decrypt.mSuccess = &result;
decrypt.mDidSig = &did_sig;
cout << " DATA:" << endl << decrypt.mInputData << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDecryptVerifyData, &decrypt, refCon);
if (result)
{
cout << " DECRYPTED:" << endl;
{
char* p = out;
long len = out_len;
while(len--)
if (*p == '\r')
*p++ = '\n';
else
p++;
}
cout.write(out, out_len);
cout << endl;
}
else
cout << " DECRYPT FAILED" << endl;
cout << "GPGTest: Dispose Data" << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityDisposeData, (void*) *decrypt.mOutputData, refCon);
}
void TestSignFile(long refCon)
{
const char* in = in_file;
const char* out = out_file;
#if __dest_os == __mac_os
FSSpec _in_spec;
FSSpec* in_spec = &_in_spec;
OSErr err = ::FSpLocationFromFullPath(::strlen(in_file), in_file, in_spec);
FSSpec _out_spec;
FSSpec* out_spec = &_out_spec;
err = ::FSpLocationFromFullPath(::strlen(out_file), out_file, out_spec);
#else
fspec in_spec = in;
fspec out_spec = out;
#endif
cout << "GPGTest: Sign file" << endl;
CSecurityPluginDLL::SSignFile sign;
sign.mInputFile = in_spec;
sign.mKey = "daboo@cyrusoft.com";
sign.mOutputFile = out_spec;
sign.mUseMIME = true;
cout << " FILE: " << in_file << endl;
cout << " KEY: " << sign.mKey << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecuritySignFile, &sign, refCon);
cout << " SIGNED: " << out_file << endl;
}
void TestEncryptFile(long refCon)
{
const char* in = in_file;
const char* out = out_file;
#if __dest_os == __mac_os
FSSpec _in_spec;
FSSpec* in_spec = &_in_spec;
OSErr err = ::FSpLocationFromFullPath(::strlen(in_file), in_file, in_spec);
FSSpec _out_spec;
FSSpec* out_spec = &_out_spec;
err = ::FSpLocationFromFullPath(::strlen(out_file), out_file, out_spec);
#else
fspec in_spec = in;
fspec out_spec = out;
#endif
cout << "GPGTest: Encrypt file" << endl;
const char* keys[10];
keys[0] = "daboo@cyrusoft.com";
keys[1] = NULL;
CSecurityPluginDLL::SEncryptFile encrypt;
encrypt.mInputFile = in_spec;
encrypt.mKeys = keys;
encrypt.mOutputFile = out_spec;
encrypt.mUseMIME = true;
cout << " DATA: " << in_file << endl;
cout << " KEY: " << *encrypt.mKeys << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityEncryptFile, &encrypt, refCon);
cout << " ENCRYPTED: " << out_file << endl;
}
void TestEncryptSignFile(long refCon)
{
const char* in = in_file;
const char* out = out_file;
#if __dest_os == __mac_os
FSSpec _in_spec;
FSSpec* in_spec = &_in_spec;
OSErr err = ::FSpLocationFromFullPath(::strlen(in_file), in_file, in_spec);
FSSpec _out_spec;
FSSpec* out_spec = &_out_spec;
err = ::FSpLocationFromFullPath(::strlen(out_file), out_file, out_spec);
#else
fspec in_spec = in;
fspec out_spec = out;
#endif
cout << "GPGTest: Encrypt-sign file" << endl;
const char* keys[10];
keys[0] = "daboo@cyrusoft.com";
keys[1] = NULL;
CSecurityPluginDLL::SEncryptSignFile esign;
esign.mInputFile = in_spec;
esign.mKeys = keys;
esign.mSignKey = "daboo@cyrusoft.com";
esign.mOutputFile = out_spec;
esign.mUseMIME = true;
cout << " DATA: " << in_file << endl;
cout << " KEY: " << *esign.mKeys << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecurityEncryptSignFile, &esign, refCon);
cout << " ENCRYPTED-SIGNED: " << out_file << endl;
}
void TestDecryptFile(long refCon)
{
#if 0
#if __dest_os == __mac_os
FSSpec in;
FSSpec out;
PrepareFiles(&in, &out);
cout << "GPGTest: Decrypt file" << endl;
CSecurityPluginDLL::SSignFile sign;
sign.mInputFile = ∈
sign.mKey = "daboo@cyrusoft.com";
sign.mOutputFile = &out;
sign.mUseMIME = true;
cout << " FILE: " << in_file << endl;
cout << " KEY: " << sign.mKey << endl;
(*theFnPtr)(CSecurityPluginDLL::eSecuritySignFile, &sign, refCon);
cout << " SIGNED: " << out_file << endl;
#endif
#endif
}
| 29.340828 | 274 | 0.713306 | mulberry-mail |
4d5e9ccaceebba1bf9eacc85f946fa87df8c5f66 | 1,130 | cpp | C++ | projects/realtimeCamera/realtimeCamera.cpp | lucasbrsa/OpenCV3.2 | b6db40bd43dce7847dce1a808fd29bb1b140dea3 | [
"MIT"
] | null | null | null | projects/realtimeCamera/realtimeCamera.cpp | lucasbrsa/OpenCV3.2 | b6db40bd43dce7847dce1a808fd29bb1b140dea3 | [
"MIT"
] | null | null | null | projects/realtimeCamera/realtimeCamera.cpp | lucasbrsa/OpenCV3.2 | b6db40bd43dce7847dce1a808fd29bb1b140dea3 | [
"MIT"
] | null | null | null | /*
* Displaying realtime footage with first available camera
*
* 19.04.17 | Lucas Barbosa | Open source software
*/
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
#define ESC_ASCII 27
#define DEFAULT_CAMERA 0
// choose default camera
cv::VideoCapture cam_cap(DEFAULT_CAMERA);
std::string windowName = "Camera Primary Test";
char check_for_esc_key = 0;
int main (void) {
if (!cam_cap.isOpened()) {
std::cout << "No camera input." << std::endl;
return -1;
}
cv::Mat img_edges;
namedWindow(windowName, cv::WINDOW_AUTOSIZE);
while (check_for_esc_key != ESC_ASCII)
{
cv::Mat img_frame;
cv::Mat outputCannyEdges;
cam_cap >> img_frame; // get a new frame from camera
if (img_frame.empty()) {
std::cout << "Current frame is empty." << std::endl;
break;
}
cv::Canny(img_frame, outputCannyEdges, 225, (225/3));
cv::imshow( windowName, outputCannyEdges);
// wait for esc key to be pressed
check_for_esc_key = cv::waitKey(1);
}
return 0;
}
| 20.178571 | 59 | 0.661947 | lucasbrsa |
4d605d9f87e382354cffe5fcc062b36a0e931116 | 8,708 | hpp | C++ | include/VROSC/AdjustableMeshTransformUVEffect.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/AdjustableMeshTransformUVEffect.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/AdjustableMeshTransformUVEffect.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.AdjustableMeshEffect
#include "VROSC/AdjustableMeshEffect.hpp"
// Including type: UnityEngine.Vector2
#include "UnityEngine/Vector2.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: AdjustableMeshTransformUVEffect
class AdjustableMeshTransformUVEffect;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::AdjustableMeshTransformUVEffect);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::AdjustableMeshTransformUVEffect*, "VROSC", "AdjustableMeshTransformUVEffect");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x40
#pragma pack(push, 1)
// Autogenerated type: VROSC.AdjustableMeshTransformUVEffect
// [TokenAttribute] Offset: FFFFFFFF
class AdjustableMeshTransformUVEffect : public ::VROSC::AdjustableMeshEffect {
public:
// Nested type: ::VROSC::AdjustableMeshTransformUVEffect::Channel
struct Channel;
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel
// [TokenAttribute] Offset: FFFFFFFF
struct Channel/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: Channel
constexpr Channel(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv1
static constexpr const int Uv1 = 0;
// Get static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv1
static ::VROSC::AdjustableMeshTransformUVEffect::Channel _get_Uv1();
// Set static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv1
static void _set_Uv1(::VROSC::AdjustableMeshTransformUVEffect::Channel value);
// static field const value: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv2
static constexpr const int Uv2 = 1;
// Get static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv2
static ::VROSC::AdjustableMeshTransformUVEffect::Channel _get_Uv2();
// Set static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv2
static void _set_Uv2(::VROSC::AdjustableMeshTransformUVEffect::Channel value);
// static field const value: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv3
static constexpr const int Uv3 = 2;
// Get static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv3
static ::VROSC::AdjustableMeshTransformUVEffect::Channel _get_Uv3();
// Set static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv3
static void _set_Uv3(::VROSC::AdjustableMeshTransformUVEffect::Channel value);
// static field const value: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv4
static constexpr const int Uv4 = 3;
// Get static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv4
static ::VROSC::AdjustableMeshTransformUVEffect::Channel _get_Uv4();
// Set static field: static public VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel Uv4
static void _set_Uv4(::VROSC::AdjustableMeshTransformUVEffect::Channel value);
// Get instance field reference: public System.Int32 value__
[[deprecated("Use field access instead!")]] int& dyn_value__();
}; // VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel
#pragma pack(pop)
static check_size<sizeof(AdjustableMeshTransformUVEffect::Channel), 0 + sizeof(int)> __VROSC_AdjustableMeshTransformUVEffect_ChannelSizeCheck;
static_assert(sizeof(AdjustableMeshTransformUVEffect::Channel) == 0x4);
public:
// private UnityEngine.Vector2 _offset
// Size: 0x8
// Offset: 0x20
::UnityEngine::Vector2 offset;
// Field size check
static_assert(sizeof(::UnityEngine::Vector2) == 0x8);
// private VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel _channel
// Size: 0x4
// Offset: 0x28
::VROSC::AdjustableMeshTransformUVEffect::Channel channel;
// Field size check
static_assert(sizeof(::VROSC::AdjustableMeshTransformUVEffect::Channel) == 0x4);
// Padding between fields: channel and: originalUv
char __padding1[0x4] = {};
// private UnityEngine.Vector2[] _originalUv
// Size: 0x8
// Offset: 0x30
::ArrayW<::UnityEngine::Vector2> originalUv;
// Field size check
static_assert(sizeof(::ArrayW<::UnityEngine::Vector2>) == 0x8);
// private UnityEngine.Vector2[] _uv
// Size: 0x8
// Offset: 0x38
::ArrayW<::UnityEngine::Vector2> uv;
// Field size check
static_assert(sizeof(::ArrayW<::UnityEngine::Vector2>) == 0x8);
public:
// Get instance field reference: private UnityEngine.Vector2 _offset
[[deprecated("Use field access instead!")]] ::UnityEngine::Vector2& dyn__offset();
// Get instance field reference: private VROSC.AdjustableMeshTransformUVEffect/VROSC.Channel _channel
[[deprecated("Use field access instead!")]] ::VROSC::AdjustableMeshTransformUVEffect::Channel& dyn__channel();
// Get instance field reference: private UnityEngine.Vector2[] _originalUv
[[deprecated("Use field access instead!")]] ::ArrayW<::UnityEngine::Vector2>& dyn__originalUv();
// Get instance field reference: private UnityEngine.Vector2[] _uv
[[deprecated("Use field access instead!")]] ::ArrayW<::UnityEngine::Vector2>& dyn__uv();
// public System.Void SetOffset(UnityEngine.Vector2 offset)
// Offset: 0x968A88
void SetOffset(::UnityEngine::Vector2 offset);
// public System.Void .ctor()
// Offset: 0x968A90
// Implemented from: VROSC.AdjustableMeshEffect
// Base method: System.Void AdjustableMeshEffect::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AdjustableMeshTransformUVEffect* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::AdjustableMeshTransformUVEffect::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AdjustableMeshTransformUVEffect*, creationType>()));
}
}; // VROSC.AdjustableMeshTransformUVEffect
#pragma pack(pop)
static check_size<sizeof(AdjustableMeshTransformUVEffect), 56 + sizeof(::ArrayW<::UnityEngine::Vector2>)> __VROSC_AdjustableMeshTransformUVEffectSizeCheck;
static_assert(sizeof(AdjustableMeshTransformUVEffect) == 0x40);
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::VROSC::AdjustableMeshTransformUVEffect::Channel, "VROSC", "AdjustableMeshTransformUVEffect/Channel");
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::AdjustableMeshTransformUVEffect::SetOffset
// Il2CppName: SetOffset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::AdjustableMeshTransformUVEffect::*)(::UnityEngine::Vector2)>(&VROSC::AdjustableMeshTransformUVEffect::SetOffset)> {
static const MethodInfo* get() {
static auto* offset = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::AdjustableMeshTransformUVEffect*), "SetOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{offset});
}
};
// Writing MetadataGetter for method: VROSC::AdjustableMeshTransformUVEffect::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 54.086957 | 197 | 0.73932 | v0idp |
4d66241c4dea2ada15d366790b78d5106449fb72 | 320 | cpp | C++ | interview_questions/pointers_trap.cpp | ppinko/cpp_knowledge_library | 7a57acde533c1b4a3d74b12cb05b33ef6fadb957 | [
"Apache-2.0"
] | null | null | null | interview_questions/pointers_trap.cpp | ppinko/cpp_knowledge_library | 7a57acde533c1b4a3d74b12cb05b33ef6fadb957 | [
"Apache-2.0"
] | null | null | null | interview_questions/pointers_trap.cpp | ppinko/cpp_knowledge_library | 7a57acde533c1b4a3d74b12cb05b33ef6fadb957 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
int main(){
int *p = nullptr;
/* It's possible to get address of nullptr */
std::cout << p << std::endl; // out: 0
/* Dereferencing a null pointer cause a segmentation error. */
// std::cout << *p << std::endl; // segmentation error
delete p;
return 0;
} | 20 | 66 | 0.55625 | ppinko |
4d669095d83ca556a0a2a6ec29464f021ea944f9 | 1,441 | cpp | C++ | test/lib/Shell.cpp | topilski/libmemcached | 7a10166fbc4e718a3392ff744eb5bc499defd952 | [
"BSD-3-Clause"
] | 18 | 2021-06-23T15:20:25.000Z | 2022-03-25T22:51:09.000Z | test/lib/Shell.cpp | topilski/libmemcached | 7a10166fbc4e718a3392ff744eb5bc499defd952 | [
"BSD-3-Clause"
] | 108 | 2020-01-20T09:25:47.000Z | 2021-05-18T06:45:30.000Z | test/lib/Shell.cpp | topilski/libmemcached | 7a10166fbc4e718a3392ff744eb5bc499defd952 | [
"BSD-3-Clause"
] | 4 | 2021-06-25T07:49:31.000Z | 2022-02-07T21:30:45.000Z | #include "Shell.hpp"
#include <cstdlib>
bool Shell::run(const string &command_, string &output) {
auto command = prepareCommand(command_);
auto *file = popen(command.c_str(), "r");
if (!file) {
perror("Shell::run popen()");
return false;
}
do {
char data[1U<<12U];
auto read = fread(data, 1, sizeof(data), file);
if (read) {
output.append(data, read);
}
if (ferror(file)) {
cerr << "Shell::run read(): " << strerror(ferror(file));
break;
}
} while (!feof(file));
auto error = ferror(file);
auto status = pclose(file);
return !error && !status;
}
bool Shell::run(const string &command) {
auto error = system(prepareCommand(command).c_str());
if (error == -1) {
perror("Shell::run system()");
return false;
}
return !error;
}
Shell::Shell(bool redirect_stderr)
: redirect{redirect_stderr}
{
if (!system(nullptr)) {
throw runtime_error("no shell available");
}
}
Shell::Shell(string prefix_, bool redirect_stderr)
: prefix{move(prefix_)}
, redirect{redirect_stderr}
{
if (!system(nullptr)) {
throw runtime_error("no shell available");
}
}
string Shell::prepareCommand(const string &command_) {
string command;
if (prefix.length()) {
command.append(prefix);
command.append("/");
}
command.append(command_);
if (redirect) {
command.append(" 2>&1");
}
INFO("Prepared command: " << command);
return command;
}
| 20.295775 | 62 | 0.62526 | topilski |
4d672d36190cf30b0fb826cb3665e9672c6fca2b | 13,238 | cpp | C++ | src/test/cpp/test3.cpp | chetmurthy/thrift-nicejson | 3ce7a84af55591be4388f93c095032d739ee3917 | [
"Apache-2.0"
] | 8 | 2017-11-14T13:22:09.000Z | 2020-07-30T02:33:18.000Z | src/test/cpp/test3.cpp | chetmurthy/thrift-nicejson | 3ce7a84af55591be4388f93c095032d739ee3917 | [
"Apache-2.0"
] | null | null | null | src/test/cpp/test3.cpp | chetmurthy/thrift-nicejson | 3ce7a84af55591be4388f93c095032d739ee3917 | [
"Apache-2.0"
] | 3 | 2017-11-18T10:53:10.000Z | 2018-01-16T20:11:28.000Z | #include <exception>
#include <fstream>
#include <iostream>
#include <iostream>
#include <streambuf>
#include <string>
#include <tuple>
#include "gtest/gtest.h"
#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#include <thrift/concurrency/Monitor.h>
#include <thrift/protocol/TDebugProtocol.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/transport/TTransport.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/THttpServer.h>
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TFileTransport.h>
#include "thrift/transport/TFDTransport.h"
#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TSocket.h>
#include <thrift/server/TThreadedServer.h>
#include "gen-cpp/test_types.h"
#include "gen-cpp-typelib/test_typelib.h"
#include "gen-cpp/S2.h"
#include "TNiceJSONProtocol.h"
#include "NiceJSON.h"
using boost::shared_ptr;
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::pair;
using std::map;
using std::list;
using std::set;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::thrift::server;
using namespace apache::thrift::nicejson;
const std::string kTestTypelib = "thrift_test.test" ;
bool thrift_test::Bar::operator<(thrift_test::Bar const& that) const {
if (this->a != that.a) return this->a < that.a ;
if (this->b != that.b) return this->b < that.b ;
return false ;
}
class myexception: public std::exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
};
class S2Handler : public thrift_test::S2If {
public:
S2Handler() {}
void ping() override { cerr << "ping()" << endl; }
int32_t foo(const int32_t n, const thrift_test::Bar& w) override {
cerr << "foo(" << n << ", ...)" << endl;
switch (n) {
case 0: {
thrift_test::InvalidOperation e ;
e.whatOp = 84 ;
e.why = "argle" ;
throw e ;
}
case 1: {
thrift_test::InvalidOperation2 e ;
e.whatOp = 42 ;
e.why = "gurgle" ;
throw e ;
}
case 2: {
throw myexception() ;
}
default:
return n ;
}
}
void goo(thrift_test::Bar& bar) override {
}
void hoo() {
cerr << "hoo()" << std::endl ;
}
};
class S2CloneFactory : virtual public thrift_test::S2IfFactory {
public:
virtual ~S2CloneFactory() {}
virtual thrift_test::S2If* getHandler(const ::apache::thrift::TConnectionInfo& connInfo)
{
boost::shared_ptr<TSocket> sock = boost::dynamic_pointer_cast<TSocket>(connInfo.transport);
cerr << "Incoming connection\n";
cerr << "\tSocketInfo: " << sock->getSocketInfo() << "\n";
cerr << "\tPeerHost: " << sock->getPeerHost() << "\n";
cerr << "\tPeerAddress: " << sock->getPeerAddress() << "\n";
cerr << "\tPeerPort: " << sock->getPeerPort() << "\n";
return new S2Handler;
}
virtual void releaseHandler( thrift_test::S2If* handler) {
delete handler;
}
};
class RPC0ThreadClass {
public:
RPC0ThreadClass(TThreadedServer& server) : server_(server) { } // Constructor
~RPC0ThreadClass() { } // Destructor
void Run() {
server_.serve() ;
}
TThreadedServer& server_ ;
} ;
using apache::thrift::concurrency::Monitor;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::Synchronized;
// copied from Thrift source !!
class TServerReadyEventHandler : public TServerEventHandler, public Monitor {
public:
TServerReadyEventHandler() : isListening_(false), accepted_(0) {}
virtual ~TServerReadyEventHandler() {}
virtual void preServe() {
Synchronized sync(*this);
isListening_ = true;
notify();
}
virtual void* createContext(boost::shared_ptr<TProtocol> input,
boost::shared_ptr<TProtocol> output) {
Synchronized sync(*this);
++accepted_;
notify();
(void)input;
(void)output;
return NULL;
}
bool isListening() const { return isListening_; }
uint64_t acceptedCount() const { return accepted_; }
private:
bool isListening_;
uint64_t accepted_;
};
void base_client(thrift_test::S2Client& client) {
cerr << "Starting the client..." << endl;
client.ping();
ASSERT_EQ( client.foo(42l, thrift_test::Bar()), 42l ) ;
thrift_test::Bar b ;
client.goo(b) ;
client.hoo() ;
client.ping();
ASSERT_THROW( client.foo(0l, thrift_test::Bar()),
thrift_test::InvalidOperation ) ;
ASSERT_THROW( client.foo(1l, thrift_test::Bar()),
thrift_test::InvalidOperation2 ) ;
ASSERT_THROW( client.foo(2l, thrift_test::Bar()),
apache::thrift::TApplicationException ) ;
}
TEST( RPC, Binary_TCP )
{
TThreadedServer server(
boost::make_shared<thrift_test::S2ProcessorFactory>(boost::make_shared<S2CloneFactory>()),
boost::make_shared<TServerSocket>(9090), //port
boost::make_shared<TBufferedTransportFactory>(),
boost::make_shared<TBinaryProtocolFactory>());
boost::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
cerr << "Starting the server..." << endl;
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9090));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
thrift_test::S2Client client(protocol);
transport->open();
base_client(client) ;
transport->close();
}
server.stop();
thread.join() ;
}
TEST( RPC, NiceJSON_TCP )
{
TThreadedServer server(
boost::make_shared<thrift_test::S2ProcessorFactory>(boost::make_shared<S2CloneFactory>()),
boost::make_shared<TServerSocket>(9091), //port
boost::make_shared<TBufferedTransportFactory>(),
boost::make_shared<TNiceJSONProtocolFactory>(kTestTypelib, "S2"));
boost::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
cerr << "Starting the server..." << endl;
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9091));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TNiceJSONProtocol(kTestTypelib, "S2", transport));
thrift_test::S2Client client(protocol);
transport->open();
base_client(client) ;
transport->close();
}
server.stop();
thread.join() ;
}
TEST( RPC, Binary_HTTP )
{
TThreadedServer server(
boost::make_shared<thrift_test::S2ProcessorFactory>(boost::make_shared<S2CloneFactory>()),
boost::make_shared<TServerSocket>(9092), //port
boost::make_shared<THttpServerTransportFactory>(),
boost::make_shared<TBinaryProtocolFactory>());
boost::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
cerr << "Starting the server..." << endl;
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9092));
boost::shared_ptr<TTransport> transport(new THttpClient(socket, "localhost", "/service"));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
thrift_test::S2Client client(protocol);
transport->open();
base_client(client) ;
transport->close();
}
server.stop();
thread.join() ;
}
TEST( RPC, JSON_HTTP )
{
TThreadedServer server(
boost::make_shared<thrift_test::S2ProcessorFactory>(boost::make_shared<S2CloneFactory>()),
boost::make_shared<TServerSocket>(9092), //port
boost::make_shared<THttpServerTransportFactory>(),
boost::make_shared<TJSONProtocolFactory>());
boost::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
cerr << "Starting the server..." << endl;
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9092));
boost::shared_ptr<TTransport> transport(new THttpClient(socket, "localhost", "/service"));
boost::shared_ptr<TProtocol> protocol(new TJSONProtocol(transport));
thrift_test::S2Client client(protocol);
transport->open();
base_client(client) ;
transport->close();
}
server.stop();
thread.join() ;
}
TEST( RPC, NiceJSON_HTTP )
{
TThreadedServer server(
boost::make_shared<thrift_test::S2ProcessorFactory>(boost::make_shared<S2CloneFactory>()),
boost::make_shared<TServerSocket>(9092), //port
boost::make_shared<THttpServerTransportFactory>(),
boost::make_shared<TNiceJSONProtocolFactory>(kTestTypelib, "S2"));
boost::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
cerr << "Starting the server..." << endl;
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 9092));
boost::shared_ptr<TTransport> transport(new THttpClient(socket, "localhost", "/service"));
boost::shared_ptr<TProtocol> protocol(new TNiceJSONProtocol(kTestTypelib, "S2", transport));
thrift_test::S2Client client(protocol);
transport->open();
base_client(client) ;
transport->close();
}
server.stop();
thread.join() ;
}
class TBlockableBufferedTransport : public TBufferedTransport {
public:
TBlockableBufferedTransport(boost::shared_ptr<TTransport> transport, uint32_t sz)
: TBufferedTransport(transport, sz),
blocked_(false) {
}
TBlockableBufferedTransport(boost::shared_ptr<TTransport> transport)
: TBufferedTransport(transport),
blocked_(false) {
}
uint32_t write_buffer_length() {
uint32_t have_bytes = static_cast<uint32_t>(wBase_ - wBuf_.get());
return have_bytes ;
}
void block() {
blocked_ = true ;
cerr << "block flushing\n" ;
}
void unblock() {
blocked_ = false ;
cerr << "unblock flushing, buffer is\n<<" << std::string((char *)wBuf_.get(), write_buffer_length()) << ">>\n" ;
}
void flush() override {
if (blocked_) {
cerr << "flush was blocked\n" ;
return ;
}
TBufferedTransport::flush() ;
}
bool blocked_ ;
} ;
TEST( RPC, JSON_BufferedHTTP )
{
auto ss = boost::make_shared<TServerSocket>(0) ;
TThreadedServer server(
boost::make_shared<thrift_test::S2ProcessorFactory>(boost::make_shared<S2CloneFactory>()),
ss, //port
boost::make_shared<THttpServerTransportFactory>(),
boost::make_shared<TJSONProtocolFactory>());
boost::shared_ptr<TServerReadyEventHandler> pEventHandler(new TServerReadyEventHandler) ;
server.setServerEventHandler(pEventHandler);
cerr << "Starting the server...\n";
RPC0ThreadClass t(server) ;
boost::thread thread(&RPC0ThreadClass::Run, &t);
{
Synchronized sync(*(pEventHandler.get()));
while (!pEventHandler->isListening()) {
pEventHandler->wait();
}
}
int port = ss->getPort() ;
cerr << "port " << port << endl ;
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", port));
boost::shared_ptr<TBlockableBufferedTransport> blockable_transport(new TBlockableBufferedTransport(socket));
boost::shared_ptr<TTransport> transport(new THttpClient(blockable_transport, "localhost", "/service"));
boost::shared_ptr<TProtocol> protocol(new TJSONProtocol(transport));
thrift_test::S2Client client(protocol);
transport->open();
client.ping();
blockable_transport->block() ;
uint32_t size0 = blockable_transport->write_buffer_length() ;
client.send_hoo() ;
uint32_t size1 = blockable_transport->write_buffer_length() ;
client.send_hoo() ;
uint32_t size2 = blockable_transport->write_buffer_length() ;
ASSERT_EQ((size1 - size0), (size2 - size1)) ;
blockable_transport->unblock() ;
client.send_ping();
blockable_transport->flush() ;
try {
client.recv_ping();
} catch (TTransportException e) {
FAIL() << "we should not get a transport exception -- this means we failed: " + std::string(e.what()) ;
}
transport->close();
}
server.stop();
thread.join() ;
cerr << "finished.\n";
}
| 28.967177 | 116 | 0.692476 | chetmurthy |
4d68a5c1abb47b5a3ddee7d2356c5cb780c6fbdd | 13,076 | cpp | C++ | src/footstepAffordance.cpp | RajPShinde/footstep_affordance | 6e8863c098fc4f6e789e0eee56adcee5df061454 | [
"Unlicense"
] | 4 | 2021-11-23T04:44:06.000Z | 2022-03-26T11:39:30.000Z | src/footstepAffordance.cpp | RajPShinde/footstep_affordance | 6e8863c098fc4f6e789e0eee56adcee5df061454 | [
"Unlicense"
] | null | null | null | src/footstepAffordance.cpp | RajPShinde/footstep_affordance | 6e8863c098fc4f6e789e0eee56adcee5df061454 | [
"Unlicense"
] | 2 | 2020-12-21T13:43:56.000Z | 2021-12-10T06:13:57.000Z | #include <footstepAffordance.hpp>
namespace costmap
{
FootstepAffordance::FootstepAffordance() {
}
FootstepAffordance::~FootstepAffordance() {
}
unsigned int FootstepAffordance::computeMeanAndCovariance(Eigen::Vector3d& meanPosition, Eigen::Matrix3d& covarianceMatrix, const std::vector<Eigen::Vector3d>& cloud) {
Eigen::VectorXd accu = Eigen::VectorXd::Zero(9, 1);
for (size_t i = 0; i < cloud.size(); ++i) {
accu[0] += cloud[i](0) * cloud[i](0); // summation x.x
accu[1] += cloud[i](0) * cloud[i](1); // summation x.y
accu[2] += cloud[i](0) * cloud[i](2); // summation x.z
accu[3] += cloud[i](1) * cloud[i](1); // summation y.y
accu[4] += cloud[i](1) * cloud[i](2); // summation y.z
accu[5] += cloud[i](2) * cloud[i](2); // summation z.z
accu[6] += cloud[i](0); // summation x
accu[7] += cloud[i](1); // summation y
accu[8] += cloud[i](2); // summation x
}
accu /= (cloud.size());
// Meam and Covariance
if (cloud.size() != 0) {
meanPosition[0] = accu[6];
meanPosition[1] = accu[7];
meanPosition[2] = accu[8];
covarianceMatrix.coeffRef(0) = accu[0] - accu[6] * accu[6];
covarianceMatrix.coeffRef(1) = accu[1] - accu[6] * accu[7];
covarianceMatrix.coeffRef(2) = accu[2] - accu[6] * accu[8];
covarianceMatrix.coeffRef(4) = accu[3] - accu[7] * accu[7];
covarianceMatrix.coeffRef(5) = accu[4] - accu[7] * accu[8];
covarianceMatrix.coeffRef(8) = accu[5] - accu[8] * accu[8];
covarianceMatrix.coeffRef(3) = covarianceMatrix.coeff(1);
covarianceMatrix.coeffRef(6) = covarianceMatrix.coeff(2);
covarianceMatrix.coeffRef(7) = covarianceMatrix.coeff(5);
}
return (static_cast<unsigned int> (cloud.size()));
}
void FootstepAffordance::solvePlaneParameters(Eigen::Vector3d &normal, double &curvature, const Eigen::Matrix3d &covarianceMatrix){
// Extract the smallest eigenvalue and its eigenvector
EIGEN_ALIGN16 Eigen::Vector3d::Scalar eigenvalue;
EIGEN_ALIGN16 Eigen::Vector3d eigenvector;
//typedef typename Eigen::Matrix3f::Scalar Scalar;
// Scale the matrix so its entries are in [-1,1]. The scaling is applied
// only when at least one matrix entry has magnitude larger than 1.
Eigen::Matrix3d::Scalar scale = covarianceMatrix.cwiseAbs().maxCoeff();
if (scale <= std::numeric_limits<Eigen::Matrix3d::Scalar>::min())
scale = Eigen::Matrix3d::Scalar(1.0);
Eigen::Matrix3d scaledMat = covarianceMatrix / scale;
Eigen::Vector3d eigenvalues;
computeRoots(eigenvalues, scaledMat);
eigenvalue = eigenvalues(0) * scale;
scaledMat.diagonal().array() -= eigenvalues(0);
Eigen::Vector3d vec1 = scaledMat.row(0).cross(scaledMat.row(1));
Eigen::Vector3d vec2 = scaledMat.row(0).cross(scaledMat.row(2));
Eigen::Vector3d vec3 = scaledMat.row(1).cross(scaledMat.row(2));
Eigen::Matrix3d::Scalar len1 = vec1.squaredNorm();
Eigen::Matrix3d::Scalar len2 = vec2.squaredNorm();
Eigen::Matrix3d::Scalar len3 = vec3.squaredNorm();
if (len1 >= len2 && len1 >= len3)
eigenvector = vec1 / std::sqrt(len1);
else if (len2 >= len1 && len2 >= len3)
eigenvector = vec2 / std::sqrt(len2);
else
eigenvector = vec3 / std::sqrt(len3);
// Check K_hat. The normal vectors should point to the +ve Z direction
if (eigenvector(2) < 0.)
eigenvector *= -1;
normal= eigenvector;
}
void FootstepAffordance::computeRoots(Eigen::Vector3d& roots, const Eigen::Matrix3d& m)
{
// The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The
// eigenvalues are the roots to this equation, all guaranteed to be
// real-valued, because the matrix is symmetric.
Eigen::Matrix3d::Scalar c0 = m(0,0) * m(1,1) * m(2,2) +
Eigen::Matrix3d::Scalar(2) * m(0,1) * m(0,2) * m(1,2)
- m(0,0) * m(1,2) * m(1,2) - m(1,1) * m(0,2) * m(0,2)
- m(2,2) * m(0,1) * m(0,1);
Eigen::Matrix3d::Scalar c1 = m(0,0) * m(1,1) - m(0,1) * m(0,1) + m(0,0) * m(2,2) -
m(0,2) * m(0,2) + m(1,1) * m(2,2) - m(1,2) * m(1,2);
Eigen::Matrix3d::Scalar c2 = m(0,0) + m(1,1) + m(2,2);
if (fabs (c0) < Eigen::NumTraits<Eigen::Matrix3d::Scalar>::epsilon ())// one root is 0 -> quadratic equation
computeRoots2(roots, c2, c1);
else
{
const Eigen::Matrix3d::Scalar s_inv3 = Eigen::Matrix3d::Scalar(1.0 / 3.0);
const Eigen::Matrix3d::Scalar s_sqrt3 = std::sqrt(Eigen::Matrix3d::Scalar (3.0));
// Construct the parameters used in classifying the roots of the equation
// and in solving the equation for the roots in closed form.
Eigen::Matrix3d::Scalar c2_over_3 = c2*s_inv3;
Eigen::Matrix3d::Scalar a_over_3 = (c1 - c2 * c2_over_3) * s_inv3;
if (a_over_3 > Eigen::Matrix3d::Scalar(0))
a_over_3 = Eigen::Matrix3d::Scalar (0);
Eigen::Matrix3d::Scalar half_b = Eigen::Matrix3d::Scalar(0.5) *
(c0 + c2_over_3 * (Eigen::Matrix3d::Scalar(2) * c2_over_3 * c2_over_3 - c1));
Eigen::Matrix3d::Scalar q = half_b * half_b + a_over_3 * a_over_3 * a_over_3;
if (q > Eigen::Matrix3d::Scalar(0))
q = Eigen::Matrix3d::Scalar(0);
// Compute the eigenvalues by solving for the roots of the polynomial.
Eigen::Matrix3d::Scalar rho = sqrt(-a_over_3);
Eigen::Matrix3d::Scalar theta = atan2(std::sqrt(-q), half_b) * s_inv3;
Eigen::Matrix3d::Scalar cos_theta = cos(theta);
Eigen::Matrix3d::Scalar sin_theta = sin(theta);
roots(0) = c2_over_3 + Eigen::Matrix3d::Scalar(2) * rho * cos_theta;
roots(1) = c2_over_3 - rho * (cos_theta + s_sqrt3 * sin_theta);
roots(2) = c2_over_3 - rho * (cos_theta - s_sqrt3 * sin_theta);
// Sort in increasing order.
double roots0 = roots(0);
double roots1 = roots(1);
double roots2 = roots(2);
if (roots(0) >= roots(1))
std::swap(roots0, roots1);
if (roots(1) >= roots(2)) {
std::swap(roots1, roots2);
if (roots(0) >= roots(1))
std::swap(roots0, roots1);
}
roots(0) = roots0;
roots(1) = roots1;
roots(2) = roots2;
if (roots(0) <= 0) // eigenvalue for symmetric positive semi-definite matrix can not be negative! Set it to 0
computeRoots2(roots, c2, c1);
}
}
void FootstepAffordance::computeRoots2(Eigen::Vector3d& roots,
const Eigen::Matrix3d::Scalar& b,
const Eigen::Matrix3d::Scalar& c)
{
roots(0) = Eigen::Matrix3d::Scalar(0);
Eigen::Matrix3d::Scalar d = Eigen::Matrix3d::Scalar(b * b - 4.0 * c);
if (d < 0.0) // no real roots!!!! THIS SHOULD NOT HAPPEN!
d = 0.0;
Eigen::Matrix3d::Scalar sd = sqrt(d);
roots(2) = 0.5f * (b + sd);
roots(1) = 0.5f * (b - sd);
}
void FootstepAffordance::run(octomap::OcTree* octomap,
const Eigen::Vector3d& robotStateXYZ,
const Eigen::Vector3d& robotStateRPY,
std::map<std::pair<double, double>, double> &hMap,
std::map<std::pair<double, double>, double> &cMap) {
ROS_ERROR_STREAM("Run");
Eigen::Vector2d boundaryMin, boundaryMax;
boundaryMax(0) = maxX + robotStateXYZ(0);
boundaryMin(0) = minX + robotStateXYZ(0);
boundaryMax(1) = maxY + robotStateXYZ(1);
boundaryMin(1) = minY + robotStateXYZ(1);
double zMax = maxZ + robotStateXYZ(2);
double zMin = minZ + robotStateXYZ(2);
double resolution = 0.02;
for(double x = boundaryMin(0); x<= boundaryMax(0); x += resolution) {
for(double y = boundaryMin(1); y<= boundaryMax(1); y += resolution) {
double rotatedX = (x - robotStateXYZ(0)) * cos(robotStateRPY(2)) - (y - robotStateXYZ(1)) * sin(robotStateRPY(2)) + robotStateXYZ(0);
double rotatedY = (x - robotStateXYZ(0)) * sin(robotStateRPY(2)) - (y - robotStateXYZ(1)) * cos(robotStateRPY(2)) + robotStateXYZ(1);
//ROS_ERROR_STREAM("rotatedY"<<rotatedY);
double zMax = maxZ + robotStateXYZ(2);
octomap::OcTreeKey topCellKey;
// Check if map data present at above X & Y
if (!octomap->coordToKeyChecked(rotatedX, rotatedY, zMax, depth_, topCellKey)) { //gives true if point in octree and also
printf("No map data at selected location\n");
return;
}
int goDownCellBy = 0;
octomap::OcTreeNode* heightmapNode = octomap->search(topCellKey, depth_);
// iterate till the surface is not below the zMin limit
while(zMax >= zMin) {
octomap::OcTreeKey currentCellKey;
currentCellKey[0] = topCellKey[0];
currentCellKey[1] = topCellKey[1];
currentCellKey[2] = topCellKey[2] - goDownCellBy;
heightmapNode = octomap->search(currentCellKey, depth_);
octomap::point3d currentCellXYZ = octomap->keyToCoord(currentCellKey, depth_);
zMax = currentCellXYZ(2);
if(heightmapNode) {
// If occupied it is the surface
if(octomap->isNodeOccupied(heightmapNode)){
//found surface cell
Eigen::Vector3d surfaceCellXYZ;
surfaceCellXYZ(0) = currentCellXYZ(0); // x
surfaceCellXYZ(1) = currentCellXYZ(1); // y
surfaceCellXYZ(2) = currentCellXYZ(2); // z
// std::cout << surfaceCellXYZ(0)<<" "<<surfaceCellXYZ(1) <<" " <<surfaceCellXYZ(2)<<"***\n";
addToHeightmap(surfaceCellXYZ, hMap);
calculateCost(octomap ,currentCellKey, cMap);
break;
}
}
goDownCellBy++;
}
}
}
//hMap = terrainParameters.heightMap;
//cMap = terrainParameters.costMap;
ROS_ERROR_STREAM("End");
}
void FootstepAffordance::calculateCost(octomap::OcTree* octomap, const octomap::OcTreeKey& surfaceCellKey, std::map<std::pair<double, double>, double> &cMap) {
ROS_ERROR_STREAM("calculate Cost");
firstRun_ = true;
bool atLeastOneNeighbour = false;
std::vector<Eigen::Vector3d> allNeighboursPosition;
octomap::OcTreeNode* surfaceCellNode = octomap->search(surfaceCellKey, depth_);
Eigen::Vector3d surfaceCellXYZ;
octomap::point3d surfaceCellPoint = octomap->keyToCoord(surfaceCellKey, depth_);
surfaceCellXYZ(0) = surfaceCellPoint(0); // x
surfaceCellXYZ(1) = surfaceCellPoint(1); // y
surfaceCellXYZ(2) = surfaceCellPoint(2); // z
allNeighboursPosition.push_back(surfaceCellXYZ);
octomap::OcTreeKey neighbourKey;
octomap::OcTreeNode* neighbourNode = surfaceCellNode;
bool yq = false;
ROS_ERROR_STREAM("Neighbours");
for(int z = -1; z<=1; z++) {
for(int y = -1; y<=1; y++) {
for(int x = -1; x<=1; x++) {
neighbourKey[0] = surfaceCellKey[0] + x;
neighbourKey[1] = surfaceCellKey[1] + y;
neighbourKey[2] = surfaceCellKey[2] + z;
neighbourNode = octomap->search(neighbourKey, depth_);
yq =true;
//ROS_ERROR_STREAM(z);
// Check if this neighbour exists
if(neighbourNode) {
// ROS_ERROR_STREAM("Found1");
if(octomap->isNodeOccupied(neighbourNode)) {
// ROS_ERROR_STREAM("Found2");
Eigen::Vector3d neighbourCellXYZ;
octomap::point3d neighbourCellPoint;
neighbourCellPoint = octomap->keyToCoord(neighbourKey, depth_);
neighbourCellXYZ(0) = neighbourCellPoint(0);
neighbourCellXYZ(1) = neighbourCellPoint(1);
neighbourCellXYZ(2) = neighbourCellPoint(2);
allNeighboursPosition.push_back(neighbourCellXYZ);
atLeastOneNeighbour = true;
}
}
}
}
}
if(yq)
ROS_WARN_STREAM("HAA andar gaya tha");
if(atLeastOneNeighbour) {
//compute cost
ROS_ERROR_STREAM("At Least One Neighbour");
EIGEN_ALIGN16 Eigen::Matrix3d covarianceMatrix;
if(allNeighboursPosition.size()<3 || computeMeanAndCovariance(terrainParameters.meanPosition, covarianceMatrix, allNeighboursPosition)==0){
ROS_ERROR_STREAM("<3");
return;
}
ROS_WARN_STREAM(allNeighboursPosition.size());
terrainParameters.centroidPosition(0) = allNeighboursPosition[0](0);
terrainParameters.centroidPosition(1) = allNeighboursPosition[0](1);
terrainParameters.centroidPosition(2) = allNeighboursPosition[0](2);
solvePlaneParameters(terrainParameters.normal, terrainParameters.curvature, covarianceMatrix);
}
ROS_ERROR_STREAM("Cost");
ROS_ERROR_STREAM(terrainParameters.normal);
double cost, weight, totalCost = 0;
// for(auto i: features) {
features.computeSlopeCost(cost, terrainParameters);
totalCost = 1*cost;
// }
// put totalCost in costmap
addToCostmap(surfaceCellXYZ, totalCost, cMap);
}
void FootstepAffordance::addToCostmap(Eigen::Vector3d surfaceCellXYZ, double &totalCost, std::map<std::pair<double, double>, double> &cMap){
std::map<std::pair<double, double>, double>::iterator it = cMap.find(std::make_pair(surfaceCellXYZ(0),surfaceCellXYZ(1)));
if (it != cMap.end()) {
if(it->second!=totalCost) {
it->second = totalCost;
}
}
else
cMap.insert({std::make_pair(surfaceCellXYZ(0),surfaceCellXYZ(1)), totalCost});
}
void FootstepAffordance::addToHeightmap(Eigen::Vector3d surfaceCellXYZ, std::map<std::pair<double, double>, double> &hMap){
std::map<std::pair<double, double>, double>::iterator it = hMap.find(std::make_pair(surfaceCellXYZ(0),surfaceCellXYZ(1)));
if (it != hMap.end()) {
if(it->second!=surfaceCellXYZ(2)) {
it->second = surfaceCellXYZ(2);
}
}
else
hMap.insert({std::make_pair(surfaceCellXYZ(0),surfaceCellXYZ(1)), surfaceCellXYZ(2)});
}
} | 38.011628 | 168 | 0.658458 | RajPShinde |
4d69e28ebe9f973ea99c0be5d884e6267bdfbf6f | 392 | cpp | C++ | HRank/Hill.cpp | SeekerNik/code | e36105361daffac2b6e48ab63f3b9d79120f6310 | [
"MIT"
] | null | null | null | HRank/Hill.cpp | SeekerNik/code | e36105361daffac2b6e48ab63f3b9d79120f6310 | [
"MIT"
] | null | null | null | HRank/Hill.cpp | SeekerNik/code | e36105361daffac2b6e48ab63f3b9d79120f6310 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
string s = "DDUUUUDD";
int Position = 0;
int valley = 0;
for (int i = 0; i < s.size() - 1; i++)
{
s[i] == 'U' ? Position++ : Position--;
if (Position < 0 && s[i + 1] == 'U' && 0 == Position + 1)
{
valley++;
}
}
cout << valley;
return 0;
} | 20.631579 | 66 | 0.408163 | SeekerNik |
4d6de70dedddefcb6c1f6b3b1f6cea26faf03aa3 | 3,975 | cc | C++ | syslog-cat/syslogcat.cc | dgreid/platform2 | 9b8b30df70623c94f1c8aa634dba94195343f37b | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | syslog-cat/syslogcat.cc | dgreid/platform2 | 9b8b30df70623c94f1c8aa634dba94195343f37b | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | syslog-cat/syslogcat.cc | dgreid/platform2 | 9b8b30df70623c94f1c8aa634dba94195343f37b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium OS 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 "syslog-cat/syslogcat.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/files/scoped_file.h>
#include <base/logging.h>
#include <base/posix/eintr_wrapper.h>
#include <base/strings/stringprintf.h>
namespace {
base::ScopedFD PrepareSocket(const std::string& identifier,
int severity,
int pid,
const base::FilePath& socket_path) {
DCHECK(!identifier.empty());
DCHECK_GE(severity, 0);
DCHECK_LE(severity, 7);
// Open the unix socket to write logs.
base::ScopedFD sock(
socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_CLOEXEC, 0));
if (!sock.is_valid()) {
PLOG(ERROR) << "opening stream socket";
return base::ScopedFD();
}
// Connect the syslog unix socket file.
struct sockaddr_un server = {};
server.sun_family = AF_UNIX;
CHECK_GT(sizeof(server.sun_path), socket_path.value().length());
strncpy(server.sun_path, socket_path.value().c_str(),
sizeof(server.sun_path));
if (HANDLE_EINTR(connect(sock.get(), (struct sockaddr*)&server,
sizeof(struct sockaddr_un))) < 0) {
PLOG(ERROR) << "connecting stream socket";
return base::ScopedFD();
}
// Construct the header string to send.
std::string header = base::StringPrintf("TAG=%s[%d]\nPRIORITY=%d\n\n",
identifier.c_str(), pid, severity);
// Send headers (tag and severity).
if (!base::WriteFileDescriptor(sock.get(), header.c_str(), header.size())) {
PLOG(ERROR) << "writing headers on stream socket";
return base::ScopedFD();
}
return sock;
}
bool CreateSocketAndBindToFD(const std::string& identifier,
int severity,
int pid,
int target_fd,
const base::FilePath& socket_path) {
base::ScopedFD sock = PrepareSocket(identifier, severity, pid, socket_path);
if (!sock.is_valid()) {
LOG(ERROR) << "Failed to open the rsyslog socket for stderr.";
return false;
}
// Connect the socket to stderr.
if (HANDLE_EINTR(dup2(sock.get(), target_fd)) == -1) {
PLOG(ERROR) << "duping the stderr";
return false;
}
return true;
}
} // namespace
void ExecuteCommandWithRedirection(
const std::string& target_command,
const std::vector<const char*>& target_command_argv,
const std::string& identifier,
int severity_stdout,
int severity_stderr,
const base::FilePath& socket_path_stdout,
const base::FilePath& socket_path_stderr) {
// Prepare a pid.
pid_t pid = getpid();
// Open the unix socket to redirect logs from stdout (and stderr).
bool ret_stdout = CreateSocketAndBindToFD(identifier, severity_stdout, pid,
STDOUT_FILENO, socket_path_stdout);
CHECK(ret_stdout) << "Failed to bind stdout.";
// Open the unix socket to redirect logs from stderr.
// We prepare a separate socket for stderr even if the severities are same,
// in order to prevent interleave of simultaneous lines.
bool ret_stderr = CreateSocketAndBindToFD(identifier, severity_stderr, pid,
STDERR_FILENO, socket_path_stderr);
CHECK(ret_stderr) << "Failed to bind stderr.";
// Execute the target process.
execvp(const_cast<char*>(target_command.c_str()),
const_cast<char**>(target_command_argv.data()));
/////////////////////////////////////////////////////////////////////////////
// The code below is executed only when the execvp() above failed.
// (eg. the executable doesn't exist, or is not executable)
PLOG(ERROR) << "execvp '" << target_command << "'";
}
| 34.565217 | 79 | 0.627925 | dgreid |
4d6e70a215b4efb2593cc59b4b3da25ddfe22a54 | 5,453 | cpp | C++ | gwen/src/Gwen/Skins/Texturing.cpp | CristianoBeato/SDLGwen | c2440f256d87c472f8e1b7b3d680521b2c0c0837 | [
"MIT"
] | 1 | 2019-02-18T09:11:10.000Z | 2019-02-18T09:11:10.000Z | gwen/src/Gwen/Skins/Texturing.cpp | CristianoBeato/SDLGwen | c2440f256d87c472f8e1b7b3d680521b2c0c0837 | [
"MIT"
] | null | null | null | gwen/src/Gwen/Skins/Texturing.cpp | CristianoBeato/SDLGwen | c2440f256d87c472f8e1b7b3d680521b2c0c0837 | [
"MIT"
] | null | null | null | /*
===========================================================================
GWEN
Copyright (c) 2010 Facepunch Studios
Copyright (c) 2017-2019 Cristiano Beato
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#include "Gwen/Skins/Texturing.h"
Gwen::Skin::Texturing::Single::Single(void)
{
texture = NULL;
}
void Gwen::Skin::Texturing::Single::Init(Texture * pTexture, float x, float y, float w, float h)
{
texture = pTexture;
float texw = texture->getWidth();
float texh = texture->getHeight();
uv[0] = x / texw;
uv[1] = y / texh;
uv[2] = (x + w) / texw;
uv[3] = (y + h) / texh;
this->iWidth = w;
this->iHeight = h;
}
void Gwen::Skin::Texturing::Single::Draw(Renderer::BaseRender * render, Rect r, const Color & col)
{
if (!texture)
return;
render->SetDrawColor(col);
render->DrawTexturedRect(texture, r, uv[0], uv[1], uv[2], uv[3]);
}
void Gwen::Skin::Texturing::Single::DrawCenter(Renderer::BaseRender * render, Rect r, const Color & col)
{
if (!texture)
return;
r.x += (r.w - iWidth) * 0.5;
r.y += (r.h - iHeight) * 0.5;
r.w = iWidth;
r.h = iHeight;
Draw(render, r, col);
}
Gwen::Skin::Texturing::Bordered::Bordered(void)
{
texture = NULL;
}
void Gwen::Skin::Texturing::Bordered::Init(Texture * pTexture, float x, float y, float w, float h, Margin in_margin, float DrawMarginScale)
{
texture = pTexture;
margin = in_margin;
SetRect(0, x, y, margin.left, margin.top);
SetRect(1, x + margin.left, y, w - margin.left - margin.right, margin.top);
SetRect(2, (x + w) - margin.right, y, margin.right, margin.top);
SetRect(3, x, y + margin.top, margin.left, h - margin.top - margin.bottom);
SetRect(4, x + margin.left, y + margin.top, w - margin.left - margin.right, h - margin.top - margin.bottom);
SetRect(5, (x + w) - margin.right, y + margin.top, margin.right, h - margin.top - margin.bottom);
SetRect(6, x, (y + h) - margin.bottom, margin.left, margin.bottom);
SetRect(7, x + margin.left, (y + h) - margin.bottom, w - margin.left - margin.right, margin.bottom);
SetRect(8, (x + w) - margin.right, (y + h) - margin.bottom, margin.right, margin.bottom);
margin.left *= DrawMarginScale;
margin.right *= DrawMarginScale;
margin.top *= DrawMarginScale;
margin.bottom *= DrawMarginScale;
width = w - x;
height = h - y;
}
void Gwen::Skin::Texturing::Bordered::SetRect(int iNum, float x, float y, float w, float h)
{
float texw = texture->getWidth();
float texh = texture->getHeight();
//x -= 1.0f;
//y -= 1.0f;
rects[iNum].uv[0] = x / texw;
rects[iNum].uv[1] = y / texh;
rects[iNum].uv[2] = (x + w) / texw;
rects[iNum].uv[3] = (y + h) / texh;
// rects[iNum].uv[0] += 1.0f / texture->width;
// rects[iNum].uv[1] += 1.0f / texture->width;
}
void Gwen::Skin::Texturing::Bordered::Draw(Gwen::Renderer::BaseRender * render, Gwen::Rect r, const Gwen::Color & col, bool b1, bool b2, bool b3, bool b4, bool b5, bool b6, bool b7, bool b8, bool b9)
{
if (!texture)
return;
render->SetDrawColor(col);
if (r.w < width && r.h < height)
{
render->DrawTexturedRect(texture,
r,
rects[0].uv[0], rects[0].uv[1], rects[8].uv[2], rects[8].uv[3]);
return;
}
if (b1)
DrawRect(render, 0, r.x, r.y, margin.left, margin.top);
if (b2)
DrawRect(render, 1, r.x + margin.left, r.y, r.w - margin.left - margin.right, margin.top);
if (b3)
DrawRect(render, 2, (r.x + r.w) - margin.right, r.y, margin.right, margin.top);
if (b4)
DrawRect(render, 3, r.x, r.y + margin.top, margin.left, r.h - margin.top - margin.bottom);
if (b5)
DrawRect(render, 4, r.x + margin.left, r.y + margin.top, r.w - margin.left - margin.right, r.h - margin.top - margin.bottom);
if (b6)
DrawRect(render, 5, (r.x + r.w) - margin.right, r.y + margin.top, margin.right, r.h - margin.top - margin.bottom);
if (b7)
DrawRect(render, 6, r.x, (r.y + r.h) - margin.bottom, margin.left, margin.bottom);
if (b8)
DrawRect(render, 7, r.x + margin.left, (r.y + r.h) - margin.bottom, r.w - margin.left - margin.right, margin.bottom);
if (b9)
DrawRect(render, 8, (r.x + r.w) - margin.right, (r.y + r.h) - margin.bottom, margin.right, margin.bottom);
}
void Gwen::Skin::Texturing::Bordered::DrawRect(Gwen::Renderer::BaseRender * render, int i, int x, int y, int w, int h)
{
render->DrawTexturedRect(texture,
Gwen::Rect(x, y, w, h),
rects[i].uv[0], rects[i].uv[1], rects[i].uv[2], rects[i].uv[3]);
}
| 33.25 | 199 | 0.653402 | CristianoBeato |
4d6f8b373d7c89efcef9efbed51300ec684dd9f5 | 1,151 | hpp | C++ | include/licon/nn/node/elt_wise_sum.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | 93 | 2017-10-25T07:48:42.000Z | 2022-02-02T15:18:11.000Z | include/licon/nn/node/elt_wise_sum.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | null | null | null | include/licon/nn/node/elt_wise_sum.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | 20 | 2018-02-06T10:01:36.000Z | 2019-07-07T09:26:40.000Z | #ifndef LICON_NN_NODE_ELT_WISE_SUM_HPP
#define LICON_NN_NODE_ELT_WISE_SUM_HPP
/**
* the container of hstack some opnode together then element wise sum into one tensor
*/
#include "licon/nn/node/neuron_stack.hpp"
namespace licon
{
namespace nn
{
class EltWiseSum : public Stack<F> {
public:
// the heap creator, if set true, the container will set one path to self
static nn::NodePtr CreateEltWiseSum(bool need_self = true);
// the name of this node
virtual inline std::string name() const { return "elt_wise_sum"; }
// add a neuron node into the squential container
virtual void Add(std::unique_ptr<OpNode<F> > neuron_node);
// add a neuron node, give its sub node name at the same time
virtual void Add(std::string sub_node_name, std::unique_ptr<OpNode<F> > neuron_node);
// the forward and backward
virtual void Forward(const std::vector<utils::ETensor<F>* >& bottom);
virtual void Backward(const std::vector<utils::ETensor<F>* >& top);
private:
// the constructor
EltWiseSum(bool need_self);
bool m_need_self;
};
} //nn
} //licon
#endif /*LICON_NN_NODE_ELT_WISE_SUM_HPP*/ | 23.02 | 89 | 0.711555 | wzppengpeng |
4d73799fb2053463efade6cfdf9d1e90879c1802 | 11,459 | cc | C++ | src/utils/bitcoin_random.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | 1 | 2021-01-11T14:19:51.000Z | 2021-01-11T14:19:51.000Z | src/utils/bitcoin_random.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | src/utils/bitcoin_random.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// bitcoin/src/support/cleanse.cpp
// bitcoin/src/random.cpp
#include "utils/bitcoin_random.h"
#include <sys/time.h>
#include <sys/syscall.h>
#include <linux/random.h>
#include <sys/sysctl.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <atomic>
#include <limits>
#include <chrono>
#include <mutex>
#include <thread>
#include "utils/bitcoin_sha512.h"
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
#include <cpuid.h>
#endif
#include <openssl/err.h>
#include <openssl/rand.h>
namespace bubblefs {
namespace mybitcoin {
/*
* Attempt to overwrite data in the specified memory span.
* Compilers have a bad habit of removing "superfluous" memset calls that
* are trying to zero memory. For example, when memset()ing a buffer and
* then free()ing it, the compiler might decide that the memset is
* unobservable and thus can be removed.
*
* Previously we used OpenSSL which tried to stop this by a) implementing
* memset in assembly on x86 and b) putting the function in its own file
* for other platforms.
*
* This change removes those tricks in favour of using asm directives to
* scare the compiler away. As best as our compiler folks can tell, this is
* sufficient and will continue to be so.
*
* Adam Langley <agl@google.com>
* Commit: ad1907fe73334d6c696c8539646c21b11178f20f
* BoringSSL (LICENSE: ISC)
*/
void memory_cleanse(void *ptr, size_t len)
{
memset(ptr, 0, len);
/* As best as we can tell, this is sufficient to break any optimisations that
might try to eliminate "superfluous" memsets. If there's an easy way to
detect memset_s, it would be better to use that. */
#if defined(_MSC_VER)
SecureZeroMemory(ptr, len);
#else
__asm__ __volatile__("" : : "r"(ptr) : "memory");
#endif
}
static void RandFailure()
{
printf("Failed to read randomness, aborting\n");
abort();
}
static inline int64_t GetPerformanceCounter()
{
// Read the hardware time stamp counter when available.
// See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information.
#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
return __rdtsc();
#elif !defined(_MSC_VER) && defined(__i386__)
uint64_t r = 0;
__asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair.
return r;
#elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__))
uint64_t r1 = 0, r2 = 0;
__asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx.
return (r2 << 32) | r1;
#else
// Fall back to using C++11 clock (usually microsecond or nanosecond precision)
return std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
}
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
static std::atomic<bool> hwrand_initialized{false};
static bool rdrand_supported = false;
static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000;
static void RDRandInit()
{
uint32_t eax, ebx, ecx, edx;
if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx & CPUID_F1_ECX_RDRAND)) {
printf("Using RdRand as an additional entropy source\n");
rdrand_supported = true;
}
hwrand_initialized.store(true);
}
#else
static void RDRandInit() {}
#endif
static bool GetHWRand(unsigned char* ent32) {
#if defined(__x86_64__) || defined(__amd64__) || defined(__i386__)
assert(hwrand_initialized.load(std::memory_order_relaxed));
if (rdrand_supported) {
uint8_t ok;
// Not all assemblers support the rdrand instruction, write it in hex.
#ifdef __i386__
for (int iter = 0; iter < 4; ++iter) {
uint32_t r1, r2;
__asm__ volatile (".byte 0x0f, 0xc7, 0xf0;" // rdrand %eax
".byte 0x0f, 0xc7, 0xf2;" // rdrand %edx
"setc %2" :
"=a"(r1), "=d"(r2), "=q"(ok) :: "cc");
if (!ok) return false;
WriteLE32(ent32 + 8 * iter, r1);
WriteLE32(ent32 + 8 * iter + 4, r2);
}
#else
uint64_t r1, r2, r3, r4;
__asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf0, " // rdrand %rax
"0x48, 0x0f, 0xc7, 0xf3, " // rdrand %rbx
"0x48, 0x0f, 0xc7, 0xf1, " // rdrand %rcx
"0x48, 0x0f, 0xc7, 0xf2; " // rdrand %rdx
"setc %4" :
"=a"(r1), "=b"(r2), "=c"(r3), "=d"(r4), "=q"(ok) :: "cc");
if (!ok) return false;
WriteLE64(ent32, r1);
WriteLE64(ent32 + 8, r2);
WriteLE64(ent32 + 16, r3);
WriteLE64(ent32 + 24, r4);
#endif
return true;
}
#endif
return false;
}
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memory_cleanse((void*)&nCounter, sizeof(nCounter));
}
static void RandAddSeedPerfmon()
{
RandAddSeed();
}
/** Fallback: get 32 bytes of system entropy from /dev/urandom. The most
* compatible way to get cryptographic randomness on UNIX-ish platforms.
*/
void GetDevURandom(unsigned char *ent32)
{
int f = open("/dev/urandom", O_RDONLY);
if (f == -1) {
RandFailure();
}
int have = 0;
do {
ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have);
if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) {
close(f);
RandFailure();
}
have += n;
} while (have < NUM_OS_RANDOM_BYTES);
close(f);
}
/** Get 32 bytes of system entropy. */
void GetOSRand(unsigned char *ent32)
{
/* Fall back to /dev/urandom if there is no specific method implemented to
* get system entropy for this OS.
*/
GetDevURandom(ent32);
}
void GetRandBytes(unsigned char* buf, int num)
{
if (RAND_bytes(buf, num) != 1) {
RandFailure();
}
}
static void AddDataToRng(void* data, size_t len);
void RandAddSeedSleep()
{
int64_t nPerfCounter1 = GetPerformanceCounter();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
int64_t nPerfCounter2 = GetPerformanceCounter();
// Combine with and update state
AddDataToRng(&nPerfCounter1, sizeof(nPerfCounter1));
AddDataToRng(&nPerfCounter2, sizeof(nPerfCounter2));
memory_cleanse(&nPerfCounter1, sizeof(nPerfCounter1));
memory_cleanse(&nPerfCounter2, sizeof(nPerfCounter2));
}
static std::mutex cs_rng_state;
static unsigned char rng_state[32] = {0};
static uint64_t rng_counter = 0;
static void AddDataToRng(void* data, size_t len) {
CSHA512 hasher;
hasher.Write((const unsigned char*)&len, sizeof(len));
hasher.Write((const unsigned char*)data, len);
unsigned char buf[64];
{
std::unique_lock<std::mutex> lock(cs_rng_state);
hasher.Write(rng_state, sizeof(rng_state));
hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
++rng_counter;
hasher.Finalize(buf);
memcpy(rng_state, buf + 32, 32);
}
memory_cleanse(buf, 64);
}
void GetStrongRandBytes(unsigned char* out, int num)
{
assert(num <= 32);
CSHA512 hasher;
unsigned char buf[64];
// First source: OpenSSL's RNG
RandAddSeedPerfmon();
GetRandBytes(buf, 32);
hasher.Write(buf, 32);
// Second source: OS RNG
GetOSRand(buf);
hasher.Write(buf, 32);
// Third source: HW RNG, if available.
if (GetHWRand(buf)) {
hasher.Write(buf, 32);
}
// Combine with and update state
{
std::unique_lock<std::mutex> lock(cs_rng_state);
hasher.Write(rng_state, sizeof(rng_state));
hasher.Write((const unsigned char*)&rng_counter, sizeof(rng_counter));
++rng_counter;
hasher.Finalize(buf);
memcpy(rng_state, buf + 32, 32);
}
// Produce output
memcpy(out, buf, num);
memory_cleanse(buf, 64);
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do {
GetRandBytes((unsigned char*)&nRand, sizeof(nRand));
} while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
GetRandBytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
void FastRandomContext::RandomSeed()
{
uint256 seed = GetRandHash();
rng.SetKey(seed.begin(), 32);
requires_seed = false;
}
uint256 FastRandomContext::rand256()
{
if (bytebuf_size < 32) {
FillByteBuffer();
}
uint256 ret;
memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32);
bytebuf_size -= 32;
return ret;
}
std::vector<unsigned char> FastRandomContext::randbytes(size_t len)
{
std::vector<unsigned char> ret(len);
if (len > 0) {
rng.Output(&ret[0], len);
}
return ret;
}
FastRandomContext::FastRandomContext(const uint256& seed) : requires_seed(false), bytebuf_size(0), bitbuf_size(0)
{
rng.SetKey(seed.begin(), 32);
}
bool Random_SanityCheck()
{
uint64_t start = GetPerformanceCounter();
/* This does not measure the quality of randomness, but it does test that
* OSRandom() overwrites all 32 bytes of the output given a maximum
* number of tries.
*/
static const ssize_t MAX_TRIES = 1024;
uint8_t data[NUM_OS_RANDOM_BYTES];
bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */
int num_overwritten;
int tries = 0;
/* Loop until all bytes have been overwritten at least once, or max number tries reached */
do {
memset(data, 0, NUM_OS_RANDOM_BYTES);
GetOSRand(data);
for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
overwritten[x] |= (data[x] != 0);
}
num_overwritten = 0;
for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) {
if (overwritten[x]) {
num_overwritten += 1;
}
}
tries += 1;
} while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES);
if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */
// Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep.
std::this_thread::sleep_for(std::chrono::milliseconds(1));
uint64_t stop = GetPerformanceCounter();
if (stop == start) return false;
// We called GetPerformanceCounter. Use it as entropy.
RAND_add((const unsigned char*)&start, sizeof(start), 1);
RAND_add((const unsigned char*)&stop, sizeof(stop), 1);
return true;
}
FastRandomContext::FastRandomContext(bool fDeterministic) : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0)
{
if (!fDeterministic) {
return;
}
uint256 seed;
rng.SetKey(seed.begin(), 32);
}
void RandomInit()
{
RDRandInit();
}
} // namespace mybitcoin
} // namespace bubblefs | 29.382051 | 123 | 0.641504 | pengdu |
4d75bf01f7abe593b44d5fe7193fe6747ebbf5ab | 1,527 | hpp | C++ | include/bsoid/operators/ImplicitOperator.hpp | yaoyao0821/bsoid_test | 6222653652cf29cc09c1bb2435874573f31a6369 | [
"MIT"
] | null | null | null | include/bsoid/operators/ImplicitOperator.hpp | yaoyao0821/bsoid_test | 6222653652cf29cc09c1bb2435874573f31a6369 | [
"MIT"
] | 2 | 2019-03-13T23:07:52.000Z | 2019-04-29T22:23:25.000Z | include/bsoid/operators/ImplicitOperator.hpp | yaoyao0821/bsoid_test | 6222653652cf29cc09c1bb2435874573f31a6369 | [
"MIT"
] | 1 | 2019-03-15T00:05:54.000Z | 2019-03-15T00:05:54.000Z | #ifndef BSOID_INCLUDE_BSOID_OPERATORS_IMPLICIT_OPERATOR_HPP
#define BSOID_INCLUDE_BSOID_OPERATORS_IMPLICIT_OPERATOR_HPP
#pragma once
#include "Operators.hpp"
#include "bsoid/fields/ImplicitField.hpp"
#include <vector>
namespace bsoid
{
namespace operators
{
class ImplicitOperator : public fields::ImplicitField
{
public:
ImplicitOperator() = default;
virtual ~ImplicitOperator() = default;
ImplicitOperatorPtr makeEmpty() const
{
return ImplicitOperatorPtr(cloneEmpty());
}
atlas::utils::BBox getBBox() const override
{
return box();
}
void insertField(fields::ImplicitFieldPtr const& field)
{
mFields.push_back(field);
}
void insertFields(
std::vector<fields::ImplicitFieldPtr> const& fields)
{
for (auto& field : fields)
{
insertField(field);
}
}
float eval(atlas::math::Point const& p) const override
{
return sdf(p);
}
atlas::math::Normal grad(atlas::math::Point const& p) const override
{
return sdg(p);
}
protected:
virtual ImplicitOperator* cloneEmpty() const = 0;
std::vector<fields::ImplicitFieldPtr> mFields;
};
}
}
#endif | 23.859375 | 80 | 0.525868 | yaoyao0821 |
4d7a56485ae89b97e994beaa97107e7e3b54a0f5 | 1,860 | cpp | C++ | LeetCode/Problems/Algorithms/#1763_LongestNiceSubstring_sol2_divide_and_conquer_with_sliding_window_O(N^2)_time_O(N+52)_extra_space.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#1763_LongestNiceSubstring_sol2_divide_and_conquer_with_sliding_window_O(N^2)_time_O(N+52)_extra_space.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#1763_LongestNiceSubstring_sol2_divide_and_conquer_with_sliding_window_O(N^2)_time_O(N+52)_extra_space.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
private:
int computeMaxLen(const string& S, int startPos, int endPos){
if(startPos >= endPos){
return 0;
}
int lowMask = 0;
int upMask = 0;
for(int i = startPos; i <= endPos; ++i){
if(islower(S[i])){
lowMask |= (1 << (S[i] - 'a'));
}else{
upMask |= (1 << (S[i] - 'A'));
}
}
if(lowMask == upMask){
return endPos - startPos + 1;
}
int maxLen = 0;
for(int i = startPos; i <= endPos; ++i){
if((((lowMask >> (tolower(S[i]) - 'a')) & 1) ^ ((upMask >> (toupper(S[i]) - 'A')) & 1)) == 1){
maxLen = max(computeMaxLen(S, startPos, i - 1), computeMaxLen(S, i + 1, endPos));
break;
}
}
return maxLen;
}
public:
string longestNiceSubstring(string s) {
const int N = s.length();
// divide and conquer
int maxLen = computeMaxLen(s, 0, N - 1);
// sliding window
int startPos = 0;
unordered_map<char, int> count;
for(int i = 0; i < N; ++i){
count[s[i]] += 1;
if(i >= maxLen){
count[s[i - maxLen]] -= 1;
}
if(i >= maxLen - 1){
bool found = true;
for(char c = 'a'; c <= 'z'; ++c){
if((count[c] == 0) != (count[toupper(c)] == 0)){
found = false;
}
}
if(found){
startPos = i - maxLen + 1;
break;
}
}
}
return s.substr(startPos, maxLen);
}
}; | 29.0625 | 107 | 0.355914 | Tudor67 |
4d7bd77449443210324ab9043d27ef0ef5a83bd5 | 6,002 | cpp | C++ | src/memorylayout.cpp | consultorio-molinari/splintermind-attributes | 4dd0a65d1af68c8ee7e7b76d8e52efda22411147 | [
"MIT"
] | null | null | null | src/memorylayout.cpp | consultorio-molinari/splintermind-attributes | 4dd0a65d1af68c8ee7e7b76d8e52efda22411147 | [
"MIT"
] | null | null | null | src/memorylayout.cpp | consultorio-molinari/splintermind-attributes | 4dd0a65d1af68c8ee7e7b76d8e52efda22411147 | [
"MIT"
] | null | null | null | #include <QtCore>
#include "memorylayout.h"
#include "gamedatareader.h"
#include "utils.h"
#include "truncatingfilelogger.h"
#include "dfinstance.h"
MemoryLayout::MemoryLayout(const QString &filename)
: m_filename(filename)
, m_checksum(QString::null)
, m_data(0)
, m_complete(true)
{
TRACE << "Attempting to contruct MemoryLayout from file " << filename;
QFileInfo info(m_filename);
if (info.exists() && info.isReadable()) {
m_data = new QSettings(m_filename, QSettings::IniFormat);
load_data();
} else {
LOGE << m_filename << "could either not be found or not be opened!";
}
}
MemoryLayout::MemoryLayout(const QString & filename, QSettings * data):
m_filename(filename),
m_checksum(QString::null),
m_data(NULL),
m_complete(false)
{
m_data = new QSettings(m_filename, QSettings::IniFormat);
foreach(QString key, data->allKeys()) {
m_data->setValue(key, data->value(key));
}
}
void MemoryLayout::load_data() {
if (!is_valid()) {
LOGE << "Skipping read of invalid memory layout in" << m_filename;
return;
}
// basics (if these are missing, don't read anything else)
m_data->beginGroup("info");
m_checksum = m_data->value("checksum", "UNKNOWN").toString().toLower();
m_game_version = m_data->value("version_name", "UNKNOWN").toString().toLower();
m_complete = m_data->value("complete", true).toBool();
m_data->endGroup();
read_group("addresses", m_addresses);
read_group("offsets", m_offsets);
read_group("dwarf_offsets", m_dwarf_offsets);
read_group("job_details", m_job_details);
read_group("soul_details", m_soul_details);
read_group("squad_offsets", m_squad_offsets);
read_group("word_offsets", m_word_offsets);
read_group("race_offsets", m_race_offsets);
read_group("caste_offsets", m_caste_offsets);
read_group("hist_figure_offsets", m_hist_fig_offsets);
read_group("hist_entity_offsets", m_hist_entity_offsets);
read_group("plant_offsets", m_plant_offsets);
read_group("material_offsets", m_material_offsets);
read_group("weapon_subtype_offsets", m_weapon_subtype_offsets);
read_group("armor_subtype_offsets", m_armor_subtype_offsets);
read_group("item_subtype_offsets", m_item_subtype_offsets);
read_group("item_offsets", m_item_offsets);
read_group("item_filter_offsets", m_item_filter_offsets);
read_group("descriptor_offsets", m_descriptor_offsets);
read_group("general_ref_offsets", m_general_ref_offsets);
read_group("health_offsets", m_health_offsets);
read_group("unit_wound_offsets", m_unit_wound_offsets);
read_group("syndrome_offsets", m_syndrome_offsets);
// flags
int flag_count = m_data->beginReadArray("valid_flags_1");
for (int i = 0; i < flag_count; ++i) {
m_data->setArrayIndex(i);
m_valid_flags_1.insert(read_hex("value"),
m_data->value("name", "UNKNOWN VALID FLAG 1").toString());
}
m_data->endArray();
flag_count = m_data->beginReadArray("invalid_flags_1");
for (int i = 0; i < flag_count; ++i) {
m_data->setArrayIndex(i);
m_invalid_flags_1.insert(read_hex("value"),
m_data->value("name", "UNKNOWN INVALID FLAG 1").toString());
}
m_data->endArray();
flag_count = m_data->beginReadArray("valid_flags_2");
//LOGD << "valid_flags_2 count: " << flag_count;
for (int i = 0; i < flag_count; ++i) {
m_data->setArrayIndex(i);
m_valid_flags_2.insert(read_hex("value"),
m_data->value("name", "UNKNOWN VALID FLAG 2").toString());
}
m_data->endArray();
flag_count = m_data->beginReadArray("invalid_flags_2");
for (int i = 0; i < flag_count; ++i) {
m_data->setArrayIndex(i);
m_invalid_flags_2.insert(read_hex("value"),
m_data->value("name", "UNKNOWN INVALID FLAG 2").toString());
}
m_data->endArray();
flag_count = m_data->beginReadArray("invalid_flags_3");
for (int i = 0; i < flag_count; ++i) {
m_data->setArrayIndex(i);
m_invalid_flags_3.insert(read_hex("value"),
m_data->value("name", "UNKNOWN INVALID FLAG 3").toString());
}
m_data->endArray();
}
uint MemoryLayout::read_hex(QString key) {
bool ok;
QString data = m_data->value(key, -1).toString();
uint val = data.toUInt(&ok, 16);
return val;
}
bool MemoryLayout::is_valid() {
return m_data != NULL && m_data->contains("info/checksum")
&& m_data->contains("info/version_name");
}
void MemoryLayout::read_group(const QString &group, AddressHash &map) {
m_data->beginGroup(group);
foreach(QString k, m_data->childKeys()) {
map.insert(k, read_hex(k));
}
m_data->endGroup();
}
uint MemoryLayout::string_buffer_offset() {
return m_offsets.value("string_buffer_offset", DFInstance::STRING_BUFFER_OFFSET);
}
uint MemoryLayout::string_length_offset() {
return string_buffer_offset() +
m_offsets.value("string_length_offset", DFInstance::STRING_LENGTH_OFFSET);
}
uint MemoryLayout::string_cap_offset() {
return string_buffer_offset() +
m_offsets.value("string_cap_offset", DFInstance::STRING_CAP_OFFSET);
}
void MemoryLayout::set_address(const QString & key, uint value) {
m_data->setValue(key, hexify(value));
}
void MemoryLayout::set_game_version(const QString & value) {
m_game_version = value;
m_data->setValue("info/version_name", m_game_version);
}
void MemoryLayout::set_checksum(const QString & checksum) {
m_checksum = checksum;
m_data->setValue("info/checksum", m_checksum);
}
void MemoryLayout::save_data() {
m_data->sync();
}
void MemoryLayout::set_complete() {
m_complete = true;
m_data->setValue("info/complete", "true");
}
| 32.619565 | 87 | 0.656281 | consultorio-molinari |
4d7d66c6ff3c229ab2263cd57b62255907751b1c | 4,942 | cpp | C++ | lesson_5/RC4.cpp | FilippoNevi/Advanced-Computer-Architectures | 9d03ea9491df99d863c2e9777ed04a68df2cfd40 | [
"BSD-3-Clause"
] | null | null | null | lesson_5/RC4.cpp | FilippoNevi/Advanced-Computer-Architectures | 9d03ea9491df99d863c2e9777ed04a68df2cfd40 | [
"BSD-3-Clause"
] | null | null | null | lesson_5/RC4.cpp | FilippoNevi/Advanced-Computer-Architectures | 9d03ea9491df99d863c2e9777ed04a68df2cfd40 | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <omp.h>
#include <unistd.h>
#include "Timer.hpp"
void key_scheduling_alg(unsigned char* S,
const unsigned char* key,
const int key_length) {
for (int i = 0; i < 256; ++i)
S[i] = i;
int j = 0;
for (int i = 0; i < 256; ++i) {
j = (j + S[i] + key[i % key_length]) % 256;
std::swap(S[i], S[j]);
}
}
void pseudo_random_gen(unsigned char* S,
unsigned char* stream,
int input_length) {
for (int x = 0; x < input_length; ++x) {
int i = (i + 1) % 256;
int j = (j + S[i]) % 256;
std::swap(S[i], S[j]);
stream[x] = S[(S[i] + S[j]) % 256];
}
}
bool chech_hex(const unsigned char* cipher_text,
const unsigned char* stream,
const int key_length) {
for (int i = 0; i < key_length; ++i) {
if (cipher_text[i] != stream[i])
return false;
}
return true;
}
void print_hex(const unsigned char* text, const int length, const char* str) {
std::cout << std::endl << std::left << std::setw(15) << str;
for (int i = 0; i < length; ++i)
std::cout << std::hex << std::uppercase << (int) text[i] << ' ';
std::cout << std::dec << std::endl;
}
const int bitLength = 24;
const int key_length = bitLength / 8;
int main() {
using namespace timer;
unsigned char S[256],
stream[key_length],
key[key_length] = {'K','e','y'},
Plaintext[key_length] = {'j','j','j'},
cipher_text[key_length] = {0xB, 0xC7, 0x85};
print_hex(Plaintext, key_length, "Plaintext:");
print_hex(cipher_text, key_length, "cipher_text:");
print_hex(key, key_length, "Key:");
//sequential//
// -------------------------------------------------------------------------
Timer<HOST> TM_seq;
TM_seq.start();
std::cout << "Sequential Execution\n";
key_scheduling_alg(S, key, key_length);
pseudo_random_gen(S, stream, key_length);
print_hex(stream, key_length, "PRGA Stream:");
for (int i = 0; i < key_length; ++i)
stream[i] = stream[i] ^ Plaintext[i]; // XOR
print_hex(stream, key_length, "XOR:");
if (chech_hex(cipher_text, stream, key_length))
std::cout << "check ok!\n";
std::cout << "Cracking..." << std::endl;
// --------------------- CRACKING ------------------------------------------
std::fill(key, key + key_length, 0);
bool find = false;
for (int k = 0; k < (1<<24); ++k) {
key_scheduling_alg(S, key, key_length);
pseudo_random_gen(S, stream, key_length);
for (int i = 0; i < key_length; ++i)
stream[i] = stream[i] ^ Plaintext[i]; // XOR
if (chech_hex(cipher_text, stream, key_length)) {
std::cout << " <> CORRECT\n";
find=true;
break;
}
int next = 0;
while (key[next] == 255) {
key[next] = 0;
++next;
}
++key[next];
}
if(!find){
std::cout << "ERROR!! key not found\n";
}
TM_seq.stop();
TM_seq.print("Sequential Time");
//end sequential
Timer<HOST> TM_par;
//start parallel
std::cout << "\nParallel Execution\n";
TM_par.start();
key_scheduling_alg(S, key, key_length);
pseudo_random_gen(S, stream, key_length);
print_hex(stream, key_length, "PRGA Stream:");
for (int i = 0; i < key_length; ++i)
stream[i] = stream[i] ^ Plaintext[i]; // XOR
print_hex(stream, key_length, "XOR:");
if (chech_hex(cipher_text, stream, key_length))
std::cout << "check ok!\n";
std::cout << "Cracking..." << std::endl;
// --------------------- CRACKING ------------------------------------------
std::fill(key, key + key_length, 0);
find = false;
#pragma omp parallel for
for (int k = 0; k < (1<<24); ++k) {
if(!find){
key_scheduling_alg(S, key, key_length);
pseudo_random_gen(S, stream, key_length);
for (int i = 0; i < key_length; ++i)
stream[i] = stream[i] ^ Plaintext[i]; // XOR
if (chech_hex(cipher_text, stream, key_length)) {
std::cout << " <> CORRECT\n";
find=true;
}
int next = 0;
while (key[next] == 255) {
key[next] = 0;
++next;
}
++key[next];
}
}
if(!find){
std::cout << "ERROR!! key not found\n";
}
TM_par.stop();
TM_par.print("Parallel Time");
//end parallel
std::cout << TM_seq.duration() << ";" << TM_par.duration() << ";" << TM_seq.duration() / TM_par.duration() << std::endl;
return 0;
}
| 27.764045 | 124 | 0.486443 | FilippoNevi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.