hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
78a04353da2e028bd85202a0a06439ec43ce59b5 | 12,502 | cc | C++ | vendor_libs/test_vendor_lib/src/event_packet.cc | digi-embedded/android_platform_system_bt | 635ddc5671274697ecfc9d4d44881f23d73a4cd0 | [
"Apache-2.0"
] | null | null | null | vendor_libs/test_vendor_lib/src/event_packet.cc | digi-embedded/android_platform_system_bt | 635ddc5671274697ecfc9d4d44881f23d73a4cd0 | [
"Apache-2.0"
] | null | null | null | vendor_libs/test_vendor_lib/src/event_packet.cc | digi-embedded/android_platform_system_bt | 635ddc5671274697ecfc9d4d44881f23d73a4cd0 | [
"Apache-2.0"
] | 2 | 2019-05-30T08:37:28.000Z | 2019-10-01T16:39:33.000Z | //
// Copyright 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#define LOG_TAG "event_packet"
#include "event_packet.h"
#include "osi/include/log.h"
#include "stack/include/hcidefs.h"
using std::vector;
namespace test_vendor_lib {
EventPacket::EventPacket(uint8_t event_code)
: Packet(DATA_TYPE_EVENT, {event_code}) {}
uint8_t EventPacket::GetEventCode() const { return GetHeader()[0]; }
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.1
std::unique_ptr<EventPacket> EventPacket::CreateInquiryCompleteEvent(
uint8_t status) {
std::unique_ptr<EventPacket> evt_ptr =
std::unique_ptr<EventPacket>(new EventPacket(HCI_INQUIRY_COMP_EVT));
CHECK(evt_ptr->AddPayloadOctets1(status));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.14
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteEvent(
uint16_t command_opcode, const vector<uint8_t>& event_return_parameters) {
std::unique_ptr<EventPacket> evt_ptr =
std::unique_ptr<EventPacket>(new EventPacket(HCI_COMMAND_COMPLETE_EVT));
CHECK(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
CHECK(evt_ptr->AddPayloadOctets2(command_opcode));
CHECK(evt_ptr->AddPayloadOctets(event_return_parameters.size(),
event_return_parameters));
return evt_ptr;
}
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteOnlyStatusEvent(
uint16_t command_opcode, uint8_t status) {
std::unique_ptr<EventPacket> evt_ptr =
std::unique_ptr<EventPacket>(new EventPacket(HCI_COMMAND_COMPLETE_EVT));
CHECK(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
CHECK(evt_ptr->AddPayloadOctets2(command_opcode));
CHECK(evt_ptr->AddPayloadOctets1(status));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.7.15
std::unique_ptr<EventPacket> EventPacket::CreateCommandStatusEvent(
uint8_t status, uint16_t command_opcode) {
std::unique_ptr<EventPacket> evt_ptr =
std::unique_ptr<EventPacket>(new EventPacket(HCI_COMMAND_STATUS_EVT));
CHECK(evt_ptr->AddPayloadOctets1(status));
CHECK(evt_ptr->AddPayloadOctets1(1)); // num_hci_command_packets
CHECK(evt_ptr->AddPayloadOctets2(command_opcode));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.3.12
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteReadLocalName(
uint8_t status, const std::string& local_name) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(HCI_READ_LOCAL_NAME,
status);
for (size_t i = 0; i < local_name.length(); i++)
CHECK(evt_ptr->AddPayloadOctets1(local_name[i]));
CHECK(evt_ptr->AddPayloadOctets1(0)); // Null terminated
for (size_t i = 0; i < 248 - local_name.length() - 1; i++)
CHECK(evt_ptr->AddPayloadOctets1(0xFF));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.1
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteReadLocalVersionInformation(
uint8_t status, uint8_t hci_version, uint16_t hci_revision,
uint8_t lmp_pal_version, uint16_t manufacturer_name,
uint16_t lmp_pal_subversion) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_READ_LOCAL_VERSION_INFO, status);
CHECK(evt_ptr->AddPayloadOctets1(hci_version));
CHECK(evt_ptr->AddPayloadOctets2(hci_revision));
CHECK(evt_ptr->AddPayloadOctets1(lmp_pal_version));
CHECK(evt_ptr->AddPayloadOctets2(manufacturer_name));
CHECK(evt_ptr->AddPayloadOctets2(lmp_pal_subversion));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.2
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteReadLocalSupportedCommands(
uint8_t status, const vector<uint8_t>& supported_commands) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_READ_LOCAL_SUPPORTED_CMDS, status);
CHECK(evt_ptr->AddPayloadOctets(64, supported_commands));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.4
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteReadLocalExtendedFeatures(
uint8_t status, uint8_t page_number, uint8_t maximum_page_number,
uint64_t extended_lmp_features) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_READ_LOCAL_EXT_FEATURES, status);
CHECK(evt_ptr->AddPayloadOctets1(page_number));
CHECK(evt_ptr->AddPayloadOctets1(maximum_page_number));
CHECK(evt_ptr->AddPayloadOctets8(extended_lmp_features));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.5
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteReadBufferSize(
uint8_t status, uint16_t hc_acl_data_packet_length,
uint8_t hc_synchronous_data_packet_length,
uint16_t hc_total_num_acl_data_packets,
uint16_t hc_total_synchronous_data_packets) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(HCI_READ_BUFFER_SIZE,
status);
CHECK(evt_ptr->AddPayloadOctets2(hc_acl_data_packet_length));
CHECK(evt_ptr->AddPayloadOctets1(hc_synchronous_data_packet_length));
CHECK(evt_ptr->AddPayloadOctets2(hc_total_num_acl_data_packets));
CHECK(evt_ptr->AddPayloadOctets2(hc_total_synchronous_data_packets));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.6
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteReadBdAddr(
uint8_t status, const BtAddress& address) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(HCI_READ_BD_ADDR,
status);
CHECK(evt_ptr->AddPayloadBtAddress(address));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.4.8
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteReadLocalSupportedCodecs(
uint8_t status, const vector<uint8_t>& supported_codecs,
const vector<uint32_t>& vendor_specific_codecs) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_READ_LOCAL_SUPPORTED_CODECS, status);
CHECK(evt_ptr->AddPayloadOctets(supported_codecs.size(), supported_codecs));
for (size_t i = 0; i < vendor_specific_codecs.size(); i++)
CHECK(evt_ptr->AddPayloadOctets4(vendor_specific_codecs[i]));
return evt_ptr;
}
std::unique_ptr<EventPacket> EventPacket::CreateInquiryResultEvent(
const BtAddress& address,
const PageScanRepetitionMode page_scan_repetition_mode,
uint32_t class_of_device, uint16_t clock_offset) {
std::unique_ptr<EventPacket> evt_ptr =
std::unique_ptr<EventPacket>(new EventPacket(HCI_INQUIRY_RESULT_EVT));
CHECK(evt_ptr->AddPayloadOctets1(1)); // Start with a single response
CHECK(evt_ptr->AddPayloadBtAddress(address));
CHECK(evt_ptr->AddPayloadOctets1(page_scan_repetition_mode));
CHECK(evt_ptr->AddPayloadOctets2(kReservedZero));
CHECK(evt_ptr->AddPayloadOctets3(class_of_device));
CHECK(!(clock_offset & 0x8000));
CHECK(evt_ptr->AddPayloadOctets2(clock_offset));
return evt_ptr;
}
void EventPacket::AddInquiryResult(
const BtAddress& address,
const PageScanRepetitionMode page_scan_repetition_mode,
uint32_t class_of_device, uint16_t clock_offset) {
CHECK(GetEventCode() == HCI_INQUIRY_RESULT_EVT);
CHECK(IncrementPayloadCounter(1)); // Increment the number of responses
CHECK(AddPayloadBtAddress(address));
CHECK(AddPayloadOctets1(page_scan_repetition_mode));
CHECK(AddPayloadOctets2(kReservedZero));
CHECK(AddPayloadOctets3(class_of_device));
CHECK(!(clock_offset & 0x8000));
CHECK(AddPayloadOctets2(clock_offset));
}
std::unique_ptr<EventPacket> EventPacket::CreateExtendedInquiryResultEvent(
const BtAddress& address,
const PageScanRepetitionMode page_scan_repetition_mode,
uint32_t class_of_device, uint16_t clock_offset, uint8_t rssi,
const vector<uint8_t>& extended_inquiry_response) {
std::unique_ptr<EventPacket> evt_ptr = std::unique_ptr<EventPacket>(
new EventPacket(HCI_EXTENDED_INQUIRY_RESULT_EVT));
CHECK(evt_ptr->AddPayloadOctets1(1)); // Always contains a single response
CHECK(evt_ptr->AddPayloadBtAddress(address));
CHECK(evt_ptr->AddPayloadOctets1(page_scan_repetition_mode));
CHECK(evt_ptr->AddPayloadOctets1(kReservedZero));
CHECK(evt_ptr->AddPayloadOctets3(class_of_device));
CHECK(!(clock_offset & 0x8000));
CHECK(evt_ptr->AddPayloadOctets2(clock_offset));
CHECK(evt_ptr->AddPayloadOctets1(rssi));
CHECK(evt_ptr->AddPayloadOctets(extended_inquiry_response.size(),
extended_inquiry_response));
while (evt_ptr->AddPayloadOctets1(0xff))
; // Fill packet
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.2
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteLeReadBufferSize(
uint8_t status, uint16_t hc_le_data_packet_length,
uint8_t hc_total_num_le_data_packets) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_BLE_READ_BUFFER_SIZE, status);
CHECK(evt_ptr->AddPayloadOctets2(hc_le_data_packet_length));
CHECK(evt_ptr->AddPayloadOctets1(hc_total_num_le_data_packets));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.3
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteLeReadLocalSupportedFeatures(
uint8_t status, uint64_t le_features) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_BLE_READ_LOCAL_SPT_FEAT, status);
CHECK(evt_ptr->AddPayloadOctets8(le_features));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.14
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteLeReadWhiteListSize(uint8_t status,
uint8_t white_list_size) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_BLE_READ_WHITE_LIST_SIZE, status);
CHECK(evt_ptr->AddPayloadOctets8(white_list_size));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.23
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteLeRand(
uint8_t status, uint64_t random_val) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(HCI_BLE_RAND, status);
CHECK(evt_ptr->AddPayloadOctets8(random_val));
return evt_ptr;
}
// Bluetooth Core Specification Version 4.2, Volume 2, Part E, Section 7.8.27
std::unique_ptr<EventPacket>
EventPacket::CreateCommandCompleteLeReadSupportedStates(uint8_t status,
uint64_t le_states) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(
HCI_BLE_READ_SUPPORTED_STATES, status);
CHECK(evt_ptr->AddPayloadOctets8(le_states));
return evt_ptr;
}
// Vendor-specific commands (see hcidefs.h)
std::unique_ptr<EventPacket> EventPacket::CreateCommandCompleteLeVendorCap(
uint8_t status, const vector<uint8_t>& vendor_cap) {
std::unique_ptr<EventPacket> evt_ptr =
EventPacket::CreateCommandCompleteOnlyStatusEvent(HCI_BLE_VENDOR_CAP_OCF,
status);
CHECK(evt_ptr->AddPayloadOctets(vendor_cap.size(), vendor_cap));
return evt_ptr;
}
} // namespace test_vendor_lib
| 38 | 80 | 0.756199 | [
"vector"
] |
78a0a26d23b5bbfd2defc613578e99e3578f6064 | 2,063 | cpp | C++ | src/xrEngine/Environment_render.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrEngine/Environment_render.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrEngine/Environment_render.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | #include "stdafx.h"
#pragma hdrstop
#include "Environment.h"
#ifndef _EDITOR
#include "Render.h"
#endif
#include "xr_efflensflare.h"
#include "Rain.h"
#include "thunderbolt.h"
#ifndef _EDITOR
#include "IGame_Level.h"
#endif
//-----------------------------------------------------------------------------
// Environment render
//-----------------------------------------------------------------------------
void CEnvironment::RenderSky()
{
#ifndef _EDITOR
if (0 == g_pGameLevel)
return;
#endif
m_pRender->RenderSky(*this);
}
void CEnvironment::RenderClouds()
{
#ifndef _EDITOR
if (0 == g_pGameLevel)
return;
#endif
// draw clouds
if (fis_zero(CurrentEnv->clouds_color.w, EPS_L))
return;
m_pRender->RenderClouds(*this);
}
void CEnvironment::RenderFlares()
{
#ifndef _EDITOR
if (0 == g_pGameLevel)
return;
#endif
// 1
eff_LensFlare->Render(false, true, true);
}
void CEnvironment::RenderLast()
{
#ifndef _EDITOR
if (0 == g_pGameLevel)
return;
#endif
// 2
eff_Rain->Render();
eff_Thunderbolt->Render();
}
void CEnvironment::OnDeviceCreate()
{
m_pRender->OnDeviceCreate();
// weathers
for (auto& cycle : WeatherCycles)
{
for (auto& envDescriptor : cycle.second)
envDescriptor->on_device_create();
}
// effects
for (auto& cycle : WeatherFXs)
{
for (auto& envDescriptor : cycle.second)
envDescriptor->on_device_create();
}
Invalidate();
OnFrame();
}
void CEnvironment::OnDeviceDestroy()
{
m_pRender->OnDeviceDestroy();
// weathers
for (auto& cycle : WeatherCycles)
{
for (auto& envDescriptor : cycle.second)
envDescriptor->on_device_destroy();
}
// effects
for (auto& cycle : WeatherFXs)
{
for (auto& envDescriptor : cycle.second)
envDescriptor->on_device_destroy();
}
CurrentEnv->destroy();
}
#ifdef _EDITOR
void CEnvironment::ED_Reload()
{
OnDeviceDestroy();
OnDeviceCreate();
}
#endif
| 18.096491 | 79 | 0.580708 | [
"render"
] |
78a5d19aa51e1afff0e664d17dcd6a3121b60cd3 | 18,132 | cpp | C++ | plugins/DataInterfacePlugin/src/base/datareader/TcopsVHFAscii.cpp | rockstorm101/GMAT | 00b6b61a40560c095da3d83dab4ab1e9157f01c7 | [
"Apache-2.0"
] | 1 | 2018-09-18T07:09:36.000Z | 2018-09-18T07:09:36.000Z | plugins/DataInterfacePlugin/src/base/datareader/TcopsVHFAscii.cpp | rockstorm101/GMAT | 00b6b61a40560c095da3d83dab4ab1e9157f01c7 | [
"Apache-2.0"
] | null | null | null | plugins/DataInterfacePlugin/src/base/datareader/TcopsVHFAscii.cpp | rockstorm101/GMAT | 00b6b61a40560c095da3d83dab4ab1e9157f01c7 | [
"Apache-2.0"
] | 2 | 2020-06-18T04:45:30.000Z | 2021-07-20T02:11:54.000Z | //$Id$
//------------------------------------------------------------------------------
// TcopsVHFAscii
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under the FDSS
// contract, Task Order 28
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: May 3, 2013
/**
* Implementation of the TCOPS Vector Hold File ASCII reader
*/
//------------------------------------------------------------------------------
#include "TcopsVHFAscii.hpp"
#include "InterfaceException.hpp"
#include "StringUtil.hpp"
#include "DateUtil.hpp" // To get the ModJulian date
#include "MessageInterface.hpp"
#include <sstream>
//#define DEBUG_FILEREAD
//------------------------------------------------------------------------------
// TcopsVHFAscii(const std::string& theName)
//------------------------------------------------------------------------------
/**
* Constructor
*
* @param theName Name of this reader
*/
//------------------------------------------------------------------------------
TcopsVHFAscii::TcopsVHFAscii(const std::string& theName) :
TcopsVHFData ("TVHF_ASCII", theName),
isDumpFile (false),
utcEpoch (0.0)
{
// Set up the engine accessor fields
objectTypeNames.push_back("TVHF_ASCII");
objectTypeNames.push_back("TcopsVHFAscii");
for (Integer i = 0; i < 7; ++i)
startVector[i] = 0.0;
}
//------------------------------------------------------------------------------
// ~TcopsVHFAscii()
//------------------------------------------------------------------------------
/**
* Destructor
*/
//------------------------------------------------------------------------------
TcopsVHFAscii::~TcopsVHFAscii()
{
}
//------------------------------------------------------------------------------
// TcopsVHFAscii(const TcopsVHFAscii& vhf) :
//------------------------------------------------------------------------------
/**
* Copy constructor
*
* @param vhf The reader copied to make the new one
*/
//------------------------------------------------------------------------------
TcopsVHFAscii::TcopsVHFAscii(const TcopsVHFAscii& vhf) :
TcopsVHFData (vhf),
isDumpFile (vhf.isDumpFile),
utcEpoch (0.0)
{
for (Integer i = 0; i < 7; ++i)
startVector[i] = 0.0;
}
//------------------------------------------------------------------------------
// TcopsVHFAscii& operator=(const TcopsVHFAscii& vhf)
//------------------------------------------------------------------------------
/**
* Assignment operator
*
* @param vhf The reader copied into this one
*
* @return This reader, set to match vhf
*/
//------------------------------------------------------------------------------
TcopsVHFAscii& TcopsVHFAscii::operator=(const TcopsVHFAscii& vhf)
{
if (this == &vhf)
{
TcopsVHFData::operator=(vhf);
isDumpFile = vhf.isDumpFile;
for (Integer i = 0; i < 7; ++i)
startVector[i] = 0.0;
utcEpoch = 0.0;
}
return *this;
}
//------------------------------------------------------------------------------
// GmatBase* Clone() const
//------------------------------------------------------------------------------
/**
* Method to make a publicly identiccal copy of this reader
*
* @return The copy
*/
//------------------------------------------------------------------------------
GmatBase* TcopsVHFAscii::Clone() const
{
return new TcopsVHFAscii(*this);
}
//------------------------------------------------------------------------------
// bool ReadData()
//------------------------------------------------------------------------------
/**
* The method that actually reads in all of the data
*
* @return true if the read succeeds, meaning that the file is a TVHF and it
* contained at least one data element that we requested
*/
//------------------------------------------------------------------------------
bool TcopsVHFAscii::ReadData()
{
#ifdef DEBUG_FILEREAD
MessageInterface::ShowMessage("TcopsVHFAscii::ReadData() entered\n");
#endif
bool retval = false;
if (clearOnRead)
{
realData.clear();
rvector6Data.clear();
stringData.clear();
for (Integer i = 0; i < 7; ++i)
startVector[i] = 0.0;
}
if (theStream)
{
std::string theLine;
Integer count = 0, blockCount = 0;
bool finished = false;
bool headerFound = false;
dataBuffer.clear();
while (!finished)
{
if (ReadLine(theLine))
{
++count;
#ifdef DEBUG_FILEREAD
MessageInterface::ShowMessage("%d: \"%s\"\n", count,
theLine.c_str());
#endif
// Skip blank lines
if (theLine != "")
{
if (!headerFound)
{
// Don't do any extra processing
headerFound = CheckForHeader(theLine);
if (headerFound)
ManageStartData();
else
dataBuffer.push_back(theLine);
}
else
{
if (!CheckForBlockBoundary(theLine))
{
dataBuffer.push_back(theLine);
}
else
{
++blockCount;
if (blockCount > 1)
{
// Put the logic here to see if we are at the requested
// block; for now, we just keep the first block
finished = true;
}
}
}
}
}
else
// ReadLine returns false on EOF
finished = true;
// The header line must occur in the first 100 lines of the file
if ((count > 100) && !headerFound)
finished = true;
}
// Now that the file has been read, parse the data for the desired fields
retval = ParseDataBlock();
BuildOriginName();
BuildCSName();
dataReady = retval;
}
#ifdef DEBUG_FILEREAD
else
MessageInterface::ShowMessage("TcopsVHFAscii::ReadData(): The data "
"stream was not set\n");
#endif
return retval;
}
//------------------------------------------------------------------------------
// bool CheckForHeader(const std::string& theLine)
//------------------------------------------------------------------------------
/**
* Checks the header to see if the file is a VHF dump
*
* VHF dumps are identified by a specific string in the text od the file. This
* method checks the current line to see if it contains that string.
* In addition, it uses the detected string to identify if the file is an
* unedited dump file or a Task 9 edited file, and sets the isDumpFile flag true
* for the unedited version.
*
* For task 9 files, the data at the top of the file is loaded into the
* startVector array. Those data are compared to the parsed out data in
* ParseDataBlock() and, if different, post a warning message.
*
* @param theLine The line that is being checked to see if the file is a VHF
*
* @return true if a header line was detected, false if not
*/
//------------------------------------------------------------------------------
bool TcopsVHFAscii::CheckForHeader(const std::string& theLine)
{
bool isHeader = false;
std::string upperLine = theLine;
transform(upperLine.begin(), upperLine.end(), upperLine.begin(), toupper);
// Unedited dump file
if (upperLine.find("TCOPS VECTOR HOLD FILE DUMP PROGRAM") !=
std::string::npos)
{
isDumpFile = true;
isHeader = true;
}
// Task 9 version
if (upperLine.find("TVHF ELEMENT SET SUMMARY") != std::string::npos)
isHeader = true;
return isHeader;
}
//------------------------------------------------------------------------------
// bool TcopsVHFAscii::CheckForBlockBoundary(const std::string& theLine)
//------------------------------------------------------------------------------
/**
* Identifies block boundaries for the unedited TVHF.
*
* @param theLine The current line from the file
*
* @return true if the block header was found, false if not
*/
//------------------------------------------------------------------------------
bool TcopsVHFAscii::CheckForBlockBoundary(const std::string& theLine)
{
bool retval = false;
// The unedited dump file starts each block with a block header; other
// formats just read to the end
if (isDumpFile)
{
std::string upperLine = theLine;
transform(upperLine.begin(), upperLine.end(), upperLine.begin(), toupper);
if (upperLine.find("LONG REPORT OF THE TCOPS VECTOR HOLD FILE") !=
std::string::npos)
retval = true;
}
return retval;
}
//------------------------------------------------------------------------------
// void ManageStartData()
//------------------------------------------------------------------------------
/**
* Processes data found before the line that identified this file as a TVFH
*
* The data parsed here is the initial data vector in a Task 9 formatted file.
* At his time there is no other pre-header information processed.
*/
//------------------------------------------------------------------------------
void TcopsVHFAscii::ManageStartData()
{
// Task 9 files have the isDumpFile flag set false
if (!isDumpFile)
{
// Fill in the starting vector, assumed to be first 7 lines of the file
Real value;
Integer errorCode;
if (dataBuffer.size() >= 7)
{
for (Integer i = 0; i < 7; ++i)
if (GmatStringUtil::IsValidReal(dataBuffer[i], value, errorCode))
startVector[i] = value;
else
{
throw InterfaceException("The Task 9 TVHF \"" + filename +
"\" initial vector contains invalid data in the element \"" +
dataBuffer[i] + "\"");
}
}
else
throw InterfaceException("The Task 9 TVHF \"" + filename +
"\" does not contain an initial vector");
#ifdef DEBUG_FILEREAD
MessageInterface::ShowMessage("Code 9 file detected with initial "
"data:\n");
for (Integer i = 0; i < 7; ++i)
MessageInterface::ShowMessage(" %16lf\n", startVector[i]);
#endif
}
}
//------------------------------------------------------------------------------
// bool ParseDataBlock()
//------------------------------------------------------------------------------
/**
* Pulls data from a loaded data block
*
* @return true on success, false on failure
*/
//------------------------------------------------------------------------------
bool TcopsVHFAscii::ParseDataBlock()
{
bool retval = false;
for (UnsignedInt i = 0; i < supportedFields.size(); ++i)
{
std::string theField = supportedFields[i];
if (readAllSupportedFields || (find(selectedFields.begin(),
selectedFields.end(), theField) != selectedFields.end()))
{
// Read the data block looking for a file string match
for (UnsignedInt i = 0; i < dataBuffer.size(); ++i)
{
if (dataBuffer[i].find(fileStringMap[theField])!=std::string::npos)
{
switch (dataType[theField])
{
case READER_REAL:
if (ParseRealValue(i, theField))
retval = true;;
break;
case READER_RVECTOR6:
{
// Set up for the Cartesian State scan
StringArray theIds;
theIds.push_back("X "); // ' ' to distinguish from XDOT,
theIds.push_back("Y "); // YDOT, and ZDOT
theIds.push_back("Z ");
theIds.push_back("XDOT");
theIds.push_back("YDOT");
theIds.push_back("ZDOT");
// And find it
if (ParseRvector6Value(i, theField, theIds))
retval = true;
}
break;
case READER_STRING:
case READER_TIMESTRING:
if (ParseStringValue(i, theField))
{
if (dataType[theField] == READER_TIMESTRING)
ParseTime(theField);
retval = true;
}
break;
default:
// Skip the other types (basically the subtypes)
break;
}
}
}
}
}
return retval;
}
//------------------------------------------------------------------------------
// void ParseTime(std::string& theField)
//------------------------------------------------------------------------------
/**
* Special handler for the time data in the TVHF
*
* @param theField The field identifier for the string containing epoch data
*/
//------------------------------------------------------------------------------
void TcopsVHFAscii::ParseTime(std::string& theField)
{
// Only process if the field is in the string map
if (stringData.find(theField) != stringData.end())
{
std::stringstream theData;
theData << stringData[theField];
#ifdef DEBUG_FILEREAD
MessageInterface::ShowMessage(" Raw data: \"%s\" stream data: "
"\"%s\"\n", stringData[theField].c_str(), theData.str().c_str());
#endif
Integer year, month, day, hour, minute;
Real second;
theData >> year >> month >> day >> hour >> minute >> second;
if (year < 50)
year += 2000;
else if (year < 100)
year += 1900;
// Validate the ranges
std::stringstream errstream;
if (year < 1950)
errstream << " The specified year, " << year << ", is not valid.\n";
if ((month < 1) || (month > 12))
errstream << " The specified month, " << month
<< ", is not valid; it must be between 1 and 12.\n";
if ((day < 1) || (day > 31))
errstream << " The specified day of month, " << day << ", is not valid.\n";
else
{
if (month == 2)
{
if (day > 29)
errstream << " The specified day of month, " << day << ", is not "
"valid for month " << month << ".\n";
else if (day == 29)
{
if (year % 4 != 0)
errstream << " The specified day of month, " << day
<< ", is not valid for month " << month
<< "in the year " << year << ".\n";
}
}
if ((month == 4) || (month == 6) || (month == 9) || (month == 11))
if (day > 30)
errstream << " The specified day of month, " << day
<< ", is not valid for month " << month << ".\n";
}
if ((hour < 0) || (hour > 24))
errstream << " The specified hour of day, " << hour
<< ", is not valid[ it must be between 0 and 24.\n";
else
if (((minute > 0) || (second > 0.0)) && (hour == 24))
errstream << " The specified hour of day, " << hour
<< ", is not valid with non-zero minutes "
"or seconds.\n";
if ((minute < 0) || (minute > 60))
errstream << " The specified number of minutes, " << minute
<< ", is not valid; it must be between 0 and 60.\n";
else
if ((minute == 60) && (second > 0.0))
errstream << " The specified number of minutes, " << minute
<< ", is not valid with non-zero seconds.\n";
if ((second < 0.0) || (second > 60.5))
errstream << " The specified number of seconds, " << second
<< ", is not valid; it must be between 0 and 60.5\n";
if (errstream.str().length() > 0)
throw InterfaceException("Error parsing the epoch data from the data file " + filename +
":\n" + errstream.str());
utcEpoch = ModifiedJulianDate(year,month,day,hour,minute,second);
realData[theField] = utcEpoch;
dataLoaded[theField] = true;
#ifdef DEBUG_FILEREAD
MessageInterface::ShowMessage(" %s is at [%d %d %d %d %d %lf] = "
"%17.12lf\n", theField.c_str(), year, month, day, hour,
minute, second, utcEpoch);
#endif
}
}
| 35.003861 | 98 | 0.446724 | [
"vector",
"transform"
] |
78a72ed2f5baf043d57d3f79cc0f3f9ee427fbc6 | 4,149 | hh | C++ | vendor/bundle/ruby/2.6.0/gems/unf_ext-0.0.7.7/ext/unf_ext/unf/trie/char_stream.hh | connorslagle/connorslagle.github.io | 344ff2142d6da508fec037bff26e8946cccf41b2 | [
"MIT"
] | 182 | 2017-03-21T15:58:53.000Z | 2022-03-29T17:07:57.000Z | vendor/bundle/ruby/2.6.0/gems/unf_ext-0.0.7.7/ext/unf_ext/unf/trie/char_stream.hh | connorslagle/connorslagle.github.io | 344ff2142d6da508fec037bff26e8946cccf41b2 | [
"MIT"
] | 861 | 2017-04-08T14:26:50.000Z | 2022-03-30T04:01:57.000Z | vendor/bundle/ruby/2.6.0/gems/unf_ext-0.0.7.7/ext/unf_ext/unf/trie/char_stream.hh | connorslagle/connorslagle.github.io | 344ff2142d6da508fec037bff26e8946cccf41b2 | [
"MIT"
] | 257 | 2017-03-24T06:22:12.000Z | 2022-03-27T10:41:48.000Z | #ifndef UNF_TRIE_CHAR_STREAM_HH
#define UNF_TRIE_CHAR_STREAM_HH
#include <vector>
#include <string>
#include "../util.hh"
namespace UNF {
namespace Trie {
class CharStream {
public:
CharStream(const char* str) : cur_(str) {}
unsigned char read() { return eos() ? '\0' : *cur_++; }
unsigned char prev() const { return cur_[-1]; }
unsigned char peek() const { return *cur_; }
const char* cur() const { return cur_; }
bool eos() const { return *cur_ == '\0'; }
void setCur(const char* new_cur) { cur_ = new_cur; }
private:
const char* cur_;
};
class RangeCharStream {
public:
RangeCharStream(const char* beg, const char* end) : cur_(beg), end_(end) {}
unsigned char read() { return eos() ? '\0' : *cur_++; }
unsigned char prev() const { return cur_[-1]; }
unsigned char peek() const { return *cur_; }
const char* cur() const { return cur_; }
const char* end() const { return end_; }
bool eos() const { return cur_ == end_; }
private:
const char* cur_;
const char* end_;
};
class CompoundCharStream {
public:
CompoundCharStream(const char* first, const char* second)
: beg1(first), beg2(second), cur1(beg1), cur2(beg2) {}
unsigned char read() { return !eos1() ? read1() : read2(); }
unsigned char peek() const { return !eos1() ? *cur1 : *cur2; }
unsigned char prev() const { return !eos1() || beg2==cur2 ? cur1[-1] : cur2[-1]; }
const char* cur() const { return !eos1() ? cur1 : cur2; }
bool eos() const { return eos1() && eos2(); }
bool within_first() const { return !eos1(); }
unsigned offset() const { return cur1-beg1 + cur2-beg2; }
void setCur(const char* p) {
if(beg1 <= p && p <= cur1) {
cur1=p;
cur2=beg2;
} else {
cur2=p;
}
}
protected:
unsigned char read1() { return eos1() ? '\0' : *cur1++; }
unsigned char read2() { return eos2() ? '\0' : *cur2++; }
bool eos1() const { return *cur1=='\0'; }
bool eos2() const { return *cur2=='\0'; }
protected:
const char* beg1;
const char* beg2;
const char* cur1;
const char* cur2;
};
class CharStreamForComposition : public CompoundCharStream {
public:
CharStreamForComposition (const char* first, const char* second,
const std::vector<unsigned char>& canonical_classes,
std::string& buf)
: CompoundCharStream(first, second), classes(canonical_classes), skipped(buf)
{}
void init_skipinfo() {
skipped.clear();
skipped_tail = 0;
}
void mark_as_last_valid_point() {
skipped_tail = skipped.size();
marked_point = cur();
}
void reset_at_marked_point() {
setCur(marked_point);
}
void append_read_char_to_str(std::string& s, const char* beg) const {
if(eos1()==false) {
s.append(beg, cur());
} else {
s.append(beg, cur1);
s.append(beg2, cur());
}
}
void append_skipped_chars_to_str(std::string& s) const {
s.append(skipped.begin(), skipped.begin()+skipped_tail);
}
unsigned char get_canonical_class() const {
return offset() < classes.size() ? classes[offset()] : 0;
}
bool next_combining_char(unsigned char prev_class, const char* ppp) {
while(Util::is_utf8_char_start_byte(peek()) == false)
read();
unsigned char mid_class = get_prev_canonical_class();
unsigned char cur_class = get_canonical_class();
if(prev_class==0 && mid_class==0 && cur_class!=0)
return false;
if(prev_class < cur_class && mid_class < cur_class) {
skipped.append(ppp, cur());
return true;
} else {
if(cur_class != 0) {
read();
return next_combining_char(prev_class,ppp);
}
return false;
}
}
private:
unsigned char get_prev_canonical_class() const {
return offset()-1 < classes.size() ? classes[offset()-1] : 0;
}
private:
const std::vector<unsigned char>& classes;
std::string& skipped;
unsigned skipped_tail;
const char* marked_point;
};
}
}
#endif
| 27.476821 | 88 | 0.595565 | [
"vector"
] |
78a8082bcd8d45ee925f337edb80e415b037590c | 7,171 | cpp | C++ | test/tbb/test_overwrite_node.cpp | dishasrivastavapuresoftware/oneTBB | 34dd71e7238d278a807a0380311f39102a916223 | [
"Apache-2.0"
] | 1,736 | 2020-03-17T20:23:25.000Z | 2022-03-31T16:01:44.000Z | test/tbb/test_overwrite_node.cpp | dishasrivastavapuresoftware/oneTBB | 34dd71e7238d278a807a0380311f39102a916223 | [
"Apache-2.0"
] | 500 | 2020-09-15T09:45:10.000Z | 2022-03-30T04:28:38.000Z | test/tbb/test_overwrite_node.cpp | dishasrivastavapuresoftware/oneTBB | 34dd71e7238d278a807a0380311f39102a916223 | [
"Apache-2.0"
] | 376 | 2020-03-19T06:15:59.000Z | 2022-03-25T06:26:31.000Z | /*
Copyright (c) 2005-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "common/config.h"
#include "tbb/flow_graph.h"
#include "common/test.h"
#include "common/utils.h"
#include "common/utils_assert.h"
#include "common/graph_utils.h"
#include "common/test_follows_and_precedes_api.h"
//! \file test_overwrite_node.cpp
//! \brief Test for [flow_graph.overwrite_node] specification
#define N 300
#define T 4
#define M 5
template< typename R >
void simple_read_write_tests() {
tbb::flow::graph g;
tbb::flow::overwrite_node<R> n(g);
for ( int t = 0; t < T; ++t ) {
R v0(N+1);
std::vector< std::shared_ptr<harness_counting_receiver<R>> > r;
for (size_t i = 0; i < M; ++i) {
r.push_back( std::make_shared<harness_counting_receiver<R>>(g) );
}
CHECK_MESSAGE( n.is_valid() == false, "" );
CHECK_MESSAGE( n.try_get( v0 ) == false, "" );
if ( t % 2 ) {
CHECK_MESSAGE( n.try_put( static_cast<R>(N) ), "" );
CHECK_MESSAGE( n.is_valid() == true, "" );
CHECK_MESSAGE( n.try_get( v0 ) == true, "" );
CHECK_MESSAGE( v0 == R(N), "" );
}
for (int i = 0; i < M; ++i) {
tbb::flow::make_edge( n, *r[i] );
}
for (int i = 0; i < N; ++i ) {
R v1(static_cast<R>(i));
CHECK_MESSAGE( n.try_put( v1 ), "" );
CHECK_MESSAGE( n.is_valid() == true, "" );
for (int j = 0; j < N; ++j ) {
R v2(0);
CHECK_MESSAGE( n.try_get( v2 ), "" );
CHECK_MESSAGE( v1 == v2, "" );
}
}
for (int i = 0; i < M; ++i) {
size_t c = r[i]->my_count;
CHECK_MESSAGE( int(c) == N+t%2, "" );
}
for (int i = 0; i < M; ++i) {
tbb::flow::remove_edge( n, *r[i] );
}
CHECK_MESSAGE( n.try_put( R(0) ), "" );
for (int i = 0; i < M; ++i) {
size_t c = r[i]->my_count;
CHECK_MESSAGE( int(c) == N+t%2, "" );
}
n.clear();
CHECK_MESSAGE( n.is_valid() == false, "" );
CHECK_MESSAGE( n.try_get( v0 ) == false, "" );
}
}
template< typename R >
class native_body : utils::NoAssign {
tbb::flow::overwrite_node<R> &my_node;
public:
native_body( tbb::flow::overwrite_node<R> &n ) : my_node(n) {}
void operator()( int i ) const {
R v1(static_cast<R>(i));
CHECK_MESSAGE( my_node.try_put( v1 ), "" );
CHECK_MESSAGE( my_node.is_valid() == true, "" );
}
};
template< typename R >
void parallel_read_write_tests() {
tbb::flow::graph g;
tbb::flow::overwrite_node<R> n(g);
//Create a vector of identical nodes
std::vector< tbb::flow::overwrite_node<R> > ow_vec(2, n);
for (size_t node_idx=0; node_idx<ow_vec.size(); ++node_idx) {
for ( int t = 0; t < T; ++t ) {
std::vector< std::shared_ptr<harness_counting_receiver<R>> > r;
for (size_t i = 0; i < M; ++i) {
r.push_back( std::make_shared<harness_counting_receiver<R>>(g) );
}
for (int i = 0; i < M; ++i) {
tbb::flow::make_edge( ow_vec[node_idx], *r[i] );
}
R v0;
CHECK_MESSAGE( ow_vec[node_idx].is_valid() == false, "" );
CHECK_MESSAGE( ow_vec[node_idx].try_get( v0 ) == false, "" );
#if TBB_TEST_LOW_WORKLOAD
const int nthreads = 30;
#else
const int nthreads = N;
#endif
utils::NativeParallelFor( nthreads, native_body<R>( ow_vec[node_idx] ) );
for (int i = 0; i < M; ++i) {
size_t c = r[i]->my_count;
CHECK_MESSAGE( int(c) == nthreads, "" );
}
for (int i = 0; i < M; ++i) {
tbb::flow::remove_edge( ow_vec[node_idx], *r[i] );
}
CHECK_MESSAGE( ow_vec[node_idx].try_put( R(0) ), "" );
for (int i = 0; i < M; ++i) {
size_t c = r[i]->my_count;
CHECK_MESSAGE( int(c) == nthreads, "" );
}
ow_vec[node_idx].clear();
CHECK_MESSAGE( ow_vec[node_idx].is_valid() == false, "" );
CHECK_MESSAGE( ow_vec[node_idx].try_get( v0 ) == false, "" );
}
}
}
#if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
#include <array>
#include <vector>
void test_follows_and_precedes_api() {
using msg_t = tbb::flow::continue_msg;
std::array<msg_t, 3> messages_for_follows = { {msg_t(), msg_t(), msg_t()} };
std::vector<msg_t> messages_for_precedes = {msg_t()};
follows_and_precedes_testing::test_follows<msg_t, tbb::flow::overwrite_node<msg_t>>(messages_for_follows);
follows_and_precedes_testing::test_precedes<msg_t, tbb::flow::overwrite_node<msg_t>>(messages_for_precedes);
}
#endif
#if __TBB_CPP17_DEDUCTION_GUIDES_PRESENT
void test_deduction_guides() {
using namespace tbb::flow;
graph g;
broadcast_node<int> b1(g);
overwrite_node<int> o0(g);
#if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
overwrite_node o1(follows(b1));
static_assert(std::is_same_v<decltype(o1), overwrite_node<int>>);
overwrite_node o2(precedes(b1));
static_assert(std::is_same_v<decltype(o2), overwrite_node<int>>);
#endif
overwrite_node o3(o0);
static_assert(std::is_same_v<decltype(o3), overwrite_node<int>>);
}
#endif
//! Test read-write properties
//! \brief \ref requirement \ref error_guessing
TEST_CASE("Read-write"){
simple_read_write_tests<int>();
simple_read_write_tests<float>();
}
//! Read-write and ParallelFor tests under limited parallelism
//! \brief \ref error_guessing
TEST_CASE("Limited parallelism"){
for( unsigned int p=utils::MinThread; p<=utils::MaxThread; ++p ) {
tbb::task_arena arena(p);
arena.execute(
[&]() {
parallel_read_write_tests<int>();
parallel_read_write_tests<float>();
test_reserving_nodes<tbb::flow::overwrite_node, size_t>();
}
);
}
}
#if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
//! Test follows and precedes API
//! \brief \ref error_guessing
TEST_CASE("Follows and precedes API"){
test_follows_and_precedes_api();
}
#endif
#if __TBB_CPP17_DEDUCTION_GUIDES_PRESENT
//! Test decution guides
//! \brief \ref requirement
TEST_CASE("Deduction guides"){
test_deduction_guides();
}
#endif
//! Test try_release
//! \brief \ref error_guessing
TEST_CASE("try_release"){
tbb::flow::graph g;
tbb::flow::overwrite_node<int> on(g);
CHECK_MESSAGE ((on.try_release()== true), "try_release should return true");
}
| 30.776824 | 112 | 0.583601 | [
"vector"
] |
78ab1bf9a0ff8ef2c7eaa85a493426d8867318aa | 2,245 | cpp | C++ | proxy/src/Main.cpp | hku-systems/hams | 3a5720657252c650c9a6c5d9b674f7ea6153e557 | [
"Apache-2.0"
] | 6 | 2020-08-19T11:46:23.000Z | 2021-12-24T07:34:15.000Z | proxy/src/Main.cpp | hku-systems/hams | 3a5720657252c650c9a6c5d9b674f7ea6153e557 | [
"Apache-2.0"
] | 1 | 2021-03-25T23:40:15.000Z | 2021-03-25T23:40:15.000Z | proxy/src/Main.cpp | hku-systems/hams | 3a5720657252c650c9a6c5d9b674f7ea6153e557 | [
"Apache-2.0"
] | 2 | 2020-10-31T16:48:39.000Z | 2021-03-07T09:14:25.000Z | //
// Created by xusheng on 3/4/19.
//
#include "Proxy.hpp"
#include <glog/logging.h>
#include "common.hpp"
#include "Config.hpp"
int main(int argc, char* argv[]){
//TODO: this arg parsing is very bad
google::InitGoogleLogging(argv[0]);
std::shared_ptr<Config> config = std::make_shared<Config>();
std::shared_ptr<Proxy> proxy;
if (config->CLI_TEST == false){
proxy = std::make_shared<Proxy>(config->PROXY_PORT, config);
proxy->start_handler();
}
else {
if (argc < 4) {
LOG(FATAL)
<< "usage: proxy proxy_port model_port is_stateful(true/false) {group_count [downstream_ip downstream_port]}"
<< std::endl;
return -1;
}
std::string my_uri = std::string("127.0.0.1") + ":" + argv[1];
proxy = std::make_shared<Proxy>(std::stoi(argv[1]), config);
proxy->setMyUri(my_uri);
proxy->start_handler();
if (strcmp(argv[3], "true") == 0) {
proxy->register_model("127.0.0.1", std::stoi(argv[2]));
DLOG(INFO) << "Stateful from parsing the cmd";
} else {
proxy->register_model("127.0.0.1", std::stoi(argv[2]));
DLOG(INFO) << "Stateless from parsing the cmd";
}
if (strcmp(argv[4], "recovery") == 0) {
proxy->set_status(PROXY_RECOVERING);
} else {
int parsed = 4;
while (argc > parsed) {
int group_count = std::stoi(argv[parsed++]);
std::vector<std::shared_ptr<DownStreamConn>> conns;
for (int i = 0; i < group_count; i++) {
std::string ip = argv[parsed];
auto conn = std::make_shared<DownStreamConn>(ip, uint(std::stoi(argv[parsed + 1])), 1, ip, ip, proxy,
my_uri, config);
parsed += 2;
conns.push_back(conn);
}
auto group = std::make_shared<DownstreamGroup>(proxy);
group->add(conns);
proxy->add_downstream_group(group);
}
proxy->init();
}
}
proxy->wait();
}
| 27.378049 | 129 | 0.500668 | [
"vector"
] |
78afe1b297217671a1e86f039c10425751b17105 | 3,906 | cpp | C++ | cdn/src/v20180606/model/ScdnTopDomainData.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cdn/src/v20180606/model/ScdnTopDomainData.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cdn/src/v20180606/model/ScdnTopDomainData.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cdn/v20180606/model/ScdnTopDomainData.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdn::V20180606::Model;
using namespace std;
ScdnTopDomainData::ScdnTopDomainData() :
m_domainHasBeenSet(false),
m_valueHasBeenSet(false),
m_percentHasBeenSet(false)
{
}
CoreInternalOutcome ScdnTopDomainData::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Domain") && !value["Domain"].IsNull())
{
if (!value["Domain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ScdnTopDomainData.Domain` IsString=false incorrectly").SetRequestId(requestId));
}
m_domain = string(value["Domain"].GetString());
m_domainHasBeenSet = true;
}
if (value.HasMember("Value") && !value["Value"].IsNull())
{
if (!value["Value"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `ScdnTopDomainData.Value` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_value = value["Value"].GetUint64();
m_valueHasBeenSet = true;
}
if (value.HasMember("Percent") && !value["Percent"].IsNull())
{
if (!value["Percent"].IsLosslessDouble())
{
return CoreInternalOutcome(Core::Error("response `ScdnTopDomainData.Percent` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_percent = value["Percent"].GetDouble();
m_percentHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void ScdnTopDomainData::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_domainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_valueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Value";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_value, allocator);
}
if (m_percentHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Percent";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_percent, allocator);
}
}
string ScdnTopDomainData::GetDomain() const
{
return m_domain;
}
void ScdnTopDomainData::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool ScdnTopDomainData::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
uint64_t ScdnTopDomainData::GetValue() const
{
return m_value;
}
void ScdnTopDomainData::SetValue(const uint64_t& _value)
{
m_value = _value;
m_valueHasBeenSet = true;
}
bool ScdnTopDomainData::ValueHasBeenSet() const
{
return m_valueHasBeenSet;
}
double ScdnTopDomainData::GetPercent() const
{
return m_percent;
}
void ScdnTopDomainData::SetPercent(const double& _percent)
{
m_percent = _percent;
m_percentHasBeenSet = true;
}
bool ScdnTopDomainData::PercentHasBeenSet() const
{
return m_percentHasBeenSet;
}
| 26.571429 | 151 | 0.68638 | [
"model"
] |
78bb1b8a8a7eeea019b4229c229c08aff6cc5e0b | 831 | cpp | C++ | UVa/10646.cpp | axelgio01/cp | 7a1c3490f913e4aea53e46bcfb5bb56c9b15605d | [
"MIT"
] | null | null | null | UVa/10646.cpp | axelgio01/cp | 7a1c3490f913e4aea53e46bcfb5bb56c9b15605d | [
"MIT"
] | null | null | null | UVa/10646.cpp | axelgio01/cp | 7a1c3490f913e4aea53e46bcfb5bb56c9b15605d | [
"MIT"
] | null | null | null | // https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1587
#include <bits/stdc++.h>
using namespace std;
int valueOfCard(const char &c) {
if ('2' <= c && c <= '9') {
return c - '2' + 2;
}
return 10;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int tt; cin >> tt;
for (int t = 1; t <= tt; ++t) {
vector<string> cards(52 - 25);
for (int i = 0; i < 52 - 25; ++i) {
cin >> cards[i];
}
int y = 0;
for (int i = 0; i < 3; ++i) {
int x = valueOfCard(cards[cards.size() - 1][0]);
y += x;
cards.pop_back();
for (int i = 0; i < 10 - x; ++i) {
cards.pop_back();
}
}
for (int i = 0; i < 25; ++i) {
string x; cin >> x;
cards.push_back(x);
}
cout << "Case " << t << ": " << cards[y - 1] << endl;
}
return 0;
} | 22.459459 | 111 | 0.525872 | [
"vector"
] |
78c179fb0f5b5dfaa8753f1faab9e299dfdc196a | 6,002 | hpp | C++ | R2017b/extern/include/MatlabEngine/detail/engine_future_impl.hpp | catou93/pelican_test | 23de9722c431fa0caa3c68d038de9423cfcdda80 | [
"BSD-2-Clause"
] | null | null | null | R2017b/extern/include/MatlabEngine/detail/engine_future_impl.hpp | catou93/pelican_test | 23de9722c431fa0caa3c68d038de9423cfcdda80 | [
"BSD-2-Clause"
] | null | null | null | R2017b/extern/include/MatlabEngine/detail/engine_future_impl.hpp | catou93/pelican_test | 23de9722c431fa0caa3c68d038de9423cfcdda80 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright 2017 The MathWorks, Inc. */
#ifndef ENGINE_FUTURE_IMPL_HPP
#define ENGINE_FUTURE_IMPL_HPP
#include <vector>
#include <streambuf>
#include <memory>
#include <future>
#include "../engine_future.hpp"
#include "../cpp_engine_api.hpp"
#include "../task_reference.hpp"
#include "../engine_exception.hpp"
namespace matlab {
namespace engine {
inline FutureResult<std::unique_ptr<MATLABEngine>>::FutureResult() :std::future<std::unique_ptr<MATLABEngine>>(), future() {}
inline void FutureResult<std::unique_ptr<MATLABEngine>>::swap(FutureResult<std::unique_ptr<MATLABEngine>>& a_futureresult) {
std::swap(future, a_futureresult.future);
std::swap(*static_cast<std::future<std::unique_ptr<MATLABEngine>>*>(this), static_cast<std::future<std::unique_ptr<MATLABEngine>>&>(a_futureresult));
}
inline FutureResult<std::unique_ptr<MATLABEngine>>::FutureResult(std::future<std::unique_ptr<MATLABEngine>>&& a_future):std::future<std::unique_ptr<MATLABEngine>>(), future(std::move(a_future)) {
}
inline FutureResult<std::unique_ptr<MATLABEngine>>::FutureResult(FutureResult<std::unique_ptr<MATLABEngine>>&& rhs):std::future<std::unique_ptr<MATLABEngine>>(), future() {
swap(rhs);
}
inline FutureResult<std::unique_ptr<MATLABEngine>>& FutureResult<std::unique_ptr<MATLABEngine>>::operator=(FutureResult<std::unique_ptr<MATLABEngine>>&& rhs) {
swap(rhs);
return *this;
}
inline FutureResult<std::unique_ptr<MATLABEngine>>::~FutureResult() {
}
inline std::unique_ptr<MATLABEngine> FutureResult<std::unique_ptr<MATLABEngine>>::get() {
return future.get();
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>> FutureResult<std::unique_ptr<MATLABEngine>>::share() {
return SharedFutureResult<std::unique_ptr<MATLABEngine>>(std::move(*this));
}
inline bool FutureResult<std::unique_ptr<MATLABEngine>>::valid() const {
return future.valid();
}
inline void FutureResult<std::unique_ptr<MATLABEngine>>::wait() const {
return future.wait();
}
template<class Clock, class Duration>
std::future_status FutureResult<std::unique_ptr<MATLABEngine>>::wait_until(const std::chrono::time_point<Clock, Duration>& abs_time) const {
return future.wait_until(abs_time);
}
template<class Rep, class Period>
std::future_status FutureResult<std::unique_ptr<MATLABEngine>>::wait_for(const std::chrono::duration<Rep, Period>& rel_time) const {
return future.wait_for(rel_time);
}
inline bool FutureResult<std::unique_ptr<MATLABEngine>>::cancel(bool allowInterrupt) {
return false;
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>::SharedFutureResult():std::shared_future<std::unique_ptr<MATLABEngine>>(), sharedFuture() {
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>::~SharedFutureResult() {
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>::SharedFutureResult(const SharedFutureResult& a_sharedfuture):std::shared_future<std::unique_ptr<MATLABEngine>>(), sharedFuture(a_sharedfuture.sharedFuture) {
}
inline void SharedFutureResult<std::unique_ptr<MATLABEngine>>::swap(SharedFutureResult<std::unique_ptr<MATLABEngine>>& a_sharedfuture) {
std::swap(sharedFuture, a_sharedfuture.sharedFuture);
std::swap(*static_cast<std::shared_future<std::unique_ptr<MATLABEngine>>*>(this), static_cast<std::shared_future<std::unique_ptr<MATLABEngine>>&>(a_sharedfuture));
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>::SharedFutureResult(SharedFutureResult&& a_sharedfuture):std::shared_future<std::unique_ptr<MATLABEngine>>(), sharedFuture() {
swap(a_sharedfuture);
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>::SharedFutureResult(FutureResult<std::unique_ptr<MATLABEngine>>&& a_futureresult):std::shared_future<std::unique_ptr<MATLABEngine>>(), sharedFuture(std::move(a_futureresult.future)) {
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>& SharedFutureResult<std::unique_ptr<MATLABEngine>>::operator=(SharedFutureResult<std::unique_ptr<MATLABEngine>>&& rhs) {
swap(rhs);
return *this;
}
inline SharedFutureResult<std::unique_ptr<MATLABEngine>>& SharedFutureResult<std::unique_ptr<MATLABEngine>>::operator=(const SharedFutureResult<std::unique_ptr<MATLABEngine>>& rhs) {
*(static_cast<std::shared_future<std::unique_ptr<MATLABEngine>>*>(this)) = rhs;
sharedFuture = rhs.sharedFuture;
return *this;
}
inline const std::unique_ptr<MATLABEngine>& SharedFutureResult<std::unique_ptr<MATLABEngine>>::get() const {
return sharedFuture.get();
}
inline bool SharedFutureResult<std::unique_ptr<MATLABEngine>>::valid() const {
return sharedFuture.valid();
}
inline void SharedFutureResult<std::unique_ptr<MATLABEngine>>::wait() const {
return sharedFuture.wait();
}
template<class Clock, class Duration>
std::future_status SharedFutureResult<std::unique_ptr<MATLABEngine>>::wait_until(const std::chrono::time_point<Clock, Duration>& abs_time) const {
return sharedFuture.wait_until(abs_time);
}
template<class Rep, class Period>
std::future_status SharedFutureResult<std::unique_ptr<MATLABEngine>>::wait_for(const std::chrono::duration<Rep, Period>& rel_time) const {
return sharedFuture.wait_for(rel_time);
}
inline bool SharedFutureResult<std::unique_ptr<MATLABEngine>>::cancel(bool allowInterrupt) {
return false;
}
}
}
#endif /* ENGINE_FUTURE_IMPL_HPP */ | 45.12782 | 248 | 0.681606 | [
"vector"
] |
78c1b6b30731c752c88e9b4e67e05bcc3d353d37 | 13,602 | cpp | C++ | src/qt/forms/accountpage.cpp | jommy99/pandacoin-1 | 10ccdd55fa369ba066fddaefa456a44d2bf1300a | [
"MIT"
] | 1 | 2019-01-09T10:01:10.000Z | 2019-01-09T10:01:10.000Z | src/qt/forms/accountpage.cpp | jommy99/pandacoin-1 | 10ccdd55fa369ba066fddaefa456a44d2bf1300a | [
"MIT"
] | null | null | null | src/qt/forms/accountpage.cpp | jommy99/pandacoin-1 | 10ccdd55fa369ba066fddaefa456a44d2bf1300a | [
"MIT"
] | 1 | 2018-03-23T06:51:16.000Z | 2018-03-23T06:51:16.000Z | #include "accountpage.h"
#include "ui_accountpage.h"
#include "walletmodel.h"
#include "wallet.h"
#include "accountmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "richtextdelegate.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "qrcodedialog.h"
#include <QClipboard>
#include <QListView>
#include <cstdlib>
#include "pandastyles.h"
AccountPage::AccountPage(CWallet* wallet_, QWidget *parent)
: QFrame(parent)
, ui(new Ui::AccountPage)
, model(NULL)
, wallet(wallet_)
, accountListModel(NULL)
{
ui->setupUi(this);
#ifndef USE_QRCODE
delete ui->show_qrcode_button;
ui->show_qrcode_button = NULL;
#endif
#ifdef USE_QRCODE
ui->show_qrcode_button->setEnabled(false);
#endif
ui->copy_address_button->setEnabled(false);
ui->sign_message_button->setEnabled(false);
connect(ui->transaction_table->transactionView,SIGNAL(clicked(QModelIndex)),this,SLOT(transaction_table_cellClicked(QModelIndex)));
connect(ui->account_filter_header,SIGNAL(exportClicked()),ui->transaction_table,SLOT(exportClicked()));
connect(ui->CreateAccountBox, SIGNAL(cancelAccountCreation()), this, SLOT(cancelAccountCreation()));
ui->last_30_days_in_bar->setMaximum(100);
ui->last_30_days_out_bar->setMaximum(100);
}
void AccountPage::setModel(WalletModel *model)
{
//fixme: delete signal connection if model already set at this point
//fixme: LEAKLEAK
RichTextDelegate* richTextDelegate = new RichTextDelegate(this);
this->model = model;
this->wallet = model->getWallet();
delete accountListModel;
if(model && model->getOptionsModel())
{
connect(model, SIGNAL(addressBookUpdated()), this, SLOT(update()));
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(update()));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(update()));
accountListModel = new SingleColumnAccountModel(model->getMyAccountModel(),true,true);
ui->TransactionTabAccountSelection->setModel(accountListModel);
ui->TransactionTabAccountSelection->setItemDelegate(richTextDelegate);
// Sadly the below is necessary in order to be able to style QComboBox pull down lists properly.
ui->TransactionTabAccountSelection->setView(new QListView(this));
ui->transaction_table->setModel(model);
ui->account_filter_header->setModel(ui->transaction_table->transactionProxyModel);
ui->CreateAccountBox->setModel(model);
ui->account_summary_header->setModel(model);
}
update();
}
void AccountPage::setActiveAccount(const QString& accountName)
{
if(accountName.isEmpty())
{
ui->TransactionTabAccountSelection->setCurrentIndex(0);
}
else
{
setSelectedAccountFromName(accountName);
}
}
void AccountPage::setActivePane(int paneIndex)
{
ui->tabWidget->setCurrentIndex(0);
}
AccountPage::~AccountPage()
{
delete ui;
}
void AccountPage::on_TransactionTabAccountSelection_currentIndexChanged(int index)
{
if(index == -1)
return;
if(ui->transaction_table->transactionProxyModel)
{
if(index==0)
{
model->getTransactionTableModel()->setCurrentAccountPrefix("");
ui->transaction_table->transactionProxyModel->setAddressPrefix("");
#ifdef USE_QRCODE
ui->show_qrcode_button->setEnabled(false);
#endif
ui->copy_address_button->setEnabled(false);
ui->sign_message_button->setEnabled(false);
}
else
{
model->getTransactionTableModel()->setCurrentAccountPrefix(model->getMyAccountModel()->data(1,index-1).toString());
ui->transaction_table->transactionProxyModel->setAddressPrefix(model->getMyAccountModel()->data(1,index-1).toString());
#ifdef USE_QRCODE
ui->show_qrcode_button->setEnabled(true);
#endif
ui->copy_address_button->setEnabled(true);
ui->sign_message_button->setEnabled(true);
}
update();
}
}
void AccountPage::update()
{
if (currentLoadState == LoadState_SyncHeadersFromEpoch)
return;
// Calculate various values used for widget display
int selectionIndex = ui->TransactionTabAccountSelection->currentIndex();
if(selectionIndex == -1)
return;
QString selectedAccountLabel;
QString selectedAccountAddress;
int64_t selectedAccountBalance = 0;
int64_t selectedAccountAvailable = 0;
int64_t selectedAccountEarningInterest = 0;
int64_t selectedAccountPending = 0;
qint64 allAccountEarningInterest = model->getStake();
qint64 allAccountPending = model->getUnconfirmedBalance();
qint64 allAccountBalance = model->getBalance();
int unit = model->getOptionsModel()->getDisplayUnit();
if(selectionIndex==0)
{
selectedAccountLabel=tr("All Accounts");
selectedAccountAddress="";
selectedAccountEarningInterest = allAccountEarningInterest;
selectedAccountPending = allAccountPending;
selectedAccountAvailable = allAccountBalance;
}
else
{
selectedAccountLabel=model->getMyAccountModel()->data(0,selectionIndex-1).toString();
selectedAccountAddress=model->getMyAccountModel()->data(1,selectionIndex-1).toString();
wallet->GetBalanceForAddress(selectedAccountAddress.toStdString(), selectedAccountEarningInterest, selectedAccountPending, selectedAccountAvailable);
}
selectedAccountBalance = selectedAccountEarningInterest + selectedAccountPending + selectedAccountAvailable;
// Setup display values for 'account summary' header at top
{
ui->account_summary_header->update(selectedAccountLabel, selectedAccountAddress, formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(unit, selectedAccountBalance, true, false)), formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(unit, selectedAccountAvailable, true, false)), formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(unit, selectedAccountEarningInterest, true, false)), formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(unit, selectedAccountPending, true, false)),selectionIndex == 0 ? false : true);
}
// Setup display values for 'transaction total' header at bottom
{
int numTransactions = ui->transaction_table->transactionProxyModel->rowCount();
if(numTransactions==1)
{
ui->num_transactions_found_footer->setText("1 "+tr("transactions found"));
}
else
{
ui->num_transactions_found_footer->setText(QString::number(numTransactions)+" "+tr("transactions found"));
}
}
// Setup display values for 'in/out transaction summary' widget at top right
{
qint64 inTotal, outTotal;
ui->transaction_table->transactionProxyModel->getLast30DaysInOut(inTotal, outTotal);
outTotal = std::abs(outTotal);
QString last30DaysInTotal = formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), inTotal, true, false));
QString last30DaysOutTotal = formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), outTotal, true, false));
ui->last_30_days_in_total->setText(last30DaysInTotal);
ui->last_30_days_out_total->setText(last30DaysOutTotal);
if(inTotal == 0 && outTotal == 0)
{
ui->last_30_days_in_bar->setValue(0);
ui->last_30_days_out_bar->setValue(0);
}
else if(inTotal == outTotal)
{
ui->last_30_days_in_bar->setValue(50);
ui->last_30_days_out_bar->setValue(50);
}
else
{
ui->last_30_days_in_bar->setValue(((double)inTotal/(inTotal+outTotal))*100);
ui->last_30_days_out_bar->setValue(((double)outTotal/(inTotal+outTotal))*100);
}
}
int64_t allAccountInterest = model->getTransactionTableModel()->getInterestGenerated();
// Setup display values for 'interest summary' widget at bottom right
if(wallet)
{
for(std::map<QLabel*,QLabel*>::iterator iter = mapInterestLabels.begin(); iter != mapInterestLabels.end(); iter++)
{
iter->first->deleteLater();
iter->second->deleteLater();
}
mapInterestLabels.clear();
for(int i = 0; i < model->getMyAccountModel()->rowCount(model->getMyAccountModel()->index(0,0)); i++)
{
QString accountName = model->getMyAccountModel()->data(0,i).toString().trimmed();
QString accountAddress = model->getMyAccountModel()->data(1,i).toString().trimmed();
int64_t accountInterest = model->getTransactionTableModel()->getInterestGenerated(accountAddress);
QLabel* accountInterestLabel = new QLabel(accountName);
QFont lblFont = accountInterestLabel->font();
QString fontSize = TOTAL_FONT_SIZE;
fontSize = fontSize.replace("px","");
lblFont.setPixelSize(fontSize.toLong());
QPalette lblPal = accountInterestLabel->palette();
lblPal.setColor(QPalette::WindowText, QColor("#424242"));
accountInterestLabel->setFont(lblFont);
accountInterestLabel->setPalette(lblPal);
QLabel* accountInterestValue = new QLabel(formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), accountInterest, true, false)));
accountInterestValue->setFont(lblFont);
accountInterestValue->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
accountInterestValue->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
mapInterestLabels[accountInterestLabel] = accountInterestValue;
ui->interest_form_layout->insertRow(0, accountInterestLabel, accountInterestValue);
}
ui->total_interest_value->setText(formatBitcoinAmountAsRichString(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), allAccountInterest, true, false)));
}
}
void AccountPage::on_sign_message_button_pressed()
{
int selectionIndex = ui->TransactionTabAccountSelection->currentIndex();
QString selectedAccountAddress;
if(selectionIndex!=0)
{
selectedAccountAddress=model->getMyAccountModel()->data(1,selectionIndex-1).toString();
emit signMessage(selectedAccountAddress);
}
}
void AccountPage::on_show_qrcode_button_pressed()
{
#ifdef USE_QRCODE
int selectionIndex = ui->TransactionTabAccountSelection->currentIndex();
QString selectedAccountAddress;
QString selectedAccountLabel;
if(selectionIndex!=0)
{
selectedAccountAddress=model->getMyAccountModel()->data(1,selectionIndex-1).toString();
selectedAccountLabel=model->getMyAccountModel()->data(0,selectionIndex-1).toString();
QRCodeDialog *dialog = new QRCodeDialog(selectedAccountAddress, selectedAccountLabel, true , this);
dialog->setModel(model->getOptionsModel());
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
#endif
}
void AccountPage::on_copy_address_button_pressed()
{
int selectionIndex = ui->TransactionTabAccountSelection->currentIndex();
if(selectionIndex!=0)
{
QApplication::clipboard()->setText(model->getMyAccountModel()->data(1,selectionIndex-1).toString());
}
}
void AccountPage::transaction_table_cellClicked(const QModelIndex &index)
{
//fixme: Hardcoded magic number, use proper column mapping
//if(index.column() == TransactionTableModel::ToAddress || index.column() == TransactionTableModel::FromAddress || index.column() == TransactionTableModel::OurAddress || index.column() == TransactionTableModel::OtherAddress)
if(index.column() == 3)
{
QString selectedAccountLabel = ui->transaction_table->transactionProxyModel->data(index).toString();
setSelectedAccountFromName(selectedAccountLabel);
}
}
void AccountPage::setSelectedAccountFromName(const QString &accountName)
{
QString accountLabel=accountName.trimmed();
for(int i = 0; i < model->getMyAccountModel()->rowCount(model->getMyAccountModel()->index(0,0)); i++)
{
QString accountCompare = model->getMyAccountModel()->data(0,i).toString();
accountCompare=accountCompare.trimmed();
if(accountCompare == accountLabel)
{
ui->TransactionTabAccountSelection->setCurrentIndex(i+1);
return;
}
}
}
void AccountPage::cancelAccountCreation()
{
ui->TransactionTabAccountSelection->setCurrentIndex(0);
ui->tabWidget->setCurrentIndex(0);
}
void AccountPage::resizeEvent(QResizeEvent * e)
{
setUpdatesEnabled(false);
updateHeaderWidths();
QFrame::resizeEvent(e);
setUpdatesEnabled(true);
}
void AccountPage::showEvent(QShowEvent *e)
{
QFrame::showEvent(e);
updateHeaderWidths();
}
int countu=0;
// Link the width of the columns in out 'summary header' to the columns in the 'transaction table'.
void AccountPage::updateHeaderWidths()
{
if(countu<2)
{
++countu;
//int balanceWidth = ui->transaction_table->getBalanceColumnWidth();
//int amountWidth = ui->transaction_table->getAmountColumnWidth();
//int accountWidth = ui->transaction_table->getAccountColumnWidth();
//ui->account_summary_header->setColumnWidths(accountWidth, amountWidth, balanceWidth);
}
}
| 37.888579 | 558 | 0.701073 | [
"model"
] |
78c1fc692fca12d0b264dfe6a9ef54107d05ba7c | 3,592 | hpp | C++ | include/codegen/include/UnityEngine/ProBuilder/Normal.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/ProBuilder/Normal.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/ProBuilder/Normal.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:21 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IEquatable`1
#include "System/IEquatable_1.hpp"
// Including type: UnityEngine.Vector3
#include "UnityEngine/Vector3.hpp"
// Including type: UnityEngine.Vector4
#include "UnityEngine/Vector4.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine.ProBuilder
namespace UnityEngine::ProBuilder {
// Autogenerated type: UnityEngine.ProBuilder.Normal
struct Normal : public System::ValueType, public System::IEquatable_1<UnityEngine::ProBuilder::Normal> {
public:
// private UnityEngine.Vector3 <normal>k__BackingField
// Offset: 0x0
UnityEngine::Vector3 normal;
// private UnityEngine.Vector4 <tangent>k__BackingField
// Offset: 0xC
UnityEngine::Vector4 tangent;
// private UnityEngine.Vector3 <bitangent>k__BackingField
// Offset: 0x1C
UnityEngine::Vector3 bitangent;
// Creating value type constructor for type: Normal
Normal(UnityEngine::Vector3 normal_ = {}, UnityEngine::Vector4 tangent_ = {}, UnityEngine::Vector3 bitangent_ = {}) : normal{normal_}, tangent{tangent_}, bitangent{bitangent_} {}
// public UnityEngine.Vector3 get_normal()
// Offset: 0xA3C3B0
UnityEngine::Vector3 get_normal();
// public System.Void set_normal(UnityEngine.Vector3 value)
// Offset: 0xA3C3BC
void set_normal(UnityEngine::Vector3 value);
// public UnityEngine.Vector4 get_tangent()
// Offset: 0xA3C3C8
UnityEngine::Vector4 get_tangent();
// public System.Void set_tangent(UnityEngine.Vector4 value)
// Offset: 0xA3C3D4
void set_tangent(UnityEngine::Vector4 value);
// public UnityEngine.Vector3 get_bitangent()
// Offset: 0xA3C3E0
UnityEngine::Vector3 get_bitangent();
// public System.Void set_bitangent(UnityEngine.Vector3 value)
// Offset: 0xA3C3EC
void set_bitangent(UnityEngine::Vector3 value);
// public override System.Boolean Equals(System.Object obj)
// Offset: 0xA3C3F8
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0xA3C400
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode();
// public System.Boolean Equals(UnityEngine.ProBuilder.Normal other)
// Offset: 0xA3C408
// Implemented from: System.IEquatable`1
// Base method: System.Boolean IEquatable`1::Equals(UnityEngine.ProBuilder.Normal other)
bool Equals(UnityEngine::ProBuilder::Normal other);
}; // UnityEngine.ProBuilder.Normal
// static public System.Boolean op_Equality(UnityEngine.ProBuilder.Normal a, UnityEngine.ProBuilder.Normal b)
// Offset: 0x1019F5C
bool operator ==(const UnityEngine::ProBuilder::Normal& a, const UnityEngine::ProBuilder::Normal& b);
// static public System.Boolean op_Inequality(UnityEngine.ProBuilder.Normal a, UnityEngine.ProBuilder.Normal b)
// Offset: 0x1019F90
bool operator !=(const UnityEngine::ProBuilder::Normal& a, const UnityEngine::ProBuilder::Normal& b);
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::Normal, "UnityEngine.ProBuilder", "Normal");
#pragma pack(pop)
| 45.468354 | 182 | 0.726336 | [
"object"
] |
78c206ee0db764360c301f37ef876f2a0364f0ff | 6,471 | hpp | C++ | include/src/Core/Utils/Signal.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | 1 | 2021-11-03T11:30:05.000Z | 2021-11-03T11:30:05.000Z | include/src/Core/Utils/Signal.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | include/src/Core/Utils/Signal.hpp | sjokic/WallDestruction | 2e1c000096df4aa027a91ff1732ce50a205b221a | [
"MIT"
] | null | null | null | /*
* This file is part of bogus, a C++ sparse block matrix library.
*
* Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef BOGUS_SIGNAL_HPP
#define BOGUS_SIGNAL_HPP
#include <list>
namespace bogus {
template < typename Derived >
struct SignalTraits
{ } ;
template< typename Arg1, typename Arg2 = void, typename Arg3 = void >
struct Signal ;
//! Base class for Signal of different arities
template< typename Derived >
class SignalBase
{
typedef SignalTraits< Derived > Traits ;
public:
virtual ~SignalBase()
{
disconnectAll();
}
//! Disconnects all listeners
void disconnectAll() ;
//! Connects the signal to a free function
/*! Its signature should be func( Arg 1, ..., Arg n ) ; */
void connect( typename Traits::Function::Type func ) ;
//! Connects the signal to a member function
/*! Its signature should be T::member_func( Arg 1, ..., Arg n ) ; */
template <typename T >
void connect( T& object, typename Traits::template Method< T >::Type member_func ) ;
//! Connects the signal to another Signal
/*! It should have the same template parameters */
void connect( const Derived &other ) ;
protected:
typedef std::list< typename Traits::Callable* > Callables ;
Callables m_callees ;
} ;
template < typename Arg1, typename Arg2, typename Arg3 >
struct SignalTraits< Signal< Arg1, Arg2, Arg3 > >
{
struct Callable
{
virtual ~Callable() {}
virtual void call( Arg1, Arg2, Arg3 ) = 0 ;
} ;
struct Function : public Callable
{
typedef void (*Type)( Arg1, Arg2, Arg3 ) ;
Type func ;
Function ( Type _func ) : func( _func ) {}
virtual void call( Arg1 arg1, Arg2 arg2, Arg3 arg3 ) { func( arg1, arg2, arg3 ) ; }
} ;
template< typename T >
struct Method : public Callable
{
typedef void (T::*Type)( Arg1, Arg2, Arg3 ) ;
T& obj ;
Type func ;
Method ( T& _obj, Type _func ) : obj( _obj ), func( _func ) {}
virtual void call( Arg1 arg1, Arg2 arg2, Arg3 arg3 ) { (obj.*func)( arg1, arg2, arg3 ) ; }
} ;
struct Proxy : public Callable
{
typedef Signal< Arg1, Arg2, Arg3 > Type ;
const Type& obj ;
Proxy( const Type& _obj ) : obj( _obj ) {}
virtual void call( Arg1 arg1, Arg2 arg2, Arg3 arg3 ) { obj.trigger( arg1, arg2, arg3 ) ; }
};
} ;
template < typename Arg1, typename Arg2 >
struct SignalTraits< Signal< Arg1, Arg2 > >
{
struct Callable
{
virtual ~Callable() {}
virtual void call( Arg1, Arg2 ) = 0 ;
} ;
struct Function : public Callable
{
typedef void (*Type)( Arg1, Arg2 ) ;
Type func ;
Function ( Type _func ) : func( _func ) {}
virtual void call( Arg1 arg1, Arg2 arg2 ) { func( arg1, arg2 ) ; }
} ;
template< typename T >
struct Method : public Callable
{
typedef void (T::*Type)( Arg1, Arg2 ) ;
T& obj ;
Type func ;
Method ( T& _obj, Type _func ) : obj( _obj ), func( _func ) {}
virtual void call( Arg1 arg1, Arg2 arg2 ) { (obj.*func)( arg1, arg2 ) ; }
} ;
struct Proxy : public Callable
{
typedef Signal< Arg1, Arg2 > Type ;
const Type& obj ;
Proxy( const Type& _obj ) : obj( _obj ) {}
virtual void call( Arg1 arg1, Arg2 arg2 ) { obj.trigger( arg1, arg2 ) ; }
};
} ;
template< typename Arg >
struct SignalTraits< Signal< Arg, void > >
{
struct Callable
{
virtual ~Callable() {}
virtual void call( Arg ) = 0 ;
} ;
struct Function : public Callable
{
typedef void (*Type)( Arg ) ;
Type func ;
Function ( Type _func ) : func( _func ) {}
virtual void call( Arg arg ) { func( arg ) ; }
} ;
template< typename T >
struct Method : public Callable
{
typedef void (T::*Type)( Arg ) ;
T& obj ;
Type func ;
Method ( T& _obj, Type _func ) : obj( _obj ), func( _func ) {}
virtual void call( Arg arg ) { (obj.*func)( arg ) ; }
} ;
struct Proxy : public Callable
{
typedef Signal< Arg, void > Type ;
const Type& obj ;
Proxy( const Type& _obj ) : obj( _obj ) {}
virtual void call( Arg arg ) { trigger( arg ) ; }
};
} ;
//! Signal class, to which an arbitrary number of listeners can be connected
/*!
Each time the Signal::trigger() method is called with arguments ( Arg 1, ..., Arg n ),
the listener functions are called with those same arguments.
The number and types of arguments are determined by the template parameters of the Signal class.
At the moment, only signals with up to 3 parameters are supported.
*/
template< typename Arg1, typename Arg2, typename Arg3 >
struct Signal : public SignalBase< Signal< Arg1, Arg2, Arg3 > >
{
//! Triggers the signal
void trigger( Arg1 arg1, Arg2 arg2, Arg3 arg3 ) const
{
typedef SignalBase< Signal > Base ;
for( typename Base::Callables::const_iterator it = this->m_callees.begin() ; it != this->m_callees.end() ; ++it )
{ (*it)->call( arg1, arg2, arg3 ) ; }
}
} ;
template< typename Arg1, typename Arg2 >
struct Signal< Arg1, Arg2, void > : public SignalBase< Signal< Arg1, Arg2 > >
{
//! Triggers the signal
void trigger( Arg1 arg1, Arg2 arg2 ) const
{
typedef SignalBase< Signal > Base ;
for( typename Base::Callables::const_iterator it = this->m_callees.begin() ; it != this->m_callees.end() ; ++it )
{ (*it)->call( arg1, arg2 ) ; }
}
} ;
template< typename Arg >
struct Signal< Arg, void, void > : public SignalBase< Signal< Arg, void > >
{
//! Triggers the signal
void trigger( Arg arg ) const
{
typedef SignalBase< Signal > Base ;
for( typename Base::Callables::const_iterator it = this->m_callees.begin() ; it != this->m_callees.end() ; ++it )
{ (*it)->call( arg ) ; }
}
} ;
template< typename Derived >
void SignalBase< Derived >::disconnectAll() {
for( typename Callables::iterator it = m_callees.begin() ; it != m_callees.end() ; ++it )
{
delete *it ;
}
m_callees.clear() ;
}
template< typename Derived >
void SignalBase< Derived >::connect( typename Traits::Function::Type func )
{
m_callees.push_back( new typename Traits::Function( func ) );
}
template< typename Derived >
template <typename T >
void SignalBase< Derived >::connect( T& object, typename Traits::template Method< T >::Type member_func )
{
m_callees.push_back( new typename Traits::template Method< T >( object, member_func ) );
}
template< typename Derived >
void SignalBase< Derived >::connect( const Derived& other )
{
m_callees.push_back( new typename Traits::Proxy( other ) );
}
} // namespace bogus
#endif
| 26.62963 | 115 | 0.659403 | [
"object"
] |
78c3ae0eaad8ca5840d9e1f11be5e5cd91be7d86 | 527 | hh | C++ | include/Surface.hh | KPO-2020-2021/zad5_3-ArkadiuszPlaza | 48888d08169b9e671013ba9e019c6d3950a3beff | [
"Unlicense"
] | null | null | null | include/Surface.hh | KPO-2020-2021/zad5_3-ArkadiuszPlaza | 48888d08169b9e671013ba9e019c6d3950a3beff | [
"Unlicense"
] | null | null | null | include/Surface.hh | KPO-2020-2021/zad5_3-ArkadiuszPlaza | 48888d08169b9e671013ba9e019c6d3950a3beff | [
"Unlicense"
] | null | null | null | #ifndef Surface_HH
#define Surface_HH
#include "Vector3d.hh"
#include "Matrix3x3.hh"
#include <fstream>
#include <vector>
class Surface
{
protected:
std::vector<Vector3d> wierz;
std::string nazwa;
int licz_prostych;
public:
Surface(Vector3d wymiary=Vector3d(),int gestosc_siatki=10, std::string nazwa="../datasets/Surface");
Vector3d &operator[](int index);
Vector3d operator[](int index) const;
void set_nazwa(std::string nazwa);
std::string get_nazwa() const;
void zapisz();
};
#endif | 19.518519 | 104 | 0.70019 | [
"vector"
] |
78c42cb6fcf7b599cfbeca502e637c5e24231692 | 2,889 | cpp | C++ | Lumos/Source/Lumos/Physics/LumosPhysicsEngine/CollisionShapes/SphereCollisionShape.cpp | jmorton06/UntitledEngine | eabeb8b5b43c6b5039c0c3b9ab2bd7e3af03e7f4 | [
"MIT"
] | null | null | null | Lumos/Source/Lumos/Physics/LumosPhysicsEngine/CollisionShapes/SphereCollisionShape.cpp | jmorton06/UntitledEngine | eabeb8b5b43c6b5039c0c3b9ab2bd7e3af03e7f4 | [
"MIT"
] | null | null | null | Lumos/Source/Lumos/Physics/LumosPhysicsEngine/CollisionShapes/SphereCollisionShape.cpp | jmorton06/UntitledEngine | eabeb8b5b43c6b5039c0c3b9ab2bd7e3af03e7f4 | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "SphereCollisionShape.h"
#include "Physics/LumosPhysicsEngine/RigidBody3D.h"
#include <glm/mat3x3.hpp>
#include "Graphics/Renderers/DebugRenderer.h"
namespace Lumos
{
SphereCollisionShape::SphereCollisionShape()
{
m_Radius = 1.0f;
m_LocalTransform = glm::scale(glm::mat4(1.0), glm::vec3(m_Radius * 2.0f));
m_Type = CollisionShapeType::CollisionSphere;
}
SphereCollisionShape::SphereCollisionShape(float radius)
{
m_Radius = radius;
m_LocalTransform = glm::scale(glm::mat4(1.0), glm::vec3(m_Radius * 2.0f));
m_Type = CollisionShapeType::CollisionSphere;
}
SphereCollisionShape::~SphereCollisionShape()
{
}
glm::mat3 SphereCollisionShape::BuildInverseInertia(float invMass) const
{
LUMOS_PROFILE_FUNCTION();
float i = 2.5f * invMass / (m_Radius * m_Radius); // SOLID
// float i = 1.5f * invMass * m_Radius * m_Radius; //HOLLOW
glm::mat3 inertia;
inertia[0][0] = i;
inertia[1][1] = i;
inertia[2][2] = i;
return inertia;
}
std::vector<glm::vec3>& SphereCollisionShape::GetCollisionAxes(const RigidBody3D* currentObject)
{
/* There is infinite edges so handle seperately */
m_Axes.clear();
return m_Axes;
}
std::vector<CollisionEdge>& SphereCollisionShape::GetEdges(const RigidBody3D* currentObject)
{
/* There is infinite edges on a sphere so handle seperately */
return m_Edges;
}
void SphereCollisionShape::GetMinMaxVertexOnAxis(const RigidBody3D* currentObject, const glm::vec3& axis, glm::vec3* out_min, glm::vec3* out_max) const
{
LUMOS_PROFILE_FUNCTION();
glm::mat4 transform = currentObject ? currentObject->GetWorldSpaceTransform() * m_LocalTransform : m_LocalTransform;
glm::vec3 pos = transform[3];
if(out_min)
*out_min = pos - axis * m_Radius;
if(out_max)
*out_max = pos + axis * m_Radius;
}
void SphereCollisionShape::GetIncidentReferencePolygon(const RigidBody3D* currentObject,
const glm::vec3& axis,
ReferencePolygon& refPolygon) const
{
LUMOS_PROFILE_FUNCTION();
refPolygon.Faces[0] = currentObject->GetPosition() + axis * m_Radius;
refPolygon.FaceCount = 1;
refPolygon.Normal = axis;
}
void SphereCollisionShape::DebugDraw(const RigidBody3D* currentObject) const
{
LUMOS_PROFILE_FUNCTION();
glm::mat4 transform = currentObject->GetWorldSpaceTransform() * m_LocalTransform;
auto pos = transform[3];
auto sphere = Maths::BoundingSphere(pos, m_Radius);
DebugRenderer::DebugDraw(sphere, glm::vec4(1.0f, 1.0f, 1.0f, 0.2f));
DebugRenderer::DebugDrawSphere(m_Radius, pos, glm::vec4(1.0f, 0.3f, 1.0f, 1.0f));
}
}
| 31.747253 | 155 | 0.650052 | [
"vector",
"transform",
"solid"
] |
78c9eca424be3337513befad5c769615ed5f0cfa | 506 | cpp | C++ | src/InteractiveObjects.cpp | jenningsm42/ggj-2019 | 241cb4e2e7ac4af25fc85d338e904cb24e5376d6 | [
"MIT"
] | 1 | 2019-01-26T05:43:39.000Z | 2019-01-26T05:43:39.000Z | src/InteractiveObjects.cpp | jenningsm42/ggj-2019 | 241cb4e2e7ac4af25fc85d338e904cb24e5376d6 | [
"MIT"
] | null | null | null | src/InteractiveObjects.cpp | jenningsm42/ggj-2019 | 241cb4e2e7ac4af25fc85d338e904cb24e5376d6 | [
"MIT"
] | null | null | null | #include "InteractiveObjects.hpp"
void InteractiveObjects::addObject(std::shared_ptr<InteractiveObject> object) {
m_objects.push_back(object);
}
void InteractiveObjects::update(Game& game, Player& player, float deltaTime) noexcept {
for (auto& object : m_objects) {
object->update(game, player, deltaTime);
}
}
void InteractiveObjects::draw(sf::RenderTarget& target, sf::RenderStates states) const {
for (auto& object : m_objects) {
target.draw(*object, states);
}
}
| 28.111111 | 88 | 0.705534 | [
"object"
] |
78ca1326046f80c33e14f3421bdcb09242f82e98 | 2,445 | hpp | C++ | ql/methods/montecarlo/earlyexercisepathpricer.hpp | boobar/QuantLib | d7c43398e7bc78d6ad9ea2dc93f899e93e452875 | [
"BSD-3-Clause"
] | null | null | null | ql/methods/montecarlo/earlyexercisepathpricer.hpp | boobar/QuantLib | d7c43398e7bc78d6ad9ea2dc93f899e93e452875 | [
"BSD-3-Clause"
] | null | null | null | ql/methods/montecarlo/earlyexercisepathpricer.hpp | boobar/QuantLib | d7c43398e7bc78d6ad9ea2dc93f899e93e452875 | [
"BSD-3-Clause"
] | null | null | null | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file earlyexercisepathpricer.hpp
\brief base class for early exercise single-path pricers
*/
#ifndef quantlib_early_exercise_path_pricer_hpp
#define quantlib_early_exercise_path_pricer_hpp
#include <ql/math/array.hpp>
#include <ql/methods/montecarlo/path.hpp>
#include <ql/methods/montecarlo/multipath.hpp>
#include <ql/function.hpp>
namespace QuantLib {
template <class PathType>
class EarlyExerciseTraits {
// dummy definition, will not work
};
template <>
class EarlyExerciseTraits<Path> {
public:
typedef Real StateType;
static Size pathLength(const Path& path) {
return path.length();
}
};
template <>
class EarlyExerciseTraits<MultiPath> {
public:
typedef Array StateType;
static Size pathLength(const MultiPath& path) {
return path.pathSize();
}
};
//! base class for early exercise path pricers
/*! Returns the value of an option on a given path and given time.
\ingroup mcarlo
*/
template<class PathType,
class TimeType=Size, class ValueType=Real>
class EarlyExercisePathPricer {
public:
typedef typename EarlyExerciseTraits<PathType>::StateType StateType;
virtual ~EarlyExercisePathPricer() {}
virtual ValueType operator()(const PathType& path,
TimeType t) const = 0;
virtual StateType
state(const PathType& path, TimeType t) const = 0;
virtual std::vector<ext::function<ValueType(StateType)> >
basisSystem() const = 0;
};
}
#endif
| 30.185185 | 79 | 0.678937 | [
"vector"
] |
78cdfbc56a6144c2229fc0261b1fc69a22b30f0e | 2,278 | cpp | C++ | Leetcode Daily Challenge/June-2021/13. Palindrome Pairs.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | Leetcode Daily Challenge/June-2021/13. Palindrome Pairs.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | Leetcode Daily Challenge/June-2021/13. Palindrome Pairs.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Palindrome Pairs
================
Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome.
Example 1:
Input: words = ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:
Input: words = ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
Example 3:
Input: words = ["a",""]
Output: [[0,1],[1,0]]
Constraints:
1 <= words.length <= 5000
0 <= words[i].length <= 300
words[i] consists of lower-case English letters.
*/
class Solution
{
public:
bool palendrome(string str)
{
int i = 0, j = str.size() - 1;
while (i < j)
{
if (str[i++] != str[j--])
return false;
}
return true;
}
vector<vector<int>> palindromePairs(vector<string> &arr)
{
unordered_map<string, int> words;
vector<vector<int>> ans;
vector<bool> isPal(arr.size(), 0);
for (int i = 0; i < arr.size(); ++i)
isPal[i] = palendrome(arr[i]);
for (int i = 0; i < arr.size(); ++i)
words[arr[i]] = i;
for (int i = 0; i < arr.size(); ++i)
{
// first type, right me add krke palendrome bnao
// ie, we have to find prefix ka reverse
string curr = "";
for (int j = 0; j < arr[i].size(); ++j)
{
curr = arr[i][j] + curr;
if (words.count(curr) && words[curr] != i && palendrome(arr[i] + curr))
{
ans.push_back({i, words[curr]});
}
}
// phir suffix ka reverse dekhna hai
curr = "";
for (int j = arr[i].size() - 1; j > 0; --j)
{
curr += arr[i][j];
if (words.count(curr) && words[curr] != i && palendrome(curr + arr[i]))
{
ans.push_back({words[curr], i});
}
}
}
// match empty string with all palendromes
for (int i = 0; i < arr.size(); ++i)
{
if (arr[i] == "")
{
for (int j = 0; j < arr.size(); ++j)
{
if (i != j && isPal[j])
{
ans.push_back({i, j});
ans.push_back({j, i});
}
}
}
}
return ans;
}
};
| 23.244898 | 180 | 0.505707 | [
"vector"
] |
78ce16da0d13aa45eebb351c021f2a98c0e2709d | 3,127 | cpp | C++ | Dev_class4_handout/Motor2D/j1Map.cpp | marcgreig/Videogame-Development | 64f0bc91476e642c9b103b8c77ede9a8c975f9ed | [
"MIT"
] | null | null | null | Dev_class4_handout/Motor2D/j1Map.cpp | marcgreig/Videogame-Development | 64f0bc91476e642c9b103b8c77ede9a8c975f9ed | [
"MIT"
] | null | null | null | Dev_class4_handout/Motor2D/j1Map.cpp | marcgreig/Videogame-Development | 64f0bc91476e642c9b103b8c77ede9a8c975f9ed | [
"MIT"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Map.h"
#include <math.h>
j1Map::j1Map() : j1Module(), map_loaded(false)
{
name.create("map");
}
// Destructor
j1Map::~j1Map()
{}
// Called before render is available
bool j1Map::Awake(pugi::xml_node& config)
{
LOG("Loading Map Parser");
bool ret = true;
folder.create(config.child("folder").child_value());
return ret;
}
void j1Map::Draw()
{
if(map_loaded == false)
return;
// TODO 6: Iterate all tilesets and draw all their
// images in 0,0 (you should have only one tileset for now)
}
// Called before quitting
bool j1Map::CleanUp()
{
LOG("Unloading map");
// TODO 2: Make sure you clean up any memory allocated
// from tilesets / map
map_file.reset();
return true;
}
// Load new map
bool j1Map::Load(const char* file_name)
{
bool ret = true;
p2SString tmp("%s%s", folder.GetString(), file_name);
pugi::xml_parse_result result = map_file.load_file(tmp.GetString());
if(result == NULL)
{
LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description());
ret = false;
}
if(ret == true)
{
// TODO 3: Create and call a private function to load and fill
// all your map data
pugi::xml_node map_node;
map_node = map_file.child(file_name).child("map");
map_info.version= map_file.child("version").attribute("value").as_float();
map_info.orientation = map_file.child("orientation").attribute("value").as_int();
map_info.renderer = map_file.child("renderorder").attribute("value").as_string();
map_info.height = map_file.child("height").attribute("value").as_uint();
map_info.width = map_file.child("width").attribute("value").as_uint();
map_info.tileheight = map_file.child("tileheight").attribute("value").as_uint();
map_info.tilewidth = map_file.child("tilewidth").attribute("value").as_uint();
map_info.nextobjectid = map_file.child("nextobjectid").attribute("value").as_uint();
}
// TODO 4: Create and call a private function to load a tileset
// remember to support more any number of tilesets!
for (pugi::xml_node tileset = map_file.child("map").child("tileset"); tileset; tileset = tileset.next_sibling("tileset")) {
tileset_info.firstgid = map_file.child("firstgid").attribute("value").as_uint();
tileset_info.name = map_file.child("name").attribute("value").as_string();
tileset_info.tileheight = map_file.child("tileheight").attribute("value").as_uint();
tileset_info.tilewidth = map_file.child("tilewidth").attribute("value").as_uint();
tileset_info.spacing = map_file.child("spacing").attribute("value").as_uint();
tileset_info.margin = map_file.child("margin").attribute("value").as_uint();
tileset_info.image_source = map_file.child("image").attribute("source").as_string();
tileset_info.image_height = map_file.child("image").attribute("height").as_uint();
tileset_info.image_width = map_file.child("image").attribute("width").as_uint();
}
if(ret == true)
{
// TODO 5: LOG all the data loaded
// iterate all tilesets and LOG everything
}
map_loaded = ret;
return ret;
}
| 27.919643 | 124 | 0.706428 | [
"render"
] |
78cf7b2629575e25947e8a5d9bdd0e54625f058b | 1,119 | hpp | C++ | src/utils/dbus_mapper.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 4 | 2019-11-14T10:41:34.000Z | 2021-12-09T23:54:52.000Z | src/utils/dbus_mapper.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | null | null | null | src/utils/dbus_mapper.hpp | aahmed-2/telemetry | 7e098e93ef0974739459d296f99ddfab54722c23 | [
"Apache-2.0"
] | 2 | 2021-08-05T11:17:03.000Z | 2021-12-13T15:22:48.000Z | #pragma once
#include <boost/asio/spawn.hpp>
#include <sdbusplus/asio/object_server.hpp>
#include <array>
#include <string>
#include <utility>
#include <vector>
namespace utils
{
using SensorPath = std::string;
using ServiceName = std::string;
using Ifaces = std::vector<std::string>;
using SensorIfaces = std::vector<std::pair<ServiceName, Ifaces>>;
using SensorTree = std::pair<SensorPath, SensorIfaces>;
inline std::vector<SensorTree>
getSubTreeSensors(boost::asio::yield_context& yield,
const std::shared_ptr<sdbusplus::asio::connection>& bus)
{
std::array<const char*, 1> interfaces = {
"xyz.openbmc_project.Sensor.Value"};
boost::system::error_code ec;
auto tree = bus->yield_method_call<std::vector<SensorTree>>(
yield, ec, "xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
"xyz.openbmc_project.ObjectMapper", "GetSubTree",
"/xyz/openbmc_project/sensors", 2, interfaces);
if (ec)
{
throw std::runtime_error("Failed to query ObjectMapper!");
}
return tree;
}
} // namespace utils
| 27.292683 | 78 | 0.68454 | [
"vector"
] |
78d19a8eadf887748351220601d217e9222e6e21 | 19,639 | cc | C++ | btech/btfi/Value.cc | KrugerHeavyIndustries/btmux | e502d9a1c7264b0400c61c076a73f6f231ad2a42 | [
"Artistic-1.0"
] | 2 | 2021-11-04T01:27:46.000Z | 2022-03-31T01:04:17.000Z | btech/btfi/Value.cc | KrugerHeavyIndustries/btmux | e502d9a1c7264b0400c61c076a73f6f231ad2a42 | [
"Artistic-1.0"
] | null | null | null | btech/btfi/Value.cc | KrugerHeavyIndustries/btmux | e502d9a1c7264b0400c61c076a73f6f231ad2a42 | [
"Artistic-1.0"
] | null | null | null | /*
* Dynamically-castable Value class implementation.
*/
#include "autoconf.h"
#include <cstddef>
#include <cstring>
#include <cassert>
#include <memory>
#include "values.h"
#include "Codec.hh"
#include "Value.hh"
#include "Serializable.hh"
// Use unique_ptr to avoid memory leak warnings from valgrind & friends.
using std::unique_ptr;
namespace BTech {
namespace FI {
/*
* Dynamic value table. Holds pre-decoded values from parsing. (We don't
* support writing values by index, at least at this time.)
*
* ATTRIBUTE VALUE
* CONTENT CHARACTER CHUNK
* OTHER STRING
*
* In the standard, this is just a dynamic string table (8.4).
*/
DV_VocabTable::TypedVocabTable *
DV_VocabTable::builtin_table()
{
static DV_VocabTable builtins (true, FI_ONE_MEG);
return &builtins;
}
DV_VocabTable::DV_VocabTable(bool read_only, FI_VocabIndex max_idx)
: DynamicTypedVocabTable<value_type> (true, max_idx)
{
// Index 0 is the empty value.
base_idx = 0;
last_idx = -1;
// Add built-in values.
static unique_ptr<Entry>
entry_0 (addStaticEntry (FI_VOCAB_INDEX_NULL, Value ()));
}
DV_VocabTable::DV_VocabTable()
: DynamicTypedVocabTable<value_type> (false, builtin_table())
{
}
/*
* Dynamically-typed Value implementation.
*/
namespace {
// Get the size of a type dynamically.
size_t
get_size_of(FI_ValueType value_type)
{
switch (value_type) {
case FI_VALUE_AS_NULL:
return 0;
case FI_VALUE_AS_SHORT:
return sizeof(FI_Int16);
case FI_VALUE_AS_INT:
return sizeof(FI_Int32);
case FI_VALUE_AS_LONG:
return sizeof(FI_Int64);
case FI_VALUE_AS_BOOLEAN:
return sizeof(FI_Boolean);
case FI_VALUE_AS_FLOAT:
return sizeof(FI_Float32);
case FI_VALUE_AS_DOUBLE:
return sizeof(FI_Float64);
case FI_VALUE_AS_UUID:
return sizeof(FI_UUID);
case FI_VALUE_AS_UTF8:
return sizeof(FI_UInt8);
case FI_VALUE_AS_UTF16:
return sizeof(FI_UInt16);
case FI_VALUE_AS_OCTETS:
return sizeof(FI_Octet);
default:
// Don't understand that value type.
throw InvalidArgumentException ();
}
}
void
pow2_ceil_down(size_t& pow2_size, size_t exact_size)
{
size_t tmp_pow2_size = pow2_size >> 1;
while (tmp_pow2_size > exact_size) {
pow2_size = tmp_pow2_size;
tmp_pow2_size >>= 1;
}
}
bool
pow2_ceil_up(size_t& pow2_size, size_t exact_size)
{
while (pow2_size < exact_size) {
const size_t tmp_pow2_size = pow2_size << 1;
if (tmp_pow2_size <= pow2_size) {
// Would overflow.
return false;
}
pow2_size = tmp_pow2_size;
}
return true;
}
} // anonymous namespace
Value::~Value()
{
delete[] static_cast<char *>(value_buf);
}
Value::Value (const Value& src)
: value_type (src.value_type), value_count (src.value_count),
value_size (src.value_size), value_buf_size (src.value_buf_size)
{
if (value_type == FI_VALUE_AS_NULL) {
// Empty buffer.
value_buf = 0;
return;
}
// Instead of re-throwing our own Exception, maybe just pass the
// std::bad_alloc up? Either that, or we have to guarantee that we
// never throw unexpected exceptions.
try {
value_buf = new char[value_buf_size];
} catch (const std::bad_alloc& e) {
throw OutOfMemoryException ();
}
memcpy(value_buf, src.value_buf, value_size);
}
Value&
Value::operator = (const Value& src)
{
if (&src == this) {
// Self-assignment, don't do any work.
return *this;
}
if (src.value_type == FI_VALUE_AS_NULL) {
allocateValueBuffer(0);
return *this;
}
// Instead of re-throwing our own Exception, maybe just pass the
// std::bad_alloc up? Either that, or we have to guarantee that we
// never throw unexpected exceptions.
try {
allocateValueBuffer(src.value_buf_size);
} catch (const std::bad_alloc& e) {
throw OutOfMemoryException ();
}
value_type = src.value_type;
value_count = src.value_count;
value_size = src.value_size;
memcpy(value_buf, src.value_buf, value_size);
return *this;
}
// (Re)allocate value buffer. The existing value will be deallocated. Note
// that constructors/destructors will not be called; use POD types only.
//
// With some casting/templates/massive switch statements/polymorphism, we could
// support arbitrary types, but that's a heavyweight solution for our needs,
// which is essentially a dynamically "typed" bag of bytes.
void
Value::allocateValueBuffer(size_t new_buf_size)
{
if (new_buf_size == 0) {
// Null assignment.
value_type = FI_VALUE_AS_NULL;
value_count = 0;
value_size = 0;
delete[] static_cast<char *>(value_buf);
value_buf = 0;
value_buf_size = 0;
return;
}
// Conditionally replace existing buffer.
if (new_buf_size != value_buf_size) {
char *new_buf = new char[new_buf_size];
delete[] static_cast<char *>(value_buf);
value_buf = new_buf;
value_buf_size = new_buf_size;
}
}
bool
Value::setBufferType(FI_ValueType type, size_t count)
{
// Handle assignment of empty value.
// We don't require type == FI_VALUE_AS_NULL, as a convenience.
if (count < 1 || type == FI_VALUE_AS_NULL) {
allocateValueBuffer(0);
return true;
}
// Compute value size.
const size_t item_size = get_size_of(type);
if (count > ((size_t)-1) / item_size) {
// Would overflow.
return false;
}
const size_t exact_size = count * item_size;
assert(exact_size > 0);
// Compute value buffer size.
size_t pow2_size;
if (value_buf) {
pow2_size = value_buf_size >> 2;
if (exact_size <= pow2_size) {
// Adjust buffer size downward when it saves >75%.
pow2_ceil_down(pow2_size, exact_size);
} else {
// Adjust buffer size upward by powers of 2.
pow2_size = value_buf_size;
if (!pow2_ceil_up(pow2_size, exact_size)) {
// Would overflow.
return false;
}
}
} else {
// Set initial buffer size as a power of 2.
pow2_size = 1;
if (!pow2_ceil_up(pow2_size, exact_size)) {
// Would overflow.
return false;
}
}
// Update object state.
try {
allocateValueBuffer(pow2_size);
} catch (const std::bad_alloc& e) {
return false;
}
value_type = type;
value_count = count;
value_size = exact_size;
return true;
}
// Set the value buffer from the contents of an external buffer.
void
Value::setBufferValue(const void *src)
{
if (!value_buf) {
// Not really needed, but okay.
return;
}
memcpy(value_buf, src, value_size);
}
// Imposes an absolute ordering on all possible values. Note that some values
// which would otherwise be equal may compare as non-equal; this operator is
// not generally useful, except to provide ordering for containers.
bool
Value::operator < (const Value& rhs) const
{
// Values are directly comparable if they have the same type. If they
// have different types, then they are ordered by increasing value of
// the FI_ValueType enumeration.
if (value_type < rhs.value_type) {
return true;
} else if (rhs.value_type > value_type) {
return false;
}
// All FI_VALUE_AS_NULL values compare as equal (not-less-than).
if (value_type == FI_VALUE_AS_NULL) {
assert(rhs.value_type == FI_VALUE_AS_NULL);
return false;
}
assert(value_count > 0);
// Values are directly comparable if they have the same count. If they
// have different counts, then they are ordered by increasing count.
if (value_count < rhs.value_count) {
return true;
} else if (rhs.value_count < value_count) {
return false;
}
assert(value_size == rhs.value_size);
// Compare the values. We consider two dynamic values the same only if
// they have the exact same bits (to deal with things like multiple NaN
// types in IEEE 754 floating point). Note that this requires that
// bitwise comparison be valid, usually appropriate only for POD.
//
// This ordering is really only used for caching identical Value
// objects, so we don't really suffer a penalty if some values don't
// compare equal, other than a slight increase in space usage.
return (memcmp(value_buf, rhs.value_buf, value_size) < 0);
}
/*
* Fast Infoset serialization support.
*/
namespace {
// Selecting the encoding format based on value type.
EncodingFormat
choose_enc_format(FI_ValueType value_type)
{
switch (value_type) {
case FI_VALUE_AS_UTF8:
return ENCODE_AS_UTF8;
case FI_VALUE_AS_UTF16:
return ENCODE_AS_UTF16;
default:
// Try to encode everything else with an algorithm.
return ENCODE_WITH_ALGORITHM;
}
}
// Select the encoding algorithm index based on value type.
FI_VocabIndex
choose_enc_alg(FI_ValueType value_type)
{
switch (value_type) {
case FI_VALUE_AS_SHORT:
return FI_EA_SHORT;
case FI_VALUE_AS_INT:
return FI_EA_INT;
case FI_VALUE_AS_LONG:
return FI_EA_LONG;
case FI_VALUE_AS_BOOLEAN:
return FI_EA_BOOLEAN;
case FI_VALUE_AS_FLOAT:
return FI_EA_FLOAT;
case FI_VALUE_AS_DOUBLE:
return FI_EA_DOUBLE;
case FI_VALUE_AS_UUID:
return FI_EA_UUID;
case FI_VALUE_AS_OCTETS:
return FI_EA_BASE64;
default:
// Couldn't select an appropriate algorithm.
throw UnsupportedOperationException ();
}
}
} // anonymous namespace
void
Value::setVocabTable(DV_VocabTable& new_vocab_table)
{
vocab_table = &new_vocab_table;
}
void
Value::write(Encoder& encoder) const
{
switch (encoder.getBitOffset()) {
case 0:
// Write value starting on first bit (C.14).
write_bit1_or_3(encoder);
break;
case 2:
// Write value starting on third bit (C.15).
write_bit1_or_3(encoder, false);
break;
default:
// Should never happen.
throw AssertionFailureException ();
}
}
bool
Value::read(Decoder& decoder)
{
reparse:
switch (decoder.ext_super_step) {
case 0:
decoder.ext_sub_step = 0;
switch (decoder.getBitOffset()) {
case 0:
// On first bit.
break;
case 2:
// On third bit.
decoder.ext_super_step = 2;
goto reparse;
default:
// Should never happen.
throw AssertionFailureException ();
}
decoder.ext_super_step = 1;
// FALLTHROUGH
case 1:
// Read value header starting on first bit (C.14).
if (!read_bit1_or_3(decoder)) {
return false;
}
break;
case 2:
// Read value header starting on third bit (C.15).
if (!read_bit1_or_3(decoder, false)) {
return false;
}
break;
default:
// Should never happen.
throw AssertionFailureException ();
}
decoder.ext_super_step = 0;
return true;
}
void
Value::encodeOctets(Encoder& encoder, FI_Length len) const
{
FI_Octet *w_buf = encoder.getWriteBuffer(len);
const FI_EncodingAlgorithm *enc_alg;
switch (choose_enc_format(value_type)) {
case ENCODE_AS_UTF8:
// TODO: This is a bit too liberal to be UTF-8.
memcpy(w_buf, value_buf, len);
break;
case ENCODE_AS_UTF16:
case ENCODE_WITH_ALPHABET:
// FIXME: Implementation restriction.
throw UnsupportedOperationException ();
case ENCODE_WITH_ALGORITHM:
// Use encoding algorithm.
enc_alg = *encoder.encoding_algorithm;
if (!enc_alg->encode(&encoder.encoding_context,
w_buf, FI_Value::cast(*this))) {
// FIXME: This Exception isn't really appropriate.
throw UnsupportedOperationException ();
}
encoder.encoding_algorithm = 0;
break;
}
}
// XXX: If this routine fails, we guarantee the Value will be left in a
// consistent state, but it may lose its original value before decoding aborts.
// In that case, the Value will become an FI_VALUE_AS_NULL, though the caller
// still shouldn't try to make use of it, except to assign a new value.
bool
Value::decodeOctets(Decoder& decoder, FI_Length len)
{
const FI_Octet *r_buf = decoder.getReadBuffer(len);
if (!r_buf) {
return false;
}
const FI_EncodingAlgorithm *enc_alg;
switch (saved_format) {
case ENCODE_AS_UTF8:
// TODO: This is a bit too liberal to be UTF-8.
if (!setBufferType(FI_VALUE_AS_UTF8, len)) {
// FIXME: This Exception isn't really appropriate.
throw UnsupportedOperationException ();
}
setBufferValue(r_buf);
break;
case ENCODE_AS_UTF16:
case ENCODE_WITH_ALPHABET:
// FIXME: Implementation restriction.
throw UnsupportedOperationException ();
case ENCODE_WITH_ALGORITHM:
// Use encoding algorithm.
enc_alg = *decoder.encoding_algorithm;
if (!enc_alg->decode(&decoder.encoding_context,
FI_Value::cast(*this), len, r_buf)) {
// FIXME: This Exception isn't really appropriate.
throw UnsupportedOperationException ();
}
break;
}
if (add_value_to_table) {
vocab_table->getEntry(*this).getNewIndex();
}
return true;
}
// C.14/C.19, C.15/C.20
// Note that we only choose to encode by literal, not index, except for the
// empty string/value. Also, we never request values be added to the table,
// although we do support adding during parsing.
void
Value::write_bit1_or_3(Encoder& encoder, bool is_bit1) const
{
assert(!is_bit1 || encoder.getBitOffset() == 0); // C.14.2
assert(is_bit1 || encoder.getBitOffset() == 2); // C.15.2
if (value_type == FI_VALUE_AS_NULL) {
// Use index rules (C.14.4, C.15.5).
if (!is_bit1) {
// C.15 doesn't allow index 0 (null character data).
throw AssertionFailureException ();
}
// Write string-index discriminant (C.14.4, C.15.4: 1).
encoder.writeBits(1, FI_BITS(1,,,,,,,));
// Write string-index using C.26 (C.14.4), C.28 (C.15.4).
encoder.writeUInt21_bit2(FI_VOCAB_INDEX_NULL);
return;
}
// Use literal rules (C.14.3, C.15.3).
// Write literal-character-string discriminant (C.14.3, C.15.3: 0).
// Write add-to-table (C.14.3.1, C.15.3.1: 0). (Not currently used.)
if (is_bit1) {
encoder.writeBits(2, FI_BITS(0, 0,,,,,,));
} else {
encoder.writeBits(2, FI_BITS(,,0, 0,,,,));
}
// Write character-string using C.19 (C.14.3.2), C.20 (C.15.3.2).
// Write discriminant (C.19.3, C.20.3).
const EncodingFormat format = choose_enc_format(value_type);
if (is_bit1) {
encoder.writeBits(2, format);
} else {
encoder.writeBits(2, (format >> 2));
}
// Write encoded string length using C.23.3 (C.19.4), C.24.3 (C.20.4).
// (And potentially the alphabet/algorithm index.)
FI_Length len;
FI_VocabIndex encoding_idx;
const FI_EncodingAlgorithm *enc_alg;
switch (format) {
case ENCODE_AS_UTF8:
if (value_count > FI_LENGTH_MAX / 1) {
// Overflow.
throw UnsupportedOperationException ();
}
encoder.encoding_algorithm = 0;
len = value_count * 1;
break;
case ENCODE_AS_UTF16:
// TODO: We don't use the utf-16 alternative.
if (value_count > FI_LENGTH_MAX / 2) {
// Overflow.
throw UnsupportedOperationException ();
}
encoder.encoding_algorithm = 0;
len = value_count * 2;
throw UnsupportedOperationException ();
case ENCODE_WITH_ALPHABET:
// TODO: We don't use the restricted-alphabet alternative.
// Write alphabet index using C.29 (C.19.3.3, C.20.3.3).
throw UnsupportedOperationException ();
case ENCODE_WITH_ALGORITHM:
// Write algorithm index using C.29 (C.19.3.4, C.20.3.4).
encoder.setEncodingAlgorithm(choose_enc_alg(value_type));
enc_alg = *encoder.encoding_algorithm;
if (!enc_alg->encoded_size(&encoder.encoding_context,
FI_Value::cast(*this))) {
// FIXME: This Exception isn't really appropriate.
throw UnsupportedOperationException ();
}
len = encoder.encoding_context.encoded_size;
encoding_idx = encoder.encoding_algorithm.getIndex();
assert(encoding_idx > 0 && encoding_idx <= FI_PINT8_MAX);
encoder.writePInt8(FI_UINT_TO_PINT(encoding_idx));
break;
}
// Encode octets.
assert(len > 0 && len <= FI_UINT32_MAX);
if (is_bit1) {
encoder.writeNonEmptyOctets_len_bit5(FI_UINT_TO_PINT(len));
} else {
encoder.writeNonEmptyOctets_len_bit7(FI_UINT_TO_PINT(len));
}
encodeOctets(encoder, len);
}
bool
Value::read_bit1_or_3(Decoder& decoder, bool is_bit1)
{
FI_Octet bits;
FI_VocabIndex idx;
FI_PInt32 len;
FI_PInt8 encoding_idx;
reparse:
switch (decoder.ext_sub_step) {
case 0:
assert(!is_bit1 || decoder.getBitOffset() == 0); // C.14.2
assert(is_bit1 || decoder.getBitOffset() == 2); // C.15.2
// Examine discriminator bits.
if (is_bit1) {
if (!decoder.readBits(1)) {
return false;
}
bits = decoder.getBits();
} else {
decoder.readBits(1);
bits = decoder.getBits() << 2;
}
if (!(bits & FI_BIT_1)) {
// Use literal rules (C.14.3, C.15.3).
// Read add-to-table (C.14.3.1, C.15.3.1).
decoder.readBits(1);
add_value_to_table = bits & FI_BIT_2;
decoder.ext_sub_step = 2;
goto reparse;
}
decoder.ext_sub_step = 1;
// FALLTHROUGH
case 1:
// Read string-index using C.26 (C.14.4), C.28 (C.15.4).
if (is_bit1) {
FI_UInt21 tmp_idx;
if (!decoder.readUInt21_bit2(tmp_idx)) {
return false;
}
idx = tmp_idx;
} else {
FI_PInt20 tmp_idx;
if (!decoder.readPInt20_bit4(tmp_idx)) {
return false;
}
idx = FI_PINT_TO_UINT(tmp_idx);
}
// XXX: Throws IndexOutOfBoundsException on bogus index.
*this = *(*vocab_table)[idx];
break;
case 2:
// Read character-string using C.19 (C.14.3.2), C.20 (C.15.3.3).
// Examine discriminator bits.
decoder.readBits(2);
if (is_bit1) {
bits = decoder.getBits();
} else {
bits = decoder.getBits() << 2;
}
switch (bits & FI_BITS(,,1,1,,,,)) {
case ENCODE_AS_UTF8:
// Use UTF-8 decoding rules.
saved_format = ENCODE_AS_UTF8;
break;
case ENCODE_AS_UTF16:
// FIXME: We don't support the utf-16 alternative.
saved_format = ENCODE_AS_UTF16;
throw UnsupportedOperationException ();
case ENCODE_WITH_ALPHABET:
saved_format = ENCODE_WITH_ALPHABET;
decoder.ext_sub_step = 5;
goto reparse;
case ENCODE_WITH_ALGORITHM:
saved_format = ENCODE_WITH_ALGORITHM;
decoder.ext_sub_step = 6;
goto reparse;
default:
// This should never happen.
throw AssertionFailureException ();
}
decoder.ext_sub_step = 3;
// FALLTHROUGH
case 3:
// Read encoded length using C.23.3 (C.19.4), C.24.3 (C.20.4).
if (is_bit1) {
if (!decoder.readNonEmptyOctets_len_bit5(len)) {
return false;
}
} else {
if (!decoder.readNonEmptyOctets_len_bit7(len)) {
return false;
}
}
// XXX: FI_PINT_TO_UINT() can't overflow, because we already
// checked in readNonEmptyOctets_len_bit{5,7}().
decoder.ext_saved_len = FI_PINT_TO_UINT(len);
decoder.ext_sub_step = 4;
// FALLTHROUGH
case 4:
// Read encoded string octets.
if (!decodeOctets(decoder, decoder.ext_saved_len)) {
return false;
}
break;
case 5:
// Read alphabet index using C.29 (C.19.3.3, C.20.3.3).
if (!decoder.readPInt8(encoding_idx)) {
return false;
}
// Determine future value type.
// FIXME: We don't support the restricted-alphabet alternative.
throw UnsupportedOperationException ();
case 6:
// Read algorithm index using C.29 (C.19.3.4, C.20.3.4).
if (!decoder.readPInt8(encoding_idx)) {
return false;
}
// XXX: Throws IndexOutOfBoundsException on bogus index.
decoder.setEncodingAlgorithm(FI_PINT_TO_UINT(encoding_idx));
decoder.ext_sub_step = 3;
goto reparse;
default:
// Should never happen.
throw AssertionFailureException ();
}
decoder.ext_sub_step = 0;
return true;
}
} // namespace FI
} // namespace BTech
/*
* C interface.
*/
using namespace BTech::FI;
FI_Value *
fi_create_value(void)
{
try {
return new FI_Value ();
} catch (const std::bad_alloc& e) {
return 0;
}
}
void
fi_destroy_value(FI_Value *obj)
{
delete obj;
}
FI_ValueType
fi_get_value_type(const FI_Value *obj)
{
return obj->getType();
}
size_t
fi_get_value_count(const FI_Value *obj)
{
return obj->getCount();
}
const void *
fi_get_value(const FI_Value *obj)
{
return obj->getBuffer();
}
int
fi_set_value_type(FI_Value *obj, FI_ValueType type, size_t count)
{
return obj->setBufferType(type, count);
}
void
fi_set_value(FI_Value *obj, const void *buf)
{
obj->setBufferValue(buf);
}
void *
fi_get_value_buffer(FI_Value *obj)
{
return obj->getBuffer();
}
| 21.652701 | 79 | 0.702582 | [
"object"
] |
78d5db4f2da2deb7364d3a4fa40ede6f66e66809 | 2,479 | cpp | C++ | src/Witness_complex/example/example_witness_complex_sphere.cpp | m0baxter/gudhi-devel | 6e14ef1f31e09f3875316440303450ff870d9881 | [
"MIT"
] | null | null | null | src/Witness_complex/example/example_witness_complex_sphere.cpp | m0baxter/gudhi-devel | 6e14ef1f31e09f3875316440303450ff870d9881 | [
"MIT"
] | 1 | 2020-05-24T14:34:45.000Z | 2020-05-24T14:34:45.000Z | src/Witness_complex/example/example_witness_complex_sphere.cpp | m0baxter/gudhi-devel | 6e14ef1f31e09f3875316440303450ff870d9881 | [
"MIT"
] | 1 | 2020-04-06T07:16:17.000Z | 2020-04-06T07:16:17.000Z | #define BOOST_PARAMETER_MAX_ARITY 12
#include <gudhi/Simplex_tree.h>
#include <gudhi/Euclidean_witness_complex.h>
#include <gudhi/pick_n_random_points.h>
#include <gudhi/choose_n_farthest_points.h>
#include <gudhi/reader_utils.h>
#include <CGAL/Epick_d.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <utility>
#include <string>
#include <vector>
#include "generators.h"
/** Write a gnuplot readable file.
* Data range is a random access range of pairs (arg, value)
*/
template <typename Data_range>
void write_data(Data_range& data, std::string filename) {
std::ofstream ofs(filename, std::ofstream::out);
for (auto entry : data) ofs << entry.first << ", " << entry.second << "\n";
ofs.close();
}
int main(int argc, char* const argv[]) {
using Kernel = CGAL::Epick_d<CGAL::Dynamic_dimension_tag>;
using Witness_complex = Gudhi::witness_complex::Euclidean_witness_complex<Kernel>;
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " number_of_landmarks \n";
return 0;
}
int number_of_landmarks = atoi(argv[1]);
std::vector<std::pair<int, double> > l_time;
// Generate points
for (int nbP = 500; nbP < 10000; nbP += 500) {
clock_t start, end;
// Construct the Simplex Tree
Gudhi::Simplex_tree<> simplex_tree;
Point_Vector point_vector, landmarks;
generate_points_sphere(point_vector, nbP, 4);
std::clog << "Successfully generated " << point_vector.size() << " points.\n";
std::clog << "Ambient dimension is " << point_vector[0].size() << ".\n";
// Choose landmarks
start = clock();
// Gudhi::subsampling::pick_n_random_points(point_vector, number_of_landmarks, std::back_inserter(landmarks));
Gudhi::subsampling::choose_n_farthest_points(K(), point_vector, number_of_landmarks,
Gudhi::subsampling::random_starting_point,
std::back_inserter(landmarks));
// Compute witness complex
Witness_complex witness_complex(landmarks, point_vector);
witness_complex.create_complex(simplex_tree, 0);
end = clock();
double time = static_cast<double>(end - start) / CLOCKS_PER_SEC;
std::clog << "Witness complex for " << number_of_landmarks << " landmarks took " << time << " s. \n";
std::clog << "Number of simplices is: " << simplex_tree.num_simplices() << "\n";
l_time.push_back(std::make_pair(nbP, time));
}
write_data(l_time, "w_time.dat");
}
| 34.915493 | 114 | 0.669221 | [
"vector"
] |
78db69f397ce2a1087eb8c7a2b869758bb69ad2b | 21,127 | cpp | C++ | software/colorHarmonize/colorHarmonizeEngineGlobal.cpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | software/colorHarmonize/colorHarmonizeEngineGlobal.cpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | software/colorHarmonize/colorHarmonizeEngineGlobal.cpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 1 | 2019-02-18T09:49:32.000Z | 2019-02-18T09:49:32.000Z |
// Copyright (c) 2013, 2014 i23dSFM authors.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "colorHarmonizeEngineGlobal.hpp"
#include "software/SfM/SfMIOHelper.hpp"
#include "i23dSFM/image/image.hpp"
//-- Feature matches
#include <i23dSFM/matching/indMatch.hpp>
#include "i23dSFM/matching/indMatch_utils.hpp"
#include "i23dSFM/stl/stl.hpp"
#include "i23dSFM/sfm/sfm.hpp"
#include "i23dSFM/graph/graph.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/vectorGraphics/svgDrawer.hpp"
//-- Selection Methods
#include "i23dSFM/color_harmonization/selection_fullFrame.hpp"
#include "i23dSFM/color_harmonization/selection_matchedPoints.hpp"
#include "i23dSFM/color_harmonization/selection_VLDSegment.hpp"
//-- Color harmonization solver
#include "i23dSFM/color_harmonization/global_quantile_gain_offset_alignment.hpp"
#include "i23dSFM/system/timer.hpp"
#include "third_party/progress/progress.hpp"
#include <numeric>
#include <iomanip>
#include <iterator>
#include <algorithm>
#include <functional>
#include <sstream>
namespace i23dSFM{
using namespace lemon;
using namespace i23dSFM::image;
using namespace i23dSFM::matching;
using namespace i23dSFM::lInfinity;
using namespace i23dSFM::sfm;
typedef features::SIOPointFeature FeatureT;
typedef vector< FeatureT > featsT;
ColorHarmonizationEngineGlobal::ColorHarmonizationEngineGlobal(
const string & sSfM_Data_Filename,
const string & sMatchesPath,
const std::string & sMatchesFile,
const string & sOutDirectory,
const int selectionMethod,
const int imgRef):
_sSfM_Data_Path(sSfM_Data_Filename),
_sMatchesPath(sMatchesPath),
_sOutDirectory(sOutDirectory),
_selectionMethod( selectionMethod ),
_imgRef( imgRef ),
_sMatchesFile(sMatchesFile)
{
if( !stlplus::folder_exists( sOutDirectory ) )
{
stlplus::folder_create( sOutDirectory );
}
}
ColorHarmonizationEngineGlobal::~ColorHarmonizationEngineGlobal()
{
}
static void pauseProcess()
{
unsigned char i;
cout << "\nPause : type key and press enter: ";
std::cin >> i;
}
bool ColorHarmonizationEngineGlobal::Process()
{
const std::string vec_selectionMethod[ 3 ] = { "fullFrame", "matchedPoints", "KVLD" };
const std::string vec_harmonizeMethod[ 1 ] = { "quantifiedGainCompensation" };
const int harmonizeMethod = 0;
//-------------------
// Load data
//-------------------
if( !ReadInputData() )
return false;
if( _map_Matches.size() == 0 )
{
cout << endl << "Matches file is empty" << endl;
return false;
}
//-- Remove EG with poor support:
for (matching::PairWiseMatches::iterator iter = _map_Matches.begin();
iter != _map_Matches.end();
++iter)
{
if (iter->second.size() < 120)
{
_map_Matches.erase(iter);
iter = _map_Matches.begin();
}
}
{
graph::indexedGraph putativeGraph(getPairs(_map_Matches));
// Save the graph before cleaning:
graph::exportToGraphvizData(
stlplus::create_filespec(_sOutDirectory, "input_graph_poor_supportRemoved"),
putativeGraph.g);
}
//-------------------
// Keep the largest CC in the image graph
//-------------------
if (!CleanGraph())
{
std::cout << std::endl << "There is no largest CC in the graph" << std::endl;
return false;
}
//-------------------
//-- Color Harmonization
//-------------------
//Choose image reference
if( _imgRef == -1 )
{
do
{
cout << "Choose your reference image:\n";
for( int i = 0; i < _vec_fileNames.size(); ++i )
{
cout << "id: " << i << "\t" << _vec_fileNames[ i ] << endl;
}
}while( !( cin >> _imgRef ) || _imgRef < 0 || _imgRef >= _vec_fileNames.size() );
}
//Choose selection method
if( _selectionMethod == -1 )
{
cout << "Choose your selection method:\n"
<< "- FullFrame: 0\n"
<< "- Matched Points: 1\n"
<< "- VLD Segment: 2\n";
while( ! ( cin >> _selectionMethod ) || _selectionMethod < 0 || _selectionMethod > 2 )
{
cout << _selectionMethod << " is not accepted.\nTo use: \n- FullFrame enter: 0\n- Matched Points enter: 1\n- VLD Segment enter: 2\n";
}
}
//-------------------
// Compute remaining camera node Id
//-------------------
std::map<size_t, size_t> map_cameraNodeToCameraIndex; // graph node Id to 0->Ncam
std::map<size_t, size_t> map_cameraIndexTocameraNode; // 0->Ncam correspondance to graph node Id
std::set<size_t> set_indeximage;
for (size_t i = 0; i < _map_Matches.size(); ++i)
{
matching::PairWiseMatches::const_iterator iter = _map_Matches.begin();
std::advance(iter, i);
const size_t I = iter->first.first;
const size_t J = iter->first.second;
set_indeximage.insert(I);
set_indeximage.insert(J);
}
for (std::set<size_t>::const_iterator iterSet = set_indeximage.begin();
iterSet != set_indeximage.end(); ++iterSet)
{
map_cameraIndexTocameraNode[std::distance(set_indeximage.begin(), iterSet)] = *iterSet;
map_cameraNodeToCameraIndex[*iterSet] = std::distance(set_indeximage.begin(), iterSet);
}
std::cout << "\n Remaining cameras after CC filter : \n"
<< map_cameraIndexTocameraNode.size() << " from a total of " << _vec_fileNames.size() << std::endl;
size_t bin = 256;
double minvalue = 0.0;
double maxvalue = 255.0;
// For each edge computes the selection masks and histograms (for the RGB channels)
std::vector<relativeColorHistogramEdge> map_relativeHistograms[3];
map_relativeHistograms[0].resize(_map_Matches.size());
map_relativeHistograms[1].resize(_map_Matches.size());
map_relativeHistograms[2].resize(_map_Matches.size());
for (size_t i = 0; i < _map_Matches.size(); ++i)
{
matching::PairWiseMatches::const_iterator iter = _map_Matches.begin();
std::advance(iter, i);
const size_t I = iter->first.first;
const size_t J = iter->first.second;
const std::vector<IndMatch> & vec_matchesInd = iter->second;
//-- Edges names:
std::pair< std::string, std::string > p_imaNames;
p_imaNames = make_pair( _vec_fileNames[ I ], _vec_fileNames[ J ] );
std::cout << "Current edge : "
<< stlplus::filename_part(p_imaNames.first) << "\t"
<< stlplus::filename_part(p_imaNames.second) << std::endl;
//-- Compute the masks from the data selection:
Image< unsigned char > maskI ( _vec_imageSize[ I ].first, _vec_imageSize[ I ].second );
Image< unsigned char > maskJ ( _vec_imageSize[ J ].first, _vec_imageSize[ J ].second );
switch(_selectionMethod)
{
enum EHistogramSelectionMethod
{
eHistogramHarmonizeFullFrame = 0,
eHistogramHarmonizeMatchedPoints = 1,
eHistogramHarmonizeVLDSegment = 2,
};
case eHistogramHarmonizeFullFrame:
{
color_harmonization::commonDataByPair_FullFrame dataSelector(
p_imaNames.first,
p_imaNames.second);
dataSelector.computeMask( maskI, maskJ );
}
break;
case eHistogramHarmonizeMatchedPoints:
{
int circleSize = 10;
color_harmonization::commonDataByPair_MatchedPoints dataSelector(
p_imaNames.first,
p_imaNames.second,
vec_matchesInd,
_map_feats[ I ],
_map_feats[ J ],
circleSize);
dataSelector.computeMask( maskI, maskJ );
}
break;
case eHistogramHarmonizeVLDSegment:
{
color_harmonization::commonDataByPair_VLDSegment dataSelector(
p_imaNames.first,
p_imaNames.second,
vec_matchesInd,
_map_feats[ I ],
_map_feats[ J ]);
dataSelector.computeMask( maskI, maskJ );
}
break;
default:
std::cout << "Selection method unsupported" << std::endl;
return false;
}
//-- Export the masks
bool bExportMask = false;
if (bExportMask)
{
string sEdge = _vec_fileNames[ I ] + "_" + _vec_fileNames[ J ];
sEdge = stlplus::create_filespec( _sOutDirectory, sEdge );
if( !stlplus::folder_exists( sEdge ) )
stlplus::folder_create( sEdge );
string out_filename_I = "00_mask_I.png";
out_filename_I = stlplus::create_filespec( sEdge, out_filename_I );
string out_filename_J = "00_mask_J.png";
out_filename_J = stlplus::create_filespec( sEdge, out_filename_J );
WriteImage( out_filename_I.c_str(), maskI );
WriteImage( out_filename_J.c_str(), maskJ );
}
//-- Compute the histograms
Image< RGBColor > imageI, imageJ;
ReadImage( p_imaNames.first.c_str(), &imageI );
ReadImage( p_imaNames.second.c_str(), &imageJ );
Histogram< double > histoI( minvalue, maxvalue, bin);
Histogram< double > histoJ( minvalue, maxvalue, bin);
int channelIndex = 0; // RED channel
color_harmonization::commonDataByPair::computeHisto( histoI, maskI, channelIndex, imageI );
color_harmonization::commonDataByPair::computeHisto( histoJ, maskJ, channelIndex, imageJ );
relativeColorHistogramEdge & edgeR = map_relativeHistograms[channelIndex][i];
edgeR = relativeColorHistogramEdge(map_cameraNodeToCameraIndex[I], map_cameraNodeToCameraIndex[J],
histoI.GetHist(), histoJ.GetHist());
histoI = histoJ = Histogram< double >( minvalue, maxvalue, bin);
channelIndex = 1; // GREEN channel
color_harmonization::commonDataByPair::computeHisto( histoI, maskI, channelIndex, imageI );
color_harmonization::commonDataByPair::computeHisto( histoJ, maskJ, channelIndex, imageJ );
relativeColorHistogramEdge & edgeG = map_relativeHistograms[channelIndex][i];
edgeG = relativeColorHistogramEdge(map_cameraNodeToCameraIndex[I], map_cameraNodeToCameraIndex[J],
histoI.GetHist(), histoJ.GetHist());
histoI = histoJ = Histogram< double >( minvalue, maxvalue, bin);
channelIndex = 2; // BLUE channel
color_harmonization::commonDataByPair::computeHisto( histoI, maskI, channelIndex, imageI );
color_harmonization::commonDataByPair::computeHisto( histoJ, maskJ, channelIndex, imageJ );
relativeColorHistogramEdge & edgeB = map_relativeHistograms[channelIndex][i];
edgeB = relativeColorHistogramEdge(map_cameraNodeToCameraIndex[I], map_cameraNodeToCameraIndex[J],
histoI.GetHist(), histoJ.GetHist());
}
std::cout << "\n -- \n SOLVE for color consistency with linear programming\n --" << std::endl;
//-- Solve for the gains and offsets:
std::vector<size_t> vec_indexToFix;
vec_indexToFix.push_back(map_cameraNodeToCameraIndex[_imgRef]);
using namespace i23dSFM::linearProgramming;
std::vector<double> vec_solution_r(_vec_fileNames.size() * 2 + 1);
std::vector<double> vec_solution_g(_vec_fileNames.size() * 2 + 1);
std::vector<double> vec_solution_b(_vec_fileNames.size() * 2 + 1);
i23dSFM::system::Timer timer;
#ifdef I23DSFM_HAVE_MOSEK
typedef MOSEK_SolveWrapper SOLVER_LP_T;
#else
typedef OSI_CLP_SolverWrapper SOLVER_LP_T;
#endif
// Red channel
{
SOLVER_LP_T lpSolver(vec_solution_r.size());
ConstraintBuilder_GainOffset cstBuilder(map_relativeHistograms[0], vec_indexToFix);
LP_Constraints_Sparse constraint;
cstBuilder.Build(constraint);
lpSolver.setup(constraint);
lpSolver.solve();
lpSolver.getSolution(vec_solution_r);
}
// Green channel
{
SOLVER_LP_T lpSolver(vec_solution_g.size());
ConstraintBuilder_GainOffset cstBuilder(map_relativeHistograms[1], vec_indexToFix);
LP_Constraints_Sparse constraint;
cstBuilder.Build(constraint);
lpSolver.setup(constraint);
lpSolver.solve();
lpSolver.getSolution(vec_solution_g);
}
// Blue channel
{
SOLVER_LP_T lpSolver(vec_solution_b.size());
ConstraintBuilder_GainOffset cstBuilder(map_relativeHistograms[2], vec_indexToFix);
LP_Constraints_Sparse constraint;
cstBuilder.Build(constraint);
lpSolver.setup(constraint);
lpSolver.solve();
lpSolver.getSolution(vec_solution_b);
}
std::cout << std::endl
<< " ColorHarmonization solving on a graph with: " << _map_Matches.size() << " edges took (s): "
<< timer.elapsed() << std::endl
<< "LInfinity fitting error: \n"
<< "- for the red channel is: " << vec_solution_r.back() << " gray level(s)" <<std::endl
<< "- for the green channel is: " << vec_solution_g.back() << " gray level(s)" << std::endl
<< "- for the blue channel is: " << vec_solution_b.back() << " gray level(s)" << std::endl;
std::cout << "\n\nFound solution_r:\n";
std::copy(vec_solution_r.begin(), vec_solution_r.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout << "\n\nFound solution_g:\n";
std::copy(vec_solution_g.begin(), vec_solution_g.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout << "\n\nFound solution_b:\n";
std::copy(vec_solution_b.begin(), vec_solution_b.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
std::cout << "\n\nThere is :\n" << set_indeximage.size() << " images to transform." << std::endl;
//-> convert solution to gain offset and creation of the LUT per image
C_Progress_display my_progress_bar( set_indeximage.size() );
for (std::set<size_t>::const_iterator iterSet = set_indeximage.begin();
iterSet != set_indeximage.end(); ++iterSet, ++my_progress_bar)
{
const size_t imaNum = *iterSet;
typedef Eigen::Matrix<double, 256, 1> Vec256;
std::vector< Vec256 > vec_map_lut(3);
const size_t nodeIndex = std::distance(set_indeximage.begin(), iterSet);
const double g_r = vec_solution_r[nodeIndex*2];
const double offset_r = vec_solution_r[nodeIndex*2+1];
const double g_g = vec_solution_g[nodeIndex*2];
const double offset_g = vec_solution_g[nodeIndex*2+1];
const double g_b = vec_solution_b[nodeIndex*2];
const double offset_b = vec_solution_b[nodeIndex*2+1];
for( size_t k = 0; k < 256; ++k)
{
vec_map_lut[0][k] = clamp( k * g_r + offset_r, 0., 255. );
vec_map_lut[1][k] = clamp( k * g_g + offset_g, 0., 255. );
vec_map_lut[2][k] = clamp( k * g_b + offset_b, 0., 255. );
}
Image< RGBColor > image_c;
ReadImage( _vec_fileNames[ imaNum ].c_str(), &image_c );
#ifdef I23DSFM_USE_OPENMP
#pragma omp parallel for
#endif
for( int j = 0; j < image_c.Height(); ++j )
{
for( int i = 0; i < image_c.Width(); ++i )
{
image_c(j, i)[0] = clamp(vec_map_lut[0][image_c(j, i)[0]], 0., 255.);
image_c(j, i)[1] = clamp(vec_map_lut[1][image_c(j, i)[1]], 0., 255.);
image_c(j, i)[2] = clamp(vec_map_lut[2][image_c(j, i)[2]], 0., 255.);
}
}
const std::string out_folder = stlplus::create_filespec( _sOutDirectory,
vec_selectionMethod[ _selectionMethod ] + "_" + vec_harmonizeMethod[ harmonizeMethod ]);
if( !stlplus::folder_exists( out_folder ) )
stlplus::folder_create( out_folder );
const std::string out_filename = stlplus::create_filespec( out_folder, stlplus::filename_part(_vec_fileNames[ imaNum ]) );
WriteImage( out_filename.c_str(), image_c );
}
return true;
}
bool ColorHarmonizationEngineGlobal::ReadInputData()
{
if ( !stlplus::is_folder( _sMatchesPath) ||
!stlplus::is_folder( _sOutDirectory) )
{
std::cerr << std::endl
<< "One of the required directory is not a valid directory" << std::endl;
return false;
}
if ( !stlplus::is_file( _sSfM_Data_Path ))
{
std::cerr << std::endl
<< "Invalid input sfm_data file: (" << stlplus::basename_part(_sMatchesFile) << ")" << std::endl;
return false;
}
if (!stlplus::is_file( _sMatchesFile ))
{
std::cerr << std::endl
<< "Invalid match file: (" << stlplus::basename_part(_sMatchesFile) << ")"<< std::endl;
return false;
}
// a. Read input scenes views
SfM_Data sfm_data;
if (!Load(sfm_data, _sSfM_Data_Path, ESfM_Data(VIEWS))) {
std::cerr << std::endl
<< "The input file \""<< _sSfM_Data_Path << "\" cannot be read" << std::endl;
return false;
}
// Read images names
for (Views::const_iterator iter = sfm_data.GetViews().begin();
iter != sfm_data.GetViews().end(); ++iter)
{
const View * v = iter->second.get();
_vec_fileNames.push_back( stlplus::create_filespec(sfm_data.s_root_path, v->s_Img_path));
_vec_imageSize.push_back( std::make_pair( v->ui_width, v->ui_height ));
}
// b. Read matches
if( !matching::PairedIndMatchImport( _sMatchesFile, _map_Matches ) )
{
cerr<< "Unable to read the geometric matrix matches" << endl;
return false;
}
// Read features:
for( size_t i = 0; i < _vec_fileNames.size(); ++i )
{
const size_t camIndex = i;
if( !loadFeatsFromFile(
stlplus::create_filespec( _sMatchesPath,
stlplus::basename_part( _vec_fileNames[ camIndex ] ),
".feat" ),
_map_feats[ camIndex ] ) )
{
cerr << "Bad reading of feature files" << endl;
return false;
}
}
graph::indexedGraph putativeGraph(getPairs(_map_Matches));
// Save the graph before cleaning:
graph::exportToGraphvizData(
stlplus::create_filespec( _sOutDirectory, "initialGraph" ),
putativeGraph.g );
return true;
}
bool ColorHarmonizationEngineGlobal::CleanGraph()
{
// Create a graph from pairwise correspondences:
// - keep the largest connected component.
graph::indexedGraph putativeGraph(getPairs(_map_Matches));
// Save the graph before cleaning:
graph::exportToGraphvizData(
stlplus::create_filespec(_sOutDirectory, "initialGraph"),
putativeGraph.g);
const int connectedComponentCount = lemon::countConnectedComponents(putativeGraph.g);
std::cout << "\n"
<< "ColorHarmonizationEngineGlobal::CleanGraph() :: => connected Component cardinal: "
<< connectedComponentCount << std::endl;
if (connectedComponentCount > 1) // If more than one CC, keep the largest
{
// Search the largest CC index
const std::map<IndexT, std::set<lemon::ListGraph::Node> > map_subgraphs =
i23dSFM::graph::exportGraphToMapSubgraphs<lemon::ListGraph, IndexT>(putativeGraph.g);
size_t count = std::numeric_limits<size_t>::min();
std::map<IndexT, std::set<lemon::ListGraph::Node> >::const_iterator iterLargestCC = map_subgraphs.end();
for(std::map<IndexT, std::set<lemon::ListGraph::Node> >::const_iterator iter = map_subgraphs.begin();
iter != map_subgraphs.end(); ++iter)
{
if (iter->second.size() > count) {
count = iter->second.size();
iterLargestCC = iter;
}
std::cout << "Connected component of size : " << iter->second.size() << std::endl;
}
//-- Remove all nodes that are not listed in the largest CC
for(std::map<IndexT, std::set<lemon::ListGraph::Node> >::const_iterator iter = map_subgraphs.begin();
iter != map_subgraphs.end(); ++iter)
{
if (iter == iterLargestCC) // Skip this CC since it's the one we want to keep
continue;
const std::set<lemon::ListGraph::Node> & ccSet = iter->second;
for (std::set<lemon::ListGraph::Node>::const_iterator iter2 = ccSet.begin();
iter2 != ccSet.end(); ++iter2)
{
// Remove all outgoing edges
for (lemon::ListGraph::OutArcIt e(putativeGraph.g, *iter2); e!=INVALID; ++e)
{
putativeGraph.g.erase(e);
const IndexT Idu = (*putativeGraph.map_nodeMapIndex)[putativeGraph.g.target(e)];
const IndexT Idv = (*putativeGraph.map_nodeMapIndex)[putativeGraph.g.source(e)];
matching::PairWiseMatches::iterator iterM = _map_Matches.find(std::make_pair(Idu,Idv));
if( iterM != _map_Matches.end())
{
_map_Matches.erase(iterM);
}
else // Try to find the opposite directed edge
{
iterM = _map_Matches.find(std::make_pair(Idv,Idu));
if( iterM != _map_Matches.end())
_map_Matches.erase(iterM);
}
}
}
}
}
// Save the graph after cleaning:
graph::exportToGraphvizData(
stlplus::create_filespec(_sOutDirectory, "cleanedGraph"),
putativeGraph.g);
std::cout << "\n"
<< "Cardinal of nodes: " << lemon::countNodes(putativeGraph.g) << "\n"
<< "Cardinal of edges: " << lemon::countEdges(putativeGraph.g) << std::endl
<< std::endl;
return true;
}
} // namespace i23dSFM
| 35.270451 | 140 | 0.643773 | [
"vector",
"transform"
] |
78dbf150f99ccd784c595512a45cc9ffb3fd50d3 | 12,224 | hpp | C++ | include/codegen/include/System/Text/RegularExpressions/Regex.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/Text/RegularExpressions/Regex.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/Text/RegularExpressions/Regex.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:17 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: System.Runtime.Serialization.ISerializable
#include "System/Runtime/Serialization/ISerializable.hpp"
// Including type: System.Text.RegularExpressions.RegexOptions
#include "System/Text/RegularExpressions/RegexOptions.hpp"
// Including type: System.TimeSpan
#include "System/TimeSpan.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Text::RegularExpressions
namespace System::Text::RegularExpressions {
// Forward declaring type: RegexRunnerFactory
class RegexRunnerFactory;
// Forward declaring type: ExclusiveReference
class ExclusiveReference;
// Forward declaring type: SharedReference
class SharedReference;
// Forward declaring type: RegexCode
class RegexCode;
// Forward declaring type: CachedCodeEntry
class CachedCodeEntry;
// Forward declaring type: Match
class Match;
// Forward declaring type: MatchEvaluator
class MatchEvaluator;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: Hashtable
class Hashtable;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: LinkedList`1<T>
template<typename T>
class LinkedList_1;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
// Forward declaring type: StreamingContext
struct StreamingContext;
}
// Completed forward declares
// Type namespace: System.Text.RegularExpressions
namespace System::Text::RegularExpressions {
// Autogenerated type: System.Text.RegularExpressions.Regex
class Regex : public ::Il2CppObject, public System::Runtime::Serialization::ISerializable {
public:
// protected internal System.String pattern
// Offset: 0x10
::Il2CppString* pattern;
// protected internal System.Text.RegularExpressions.RegexRunnerFactory factory
// Offset: 0x18
System::Text::RegularExpressions::RegexRunnerFactory* factory;
// protected internal System.Text.RegularExpressions.RegexOptions roptions
// Offset: 0x20
System::Text::RegularExpressions::RegexOptions roptions;
// Get static field: static private readonly System.TimeSpan MaximumMatchTimeout
static System::TimeSpan _get_MaximumMatchTimeout();
// Set static field: static private readonly System.TimeSpan MaximumMatchTimeout
static void _set_MaximumMatchTimeout(System::TimeSpan value);
// Get static field: static public readonly System.TimeSpan InfiniteMatchTimeout
static System::TimeSpan _get_InfiniteMatchTimeout();
// Set static field: static public readonly System.TimeSpan InfiniteMatchTimeout
static void _set_InfiniteMatchTimeout(System::TimeSpan value);
// protected internal System.TimeSpan internalMatchTimeout
// Offset: 0x28
System::TimeSpan internalMatchTimeout;
// Get static field: static readonly System.TimeSpan FallbackDefaultMatchTimeout
static System::TimeSpan _get_FallbackDefaultMatchTimeout();
// Set static field: static readonly System.TimeSpan FallbackDefaultMatchTimeout
static void _set_FallbackDefaultMatchTimeout(System::TimeSpan value);
// Get static field: static readonly System.TimeSpan DefaultMatchTimeout
static System::TimeSpan _get_DefaultMatchTimeout();
// Set static field: static readonly System.TimeSpan DefaultMatchTimeout
static void _set_DefaultMatchTimeout(System::TimeSpan value);
// protected internal System.Collections.Hashtable caps
// Offset: 0x30
System::Collections::Hashtable* caps;
// protected internal System.Collections.Hashtable capnames
// Offset: 0x38
System::Collections::Hashtable* capnames;
// protected internal System.String[] capslist
// Offset: 0x40
::Array<::Il2CppString*>* capslist;
// protected internal System.Int32 capsize
// Offset: 0x48
int capsize;
// System.Text.RegularExpressions.ExclusiveReference runnerref
// Offset: 0x50
System::Text::RegularExpressions::ExclusiveReference* runnerref;
// System.Text.RegularExpressions.SharedReference replref
// Offset: 0x58
System::Text::RegularExpressions::SharedReference* replref;
// System.Text.RegularExpressions.RegexCode code
// Offset: 0x60
System::Text::RegularExpressions::RegexCode* code;
// System.Boolean refsInitialized
// Offset: 0x68
bool refsInitialized;
// Get static field: static System.Collections.Generic.LinkedList`1<System.Text.RegularExpressions.CachedCodeEntry> livecode
static System::Collections::Generic::LinkedList_1<System::Text::RegularExpressions::CachedCodeEntry*>* _get_livecode();
// Set static field: static System.Collections.Generic.LinkedList`1<System.Text.RegularExpressions.CachedCodeEntry> livecode
static void _set_livecode(System::Collections::Generic::LinkedList_1<System::Text::RegularExpressions::CachedCodeEntry*>* value);
// Get static field: static System.Int32 cacheSize
static int _get_cacheSize();
// Set static field: static System.Int32 cacheSize
static void _set_cacheSize(int value);
// public System.Void .ctor(System.String pattern)
// Offset: 0x1208C14
static Regex* New_ctor(::Il2CppString* pattern);
// public System.Void .ctor(System.String pattern, System.Text.RegularExpressions.RegexOptions options)
// Offset: 0x120912C
static Regex* New_ctor(::Il2CppString* pattern, System::Text::RegularExpressions::RegexOptions options);
// private System.Void .ctor(System.String pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout, System.Boolean useCache)
// Offset: 0x1208C9C
static Regex* New_ctor(::Il2CppString* pattern, System::Text::RegularExpressions::RegexOptions options, System::TimeSpan matchTimeout, bool useCache);
// protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1209A44
static Regex* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context);
// static protected internal System.Void ValidateMatchTimeout(System.TimeSpan matchTimeout)
// Offset: 0x12091B8
static void ValidateMatchTimeout(System::TimeSpan matchTimeout);
// static private System.TimeSpan InitDefaultMatchTimeout()
// Offset: 0x1209C74
static System::TimeSpan InitDefaultMatchTimeout();
// public System.Text.RegularExpressions.RegexOptions get_Options()
// Offset: 0x1209ECC
System::Text::RegularExpressions::RegexOptions get_Options();
// public System.TimeSpan get_MatchTimeout()
// Offset: 0x1209ED4
System::TimeSpan get_MatchTimeout();
// public System.Boolean get_RightToLeft()
// Offset: 0x1209EDC
bool get_RightToLeft();
// public System.String GroupNameFromNumber(System.Int32 i)
// Offset: 0x1207410
::Il2CppString* GroupNameFromNumber(int i);
// static public System.Boolean IsMatch(System.String input, System.String pattern)
// Offset: 0x1209EFC
static bool IsMatch(::Il2CppString* input, ::Il2CppString* pattern);
// static public System.Boolean IsMatch(System.String input, System.String pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout)
// Offset: 0x1209F80
static bool IsMatch(::Il2CppString* input, ::Il2CppString* pattern, System::Text::RegularExpressions::RegexOptions options, System::TimeSpan matchTimeout);
// public System.Boolean IsMatch(System.String input)
// Offset: 0x120A014
bool IsMatch(::Il2CppString* input);
// public System.Boolean IsMatch(System.String input, System.Int32 startat)
// Offset: 0x120A0BC
bool IsMatch(::Il2CppString* input, int startat);
// static public System.Text.RegularExpressions.Match Match(System.String input, System.String pattern)
// Offset: 0x120A174
static System::Text::RegularExpressions::Match* Match(::Il2CppString* input, ::Il2CppString* pattern);
// static public System.Text.RegularExpressions.Match Match(System.String input, System.String pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout)
// Offset: 0x120A1F8
static System::Text::RegularExpressions::Match* Match(::Il2CppString* input, ::Il2CppString* pattern, System::Text::RegularExpressions::RegexOptions options, System::TimeSpan matchTimeout);
// public System.Text.RegularExpressions.Match Match(System.String input)
// Offset: 0x120A28C
System::Text::RegularExpressions::Match* Match(::Il2CppString* input);
// public System.Text.RegularExpressions.Match Match(System.String input, System.Int32 startat)
// Offset: 0x120A334
System::Text::RegularExpressions::Match* Match(::Il2CppString* input, int startat);
// public System.String Replace(System.String input, System.Text.RegularExpressions.MatchEvaluator evaluator)
// Offset: 0x120A3E0
::Il2CppString* Replace(::Il2CppString* input, System::Text::RegularExpressions::MatchEvaluator* evaluator);
// public System.String Replace(System.String input, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Int32 count, System.Int32 startat)
// Offset: 0x120A494
::Il2CppString* Replace(::Il2CppString* input, System::Text::RegularExpressions::MatchEvaluator* evaluator, int count, int startat);
// protected System.Void InitializeReferences()
// Offset: 0x1209560
void InitializeReferences();
// System.Text.RegularExpressions.Match Run(System.Boolean quick, System.Int32 prevlen, System.String input, System.Int32 beginning, System.Int32 length, System.Int32 startat)
// Offset: 0x1207BB8
System::Text::RegularExpressions::Match* Run(bool quick, int prevlen, ::Il2CppString* input, int beginning, int length, int startat);
// static private System.Text.RegularExpressions.CachedCodeEntry LookupCachedAndUpdate(System.String key)
// Offset: 0x1209328
static System::Text::RegularExpressions::CachedCodeEntry* LookupCachedAndUpdate(::Il2CppString* key);
// private System.Text.RegularExpressions.CachedCodeEntry CacheCode(System.String key)
// Offset: 0x1209654
System::Text::RegularExpressions::CachedCodeEntry* CacheCode(::Il2CppString* key);
// protected System.Boolean UseOptionR()
// Offset: 0x1209EE8
bool UseOptionR();
// System.Boolean UseOptionInvariant()
// Offset: 0x120A54C
bool UseOptionInvariant();
// static private System.Void .cctor()
// Offset: 0x120A5F8
static void _cctor();
// protected System.Void .ctor()
// Offset: 0x1208B98
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static Regex* New_ctor();
// private System.Void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1209BA0
// Implemented from: System.Runtime.Serialization.ISerializable
// Base method: System.Void ISerializable::GetObjectData(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext context)
void System_Runtime_Serialization_ISerializable_GetObjectData(System::Runtime::Serialization::SerializationInfo* si, System::Runtime::Serialization::StreamingContext context);
// public override System.String ToString()
// Offset: 0x1209EF4
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::Il2CppString* ToString();
}; // System.Text.RegularExpressions.Regex
}
DEFINE_IL2CPP_ARG_TYPE(System::Text::RegularExpressions::Regex*, "System.Text.RegularExpressions", "Regex");
#pragma pack(pop)
| 55.563636 | 193 | 0.760389 | [
"object"
] |
78ded03088b5f812036eff7ae8dd8128aa76468b | 60,858 | cpp | C++ | deps/steamworks_sdk/glmgr/cglmtex.cpp | Ryjek0/greenworks | 0ab7427d829e0f5e9d47c6c5ad18fdde8aa96225 | [
"MIT"
] | null | null | null | deps/steamworks_sdk/glmgr/cglmtex.cpp | Ryjek0/greenworks | 0ab7427d829e0f5e9d47c6c5ad18fdde8aa96225 | [
"MIT"
] | null | null | null | deps/steamworks_sdk/glmgr/cglmtex.cpp | Ryjek0/greenworks | 0ab7427d829e0f5e9d47c6c5ad18fdde8aa96225 | [
"MIT"
] | null | null | null | //============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// cglmtex.cpp
//
//===============================================================================
#include "glmgr.h"
#include "cglmtex.h"
#include "dxabstract.h"
//===============================================================================
#define TEXSPACE_LOGGING 0
// encoding layout to an index where the bits read
// 4 : 1 if compressed
// 2 : 1 if not power of two
// 1 : 1 if mipmapped
bool pwroftwo (int val )
{
return (val & (val-1)) == 0;
}
int sEncodeLayoutAsIndex( GLMTexLayoutKey *key )
{
int index = 0;
if (key->m_texFlags & kGLMTexMipped)
{
index |= 1;
}
if ( ! ( pwroftwo(key->m_xSize) && pwroftwo(key->m_ySize) && pwroftwo(key->m_zSize) ) )
{
// if not all power of two
index |= 2;
}
if (GetFormatDesc( key->m_texFormat )->m_chunkSize >1 )
{
index |= 4;
}
return index;
}
static unsigned long g_texGlobalBytes[8];
//===============================================================================
const GLMTexFormatDesc g_formatDescTable[] =
{
// not yet handled by this table:
// D3DFMT_INDEX16, D3DFMT_VERTEXDATA // D3DFMT_INDEX32,
// WTF { D3DFMT_R5G6R5 ???, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 1, 2 },
// WTF { D3DFMT_A ???, GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE, 1, 1 },
// ??? D3DFMT_V8U8,
// ??? D3DFMT_Q8W8V8U8,
// ??? D3DFMT_X8L8V8U8,
// ??? D3DFMT_R32F,
// ??? D3DFMT_D24X4S4 unsure how to handle or if it is ever used..
// ??? D3DFMT_D15S1 ever used ?
// ??? D3DFMT_D24X8 ever used?
// summ-name d3d-format gl-int-format gl-int-format-srgb gl-data-format gl-data-type chunksize, bytes-per-sqchunk
{ "_D16", D3DFMT_D16, GL_DEPTH_COMPONENT16, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 1, 2 },
{ "_D24X8", D3DFMT_D24X8, GL_DEPTH_COMPONENT24, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 1, 4 }, // ??? unsure on this one
{ "_D24S8", D3DFMT_D24S8, GL_DEPTH24_STENCIL8_EXT, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, 1, 4 },
{ "_A8R8G8B8", D3DFMT_A8R8G8B8, GL_RGBA8, GL_SRGB8_ALPHA8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 },
{ "_A4R4G4B4", D3DFMT_A4R4G4B4, GL_RGBA4, 0, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, 1, 2 },
{ "_X8R8G8B8", D3DFMT_X8R8G8B8, GL_RGB8, GL_SRGB8_EXT, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 },
{ "_X1R5G5B5", D3DFMT_X1R5G5B5, GL_RGB5, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 1, 2 },
{ "_A1R5G5B5", D3DFMT_A1R5G5B5, GL_RGB5_A1, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 1, 2 },
{ "_L8", D3DFMT_L8, GL_LUMINANCE8, GL_SLUMINANCE8_EXT, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, 1 },
{ "_A8L8", D3DFMT_A8L8, GL_LUMINANCE8_ALPHA8, GL_SLUMINANCE8_ALPHA8_EXT, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 1, 2 },
{ "_DXT1", D3DFMT_DXT1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, GL_RGB, GL_UNSIGNED_BYTE, 4, 8 },
{ "_DXT3", D3DFMT_DXT3, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, 4, 16 },
{ "_DXT5", D3DFMT_DXT5, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, 4, 16 },
{ "_A16B16G16R16F", D3DFMT_A16B16G16R16F, GL_RGBA16F_ARB, 0, GL_RGBA, GL_HALF_FLOAT_ARB, 1, 8 },
{ "_A16B16G16R16", D3DFMT_A16B16G16R16, GL_RGBA16, 0, GL_RGBA, GL_UNSIGNED_SHORT, 1, 8 }, // 16bpc integer tex
{ "_A32B32G32R32F", D3DFMT_A32B32G32R32F, GL_RGBA32F_ARB, 0, GL_RGBA, GL_FLOAT, 1, 16 },
{ "_R8G8B8", D3DFMT_R8G8B8, GL_RGB8, GL_SRGB8_EXT, GL_BGR, GL_UNSIGNED_BYTE, 1, 3 },
{ "_A8", D3DFMT_A8, GL_ALPHA8, 0, GL_ALPHA, GL_UNSIGNED_BYTE, 1, 1 },
{ "_R5G6B5", D3DFMT_R5G6B5, GL_RGB, GL_SRGB_EXT, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 1, 2 },
// fakey tex formats: the stated GL format and the memory layout may not agree (U8V8 for example)
// _Q8W8V8U8 we just pass through as RGBA bytes. Shader does scale/bias fix
{ "_Q8W8V8U8", D3DFMT_Q8W8V8U8, GL_RGBA8, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 1, 4 }, // straight ripoff of D3DFMT_A8R8G8B8
// U8V8 is exposed to the client as 2-bytes per texel, but we download it as 3-byte RGB.
// WriteTexels needs to do that conversion from rg8 to rgb8 in order to be able to download it correctly
{ "_V8U8", D3DFMT_V8U8, GL_RGB8, 0, GL_RG, GL_BYTE, 1, 2 },
/*
// NV shadow depth tex
D3DFMT_NV_INTZ = 0x5a544e49, // MAKEFOURCC('I','N','T','Z')
D3DFMT_NV_RAWZ = 0x5a574152, // MAKEFOURCC('R','A','W','Z')
// NV null tex
D3DFMT_NV_NULL = 0x4c4c554e, // MAKEFOURCC('N','U','L','L')
// ATI shadow depth tex
D3DFMT_ATI_D16 = 0x36314644, // MAKEFOURCC('D','F','1','6')
D3DFMT_ATI_D24S8 = 0x34324644, // MAKEFOURCC('D','F','2','4')
// ATI 1N and 2N compressed tex
D3DFMT_ATI_2N = 0x32495441, // MAKEFOURCC('A', 'T', 'I', '2')
D3DFMT_ATI_1N = 0x31495441, // MAKEFOURCC('A', 'T', 'I', '1')
*/
};
int g_formatDescTableCount = sizeof(g_formatDescTable) / sizeof( g_formatDescTable[0] );
const GLMTexFormatDesc *GetFormatDesc( D3DFORMAT format )
{
for( int i=0; i<g_formatDescTableCount; i++)
{
if (g_formatDescTable[i].m_d3dFormat == format)
{
return &g_formatDescTable[i];
}
}
return (const GLMTexFormatDesc *)NULL; // not found
}
//===============================================================================
void InsertTexelComponentFixed( float value, int width, unsigned long *valuebuf )
{
unsigned long range = (1<<width);
unsigned long scaled = (value * (float) range) * (range-1) / (range);
if (scaled >= range) Debugger();
*valuebuf = (*valuebuf << width) | scaled;
}
// return true if successful
bool GLMGenTexels( GLMGenTexelParams *params )
{
unsigned char chunkbuf[256]; // can't think of any chunk this big..
const GLMTexFormatDesc *format = GetFormatDesc( params->m_format );
if (!format)
{
return FALSE; // fail
}
// this section just generates one square chunk in the desired format
unsigned long *temp32 = (unsigned long*)chunkbuf;
unsigned int chunksize = 0; // we can sanity check against the format table with this
switch( params->m_format )
{
// comment shows byte order in RAM
// lowercase is bit arrangement in a byte
case D3DFMT_A8R8G8B8: // B G R A
InsertTexelComponentFixed( params->a, 8, temp32 ); // A is inserted first and winds up at most significant bits after insertions follow
InsertTexelComponentFixed( params->r, 8, temp32 );
InsertTexelComponentFixed( params->g, 8, temp32 );
InsertTexelComponentFixed( params->b, 8, temp32 );
chunksize = 4;
break;
case D3DFMT_A4R4G4B4: // [ggggbbbb] [aaaarrrr] RA (nibbles)
InsertTexelComponentFixed( params->a, 4, temp32 );
InsertTexelComponentFixed( params->r, 4, temp32 );
InsertTexelComponentFixed( params->g, 4, temp32 );
InsertTexelComponentFixed( params->b, 4, temp32 );
chunksize = 2;
break;
case D3DFMT_X8R8G8B8: // B G R X
InsertTexelComponentFixed( 0.0, 8, temp32 );
InsertTexelComponentFixed( params->r, 8, temp32 );
InsertTexelComponentFixed( params->g, 8, temp32 );
InsertTexelComponentFixed( params->b, 8, temp32 );
chunksize = 4;
break;
case D3DFMT_X1R5G5B5: // [gggbbbbb] [xrrrrrgg]
InsertTexelComponentFixed( 0.0, 1, temp32 );
InsertTexelComponentFixed( params->r, 5, temp32 );
InsertTexelComponentFixed( params->g, 5, temp32 );
InsertTexelComponentFixed( params->b, 5, temp32 );
chunksize = 2;
break;
case D3DFMT_A1R5G5B5: // [gggbbbbb] [arrrrrgg]
InsertTexelComponentFixed( params->a, 1, temp32 );
InsertTexelComponentFixed( params->r, 5, temp32 );
InsertTexelComponentFixed( params->g, 5, temp32 );
InsertTexelComponentFixed( params->b, 5, temp32 );
chunksize = 2;
break;
case D3DFMT_L8: // L // caller, use R for L
InsertTexelComponentFixed( params->r, 8, temp32 );
chunksize = 1;
break;
case D3DFMT_A8L8: // L A // caller, use R for L and A for A
InsertTexelComponentFixed( params->a, 8, temp32 );
InsertTexelComponentFixed( params->r, 8, temp32 );
chunksize = 2;
break;
case D3DFMT_R8G8B8: // B G R
InsertTexelComponentFixed( params->r, 8, temp32 );
InsertTexelComponentFixed( params->g, 8, temp32 );
InsertTexelComponentFixed( params->b, 8, temp32 );
chunksize = 3;
break;
case D3DFMT_A8: // A
InsertTexelComponentFixed( params->a, 8, temp32 );
chunksize = 1;
break;
case D3DFMT_R5G6B5: // [gggbbbbb] [rrrrrggg]
InsertTexelComponentFixed( params->r, 5, temp32 );
InsertTexelComponentFixed( params->g, 6, temp32 );
InsertTexelComponentFixed( params->b, 5, temp32 );
chunksize = 2;
break;
case D3DFMT_DXT1:
{
memset( temp32, 0, 8 ); // zap 8 bytes
// two 565 RGB words followed by 32 bits of 2-bit interp values for a 4x4 block
// we write the same color to both slots and all zeroes for the mask (one color total)
unsigned long dxt1_color = 0;
// generate one such word and clone it
InsertTexelComponentFixed( params->r, 5, &dxt1_color );
InsertTexelComponentFixed( params->g, 6, &dxt1_color );
InsertTexelComponentFixed( params->b, 5, &dxt1_color );
// dupe
dxt1_color = dxt1_color | (dxt1_color<<16);
// write into chunkbuf
*(unsigned long*)&chunkbuf[0] = dxt1_color;
// color mask bits after that are already set to all zeroes. chunk is done.
chunksize = 8;
}
break;
case D3DFMT_DXT3:
{
memset( temp32, 0, 16 ); // zap 16 bytes
// eight bytes of alpha (16 4-bit alpha nibbles)
// followed by a DXT1 block
unsigned long dxt3_alpha = 0;
for( int i=0; i<8; i++)
{
// splat same alpha through block
InsertTexelComponentFixed( params->a, 4, &dxt3_alpha );
}
unsigned long dxt3_color = 0;
// generate one such word and clone it
InsertTexelComponentFixed( params->r, 5, &dxt3_color );
InsertTexelComponentFixed( params->g, 6, &dxt3_color );
InsertTexelComponentFixed( params->b, 5, &dxt3_color );
// dupe
dxt3_color = dxt3_color | (dxt3_color<<16);
// write into chunkbuf
*(unsigned long*)&chunkbuf[0] = dxt3_alpha;
*(unsigned long*)&chunkbuf[4] = dxt3_alpha;
*(unsigned long*)&chunkbuf[8] = dxt3_color;
*(unsigned long*)&chunkbuf[12] = dxt3_color;
chunksize = 16;
}
break;
case D3DFMT_DXT5:
{
memset( temp32, 0, 16 ); // zap 16 bytes
// DXT5 has 8 bytes of compressed alpha, then 8 bytes of compressed RGB like DXT1.
// the 8 alpha bytes are 2 bytes of endpoint alpha values, then 16x3 bits of interpolants.
// so to write a single alpha value, just figure out the value, store it in both the first two bytes then store zeroes.
InsertTexelComponentFixed( params->a, 8, (unsigned long*)&chunkbuf[0] );
InsertTexelComponentFixed( params->a, 8, (unsigned long*)&chunkbuf[0] );
// rest of the alpha mask was already zeroed.
// now do colors
unsigned long dxt5_color = 0;
// generate one such word and clone it
InsertTexelComponentFixed( params->r, 5, &dxt5_color );
InsertTexelComponentFixed( params->g, 6, &dxt5_color );
InsertTexelComponentFixed( params->b, 5, &dxt5_color );
// dupe
dxt5_color = dxt5_color | (dxt5_color<<16);
// write into chunkbuf
*(unsigned long*)&chunkbuf[8] = dxt5_color;
*(unsigned long*)&chunkbuf[12] = dxt5_color;
chunksize = 16;
}
break;
case D3DFMT_A32B32G32R32F:
{
*(float*)&chunkbuf[0] = params->r;
*(float*)&chunkbuf[4] = params->g;
*(float*)&chunkbuf[8] = params->b;
*(float*)&chunkbuf[12] = params->a;
chunksize = 16;
}
break;
case D3DFMT_A16B16G16R16:
memset( chunkbuf, 0, 8 );
// R and G wind up in the first 32 bits
// B and A wind up in the second 32 bits
InsertTexelComponentFixed( params->a, 16, (unsigned long*)&chunkbuf[4] ); // winds up as MSW of second word (note [4]) - thus last in RAM
InsertTexelComponentFixed( params->b, 16, (unsigned long*)&chunkbuf[4] );
InsertTexelComponentFixed( params->g, 16, (unsigned long*)&chunkbuf[0] );
InsertTexelComponentFixed( params->r, 16, (unsigned long*)&chunkbuf[0] ); // winds up as LSW of first word, thus first in RAM
chunksize = 8;
break;
// not done yet
//case D3DFMT_D16:
//case D3DFMT_D24X8:
//case D3DFMT_D24S8:
//case D3DFMT_A16B16G16R16F:
default:
return FALSE; // fail
break;
}
// once the chunk buffer is filled..
// sanity check the reported chunk size.
if (chunksize != format->m_bytesPerSquareChunk)
{
Debugger();
return FALSE;
}
// verify that the amount you want to write will not exceed the limit byte count
unsigned long destByteCount = chunksize * params->m_chunkCount;
if (destByteCount > params->m_byteCountLimit)
{
Debugger();
return FALSE;
}
// write the bytes.
unsigned char *destP = (unsigned char*)params->m_dest;
for( int chunk=0; chunk < params->m_chunkCount; chunk++)
{
for( int byteindex = 0; byteindex < chunksize; byteindex++)
{
*destP++ = chunkbuf[byteindex];
}
}
params->m_bytesWritten = destP - (unsigned char*)params->m_dest;
return TRUE;
}
//===============================================================================
CGLMTexLayoutTable::CGLMTexLayoutTable()
{
}
GLMTexLayout *CGLMTexLayoutTable::NewLayoutRef( GLMTexLayoutKey *key )
{
// look up 'key' in the map and see if it's a hit, if so, bump the refcount and return
// if not, generate a completed layout based on the key, add to map, set refcount to 1, return that
const GLMTexFormatDesc *formatDesc = GetFormatDesc( key->m_texFormat );
if (!formatDesc)
{
GLMStop(); // bad news
}
bool compression = (formatDesc->m_chunkSize > 1);
GLMTexLayoutKeyMap::iterator p = m_layoutMap.find( *key );
if (p != m_layoutMap.end())
{
// found it
//printf(" -hit- ");
GLMTexLayout *ptr = (*p).second;
// bump ref count
ptr->m_refCount++;
return ptr;
}
else
{
//printf(" -miss- ");
// need to make a new one
// to allocate it, we need to know how big to make it (slice count)
// figure out how many mip levels are in play
int mipCount = 1;
if (key->m_texFlags & kGLMTexMipped)
{
int largestAxis = key->m_xSize;
if (key->m_ySize > largestAxis)
largestAxis = key->m_ySize;
if (key->m_zSize > largestAxis)
largestAxis = key->m_zSize;
mipCount = 0;
while( largestAxis > 0 )
{
mipCount ++;
largestAxis >>= 1;
}
}
int faceCount = 1;
if (key->m_texGLTarget == GL_TEXTURE_CUBE_MAP)
{
faceCount = 6;
}
int sliceCount = mipCount * faceCount;
if (key->m_texFlags & kGLMTexMultisampled)
{
Assert( (key->m_texGLTarget == GL_TEXTURE_2D) );
Assert( sliceCount == 1 );
// assume non mipped
Assert( (key->m_texFlags & kGLMTexMipped) == 0 );
Assert( (key->m_texFlags & kGLMTexMippedAuto) == 0 );
// assume renderable and srgb
Assert( (key->m_texFlags & kGLMTexRenderable) !=0 );
//Assert( (key->m_texFlags & kGLMTexSRGB) !=0 ); //FIXME don't assert on making depthstencil surfaces which are non srgb
// double check sample count (FIXME need real limit check here against device/driver)
Assert( (key->m_texSamples==2) || (key->m_texSamples==4) || (key->m_texSamples==6) || (key->m_texSamples==8) );
}
// now we know enough to allocate and populate the new tex layout.
// malloc the new layout
int layoutSize = sizeof( GLMTexLayout ) + (sliceCount * sizeof( GLMTexLayoutSlice ));
GLMTexLayout *layout = (GLMTexLayout *)malloc( layoutSize );
memset( layout, 0, layoutSize );
// clone the key in there
memset( &layout->m_key, 0x00, sizeof(layout->m_key) );
layout->m_key = *key;
// set refcount
layout->m_refCount = 1;
// save the format desc
layout->m_format = (GLMTexFormatDesc *)formatDesc;
// we know the mipcount from before
layout->m_mipCount = mipCount;
// we know the face count too
layout->m_faceCount = faceCount;
// slice count is the product
layout->m_sliceCount = mipCount * faceCount;
// we can now fill in the slices.
GLMTexLayoutSlice *slicePtr = &layout->m_slices[0];
int storageOffset = 0;
bool compressed = (formatDesc->m_chunkSize > 1); // true if DXT
for( int mip = 0; mip < mipCount; mip ++ )
{
for( int face = 0; face < faceCount; face++ )
{
// note application of chunk size which is 1 for uncompressed, and 4 for compressed tex (DXT)
// note also that the *dimensions* must scale down to 1
// but that the *storage* cannot go below 4x4.
// we introduce the "storage sizes" which are clamped, to compute the storage footprint.
int storage_x,storage_y,storage_z;
slicePtr->m_xSize = layout->m_key.m_xSize >> mip;
slicePtr->m_xSize = std::max( slicePtr->m_xSize, 1 ); // dimension can't go to zero
storage_x = std::max( slicePtr->m_xSize, formatDesc->m_chunkSize ); // storage extent can't go below chunk size
slicePtr->m_ySize = layout->m_key.m_ySize >> mip;
slicePtr->m_ySize = std::max( slicePtr->m_ySize, 1 ); // dimension can't go to zero
storage_y = std::max( slicePtr->m_ySize, formatDesc->m_chunkSize ); // storage extent can't go below chunk size
slicePtr->m_zSize = layout->m_key.m_zSize >> mip;
slicePtr->m_zSize = std::max( slicePtr->m_zSize, 1 ); // dimension can't go to zero
storage_z = std::max( slicePtr->m_zSize, 1); // storage extent for Z cannot go below '1'.
//if (compressed) NO NO NO do not lie about the dimensionality, just fudge the storage.
//{
// // round up to multiple of 4 in X and Y axes
// slicePtr->m_xSize = (slicePtr->m_xSize+3) & (~3);
// slicePtr->m_ySize = (slicePtr->m_ySize+3) & (~3);
//}
int xchunks = (storage_x / formatDesc->m_chunkSize );
int ychunks = (storage_y / formatDesc->m_chunkSize );
slicePtr->m_storageSize = (xchunks * ychunks * formatDesc->m_bytesPerSquareChunk) * storage_z;
slicePtr->m_storageOffset = storageOffset;
storageOffset += slicePtr->m_storageSize;
storageOffset = ( (storageOffset+0x0F) & (~0x0F)); // keep each MIP starting on a 16 byte boundary.
slicePtr++;
}
}
layout->m_storageTotalSize = storageOffset;
//printf("\n size %08x for key (x=%d y=%d z=%d, fmt=%08x, bpsc=%d)", layout->m_storageTotalSize, key->m_xSize, key->m_ySize, key->m_zSize, key->m_texFormat, formatDesc->m_bytesPerSquareChunk );
// generate summary
// "target, format, +/- mips, base size"
char scratch[1024];
const char *targetname;
switch( key->m_texGLTarget )
{
case GL_TEXTURE_2D: targetname = "2D "; break;
case GL_TEXTURE_3D: targetname = "3D "; break;
case GL_TEXTURE_CUBE_MAP: targetname = "CUBE"; break;
}
sprintf( scratch, "[%s %s %dx%dx%d mips=%d slices=%d flags=%02lX%s]",
targetname,
formatDesc->m_formatSummary,
layout->m_key.m_xSize, layout->m_key.m_ySize, layout->m_key.m_zSize,
mipCount,
sliceCount,
layout->m_key.m_texFlags,
(layout->m_key.m_texFlags & kGLMTexSRGB) ? " SRGB" : ""
);
layout->m_layoutSummary = strdup( scratch );
//GLMPRINTF(("-D- new tex layout [ %s ]", scratch ));
// then insert into map. disregard returned index.
m_layoutMap[ layout->m_key ] = layout;
return layout;
}
}
void CGLMTexLayoutTable::DelLayoutRef( GLMTexLayout *layout )
{
// locate layout in hash, drop refcount
GLMTexLayoutKeyMap::iterator p = m_layoutMap.find( layout->m_key );
if (p != m_layoutMap.end())
{
// found it
GLMTexLayout *ptr = (*p).second;
// drop ref count
ptr->m_refCount--;
}
}
void CGLMTexLayoutTable::DumpStats( )
{
for( GLMTexLayoutKeyMap::iterator p = m_layoutMap.begin(); p != m_layoutMap.end(); p++ )
{
GLMTexLayout *layout = (*p).second;
// print it out
printf("\n%05d instances %08d bytes %08d totbytes %s", layout->m_refCount, layout->m_storageTotalSize, (layout->m_refCount*layout->m_storageTotalSize), layout->m_layoutSummary );
}
}
#if 0
ConVar gl_texclientstorage( "gl_texclientstorage", "1" ); // default 1 for L4D2
ConVar gl_texmsaalog ( "gl_texmsaalog", "0");
ConVar gl_rt_forcergba ( "gl_rt_forcergba", "1" ); // on teximage of a renderable tex, pass GL_RGBA in place of GL_BGRA
ConVar gl_minimize_rt_tex ( "gl_minimize_rt_tex", "0" ); // if 1, set the GL_TEXTURE_MINIMIZE_STORAGE_APPLE texture parameter to cut off mipmaps for RT's
ConVar gl_minimize_all_tex ( "gl_minimize_all_tex", "1" ); // if 1, set the GL_TEXTURE_MINIMIZE_STORAGE_APPLE texture parameter to cut off mipmaps for textures which are unmipped
ConVar gl_minimize_tex_log ( "gl_minimize_tex_log", "0" ); // if 1, printf the names of the tex that got minimized
#else
int gl_texclientstorage = 1;
int gl_texmsaalog = 0;
int gl_rt_forcergba = 1;
int gl_minimize_rt_tex = 0;
int gl_minimize_all_tex =1;
int gl_minimize_tex_log =0;
#endif
CGLMTex::CGLMTex( GLMContext *ctx, GLMTexLayout *layout, GLMTexSamplingParams *sampling, const char *debugLabel )
{
// caller has responsibility to make 'ctx' current, but we check to be sure.
ctx->CheckCurrent();
// note layout requested
m_layout = layout;
m_maxActiveMip = -1; //index of highest mip that has been written - increase as each mip arrives
m_minActiveMip = 999; //index of lowest mip that has been written - lower it as each mip arrives
// note sampling (copy values)
m_sampling = *sampling;
// note context owner
m_ctx = ctx;
// clear the bind point flags
m_bindPoints = 0; // was ClearAll() with bitvec
// clear the RT attach count
m_rtAttachCount = 0;
// come up with a GL name for this texture.
// for MTGL friendliness, we should generate our own names at some point..
glGenTextures( 1, &m_texName );
//sense whether to try and apply client storage upon teximage/subimage
m_texClientStorage = (gl_texclientstorage/* .GetInt() */ != 0);
// flag that we have not yet been explicitly kicked into VRAM..
m_texPreloaded = false;
// clone the debug label if there is one.
m_debugLabel = debugLabel ? strdup(debugLabel) : NULL;
// if tex is MSAA renderable, make an RBO, else zero the RBO name and dirty bit
if (layout->m_key.m_texFlags & kGLMTexMultisampled)
{
glGenRenderbuffersEXT( 1, &m_rboName );
m_rboDirty = false;
// so we have enough info to go ahead and bind the RBO and put storage on it?
// try it.
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, m_rboName );
GLMCheckError();
// quietly clamp if sample count exceeds known limit for the device
int sampleCount = layout->m_key.m_texSamples;
if (sampleCount > ctx->Caps().m_maxSamples)
{
sampleCount = ctx->Caps().m_maxSamples; // clamp
}
GLenum msaaFormat = (layout->m_key.m_texFlags & kGLMTexSRGB) ? layout->m_format->m_glIntFormatSRGB : layout->m_format->m_glIntFormat;
glRenderbufferStorageMultisampleEXT( GL_RENDERBUFFER_EXT,
sampleCount, // not "layout->m_key.m_texSamples"
msaaFormat,
layout->m_key.m_xSize,
layout->m_key.m_ySize );
GLMCheckError();
if (gl_texmsaalog/* .GetInt() */)
{
printf( "\n == MSAA Tex %p %s : MSAA RBO is intformat %s (%x)", this, m_debugLabel?m_debugLabel:"", GLMDecode( eGL_ENUM, msaaFormat ), msaaFormat );
}
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
GLMCheckError();
}
else
{
m_rboName = 0;
m_rboDirty = false;
}
// at this point we have the complete description of the texture, and a name for it, but no data and no actual GL object.
// we know this name has bever seen duty before, so we're going to hard-bind it to TMU 0, displacing any other tex that might have been bound there.
// any previously bound tex will be unbound and appropriately marked as a result.
// the active TMU will be set as a side effect.
ctx->BindTexToTMU( this, 0 );
// OK, our texture now exists and is bound on the active TMU. Not drawable yet though.
// impose the sampling params we were given, unconditionally
ApplySamplingParams( sampling, true );
// if not an RT, create backing storage and fill it
if ( !(layout->m_key.m_texFlags & kGLMTexRenderable) )
{
m_backing = (char *)malloc( m_layout->m_storageTotalSize );
memset( m_backing, 0, m_layout->m_storageTotalSize );
// track bytes allocated for non-RT's
int formindex = sEncodeLayoutAsIndex( &layout->m_key );
g_texGlobalBytes[ formindex ] += m_layout->m_storageTotalSize;
#if TEXSPACE_LOGGING
printf( "\n Tex %s added %d bytes in form %d which is now %d bytes", m_debugLabel ? m_debugLabel : "-", m_layout->m_storageTotalSize, formindex, g_texGlobalBytes[ formindex ] );
printf( "\n\t\t[ %d %d %d %d %d %d %d %d ]",
g_texGlobalBytes[ 0 ],g_texGlobalBytes[ 1 ],g_texGlobalBytes[ 2 ],g_texGlobalBytes[ 3 ],
g_texGlobalBytes[ 4 ],g_texGlobalBytes[ 5 ],g_texGlobalBytes[ 6 ],g_texGlobalBytes[ 7 ]
);
#endif
}
else
{
m_backing = NULL;
m_texClientStorage = false;
}
// init lock count
// lock reqs are tracked by the owning context
m_lockCount = 0;
m_sliceFlags.resize( m_layout->m_sliceCount );
for( int i=0; i< m_layout->m_sliceCount; i++)
{
m_sliceFlags[i] = 0;
// kSliceValid = false (we have not teximaged each slice yet)
// kSliceStorageValid = false (the storage allocated does not reflect what is in the tex)
// kSliceLocked = false (the slices are not locked)
// kSliceFullyDirty = false (this does not come true til first lock)
}
// texture minimize parameter keeps driver from allocing mips when it should not, by being explicit about the ones that have no mips.
bool setMinimizeParameter = false;
bool minimize_rt = (gl_minimize_rt_tex/* .GetInt() */!=0);
bool minimize_all = (gl_minimize_all_tex/* .GetInt() */!=0);
if (layout->m_key.m_texFlags & kGLMTexRenderable)
{
// it's an RT. if mips were not explicitly requested, and "gl_minimize_rt_tex" is true, set the minimize parameter.
if ( (minimize_rt || minimize_all) && ( !(layout->m_key.m_texFlags & kGLMTexMipped) ) )
{
setMinimizeParameter = true;
}
}
else
{
// not an RT. if mips were not requested, and "gl_minimize_all_tex" is true, set the minimize parameter.
if ( minimize_all && ( !(layout->m_key.m_texFlags & kGLMTexMipped) ) )
{
setMinimizeParameter = true;
}
}
if (setMinimizeParameter)
{
if (gl_minimize_tex_log/* .GetInt() */)
{
printf("\n minimizing storage for tex '%s' [%s] ", m_debugLabel?m_debugLabel:"-", m_layout->m_layoutSummary );
}
glTexParameteri( m_layout->m_key.m_texGLTarget, GL_TEXTURE_MINIMIZE_STORAGE_APPLE, 1 );
}
// after a lot of pain with texture completeness...
// always push black into all slices of all newly created textures.
#if 0
bool pushRenderableSlices = (m_layout->m_key.m_texFlags & kGLMTexRenderable) != 0;
bool pushTexSlices = true; // just do it everywhere (m_layout->m_mipCount>1) && (m_layout->m_format->m_chunkSize !=1) ;
if (pushTexSlices)
{
// fill storage with mostly-opaque purple
GLMGenTexelParams genp;
memset( &genp, 0, sizeof(genp) );
genp.m_format = m_layout->m_format->m_d3dFormat;
const GLMTexFormatDesc *format = GetFormatDesc( genp.m_format );
genp.m_dest = m_backing; // dest addr
genp.m_chunkCount = m_layout->m_storageTotalSize / format->m_bytesPerSquareChunk; // fill the whole slab
genp.m_byteCountLimit = m_layout->m_storageTotalSize; // limit writes to this amount
genp.r = 1.0;
genp.g = 0.0;
genp.b = 1.0;
genp.a = 0.75;
GLMGenTexels( &genp );
}
#endif
//if (pushRenderableSlices || pushTexSlices)
if (1)
{
for( int face=0; face <m_layout->m_faceCount; face++)
{
for( int mip=0; mip <m_layout->m_mipCount; mip++)
{
// we're not really going to lock, we're just going to write the blank data from the backing store we just made
GLMTexLockDesc desc;
desc.m_req.m_tex = this;
desc.m_req.m_face = face;
desc.m_req.m_mip = mip;
desc.m_sliceIndex = CalcSliceIndex( face, mip );
GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc.m_sliceIndex ];
desc.m_req.m_region.xmin = desc.m_req.m_region.ymin = desc.m_req.m_region.zmin = 0;
desc.m_req.m_region.xmax = slice->m_xSize;
desc.m_req.m_region.ymax = slice->m_ySize;
desc.m_req.m_region.zmax = slice->m_zSize;
desc.m_sliceBaseOffset = slice->m_storageOffset; // doesn't really matter... we're just pushing zeroes..
desc.m_sliceRegionOffset = 0;
this->WriteTexels( &desc, true, (layout->m_key.m_texFlags & kGLMTexRenderable)!=0 ); // write whole slice - but disable data source if it's an RT, as there's no backing
}
}
}
GLMPRINTF(("-A- -**TEXNEW '%-60s' name=%06d size=%09d storage=%08x label=%s ", m_layout->m_layoutSummary, m_texName, m_layout->m_storageTotalSize, m_backing, m_debugLabel ? m_debugLabel : "-" ));
}
CGLMTex::~CGLMTex( )
{
if ( !(m_layout->m_key.m_texFlags & kGLMTexRenderable) )
{
int formindex = sEncodeLayoutAsIndex( &m_layout->m_key );
g_texGlobalBytes[ formindex ] -= m_layout->m_storageTotalSize;
#if TEXSPACE_LOGGING
printf( "\n Tex %s freed %d bytes in form %d which is now %d bytes", m_debugLabel ? m_debugLabel : "-", m_layout->m_storageTotalSize, formindex, g_texGlobalBytes[ formindex ] );
printf( "\n\t\t[ %d %d %d %d %d %d %d %d ]",
g_texGlobalBytes[ 0 ],g_texGlobalBytes[ 1 ],g_texGlobalBytes[ 2 ],g_texGlobalBytes[ 3 ],
g_texGlobalBytes[ 4 ],g_texGlobalBytes[ 5 ],g_texGlobalBytes[ 6 ],g_texGlobalBytes[ 7 ]
);
#endif
}
GLMPRINTF(("-A- -**TEXDEL '%-60s' name=%06d size=%09d storage=%08x label=%s ", m_layout->m_layoutSummary, m_texName, m_layout->m_storageTotalSize, m_backing, m_debugLabel ? m_debugLabel : "-" ));
// check first to see if we were still bound anywhere or locked... these should be failures.
// if all that is OK, then delete the underlying tex
glDeleteTextures( 1, &m_texName );
GLMCheckError();
m_texName = 0;
if(m_rboName)
{
glDeleteRenderbuffersEXT( 1, &m_rboName );
GLMCheckError();
m_rboName = 0;
m_rboDirty = false;
}
// release our usage of the layout
m_ctx->m_texLayoutTable->DelLayoutRef( m_layout );
m_layout = NULL;
if (m_backing)
{
free( m_backing );
m_backing = NULL;
}
if (m_debugLabel)
{
free( m_debugLabel );
m_debugLabel = NULL;
}
m_ctx = NULL;
}
int CGLMTex::CalcSliceIndex( int face, int mip )
{
// faces of the same mip level are adjacent. "face major" storage
int index = (mip * m_layout->m_faceCount) + face;
return index;
}
void CGLMTex::CalcTexelDataOffsetAndStrides( int sliceIndex, int x, int y, int z, int *offsetOut, int *yStrideOut, int *zStrideOut )
{
int offset = 0;
int yStride = 0;
int zStride = 0;
GLMTexFormatDesc *format = m_layout->m_format;
if (format->m_chunkSize==1)
{
// figure out row stride and layer stride
yStride = format->m_bytesPerSquareChunk * m_layout->m_slices[sliceIndex].m_xSize; // bytes per texel row (y stride)
zStride = yStride * m_layout->m_slices[sliceIndex].m_ySize; // bytes per texel layer (if 3D tex)
offset = x * format->m_bytesPerSquareChunk; // lateral offset
offset += (y * yStride); // scanline offset
offset += (z * zStride); // should be zero for 2D tex
}
else
{
yStride = format->m_bytesPerSquareChunk * (m_layout->m_slices[sliceIndex].m_xSize / format->m_chunkSize);
zStride = yStride * (m_layout->m_slices[sliceIndex].m_ySize / format->m_chunkSize);
// compressed format. scale the x,y,z values into chunks.
// assert if any of them are not multiples of a chunk.
int chunkx = x / format->m_chunkSize;
int chunky = y / format->m_chunkSize;
int chunkz = z / format->m_chunkSize;
if ( (chunkx * format->m_chunkSize) != x)
{
GLMStop();
}
if ( (chunky * format->m_chunkSize) != y)
{
GLMStop();
}
if ( (chunkz * format->m_chunkSize) != z)
{
GLMStop();
}
offset = chunkx * format->m_bytesPerSquareChunk; // lateral offset
offset += (chunky * yStride); // chunk row offset
offset += (chunkz * zStride); // should be zero for 2D tex
}
*offsetOut = offset;
*yStrideOut = yStride;
*zStrideOut = zStride;
}
void CGLMTex::ApplySamplingParams( GLMTexSamplingParams *params, bool noCheck )
{
#define DIFF(fff) (noCheck || (params->fff != m_sampling.fff))
GLenum target = m_layout->m_key.m_texGLTarget;
// if the texture is compressed, and has a maxActiveMip that is >=0 but less than the mip count,
// (i.e. they supplied *some* but not *all* mips needed)...
// generate them, and fix the max mip count.
//if ( /*(m_layout->m_format->m_chunkSize !=1) &&*/ (m_layout->m_mipCount>3) )
//{
// m_maxActiveMip = m_layout->m_mipCount-3; // pull back three levels
// glTexParameteri( target, GL_TEXTURE_MAX_LEVEL, m_maxActiveMip);
// GLMCheckError();
//}
if (DIFF(m_addressModes[0]))
{
m_sampling.m_addressModes[0] = params->m_addressModes[0];
glTexParameteri( target, GL_TEXTURE_WRAP_S, m_sampling.m_addressModes[0]);
GLMCheckError();
}
if (DIFF(m_addressModes[1]))
{
m_sampling.m_addressModes[1] = params->m_addressModes[1];
glTexParameteri( target, GL_TEXTURE_WRAP_T, m_sampling.m_addressModes[1]);
GLMCheckError();
}
if (DIFF(m_addressModes[2]))
{
m_sampling.m_addressModes[2] = params->m_addressModes[2];
glTexParameteri( target, GL_TEXTURE_WRAP_R, m_sampling.m_addressModes[2]);
GLMCheckError();
}
if ( noCheck || memcmp( params->m_borderColor, m_sampling.m_borderColor, sizeof(m_sampling.m_borderColor) ) )
{
memcpy( m_sampling.m_borderColor, params->m_borderColor, sizeof(params->m_borderColor) );
glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR, params->m_borderColor );
GLMCheckError();
}
if (DIFF(m_magFilter))
{
m_sampling.m_magFilter = params->m_magFilter;
glTexParameteri( target, GL_TEXTURE_MAG_FILTER, params->m_magFilter);
GLMCheckError();
}
if (DIFF(m_minFilter))
{
m_sampling.m_minFilter = params->m_minFilter;
glTexParameteri( target, GL_TEXTURE_MIN_FILTER, params->m_minFilter);
GLMCheckError();
}
if (DIFF(m_mipmapBias))
{
m_sampling.m_mipmapBias = params->m_mipmapBias;
//glTexParameterf( target, GL_TEXTURE_LOD_BIAS, params->m_mipmapBias );
GLMCheckError();
}
if (DIFF(m_minMipLevel))
{
// don't let minmiplevel go below min active mip level
m_sampling.m_minMipLevel = std::max( m_minActiveMip, params->m_minMipLevel );
glTexParameteri( target, GL_TEXTURE_MIN_LOD, m_sampling.m_minMipLevel);
GLMCheckError();
}
if (DIFF(m_maxMipLevel))
{
// do not let max selectable LOD exceed the max submitted mip
m_sampling.m_maxMipLevel = std::min( m_maxActiveMip, params->m_maxMipLevel);
glTexParameteri( target, GL_TEXTURE_MAX_LOD, m_sampling.m_maxMipLevel);
GLMCheckError();
}
if (m_layout->m_mipCount > 1) // only apply aniso setting to mipped tex
{
if (DIFF(m_maxAniso))
{
m_sampling.m_maxAniso = params->m_maxAniso >= 1.0f ? params->m_maxAniso : 1.0f;
glTexParameteri( target, GL_TEXTURE_MAX_ANISOTROPY_EXT, params->m_maxAniso );
GLMCheckError();
}
}
if (DIFF(m_compareMode))
{
m_sampling.m_compareMode = params->m_compareMode;
glTexParameteri( target, GL_TEXTURE_COMPARE_MODE_ARB, params->m_compareMode );
GLMCheckError();
if (params->m_compareMode == GL_COMPARE_R_TO_TEXTURE_ARB)
{
glTexParameteri( target, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL );
GLMCheckError();
}
}
if (DIFF(m_srgb))
{
m_sampling.m_srgb = params->m_srgb; // we might have to re-DL the tex if the SRGB read status changes..
}
#undef DIFF
}
void CGLMTex::ReadTexels( GLMTexLockDesc *desc, bool readWholeSlice )
{
GLMRegion readBox;
if (readWholeSlice)
{
readBox.xmin = readBox.ymin = readBox.zmin = 0;
readBox.xmax = m_layout->m_slices[ desc->m_sliceIndex ].m_xSize;
readBox.ymax = m_layout->m_slices[ desc->m_sliceIndex ].m_ySize;
readBox.zmax = m_layout->m_slices[ desc->m_sliceIndex ].m_zSize;
}
else
{
readBox = desc->m_req.m_region;
}
m_ctx->BindTexToTMU( this, 0, false ); // SelectTMU(n) is a side effect
if (readWholeSlice)
{
// make this work first.... then write the partial path
// (Hmmmm, I don't think we will ever actually need a partial path -
// since we have no notion of a partially valid slice of storage
GLMTexFormatDesc *format = m_layout->m_format;
GLenum target = m_layout->m_key.m_texGLTarget;
void *sliceAddress = m_backing + m_layout->m_slices[ desc->m_sliceIndex ].m_storageOffset; // this would change for PBO
int sliceSize = m_layout->m_slices[ desc->m_sliceIndex ].m_storageSize;
// interestingly enough, we can use the same path for both 2D and 3D fetch
switch( target )
{
case GL_TEXTURE_CUBE_MAP:
// adjust target to steer to the proper face, then fall through to the 2D texture path.
target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + desc->m_req.m_face;
case GL_TEXTURE_2D:
case GL_TEXTURE_3D:
{
// check compressed or not
if (format->m_chunkSize != 1)
{
// compressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glGetCompressedTexImage.xml
glGetCompressedTexImage( target, // target
desc->m_req.m_mip, // level
sliceAddress ); // destination
GLMCheckError();
}
else
{
// uncompressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glGetTexImage.xml
glGetTexImage( target, // target
desc->m_req.m_mip, // level
format->m_glDataFormat, // dataformat
format->m_glDataType, // datatype
sliceAddress ); // destination
GLMCheckError();
}
}
break;
}
}
else
{
GLMStop();
}
}
// defaulting the subimage support off, since it's breaking Ep2 at startup on some NV 9400 and friends
// defaulting it back to "1" for L4D2 and see if it flies
int gl_enabletexsubimage = 1;
//ConVar gl_enabletexsubimage( "gl_enabletexsubimage", "1" );
void CGLMTex::WriteTexels( GLMTexLockDesc *desc, bool writeWholeSlice, bool noDataWrite )
{
GLMRegion writeBox;
bool needsExpand = false;
char *expandTemp = NULL;
switch( m_layout->m_format->m_d3dFormat)
{
case D3DFMT_V8U8:
{
needsExpand = true;
writeWholeSlice = true;
// shoot down client storage if we have to generate a new flavor of the data
m_texClientStorage = false;
}
break;
}
if (writeWholeSlice)
{
writeBox.xmin = writeBox.ymin = writeBox.zmin = 0;
writeBox.xmax = m_layout->m_slices[ desc->m_sliceIndex ].m_xSize;
writeBox.ymax = m_layout->m_slices[ desc->m_sliceIndex ].m_ySize;
writeBox.zmax = m_layout->m_slices[ desc->m_sliceIndex ].m_zSize;
}
else
{
writeBox = desc->m_req.m_region;
}
// first thing is to get the GL texture bound to a TMU, or just select one if already bound
// to get this running we will just always slam TMU 0 and let the draw time code fix it back
// a later optimization would be to hoist the bind call to the caller, do it exactly once
m_ctx->BindTexToTMU( this, 0, false ); // SelectTMU(n) is a side effect
GLMTexFormatDesc *format = m_layout->m_format;
GLenum target = m_layout->m_key.m_texGLTarget;
GLenum glDataFormat = format->m_glDataFormat; // this could change if expansion kicks in
GLenum glDataType = format->m_glDataType;
GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc->m_sliceIndex ];
void *sliceAddress = m_backing ? (m_backing + slice->m_storageOffset) : NULL; // this would change for PBO
// allow use of subimage if the target is texture2D and it has already been teximage'd
bool mayUseSubImage = false;
if ( (target==GL_TEXTURE_2D) && (m_sliceFlags[ desc->m_sliceIndex ] & kSliceValid) )
{
mayUseSubImage = gl_enabletexsubimage/* .GetInt() */;
}
// check flavor, 2D, 3D, or cube map
// we also have the choice to use subimage if this is a tex already created. (open question as to benefit)
// SRGB select. At this level (writetexels) we firmly obey the m_texFlags.
// (mechanism not policy)
GLenum intformat = (m_layout->m_key.m_texFlags & kGLMTexSRGB) ? format->m_glIntFormatSRGB : format->m_glIntFormat;
if (0 /* CommandLine()->FindParm("-disable_srgbtex") */)
{
// force non srgb flavor - experiment to make ATI r600 happy on 10.5.8 (maybe x1600 too!)
intformat = format->m_glIntFormat;
}
Assert( intformat != 0 );
if (m_layout->m_key.m_texFlags & kGLMTexSRGB)
{
Assert( m_layout->m_format->m_glDataFormat != GL_DEPTH_COMPONENT );
Assert( m_layout->m_format->m_glDataFormat != GL_DEPTH_STENCIL_EXT );
Assert( m_layout->m_format->m_glDataFormat != GL_ALPHA );
}
// adjust min and max mip written
if (desc->m_req.m_mip > m_maxActiveMip)
{
m_maxActiveMip = desc->m_req.m_mip;
glTexParameteri( target, GL_TEXTURE_MAX_LEVEL, desc->m_req.m_mip);
GLMCheckError();
}
if (desc->m_req.m_mip < m_minActiveMip)
{
m_minActiveMip = desc->m_req.m_mip;
glTexParameteri( target, GL_TEXTURE_BASE_LEVEL, desc->m_req.m_mip);
GLMCheckError();
}
if (needsExpand)
{
int expandSize = 0;
switch( m_layout->m_format->m_d3dFormat)
{
case D3DFMT_V8U8:
{
// figure out new size based on 3byte RGB format
// easy, just take the two byte size and grow it by 50%
expandSize = (slice->m_storageSize * 3) / 2;
expandTemp = (char*)malloc( expandSize );
char *src = (char*)sliceAddress;
char *dst = expandTemp;
// transfer RG's to RGB's
while(expandSize>0)
{
*dst = *src++; // move first byte
*dst = *src++; // move second byte
*dst = 0xBB; // pad third byte
expandSize -= 3;
}
// move the slice pointer
sliceAddress = expandTemp;
// change the data format we tell GL about
glDataFormat = GL_RGB;
}
break;
default: Assert(!"Don't know how to expand that format..");
}
}
// set up the client storage now, one way or another
glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, m_texClientStorage );
GLMCheckError();
switch( target )
{
case GL_TEXTURE_CUBE_MAP:
// adjust target to steer to the proper face, then fall through to the 2D texture path.
target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + desc->m_req.m_face;
case GL_TEXTURE_2D:
{
// check compressed or not
if (format->m_chunkSize != 1)
{
Assert( writeWholeSlice ); //subimage not implemented in this path yet
// compressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glCompressedTexImage2D.xml
glCompressedTexImage2D( target, // target
desc->m_req.m_mip, // level
intformat, // internalformat - don't use format->m_glIntFormat because we have the SRGB select going on above
slice->m_xSize, // width
slice->m_ySize, // height
0, // border
slice->m_storageSize, // imageSize
sliceAddress ); // data
GLMCheckError();
}
else
{
if (mayUseSubImage)
{
// go subimage2D if it's a replacement, not a creation
glPixelStorei( GL_UNPACK_ROW_LENGTH, slice->m_xSize ); // in pixels
glPixelStorei( GL_UNPACK_SKIP_PIXELS, writeBox.xmin ); // in pixels
glPixelStorei( GL_UNPACK_SKIP_ROWS, writeBox.ymin ); // in pixels
GLMCheckError();
glTexSubImage2D( target,
desc->m_req.m_mip, // level
writeBox.xmin, // xoffset into dest
writeBox.ymin, // yoffset into dest
writeBox.xmax - writeBox.xmin, // width (was slice->m_xSize)
writeBox.ymax - writeBox.ymin, // height (was slice->m_ySize)
glDataFormat, // format
glDataType, // type
sliceAddress // data (will be offsetted by the SKIP_PIXELS and SKIP_ROWS - let GL do the math to find the first source texel)
);
GLMCheckError();
glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
GLMCheckError();
/*
//http://www.opengl.org/sdk/docs/man/xhtml/glTexSubImage2D.xml
glTexSubImage2D( target,
desc->m_req.m_mip, // level
0, // xoffset
0, // yoffset
slice->m_xSize, // width
slice->m_ySize, // height
glDataFormat, // format
glDataType, // type
sliceAddress // data
);
GLMCheckError();
*/
}
else
{
if (m_layout->m_key.m_texFlags & kGLMTexRenderable)
{
if (gl_rt_forcergba/* .GetInt() */)
{
if (glDataFormat == GL_BGRA)
{
// change it
glDataFormat = GL_RGBA;
}
}
}
// uncompressed path
// http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html
glTexImage2D( target, // target
desc->m_req.m_mip, // level
intformat, // internalformat - don't use format->m_glIntFormat because we have the SRGB select going on above
slice->m_xSize, // width
slice->m_ySize, // height
0, // border
glDataFormat, // dataformat
glDataType, // datatype
noDataWrite ? NULL : sliceAddress ); // data (optionally suppressed in case ResetSRGB desires)
if (m_layout->m_key.m_texFlags & kGLMTexMultisampled)
{
if (gl_texmsaalog/* .GetInt() */)
{
printf( "\n == MSAA Tex %p %s : glTexImage2D for flat tex using intformat %s (%x)", this, m_debugLabel?m_debugLabel:"", GLMDecode( eGL_ENUM, intformat ), intformat );
printf( "\n" );
}
}
m_sliceFlags[ desc->m_sliceIndex ] |= kSliceValid; // for next time, we can subimage..
}
}
}
break;
case GL_TEXTURE_3D:
{
// check compressed or not
if (format->m_chunkSize != 1)
{
// compressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glCompressedTexImage3D.xml
glCompressedTexImage3D( target, // target
desc->m_req.m_mip, // level
format->m_glIntFormat, // internalformat
slice->m_xSize, // width
slice->m_ySize, // height
slice->m_zSize, // depth
0, // border
slice->m_storageSize, // imageSize
sliceAddress ); // data
GLMCheckError();
}
else
{
// uncompressed path
// http://www.opengl.org/sdk/docs/man/xhtml/glTexImage3D.xml
glTexImage3D( target, // target
desc->m_req.m_mip, // level
format->m_glIntFormat, // internalformat
slice->m_xSize, // width
slice->m_ySize, // height
slice->m_zSize, // depth
0, // border
glDataFormat, // dataformat
glDataType, // datatype
noDataWrite ? NULL : sliceAddress ); // data (optionally suppressed in case ResetSRGB desires)
GLMCheckError();
}
}
break;
}
glPixelStorei( GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE );
GLMCheckError();
if ( expandTemp )
{
free( expandTemp );
}
}
void CGLMTex::Lock( GLMTexLockParams *params, char** addressOut, int* yStrideOut, int *zStrideOut )
{
// locate appropriate slice in layout record
int sliceIndex = CalcSliceIndex( params->m_face, params->m_mip );
GLMTexLayoutSlice *slice = &m_layout->m_slices[sliceIndex];
// obtain offset
int sliceBaseOffset = slice->m_storageOffset;
// cross check region req against slice bounds - figure out if it matches, exceeds, or is less than the whole slice.
char exceed = (params->m_region.xmin < 0) || (params->m_region.xmax > slice->m_xSize) ||
(params->m_region.ymin < 0) || (params->m_region.ymax > slice->m_ySize) ||
(params->m_region.zmin < 0) || (params->m_region.zmax > slice->m_zSize);
char partial = (params->m_region.xmin > 0) || (params->m_region.xmax < slice->m_xSize) ||
(params->m_region.ymin > 0) || (params->m_region.ymax < slice->m_ySize) ||
(params->m_region.zmin > 0) || (params->m_region.zmax < slice->m_zSize);
bool copyout = false; // set if a readback of the texture slice from GL is needed
if (exceed)
{
// illegal rect, out of bounds
GLMStop();
}
// on return, these things need to be true
// a - there needs to be storage allocated, which we will return an address within
// b - the region corresponding to the slice being locked, will have valid data there for the whole slice.
// c - the slice is marked as locked
// d - the params of the lock request have been saved in the lock table (in the context)
// so step 1 is unambiguous. If there's no backing storage, make some.
if (!m_backing)
{
m_backing = (char *)malloc( m_layout->m_storageTotalSize );
memset( m_backing, 0, m_layout->m_storageTotalSize );
// clear the kSliceStorageValid bit on all slices
for( int i=0; i<m_layout->m_sliceCount; i++)
{
m_sliceFlags[i] &= ~kSliceStorageValid;
}
}
// work on this slice now
// storage is known to exist at this point, but we need to check if its contents are valid for this slice.
// this is tracked per-slice so we don't hoist all the texels back out of GL across all slices if caller only
// wanted to lock some of them.
// (i.e. if we just alloced it, it's blank)
// if storage is invalid, but the texture itself is valid, hoist the texels back to the storage and mark it valid.
// if storage is invalid, and texture itself is also invalid, go ahead and mark storage as valid and fully dirty... to force teximage.
// ???????????? we need to go over this more carefully re "slice valid" (it has been teximaged) vs "storage valid" (it has been copied out).
unsigned char *sliceFlags = &m_sliceFlags[ sliceIndex ];
if (params->m_readback)
{
// caller is letting us know that it wants to readback the real texels.
*sliceFlags |= kSliceStorageValid;
*sliceFlags |= kSliceValid;
*sliceFlags &= ~(kSliceFullyDirty);
copyout = true;
}
else
{
// caller is pushing texels.
if (! (*sliceFlags & kSliceStorageValid) )
{
// storage is invalid. check texture state
if ( *sliceFlags & kSliceValid )
{
// kSliceValid set: the texture itself has a valid slice, but we don't have it in our backing copy, so copy it out.
copyout = true;
}
else
{
// kSliceValid not set: the texture does not have a valid slice to copy out - it hasn't been teximage'd yet.
// set the "full dirty" bit to make sure we teximage the whole thing on unlock.
*sliceFlags |= kSliceFullyDirty;
// assert if they did not ask to lock the full slice size on this go-round
if (partial)
{
// choice here -
// 1 - stop cold, we don't know how to subimage yet.
// 2 - grin and bear it, mark whole slice dirty (ah, we already did... so, do nothing).
// choice 2: // GLMStop();
}
}
// one way or another, upon reaching here the slice storage is valid for read.
*sliceFlags |= kSliceStorageValid;
}
}
// when we arrive here, there is storage, and the content of the storage for this slice is valid
// (or zeroes if it's the first lock)
// log the lock request in the context.
GLMTexLockDesc newdesc;
newdesc.m_req = *params;
newdesc.m_active = true;
newdesc.m_sliceIndex = sliceIndex;
newdesc.m_sliceBaseOffset = m_layout->m_slices[sliceIndex].m_storageOffset;
// to calculate the additional offset we need to look at the rect's min corner
// combined with the per-texel size and Y/Z stride
// also cross check it for 4x multiple if there is compression in play
int offsetInSlice = 0;
int yStride = 0;
int zStride = 0;
CalcTexelDataOffsetAndStrides( sliceIndex, params->m_region.xmin, params->m_region.ymin, params->m_region.zmin, &offsetInSlice, &yStride, &zStride );
// for compressed case...
// since there is presently no way to texsubimage a DXT when the rect does not cover the whole width,
// we will probably need to inflate the dirty rect in the recorded lock req so that the entire span is
// pushed across at unlock time.
newdesc.m_sliceRegionOffset = offsetInSlice + newdesc.m_sliceBaseOffset;
if (copyout)
{
// read the whole slice
// (odds are we'll never request anything but a whole slice to be read..)
ReadTexels( &newdesc, true );
} // this would be a good place to fill with scrub value if in debug...
*addressOut = m_backing + newdesc.m_sliceRegionOffset;
*yStrideOut = yStride;
*zStrideOut = zStride;
m_ctx->m_texLocks.push_back( newdesc );
m_lockCount++;
}
void CGLMTex::Unlock( GLMTexLockParams *params )
{
// look for an active lock request on this face and mip (doesn't necessarily matter which one, if more than one)
// and mark it inactive.
// --> if you can't find one, fail. first line of defense against mismatched locks/unlocks..
int i=0;
bool found = false;
while( !found && (i<m_ctx->m_texLocks.size()) )
{
GLMTexLockDesc *desc = &m_ctx->m_texLocks[i];
// is lock at index 'i' targeted at the texture/face/mip in question?
if ( (desc->m_req.m_tex == this) && (desc->m_req.m_face == params->m_face) & (desc->m_req.m_mip == params->m_mip) && (desc->m_active) )
{
// matched and active, so retire it
desc->m_active = false;
// stop searching
found = true;
}
i++;
}
if (!found)
{
GLMStop(); // bad news
}
// found - so drop lock count
m_lockCount--;
if (m_lockCount <0)
{
GLMStop(); // bad news
}
if (m_lockCount==0)
{
// there should not be any active locks remaining on this texture.
// motivation to defer all texel pushing til *all* open locks are closed out -
// if/when we back the texture with a PBO, we will need to unmap that PBO before teximaging from it;
// by waiting for all the locks to clear this gives us an unambiguous signal to act on.
// scan through all the retired locks for this texture and push the texels for each one.
// after each one is dispatched, remove it from the pile.
int j=0;
while( j<m_ctx->m_texLocks.size() )
{
GLMTexLockDesc *desc = &m_ctx->m_texLocks[j];
if ( desc->m_req.m_tex == this )
{
// if it's active, something is wrong
if (desc->m_active)
{
GLMStop();
}
// write the texels
bool fullyDirty = false;
fullyDirty |= ((m_sliceFlags[ desc->m_sliceIndex ] & kSliceFullyDirty) != 0);
// this is not optimal and will result in full downloads on any dirty.
// we're papering over the fact that subimage isn't done yet.
// but this is safe if the slice of storage is all valid.
// at some point we'll need to actually compare the lock box against the slice bounds.
// fullyDirty |= (m_sliceFlags[ desc->m_sliceIndex ] & kSliceStorageValid);
WriteTexels( desc, fullyDirty );
// logical place to trigger preloading
// only do it for an RT tex, if it is not yet attached to any FBO.
// also, only do it if the slice number is the last slice in the tex.
if ( desc->m_sliceIndex == (m_layout->m_sliceCount-1) )
{
if ( !(m_layout->m_key.m_texFlags & kGLMTexRenderable) || (m_rtAttachCount==0) )
{
m_ctx->PreloadTex( this );
// printf("( slice %d of %d )", desc->m_sliceIndex, m_layout->m_sliceCount );
}
}
m_ctx->m_texLocks.erase( m_ctx->m_texLocks.begin() + j ); // remove from the pile, don't advance index
}
else
{
j++; // move on to next one
}
}
// clear the locked and full-dirty flags for all slices
for( int slice=0; slice < m_layout->m_sliceCount; slice++)
{
m_sliceFlags[slice] &= ~( kSliceLocked | kSliceFullyDirty );
}
}
}
void CGLMTex::ResetSRGB( bool srgb, bool noDataWrite )
{
// see if requested SRGB state differs from the known one
bool wasSRGB = (m_layout->m_key.m_texFlags & kGLMTexSRGB);
GLMTexLayout *oldLayout = m_layout; // need to m_ctx->m_texLayoutTable->DelLayoutRef on this one if we flip
if (srgb != wasSRGB)
{
// we're going to need a new layout (though the storage size should be the same - check it)
GLMTexLayoutKey newKey = m_layout->m_key;
newKey.m_texFlags &= (~kGLMTexSRGB); // turn off that bit
newKey.m_texFlags |= srgb ? kGLMTexSRGB : 0; // turn on that bit if it should be so
// get new layout
GLMTexLayout *newLayout = m_ctx->m_texLayoutTable->NewLayoutRef( &newKey );
// if SRGB requested, verify that the layout we just got can do it.
// if it can't, delete the new layout ref and bail.
if (srgb && (newLayout->m_format->m_glIntFormatSRGB == 0))
{
Assert( !"Can't enable SRGB mode on this format" );
m_ctx->m_texLayoutTable->DelLayoutRef( newLayout );
return;
}
// check sizes and fail if no match
if( newLayout->m_storageTotalSize != oldLayout->m_storageTotalSize )
{
Assert( !"Bug: layout sizes don't match on SRGB change" );
m_ctx->m_texLayoutTable->DelLayoutRef( newLayout );
return;
}
// commit to new layout
m_layout = newLayout;
// check same size
Assert( m_layout->m_storageTotalSize == oldLayout->m_storageTotalSize );
// release old
m_ctx->m_texLayoutTable->DelLayoutRef( oldLayout );
oldLayout = NULL;
// force texel re-DL
// note this messes with TMU 0 as side effect of WriteTexels
// so we save and restore the TMU 0 binding first
// since we're likely to be called in dxabstract when it is syncing sampler state, we can't go trampling the bindings.
// a refinement would be to have each texture make a note of which TMU they're bound on, and just use that active TMU for DL instead of 0.
CGLMTex *tmu0save = m_ctx->m_samplers[0].m_drawTex;
for( int face=0; face <m_layout->m_faceCount; face++)
{
for( int mip=0; mip <m_layout->m_mipCount; mip++)
{
// we're not really going to lock, we're just going to rewrite the orig data
GLMTexLockDesc desc;
desc.m_req.m_tex = this;
desc.m_req.m_face = face;
desc.m_req.m_mip = mip;
desc.m_sliceIndex = CalcSliceIndex( face, mip );
GLMTexLayoutSlice *slice = &m_layout->m_slices[ desc.m_sliceIndex ];
desc.m_req.m_region.xmin = desc.m_req.m_region.ymin = desc.m_req.m_region.zmin = 0;
desc.m_req.m_region.xmax = slice->m_xSize;
desc.m_req.m_region.ymax = slice->m_ySize;
desc.m_req.m_region.zmax = slice->m_zSize;
desc.m_sliceBaseOffset = slice->m_storageOffset; // doesn't really matter... we're just pushing zeroes..
desc.m_sliceRegionOffset = 0;
this->WriteTexels( &desc, true, noDataWrite ); // write whole slice. and avoid pushing real bits if the caller requests (RT's)
}
}
// put it back
m_ctx->BindTexToTMU( tmu0save, 0, true );
}
}
| 33.716343 | 199 | 0.644155 | [
"object",
"3d"
] |
78e0a96d23637c78a4692a3ae380f52fbe631f8f | 40,250 | hxx | C++ | include/vigra/skeleton.hxx | ThomasWalter/vigra | e92c892aae38c3977dc3f6400f46377b0cb61799 | [
"MIT"
] | null | null | null | include/vigra/skeleton.hxx | ThomasWalter/vigra | e92c892aae38c3977dc3f6400f46377b0cb61799 | [
"MIT"
] | null | null | null | include/vigra/skeleton.hxx | ThomasWalter/vigra | e92c892aae38c3977dc3f6400f46377b0cb61799 | [
"MIT"
] | null | null | null | /************************************************************************/
/* */
/* Copyright 2013-2014 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_SKELETON_HXX
#define VIGRA_SKELETON_HXX
#include <vector>
#include <set>
#include <map>
#include "vector_distance.hxx"
#include "iteratorfacade.hxx"
#include "pixelneighborhood.hxx"
#include "graph_algorithms.hxx"
namespace vigra
{
namespace detail {
template <class Node>
struct SkeletonNode
{
Node parent, principal_child;
double length, salience;
MultiArrayIndex partial_area;
bool is_loop;
SkeletonNode()
: parent(lemon::INVALID)
, principal_child(lemon::INVALID)
, length(0.0)
, salience(1.0)
, partial_area(0)
, is_loop(false)
{}
SkeletonNode(Node const & s)
: parent(s)
, principal_child(lemon::INVALID)
, length(0.0)
, salience(1.0)
, partial_area(0)
, is_loop(false)
{}
};
template <class Node>
struct SkeletonRegion
{
typedef SkeletonNode<Node> SNode;
typedef std::map<Node, SNode> Skeleton;
Node anchor, lower, upper;
Skeleton skeleton;
SkeletonRegion()
: anchor(lemon::INVALID)
, lower(NumericTraits<MultiArrayIndex>::max())
, upper(NumericTraits<MultiArrayIndex>::min())
{}
void addNode(Node const & n)
{
skeleton[n] = SNode(n);
anchor = n;
lower = min(lower, n);
upper = max(upper, n);
}
};
template <class Graph, class Node, class NodeMap>
inline unsigned int
neighborhoodConfiguration(Graph const & g, Node const & n, NodeMap const & labels)
{
typedef typename Graph::OutArcIt ArcIt;
typedef typename NodeMap::value_type LabelType;
LabelType label = labels[n];
unsigned int v = 0;
for(ArcIt arc(g, n); arc != lemon::INVALID; ++arc)
{
v = (v << 1) | (labels[g.target(*arc)] == label ? 1 : 0);
}
return v;
}
template <class Node, class Cost>
struct SkeletonSimplePoint
{
Node point;
Cost cost;
SkeletonSimplePoint(Node const & p, Cost c)
: point(p), cost(c)
{}
bool operator<(SkeletonSimplePoint const & o) const
{
return cost < o.cost;
}
bool operator>(SkeletonSimplePoint const & o) const
{
return cost > o.cost;
}
};
template <class CostMap, class LabelMap>
void
skeletonThinning(CostMap const & cost, LabelMap & labels,
bool preserve_endpoints=true)
{
typedef GridGraph<CostMap::actual_dimension> Graph;
typedef typename Graph::Node Node;
typedef typename Graph::NodeIt NodeIt;
typedef typename Graph::OutArcIt ArcIt;
Graph g(labels.shape(), IndirectNeighborhood);
typedef SkeletonSimplePoint<Node, double> SP;
// use std::greater because we need the smallest distances at the top of the queue
// (std::priority_queue is a max queue by default)
std::priority_queue<SP, std::vector<SP>, std::greater<SP> > pqueue;
bool isSimpleStrong[256] = {
0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1,
0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1,
1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1,
1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1,
1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0,
};
bool isSimplePreserveEndPoints[256] = {
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
bool * isSimplePoint = preserve_endpoints
? isSimplePreserveEndPoints
: isSimpleStrong;
int max_degree = g.maxDegree();
double epsilon = 0.5/labels.size(), offset = 0;
for (NodeIt node(g); node != lemon::INVALID; ++node)
{
Node p = *node;
if(g.out_degree(p) == max_degree &&
labels[p] > 0 &&
isSimplePoint[neighborhoodConfiguration(g, p, labels)])
{
// add an offset to break ties in a FIFI manner
pqueue.push(SP(p, cost[p]+offset));
offset += epsilon;
}
}
while(pqueue.size())
{
Node p = pqueue.top().point;
pqueue.pop();
if(labels[p] == 0 ||
!isSimplePoint[neighborhoodConfiguration(g, p, labels)])
{
continue; // point already deleted or no longer simple
}
labels[p] = 0; // delete simple point
for (ArcIt arc(g, p); arc != lemon::INVALID; ++arc)
{
Node q = g.target(*arc);
if(g.out_degree(q) == max_degree &&
labels[q] > 0 &&
isSimplePoint[neighborhoodConfiguration(g, q, labels)])
{
pqueue.push(SP(q, cost[q]+offset));
offset += epsilon;
}
}
}
}
template <class Label, class Labels>
struct CheckForHole
{
Label label;
Labels const & labels;
CheckForHole(Label l, Labels const & ls)
: label(l)
, labels(ls)
{}
template <class Node>
bool operator()(Node const & n) const
{
return labels[n] == label;
}
};
} // namespace detail
/** \addtogroup MultiArrayDistanceTransform
*/
//@{
/** \brief Option object for \ref skeletonizeImage()
*/
struct SkeletonOptions
{
enum SkeletonMode {
DontPrune = 0,
Prune = 1,
Relative = 2,
PreserveTopology = 4,
Length = 8,
Salience = 16,
PruneCenterLine = 32,
PruneLength = Length + Prune,
PruneLengthRelative = PruneLength + Relative,
PruneSalience = Salience + Prune,
PruneSalienceRelative = PruneSalience + Relative,
PruneTopology = PreserveTopology + Prune
};
SkeletonMode mode;
double pruning_threshold;
/** \brief construct with default settings
(default: <tt>pruneSalienceRelative(0.2, true)</tt>)
*/
SkeletonOptions()
: mode(SkeletonMode(PruneSalienceRelative | PreserveTopology))
, pruning_threshold(0.2)
{}
/** \brief return the un-pruned skeletong
*/
SkeletonOptions & dontPrune()
{
mode = DontPrune;
return *this;
}
/** \brief return only the region's center line (i.e. skeleton graph diameter)
*/
SkeletonOptions & pruneCenterLine()
{
mode = PruneCenterLine;
return *this;
}
/** \brief Don't prune and return the length of each skeleton segment.
*/
SkeletonOptions & returnLength()
{
mode = Length;
return *this;
}
/** \brief prune skeleton segments whose length is below the given threshold
If \a preserve_topology is <tt>true</tt> (default), skeleton loops
(i.e. parts enclosing a hole in the region) are preserved even if their
length is below the threshold. Otherwise, loops are pruned as well.
*/
SkeletonOptions & pruneLength(double threshold, bool preserve_topology=true)
{
mode = PruneLength;
if(preserve_topology)
mode = SkeletonMode(mode | PreserveTopology);
pruning_threshold = threshold;
return *this;
}
/** \brief prune skeleton segments whose relative length is below the given threshold
This works like <tt>pruneLength()</tt>, but the threshold is specified as a
fraction of the maximum segment length in the skeleton.
*/
SkeletonOptions & pruneLengthRelative(double threshold, bool preserve_topology=true)
{
mode = PruneLengthRelative;
if(preserve_topology)
mode = SkeletonMode(mode | PreserveTopology);
pruning_threshold = threshold;
return *this;
}
/** \brief Don't prune and return the salience of each skeleton segment.
*/
SkeletonOptions & returnSalience()
{
mode = Salience;
return *this;
}
/** \brief prune skeleton segments whose salience is below the given threshold
If \a preserve_topology is <tt>true</tt> (default), skeleton loops
(i.e. parts enclosing a hole in the region) are preserved even if their
salience is below the threshold. Otherwise, loops are pruned as well.
*/
SkeletonOptions & pruneSalience(double threshold, bool preserve_topology=true)
{
mode = PruneSalience;
if(preserve_topology)
mode = SkeletonMode(mode | PreserveTopology);
pruning_threshold = threshold;
return *this;
}
/** \brief prune skeleton segments whose relative salience is below the given threshold
This works like <tt>pruneSalience()</tt>, but the threshold is specified as a
fraction of the maximum segment salience in the skeleton.
*/
SkeletonOptions & pruneSalienceRelative(double threshold, bool preserve_topology=true)
{
mode = PruneSalienceRelative;
if(preserve_topology)
mode = SkeletonMode(mode | PreserveTopology);
pruning_threshold = threshold;
return *this;
}
/** \brief prune such that only the topology is preserved
If \a preserve_center is <tt>true</tt> (default), the eccentricity center
of the skeleton will not be pruned, even if it is not essential for the topology.
Otherwise, the center is only preserved if it is essential. The center is always
preserved (and is the only remaining point) when the region has no holes.
*/
SkeletonOptions & pruneTopology(bool preserve_center=true)
{
if(preserve_center)
mode = PruneTopology;
else
mode = Prune;
return *this;
}
};
template <class T1, class S1,
class T2, class S2,
class ArrayLike>
void
skeletonizeImageImpl(MultiArrayView<2, T1, S1> const & labels,
MultiArrayView<2, T2, S2> dest,
ArrayLike * features,
SkeletonOptions const & options)
{
static const unsigned int N = 2;
typedef typename MultiArrayShape<N>::type Shape;
typedef GridGraph<N> Graph;
typedef typename Graph::Node Node;
typedef typename Graph::NodeIt NodeIt;
typedef typename Graph::EdgeIt EdgeIt;
typedef typename Graph::OutArcIt ArcIt;
typedef typename Graph::OutBackArcIt BackArcIt;
typedef double WeightType;
typedef detail::SkeletonNode<Node> SNode;
typedef std::map<Node, SNode> Skeleton;
vigra_precondition(labels.shape() == dest.shape(),
"skeleton(): shape mismatch between input and output.");
MultiArray<N, MultiArrayIndex> squared_distance;
dest = 0;
T1 maxLabel = 0;
// find skeleton points
{
using namespace multi_math;
MultiArray<N, Shape> vectors(labels.shape());
boundaryVectorDistance(labels, vectors, false, OuterBoundary);
squared_distance = squaredNorm(vectors);
ArrayVector<Node> ends_to_be_checked;
Graph g(labels.shape());
for (EdgeIt edge(g); edge != lemon::INVALID; ++edge)
{
Node p1 = g.u(*edge),
p2 = g.v(*edge);
T1 l1 = labels[p1],
l2 = labels[p2];
maxLabel = max(maxLabel, max(l1, l2));
if(l1 == l2)
{
if(l1 <= 0) // only consider positive labels
continue;
const Node v1 = vectors[p1],
v2 = vectors[p2],
dp = p2 - p1,
dv = v2 - v1 + dp;
if(max(abs(dv)) <= 1) // points whose support points coincide or are adjacent
continue; // don't belong to the skeleton
// among p1 and p2, the point which is closer to the bisector
// of the support points p1 + v1 and p2 + v2 belongs to the skeleton
const MultiArrayIndex d1 = dot(dv, dp),
d2 = dot(dv, v1+v2);
if(d1*d2 <= 0)
{
dest[p1] = l1;
if(squared_distance[p1] == 4)
ends_to_be_checked.push_back(p1);
}
else
{
dest[p2] = l2;
if(squared_distance[p2] == 4)
ends_to_be_checked.push_back(p2);
}
}
else
{
if(l1 > 0 && max(abs(vectors[p1] + p1 - p2)) > 1)
dest[p1] = l1;
if(l2 > 0 && max(abs(vectors[p2] + p2 - p1)) > 1)
dest[p2] = l2;
}
}
// add a point when a skeleton line stops short of the shape boundary
// FIXME: can this be solved during the initial detection above?
Graph g8(labels.shape(), IndirectNeighborhood);
for (unsigned k=0; k<ends_to_be_checked.size(); ++k)
{
// The phenomenon only occurs at points whose distance from the background is 2.
// We've put these points into ends_to_be_checked.
Node p1 = ends_to_be_checked[k];
T2 label = dest[p1];
int count = 0;
for (ArcIt arc(g8, p1); arc != lemon::INVALID; ++arc)
{
Node p2 = g8.target(*arc);
if(dest[p2] == label && squared_distance[p2] < 4)
++count;
}
if(count == 0) // point p1 has no neighbor at the boundary => activate one
dest[p1+vectors[p1]/2] = label;
}
// from here on, we only need the squared DT, not the vector DT
}
// The true skeleton is defined by the interpixel edges between the
// Voronoi regions of the DT. Our skeleton detection algorithm affectively
// rounds the interpixel edges to the nearest pixel such that the result
// is mainly 8-connected and thin. However, thick skeleton pieces may still
// arise when two interpixel contours are only one pixel apart, i.e. a
// Voronoi region is only one pixel wide. Since this happens rarely, we
// can simply remove these cases by thinning.
detail::skeletonThinning(squared_distance, dest);
if(options.mode == SkeletonOptions::PruneCenterLine)
dest = 0;
// Reduce the full grid graph to a skeleton graph by inserting infinite
// edge weights between skeleton pixels and non-skeleton pixels.
if(features)
features->resize((size_t)maxLabel + 1);
ArrayVector<detail::SkeletonRegion<Node> > regions((size_t)maxLabel + 1);
Graph g(labels.shape(), IndirectNeighborhood);
WeightType maxWeight = g.edgeNum()*sqrt(N),
infiniteWeight = 0.5*NumericTraits<WeightType>::max();
typename Graph::template EdgeMap<WeightType> weights(g);
for (NodeIt node(g); node != lemon::INVALID; ++node)
{
Node p1 = *node;
T2 label = dest[p1];
if(label <= 0)
continue;
// FIXME: consider using an AdjacencyListGraph from here on
regions[(size_t)label].addNode(p1);
for (ArcIt arc(g, p1); arc != lemon::INVALID; ++arc)
{
Node p2 = g.target(*arc);
if(dest[p2] == label)
weights[*arc] = norm(p1-p2);
else
weights[*arc] = infiniteWeight;
}
}
ShortestPathDijkstra<Graph, WeightType> pathFinder(g);
// Handle the skeleton of each region individually.
for(std::size_t label=1; label < regions.size(); ++label)
{
Skeleton & skeleton = regions[label].skeleton;
if(skeleton.size() == 0) // label doesn't exist
continue;
// Find a diameter (longest path) in the skeleton.
Node anchor = regions[label].anchor,
lower = regions[label].lower,
upper = regions[label].upper + Shape(1);
pathFinder.run(lower, upper, weights, anchor, lemon::INVALID, maxWeight);
anchor = pathFinder.target();
pathFinder.reRun(weights, anchor, lemon::INVALID, maxWeight);
anchor = pathFinder.target();
Polygon<Shape> center_line;
center_line.push_back_unsafe(anchor);
while(pathFinder.predecessors()[center_line.back()] != center_line.back())
center_line.push_back_unsafe(pathFinder.predecessors()[center_line.back()]);
if(options.mode == SkeletonOptions::PruneCenterLine)
{
for(unsigned int k=0; k<center_line.size(); ++k)
dest[center_line[k]] = (T2)label;
continue; // to next label
}
// Perform the eccentricity transform of the skeleton
Node center = center_line[roundi(center_line.arcLengthQuantile(0.5))];
pathFinder.reRun(weights, center, lemon::INVALID, maxWeight);
bool compute_salience = (options.mode & SkeletonOptions::Salience) != 0;
ArrayVector<Node> raw_skeleton(pathFinder.discoveryOrder());
// from periphery to center: create skeleton tree and compute salience
for(int k=raw_skeleton.size()-1; k >= 0; --k)
{
Node p1 = raw_skeleton[k],
p2 = pathFinder.predecessors()[p1];
SNode & n1 = skeleton[p1];
SNode & n2 = skeleton[p2];
n1.parent = p2;
// remove non-skeleton edges (i.e. set weight = infiniteWeight)
for (BackArcIt arc(g, p1); arc != lemon::INVALID; ++arc)
{
Node p = g.target(*arc);
if(weights[*arc] == infiniteWeight)
continue; // edge never was in the graph
if(p == p2)
continue; // edge belongs to the skeleton
if(pathFinder.predecessors()[p] == p1)
continue; // edge belongs to the skeleton
if(n1.principal_child == lemon::INVALID ||
skeleton[p].principal_child == lemon::INVALID)
continue; // edge may belong to a loop => test later
weights[*arc] = infiniteWeight;
}
// propagate length to parent if this is the longest subtree
WeightType l = n1.length + norm(p1-p2);
if(n2.length < l)
{
n2.length = l;
n2.principal_child = p1;
}
if(compute_salience)
{
const double min_length = 4.0; // salience is meaningless for shorter segments due
// to quantization noise (staircasing) of the boundary
if(n1.length >= min_length)
{
n1.salience = max(n1.salience, (n1.length + 0.5) / sqrt(squared_distance[p1]));
// propagate salience to parent if this is the most salient subtree
if(n2.salience < n1.salience)
n2.salience = n1.salience;
}
}
else if(options.mode == SkeletonOptions::DontPrune)
n1.salience = dest[p1];
else
n1.salience = n1.length;
}
// from center to periphery: propagate salience and compute twice the partial area
for(int k=0; k < (int)raw_skeleton.size(); ++k)
{
Node p1 = raw_skeleton[k];
SNode & n1 = skeleton[p1];
Node p2 = n1.parent;
SNode & n2 = skeleton[p2];
if(p1 == n2.principal_child)
{
n1.length = n2.length;
n1.salience = n2.salience;
}
else
{
n1.length += norm(p2-p1);
}
n1.partial_area = n2.partial_area + (p1[0]*p2[1] - p1[1]*p2[0]);
}
// always treat eccentricity center as a loop, so that it cannot be pruned
// away unless (options.mode & PreserveTopology) is false.
skeleton[center].is_loop = true;
// from periphery to center: * find and propagate loops
// * delete branches not reaching the boundary
detail::CheckForHole<std::size_t, MultiArrayView<2, T1, S1> > hasNoHole(label, labels);
int hole_count = 0;
double total_length = 0.0;
for(int k=raw_skeleton.size()-1; k >= 0; --k)
{
Node p1 = raw_skeleton[k];
SNode & n1 = skeleton[p1];
if(n1.principal_child == lemon::INVALID)
{
for (ArcIt arc(g, p1); arc != lemon::INVALID; ++arc)
{
Node p2 = g.target(*arc);
SNode * n2 = &skeleton[p2];
if(n1.parent == p2)
continue; // going back to the parent can't result in a loop
if(weights[*arc] == infiniteWeight)
continue; // p2 is not in the tree or the loop has already been handled
// compute twice the area exclosed by the potential loop
MultiArrayIndex area2 = abs(n1.partial_area - (p1[0]*p2[1] - p1[1]*p2[0]) - n2->partial_area);
if(area2 <= 3) // area is too small to enclose a hole => loop is a discretization artifact
continue;
// use Dijkstra to find the loop
WeightType edge_length = weights[*arc];
weights[*arc] = infiniteWeight;
pathFinder.reRun(weights, p1, p2);
Polygon<Shape2> poly;
{
poly.push_back_unsafe(p1);
poly.push_back_unsafe(p2);
Node p = p2;
do
{
p = pathFinder.predecessors()[p];
poly.push_back_unsafe(p);
}
while(p != pathFinder.predecessors()[p]);
}
// check if the loop contains a hole or is just a discretization artifact
if(!inspectPolygon(poly, hasNoHole))
{
// it's a genuine loop => mark it and propagate salience
++hole_count;
total_length += n1.length + n2->length;
double max_salience = max(n1.salience, n2->salience);
for(int p=1; p<poly.size(); ++p)
{
SNode & n = skeleton[poly[p]];
n.is_loop = true;
n.salience = max(n.salience, max_salience);
}
}
}
// delete skeleton branches that are not loops and don't reach the shape border
// (these branches are discretization artifacts)
if(!n1.is_loop && squared_distance[p1] >= 4)
{
SNode * n = &n1;
while(true)
{
n->salience = 0;
// remove all of p1's edges
for(ArcIt arc(g, p1); arc != lemon::INVALID; ++arc)
{
weights[*arc] = infiniteWeight;
}
if(skeleton[n->parent].principal_child != p1)
break;
p1 = n->parent;
n = &skeleton[p1];
}
}
}
if(n1.is_loop)
skeleton[n1.parent].is_loop = true;
}
bool dont_prune = (options.mode & SkeletonOptions::Prune) == 0;
bool preserve_topology = (options.mode & SkeletonOptions::PreserveTopology) != 0 ||
options.mode == SkeletonOptions::Prune;
bool relative_pruning = (options.mode & SkeletonOptions::Relative) != 0;
WeightType threshold = (options.mode == SkeletonOptions::PruneTopology ||
options.mode == SkeletonOptions::Prune)
? infiniteWeight
: relative_pruning
? options.pruning_threshold*skeleton[center].salience
: options.pruning_threshold;
// from center to periphery: write result
int branch_count = 0;
double average_length = 0;
for(int k=0; k < (int)raw_skeleton.size(); ++k)
{
Node p1 = raw_skeleton[k];
SNode & n1 = skeleton[p1];
Node p2 = n1.parent;
SNode & n2 = skeleton[p2];
if(n1.principal_child == lemon::INVALID &&
n1.salience >= threshold &&
!n1.is_loop)
{
++branch_count;
average_length += n1.length;
total_length += n1.length;
}
if(dont_prune)
dest[p1] = n1.salience;
else if(preserve_topology)
{
if(!n1.is_loop && n1.salience < threshold)
dest[p1] = 0;
}
else if(p1 != center && n1.salience < threshold)
dest[p1] = 0;
}
if(branch_count > 0)
average_length /= branch_count;
if(features)
{
(*features)[label].diameter = center_line.length();
(*features)[label].total_length = total_length;
(*features)[label].average_length = average_length;
(*features)[label].branch_count = branch_count;
(*features)[label].hole_count = hole_count;
(*features)[label].center = center;
(*features)[label].terminal1 = center_line.front();
(*features)[label].terminal2 = center_line.back();
(*features)[label].euclidean_diameter = norm(center_line.back()-center_line.front());
}
}
if(options.mode == SkeletonOptions::Prune)
detail::skeletonThinning(squared_distance, dest, false);
}
class SkeletonFeatures
{
public:
double diameter, total_length, average_length, euclidean_diameter;
UInt32 branch_count, hole_count;
Shape2 center, terminal1, terminal2;
SkeletonFeatures()
: diameter(0)
, total_length(0)
, average_length(0)
, euclidean_diameter(0)
, branch_count(0)
, hole_count(0)
{}
};
/********************************************************/
/* */
/* skeletonizeImage */
/* */
/********************************************************/
/*
To compute the skeleton reliably in higher dimensions, we have to work on
a topological grid. The tricks to work with rounded skeletons on the
pixel grid probably don't generalize from 2D to 3D and higher. Specifically:
* Compute Voronoi regions of the vector distance transformation according to
identical support point to make sure that disconnected Voronoi regions
still get only a single label.
* Merge Voronoi regions whose support points are adjacent.
* Mark skeleton candidates on the interpixel grid after the basic merge.
* Detect skeleton segments simply by connected components labeling in the interpixel grid.
* Skeleton segments form hyperplanes => use this property to compute segment
attributes.
* Detect holes (and therefore, skeleton segments that are critical for topology)
by computing the depth of each region/surface in the homotopy tree.
* Add a pruning mode where holes are only preserved if their size exceeds a threshold.
To implement this cleanly, we first need a good implementation of the topological grid graph.
*/
// template <unsigned int N, class T1, class S1,
// class T2, class S2>
// void
// skeletonizeImage(MultiArrayView<N, T1, S1> const & labels,
// MultiArrayView<N, T2, S2> dest,
// SkeletonOptions const & options = SkeletonOptions())
// {
/** \brief Skeletonization of all regions in a labeled 2D image.
<b> Declarations:</b>
\code
namespace vigra {
template <class T1, class S1,
class T2, class S2>
void
skeletonizeImage(MultiArrayView<2, T1, S1> const & labels,
MultiArrayView<2, T2, S2> dest,
SkeletonOptions const & options = SkeletonOptions());
}
\endcode
This function computes the skeleton for each region in the 2D label image \a labels
and paints the results into the result image \a dest. Input label
<tt>0</tt> is interpreted as background and always ignored. Skeletons will be
marked with the same label as the corresponding region (unless options
<tt>returnLength()</tt> or <tt>returnSalience()</tt> are selected, see below).
Non-skeleton pixels will receive label <tt>0</tt>.
For each region, the algorithm proceeds in the following steps:
<ol>
<li>Compute the \ref boundaryVectorDistance() relative to the \ref OuterBoundary of the region.</li>
<li>Mark the raw skeleton: find 4-adjacent pixel pairs whose nearest boundary points are neither equal
nor adjacent and mark one pixel of the pair as a skeleton candidate. The resulting raw skeleton
is 8-connected and thin. Skip the remaining steps when option <tt>dontPrune()</tt> is selected.</li>
<li>Compute the eccentricity transform of the raw skeleton and turn the skeleton into a tree
whose root is the eccentricity center. When option <tt>pruneCenterLine()</tt> is selected,
delete all skeleton points that do not belong to the two longest tree branches and
skip the remaining steps.</li>
<li>For each pixel on the skeleton, compute its <tt>length</tt> attribute as the depth of the
pixel's longest subtree. Compute its <tt>salience</tt> attribute as the ratio between
<tt>length</tt> and <tt>distance</tt>, where <tt>distance</tt> is the pixel's distance to
the nearest boundary point according to the distance transform. It holds that <tt>length >= 0.5</tt>
and <tt>salience >= 1.0</tt>.</li>
<li>Detect skeleton branching points and define <i>skeleton segments</i> as maximal connected pieces
without branching points.</li>
<li>Compute <tt>length</tt> and <tt>salience</tt> of each segment as the maximum of these
attributes among the pixels in the segment. When options <tt>returnLength()</tt> or
<tt>returnSalience()</tt> are selected, skip the remaining steps and return the
requested segment attribute in <tt>dest</tt>. In this case, <tt>dest</tt>'s
<tt>value_type</tt> should be a floating point type to exactly accomodate the
attribute values.</li>
<li>Detect minimal cycles in the raw skeleton that enclose holes in the region (if any) and mark
the corresponding pixels as critical for skeleton topology.</li>
<li>Prune skeleton segments according to the selected pruning strategy and return the result.
The following pruning strategies are available:
<ul>
<li><tt>pruneLength(threshold, preserve_topology)</tt>: Retain only segments whose length attribute
exceeds the given <tt>threshold</tt>. When <tt>preserve_topology</tt> is true
(the defult), cycles around holes are preserved regardless of their length.
Otherwise, they are pruned as well.</li>
<li><tt>pruneLengthRelative(threshold, preserve_topology)</tt>: Like <tt>pruneLength()</tt>,
but the threshold is specified as a fraction of the maximum segment length in
the present region.</li>
<li><tt>pruneSalience(threshold, preserve_topology)</tt>: Retain only segments whose salience attribute
exceeds the given <tt>threshold</tt>. When <tt>preserve_topology</tt> is true
(the defult), cycles around holes are preserved regardless of their salience.
Otherwise, they are pruned as well.</li>
<li><tt>pruneSalienceRelative(threshold, preserve_topology)</tt>: Like <tt>pruneSalience()</tt>,
but the threshold is specified as a fraction of the maximum segment salience in
the present region.</li>
<li><tt>pruneTopology(preserve_center)</tt>: Retain only segments that are essential for the region's
topology. If <tt>preserve_center</tt> is true (the default), the eccentricity
center is also preserved, even if it is not essential. Otherwise, it might be
removed. The eccentricity center is always the only remaining point when
the region has no holes.</li>
</ul></li>
</ol>
The skeleton has the following properties:
<ul>
<li>It is 8-connected and thin (except when two independent branches happen to run alongside
before they divert). Skeleton points are defined by rounding the exact Euclidean skeleton
locations to the nearest pixel.</li>
<li>Skeleton branches terminate either at the region boundary or at a cycle. There are no branch
end points in the region interior.</li>
<li>The salience threshold acts as a scale parameter: Large thresholds only retain skeleton
branches characterizing the general region shape. When the threshold gets smaller, ever
more detailed boundary bulges will be represented by a skeleton branch.</li>
</ul>
Remark: If you have an application where a skeleton graph would be more useful
than a skeleton image, function <tt>skeletonizeImage()</tt> can be changed/extended easily.
<b> Usage:</b>
<b>\#include</b> \<vigra/skeleton.hxx\><br/>
Namespace: vigra
\code
Shape2 shape(width, height);
MultiArray<2, UInt32> source(shape);
MultiArray<2, UInt32> dest(shape);
...
// Skeletonize and keep only those segments that are at least 10% of the maximum
// length (the maximum length is half the skeleton diameter).
skeletonizeImage(source, dest,
SkeletonOptions().pruneLengthRelative(0.1));
\endcode
\see vigra::boundaryVectorDistance()
*/
doxygen_overloaded_function(template <...> void skeletonizeImage)
template <class T1, class S1,
class T2, class S2>
void
skeletonizeImage(MultiArrayView<2, T1, S1> const & labels,
MultiArrayView<2, T2, S2> dest,
SkeletonOptions const & options = SkeletonOptions())
{
skeletonizeImageImpl(labels, dest, (ArrayVector<SkeletonFeatures>*)0, options);
}
template <class T, class S>
void
extractSkeletonFeatures(MultiArrayView<2, T, S> const & labels,
ArrayVector<SkeletonFeatures> & features,
SkeletonOptions const & options = SkeletonOptions())
{
MultiArray<2, float> skeleton(labels.shape());
skeletonizeImageImpl(labels, skeleton, &features, options);
}
//@}
} //-- namespace vigra
#endif //-- VIGRA_SKELETON_HXX
| 41.282051 | 115 | 0.535727 | [
"object",
"shape",
"vector",
"transform",
"3d"
] |
78e1cea4c9cfb56baf4f69c6b1fd23a77da7933e | 20,317 | cpp | C++ | core/mapi/mapiProfileFunctions.cpp | jimbeveridge/mfcmapi | 9f01b707a73bcede539e0b057a855bddaf1e9ae9 | [
"MIT"
] | 1 | 2019-08-09T16:48:38.000Z | 2019-08-09T16:48:38.000Z | core/mapi/mapiProfileFunctions.cpp | killvxk/mfcmapi | 0b3c95bfa62bb335f027944e92040d37b0b8115d | [
"MIT"
] | 1 | 2019-11-21T15:24:31.000Z | 2019-11-21T18:05:57.000Z | core/mapi/mapiProfileFunctions.cpp | youtiaocoder/mfcmapi-1 | f2e58e7153b033b92c0b3989010428a2291d8527 | [
"MIT"
] | null | null | null | #include <core/stdafx.h>
#include <core/mapi/mapiProfileFunctions.h>
#include <core/mapi/extraPropTags.h>
#include <core/utility/output.h>
#include <core/utility/strings.h>
#include <core/utility/error.h>
#include <core/mapi/mapiFunctions.h>
#include <core/mapi/interfaces.h>
#include <core/mapi/mapiOutput.h>
namespace mapi
{
namespace profile
{
#define PR_MARKER PR_BODY_A
#define MARKER_STRING "MFCMAPI Existing Provider Marker" // STRING_OK
// Walk through providers and add/remove our tag
// bAddMark of true will add tag, bAddMark of false will remove it
_Check_return_ HRESULT HrMarkExistingProviders(_In_ LPSERVICEADMIN lpServiceAdmin, bool bAddMark)
{
LPMAPITABLE lpProviderTable = nullptr;
if (!lpServiceAdmin) return MAPI_E_INVALID_PARAMETER;
static const SizedSPropTagArray(1, pTagUID) = {1, {PR_SERVICE_UID}};
auto hRes = EC_MAPI(lpServiceAdmin->GetMsgServiceTable(0, &lpProviderTable));
if (lpProviderTable)
{
LPSRowSet lpRowSet = nullptr;
hRes =
EC_MAPI(HrQueryAllRows(lpProviderTable, LPSPropTagArray(&pTagUID), nullptr, nullptr, 0, &lpRowSet));
if (lpRowSet) output::outputSRowSet(output::DBGGeneric, nullptr, lpRowSet, nullptr);
if (lpRowSet && lpRowSet->cRows >= 1)
{
for (ULONG i = 0; i < lpRowSet->cRows; i++)
{
const auto lpCurRow = &lpRowSet->aRow[i];
auto lpServiceUID = PpropFindProp(lpCurRow->lpProps, lpCurRow->cValues, PR_SERVICE_UID);
if (lpServiceUID)
{
auto lpSect = OpenProfileSection(lpServiceAdmin, &lpServiceUID->Value.bin);
if (lpSect)
{
if (bAddMark)
{
SPropValue PropVal;
PropVal.ulPropTag = PR_MARKER;
PropVal.Value.lpszA = const_cast<LPSTR>(MARKER_STRING);
EC_MAPI_S(lpSect->SetProps(1, &PropVal, nullptr));
}
else
{
SPropTagArray pTagArray = {1, {PR_MARKER}};
WC_MAPI_S(lpSect->DeleteProps(&pTagArray, nullptr));
}
hRes = EC_MAPI(lpSect->SaveChanges(0));
lpSect->Release();
}
}
}
}
FreeProws(lpRowSet);
lpProviderTable->Release();
}
return hRes;
}
// Returns first provider without our mark on it
_Check_return_ LPSRowSet HrFindUnmarkedProvider(_In_ LPSERVICEADMIN lpServiceAdmin)
{
if (!lpServiceAdmin) return nullptr;
LPSRowSet lpRowSet = nullptr;
static const SizedSPropTagArray(1, pTagUID) = {1, {PR_SERVICE_UID}};
LPMAPITABLE lpProviderTable = nullptr;
auto hRes = EC_MAPI(lpServiceAdmin->GetMsgServiceTable(0, &lpProviderTable));
if (lpProviderTable)
{
LPPROFSECT lpSect = nullptr;
EC_MAPI_S(lpProviderTable->SetColumns(LPSPropTagArray(&pTagUID), TBL_BATCH));
for (;;)
{
hRes = EC_MAPI(lpProviderTable->QueryRows(1, 0, &lpRowSet));
if (hRes == S_OK && lpRowSet && 1 == lpRowSet->cRows)
{
const auto lpCurRow = &lpRowSet->aRow[0];
auto lpServiceUID = PpropFindProp(lpCurRow->lpProps, lpCurRow->cValues, PR_SERVICE_UID);
if (lpServiceUID)
{
lpSect = OpenProfileSection(lpServiceAdmin, &lpServiceUID->Value.bin);
if (lpSect)
{
auto pTagArray = SPropTagArray{1, {PR_MARKER}};
ULONG ulPropVal = 0;
LPSPropValue lpsPropVal = nullptr;
EC_H_GETPROPS_S(lpSect->GetProps(&pTagArray, NULL, &ulPropVal, &lpsPropVal));
if (!(strings::CheckStringProp(lpsPropVal, PROP_TYPE(PR_MARKER)) &&
!strcmp(lpsPropVal->Value.lpszA, MARKER_STRING)))
{
// got an unmarked provider - this is our hit
// Don't free *lpRowSet - we're returning it
MAPIFreeBuffer(lpsPropVal);
break;
}
MAPIFreeBuffer(lpsPropVal);
lpSect->Release();
lpSect = nullptr;
}
}
// go on to next one in the loop
FreeProws(lpRowSet);
lpRowSet = nullptr;
}
else
{
// no more hits - get out of the loop
FreeProws(lpRowSet);
lpRowSet = nullptr;
break;
}
}
if (lpSect) lpSect->Release();
lpProviderTable->Release();
}
return lpRowSet;
}
_Check_return_ HRESULT HrAddServiceToProfile(
_In_ const std::string& lpszServiceName, // Service Name
_In_ ULONG_PTR ulUIParam, // hwnd for CreateMsgService
ULONG ulFlags, // Flags for CreateMsgService
ULONG cPropVals, // Count of properties for ConfigureMsgService
_In_opt_ LPSPropValue lpPropVals, // Properties for ConfigureMsgService
_In_ const std::string& lpszProfileName) // profile name
{
if (lpszServiceName.empty() || lpszProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
output::DebugPrint(
output::DBGGeneric,
L"HrAddServiceToProfile(%hs,%hs)\n",
lpszServiceName.c_str(),
lpszProfileName.c_str());
LPPROFADMIN lpProfAdmin = nullptr;
// Connect to Profile Admin interface.
auto hRes = EC_MAPI(MAPIAdminProfiles(0, &lpProfAdmin));
if (!lpProfAdmin) return hRes;
LPSERVICEADMIN lpServiceAdmin = nullptr;
hRes = EC_MAPI(lpProfAdmin->AdminServices(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszProfileName.c_str())),
LPTSTR(""),
0,
0,
&lpServiceAdmin));
if (lpServiceAdmin)
{
MAPIUID uidService = {0};
auto lpuidService = &uidService;
auto lpServiceAdmin2 = mapi::safe_cast<LPSERVICEADMIN2>(lpServiceAdmin);
if (lpServiceAdmin2)
{
hRes = EC_H_MSG(
IDS_CREATEMSGSERVICEFAILED,
lpServiceAdmin2->CreateMsgServiceEx(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszServiceName.c_str())),
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszServiceName.c_str())),
ulUIParam,
ulFlags,
&uidService));
}
else
{
// Only need to mark if we plan on calling ConfigureMsgService
if (lpPropVals)
{
// Add a dummy prop to the current providers
hRes = EC_H(HrMarkExistingProviders(lpServiceAdmin, true));
}
if (SUCCEEDED(hRes))
{
hRes = EC_H_MSG(
IDS_CREATEMSGSERVICEFAILED,
lpServiceAdmin->CreateMsgService(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszServiceName.c_str())),
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszServiceName.c_str())),
ulUIParam,
ulFlags));
}
if (lpPropVals)
{
// Look for a provider without our dummy prop
const auto lpRowSet = HrFindUnmarkedProvider(lpServiceAdmin);
if (lpRowSet) output::outputSRowSet(output::DBGGeneric, nullptr, lpRowSet, nullptr);
// should only have one unmarked row
if (lpRowSet && lpRowSet->cRows == 1)
{
const auto lpServiceUIDProp =
PpropFindProp(lpRowSet->aRow[0].lpProps, lpRowSet->aRow[0].cValues, PR_SERVICE_UID);
if (lpServiceUIDProp)
{
lpuidService = reinterpret_cast<LPMAPIUID>(lpServiceUIDProp->Value.bin.lpb);
}
}
// Strip out the dummy prop
hRes = EC_H(HrMarkExistingProviders(lpServiceAdmin, false));
FreeProws(lpRowSet);
}
}
if (lpPropVals)
{
hRes =
EC_H_CANCEL(lpServiceAdmin->ConfigureMsgService(lpuidService, NULL, 0, cPropVals, lpPropVals));
}
if (lpServiceAdmin2) lpServiceAdmin2->Release();
lpServiceAdmin->Release();
}
lpProfAdmin->Release();
return hRes;
}
_Check_return_ HRESULT HrAddExchangeToProfile(
_In_ ULONG_PTR ulUIParam, // hwnd for CreateMsgService
_In_ const std::string& lpszServerName,
_In_ const std::string& lpszMailboxName,
_In_ const std::string& lpszProfileName)
{
output::DebugPrint(
output::DBGGeneric,
L"HrAddExchangeToProfile(%hs,%hs,%hs)\n",
lpszServerName.c_str(),
lpszMailboxName.c_str(),
lpszProfileName.c_str());
if (lpszServerName.empty() || lpszMailboxName.empty() || lpszProfileName.empty())
return MAPI_E_INVALID_PARAMETER;
#define NUMEXCHANGEPROPS 2
SPropValue PropVal[NUMEXCHANGEPROPS];
PropVal[0].ulPropTag = PR_PROFILE_UNRESOLVED_SERVER;
PropVal[0].Value.lpszA = const_cast<LPSTR>(lpszServerName.c_str());
PropVal[1].ulPropTag = PR_PROFILE_UNRESOLVED_NAME;
PropVal[1].Value.lpszA = const_cast<LPSTR>(lpszMailboxName.c_str());
const auto hRes = EC_H(HrAddServiceToProfile(
"MSEMS", ulUIParam, NULL, NUMEXCHANGEPROPS, PropVal, lpszProfileName)); // STRING_OK
return hRes;
}
_Check_return_ HRESULT HrAddPSTToProfile(
_In_ ULONG_PTR ulUIParam, // hwnd for CreateMsgService
bool bUnicodePST,
_In_ const std::wstring& lpszPSTPath, // PST name
_In_ const std::string& lpszProfileName, // profile name
bool bPasswordSet, // whether or not to include a password
_In_ const std::string& lpszPassword) // password to include
{
auto hRes = S_OK;
output::DebugPrint(
output::DBGGeneric,
L"HrAddPSTToProfile(0x%X,%ws,%hs,0x%X,%hs)\n",
bUnicodePST,
lpszPSTPath.c_str(),
lpszProfileName.c_str(),
bPasswordSet,
lpszPassword.c_str());
if (lpszPSTPath.empty() || lpszProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
if (bUnicodePST)
{
SPropValue PropVal[3];
PropVal[0].ulPropTag = CHANGE_PROP_TYPE(PR_PST_PATH, PT_UNICODE);
PropVal[0].Value.lpszW = const_cast<LPWSTR>(lpszPSTPath.c_str());
PropVal[1].ulPropTag = PR_PST_CONFIG_FLAGS;
PropVal[1].Value.ul = PST_CONFIG_UNICODE;
PropVal[2].ulPropTag = PR_PST_PW_SZ_OLD;
PropVal[2].Value.lpszA = const_cast<LPSTR>(lpszPassword.c_str());
hRes = EC_H(HrAddServiceToProfile(
"MSUPST MS", ulUIParam, NULL, bPasswordSet ? 3 : 2, PropVal, lpszProfileName)); // STRING_OK
}
else
{
SPropValue PropVal[2];
PropVal[0].ulPropTag = CHANGE_PROP_TYPE(PR_PST_PATH, PT_UNICODE);
PropVal[0].Value.lpszW = const_cast<LPWSTR>(lpszPSTPath.c_str());
PropVal[1].ulPropTag = PR_PST_PW_SZ_OLD;
PropVal[1].Value.lpszA = const_cast<LPSTR>(lpszPassword.c_str());
hRes = EC_H(HrAddServiceToProfile(
"MSPST MS", ulUIParam, NULL, bPasswordSet ? 2 : 1, PropVal, lpszProfileName)); // STRING_OK
}
return hRes;
}
// Creates an empty profile.
_Check_return_ HRESULT HrCreateProfile(_In_ const std::string& lpszProfileName) // profile name
{
LPPROFADMIN lpProfAdmin = nullptr;
output::DebugPrint(output::DBGGeneric, L"HrCreateProfile(%hs)\n", lpszProfileName.c_str());
if (lpszProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
// Connect to Profile Admin interface.
auto hRes = EC_MAPI(MAPIAdminProfiles(0, &lpProfAdmin));
if (!lpProfAdmin) return hRes;
// Create the profile
hRes = WC_MAPI(lpProfAdmin->CreateProfile(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszProfileName.c_str())),
nullptr,
0,
NULL)); // fMapiUnicode is not supported!
if (hRes != S_OK)
{
// Did it fail because a profile of this name already exists?
const auto hResCheck = HrMAPIProfileExists(lpProfAdmin, lpszProfileName);
CHECKHRESMSG(hResCheck, IDS_DUPLICATEPROFILE);
}
lpProfAdmin->Release();
return hRes;
}
// Removes a profile.
_Check_return_ HRESULT HrRemoveProfile(_In_ const std::string& lpszProfileName)
{
LPPROFADMIN lpProfAdmin = nullptr;
output::DebugPrint(output::DBGGeneric, L"HrRemoveProfile(%hs)\n", lpszProfileName.c_str());
if (lpszProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
auto hRes = EC_MAPI(MAPIAdminProfiles(0, &lpProfAdmin));
if (!lpProfAdmin) return hRes;
hRes = EC_MAPI(
lpProfAdmin->DeleteProfile(reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszProfileName.c_str())), 0));
lpProfAdmin->Release();
RegFlushKey(HKEY_LOCAL_MACHINE);
RegFlushKey(HKEY_CURRENT_USER);
return hRes;
}
// Set a profile as default.
_Check_return_ HRESULT HrSetDefaultProfile(_In_ const std::string& lpszProfileName)
{
LPPROFADMIN lpProfAdmin = nullptr;
output::DebugPrint(output::DBGGeneric, L"HrRemoveProfile(%hs)\n", lpszProfileName.c_str());
if (lpszProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
auto hRes = EC_MAPI(MAPIAdminProfiles(0, &lpProfAdmin));
if (!lpProfAdmin) return hRes;
hRes = EC_MAPI(lpProfAdmin->SetDefaultProfile(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszProfileName.c_str())), 0));
lpProfAdmin->Release();
RegFlushKey(HKEY_LOCAL_MACHINE);
RegFlushKey(HKEY_CURRENT_USER);
return hRes;
}
// Checks for an existing profile.
_Check_return_ HRESULT
HrMAPIProfileExists(_In_ LPPROFADMIN lpProfAdmin, _In_ const std::string& lpszProfileName)
{
LPMAPITABLE lpTable = nullptr;
LPSRowSet lpRows = nullptr;
static const SizedSPropTagArray(1, rgPropTag) = {1, {PR_DISPLAY_NAME_A}};
output::DebugPrint(output::DBGGeneric, L"HrMAPIProfileExists()\n");
if (!lpProfAdmin || lpszProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
// Get a table of existing profiles
auto hRes = EC_MAPI(lpProfAdmin->GetProfileTable(0, &lpTable));
if (!lpTable) return hRes;
hRes = EC_MAPI(HrQueryAllRows(lpTable, LPSPropTagArray(&rgPropTag), nullptr, nullptr, 0, &lpRows));
if (lpRows)
{
if (lpRows->cRows == 0)
{
// If table is empty then profile doesn't exist
hRes = S_OK;
}
else
{
// Search rows for the folder in question
if (SUCCEEDED(hRes))
{
for (ULONG i = 0; i < lpRows->cRows; i++)
{
const auto lpProp = lpRows->aRow[i].lpProps;
const auto ulComp = EC_D(
ULONG,
CompareStringA(
g_lcid, // LOCALE_INVARIANT,
NORM_IGNORECASE,
lpProp[0].Value.lpszA,
-1,
lpszProfileName.c_str(),
-1));
if (ulComp == CSTR_EQUAL)
{
hRes = E_ACCESSDENIED;
break;
}
}
}
}
}
if (lpRows) FreeProws(lpRows);
lpTable->Release();
return hRes;
}
_Check_return_ HRESULT GetProfileServiceVersion(
_In_ const std::string& lpszProfileName,
_Out_ ULONG* lpulServerVersion,
_Out_ EXCHANGE_STORE_VERSION_NUM* lpStoreVersion,
_Out_ bool* lpbFoundServerVersion,
_Out_ bool* lpbFoundServerFullVersion)
{
if (lpszProfileName.empty() || !lpulServerVersion || !lpStoreVersion || !lpbFoundServerVersion ||
!lpbFoundServerFullVersion)
return MAPI_E_INVALID_PARAMETER;
*lpulServerVersion = NULL;
memset(lpStoreVersion, 0, sizeof(EXCHANGE_STORE_VERSION_NUM));
*lpbFoundServerVersion = false;
*lpbFoundServerFullVersion = false;
LPPROFADMIN lpProfAdmin = nullptr;
LPSERVICEADMIN lpServiceAdmin = nullptr;
output::DebugPrint(output::DBGGeneric, L"GetProfileServiceVersion(%hs)\n", lpszProfileName.c_str());
auto hRes = EC_MAPI(MAPIAdminProfiles(0, &lpProfAdmin));
if (!lpProfAdmin) return hRes;
hRes = EC_MAPI(lpProfAdmin->AdminServices(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszProfileName.c_str())),
LPTSTR(""),
0,
0,
&lpServiceAdmin));
if (lpServiceAdmin)
{
LPPROFSECT lpProfSect = nullptr;
hRes = EC_MAPI(
lpServiceAdmin->OpenProfileSection(LPMAPIUID(pbGlobalProfileSectionGuid), nullptr, 0, &lpProfSect));
if (lpProfSect)
{
LPSPropValue lpServerVersion = nullptr;
hRes = WC_MAPI(HrGetOneProp(lpProfSect, PR_PROFILE_SERVER_VERSION, &lpServerVersion));
if (SUCCEEDED(hRes) && lpServerVersion && PR_PROFILE_SERVER_VERSION == lpServerVersion->ulPropTag)
{
*lpbFoundServerVersion = true;
*lpulServerVersion = lpServerVersion->Value.l;
}
MAPIFreeBuffer(lpServerVersion);
LPSPropValue lpServerFullVersion = nullptr;
hRes = WC_MAPI(HrGetOneProp(lpProfSect, PR_PROFILE_SERVER_FULL_VERSION, &lpServerFullVersion));
if (SUCCEEDED(hRes) && lpServerFullVersion &&
PR_PROFILE_SERVER_FULL_VERSION == lpServerFullVersion->ulPropTag &&
sizeof(EXCHANGE_STORE_VERSION_NUM) == lpServerFullVersion->Value.bin.cb)
{
output::DebugPrint(output::DBGGeneric, L"PR_PROFILE_SERVER_FULL_VERSION = ");
output::outputBinary(output::DBGGeneric, nullptr, lpServerFullVersion->Value.bin);
output::DebugPrint(output::DBGGeneric, L"\n");
memcpy(lpStoreVersion, lpServerFullVersion->Value.bin.lpb, sizeof(EXCHANGE_STORE_VERSION_NUM));
*lpbFoundServerFullVersion = true;
}
MAPIFreeBuffer(lpServerFullVersion);
lpProfSect->Release();
}
lpServiceAdmin->Release();
}
lpProfAdmin->Release();
// If we found any server version, consider the call a success
if (*lpbFoundServerVersion || *lpbFoundServerFullVersion) hRes = S_OK;
return hRes;
}
// Copies a profile.
_Check_return_ HRESULT
HrCopyProfile(_In_ const std::string& lpszOldProfileName, _In_ const std::string& lpszNewProfileName)
{
LPPROFADMIN lpProfAdmin = nullptr;
output::DebugPrint(
output::DBGGeneric,
L"HrCopyProfile(%hs, %hs)\n",
lpszOldProfileName.c_str(),
lpszNewProfileName.c_str());
if (lpszOldProfileName.empty() || lpszNewProfileName.empty()) return MAPI_E_INVALID_PARAMETER;
auto hRes = EC_MAPI(MAPIAdminProfiles(0, &lpProfAdmin));
if (!lpProfAdmin) return hRes;
hRes = EC_MAPI(lpProfAdmin->CopyProfile(
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszOldProfileName.c_str())),
nullptr,
reinterpret_cast<LPTSTR>(const_cast<LPSTR>(lpszNewProfileName.c_str())),
NULL,
NULL));
lpProfAdmin->Release();
return hRes;
}
_Check_return_ LPPROFSECT OpenProfileSection(_In_ LPSERVICEADMIN lpServiceAdmin, _In_ LPSBinary lpServiceUID)
{
if (!lpServiceUID || !lpServiceAdmin) return nullptr;
output::DebugPrint(output::DBGOpenItemProp, L"OpenProfileSection opening lpServiceUID = ");
output::outputBinary(output::DBGOpenItemProp, nullptr, *lpServiceUID);
output::DebugPrint(output::DBGOpenItemProp, L"\n");
LPPROFSECT lpProfSect = nullptr;
// First, we try the normal way of opening the profile section:
WC_MAPI_S(lpServiceAdmin->OpenProfileSection(
reinterpret_cast<LPMAPIUID>(lpServiceUID->lpb),
nullptr,
MAPI_MODIFY | MAPI_FORCE_ACCESS, // passing this flag might actually work with Outlook 2000 and XP
&lpProfSect));
if (!lpProfSect)
{
///////////////////////////////////////////////////////////////////
// HACK CENTRAL. This is a MAJOR hack. MAPI will always return E_ACCESSDENIED
// when we open a profile section on the service if we are a client. The workaround
// (HACK) is to call into one of MAPI's internal functions that bypasses
// the security check. We build a Interface to it and then point to it from our
// offset of 0x48. USE AT YOUR OWN RISK! NOT SUPPORTED!
interface IOpenSectionHack : IUnknown
{
virtual HRESULT STDMETHODCALLTYPE OpenSection(LPMAPIUID, ULONG, LPPROFSECT*) = 0;
};
const auto ppProfile =
reinterpret_cast<IOpenSectionHack**>((reinterpret_cast<BYTE*>(lpServiceAdmin) + 0x48));
// Now, we want to get open the Services Profile Section and store that
// interface with the Object
if (ppProfile && *ppProfile)
{
EC_MAPI_S(
(*ppProfile)
->OpenSection(reinterpret_cast<LPMAPIUID>(lpServiceUID->lpb), MAPI_MODIFY, &lpProfSect));
}
// END OF HACK. I'm amazed that this works....
///////////////////////////////////////////////////////////////////
}
return lpProfSect;
}
_Check_return_ LPPROFSECT OpenProfileSection(_In_ LPPROVIDERADMIN lpProviderAdmin, _In_ LPSBinary lpProviderUID)
{
if (!lpProviderUID || !lpProviderAdmin) return nullptr;
output::DebugPrint(output::DBGOpenItemProp, L"OpenProfileSection opening lpServiceUID = ");
output::outputBinary(output::DBGOpenItemProp, nullptr, *lpProviderUID);
output::DebugPrint(output::DBGOpenItemProp, L"\n");
LPPROFSECT lpProfSect = nullptr;
WC_MAPI_S(lpProviderAdmin->OpenProfileSection(
reinterpret_cast<LPMAPIUID>(lpProviderUID->lpb),
nullptr,
MAPI_MODIFY | MAPI_FORCE_ACCESS,
&lpProfSect));
if (!lpProfSect)
{
// We only do this hack as a last resort - it can crash some versions of Outlook, but is required for Exchange
*(reinterpret_cast<BYTE*>(lpProviderAdmin) + 0x60) = 0x2; // Use at your own risk! NOT SUPPORTED!
WC_MAPI_S(lpProviderAdmin->OpenProfileSection(
reinterpret_cast<LPMAPIUID>(lpProviderUID->lpb), nullptr, MAPI_MODIFY, &lpProfSect));
}
return lpProfSect;
}
} // namespace profile
} // namespace mapi | 31.548137 | 114 | 0.687749 | [
"object"
] |
78e2a2e011401a6ef6eab5fdef661f6626f45741 | 1,719 | cpp | C++ | aws-cpp-sdk-lookoutequipment/source/model/MonotonicValues.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-lookoutequipment/source/model/MonotonicValues.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-lookoutequipment/source/model/MonotonicValues.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lookoutequipment/model/MonotonicValues.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LookoutEquipment
{
namespace Model
{
MonotonicValues::MonotonicValues() :
m_status(StatisticalIssueStatus::NOT_SET),
m_statusHasBeenSet(false),
m_monotonicity(Monotonicity::NOT_SET),
m_monotonicityHasBeenSet(false)
{
}
MonotonicValues::MonotonicValues(JsonView jsonValue) :
m_status(StatisticalIssueStatus::NOT_SET),
m_statusHasBeenSet(false),
m_monotonicity(Monotonicity::NOT_SET),
m_monotonicityHasBeenSet(false)
{
*this = jsonValue;
}
MonotonicValues& MonotonicValues::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Status"))
{
m_status = StatisticalIssueStatusMapper::GetStatisticalIssueStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("Monotonicity"))
{
m_monotonicity = MonotonicityMapper::GetMonotonicityForName(jsonValue.GetString("Monotonicity"));
m_monotonicityHasBeenSet = true;
}
return *this;
}
JsonValue MonotonicValues::Jsonize() const
{
JsonValue payload;
if(m_statusHasBeenSet)
{
payload.WithString("Status", StatisticalIssueStatusMapper::GetNameForStatisticalIssueStatus(m_status));
}
if(m_monotonicityHasBeenSet)
{
payload.WithString("Monotonicity", MonotonicityMapper::GetNameForMonotonicity(m_monotonicity));
}
return payload;
}
} // namespace Model
} // namespace LookoutEquipment
} // namespace Aws
| 22.324675 | 109 | 0.757999 | [
"model"
] |
78e2ed48918994f1be7f138d1d8207a45648abec | 1,457 | cpp | C++ | codeforces/C - Bargain/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/C - Bargain/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/C - Bargain/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: * kzvd4729 created: Oct/04/2020 22:42
* solution_verdict: Accepted language: GNU C++14
* run_time: 46 ms memory_used: 8100 KB
* problem: https://codeforces.com/contest/1422/problem/C
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
#include<chrono>
#include<stack>
#include<deque>
#include<random>
#define long long long
using namespace std;
const int N=1e6,mod=1e9+7;
int pw[N+2],ad[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
string s;cin>>s;int n=s.size();
pw[0]=1,ad[0]=1;
for(int i=1;i<=n;i++)
{
pw[i]=(pw[i-1]*10LL)%mod;
ad[i]=(ad[i-1]+pw[i])%mod;
}
int ans=0,nm=0;
for(int i=1;i<n;i++)
{
nm=(nm*10LL+s[i-1]-'0')%mod;
ans=(ans+1LL*nm*ad[n-i-1])%mod;
}
nm=0;
for(int i=n-2;i>=0;i--)
{
nm=(nm+1LL*(s[i+1]-'0')*pw[n-2-i])%mod;
ans=(ans+1LL*nm*(i+1))%mod;
}
cout<<ans<<endl;
return 0;
} | 27.490566 | 111 | 0.469458 | [
"vector"
] |
78f4b29a06dba39433737efce6a15cea9cec3f73 | 24,325 | cpp | C++ | IHHook/IHMenu.cpp | TinManTex/IHHook | c9b43d220c4f9f838956846fef4b4b3fc580bca3 | [
"MIT"
] | 5 | 2020-05-30T20:12:13.000Z | 2021-06-09T11:38:47.000Z | IHHook/IHMenu.cpp | ZipfsLaw/IHHook | c9b43d220c4f9f838956846fef4b4b3fc580bca3 | [
"MIT"
] | 1 | 2021-11-29T20:36:04.000Z | 2021-11-29T20:36:56.000Z | IHHook/IHMenu.cpp | ZipfsLaw/IHHook | c9b43d220c4f9f838956846fef4b4b3fc580bca3 | [
"MIT"
] | 8 | 2020-05-30T20:13:09.000Z | 2021-12-14T15:01:51.000Z | #include <string>
#include <vector>
#include <map>
#include <imgui/imgui.h>
#include "spdlog/spdlog.h"
#include <queue>
#include "Util.h"
#include "IHHook.h"//SetDrawUI
#include "IHMenu.h"
namespace IHHook {
namespace IHMenu {
std::string modTitle = "IH";
std::string titleHelp = "[F3] Menu, [F2] Cursor";
//tex would like to keep it const char* all the way through from lua to imgui instead of back and forthing bewtween char* and string, but imgui shits the bed at some point when I try that
//try converting just menuItems to see
std::string windowTitle{ "windowTitle" };
std::string menuTitle{ "menuTitle" };
int selectedItem = 0;
int prevSelectedItem = 0;
int maxStrLength = 0;//tex length of longest string in menuItems
std::vector<std::string> menuItems{
"1:Menu line test = 1:SomeSetting",
"2:Menu line test = 1:SomeSetting",
"3:Menu line test = 1:SomeSetting",
"4:Menu line test = 1:SomeSetting",
"5:Menu line test = 1:SomeSetting",
};
std::string menuLine{ "1:Menu line test:" };
int selectedSetting = 0;
std::vector<std::string> menuSettings{
"1:SomeSetting",
"2:SomeSetting",
"3:SomeSetting",
"4:SomeSetting",
};
std::string menuHelp = "Some super long textand stuff that might describeand option.Yet more text letst see how this wraps.Some super long textand stuff that might describeand option.Yet more text letst see how this wraps.And more.Some super long textand stuff that might describeand option.Yet more text letst see how this wraps.How much more.Some super long textand stuff that might describeand option.Yet more text lets see how this wraps.So much more.Some super long textand stuff that might describeand option.Yet more text letst see how this wraps.";
const int bufferSize = 1024;
char inputBuffer[bufferSize] = "";
char settingInputBuffer[bufferSize] = "";
void DrawList(float contentHeight, int helpHeightInItems);
bool TextInputComboBox(const char* id, char* buffer, size_t maxInputSize, std::vector<std::string> items, short showMaxItems);
//IH/Lua > IHMenu
//DEBUGNOW tex: this is pretty trash, it's really just getting the IHExt api (which was also trash but atleas more flexible so since pushing through WPF) satisfied with the least fuss.
//If IHHook and D3D hook turns out to be robust enough for users then IHExt can be ditched and this should be overhauled along with the IH side where it pushes menu or imgui specific stuff and leaves ExtCmd/Pipe stuff for other purposes
void SetContent(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
std::string content = args[3];
if (name == "menuTitle") {
menuTitle = content;
}
}//SetContent
void SetText(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
std::string content = args[3];
if (name == "menuHelp") {
menuHelp = content;
}
}//SetText
void SetTextBox(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
std::string content = args[3];
if (name == "menuLine") {
menuLine = content;
strcpy(inputBuffer, menuLine.c_str());//DEBUGNOW
}
}//SetTextBox
//args: string name, bool visible
void UiElementVisible(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
int visible = std::stoi(args[3]);
if (name == "menuHelp") {
if (visible == 0) {
menuHelp = "";
}
else {
}
}
//DEBUGNOW dont like this
else if (name == "menuTitle") {
if (visible == 1) {
g_ihhook->SetDrawUI(true);
//DEBUGNOW g_ihhook->SetCursor(true);//tex now handled by ivars.menu_enableCursorOnMenuOpen
}
else {
g_ihhook->SetDrawUI(false);
g_ihhook->SetCursor(false);
}
}
}//UiElementVisible
void ClearTable(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 1) {
return;
}
std::string name = args[2];
if (name == "menuItems") {
menuItems.clear();
maxStrLength = 0;
}
}//ClearTable
void AddToTable(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
std::string itemString = args[3];
if (name == "menuItems") {
menuItems.push_back(itemString);
if (itemString.length() > maxStrLength) {
maxStrLength = (int)itemString.length();
}
}
}//AddToTable
//args: string name, int itemIndex, string itemString
void UpdateTable(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 3) {
return;
}
std::string name = args[2];
int itemIndex = std::stoi(args[3]);
std::string itemString = args[4];
if (name == "menuItems") {
if (itemIndex >= 0 && itemIndex < menuItems.size()) {
menuItems[itemIndex] = itemString;
}
}
}//UpdateTable
//args: string name, int itemIndex
void SelectItem(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
int itemIndex = std::stoi(args[3]);
if (name == "menuItems") {
if (itemIndex >= 0 && itemIndex < menuItems.size()) {
selectedItem = itemIndex;
}
else {
spdlog::warn("IHMenu.SelectItem: itemIndex {} out of bounds: {}",itemIndex, menuItems.size());
}
}
}//SelectItem
void ClearCombo(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 1) {
return;
}
std::string name = args[2];
if (name == "menuSetting") {
menuSettings.clear();
settingInputBuffer[0] = '\0';
}
}//ClearCombo
void AddToCombo(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
std::string itemString = args[3];
if (name == "menuSetting") {
menuSettings.push_back(itemString);
if (menuSettings.size() == 1) {
strcpy(settingInputBuffer, menuSettings[0].c_str());
}
}
}//AddToCombo
void SelectCombo(std::vector<std::string> args) {
//spdlog::trace(__func__);
if (args.size() < 1 + 2) {
return;
}
std::string name = args[2];
int selectedIndex = std::stoi(args[3]);
if (name == "menuSetting") {
if (selectedIndex >= 0 && selectedIndex < menuSettings.size()) {
selectedSetting = selectedIndex;
strcpy_s(settingInputBuffer, bufferSize, menuSettings[selectedSetting].c_str());//DEBUGNOW
}
else {
spdlog::warn("IHMenu.SelectCombo: itemIndex {} out of bounds: {}", selectedIndex, menuSettings.size());
}
}
}//SelectCombo
void ToggleStyleEditor(std::vector<std::string> args) {
g_ihhook->ToggleStyleEditor();
}//ToggleStyleEditor
void ToggleImguiDemo(std::vector<std::string> args) {
g_ihhook->ToggleImguiDemo();
}//ToggleImguiDemo
void EnableCursor(std::vector<std::string> args) {
g_ihhook->SetCursor(true);
}//EnableCursor
typedef void(*MenuCommandFunc) (std::vector<std::string> args);
std::map<std::string, MenuCommandFunc> menuCommands;
void AddMenuCommands() {
menuCommands["SetContent"] = SetContent;
menuCommands["SetText"] = SetText;
menuCommands["SetTextBox"] = SetTextBox;
menuCommands["UiElementVisible"] = UiElementVisible;
menuCommands["ClearTable"] = ClearTable;
menuCommands["AddToTable"] = AddToTable;
menuCommands["UpdateTable"] = UpdateTable;
menuCommands["SelectItem"] = SelectItem;
menuCommands["ClearCombo"] = ClearCombo;
menuCommands["AddToCombo"] = AddToCombo;
menuCommands["SelectCombo"] = SelectCombo;
menuCommands["ToggleStyleEditor"] = ToggleStyleEditor;
menuCommands["ToggleImguiDemo"] = ToggleImguiDemo;
menuCommands["EnableCursor"] = EnableCursor;
//SelectAllText
}//AddMenuCommands
//DEBUGNOW
void MenuMessage(std::string message) {
//spdlog::trace(__func__);
std::vector<std::string> args = split(message, "|");
std::string cmd = args[1];
if (menuCommands.count(cmd) == 0) {
spdlog::warn("MenuMessage: Could not find menuCommand {}", cmd);
return;
}
MenuCommandFunc MenuCommand = menuCommands[cmd];
MenuCommand(args);
}//MenuMessage
void ProcessMessages() {
//tex process messagesOut (lua > ihmenu commands) on this thread DEBUGNOW
std::optional <std::string> messageOpt = messagesOut.pop();//tex waits if empty
while (messageOpt) {
std::string message = *messageOpt;
MenuMessage(message);
messageOpt = messagesOut.pop();
}
}//ProcessMessages
//< IH/Lua > IHMenu
//IHMenu > IH/Lua
//tex: needs to be thread safe since game/lua is different thread than IHMenu (which is on d3d present)
//DEBUGNOW TODO rename to menuMessagesIn to differentiate from pipe?
SafeQueue<std::string> messagesIn;
SafeQueue<std::string> messagesOut;
//tex lua > ihmenu (via l_MenuMessage)
void QueueMessageOut(std::string message) {
messagesOut.push(message);
}//QueueMessageOut
//tex ihmenu > lua (via l_GetMenuMessages)
void QueueMessageIn(std::string message) {
spdlog::trace("QueueMessageIn: " + message);
messagesIn.push(message);
}//QueueMessageIn
//CALLER: FramInitialize firstFrame
void SetInitialText() {
windowTitle = "Infinite Heaven";
menuTitle = std::string("IHHook r") + std::to_string(Version);
menuItems.clear();
//menuItems.push_back(std::string("IHHook r") + std::to_string(Version));
menuItems.push_back("This window should close shortly");
menuItems.push_back("If it doesn't there may");
menuItems.push_back("be an issue with IH");
menuItems.push_back("If IH is not installed then");
menuItems.push_back("delete MGS_TPP\\dinput8.dll");
menuItems.push_back("to remove IHHook");
menuItems.push_back("");
if (errorMessages.size() > 0) {
for each (std::string message in errorMessages) {
menuItems.push_back(message);
}
}
menuLine = "";
menuSettings.clear();
menuHelp = "";
}//SetInitialText
void DrawMenu(bool* p_open, bool openPrev) {
ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_::ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(300, 500), ImGuiCond_::ImGuiCond_FirstUseEver);
ImGuiIO& io = ImGui::GetIO();
io.ConfigWindowsMoveFromTitleBarOnly = true;
ImGuiWindowFlags windowFlags = 0;
//windowFlags |= ImGuiWindowFlags_AlwaysAutoResize;
//windowFlags |= ImGuiWindowFlags_NoSavedSettings;
windowFlags |= ImGuiWindowFlags_NoScrollbar;
windowFlags |= ImGuiWindowFlags_NoScrollWithMouse;
if (ihVersion != 0) {
windowTitle = modTitle + " r" + std::to_string(ihVersion) + " : " + titleHelp;
}
//tex: GOTCHA name acts as id by default so setting it to something dynamic like menuTitle means each submenu is a new window so it will have individual position and size if user changes it.
//Alternative is to menuTitle + "##menuTitle"? or pushID, popID
//if (!
ImGui::Begin(windowTitle.c_str(), p_open, windowFlags); //tex: TODO: there's probably a better way to handle the x/close button somehow rather than this which just flips a bool
//QueueMessageIn("togglemenu|1");
//}
ImGui::Text(menuTitle.c_str());
ImGui::PushItemWidth(-1);//tex push out label
ImVec2 vMin = ImGui::GetWindowContentRegionMin();
ImVec2 vMax = ImGui::GetWindowContentRegionMax();
float contentHeight = vMax.y - vMin.y;
//DEBUG draw content bounds
//{
// ImVec2 drawMin = vMin;
// ImVec2 drawMax = vMax;
// vMin.x += ImGui::GetWindowPos().x;
// vMin.y += ImGui::GetWindowPos().y;
// vMax.x += ImGui::GetWindowPos().x;
// vMax.y += ImGui::GetWindowPos().y;
// ImGui::GetForegroundDrawList()->AddRect(vMin, vMax, IM_COL32(255, 255, 0, 255));
//}
int helpHeightInItems = 4;
if (menuHelp == "") {//tex: 'turning off help' simply sets an empty string
helpHeightInItems = 1;//tex leave a lines worth of buffer otherwise the window drag corner icon clashes visually with the combo box
}
if (menuItems.size() > 0) {
DrawList(contentHeight, helpHeightInItems);
}//if menuItems
ImGuiInputTextFlags inputFlags = 0;
inputFlags |= ImGuiInputTextFlags_EnterReturnsTrue;
inputFlags |= ImGuiInputTextFlags_AutoSelectAll;
if (ImGui::InputText("##menuLine", inputBuffer, IM_ARRAYSIZE(inputBuffer), inputFlags)) {
menuLine = inputBuffer;
QueueMessageIn("EnterText|menuLine|" + menuLine);
}
//ImGui::Text(inputBuffer); //DEBUG
//CULL
///*if (menuSettings.size() == 0) {
// //DEBUGNOW CULL ImGui::Text("");
// ImGui::Selectable("menuSettingsDummy", false, 0);
//} else*/ if (menuSettings.size() == 1) {//tex just a value
// ImGuiInputTextFlags settingInputFlags = 0;
// settingInputFlags |= ImGuiInputTextFlags_EnterReturnsTrue;
// if (ImGui::InputText("##menuSettingInput", settingInputBuffer, IM_ARRAYSIZE(settingInputBuffer), settingInputFlags)) {
// if (menuSettings.size() == 1) {
// menuSettings[0] = settingInputBuffer;
// QueueMessageIn("input|menuSetting|" + menuSettings[0]);
// }
// }
//} else {//tex use combo box
// const char* comboLabel = "";// Label to preview before opening the combo (technically it could be anything)
// if (menuSettings.size() > 0 && selectedSetting < menuSettings.size()) {
// comboLabel = menuSettings[selectedSetting].c_str();
// }
// static ImGuiComboFlags flags = 0;
// if (ImGui::BeginCombo("##menuSettings", comboLabel, flags)) {
// for (int i = 0; i < menuSettings.size(); i++) {
// ImGui::PushID(i);
// bool selected = (selectedSetting == i);
// if (ImGui::Selectable(menuSettings[i].c_str(), selected)) {
// selectedSetting = i;
// QueueMessageIn("selectedcombo|menuSetting|" + std::to_string(selectedSetting));
// }
// // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
// if (selected) {
// //DEBUGNOW ImGui::SetItemDefaultFocus();
// }
// ImGui::PopID();
// }
// ImGui::EndCombo();
// }//if Combo
//}//menuSetting
//DEBUGNOW
int maxItemsShown = 7;//0 == show all, but you don't get a scroll bar so it's unusable and will be off screen for large lists anyhoo
if (TextInputComboBox("##menuSettings", settingInputBuffer, bufferSize, menuSettings, maxItemsShown)) {
if (menuSettings.size() == 1) {
menuSettings[0] = settingInputBuffer;
QueueMessageIn("input|menuSetting|" + menuSettings[0]);
}
else {
bool didSelect = false;
for (int i = 0; i < menuSettings.size(); i++) {
if (menuSettings[i].compare(settingInputBuffer) == 0) {//tex settingInputBuffer matches a setting
selectedSetting = i;
didSelect = true;
QueueMessageIn("selectedcombo|menuSetting|" + std::to_string(selectedSetting));
break;
}
}
if (!didSelect) {
QueueMessageIn("input|menuSetting|" + std::string(settingInputBuffer));
}
}//if menuSettings.size
}//if TextInputComboBox
ImGui::BeginChild("ChildHelp", ImVec2(0, ImGui::GetFontSize() * helpHeightInItems), false, 0);
ImGui::TextWrapped("%s", menuHelp.c_str());//tex WORKAROUND: Text widget takes fmted text, so slap it in like this so it doesn't choke on stuff like %, there's also ::TextUnformatted that's more performant, but it doesn't wrap.
ImGui::EndChild();
ImGui::End();
//ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(0, -1));//DEBUGNOW
}//DrawMenu
void DrawList(float contentHeight, int helpHeightInItems) {
//float numItemsF = (contentHeight * 0.50f)/ ImGui::GetFontSize();
float fontSize = ImGui::GetFontSize();
float padding = 4;//tex TODO: calculate from actual padding
float otherItems = 4;//tex menu title, setting name, setting value + 1 for a buffer
float numItemsF = (contentHeight / (fontSize + padding)) - (otherItems + helpHeightInItems);
int listboxHeightInItems = static_cast<int>(std::round(numItemsF));
//listboxHeightInItems = std::min(listboxHeightInItems, (int)menuItems.size());//tex still deciding whether size menu to its number of items (this line uncommented), or to fill menu to window (this line commented out), and what to do with the bottom of the window
if (listboxHeightInItems > 0) {
if (ImGui::ListBoxHeader("##menuItems", (int)menuItems.size(), listboxHeightInItems)) {
for (int i = 0; i < menuItems.size(); i++) {
ImGui::PushItemWidth(-1);//tex push out label
ImGui::PushID(i);//tex in theory shouldnt be a problem as menu items have a number prefixed
bool selected = (selectedItem == i);
//tex putting this before -v- means that ih/lua can set selectedItem (call SelectItem on keyboard scroll)
//and have this scroll the selection into the view, but let ImGui::Selectable //DEBUGNOW unless there's a loop with togamecmd 'selected' that calls SelectItem again?
if (selected && prevSelectedItem != selectedItem) {
prevSelectedItem = selectedItem;
float center_y_ratio = 0.15f;
if (listboxHeightInItems <= 2) {
center_y_ratio = 1.0f;
}
ImGui::SetScrollHereY(center_y_ratio);
}
if (ImGui::Selectable(menuItems[i].c_str(), selected, ImGuiSelectableFlags_AllowDoubleClick)) {
selectedItem = i;
prevSelectedItem = selectedItem;//tex to stop autoscroll from kicking off since we changed selectedItem
QueueMessageIn("selected|menuItems|" + std::to_string(selectedItem));
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) {
QueueMessageIn("activate|menuItems|" + std::to_string(selectedItem));
}
}
//tex set selected as focus otherwise if inputtext has focus on menu open it's annoying
//if (*p_open && *p_open != openPrev) {
//DEBUGNOW ImGui::SetItemDefaultFocus();
//DEBUGNOW ImGui::SetKeyboardFocusHere();
//}
ImGui::PopID();
}
ImGui::ListBoxFooter();
}//if ListBox
}//if listboxHeightInItems>0
}//DrawList
//TextInputComboBox https://github.com/ocornut/imgui/issues/2057
bool identical(const char* buf, const char* item) {
size_t buf_size = strlen(buf);
size_t item_size = strlen(item);
//Check if the item length is shorter or equal --> exclude
if (buf_size >= item_size) return false;
for (int i = 0; i < strlen(buf); ++i)
// set the current pos if matching or return the pos if not
if (buf[i] != item[i]) return false;
// Complete match
// and the item size is greater --> include
return true;
}//identical
int propose(ImGuiInputTextCallbackData* data) {
//tex TODO: needs a lot more work
//We don't want to "preselect" anything
if (strlen(data->Buf) == 0) return 0;
//Get our items back
std::vector<std::string>* items = static_cast<std::vector<std::string>*> (data->UserData);
//WORKAROUND: tex setting is a direct value, don't autocomplete cause its annoying
if (items->size() == 0 || items->size() == 1) {
return 0;
}
//We need to give the user a chance to remove wrong input
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Backspace))) {
//We delete the last char automatically, since it is what the user wants to delete, but only if there is something (selected/marked/hovered)
//FIXME: This worked fine, when not used as helper function
if (data->SelectionEnd != data->SelectionStart)
if (data->BufTextLen > 0) //...and the buffer isn't empty
if (data->CursorPos > 0) //...and the cursor not at pos 0
data->DeleteChars(data->CursorPos - 1, 1);
return 0;
}
//if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Delete))) return 0;
//tex TODO: will pretty much just override deletions
//only does exact match
for (int i = 0; i < items->size(); i++) {
if (identical(data->Buf, items->at(i).c_str())) {
const int cursor = data->CursorPos;
//Insert the first match
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, items->at(i).c_str());
//Reset the cursor position
data->CursorPos = cursor;
//Select the text, so the user can simply go on writing
data->SelectionStart = cursor;
data->SelectionEnd = data->BufTextLen;
break;
}
}
return 0;
}//propose
//DEBUGNOW figure this out and fold into main TextInputComboBox
//bool TextInputComboBox(const char* id, std::string& str, size_t maxInputSize, std::vector<std::string> items, short maxItemsShown) {
// if (str.size() > maxInputSize) { // too large for editing
// ImGui::Text(str.c_str());
// return false;
// }
// std::string buffer(str);
// buffer.resize(maxInputSize);
// bool changed = TextInputComboBox(id, &buffer[0], maxInputSize, items, maxItemsShown);
// // using string as char array
// if (changed) {
// auto i = buffer.find_first_of('\0');
// str = buffer.substr(0u, i);
// }
// return changed;
//}//TextInputComboBox
// Creates a ComboBox with free text input and completion proposals
// Pass your items via items
// maxItemsShown determines how many items are shown, when the dropdown is open; if 0 is passed the complete list will be shown; you will want normaly a value of 8
// tex adapted from https://github.com/ocornut/imgui/issues/2057 to be kinda ihmenu specific
bool TextInputComboBox(const char* id, char* buffer, size_t maxInputSize, std::vector<std::string> items, short showMaxItems) {
//Check if both strings matches
if (showMaxItems == 0)
showMaxItems = items.size();
if (showMaxItems > items.size()) {
showMaxItems = items.size();
}
ImGui::PushID(id);
//std::pair<const char**, size_t> pass(items, item_len); //We need to pass the array length as well//DEBUGNOW
ImGui::PushItemWidth(-ImGui::GetFrameHeight());//tex decrease size by Arrow button default size
ImGuiInputTextFlags inputFlags = 0;
inputFlags |= ImGuiInputTextFlags_EnterReturnsTrue;
inputFlags |= ImGuiInputTextFlags_CallbackAlways;
bool ret = ImGui::InputText("##in", buffer, maxInputSize, inputFlags, propose, static_cast<void*>(&items));
if (ret) {//DEBUGNOW
bool blurg = true;
}
ImGui::OpenPopupOnItemClick("combobox"); //Enable right-click
ImVec2 pos = ImGui::GetItemRectMin();
ImVec2 size = ImGui::GetItemRectSize();
ImGui::SameLine(0, 0);
if (ImGui::ArrowButton("##openCombo", ImGuiDir_Down)) {
ImGui::OpenPopup("combobox");
}
ImGui::OpenPopupOnItemClick("combobox"); //Enable right-click
if (items.size() > 0 && selectedSetting < items.size()) {
//strcpy_s(buffer, bufferSize, items[selectedSetting].c_str());//DEBUGNOW
}
float baseHeight = size.y;
pos.y += baseHeight;
size.x += ImGui::GetItemRectSize().x;
size.y += 8 + (baseHeight * (showMaxItems - 1));
//tex TODO: if bottom of popup below bottom of screen then have popup above input/selected line like vanilla comboboxes behaviour.
ImGuiIO& io = ImGui::GetIO();
float windowHeight = io.DisplaySize.y;
float bottom = pos.y + size.y;
if (bottom > windowHeight) {
pos.y -= baseHeight;//tex undo above
pos.y -= size.y;
}
ImGui::SetNextWindowPos(pos);
ImGui::SetNextWindowSize(size);
if (ImGui::BeginPopup("combobox", ImGuiWindowFlags_::ImGuiWindowFlags_NoMove)) {
//ImGui::Text("Select one item or type");
//ImGui::Separator();
for (int i = 0; i < items.size(); i++) {
ImGui::PushID(i);//tex in theory shouldnt be a problem as menu items have a number prefixed
bool selected = (selectedSetting == i);
if (ImGui::Selectable(items[i].c_str(), selected)) {
selectedSetting = i;//tex IHMenu
strcpy_s(buffer, bufferSize, items[selectedSetting].c_str());//DEBUGNOW
QueueMessageIn("selectedcombo|menuSetting|" + std::to_string(selectedSetting));//tex IHMenu
}
ImGui::PopID();
}
ImGui::EndPopup();
}
ImGui::PopID();
//label
//ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
//ImGui::Text(id);
return ret;
}//TextInputComboBox
////
}//namespace IHMenu
}//namespace IHHook | 35.510949 | 558 | 0.667544 | [
"vector"
] |
78f5cbb64e23abe94eadfe09471b01e6c58aa67f | 2,761 | cpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_transform_reduce.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_transform_reduce.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 1 | 2019-04-04T18:00:00.000Z | 2019-04-04T18:00:00.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_transform_reduce.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE TestTransformReduce
#include <boost/test/unit_test.hpp>
#include <boost/compute/lambda.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/functional.hpp>
#include <boost/compute/algorithm/transform_reduce.hpp>
#include <boost/compute/container/vector.hpp>
#include "context_setup.hpp"
namespace compute = boost::compute;
BOOST_AUTO_TEST_CASE(sum_abs_int_doctest)
{
using boost::compute::abs;
using boost::compute::plus;
int data[] = { 1, -2, -3, -4, 5 };
compute::vector<int> vec(data, data + 5, queue);
//! [sum_abs_int]
int sum = 0;
boost::compute::transform_reduce(
vec.begin(), vec.end(), &sum, abs<int>(), plus<int>(), queue
);
//! [sum_abs_int]
BOOST_CHECK_EQUAL(sum, 15);
}
BOOST_AUTO_TEST_CASE(multiply_vector_length)
{
float data[] = { 2.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 4.0f, 0.0f };
compute::vector<compute::float4_> vector(
reinterpret_cast<compute::float4_ *>(data),
reinterpret_cast<compute::float4_ *>(data) + 3,
queue
);
float product;
compute::transform_reduce(
vector.begin(),
vector.end(),
&product,
compute::length<compute::float4_>(),
compute::multiplies<float>(),
queue
);
BOOST_CHECK_CLOSE(product, 24.0f, 1e-4f);
}
BOOST_AUTO_TEST_CASE(mean_and_std_dev)
{
using compute::lambda::_1;
using compute::lambda::pow;
float data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
compute::vector<float> vector(data, data + 10, queue);
float sum;
compute::reduce(
vector.begin(),
vector.end(),
&sum,
compute::plus<float>(),
queue
);
float mean = sum / vector.size();
BOOST_CHECK_CLOSE(mean, 5.5f, 1e-4);
compute::transform_reduce(
vector.begin(),
vector.end(),
&sum,
pow(_1 - mean, 2),
compute::plus<float>(),
queue
);
float variance = sum / vector.size();
BOOST_CHECK_CLOSE(variance, 8.25f, 1e-4);
float std_dev = std::sqrt(variance);
BOOST_CHECK_CLOSE(std_dev, 2.8722813232690143, 1e-4);
}
BOOST_AUTO_TEST_SUITE_END()
| 27.068627 | 80 | 0.565375 | [
"vector"
] |
78f8904b409859a6136058bae5ab8e535efce8e2 | 307 | hpp | C++ | modules/engine/include/randar/Render/ModelCollection.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | 1 | 2016-11-12T02:43:29.000Z | 2016-11-12T02:43:29.000Z | modules/engine/include/randar/Render/ModelCollection.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | modules/engine/include/randar/Render/ModelCollection.hpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | #ifndef RANDAR_RENDER_MODEL_COLLECTION_HPP
#define RANDAR_RENDER_MODEL_COLLECTION_HPP
#include <vector>
#include <randar/Render/Model.hpp>
namespace randar
{
typedef std::vector<randar::Model*> ModelCollection;
}
#ifdef SWIG
%template(ModelCollection) std::vector<randar::Model*>;
#endif
#endif
| 18.058824 | 59 | 0.778502 | [
"render",
"vector",
"model"
] |
78fa5f0846f0cb21f1d98a102de78cbe98f729f9 | 36,954 | cxx | C++ | main/cui/source/dialogs/cuifmsearch.cxx | jimjag/openoffice | 74746a22d8cc22b031b00fcd106f4496bf936c77 | [
"Apache-2.0"
] | 1 | 2019-12-27T19:25:34.000Z | 2019-12-27T19:25:34.000Z | main/cui/source/dialogs/cuifmsearch.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 1 | 2019-11-25T03:08:58.000Z | 2019-11-25T03:08:58.000Z | main/cui/source/dialogs/cuifmsearch.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 6 | 2019-11-19T00:28:25.000Z | 2019-11-22T06:48:49.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cui.hxx"
#include <tools/debug.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/svapp.hxx>
#include <tools/shl.hxx>
#include <dialmgr.hxx>
#include <sfx2/tabdlg.hxx>
#include <osl/mutex.hxx>
#include <sfx2/app.hxx>
#include <cuires.hrc>
#include <svl/filerec.hxx>
#include <svx/fmsrccfg.hxx>
#include <svx/fmsrcimp.hxx>
#include "fmsearch.hrc"
#include "cuifmsearch.hxx"
#include <svx/srchdlg.hxx>
#include <svl/cjkoptions.hxx>
#include <com/sun/star/i18n/TransliterationModules.hpp>
#include <comphelper/processfactory.hxx>
#include <svx/svxdlg.hxx>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::i18n;
using namespace ::svxform;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::util;
#define MAX_HISTORY_ENTRIES 50
//------------------------------------------------------------------------
void FmSearchDialog::initCommon( const Reference< XResultSet >& _rxCursor )
{
// init the engine
DBG_ASSERT( m_pSearchEngine, "FmSearchDialog::initCommon: have no engine!" );
m_pSearchEngine->SetProgressHandler(LINK(this, FmSearchDialog, OnSearchProgress));
// some layout changes according to available CJK options
SvtCJKOptions aCJKOptions;
if (!aCJKOptions.IsJapaneseFindEnabled())
{
sal_Int32 nUpper = m_cbApprox.GetPosPixel().Y();
sal_Int32 nDifference = m_aSoundsLikeCJKSettings.GetPosPixel().Y() - nUpper;
// hide the options for the japanese search
Control* pFieldsToMove[] = { &m_flState, &m_ftRecordLabel, &m_ftRecord, &m_ftHint };
implMoveControls(pFieldsToMove, sizeof(pFieldsToMove)/sizeof(pFieldsToMove[0]), nDifference, &m_flOptions);
m_aSoundsLikeCJK.Hide();
m_aSoundsLikeCJKSettings.Hide();
}
if (!aCJKOptions.IsCJKFontEnabled())
{
m_aHalfFullFormsCJK.Hide();
// never ignore the width (ignoring is expensive) if the option is not available at all
// 04.12.2001 - 91973 - fs@openoffice.org
m_pSearchEngine->SetIgnoreWidthCJK( sal_False );
}
// some initial record texts
m_ftRecord.SetText( String::CreateFromInt32( _rxCursor->getRow() ) );
m_pbClose.SetHelpText(String());
}
//------------------------------------------------------------------------
FmSearchDialog::FmSearchDialog(Window* pParent, const UniString& sInitialText, const ::std::vector< String >& _rContexts, sal_Int16 nInitialContext,
const Link& lnkContextSupplier)
:ModalDialog(pParent, CUI_RES(RID_SVXDLG_SEARCHFORM))
,m_flSearchFor (this, CUI_RES(FL_SEARCHFOR))
,m_rbSearchForText (this, CUI_RES(RB_SEARCHFORTEXT))
,m_rbSearchForNull (this, CUI_RES(RB_SEARCHFORNULL))
,m_rbSearchForNotNull (this, CUI_RES(RB_SEARCHFORNOTNULL))
,m_cmbSearchText (this, CUI_RES(CMB_SEARCHTEXT))
,m_flWhere (this, CUI_RES(FL_WHERE))
,m_ftForm (this, CUI_RES(FT_FORM))
,m_lbForm (this, CUI_RES(LB_FORM))
,m_rbAllFields (this, CUI_RES(RB_ALLFIELDS))
,m_rbSingleField (this, CUI_RES(RB_SINGLEFIELD))
,m_lbField (this, CUI_RES(LB_FIELD))
,m_flOptions (this, CUI_RES(FL_OPTIONS))
,m_ftPosition (this, CUI_RES(FT_POSITION))
,m_lbPosition (this, CUI_RES(LB_POSITION))
,m_cbUseFormat (this, CUI_RES(CB_USEFORMATTER))
,m_cbCase (this, CUI_RES(CB_CASE))
,m_cbBackwards (this, CUI_RES(CB_BACKWARD))
,m_cbStartOver (this, CUI_RES(CB_STARTOVER))
,m_cbWildCard (this, CUI_RES(CB_WILDCARD))
,m_cbRegular (this, CUI_RES(CB_REGULAR))
,m_cbApprox (this, CUI_RES(CB_APPROX))
,m_pbApproxSettings (this, CUI_RES(PB_APPROXSETTINGS))
,m_aHalfFullFormsCJK (this, CUI_RES(CB_HALFFULLFORMS))
,m_aSoundsLikeCJK (this, CUI_RES(CB_SOUNDSLIKECJK))
,m_aSoundsLikeCJKSettings (this, CUI_RES(PB_SOUNDSLIKESETTINGS))
,m_flState (this, CUI_RES(FL_STATE))
,m_ftRecordLabel (this, CUI_RES(FT_RECORDLABEL))
,m_ftRecord (this, CUI_RES(FT_RECORD))
,m_ftHint (this, CUI_RES(FT_HINT))
,m_pbSearchAgain (this, CUI_RES(PB_SEARCH))
,m_pbClose (this, CUI_RES(1))
,m_pbHelp (this, CUI_RES(1))
,m_sSearch ( m_pbSearchAgain.GetText() )
,m_sCancel ( Button::GetStandardText( BUTTON_CANCEL ) )
,m_pPreSearchFocus( NULL )
,m_lnkContextSupplier(lnkContextSupplier)
,m_pConfig( NULL )
{
DBG_ASSERT(m_lnkContextSupplier.IsSet(), "FmSearchDialog::FmSearchDialog : have no ContextSupplier !");
// erst mal die Informationen fuer den initialen Kontext
FmSearchContext fmscInitial;
fmscInitial.nContext = nInitialContext;
m_lnkContextSupplier.Call(&fmscInitial);
DBG_ASSERT(fmscInitial.xCursor.is(), "FmSearchDialog::FmSearchDialog : invalid data supplied by ContextSupplier !");
DBG_ASSERT(fmscInitial.strUsedFields.GetTokenCount(';') == (xub_StrLen)fmscInitial.arrFields.size(),
"FmSearchDialog::FmSearchDialog : invalid data supplied by ContextSupplied !");
#if (OSL_DEBUG_LEVEL > 1) || defined DBG_UTIL
for (sal_Int32 i=0; i<(sal_Int32)fmscInitial.arrFields.size(); ++i)
DBG_ASSERT(fmscInitial.arrFields.at(i).is(), "FmSearchDialog::FmSearchDialog : invalid data supplied by ContextSupplier !");
#endif // (OSL_DEBUG_LEVEL > 1) || DBG_UTIL
for ( ::std::vector< String >::const_iterator context = _rContexts.begin();
context != _rContexts.end();
++context
)
{
m_arrContextFields.push_back(String());
m_lbForm.InsertEntry(*context);
}
m_lbForm.SelectEntryPos(nInitialContext);
m_lbForm.SetSelectHdl(LINK(this, FmSearchDialog, OnContextSelection));
if (m_arrContextFields.size() == 1)
{ // remove the context selection listbox and rearrange the controls accordingly
sal_Int32 nUpper = m_lbForm.GetPosPixel().Y();
sal_Int32 nDifference = m_rbAllFields.GetPosPixel().Y() - nUpper;
// move all controls below the affected ones up
Control* pFieldsToMove[] = { &m_rbAllFields, &m_rbSingleField, &m_lbField, &m_flOptions, &m_ftPosition, &m_lbPosition,
&m_cbUseFormat, &m_cbCase, &m_cbBackwards, &m_cbStartOver, &m_cbWildCard, &m_cbRegular, &m_cbApprox,
&m_pbApproxSettings, &m_aHalfFullFormsCJK, &m_aSoundsLikeCJK, &m_aSoundsLikeCJKSettings,
&m_flState, &m_ftRecordLabel, &m_ftRecord, &m_ftHint };
implMoveControls(pFieldsToMove, sizeof(pFieldsToMove)/sizeof(pFieldsToMove[0]), nDifference, &m_flWhere);
Point pt = m_rbAllFields.GetPosPixel();
pt.X() = m_ftForm.GetPosPixel().X();
m_rbAllFields.SetPosPixel( pt );
pt = m_rbSingleField.GetPosPixel();
pt.X() = m_ftForm.GetPosPixel().X();
m_rbSingleField.SetPosPixel( pt );
// hide dispensable controls
m_ftForm.Hide();
m_lbForm.Hide();
}
m_pSearchEngine = new FmSearchEngine(
::comphelper::getProcessServiceFactory(), fmscInitial.xCursor, fmscInitial.strUsedFields, fmscInitial.arrFields, SM_ALLOWSCHEDULE );
initCommon( fmscInitial.xCursor );
if (fmscInitial.sFieldDisplayNames.Len() != 0)
{ // use the display names if supplied
DBG_ASSERT(fmscInitial.sFieldDisplayNames.GetTokenCount() == fmscInitial.strUsedFields.GetTokenCount(),
"FmSearchDialog::FmSearchDialog : invalid initial context description !");
Init(fmscInitial.sFieldDisplayNames, sInitialText);
}
else
Init(fmscInitial.strUsedFields, sInitialText);
}
//------------------------------------------------------------------------
void FmSearchDialog::implMoveControls(
Control** _ppControls,
sal_Int32 _nControls,
sal_Int32 _nUp,
Control* /*_pToResize*/)
{
for (sal_Int32 i=0; i<_nControls; ++i)
{
Point pt = _ppControls[i]->GetPosPixel();
pt.Y() -= _nUp;
_ppControls[i]->SetPosPixel(pt);
}
// resize myself
Size sz = GetSizePixel();
sz.Height() -= _nUp;
SetSizePixel(sz);
}
//------------------------------------------------------------------------
FmSearchDialog::~FmSearchDialog()
{
if (m_aDelayedPaint.IsActive())
m_aDelayedPaint.Stop();
SaveParams();
if (m_pConfig)
{
delete m_pConfig;
m_pConfig = NULL;
}
delete m_pSearchEngine;
}
//------------------------------------------------------------------------
void FmSearchDialog::Init(const UniString& strVisibleFields, const UniString& sInitialText)
{
// die Initialisierung all der Controls
m_rbSearchForText.SetClickHdl(LINK(this, FmSearchDialog, OnClickedFieldRadios));
m_rbSearchForNull.SetClickHdl(LINK(this, FmSearchDialog, OnClickedFieldRadios));
m_rbSearchForNotNull.SetClickHdl(LINK(this, FmSearchDialog, OnClickedFieldRadios));
m_rbAllFields.SetClickHdl(LINK(this, FmSearchDialog, OnClickedFieldRadios));
m_rbSingleField.SetClickHdl(LINK(this, FmSearchDialog, OnClickedFieldRadios));
m_pbSearchAgain.SetClickHdl(LINK(this, FmSearchDialog, OnClickedSearchAgain));
m_pbApproxSettings.SetClickHdl(LINK(this, FmSearchDialog, OnClickedSpecialSettings));
m_aSoundsLikeCJKSettings.SetClickHdl(LINK(this, FmSearchDialog, OnClickedSpecialSettings));
m_lbPosition.SetSelectHdl(LINK(this, FmSearchDialog, OnPositionSelected));
m_lbField.SetSelectHdl(LINK(this, FmSearchDialog, OnFieldSelected));
m_cmbSearchText.SetModifyHdl(LINK(this, FmSearchDialog, OnSearchTextModified));
m_cmbSearchText.EnableAutocomplete(sal_False);
m_cmbSearchText.SetGetFocusHdl(LINK(this, FmSearchDialog, OnFocusGrabbed));
m_cbUseFormat.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_cbBackwards.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_cbStartOver.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_cbCase.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_cbWildCard.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_cbRegular.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_cbApprox.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_aHalfFullFormsCJK.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
m_aSoundsLikeCJK.SetToggleHdl(LINK(this, FmSearchDialog, OnCheckBoxToggled));
// die Listboxen fuellen
// die Methoden des Feldvergleiches
sal_uInt16 nResIds[] = {
RID_STR_SEARCH_ANYWHERE,
RID_STR_SEARCH_BEGINNING,
RID_STR_SEARCH_END,
RID_STR_SEARCH_WHOLE
};
for ( size_t i=0; i<sizeof(nResIds)/sizeof(nResIds[0]); ++i )
m_lbPosition.InsertEntry( String( CUI_RES( nResIds[i] ) ) );
m_lbPosition.SelectEntryPos(MATCHING_ANYWHERE);
// die Feld-Listbox
for (sal_uInt16 i=0; i<strVisibleFields.GetTokenCount(';'); ++i)
m_lbField.InsertEntry(strVisibleFields.GetToken(i, ';'));
m_pConfig = new FmSearchConfigItem;
LoadParams();
m_cmbSearchText.SetText(sInitialText);
// wenn die Edit-Zeile den Text veraendert hat (weil er zum Beispiel Steuerzeichen enthielt, wie das bei Memofeldern der Fall
// sein kann), nehme ich einen leeren UniString
UniString sRealSetText = m_cmbSearchText.GetText();
if (!sRealSetText.Equals(sInitialText))
m_cmbSearchText.SetText(UniString());
LINK(this, FmSearchDialog, OnSearchTextModified).Call(&m_cmbSearchText);
// initial die ganzen UI-Elemente fuer die Suche an
m_aDelayedPaint.SetTimeoutHdl(LINK(this, FmSearchDialog, OnDelayedPaint));
m_aDelayedPaint.SetTimeout(500);
EnableSearchUI(sal_True);
if ( m_rbSearchForText.IsChecked() )
m_cmbSearchText.GrabFocus();
FreeResource();
}
//------------------------------------------------------------------------
sal_Bool FmSearchDialog::Close()
{
// Wenn der Close-Button disabled ist und man im Dialog ESC drueckt, dann wird irgendwo vom Frame trotzdem Close aufgerufen,
// was ich allerdings nicht will, wenn ich gerade mitten in einer (eventuell in einem extra Thread laufenden) Suche bin
if (!m_pbClose.IsEnabled())
return sal_False;
return ModalDialog::Close();
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnClickedFieldRadios, Button*, pButton)
{
if ((pButton == &m_rbSearchForText) || (pButton == &m_rbSearchForNull) || (pButton == &m_rbSearchForNotNull))
{
EnableSearchForDependees(sal_True);
}
else
// die Feldlistbox entsprechend en- oder disablen
if (pButton == &m_rbSingleField)
{
m_lbField.Enable();
m_pSearchEngine->RebuildUsedFields(m_lbField.GetSelectEntryPos());
}
else
{
m_lbField.Disable();
m_pSearchEngine->RebuildUsedFields(-1);
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnClickedSearchAgain, Button*, EMPTYARG)
{
if (m_pbClose.IsEnabled())
{ // der Button hat die Funktion 'Suchen'
UniString strThisRoundText = m_cmbSearchText.GetText();
// zur History dazu
m_cmbSearchText.RemoveEntry(strThisRoundText);
m_cmbSearchText.InsertEntry(strThisRoundText, 0);
// das Remove/Insert stellt a) sicher, dass der UniString nicht zweimal auftaucht, b), dass die zuletzt gesuchten Strings am
// Anfang stehen
// und die Listenlaenge beschraenken
while (m_cmbSearchText.GetEntryCount() > MAX_HISTORY_ENTRIES)
m_cmbSearchText.RemoveEntry(m_cmbSearchText.GetEntryCount()-1);
// den 'Ueberlauf'-Hint rausnehmen
m_ftHint.SetText(UniString());
m_ftHint.Invalidate();
if (m_cbStartOver.IsChecked())
{
m_cbStartOver.Check(sal_False);
EnableSearchUI(sal_False);
if (m_rbSearchForText.IsChecked())
m_pSearchEngine->StartOver(strThisRoundText);
else
m_pSearchEngine->StartOverSpecial(m_rbSearchForNull.IsChecked());
}
else
{
EnableSearchUI(sal_False);
if (m_rbSearchForText.IsChecked())
m_pSearchEngine->SearchNext(strThisRoundText);
else
m_pSearchEngine->SearchNextSpecial(m_rbSearchForNull.IsChecked());
}
}
else
{ // der Button hat die Fukntion 'Abbrechen'
DBG_ASSERT(m_pSearchEngine->GetSearchMode() != SM_BRUTE, "FmSearchDialog, OnClickedSearchAgain : falscher Modus !");
// der CancelButton wird normalerweise nur disabled, wenn ich in einem Thread oder mit Reschedule arbeite
m_pSearchEngine->CancelSearch();
// mein ProgressHandler wird gerufen, wenn es wirklich zu Ende ist, das hier war nur eine Anforderung
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnClickedSpecialSettings, Button*, pButton )
{
if (&m_pbApproxSettings == pButton)
{
AbstractSvxSearchSimilarityDialog* pDlg = NULL;
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if ( pFact )
pDlg = pFact->CreateSvxSearchSimilarityDialog( this, m_pSearchEngine->GetLevRelaxed(), m_pSearchEngine->GetLevOther(),
m_pSearchEngine->GetLevShorter(), m_pSearchEngine->GetLevLonger() );
DBG_ASSERT( pDlg, "FmSearchDialog, OnClickedSpecialSettings: could not load the dialog!" );
if ( pDlg && pDlg->Execute() == RET_OK )
{
m_pSearchEngine->SetLevRelaxed( pDlg->IsRelaxed() );
m_pSearchEngine->SetLevOther( pDlg->GetOther() );
m_pSearchEngine->SetLevShorter(pDlg->GetShorter() );
m_pSearchEngine->SetLevLonger( pDlg->GetLonger() );
}
delete pDlg;
}
else if (&m_aSoundsLikeCJKSettings == pButton)
{
SfxItemSet aSet( SFX_APP()->GetPool() );
//CHINA001 SvxJSearchOptionsDialog aDlg( this, aSet, RID_SVXPAGE_JSEARCH_OPTIONS, m_pSearchEngine->GetTransliterationFlags() );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
if(pFact)
{
AbstractSvxJSearchOptionsDialog* aDlg = pFact->CreateSvxJSearchOptionsDialog( this, aSet, m_pSearchEngine->GetTransliterationFlags() );
DBG_ASSERT(aDlg, "Dialogdiet fail!");//CHINA001
aDlg->Execute(); //CHINA001 aDlg.Execute();
sal_Int32 nFlags = aDlg->GetTransliterationFlags(); //CHINA001 sal_Int32 nFlags = aDlg.GetTransliterationFlags();
m_pSearchEngine->SetTransliterationFlags(nFlags);
m_cbCase.Check(m_pSearchEngine->GetCaseSensitive());
OnCheckBoxToggled( &m_cbCase );
m_aHalfFullFormsCJK.Check( !m_pSearchEngine->GetIgnoreWidthCJK() );
OnCheckBoxToggled( &m_aHalfFullFormsCJK );
delete aDlg; //add for CHINA001
}
}
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnSearchTextModified, ComboBox*, EMPTYARG)
{
if ((m_cmbSearchText.GetText().Len() != 0) || !m_rbSearchForText.IsChecked())
m_pbSearchAgain.Enable();
else
m_pbSearchAgain.Disable();
m_pSearchEngine->InvalidatePreviousLoc();
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnFocusGrabbed, ComboBox*, EMPTYARG)
{
m_cmbSearchText.SetSelection( Selection( SELECTION_MIN, SELECTION_MAX ) );
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnPositionSelected, ListBox*, pBox)
{
(void) pBox; // avoid warning
DBG_ASSERT(pBox->GetSelectEntryCount() == 1, "FmSearchDialog::OnMethodSelected : unerwartet : nicht genau ein Eintrag selektiert !");
m_pSearchEngine->SetPosition(m_lbPosition.GetSelectEntryPos());
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnFieldSelected, ListBox*, pBox)
{
(void) pBox; // avoid warning
DBG_ASSERT(pBox->GetSelectEntryCount() == 1, "FmSearchDialog::OnFieldSelected : unerwartet : nicht genau ein Eintrag selektiert !");
m_pSearchEngine->RebuildUsedFields(m_rbAllFields.IsChecked() ? -1 : (sal_Int16)m_lbField.GetSelectEntryPos());
// ruft auch m_pSearchEngine->InvalidatePreviousLoc auf
sal_Int32 nCurrentContext = m_lbForm.GetSelectEntryPos();
if (nCurrentContext != LISTBOX_ENTRY_NOTFOUND)
m_arrContextFields[nCurrentContext] = UniString(m_lbField.GetSelectEntry());
return 0;
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnCheckBoxToggled, CheckBox*, pBox)
{
sal_Bool bChecked = pBox->IsChecked();
// Formatter oder case -> an die Engine weiterreichen
if (pBox == &m_cbUseFormat)
m_pSearchEngine->SetFormatterUsing(bChecked);
else if (pBox == &m_cbCase)
m_pSearchEngine->SetCaseSensitive(bChecked);
// Richtung -> weiterreichen und Checkbox-Text fuer StartOver neu setzen
else if (pBox == &m_cbBackwards)
{
m_cbStartOver.SetText( String( CUI_RES( bChecked ? RID_STR_FROM_BOTTOM : RID_STR_FROM_TOP ) ) );
m_pSearchEngine->SetDirection(!bChecked);
}
// Aehnlichkeitssuche oder regulaerer Ausdruck
else if ((pBox == &m_cbApprox) || (pBox == &m_cbRegular) || (pBox == &m_cbWildCard))
{
// die beiden jeweils anderen Boxes disablen oder enablen
CheckBox* pBoxes[] = { &m_cbWildCard, &m_cbRegular, &m_cbApprox };
for (sal_uInt32 i=0; i<sizeof(pBoxes)/sizeof(CheckBox*); ++i)
{
if (pBoxes[i] != pBox)
{
if (bChecked)
pBoxes[i]->Disable();
else
pBoxes[i]->Enable();
}
}
// an die Engine weiterreichen
m_pSearchEngine->SetWildcard(m_cbWildCard.IsEnabled() ? m_cbWildCard.IsChecked() : sal_False);
m_pSearchEngine->SetRegular(m_cbRegular.IsEnabled() ? m_cbRegular.IsChecked() : sal_False);
m_pSearchEngine->SetLevenshtein(m_cbApprox.IsEnabled() ? m_cbApprox.IsChecked() : sal_False);
// (Boxes, die disabled sind, muessen als sal_False an die Engine gehen)
// die Position-Listbox anpassen (ist bei Wildcard-Suche nicht erlaubt)
if (pBox == &m_cbWildCard)
{
if (bChecked)
{
m_ftPosition.Disable();
m_lbPosition.Disable();
}
else
{
m_ftPosition.Enable();
m_lbPosition.Enable();
}
}
// und den Button fuer die Aehnlichkeitssuche
if (pBox == &m_cbApprox)
{
if (bChecked)
m_pbApproxSettings.Enable();
else
m_pbApproxSettings.Disable();
}
}
else if (pBox == &m_aHalfFullFormsCJK)
{
// forward to the search engine
m_pSearchEngine->SetIgnoreWidthCJK( !bChecked );
}
else if (pBox == &m_aSoundsLikeCJK)
{
m_aSoundsLikeCJKSettings.Enable(bChecked);
// two other buttons which depend on this one
sal_Bool bEnable = ( m_rbSearchForText.IsChecked()
&& !m_aSoundsLikeCJK.IsChecked()
)
|| !SvtCJKOptions().IsJapaneseFindEnabled();
m_cbCase.Enable(bEnable);
m_aHalfFullFormsCJK.Enable(bEnable);
// forward to the search engine
m_pSearchEngine->SetTransliteration( bChecked );
}
return 0;
}
//------------------------------------------------------------------------
void FmSearchDialog::InitContext(sal_Int16 nContext)
{
FmSearchContext fmscContext;
fmscContext.nContext = nContext;
#ifdef DBG_UTIL
sal_uInt32 nResult =
#endif
m_lnkContextSupplier.Call(&fmscContext);
DBG_ASSERT(nResult > 0, "FmSearchDialog::InitContext : ContextSupplier didn't give me any controls !");
// packen wir zuerst die Feld-Namen in die entsprechende Listbox
m_lbField.Clear();
if (fmscContext.sFieldDisplayNames.Len() != 0)
{
// use the display names if supplied
DBG_ASSERT(fmscContext.sFieldDisplayNames.GetTokenCount() == fmscContext.strUsedFields.GetTokenCount(),
"FmSearchDialog::InitContext : invalid context description supplied !");
for (xub_StrLen i=0; i<fmscContext.sFieldDisplayNames.GetTokenCount(); ++i)
m_lbField.InsertEntry(fmscContext.sFieldDisplayNames.GetToken(i));
}
else
// else use the field names
for (xub_StrLen i=0; i<fmscContext.strUsedFields.GetTokenCount(); ++i)
m_lbField.InsertEntry(fmscContext.strUsedFields.GetToken(i));
if (nContext < (sal_Int32)m_arrContextFields.size() && m_arrContextFields[nContext].Len())
{
m_lbField.SelectEntry(m_arrContextFields[nContext]);
}
else
{
m_lbField.SelectEntryPos(0);
if (m_rbSingleField.IsChecked() && (m_lbField.GetEntryCount() > 1))
m_lbField.GrabFocus();
}
// dann geben wir der Engine Bescheid
m_pSearchEngine->SwitchToContext(fmscContext.xCursor, fmscContext.strUsedFields, fmscContext.arrFields,
m_rbAllFields.IsChecked() ? -1 : 0);
// und die Position des neuen Cursors anzeigen
m_ftRecord.SetText(String::CreateFromInt32(fmscContext.xCursor->getRow()));
}
//------------------------------------------------------------------------
IMPL_LINK( FmSearchDialog, OnContextSelection, ListBox*, pBox)
{
InitContext(pBox->GetSelectEntryPos());
return 0L;
}
//------------------------------------------------------------------------
void FmSearchDialog::EnableSearchUI(sal_Bool bEnable)
{
// wenn die Controls disabled werden sollen, schalte ich mal eben kurz ihr Paint aus und verzoegert wieder an
if (!bEnable)
EnableControlPaint(sal_False);
else
{ // beim Enablen teste ich, ob der Timer fuer das delayed paint aktiv ist und stoppe ihn wenn noetig
if (m_aDelayedPaint.IsActive())
m_aDelayedPaint.Stop();
}
// (das ganze geht unten noch weiter)
// diese kleine Verrenkung fuehrt hoffentlich dazu, dass es nicht flackert, wenn man die SearchUI schnell hintereinander
// aus- und wieder einschaltet (wie das bei einem kurzen Suchvorgang zwangslaeufig der Fall ist)
if ( !bEnable )
{
// if one of my children has the focus, remember it
// 104332 - 2002-10-17 - fs@openoffice.org
Window* pFocusWindow = Application::GetFocusWindow( );
if ( pFocusWindow && IsChild( pFocusWindow ) )
m_pPreSearchFocus = pFocusWindow;
else
m_pPreSearchFocus = NULL;
}
// der Suchen-Button hat einen Doppelfunktion, seinen Text entsprechend anpassen
String sButtonText( bEnable ? m_sSearch : m_sCancel );
m_pbSearchAgain.SetText( sButtonText );
// jetzt Controls en- oder disablen
if (m_pSearchEngine->GetSearchMode() != SM_BRUTE)
{
m_flSearchFor.Enable (bEnable);
m_rbSearchForText.Enable (bEnable);
m_rbSearchForNull.Enable (bEnable);
m_rbSearchForNotNull.Enable (bEnable);
m_flWhere.Enable (bEnable);
m_ftForm.Enable (bEnable);
m_lbForm.Enable (bEnable);
m_rbAllFields.Enable (bEnable);
m_rbSingleField.Enable (bEnable);
m_lbField.Enable (bEnable && m_rbSingleField.IsChecked());
m_flOptions.Enable (bEnable);
m_cbBackwards.Enable (bEnable);
m_cbStartOver.Enable (bEnable);
m_pbClose.Enable (bEnable);
EnableSearchForDependees (bEnable);
if ( !bEnable )
{ // this means we're preparing for starting a search
// In this case, EnableSearchForDependees disabled the search button
// But as we're about to use it for cancelling the search, we really need to enable it, again
// 07.12.2001 - 95246 - fs@openoffice.org
m_pbSearchAgain.Enable( sal_True );
}
}
// und den Rest fuer das delayed paint
if (!bEnable)
m_aDelayedPaint.Start();
else
EnableControlPaint(sal_True);
if ( bEnable )
{ // restore focus
// 104332 - 2002-10-17 - fs@openoffice.org
if ( m_pPreSearchFocus )
{
m_pPreSearchFocus->GrabFocus();
if ( WINDOW_EDIT == m_pPreSearchFocus->GetType() )
{
Edit* pEdit = static_cast< Edit* >( m_pPreSearchFocus );
pEdit->SetSelection( Selection( 0, pEdit->GetText().Len() ) );
}
}
m_pPreSearchFocus = NULL;
}
}
//------------------------------------------------------------------------
void FmSearchDialog::EnableSearchForDependees(sal_Bool bEnable)
{
sal_Bool bSearchingForText = m_rbSearchForText.IsChecked();
m_pbSearchAgain.Enable(bEnable && (!bSearchingForText || (m_cmbSearchText.GetText().Len() != 0)));
bEnable = bEnable && bSearchingForText;
sal_Bool bEnableRedundants = !m_aSoundsLikeCJK.IsChecked() || !SvtCJKOptions().IsJapaneseFindEnabled();
m_cmbSearchText.Enable (bEnable);
m_ftPosition.Enable (bEnable && !m_cbWildCard.IsChecked());
m_cbWildCard.Enable (bEnable && !m_cbRegular.IsChecked() && !m_cbApprox.IsChecked());
m_cbRegular.Enable (bEnable && !m_cbWildCard.IsChecked() && !m_cbApprox.IsChecked());
m_cbApprox.Enable (bEnable && !m_cbWildCard.IsChecked() && !m_cbRegular.IsChecked());
m_pbApproxSettings.Enable (bEnable && m_cbApprox.IsChecked());
m_aHalfFullFormsCJK.Enable (bEnable && bEnableRedundants);
m_aSoundsLikeCJK.Enable (bEnable);
m_aSoundsLikeCJKSettings.Enable (bEnable && m_aSoundsLikeCJK.IsChecked());
m_lbPosition.Enable (bEnable && !m_cbWildCard.IsChecked());
m_cbUseFormat.Enable (bEnable);
m_cbCase.Enable (bEnable && bEnableRedundants);
}
//------------------------------------------------------------------------
void FmSearchDialog::EnableControlPaint(sal_Bool bEnable)
{
Control* pAffectedControls[] = { &m_flSearchFor, &m_rbSearchForText, &m_cmbSearchText, &m_rbSearchForNull, &m_rbSearchForNotNull,
&m_rbSearchForText, &m_flWhere, &m_rbAllFields, &m_rbSingleField, &m_lbField, &m_flOptions, &m_ftPosition, &m_lbPosition,
&m_cbUseFormat, &m_cbCase, &m_cbBackwards, &m_cbStartOver, &m_cbWildCard, &m_cbRegular, &m_cbApprox, &m_pbApproxSettings,
&m_pbSearchAgain, &m_pbClose };
if (!bEnable)
for (sal_uInt32 i=0; i<sizeof(pAffectedControls)/sizeof(pAffectedControls[0]); ++i)
{
pAffectedControls[i]->SetUpdateMode(bEnable);
pAffectedControls[i]->EnablePaint(bEnable);
}
else
for (sal_uInt32 i=0; i<sizeof(pAffectedControls)/sizeof(pAffectedControls[0]); ++i)
{
pAffectedControls[i]->EnablePaint(bEnable);
pAffectedControls[i]->SetUpdateMode(bEnable);
}
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnDelayedPaint, void*, EMPTYARG)
{
EnableControlPaint(sal_True);
return 0L;
}
//------------------------------------------------------------------------
void FmSearchDialog::OnFound(const ::com::sun::star::uno::Any& aCursorPos, sal_Int16 nFieldPos)
{
FmFoundRecordInformation friInfo;
friInfo.nContext = m_lbForm.GetSelectEntryPos();
// wenn ich keine Suche in Kontexten mache, steht hier was ungueltiges drin, aber dann ist es auch egal
friInfo.aPosition = aCursorPos;
if (m_rbAllFields.IsChecked())
friInfo.nFieldPos = nFieldPos;
else
friInfo.nFieldPos = m_lbField.GetSelectEntryPos();
// das setzt natuerlich voraus, dass ich wirklich in dem Feld gesucht habe, dass in der Listbox ausgewaehlt ist,
// genau das wird auch in RebuildUsedFields sichergestellt
// dem Handler Bescheid sagen
m_lnkFoundHandler.Call(&friInfo);
// und wieder Focus auf mich
m_cmbSearchText.GrabFocus();
}
//------------------------------------------------------------------------
IMPL_LINK(FmSearchDialog, OnSearchProgress, FmSearchProgress*, pProgress)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
// diese eine Methode Thread-sicher machen (das ist ein Overkill, die ganze restliche Applikation dafuer zu blockieren,
// aber im Augenblick haben wir kein anderes Sicherheitskonpzept)
switch (pProgress->aSearchState)
{
case FmSearchProgress::STATE_PROGRESS:
if (pProgress->bOverflow)
{
String sHint( CUI_RES( m_cbBackwards.IsChecked() ? RID_STR_OVERFLOW_BACKWARD : RID_STR_OVERFLOW_FORWARD ) );
m_ftHint.SetText( sHint );
m_ftHint.Invalidate();
}
m_ftRecord.SetText(String::CreateFromInt32(1 + pProgress->nCurrentRecord));
m_ftRecord.Invalidate();
break;
case FmSearchProgress::STATE_PROGRESS_COUNTING:
m_ftHint.SetText(CUI_RESSTR(RID_STR_SEARCH_COUNTING));
m_ftHint.Invalidate();
m_ftRecord.SetText(String::CreateFromInt32(pProgress->nCurrentRecord));
m_ftRecord.Invalidate();
break;
case FmSearchProgress::STATE_SUCCESSFULL:
OnFound(pProgress->aBookmark, (sal_Int16)pProgress->nFieldIndex);
EnableSearchUI(sal_True);
break;
case FmSearchProgress::STATE_ERROR:
case FmSearchProgress::STATE_NOTHINGFOUND:
{
sal_uInt16 nErrorId = (FmSearchProgress::STATE_ERROR == pProgress->aSearchState)
? RID_SVXERR_SEARCH_GENERAL_ERROR
: RID_SVXERR_SEARCH_NORECORD;
ErrorBox(this, CUI_RES(nErrorId)).Execute();
}
// KEIN break !
case FmSearchProgress::STATE_CANCELED:
EnableSearchUI(sal_True);
if (m_lnkCanceledNotFoundHdl.IsSet())
{
FmFoundRecordInformation friInfo;
friInfo.nContext = m_lbForm.GetSelectEntryPos();
// wenn ich keine Suche in Kontexten mache, steht hier was ungueltiges drin, aber dann ist es auch egal
friInfo.aPosition = pProgress->aBookmark;
m_lnkCanceledNotFoundHdl.Call(&friInfo);
}
break;
}
m_ftRecord.SetText(String::CreateFromInt32(1 + pProgress->nCurrentRecord));
return 0L;
}
//------------------------------------------------------------------------
void FmSearchDialog::LoadParams()
{
FmSearchParams aParams(m_pConfig->getParams());
const ::rtl::OUString* pHistory = aParams.aHistory.getConstArray();
const ::rtl::OUString* pHistoryEnd = pHistory + aParams.aHistory.getLength();
for (; pHistory != pHistoryEnd; ++pHistory)
m_cmbSearchText.InsertEntry( *pHistory );
// die Einstellungen nehme ich an meinen UI-Elementen vor und rufe dann einfach den entsprechenden Change-Handler auf,
// dadurch werden die Daten an die SearchEngine weitergereicht und alle abhaengigen Enstellungen vorgenommen
// aktuelles Feld
sal_uInt16 nInitialField = m_lbField.GetEntryPos( String( aParams.sSingleSearchField ) );
if (nInitialField == COMBOBOX_ENTRY_NOTFOUND)
nInitialField = 0;
m_lbField.SelectEntryPos(nInitialField);
LINK(this, FmSearchDialog, OnFieldSelected).Call(&m_lbField);
// alle/einzelnes Feld (NACH dem Selektieren des Feldes, da OnClickedFieldRadios dort einen gueltigen Eintrag erwartet)
if (aParams.bAllFields)
{
m_rbSingleField.Check(sal_False);
m_rbAllFields.Check(sal_True);
LINK(this, FmSearchDialog, OnClickedFieldRadios).Call(&m_rbAllFields);
// OnClickedFieldRadios ruft auch um RebuildUsedFields
}
else
{
m_rbAllFields.Check(sal_False);
m_rbSingleField.Check(sal_True);
LINK(this, FmSearchDialog, OnClickedFieldRadios).Call(&m_rbSingleField);
}
// Position im Feld
m_lbPosition.SelectEntryPos(aParams.nPosition);
LINK(this, FmSearchDialog, OnPositionSelected).Call(&m_lbPosition);
// Feld-Formatierung/Case-Sensitivitaet/Richtung
m_cbUseFormat.Check(aParams.bUseFormatter);
m_cbCase.Check( aParams.isCaseSensitive() );
m_cbBackwards.Check(aParams.bBackwards);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_cbUseFormat);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_cbCase);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_cbBackwards);
m_aHalfFullFormsCJK.Check( !aParams.isIgnoreWidthCJK( ) ); // BEWARE: this checkbox has a inverse semantics!
m_aSoundsLikeCJK.Check( aParams.bSoundsLikeCJK );
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_aHalfFullFormsCJK);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_aSoundsLikeCJK);
// die drei Checkboxen fuer spezielle Sucharten
// erst mal alle ruecksetzen
m_cbWildCard.Check(sal_False);
m_cbRegular.Check(sal_False);
m_cbApprox.Check(sal_False);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_cbWildCard);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_cbRegular);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(&m_cbApprox);
// dann die richtige setzen
CheckBox* pToCheck = NULL;
if (aParams.bWildcard)
pToCheck = &m_cbWildCard;
if (aParams.bRegular)
pToCheck = &m_cbRegular;
if (aParams.bApproxSearch)
pToCheck = &m_cbApprox;
if (aParams.bSoundsLikeCJK)
pToCheck = &m_aSoundsLikeCJK;
if (pToCheck)
{
pToCheck->Check(sal_True);
LINK(this, FmSearchDialog, OnCheckBoxToggled).Call(pToCheck);
}
// die Levenshtein-Parameter direkt an der SearchEngine setzen
m_pSearchEngine->SetLevRelaxed(aParams.bLevRelaxed);
m_pSearchEngine->SetLevOther(aParams.nLevOther);
m_pSearchEngine->SetLevShorter(aParams.nLevShorter);
m_pSearchEngine->SetLevLonger(aParams.nLevLonger);
m_pSearchEngine->SetTransliterationFlags( aParams.getTransliterationFlags( ) );
m_rbSearchForText.Check(sal_False);
m_rbSearchForNull.Check(sal_False);
m_rbSearchForNotNull.Check(sal_False);
switch (aParams.nSearchForType)
{
case 1: m_rbSearchForNull.Check(sal_True); break;
case 2: m_rbSearchForNotNull.Check(sal_True); break;
default: m_rbSearchForText.Check(sal_True); break;
}
LINK(this, FmSearchDialog, OnClickedFieldRadios).Call(&m_rbSearchForText);
}
//------------------------------------------------------------------------
void FmSearchDialog::SaveParams() const
{
if (!m_pConfig)
return;
FmSearchParams aCurrentSettings;
aCurrentSettings.aHistory.realloc( m_cmbSearchText.GetEntryCount() );
::rtl::OUString* pHistory = aCurrentSettings.aHistory.getArray();
for (sal_uInt16 i=0; i<m_cmbSearchText.GetEntryCount(); ++i, ++pHistory)
*pHistory = m_cmbSearchText.GetEntry(i);
aCurrentSettings.sSingleSearchField = m_lbField.GetSelectEntry();
aCurrentSettings.bAllFields = m_rbAllFields.IsChecked();
aCurrentSettings.nPosition = m_pSearchEngine->GetPosition();
aCurrentSettings.bUseFormatter = m_pSearchEngine->GetFormatterUsing();
aCurrentSettings.setCaseSensitive ( m_pSearchEngine->GetCaseSensitive() );
aCurrentSettings.bBackwards = !m_pSearchEngine->GetDirection();
aCurrentSettings.bWildcard = m_pSearchEngine->GetWildcard();
aCurrentSettings.bRegular = m_pSearchEngine->GetRegular();
aCurrentSettings.bApproxSearch = m_pSearchEngine->GetLevenshtein();
aCurrentSettings.bLevRelaxed = m_pSearchEngine->GetLevRelaxed();
aCurrentSettings.nLevOther = m_pSearchEngine->GetLevOther();
aCurrentSettings.nLevShorter = m_pSearchEngine->GetLevShorter();
aCurrentSettings.nLevLonger = m_pSearchEngine->GetLevLonger();
aCurrentSettings.bSoundsLikeCJK = m_pSearchEngine->GetTransliteration();
aCurrentSettings.setTransliterationFlags ( m_pSearchEngine->GetTransliterationFlags() );
if (m_rbSearchForNull.IsChecked())
aCurrentSettings.nSearchForType = 1;
else if (m_rbSearchForNotNull.IsChecked())
aCurrentSettings.nSearchForType = 2;
else
aCurrentSettings.nSearchForType = 0;
m_pConfig->setParams( aCurrentSettings );
}
| 38.096907 | 148 | 0.699978 | [
"vector"
] |
78ffac498d57cb3658b80d8f5198a181db1457fd | 10,680 | cpp | C++ | core/GunnsBasicConductor.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | core/GunnsBasicConductor.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | core/GunnsBasicConductor.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | /**
@file
@brief GUNNS Basic Conductor Link implementation
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
PURPOSE:
(Provides the classes for modeling the GUNNS basic conductor.)
REQUIREMENTS:
()
REFERENCE:
()
ASSUMPTIONS AND LIMITATIONS:
()
LIBRARY DEPENDENCY:
(
(GunnsBasicLink.o)
)
PROGRAMMERS:
(
(Jason Harvey) (L3) (2011-02) (Initial Prototype))
(Kevin Supak) (L3) (2011-02) (Updated to Coding Standards))
)
*/
#include "GunnsBasicConductor.hh"
#include "math/MsMath.hh"
#include "software/exceptions/TsInitializationException.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] name (--) Link name
/// @param[in] nodes (--) Network nodes array
/// @param[in] defaultConductivity (--) Default conductivity of the link
///
/// @details Constructs the Basic Conductor Config data
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductorConfigData::GunnsBasicConductorConfigData(const std::string& name,
GunnsNodeList* nodes,
const double defaultConductivity)
:
GunnsBasicLinkConfigData(name, nodes),
mDefaultConductivity(defaultConductivity)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Object to copy from
///
/// @details Copy Constructs the Basic Conductor Config data
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductorConfigData::GunnsBasicConductorConfigData(
const GunnsBasicConductorConfigData& that)
:
GunnsBasicLinkConfigData(that),
mDefaultConductivity(that.mDefaultConductivity)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Destructs the Basic Conductor Config Data Object
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductorConfigData::~GunnsBasicConductorConfigData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] malfBlockageFlag (--) Blockage malfunction flag
/// @param[in] malfBlockageValue (--) Blockage malfunction fractional value (0-1)
///
/// @details Default constructs this Basic Conductor input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductorInputData::GunnsBasicConductorInputData(const bool malfBlockageFlag,
const double malfBlockageValue)
:
GunnsBasicLinkInputData(malfBlockageFlag, malfBlockageValue)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Object to copy
///
/// @details Copy constructs this Basic Conductor input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductorInputData::GunnsBasicConductorInputData(const GunnsBasicConductorInputData& that)
:
GunnsBasicLinkInputData(that)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this Basic Conductor input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductorInputData::~GunnsBasicConductorInputData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Constructs the Basic Conductor Object
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductor::GunnsBasicConductor():
GunnsBasicLink(NPORTS),
mEffectiveConductivity(0.0),
mDefaultConductivity (0.0),
mSystemConductance (0.0)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Destructs the Basic Conductor Object
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsBasicConductor::~GunnsBasicConductor()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] configData (--) Reference to Link Config Data
/// @param[in] inputData (--) Reference to Link Input Data
/// @param[in,out] networkLinks (--) Reference to the Network Link Vector
/// @param[in] port0 (--) Port 0 Mapping
/// @param[in] port1 (--) Port 1 Mapping
///
/// @throws TsInitializationException
///
/// @details Initializes the basic conductor with config and input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::initialize(const GunnsBasicConductorConfigData& configData,
const GunnsBasicConductorInputData& inputData,
std::vector<GunnsBasicLink*>& networkLinks,
const int port0,
const int port1)
{
/// - Initialize the parent class.
int ports[2] = {port0, port1};
GunnsBasicLink::initialize(configData, inputData, networkLinks, ports);
/// - Reset init flag.
mInitFlag = false;
/// - Initialize class attributes.
mDefaultConductivity = configData.mDefaultConductivity;
mEffectiveConductivity = mDefaultConductivity;
mSystemConductance = 0.0;
validate();
/// - Set init flag on successful validation.
mInitFlag = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @throws TsInitializationException
///
/// @details Validates the link
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::validate() const
{
/// - Issue an error on conductivity being less than zero.
if (mEffectiveConductivity < 0.0) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Link has conductivity < 0.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Derived classes should call their base class implementation too.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::restartModel()
{
/// - Reset the base class.
GunnsBasicLink::restartModel();
/// - Reset non-config & non-checkpointed class attributes.
mEffectiveConductivity = 0.0;
mSystemConductance = 0.0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Integration time step
///
/// @details Updates the basic conductor during the time step
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::step(const double dt)
{
/// - Process user commands to dynamically re-map ports.
processUserPortCommand();
/// - Call the virtual updateState method so a derived model can calculate a new conductivity.
/// - Default the effective conductivity, then call the virtual updateState method so a derived
/// model can calculate a new conductivity.
mEffectiveConductivity = mDefaultConductivity;
updateState(dt);
/// - Set the link's system conductance based on the effective conductivity and the blockage
/// fraction.
mSystemConductance = mEffectiveConductivity;
if (mMalfBlockageFlag) {
mSystemConductance *= (1.0 - mMalfBlockageValue);
}
mSystemConductance = MsMath::limitRange(0.0, mSystemConductance, mConductanceLimit);
buildConductance();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Protected method for building the conductance into the system of equations.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::buildConductance()
{
if (fabs(mAdmittanceMatrix[0] - mSystemConductance) > 0.0) {
mAdmittanceMatrix[0] = mSystemConductance;
mAdmittanceMatrix[1] = -mAdmittanceMatrix[0];
mAdmittanceMatrix[2] = -mAdmittanceMatrix[0];
mAdmittanceMatrix[3] = mAdmittanceMatrix[0];
mAdmittanceUpdate = true;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Integration time step
///
/// @details Method for computing the flows across the link
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::computeFlows(const double dt)
{
mPotentialDrop = getDeltaPotential();
computeFlux();
updateFlux(dt, mFlux);
computePower();
transportFlux();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Compute flux across the link, defined positive from port 0 to port 1.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsBasicConductor::computeFlux()
{
const double hiP = std::max(mPotentialVector[0], mPotentialVector[1]);
if (fabs(mPotentialDrop) < (hiP * m100EpsilonLimit)) {
/// - Zero flux if dP is too low. This eliminates most false quantity leak due to rounding
/// error in the solver.
mFlux = 0.0;
} else {
mFlux = mPotentialDrop * mAdmittanceMatrix[0];
}
}
| 41.076923 | 101 | 0.460393 | [
"object",
"vector",
"model"
] |
6003e827a9f241c88d2f4b3e3d0ed3d6fcb75d39 | 7,815 | hh | C++ | include/click/netmapdevice.hh | BorisPis/asplos22-nicmem-fastclick | ab4df08ee056ed48a4c534ec5f8536a958f756b5 | [
"BSD-3-Clause-Clear"
] | 1 | 2021-01-30T15:51:59.000Z | 2021-01-30T15:51:59.000Z | include/click/netmapdevice.hh | BorisPis/asplos22-nicmem-fastclick | ab4df08ee056ed48a4c534ec5f8536a958f756b5 | [
"BSD-3-Clause-Clear"
] | null | null | null | include/click/netmapdevice.hh | BorisPis/asplos22-nicmem-fastclick | ab4df08ee056ed48a4c534ec5f8536a958f756b5 | [
"BSD-3-Clause-Clear"
] | null | null | null | // -*- c-basic-offset: 4; related-file-name: "../../lib/netmapdevice.cc" -*-
/*
* netmapdevice.{cc,hh} -- Library to use netmap
* Eddie Kohler, Luigi Rizzo, Tom Barbette
*
* Copyright (c) 2012 Eddie Kohler
* Copyright (c) 2014-2015 University of Liege
*
* NetmapBufQ implementation was started by Luigi Rizzo and moved from
* netmapinfo.hh.
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#ifndef CLICK_NETMAPDEVICE_HH
#define CLICK_NETMAPDEVICE_HH
#if HAVE_NETMAP && CLICK_USERLEVEL
#include <net/if.h>
#include <net/netmap.h>
#define NETMAP_WITH_LIBS 1
#include <net/netmap_user.h>
#define NS_NOFREE 0x80 //We use this to set that a buffer is shared and should not be freed
#include <click/error.hh>
#include <click/ring.hh>
#include <click/vector.hh>
#include <click/hashmap.hh>
#include <click/element.hh>
#include <click/args.hh>
#include <click/packet.hh>
#include <click/sync.hh>
CLICK_DECLS
#define CLICK_NETMAP_POOL_DEBUG 0
#define NETMAP_PACKET_POOL_SIZE 2048
#define BUFFER_PTR(idx) reinterpret_cast<uint32_t *>(buf_start + idx * buf_size)
#define BUFFER_NEXT_LIST(idx) *(((uint32_t*)BUFFER_PTR(idx)) + 1)
#define CLICK_NETMAP_POOL_DEBUG_MAGIC(idx) (*(BUFFER_PTR(idx)+3))
#define CLICK_NETMAP_POOL_DEBUG_MAGIC_VALUE 0b01011100010111000101110001011100
/* a queue of netmap buffers, by index*/
class NetmapBufQ {
public:
NetmapBufQ();
~NetmapBufQ();
inline void expand();
inline void insert(uint32_t idx);
inline void insert_p(unsigned char *p);
inline void insert_all(uint32_t idx, bool check_size);
inline uint32_t extract();
inline unsigned char * extract_p();
inline int count_buffers(uint32_t idx);
inline int count() const {
return _count;
};
//Static functions
static int static_initialize(struct nm_desc* nmd);
static uint32_t static_cleanup();
static void global_insert_all(uint32_t idx, int count);
inline static unsigned int buffer_size() {
return buf_size;
}
static void buffer_destructor(unsigned char *buf, size_t, void *) {
NetmapBufQ::local_pool()->insert_p(buf);
}
inline static bool is_netmap_packet(Packet* p) {
return (p->buffer_destructor() == buffer_destructor ||
(p->buffer() > NetmapBufQ::buf_start && p->buffer() < NetmapBufQ::buf_end));
}
inline static bool is_valid_netmap_buffer(void* data) {
return (data > NetmapBufQ::buf_start && data < NetmapBufQ::buf_end);
}
inline static bool is_valid_netmap_packet(Packet* p) {
return (p->buffer() > NetmapBufQ::buf_start && p->buffer() < NetmapBufQ::buf_end);
}
inline static NetmapBufQ* local_pool() {
return NetmapBufQ::netmap_buf_pools[click_current_cpu_id()];
}
static inline bool initialized() {
return netmap_buf_pools != 0;
}
bool check_list() {
return find_count(_head) == _count;
}
static int find_count(uint32_t cur,int limit = 65536) {
int c = 0;
while (cur > 0) {
uint32_t* p = BUFFER_PTR(cur);
cur = *p;
c++;
assert(c <= limit);
}
return c;
}
private :
uint32_t _head; /* index of first buffer */
int _count; /* how many ? */
//Static attributes (shared between all queues)
static unsigned char *buf_start; /* base address */
static unsigned char *buf_end; /* error checking */
static unsigned int buf_size;
static uint32_t max_index; /* error checking */
static Spinlock global_buffer_lock;
//The global netmap buffer list is used to exchange batch of buffers between threads
//The second uint32_t in the buffer is used to point to the next batch
static uint32_t global_buffer_list;
static int messagelimit;
static NetmapBufQ** netmap_buf_pools;
} __attribute__((aligned(64)));
/**
* A Netmap interface, its global descriptor and one descriptor per queue
*/
class NetmapDevice {
public:
NetmapDevice(String ifname) CLICK_COLD;
~NetmapDevice() CLICK_COLD;
int initialize() CLICK_COLD;
void destroy() CLICK_COLD;
atomic_uint32_t n_refs;
struct nm_desc* parent_nmd;
Vector<struct nm_desc*> nmds;
String ifname;
int n_queues;
#if HAVE_NETMAP_PACKET_POOL
static WritablePacket* make_netmap(unsigned char* data, struct netmap_ring* rxring, struct netmap_slot* slot);
# if HAVE_BATCH
static PacketBatch* make_netmap_batch(unsigned int n, struct netmap_ring* rxring, unsigned int &cur);
# endif
#endif
static NetmapDevice* open(String ifname);
static void static_cleanup();
static struct nm_desc* some_nmd;
static int global_alloc;
int _minfd;
int _maxfd;
int get_num_slots() {
return some_nmd->some_ring->num_slots;
}
private :
static HashMap<String,NetmapDevice*> nics;
int _use_count;
};
/*
* Inline functions
*/
inline void NetmapBufQ::expand() {
global_buffer_lock.acquire();
if (global_buffer_list != 0) {
//Transfer from global pool
_head = global_buffer_list;
global_buffer_list = BUFFER_NEXT_LIST(global_buffer_list);
_count = NETMAP_PACKET_POOL_SIZE;
} else {
#ifdef NIOCALLOCBUF
click_chatter("Expanding buffer pool with %d new packets",NETMAP_PACKET_POOL_SIZE);
struct nmbufreq nbr;
nbr.num = NETMAP_PACKET_POOL_SIZE;
nbr.head = 0;
if (ioctl(NetmapDevice::some_nmd->fd,NIOCALLOCBUF,&nbr) == 0) {
insert_all(nbr.head,false);
} else
#endif
{
if (messagelimit < 5)
click_chatter("No more netmap buffers !");
messagelimit++;
}
}
global_buffer_lock.release();
}
/**
* Insert a list of netmap buffers in the queue
*/
inline void NetmapBufQ::insert_all(uint32_t idx,bool check_size = false) {
if (unlikely(idx >= max_index || idx == 0)) {
click_chatter("Error : cannot insert index %d",idx);
return;
}
uint32_t firstidx = idx;
uint32_t *p = 0;
while (idx > 0) { //Go to the end of the passed list
if (check_size) {
insert(idx);
} else {
p = BUFFER_PTR(idx);
idx = *p;
_count++;
}
}
//Add the current list at the end of this one
if (!check_size) {
*p = _head;
_head = firstidx;
}
}
/**
* Return the number of buffer inside a netmap buffer list
*/
int NetmapBufQ::count_buffers(uint32_t idx) {
int count=0;
while (idx != 0) {
count++;
idx = *BUFFER_PTR(idx);
}
return count;
}
inline void NetmapBufQ::insert(uint32_t idx) {
#if CLICK_NETMAP_POOL_DEBUG
assert(idx > 0 && idx < max_index);
assert(CLICK_NETMAP_POOL_DEBUG_MAGIC(idx) != CLICK_NETMAP_POOL_DEBUG_MAGIC_VALUE);
#endif
if (_count < NETMAP_PACKET_POOL_SIZE) {
*BUFFER_PTR(idx) = _head;
_head = idx;
_count++;
} else {
#if CLICK_NETMAP_POOL_DEBUG
assert(_count == NETMAP_PACKET_POOL_SIZE);
assert(find_count(_head) == NETMAP_PACKET_POOL_SIZE);
#endif
global_buffer_lock.acquire();
BUFFER_NEXT_LIST(_head) = global_buffer_list;
global_buffer_list = _head;
global_buffer_lock.release();
_head = idx;
*BUFFER_PTR(idx) = 0;
_count = 1;
}
}
inline void NetmapBufQ::insert_p(unsigned char* buf) {
insert((buf - buf_start) / buf_size);
}
inline uint32_t NetmapBufQ::extract() {
if (_count <= 0) {
expand();
if (_count == 0) return 0;
}
uint32_t idx;
uint32_t *p;
idx = _head;
p = BUFFER_PTR(idx);
_head = *p;
_count--;
#if CLICK_NETMAP_POOL_DEBUG
CLICK_NETMAP_POOL_DEBUG_MAGIC(idx) = 0;
#endif
return idx;
}
inline unsigned char* NetmapBufQ::extract_p() {
uint32_t idx = extract();
return (idx == 0) ? 0 : reinterpret_cast<unsigned char*>(BUFFER_PTR(idx));
}
#endif
#endif
| 24.809524 | 114 | 0.722585 | [
"vector"
] |
600c9d42801b4f4094d4de321dc08d2296c030ec | 7,336 | cc | C++ | mediapipe/modules/face_geometry/geometry_pipeline_calculator.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 3 | 2020-11-23T18:15:28.000Z | 2020-11-29T15:51:10.000Z | mediapipe/modules/face_geometry/geometry_pipeline_calculator.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 2 | 2020-12-24T06:35:19.000Z | 2021-01-04T08:44:25.000Z | mediapipe/modules/face_geometry/geometry_pipeline_calculator.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 3 | 2021-01-19T14:40:59.000Z | 2021-06-09T13:43:49.000Z | // Copyright 2020 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/landmark.pb.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/port/status_macros.h"
#include "mediapipe/framework/port/statusor.h"
#include "mediapipe/modules/face_geometry/geometry_pipeline_calculator.pb.h"
#include "mediapipe/modules/face_geometry/libs/geometry_pipeline.h"
#include "mediapipe/modules/face_geometry/libs/validation_utils.h"
#include "mediapipe/modules/face_geometry/protos/environment.pb.h"
#include "mediapipe/modules/face_geometry/protos/face_geometry.pb.h"
#include "mediapipe/modules/face_geometry/protos/geometry_pipeline_metadata.pb.h"
#include "mediapipe/util/resource_util.h"
namespace mediapipe {
namespace {
static constexpr char kEnvironmentTag[] = "ENVIRONMENT";
static constexpr char kImageSizeTag[] = "IMAGE_SIZE";
static constexpr char kMultiFaceGeometryTag[] = "MULTI_FACE_GEOMETRY";
static constexpr char kMultiFaceLandmarksTag[] = "MULTI_FACE_LANDMARKS";
// A calculator that renders a visual effect for multiple faces.
//
// Inputs:
// IMAGE_SIZE (`std::pair<int, int>`, required):
// The size of the current frame. The first element of the pair is the frame
// width; the other one is the frame height.
//
// The face landmarks should have been detected on a frame with the same
// ratio. If used as-is, the resulting face geometry visualization should be
// happening on a frame with the same ratio as well.
//
// MULTI_FACE_LANDMARKS (`std::vector<NormalizedLandmarkList>`, required):
// A vector of face landmark lists.
//
// Input side packets:
// ENVIRONMENT (`face_geometry::Environment`, required)
// Describes an environment; includes the camera frame origin point location
// as well as virtual camera parameters.
//
// Output:
// MULTI_FACE_GEOMETRY (`std::vector<face_geometry::FaceGeometry>`, required):
// A vector of face geometry data.
//
// Options:
// metadata_path (`string`, optional):
// Defines a path for the geometry pipeline metadata file.
//
// The geometry pipeline metadata file format must be the binary
// `face_geometry.GeometryPipelineMetadata` proto.
//
class GeometryPipelineCalculator : public CalculatorBase {
public:
static mediapipe::Status GetContract(CalculatorContract* cc) {
cc->InputSidePackets()
.Tag(kEnvironmentTag)
.Set<face_geometry::Environment>();
cc->Inputs().Tag(kImageSizeTag).Set<std::pair<int, int>>();
cc->Inputs()
.Tag(kMultiFaceLandmarksTag)
.Set<std::vector<NormalizedLandmarkList>>();
cc->Outputs()
.Tag(kMultiFaceGeometryTag)
.Set<std::vector<face_geometry::FaceGeometry>>();
return mediapipe::OkStatus();
}
mediapipe::Status Open(CalculatorContext* cc) override {
cc->SetOffset(mediapipe::TimestampDiff(0));
const auto& options = cc->Options<FaceGeometryPipelineCalculatorOptions>();
ASSIGN_OR_RETURN(
face_geometry::GeometryPipelineMetadata metadata,
ReadMetadataFromFile(options.metadata_path()),
_ << "Failed to read the geometry pipeline metadata from file!");
MP_RETURN_IF_ERROR(
face_geometry::ValidateGeometryPipelineMetadata(metadata))
<< "Invalid geometry pipeline metadata!";
const face_geometry::Environment& environment =
cc->InputSidePackets()
.Tag(kEnvironmentTag)
.Get<face_geometry::Environment>();
MP_RETURN_IF_ERROR(face_geometry::ValidateEnvironment(environment))
<< "Invalid environment!";
ASSIGN_OR_RETURN(
geometry_pipeline_,
face_geometry::CreateGeometryPipeline(environment, metadata),
_ << "Failed to create a geometry pipeline!");
return mediapipe::OkStatus();
}
mediapipe::Status Process(CalculatorContext* cc) override {
// Both the `IMAGE_SIZE` and the `MULTI_FACE_LANDMARKS` streams are required
// to have a non-empty packet. In case this requirement is not met, there's
// nothing to be processed at the current timestamp.
if (cc->Inputs().Tag(kImageSizeTag).IsEmpty() ||
cc->Inputs().Tag(kMultiFaceLandmarksTag).IsEmpty()) {
return mediapipe::OkStatus();
}
const auto& image_size =
cc->Inputs().Tag(kImageSizeTag).Get<std::pair<int, int>>();
const auto& multi_face_landmarks =
cc->Inputs()
.Tag(kMultiFaceLandmarksTag)
.Get<std::vector<NormalizedLandmarkList>>();
auto multi_face_geometry =
absl::make_unique<std::vector<face_geometry::FaceGeometry>>();
ASSIGN_OR_RETURN(
*multi_face_geometry,
geometry_pipeline_->EstimateFaceGeometry(
multi_face_landmarks, //
/*frame_width*/ image_size.first,
/*frame_height*/ image_size.second),
_ << "Failed to estimate face geometry for multiple faces!");
cc->Outputs()
.Tag(kMultiFaceGeometryTag)
.AddPacket(mediapipe::Adopt<std::vector<face_geometry::FaceGeometry>>(
multi_face_geometry.release())
.At(cc->InputTimestamp()));
return mediapipe::OkStatus();
}
mediapipe::Status Close(CalculatorContext* cc) override {
return mediapipe::OkStatus();
}
private:
static mediapipe::StatusOr<face_geometry::GeometryPipelineMetadata>
ReadMetadataFromFile(const std::string& metadata_path) {
ASSIGN_OR_RETURN(std::string metadata_blob,
ReadContentBlobFromFile(metadata_path),
_ << "Failed to read a metadata blob from file!");
face_geometry::GeometryPipelineMetadata metadata;
RET_CHECK(metadata.ParseFromString(metadata_blob))
<< "Failed to parse a metadata proto from a binary blob!";
return metadata;
}
static mediapipe::StatusOr<std::string> ReadContentBlobFromFile(
const std::string& unresolved_path) {
ASSIGN_OR_RETURN(std::string resolved_path,
mediapipe::PathToResourceAsFile(unresolved_path),
_ << "Failed to resolve path! Path = " << unresolved_path);
std::string content_blob;
MP_RETURN_IF_ERROR(
mediapipe::GetResourceContents(resolved_path, &content_blob))
<< "Failed to read content blob! Resolved path = " << resolved_path;
return content_blob;
}
std::unique_ptr<face_geometry::GeometryPipeline> geometry_pipeline_;
};
} // namespace
using FaceGeometryPipelineCalculator = GeometryPipelineCalculator;
REGISTER_CALCULATOR(FaceGeometryPipelineCalculator);
} // namespace mediapipe
| 37.050505 | 81 | 0.710196 | [
"geometry",
"vector"
] |
601a13bdcfb1c9c78b932c491e435493c94fe8f7 | 1,401 | cpp | C++ | H-Heap/MinCostRopes.cpp | riyasingh240601/LearnCPP | 5dc75a4d7cd1a1c4519018bc4ef1f54151c0a8ed | [
"MIT"
] | 1 | 2022-03-26T02:34:12.000Z | 2022-03-26T02:34:12.000Z | H-Heap/MinCostRopes.cpp | riyasingh240601/LearnCPP | 5dc75a4d7cd1a1c4519018bc4ef1f54151c0a8ed | [
"MIT"
] | null | null | null | H-Heap/MinCostRopes.cpp | riyasingh240601/LearnCPP | 5dc75a4d7cd1a1c4519018bc4ef1f54151c0a8ed | [
"MIT"
] | null | null | null | /* Minimum Cost Of Ropes
Time Complexity : O(n log n)
Space Complexity : O(n) , since we are using priority queue for storing data. */
#include <bits/stdc++.h>
using namespace std;
//Function to return the minimum cost of connecting the ropes.
long long cost(long long arr[], long long n)
{
priority_queue<long long,vector<long long>,greater<long long>>pq(arr,arr+n);
//declared min heap so that elements should be stored in ascending order
long long cost = 0;
while(pq.size()>1) //till heap is not empty, run this loop
{
long long first = pq.top();
pq.pop();
long long second = pq.top();
pq.pop();
// take out first two minimum elements from priority queue and add them
cost = cost+first+second;
pq.push(first+second); // push the final result in priority queue
}
return cost;
}
int main()
{
long long n,i,a[100001];
cout<<"Enter the no. of elements in array : ";
cin >> n;
cout<<"Enter the elements.....\n";
for (i = 0; i < n; i++)
{
cin >> a[i];
}
cout<<"\n";
cout<<"Minimum cost for connecting ropes : "<<cost(a,n);
return 0;
} | 30.456522 | 91 | 0.508208 | [
"vector"
] |
601b54fd21a41fde897edc2cb1f5cebc5d478563 | 7,380 | cpp | C++ | src/tests/pixel.cpp | gmiz/notcurses | 33f581988ddb2ccc0cdf9ab1545bc57a6eafab74 | [
"Apache-2.0"
] | null | null | null | src/tests/pixel.cpp | gmiz/notcurses | 33f581988ddb2ccc0cdf9ab1545bc57a6eafab74 | [
"Apache-2.0"
] | null | null | null | src/tests/pixel.cpp | gmiz/notcurses | 33f581988ddb2ccc0cdf9ab1545bc57a6eafab74 | [
"Apache-2.0"
] | 1 | 2022-02-11T17:19:32.000Z | 2022-02-11T17:19:32.000Z | #include "main.h"
#include <vector>
TEST_CASE("Pixel") {
auto nc_ = testing_notcurses();
REQUIRE(nullptr != nc_);
ncplane* ncp_ = notcurses_stdplane(nc_);
REQUIRE(ncp_);
auto n_ = notcurses_stdplane(nc_);
REQUIRE(n_);
if(notcurses_check_pixel_support(nc_) <= 0){
CHECK(0 == nc_->tcache.sixel_supported);
CHECK(!notcurses_stop(nc_));
return;
}
SUBCASE("SprixelTermValues") {
CHECK(0 < nc_->tcache.cellpixy);
CHECK(0 < nc_->tcache.cellpixx);
CHECK(nc_->tcache.sixel_supported);
}
#ifdef NOTCURSES_USE_MULTIMEDIA
SUBCASE("PixelRender") {
auto ncv = ncvisual_from_file(find_data("worldmap.png"));
REQUIRE(ncv);
struct ncvisual_options vopts{};
vopts.blitter = NCBLIT_PIXEL;
vopts.flags = NCVISUAL_OPTION_NODEGRADE;
auto newn = ncvisual_render(nc_, ncv, &vopts);
CHECK(newn);
CHECK(0 == notcurses_render(nc_));
ncplane_destroy(newn);
CHECK(0 == notcurses_render(nc_));
ncvisual_destroy(ncv);
}
#endif
SUBCASE("PixelCellWipe") {
// first, assemble a visual equivalent to 4 cells
auto y = 2 * nc_->tcache.cellpixy;
auto x = 2 * nc_->tcache.cellpixx;
std::vector<uint32_t> v(x * y, 0xffffffff);
auto ncv = ncvisual_from_rgba(v.data(), y, sizeof(decltype(v)::value_type) * x, x);
REQUIRE(nullptr != ncv);
struct ncvisual_options vopts = {
.n = nullptr,
.scaling = NCSCALE_NONE,
.y = 0, .x = 0,
.begy = 0, .begx = 0,
.leny = y, .lenx = x,
.blitter = NCBLIT_PIXEL,
.flags = NCVISUAL_OPTION_NODEGRADE,
};
auto n = ncvisual_render(nc_, ncv, &vopts);
REQUIRE(nullptr != n);
auto s = n->sprite;
REQUIRE(nullptr != s);
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 0, 0, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 1, 1, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 1, 0, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 0, 1, 'x'));
CHECK(0 == notcurses_render(nc_));
ncplane_destroy(n);
ncvisual_destroy(ncv);
CHECK(0 == notcurses_render(nc_));
}
SUBCASE("PixelCellWipePolychromatic") {
// first, assemble a visual equivalent to 4 cells
auto y = 2 * nc_->tcache.cellpixy;
auto x = 2 * nc_->tcache.cellpixx;
std::vector<uint32_t> v(x * y, 0xffffffff);
for(auto& e : v){
e -= random() % 0x1000000;
}
auto ncv = ncvisual_from_rgba(v.data(), y, sizeof(decltype(v)::value_type) * x, x);
REQUIRE(nullptr != ncv);
struct ncvisual_options vopts = {
.n = nullptr,
.scaling = NCSCALE_NONE,
.y = 0, .x = 0,
.begy = 0, .begx = 0,
.leny = y, .lenx = x,
.blitter = NCBLIT_PIXEL,
.flags = NCVISUAL_OPTION_NODEGRADE,
};
auto n = ncvisual_render(nc_, ncv, &vopts);
REQUIRE(nullptr != n);
auto s = n->sprite;
REQUIRE(nullptr != s);
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 0, 0, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 1, 1, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 1, 0, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 0, 1, 'x'));
CHECK(0 == notcurses_render(nc_));
ncplane_destroy(n);
ncvisual_destroy(ncv);
CHECK(0 == notcurses_render(nc_));
}
SUBCASE("PixelBigCellWipePolychromatic") {
// first, assemble a visual equivalent to 100 cells
auto y = 10 * nc_->tcache.cellpixy;
auto x = 10 * nc_->tcache.cellpixx;
std::vector<uint32_t> v(x * y, 0xffffffff);
for(auto& e : v){
e -= random() % 0x1000000;
}
auto ncv = ncvisual_from_rgba(v.data(), y, sizeof(decltype(v)::value_type) * x, x);
REQUIRE(nullptr != ncv);
struct ncvisual_options vopts = {
.n = nullptr,
.scaling = NCSCALE_NONE,
.y = 0, .x = 0,
.begy = 0, .begx = 0,
.leny = y, .lenx = x,
.blitter = NCBLIT_PIXEL,
.flags = NCVISUAL_OPTION_NODEGRADE,
};
auto n = ncvisual_render(nc_, ncv, &vopts);
REQUIRE(nullptr != n);
auto s = n->sprite;
REQUIRE(nullptr != s);
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 5, 5, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 3, 3, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 8, 8, 'x'));
CHECK(0 == notcurses_render(nc_));
CHECK(1 == ncplane_putchar_yx(n_, 8, 3, 'x'));
CHECK(0 == notcurses_render(nc_));
ncplane_destroy(n);
ncvisual_destroy(ncv);
CHECK(0 == notcurses_render(nc_));
}
// verify that the sprixel's TAM is properly initialized
SUBCASE("PixelTAMSetup") {
// first, assemble a visual equivalent to 81 cells
auto dimy = 9;
auto dimx = 9;
auto y = dimy * nc_->tcache.cellpixy;
auto x = dimx * nc_->tcache.cellpixx;
std::vector<uint32_t> v(x * y, 0xffffffff);
// every other cell, set some pixels transparent
for(int i = 0 ; i < dimy * dimx ; ++i){
if(i % 2){
int py = (i / dimx) * nc_->tcache.cellpixy;
int px = (i % dimx) * nc_->tcache.cellpixx;
ncpixel_set_a(&v[py * x + px], 0);
}
}
auto ncv = ncvisual_from_rgba(v.data(), y, sizeof(decltype(v)::value_type) * x, x);
REQUIRE(nullptr != ncv);
struct ncvisual_options vopts = {
.n = nullptr,
.scaling = NCSCALE_NONE,
.y = 0, .x = 0,
.begy = 0, .begx = 0,
.leny = y, .lenx = x,
.blitter = NCBLIT_PIXEL,
.flags = NCVISUAL_OPTION_NODEGRADE,
};
auto n = ncvisual_render(nc_, ncv, &vopts);
REQUIRE(nullptr != n);
ncvisual_destroy(ncv);
CHECK(0 == notcurses_render(nc_));
const auto s = n->sprite;
REQUIRE(s);
CHECK(s->dimy == dimy);
CHECK(s->dimx == dimx);
const auto tam = n->tacache;
for(int i = 0 ; i < s->dimy * s->dimx ; ++i){
int py = (i / dimx) * nc_->tcache.cellpixy;
int px = (i % dimx) * nc_->tcache.cellpixx;
// cells with a transparent pixel ought be SPRIXCELL_CONTAINS_TRANS;
// cells without one ought be SPRIXCELL_OPAQUE.
CHECK((i % 2) == tam[(i / dimx) + (i % dimx)]);
ncpixel_set_a(&v[py * x + px], 0);
}
ncplane_destroy(n);
}
// too much output -- OOMs ctest FIXME
/*
#ifdef NOTCURSES_USE_MULTIMEDIA
SUBCASE("PixelWipeImage") {
uint64_t channels = 0;
channels_set_fg_alpha(&channels, CELL_ALPHA_TRANSPARENT);
channels_set_bg_alpha(&channels, CELL_ALPHA_TRANSPARENT);
CHECK(0 == ncplane_set_base(n_, "", 0, channels));
auto ncv = ncvisual_from_file(find_data("worldmap.png"));
REQUIRE(ncv);
struct ncvisual_options vopts{};
vopts.blitter = NCBLIT_PIXEL;
vopts.flags = NCVISUAL_OPTION_NODEGRADE;
auto newn = ncvisual_render(nc_, ncv, &vopts);
CHECK(newn);
ncplane_move_bottom(newn);
CHECK(0 == notcurses_render(nc_));
const auto s = newn->sprite;
for(int y = 0 ; y < s->dimy ; ++y){
for(int x = 0 ; x < s->dimx ; ++x){
CHECK(1 == ncplane_putchar_yx(n_, y, x, 'x'));
CHECK(0 == notcurses_render(nc_));
}
}
ncplane_destroy(newn);
CHECK(0 == notcurses_render(nc_));
ncvisual_destroy(ncv);
}
#endif
*/
CHECK(!notcurses_stop(nc_));
}
| 32.368421 | 87 | 0.605827 | [
"vector"
] |
e743ba5f860c831f4e98234754602a65b345b702 | 4,755 | cpp | C++ | PS5/src/TFractal.cpp | 1ssepehr/UML-Comp-IV | b6ae1f9acbb12948ac4da17daa21dfbc353d6ac5 | [
"MIT"
] | null | null | null | PS5/src/TFractal.cpp | 1ssepehr/UML-Comp-IV | b6ae1f9acbb12948ac4da17daa21dfbc353d6ac5 | [
"MIT"
] | null | null | null | PS5/src/TFractal.cpp | 1ssepehr/UML-Comp-IV | b6ae1f9acbb12948ac4da17daa21dfbc353d6ac5 | [
"MIT"
] | null | null | null | // (C) Copyright Seyedsepehr Madani, 2021.
// Distributed under MIT license, available at
// https://opensource.org/licenses/MIT.
#include <iostream>
#include <stdexcept>
#include <vector>
#include <SFML/Window.hpp>
#include "Triangle.hpp"
static char optionsMsg[] =
"Invalid options. Please use:\n"
" `./Triangle L N',\n"
"where:\n"
" L = length of base triangle's side (double), and\n"
" N = recursion depth (int).";
static char controlsText[] =
"Up/Down: Increase/Decrease N\n"
"Right/Left: Increase/Decrease L\n"
"Enter: Change Color\n"
"Space: Change Style\n"
"Backspace: Show/Hide this text";
// Path to the font file for controls
static char fontPath[] = "./assets/Oxanium.ttf";
// Series of dark colors to be used for the triangles
sf::Color colors[] = {
sf::Color(128, 0, 0), sf::Color(220, 20, 60), sf::Color(205, 92, 92),
sf::Color(184, 134, 11), sf::Color(128, 128, 0), sf::Color(85, 107, 47),
sf::Color(0, 100, 0), sf::Color(46, 139, 87), sf::Color(47, 79, 79),
sf::Color(70, 130, 180), sf::Color(25, 25, 112), sf::Color(139, 0, 139),
sf::Color(128, 0, 128), sf::Color(199, 21, 133), sf::Color(139, 69, 19),
sf::Color(112, 128, 144)};
auto colorCount = sizeof(colors) / sizeof(colors[0]);
// Recursive function to initalize the vector of triangles
void fTree(std::vector<Triangle> *shapes, Point center, double L, int n,
sf::PrimitiveType type, int colorKey) {
if (n < 0) return;
if (L < 0) L = 0;
shapes->push_back(Triangle(center, L, colors[colorKey % colorCount], type));
auto A = L * std::cos(M_PI / 6.0); // Altitude of the triangle
Point right = {center.x + (L * 0.75), center.y - (A / 6.0)};
Point left = {center.x - (L * 0.5), center.y - (A * 2.0 / 3.0)};
Point bottom = {center.x - (L * 0.25), center.y + (A * 5.0 / 6.0)};
fTree(shapes, right, 0.5 * L, n - 1, type, colorKey + 1);
fTree(shapes, left, 0.5 * L, n - 1, type, colorKey + 1);
fTree(shapes, bottom, 0.5 * L, n - 1, type, colorKey + 1);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << optionsMsg << std::endl;
return -1;
}
try {
// Load Sierpinsky triangle arguments
auto L = std::stod(argv[1]); // Length of triangle
auto N = std::stoi(argv[2]); // Recursion depth level
auto drawType = sf::Triangles; // Type of drawing (hollow or filled)
auto colorKey = 0; // Base color for the first triangle
std::vector<Triangle> triangles{};
// Create RenderWindow
sf::ContextSettings settings;
settings.antialiasingLevel = 8;
auto w_size = 960;
sf::RenderWindow window(sf::VideoMode(w_size, w_size),
"Sierpinski's Triangle", sf::Style::Default,
settings);
window.setPosition({150, 50});
window.setFramerateLimit(60);
// Controls text on the screen
sf::Font font;
if (!font.loadFromFile(fontPath))
throw std::runtime_error("Assets not present with the program!");
sf::Text controls(controlsText, font, 20);
controls.setFillColor(sf::Color::Black);
bool showControls = true;
// Program event loop
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) L -= 20;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) L += 20;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) --N;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) ++N;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) ++colorKey;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
drawType =
(drawType == sf::Triangles) ? sf::LineStrip : sf::Triangles;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Backspace))
showControls ^= 1;
if (N < 0) N = 0;
if (L < 0) L = 0;
break;
default:
break;
}
// Recalculate the triangles with [potentially new] parameters
triangles.clear();
fTree(&triangles, {0.5 * w_size, 0.5 * w_size}, L, N, drawType, colorKey);
// Draw triangles onto the canvas
window.clear(sf::Color::White);
for (auto& x : triangles) window.draw(x);
if (showControls) window.draw(controls);
window.display();
}
} catch (std::invalid_argument &e) {
std::cerr << optionsMsg << std::endl;
return -1;
} catch (std::runtime_error &e) {
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
| 34.963235 | 80 | 0.588644 | [
"vector"
] |
e7450fc4e55a51f18edcbc918a793a0f45341245 | 2,650 | cc | C++ | 212_word_search_ii.cc | cchord/leetcode | 9fc35186c165a155d02e5f6e90a789ade8ba5e2b | [
"MIT"
] | null | null | null | 212_word_search_ii.cc | cchord/leetcode | 9fc35186c165a155d02e5f6e90a789ade8ba5e2b | [
"MIT"
] | null | null | null | 212_word_search_ii.cc | cchord/leetcode | 9fc35186c165a155d02e5f6e90a789ade8ba5e2b | [
"MIT"
] | null | null | null | // Given a 2D board and a list of words from the dictionary, find all words in the board.
//
// Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
// // For example,
// Given words = ["oath","pea","eat","rain"] and board =
//
// [
// ['o','a','a','n'],
// ['e','t','a','e'],
// ['i','h','k','r'],
// ['i','f','l','v']
// ]
// Return ["eat","oath"].
#include "gtest/gtest.h"
#include <vector>
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;
namespace {
class Solution {
vector<vector<char>>* board_;
int r_ = 0;
int c_ = 0;
vector<string> res;
struct TrieNode {
TrieNode* children[26] = {0};
string word;
};
TrieNode *root_ = new TrieNode();
void buildTrie(vector<string>& words) {
for (auto &w : words) {
TrieNode *cur = root_;
for (auto &c : w) {
int i = c-'a';
if (!cur->children[i])
cur->children[i] = new TrieNode();
cur = cur->children[i];
}
cur->word = w;
}
}
void dfs(int i, int j, TrieNode *n) {
if (i < 0 || i >= r_ || j < 0 || j >= c_ || !n)
return;
char c = (*board_)[i][j];
if (c == '#')
return;
if (!n->children[c-'a'])
return;
auto child = n->children[c-'a'];
if(!child->word.empty()) {
res.push_back(child->word);
child->word = "";
}
(*board_)[i][j] = '#';
dfs(i-1, j, child);
dfs(i+1, j, child);
dfs(i, j-1, child);
dfs(i, j+1, child);
(*board_)[i][j] = c;
}
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
r_ = board.size();
if (!r_)
return res;
c_ = board[0].size();
if (!c_)
return res;
if (words.size() == 0)
return res;
board_ = &board;
buildTrie(words);
for (int i = 0; i < r_; ++i)
for (int j = 0; j < c_; ++j)
dfs(i,j,root_);
return res;
}
};
TEST(WordSearch2, 1) {
Solution s;
vector<vector<char>> board{ {'o','a','a','n'}, {'e','t','a','e'}, {'i','h','k','r'}, {'i','f','l','v'} };
vector<string> words{"eat", "oath"};
auto res = s.findWords(board, words);
copy(res.begin(), res.end(), ostream_iterator<string>(cout, " "));
}
}
| 25 | 212 | 0.475094 | [
"vector"
] |
e74727563d7f40b8abc470e3ba80afd6d04105b5 | 4,450 | cpp | C++ | src/webots/wren/WbLightRepresentation.cpp | Justin-Fisher/webots | 8a39e8e4390612919a8d82c7815aa914f4c079a4 | [
"Apache-2.0"
] | 1,561 | 2019-09-04T11:32:32.000Z | 2022-03-31T18:00:09.000Z | src/webots/wren/WbLightRepresentation.cpp | Justin-Fisher/webots | 8a39e8e4390612919a8d82c7815aa914f4c079a4 | [
"Apache-2.0"
] | 2,184 | 2019-09-03T11:35:02.000Z | 2022-03-31T10:01:44.000Z | src/webots/wren/WbLightRepresentation.cpp | Justin-Fisher/webots | 8a39e8e4390612919a8d82c7815aa914f4c079a4 | [
"Apache-2.0"
] | 1,013 | 2019-09-07T05:09:32.000Z | 2022-03-31T13:01:28.000Z | // Copyright 1996-2021 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WbLightRepresentation.hpp"
#include "WbWrenRenderingContext.hpp"
#include "WbWrenShaders.hpp"
#include <wren/material.h>
#include <wren/node.h>
#include <wren/renderable.h>
#include <wren/scene.h>
#include <wren/shader_program.h>
#include <wren/static_mesh.h>
#include <wren/texture.h>
#include <wren/texture_2d.h>
#include <wren/transform.h>
#include <wren/viewport.h>
#include <QtCore/QFileInfo>
#include <QtGui/QImage>
static const int ICON_SIZE = 32; // Size of light icon in pixels
void WbLightRepresentation::updateScreenScale(int width, int height) {
const float screenScale = 2.0f * ICON_SIZE / (width > height ? width : height);
WrShaderProgram *shader = WbWrenShaders::lightRepresentationShader();
wr_shader_program_set_custom_uniform_value(shader, "screenScale", WR_SHADER_PROGRAM_UNIFORM_TYPE_FLOAT,
reinterpret_cast<const char *>(&screenScale));
}
WbLightRepresentation::WbLightRepresentation(WrTransform *parent, const WbVector3 &position) :
mPosition(position),
mQImage(NULL) {
// Load sun texture (512x512 ARGB)
QByteArray imagePath = QFileInfo("gl:textures/light_representation.png").absoluteFilePath().toUtf8();
mTexture = wr_texture_2d_copy_from_cache(imagePath.constData());
if (!mTexture) {
mQImage = new QImage(imagePath.constData());
assert(!mQImage->isNull());
mTexture = wr_texture_2d_new();
wr_texture_set_translucent(WR_TEXTURE(mTexture), true);
wr_texture_set_size(WR_TEXTURE(mTexture), mQImage->width(), mQImage->height());
wr_texture_2d_set_data(mTexture, reinterpret_cast<const char *>(mQImage->bits()));
wr_texture_2d_set_file_path(mTexture, imagePath);
wr_texture_setup(WR_TEXTURE(mTexture));
}
mMaterial = wr_phong_material_new();
wr_material_set_texture(mMaterial, WR_TEXTURE(mTexture), 0);
wr_material_set_default_program(mMaterial, WbWrenShaders::lightRepresentationShader());
const float vertices[12] = {-0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f};
// Null normals as we wont use them
const float normals[12] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const float textureCoordinates[8] = {
0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
};
const unsigned int indices[6] = {2, 1, 0, 0, 3, 2};
mMesh = wr_static_mesh_new(4, 6, vertices, normals, textureCoordinates, textureCoordinates, indices, false);
mRenderable = wr_renderable_new();
wr_renderable_set_cast_shadows(mRenderable, false);
wr_renderable_set_receive_shadows(mRenderable, false);
wr_renderable_set_material(mRenderable, mMaterial, NULL);
wr_renderable_set_visibility_flags(mRenderable, WbWrenRenderingContext::VF_LIGHTS_POSITIONS);
wr_renderable_set_mesh(mRenderable, WR_MESH(mMesh));
wr_renderable_set_drawing_order(mRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1);
mTransform = wr_transform_new();
wr_node_set_visible(WR_NODE(mTransform), false);
wr_transform_attach_child(mTransform, WR_NODE(mRenderable));
wr_transform_attach_child(parent, WR_NODE(mTransform));
WrViewport *viewport = wr_scene_get_viewport(wr_scene_get_instance());
updateScreenScale(wr_viewport_get_width(viewport), wr_viewport_get_height(viewport));
}
WbLightRepresentation::~WbLightRepresentation() {
wr_node_delete(WR_NODE(mTransform));
wr_node_delete(WR_NODE(mRenderable));
wr_material_delete(mMaterial);
wr_static_mesh_delete(mMesh);
wr_texture_delete(WR_TEXTURE(mTexture));
delete mQImage;
}
void WbLightRepresentation::setPosition(const WbVector3 &position) {
float positionArray[3];
position.toFloatArray(positionArray);
wr_transform_set_position(mTransform, positionArray);
mPosition = position;
}
void WbLightRepresentation::setVisible(bool visible) {
wr_node_set_visible(WR_NODE(mTransform), visible);
}
| 40.09009 | 110 | 0.756629 | [
"transform"
] |
e748b40d3ddc05955add2dca5f5a8af20fdadfa3 | 1,762 | hpp | C++ | src/gpu/gpu_stream.hpp | SJTU-IPADS/wukong-cube | ccabf1b754978322277dc881a43cedfd2687070f | [
"Apache-2.0"
] | 7 | 2021-06-22T06:24:21.000Z | 2022-02-16T02:48:38.000Z | src/gpu/gpu_stream.hpp | SJTU-IPADS/wukong-cube | ccabf1b754978322277dc881a43cedfd2687070f | [
"Apache-2.0"
] | null | null | null | src/gpu/gpu_stream.hpp | SJTU-IPADS/wukong-cube | ccabf1b754978322277dc881a43cedfd2687070f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* 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.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong.html
*
*/
#pragma once
#ifdef USE_GPU
#include <cuda_runtime.h>
namespace wukong {
class GPUStreamPool {
private:
std::vector<cudaStream_t> streams;
uint64_t rr_cnt;
int num_streams;
cudaStream_t split_stream;
public:
GPUStreamPool(int num_streams) : num_streams(num_streams) {
rr_cnt = 0;
streams.reserve(num_streams);
for (int i = 0; i < num_streams; ++i)
cudaStreamCreate(&streams[i]);
cudaStreamCreate(&split_stream);
}
~GPUStreamPool() {
for (auto s : streams)
cudaStreamDestroy(s);
cudaStreamDestroy(split_stream);
}
cudaStream_t get_stream() {
// select Stream in a round-robin way
int idx = (rr_cnt++) % num_streams;
return streams[idx];
}
cudaStream_t get_stream(int pid) {
assert(pid > 0);
return streams[pid % num_streams];
}
cudaStream_t get_split_query_stream() { return split_stream; }
};
} // namespace wukong
#endif
| 24.136986 | 68 | 0.660045 | [
"vector"
] |
e75392cb62da1d9e3730549f7b9cab5d8e072fc2 | 10,027 | cpp | C++ | Principal_component_analysis/demo/Principal_component_analysis/Scene.cpp | gaschler/cgal | d1fe2afa18da5524db6d4946f42ca4b8d00e0bda | [
"CC0-1.0"
] | 2 | 2020-12-12T09:30:07.000Z | 2021-01-04T05:00:23.000Z | Principal_component_analysis/demo/Principal_component_analysis/Scene.cpp | guorongtao/cgal | a848e52552a9205124b7ae13c7bcd2b860eb4530 | [
"CC0-1.0"
] | null | null | null | Principal_component_analysis/demo/Principal_component_analysis/Scene.cpp | guorongtao/cgal | a848e52552a9205124b7ae13c7bcd2b860eb4530 | [
"CC0-1.0"
] | null | null | null | #include "Scene.h"
#include "Viewer.h"
#include <iostream>
#include <fstream>
#include <QString>
#include <QTextStream>
#include <QFileInfo>
#include <QInputDialog>
#include <CGAL/Timer.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/subdivision_method_3.h>
#include <CGAL/centroid.h>
#include <CGAL/linear_least_squares_fitting_3.h>
Scene::Scene()
{
is_gl_init = false;
m_pPolyhedron = NULL;
// view options
m_view_polyhedron = true;
}
Scene::~Scene()
{
delete m_pPolyhedron;
}
int Scene::open(QString filename)
{
QTextStream cerr(stderr);
cerr << QString("Opening file \"%1\"\n").arg(filename);
QApplication::setOverrideCursor(QCursor(::Qt::WaitCursor));
QFileInfo fileinfo(filename);
std::ifstream in(filename.toUtf8());
if(!in || !fileinfo.isFile() || ! fileinfo.isReadable())
{
std::cerr << "unable to open file" << std::endl;
QApplication::restoreOverrideCursor();
return -1;
}
if(m_pPolyhedron != NULL)
delete m_pPolyhedron;
// allocate new polyhedron
m_pPolyhedron = new Polyhedron;
in >> *m_pPolyhedron;
if(!in)
{
std::cerr << "invalid OFF file" << std::endl;
QApplication::restoreOverrideCursor();
delete m_pPolyhedron;
m_pPolyhedron = NULL;
return -1;
}
QApplication::restoreOverrideCursor();
return 0;
}
void Scene::update_bbox()
{
std::cout << "Compute bbox...";
m_bbox = Bbox();
if(m_pPolyhedron == NULL)
{
std::cout << "failed (no polyhedron)." << std::endl;
return;
}
if(m_pPolyhedron->empty())
{
std::cout << "failed (empty polyhedron)." << std::endl;
return;
}
Polyhedron::Point_iterator it = m_pPolyhedron->points_begin();
m_bbox = (*it).bbox();
for(; it != m_pPolyhedron->points_end();it++)
m_bbox = m_bbox + (*it).bbox();
std::cout << "done (" << m_pPolyhedron->size_of_facets()
<< " facets)" << std::endl;
}
void Scene::draw(Viewer* viewer)
{
if(!is_gl_init)
gl_init();
rendering_program.bind();
//setup mvp matrix
QMatrix4x4 mvp_matrix;
GLdouble mat[16];
viewer->camera()->getModelViewProjectionMatrix(mat);
for(int i=0; i<16; ++i)
mvp_matrix.data()[i] = (GLfloat)mat[i];
rendering_program.setUniformValue("mvp_matrix", mvp_matrix);
if(m_view_polyhedron){
rendering_program.setUniformValue("color", QColor(Qt::black));
render_polyhedron(viewer);
}
//draw points and lines
rendering_program.setUniformValue("color", QColor(Qt::darkBlue));
render_line(viewer);
rendering_program.setUniformValue("color", QColor(Qt::red));
render_plane(viewer);
rendering_program.setUniformValue("color", QColor(Qt::darkGreen));
render_centroid(viewer);
rendering_program.release();
}
void Scene::render_plane(Viewer* viewer)
{
Point o = m_plane.projection(m_centroid);
Point a = o + normalize(m_plane.base1()) + normalize(m_plane.base2());
Point b = o + normalize(m_plane.base1()) - normalize(m_plane.base2());
Point c = o - normalize(m_plane.base1()) - normalize(m_plane.base2());
Point d = o - normalize(m_plane.base1()) + normalize(m_plane.base2());
GLfloat verts[12];
verts[0]= a.x();verts[1]=a.y();verts[2]=a.z();
verts[3]= b.x();verts[4]=b.y();verts[5]=b.z();
verts[6]= c.x();verts[7]=c.y();verts[8]=c.z();
verts[9]= d.x();verts[10]=d.y();verts[11]=d.z();
vao[0].bind();
buffers[0].bind();
buffers[0].allocate(verts, 12*sizeof(GLfloat));
rendering_program.setAttributeBuffer("vertex", GL_FLOAT, 0,3);
rendering_program.enableAttributeArray("vertex");
buffers[0].release();
viewer->glDrawArrays(GL_LINE_LOOP, 0, 4);
vao[0].release();
}
void Scene::render_line(Viewer* viewer)
{
Point o = m_line.projection(m_centroid);
Point a = o + normalize(m_line.to_vector());
Point b = o - normalize(m_line.to_vector());
GLfloat verts[6];
verts[0]=a.x();verts[1]=a.y();verts[2]=a.z();
verts[3]=b.x();verts[4]=b.y();verts[5]=b.z();
vao[1].bind();
buffers[1].bind();
buffers[1].allocate(verts, 6*sizeof(GLfloat));
rendering_program.setAttributeBuffer("vertex", GL_FLOAT, 0,3);
rendering_program.enableAttributeArray("vertex");
buffers[1].release();
viewer->glDrawArrays(GL_LINES, 0, 2);
vao[1].release();
}
void Scene::render_centroid(Viewer* viewer)
{
GLfloat verts[3];
verts[0]=m_centroid.x();verts[1]=m_centroid.y();verts[2]=m_centroid.z();
vao[2].bind();
buffers[2].bind();
buffers[2].allocate(verts, 3*sizeof(GLfloat));
rendering_program.setAttributeBuffer("vertex", GL_FLOAT, 0,3);
rendering_program.enableAttributeArray("vertex");
buffers[2].release();
viewer->glDrawArrays(GL_POINTS, 0, 1);
vao[2].release();
}
Vector Scene::normalize(const Vector& v)
{
return v / std::sqrt(v*v);
}
void Scene::render_polyhedron(Viewer *viewer)
{
// draw black edges
if(m_pPolyhedron != NULL)
{
typedef Kernel::Point_3 Point;
std::vector<GLfloat> verts;
Polyhedron::Edge_iterator he;
for(he = m_pPolyhedron->edges_begin();
he != m_pPolyhedron->edges_end();
he++)
{
const Point& a = he->vertex()->point();
const Point& b = he->opposite()->vertex()->point();
verts.push_back(a.x());verts.push_back(a.y());verts.push_back(a.z());
verts.push_back(b.x());verts.push_back(b.y());verts.push_back(b.z());
}
vao[3].bind();
buffers[3].bind();
buffers[3].allocate(verts.data(), static_cast<int>(verts.size()*sizeof(GLfloat)));
rendering_program.setAttributeBuffer("vertex", GL_FLOAT, 0,3);
rendering_program.enableAttributeArray("vertex");
buffers[3].release();
viewer->glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(verts.size()/3));
vao[3].release();
}
}
void Scene::refine_loop()
{
if(m_pPolyhedron == NULL)
{
std::cout << "Load polyhedron first." << std::endl;
return;
}
std::cout << "Loop subdivision...";
CGAL::Subdivision_method_3::Loop_subdivision(*m_pPolyhedron);
std::cout << "done (" << m_pPolyhedron->size_of_facets() << " facets)" << std::endl;
}
void Scene::toggle_view_poyhedron()
{
m_view_polyhedron = !m_view_polyhedron;
}
void Scene::fit_triangles()
{
std::cout << "Fit triangles...";
std::list<Triangle> triangles;
Polyhedron::Facet_iterator it;
for(it = m_pPolyhedron->facets_begin();
it != m_pPolyhedron->facets_end();
it++)
{
Polyhedron::Halfedge_handle he = it->halfedge();
const Point& a = he->vertex()->point();
const Point& b = he->next()->vertex()->point();
const Point& c = he->next()->next()->vertex()->point();
Triangle triangle(a,b,c);
triangles.push_back(triangle);
}
m_centroid = CGAL::centroid(triangles.begin(),triangles.end());
CGAL::linear_least_squares_fitting_3(triangles.begin(),
triangles.end(), m_line, CGAL::Dimension_tag<2>());
CGAL::linear_least_squares_fitting_3(triangles.begin(),
triangles.end(), m_plane, CGAL::Dimension_tag<2>());
std::cout << "done" << std::endl;
}
void Scene::fit_edges()
{
std::cout << "Fit edges...";
std::list<Segment> segments;
Polyhedron::Edge_iterator he;
for(he = m_pPolyhedron->edges_begin();
he != m_pPolyhedron->edges_end();
he++)
{
const Point& a = he->vertex()->point();
const Point& b = he->opposite()->vertex()->point();
Segment segment(a,b);
segments.push_back(segment);
}
m_centroid = CGAL::centroid(segments.begin(),segments.end());
CGAL::linear_least_squares_fitting_3(segments.begin(),
segments.end(), m_line, CGAL::Dimension_tag<1>());
CGAL::linear_least_squares_fitting_3(segments.begin(),
segments.end(), m_plane, CGAL::Dimension_tag<1>());
std::cout << "done" << std::endl;
}
void Scene::fit_vertices()
{
std::cout << "Fit vertices...";
std::list<Point> points;
Polyhedron::Vertex_iterator v;
for(v = m_pPolyhedron->vertices_begin();
v != m_pPolyhedron->vertices_end();
v++)
{
const Point& p = v->point();
points.push_back(p);
}
m_centroid = CGAL::centroid(points.begin(),points.end());
CGAL::linear_least_squares_fitting_3(points.begin(),
points.end(), m_line, CGAL::Dimension_tag<0>());
CGAL::linear_least_squares_fitting_3(points.begin(),
points.end(), m_plane, CGAL::Dimension_tag<0>());
std::cout << "done" << std::endl;
}
void Scene::gl_init()
{
//Vertex source code
const char vertex_source[] =
{
"#version 120 \n"
"attribute highp vec4 vertex;\n"
"uniform highp mat4 mvp_matrix;\n"
"void main(void)\n"
"{\n"
" gl_PointSize = 10.0;\n"
" gl_Position = mvp_matrix * vertex;\n"
"}"
};
//Vertex source code
const char fragment_source[] =
{
"#version 120 \n"
"uniform highp vec4 color; \n"
"void main(void) { \n"
" gl_FragColor = color; \n"
"} \n"
"\n"
};
QOpenGLShader *vertex_shader = new QOpenGLShader(QOpenGLShader::Vertex);
if(!vertex_shader->compileSourceCode(vertex_source))
{
std::cerr<<"Compiling vertex source FAILED"<<std::endl;
}
QOpenGLShader *fragment_shader= new QOpenGLShader(QOpenGLShader::Fragment);
if(!fragment_shader->compileSourceCode(fragment_source))
{
std::cerr<<"Compiling fragmentsource FAILED"<<std::endl;
}
if(!rendering_program.addShader(vertex_shader))
{
std::cerr<<"adding vertex shader FAILED"<<std::endl;
}
if(!rendering_program.addShader(fragment_shader))
{
std::cerr<<"adding fragment shader FAILED"<<std::endl;
}
if(!rendering_program.link())
{
std::cerr<<"linking Program FAILED"<<std::endl;
}
for(int i=0; i< 4; ++i)
{
buffers[i].create();
vao[i].create();
}
is_gl_init = true;
}
| 27.173442 | 88 | 0.62581 | [
"vector"
] |
e75647ea8a4707e51da19a0f437e9911580dd9a7 | 1,378 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/world/geometry/DescriptionQuery.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/world/geometry/DescriptionQuery.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/world/geometry/DescriptionQuery.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/IScriptable.hpp>
#include <RED4ext/Scripting/Natives/Generated/Quaternion.hpp>
#include <RED4ext/Scripting/Natives/Generated/Vector4.hpp>
#include <RED4ext/Scripting/Natives/Generated/physics/QueryFilter.hpp>
namespace RED4ext
{
namespace world::geometry {
struct DescriptionQuery : IScriptable
{
static constexpr const char* NAME = "worldgeometryDescriptionQuery";
static constexpr const char* ALIAS = "GeometryDescriptionQuery";
Vector4 refPosition; // 40
Vector4 refDirection; // 50
Vector4 refUp; // 60
Vector4 primitiveDimension; // 70
Quaternion primitiveRotation; // 80
float maxDistance; // 90
float maxExtent; // 94
float raycastStartDistance; // 98
float probingPrecision; // 9C
float probingMaxDistanceDiff; // A0
uint8_t unkA4[0xA8 - 0xA4]; // A4
uint32_t maxProbes; // A8
uint8_t unkAC[0xB0 - 0xAC]; // AC
Vector4 probeDimensions; // B0
physics::QueryFilter filter; // C0
uint8_t unkD0[0xD4 - 0xD0]; // D0
uint32_t flags; // D4
uint8_t unkD8[0xE0 - 0xD8]; // D8
};
RED4EXT_ASSERT_SIZE(DescriptionQuery, 0xE0);
} // namespace world::geometry
using GeometryDescriptionQuery = world::geometry::DescriptionQuery;
} // namespace RED4ext
| 32.046512 | 72 | 0.727141 | [
"geometry"
] |
e757567cb7ddf26777790848498207118c1a5385 | 4,982 | cpp | C++ | example/BenchTest/main_reactor.cpp | fast01/chaosframework | 28194bcca5f976fd5cf61448ca84ce545e94d822 | [
"Apache-2.0"
] | 2 | 2020-04-16T13:20:57.000Z | 2021-06-24T02:05:25.000Z | example/BenchTest/main_reactor.cpp | fast01/chaosframework | 28194bcca5f976fd5cf61448ca84ce545e94d822 | [
"Apache-2.0"
] | null | null | null | example/BenchTest/main_reactor.cpp | fast01/chaosframework | 28194bcca5f976fd5cf61448ca84ce545e94d822 | [
"Apache-2.0"
] | null | null | null | /*
* ControlUnitTest.cpp
* !CHOAS
* Created by Bisegni Claudio.
*
* Copyright 2012 INFN, National Institute of Nuclear Physics
*
* 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 "BenchTestCU.h"
#include <chaos/common/chaos_constants.h>
#include <chaos/cu_toolkit/ChaosCUToolkit.h>
#include <iostream>
#include <string>
/*! \page page_benchtest_sd Bench Test Simulated Device
* \section page_benchtest_sd_sec This represent a simulated device for a bench test in !CHOAS
*
* \subsection page_example_cue_sec_sub1 Toolkit usage
* ChaosCUToolkit has private constructor so it can be used only using singleton pattern,
* the only way to get unique isntance is; ChaosCUToolkit::getInstance(). So the first call of
* getInstance method will provide the CUToolkit and Common layer initial setup.
* \snippet example/ControlUnitTest/ControlUnitExample.cpp Custom Option
*
* Then it must be initialized, in this method can be passed the main argument
* of a c or c++ programm
* \snippet example/ControlUnitTest/ControlUnitExample.cpp CUTOOLKIT Init
*
* At this point the custom implementation af a control unit cab be added to framework
* \snippet example/ControlUnitTest/ControlUnitExample.cpp Adding the CustomControlUnit
*
* At this step the framework can be started, it will perform all needs, comunicate with
* Metadata Server and all chaos workflow will start. The start method call will block the main execution
* until the chaos workflow of this isnstance need to be online
* \snippet example/ControlUnitTest/ControlUnitExample.cpp Starting the Framework
*/
using namespace std;
using namespace chaos;
using namespace chaos::cu;
#include <vector>
#include <string>
#include "config.h"
#include "Batch_Reactor.h"
int main (int argc, char* argv[] )
{
int64_t reactorsNumber = 0;
std::vector< std::string > names;
string tmpDeviceID("bench_reactor");
//initial state value
vector<double> stateOption;
try {
//! [Custom Option]
ChaosCUToolkit::getInstance()->getGlobalConfigurationInstance()->addOption(REACTOR_NAMES, po::value< std::vector< std::string > >()->multitoken(), "The name (and implicit the number) of the rectors");
ChaosCUToolkit::getInstance()->getGlobalConfigurationInstance()->addOption(OPT_START_STATE, po::value< std::vector<double> >()->multitoken(), "Initila condition for the Rector internal state");
//! [Custom Option]
//! [CUTOOLKIT Init]
ChaosCUToolkit::getInstance()->init(argc, argv);
//! [CUTOOLKIT Init]
//! [Adding the CustomControlUnit]
if(ChaosCUToolkit::getInstance()->getGlobalConfigurationInstance()->hasOption(REACTOR_NAMES)){
names = ChaosCUToolkit::getInstance()->getGlobalConfigurationInstance()->getOption< std::vector< std::string > >(REACTOR_NAMES);
reactorsNumber = names.size();
}
if(ChaosCUToolkit::getInstance()->getGlobalConfigurationInstance()->hasOption(OPT_START_STATE)){
stateOption = ChaosCUToolkit::getInstance()->getGlobalConfigurationInstance()->getOption< std::vector< double > >(OPT_START_STATE);
} else {
for (int i = 0; i < N; i++) {
stateOption.push_back(0.0);
}
}
//allocate the reactor isnstance
if(reactorsNumber >= 1) {
for (int idx1 = 0; idx1 < reactorsNumber; idx1++) {
Batch_Reactor *rInstance = new Batch_Reactor();
for (int idx2 = 0; idx2 < N; idx2++) {
rInstance->x[idx2] = stateOption[idx2];
}
ChaosCUToolkit::getInstance()->addControlUnit(new BenchTestCU(names[idx1], rInstance));
}
} else {
Batch_Reactor *rInstance = new Batch_Reactor();
for (int idx = 0; idx < N; idx++) {
rInstance->x[idx] = stateOption[idx];
}
ChaosCUToolkit::getInstance()->addControlUnit(new BenchTestCU(tmpDeviceID, rInstance));
}
//! [Adding the CustomControlUnit]
//! [Starting the Framework]
ChaosCUToolkit::getInstance()->start();
//! [Starting the Framework]
} catch (CException& e) {
std::cerr<< e.errorDomain << std::endl;
std::cerr<< e.errorMessage << std::endl;
}
return 0;
}
| 41.173554 | 208 | 0.661381 | [
"vector"
] |
e7582db07b11264ee47b1f602682c25fe71b7535 | 1,241 | cpp | C++ | Valid Mountain Array/solution cpp.cpp | LucasColas/Coding-Problems | a0d1f375fbde66c0d7d01f976a6c010c914939c1 | [
"Apache-2.0"
] | null | null | null | Valid Mountain Array/solution cpp.cpp | LucasColas/Coding-Problems | a0d1f375fbde66c0d7d01f976a6c010c914939c1 | [
"Apache-2.0"
] | null | null | null | Valid Mountain Array/solution cpp.cpp | LucasColas/Coding-Problems | a0d1f375fbde66c0d7d01f976a6c010c914939c1 | [
"Apache-2.0"
] | null | null | null | /*
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
From Leetcode : https://leetcode.com/problems/valid-mountain-array/
*/
class Solution {
public:
bool validMountainArray(vector<int>& arr) {
if (arr.size() < 3) {
return false;
}
int i = 0;
bool increase = false;
bool decrease = false;
while (i < arr.size() && (arr[i] < arr[i+1])) {
i++;
increase = true;
if (i == (arr.size()-1)) {
break;
}
}
while (i < arr.size() && (arr[i] > arr[i+1])) {
i++;
//cout << i << endl;
decrease = true;
if (i == (arr.size()-1)) {
break;
}
}
if ((i == (arr.size()-1)) && increase && decrease) {
return true;
}
return false;
}
};
| 22.981481 | 88 | 0.42224 | [
"vector"
] |
e758f610cd3404626f5b4966178bb0af02961685 | 6,188 | cpp | C++ | code/engine.vc2008/xrGame/stalker_animation_manager_update.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/engine.vc2008/xrGame/stalker_animation_manager_update.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/engine.vc2008/xrGame/stalker_animation_manager_update.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2020-06-26T11:41:44.000Z | 2021-09-29T19:35:04.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : stalker_animation_manager_update.cpp
// Created : 25.02.2003
// Modified : 13.12.2006
// Author : Dmitriy Iassenev
// Description : Stalker animation manager update cycle
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "stalker_animation_manager.h"
#include "ai/stalker/ai_stalker.h"
#include "game_object_space.h"
#include "script_callback_ex.h"
#include "../xrEngine/profiler.h"
#include "stalker_movement_manager_smart_cover.h"
void CStalkerAnimationManager::play_delayed_callbacks ()
{
if (m_call_script_callback) {
m_call_script_callback = false;
object().callback (GameObject::eScriptAnimation) ();
return;
}
if (m_call_global_callback) {
m_call_global_callback = false;
if (m_global_callback)
m_global_callback ();
return;
}
}
IC bool CStalkerAnimationManager::script_callback () const
{
if (script_animations().empty())
return (false);
return (object().callback(GameObject::eScriptAnimation));
}
IC bool CStalkerAnimationManager::need_update () const
{
if (script_callback())
return (true);
return (non_script_need_update());
}
IC void CStalkerAnimationManager::update_tracks ()
{
if (!need_update())
return;
m_skeleton_animated->UpdateTracks ();
}
#ifdef USE_HEAD_BONE_PART_FAKE
IC void CStalkerAnimationManager::play_script_impl ()
{
clear_unsafe_callbacks ();
global().reset ();
torso().reset ();
legs().reset ();
const CStalkerAnimationScript &selected = assign_script_animation();
script().animation (selected.animation());
if (selected.use_movement_controller()) {
script().target_matrix (selected.transform(object()));
if ( m_start_new_script_animation ) {
m_start_new_script_animation = false;
if ( selected.has_transform() && object().animation_movement( ) )
object().destroy_anim_mov_ctrl ( );
}
}
script().play (
m_skeleton_animated,
script_play_callback,
selected.use_movement_controller(),
selected.local_animation(),
false,
m_script_bone_part_mask
);
head().animation (assign_head_animation());
head().play (m_skeleton_animated,head_play_callback,false,false);
}
#else // USE_HEAD_BONE_PART_FAKE
IC void CStalkerAnimationManager::play_script_impl ()
{
clear_unsafe_callbacks ();
global().reset ();
head().reset ();
torso().reset ();
legs().reset ();
const CStalkerAnimationScript &selected = assign_script_animation();
script().animation (selected.animation());
script().play (
m_skeleton_animated,
script_play_callback,
selected.use_movement_controller(),
selected.local_animation(),
false,
m_script_bone_part_mask
);
}
#endif // USE_HEAD_BONE_PART_FAKE
bool CStalkerAnimationManager::play_script ()
{
if (script_animations().empty()) {
m_start_new_script_animation = false;
script().reset ();
return (false);
}
play_script_impl ();
return (true);
}
#ifdef USE_HEAD_BONE_PART_FAKE
IC void CStalkerAnimationManager::play_global_impl (const MotionID &animation, bool const &animation_movement_controller)
{
torso().reset ();
legs().reset ();
global().animation (animation);
global().play (
m_skeleton_animated,
global_play_callback,
animation_movement_controller,
true,
false,
m_script_bone_part_mask,
true
);
if (m_global_modifier)
m_global_modifier (global().blend());
head().animation (assign_head_animation());
head().play (m_skeleton_animated,head_play_callback,false,false);
}
#else // USE_HEAD_BONE_PART_FAKE
IC void CStalkerAnimationManager::play_global_impl (const MotionID &animation, bool const &animation_movement_controller)
{
head().reset ();
torso().reset ();
legs().reset ();
global().animation (animation);
global().play (m_skeleton_animated,global_play_callback,false,false,false);
}
#endif // USE_HEAD_BONE_PART_FAKE
bool CStalkerAnimationManager::play_global ()
{
bool animation_movement_controller = false;
const MotionID &global_animation = assign_global_animation(animation_movement_controller);
if (!global_animation) {
clear_unsafe_callbacks ();
global().reset ();
return (false);
}
play_global_impl (global_animation, animation_movement_controller);
return (true);
}
IC void CStalkerAnimationManager::play_head ()
{
head().animation (assign_head_animation());
head().play (m_skeleton_animated,head_play_callback,false,false);
}
IC void CStalkerAnimationManager::play_torso ()
{
torso().animation (assign_torso_animation());
torso().play (m_skeleton_animated,torso_play_callback,false,false);
}
void CStalkerAnimationManager::play_legs ()
{
float speed = 0.f;
bool first_time = !legs().animation();
bool result = legs().animation(assign_legs_animation());
if (!first_time && !result && legs().blend()) {
float amount = legs().blend()->blendAmount;
m_previous_speed = (m_target_speed - m_previous_speed)*amount + m_previous_speed;
}
legs().play (m_skeleton_animated,legs_play_callback,false,false,!fis_zero(m_target_speed));
if (result && legs().blend()) {
float amount = legs().blend()->blendAmount;
speed = (m_target_speed - m_previous_speed)*amount + m_previous_speed;
}
if (fis_zero(speed))
return;
if (!legs().blend())
return;
object().movement().setup_speed_from_animation (speed);
}
void CStalkerAnimationManager::update_impl ()
{
if (!object().g_Alive())
return;
update_tracks ();
play_delayed_callbacks ();
if (play_script())
return;
if (play_global())
return;
play_head ();
play_torso ();
play_legs ();
torso().synchronize (m_skeleton_animated,m_legs);
}
void CStalkerAnimationManager::update ()
{
START_PROFILE("stalker/client_update/animations")
try
{
update_impl();
}
// The infamous 'error in stalker with visual' related issues can be averted by resetting
catch(...)
{
Msg("! error in stalker with visual %s and ID %s",*object().cNameVisual(),object().ID());
head().reset();
torso().reset();
legs().reset();
global().reset();
return;
}
STOP_PROFILE
}
| 24.555556 | 123 | 0.698933 | [
"object",
"transform"
] |
e75b9cdbe53a26c0b3fff99bc41b98f6fa291f76 | 1,099 | cpp | C++ | Algorithm/log jumping/jump.cpp | dkswnkk/DongA-Univ | 078866eef9187b319b85194c488ec44512764a36 | [
"MIT"
] | null | null | null | Algorithm/log jumping/jump.cpp | dkswnkk/DongA-Univ | 078866eef9187b319b85194c488ec44512764a36 | [
"MIT"
] | null | null | null | Algorithm/log jumping/jump.cpp | dkswnkk/DongA-Univ | 078866eef9187b319b85194c488ec44512764a36 | [
"MIT"
] | null | null | null | // Copyright © 2021 안주형. All rights reserved.
// https://github.com/dkswnkk
// 2021학년 동아대학교 알고리즘과목 과제
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
freopen("jump.inp", "r", stdin);
freopen("jump.out", "w", stdout);
int T; cin>>T;
while(T--){
int n,ans=0; cin>>n;
vector<int>v;
for(int i=0; i<n; i++){
int inp; cin>>inp;
v.push_back(inp);
}
sort(v.begin(),v.end());
deque<int> dq;
int max_value;
for(int i=v.size()-1; i>=0; i--){
max_value = v[i];
if(i&1) dq.push_back(max_value);
else dq.push_front(max_value);
}
ans=max(abs(dq[0]-dq[dq.size()-1]),abs(dq[dq.size()-1]-dq[dq.size()-2]));
for(int i=1; i<dq.size()-1; i++){
ans=max(abs(dq[i]-dq[i-1]),max(abs(dq[i]-dq[i+1]),ans));
}
cout<<ans<<'\n';
}
}
| 21.54902 | 81 | 0.465878 | [
"vector"
] |
e75eeed8870c839ad9f5b2d9b8fee2f058d4e647 | 5,246 | hpp | C++ | include/pkmn/pokemon_box.hpp | ncorgan/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 4 | 2017-06-10T13:21:44.000Z | 2019-10-30T21:20:19.000Z | include/pkmn/pokemon_box.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 12 | 2017-04-05T11:13:34.000Z | 2018-06-03T14:31:03.000Z | include/pkmn/pokemon_box.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 2 | 2019-01-22T21:02:31.000Z | 2019-10-30T21:20:20.000Z | /*
* Copyright (c) 2016,2018 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#ifndef PKMN_POKEMON_BOX_HPP
#define PKMN_POKEMON_BOX_HPP
#include <pkmn/config.hpp>
#include <pkmn/pokemon.hpp>
#include <pkmn/enums/game.hpp>
#include <memory>
#include <string>
#include <vector>
namespace pkmn
{
/*!
* @brief A list of the Pokémon a trainer stores in a PC box.
*
* This class is an abstraction of the different in-game representations of
* a Pokémon box throughout the different games, providing a common API
* for interacting with the box.
*/
class PKMN_API pokemon_box
{
public:
/*!
* @brief The actual interface for using the pokemon_box class.
*
* The pokemon_box class itself is abstract and thus cannot be
* used directly.
*/
typedef std::shared_ptr<pokemon_box> sptr;
/*!
* @brief The factory function for instantiating a Pokémon box.
*
* This function uses the game to determine which underlying
* representation to use. This function will fail if given an
* invalid game.
*
* \param game Which game the box corresponds to
* \throws std::invalid_argument If the given game is invalid
*/
static sptr make(pkmn::e_game game);
/*!
* @brief Returns this box's name.
*
* Box names were only supported in Generation II, so this call
* will fail for Generation I boxes.
*
* \throws pkmn::feature_not_in_game_error If the box is from a Generation I game
*/
virtual std::string get_name() = 0;
/*!
* @brief Sets this box's name.
*
* Valid box names are of length [1-8].
*
* Box names were only supported in Generation II, so this call
* will fail for Generation I boxes.
*
* \param name The new name for the box
* \throws std::invalid_argument If the box name is not of length [1-8]
* \throws pkmn::feature_not_in_game_error If the box is from a Generation I game
*/
virtual void set_name(
const std::string& name
) = 0;
/*!
* @brief Returns the game this box comes from.
*/
virtual pkmn::e_game get_game() = 0;
/*!
* @brief Returns the number of Pokémon in this box.
*
* This number will always be of length [0-capacity].
*/
virtual int get_num_pokemon() = 0;
/*!
* @brief Returns the number of Pokémon this box can hold.
*/
virtual int get_capacity() = 0;
/*!
* @brief Returns the Pokémon at the given position (0-based).
*
* \param index The position on the box whose Pokémon to return
* \throws std::out_of_range If index is not in the range [0-5]
*/
virtual const pkmn::pokemon::sptr& get_pokemon(
int index
) = 0;
/*!
* @brief Copies the given Pokémon to the given position in the box (0-based).
*
* If the given Pokémon is not from the same game as the box, LibPKMN
* will attempt to convert the Pokémon to the given game, and this
* converted Pokémon will be added.
*
* In Generations I-II, Pokémon in boxes are stored contiguously, so
* attempting to place a Pokémon in a position past this point will result
* in an error.
*
* \param index The position on the team where to copy the Pokémon
* \param new_pokemon The Pokémon to add to the box
* \throws std::out_of_range If the index is outside the range [0-num_pokemon)
* for Generation I-II boxes
* \throws std::out_of_range If the index is outside the range [0-capacity)
* \throws std::invalid_argument If the new Pokémon is incompatible with the box's game
*/
virtual void set_pokemon(
int index,
const pkmn::pokemon::sptr& new_pokemon
) = 0;
virtual std::string get_wallpaper() = 0;
virtual void set_wallpaper(
const std::string& wallpaper
) = 0;
/*!
* @brief Returns a vector representation of the Pokémon box.
*/
virtual const pkmn::pokemon_list_t& as_vector() = 0;
#ifndef __DOXYGEN__
pokemon_box() {}
virtual ~pokemon_box() {}
virtual void* get_native() = 0;
#endif
};
typedef std::vector<pkmn::pokemon_box::sptr> pokemon_box_list_t;
}
#endif /* PKMN_POKEMON_BOX_HPP */
| 34.973333 | 99 | 0.542509 | [
"vector"
] |
e75f6b27e1c0d2deeff72c90b8866605f024f38a | 3,982 | cxx | C++ | icetray/private/icetray/I3ConditionalModule.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 1 | 2020-12-24T22:00:01.000Z | 2020-12-24T22:00:01.000Z | icetray/private/icetray/I3ConditionalModule.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | null | null | null | icetray/private/icetray/I3ConditionalModule.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 3 | 2020-07-17T09:20:29.000Z | 2021-03-30T16:44:18.000Z | /**
* $Id: I3ConditionalModule.cxx 168811 2017-05-10 01:00:15Z olivas $
*
* Copyright (C) 2007
* Troy D. Straszheim <troy@icecube.umd.edu>
* Phil Roth <proth@icecube.umd.edu>
* and the IceCube Collaboration <http://www.icecube.wisc.edu>
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
#include "icetray/I3ConditionalModule.h"
#include "icetray/I3Context.h"
#include "icetray/impl.h"
I3ConditionalModule::I3ConditionalModule(const I3Context& context) :
I3Module(context)
{
i3_log("%s", __PRETTY_FUNCTION__);
AddParameter("IcePickServiceKey",
"Key for an IcePick in the context that this module should check "
"before processing physics frames.",
"");
AddParameter("If",
"A python function... if this returns something that evaluates to True,"
" Module runs, else it doesn't",
if_);
i3_log("if_=%p", if_.ptr());
}
I3ConditionalModule::~I3ConditionalModule() { }
void I3ConditionalModule::Configure_()
{
i3_log("%s", __PRETTY_FUNCTION__);
boost::python::object configured_if_;
GetParameter("If", configured_if_);
i3_log("configured_if_=%p", configured_if_.ptr());
if (if_.ptr() != configured_if_.ptr()) // user set the parameter to something
{
i3_log("user passed us something");
if (!PyCallable_Check(configured_if_.ptr()))
log_fatal("'If' parameter to module %s must be a callable object", GetName().c_str());
else
{
i3_log("user passed us something and it is a PyFunction");
if_ = configured_if_;
use_if_ = true;
}
}
else // got nothing from user
use_if_ = false;
boost::python::object obj;
i3_log("(%s) Configuring the Conditional Module stuff.",GetName().c_str());
std::string pickKey;
GetParameter("IcePickServiceKey",pickKey);
use_pick_ = false;
if(pickKey != "")
{
if (use_if_)
log_fatal("Please specify either IcePickServiceKey or If, but not both");
i3_log("Looking for pick %s in the context.",pickKey.c_str());
pick_ = GetContext().Get<I3IcePickPtr>(pickKey);
if(!pick_)
log_fatal("IcePick %s was not found in the context. "
"Did you install it?",pickKey.c_str());
else
use_pick_ = true;
}
// bounce this guy back to I3Module, which will in turn bounce to whoever derives
// from us
I3Module::Configure_(); // this also adds a default OutBox
}
bool I3ConditionalModule::ShouldDoProcess(I3FramePtr frame)
{
i3_log("%s", __PRETTY_FUNCTION__);
// For all frame types except DAQ and Physics, the answer is always yes
if (frame->GetStop() != I3Frame::DAQ && frame->GetStop() != I3Frame::Physics)
return true;
i3_log("use_if_=%d", use_if_);
if (use_if_)
{
boost::python::object rv = if_(frame);
bool flag = boost::python::extract<bool>(rv);
if (flag)
++nexecuted_;
else
++nskipped_;
i3_log("ShouldDoProcess == %d", flag);
return flag;
}
if(use_pick_)
{
i3_log("Sending frame to our IcePick.");
bool flag = pick_->SelectFrameInterface(*frame);
if (flag)
++nexecuted_;
else
++nskipped_;
i3_log("ShouldDoPhysics == %d", flag);
return flag;
}
i3_log("%s", "No conditional execution.");
++nexecuted_;
i3_log("%s", "ShouldDoPhysics == true");
return true;
}
| 29.716418 | 94 | 0.654696 | [
"object"
] |
e760c06f5d33657cdf431d2291f0e101e3c2652d | 933 | cpp | C++ | CodeForces/Beautiful Matrix.cpp | abdelrahman0123/Problem-Solving | 9d40ed9adb6e6d519dc53f676b6dd44ca15ee70b | [
"MIT"
] | null | null | null | CodeForces/Beautiful Matrix.cpp | abdelrahman0123/Problem-Solving | 9d40ed9adb6e6d519dc53f676b6dd44ca15ee70b | [
"MIT"
] | null | null | null | CodeForces/Beautiful Matrix.cpp | abdelrahman0123/Problem-Solving | 9d40ed9adb6e6d519dc53f676b6dd44ca15ee70b | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <string.h>
#include <cmath>
#include <ctype.h>
#include <cstdio>
#include <stdio.h>
#include <cstdlib>
#include <conio.h>
#include <ctime>
using namespace std;
void find_index(int arr[][5], int& a, int& b) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (arr[i][j] == 1) {
a = i;
b = j;
return;
}
}
}
}
int main() {
int arr[5][5];
int x, y, n;
n = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cin >> arr[i][j];
}
}
find_index(arr, x, y);
if (x <= 2) {
while (x != 2) {
x++;
n++;
}
}
else {
while (x != 2) {
x--;
n++;
}
}
if (y <= 2) {
while (y != 2) {
y++;
n++;
}
}
else {
while (y != 2) {
y--;
n++;
}
}
cout << n << endl;
}
| 14.809524 | 48 | 0.433012 | [
"vector"
] |
e76223f0b9bd250cc03d51eb038ef14184a9ff5b | 9,674 | cpp | C++ | tests/test_knn/knn_test.cpp | rafael-radkowski/TrackingExpert- | 007310637e1582d9623e518510d5d9eccaa23c2c | [
"MIT"
] | 26 | 2020-02-28T06:20:36.000Z | 2021-12-09T09:52:06.000Z | tests/test_knn/knn_test.cpp | rafael-radkowski/TrackingExpert- | 007310637e1582d9623e518510d5d9eccaa23c2c | [
"MIT"
] | 6 | 2020-02-19T15:04:27.000Z | 2021-08-15T20:32:08.000Z | tests/test_knn/knn_test.cpp | rafael-radkowski/TrackingExpert- | 007310637e1582d9623e518510d5d9eccaa23c2c | [
"MIT"
] | 5 | 2020-07-09T18:58:34.000Z | 2021-08-16T00:40:06.000Z | /*
@file knn_test.cpp
This file tests the kd-tree and the k-nearest neighbors methods.
The kd-tree is a cuda implementation. The test compares the cuda implementation (O( n log(n) )
vs. a naive O(n^2) implementation.
The test runs multiple times with different random datasets.
Note that error < 4% can be expected. The cuda version stops to backtrack adjacent
branches at one point to increase performance. Also, it uses a Radix sort with integers,
and the conversion results in inaccuracies that yield some errors.
The kd-tree was develop with point clouds in mind, so the camera tolerances introduce larger errors.
Rafael Radkowski
Iowa State University
rafael@iastate.edu
January 2020
MIT License
-----------------------------------------------------------------------------------------------------------------------------
Last edited:
July 7, 2020, RR
- Added a function to test the radius search.
*/
// STL
#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>
#include <thread>
#include <mutex>
#include <cmath>
// GLM include files
#define GLM_FORCE_INLINE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp> // transformation
#include <glm/gtx/quaternion.hpp> // quaternions
// TrackingExpert
#include "trackingx.h"
#include "graphicsx.h"
#include "ReaderWriterOBJ.h"
#include "ReaderWriterPLY.h"
#include "Cuda_KdTree.h" // the ICP class to test
#include "KNN.h"
#include "RandomGenerator.h"
using namespace texpert;
//-------------------------------------------------------------
// The knn tool
KNN* knn;
PointCloud cameraPoints0;
PointCloud cameraPoints1;
std::vector<MyMatches> matches0;
std::vector<MyMatches> matches1;
/*
Function to generate random point clouds and normal vectors. Note that the normal vectors are just
points.
@param pc - reference to the location for the point cloud.
@param num_points - number of points to generatel
@param min, max - the minimum and maximum range of the points.
*/
void GenerateRandomPointCloud( PointCloud& pc, int num_points, float min = -2.0, float max = 2.0)
{
pc.points.clear();
pc.normals.clear();
for (int i = 0; i < num_points; i++) {
vector<float> p = RandomGenerator::FloatPosition(min, max);
pc.points.push_back(Eigen::Vector3f(p[0], p[1], p[2]));
pc.normals.push_back(Eigen::Vector3f(p[0], p[1], p[2]));
}
pc.size();
}
/*
Calculate the distance between two points.
@param p0 - the first point as Eigen Vector3f (x, y, z)
@param p1 - the second point as Eigen Vector3f (x, y, z)
@return - the distance as float.
*/
float Distance(Eigen::Vector3f p0, Eigen::Vector3f p1) {
return std::sqrt( std::pow( p0.x() - p1.x(),2) + std::pow( p0.y() - p1.y(),2) + std::pow( p0.z() - p1.z(),2));
}
/*
Find the nearest neighbors between a search point set and a second one. For each point in pc_search, the function output a
nearest neighbor from pc_cam.
@param pc_search - the search point cloud
@param pc_cam - the other point clud
@param k - currently not in use.
@param matches - a location to store the matches.
*/
bool FindKNN_Naive(PointCloud& pc_search, PointCloud& pc_cam, int k, std::vector<MyMatches>& matches)
{
int s = pc_search.size();
int p = pc_cam.size();
matches.clear();
matches.resize(s);
for (int i = 0; i < s; i++) {
float min_distance = 10000000.00;
int min_idx = -1;
for (int j = 0; j < p; j++) {
float d = Distance(pc_search.points[i], pc_cam.points[j]);
if ( d < min_distance) {
min_distance = d;
min_idx = j;
}
}
matches[i].matches[0].first = i;
matches[i].matches[0].second = min_idx;
matches[i].matches[0].distance = min_distance;
}
return true;
}
/*
Compare two set of matches. For each search point, the naive method and the kd-tree should
find the identical match. Thus, the function compares the point indices and reports an error,
if the point-pairs do not match.
@param matches0 - the location with the first set of matches
@param matches1 - the location with the second set of matches.
*/
int CompareMatches(std::vector<MyMatches>& matches0, std::vector<MyMatches>& matches1)
{
int s0 = matches0.size();
int s1 = matches1.size();
if (s0 != s1) {
std::cout << "Error - matches have not the same size " << s0 << " to " << s1 << endl;
}
int error_count = 0;
for (int i = 0; i < s0; i++) {
if (matches0[i].matches[0].second != matches1[i].matches[0].second) {
//std::cout << "Found error for i = " << i << " with gpu " << matches0[i].matches[0].second << " and naive " << matches1[i].matches[0].second << " with distance " << matches0[i].matches[0].distance << " and " << matches1[i].matches[0].distance * matches1[i].matches[0].distance << std::endl;
error_count++;
}
}
float error_percentage = float(error_count)/float(s0) * 100.0;
std::cout << "[INFO] - Found " << error_count << " in total (" << error_percentage << "%)" << std::endl;
// When working with the kd-tree, some minor errors can be expected. Those are the result of a integer conversion, the tree
// works with a Radix search. Also, the tree does not backtrack into adjacent branches indefinitely.
// The error does not matter when working with point cloud data from cameras, since the camera tolerances yield larger variances.
// The error was never larger than 5%. If you encounter a larger error, this requires furter investigation but may not point to a bug, etc.
if (error_percentage > 5.0) {
std::cout << "[ERROR] - The last run yielded an error > 5% with " << error_percentage << "%. That is higher than expected." << std::endl;
}
return error_count;
}
/*
Run the test.
The function runs the test.
*/
int RunTest(int num_points, float min_range, float max_range) {
// generate two set of random point clouds.
GenerateRandomPointCloud( cameraPoints0, num_points, min_range, max_range);
GenerateRandomPointCloud( cameraPoints1, num_points, min_range, max_range);
matches0.clear();
matches1.clear();
// populate the kd-tree
knn->reset();
knn->populate(cameraPoints0);
// search for the neaarest neighbors
knn->knn(cameraPoints1,1,matches0);
// run the naive knn method.
FindKNN_Naive(cameraPoints1, cameraPoints0, 1, matches1);
// compare the results
return CompareMatches( matches0, matches1);
}
int RunRadiusTest(int num_points, int num_serach_points, float min_range, float max_range, float search_radius) {
// generate two set of random point clouds.
GenerateRandomPointCloud( cameraPoints0, num_points, min_range, max_range);
GenerateRandomPointCloud( cameraPoints1, num_serach_points, min_range, max_range);
matches0.clear();
matches1.clear();
// populate the kd-tree
knn->reset();
knn->populate(cameraPoints0);
// search for the neaarest neighbors
knn->radius(cameraPoints1,search_radius,matches0);
int error_count = 0;
int print = 0;
for (int i = 0; i < matches0.size(); i++) {
MyMatches m = matches0[i];
for (int j = 0; j < 21; j++) {
if( m.matches[j].distance > 0.0){
if(m.matches[j].distance > search_radius*search_radius){
error_count++;
if(print < 100){
std::cout << "[ERROR] " << m.matches[j].second << ": distance: " << m.matches[j].distance << std::endl;
print++;
}
}
}
}
}
if (error_count == 0) {
std::cout << "[INFO] - Found " << error_count << ", all distances are within the margin of " << search_radius << "." << std::endl;
}
else
{
std::cout << "[ERROR] - Found " << error_count << " points which exceeds the distance of " << search_radius << "." << std::endl;
}
return matches0.size();
}
int main(int argc, char** argv)
{
std::cout << "KNN Test.\n" << std::endl;
std::cout << "This application implements a k-nearest neighbors test using a kd-tree." << std::endl;
std::cout << "The kd-tree uses cuda to construct the tree and to find nearest neighbors. " << std::endl;
std::cout << "The test compares the kd-tree solution with a naive solution. \nThe application runs 17 test in 3-stages, using different data set complexities.\n" << std::endl;
std::cout << "Rafael Radkowski\nIowa State University\nrafael@iastate.edu" << std::endl;
std::cout << "-----------------------------------------------------------------------------------------\n" << std::endl;
// create the knn
knn = new KNN();
//-------------------------------------------------
// First test round
std::cout << "[Info] 1. Testing with the same points." << endl;
// generate
GenerateRandomPointCloud( cameraPoints0, 100);
// KNN
knn->populate(cameraPoints0);
knn->knn(cameraPoints0,1,matches0);
// naive
FindKNN_Naive(cameraPoints0, cameraPoints0, 1, matches1);
// compare
CompareMatches( matches0, matches1);
//-------------------------------------------------
// Second test round
std::cout << "\n[Info] 2. Testing with different points." << endl;
// generate
GenerateRandomPointCloud( cameraPoints1, 100);
knn->knn(cameraPoints1,1,matches0);
// naive
FindKNN_Naive(cameraPoints1, cameraPoints0, 1, matches1);
// compare
CompareMatches( matches0, matches1);
//-------------------------------------------------
// Third test round
std::cout << "\n[Info] 3. Testing with different points and increased point size." << endl;
for(int i = 0; i< 15; i++){
int k = 10000;
RunTest( k, -1.0, 1.0);
}
//-------------------------------------------------
// Run a radius test
std::cout << "\n[Info] 4. Run a radius search test." << endl;
for(int i = 0; i< 15; i++){
float radius = 0.1 * i + 0.1;
float max = i * 1.0;
RunRadiusTest(10000, 2000, -max, max, radius);
}
RunRadiusTest(10000, 2000, -15.0, 15.0, 1.5);
delete knn;
}
| 28.536873 | 295 | 0.65154 | [
"vector",
"transform"
] |
e76b8e69ecb58c1b7eb8c312472bf46011324734 | 10,400 | cpp | C++ | src/openms/source/ANALYSIS/ID/PILISScoring.cpp | aiche/OpenMS | 5d212db863ff1ef48b3a70fe4d556ef179ae4f49 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/ANALYSIS/ID/PILISScoring.cpp | aiche/OpenMS | 5d212db863ff1ef48b3a70fe4d556ef179ae4f49 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/ANALYSIS/ID/PILISScoring.cpp | aiche/OpenMS | 5d212db863ff1ef48b3a70fe4d556ef179ae4f49 | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
//
#include <OpenMS/ANALYSIS/ID/PILISScoring.h>
#include <OpenMS/MATH/STATISTICS/LinearRegression.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
using namespace std;
namespace OpenMS
{
PILISScoring::PILISScoring() :
DefaultParamHandler("PILISScoring")
{
defaults_.setValue("use_local_scoring", 1, "If set to 1, a E-Value of an identification run of one spectrum is used additionally");
defaults_.setValue("survival_function_bin_size", 20, "Bin size of the survival function", ListUtils::create<String>("advanced"));
defaults_.setValue("global_linear_fitting_threshold", 0.1, "Fitting threshold of the survival function of the global E-Value calculation", ListUtils::create<String>("advanced"));
defaults_.setValue("local_linear_fitting_threshold", 0.5, "Fitting threshold of the survival function of the local E-Value calculation", ListUtils::create<String>("advanced"));
defaults_.setValue("score_default_value", 10e10, "If no score can be assigned use this one", ListUtils::create<String>("advanced"));
defaultsToParam_();
}
PILISScoring::PILISScoring(const PILISScoring & rhs) :
DefaultParamHandler(rhs)
{
}
PILISScoring & PILISScoring::operator=(const PILISScoring & rhs)
{
if (this != &rhs)
{
DefaultParamHandler::operator=(rhs);
}
return *this;
}
PILISScoring::~PILISScoring()
{
}
void PILISScoring::getScore(PeptideIdentification & id)
{
if (id.getHits().empty())
{
return;
}
if (id.getHits().size() > 2)
{
vector<double> scores;
vector<PeptideHit>::const_iterator it = id.getHits().begin();
for (++it; it != id.getHits().end(); ++it)
{
scores.push_back(it->getScore());
}
double slope(0);
double intercept(0);
getFitParameter_(slope, intercept, scores, (double)param_.getValue("local_linear_fitting_threshold"));
if (slope != 0 && intercept != 0)
{
id.setScoreType("PILIS-E-value");
vector<PeptideHit> tmp_hits = id.getHits();
for (vector<PeptideHit>::iterator it = tmp_hits.begin(); it != tmp_hits.end(); ++it)
{
double evalue = exp(intercept + slope * log(it->getScore()));
it->setScore(evalue);
}
id.setHits(tmp_hits);
}
}
}
void PILISScoring::getScores(vector<PeptideIdentification> & ids)
{
// get all but the first scores
vector<double> global_scores;
for (vector<PeptideIdentification>::const_iterator it = ids.begin(); it != ids.end(); ++it)
{
if (it->getHits().empty())
{
break;
}
vector<PeptideHit>::const_iterator it1 = it->getHits().begin();
for (++it1; it1 != it->getHits().end(); ++it1)
{
global_scores.push_back(it1->getScore());
}
}
// get the fit parameter for the global survival function
double global_slope = 0;
double global_intercept = 0;
getFitParameter_(global_slope, global_intercept, global_scores, (double)param_.getValue("global_linear_fitting_threshold"));
// annotate the ProteinIdentification with both scores (global and single identification)
for (vector<PeptideIdentification>::iterator it = ids.begin(); it != ids.end(); ++it)
{
getScore_(*it, global_slope, global_intercept);
}
return;
}
void PILISScoring::getScore_(PeptideIdentification & id, double global_slope, double global_intercept)
{
if (id.getHits().empty())
{
return;
}
bool use_local_scoring(true);
if ((Size)param_.getValue("use_local_scoring") == 0)
{
use_local_scoring = false;
}
// if possible and allowed using local scoring
if (id.getHits().size() > 2 && use_local_scoring)
{
vector<double> scores;
vector<PeptideHit>::const_iterator it = id.getHits().begin();
for (++it; it != id.getHits().end(); ++it)
{
scores.push_back(it->getScore());
}
double slope(0);
double intercept(0);
getFitParameter_(slope, intercept, scores, (double)param_.getValue("local_linear_fitting_threshold"));
if (slope != 0 && intercept != 0)
{
id.setScoreType("PILIS-E-value");
vector<PeptideHit> tmp_hits = id.getHits();
for (vector<PeptideHit>::iterator it = tmp_hits.begin(); it != tmp_hits.end(); ++it)
{
double local_evalue = exp(intercept + slope * log(it->getScore()));
double global_evalue = exp(global_intercept + global_slope * log(it->getScore()));
it->setScore(local_evalue + global_evalue);
}
id.setHits(tmp_hits);
}
else
{
double score_default_value = (double)param_.getValue("score_default_value");
id.setScoreType("PILIS-E-value");
vector<PeptideHit> tmp_hits = id.getHits();
for (vector<PeptideHit>::iterator it = tmp_hits.begin(); it != tmp_hits.end(); ++it)
{
it->setScore(score_default_value);
}
id.setHits(tmp_hits);
}
}
else
{
if (global_intercept != 0 && global_slope != 0)
{
id.setScoreType("PILIS-E-value");
vector<PeptideHit> tmp_hits = id.getHits();
for (vector<PeptideHit>::iterator it = tmp_hits.begin(); it != tmp_hits.end(); ++it)
{
it->setScore(exp(global_intercept + global_slope * log(it->getScore())));
}
id.setHits(tmp_hits);
}
else
{
double score_default_value = (double)param_.getValue("score_default_value");
id.setScoreType("PILIS-E-value");
vector<PeptideHit> tmp_hits = id.getHits();
for (vector<PeptideHit>::iterator it = tmp_hits.begin(); it != tmp_hits.end(); ++it)
{
it->setScore(score_default_value);
}
id.setHits(tmp_hits);
}
}
}
void PILISScoring::getFitParameter_(double & slope, double & intercept, const vector<double> & scores, double threshold)
{
slope = 0;
intercept = 0;
double survival_function_bin_size = (double)param_.getValue("survival_function_bin_size");
Map<UInt, double> score_dist_discrete;
for (vector<double>::const_iterator it = scores.begin(); it != scores.end(); ++it)
{
UInt bin = (UInt)((*it) * survival_function_bin_size);
if (score_dist_discrete.has(bin))
{
score_dist_discrete[bin] += 1;
}
else
{
score_dist_discrete[bin] = 1;
}
}
vector<DPosition<2> > survival_function;
getSurvivalFunction_(score_dist_discrete, survival_function);
// fit the high scoring part of the survival function linearly
vector<double> x_values;
vector<double> y_values;
for (vector<DPosition<2> >::const_iterator sit = survival_function.begin(); sit != survival_function.end(); ++sit)
{
if (sit->getY() < threshold)
{
x_values.push_back(log(sit->getX()));
y_values.push_back(log(sit->getY()));
}
}
Math::LinearRegression lin_reg;
if (x_values.size() > 2)
{
lin_reg.computeRegression(0.95, x_values.begin(), x_values.end(), y_values.begin());
slope = lin_reg.getSlope();
intercept = lin_reg.getIntercept();
}
}
void PILISScoring::getSurvivalFunction_(Map<UInt, double> & points, vector<DPosition<2> > & survival_function)
{
// normalize the score density
double sum(0);
vector<UInt> indices;
for (Map<UInt, double>::ConstIterator it = points.begin(); it != points.end(); ++it)
{
sum += it->second;
indices.push_back(it->first);
}
for (Map<UInt, double>::Iterator it = points.begin(); it != points.end(); ++it)
{
it->second /= sum;
}
double survival_function_bin_size = (double)param_.getValue("survival_function_bin_size");
sort(indices.begin(), indices.end());
for (Size i = 0; i != indices.size(); ++i)
{
//cerr << indices[i] << " ";
sum = 0;
for (Size j = i; j != indices.size(); ++j)
{
sum += points[indices[j]];
}
DPosition<2> pos;
pos.setX((double)indices[i] / survival_function_bin_size);
//cerr << (double)points[indices[i]] << endl;
pos.setY(sum);
survival_function.push_back(pos);
}
return;
}
}
| 34.551495 | 182 | 0.620481 | [
"vector"
] |
e76c919a6cd99768f0bd1d577675f6f357e913e2 | 15,968 | hpp | C++ | ocs2_thirdparty/include/cppad/local/sparse/internal.hpp | grizzi/ocs2 | 4b78c4825deb8b2efc992fdbeef6fdb1fcca2345 | [
"BSD-3-Clause"
] | 126 | 2021-07-13T13:59:12.000Z | 2022-03-31T02:52:18.000Z | ocs2_thirdparty/include/cppad/local/sparse/internal.hpp | grizzi/ocs2 | 4b78c4825deb8b2efc992fdbeef6fdb1fcca2345 | [
"BSD-3-Clause"
] | 27 | 2021-07-14T12:14:04.000Z | 2022-03-30T16:27:52.000Z | ocs2_thirdparty/include/cppad/local/sparse/internal.hpp | grizzi/ocs2 | 4b78c4825deb8b2efc992fdbeef6fdb1fcca2345 | [
"BSD-3-Clause"
] | 55 | 2021-07-14T07:08:47.000Z | 2022-03-31T15:54:30.000Z | # ifndef CPPAD_LOCAL_SPARSE_INTERNAL_HPP
# define CPPAD_LOCAL_SPARSE_INTERNAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-19 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
// necessary definitions
# include <cppad/local/define.hpp>
# include <cppad/local/sparse/pack_setvec.hpp>
# include <cppad/local/sparse/list_setvec.hpp>
# include <cppad/local/sparse/svec_setvec.hpp>
// BEGIN_CPPAD_LOCAL_SPARSE_NAMESPACE
namespace CppAD { namespace local { namespace sparse {
/*!
\file sparse_internal.hpp
Routines that enable code to be independent of which internal spasity pattern
is used.
*/
// ---------------------------------------------------------------------------
/*!
Template structure used obtain the internal sparsity pattern type
form the corresponding element type.
The general form is not valid, must use a specialization.
\tparam Element_type
type of an element in the sparsity structrue.
\par <code>internal_pattern<Element_type>::pattern_type</code>
is the type of the corresponding internal sparsity pattern.
*/
template <class Element_type> struct internal_pattern;
/// Specilization for bool elements.
template <>
struct internal_pattern<bool>
{
typedef sparse::pack_setvec pattern_type;
};
/// Specilization for <code>std::set<size_t></code> elements.
template <>
struct internal_pattern< std::set<size_t> >
{
typedef list_setvec pattern_type;
};
// ---------------------------------------------------------------------------
/*!
Update the internal sparsity pattern for a sub-set of rows
\tparam SizeVector
The type used for index sparsity patterns. This is a simple vector
with elements of type size_t.
\tparam InternalSparsitiy
The type used for intenal sparsity patterns. This can be either
sparse::pack_setvec or list_setvec.
\param zero_empty
If this is true, the internal sparstity pattern corresponds to row zero
must be empty on input and will be emtpy output; i.e., any corresponding
values in pattern_in will be ignored.
\param input_empty
If this is true, the initial sparsity pattern for row
internal_index[i] is empty for all i.
In this case, one is setting the sparsity patterns; i.e.,
the output pattern in row internal_index[i] is the corresponding
entries in pattern.
\param transpose
If this is true, pattern_in is transposed.
\param internal_index
This specifies the sub-set of rows in internal_pattern that we are updating.
If traspose is false (true),
this is the mapping from row (column) index in pattern_in to the corresponding
row index in the internal_pattern.
\param internal_pattern
On input, the number of sets internal_pattern.n_set(),
and possible elements internal_pattern.end(), have been set.
If input_empty is true, and all of the sets
in internal_index are empty on input.
On output, the entries in pattern_in are added to internal_pattern.
To be specific, suppose transpose is false, and (i, j) is a possibly
non-zero entry in pattern_in, the entry (internal_index[i], j) is added
to internal_pattern.
On the other hand, if transpose is true,
the entry (internal_index[j], i) is added to internal_pattern.
\param pattern_in
This is the sparsity pattern for variables,
or its transpose, depending on the value of transpose.
*/
template <class SizeVector, class InternalSparsity>
void set_internal_pattern(
bool zero_empty ,
bool input_empty ,
bool transpose ,
const pod_vector<size_t>& internal_index ,
InternalSparsity& internal_pattern ,
const sparse_rc<SizeVector>& pattern_in )
{
size_t nr = internal_index.size();
# ifndef NDEBUG
size_t nc = internal_pattern.end();
if( transpose )
{ CPPAD_ASSERT_UNKNOWN( pattern_in.nr() == nc );
CPPAD_ASSERT_UNKNOWN( pattern_in.nc() == nr );
}
else
{ CPPAD_ASSERT_UNKNOWN( pattern_in.nr() == nr );
CPPAD_ASSERT_UNKNOWN( pattern_in.nc() == nc );
}
if( input_empty ) for(size_t i = 0; i < nr; i++)
{ size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( internal_pattern.number_elements(i_var) == 0 );
}
# endif
const SizeVector& row( pattern_in.row() );
const SizeVector& col( pattern_in.col() );
size_t nnz = row.size();
for(size_t k = 0; k < nnz; k++)
{ size_t r = row[k];
size_t c = col[k];
if( transpose )
std::swap(r, c);
//
size_t i_var = internal_index[r];
CPPAD_ASSERT_UNKNOWN( i_var < internal_pattern.n_set() );
CPPAD_ASSERT_UNKNOWN( c < nc );
bool ignore = zero_empty && i_var == 0;
if( ! ignore )
internal_pattern.post_element( internal_index[r], c );
}
// process posts
for(size_t i = 0; i < nr; ++i)
internal_pattern.process_post( internal_index[i] );
}
template <class InternalSparsity>
void set_internal_pattern(
bool zero_empty ,
bool input_empty ,
bool transpose ,
const pod_vector<size_t>& internal_index ,
InternalSparsity& internal_pattern ,
const vectorBool& pattern_in )
{ size_t nr = internal_index.size();
size_t nc = internal_pattern.end();
# ifndef NDEBUG
CPPAD_ASSERT_UNKNOWN( pattern_in.size() == nr * nc );
if( input_empty ) for(size_t i = 0; i < nr; i++)
{ size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( internal_pattern.number_elements(i_var) == 0 );
}
# endif
for(size_t i = 0; i < nr; i++)
{ for(size_t j = 0; j < nc; j++)
{ bool flag = pattern_in[i * nc + j];
if( transpose )
flag = pattern_in[j * nr + i];
if( flag )
{ size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( i_var < internal_pattern.n_set() );
CPPAD_ASSERT_UNKNOWN( j < nc );
bool ignore = zero_empty && i_var == 0;
if( ! ignore )
internal_pattern.post_element( i_var, j);
}
}
}
// process posts
for(size_t i = 0; i < nr; ++i)
internal_pattern.process_post( internal_index[i] );
return;
}
template <class InternalSparsity>
void set_internal_pattern(
bool zero_empty ,
bool input_empty ,
bool transpose ,
const pod_vector<size_t>& internal_index ,
InternalSparsity& internal_pattern ,
const vector<bool>& pattern_in )
{ size_t nr = internal_index.size();
size_t nc = internal_pattern.end();
# ifndef NDEBUG
CPPAD_ASSERT_UNKNOWN( pattern_in.size() == nr * nc );
if( input_empty ) for(size_t i = 0; i < nr; i++)
{ size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( internal_pattern.number_elements(i_var) == 0 );
}
# endif
for(size_t i = 0; i < nr; i++)
{ for(size_t j = 0; j < nc; j++)
{ bool flag = pattern_in[i * nc + j];
if( transpose )
flag = pattern_in[j * nr + i];
if( flag )
{ size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( i_var < internal_pattern.n_set() );
CPPAD_ASSERT_UNKNOWN( j < nc );
bool ignore = zero_empty && i_var == 0;
if( ! ignore )
internal_pattern.post_element( i_var, j);
}
}
}
// process posts
for(size_t i = 0; i < nr; ++i)
internal_pattern.process_post( internal_index[i] );
return;
}
template <class InternalSparsity>
void set_internal_pattern(
bool zero_empty ,
bool input_empty ,
bool transpose ,
const pod_vector<size_t>& internal_index ,
InternalSparsity& internal_pattern ,
const vector< std::set<size_t> >& pattern_in )
{ size_t nr = internal_index.size();
size_t nc = internal_pattern.end();
# ifndef NDEBUG
if( input_empty ) for(size_t i = 0; i < nr; i++)
{ size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( internal_pattern.number_elements(i_var) == 0 );
}
# endif
if( transpose )
{ CPPAD_ASSERT_UNKNOWN( pattern_in.size() == nc );
for(size_t j = 0; j < nc; j++)
{ std::set<size_t>::const_iterator itr( pattern_in[j].begin() );
while( itr != pattern_in[j].end() )
{ size_t i = *itr;
size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( i_var < internal_pattern.n_set() );
CPPAD_ASSERT_UNKNOWN( j < nc );
bool ignore = zero_empty && i_var == 0;
if( ! ignore )
internal_pattern.post_element( i_var, j);
++itr;
}
}
}
else
{ CPPAD_ASSERT_UNKNOWN( pattern_in.size() == nr );
for(size_t i = 0; i < nr; i++)
{ std::set<size_t>::const_iterator itr( pattern_in[i].begin() );
while( itr != pattern_in[i].end() )
{ size_t j = *itr;
size_t i_var = internal_index[i];
CPPAD_ASSERT_UNKNOWN( i_var < internal_pattern.n_set() );
CPPAD_ASSERT_UNKNOWN( j < nc );
bool ignore = zero_empty && i_var == 0;
if( ! ignore )
internal_pattern.post_element( i_var, j);
++itr;
}
}
}
// process posts
for(size_t i = 0; i < nr; ++i)
internal_pattern.process_post( internal_index[i] );
return;
}
// ---------------------------------------------------------------------------
/*!
Get sparsity pattern for a sub-set of variables
\tparam SizeVector
The type used for index sparsity patterns. This is a simple vector
with elements of type size_t.
\tparam InternalSparsitiy
The type used for intenal sparsity patterns. This can be either
sparse::pack_setvec or list_setvec.
\param transpose
If this is true, pattern_out is transposed.
\param internal_index
If transpose is false (true)
this is the mapping from row (column) an index in pattern_out
to the corresponding row index in internal_pattern.
\param internal_pattern
This is the internal sparsity pattern.
\param pattern_out
The input value of pattern_out does not matter.
Upon return it is an index sparsity pattern for each of the variables
in internal_index, or its transpose, depending on the value of transpose.
*/
template <class SizeVector, class InternalSparsity>
void get_internal_pattern(
bool transpose ,
const pod_vector<size_t>& internal_index ,
const InternalSparsity& internal_pattern ,
sparse_rc<SizeVector>& pattern_out )
{ typedef typename InternalSparsity::const_iterator iterator;
// number variables
size_t nr = internal_index.size();
// column size of interanl sparstiy pattern
size_t nc = internal_pattern.end();
// determine nnz, the number of possibly non-zero index pairs
size_t nnz = 0;
for(size_t i = 0; i < nr; i++)
{ CPPAD_ASSERT_UNKNOWN( internal_index[i] < internal_pattern.n_set() );
iterator itr(internal_pattern, internal_index[i]);
size_t j = *itr;
while( j < nc )
{ ++nnz;
j = *(++itr);
}
}
// transposed
if( transpose )
{ pattern_out.resize(nc, nr, nnz);
//
size_t k = 0;
for(size_t i = 0; i < nr; i++)
{ iterator itr(internal_pattern, internal_index[i]);
size_t j = *itr;
while( j < nc )
{ pattern_out.set(k++, j, i);
j = *(++itr);
}
}
return;
}
// not transposed
pattern_out.resize(nr, nc, nnz);
//
size_t k = 0;
for(size_t i = 0; i < nr; i++)
{ iterator itr(internal_pattern, internal_index[i]);
size_t j = *itr;
while( j < nc )
{ pattern_out.set(k++, i, j);
j = *(++itr);
}
}
return;
}
template <class InternalSparsity>
void get_internal_pattern(
bool transpose ,
const pod_vector<size_t>& internal_index ,
const InternalSparsity& internal_pattern ,
vectorBool& pattern_out )
{ typedef typename InternalSparsity::const_iterator iterator;
// number variables
size_t nr = internal_index.size();
//
// column size of interanl sparstiy pattern
size_t nc = internal_pattern.end();
//
pattern_out.resize(nr * nc);
for(size_t ij = 0; ij < nr * nc; ij++)
pattern_out[ij] = false;
//
for(size_t i = 0; i < nr; i++)
{ CPPAD_ASSERT_UNKNOWN( internal_index[i] < internal_pattern.n_set() );
iterator itr(internal_pattern, internal_index[i]);
size_t j = *itr;
while( j < nc )
{ if( transpose )
pattern_out[j * nr + i] = true;
else
pattern_out[i * nc + j] = true;
j = *(++itr);
}
}
return;
}
template <class InternalSparsity>
void get_internal_pattern(
bool transpose ,
const pod_vector<size_t>& internal_index ,
const InternalSparsity& internal_pattern ,
vector<bool>& pattern_out )
{ typedef typename InternalSparsity::const_iterator iterator;
// number variables
size_t nr = internal_index.size();
//
// column size of interanl sparstiy pattern
size_t nc = internal_pattern.end();
//
pattern_out.resize(nr * nc);
for(size_t ij = 0; ij < nr * nc; ij++)
pattern_out[ij] = false;
//
for(size_t i = 0; i < nr; i++)
{ CPPAD_ASSERT_UNKNOWN( internal_index[i] < internal_pattern.n_set() );
iterator itr(internal_pattern, internal_index[i]);
size_t j = *itr;
while( j < nc )
{ if( transpose )
pattern_out[j * nr + i] = true;
else
pattern_out[i * nc + j] = true;
j = *(++itr);
}
}
return;
}
template <class InternalSparsity>
void get_internal_pattern(
bool transpose ,
const pod_vector<size_t>& internal_index ,
const InternalSparsity& internal_pattern ,
vector< std::set<size_t> >& pattern_out )
{ typedef typename InternalSparsity::const_iterator iterator;
// number variables
size_t nr = internal_index.size();
//
// column size of interanl sparstiy pattern
size_t nc = internal_pattern.end();
//
if( transpose )
pattern_out.resize(nc);
else
pattern_out.resize(nr);
for(size_t k = 0; k < pattern_out.size(); k++)
pattern_out[k].clear();
//
for(size_t i = 0; i < nr; i++)
{ CPPAD_ASSERT_UNKNOWN( internal_index[i] < internal_pattern.n_set() );
iterator itr(internal_pattern, internal_index[i]);
size_t j = *itr;
while( j < nc )
{ if( transpose )
pattern_out[j].insert(i);
else
pattern_out[i].insert(j);
j = *(++itr);
}
}
return;
}
} } } // END_CPPAD_LOCAL_SPARSE_NAMESPACE
# endif
| 35.017544 | 79 | 0.587049 | [
"vector"
] |
e76d3724b3276f9094bee5dbc3bfa9997e4c43d4 | 3,454 | cpp | C++ | simpleuv/parametrize.cpp | ZhengZerong/simpleuv | a3f5bbbac93352b57973c657c38867832749d74d | [
"MIT"
] | 1 | 2019-12-09T06:18:22.000Z | 2019-12-09T06:18:22.000Z | simpleuv/parametrize.cpp | ZhengZerong/simpleuv | a3f5bbbac93352b57973c657c38867832749d74d | [
"MIT"
] | null | null | null | simpleuv/parametrize.cpp | ZhengZerong/simpleuv | a3f5bbbac93352b57973c657c38867832749d74d | [
"MIT"
] | 2 | 2020-11-13T10:08:07.000Z | 2021-05-14T08:23:26.000Z | #include <igl/arap.h>
#include <igl/lscm.h>
#include <igl/boundary_loop.h>
#include <igl/harmonic.h>
#include <igl/map_vertices_to_circle.h>
#include <simpleuv/parametrize.h>
namespace simpleuv
{
void parametrizeUsingARAP(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, const Eigen::VectorXi &bnd, Eigen::MatrixXd &V_uv)
{
Eigen::MatrixXd initial_guess;
Eigen::MatrixXd bnd_uv;
igl::map_vertices_to_circle(V,bnd,bnd_uv);
igl::harmonic(V,F,bnd,bnd_uv,1,initial_guess);
// Add dynamic regularization to avoid to specify boundary conditions
igl::ARAPData arap_data;
arap_data.with_dynamics = true;
Eigen::VectorXi b = Eigen::VectorXi::Zero(0);
Eigen::MatrixXd bc = Eigen::MatrixXd::Zero(0,0);
// Initialize ARAP
arap_data.max_iter = 100;
// 2 means that we're going to *solve* in 2d
arap_precomputation(V,F,2,b,arap_data);
// Solve arap using the harmonic map as initial guess
V_uv = initial_guess;
arap_solve(bc,arap_data,V_uv);
}
void parametrizeUsingLSCM(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, const Eigen::VectorXi &bnd, Eigen::MatrixXd &V_uv)
{
Eigen::VectorXi b(2,1);
b(0) = bnd(0);
b(1) = bnd(round(bnd.size()/2));
Eigen::MatrixXd bc(2,2);
bc<<0,0,1,0;
// LSCM parametrization
igl::lscm(V,F,b,bc,V_uv);
}
bool extractResult(const std::vector<Vertex> &verticies, const Eigen::MatrixXd &V_uv, std::vector<TextureCoord> &vertexUvs)
{
vertexUvs.clear();
auto isCoordValid = [=](float coord) {
if (std::isnan(coord) || std::isinf(coord))
return false;
return true;
};
if ((decltype(verticies.size()))V_uv.size() < verticies.size() * 2) {
//qDebug() << "Invalid V_uv.size:" << V_uv.size() << "Expected:" << verticies.size() * 2;
return false;
}
for (decltype(verticies.size()) i = 0; i < verticies.size(); i++) {
TextureCoord coord;
coord.uv[0] = V_uv.row(i)[0];
coord.uv[1] = V_uv.row(i)[1];
if (isCoordValid(coord.uv[0]) && isCoordValid(coord.uv[1])) {
vertexUvs.push_back(coord);
continue;
}
vertexUvs.clear();
return false;
}
return true;
}
// Modified from the libigl example code
// https://github.com/libigl/libigl/blob/master/tutorial/503_ARAPParam/main.cpp
bool parametrize(const std::vector<Vertex> &verticies,
const std::vector<Face> &faces,
std::vector<TextureCoord> &vertexUvs)
{
if (verticies.empty() || faces.empty())
return false;
Eigen::MatrixXd V(verticies.size(), 3);
Eigen::MatrixXi F(faces.size(), 3);
for (decltype(verticies.size()) i = 0; i < verticies.size(); i++) {
const auto &vertex = verticies[i];
V.row(i) << vertex.xyz[0], vertex.xyz[1], vertex.xyz[2];
}
for (decltype(faces.size()) i = 0; i < faces.size(); i++) {
const auto &face = faces[i];
F.row(i) << face.indices[0], face.indices[1], face.indices[2];
}
Eigen::VectorXi bnd;
igl::boundary_loop(F,bnd);
// {
// Eigen::MatrixXd V_uv;
// parametrizeUsingARAP(V, F, bnd, V_uv);
// if (extractResult(verticies, V_uv, vertexUvs))
// return true;
// }
{
Eigen::MatrixXd V_uv;
parametrizeUsingLSCM(V, F, bnd, V_uv);
if (extractResult(verticies, V_uv, vertexUvs))
return true;
}
return false;
}
}
| 29.271186 | 128 | 0.612913 | [
"vector"
] |
e76f780aebc3fe886be8f3879850a9eec6ef5921 | 12,013 | cpp | C++ | engine/src/resources/particleeffect.cpp | thunder-engine/thunder | 14a70d46532b8b78635835fc05c0ac2f33a12d8b | [
"Apache-2.0"
] | 162 | 2020-09-18T19:42:43.000Z | 2022-03-30T20:27:42.000Z | engine/src/resources/particleeffect.cpp | southdy/thunder | 4df2904da3983ac795ee00ca43fd0c6b771a2df5 | [
"Apache-2.0"
] | 162 | 2020-10-10T11:16:52.000Z | 2022-03-30T17:09:11.000Z | engine/src/resources/particleeffect.cpp | southdy/thunder | 4df2904da3983ac795ee00ca43fd0c6b771a2df5 | [
"Apache-2.0"
] | 12 | 2020-10-18T09:16:35.000Z | 2022-01-08T11:23:17.000Z | #include "particleeffect.h"
#include "material.h"
#include "mesh.h"
#define EMITTERS "Emitters"
ParticleModificator::ParticleModificator() :
m_Type(CONSTANT),
m_Min(1.0f),
m_Max(1.0f) {
}
ParticleModificator::~ParticleModificator() {
}
void ParticleModificator::spawnParticle(ParticleData &data) {
A_UNUSED(data);
}
void ParticleModificator::updateParticle(ParticleData &data, float dt) {
A_UNUSED(data);
A_UNUSED(dt);
}
void ParticleModificator::loadData(const VariantList &list) {
auto it = list.begin();
m_Type = static_cast<ValueType>((*it).toInt());
it++;
if(m_Type < CURVE) {
m_Min = (*it).toVector4();
it++;
}
if(m_Type == RANGE) {
m_Max = (*it).toVector4();
}
}
ParticleEmitter::ParticleEmitter() :
m_pMesh(nullptr),
m_pMaterial(nullptr),
m_Distibution(1.0f),
m_Gpu(false),
m_Local(false),
m_Continous(true) {
}
bool ParticleEmitter::operator== (const ParticleEmitter &emitter) const {
return (m_pMesh == emitter.m_pMesh) &&
(m_pMaterial == emitter.m_pMaterial) &&
(m_Distibution == emitter.m_Distibution) &&
(m_Gpu == emitter.m_Gpu) &&
(m_Local == emitter.m_Local) &&
(m_Continous == emitter.m_Continous);
}
Mesh *ParticleEmitter::mesh() const {
return m_pMesh;
}
void ParticleEmitter::setMesh(Mesh *mesh) {
m_pMesh = mesh;
}
Material *ParticleEmitter::material() const {
return m_pMaterial;
}
void ParticleEmitter::setMaterial(Material *material) {
m_pMaterial = material;
}
float ParticleEmitter::distibution() const {
return m_Distibution;
}
void ParticleEmitter::setDistibution(float distibution) {
m_Distibution = distibution;
}
bool ParticleEmitter::local() const {
return m_Local;
}
void ParticleEmitter::setLocal(bool local) {
m_Local = local;
}
bool ParticleEmitter::gpu() const {
return m_Gpu;
}
void ParticleEmitter::setGpu(bool gpu) {
m_Gpu = gpu;
}
bool ParticleEmitter::continous() const {
return m_Continous;
}
void ParticleEmitter::setContinous(bool continous) {
m_Continous = continous;
}
ModifiersDeque &ParticleEmitter::modifiers() {
return m_Modifiers;
}
void ParticleEmitter::setModifiers(const ModifiersDeque &modifiers) {
m_Modifiers = modifiers;
}
ParticleData::ParticleData() :
life(1.0),
frame(0.0),
distance(-1.0f),
transform(0.0f),
angle(0.0f),
color(1.0f),
size(1.0f),
colrate(0.0f),
position(0.0f),
velocity(0.0f),
anglerate(0.0f),
sizerate(0.0f) {
}
class Lifetime: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.life = m_Min.x;
} break;
case RANGE: {
data.life = RANGE(m_Min.x, m_Max.x);
} break;
default: break;
}
}
};
class StartSize: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.size.x = m_Min.x;
data.size.y = m_Min.y;
data.size.z = m_Min.z;
} break;
case RANGE: {
data.size.x = RANGE(m_Min.x, m_Max.x);
data.size.y = RANGE(m_Min.y, m_Max.y);
data.size.z = RANGE(m_Min.z, m_Max.z);
} break;
default: break;
}
}
};
class StartColor: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.color.x = m_Min.x;
data.color.y = m_Min.y;
data.color.z = m_Min.z;
data.color.w = m_Min.w;
} break;
case RANGE: {
data.color.x = RANGE(m_Min.x, m_Max.x);
data.color.y = RANGE(m_Min.y, m_Max.y);
data.color.z = RANGE(m_Min.z, m_Max.z);
data.color.w = RANGE(m_Min.w, m_Max.w);
} break;
default: break;
}
}
};
class StartAngle: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.angle.x = m_Min.x * DEG2RAD;
data.angle.y = m_Min.y * DEG2RAD;
data.angle.z = m_Min.z * DEG2RAD;
} break;
case RANGE: {
data.angle.x = RANGE(m_Min.x, m_Max.x) * DEG2RAD;
data.angle.y = RANGE(m_Min.y, m_Max.y) * DEG2RAD;
data.angle.z = RANGE(m_Min.z, m_Max.z) * DEG2RAD;
} break;
default: break;
}
}
};
class StartPosition: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.position.x = m_Min.x;
data.position.y = m_Min.y;
data.position.z = m_Min.z;
} break;
case RANGE: {
data.position.x = RANGE(m_Min.x, m_Max.x);
data.position.y = RANGE(m_Min.y, m_Max.y);
data.position.z = RANGE(m_Min.z, m_Max.z);
} break;
default: break;
}
}
};
class ScaleSize: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.sizerate.x = m_Min.x;
data.sizerate.y = m_Min.y;
data.sizerate.z = m_Min.z;
} break;
case RANGE: {
data.sizerate.x = RANGE(m_Min.x, m_Max.x);
data.sizerate.y = RANGE(m_Min.y, m_Max.y);
data.sizerate.z = RANGE(m_Min.z, m_Max.z);
} break;
default: break;
}
}
void updateParticle(ParticleData &data, float dt) {
data.size += data.sizerate * dt;
}
};
class ScaleColor: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.colrate.x = m_Min.x;
data.colrate.y = m_Min.y;
data.colrate.z = m_Min.z;
data.colrate.w = m_Min.w;
} break;
case RANGE: {
data.colrate.x = RANGE(m_Min.x, m_Max.x);
data.colrate.y = RANGE(m_Min.y, m_Max.y);
data.colrate.z = RANGE(m_Min.z, m_Max.z);
data.colrate.w = RANGE(m_Min.w, m_Max.w);
} break;
default: break;
}
}
void updateParticle(ParticleData &data, float dt) {
data.color += data.colrate * dt;
}
};
class ScaleAngle: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.anglerate.x = m_Min.x;
data.anglerate.y = m_Min.y;
data.anglerate.z = m_Min.z;
} break;
case RANGE: {
data.anglerate.x = RANGE(m_Min.x, m_Max.x);
data.anglerate.y = RANGE(m_Min.y, m_Max.y);
data.anglerate.z = RANGE(m_Min.z, m_Max.z);
} break;
default: break;
}
}
void updateParticle(ParticleData &data, float dt) {
data.angle += data.anglerate * DEG2RAD * dt;
}
};
class Velocity: public ParticleModificator {
public:
void spawnParticle(ParticleData &data) {
switch(m_Type) {
case CONSTANT: {
data.velocity.x = m_Min.x;
data.velocity.y = m_Min.y;
data.velocity.z = m_Min.z;
} break;
case RANGE: {
data.velocity.x = RANGE(m_Min.x, m_Max.x);
data.velocity.y = RANGE(m_Min.y, m_Max.y);
data.velocity.z = RANGE(m_Min.z, m_Max.z);
} break;
default: break;
}
}
void updateParticle(ParticleData &data, float dt) {
data.position += data.velocity * dt;
}
};
/*!
\class ParticleEffect
\brief Contains all necessary information about the effect.
\inmodule Resources
PartcileEffect alows developer to create or modify a complex particle effects.
*/
ParticleEffect::ParticleEffect() {
PROFILE_FUNCTION();
}
ParticleEffect::~ParticleEffect() {
PROFILE_FUNCTION();
}
/*!
Removes all emitters from the effect
*/
void ParticleEffect::clear() {
m_Emitters.clear();
}
/*!
Returns a count of the emitters for effect.
*/
int ParticleEffect::emittersCount() const {
PROFILE_FUNCTION();
return m_Emitters.size();
}
/*!
Returns an emitter with \a index.
*/
ParticleEmitter *ParticleEffect::emitter(int index) {
PROFILE_FUNCTION();
return &m_Emitters[index];
}
/*!
Adds an \a emitter to the effect.
*/
void ParticleEffect::addEmitter(ParticleEmitter *emitter) {
if(emitter) {
m_Emitters.push_back(*emitter);
}
}
/*!
\internal
*/
void ParticleEffect::loadUserData(const VariantMap &data) {
PROFILE_FUNCTION();
clear();
{
auto section = data.find(EMITTERS);
if(section != data.end()) {
VariantList list = (*section).second.value<VariantList>();
for(auto e : list) {
VariantList fields = e.value<VariantList>();
auto it = fields.begin();
ParticleEmitter emitter;
emitter.setMesh(Engine::loadResource<Mesh>((*it).toString()));
it++;
emitter.setMaterial(Engine::loadResource<Material>((*it).toString()));
it++;
emitter.setGpu((*it).toBool());
it++;
emitter.setLocal((*it).toBool());
it++;
emitter.setContinous((*it).toBool());
it++;
emitter.setDistibution((*it).toFloat());
it++;
for(auto m : (*it).value<VariantList>()) {
VariantList mods = m.value<VariantList>();
auto mod = mods.begin();
int32_t type = (*mod).toInt();
ParticleModificator *modificator = nullptr;
switch (type) {
case ParticleModificator::LIFETIME: modificator = new Lifetime(); break;
case ParticleModificator::STARTSIZE: modificator = new StartSize(); break;
case ParticleModificator::STARTCOLOR: modificator = new StartColor(); break;
case ParticleModificator::STARTANGLE: modificator = new StartAngle(); break;
case ParticleModificator::STARTPOSITION: modificator = new StartPosition(); break;
case ParticleModificator::SCALESIZE: modificator = new ScaleSize(); break;
case ParticleModificator::SCALECOLOR: modificator = new ScaleColor(); break;
case ParticleModificator::SCALEANGLE: modificator = new ScaleAngle(); break;
case ParticleModificator::VELOCITY: modificator = new Velocity(); break;
default: break;
}
if(modificator) {
mod++;
modificator->loadData((*mod).value<VariantList>());
emitter.modifiers().push_back(modificator);
}
}
m_Emitters.push_back(emitter);
}
}
}
setState(Ready);
}
/*!
\internal
\warning Do not call this function manually
*/
void ParticleEffect::registerSuper(ObjectSystem *system) {
REGISTER_META_TYPE(ParticleEmitter);
ParticleEffect::registerClassFactory(system);
}
| 28.067757 | 106 | 0.545326 | [
"mesh",
"transform"
] |
e76f7ed87a85d013ec89ad4cea030646e5788810 | 9,731 | hpp | C++ | src/metaSMT/backend/ClauseWriter.hpp | finnhaedicke/metaSMT | 949245da0bf0f3c042cb589aaea5d015e2ed9e9a | [
"MIT"
] | 33 | 2015-04-09T14:14:25.000Z | 2022-03-27T08:55:58.000Z | src/metaSMT/backend/ClauseWriter.hpp | finnhaedicke/metaSMT | 949245da0bf0f3c042cb589aaea5d015e2ed9e9a | [
"MIT"
] | 28 | 2015-03-13T14:21:33.000Z | 2019-04-02T07:59:34.000Z | src/metaSMT/backend/ClauseWriter.hpp | finnhaedicke/metaSMT | 949245da0bf0f3c042cb589aaea5d015e2ed9e9a | [
"MIT"
] | 9 | 2015-04-22T18:10:51.000Z | 2021-08-06T12:44:12.000Z | #pragma once
#include "../tags/SAT.hpp"
#include "../result_wrapper.hpp"
#include "SAT/model_parser.hpp"
#include "../support/GoTmp.hpp"
#include <vector>
#include <exception>
#include <fstream>
#include <iostream>
#include <cstdio>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/optional.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/spirit/home/support/iterators/istream_iterator.hpp>
namespace metaSMT {
namespace solver {
using namespace boost::assign;
namespace executable {
struct Glucoser // performs extended resolution
{
static boost::optional < bool > execute ( std::string const& dimacsFile, std::string const& log, std::string const& err)
{
std::string cmd;
char* env;
if( (env = getenv("GLOCUSER_EXECUTABLE")) ) {
cmd = env;
} else {
cmd = "glucoser";
}
std::string call = boost::str ( boost::format ( "%s %s %s &> %s" ) % cmd % dimacsFile % log % err ) ;
std::cout << call << std::endl;
int returnValue = system ( call.c_str() );
int exitStatus = WEXITSTATUS ( returnValue );
if ( returnValue < 0 )
return boost::optional < bool > ();
return boost::optional < bool > ( exitStatus == 10 ); // 10 for satisfiable, 20 for unsatisfiable
}
};
struct MiniSAT
{
static boost::optional < bool > execute ( std::string const& dimacsFile, std::string const& log, std::string const& err)
{
std::string cmd;
char* env;
if( (env = getenv("MiniSat_EXECUTABLE")) ) {
cmd = env;
} else {
cmd = "minisat";
}
int returnValue = system ( boost::str ( boost::format ( "%s %s %s &> %s" ) % cmd % dimacsFile % log % err ).c_str() );
int exitStatus = WEXITSTATUS ( returnValue );
if ( returnValue < 0 )
return boost::optional < bool > ();
return boost::optional < bool > ( exitStatus == 10 ); // 10 for satisfiable, 20 for unsatisfiable
}
};
struct PicoSAT
{
static boost::optional < bool > execute ( std::string const& dimacsFile, std::string const& log, std::string const& err)
{
std::string cmd;
char* env;
if( (env = getenv("PicoSAT_EXECUTABLE")) ) {
cmd = env;
} else {
cmd = "picosat";
}
int returnValue = system ( boost::str ( boost::format ( "%s %s > %s 2> %s" ) % cmd % dimacsFile % log % err ).c_str() );
int exitStatus = WEXITSTATUS ( returnValue );
if ( returnValue < 0 )
return boost::optional < bool > ();
bool sat = exitStatus == 10;
return boost::optional < bool > ( sat ); // 10 for satisfiable
}
};
struct Plingeling
{
static boost::optional < bool > execute ( std::string const& dimacsFile, std::string const& log, std::string const& err)
{
int returnValue = system ( boost::str ( boost::format ( "plingeling -v %s > %s 2> %s" ) % dimacsFile % log % err).c_str() );
int exitStatus = WEXITSTATUS ( returnValue );
if ( returnValue < 0 )
return boost::optional < bool > ();
bool sat = exitStatus == 10;
//std::cout << "SAT: " << sat << std::endl;
return boost::optional < bool > ( sat ); // 10 for satisfiable
}
};
struct PrecoSAT
{
static boost::optional < bool > execute ( std::string const& dimacsFile, std::string const& log, std::string const& err)
{
int returnValue = system ( boost::str ( boost::format ( "precosat -v %s > %s " ) % dimacsFile % err).c_str() );
int exitStatus = WEXITSTATUS ( returnValue );
if ( returnValue < 0 )
return boost::optional < bool > ();
bool sat = exitStatus == 10;
//std::cout << "SAT: " << sat << std::endl;
return boost::optional < bool > ( sat ); // 10 for satisfiable
}
};
}
template<typename Exec>
struct dimacs_solver
{
dimacs_solver ( std::vector < unsigned >& model ) : model ( model )
{
}
void readModel ( std::string const& log )
{
// open file, disable skipping of whitespace
std::ifstream in(log.c_str());
in.unsetf(std::ios::skipws);
// wrap istream into iterator
boost::spirit::istream_iterator begin(in);
boost::spirit::istream_iterator end;
SAT::model_grammar<boost::spirit::istream_iterator> p;
SAT::result_tuple result;
// use iterator to parse file data
bool match = boost::spirit::qi::parse(begin, end, p, result);
assert ( match );
BOOST_FOREACH ( int val, result.get<1>() )
{
if ( val == 0 ) continue;
unsigned position = abs ( val );
unsigned X = val < 0 ? 0 : 1;
if (position >= model.size()) {
std::cout << model.size() << " " << position << std::endl;
}
assert(model.size() > position);
model[position] = X;
}
}
boost::optional < bool > solve ( std::string const& filename )
{
std::string log = boost::str( boost::format("solver-%d.log") % getpid());
std::string err = boost::str( boost::format("solver-%d.err") % getpid());
boost::optional < bool > result = Exec::execute ( filename, log, err );
bool returnValue = false;
if ( result )
{
//std::cout << "SAT? " << *result << std::endl;
if ( *result )
{
readModel ( log );
returnValue = true;
}
else
returnValue = false;
}
std::remove( log.c_str() );
std::remove( err.c_str() );
return returnValue;
}
private:
std::vector < unsigned >& model;
};
template<typename Solver>
class ClauseWriter
{
public:
typedef std::vector < int > clause_vec;
typedef std::vector < clause_vec > clause_db;
public:
ClauseWriter () : vars (0)
{
}
int toLit ( SAT::tag::lit_tag lit )
{
int l = lit.id;
if ( unsigned (abs ( l ) ) > vars )
vars = abs ( l );
return l;
}
void clause ( std::vector < SAT::tag::lit_tag > const& fromClause )
{
clause_vec cls;
BOOST_FOREACH ( SAT::tag::lit_tag const& lit, fromClause )
cls += toLit ( lit );
db += cls;
}
void assertion ( SAT::tag::lit_tag lit )
{
clause_vec cls;
cls += toLit ( lit );
db.push_back ( cls );
}
void assumption ( SAT::tag::lit_tag lit )
{
clause_vec cls;
cls += toLit ( lit );
assumptions.push_back ( cls );
}
void write_header ( std::ostream& stream )
{
stream << "p cnf " << vars << " " << db.size() + assumptions.size() << std::endl;
}
void write_cnf ( std::string const& filename )
{
std::ofstream cnf ( filename.c_str() ) ;
write_header ( cnf );
BOOST_FOREACH ( clause_vec const& cls, db )
{
std::for_each (cls.begin(), cls.end(),
cnf << boost::lambda::free1 << " ");
cnf << "0" << std::endl;
}
BOOST_FOREACH ( clause_vec const& cls, assumptions )
{
std::for_each (cls.begin(), cls.end(),
cnf << boost::lambda::free1 << " ");
cnf << "0" << std::endl;
}
}
bool solve ( )
{
// // GoTmp working_directory;
std::string name = boost::str( boost::format("clause-writer-%d.cnf") % getpid());
write_cnf ( name );
//system ("cnf2aig clause-writer.cnf clause-writer.aig");
//system ("optimize_aig.sh clause-writer.aig ");
//system ("aigtocnf clause-writer.aig clause-writer.cnf");
assumptions.clear();
model.resize ( vars+1, 0 );
Solver solver ( model );
boost::optional < bool > result = solver.solve ( name );
assert ( result );
std::remove(name.c_str());
if ( *result == false ) return false;
return true;
}
result_wrapper read_value ( SAT::tag::lit_tag lit )
{
assert ( !model.empty() );
assert ( int(model.size()) > toLit ( lit ) );
switch ( model[ abs ( toLit ( lit ) ) ] )
{
case 1:
return result_wrapper ( '1' );
case 0:
return result_wrapper ( '0' );
default:
assert ( false );
return result_wrapper ( 'X' );
}
}
private:
clause_db db;
clause_db assumptions;
unsigned vars;
std::vector < unsigned > model;
};
} /* solver */
} /* metaSMT */
// vim: ts=2 sw=2 et
| 30.126935 | 135 | 0.489878 | [
"vector",
"model"
] |
e76ffbc24653d4d99c0238674e23163dcd9cec74 | 1,496 | hpp | C++ | src/scene/scene_parser.hpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | 21 | 2020-05-02T06:32:23.000Z | 2021-07-14T11:22:07.000Z | src/scene/scene_parser.hpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | null | null | null | src/scene/scene_parser.hpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | 1 | 2021-05-24T13:44:56.000Z | 2021-05-24T13:44:56.000Z | #ifndef SCENE_PARSER_HPP
#define SCENE_PARSER_HPP
#include <optional>
#include <toml.hpp>
#include "kernel_types/area_light.hpp"
#include "vector/vector_types.hpp"
namespace nova {
struct OutputSettings {
vec2i dimensions;
std::string file_path;
bool path_tracing;
int num_samples;
};
struct ModelSettings {
std::vector<std::string> model_paths;
std::string sky_path;
};
struct PostProcessingSettings {
bool last_frame_denoise;
bool anti_aliasing;
float exposure;
};
struct CameraSettings {
vec3f position;
vec3f target;
vec3f up;
float fovy;
};
struct ShadingDefaultSettings {
vec3f diffuse;
float metallic;
float roughness;
};
struct ParsedLight {
vec3f intensity;
vec3f position;
vec3f normal;
vec2f dims;
};
struct LightSettings {
std::vector<ParsedLight> lights;
};
struct ParsedGroundPlane {
vec3f position;
vec3f normal;
vec2f dims;
vec3f diffuse;
float metallic;
float roughness;
};
struct GroundSettings {
std::optional<ParsedGroundPlane> ground;
};
class SceneParser {
public:
SceneParser();
OutputSettings get_output_settings() const;
ModelSettings get_model_settings() const;
PostProcessingSettings get_post_processing_settings() const;
CameraSettings get_camera_settings() const;
LightSettings get_light_settings() const;
ShadingDefaultSettings get_shading_default_settings() const;
GroundSettings get_ground_settings() const;
private:
toml::value parsed_data;
};
}
#endif // SCENE_PARSER_HPP | 17.6 | 62 | 0.759358 | [
"vector"
] |
e770d4470b56468eb209df2a3f5bebf0643a3156 | 14,723 | cpp | C++ | src/listener_tests/atsc3_mmt_listener_test.cpp | jonathas/libatsc3 | b1f1f340d92e1dc75144c535b4f0e2a1c1d1961a | [
"MIT"
] | null | null | null | src/listener_tests/atsc3_mmt_listener_test.cpp | jonathas/libatsc3 | b1f1f340d92e1dc75144c535b4f0e2a1c1d1961a | [
"MIT"
] | null | null | null | src/listener_tests/atsc3_mmt_listener_test.cpp | jonathas/libatsc3 | b1f1f340d92e1dc75144c535b4f0e2a1c1d1961a | [
"MIT"
] | null | null | null | /*
* atsc3_mmt_listener_test.c
*
* Created on: Jan 19, 2019
* Author: jjustman
*
* this has very early mpu defragmentation model
*/
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <string.h>
#include <sys/stat.h>
#include <pthread.h>
#include "../atsc3_listener_udp.h"
#include "../atsc3_utils.h"
#include "../atsc3_lls.h"
#include "../atsc3_lls_slt_parser.h"
#include "../atsc3_mmtp_types.h"
#include "../atsc3_mmtp_parser.h"
#include "../atsc3_mmt_mpu_parser.h"
#include "../atsc3_mmt_mpu_utils.h"
#include "../atsc3_lls_mmt_utils.h"
#include "../atsc3_player_ffplay.h"
#include "../atsc3_logging_externs.h"
uint32_t* dst_ip_addr_filter = NULL;
uint16_t* dst_ip_port_filter = NULL;
uint16_t* dst_packet_id_filter = NULL;
lls_slt_monitor_t* lls_slt_monitor;
//make sure to invoke mmtp_sub_flow_vector_init(&p_sys->mmtp_sub_flow_vector);
mmtp_sub_flow_vector_t* mmtp_sub_flow_vector;
//todo - keep track of these by flow and packet_id to detect mpu_sequence_number increment
mmtp_payload_fragments_union_t* mmtp_payload_previous_for_reassembly = NULL;
uint32_t __SEQUENCE_NUMBER_COUNT=0;
pipe_ffplay_buffer_t* pipe_ffplay_buffer = NULL;
uint32_t last_mpu_sequence_number = 0;
uint32_t fragment_count = 0;
void process_packet(u_char *user, const struct pcap_pkthdr *pkthdr, const u_char *packet) {
udp_packet_t* udp_packet = process_packet_from_pcap(user, pkthdr, packet);
if(!udp_packet) {
return;
}
//dispatch for LLS extraction and dump
if(udp_packet->udp_flow.dst_ip_addr == LLS_DST_ADDR && udp_packet->udp_flow.dst_port == LLS_DST_PORT) {
lls_table_t* lls_table = lls_table_create_or_update_from_lls_slt_monitor(lls_slt_monitor, udp_packet->data, udp_packet->data_length);
}
if(udp_packet->udp_flow.dst_ip_addr <= MIN_ATSC3_MULTICAST_BLOCK || udp_packet->udp_flow.dst_ip_addr >= MAX_ATSC3_MULTICAST_BLOCK) {
//out of range, so drop
goto cleanup;
}
if((dst_ip_addr_filter == NULL && dst_ip_port_filter == NULL) || (udp_packet->udp_flow.dst_ip_addr == *dst_ip_addr_filter && udp_packet->udp_flow.dst_port == *dst_ip_port_filter)) {
lls_sls_mmt_session_t* matching_lls_slt_mmt_session = lls_slt_mmt_session_find_from_udp_packet(lls_slt_monitor, udp_packet->udp_flow.src_ip_addr, udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port);
if(matching_lls_slt_mmt_session) {
mmtp_payload_fragments_union_t* mmtp_payload = mmtp_packet_parse(mmtp_sub_flow_vector, udp_packet);
if(!mmtp_payload) {
return cleanup(&udp_packet);
}
//for filtering MMT flows by a specific packet_id
if(dst_packet_id_filter && *dst_packet_id_filter != mmtp_payload->mmtp_packet_header.mmtp_packet_id) {
goto cleanup;
}
//dump header, then dump applicable packet type
//mmtp_packet_header_dump(mmtp_payload);
if(mmtp_payload->mmtp_packet_header.mmtp_payload_type == 0x0) {
if(mmtp_payload->mmtp_mpu_type_packet_header.mpu_timed_flag == 1) {
if(mmtp_payload_previous_for_reassembly && mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number != mmtp_payload->mmtp_mpu_type_packet_header.mpu_sequence_number) {
__INFO("recon for mpu_sequence_number: %u", mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number);
//reassemble previous segment
mmtp_sub_flow_t* mmtp_sub_flow = mmtp_sub_flow_vector_get_or_set_packet_id(mmtp_sub_flow_vector, &udp_packet->udp_flow, mmtp_payload_previous_for_reassembly->mmtp_packet_header.mmtp_packet_id);
mpu_data_unit_payload_fragments_t* mpu_metadata_fragments = mpu_data_unit_payload_fragments_find_mpu_sequence_number(&mmtp_sub_flow->mpu_fragments->mpu_metadata_fragments_vector, mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number);
mpu_data_unit_payload_fragments_t* mpu_movie_fragments = mpu_data_unit_payload_fragments_find_mpu_sequence_number(&mmtp_sub_flow->mpu_fragments->movie_fragment_metadata_vector, mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number);
mpu_data_unit_payload_fragments_t* data_unit_payload_types = mpu_data_unit_payload_fragments_find_mpu_sequence_number(&mmtp_sub_flow->mpu_fragments->media_fragment_unit_vector, mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number);
if(!data_unit_payload_types) {
__WARN("data_unit_payload_types is null!");
goto cleanup;
}
mpu_data_unit_payload_fragments_timed_vector_t* data_unit_payload_fragments = &data_unit_payload_types->timed_fragments_vector;
if(!data_unit_payload_fragments) {
__WARN("data_unit_payload_fragments is null!");
goto cleanup;
}
mmtp_payload_fragments_union_t* mpu_metadata = NULL;
if(mpu_metadata_fragments && mpu_metadata_fragments->timed_fragments_vector.size) {
mpu_metadata = mpu_metadata_fragments->timed_fragments_vector.data[0];
__INFO("recon for mpu_sequence_number: %u, mpu_metadata packet_id: %d", mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number, mpu_metadata->mmtp_packet_header.mmtp_packet_id);
} else {
__WARN("mpu_metadata is NULL!");
}
mmtp_payload_fragments_union_t* fragment_metadata = NULL;
if(mpu_movie_fragments && mpu_movie_fragments->timed_fragments_vector.size) {
fragment_metadata = mpu_movie_fragments->timed_fragments_vector.data[0];
__INFO("recon for mpu_sequence_number: %u, fragment_metadata packet_id: %d", mmtp_payload_previous_for_reassembly->mmtp_mpu_type_packet_header.mpu_sequence_number, fragment_metadata->mmtp_packet_header.mmtp_packet_id);
} else {
__WARN("fragment_metadata is NULL!");
}
int total_fragments = data_unit_payload_fragments->size;
__INFO("in reassembly - total_fragments: %d", total_fragments);
int first_fragment_counter = -1;
int last_fragment_counter = -1;
int started_with_first_fragment_of_du = 0;
int ended_with_last_fragment_of_du = 0;
int total_sample_count = 0;
uint32_t total_mdat_body_size = 0;
//todo - keep an array of our offsets here if we have sequence gaps...
//data_unit payload is only fragment_type = 0x2
for(int i=0; i < total_fragments; i++) {
mmtp_payload_fragments_union_t* packet = data_unit_payload_fragments->data[i];
__MMT_MPU_INFO("i: %d, p: %p, frag indicator is: %d, mpu_sequence_number: %u, size: %u, packet_counter: %u, data_unit payload: %p, block_t: %p, size: %u",
i,
packet,
packet->mpu_data_unit_payload_fragments_timed.mpu_fragmentation_indicator,
packet->mpu_data_unit_payload_fragments_timed.mpu_sequence_number,
packet->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload->i_pos,
packet->mpu_data_unit_payload_fragments_timed.packet_counter,
packet->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload,
packet->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload->p_buffer,
packet->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload->i_pos);
total_mdat_body_size += packet->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload->i_pos;
}
if(fragment_metadata) {
int fragment_metadata_len = fragment_metadata->mmtp_mpu_type_packet_header.mpu_data_unit_payload->i_pos;
uint8_t mdat_box[8];
__MMT_MPU_INFO("total_mdat_body_size: %u, total box size: %u", total_mdat_body_size, total_mdat_body_size+8);
total_mdat_body_size +=8;
memcpy(&mdat_box, &fragment_metadata->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload->p_buffer[fragment_metadata_len-8], 8);
__MMT_MPU_INFO("packet_counter: %u, last 8 bytes of metadata fragment before recalc: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x",
fragment_metadata->mpu_data_unit_payload_fragments_timed.packet_counter,
mdat_box[0], mdat_box[1], mdat_box[2], mdat_box[3], mdat_box[4], mdat_box[5], mdat_box[6], mdat_box[7]);
if(mdat_box[4] == 'm' && mdat_box[5] == 'd' && mdat_box[6] == 'a' && mdat_box[7] == 't') {
mdat_box[0] = (total_mdat_body_size >> 24) & 0xFF;
mdat_box[1] = (total_mdat_body_size >> 16) & 0xFF;
mdat_box[2] = (total_mdat_body_size >> 8) & 0xFF;
mdat_box[3] = (total_mdat_body_size) & 0xFF;
memcpy(&fragment_metadata->mpu_data_unit_payload_fragments_timed.mpu_data_unit_payload->p_buffer[fragment_metadata_len-8], &mdat_box, 4);
__MMT_MPU_INFO("last 8 bytes of metadata fragment updated to: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x",
mdat_box[0], mdat_box[1], mdat_box[2], mdat_box[3], mdat_box[4], mdat_box[5], mdat_box[6], mdat_box[7]);
} else {
__MMT_MPU_ERROR("fragment metadata packet, cant find trailing mdat!");
}
} else {
__MMT_MPU_ERROR("fragment metadata packet IS NULL");
}
__MMT_MPU_INFO("pushing boxes");
pipe_buffer_reader_mutex_lock(pipe_ffplay_buffer);
if(mpu_metadata) {
mpu_push_to_output_buffer_no_locking(pipe_ffplay_buffer, mpu_metadata);
}
if(fragment_metadata) {
mpu_push_to_output_buffer_no_locking(pipe_ffplay_buffer, fragment_metadata);
}
//push to mpu_push_output_buffer
for(int i=0; i < total_fragments; i++) {
mmtp_payload_fragments_union_t* packet = data_unit_payload_fragments->data[i];
mpu_push_to_output_buffer_no_locking(pipe_ffplay_buffer, packet);
}
__INFO("Calling pipe_buffer_condition_signal");
pipe_buffer_notify_semaphore_post(pipe_ffplay_buffer);
pipe_buffer_reader_mutex_unlock(pipe_ffplay_buffer);
mmtp_payload_previous_for_reassembly = mmtp_payload;
//usleep(5000); //sleep 1 ms so our output thread can flush out first box
}
//mmtp_sub_flow_t* packet_subflow = mmtp_payload->mmtp_packet_header.mmtp_sub_flow;
//mpu_dump_flow(udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port, mmtp_payload);
//mpu_dump_reconstitued(udp_packet->udp_flow.dst_ip_addr, udp_packet->udp_flow.dst_port, mmtp_payload);
// mpu_play_object(ffplay_buffer, mmtp_payload);
} else {
//non-timed
}
mmtp_payload_previous_for_reassembly = mmtp_payload;
} else if(mmtp_payload->mmtp_packet_header.mmtp_payload_type == 0x2) {
signaling_message_dump(mmtp_payload);
} else {
_MMTP_WARN("mmtp_packet_parse: unknown payload type of 0x%x", mmtp_payload->mmtp_packet_header.mmtp_payload_type);
goto cleanup;
}
}
}
cleanup:
if(udp_packet->data) {
free(udp_packet->data);
udp_packet->data = NULL;
}
if(udp_packet) {
free(udp_packet);
udp_packet = NULL;
}
}
void* pcap_loop_run_thread(void* dev_pointer) {
char* dev = (char*) dev_pointer;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t* descr;
struct bpf_program fp;
bpf_u_int32 maskp;
bpf_u_int32 netp;
pcap_lookupnet(dev, &netp, &maskp, errbuf);
descr = pcap_open_live(dev, MAX_PCAP_LEN, 1, 0, errbuf);
if(descr == NULL) {
printf("pcap_open_live(): %s",errbuf);
exit(1);
}
char filter[] = "udp";
if(pcap_compile(descr,&fp, filter,0,netp) == -1) {
fprintf(stderr,"Error calling pcap_compile");
exit(1);
}
if(pcap_setfilter(descr,&fp) == -1) {
fprintf(stderr,"Error setting filter");
exit(1);
}
pcap_loop(descr,-1,process_packet,NULL);
return 0;
}
#define MAX_PCAP_LEN 1514
/**
*
* atsc3_mmt_listener_test interface (dst_ip) (dst_port)
*
* arguments:
*/
int main(int argc,char **argv) {
char *dev;
char *filter_dst_ip = NULL;
char *filter_dst_port = NULL;
char *filter_packet_id = NULL;
int dst_port_filter_int;
int dst_ip_port_filter_int;
int dst_packet_id_filter_int;
_MMT_MPU_DEBUG_ENABLED = 1;
_PLAYER_FFPLAY_DEBUG_ENABLED = 1;
_MMTP_DEBUG_ENABLED = 0;
_MPU_DEBUG_ENABLED = 0;
_LLS_DEBUG_ENABLED = 0;
//listen to all flows
if(argc == 2) {
dev = argv[1];
__INFO("listening on dev: %s", dev);
} else if(argc>=4) {
//listen to a selected flow
dev = argv[1];
filter_dst_ip = argv[2];
//skip ip address filter if our params are * or -
if(!(strncmp("*", filter_dst_ip, 1) == 0 || strncmp("-", filter_dst_ip, 1) == 0)) {
dst_ip_addr_filter = (uint32_t*)calloc(1, sizeof(uint32_t));
char* pch = strtok (filter_dst_ip,".");
int offset = 24;
while (pch != NULL && offset>=0) {
uint8_t octet = atoi(pch);
*dst_ip_addr_filter |= octet << offset;
offset-=8;
pch = strtok (NULL, ".");
}
}
if(argc>=4) {
filter_dst_port = argv[3];
if(!(strncmp("*", filter_dst_port, 1) == 0 || strncmp("-", filter_dst_port, 1) == 0)) {
__INFO("832:");
dst_port_filter_int = atoi(filter_dst_port);
dst_ip_port_filter = (uint16_t*)calloc(1, sizeof(uint16_t));
*dst_ip_port_filter |= dst_port_filter_int & 0xFFFF;
}
}
if(argc>=5) {
filter_packet_id = argv[4];
if(!(strncmp("*", filter_packet_id, 1) == 0 || strncmp("-", filter_packet_id, 1) == 0)) {
dst_packet_id_filter_int = atoi(filter_packet_id);
dst_packet_id_filter = (uint16_t*)calloc(1, sizeof(uint16_t));
*dst_packet_id_filter |= dst_packet_id_filter_int & 0xFFFF;
}
}
__INFO("listening on dev: %s, dst_ip: %s (%p), dst_port: %s (%p), dst_packet_id: %s (%p)", dev, filter_dst_ip, dst_ip_addr_filter, filter_dst_port, dst_ip_port_filter, filter_packet_id, dst_packet_id_filter);
} else {
println("%s - a udp mulitcast listener test harness for atsc3 mmt messages", argv[0]);
println("---");
println("args: dev (dst_ip) (dst_port)");
println(" dev: device to listen for udp multicast, default listen to 0.0.0.0:0");
println(" (dst_ip): optional, filter to specific ip address");
println(" (dst_port): optional, filter to specific port");
println("");
exit(1);
}
mmtp_sub_flow_vector = (mmtp_sub_flow_vector_t*)calloc(1, sizeof(mmtp_sub_flow_vector_t));
mmtp_sub_flow_vector_init(mmtp_sub_flow_vector);
lls_slt_monitor = lls_slt_monitor_create();
mkdir("mpu", 0777);
//pipe_ffplay_buffer = pipe_create_ffplay();
#ifndef _TEST_RUN_VALGRIND_OSX_
pthread_t global_pcap_thread_id;
int pcap_ret = pthread_create(&global_pcap_thread_id, NULL, pcap_loop_run_thread, (void*)dev);
assert(!pcap_ret);
pthread_join(global_pcap_thread_id, NULL);
#else
pcap_loop_run(dev);
#endif
return 0;
}
| 37.463104 | 273 | 0.729403 | [
"model"
] |
e7773ff796c90ce1c9b14fab4801037aede5fa48 | 30,074 | cc | C++ | modules/reports/threads.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 119 | 2016-04-14T14:16:22.000Z | 2022-03-08T20:24:38.000Z | modules/reports/threads.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 9 | 2017-04-26T20:48:42.000Z | 2021-09-07T01:52:44.000Z | modules/reports/threads.cc | mueller/mysql-shell | 29bafc5692bd536a12c4e41c54cb587375fe52cf | [
"Apache-2.0"
] | 51 | 2016-07-20T05:06:48.000Z | 2022-03-09T01:20:53.000Z | /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is also distributed with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have included with MySQL.
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "modules/reports/threads.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "modules/mod_shell_reports.h"
#include "modules/reports/native_report.h"
#include "modules/reports/utils.h"
#include "modules/reports/utils_options.h"
#include "mysqlshdk/libs/utils/utils_general.h"
#include "mysqlshdk/libs/utils/utils_sqlstring.h"
#include "mysqlshdk/libs/utils/utils_string.h"
using mysqlshdk::utils::nullable;
namespace mysqlsh {
namespace reports {
namespace {
#define DEFAULT_SORT_ORDER "tid"
#define COLUMN_DESCRIPTIONS \
S("Thread identifiers") \
X("tid", "t.THREAD_ID", "thread ID") \
X("cid", "t.PROCESSLIST_ID", \
"connection ID in case of threads associated with a user connection, or " \
"NULL for a background thread") \
S("Information about a thread") \
X("command", "t.PROCESSLIST_COMMAND", \
"the type of command the thread is executing") \
X("db", "t.PROCESSLIST_DB", \
"the default database, if one is selected; otherwise NULL") \
X("group", "NULLIF(CONCAT(''/*!80000, t.RESOURCE_GROUP*/), '')", \
"the resource group label; this value is NULL if resource groups are not " \
"supported on the current platform or server configuration") \
X("history", "t.HISTORY", \
"whether event history logging is enabled for the thread") \
X("host", "t.PROCESSLIST_HOST", \
"the host name of the client who issued the statement, or NULL for a " \
"background thread") \
X("instr", "t.INSTRUMENTED", \
"whether events executed by the thread are instrumented") \
X("lastwait", "p.last_wait", \
"the name of the most recent wait event for the thread") \
X("lastwaitl", "p.last_wait_latency", \
"the wait time of the most recent wait event for the thread") \
X("memory", "p.current_memory", \
"the number of bytes allocated by the thread") \
X("name", "replace(t.NAME,'thread/','')", \
"the name associated with the current thread instrumentation in the " \
"server") \
X("osid", "t.THREAD_OS_ID", \
"the thread or task identifier as defined by the underlying operating " \
"system, if there is one") \
X("protocol", "t.CONNECTION_TYPE", \
"the protocol used to establish the connection, or NULL for background " \
"threads") \
X("ptid", "t.PARENT_THREAD_ID", \
"If this thread is a subthread, this is the thread ID value of the " \
"spawning thread. ") \
X("started", \
"cast(date_sub(now(), interval t.PROCESSLIST_TIME second) as char)", \
"time when thread started to be in its current state") \
X("state", "t.PROCESSLIST_STATE", \
"an action, event, or state that indicates what the thread is doing") \
X("tidle", \
"if(esc.END_EVENT_ID,(SELECT concat(if(x-(esc.TIMER_END DIV " \
"1e+12)<36000,'0',''),(x-(esc.TIMER_END DIV 1e+12)) DIV " \
"3600,':',lpad(((x-(esc.TIMER_END DIV 1e+12)) DIV " \
"60)%60,2,'0'),':',lpad((x-(esc.TIMER_END DIV 1e+12))%60,2,'0')) FROM " \
"(SELECT gs.VARIABLE_VALUE AS x FROM performance_schema.global_status AS " \
"gs WHERE gs.VARIABLE_NAME = 'Uptime') AS x),NULL)", \
"the time the thread has been idle") \
X("time", \
"concat(if(t.PROCESSLIST_TIME<36000,'0',''),t.PROCESSLIST_TIME DIV " \
"3600,':',lpad((t.PROCESSLIST_TIME DIV " \
"60)%60,2,'0'),':',lpad(t.PROCESSLIST_TIME%60,2,'0'))", \
"the time that the thread has been in its current state,") \
X("type", "t.TYPE", "the thread type, either FOREGROUND or BACKGROUND") \
X("user", "t.PROCESSLIST_USER", \
"the user who issued the statement, or NULL for a background thread") \
S("Information about statements") \
X("digest", "if((esc.END_EVENT_ID is NULL),esc.DIGEST,NULL)", \
"the hash value of the statement digest the thread is executing") \
X("digesttxt", "if((esc.END_EVENT_ID is NULL),esc.DIGEST_TEXT,NULL)", \
"the normalized digest of the statement the thread is executing") \
X("fullscan", "p.full_scan", \
"whether a full table scan was performed by the current statement") \
X("info", "sys.format_statement(replace(t.PROCESSLIST_INFO,'\n',' '))", \
"the statement the thread is executing, truncated to be shorter") \
X("infofull", "replace(t.PROCESSLIST_INFO,'\n',' ')", \
"the statement the thread is executing, or NULL if it is not executing " \
"any statement") \
X("latency", "p.statement_latency", \
"how long the statement has been executing") \
X("llatency", "p.lock_latency", \
"the time spent waiting for locks by the current statement") \
X("nraffected", "p.rows_affected", \
"the number of rows affected by the current statement") \
X("nrexamined", "p.rows_examined", \
"the number of rows read from storage engines by the current statement") \
X("nrsent", "p.rows_sent", \
"the number of rows returned by the current statement") \
X("ntmpdtbls", "p.tmp_disk_tables", \
"the number of internal on-disk temporary tables created by the current " \
"statement") \
X("ntmptbls", "p.tmp_tables", \
"the number of internal in-memory temporary tables created by the " \
"current statement") \
X("pdigest", "if((esc.END_EVENT_ID is NOT NULL),esc.DIGEST,NULL)", \
"the hash value of the last statement digest executed by the thread") \
X("pdigesttxt", "if((esc.END_EVENT_ID is NOT NULL),esc.DIGEST_TEXT,NULL)", \
"the normalized digest of the last statement executed by the thread") \
X("pinfo", "p.last_statement", \
"the last statement executed by the thread, if there is no currently " \
"executing statement or wait") \
X("platency", "p.last_statement_latency", \
"how long the last statement was executed") \
X("progress", "p.progress", \
"the percentage of work completed for stages that support progress " \
"reporting") \
X("stmtid", "concat(esc.THREAD_ID,':',esc.EVENT_ID)", \
"ID of the statement that is currently being executed by the thread") \
S("Counters") \
X("nblocked", \
"(SELECT count(*) FROM sys.innodb_lock_waits AS ilw WHERE " \
"t.PROCESSLIST_ID = ilw.blocking_pid) + (SELECT count(*) FROM " \
"sys.schema_table_lock_waits AS stlw WHERE t.THREAD_ID = " \
"stlw.blocking_thread_id)", \
"the number of other threads blocked by the thread") \
X("nblocking", \
"(SELECT count(*) FROM sys.innodb_lock_waits AS ilw WHERE " \
"t.PROCESSLIST_ID = ilw.waiting_pid) + (SELECT count(*) FROM " \
"sys.schema_table_lock_waits AS stlw WHERE t.THREAD_ID = " \
"stlw.waiting_thread_id)", \
"the number of other threads blocking the thread") \
X("npstmts", \
"(SELECT count(*) FROM performance_schema.prepared_statements_instances " \
"AS psi WHERE psi.OWNER_THREAD_ID = t.THREAD_ID)", \
"the number of prepared statements allocated by the thread") \
X("nvars", \
"(SELECT count(*) FROM performance_schema.user_variables_by_thread AS " \
"uvbt WHERE t.THREAD_ID = uvbt.THREAD_ID)", \
"the number of user variables defined for the thread") \
S("Information about transactions") \
X("ntxrlckd", "trx.TRX_ROWS_LOCKED", \
"the approximate number or rows locked by the current InnoDB transaction") \
X("ntxrmod", "trx.TRX_ROWS_MODIFIED", \
"the number of modified and inserted rows in the current InnoDB " \
"transaction") \
X("ntxtlckd", "trx.TRX_TABLES_LOCKED", \
"the number of InnoDB tables that the current transaction has row locks " \
"on") \
X("txaccess", \
"if(trx.TRX_IS_READ_ONLY IS NULL,NULL,if(trx.TRX_IS_READ_ONLY=1,'READ " \
"ONLY','READ WRITE'))", \
"the access mode of the current InnoDB transaction") \
X("txid", "trx.TRX_ID", \
"ID of the InnoDB transaction that is currently being executed by the " \
"thread") \
X("txisolvl", "trx.TRX_ISOLATION_LEVEL", \
"the isolation level of the current InnoDB transaction") \
X("txstart", "trx.TRX_STARTED", \
"time when thread started executing the current InnoDB transaction") \
X("txstate", "trx.TRX_STATE", "the current InnoDB transaction state") \
X("txtime", "cast(timediff(now(), trx.TRX_STARTED) as char)", \
"the time that the thread is executing the current InnoDB transaction") \
S("Information about I/O events") \
X("ioavgltncy", "io.avg_latency", \
"the average wait time per timed I/O event for the thread") \
X("ioltncy", "io.total_latency", \
"the total wait time of timed I/O events for the thread") \
X("iomaxltncy", "io.max_latency", \
"the maximum single wait time of timed I/O events for the thread") \
X("iominltncy", "io.min_latency", \
"the minimum single wait time of timed I/O events for the thread") \
X("nio", "io.total", "the total number of I/O events for the thread") \
S("Information about client") \
X("pid", "p.pid", "the client process ID") \
X("progname", "p.program_name", "the client program name") \
X("ssl", \
"CASE t.NAME WHEN 'thread/mysqlx/worker' THEN '?' WHEN " \
"'thread/sql/one_connection' THEN (SELECT sbt.VARIABLE_VALUE FROM " \
"performance_schema.status_by_thread AS sbt WHERE sbt.THREAD_ID = " \
"t.THREAD_ID AND sbt.VARIABLE_NAME = 'Ssl_cipher') ELSE '' END", \
"SSL cipher in use by the client") \
S("Diagnostic information") \
X("diagerrno", "esc.MYSQL_ERRNO", "the statement error number") \
X("diagerror", "if(ifnull(esc.ERRORS,0)=0,'NO','YES')", \
"whether an error occurred for the statement") \
X("diagstate", "esc.RETURNED_SQLSTATE", "the statement SQLSTATE value") \
X("diagtext", "esc.RETURNED_SQLSTATE", "the statement error message") \
X("diagwarn", "esc.WARNINGS", "the statement number of warnings") \
S("Statistics") \
X("nseljoin", "esc.SELECT_FULL_JOIN", \
"the number of joins that perform table scans because they do not use " \
"indexes") \
X("nselrjoin", "esc.SELECT_FULL_RANGE_JOIN", \
"the number of joins that used a range search on a reference table") \
X("nselrange", "esc.SELECT_RANGE", \
"the number of joins that used ranges on the first table") \
X("nselrangec", "esc.SELECT_RANGE_CHECK", \
"the number of joins without keys that check for key usage after each " \
"row") \
X("nselscan", "esc.SELECT_SCAN", \
"the number of joins that did a full scan of the first table") \
X("nsortmp", "esc.SORT_MERGE_PASSES", \
"the number of merge passes that the sort algorithm has had to do") \
X("nsortrange", "esc.SORT_RANGE", \
"the number of sorts that were done using ranges") \
X("nsortrows", "esc.SORT_ROWS", "the number of sorted rows") \
X("nsortscan", "esc.SORT_SCAN", \
"the number of sorts that were done by scanning the table") \
S("Special columns") \
X("status", \
"(SELECT sbt.VARIABLE_VALUE FROM performance_schema.status_by_thread AS " \
"sbt WHERE sbt.THREAD_ID = t.THREAD_ID AND sbt.VARIABLE_NAME = ?)", \
"used as <b>status.NAME</b>, provides value of session status variable " \
"'NAME'") \
X("system", \
"(SELECT vbt.VARIABLE_VALUE FROM performance_schema.variables_by_thread " \
"AS vbt WHERE vbt.THREAD_ID = t.THREAD_ID AND vbt.VARIABLE_NAME = ?)", \
"used as <b>system.NAME</b>, provides value of session system variable " \
"'NAME'")
#define X(name, query, _) {name, {name, nullptr, query}},
#define S(section)
bool comparator(const std::string &l, const std::string &r) {
return shcore::str_casecmp(l, r) < 0;
}
const std::map<std::string, Column_definition,
std::function<decltype(comparator)>>
allowed_columns{{COLUMN_DESCRIPTIONS}, comparator};
#undef S
#undef X
constexpr auto query = R"(AS th
FROM performance_schema.threads AS t
LEFT JOIN information_schema.innodb_trx AS trx ON t.PROCESSLIST_ID = trx.TRX_MYSQL_THREAD_ID
LEFT JOIN sys.processlist AS p ON t.THREAD_ID = p.thd_id
LEFT JOIN performance_schema.events_statements_current AS esc ON t.THREAD_ID = esc.THREAD_ID
LEFT JOIN sys.io_by_thread_by_latency AS io ON t.THREAD_ID = io.thread_id
)";
std::vector<std::string> get_details() {
std::vector<std::string> details{
"This report may contain the following columns:"};
#define X(name, _, description) \
details.emplace_back(std::string{"@entry{"} + name + "} " + description);
#define S(section) details.emplace_back(section);
COLUMN_DESCRIPTIONS
#undef S
#undef X
return details;
}
#undef COLUMN_DESCRIPTIONS
#define OPTIONS \
XX(foreground, Bool, "Causes the report to list all foreground threads.", \
"f") \
XX(background, Bool, "Causes the report to list all background threads.", \
"b") \
XX(all, Bool, \
"Causes the report to list all threads, both foreground and background.", \
"A") \
XX(format, String, \
"Allows to specify order and number of columns returned by the report, " \
"optionally defining new column names.", \
"o", \
{"The <b>format</b> option expects a string in the following form: " \
"<b>column[=alias][,column[=alias]]*</b>. If column with the given " \
"name does not exist, all columns that match the given prefix are " \
"selected and alias is ignored."}, \
false, false, nullable<std::string>) \
XX(where, String, "Allows to filter the result.", "", \
std::vector<std::string>( \
{"The <b>where</b> option expects a string in the following format: " \
"<b>column OP value [LOGIC column OP value]*</b>, where:", \
"@li column - name of the column,", "@li value - an SQL value,", \
"@li OP - relational operator: =, !=, <>, >, >=, <, <=, LIKE,", \
"@li LOGIC - logical operator: AND, OR, NOT (case insensitive),", \
"@li the logical expressions can be grouped using parenthesis " \
"characters: ( )."})) \
XX(order_by, String, \
"A comma separated list which specifies the columns to be used to sort " \
"the output.", \
"", {"By default, output is ordered by: <b>" DEFAULT_SORT_ORDER "</b>."}) \
XX(desc, Bool, "Causes the output to be sorted in descending order.", "", \
{"If the <b>desc</b> option is not provided, output is sorted in " \
"ascending order."}) \
XX(limit, Integer, "Limits the number of returned threads.", "l", {}, false, \
false, nullable<uint64_t>)
class Threads_report : public Native_report {
public:
class Config {
public:
static const char *name() { return "threads"; }
static Report::Type type() { return Report::Type::LIST; }
static const char *brief() {
return "Lists threads that belong to the user who owns the current "
"session.";
}
static std::vector<std::string> details() { return get_details(); }
#define X X_GET_OPTIONS
GET_OPTIONS
#undef X
static Report::Argc argc() { return {0, 0}; }
static Report::Examples examples() {
return {{"Show foreground threads, display 'tid' and 'cid' columns and "
"value of 'autocommit' system variable.",
{{"o", "tid,cid,system.autocommit"}, {"foreground", "true"}},
{}},
{"Show background threads with 'tid' greater than 10 and name "
"containing 'innodb' string.",
{{"where", "tid > 10 AND name LIKE '%innodb%'"},
{"background", "true"}},
{}}};
}
};
private:
void parse(const shcore::Array_t & /* argv */,
const shcore::Dictionary_t &options) override {
#define X X_OPTIONS_STRUCT
OPTIONS_STRUCT
#undef X
o.where = "TRUE";
o.order_by = DEFAULT_SORT_ORDER;
#define X X_PARSE_OPTIONS
PARSE_OPTIONS
#undef X
// WHERE part of the query, based on 'all', 'foreground' and 'background'
// options
std::string where;
if (o.all || (o.foreground && o.background)) {
where = "TRUE";
} else if (o.foreground) {
where = "t.TYPE = 'FOREGROUND'";
} else if (o.background) {
where = "t.TYPE = 'BACKGROUND'";
} else {
const auto co = m_session->get_connection_options();
where = shcore::sqlstring(
"t.PROCESSLIST_USER = ? AND t.PROCESSLIST_HOST = ?", 0)
<< co.get_user() << co.get_host();
}
// format
if (!o.format) {
if (o.background && !o.all && !o.foreground) {
o.format = "tid,name,nio,ioltncy,iominltncy,ioavgltncy,iomaxltncy";
} else {
o.format =
"tid,cid,user,host,db,command,time,state,txstate,info,nblocking";
}
}
if (o.format->empty()) {
throw shcore::Exception::argument_error(
"The 'format' parameter cannot be empty.");
}
for (const auto &column : shcore::str_split(*o.format, ",")) {
auto names = shcore::str_split(column, "=");
auto name = std::move(names[0]);
std::string alias;
switch (names.size()) {
case 1:
alias = name;
break;
case 2:
if (names[1].empty()) {
throw shcore::Exception::argument_error(
"Name of the alias in the 'format' parameter cannot be empty.");
}
alias = std::move(names[1]);
break;
default:
throw shcore::Exception::argument_error(
"Invalid format of the 'format' parameter.");
}
try {
m_format_columns.emplace_back(add_column(name));
m_format_names.emplace_back(std::move(alias));
} catch (const std::exception &ex) {
// no exact match found, try to find a partial match
std::vector<std::string> matches;
for (const auto &col : allowed_columns) {
if (shcore::str_ibeginswith(col.first, name) &&
!is_special_column(col.first)) {
matches.emplace_back(col.first);
}
}
if (matches.empty()) {
throw shcore::Exception::argument_error(
"Cannot use '" + name + "' in 'format' parameter: " + ex.what());
} else {
for (auto &m : matches) {
m_format_columns.emplace_back(add_column(m));
m_format_names.emplace_back(std::move(m));
}
}
}
}
// HAVING part of the query, based on 'where' option
if (o.where.empty()) {
throw shcore::Exception::argument_error(
"The 'where' parameter cannot be empty.");
}
std::string having;
try {
having = Sql_condition{[this](const std::string &ident) {
return "th->>'$.\"" + add_column(ident) + "\"'";
}}.parse(o.where);
} catch (const std::exception &e) {
throw shcore::Exception::argument_error(
"Failed to parse 'where' parameter: " + std::string(e.what()));
}
// ORDER BY part of the query
std::string order_by;
if (o.order_by.empty()) {
throw shcore::Exception::argument_error(
"The 'order-by' parameter cannot be empty.");
}
for (const auto &column : shcore::str_split(o.order_by, ",")) {
try {
order_by += "th->'$.\"" + add_column(column) + "\"',";
} catch (const std::exception &ex) {
throw shcore::Exception::argument_error(
"Cannot use '" + column +
"' as a column to order by: " + ex.what());
}
}
// remove extra comma
order_by.pop_back();
m_conditions = shcore::str_format(
"WHERE %s HAVING %s ORDER BY %s %s", where.c_str(), having.c_str(),
order_by.c_str(), o.desc ? "DESC" : "ASC");
if (o.limit) {
m_conditions.append(shcore::sqlstring(" LIMIT ?", 0) << *o.limit);
}
}
shcore::Array_t execute() const override {
std::vector<Column_definition> columns;
for (size_t idx = 0, size = m_format_columns.size(); idx < size; ++idx) {
columns.emplace_back(m_used_columns.at(m_format_columns[idx]));
columns.back().name = m_format_names[idx].c_str();
}
std::vector<Column_definition> used_columns;
std::transform(std::begin(m_used_columns), std::end(m_used_columns),
std::back_inserter(used_columns),
[](const decltype(m_used_columns)::value_type &it) {
return it.second;
});
return create_report_from_json_object(m_session, query + m_conditions,
used_columns, columns);
}
std::string add_column(const std::string &name) {
std::string new_name;
Column_definition column;
const auto pos = name.find(".");
if (std::string::npos == pos) {
const auto col = allowed_columns.find(name);
if (allowed_columns.end() != col) {
if (is_special_column(col->first)) {
throw shcore::Exception::argument_error(
"Column '" + name + "' requires a variable name, i.e.: " + name +
".NAME");
}
new_name = col->first;
column = col->second;
}
} else {
const auto col = allowed_columns.find(name.substr(0, pos));
if (allowed_columns.end() != col && is_special_column(col->first)) {
const std::string variable = name.substr(pos + 1);
column.id = add_to_cache(col->first + "." + variable);
column.query =
add_to_cache(shcore::sqlstring(col->second.query, 0) << variable);
new_name = column.id;
}
}
if (new_name.empty()) {
throw shcore::Exception::argument_error("Unknown column name: " + name);
}
m_used_columns.emplace(new_name, std::move(column));
return new_name;
}
const char *add_to_cache(std::string &&v) {
m_string_cache.emplace_back(std::make_unique<std::string>(move(v)));
return m_string_cache.back()->c_str();
}
bool is_special_column(const std::string &c) const {
static constexpr const char *special[] = {"status", "system"};
return std::end(special) !=
std::find(std::begin(special), std::end(special), c);
}
std::map<std::string, Column_definition> m_used_columns;
std::vector<std::string> m_format_columns;
std::vector<std::string> m_format_names;
std::string m_conditions;
std::vector<std::unique_ptr<std::string>> m_string_cache;
};
} // namespace
void register_threads_report(Shell_reports *reports) {
Native_report::register_report<Threads_report>(reports);
}
} // namespace reports
} // namespace mysqlsh
| 51.059423 | 92 | 0.499302 | [
"vector",
"transform"
] |
e785ea342f40a7d18065523ad62897e2d941b7d1 | 3,278 | cpp | C++ | test/test_simple_moving_average.cpp | LBL-EESA/TECA | 63923b8a12914f3758dc9525239bc48cd8864b39 | [
"BSD-3-Clause-LBNL"
] | 34 | 2017-03-28T14:22:25.000Z | 2022-01-23T05:02:25.000Z | test/test_simple_moving_average.cpp | LBL-EESA/TECA | 63923b8a12914f3758dc9525239bc48cd8864b39 | [
"BSD-3-Clause-LBNL"
] | 476 | 2016-11-28T18:06:06.000Z | 2022-01-25T05:31:42.000Z | test/test_simple_moving_average.cpp | LBL-EESA/TECA | 63923b8a12914f3758dc9525239bc48cd8864b39 | [
"BSD-3-Clause-LBNL"
] | 19 | 2017-04-25T18:15:04.000Z | 2020-11-28T18:16:05.000Z | #include "teca_cf_reader.h"
#include "teca_normalize_coordinates.h"
#include "teca_indexed_dataset_cache.h"
#include "teca_simple_moving_average.h"
#include "teca_cartesian_mesh_writer.h"
#include "teca_cf_writer.h"
#include "teca_dataset_diff.h"
#include "teca_index_executive.h"
#include "teca_system_interface.h"
#include "teca_system_util.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
teca_system_interface::set_stack_trace_on_error();
if (argc < 8)
{
std::cerr << std::endl << "Usage error:" << std::endl
<< "test_simple_moving_average [input regex] [baseline] [first step] [last step]"
" [filter width] [n threads] [array] [array] ..." << std::endl
<< std::endl;
return -1;
}
// parse command line
string regex = argv[1];
string baseline = argv[2];
long first_step = atoi(argv[3]);
long last_step = atoi(argv[4]);
int filter_width = atoi(argv[5]);
int n_threads = atoi(argv[6]);
std::vector<std::string> arrays;
arrays.push_back(argv[7]);
for (int i = 8; i < argc; ++i)
arrays.push_back(argv[i]);
// create the cf reader
p_teca_cf_reader r = teca_cf_reader::New();
r->set_files_regex(regex);
// normalize coords
p_teca_normalize_coordinates c = teca_normalize_coordinates::New();
c->set_input_connection(r->get_output_port());
// ds cache
p_teca_indexed_dataset_cache dsc = teca_indexed_dataset_cache::New();
dsc->set_input_connection(c->get_output_port());
dsc->set_max_cache_size(2*n_threads*filter_width);
// temporal avg
p_teca_simple_moving_average a = teca_simple_moving_average::New();
a->set_filter_width(filter_width);
a->set_filter_type(teca_simple_moving_average::backward);
a->set_input_connection(dsc->get_output_port());
bool do_test = true;
teca_system_util::get_environment_variable("TECA_DO_TEST", do_test);
if (do_test)
{
std::cerr << "running the test..." << std::endl;
baseline += ".*\\.nc$";
p_teca_cf_reader br = teca_cf_reader::New();
br->set_files_regex(baseline);
// executive
p_teca_index_executive rex = teca_index_executive::New();
rex->set_start_index(first_step);
rex->set_end_index(last_step);
rex->set_arrays(arrays);
p_teca_dataset_diff diff = teca_dataset_diff::New();
diff->set_input_connection(0, br->get_output_port());
diff->set_input_connection(1, a->get_output_port());
diff->set_verbose(1);
diff->set_executive(rex);
// TODO : test with threads
//diff->set_thread_pool_size(n_threads);
diff->update();
}
else
{
std::cerr << "writing the baseline..." << std::endl;
baseline += "_%t%.nc";
// writer
p_teca_cf_writer w = teca_cf_writer::New();
w->set_input_connection(a->get_output_port());
w->set_thread_pool_size(n_threads);
w->set_point_arrays(arrays);
w->set_file_name(baseline);
w->set_first_step(first_step);
w->set_last_step(last_step);
w->set_steps_per_file(10000);
w->update();
}
return 0;
}
| 30.351852 | 93 | 0.645821 | [
"vector"
] |
e78abc3470cb6c6a6e64f68a8208fffd67719011 | 4,970 | cpp | C++ | code/server/lua_service_origin/lua_service/engine/server_logic/ServerLogic.cpp | UtopiaCoder/utopia_origin | e9ce25193c21264b1d896d18ae8a472e3d54370c | [
"MIT"
] | null | null | null | code/server/lua_service_origin/lua_service/engine/server_logic/ServerLogic.cpp | UtopiaCoder/utopia_origin | e9ce25193c21264b1d896d18ae8a472e3d54370c | [
"MIT"
] | null | null | null | code/server/lua_service_origin/lua_service/engine/server_logic/ServerLogic.cpp | UtopiaCoder/utopia_origin | e9ce25193c21264b1d896d18ae8a472e3d54370c | [
"MIT"
] | 1 | 2018-12-30T10:03:20.000Z | 2018-12-30T10:03:20.000Z | #include "ServerLogic.h"
#include <thread>
#include <chrono>
#include <ctime>
#include "module_def/module_mgr.h"
#ifdef WIN32
static int getpagesize() { return 4096; }
#else
#include <unistd.h>
#endif // WIN32
extern int64_t RealMs();
ServerLogic *server_logic = nullptr;
const int TRY_MAX_TIMES = 100000;
ServerLogic::ServerLogic()
{
std::vector<size_t> bolck_sizes = { 8, 16, 32, 64, 96, 128, 256, 384, 512, 1024, 2048, 5120 };
m_memory_pool_mgr = new MemoryPoolMgr(bolck_sizes, getpagesize(), 8, 32);
m_module_mgr = new ModuleMgr(this);
m_log_mgr = new LogMgr();
m_timer_mgr = new TimerMgr(RealMs());
m_http_client_mgr = new HttpClientMgr(this);
memset(m_module_params, 0, sizeof(m_module_params));
m_async_task_mgr = new AsyncTaskMgr();
m_dns_service = new DnsService();
}
ServerLogic::~ServerLogic()
{
delete m_http_client_mgr; m_http_client_mgr = nullptr;
delete m_module_mgr; m_module_mgr = nullptr;
delete m_timer_mgr; m_timer_mgr = nullptr;
delete m_async_task_mgr; m_async_task_mgr = nullptr;
delete m_dns_service; m_dns_service = nullptr;
m_log_mgr->Stop();
delete m_log_mgr; m_log_mgr = nullptr;
delete m_memory_pool_mgr;
}
bool ServerLogic::StartLog(ELogLevel log_lvl)
{
return m_log_mgr->Start(log_lvl);
}
void ServerLogic::SetService(IService * service)
{
assert(EServerLogicState_Free == m_state);
assert(service);
assert(nullptr == m_service);
m_module_mgr->SetServiceLogic(service);
m_service = service;
}
bool ServerLogic::Init()
{
if (EServerLogicState_Free != m_state)
return false;
m_state = EServerLogicState_Init;
{
const static int ASYNC_TASK_THREAD_NUM = 2;
m_async_task_mgr->Start(ASYNC_TASK_THREAD_NUM);
m_dns_service->Start();
}
int loop_times = 0;
EModuleRetCode retCode = EModuleRetCode_Succ;
do
{
this->OnFrame();
retCode = m_module_mgr->Init(m_module_params);
std::this_thread::sleep_for(std::chrono::milliseconds(m_loop_span_ms));
} while (EModuleRetCode_Pending == retCode && loop_times++ < TRY_MAX_TIMES);
bool ret = EModuleRetCode_Succ == retCode;
if (!ret)
{
this->Quit();
}
return ret;
}
bool ServerLogic::Awake()
{
if (EServerLogicState_Init != m_state)
return false;
m_state = EServerLogicState_Awake;
int loop_times = 0;
EModuleRetCode retCode = EModuleRetCode_Succ;
do
{
this->OnFrame();
retCode = m_module_mgr->Awake();
std::this_thread::sleep_for(std::chrono::milliseconds(m_loop_span_ms));
} while (EModuleRetCode_Pending == retCode && loop_times++ < TRY_MAX_TIMES);
bool ret = EModuleRetCode_Succ == retCode;
if (!ret) this->Quit();
return ret;
}
void ServerLogic::Update()
{
if (EServerLogicState_Awake != m_state)
return;
m_state = EServerLogicState_Update;
EModuleRetCode retCode = EModuleRetCode_Succ;
do
{
this->OnFrame();
retCode = m_module_mgr->Update();
if (EModuleRetCode_Failed == retCode)
{
this->Quit();
}
int64_t real_ms = RealMs();
int64_t logic_ms = this->LogicMs();
int64_t consume_ms = real_ms - logic_ms;
consume_ms = consume_ms >= 0 ? consume_ms : 0;
// m_log_mgr->Debug("consume_ms {0}", consume_ms);
long long sleep_time = m_loop_span_ms - consume_ms;
if (sleep_time > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));
} while (EServerLogicState_Update == m_state );
}
void ServerLogic::Realse()
{
m_service = nullptr;
m_state = EServerLogicState_Release;
int loop_times = 0;
EModuleRetCode retCode = EModuleRetCode_Succ;
do
{
this->OnFrame();
retCode = m_module_mgr->Realse();
std::this_thread::sleep_for(std::chrono::milliseconds(m_loop_span_ms));
} while (EModuleRetCode_Pending == retCode && loop_times++ < TRY_MAX_TIMES);
}
void ServerLogic::Destroy()
{
m_state = EServerLogicState_Destroy;
{
m_async_task_mgr->Stop();
m_dns_service->Stop();
}
int loop_times = 0;
EModuleRetCode retCode = EModuleRetCode_Succ;
do
{
this->OnFrame();
retCode = m_module_mgr->Destroy();
this->OnFrame();
std::this_thread::sleep_for(std::chrono::milliseconds(m_loop_span_ms));
} while (EModuleRetCode_Pending == retCode && loop_times++ < TRY_MAX_TIMES);
if (nullptr != m_module_params_clear_fn)
{
m_module_params_clear_fn(m_module_params);
}
}
void ServerLogic::Loop()
{
this->OnFrame();
bool ret = true;
ret = ret && this->Init();
ret = ret && this->Awake();
this->Update();
this->Realse();
this->Destroy();
m_state = EServerLogicState_Max;
this->OnFrame();
}
void ServerLogic::Quit()
{
if (m_state <= EServerLogicState_Update)
{
m_state = EServerLogicState_Release;
}
}
INetworkModule * ServerLogic::GetNet()
{
return m_module_mgr->GetModule<INetworkModule>();
}
void ServerLogic::OnFrame()
{
uint64_t old_ms = m_logic_ms;
m_logic_ms = RealMs();
m_logic_sec = m_logic_ms / 1000.0;
if (m_logic_ms > old_ms)
{
m_delta_ms = m_logic_ms - old_ms;
}
else
{
m_delta_ms = 0;
}
m_timer_mgr->UpdateTime(m_logic_ms);
m_async_task_mgr->OnFrame();
m_dns_service->OnFrame();
// m_log_mgr->Flush();
} | 22.798165 | 95 | 0.723541 | [
"vector"
] |
e78b7f53116d3d854901b326bf35b6ed14d325e4 | 12,614 | cpp | C++ | gui/voip/secureCallWnd.cpp | SammyEnigma/im-desktop | d93c1c335c8290b21b69c578c399edf61cb899e8 | [
"Apache-2.0"
] | 2 | 2020-10-23T06:27:27.000Z | 2021-11-12T12:06:12.000Z | gui/voip/secureCallWnd.cpp | john-preston/im-desktop | 271e42db657bdaa8e261f318c627ca5414e0dd87 | [
"Apache-2.0"
] | null | null | null | gui/voip/secureCallWnd.cpp | john-preston/im-desktop | 271e42db657bdaa8e261f318c627ca5414e0dd87 | [
"Apache-2.0"
] | 1 | 2022-03-25T16:10:33.000Z | 2022-03-25T16:10:33.000Z | #include "stdafx.h"
#include "secureCallWnd.h"
#include "../core_dispatcher.h"
#include "../common.shared/config/config.h"
#include "../controls/DialogButton.h"
#include "../utils/gui_coll_helper.h"
#include "../utils/InterConnector.h"
#include "../utils/SChar.h"
#include "../utils/features.h"
#include "../styles/ThemeParameters.h"
#define SECURE_CALL_WINDOW_W Utils::scale_value(360)
#define SECURE_CALL_WINDOW_H Utils::scale_value(320)
#define SECURE_CALL_WINDOW_BORDER Utils::scale_value(24)
#define SECURE_CALL_WINDOW_BORDER_UP Utils::scale_value(22)
#define SECURE_CALL_WINDOW_UP_ARROW Utils::scale_value(8)
#define SECURE_CALL_WINDOW_UP_OFFSET (SECURE_CALL_WINDOW_UP_ARROW + SECURE_CALL_WINDOW_BORDER_UP)
class WidgetWithBorder : public QWidget
{
public:
WidgetWithBorder(QWidget* parent);
protected:
virtual void paintEvent(QPaintEvent* _e) override;
};
Ui::ImageContainer::ImageContainer(QWidget* _parent)
: QWidget(_parent)
, kerning_(0)
{
}
Ui::ImageContainer::~ImageContainer()
{
}
void Ui::ImageContainer::setKerning(int _kerning)
{
kerning_ = _kerning;
calculateRectDraw();
}
void Ui::ImageContainer::calculateRectDraw()
{
int height = 0;
int width = images_.empty() ? 0 : (images_.size() - 1) * kerning_;
std::shared_ptr<QImage> image;
for (unsigned ix = 0; ix < images_.size(); ++ix)
{
image = images_[ix];
assert(!!image);
if (!!image)
{
width += imageDrawSize_.width();
height = std::max(imageDrawSize_.height(), height);
}
}
const QRect rc = rect();
const QPoint center = rc.center();
const int w = std::min(rc.width(), width);
const int h = std::min(rc.height(), height);
rcDraw_ = QRect(center.x() - w*0.5f, center.y() - h*0.5f, w, h);
}
void Ui::ImageContainer::resizeEvent(QResizeEvent* _e)
{
QWidget::resizeEvent(_e);
calculateRectDraw();
}
void Ui::ImageContainer::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.save();
painter.setRenderHint(QPainter::Antialiasing);
std::shared_ptr<QImage> image;
QRect rcDraw = rcDraw_;
for (unsigned ix = 0; ix < images_.size(); ++ix)
{
image = images_[ix];
if (!!image)
{
QRect r(rcDraw.left(), rcDraw.top(), imageDrawSize_.width(), imageDrawSize_.height());
auto resizedImage = image->scaled(Utils::scale_bitmap(r.size()), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
painter.drawImage(r, resizedImage, resizedImage.rect());
rcDraw.setLeft(rcDraw.left() + kerning_ + imageDrawSize_.width());
}
}
painter.restore();
}
void Ui::ImageContainer::swapImagePack(std::vector<std::shared_ptr<QImage> >& _images, const QSize& imageDrawSize)
{
imageDrawSize_ = imageDrawSize;
images_.swap(_images);
calculateRectDraw();
}
QPolygon getPolygon(const QRect& rc)
{
QRect rc1 = rc;
#ifdef __APPLE__
// Fixed border under mac.
rc1.setWidth(rc.width() + 1);
rc1.setHeight(rc.height() + 1);
#endif
const int cx = (rc1.left() + rc1.right()) * 0.5f;
const int cy = rc1.y();
int polygon[7][2];
polygon[0][0] = cx - SECURE_CALL_WINDOW_UP_ARROW;
polygon[0][1] = cy + SECURE_CALL_WINDOW_UP_ARROW;
polygon[1][0] = cx;
polygon[1][1] = cy;
polygon[2][0] = cx + SECURE_CALL_WINDOW_UP_ARROW;
polygon[2][1] = cy + SECURE_CALL_WINDOW_UP_ARROW;
polygon[3][0] = rc1.right();
polygon[3][1] = rc1.y() + SECURE_CALL_WINDOW_UP_ARROW;
polygon[4][0] = rc1.bottomRight().x();
polygon[4][1] = rc1.bottomRight().y();
polygon[5][0] = rc1.bottomLeft().x() + 1;
polygon[5][1] = rc1.bottomLeft().y();
polygon[6][0] = rc1.left() + 1;
polygon[6][1] = rc1.y() + SECURE_CALL_WINDOW_UP_ARROW;
QPolygon arrow;
arrow.setPoints(7, &polygon[0][0]);
return arrow;
}
QLabel* Ui::SecureCallWnd::createUniformLabel_(const QString& _text, const unsigned _fontSize, QSizePolicy _policy)
{
assert(rootWidget_);
QFont f = QApplication::font();
f.setPixelSize(_fontSize);
f.setStyleStrategy(QFont::PreferAntialias);
QLabel* label = new QLabel(rootWidget_);
label->setFont(f);
label->setSizePolicy(_policy);
label->setText(_text);
label->setWordWrap(true);
label->setAlignment(Qt::AlignCenter);
return label;
}
Ui::SecureCallWnd::SecureCallWnd(QWidget* _parent)
: QMenu(_parent)
, rootLayout_(new QVBoxLayout())
, rootWidget_(new WidgetWithBorder(this))
, textSecureCode_ (new ImageContainer(rootWidget_))
{
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
Utils::ApplyStyle(this, qsl("QWidget { background-color: %1; }").arg(Styling::getParameters().getColorHex(Styling::StyleVariable::BASE_GLOBALWHITE)));
{
QVBoxLayout* k = Utils::emptyVLayout();
setLayout(k);
k->addWidget(rootWidget_);
}
rootLayout_->setContentsMargins(SECURE_CALL_WINDOW_BORDER, SECURE_CALL_WINDOW_UP_OFFSET, SECURE_CALL_WINDOW_BORDER, SECURE_CALL_WINDOW_BORDER);
rootLayout_->setSpacing(0);
rootLayout_->setAlignment(Qt::AlignCenter);
rootWidget_->setLayout(rootLayout_);
{ // window header text
QLabel* label = createUniformLabel_(QT_TRANSLATE_NOOP("voip_pages", "Call is secured"), Utils::scale_value(24), QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred));
assert(label);
if (label)
{
label->setContentsMargins(0, 0, 0, Utils::scale_value(18));
rootLayout_->addWidget(label);
}
}
{ // secure code emogi widget
textSecureCode_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
//textSecureCode_->setFixedHeight(Utils::scale_value(80));
textSecureCode_->setKerning(Utils::scale_value(12));
rootLayout_->addWidget(textSecureCode_);
}
{ // invitation description
QLabel* label = createUniformLabel_(QT_TRANSLATE_NOOP("voip_pages", "For security check, you can verify your images with your partner"), Utils::scale_value(15));
if (label)
{
Utils::ApplyStyle(label, qsl("QLabel { color : %1; }").arg(Styling::getParameters().getColorHex(Styling::StyleVariable::BASE_PRIMARY)));
rootLayout_->addWidget(label);
}
}
{ // details button
QFont f = QApplication::font();
f.setPixelSize(Utils::scale_value(15));
f.setStyleStrategy(QFont::PreferAntialias);
f.setUnderline(true);
QWidget* underBtnWidget = new QWidget(rootWidget_);
underBtnWidget->setContentsMargins(0, 0, 0, 0);
rootLayout_->addWidget(underBtnWidget);
QHBoxLayout* underBtnLayout = Utils::emptyHLayout();
underBtnWidget->setLayout(underBtnLayout);
underBtnLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding));
QPushButton* referenceBtn = new QPushButton(rootWidget_);
referenceBtn->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
referenceBtn->setFlat(true);
referenceBtn->setFont(f);
referenceBtn->setText(QT_TRANSLATE_NOOP("voip_pages", "How it works"));
connect(referenceBtn, SIGNAL(clicked()), this, SLOT(onDetailsButtonClicked()), Qt::QueuedConnection);
const QString DETAILS_BUTTON_STYLE = qsl(
"QPushButton { text-align: bottom; vertical-align: text-bottom; color: %1;"
"border-style: none; background-color: transparent; margin-bottom: 21dip; }"
).arg(Styling::getParameters().getColorHex(Styling::StyleVariable::TEXT_PRIMARY));
Utils::ApplyStyle(referenceBtn, DETAILS_BUTTON_STYLE);
referenceBtn->setFocusPolicy(Qt::NoFocus);
referenceBtn->setCursor(Qt::CursorShape::PointingHandCursor);
underBtnLayout->addWidget(referenceBtn);
referenceBtn->setVisible(config::get().is_on(config::features::show_security_call_link));
underBtnLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding));
}
{ // btn OK -> start encryption
QFont f = QApplication::font();
f.setPixelSize(Utils::scale_value(17));
f.setStyleStrategy(QFont::PreferAntialias);
QWidget* underBtnWidget = new QWidget(rootWidget_);
underBtnWidget->setContentsMargins(0, 0, 0, 0);
rootLayout_->addWidget(underBtnWidget);
QHBoxLayout* underBtnLayout = Utils::emptyHLayout();
underBtnWidget->setLayout(underBtnLayout);
underBtnLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding));
QPushButton* btnOk = new DialogButton(this, QT_TRANSLATE_NOOP("popup_window", "Next"), DialogButtonRole::CONFIRM);
btnOk->setCursor(QCursor(Qt::PointingHandCursor));
//Utils::ApplyStyle(btnOk, Styling::getParameters().getButtonCommonQss());
btnOk->setText(QT_TRANSLATE_NOOP("voip_pages", "OK"));
connect(btnOk, SIGNAL(clicked()), this, SLOT(onBtnOkClicked()), Qt::QueuedConnection);
underBtnLayout->addWidget(btnOk);
underBtnLayout->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Expanding));
}
setMinimumSize(SECURE_CALL_WINDOW_W, SECURE_CALL_WINDOW_H);
setMaximumSize(SECURE_CALL_WINDOW_W, SECURE_CALL_WINDOW_H);
resize(SECURE_CALL_WINDOW_W, SECURE_CALL_WINDOW_H);
updateMask();
}
void Ui::SecureCallWnd::setSecureCode(const std::string& _text)
{
assert(textSecureCode_ && !_text.empty());
voip_proxy::VoipEmojiManager& voipEmojiManager = Ui::GetDispatcher()->getVoipController().getEmojiManager();
std::vector<std::shared_ptr<QImage>> images;
images.reserve(5);
auto decoded = QString::fromUtf8(_text.c_str());
QTextStream textStream(&decoded, QIODevice::ReadOnly);
unsigned codepoint;
while (true)
{
const Utils::SChar superChar = Utils::ReadNextSuperChar(textStream);
if (superChar.IsNull())
break;
QByteArray byteArray = superChar.ToQString().toUtf8();
char* dataPtr = byteArray.data();
size_t dataSz = byteArray.size();
assert(dataPtr && dataSz);
if (!dataPtr || !dataSz)
continue;
codepoint = 0;
codepoint |= ((*dataPtr & 0xff) << 24) * (dataSz >= 4); dataPtr += 1 * (dataSz >= 4);
codepoint |= ((*dataPtr & 0xff) << 16) * (dataSz >= 3); dataPtr += 1 * (dataSz >= 3);
codepoint |= ((*dataPtr & 0xff) << 8) * (dataSz >= 2); dataPtr += 1 * (dataSz >= 2);
codepoint |= ((*dataPtr & 0xff) << 0) * (dataSz >= 1); dataPtr += 1 * (dataSz >= 1);
std::shared_ptr<QImage> image(new QImage());
if (voipEmojiManager.getEmoji(codepoint, Utils::scale_bitmap_with_value(64), *image))
images.push_back(image);
}
textSecureCode_->swapImagePack(images, Utils::scale_value(QSize(64, 64)));
}
void Ui::SecureCallWnd::updateMask()
{
auto arrow = getPolygon(rect());
QPainterPath path(QPointF(0, 0));
path.addPolygon(arrow);
QRegion region(path.toFillPolygon().toPolygon());
setMask(region);
}
Ui::SecureCallWnd::~SecureCallWnd()
{
}
void Ui::SecureCallWnd::showEvent(QShowEvent* _e)
{
QMenu::showEvent(_e);
Q_EMIT onSecureCallWndOpened();
}
void Ui::SecureCallWnd::hideEvent(QHideEvent* _e)
{
QMenu::hideEvent(_e);
Q_EMIT onSecureCallWndClosed();
}
void Ui::SecureCallWnd::changeEvent(QEvent* _e)
{
QMenu::changeEvent(_e);
if (QEvent::ActivationChange == _e->type())
{
if (!isActiveWindow())
hide();
}
}
void Ui::SecureCallWnd::onBtnOkClicked()
{
hide();
onSecureCallWndClosed();
}
void Ui::SecureCallWnd::onDetailsButtonClicked()
{
QDesktopServices::openUrl(Features::securityCallLink());
// On Mac it does not hide automatically, we make it manually.
hide();
onSecureCallWndClosed();
}
void Ui::SecureCallWnd::resizeEvent(QResizeEvent * event)
{
QWidget::resizeEvent(event);
#ifdef __APPLE__
updateMask();
#endif
}
WidgetWithBorder::WidgetWithBorder(QWidget* parent) : QWidget (parent) {}
void WidgetWithBorder::paintEvent(QPaintEvent* _e)
{
QWidget::paintEvent(_e);
if (parentWidget())
{
// Draw the border.
QPolygon polygon = getPolygon(parentWidget()->rect());
polygon.push_back(polygon.point(0));
QPainterPath path(QPointF(0, 0));
path.addPolygon(polygon);
QPainter painter(this);
QColor borderColor("#000000");
borderColor.setAlphaF(0.5);
painter.strokePath(path, QPen(borderColor, Utils::scale_value(2)));
}
}
| 32.594315 | 181 | 0.664579 | [
"vector"
] |
e78f479efcf8dc7ddb4345a59b7bb777b446955f | 6,632 | cpp | C++ | s/balancer_policy.cpp | rauchg/mongo | 5a99f52a74d5135c8464871c376e72c6f61a86c8 | [
"Apache-2.0"
] | 3 | 2015-02-19T10:06:35.000Z | 2021-04-21T21:28:57.000Z | s/balancer_policy.cpp | kharayo/mongo | 5a99f52a74d5135c8464871c376e72c6f61a86c8 | [
"Apache-2.0"
] | null | null | null | s/balancer_policy.cpp | kharayo/mongo | 5a99f52a74d5135c8464871c376e72c6f61a86c8 | [
"Apache-2.0"
] | 2 | 2015-02-19T10:19:03.000Z | 2020-10-29T07:00:33.000Z | // balancer_policy.cpp
/**
* Copyright (C) 2010 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pch.h"
#include "config.h"
#include "../client/dbclient.h"
#include "../util/stringutils.h"
#include "../util/unittest.h"
#include "balancer_policy.h"
namespace mongo {
// limits map fields
BSONField<long long> LimitsFields::currSize( "currSize" );
BSONField<bool> LimitsFields::hasOpsQueued( "hasOpsQueued" );
BalancerPolicy::ChunkInfo* BalancerPolicy::balance( const string& ns,
const ShardToLimitsMap& shardToLimitsMap,
const ShardToChunksMap& shardToChunksMap,
int balancedLastTime ){
pair<string,unsigned> min("",numeric_limits<unsigned>::max());
pair<string,unsigned> max("",0);
vector<string> drainingShards;
for (ShardToChunksIter i = shardToChunksMap.begin(); i!=shardToChunksMap.end(); ++i ){
// Find whether this shard's capacity or availability are exhausted
const string& shard = i->first;
BSONObj shardLimits;
ShardToLimitsIter it = shardToLimitsMap.find( shard );
if ( it != shardToLimitsMap.end() ) shardLimits = it->second;
const bool maxedOut = isSizeMaxed( shardLimits );
const bool draining = isDraining( shardLimits );
const bool opsQueued = hasOpsQueued( shardLimits );
// Is this shard a better chunk receiver then the current one?
// Shards that would be bad receiver candidates:
// + maxed out shards
// + draining shards
// + shards with operations queued for writeback
const unsigned size = i->second.size();
if ( ! maxedOut && ! draining && ! opsQueued ){
if ( size < min.second ){
min = make_pair( shard , size );
}
}
// Check whether this shard is a better chunk donor then the current one.
// Draining shards take a lower priority than overloaded shards.
if ( size > max.second ){
max = make_pair( shard , size );
}
if ( draining && (size > 0)){
drainingShards.push_back( shard );
}
}
// If there is no candidate chunk receiver -- they may have all been maxed out,
// draining, ... -- there's not much that the policy can do.
if ( min.second == numeric_limits<unsigned>::max() ){
log() << "no availalable shards to take chunks" << endl;
return NULL;
}
log(1) << "collection : " << ns << endl;
log(1) << "donor : " << max.second << " chunks on " << max.first << endl;
log(1) << "receiver : " << min.second << " chunks on " << min.first << endl;
if ( ! drainingShards.empty() ){
string drainingStr;
joinStringDelim( drainingShards, &drainingStr, ',' );
log(1) << "draining : " << ! drainingShards.empty() << "(" << drainingShards.size() << ")" << endl;
}
// Solving imbalances takes a higher priority than draining shards. Many shards can
// be draining at once but we choose only one of them to cater to per round.
const int imbalance = max.second - min.second;
const int threshold = balancedLastTime ? 2 : 8;
string from, to;
if ( imbalance >= threshold ){
from = max.first;
to = min.first;
} else if ( ! drainingShards.empty() ){
from = drainingShards[ rand() % drainingShards.size() ];
to = min.first;
} else {
// Everything is balanced here!
return NULL;
}
const vector<BSONObj>& chunksFrom = shardToChunksMap.find( from )->second;
const vector<BSONObj>& chunksTo = shardToChunksMap.find( to )->second;
BSONObj chunkToMove = pickChunk( chunksFrom , chunksTo );
log() << "chose [" << from << "] to [" << to << "] " << chunkToMove << endl;
return new ChunkInfo( ns, to, from, chunkToMove );
}
BSONObj BalancerPolicy::pickChunk( const vector<BSONObj>& from, const vector<BSONObj>& to ){
// It is possible for a donor ('from') shard to have less chunks than a recevier one ('to')
// if the donor is in draining mode.
if ( to.size() == 0 )
return from[0];
if ( from[0]["min"].Obj().woCompare( to[to.size()-1]["max"].Obj() , BSONObj() , false ) == 0 )
return from[0];
if ( from[from.size()-1]["max"].Obj().woCompare( to[0]["min"].Obj() , BSONObj() , false ) == 0 )
return from[from.size()-1];
return from[0];
}
bool BalancerPolicy::isSizeMaxed( BSONObj limits ){
// If there's no limit information for the shard, assume it can be a chunk receiver
// (i.e., there's not bound on space utilization)
if ( limits.isEmpty() ){
return false;
}
long long maxUsage = limits[ ShardFields::maxSize.name() ].Long();
if ( maxUsage == 0 ){
return false;
}
long long currUsage = limits[ LimitsFields::currSize.name() ].Long();
if ( currUsage < maxUsage ){
return false;
}
return true;
}
bool BalancerPolicy::isDraining( BSONObj limits ){
BSONElement draining = limits[ ShardFields::draining.name() ];
if ( draining.eoo() || ! draining.Bool() ){
return false;
}
return true;
}
bool BalancerPolicy::hasOpsQueued( BSONObj limits ){
BSONElement opsQueued = limits[ LimitsFields::hasOpsQueued.name() ];
if ( opsQueued.eoo() || ! opsQueued.Bool() ){
return false;
}
return true;
}
} // namespace mongo
| 38.55814 | 121 | 0.560163 | [
"vector"
] |
e7939ef19dac859bb900a875d352d014de31dcdc | 9,497 | cpp | C++ | slgr_engine/feat_mfcc.cpp | nathandouglas/pyslgr | 89076bbb432ff9b8159b84e1894bb7883ea59617 | [
"Apache-2.0"
] | 8 | 2017-03-22T14:34:05.000Z | 2021-04-26T03:05:22.000Z | slgr_engine/feat_mfcc.cpp | nathandouglas/pyslgr | 89076bbb432ff9b8159b84e1894bb7883ea59617 | [
"Apache-2.0"
] | 1 | 2017-10-15T23:18:45.000Z | 2017-10-30T23:08:03.000Z | slgr_engine/feat_mfcc.cpp | nathandouglas/pyslgr | 89076bbb432ff9b8159b84e1894bb7883ea59617 | [
"Apache-2.0"
] | 4 | 2016-12-21T18:47:19.000Z | 2018-11-09T14:09:55.000Z | //
// Copyright 2016 MIT Lincoln Laboratory, Massachusetts Institute of Technology
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use these files 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.
//
// MFCCs
// Refactored from LLSpeech 2.2.10 code & BC Speech Tools:
// filtbank.cc, mfb_to_cep.cc, mfb_to_cep_subs.cc, mfb_utils.cc, pcm_to_feat.cc, pcm_to_mfb_subs.cc, vec_utils.cc
// Written by BC 10/18/10
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#include "speech_tools.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using boost::property_tree::read_json;
#define PI 3.141592653589793
typedef float* flt_ptr;
static float warp (float freq, float alpha, float sfreq);
//
// Main processing routine
//
void MFCC_Features::process (Signal &x, string &config_str)
{
// MFCC configuration
config(x, config_str);
// Set up storage
Frame f(win_len, win_inc);
mag_fft m(win_len);
vec<REAL_FEAT> x_frame(win_len);
vec<REAL_FFT> x_mag(n2_fft+1);
vec<REAL_FFT> x_fb(num_filt_bl);
vec<REAL_FEAT> x_cep(num_features);
REAL_FEAT *feat_ptr;
// Allocate space for features
num_vectors = f.get_num_frames(x);
feat_ptr = feat = new REAL_FEAT[num_vectors*num_features];
energy = new REAL_FEAT[num_vectors];
// Loop across frames
int i, j;
for (i=0; i<num_vectors; i++) {
// Frame based pre-processing
f.get_frame(x, i);
f.dither(dither);
f.rm_dc();
f.hamming_window();
energy[i] = f.energy();
// FFT magnitudes -- FFT not quite the same as LLSpeech
x_frame = f.vector();
x_mag = m.calc(x_frame);
// Pre-emphasis
x_mag.scale(*preemp_filt);
// Calculate filterbanks with bandlimiting
x_fb = calc_fb(x_mag);
if (fb_only) {
for (j=0; j<num_features; j++, feat_ptr++)
*feat_ptr = x_fb.data[j];
} else {
// Cepstral coefficients
x_cep = icostrans(x_fb);
for (j=0; j<num_features; j++, feat_ptr++)
*feat_ptr = x_cep.data[j];
}
}
features_available = true;
energy_available = true;
}
MFCC_Features::MFCC_Features ()
{
filt_beg = 0;
filt_end = 0;
filt = 0;
fc = 0;
preemp_filt = 0;
icos_matrix = 0;
}
MFCC_Features::~MFCC_Features ()
{
delete[] filt_beg;
delete[] filt_end;
delete[] fc;
if (filt!=0) {
for (int i=0; i<num_filt; i++)
delete[] (filt[i]);
}
delete[] filt;
delete preemp_filt;
delete[] icos_matrix;
}
void MFCC_Features::config (Signal &x, string &config)
{
bool linear = false;
int tgt_num_filt = -1;
istringstream is(config);
ptree pt;
try {
read_json(is, pt);
alpha = pt.get<float>("alpha");
dither = pt.get<float>("dither");
fb_low = pt.get<float>("fb_low");
fb_hi = pt.get<float>("fb_hi");
keep_c0 = pt.get<bool>("keep_c0");
linear = pt.get<bool>("linear");
num_cep = pt.get<int>("num_cep");
win_inc_ms = pt.get<float>("win_inc_ms");
win_len_ms = pt.get<float>("win_len_ms");
if (pt.find("fb_only")==pt.not_found())
fb_only = false;
else
fb_only = pt.get<bool>("fb_only");
if (pt.find("tgt_num_filt")!=pt.not_found())
tgt_num_filt = pt.get<int>("tgt_num_filt");
} catch (exception &e) {
throw ST_exception(string("MFCC_Features::config: error in config string, ")+e.what());
}
// Sanity check
float f_max = x.sampling_freq()/2.0f;
if ((fb_low<0) || (fb_hi<fb_low) || (fb_hi>f_max))
throw ST_exception("MFCC_Features::process -- filterbank parameters don't make sense.");
sampling_freq = x.sampling_freq();
// Find window parameters
win_inc = (int) ((x.sampling_freq()*win_inc_ms)/1000);
win_len = (int) ((x.sampling_freq()*win_len_ms)/1000);
if ((win_len % 2) != 0)
win_len++;
if (win_inc<=0 || win_len<=0)
throw ST_exception("MFCC_Features::process -- Window increment or length is <= 0.");
// Initialize filterbank
for (n_fft=1; n_fft<win_len; n_fft*= 2);
n2_fft = n_fft/2;
init_filtbank(f_max, n2_fft+1, linear, tgt_num_filt);
if (fb_low==0 && fb_hi==f_max) { // Use full band
fb_index_low = 0;
fb_index_hi = num_filt-1;
} else {
fb_index_low = filtbank_get_filt_num(fb_low);
fb_index_hi = filtbank_get_filt_num(fb_hi);
}
num_filt_bl = fb_index_hi-fb_index_low+1;
// Initialize cepstral processing
if ((num_cep <= 0) || (num_cep>(num_filt_bl-1)))
throw ST_exception("Number of cepstral coefficients larger than number of filters.");
num_features = 0;
if (fb_only) {
num_features = num_filt_bl;
} else {
if (keep_c0)
num_features = 1;
num_features += num_cep;
}
num_base_features = num_features;
init_icostrans();
// Initialize pre-emphasis
preemp_filt = new vec<REAL_FFT> (n2_fft+1);
float finc = (float) (f_max/(n2_fft+1.0));
float f = 0;
for (int j=0; j<=n2_fft; f += finc, j++)
preemp_filt->data[j] = (REAL_FEAT) (1.0 + f*f/2.5e5);
}
vec<REAL_FFT> MFCC_Features::calc_fb (vec<REAL_FFT> &mag)
{
int i, j, k, l;
vec<REAL_FFT> x_fb(num_filt_bl);
REAL_FFT val;
for (i=fb_index_low, l=0; i<=fb_index_hi; i++, l++) {
val = 0;
for (j=filt_beg[i], k=0; j<filt_end[i]; j++, k++)
val += mag.data[j]*filt[i][k];
val = (REAL_FFT) (10.0*log10(val + 1e-20)-40.0);
x_fb.data[l] = val;
}
return x_fb;
}
int MFCC_Features::filtbank_get_filt_num (float freq)
{
int i;
for (i=1; i<=num_filt && fc[i]<=freq; i++);
i--;
if(i < 1)
return 0;
if (i==num_filt)
return num_filt-1;
if ((fc[i+1]-freq) < (freq-fc[i]))
i++; // move to closest center freq
return i-1;
}
vec<REAL_FEAT> MFCC_Features::icostrans (vec<REAL_FFT> &x)
{
vec<REAL_FEAT> out(num_features);
int i, j, k;
REAL_FFT val;
// Matrix vector multiply -- should use BLAS
i = keep_c0 ? 0 : 1;
for (k=0; k<num_features; k++, i++) {
val = 0;
for (j=0; j<num_filt_bl; j++)
val += icos_matrix[i*num_filt_bl+j]*x.data[j];
out.data[k] = (REAL_FEAT) val;
}
return out;
}
void MFCC_Features::init_icostrans ()
{
float tmp, W;
int i, j;
tmp = (float) (1.0/num_filt_bl);
W = (float) (PI*tmp);
icos_matrix = new REAL_FFT[(num_cep+1)*num_filt_bl];
for (i=0; i < (num_cep+1); i++) {
for (j=0; j < num_filt_bl; j++) {
icos_matrix[i*num_filt_bl+j] = (float) (cos((double) i*(j+0.5)*W)*tmp);
}
}
}
void MFCC_Features::init_filtbank (const float fmax, const int num_dft, bool linear, int tgt_num_filt)
{
float f, *Fptr, area;
float finc, delta_f;
int i, j, nf, init_len, final_len;
finc = fmax/(num_dft-1);
if (linear) {
if (tgt_num_filt<=0)
delta_f = 100;
else
delta_f = fmax/(tgt_num_filt+1);
for (nf=0, f=-delta_f; f<fmax; nf++)
f += delta_f;
fc = new float[nf];
for (nf=0, f=-delta_f; f<fmax; nf++)
fc[nf] = warp(f+=delta_f, alpha, fmax);
nf -= 2;
if ((fc[nf]+fc[nf+1])/2 > fmax)
nf--;
init_len = (int) ((fc[2]-fc[0])/finc + 1);
} else {
// Determine length of fc
for (nf=11, f=1000; f<fmax; nf++)
f *= 1.1f;
fc = new float[nf];
// Center frequencies
for (i=0; i<=10; i++) // 100 Hz
fc[i] = (float) warp((float) i*100, alpha, fmax);
for (nf=11, f=1000; f<fmax; nf++) { // 10% spacing
f *= 1.1f;
fc[nf] = warp(f, alpha, fmax);
}
nf -= 2;
if ((fc[nf]+fc[nf+1])/2 > fmax)
nf--;
// Determine maximum initial length
init_len = 0;
for (i = 1; i < nf + 1; i++) {
int x = (int) ((fc[i+1]-fc[i-1])/finc + 1);
init_len = x > init_len ? x : init_len;
}
}
filt_beg = new int[nf];
filt_end = new int[nf];
filt = new flt_ptr[nf];
float *tmp_filt = new float[init_len];
for (i=1; i<=nf; ++i) {
area = 0.0;
Fptr = tmp_filt;
filt_beg[i-1] = 0;
filt_end[i-1] = 0;
for (j=0, f=0.0; (f<fmax) && (j<num_dft); f+=finc, j++) {
if ((f <= fc[i-1]) || (f >= fc[i+1]))
continue;
if (f < fc[i]) {
if (filt_beg[i-1] == 0)
filt_beg[i-1] = j;
*Fptr = (f-fc[i-1])/(fc[i]-fc[i-1]);
area += (*Fptr++);
} else {
*Fptr = (fc[i+1]-f)/(fc[i+1]-fc[i]);
filt_end[i-1] = j+1;
area += (*Fptr++);
}
}
// Single DFT sample in filter passband, happens with very small windows (e.g., 5ms)
if ((filt_end[i-1]==0) && (filt_beg[i-1]!=0))
filt_end[i-1] = filt_beg[i-1]+1;
else if ((filt_end[i-1]!=0) && (filt_beg[i-1]==0))
filt_beg[i-1] = filt_end[i-1]-1;
final_len = filt_end[i-1] - filt_beg[i-1];
filt[i-1] = new float[final_len];
for (j=0; j<final_len; j++)
filt[i-1][j] = tmp_filt[j]/area;
} // next i
delete[] tmp_filt;
num_filt = nf;
} // init_filterbank
float MFCC_Features::duration(void)
{
return (float) (((float) num_vectors)*(0.001*win_inc_ms));
}
float MFCC_Features::get_win_inc_ms (void)
{
return win_inc_ms;
}
//
// Local functions
//
static float warp (float freq, float alpha, float sfreq)
{
float ret;
float fr = (float) (freq * PI / sfreq);
ret = (float) (fr + 2.0f * atan((double)(1.0 - alpha) * sin((double)fr) / (1.0 - (1.0 - alpha) * cos((double)fr))));
ret *= (float) (sfreq/PI);
return ret;
}
| 24.861257 | 120 | 0.617669 | [
"vector"
] |
e7949dcd822886205ae0e13d9a94cdc0a7d6da69 | 27,039 | cpp | C++ | rosplan_knowledge_base/src/VALfiles/Action.cpp | Wonseok-Oh/rosplan | c6d83a0b2da034d310497d73fadb0bfe6abff812 | [
"BSD-2-Clause"
] | 278 | 2015-03-21T00:28:14.000Z | 2022-03-28T05:34:14.000Z | rosplan_knowledge_base/src/VALfiles/Action.cpp | Wonseok-Oh/rosplan | c6d83a0b2da034d310497d73fadb0bfe6abff812 | [
"BSD-2-Clause"
] | 205 | 2015-05-08T10:58:36.000Z | 2022-03-24T16:32:42.000Z | rosplan_knowledge_base/src/VALfiles/Action.cpp | Wonseok-Oh/rosplan | c6d83a0b2da034d310497d73fadb0bfe6abff812 | [
"BSD-2-Clause"
] | 156 | 2015-05-15T10:12:49.000Z | 2022-02-17T17:41:20.000Z | /************************************************************************
* Copyright 2008, Strathclyde Planning Group,
* Department of Computer and Information Sciences,
* University of Strathclyde, Glasgow, UK
* http://planning.cis.strath.ac.uk/
*
* Maria Fox, Richard Howey and Derek Long - VAL
* Stephen Cresswell - PDDL Parser
*
* This file is part of VAL, the PDDL validator.
*
* VAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* VAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VAL. If not, see <http://www.gnu.org/licenses/>.
*
************************************************************************/
/*-----------------------------------------------------------------------------
VAL - The Automatic Plan Validator for PDDL+
$Date: 2009-02-05 10:50:10 $
$Revision: 1.2 $
Maria Fox, Richard Howey and Derek Long - PDDL+ and VAL
Stephen Cresswell - PDDL Parser
maria.fox@cis.strath.ac.uk
derek.long@cis.strath.ac.uk
stephen.cresswell@cis.strath.ac.uk
richard.howey@cis.strath.ac.uk
By releasing this code we imply no warranty as to its reliability
and its use is entirely at your own risk.
Strathclyde Planning Group
http://planning.cis.strath.ac.uk
----------------------------------------------------------------------------*/
#include "State.h"
#include "Action.h"
#include "Plan.h"
#include "main.h"
#include "Validator.h"
#include "Ownership.h"
#include "Utils.h"
#include "Proposition.h"
#include "LaTeXSupport.h"
#include "RobustAnalyse.h"
#include <string>
#include <cmath>
//#define vector std::vector
//#define list std::list
//#define map std::map
using std::map;
using std::list;
using std::vector;
using std::for_each;
namespace VAL1_2 {
Action::~Action()
{
pre->destroy();
};
bool Action::operator==(const plan_step & ps) const
{
if(act->name != ps.op_sym) return false;
var_symbol_list::const_iterator i = act->parameters->begin();
for(const_symbol_list::const_iterator j = ps.params->begin();
j != ps.params->end();++j,++i)
{
if(bindings.find(*i)->second != *j)
return false;
};
return true;
};
string Action::getName() const
{
string n;
if(LaTeX) n = "\\action{";
n += "(" + act->name->getName();
for( var_symbol_list::const_iterator i = act->parameters->begin() ; i != act->parameters->end(); ++i)
{
n += " " + bindings.find(*i)->second->getName();
};
n += ")";
if(LaTeX)
{
n += "}";
latexString(n);
};
return n;
};
//minimal action name for internal use
string Action::getName0() const
{
return actionName;
/*string n = act->name->getName();
for( var_symbol_list::const_iterator i = act->parameters->begin() ; i != act->parameters->end(); ++i)
{
n += bindings.find(*i)->second->getName();
};
return n; */
};
InvariantAction::~InvariantAction()
{
delete act;
};
CtsEffectAction::~CtsEffectAction()
{
delete act;
};
DurativeActionElement::~DurativeActionElement()
{
delete act;
const_cast<goal_list *>(durs)->clear(); // We don't own those expressions, so don't delete them!
delete durs;
};
bool Action::confirmPrecondition(const State * s) const
{
bool ans = pre->evaluate(s);
if(LaTeX && !ans) *report << " \\notOK \\\\\n \\> ";
return ans;
};
bool InvariantAction::confirmPrecondition(const State * s) const
{
if(TestingPNERobustness) ace->addActiveFEs(true);
else ace->addActiveFEs();
const_cast<Proposition*>(pre)->setUpComparisons(ace,rhsIntervalOpen);
DerivedGoal::setACE(ace,rhsIntervalOpen);
bool ans = pre->evaluate(s);
DerivedGoal::setACE(0,rhsIntervalOpen);
if(LaTeX && !ans) *report << " \\notOK \\\\\n \\> ";
return ans;
};
void Action::addTriggeredEvents(vector<const Action *> & triggeredEvents,vector<const Action *> & oldTriggeredEvents, vector<const StartAction *> & triggeredStartProcesses, vector<const EndAction *> & triggeredEndProcesses) const
{
triggeredEvents.push_back(this);
oldTriggeredEvents.push_back(this);
};
void EndAction::addTriggeredEvents(vector<const Action *> & triggeredEvents,vector<const Action *> & oldTriggeredEvents, vector<const StartAction *> & triggeredStartProcesses, vector<const EndAction *> & triggeredEndProcesses) const
{
oldTriggeredEvents.push_back(this);
triggeredEndProcesses.push_back(this);
};
void StartAction::addTriggeredEvents(vector<const Action *> & triggeredEvents,vector<const Action *> & oldTriggeredEvents, vector<const StartAction *> & triggeredStartProcesses, vector<const EndAction *> & triggeredEndProcesses) const
{
oldTriggeredEvents.push_back(this);
triggeredStartProcesses.push_back(this);
};
void Action::addErrorRecord(double t,const State * s) const
{
vld->getErrorLog().addPrecondition(t,this,s);
};
void InvariantAction::addErrorRecord(double t,const State * s) const
{
try
{
vld->getErrorLog().addUnsatInvariant(t - pre->getEndOfInterval(), t, pre->getIntervals(s),this,s);
}
catch(PolyRootError & prError)
{
vld->getErrorLog().addUnsatInvariant(t - pre->getEndOfInterval(), t, Intervals(),this,s,true);
};
};
bool
DurativeActionElement::confirmPrecondition(const State * s) const
{
double testDuration = duration;
double testTolerance = s->getTolerance();
if(Robust) //test the duration constraint according to the original duration given in the plan
{
testDuration = planStep->originalDuration;
testTolerance = 0.001;// 0.00000001; //1e-08, to within acceptable limits for calculations, should be as small as possible
};
for(goal_list::const_iterator i = durs->begin();i != durs->end();++i)
{
const comparison * c = dynamic_cast<const comparison *>(*i);
double d = s->evaluate(c->getRHS(),bindings);
bool test = true;
switch(c->getOp())
{
case E_GREATER:
test = (testDuration > d);
break;
case E_LESS:
test = (testDuration < d);
break;
case E_GREATEQ:
test = (testTolerance >= d - testDuration);
if(!test && Verbose)
{
if(LaTeX) *report << "\\notOK \\\\\n \\> ";
*report << "Tolerance of " << d-testDuration
<< " required for " << this << "\n";
};
break;
case E_LESSEQ:
test = (testDuration - d <= testTolerance);
if(!test && Verbose)
{
if(LaTeX) *report << "\\notOK \\\\\n \\> ";
*report << "Tolerance of " << testDuration - d
<< " required for " << this << "\n";
};
break;
case E_EQUALS:
test = (testDuration > d?testDuration - d:d - testDuration) < testTolerance;
if(!test && Verbose)
{
if(LaTeX) *report << " \\notOK \\\\\n \\> ";
*report << "Tolerance of " << ((testDuration > d)?testDuration -d:d-testDuration)
<< " required for " << this << "\n";
};
break;
default:
break;
};
if(!test)
{
if(Verbose)
{
if(LaTeX) *report << "\\\\\n \\> ";
*report << "Failed duration constraint in " << this << "\n";
if(LaTeX) *report << "\\\\\n \\> ";
};
if(ErrorReport)
{
double time = s->getValidator()->getCurrentHappeningTime();
s->getValidator()->getErrorLog().addUnsatDurationCondition(time,this,s,fabs(d-testDuration));
};
return false;
};
};
bool ans = pre->evaluate(s);
if(LaTeX && !ans) *report << " \\notOK \\\\\n \\> ";
return ans;
};
void StartAction::displayDurationAdvice(const State * s) const
{
double testDuration = planStep->originalDuration;
double testTolerance = 0.001;
for(goal_list::const_iterator i = durs->begin();i != durs->end();++i)
{
const comparison * c = dynamic_cast<const comparison *>(*i);
double d = s->evaluate(c->getRHS(),bindings);
bool test;
switch(c->getOp())
{
case E_GREATER:
test = (testDuration > d);
if(!test)
{
*report << "Failed duration constraint: Increase duration by at least " << d-testDuration;
if(LaTeX) *report << "\\\\";
*report << "\n";
};
break;
case E_LESS:
test = (testDuration < d);
if(!test)
{
*report << "Failed duration constraint: Decrease duration by at least " << testDuration - d;
if(LaTeX) *report << "\\\\";
*report << "\n";
};
break;
case E_GREATEQ:
test = (s->getTolerance() >= d - testDuration);
if(!test)
{
*report << "Failed duration constraint: Increase duration by at least " << d-testDuration;
if(LaTeX) *report << "\\\\";
*report << "\n";
};
break;
case E_LESSEQ:
test = (testDuration - d <= testTolerance);
if(!test)
{
*report << "Failed duration constraint: Decrease duration by at least " << testDuration - d;
if(LaTeX) *report << "\\\\";
*report << "\n";
};
break;
case E_EQUALS:
test = (testDuration > d?testDuration - d:d - testDuration) < testTolerance;
if(!test)
{
*report << "Failed duration constraint: Set the duration to " << d;
if(LaTeX) *report << "\\\\";
*report << "\n";
};
break;
default:
break;
};
};
};
void Action::displayEventInfomation() const
{
if(LaTeX)
{
*report << "\\> \\aeventtriggered{"<<*this<<"}\\\\\n";
}
else if(Verbose)
{
*report << "Triggered event "<<*this<<"\n";
};
};
void StartAction::displayEventInfomation() const
{
if(LaTeX)
{
*report << "\\> \\aprocessactivated{"<<getName()<<"}\\\\\n";
}
else if(Verbose)
{
*report << "Activated process "<<getName()<<"\n";
};
};
void EndAction::displayEventInfomation() const
{
if(LaTeX)
{
*report << "\\> \\aprocessunactivated{"<<getName()<<"}\\\\\n";
}
else if(Verbose)
{
*report << "Unactivated process "<<getName()<<"\n";
};
};
struct MIP {
Ownership & own;
MIP(Ownership & o) : own(o) {};
void operator()(const CondCommunicationAction * cca)
{
cca->markInitialPreconditions(own);
};
};
void
StartAction::markOwnedPreconditions(Ownership & o) const
{
for_each(condActions.begin(),condActions.end(),MIP(o));
DurativeActionElement::markOwnedPreconditions(o);
};
void CondCommunicationAction::markInitialPreconditions(Ownership& o) const
{
if(initPre)
initPre->markOwnedPreconditions(this,o);
};
bool
StartAction::confirmPrecondition(const State * s) const
{
for(vector<const CondCommunicationAction *>::const_iterator i = condActions.begin();
i != condActions.end();++i)
{
if(!(*i)->confirmInitialPrecondition(s))
{
if(LaTeX) *report << " \\notOK \\\\\n \\> ";
return false;
};
};
if(ctsEffects != 0) //may be no ctsEffect action if no cts effects
{
for(vector<const CondCommunicationAction *>::const_iterator i = ctsEffects->condActions.begin();
i != ctsEffects->condActions.end();++i)
{
if(!(*i)->confirmInitialPrecondition(s))
{
if(LaTeX) *report << " \\notOK \\\\\n \\> ";
return false;
};
};
};
return DurativeActionElement::confirmPrecondition(s);
};
bool CondCommunicationAction::confirmInitialPrecondition(const State * s) const
{
cout << "First one being checked\n";
if(!initPre)
{
status = true;
return true;
};
status = initPre->evaluate(s);
cout << "Status now " << status << "\n";
return true;
};
void
Action::markOwnedPreconditions(Ownership & o) const
{
pre->markOwnedPreconditions(this,o);
};
void
DurativeActionElement::markOwnedPreconditions(Ownership & o) const
{
pre->markOwnedPreconditions(this,o);
for(goal_list::const_iterator i = durs->begin();i != durs->end();++i)
{
const comparison * c = dynamic_cast<const comparison *>(*i);
o.markOwnedPreconditionFEs(this,c->getRHS(),bindings);
};
};
// Perhaps should be void - throw an exception if the ownership conditions are
// violated?
bool
Action::constructEffects(Ownership & o,EffectsRecord & e,const State * s,bool markPreCons) const
{
/* We are going to work through the effect_lists to handle each component in
* turn. We have a PropositionFactory that we can use to construct the literals
* for the terminal conditions.
*
* There is recursion required to handle conditional effects.
*/
return handleEffects(o,e,s,act->effects,markPreCons);
};
struct FAEhandler {
Validator * vld;
const Action * a;
Ownership & o;
EffectsRecord & e;
const State * s;
const effect_lists * effs;
Environment & bds;
var_symbol_list::const_iterator i;
const var_symbol_list::const_iterator endpt;
vector<const_symbol *> cs;
// Switched from var_symbol_tab to var_symbol_list (var_symbol_tab seems to be empty
// in certain cases where it is not expected to be...)
FAEhandler(Validator * v,const Action * ia,Ownership & io,EffectsRecord & ie,const State *is,
const forall_effect * eff,const Environment & bs) :
vld(v), a(ia), o(io), e(ie), s(is), effs(eff->getEffects()), bds(*bs.copy(v)),
i(eff->getVarsList()->begin()), endpt(eff->getVarsList()->end()),
cs(vld->range(*i)) {};
bool handle(bool markPreCons)
{
//cout << "About to handle an effect\n";
if(i == endpt)
{
//cout << "i was ended\n";
Environment * env = bds.copy(vld);
return a->handleEffects(o,e,s,effs,*env,markPreCons);
};
var_symbol_list::const_iterator j = i++;
// Inefficient to repeat the lookup for the range of (*i) when dropping down through this variable
// for second+ times.
vector<const_symbol *> ds = i != endpt?vld->range(*i):vector<const_symbol *>();
ds.swap(cs);
for(vector<const_symbol *>::iterator k = ds.begin();k != ds.end();++k)
{
//cout << "Handling " << (*j)->getName() << " = " << (*k)->getName() << " and i: " << (i==endpt) << "\n";
bds[*j] = *k;
if(!handle(markPreCons))
{
i = j;
ds.swap(cs);
return false;
}
};
i = j;
ds.swap(cs);
return true;
};
};
bool
Action::handleEffects(Ownership & o,EffectsRecord & e,
const State * s,const effect_lists * effs,const Environment & bds,bool markPreCons) const
{
for(list<simple_effect*>::const_iterator i = effs->add_effects.begin();
i != effs->add_effects.end();++i)
{
const SimpleProposition * p = vld->pf.buildLiteral((*i)->prop,bds);
if(!o.ownsForAdd(this,p))
{
return false;
};
e.pushAdd(p);
};
for(list<simple_effect*>::const_iterator i1 = effs->del_effects.begin();
i1 != effs->del_effects.end();++i1)
{
const SimpleProposition * p = vld->pf.buildLiteral((*i1)->prop,bds);
if(!o.ownsForDel(this,p))
{
return false;
};
e.pushDel(p);
};
for(list<cond_effect*>::const_iterator i2 = effs->cond_effects.begin();
i2 != effs->cond_effects.end();++i2)
{
// First check preconditions are satisfied.
const Proposition * p = vld->pf.buildProposition((*i2)->getCondition(),bds);
if(p->evaluate(s))
{
if( (markPreCons && !p->markOwnedPreconditions(this,o)) ||
!handleEffects(o,e,s,(*i2)->getEffects(),bds,markPreCons))
{
p->destroy();
if(Verbose)
*report << "Violation in conditional effect in " << this;
return false;
};
};
p->destroy();
};
for(list<assignment*>::const_iterator i3 = effs->assign_effects.begin();
i3 != effs->assign_effects.end();++i3)
{
// LHS is owned for appropriate update.
// RHS will be owned as if for preconditions.
// Assignment cannot be applied because of the usual problem of conditional
// effects. RHS can be evaluated and then the update recorded.
const FuncExp * lhs = vld->fef.buildFuncExp((*i3)->getFTerm(),bds);
FEScalar v = s->evaluate((*i3)->getExpr(),bds);
if(!o.markOwnedEffectFE(this,lhs,(*i3)->getOp(),(*i3)->getExpr(),bds))
{
return false;
};
e.addFEffect(lhs,(*i3)->getOp(),v);
};
for(list<forall_effect*>::const_iterator i4 = effs->forall_effects.begin();
i4 != effs->forall_effects.end();++i4)
{
FAEhandler faeh(vld,this,o,e,s,*i4,bds);
if(!faeh.handle(markPreCons)) return false;
};
return true;
};
bool Action::handleEffects(Ownership & o,EffectsRecord & e,
const State * s,const effect_lists * effs,bool markPreCons) const
{
return handleEffects(o,e,s,effs,bindings,markPreCons);
};
Action::Action(Validator * v,const operator_ * a,const const_symbol_list* bs) :
act(a), bindings(buildBindings(a,*bs)),
timedInitialLiteral(a->name->getName().substr(0,6)=="Timed "),
vld(v), pre(vld->pf.buildProposition(act->precondition,bindings)), planStep(0)
{
string n = act->name->getName();
for( var_symbol_list::const_iterator i = act->parameters->begin() ; i != act->parameters->end(); ++i)
{
n += bindings.find(*i)->second->getName();
};
actionName = n;
};
Action::Action(Validator * v,const operator_ * a,Environment * bs) :
act(a), bindings(*bs),
timedInitialLiteral(a->name->getName().substr(0,6)=="Timed "),
vld(v), pre(vld->pf.buildProposition(act->precondition,bindings)), planStep(0)
{
string n = act->name->getName();
for( var_symbol_list::const_iterator i = act->parameters->begin() ; i != act->parameters->end(); ++i)
{
n += bindings.find(*i)->second->getName();
};
actionName = n;
cout << "Just built " << n << "\n";
};
Action::Action(Validator * v,const operator_ * a,const vector<const_symbol *> & bs) :
act(a), bindings(buildBindings(a,bs)),
timedInitialLiteral(a->name->getName().substr(0,6)=="Timed "),
vld(v), pre(vld->pf.buildProposition(act->precondition,bindings)), planStep(0)
{
string n = act->name->getName();
for( var_symbol_list::const_iterator i = act->parameters->begin() ; i != act->parameters->end(); ++i)
{
n += bindings.find(*i)->second->getName();
};
actionName = n;
};
Action::Action(Validator * v,const operator_ * a,const const_symbol_list* bs,const plan_step * ps) :
act(a), bindings(buildBindings(a,*bs)),
timedInitialLiteral(a->name->getName().substr(0,6)=="Timed "),
vld(v), pre(vld->pf.buildProposition(act->precondition,bindings)), planStep(ps)
{
string n = act->name->getName();
for( var_symbol_list::const_iterator i = act->parameters->begin() ; i != act->parameters->end(); ++i)
{
n += bindings.find(*i)->second->getName();
};
actionName = n;
};
void buildForAllCondActions(Validator * vld,const durative_action * da,
const const_symbol_list * params,goal_list * gls,
goal_list * gli,goal_list * gle,effect_lists * locels,
effect_lists * locele,const var_symbol_list * vars,
var_symbol_list::const_iterator i,
vector<const CondCommunicationAction *> & condActions,
Environment * env)
{
cout << "OK, ready to go\n";
if(i == vars->end())
{
cout << "Ready to construct one\n";
condActions.push_back(new CondCommunicationAction(vld,da,params,gls,gli,gle,locels,locele,env));
}
else
{
vector<const_symbol *> vals = vld->range(*i);
const var_symbol * v = *i;
++i;
for(vector<const_symbol*>::iterator j = vals.begin();j != vals.end();++j)
{
cout << " considering value " << (*j)->getName() << "\n";
(*env)[v] = *j;
buildForAllCondActions(vld,da,params,gls,gli,gle,locels,locele,vars,i,condActions,env);
};
--i;
}
}
CondCommunicationAction::CondCommunicationAction(Validator * v,const durative_action * a,const const_symbol_list * bs,
goal_list * gs,goal_list * gi,goal_list * ge,
effect_lists * es,effect_lists * el) :
Action(v,new safeaction(a->name,a->parameters,new conj_goal(const_cast<goal_list*>(ge)),el,a->symtab),bs),
status(true),
gls(new conj_goal(const_cast<goal_list*>(gs))),
initPre(gs->empty()?0:vld->pf.buildProposition(gls,bindings)),
gli(new conj_goal(const_cast<goal_list*>(gi))),
invPre(gi->empty()?0:vld->pf.buildProposition(gli,bindings)),
gle(act->precondition),
els(es), ele(el), vars(0) {};
CondCommunicationAction::CondCommunicationAction(Validator * v,const durative_action * a,const const_symbol_list * bs,
goal_list * gs,goal_list * gi,goal_list * ge,
effect_lists * es,effect_lists * el,Environment * vs) :
Action(v,new safeaction(a->name,a->parameters,new conj_goal(const_cast<goal_list*>(ge)),el,a->symtab),vs),
status(true),
gls(new conj_goal(const_cast<goal_list*>(gs))),
// initPre(gs->empty()?0:vld->pf.buildProposition(gls,bindings)),
gli(new conj_goal(const_cast<goal_list*>(gi))),
// invPre(gi->empty()?0:vld->pf.buildProposition(gli,bindings)),
gle(act->precondition),
els(es), ele(el), vars(vs)
{
cout << "I have a real forall CCA to build for variables: ";
};
CondCommunicationAction::~CondCommunicationAction() {
delete initPre;
delete invPre;
delete act;
conj_goal * cg = dynamic_cast<conj_goal*>(gls);
if(cg) const_cast<goal_list *>(cg->getGoals())->clear();
cg = dynamic_cast<conj_goal*>(gli);
if(cg) const_cast<goal_list *>(cg->getGoals())->clear();
delete gls;
delete gli;
els->add_effects.clear();
els->del_effects.clear();
els->forall_effects.clear();
els->cond_effects.clear();
els->assign_effects.clear();
delete els;
};
void Action::adjustContext(ExecutionContext & ec) const
{};
void Action::adjustContextInvariants(ExecutionContext & ec) const
{};
void Action::adjustActiveCtsEffects(ActiveCtsEffects & ace) const
{};
struct ContextAdder {
ExecutionContext & ec;
ContextAdder(ExecutionContext & e) : ec(e) {};
void operator()(const CondCommunicationAction* cca)
{
if(cca->isActive())
ec.addCondAction(cca);
};
};
void StartAction::adjustContext(ExecutionContext & ec) const
{
ec.addInvariant(invariant);
for_each(condActions.begin(),condActions.end(),ContextAdder(ec));
};
void StartAction::adjustActiveCtsEffects(ActiveCtsEffects & ace) const
{
ace.addCtsEffect(ctsEffects);
};
struct ContextRemover {
ExecutionContext & ec;
ContextRemover(ExecutionContext & e) : ec(e) {};
void operator()(const CondCommunicationAction* cca)
{
ec.removeCondAction(cca);
};
};
void EndAction::adjustContextInvariants(ExecutionContext & ec) const
{
if(invariant != 0) invariant->setRhsIntervalOpen(true);
for(vector<const CondCommunicationAction *>::const_iterator i = condActions.begin(); i != condActions.end(); ++i)
{
(*i)->setRhsIntervalOpen(true);
};
};
void StartAction::adjustContextInvariants(ExecutionContext & ec) const
{
if(invariant != 0) invariant->setRhsIntervalOpen(false);
for(vector<const CondCommunicationAction *>::const_iterator i = condActions.begin(); i != condActions.end(); ++i)
{
(*i)->setRhsIntervalOpen(false);
};
};
void EndAction::adjustContext(ExecutionContext & ec) const
{
ec.removeInvariant(invariant);
for_each(condActions.begin(),condActions.end(),ContextRemover(ec));
};
void EndAction::adjustActiveCtsEffects(ActiveCtsEffects & ace) const
{
ace.removeCtsEffect(ctsEffects);
};
ostream & operator <<(ostream & o,const Action & a)
{
a.write(o);
return o;
};
ostream & operator <<(ostream & o,const Action * const a)
{
a->write(o);
return o;
};
void CondCommunicationAction::markOwnedPreconditions(Ownership & o) const
{
if(invPre && status)
invPre->markOwnedPreconditions(this,o);
};
bool CondCommunicationAction::confirmPrecondition(const State * s) const
{
cout << "Checking a CondAction prec\n";
if(invPre && status)
{
if(TestingPNERobustness) ace->addActiveFEs(true);
else ace->addActiveFEs();
const_cast<Proposition*>(invPre)->setUpComparisons(ace,rhsIntervalOpen);
DerivedGoal::setACE(ace,rhsIntervalOpen);
if(!invPre->evaluate(s)) status = false;
DerivedGoal::setACE(0,rhsIntervalOpen);
};
return true;
};
bool CondCommunicationAction::constructEffects(Ownership & o,EffectsRecord & e,const State * s,bool markPreCons) const
{
return true;
};
bool CondCommunicationAction::constructFinalEffects(Ownership & o,EffectsRecord & e,const State * s) const
{
if(status)
{
return Action::constructEffects(o,e,s,true);
};
return true;
};
bool EndAction::constructEffects(Ownership & o,EffectsRecord & e,const State * s,bool markPreCons) const
{
if(!Action::constructEffects(o,e,s,markPreCons))
{
return false;
};
for(vector<const CondCommunicationAction*>::const_iterator i = condActions.begin();
i != condActions.end();++i)
{
if(!(*i)->constructFinalEffects(o,e,s))
{
if(Verbose)
{
*report << "Failure in application of effects for temporal conditional effect in " << (*i) << "\n";
};
return false;
};
};
return true;
};
void CtsEffectAction::displayCtsFtns() const
{
//for LaTeX use in plan validation
for(map<const FuncExp *,ActiveFE*>::const_iterator afe = ace->activeFEs.begin(); afe != ace->activeFEs.end(); ++afe)
{
*report << " \\> \\function{"<<*(afe->first)<<"}{"<< *(afe->second->ctsFtn) << "}\\\\\n";
};
};
bool CtsEffectAction::constructEffects(Ownership & o,EffectsRecord & e,const State * s,bool markPreCons) const
{
//deal with all cts effects at once as given from ace
if(ace != 0)
{
//process cts effects, build polys etc, conditional cts effects handled here also
if(TestingPNERobustness) ace->addActiveFEs(true);
else ace->addActiveFEs();
for(map<const FuncExp *,ActiveFE*>::const_iterator i = ace->activeFEs.begin();
i != ace->activeFEs.end();++i)
{
e.addFEffect(i->first,E_ASSIGN_CTS, i->second->evaluate(ace->localUpdateTime) );
};
//record points for graph drawing
if(LaTeX)
{
latex.LaTeXBuildGraph(ace,s);
};
}
else
{
UnrecognisedCondition uc;
throw uc;
};
return true;
};
const Action * StartAction::partner() const {return otherEnd;};
const Action * InvariantAction::partner() const {return start;};
const Action * CtsEffectAction::partner() const {return start;};
const Action * CondCommunicationAction::partner() const {return start;};
};
| 26.66568 | 235 | 0.624172 | [
"vector"
] |
e79f80be3e333095d54482dc1db8347dcc3d23ab | 27,534 | cxx | C++ | panda/src/glxdisplay/glxGraphicsStateGuardian.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/glxdisplay/glxGraphicsStateGuardian.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/glxdisplay/glxGraphicsStateGuardian.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file glxGraphicsStateGuardian.cxx
* @author drose
* @date 2003-01-27
*/
#include "glxGraphicsStateGuardian.h"
#include "config_glxdisplay.h"
#include "config_glgsg.h"
#include "lightReMutexHolder.h"
#include <dlfcn.h>
TypeHandle glxGraphicsStateGuardian::_type_handle;
/**
*
*/
glxGraphicsStateGuardian::
glxGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe,
glxGraphicsStateGuardian *share_with) :
PosixGraphicsStateGuardian(engine, pipe)
{
_share_context=0;
_context=0;
_display=0;
_screen=0;
_visual=0;
_visuals=0;
_fbconfig=0;
_context_has_pbuffer = false;
_context_has_pixmap = false;
_slow = false;
_supports_swap_control = false;
_supports_fbconfig = false;
_supports_pbuffer = false;
_uses_sgix_pbuffer = false;
if (share_with != (glxGraphicsStateGuardian *)NULL) {
_prepared_objects = share_with->get_prepared_objects();
_share_context = share_with->_context;
}
_checked_get_proc_address = false;
_glXGetProcAddress = NULL;
_temp_context = (GLXContext)NULL;
_temp_xwindow = (X11_Window)NULL;
_temp_colormap = (Colormap)NULL;
}
/**
*
*/
glxGraphicsStateGuardian::
~glxGraphicsStateGuardian() {
destroy_temp_xwindow();
if (_visuals != (XVisualInfo *)NULL) {
XFree(_visuals);
}
if (_context != (GLXContext)NULL) {
glXDestroyContext(_display, _context);
_context = (GLXContext)NULL;
}
}
/**
* Gets the FrameBufferProperties to match the indicated visual.
*/
void glxGraphicsStateGuardian::
get_properties(FrameBufferProperties &properties, XVisualInfo *visual) {
int use_gl, render_mode, double_buffer, stereo,
red_size, green_size, blue_size,
alpha_size, ared_size, agreen_size, ablue_size, aalpha_size,
depth_size, stencil_size;
glXGetConfig(_display, visual, GLX_USE_GL, &use_gl);
glXGetConfig(_display, visual, GLX_RGBA, &render_mode);
glXGetConfig(_display, visual, GLX_DOUBLEBUFFER, &double_buffer);
glXGetConfig(_display, visual, GLX_STEREO, &stereo);
glXGetConfig(_display, visual, GLX_RED_SIZE, &red_size);
glXGetConfig(_display, visual, GLX_GREEN_SIZE, &green_size);
glXGetConfig(_display, visual, GLX_BLUE_SIZE, &blue_size);
glXGetConfig(_display, visual, GLX_ALPHA_SIZE, &alpha_size);
glXGetConfig(_display, visual, GLX_ACCUM_RED_SIZE, &ared_size);
glXGetConfig(_display, visual, GLX_ACCUM_GREEN_SIZE, &agreen_size);
glXGetConfig(_display, visual, GLX_ACCUM_BLUE_SIZE, &ablue_size);
glXGetConfig(_display, visual, GLX_ACCUM_ALPHA_SIZE, &aalpha_size);
glXGetConfig(_display, visual, GLX_DEPTH_SIZE, &depth_size);
glXGetConfig(_display, visual, GLX_STENCIL_SIZE, &stencil_size);
properties.clear();
if (use_gl == 0) {
// If we return a set of properties without setting either rgb_color or
// indexed_color, then this indicates a visual that's no good for any kind
// of rendering.
return;
}
if (double_buffer) {
properties.set_back_buffers(1);
}
if (stereo) {
properties.set_stereo(1);
}
if (render_mode) {
properties.set_rgb_color(1);
} else {
properties.set_indexed_color(1);
}
properties.set_rgba_bits(red_size, green_size, blue_size, alpha_size);
properties.set_stencil_bits(stencil_size);
properties.set_depth_bits(depth_size);
properties.set_accum_bits(ared_size+agreen_size+ablue_size+aalpha_size);
// Set both hardware and software bits, indicating not-yet-known.
properties.set_force_software(1);
properties.set_force_hardware(1);
}
/**
* Gets the FrameBufferProperties to match the indicated GLXFBConfig
*/
void glxGraphicsStateGuardian::
get_properties_advanced(FrameBufferProperties &properties,
bool &context_has_pbuffer, bool &context_has_pixmap,
bool &slow, GLXFBConfig config) {
properties.clear();
if (_supports_fbconfig) {
// Now update our framebuffer_mode and bit depth appropriately.
int render_type, double_buffer, stereo, red_size, green_size, blue_size,
alpha_size, ared_size, agreen_size, ablue_size, aalpha_size,
depth_size, stencil_size, samples, drawable_type, caveat, srgb_capable;
_glXGetFBConfigAttrib(_display, config, GLX_RENDER_TYPE, &render_type);
_glXGetFBConfigAttrib(_display, config, GLX_DOUBLEBUFFER, &double_buffer);
_glXGetFBConfigAttrib(_display, config, GLX_STEREO, &stereo);
_glXGetFBConfigAttrib(_display, config, GLX_RED_SIZE, &red_size);
_glXGetFBConfigAttrib(_display, config, GLX_GREEN_SIZE, &green_size);
_glXGetFBConfigAttrib(_display, config, GLX_BLUE_SIZE, &blue_size);
_glXGetFBConfigAttrib(_display, config, GLX_ALPHA_SIZE, &alpha_size);
_glXGetFBConfigAttrib(_display, config, GLX_ACCUM_RED_SIZE, &ared_size);
_glXGetFBConfigAttrib(_display, config, GLX_ACCUM_GREEN_SIZE, &agreen_size);
_glXGetFBConfigAttrib(_display, config, GLX_ACCUM_BLUE_SIZE, &ablue_size);
_glXGetFBConfigAttrib(_display, config, GLX_ACCUM_ALPHA_SIZE, &aalpha_size);
_glXGetFBConfigAttrib(_display, config, GLX_DEPTH_SIZE, &depth_size);
_glXGetFBConfigAttrib(_display, config, GLX_STENCIL_SIZE, &stencil_size);
_glXGetFBConfigAttrib(_display, config, GLX_SAMPLES, &samples);
_glXGetFBConfigAttrib(_display, config, GLX_DRAWABLE_TYPE, &drawable_type);
_glXGetFBConfigAttrib(_display, config, GLX_CONFIG_CAVEAT, &caveat);
_glXGetFBConfigAttrib(_display, config, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
context_has_pbuffer = false;
if ((drawable_type & GLX_PBUFFER_BIT)!=0) {
context_has_pbuffer = true;
}
context_has_pixmap = false;
if ((drawable_type & GLX_PIXMAP_BIT)!=0) {
context_has_pixmap = true;
}
slow = false;
if (caveat == GLX_SLOW_CONFIG) {
slow = true;
}
if ((drawable_type & GLX_WINDOW_BIT)==0) {
// We insist on having a context that will support an onscreen window.
return;
}
if (double_buffer) {
properties.set_back_buffers(1);
}
if (stereo) {
properties.set_stereo(true);
}
if (srgb_capable) {
properties.set_srgb_color(true);
}
if ((render_type & GLX_RGBA_BIT)!=0) {
properties.set_rgb_color(true);
}
if ((render_type & GLX_COLOR_INDEX_BIT)!=0) {
properties.set_indexed_color(true);
}
properties.set_rgba_bits(red_size, green_size, blue_size, alpha_size);
properties.set_stencil_bits(stencil_size);
properties.set_depth_bits(depth_size);
properties.set_accum_bits(ared_size+agreen_size+ablue_size+aalpha_size);
properties.set_multisamples(samples);
// Set both hardware and software bits, indicating not-yet-known.
properties.set_force_software(1);
properties.set_force_hardware(1);
}
}
/**
* Selects a visual or fbconfig for all the windows and buffers that use this
* gsg. Also creates the GL context and obtains the visual.
*/
void glxGraphicsStateGuardian::
choose_pixel_format(const FrameBufferProperties &properties,
X11_Display *display,
int screen, bool need_pbuffer, bool need_pixmap) {
_display = display;
_screen = screen;
_context = 0;
_fbconfig = 0;
_visual = 0;
if (_visuals != (XVisualInfo *)NULL) {
XFree(_visuals);
_visuals = NULL;
}
_fbprops.clear();
// First, attempt to create a context using the XVisual interface. We need
// this before we can query the FBConfig interface, because we need an
// OpenGL context to get the required extension function pointers.
destroy_temp_xwindow();
choose_temp_visual(properties);
if (_temp_context == NULL) {
// No good.
return;
}
// Now we have to initialize the context so we can query its capabilities
// and extensions. This also means creating a temporary window, so we have
// something to bind the context to and make it current.
init_temp_context();
if (!_supports_fbconfig) {
// We have a good OpenGL context, but it doesn't support the FBConfig
// interface, so we'll stop there.
glxdisplay_cat.debug()
<<" No FBConfig supported; using XVisual only.\n"
<< _fbprops << "\n";
_context = _temp_context;
_temp_context = (GLXContext)NULL;
// By convention, every indirect XVisual that can render to a window can
// also render to a GLXPixmap. Direct visuals we're not as sure about.
_context_has_pixmap = !glXIsDirect(_display, _context);
// Pbuffers aren't supported at all with the XVisual interface.
_context_has_pbuffer = false;
return;
}
// The OpenGL context supports the FBConfig interface, so we can use that
// more advanced interface to choose the actual window format we'll use.
// FBConfig provides for more options than the older XVisual interface, so
// we'd much rather use it if it's available.
int best_quality = 0;
int best_result = 0;
FrameBufferProperties best_props;
int render_type = GLX_RGBA_TYPE;
if (properties.get_indexed_color()) {
render_type = GLX_COLOR_INDEX_TYPE;
}
static const int max_attrib_list = 32;
int attrib_list[max_attrib_list];
int n = 0;
attrib_list[n++] = GLX_STEREO;
attrib_list[n++] = GLX_DONT_CARE;
attrib_list[n++] = GLX_RENDER_TYPE;
attrib_list[n++] = GLX_DONT_CARE;
attrib_list[n++] = GLX_DRAWABLE_TYPE;
attrib_list[n++] = GLX_DONT_CARE;
attrib_list[n] = (int)None;
int num_configs = 0;
GLXFBConfig *configs =
_glXChooseFBConfig(_display, _screen, attrib_list, &num_configs);
if (configs != 0) {
bool context_has_pbuffer, context_has_pixmap, slow;
int quality, i;
for (i = 0; i < num_configs; ++i) {
FrameBufferProperties fbprops;
get_properties_advanced(fbprops, context_has_pbuffer, context_has_pixmap,
slow, configs[i]);
quality = fbprops.get_quality(properties);
if ((quality > 0)&&(slow)) quality -= 10000000;
if (glxdisplay_cat.is_debug()) {
const char *pbuffertext = context_has_pbuffer ? " (pbuffer)" : "";
const char *pixmaptext = context_has_pixmap ? " (pixmap)" : "";
const char *slowtext = slow ? " (slow)" : "";
glxdisplay_cat.debug()
<< i << ": " << fbprops << " quality=" << quality << pbuffertext
<< pixmaptext << slowtext << "\n";
}
if (need_pbuffer && !context_has_pbuffer) {
continue;
}
if (need_pixmap && !context_has_pixmap) {
continue;
}
if (quality > best_quality) {
best_quality = quality;
best_result = i;
best_props = fbprops;
}
}
}
if (best_quality > 0) {
_fbconfig = configs[best_result];
if (_glXCreateContextAttribs != NULL) {
// NB. This is a wholly different type of attrib list than below, the
// same values are not used!
n = 0;
attrib_list[n++] = GLX_RENDER_TYPE;
attrib_list[n++] = render_type;
if (gl_version.get_num_words() > 0) {
attrib_list[n++] = GLX_CONTEXT_MAJOR_VERSION_ARB;
attrib_list[n++] = gl_version[0];
if (gl_version.get_num_words() > 1) {
attrib_list[n++] = GLX_CONTEXT_MINOR_VERSION_ARB;
attrib_list[n++] = gl_version[1];
}
}
if (gl_debug) {
attrib_list[n++] = GLX_CONTEXT_FLAGS_ARB;
attrib_list[n++] = GLX_CONTEXT_DEBUG_BIT_ARB;
}
attrib_list[n] = None;
_context = _glXCreateContextAttribs(_display, _fbconfig, _share_context,
GL_TRUE, attrib_list);
} else {
_context =
_glXCreateNewContext(_display, _fbconfig, render_type, _share_context,
GL_TRUE);
}
if (_context) {
mark_new();
if (_visuals != (XVisualInfo *)NULL) {
XFree(_visuals);
_visuals = NULL;
}
_visuals = _glXGetVisualFromFBConfig(_display, _fbconfig);
_visual = _visuals;
if (_visual) {
get_properties_advanced(_fbprops, _context_has_pbuffer, _context_has_pixmap,
_slow, _fbconfig);
if (!properties.get_srgb_color()) {
_fbprops.set_srgb_color(false);
}
if (glxdisplay_cat.is_debug()) {
glxdisplay_cat.debug()
<< "Selected context " << best_result << ": " << _fbprops << "\n";
glxdisplay_cat.debug()
<< "context_has_pbuffer = " << _context_has_pbuffer
<< ", context_has_pixmap = " << _context_has_pixmap << "\n";
}
return;
}
}
// This really shouldn't happen, so I'm not too careful about cleanup.
glxdisplay_cat.error()
<< "Could not create FBConfig context!\n";
_fbconfig = 0;
_context = 0;
_visual = 0;
_visuals = 0;
}
glxdisplay_cat.warning()
<< "No suitable FBConfig contexts available; using XVisual only.\n"
<< _fbprops << "\n";
_context = _temp_context;
_temp_context = (GLXContext)NULL;
// By convention, every indirect XVisual that can render to a window can
// also render to a GLXPixmap. Direct visuals we're not as sure about.
_context_has_pixmap = !glXIsDirect(_display, _context);
// Pbuffers aren't supported at all with the XVisual interface.
_context_has_pbuffer = false;
}
/**
* Returns true if the runtime GLX version number is at least the indicated
* value, false otherwise.
*/
bool glxGraphicsStateGuardian::
glx_is_at_least_version(int major_version, int minor_version) const {
if (_glx_version_major < major_version) {
return false;
}
if (_glx_version_major > major_version) {
return true;
}
if (_glx_version_minor < minor_version) {
return false;
}
return true;
}
/**
* Calls glFlush().
*/
void glxGraphicsStateGuardian::
gl_flush() const {
// This call requires synchronization with X.
LightReMutexHolder holder(glxGraphicsPipe::_x_mutex);
PosixGraphicsStateGuardian::gl_flush();
}
/**
* Returns the result of glGetError().
*/
GLenum glxGraphicsStateGuardian::
gl_get_error() const {
// This call requires synchronization with X.
LightReMutexHolder holder(glxGraphicsPipe::_x_mutex);
return PosixGraphicsStateGuardian::gl_get_error();
}
/**
* Queries the runtime version of OpenGL in use.
*/
void glxGraphicsStateGuardian::
query_gl_version() {
PosixGraphicsStateGuardian::query_gl_version();
show_glx_client_string("GLX_VENDOR", GLX_VENDOR);
show_glx_client_string("GLX_VERSION", GLX_VERSION);
show_glx_server_string("GLX_VENDOR", GLX_VENDOR);
show_glx_server_string("GLX_VERSION", GLX_VERSION);
glXQueryVersion(_display, &_glx_version_major, &_glx_version_minor);
// We output to glgsg_cat instead of glxdisplay_cat, since this is where the
// GL version has been output, and it's nice to see the two of these
// together.
if (glgsg_cat.is_debug()) {
glgsg_cat.debug()
<< "GLX_VERSION = " << _glx_version_major << "." << _glx_version_minor
<< "\n";
}
}
/**
* This may be redefined by a derived class (e.g. glx or wgl) to get whatever
* further extensions strings may be appropriate to that interface, in
* addition to the GL extension strings return by glGetString().
*/
void glxGraphicsStateGuardian::
get_extra_extensions() {
save_extensions(glXQueryExtensionsString(_display, _screen));
}
/**
* Returns the pointer to the GL extension function with the indicated name.
* It is the responsibility of the caller to ensure that the required
* extension is defined in the OpenGL runtime prior to calling this; it is an
* error to call this for a function that is not defined.
*/
void *glxGraphicsStateGuardian::
do_get_extension_func(const char *name) {
nassertr(name != NULL, NULL);
if (glx_get_proc_address) {
// First, check if we have glXGetProcAddress available. This will be
// superior if we can get it.
#if defined(LINK_IN_GLXGETPROCADDRESS) && defined(HAVE_GLXGETPROCADDRESS)
// If we are confident the system headers defined it, we can call it
// directly. This is more reliable than trying to determine its address
// dynamically, but it may make libpandagl.so fail to load if the symbol
// isn't in the runtime library.
return (void *)glXGetProcAddress((const GLubyte *)name);
#elif defined(LINK_IN_GLXGETPROCADDRESS) && defined(HAVE_GLXGETPROCADDRESSARB)
// The ARB extension version is OK too. Sometimes the prototype isn't
// supplied for some reason.
return (void *)glXGetProcAddressARB((const GLubyte *)name);
#else
// Otherwise, we have to fiddle around with the dynamic runtime.
if (!_checked_get_proc_address) {
const char *funcName = NULL;
if (glx_is_at_least_version(1, 4)) {
funcName = "glXGetProcAddress";
} else if (has_extension("GLX_ARB_get_proc_address")) {
funcName = "glXGetProcAddressARB";
}
if (funcName != NULL) {
_glXGetProcAddress = (PFNGLXGETPROCADDRESSPROC)get_system_func(funcName);
if (_glXGetProcAddress == NULL) {
glxdisplay_cat.warning()
<< "Couldn't load function " << funcName
<< ", GL extensions may be unavailable.\n";
}
}
_checked_get_proc_address = true;
}
// Use glxGetProcAddress() if we've got it; it should be more robust.
if (_glXGetProcAddress != NULL) {
return (void *)_glXGetProcAddress((const GLubyte *)name);
}
#endif // HAVE_GLXGETPROCADDRESS
}
// Otherwise, fall back to the OS-provided calls.
return PosixGraphicsStateGuardian::do_get_extension_func(name);
}
/**
* Queries the GLX extension pointers.
*/
void glxGraphicsStateGuardian::
query_glx_extensions() {
_supports_swap_control = has_extension("GLX_SGI_swap_control");
if (_supports_swap_control) {
_glXSwapIntervalSGI =
(PFNGLXSWAPINTERVALSGIPROC)get_extension_func("glXSwapIntervalSGI");
if (_glXSwapIntervalSGI == NULL) {
glxdisplay_cat.error()
<< "Driver claims to support GLX_SGI_swap_control extension, but does not define all functions.\n";
_supports_swap_control = false;
}
}
if (_supports_swap_control) {
// Set the video-sync setting up front, if we have the extension that
// supports it.
_glXSwapIntervalSGI(sync_video ? 1 : 0);
}
if (glx_support_fbconfig) {
if (glx_is_at_least_version(1, 3)) {
// If we have glx 1.3 or better, we have the FBConfig interface.
_supports_fbconfig = true;
_glXChooseFBConfig =
(PFNGLXCHOOSEFBCONFIGPROC)get_extension_func("glXChooseFBConfig");
_glXCreateNewContext =
(PFNGLXCREATENEWCONTEXTPROC)get_extension_func("glXCreateNewContext");
_glXGetVisualFromFBConfig =
(PFNGLXGETVISUALFROMFBCONFIGPROC)get_extension_func("glXGetVisualFromFBConfig");
_glXGetFBConfigAttrib =
(PFNGLXGETFBCONFIGATTRIBPROC)get_extension_func("glXGetFBConfigAttrib");
_glXCreatePixmap =
(PFNGLXCREATEPIXMAPPROC)get_extension_func("glXCreatePixmap");
if (_glXChooseFBConfig == NULL ||
_glXCreateNewContext == NULL ||
_glXGetVisualFromFBConfig == NULL ||
_glXGetFBConfigAttrib == NULL ||
_glXCreatePixmap == NULL) {
glxdisplay_cat.error()
<< "Driver claims to support GLX_fbconfig extension, but does not define all functions.\n";
_supports_fbconfig = false;
}
} else if (has_extension("GLX_SGIX_fbconfig")) {
// Or maybe we have the old SGIX extension for FBConfig. This is the
// same, but the function names are different--we just remap them to the
// same function pointers.
_supports_fbconfig = true;
_glXChooseFBConfig =
(PFNGLXCHOOSEFBCONFIGPROC)get_extension_func("glXChooseFBConfigSGIX");
_glXCreateNewContext =
(PFNGLXCREATENEWCONTEXTPROC)get_extension_func("glXCreateContextWithConfigSGIX");
_glXGetVisualFromFBConfig =
(PFNGLXGETVISUALFROMFBCONFIGPROC)get_extension_func("glXGetVisualFromFBConfigSGIX");
_glXGetFBConfigAttrib =
(PFNGLXGETFBCONFIGATTRIBPROC)get_extension_func("glXGetFBConfigAttribSGIX");
_glXCreatePixmap =
(PFNGLXCREATEPIXMAPPROC)get_extension_func("glXCreateGLXPixmapWithConfigSGIX");
if (_glXChooseFBConfig == NULL ||
_glXCreateNewContext == NULL ||
_glXGetVisualFromFBConfig == NULL ||
_glXGetFBConfigAttrib == NULL ||
_glXCreatePixmap == NULL) {
glxdisplay_cat.error()
<< "Driver claims to support GLX_SGIX_fbconfig extension, but does not define all functions.\n";
_supports_fbconfig = false;
}
}
if (glx_is_at_least_version(1, 3)) {
// If we have glx 1.3 or better, we have the PBuffer interface.
_supports_pbuffer = true;
_uses_sgix_pbuffer = false;
_glXCreatePbuffer =
(PFNGLXCREATEPBUFFERPROC)get_extension_func("glXCreatePbuffer");
_glXCreateGLXPbufferSGIX = NULL;
_glXDestroyPbuffer =
(PFNGLXDESTROYPBUFFERPROC)get_extension_func("glXDestroyPbuffer");
if (_glXCreatePbuffer == NULL ||
_glXDestroyPbuffer == NULL) {
glxdisplay_cat.error()
<< "Driver claims to support GLX_pbuffer extension, but does not define all functions.\n";
_supports_pbuffer = false;
}
} else if (has_extension("GLX_SGIX_pbuffer")) {
// Or maybe we have the old SGIX extension for PBuffers.
_uses_sgix_pbuffer = true;
// CreatePbuffer has a different form between SGIX and 1.3, however, so
// we must treat it specially. But we can use the same function pointer
// for DestroyPbuffer.
_glXCreatePbuffer = NULL;
_glXCreateGLXPbufferSGIX =
(PFNGLXCREATEGLXPBUFFERSGIXPROC)get_extension_func("glXCreateGLXPbufferSGIX");
_glXDestroyPbuffer =
(PFNGLXDESTROYPBUFFERPROC)get_extension_func("glXDestroyGLXPbufferSGIX");
if (_glXCreateGLXPbufferSGIX == NULL ||
_glXDestroyPbuffer == NULL) {
glxdisplay_cat.error()
<< "Driver claims to support GLX_SGIX_pbuffer extension, but does not define all functions.\n";
_supports_pbuffer = false;
}
}
if (has_extension("GLX_ARB_create_context")) {
_glXCreateContextAttribs =
(PFNGLXCREATECONTEXTATTRIBSARBPROC)get_extension_func("glXCreateContextAttribsARB");
} else {
_glXCreateContextAttribs = NULL;
}
}
if (glxdisplay_cat.is_debug()) {
glxdisplay_cat.debug()
<< "supports_swap_control = " << _supports_swap_control << "\n";
glxdisplay_cat.debug()
<< "supports_fbconfig = " << _supports_fbconfig << "\n";
glxdisplay_cat.debug()
<< "supports_pbuffer = " << _supports_pbuffer
<< " sgix = " << _uses_sgix_pbuffer << "\n";
}
// If "Mesa" is present, assume software. However, if "Mesa DRI" is found,
// it's actually a Mesa-based OpenGL layer running over a hardware driver.
if (_gl_renderer.find("Mesa") != string::npos &&
_gl_renderer.find("Mesa DRI") == string::npos) {
// It's Mesa, therefore probably a software context.
_fbprops.set_force_software(1);
_fbprops.set_force_hardware(0);
} else {
_fbprops.set_force_hardware(1);
_fbprops.set_force_software(0);
}
}
/**
* Outputs the result of glxGetClientString() on the indicated tag.
*/
void glxGraphicsStateGuardian::
show_glx_client_string(const string &name, int id) {
if (glgsg_cat.is_debug()) {
const char *text = glXGetClientString(_display, id);
if (text == (const char *)NULL) {
glgsg_cat.debug()
<< "Unable to query " << name << " (client)\n";
} else {
glgsg_cat.debug()
<< name << " (client) = " << (const char *)text << "\n";
}
}
}
/**
* Outputs the result of glxQueryServerString() on the indicated tag.
*/
void glxGraphicsStateGuardian::
show_glx_server_string(const string &name, int id) {
if (glgsg_cat.is_debug()) {
const char *text = glXQueryServerString(_display, _screen, id);
if (text == (const char *)NULL) {
glgsg_cat.debug()
<< "Unable to query " << name << " (server)\n";
} else {
glgsg_cat.debug()
<< name << " (server) = " << (const char *)text << "\n";
}
}
}
/**
* Selects an XVisual for an initial OpenGL context. This may be called
* initially, to create the first context needed in order to create the
* fbconfig. On successful return, _visual and _temp_context will be filled
* in with a non-NULL value.
*/
void glxGraphicsStateGuardian::
choose_temp_visual(const FrameBufferProperties &properties) {
nassertv(_temp_context == (GLXContext)NULL);
int best_quality = 0;
int best_result = 0;
FrameBufferProperties best_props;
// Scan available visuals.
if (_visuals != (XVisualInfo *)NULL) {
XFree(_visuals);
_visuals = NULL;
}
int nvisuals = 0;
_visuals = XGetVisualInfo(_display, 0, 0, &nvisuals);
if (_visuals != 0) {
for (int i = 0; i < nvisuals; i++) {
FrameBufferProperties fbprops;
get_properties(fbprops, _visuals + i);
int quality = fbprops.get_quality(properties);
if (quality > best_quality) {
best_quality = quality;
best_result = i;
best_props = fbprops;
}
}
}
if (best_quality > 0) {
_visual = _visuals + best_result;
_temp_context = glXCreateContext(_display, _visual, None, GL_TRUE);
if (_temp_context) {
_fbprops = best_props;
return;
}
}
glxdisplay_cat.error()
<< "Could not find a usable pixel format.\n";
}
/**
* Initializes the context created in choose_temp_visual() by creating a
* temporary window and binding the context to that window.
*/
void glxGraphicsStateGuardian::
init_temp_context() {
x11GraphicsPipe *x11_pipe;
DCAST_INTO_V(x11_pipe, get_pipe());
X11_Window root_window = x11_pipe->get_root();
// Assume everyone uses TrueColor or DirectColor these days.
Visual *visual = _visual->visual;
nassertv(visual->c_class == DirectColor || visual->c_class == TrueColor);
_temp_colormap = XCreateColormap(_display, root_window,
visual, AllocNone);
XSetWindowAttributes wa;
wa.colormap = _temp_colormap;
unsigned long attrib_mask = CWColormap;
_temp_xwindow = XCreateWindow
(_display, root_window, 0, 0, 100, 100,
0, _visual->depth, InputOutput,
visual, attrib_mask, &wa);
if (_temp_xwindow == (X11_Window)NULL) {
glxdisplay_cat.error()
<< "Could not create temporary window for context\n";
return;
}
// Now use it to query the available GLX features.
glXMakeCurrent(_display, _temp_xwindow, _temp_context);
query_gl_version();
get_extra_extensions();
query_glx_extensions();
}
/**
* Destroys the temporary unmapped window created by init_temp_context().
*/
void glxGraphicsStateGuardian::
destroy_temp_xwindow() {
glXMakeCurrent(_display, None, NULL);
if (_temp_colormap != (Colormap)NULL) {
XFreeColormap(_display, _temp_colormap);
_temp_colormap = (Colormap)NULL;
}
if (_temp_xwindow != (X11_Window)NULL) {
XDestroyWindow(_display, _temp_xwindow);
_temp_xwindow = (X11_Window)NULL;
}
if (_temp_context != (GLXContext)NULL) {
glXDestroyContext(_display, _temp_context);
_temp_context = (GLXContext)NULL;
}
}
| 33.133574 | 107 | 0.689148 | [
"render",
"3d"
] |
e7a11a11fe2896b53ce54ede8e3fc286694a1378 | 13,281 | cpp | C++ | src/layer/x86/roialign_x86.cpp | robin990/ncnn | 1357cee2b942aecbcc8e63a048a867b8b565f518 | [
"BSD-3-Clause"
] | null | null | null | src/layer/x86/roialign_x86.cpp | robin990/ncnn | 1357cee2b942aecbcc8e63a048a867b8b565f518 | [
"BSD-3-Clause"
] | null | null | null | src/layer/x86/roialign_x86.cpp | robin990/ncnn | 1357cee2b942aecbcc8e63a048a867b8b565f518 | [
"BSD-3-Clause"
] | null | null | null | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "roialign_x86.h"
#include <algorithm>
#include <math.h>
namespace ncnn {
DEFINE_LAYER_CREATOR(ROIAlign_x86)
// adapted from detectron2
// https://github.com/facebookresearch/detectron2/blob/master/detectron2/layers/csrc/ROIAlign/ROIAlign_cpu.cpp
template<typename T>
struct PreCalc
{
int pos1;
int pos2;
int pos3;
int pos4;
T w1;
T w2;
T w3;
T w4;
};
template<typename T>
void detectron2_pre_calc_for_bilinear_interpolate(
const int height,
const int width,
const int pooled_height,
const int pooled_width,
const int iy_upper,
const int ix_upper,
T roi_start_h,
T roi_start_w,
T bin_size_h,
T bin_size_w,
int roi_bin_grid_h,
int roi_bin_grid_w,
std::vector<PreCalc<T> >& pre_calc)
{
int pre_calc_index = 0;
for (int ph = 0; ph < pooled_height; ph++)
{
for (int pw = 0; pw < pooled_width; pw++)
{
for (int iy = 0; iy < iy_upper; iy++)
{
const T yy = roi_start_h + ph * bin_size_h + static_cast<T>(iy + .5f) * bin_size_h / static_cast<T>(roi_bin_grid_h); // e.g., 0.5, 1.5
for (int ix = 0; ix < ix_upper; ix++)
{
const T xx = roi_start_w + pw * bin_size_w + static_cast<T>(ix + .5f) * bin_size_w / static_cast<T>(roi_bin_grid_w);
T x = xx;
T y = yy;
// deal with: inverse elements are out of feature map boundary
if (y < -1.0 || y > height || x < -1.0 || x > width)
{
// empty
PreCalc<T> pc;
pc.pos1 = 0;
pc.pos2 = 0;
pc.pos3 = 0;
pc.pos4 = 0;
pc.w1 = 0;
pc.w2 = 0;
pc.w3 = 0;
pc.w4 = 0;
pre_calc[pre_calc_index++] = pc;
continue;
}
if (y <= 0)
{
y = 0;
}
if (x <= 0)
{
x = 0;
}
int y_low = (int)y;
int x_low = (int)x;
int y_high;
int x_high;
if (y_low >= height - 1)
{
y_high = y_low = height - 1;
y = (T)y_low;
}
else
{
y_high = y_low + 1;
}
if (x_low >= width - 1)
{
x_high = x_low = width - 1;
x = (T)x_low;
}
else
{
x_high = x_low + 1;
}
T ly = y - y_low;
T lx = x - x_low;
T hy = 1. - ly, hx = 1. - lx;
T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx;
// save weights and indices
PreCalc<T> pc;
pc.pos1 = y_low * width + x_low;
pc.pos2 = y_low * width + x_high;
pc.pos3 = y_high * width + x_low;
pc.pos4 = y_high * width + x_high;
pc.w1 = w1;
pc.w2 = w2;
pc.w3 = w3;
pc.w4 = w4;
pre_calc[pre_calc_index++] = pc;
}
}
}
}
}
template<typename T>
void original_pre_calc_for_bilinear_interpolate(
const int height,
const int width,
const int pooled_height,
const int pooled_width,
T roi_start_h,
T roi_start_w,
T bin_size_h,
T bin_size_w,
int sampling_ratio,
std::vector<PreCalc<T> >& pre_calc)
{
int pre_calc_index = 0;
for (int ph = 0; ph < pooled_height; ph++)
{
for (int pw = 0; pw < pooled_width; pw++)
{
float hstart = roi_start_h + ph * bin_size_h;
float wstart = roi_start_w + pw * bin_size_w;
float hend = roi_start_h + (ph + 1) * bin_size_h;
float wend = roi_start_w + (pw + 1) * bin_size_w;
hstart = std::min(std::max(hstart, 0.f), (float)height);
wstart = std::min(std::max(wstart, 0.f), (float)width);
hend = std::min(std::max(hend, 0.f), (float)height);
wend = std::min(std::max(wend, 0.f), (float)width);
int bin_grid_h = sampling_ratio > 0 ? sampling_ratio : ceil(hend - hstart);
int bin_grid_w = sampling_ratio > 0 ? sampling_ratio : ceil(wend - wstart);
for (int by = 0; by < bin_grid_h; by++)
{
float y = hstart + (by + 0.5f) * bin_size_h / (float)bin_grid_h;
for (int bx = 0; bx < bin_grid_w; bx++)
{
float x = wstart + (bx + 0.5f) * bin_size_w / (float)bin_grid_w;
int x0 = x;
int x1 = x0 + 1;
int y0 = y;
int y1 = y0 + 1;
float a0 = x1 - x;
float a1 = x - x0;
float b0 = y1 - y;
float b1 = y - y0;
if (x1 >= width)
{
x1 = width - 1;
a0 = 1.f;
a1 = 0.f;
}
if (y1 >= height)
{
y1 = height - 1;
b0 = 1.f;
b1 = 0.f;
}
// save weights and indices
PreCalc<T> pc;
pc.pos1 = y0 * width + x0;
pc.pos2 = y0 * width + x1;
pc.pos3 = y1 * width + x0;
pc.pos4 = y1 * width + x1;
pc.w1 = a0 * b0;
pc.w2 = a1 * b0;
pc.w3 = a0 * b1;
pc.w4 = a1 * b1;
pre_calc[pre_calc_index++] = pc;
}
}
}
}
}
ROIAlign_x86::ROIAlign_x86()
{
}
int ROIAlign_x86::forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const
{
const Mat& bottom_blob = bottom_blobs[0];
const int width = bottom_blob.w;
const int height = bottom_blob.h;
const size_t elemsize = bottom_blob.elemsize;
const int channels = bottom_blob.c;
const Mat& roi_blob = bottom_blobs[1];
Mat& top_blob = top_blobs[0];
top_blob.create(pooled_width, pooled_height, channels, elemsize, opt.blob_allocator);
if (top_blob.empty())
return -100;
// For each ROI R = [x y w h]: max pool over R
const float* roi_ptr = roi_blob;
float roi_start_w = roi_ptr[0] * spatial_scale;
float roi_start_h = roi_ptr[1] * spatial_scale;
float roi_end_w = roi_ptr[2] * spatial_scale;
float roi_end_h = roi_ptr[3] * spatial_scale;
if (aligned)
{
roi_start_w -= 0.5f;
roi_start_h -= 0.5f;
roi_end_w -= 0.5f;
roi_end_h -= 0.5f;
}
float roi_width = roi_end_w - roi_start_w;
float roi_height = roi_end_h - roi_start_h;
if (!aligned)
{
roi_width = std::max(roi_width, 1.f);
roi_height = std::max(roi_height, 1.f);
}
float bin_size_w = (float)roi_width / (float)pooled_width;
float bin_size_h = (float)roi_height / (float)pooled_height;
if (version == 0)
{
// original version
int roi_bin_grid_h = sampling_ratio > 0 ? sampling_ratio : ceil(roi_height / pooled_height);
int roi_bin_grid_w = sampling_ratio > 0 ? sampling_ratio : ceil(roi_width / pooled_width);
std::vector<PreCalc<float> > pre_calc(
roi_bin_grid_h * roi_bin_grid_w * pooled_width * pooled_height);
original_pre_calc_for_bilinear_interpolate(
height,
width,
pooled_height,
pooled_width,
roi_start_h,
roi_start_w,
bin_size_h,
bin_size_w,
sampling_ratio,
pre_calc);
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* ptr = bottom_blob.channel(q);
float* outptr = top_blob.channel(q);
int pre_calc_index = 0;
for (int ph = 0; ph < pooled_height; ph++)
{
for (int pw = 0; pw < pooled_width; pw++)
{
// Compute pooling region for this output unit:
// start (included) = ph * roi_height / pooled_height
// end (excluded) = (ph + 1) * roi_height / pooled_height
float hstart = roi_start_h + ph * bin_size_h;
float wstart = roi_start_w + pw * bin_size_w;
float hend = roi_start_h + (ph + 1) * bin_size_h;
float wend = roi_start_w + (pw + 1) * bin_size_w;
hstart = std::min(std::max(hstart, 0.f), (float)height);
wstart = std::min(std::max(wstart, 0.f), (float)width);
hend = std::min(std::max(hend, 0.f), (float)height);
wend = std::min(std::max(wend, 0.f), (float)width);
int bin_grid_h = sampling_ratio > 0 ? sampling_ratio : ceil(hend - hstart);
int bin_grid_w = sampling_ratio > 0 ? sampling_ratio : ceil(wend - wstart);
bool is_empty = (hend <= hstart) || (wend <= wstart);
int area = bin_grid_h * bin_grid_w;
float sum = 0.f;
for (int by = 0; by < bin_grid_h; by++)
{
for (int bx = 0; bx < bin_grid_w; bx++)
{
PreCalc<float>& pc = pre_calc[pre_calc_index++];
// bilinear interpolate at (x,y)
sum += pc.w1 * ptr[pc.pos1] + pc.w2 * ptr[pc.pos2] + pc.w3 * ptr[pc.pos3] + pc.w4 * ptr[pc.pos4];
}
}
outptr[pw] = is_empty ? 0.f : (sum / (float)area);
}
outptr += pooled_width;
}
}
}
else if (version == 1)
{
// the version in detectron 2
int roi_bin_grid_h = sampling_ratio > 0 ? sampling_ratio : ceil(roi_height / pooled_height);
int roi_bin_grid_w = sampling_ratio > 0 ? sampling_ratio : ceil(roi_width / pooled_width);
const float count = std::max(roi_bin_grid_h * roi_bin_grid_w, 1);
std::vector<PreCalc<float> > pre_calc(
roi_bin_grid_h * roi_bin_grid_w * pooled_width * pooled_height);
detectron2_pre_calc_for_bilinear_interpolate(
height,
width,
pooled_height,
pooled_width,
roi_bin_grid_h,
roi_bin_grid_w,
roi_start_h,
roi_start_w,
bin_size_h,
bin_size_w,
roi_bin_grid_h,
roi_bin_grid_w,
pre_calc);
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < channels; q++)
{
const float* ptr = bottom_blob.channel(q);
float* outptr = top_blob.channel(q);
int pre_calc_index = 0;
for (int ph = 0; ph < pooled_height; ph++)
{
for (int pw = 0; pw < pooled_width; pw++)
{
float output_val = 0.f;
for (int iy = 0; iy < roi_bin_grid_h; iy++)
{
for (int ix = 0; ix < roi_bin_grid_w; ix++)
{
PreCalc<float>& pc = pre_calc[pre_calc_index++];
output_val += pc.w1 * ptr[pc.pos1] + pc.w2 * ptr[pc.pos2] + pc.w3 * ptr[pc.pos3] + pc.w4 * ptr[pc.pos4];
}
}
output_val /= count;
outptr[pw] = output_val;
}
outptr += pooled_width;
}
}
}
return 0;
}
} // namespace ncnn
| 34.229381 | 150 | 0.46495 | [
"vector"
] |
e7a20c76786f7e624149eed7bd37c484b3d36737 | 6,832 | cpp | C++ | Kaskade/fem/nedelecshapefunctions.cpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 3 | 2019-07-03T14:03:31.000Z | 2021-12-19T10:18:49.000Z | Kaskade/fem/nedelecshapefunctions.cpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 6 | 2020-02-17T12:01:31.000Z | 2021-12-09T22:02:36.000Z | Kaskade/fem/nedelecshapefunctions.cpp | chenzongxiong/streambox | 76f95780d1bf6c02731e39d8ac73937cea352b95 | [
"Unlicense"
] | 2 | 2020-12-03T04:41:18.000Z | 2021-01-11T21:44:42.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the library KASKADE 7 */
/* see http://www.zib.de/projects/kaskade7-finite-element-toolbox */
/* */
/* Copyright (C) 2014 Zuse Institute Berlin */
/* */
/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
/* see $KASKADE/academic.txt */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <numeric> // needed for clang++
#include "dune/grid/config.h"
#include "fem/nedelecshapefunctions.hh"
namespace Kaskade
{
template <class ctype, int dimension, class T>
HdivSimplexShapeFunctionSet<ctype,dimension,T>::HdivSimplexShapeFunctionSet(int order)
: ShapeFunctionSet<ctype,dim,T,dim>(Dune::GeometryType(Dune::GeometryType::simplex,dim))
{
assert(order >= 1);
auto const& simplex = Dune::ReferenceElements<ctype,dim>::simplex();
// We define the shape functions as linear combinations of the Lagrangian shape functions and formulate
// the Kronecker condition of the normal components as an (underdefined) interpolation problem.
auto const& lsfs = lagrangeShapeFunctionSet<ctype,dim,T>(Dune::GeometryType(Dune::GeometryType::simplex,dim),order);
int const n = dim * SimplexLagrangeDetail::size(dim,order); // total number of vectorial shape functions
int const nFaces = simplex.size(1); // number of faces
int const nFaceNodes = SimplexLagrangeDetail::size(dim-1,order); // number of Lagrangian nodes on each face
assert(n == dim*lsfs.size());
// We partition our vectorial shape functions into first face functions and second cell-interior functions.
// Each we represent as a column vector of coefficients for linear combination of Lagrangian shape functions.
// Let these column vectors form the matrix C = [ Cf Ci ] of first face and second interior shape functions.
// As the shape functions form a basis, all columns of C are linearly independent, i.e. C is invertible.
// Evaluating the normal components of the shape functions at the Lagrangian nodes of the faces (as matrix K)
// gives the Kronecker condition K C = [ I 0 ]. Note that K has full rank. Choosing Cf = K^+ (pseudoinverse) and
// Ci as a basis of the nullspace of K satisfies the Kronecker condition. This can be obtained by computing the
// SVD K = U [S 0] [V1 V2]^T and setting Cf = V1 S^{-1} U^T and Ci = V2.
// This approach is quite implicit, and we cannot easily deduce how the individual shape functions look like
// (except for their normal component at the faces), but it's valid and easy to implement for arbitrary order.
// Create the matrix K of size nFaces*nFaceNodes x n.
DynamicMatrix<Dune::FieldMatrix<T,1,1>> K(nFaces*nFaceNodes,n);
for (int f=0; f<nFaces; ++f)
{
auto normal = simplex.integrationOuterNormal(f); // obtain the unit outer
normal /= normal.two_norm(); // normal of the corresponding face
for (int j=0; j<nFaceNodes; ++j)
{
auto idx = SimplexLagrangeDetail::tupleIndex<dim-1>(order,j); // interpolation grid position on face
auto x = simplex.template geometry<1>(f).global(SimplexLagrangeDetail::nodalPosition<dim-1>(idx,order));
for (int k=0; k<lsfs.size(); ++k)
{
double phi = lsfs[k].evaluateFunction(x);
for (int d=0; d<dim; ++d)
K[f*nFaceNodes+j][k*dim+d] = normal[d] * phi;
}
}
}
// Compute SVD.
DynamicMatrix<Dune::FieldMatrix<double,1,1>> U, V;
std::vector<double> sigma;
std::tie(U,sigma,V) = svd(K);
assert(sigma.back()>0); // check that K has full rank.
// Form C = [Cf Ci].
DynamicMatrix<Dune::FieldMatrix<double,1,1>> C(n,n);
// Cf = V_1 * sigma^{-1} * U^T
for (int j=0; j<nFaces*nFaceNodes; ++j)
for (int i=0; i<V.rows(); ++i)
{
C[i][j] = 0;
for (int k=0; k<nFaces*nFaceNodes; ++k)
C[i][j] += V[i][k] / sigma[k] * U[j][k]; // <- that's U^T[k][j]
}
// Ci = V2, do partial copy.
for (int j=nFaces*nFaceNodes; j<n; ++j)
for (int i=0; i<V.rows(); ++i)
C[i][j] = V[i][j];
// Now create the vectorial shape functions corresponding to the columns of C.
sf.reserve(n);
std::vector<Dune::FieldVector<double,dim>> coeff(lsfs.size());
for (int j=0; j<n; ++j)
{
for (int i=0; i<coeff.size(); ++i) // extract j-th column of C
for (int d=0; d<dim; ++d)
coeff[i][d] = C[i*dim+d][j];
if (j<nFaces*nFaceNodes) // face functions
sf.push_back(value_type(coeff,std::make_tuple(order,1,j/nFaceNodes,j%nFaceNodes)));
else // interior cell functions
sf.push_back(value_type(coeff,std::make_tuple(order,0,0,j-nFaces*nFaceNodes)));
}
this->order_ = order;
this->size_ = n;
}
// explicit instantiaion of method
template HdivSimplexShapeFunctionSet<double,2,double>::HdivSimplexShapeFunctionSet(int order);
template HdivSimplexShapeFunctionSet<double,3,double>::HdivSimplexShapeFunctionSet(int order);
}
#ifdef UNITTEST
#include <iostream>
using namespace Kaskade;
// output to standard out in gnuplot syntax
// inspect the shape functions with
// plot "test.gnu" index 1 using 1:2:3:4 with vectors
int main(void)
{
int const dim = 2;
int const n = 30;
for (int order=1; order<3; ++order)
{
auto const& hdivsfs = hdivShapeFunctionSet<double,dim,double>(Dune::GeometryType(Dune::GeometryType::simplex,dim),order);
std::cerr << "number of shape functions: " << hdivsfs.size() << "\n";
for (int ix=0; ix<=n; ++ix)
{
double x = (double)ix/n;
for (int iy=0; iy<=n; ++iy)
{
double y = (double)iy/n;
std::cout << x << ' ' << y << ' ';
for (int k=0; k<hdivsfs.size(); ++k)
{
Dune::FieldVector<double,dim> xi; xi[0] = x; xi[1] = y;
auto phi = hdivsfs[k].evaluateFunction(xi) / 35.0;
if (x+y>1) // outside the unit simplex...
phi = 0;
std::cout << phi[0] << ' ' << phi[1] << ' ';
}
std::cout << "\n";
}
std::cout << "\n";
}
std::cout << "\n";
}
}
#endif
| 41.91411 | 142 | 0.560012 | [
"geometry",
"shape",
"vector"
] |
e7a69df988504f582592e2ea6306be7f23e0d291 | 2,267 | hpp | C++ | include/NumCpp.hpp | faichele/NumCpp | 7c8fc50fbe44b80eaa105f0f9258120abddfcec2 | [
"MIT"
] | 1 | 2020-06-05T22:47:00.000Z | 2020-06-05T22:47:00.000Z | include/NumCpp.hpp | lamarrr/NumCpp | a24328e9d8dc472607a09ba50419baf21b1d3142 | [
"MIT"
] | null | null | null | include/NumCpp.hpp | lamarrr/NumCpp | a24328e9d8dc472607a09ba50419baf21b1d3142 | [
"MIT"
] | null | null | null | /// @section Description
/// A C++ Implementation of the Python Numpy Library
///
/// @author David Pilger <dpilger26@gmail.com>
/// [GitHub Repository](https://github.com/dpilger26/NumCpp)
///
/// @version 1.2
///
/// @section License
/// Copyright 2019 David Pilger
///
/// 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.
///
/// @section Testing
/// Compiled and tested with Visual Studio 2017/2019, and g++ 7.3.0/8.0, clang 6.0, with Boost version 1.68 and 1.70.
///
#pragma once
#include "NumCpp/Coordinates.hpp"
#include "NumCpp/Core.hpp"
#include "NumCpp/Filter.hpp"
#include "NumCpp/Functions.hpp"
#include "NumCpp/ImageProcessing.hpp"
#include "NumCpp/Linalg.hpp"
#include "NumCpp/NdArray.hpp"
#include "NumCpp/Polynomial.hpp"
#include "NumCpp/PythonInterface.hpp"
#include "NumCpp/Random.hpp"
#include "NumCpp/Rotations.hpp"
#include "NumCpp/Special.hpp"
#include "NumCpp/Utils.hpp"
#include "NumCpp/Vector.hpp"
/// \example ReadMe.cpp
/// Examples from the Quick Start Guide in README.md at [GitHub Repository](https://github.com/dpilger26/NumCpp)
///
/// \example InterfaceWithEigen.cpp
/// Example for interfaceing with Eigen Matrix
///
/// \example InterfaceWithOpenCV.cpp
/// Example for interfaceing with OpenCV Mat
| 39.086207 | 117 | 0.744155 | [
"vector"
] |
e7bd6c7b5e2f6ff72d5b6e78cda2810faebfef96 | 80,538 | cpp | C++ | src/game_app.cpp | Niki4tap/asciicker | 1fd314f940d166217deb2dfcedc5a6ccead40243 | [
"MIT"
] | null | null | null | src/game_app.cpp | Niki4tap/asciicker | 1fd314f940d166217deb2dfcedc5a6ccead40243 | [
"MIT"
] | null | null | null | src/game_app.cpp | Niki4tap/asciicker | 1fd314f940d166217deb2dfcedc5a6ccead40243 | [
"MIT"
] | null | null | null |
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdarg.h>
#if defined(__linux__) || defined(__APPLE__)
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <fcntl.h>
#ifdef __linux__
# include <linux/limits.h>
#include <linux/input.h>
#include <linux/joystick.h>
#else
# include <limits.h>
#endif
#include <unistd.h>
#include <signal.h>
#include <termios.h>
#include <time.h>
#ifdef USE_GPM
# include <gpm.h>
#endif
// work around including <netinet/tcp.h>
// which also defines TCP_CLOSE
#ifndef TCP_DELAY
#define TCP_NODELAY 1
#endif
#else
#define PATH_MAX 1024
#endif
#include <assert.h>
#include "render.h"
#include "physics.h"
#include "sprite.h"
#include "matrix.h"
#include "network.h"
// FOR GL
#include "term.h"
#include "gl.h"
#include "gl45_emu.h"
#include "rgba8.h"
#include "game.h"
#include "enemygen.h"
int tty = -1;
// configurable, or auto lookup?
void Buzz()
{
}
char base_path[1024] = "./";
void SyncConf()
{
}
char conf_path[1024]="";
const char* GetConfPath()
{
if (conf_path[0] == 0)
{
#if defined(__linux__) || defined(__APPLE__)
const char* user_dir = getenv("SNAP_USER_DATA");
if (!user_dir || user_dir[0]==0)
{
user_dir = getenv("HOME");
if (!user_dir || user_dir[0]==0)
sprintf(conf_path,"%sasciicker.cfg",base_path);
else
sprintf(conf_path,"%s/asciicker.cfg",user_dir);
}
else
sprintf(conf_path,"%s/asciicker.cfg",user_dir);
#elif defined(_WIN32)
const char* user_dir = getenv("APPDATA");
if (!user_dir || user_dir[0] == 0)
sprintf(conf_path, "%sasciicker.cfg", base_path);
else
sprintf(conf_path, "%s\\asciicker.cfg", user_dir);
#endif
}
return conf_path;
}
#if defined(__linux__) || defined(__APPLE__)
/*
https://superuser.com/questions/1185824/configure-vga-colors-linux-ubuntu
https://int10h.org/oldschool-pc-fonts/fontlist/
https://www.zap.org.au/software/fonts/console-fonts-distributed/psftx-freebsd-11.1/index.html
ftp://ftp.zap.org.au/pub/fonts/console-fonts-zap/console-fonts-zap-2.2.tar.xz
*/
template <uint16_t C> static int UTF8(char* buf)
{
if (C<0x0080)
{
buf[0]=C&0xFF;
return 1;
}
if (C<0x0800)
{
buf[0] = (char)0xC0 | ( ( C >> 6 ) & 0x1F );
buf[1] = (char)0x80 | ( C & 0x3F );
return 2;
}
buf[0] = (char)0xE0 | ( ( C >> 12 ) & 0x0F );
buf[1] = (char)0x80 | ( ( C >> 6 ) & 0x3F );
buf[2] = (char)0x80 | ( C & 0x3F );
return 3;
}
static int (* const CP437[256])(char*) =
{
UTF8<0x0020>, UTF8<0x263A>, UTF8<0x263B>, UTF8<0x2665>, UTF8<0x2666>, UTF8<0x2663>, UTF8<0x2660>, UTF8<0x2022>,
UTF8<0x25D8>, UTF8<0x25CB>, UTF8<0x25D9>, UTF8<0x2642>, UTF8<0x2640>, UTF8<0x266A>, UTF8<0x266B>, UTF8<0x263C>,
UTF8<0x25BA>, UTF8<0x25C4>, UTF8<0x2195>, UTF8<0x203C>, UTF8<0x00B6>, UTF8<0x00A7>, UTF8<0x25AC>, UTF8<0x21A8>,
UTF8<0x2191>, UTF8<0x2193>, UTF8<0x2192>, UTF8<0x2190>, UTF8<0x221F>, UTF8<0x2194>, UTF8<0x25B2>, UTF8<0x25BC>,
UTF8<0x0020>, UTF8<0x0021>, UTF8<0x0022>, UTF8<0x0023>, UTF8<0x0024>, UTF8<0x0025>, UTF8<0x0026>, UTF8<0x0027>,
UTF8<0x0028>, UTF8<0x0029>, UTF8<0x002A>, UTF8<0x002B>, UTF8<0x002C>, UTF8<0x002D>, UTF8<0x002E>, UTF8<0x002F>,
UTF8<0x0030>, UTF8<0x0031>, UTF8<0x0032>, UTF8<0x0033>, UTF8<0x0034>, UTF8<0x0035>, UTF8<0x0036>, UTF8<0x0037>,
UTF8<0x0038>, UTF8<0x0039>, UTF8<0x003A>, UTF8<0x003B>, UTF8<0x003C>, UTF8<0x003D>, UTF8<0x003E>, UTF8<0x003F>,
UTF8<0x0040>, UTF8<0x0041>, UTF8<0x0042>, UTF8<0x0043>, UTF8<0x0044>, UTF8<0x0045>, UTF8<0x0046>, UTF8<0x0047>,
UTF8<0x0048>, UTF8<0x0049>, UTF8<0x004A>, UTF8<0x004B>, UTF8<0x004C>, UTF8<0x004D>, UTF8<0x004E>, UTF8<0x004F>,
UTF8<0x0050>, UTF8<0x0051>, UTF8<0x0052>, UTF8<0x0053>, UTF8<0x0054>, UTF8<0x0055>, UTF8<0x0056>, UTF8<0x0057>,
UTF8<0x0058>, UTF8<0x0059>, UTF8<0x005A>, UTF8<0x005B>, UTF8<0x005C>, UTF8<0x005D>, UTF8<0x005E>, UTF8<0x005F>,
UTF8<0x0060>, UTF8<0x0061>, UTF8<0x0062>, UTF8<0x0063>, UTF8<0x0064>, UTF8<0x0065>, UTF8<0x0066>, UTF8<0x0067>,
UTF8<0x0068>, UTF8<0x0069>, UTF8<0x006A>, UTF8<0x006B>, UTF8<0x006C>, UTF8<0x006D>, UTF8<0x006E>, UTF8<0x006F>,
UTF8<0x0070>, UTF8<0x0071>, UTF8<0x0072>, UTF8<0x0073>, UTF8<0x0074>, UTF8<0x0075>, UTF8<0x0076>, UTF8<0x0077>,
UTF8<0x0078>, UTF8<0x0079>, UTF8<0x007A>, UTF8<0x007B>, UTF8<0x007C>, UTF8<0x007D>, UTF8<0x007E>, UTF8<0x2302>,
UTF8<0x00C7>, UTF8<0x00FC>, UTF8<0x00E9>, UTF8<0x00E2>, UTF8<0x00E4>, UTF8<0x00E0>, UTF8<0x00E5>, UTF8<0x00E7>,
UTF8<0x00EA>, UTF8<0x00EB>, UTF8<0x00E8>, UTF8<0x00EF>, UTF8<0x00EE>, UTF8<0x00EC>, UTF8<0x00C4>, UTF8<0x00C5>,
UTF8<0x00C9>, UTF8<0x00E6>, UTF8<0x00C6>, UTF8<0x00F4>, UTF8<0x00F6>, UTF8<0x00F2>, UTF8<0x00FB>, UTF8<0x00F9>,
UTF8<0x00FF>, UTF8<0x00D6>, UTF8<0x00DC>, UTF8<0x00A2>, UTF8<0x00A3>, UTF8<0x00A5>, UTF8<0x20A7>, UTF8<0x0192>,
UTF8<0x00E1>, UTF8<0x00ED>, UTF8<0x00F3>, UTF8<0x00FA>, UTF8<0x00F1>, UTF8<0x00D1>, UTF8<0x00AA>, UTF8<0x00BA>,
UTF8<0x00BF>, UTF8<0x2310>, UTF8<0x00AC>, UTF8<0x00BD>, UTF8<0x00BC>, UTF8<0x00A1>, UTF8<0x00AB>, UTF8<0x00BB>,
UTF8<0x2591>, UTF8<0x2592>, UTF8<0x2593>, UTF8<0x2502>, UTF8<0x2524>, UTF8<0x2561>, UTF8<0x2562>, UTF8<0x2556>,
UTF8<0x2555>, UTF8<0x2563>, UTF8<0x2551>, UTF8<0x2557>, UTF8<0x255D>, UTF8<0x255C>, UTF8<0x255B>, UTF8<0x2510>,
UTF8<0x2514>, UTF8<0x2534>, UTF8<0x252C>, UTF8<0x251C>, UTF8<0x2500>, UTF8<0x253C>, UTF8<0x255E>, UTF8<0x255F>,
UTF8<0x255A>, UTF8<0x2554>, UTF8<0x2569>, UTF8<0x2566>, UTF8<0x2560>, UTF8<0x2550>, UTF8<0x256C>, UTF8<0x2567>,
UTF8<0x2568>, UTF8<0x2564>, UTF8<0x2565>, UTF8<0x2559>, UTF8<0x2558>, UTF8<0x2552>, UTF8<0x2553>, UTF8<0x256B>,
UTF8<0x256A>, UTF8<0x2518>, UTF8<0x250C>, UTF8<0x2588>, UTF8<0x2584>, UTF8<0x258C>, UTF8<0x2590>, UTF8<0x2580>,
UTF8<0x03B1>, UTF8<0x00DF>, UTF8<0x0393>, UTF8<0x03C0>, UTF8<0x03A3>, UTF8<0x03C3>, UTF8<0x00B5>, UTF8<0x03C4>,
UTF8<0x03A6>, UTF8<0x0398>, UTF8<0x03A9>, UTF8<0x03B4>, UTF8<0x221E>, UTF8<0x03C6>, UTF8<0x03B5>, UTF8<0x2229>,
UTF8<0x2261>, UTF8<0x00B1>, UTF8<0x2265>, UTF8<0x2264>, UTF8<0x2320>, UTF8<0x2321>, UTF8<0x00F7>, UTF8<0x2248>,
UTF8<0x00B0>, UTF8<0x2219>, UTF8<0x00B7>, UTF8<0x221A>, UTF8<0x207F>, UTF8<0x00B2>, UTF8<0x25A0>, UTF8<0x0020>
};
bool xterm_kitty = false;
int mouse_x = -1;
int mouse_y = -1;
int mouse_down = 0;
int gpm = -1;
bool GetWH(int wh[2])
{
struct winsize size = {0};
if (ioctl(0, TIOCGWINSZ, (char *)&size)>=0)
{
wh[0] = size.ws_col;
wh[1] = size.ws_row;
if (wh[0] > 160)
wh[0] = 160;
if (wh[1] > 90)
wh[1] = 90;
return true;
}
return false;
}
void SetScreen(bool alt)
{
// kitty kitty ...
const char* term = 0; // getenv("TERM");
if (term && strcmp(term,"xterm-kitty")==0)
{
xterm_kitty = alt;
int w = write(STDOUT_FILENO, alt?"\x1B[?2017h":"\x1B[?2017l", 8);
}
// // \x1B[?1002h only drags \x1B[?1003h all mouse events
// \x1B[?1006h enable extended mouse encodings in SGR < Bc;Px;Pym|M format
static const char* on_str = "\x1B[?1049h" "\x1B[H" "\x1B[?7l" "\x1B[?25l" "\x1B[?1002h" "\x1B[?1006h"; // +home, -wrap, -cursor, +mouse
static const char* off_str = "\x1B[39m;\x1B[49m" "\x1B[?1049l" "\x1B[?7h" "\x1B[?25h" "\x1B[?1002l" "\x1B[?1006l"; // +def_fg/bg, +wrap, +cursor, -mouse
static int on_len = strlen(on_str);
static int off_len = strlen(off_str);
static struct termios old;
if (alt)
{
tcgetattr(STDIN_FILENO, &old);
struct termios t = old;
t.c_lflag |= ISIG;
t.c_iflag &= ~IGNBRK;
t.c_iflag |= BRKINT;
t.c_lflag &= ~ICANON; /* disable buffered i/o */
t.c_lflag &= ~ECHO; /* disable echo mode */
tcsetattr(STDIN_FILENO, TCSANOW, &t);
int w = write(STDOUT_FILENO,on_str,on_len);
}
else
{
tcsetattr(STDIN_FILENO, TCSANOW, &old);
int w = write(STDOUT_FILENO,off_str,off_len);
if (tty>=0)
{
int wh[2];
GetWH(wh);
char jump[64]; // jump to last line, reset palette then clear it line
int len = sprintf(jump,"\x1B[%d;%df\x1B]R\x1B[2K",wh[1],1);
w = write(STDOUT_FILENO,jump,len);
}
}
}
#define FLUSH() \
do \
{ \
int w = write(STDOUT_FILENO,out,out_pos); \
out_pos=0; \
} while(0)
#define WRITE(...) \
do \
{ \
out_pos += sprintf(out+out_pos,__VA_ARGS__); \
if (out_pos>=out_size-48) FLUSH(); \
} while(0)
// it turns out we should use our own palette
// it's quite different than xterm!!!!!
uint8_t pal_16[256];
const uint8_t pal_rgba[256][3]=
{
//{0,0,0},{0,0,170},{0,170,0},{0,85,170},{170,0,0},{170,0,170},{170,170,0},{170,170,170},
//{85,85,85},{85,85,255},{85,255,85},{85,255,255},{255,85,85},{255,85,255},{255,255,85},{255,255,255},
{0,0,0},{170,0,0},{0,170,0},{170,85,0},{0,0,170},{170,0,170},{0,170,170},{170,170,170},
{85,85,85},{255,85,85},{85,255,85},{255,255,85},{85,85,255},{255,85,255},{85,255,255},{255,255,255},
{ 0, 0, 0},{ 0, 0, 51},{ 0, 0,102},{ 0, 0,153},{ 0, 0,204},{ 0, 0,255},
{ 0, 51, 0},{ 0, 51, 51},{ 0, 51,102},{ 0, 51,153},{ 0, 51,204},{ 0, 51,255},
{ 0,102, 0},{ 0,102, 51},{ 0,102,102},{ 0,102,153},{ 0,102,204},{ 0,102,255},
{ 0,153, 0},{ 0,153, 51},{ 0,153,102},{ 0,153,153},{ 0,153,204},{ 0,153,255},
{ 0,204, 0},{ 0,204, 51},{ 0,204,102},{ 0,204,153},{ 0,204,204},{ 0,204,255},
{ 0,255, 0},{ 0,255, 51},{ 0,255,102},{ 0,255,153},{ 0,255,204},{ 0,255,255},
{ 51, 0, 0},{ 51, 0, 51},{ 51, 0,102},{ 51, 0,153},{ 51, 0,204},{ 51, 0,255},
{ 51, 51, 0},{ 51, 51, 51},{ 51, 51,102},{ 51, 51,153},{ 51, 51,204},{ 51, 51,255},
{ 51,102, 0},{ 51,102, 51},{ 51,102,102},{ 51,102,153},{ 51,102,204},{ 51,102,255},
{ 51,153, 0},{ 51,153, 51},{ 51,153,102},{ 51,153,153},{ 51,153,204},{ 51,153,255},
{ 51,204, 0},{ 51,204, 51},{ 51,204,102},{ 51,204,153},{ 51,204,204},{ 51,204,255},
{ 51,255, 0},{ 51,255, 51},{ 51,255,102},{ 51,255,153},{ 51,255,204},{ 51,255,255},
{102, 0, 0},{102, 0, 51},{102, 0,102},{102, 0,153},{102, 0,204},{102, 0,255},
{102, 51, 0},{102, 51, 51},{102, 51,102},{102, 51,153},{102, 51,204},{102, 51,255},
{102,102, 0},{102,102, 51},{102,102,102},{102,102,153},{102,102,204},{102,102,255},
{102,153, 0},{102,153, 51},{102,153,102},{102,153,153},{102,153,204},{102,153,255},
{102,204, 0},{102,204, 51},{102,204,102},{102,204,153},{102,204,204},{102,204,255},
{102,255, 0},{102,255, 51},{102,255,102},{102,255,153},{102,255,204},{102,255,255},
{153, 0, 0},{153, 0, 51},{153, 0,102},{153, 0,153},{153, 0,204},{153, 0,255},
{153, 51, 0},{153, 51, 51},{153, 51,102},{153, 51,153},{153, 51,204},{153, 51,255},
{153,102, 0},{153,102, 51},{153,102,102},{153,102,153},{153,102,204},{153,102,255},
{153,153, 0},{153,153, 51},{153,153,102},{153,153,153},{153,153,204},{153,153,255},
{153,204, 0},{153,204, 51},{153,204,102},{153,204,153},{153,204,204},{153,204,255},
{153,255, 0},{153,255, 51},{153,255,102},{153,255,153},{153,255,204},{153,255,255},
{204, 0, 0},{204, 0, 51},{204, 0,102},{204, 0,153},{204, 0,204},{204, 0,255},
{204, 51, 0},{204, 51, 51},{204, 51,102},{204, 51,153},{204, 51,204},{204, 51,255},
{204,102, 0},{204,102, 51},{204,102,102},{204,102,153},{204,102,204},{204,102,255},
{204,153, 0},{204,153, 51},{204,153,102},{204,153,153},{204,153,204},{204,153,255},
{204,204, 0},{204,204, 51},{204,204,102},{204,204,153},{204,204,204},{204,204,255},
{204,255, 0},{204,255, 51},{204,255,102},{204,255,153},{204,255,204},{204,255,255},
{255, 0, 0},{255, 0, 51},{255, 0,102},{255, 0,153},{255, 0,204},{255, 0,255},
{255, 51, 0},{255, 51, 51},{255, 51,102},{255, 51,153},{255, 51,204},{255, 51,255},
{255,102, 0},{255,102, 51},{255,102,102},{255,102,153},{255,102,204},{255,102,255},
{255,153, 0},{255,153, 51},{255,153,102},{255,153,153},{255,153,204},{255,153,255},
{255,204, 0},{255,204, 51},{255,204,102},{255,204,153},{255,204,204},{255,204,255},
{255,255, 0},{255,255, 51},{255,255,102},{255,255,153},{255,255,204},{255,255,255},
};
void Print(AnsiCell* buf, int w, int h, const char utf[256][4])
{
// heading
// w x (fg,bg,3bytes)
int bk=-1,fg=-1;
// home
// 2.3MB out buffer
const int out_size = 3/*header*/ + 40/*fg,bg,ch*/ * 320/*width*/ * 180/*height*/ + 180/*'\n'*/; // 4096;
char out[out_size];
int out_pos = 0;
WRITE("\x1B[H");
int fg16 = 0;
int bk16 = 1;
#ifdef USE_GPM
if (gpm>=0)
{
// bake mouse into buffer
if (mouse_x>=0 && mouse_y>=0 && mouse_x<w && mouse_y<h)
{
static const AnsiCell mouse = { 0, 231, '+', 0 };
buf[mouse_x + w*(h-1-mouse_y)] = mouse;
}
}
#endif // USE_GPM
if (tty>=0)
{
// in linux virtual console we will use just 2 colors
WRITE("\x1B[%d;%d;%dm",(fg16&7)+(fg16<8?30:90),(bk16&7)+40,bk16<8?25:5);
for (int y = h-1; y>=0; y--)
{
AnsiCell* ptr = buf + y*w;
for (int x=0; x<w; x++,ptr++)
{
const char* chr = utf[ptr->gl];
if (ptr->fg != fg)
{
if (ptr->bk != bk)
{
WRITE("\e]P%X%02x%02x%02x", fg16, pal_rgba[ptr->fg][0], pal_rgba[ptr->fg][1], pal_rgba[ptr->fg][2]);
WRITE("\e]P%X%02x%02x%02x", bk16, pal_rgba[ptr->bk][0], pal_rgba[ptr->bk][1], pal_rgba[ptr->bk][2]);
WRITE("%s", chr);
}
else
{
WRITE("\e]P%X%02x%02x%02x", fg16, pal_rgba[ptr->fg][0], pal_rgba[ptr->fg][1], pal_rgba[ptr->fg][2]);
WRITE("%s", chr);
}
}
else
{
if (ptr->bk != bk)
{
WRITE("\e]P%X%02x%02x%02x", bk16, pal_rgba[ptr->bk][0], pal_rgba[ptr->bk][1], pal_rgba[ptr->bk][2]);
WRITE("%s", chr);
}
else
WRITE("%s",chr);
}
bk=ptr->bk;
fg=ptr->fg;
}
if (y)
WRITE("\n");
}
}
else
{
for (int y = h-1; y>=0; y--)
{
AnsiCell* ptr = buf + y*w;
for (int x=0; x<w; x++,ptr++)
{
//const char* chr = (x+y)&1 ? "X":"Y";
const char* chr = utf[ptr->gl];
if (ptr->fg != fg)
if (ptr->bk != bk)
WRITE("\x1B[38;5;%d;48;5;%dm%s",ptr->fg,ptr->bk,chr);
else
WRITE("\x1B[38;5;%dm%s",ptr->fg,chr);
else
if (ptr->bk != bk)
WRITE("\x1B[48;5;%dm%s",ptr->bk,chr);
else
WRITE("%s",chr);
bk=ptr->bk;
fg=ptr->fg;
}
if (y)
WRITE("\n");
}
}
FLUSH();
}
bool running = false;
void exit_handler(int signum)
{
running = false;
SetScreen(false);
if (tty>0)
{
// restore old font
const char* temp_dir = getenv("SNAP_USER_DATA");
if (!temp_dir || !temp_dir[0])
temp_dir = "/tmp";
char cmd[2048];
sprintf(cmd,"setfont %s/asciicker.%d.psf; rm %s/asciicker.%d.psf; clear;", temp_dir, tty, temp_dir, tty);
system(cmd);
}
exit(0);
}
uint64_t GetTime()
{
static timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
}
#else
#define GetTime() a3dGetTime()
#endif
Material mat[256];
void* GetMaterialArr()
{
return mat;
}
void* GetFontArr();
int fonts_loaded=0;
struct MyFont
{
static bool Scan(A3D_DirItem item, const char* name, void* cookie)
{
if (!(item&A3D_FILE))
return true;
char buf[4096];
snprintf(buf,4095,"%s/%s",(char*)cookie,name);
buf[4095]=0;
a3dLoadImage(buf, 0, MyFont::Load);
return true;
}
static int Sort(const void* a, const void* b)
{
MyFont* fa = (MyFont*)a;
MyFont* fb = (MyFont*)b;
int qa = fa->width*fa->height;
int qb = fb->width*fb->height;
return qa - qb;
}
static void Free()
{
MyFont* fnt = (MyFont*)GetFontArr();
for (int i=0; i<fonts_loaded; i++)
{
glDeleteTextures(1,&fnt[i].tex);
}
}
static void Load(void* cookie, A3D_ImageFormat f, int w, int h, const void* data, int palsize, const void* palbuf)
{
if (fonts_loaded==256)
return;
MyFont* fnt = (MyFont*)GetFontArr() + fonts_loaded;
fnt->width = w;
fnt->height = h;
int ifmt = GL_RGBA8;
int fmt = GL_RGBA;
int type = GL_UNSIGNED_BYTE;
uint32_t* buf = (uint32_t*)malloc(w * h * sizeof(uint32_t));
uint8_t rgb[3] = { 0xff,0xff,0xff };
ConvertLuminance_UI32_LLZZYYXX(buf, rgb, f, w, h, data, palsize, palbuf);
gl3CreateTextures(GL_TEXTURE_2D, 1, &fnt->tex);
gl3TextureStorage2D(fnt->tex, 1, ifmt, w, h);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
gl3TextureSubImage2D(fnt->tex, 0, 0, 0, w, h, fmt, type, buf ? buf : data);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
float white_transp[4] = { 1,1,1,0 };
gl3TextureParameteri2D(fnt->tex, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
gl3TextureParameteri2D(fnt->tex, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
gl3TextureParameteri2D(fnt->tex, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
gl3TextureParameteri2D(fnt->tex, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
gl3TextureParameterfv2D(fnt->tex, GL_TEXTURE_BORDER_COLOR, white_transp);
/*
// if we want to filter font we'd have first to
// modify 3 things in font sampling by shader:
// - clamp uv to glyph boundary during sampling
// - fade result by distance normalized to 0.5 of texel
// between unclamped uv to clamping glyph boundary
// - use manual lod as log2(font_zoom)
int max_lod = 0;
while (!((w & 1) | (h & 1)))
{
max_lod++;
w >>= 1;
h >>= 1;
}
glGenerateTextureMipmap(fnt->tex);
glTextureParameteri(fnt->tex, GL_TEXTURE_MAX_LOD, max_lod);
*/
if (buf)
free(buf);
fonts_loaded++;
qsort(GetFontArr(), fonts_loaded, sizeof(MyFont), MyFont::Sort);
}
void SetTexel(int x, int y, uint8_t val)
{
uint8_t texel[4] = { 0xFF,0xFF,0xFF,val };
gl3TextureSubImage2D(tex, 0, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, texel);
}
uint8_t GetTexel(int x, int y)
{
uint8_t texel[4];
gl3GetTextureSubImage(tex, 0, x, y, 0, 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 4, texel);
return texel[3];
}
int width;
int height;
GLuint tex;
} font[256];
void* GetFontArr()
{
return font;
}
// make term happy
float pos_x,pos_y,pos_z;
float rot_yaw;
int probe_z;
float global_lt[4];
World* world=0;
Terrain* terrain=0;
int font_zoom = 0;
int GetGLFont(int wh[2], const int wnd_wh[2])
{
float err = 0;
assert(wnd_wh);
float area = (float)(wnd_wh[0]*wnd_wh[1]);
int j = -1;
for (int i=0; i<fonts_loaded; i++)
{
MyFont* f = font + i;
float e = fabsf( 120.0f*75.0f - area / ((f->width>>4)*(f->height>>4)));
if (!i || e<err)
{
j = i;
err = e;
}
}
j += font_zoom;
j = j < 0 ? 0 : j >= fonts_loaded ? fonts_loaded - 1 : j;
MyFont* f = font + j;
if (wh)
{
wh[0] = f->width;
wh[1] = f->height;
}
return f->tex;
}
static int tty_font = 4;
static const int tty_fonts[] = {6,8,10,12,14,16,18,20,24,28,32,-1};
// TODO WEB ZOOMING & FULLSCREENING!
// ...
#ifdef PURE_TERM
static bool xterm_fullscreen = false;
void ToggleFullscreen(Game* g)
{
const char* term_env = getenv("TERM");
if (!term_env)
term_env = "";
if (strcmp( term_env, "linux" ) != 0)
{
xterm_fullscreen = !xterm_fullscreen;
if (xterm_fullscreen)
int w = write(STDOUT_FILENO, "\033[9;1t",6);
else
int w = write(STDOUT_FILENO, "\033[9;0t",6);
}
}
bool IsFullscreen(Game* g)
{
return xterm_fullscreen;
}
#endif
bool PrevGLFont()
{
#ifdef PURE_TERM
if (tty>0)
{
tty_font--;
if (tty_font<0)
tty_font=0;
char cmd[1024];
sprintf(cmd,"setfont %sfonts/cp437_%dx%d.png.psf", base_path, tty_fonts[tty_font], tty_fonts[tty_font]);
system(cmd);
}
else
{
// this will work only if xterm has enabled font ops
int w = write(STDOUT_FILENO, "\033]50;#-1\a",9);
if (xterm_fullscreen)
int w = write(STDOUT_FILENO, "\033[9;1t",6);
else
int w = write(STDOUT_FILENO, "\033[9;0t",6);
}
#else
font_zoom--;
if (font_zoom < -fonts_loaded / 2)
{
font_zoom = -fonts_loaded / 2;
return false;
}
TermResizeAll();
#endif
return true;
}
bool NextGLFont()
{
#ifdef PURE_TERM
if (tty>0)
{
tty_font++;
if (tty_fonts[tty_font]<0)
tty_font--;
char cmd[1024];
sprintf(cmd,"setfont %sfonts/cp437_%dx%d.png.psf", base_path, tty_fonts[tty_font], tty_fonts[tty_font]);
system(cmd);
}
else
{
// this will work only if xterm has enabled font ops
int w = write(STDOUT_FILENO, "\033]50;#+1\a",9);
if (xterm_fullscreen)
int w = write(STDOUT_FILENO, "\033[9;1t",6);
else
int w = write(STDOUT_FILENO, "\033[9;0t",6);
}
#else
font_zoom++;
if (font_zoom > fonts_loaded/2)
{
font_zoom = fonts_loaded/2;
return false;
}
TermResizeAll();
#endif
return true;
}
Server* server = 0;
struct GameServer : Server
{
TCP_SOCKET server_socket;
static const int buf_size = 1<<16;
uint8_t buf[buf_size];
int buf_ofs;
struct MSG_FIFO
{
uint8_t* ptr;
int size;
};
static const int max_msg_size = 1 << 8;
static const int msg_size = buf_size / max_msg_size;
MSG_FIFO msg[msg_size];
int msg_read; // r/w only by main-thread wrapped at 256 to 0
int msg_write; // r/w only by net-thread wrapped at 256 to 0
volatile unsigned int msg_num; // inter_inc by net-thread, inter_and(0) by main-thread
bool Start()
{
head = 0;
tail = 0;
others = (Human*)malloc(sizeof(Human) * max_clients);
buf_ofs = 0;
msg_read = 0;
msg_write = 0;
msg_num = 0;
bool ok = THREAD_CREATE_DETACHED(Entry, this);
if (!ok)
{
return false;
}
stamp = GetTime();
return true;
}
void Recv()
{
while (1)
{
while (msg_num == msg_size)
THREAD_SLEEP(15);
int r = WS_READ(server_socket, buf + buf_ofs, 2048, 0);
MSG_FIFO* m = msg + msg_write;
m->size = r;
m->ptr = buf + buf_ofs;
INTERLOCKED_INC(&msg_num);
if (r<=0)
break;
msg_write = (msg_write + 1)&(msg_size - 1);
buf_ofs += r;
if (buf_size - buf_ofs < max_msg_size)
buf_ofs = 0;
}
}
static void* Entry(void* arg)
{
GameServer* gs = (GameServer*)arg;
gs->Recv();
return 0;
}
void Stop()
{
// finish thread
// close socket
if (server_socket != INVALID_TCP_SOCKET)
{
TCP_CLOSE(server_socket);
TCP_CLEANUP();
}
server_socket = INVALID_TCP_SOCKET;
if (others)
free(others);
others = 0;
}
};
bool Server::Send(const uint8_t* data, int size)
{
GameServer* gs = (GameServer*)this;
int w = WS_WRITE(gs->server_socket, (const uint8_t*)data, size, 0, true);
if (w <= 0)
{
gs->Stop();
free(others);
free(server);
server=0;
return false;
}
return true;
}
void Server::Proc()
{
GameServer* gs = (GameServer*)this;
int num = gs->msg_num;
for (int i = 0; i < num; i++)
{
GameServer::MSG_FIFO* m = gs->msg + gs->msg_read;
if (m->size<=0)
{
free(others);
free(server);
server = 0;
return;
}
Server::Proc(m->ptr, m->size); // this would be called directly by JS
gs->msg_read = (gs->msg_read + 1)&(GameServer::msg_size - 1);
}
INTERLOCKED_SUB(&gs->msg_num, num);
}
void Server::Log(const char* str)
{
//printf("%s",str);
}
GameServer* Connect(const char* addr, const char* port, const char* path, const char* user)
{
int iResult;
// Initialize Winsock
iResult = TCP_INIT();
if (iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return 0;
}
TCP_SOCKET server_socket = INVALID_TCP_SOCKET;
const char* hostname = addr;
const char* portname = port;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
struct addrinfo* result = 0;
iResult = getaddrinfo(hostname, portname, &hints, &result);
if (iResult != 0)
{
printf("getaddrinfo failed: %d\n", iResult);
TCP_CLEANUP();
return 0;
}
// socket create and varification
server_socket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (server_socket == INVALID_TCP_SOCKET)
{
printf("socket creation failed...\n");
TCP_CLEANUP();
return 0;
}
else
printf("Socket successfully created..\n");
// connect the client socket to server socket
if (connect(server_socket, result->ai_addr, (int)result->ai_addrlen) != 0)
{
printf("connection with the server failed...\n");
TCP_CLOSE(server_socket);
TCP_CLEANUP();
return 0;
}
else
printf("connected to the server..\n");
int optval = 1;
if (setsockopt(server_socket, SOL_SOCKET, SO_KEEPALIVE, (const char*)&optval, sizeof(optval)) != 0)
{
// ok we can live without it
}
optval = 1;
if (setsockopt(server_socket, IPPROTO_TCP, TCP_NODELAY, (const char*)&optval, sizeof(optval)) != 0)
{
// ok we can live without it
}
freeaddrinfo(result);
// first, send HTTP->WS upgrade request (over http)
const char* request_fmt =
"GET /%s HTTP/1.1\r\n"
"Host: %s\r\n"
#ifdef _WIN32
"User-Agent: native-asciicker-windows\r\n"
#else
"User-Agent: native-asciicker-linux\r\n"
#endif
"Accept: */*\r\n"
"Accept-Language: en-US,en;q=0.5\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: btsPdKGunHdaTPnSSDlfow==\r\n"
"Pragma: no-cache\r\n"
"Cache-Control: no-cache\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n\r\n";
char request[2048];
sprintf(request, request_fmt, path, addr);
int w = TCP_WRITE(server_socket, (uint8_t*)request, (int)strlen(request));
if (w < 0)
{
TCP_CLOSE(server_socket);
TCP_CLEANUP();
return 0;
}
// wait for response (check HTTP status / headers)
struct Headers
{
static int cb(const char* header, const char* value, void* param)
{
Headers* h = (Headers*)param;
if (header)
{
if (strcmp("Content-Length", header) == 0)
h->content_len = atoi(value);
}
return 0;
}
int content_len;
} headers;
headers.content_len = 0;
char buf[2048];
int over_read = HTTP_READ(server_socket, Headers::cb, &headers, buf);
if (over_read < 0 || over_read > headers.content_len || headers.content_len > 2048)
{
TCP_CLOSE(server_socket);
TCP_CLEANUP();
return 0;
}
while (headers.content_len > over_read)
{
int r = TCP_READ(server_socket, (uint8_t*)buf + over_read, headers.content_len - over_read);
if (r <= 0)
{
TCP_CLOSE(server_socket);
TCP_CLEANUP();
return 0;
}
over_read += r;
}
// server should stay silent till we join the game
// send JOIN command along with user name (over ws)
STRUCT_REQ_JOIN req_join = { 0 };
req_join.token = 'J';
strncpy(req_join.name, user, 30);
int ws = WS_WRITE(server_socket, (uint8_t*)&req_join, sizeof(STRUCT_REQ_JOIN), 0, true);
if (ws <= 0)
{
TCP_CLOSE(server_socket);
TCP_CLEANUP();
return 0;
}
// Recv for ID (over ws) (it can send us some content to display!)
STRUCT_RSP_JOIN rsp_join = { 0 };
ws = WS_READ(server_socket, (uint8_t*)&rsp_join, sizeof(STRUCT_RSP_JOIN), 0);
if (ws <= 0 || rsp_join.token != 'j')
{
TCP_CLOSE(server_socket);
TCP_CLEANUP();
return 0;
}
int ID = rsp_join.id;
printf("connected with ID:%d/%d\n", ID, rsp_join.maxcli);
GameServer* gs = (GameServer*)malloc(sizeof(GameServer));
gs->server_socket = server_socket;
gs->max_clients = rsp_join.maxcli;
return gs;
}
extern "C" void DumpLeakCounter();
#if defined(__linux__) || defined(__APPLE__)
static int find_tty()
{
char buf[256];
char* ptr;
FILE* f;
int r;
char stat;
int ppid,pgrp,sess,tty;
int pid = getpid();
while (pid>0)
{
sprintf(buf,"/proc/%d/stat",pid);
f = fopen(buf,"r");
if (!f)
return 0;
r = fread(buf,1,255,f);
fclose(f);
if (r<=0)
return 0;
buf[r] = 0;
ptr = strchr(buf,')');
if (!ptr || !ptr[1])
return 0;
r = sscanf(ptr+2,"%c %d %d %d %d", &stat,&ppid,&pgrp,&sess,&tty);
if (r!=5)
return 0;
if ( (tty&~63) == 1024 && (tty&63) )
return tty&63;
pid = ppid;
}
return 0;
}
#endif
#ifdef __linux__
#define KEY_MAX_LARGE 0x2FF
//#define KEY_MAX_SMALL 0x1FF
#define AXMAP_SIZE (ABS_MAX + 1)
#define BTNMAP_SIZE (KEY_MAX_LARGE - BTN_MISC + 1)
static uint16_t js_btnmap[BTNMAP_SIZE];
static uint8_t js_axmap[AXMAP_SIZE];
static const int js_btnmap_sdl[]=
{
0, 1, -1, // A,B
2, 3, -1, // X,Y
9,10, -1,-1, // L,R SHOULDERS
4,6,5, // BACK, START, GUIDE
7,8, -1, // L,R STICK
-1,-1,-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1
};
static const int js_axmap_sdl[]=
{
0,1,4, // LEFT X,Y,TRIG
2,3,5, // RIGHT X,Y,TRIG
-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1,
0xFE,0xFF, // X,Y AXIS FOR DIRPAD (left:13, right:14, up:11, down:12) !!!
-1,-1, -1,-1,-1,-1,
-1,-1,-1,-1, -1,-1,-1,-1
};
#endif
int scan_js(char* gamepad_name, int* gamepad_axes, int* gamepad_buttons, uint8_t* gamepad_mapping)
{
#ifdef __linux__
static int index = 0;
static int skip = 0;
if (skip>0)
{
skip--;
return -1;
}
char js_term_dev[32];
sprintf(js_term_dev,"/dev/input/js%d",index);
int fd = -1;
if ((fd = open(js_term_dev, O_RDONLY)) < 0)
{
// printf("can't open %s\n", js_term_dev);
index = (index+1) & 0xF;
skip = 10;
fd = -1;
}
else
{
#define NAME_LENGTH 128
unsigned char axes = 2;
unsigned char buttons = 2;
int version = 0x000800;
char name[NAME_LENGTH] = "Unknown";
ioctl(fd, JSIOCGVERSION, &version);
ioctl(fd, JSIOCGAXES, &axes);
ioctl(fd, JSIOCGBUTTONS, &buttons);
ioctl(fd, JSIOCGNAME(NAME_LENGTH), name);
strcpy(gamepad_name,name);
*gamepad_axes = axes;
*gamepad_buttons = buttons;
// fetch button map
memset(js_btnmap,-1,sizeof(js_btnmap));
int btnmap_res = ioctl(fd, JSIOCGBTNMAP, js_btnmap);
// fetch axis map
memset(js_axmap,-1,sizeof(js_axmap));
int axmap_res = ioctl(fd, JSIOCGAXMAP, js_axmap);
// construct mapping
uint8_t* m = gamepad_mapping;
for (int i=0; i<buttons; i++)
{
int abs = 2*axes + i;
switch(js_btnmap[i])
{
case BTN_A: m[abs] = (1<<7) | (0<<6) | 0x00; break;
case BTN_B: m[abs] = (1<<7) | (0<<6) | 0x01; break;
case BTN_X: m[abs] = (1<<7) | (0<<6) | 0x02; break;
case BTN_Y: m[abs] = (1<<7) | (0<<6) | 0x03; break;
case BTN_SELECT: m[abs] = (1<<7) | (0<<6) | 0x04/*back_button*/; break;
case BTN_MODE: m[abs] = (1<<7) | (0<<6) | 0x05/*guide_button*/; break;
case BTN_START: m[abs] = (1<<7) | (0<<6) | 0x06/*start_button*/; break;
case BTN_THUMBL: m[abs] = (1<<7) | (0<<6) | 0x07/*left_stick_button*/; break;
case BTN_THUMBR: m[abs] = (1<<7) | (0<<6) | 0x08/*right_stick_button*/; break;
case BTN_TL: m[abs] = (1<<7) | (0<<6) | 0x09/*left_shoulder_button*/; break;
case BTN_TR: m[abs] = (1<<7) | (0<<6) | 0x0A/*right_shoulder_button*/; break;
case BTN_TL2: m[abs] = (0<<7) | (0<<6) | 0x02/*left_trigger_axis*/; break;
case BTN_TR2: m[abs] = (0<<7) | (0<<6) | 0x05/*right_trigger_axis*/; break;
default:
m[i] = 0xFF;
}
}
for (int i=0; i<axes; i++)
{
int neg = 2*i;
int pos = 2*i+1;
switch(js_axmap[i])
{
case 0: //left-x
m[neg] = (0<<7) | (1<<6) | 0x00;
m[pos] = (0<<7) | (0<<6) | 0x00;
break;
case 1: //left-y
m[neg] = (0<<7) | (1<<6) | 0x01;
m[pos] = (0<<7) | (0<<6) | 0x01;
break;
case 2: // left-z (compressed, 0x04 output is unsigned )
m[neg] = (0<<7) | (0<<6) | 0x04;
m[pos] = (0<<7) | (0<<6) | 0x04;
break;
case 3: //right-x
m[neg] = (0<<7) | (1<<6) | 0x02;
m[pos] = (0<<7) | (0<<6) | 0x02;
break;
case 4: //right-y
m[neg] = (0<<7) | (1<<6) | 0x03;
m[pos] = (0<<7) | (0<<6) | 0x03;
break;
case 5: //right-z (compressed, 0x05 output is unsigned )
m[neg] = (0<<7) | (0<<6) | 0x05;
m[pos] = (0<<7) | (0<<6) | 0x05;
break;
case 16: // dirpad-x
m[neg] = (1<<7) | (0<<6) | 0x0D;
m[pos] = (1<<7) | (0<<6) | 0x0E;
break;
case 17: // dirpad-y
m[neg] = (1<<7) | (0<<6) | 0x0B;
m[pos] = (1<<7) | (0<<6) | 0x0C;
break;
default:
m[i] = 0xFF;
}
}
}
return fd;
#endif
return -1;
}
bool read_js(int fd)
{
#ifdef __linux__
#define MAX_JS_READ 64
js_event js_arr[MAX_JS_READ];
int size = read(fd, js_arr, sizeof(js_event)*MAX_JS_READ);
if (size<=0 || size % sizeof(js_event))
return false;
/*
static int dirpad_x = 0;
static int dirpad_y = 0;
*/
int n = size / sizeof(js_event);
for (int i=0; i<n; i++)
{
js_event* js = js_arr+i;
// process
switch(js->type & ~JS_EVENT_INIT)
{
case JS_EVENT_BUTTON:
GamePadButton(js->number,js->value ? 32767 : 0);
break;
case JS_EVENT_AXIS:
GamePadAxis(js->number,js->value == -32768 ? -32767 : js->value);
break;
}
}
return true;
#endif
return false;
}
int main(int argc, char* argv[])
{
/*
FILE* fpal = fopen("d:\\ascii-work\\asciicker.act", "wb");
for (int i = 0; i < 16; i++)
{
uint8_t col[3] = { 0,0,0 };
fwrite(col, 3, 1, fpal);
}
for (int r = 0; r < 6; r++)
for (int g = 0; g < 6; g++)
for (int b = 0; b < 6; b++)
{
uint8_t col[3] = { r*51,g*51,b*51 };
fwrite(col, 3, 1, fpal);
}
for (int i = 0; i < 24; i++)
{
uint8_t col[3] = { 0,0,0 };
fwrite(col, 3, 1, fpal);
}
return 0;
*/
char abs_buf[PATH_MAX];
char* abs_path = 0;
if (argc < 1)
strcpy(base_path,"./");
else
{
size_t len = 0;
#if defined(__linux__) || defined(__APPLE__)
abs_path = realpath(argv[0], abs_buf);
char* last_slash = strrchr(abs_path, '/');
if (!last_slash)
strcpy(base_path,"./");
else
{
len = last_slash - abs_path + 1;
memcpy(base_path,abs_path,len);
base_path[len] = 0;
}
#else
GetFullPathNameA(argv[0],1024,abs_buf,&abs_path);
memcpy(base_path, abs_buf, abs_path - abs_buf);
#endif
int max_attempts{15};
int attempts{0};
int new_len{0};
printf("WARN: Folder with all asciiid resources should be named 'asciiid'.\n");
printf("INFO: Asciiid will now preform recursive search for this directory with %d max attempts...\n", max_attempts);
#if defined(__linux__) || defined(__APPLE__)
while (strcmp(strrchr(base_path, '/'), "/asciiid") != 0) {
printf("INFO: Current directory: %s, searching for 'asciiid/', full path: %s\n", strrchr(base_path, '/'), base_path);
new_len = strlen(base_path) - strlen(strrchr(base_path, '/'));
if (new_len == 0) {
printf("ERR: Recursive search reached root.\n");
exit(1);
}
base_path[new_len] = 0;
if (max_attempts == attempts) {
printf("ERR: Recursive search exceeded maximum attempts.\n");
exit(1);
}
attempts++;
}
#elif defined(_WIN32)
while (strcmp(strrchr(base_path, '\\'), "\\asciiid") != 0) {
printf("INFO: Current directory: %s, searching for 'asciiid\\', full path: %s\n", strrchr(base_path, '\\'), base_path);
new_len = strlen(base_path) - strlen(strrchr(base_path, '\\'));
if (new_len == 0) {
printf("ERR: Recursive search reached root.\n");
exit(1);
}
base_path[new_len] = 0;
if (max_attempts == attempts) {
printf("ERR: Recursive search exceeded maximum attempts.\n");
exit(1);
}
attempts++;
}
#endif
size_t length = strlen(base_path);
#if defined(__linux__) || defined(__APPLE__)
base_path[length] = '/';
#elif _WIN32
base_path[length] = '\\';
#endif
base_path[length + 1] = 0;
}
printf("INFO: Execution path: %s\n", argv[0]);
printf("INFO: Resources folder path: %s\n", base_path);
/*
int c16 = 13;
printf("\x1B[%d;%dm%s",(c16&7)+40,c16<8?25:5,"\n");
for (int b=0; b<6; b++)
{
for (int r=0; r<6; r++)
{
for (int g=0; g<6; g++)
{
int c256 = b + 6*g + 36*r + 16;
printf("\e]P%X%02x%02x%02x", c16, pal_rgba[c256][0], pal_rgba[c256][1], pal_rgba[c256][2]);
printf(" ");
}
}
printf("\n");
}
exit(0);
*/
#ifdef _WIN32
PostMessage(GetConsoleWindow(), WM_SYSCOMMAND, SC_MINIMIZE, 0);
//_CrtSetBreakAlloc(5971);
#endif
// if there is no '-term' arg given run A3D (GL) term
// ...
// otherwise continue with following crap
// ...
// consider configuring kbd, it solves only key up, not multiple keys down
/*
gsettings set org.gnome.desktop.peripherals.keyboard repeat-interval 30
gsettings set org.gnome.desktop.peripherals.keyboard delay 250
*/
// if -user is given get its name and connect to server !
char* url = 0; // must be in form [user@]server_address/path[:port]
// to be upgraded by host (good if no encryption is needed but can't connect on weird port)
/*
const char* user = "player";
const char* addr = "asciicker.com";
const char* path = "/ws/y8/";
const char* port = "80";
*/
// to be upgraded by host (good if encryption is needed)
/*
const char* user = "player";
const char* addr = "asciicker.com";
const char* path = "/ws/y8/";
const char* port = "443";
*/
// directly (best but no encryption and requires weird port to be allowed to send request to)
/*
const char* user = "player";
const char* addr = "asciicker.com";
const char* path = "/ws/y8/"; // just to check if same as server expects
const char* port = "8080";
*/
bool term = false;
for (int p=1; p<argc; p++)
{
if (strcmp(argv[p],"-term")==0) {
term = true;
} else if (p+1<argc)
{
if (strcmp(argv[p], "-url") == 0)
{
p++;
url = argv[p];
}
}
}
// NET_TODO:
// if url is given try to open connection
GameServer* gs = 0;
if (url)
{
// [user@]server_address/path[:port]
char* monkey = strchr(url, '@');
char* colon = monkey ? strchr(monkey, ':') : strchr(url, ':');
char* slash = colon ? strchr(colon, '/') : monkey ? strchr(monkey, '/') : strchr(url, '/');
char def_user[] = "player";
char def_port[] = "8080";
char def_path[] = "";
char* addr = url;
char* user = def_user;
char* port = def_port;
char* path = def_path;
if (monkey)
{
*monkey = 0;
user = url;
addr = monkey + 1;
}
if (colon)
{
*colon = 0;
port = colon + 1;
}
if (slash)
{
*slash = 0;
path = slash + 1;
}
if (addr && addr[0])
{
gs = Connect(addr, port, path, user);
if (!gs)
{
printf("Couldn't connect to server, starting solo ...\n");
}
}
strcpy(player_name, user);
ConvertToCP437(player_name_cp437, player_name);
// here we should know if server is present or not
// so we can creare game or term with or without server
// ...
}
else
{
strcpy(player_name, "player");
ConvertToCP437(player_name_cp437, player_name);
}
float water = 55;
float dir = 0;
float yaw = 45;
float pos[3] = {0,15,0};
float lt[4] = {1,0,1,.5};
float last_yaw = yaw;
LoadSprites();
{
char a3d_path[1024];
sprintf(a3d_path,"%sa3d/game_map_y8.a3d", base_path);
FILE* f = fopen(a3d_path, "rb");
// TODO:
// if GameServer* gs != 0
// DO NOT LOAD ITEMS!
// we will receive them from server
if (f)
{
terrain = LoadTerrain(f);
if (terrain)
{
for (int i = 0; i < 256; i++)
{
if (fread(mat[i].shade, 1, sizeof(MatCell) * 4 * 16, f) != sizeof(MatCell) * 4 * 16)
break;
}
world = LoadWorld(f, false);
if (world)
{
// reload meshes too
Mesh* m = GetFirstMesh(world);
while (m)
{
char mesh_name[256];
GetMeshName(m, mesh_name, 256);
char obj_path[4096];
sprintf(obj_path, "%smeshes/%s", base_path, mesh_name);
if (!UpdateMesh(m, obj_path))
{
// what now?
// missing mesh file!
}
m = GetNextMesh(m);
}
LoadEnemyGens(f);
}
}
fclose(f);
}
// if (!terrain || !world)
// return -1;
// add meshes from library that aren't present in scene file
char mesh_dirname[4096];
sprintf(mesh_dirname, "%smeshes", base_path);
//a3dListDir(mesh_dirname, MeshScan, mesh_dirname);
// this is the only case when instances has no valid bboxes yet
// as meshes weren't present during their creation
// now meshes are loaded ...
// so we need to update instance boxes with (,true)
if (world)
{
RebuildWorld(world, true);
#ifdef DARK_TERRAIN
UpdateTerrainDark(terrain, world, lt, false);
#endif
}
}
if (gs)
{
server = gs;
if (!gs->Start())
{
TCP_CLEANUP();
return 1;
}
}
#ifndef PURE_TERM
if (!term)
{
probe_z = (int)water;
pos_x = pos[0];
pos_y = pos[1];
pos_z = pos[2];
rot_yaw = yaw;
global_lt[0] = lt[0];
global_lt[1] = lt[1];
global_lt[2] = lt[2];
global_lt[3] = lt[3];
if (TermOpen(0, yaw, pos, MyFont::Free))
{
char font_dirname[1024];
sprintf(font_dirname, "%sfonts", base_path); // = "./fonts";
fonts_loaded = 0;
a3dListDir(font_dirname, MyFont::Scan, font_dirname);
LoopInterface li = { GamePadMount, GamePadUnmount, GamePadButton, GamePadAxis };
a3dLoop(&li);
}
// NET_TODO:
// close network if open
// ...
if (terrain)
DeleteTerrain(terrain);
if (world)
DeleteWorld(world);
PurgeItemInstCache();
FreeSprites();
DumpLeakCounter();
#ifdef _WIN32
_CrtDumpMemoryLeaks();
#endif
return 0;
}
#endif // #ifndef PURE_TERM
#if defined(__linux__) || defined(__APPLE__)
// recursively check if we are on TTY console or 'vt'
const char* term_env = getenv("TERM");
if (!term_env)
term_env = "";
printf("TERM=%s\n",term_env);
if (strcmp( term_env, "linux" ) == 0)
{
tty = find_tty();
}
if (tty > 0)
{
// store current font
char cmd[1024];
const char* temp_dir = getenv("SNAP_USER_DATA");
if (!temp_dir || !temp_dir[0])
temp_dir = "/tmp";
sprintf(cmd,"setfont -O %s/asciicker.%d.psf;", temp_dir,tty);
system(cmd);
// setup default font
sprintf(cmd,"setfont %sfonts/cp437_%dx%d.png.psf", base_path, tty_fonts[tty_font], tty_fonts[tty_font]);
system(cmd);
#ifdef USE_GPM
Gpm_Connect conn;
conn.eventMask = ~0; /* Want to know about all the events */
conn.defaultMask = 0; /* don't handle anything by default */
conn.minMod = 0; /* want everything */
conn.maxMod = ~0; /* all modifiers included */
gpm_handler = 0;
gpm_visiblepointer = 0;
gpm = Gpm_Open(&conn, tty);
if (gpm >=0)
{
int wh[2];
GetWH(wh);
mouse_x = wh[0]/2;
mouse_y = wh[1]/2;
printf("connected to gpm\n");
}
else
{
printf("failed to connect to gpm\n");
// exit(0);
}
#endif // USE_GPM
}
else if (strncmp(term_env,"xterm",5)==0) {
printf("VIRTUAL TERMINAL EMULGLATOR\n");
/*
1. MANDATORY: install -gumix-*... fonts
cd ..directory_with_fonts
if not exist font.dir
mkfontdir
xset fp+ /home/user/asciiid/fonts
xset fp rehash
2. CONFIGURING XTerm during startup
2A. CONFIGURE Xterm to use 7 gumix fonts on startup
xterm \
-xrm "xterm*font1: -gumix-*-*-*-*-*-8-*-*-*-*-*-*" \
-xrm "xterm*font2: -gumix-*-*-*-*-*-10-*-*-*-*-*-*" \
-xrm "xterm*font3: -gumix-*-*-*-*-*-12-*-*-*-*-*-*" \
-xrm "xterm*font: -gumix-*-*-*-*-*-14-*-*-*-*-*-*" \
-xrm "xterm*font4: -gumix-*-*-*-*-*-16-*-*-*-*-*-*" \
-xrm "xterm*font5: -gumix-*-*-*-*-*-18-*-*-*-*-*-*" \
-xrm "xterm*font6: -gumix-*-*-*-*-*-20-*-*-*-*-*-*"
-xrm "xterm*allowWindowOps: true"
-xrm "xterm*allowFontOps: true"
// color and mouse ops are enabled by default
// title and TCap Ops are not neccessary
user can switch between fonts using SHIFT+NUMPAD(+/-)
2B. As above but all resource strings can be stored in .Xresources
optionally using asciicker as a class name (insteead of xterm)
xterm -class asciicker
2C. CONFIGURE Xterm on startup to use just 1 font
xterm -fn -gumix-*-*-*-*-*-14-*-*-*-*-*-*"
3. Setting current font in RUN-TIME!
Possible only if xterm has 'Allow Font Ops' enabled
echo -ne "\e]50;-gumix-*-*-*-*-*-14-*-*-*-*-*-*-*\a"
also it is possible to switch between 7 fonts (replace <n> with digit):
echo -ne "\e]50;#<n>\a"
both methods could be uses to compensate for too small or too large resolution
*/
// palette setup
for (int col = 16; col<232; col++)
{
const uint8_t* c = pal_rgba[col];
printf("\x1B]4;%d;#%02x%02x%02x\a", col, c[0],c[1],c[2]);
}
printf("\n");
}
else {
printf("UNKNOWN TERMINAL\n");
}
// try opening js device
int gamepad_axes = 0;
int gamepad_buttons = 0;
char gamepad_name[256] = {0};
uint8_t gamepad_mapping[256] = {0};
int jsfd = scan_js(gamepad_name,&gamepad_axes,&gamepad_buttons,gamepad_mapping);
SetScreen(true);
int signals[]={SIGTERM,SIGHUP,SIGINT,SIGTRAP,SIGILL,SIGABRT,SIGKILL,0};
struct sigaction new_action, old_action;
new_action.sa_handler = exit_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
for (int i=0; signals[i]; i++)
{
sigaction(signals[i], NULL, &old_action);
if (old_action.sa_handler != SIG_IGN)
sigaction(signals[i], &new_action, NULL);
}
running = true;
/*
if (!xterm_kitty)
{
SetScreen(false);
printf("TERMINATING: this pre-update build requires kitty terminal to run\n");
return -1;
}
*/
//terrain = 0;
//world = 0;
Game* game = 0;
AnsiCell* buf = 0;
int wh[2] = {-1,-1};
uint64_t begin = GetTime();
uint64_t stamp = begin;
uint64_t frames = 0;
// init CP437 to UTF8 converter
char CP437_UTF8 [256][4];
for (int i=0; i<256; i++)
CP437_UTF8[i][CP437[i](CP437_UTF8[i])]=0;
int kbd[256];
memset(kbd,0,sizeof(int)*256);
// LIGHT
{
float lit_yaw = 45;
float lit_pitch = 30;//90;
float lit_time = 12.0f;
float ambience = 0.5;
double noon_yaw[2] =
{
// zero is behind viewer
-sin(-lit_yaw*M_PI / 180),
-cos(-lit_yaw*M_PI / 180),
};
double dusk_yaw[3] =
{
-noon_yaw[1],
noon_yaw[0],
0
};
double noon_pos[4] =
{
noon_yaw[0]*cos(lit_pitch*M_PI / 180),
noon_yaw[1]*cos(lit_pitch*M_PI / 180),
sin(lit_pitch*M_PI / 180),
0
};
double lit_axis[3];
CrossProduct(dusk_yaw, noon_pos, lit_axis);
double time_tm[16];
Rotation(lit_axis, (lit_time-12)*M_PI / 12, time_tm);
double lit_pos[4];
Product(time_tm, noon_pos, lit_pos);
lt[0] = (float)lit_pos[0];
lt[1] = (float)lit_pos[1];
lt[2] = (float)lit_pos[2];
lt[3] = ambience;
}
// get initial time stamp
begin = GetTime();
stamp = begin;
game = CreateGame(water,pos,yaw,dir,stamp);
if (jsfd>=0)
{
// report mount
GamePadMount(gamepad_name,gamepad_axes,gamepad_buttons,gamepad_mapping);
}
while(running)
{
if (jsfd<0)
{
// report mount
jsfd = scan_js(gamepad_name,&gamepad_axes,&gamepad_buttons,gamepad_mapping);
if (jsfd >= 0)
GamePadMount(gamepad_name,gamepad_axes,gamepad_buttons,gamepad_mapping);
}
bool mouse_j = false;
// get time stamp
uint64_t now = GetTime();
int dt = now-stamp;
stamp = now;
if (!xterm_kitty)
{
for (int i=0; i<256; i++)
{
kbd[i] -= dt;
if (kbd[i]<0)
kbd[i]=0;
}
}
struct pollfd pfds[3]={0};
if (gpm>=0)
{
pfds[0].fd = STDIN_FILENO;
pfds[0].events = POLLIN;
pfds[0].revents = 0;
pfds[1].fd = gpm;
pfds[1].events = POLLIN;
pfds[1].revents = 0;
if (jsfd>=0)
{
pfds[2].fd = jsfd;
pfds[2].events = POLLIN|POLL_HUP|POLL_ERR;
pfds[2].revents = 0;
poll(pfds, 3, 0); // 0 no timeout, -1 block
if (pfds[2].revents & (POLLHUP|POLLERR))
{
GamePadUnmount();
close(jsfd);
jsfd=-1;
}
else
if (pfds[2].revents & POLLIN)
{
if (!read_js(jsfd))
{
GamePadUnmount();
close(jsfd);
jsfd=-1;
}
}
}
else
poll(pfds, 2, 0); // 0 no timeout, -1 block
#ifdef USE_GPM
if (pfds[1].revents & POLLIN)
{
static int mouse_read = 0;
static int mouse_write = 0;
static Gpm_Event mouse_buf[64];
int bytes = read(gpm,(char*)mouse_buf + mouse_write,32*sizeof(Gpm_Event));
mouse_write += bytes;
int events = mouse_write / sizeof(Gpm_Event) - mouse_read;
while (events)
{
Gpm_Event* event = mouse_buf + mouse_read;
events--;
mouse_read++;
mouse_x += event->dx;
mouse_y += event->dy;
if (mouse_x >= wh[0])
mouse_x = wh[0]-1;
if (mouse_x < 0)
mouse_x = 0;
if (mouse_y >= wh[1])
mouse_y = wh[1]-1;
if (mouse_y < 0)
mouse_y = 0;
bool xy_processed = false;
if (event->wdy>0)
{
xy_processed = true;
game->OnMouse(Game::MOUSE_WHEEL_UP, mouse_x, mouse_y);
}
else if (event->wdy<0) {
xy_processed = true;
game->OnMouse(Game::MOUSE_WHEEL_DOWN, mouse_x, mouse_y);
}
if (event->type & GPM_DOWN)
{
if (!(mouse_down&GPM_B_LEFT) && (event->buttons & GPM_B_LEFT))
{
xy_processed = true;
mouse_down|=GPM_B_LEFT;
game->OnMouse(Game::MOUSE_LEFT_BUT_DOWN, mouse_x, mouse_y);
}
if (!(mouse_down&GPM_B_MIDDLE) && (event->buttons & GPM_B_MIDDLE))
{
xy_processed = true;
mouse_down|=GPM_B_MIDDLE;
game->OnMouse(Game::MOUSE_MIDDLE_BUT_DOWN, mouse_x, mouse_y);
}
if (!(mouse_down&GPM_B_RIGHT) && (event->buttons & GPM_B_RIGHT))
{
xy_processed = true;
mouse_down|=GPM_B_RIGHT;
game->OnMouse(Game::MOUSE_RIGHT_BUT_DOWN, mouse_x, mouse_y);
}
}
if (event->type & GPM_UP)
{
if ((mouse_down&GPM_B_LEFT) && (event->buttons & GPM_B_LEFT))
{
xy_processed = true;
mouse_down&=~GPM_B_LEFT;
game->OnMouse(Game::MOUSE_LEFT_BUT_UP, mouse_x, mouse_y);
}
if ((mouse_down&GPM_B_MIDDLE) && (event->buttons & GPM_B_MIDDLE))
{
xy_processed = true;
mouse_down&=~GPM_B_MIDDLE;
game->OnMouse(Game::MOUSE_MIDDLE_BUT_UP, mouse_x, mouse_y);
}
if ((mouse_down&GPM_B_RIGHT) && (event->buttons & GPM_B_RIGHT))
{
xy_processed = true;
mouse_down&=~GPM_B_RIGHT;
game->OnMouse(Game::MOUSE_RIGHT_BUT_UP, mouse_x, mouse_y);
}
}
if (!xy_processed && (event->type & (GPM_MOVE|GPM_DRAG)))
{
xy_processed = true;
game->OnMouse(Game::MOUSE_MOVE, mouse_x, mouse_y);
}
}
if (mouse_write>=32*sizeof(Gpm_Event))
{
size_t tail = mouse_write - sizeof(Gpm_Event)*mouse_read;
if (tail)
memcpy(mouse_buf,mouse_buf + mouse_read, tail);
mouse_write = tail;
mouse_read = 0;
}
}
#endif // USE_GPM
}
else
{
// prep for poll
pfds[0].fd = STDIN_FILENO;
pfds[0].events = POLLIN;
pfds[0].revents = 0;
if (jsfd>=0)
{
pfds[1].fd = jsfd;
pfds[1].events = POLLIN|POLLHUP|POLLERR;
pfds[1].revents = 0;
poll(pfds, 2, 0); // 0 no timeout, -1 block
if (pfds[1].revents & (POLLHUP|POLLERR))
{
GamePadUnmount();
close(jsfd);
jsfd=-1;
}
else
if (pfds[1].revents & POLLIN)
{
if (!read_js(jsfd))
{
GamePadUnmount();
close(jsfd);
jsfd=-1;
}
}
}
else
poll(pfds, 1, 0); // 0 no timeout, -1 block
}
if (pfds[0].revents & POLLIN)
{
static int stream_bytes = 0;
static char stream[256];
char fresh[256];
int fresh_bytes = read(STDIN_FILENO, fresh, 256 - stream_bytes);
memcpy(stream + stream_bytes, fresh, fresh_bytes);
int bytes = stream_bytes + fresh_bytes;
/*
FILE* kl = fopen("keylog.txt","a");
for (int i=0; i<bytes; i++)
fprintf(kl,"0x%02X, ",stream[i]);
fprintf(kl,"\n");
fclose(kl);
*/
int i = 0;
while (i<bytes)
{
int j=i;
int type = 0, mods = 0;
if (stream[i]>=' ' && stream[i]<=127 ||
stream[i]==8 || stream[i]=='\r' || stream[i]=='\n' || stream[i]=='\t')
{
if (stream[i] == ' ')
{
// we need it both as char for TalkBox and as press for Jump
game->OnKeyb(Game::GAME_KEYB::KEYB_CHAR, ' ');
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_SPACE);
}
else if (stream[i] == '\t')
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_TAB);
else if (stream[i] == 127) // backspace (8) is encoded as del (127)
game->OnKeyb(Game::GAME_KEYB::KEYB_CHAR, 8);
else
game->OnKeyb(Game::GAME_KEYB::KEYB_CHAR, stream[i]);
i++;
continue;
}
// MUST HAVE
// TODO: non-kitty just to rotate, should emu sticky down
// F1,F2,DEL,INS,PGUP,PGDN
// ...
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == 'O' && stream[i+2] == 'P')
{
// F1
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_F1);
i+=3;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == 'O' && stream[i+2] == 'Q')
{
// F2
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_F2);
i+=3;
}
if (bytes-i >=4 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == '3' && stream[i+3] == '~')
{
// DEL
game->OnKeyb(Game::GAME_KEYB::KEYB_CHAR, 127);
i+=4;
}
if (bytes-i >=4 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == '2' && stream[i+3] == '~')
{
// INS
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_INSERT);
i+=4;
}
if (bytes-i >=4 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == '5' && stream[i+3] == '~')
{
// PGUP
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_PAGEUP);
i+=4;
}
if (bytes-i >=4 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == '6' && stream[i+3] == '~')
{
// PGDN
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_PAGEDOWN);
i+=4;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == 'D')
{
// left
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_LEFT);
i+=3;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == 'C')
{
// right
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_RIGHT);
i+=3;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == 'A')
{
// up
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_UP);
i+=3;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == 'B')
{
// down
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_DOWN);
i+=3;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == 'H')
{
// home
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_HOME);
i+=3;
}
if (bytes-i >=3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == 'F')
{
// end
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_END);
i+=3;
}
if (bytes-i >=4 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == '1' && stream[i+3] == ';')
{
if (bytes-i < 6)
break;
int mods = stream[i+4] - 0x31;
int a3d_mods = 0;
if (mods&1)
{
// shift
a3d_mods |= 0x1<<8;
}
if (mods&2)
{
// alt
a3d_mods |= 0x2<<8;
}
if (mods&4)
{
// ctrl ???
a3d_mods |= 0x4<<8;
}
switch (stream[i+5])
{
case 'P': // f1
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_F1 | a3d_mods);
break;
case 'Q': // f2
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_F2 | a3d_mods);
break;
case '3': // del
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_DELETE | a3d_mods);
break;
case '2': // ins
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_INSERT | a3d_mods);
break;
case '5': // pgup
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_PAGEUP | a3d_mods);
break;
case '6': // pgdn
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_PAGEDOWN | a3d_mods);
break;
case 'A': // up
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_UP | a3d_mods);
break;
case 'B': // down
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_DOWN | a3d_mods);
break;
case 'C': // right
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_RIGHT | a3d_mods);
break;
case 'D': // left
game->OnKeyb(Game::GAME_KEYB::KEYB_PRESS, A3D_LEFT | a3d_mods);
break;
}
i+=6;
}
// mouse SGR (1006) -> CSI < Bc;Px;Py;M (press) or CSI < Bc;Px;Py;m (release)
if (bytes-i >= 3 && stream[i] == 0x1B && stream[i+1] == '[' && stream[i+2] == '<')
{
int k=i+3;
int val[3]={0,0,0};
int fields=0, offset=0;
while (bytes-k>0)
{
if (stream[k]<'0' || stream[k]>'9')
{
int c = stream[k];
val[fields] = atoi(stream+k-offset);
fields++;
offset=0;
k++;
switch (c)
{
case ';':
if (fields<3)
continue;
break;
case 'm':
case 'M':
{
if (fields==3)
{
int but = val[0] & 0x3;
if (val[0] >= 64)
{
// wheel
if (but == 0)
game->OnMouse(Game::MOUSE_WHEEL_UP, val[1] - 1, val[2] - 1);
else
if (but == 1)
game->OnMouse(Game::MOUSE_WHEEL_DOWN, val[1] - 1, val[2] - 1);
}
else
if (val[0] >= 32)
{
// motion
int a=0;
game->OnMouse(Game::MOUSE_MOVE,val[1]-1,val[2]-1);
}
else
if (c=='M')
{
switch(but)
{
case 0:
game->OnMouse(Game::MOUSE_LEFT_BUT_DOWN,val[1]-1,val[2]-1);
break;
case 2:
game->OnMouse(Game::MOUSE_RIGHT_BUT_DOWN,val[1]-1,val[2]-1);
break;
default:
game->OnMouse(Game::MOUSE_MOVE,val[1]-1,val[2]-1);
}
}
else
if (c=='m')
{
switch(but)
{
case 0:
game->OnMouse(Game::MOUSE_LEFT_BUT_UP,val[1]-1,val[2]-1);
break;
case 2:
game->OnMouse(Game::MOUSE_RIGHT_BUT_UP,val[1]-1,val[2]-1);
break;
default:
game->OnMouse(Game::MOUSE_MOVE,val[1]-1,val[2]-1);
}
}
}
break;
}
}
i=k;
break;
}
else
{
offset++;
k++;
}
}
continue;
}
// 3. kitty keys
if (bytes-i >= 3 && stream[i] == 0x1B && stream[i+1] == '_' && stream[i+2] == 'K')
{
if (bytes-i < 8)
break;
if (bytes-i == 8 && stream[i+6] != 0x1B)
break;
switch (stream[i+3])
{
case 'p': type = +1; //press
break;
case 't': type = 0; //repeat
break;
case 'r': type = -1; //release
break;
}
if (stream[i+4]>='A' && stream[i+4]<='P')
{
mods = stream[i+4] -'A';
}
int codelen = 0;
if (stream[i+6]==0x1B && stream[i+7]=='\\')
codelen=1;
else if (stream[i+7]==0x1B && stream[i+8]=='\\')
codelen=2;
if ((mods & 4) && stream[i+5]=='U' && codelen==1) // CTRL+C
{
memset(kbd,0,sizeof(int)*256);
running = false;
break;
}
// store shift
if ( (mods&1) && type>=0 )
kbd[128+'a'] = 1;
else
kbd[128+'a'] = 0;
if (codelen==2 && stream[i+5]=='B')
{
switch (stream[i+6])
{
case 'A': // F17
case 'B': // F18
case 'C': // F19
case 'D': // F20
case 'E': // F21
case 'F': // F22
case 'G': // F23
case 'H': // F24
case 'I': // F25
case 'J': // KP0
case 'K': // KP1
case 'L': // KP2
case 'M': // KP3
case 'N': // KP4
case 'O': // KP5
case 'P': // KP6
case 'Q': // KP7
case 'R': // KP8
case 'S': // KP9
case 'T': // KP.
case 'U': // KP/
case 'V': // KP*
case 'W': // KP-
case 'X': // KP+
case 'Y': // KP enter
case 'Z': // KP=
case 'a': // left shift
case 'b': // left ctrl
case 'c': // left alt
case 'd': // left super (win?)
case 'e': // right shift
case 'f': // right ctrl
case 'g': // right alt
case 'h': // right super (win?)
{
if (type>0)
{
kbd[ 128 + stream[i+6] ] = 1;
}
if (type<0)
{
kbd[ 128 + stream[i+6] ] = 0;
}
i+=9;
break;
}
}
}
else
if (codelen==1)
{
switch (stream[i+5])
{
case '0': // TAB
case '1': // BACKSPACE
case '2': // INSERT
case '3': // DELETE
case '4': // RIGHT
case '5': // LEFT
case '6': // DOWN
case '7': // UP
case '8': // PAGEUP
case '9': // PAGEDN
case 'A': // SPACE
case 'B': // APOSTROPHE
case 'C': // COMMA
case 'D': // MINUS
case 'E': // PERIOD
case 'F': // SLASH
case 'G': // 0
case 'H': // 1
case 'I': // 2
case 'J': // 3
case 'K': // 4
case 'L': // 5
case 'M': // 6
case 'N': // 7
case 'O': // 8
case 'P': // 9
case 'Q': // SEMICOLON
case 'R': // EQUAL
case 'S': // A
case 'T': // B
case 'U': // C
case 'V': // D
case 'W': // E
case 'X': // F
case 'Y': // G
case 'Z': // H
case 'a': // I
case 'b': // J
case 'c': // K
case 'd': // L
case 'e': // M
case 'f': // N
case 'g': // O
case 'h': // P
case 'i': // Q
case 'j': // R
case 'k': // S
case 'l': // T
case 'm': // U
case 'n': // V
case 'o': // W
case 'p': // X
case 'q': // Y
case 'r': // Z
case 's': // [
case 't': // BACKSLASH
case 'u': // ]
case 'v': // ` GRAVE ACCENT
case 'w': // WORLD-1
case 'x': // WORLD-2
case 'y': // ESCAPE
case 'z': // ENTER
case '.': // HOME
case '-': // END
case '^': // PRINT SCREEN
case '+': // SCROLLOCK
case '!': // PAUSE
case '=': // NUMLOCK
case ':': // CAPSLOCK
case '/': // F1
case '*': // F2
case '?': // F3
case '&': // F4
case '<': // F5
case '>': // F6
case '(': // F7
case ')': // F8
case '[': // F9
case ']': // F10
case '{': // F11
case '}': // F12
case '@': // F13
case '%': // F14
case '$': // F15
case '#': // F16
{
if (type>0)
{
kbd[ stream[i+5] ] = 1;
}
if (type<0)
{
kbd[ stream[i+5] ] = 0;
}
i+=8;
break;
}
}
}
}
if (j==i)
break;
}
if (i)
{
// something parsed
stream_bytes = bytes - i;
memmove(stream, stream+i, stream_bytes);
}
else
{
// reset in hope of resync
memset(kbd,0,sizeof(int)*256);
stream_bytes = 0;
}
}
// get current terminal w,h
// if changed realloc renderer output
int nwh[2] = {0,0};
GetWH(nwh);
if (nwh[0]!=wh[0] || nwh[1]!=wh[1])
{
game->OnSize(nwh[0],nwh[1], 1,1);
wh[0] = nwh[0];
wh[1] = nwh[1];
/*
if (wh[0]*wh[1]>160*90)
{
float scale = sqrtf(160*90 / (wh[0]*wh[1]));
wh[0] = floor(wh[0] * scale + 0.5f);
wh[1] = floor(wh[1] * scale + 0.5f);
}
*/
buf = (AnsiCell*)realloc(buf,wh[0]*wh[1]*sizeof(AnsiCell));
}
// check all pressed chars array, release if timed out
// check number of chars awaiting in buffer
// -> read them all, mark as pressed for 0.1 sec / if already pressed prolong
// NET_TODO:
// if connection is open:
// dispatch all queued messages to game
// 1. flush list
// 2. reverse order
// 3. dispatch every message with term->game->OnMessage()
if (server)
server->Proc();
// render
if (wh[0]>0 && wh[1]>0)
{
game->Render(stamp,buf,wh[0],wh[1]);
// write to stdout
Print(buf,wh[0],wh[1],CP437_UTF8);
}
frames++;
}
if (jsfd>=0)
{
GamePadUnmount();
close(jsfd);
jsfd = -1;
}
// NET_TODO:
// close network if open
// ...
exit:
uint64_t end = GetTime();
#ifdef USE_GPM
if (gpm>=0)
{
Gpm_Close();
}
#endif // USE_GPM
if (terrain)
DeleteTerrain(terrain);
if (world)
DeleteWorld(world);
if (buf)
free(buf);
if (game)
DeleteGame(game);
SetScreen(false);
printf("FPS: %f (%dx%d)\n", frames * 1000000.0 / (end-begin), wh[0], wh[1]);
#else
printf("Currently -term parameter is unsupported on Windows\n");
#endif
PurgeItemInstCache();
FreeSprites();
#ifdef _WIN32
_CrtDumpMemoryLeaks();
#endif
return 0;
}
| 29.609559 | 156 | 0.450073 | [
"mesh",
"render"
] |
e7be0fec6217128843c1d5faa0040e9ed38b1ad0 | 3,610 | cpp | C++ | Source/Source/Tools/SceneEditor/Epoch/Maths/AxisAlignedBoundingBox.cpp | uvbs/FullSource | 07601c5f18d243fb478735b7bdcb8955598b9a90 | [
"MIT"
] | 2 | 2018-07-26T07:58:14.000Z | 2019-05-31T14:32:18.000Z | Jx3Full/Source/Source/Tools/SceneEditor/Epoch/Maths/AxisAlignedBoundingBox.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | null | null | null | Jx3Full/Source/Source/Tools/SceneEditor/Epoch/Maths/AxisAlignedBoundingBox.cpp | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
] | 5 | 2021-02-03T10:25:39.000Z | 2022-02-23T07:08:37.000Z | // File: AxisAlignedBoundingBox.cpp
// Desc:
#include"AxisAlignedBoundingBox.h"
namespace Maths
{
AxisAlignedBoundingBox::AxisAlignedBoundingBox(const Vector3F& vMin, const Vector3F& vMax, bool bCheckOverride): m_vMin(vMin), m_vMax(vMax)
{
if(bCheckOverride)
{
SetMin(vMin, vMax, m_vMin);
SetMax(vMin, vMax, m_vMax);
}
}
AxisAlignedBoundingBox& AxisAlignedBoundingBox::operator = (const AxisAlignedBoundingBox& aabb)
{
if(&aabb != this)
{
m_vMin = aabb.m_vMin;
m_vMax = aabb.m_vMax;
}
return *this;
}
bool AxisAlignedBoundingBox::IfOverlap(const AxisAlignedBoundingBox& aabb) const
{
if(aabb.m_vMin.x > m_vMax.x || aabb.m_vMin.y > m_vMax.y || aabb.m_vMin.z > m_vMax.z)
{
return false;
}
if(aabb.m_vMax.x < m_vMin.x || aabb.m_vMax.y < m_vMin.y || aabb.m_vMax.z < m_vMin.z)
{
return false;
}
return true;
}
RelativeLocation AxisAlignedBoundingBox::TestAnother(const AxisAlignedBoundingBox& aabb) const
{
if(aabb.m_vMin.x > m_vMax.x || aabb.m_vMin.y > m_vMax.y || aabb.m_vMin.z > m_vMax.z)
{
return RL_BACK;
}
if(aabb.m_vMax.x < m_vMin.x || aabb.m_vMax.y < m_vMin.y || aabb.m_vMax.z < m_vMin.z)
{
return RL_BACK;
}
if((m_vMin <= aabb.m_vMin) && (aabb.m_vMax <= m_vMax))
{
return RL_FRONT;
}
return RL_SPLIT;
}
void AxisAlignedBoundingBox::GetClosestPoint(const Vector3F& v, Vector3F& vcp) const
{
vcp.x = (v.x < m_vMin.x)? m_vMin.x: (v.x > m_vMax.x)? m_vMax.x: v.x;
vcp.y = (v.y < m_vMin.y)? m_vMin.y: (v.y > m_vMax.y)? m_vMax.y: v.y;
vcp.x = (v.z < m_vMin.z)? m_vMin.z: (v.z > m_vMax.z)? m_vMax.z: v.z;
}
void AxisAlignedBoundingBox::GetCorners(vector<Vector3F>& vCorners) const
{
vCorners.clear();
vCorners.push_back(m_vMin);
vCorners.push_back(Vector3F(m_vMin.x, m_vMax.y, m_vMin.z));
vCorners.push_back(Vector3F(m_vMax.x, m_vMax.y, m_vMin.z));
vCorners.push_back(Vector3F(m_vMax.x, m_vMin.y, m_vMin.z));
vCorners.push_back(m_vMax);
vCorners.push_back(Vector3F(m_vMax.x, m_vMin.y, m_vMax.z));
vCorners.push_back(Vector3F(m_vMin.x, m_vMin.y, m_vMax.z));
vCorners.push_back(Vector3F(m_vMin.x, m_vMax.y, m_vMax.z));
}
void AxisAlignedBoundingBox::Intersect(const AxisAlignedBoundingBox& aabb)
{
Vector3F vMin = m_vMin, vMax = m_vMax;
SetMin(vMin, aabb.m_vMin, m_vMin);
SetMax(vMax, aabb.m_vMax, m_vMax);
}
bool AxisAlignedBoundingBox::CollideLine(const Vector3F& vStart, const Vector3F& vEnd, float& ftx, float& fty, float& ftz) const
{
float st, et;
float fst = 0, fet = 1;
const float* bmin = &m_vMin.x;
const float* bmax = &m_vMax.x;
const float* si = &vStart.x;
const float* ei = &vEnd.x;
static float t[3];
for(int i = 0; i < 3; ++i)
{
float di = ei[i] - si[i];
if(si[i] < ei[i])
{
if(si[i] > bmax[i] || ei[i] < bmin[i])
{
return false;
}
st = (si[i] < bmin[i])? (bmin[i] - si[i]) / di: 0; // >0
et = (ei[i] > bmax[i])? (bmax[i] - si[i]) / di: 1; // >0
}
else
{
if(ei[i] > bmax[i] || si[i] < bmin[i])
{
return false;
}
st = (si[i] > bmax[i])? (bmax[i] - si[i]) / di: 0; // >0
et = (ei[i] < bmin[i])? (bmin[i] - si[i]) / di: 1; // >0
}
t[i] = st;
if(fst < st)
{
fst = st;
}
if(fet > et)
{
fet = et;
}
if(fet < fst)
{
return false;
}
}
ftx = t[0];
fty = t[1];
ftz = t[2];
return true;
}
bool AxisAlignedBoundingBox::CollideLine(const Vector3F& vStart, const Vector3F& vEnd) const
{
float tx, ty, tz;
return CollideLine(vStart, vEnd, tx, ty, tz);
}
} // namespace | 22.848101 | 140 | 0.613019 | [
"vector"
] |
e7c2ead3c609aca8e4f9529fa036ba41dd0bc369 | 625 | cpp | C++ | src/lib/myLaws/AlignmentLaw.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | src/lib/myLaws/AlignmentLaw.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | src/lib/myLaws/AlignmentLaw.cpp | dudu3107/cpp-life-of-boids | 89b1edcd35aa7c957e61d7131a06025f6cdbc71f | [
"Apache-2.0"
] | null | null | null | #include "AlignmentLaw.hpp"
#include "../myMath/Vec2.hpp"
#include "../myMath/utils.hpp"
#include <vector>
#include "../../resources/model/Agent.hpp"
AlignmentLaw::AlignmentLaw(const float& relaxation) : Law(relaxation){};
AlignmentLaw::AlignmentLaw() : Law(1.f){};
Vec2 AlignmentLaw::compute(Agent&, const std::vector<Agent*>& neighbors) const {
Vec2 nextVelocity(0, 0);
if (neighbors.size() > 0) {
for (int i = 0; i < (int)neighbors.size(); ++i) {
nextVelocity = nextVelocity + (*neighbors[i]).getVelocity();
}
nextVelocity = nextVelocity / (float)neighbors.size();
}
return nextVelocity * m_relaxation;
}; | 29.761905 | 80 | 0.6864 | [
"vector",
"model"
] |
b1107aeb9a7b369ebe28e39ba3f7094013264b79 | 6,731 | cpp | C++ | Sources/Core/Engine/Swapchain.cpp | vgabi94/Lava-Engine | ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19 | [
"MIT"
] | null | null | null | Sources/Core/Engine/Swapchain.cpp | vgabi94/Lava-Engine | ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19 | [
"MIT"
] | null | null | null | Sources/Core/Engine/Swapchain.cpp | vgabi94/Lava-Engine | ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19 | [
"MIT"
] | null | null | null | #include "Swapchain.h"
#include "Engine.h"
#include "Device.h"
#include <Manager\TextureManager.h>
#include <Manager\RenderpassManager.h>
#include <Manager\WorldManager.h>
namespace Vulkan
{
Swapchain g_Swapchain;
vk::SurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats)
{
if (availableFormats.size() == 1 && availableFormats[0].format == vk::Format::eUndefined)
{
return { vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear };
}
for (const auto& f : availableFormats)
{
if (f.format == vk::Format::eB8G8R8A8Unorm &&
f.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear)
{
return f;
}
}
return availableFormats[0];
}
vk::PresentModeKHR ChooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes)
{
for (const auto& p : availablePresentModes)
{
if (p == vk::PresentModeKHR::eMailbox
|| p == vk::PresentModeKHR::eImmediate)
{
return p;
}
}
return vk::PresentModeKHR::eFifo;
}
vk::Extent2D ChooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilites)
{
if (capabilites.currentExtent.width != std::numeric_limits<uint32_t>::max())
{
return capabilites.currentExtent;
}
else
{
vk::Extent2D actualExent{ WINDOW_WIDTH, WINDOW_HEIGHT };
actualExent.width = std::max(capabilites.minImageExtent.width,
std::min(capabilites.maxImageExtent.width, actualExent.width));
actualExent.height = std::max(capabilites.minImageExtent.height,
std::min(capabilites.maxImageExtent.height, actualExent.height));
return actualExent;
}
}
// --------------------- SWAPCHAIN ------------------------ //
void Swapchain::Init()
{
_Init();
GRenderpassManager.InitPasses();
mFramePass = GRenderpassManager.GetPass<Engine::FramePass>(RP::FRAME);
LOG_INFO("[LOG] Swapchain init\n");
}
void Swapchain::Destroy()
{
DestroyImageViews();
g_vkDevice.destroySwapchainKHR(mSwapchain);
g_vkDevice.destroySemaphore(mImageAvailableSem);
g_vkDevice.destroySemaphore(mRenderFinishedSem);
LOG_INFO("[LOG] Swapchain destroy\n");
}
void Swapchain::Update()
{
THROW_IF(g_CurrentWorld == nullptr, "Current world cannot be null!");
//#ifdef _DEBUG
// // Must wait for queue when validation layers are enabled
// // otherwise the memory will grow very rapidly
// PRESENTATION_QUEUE.waitIdle();
//#endif
auto res = g_vkDevice.acquireNextImageKHR(
mSwapchain,
std::numeric_limits<uint64_t>::max(),
mImageAvailableSem, nullptr);
mCurrentImageIndex = res.value;
if (res.result == vk::Result::eErrorOutOfDateKHR)
{
RecreateSwapchain();
return;
}
GDevice.WaitForFence(GRenderpassManager.GetFenceAt(mCurrentImageIndex));
GDevice.ResetFence(GRenderpassManager.GetFenceAt(mCurrentImageIndex));
GRenderpassManager.SetupPasses();
GRenderpassManager.RenderPasses(mImageAvailableSem, vk::PipelineStageFlagBits::eColorAttachmentOutput, mRenderFinishedSem);
mPreviousImageIndex = mCurrentImageIndex;
vk::PresentInfoKHR presentInfo(1, &mRenderFinishedSem, 1, &mSwapchain, &mCurrentImageIndex);
try
{
PRESENTATION_QUEUE.presentKHR(presentInfo);
}
catch (const vk::SystemError&)
{
RecreateSwapchain();
}
}
void Swapchain::_Init()
{
mImageAvailableSem = g_Device.CreateSemaphore();
mRenderFinishedSem = g_Device.CreateSemaphore();
CreateSwapchain();
CreateImageViews();
mPreviousImageIndex = -1;
mCurrentImageIndex = 0;
}
void Swapchain::CreateSwapchain()
{
SwapChainSupportDetails scsd = g_Device.QuerySwapChainSupport(g_vkPhysicalDevice, g_vkSurface);
vk::SurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(scsd.formats);
vk::PresentModeKHR presentMode = ChooseSwapPresentMode(scsd.presentModes);
vk::Extent2D extent = ChooseSwapExtent(scsd.capabilities);
uint32_t imageCount = scsd.capabilities.minImageCount;
if (scsd.capabilities.maxImageCount > 0 && imageCount > scsd.capabilities.maxImageCount)
{
imageCount = scsd.capabilities.maxImageCount;
}
vk::SharingMode sharingMode;
uint32_t queueFamilyCount;
uint32_t* queuePtr;
uint32_t queueFamilyIndices[] = {
GRAPHICS_FAMILY_INDEX,
PRESENTATION_FAMILY_INDEX
};
if (GRAPHICS_FAMILY_INDEX != PRESENTATION_FAMILY_INDEX)
{
sharingMode = vk::SharingMode::eConcurrent;
queueFamilyCount = 2;
queuePtr = queueFamilyIndices;
}
else
{
sharingMode = vk::SharingMode::eExclusive;
queueFamilyCount = 0;
queuePtr = nullptr;
}
vk::SwapchainCreateInfoKHR createInfo({},
g_vkSurface, imageCount, surfaceFormat.format,
surfaceFormat.colorSpace, extent, 1,
vk::ImageUsageFlagBits::eColorAttachment, sharingMode,
queueFamilyCount, queuePtr, scsd.capabilities.currentTransform,
vk::CompositeAlphaFlagBitsKHR::eOpaque, presentMode, VK_TRUE,
nullptr);
mSwapchain = g_vkDevice.createSwapchainKHR(createInfo);
mExtent = extent;
mImageFormat = surfaceFormat.format;
mImage = g_vkDevice.getSwapchainImagesKHR(mSwapchain);
}
void Swapchain::CreateImageViews()
{
mImageView.resize(mImage.size());
for (unsigned int i = 0; i < mImageView.size(); i++)
{
mImageView[i] = GTextureManager.CreateImageView2D(mImage[i], 1, mImageFormat);
}
}
void Swapchain::RecreateSwapchain()
{
assert(g_CurrentWorld != nullptr);
g_vkDevice.waitIdle();
Destroy();
g_CurrentWorld->FreeWorldCommandBuffers();
_Init();
mFramePass->Recreate();
g_CurrentWorld->CreateWorldCommandBuffers();
g_CurrentWorld->mDirty = WORLD_DIRTY;
LOG_INFO("[LOG] Swapchain recreate\n");
}
void Swapchain::DestroyImageViews()
{
for (unsigned int i = 0; i < mImageView.size(); i++)
{
g_vkDevice.destroyImageView(mImageView[i]);
}
}
}
| 31.900474 | 125 | 0.619967 | [
"vector"
] |
b110f6213877fa7171f4f921b7aa0647b16cee91 | 37,023 | cpp | C++ | src/vulkan/vulkan-resource-bindings.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 325 | 2021-07-19T13:55:23.000Z | 2022-03-31T20:38:58.000Z | src/vulkan/vulkan-resource-bindings.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 11 | 2021-07-20T00:15:59.000Z | 2022-03-12T08:50:33.000Z | src/vulkan/vulkan-resource-bindings.cpp | Zwingling/nvrhi | 12f3e12eb29b681e99a53af7347c60c0733a6ef9 | [
"MIT"
] | 38 | 2021-07-19T15:04:17.000Z | 2022-03-28T09:09:09.000Z | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "vulkan-backend.h"
#include <nvrhi/common/misc.h>
namespace nvrhi::vulkan
{
BindingLayoutHandle Device::createBindingLayout(const BindingLayoutDesc& desc)
{
BindingLayout* ret = new BindingLayout(m_Context, desc);
ret->bake();
return BindingLayoutHandle::Create(ret);
}
BindingLayoutHandle Device::createBindlessLayout(const BindlessLayoutDesc& desc)
{
BindingLayout* ret = new BindingLayout(m_Context, desc);
ret->bake();
return BindingLayoutHandle::Create(ret);
}
BindingLayout::BindingLayout(const VulkanContext& context, const BindingLayoutDesc& _desc)
: desc(_desc)
, isBindless(false)
, m_Context(context)
{
vk::ShaderStageFlagBits shaderStageFlags = convertShaderTypeToShaderStageFlagBits(desc.visibility);
// iterate over all binding types and add to map
for (const BindingLayoutItem& binding : desc.bindings)
{
vk::DescriptorType descriptorType;
uint32_t descriptorCount = 1;
uint32_t registerOffset;
switch (binding.type)
{
case ResourceType::Texture_SRV:
registerOffset = _desc.bindingOffsets.shaderResource;
descriptorType = vk::DescriptorType::eSampledImage;
break;
case ResourceType::Texture_UAV:
registerOffset = _desc.bindingOffsets.unorderedAccess;
descriptorType = vk::DescriptorType::eStorageImage;
break;
case ResourceType::TypedBuffer_SRV:
registerOffset = _desc.bindingOffsets.shaderResource;
descriptorType = vk::DescriptorType::eUniformTexelBuffer;
break;
case ResourceType::StructuredBuffer_SRV:
case ResourceType::RawBuffer_SRV:
registerOffset = _desc.bindingOffsets.shaderResource;
descriptorType = vk::DescriptorType::eStorageBuffer;
break;
case ResourceType::TypedBuffer_UAV:
registerOffset = _desc.bindingOffsets.unorderedAccess;
descriptorType = vk::DescriptorType::eStorageTexelBuffer;
break;
case ResourceType::StructuredBuffer_UAV:
case ResourceType::RawBuffer_UAV:
registerOffset = _desc.bindingOffsets.unorderedAccess;
descriptorType = vk::DescriptorType::eStorageBuffer;
break;
case ResourceType::ConstantBuffer:
registerOffset = _desc.bindingOffsets.constantBuffer;
descriptorType = vk::DescriptorType::eUniformBuffer;
break;
case ResourceType::VolatileConstantBuffer:
registerOffset = _desc.bindingOffsets.constantBuffer;
descriptorType = vk::DescriptorType::eUniformBufferDynamic;
break;
case ResourceType::Sampler:
registerOffset = _desc.bindingOffsets.sampler;
descriptorType = vk::DescriptorType::eSampler;
break;
case ResourceType::PushConstants:
// don't need any descriptors for the push constants, but the vulkanLayoutBindings array
// must match the binding layout items for further processing within nvrhi --
// so set descriptorCount to 0 instead of skipping it
registerOffset = _desc.bindingOffsets.constantBuffer;
descriptorType = vk::DescriptorType::eUniformBuffer;
descriptorCount = 0;
break;
case ResourceType::RayTracingAccelStruct:
registerOffset = _desc.bindingOffsets.shaderResource;
descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
break;
case ResourceType::None:
case ResourceType::Count:
default:
utils::InvalidEnum();
continue;
}
const auto bindingLocation = registerOffset + binding.slot;
vk::DescriptorSetLayoutBinding descriptorSetLayoutBinding = vk::DescriptorSetLayoutBinding()
.setBinding(bindingLocation)
.setDescriptorCount(descriptorCount)
.setDescriptorType(descriptorType)
.setStageFlags(shaderStageFlags);
vulkanLayoutBindings.push_back(descriptorSetLayoutBinding);
}
}
BindingLayout::BindingLayout(const VulkanContext& context, const BindlessLayoutDesc& _desc)
: bindlessDesc(_desc)
, isBindless(true)
, m_Context(context)
{
desc.visibility = bindlessDesc.visibility;
vk::ShaderStageFlagBits shaderStageFlags = convertShaderTypeToShaderStageFlagBits(bindlessDesc.visibility);
uint32_t bindingPoint = 0;
uint32_t arraySize = bindlessDesc.maxCapacity;
// iterate over all binding types and add to map
for (const BindingLayoutItem& space : bindlessDesc.registerSpaces)
{
vk::DescriptorType descriptorType;
switch (space.type)
{
case ResourceType::Texture_SRV:
descriptorType = vk::DescriptorType::eSampledImage;
break;
case ResourceType::Texture_UAV:
descriptorType = vk::DescriptorType::eStorageImage;
break;
case ResourceType::TypedBuffer_SRV:
descriptorType = vk::DescriptorType::eUniformTexelBuffer;
break;
case ResourceType::TypedBuffer_UAV:
descriptorType = vk::DescriptorType::eStorageTexelBuffer;
break;
case ResourceType::StructuredBuffer_SRV:
case ResourceType::StructuredBuffer_UAV:
case ResourceType::RawBuffer_SRV:
case ResourceType::RawBuffer_UAV:
descriptorType = vk::DescriptorType::eStorageBuffer;
break;
case ResourceType::ConstantBuffer:
descriptorType = vk::DescriptorType::eUniformBuffer;
break;
case ResourceType::VolatileConstantBuffer:
m_Context.error("Volatile constant buffers are not supported in bindless layouts");
descriptorType = vk::DescriptorType::eUniformBufferDynamic;
break;
case ResourceType::Sampler:
descriptorType = vk::DescriptorType::eSampler;
break;
case ResourceType::PushConstants:
continue;
case ResourceType::RayTracingAccelStruct:
descriptorType = vk::DescriptorType::eAccelerationStructureKHR;
break;
case ResourceType::None:
case ResourceType::Count:
default:
utils::InvalidEnum();
continue;
}
vk::DescriptorSetLayoutBinding descriptorSetLayoutBinding = vk::DescriptorSetLayoutBinding()
.setBinding(bindingPoint)
.setDescriptorCount(arraySize)
.setDescriptorType(descriptorType)
.setStageFlags(shaderStageFlags);
vulkanLayoutBindings.push_back(descriptorSetLayoutBinding);
++bindingPoint;
}
}
Object BindingLayout::getNativeObject(ObjectType objectType)
{
switch (objectType)
{
case ObjectTypes::VK_DescriptorSetLayout:
return Object(descriptorSetLayout);
default:
return nullptr;
}
}
vk::Result BindingLayout::bake()
{
// create the descriptor set layout object
auto descriptorSetLayoutInfo = vk::DescriptorSetLayoutCreateInfo()
.setBindingCount(uint32_t(vulkanLayoutBindings.size()))
.setPBindings(vulkanLayoutBindings.data());
std::vector<vk::DescriptorBindingFlags> bindFlag(vulkanLayoutBindings.size(), vk::DescriptorBindingFlagBits::ePartiallyBound);
auto extendedInfo = vk::DescriptorSetLayoutBindingFlagsCreateInfo()
.setBindingCount(uint32_t(vulkanLayoutBindings.size()))
.setPBindingFlags(bindFlag.data());
if (isBindless)
{
descriptorSetLayoutInfo.setPNext(&extendedInfo);
}
const vk::Result res = m_Context.device.createDescriptorSetLayout(&descriptorSetLayoutInfo,
m_Context.allocationCallbacks,
&descriptorSetLayout);
CHECK_VK_RETURN(res)
// count the number of descriptors required per type
std::unordered_map<vk::DescriptorType, uint32_t> poolSizeMap;
for (auto layoutBinding : vulkanLayoutBindings)
{
if (poolSizeMap.find(layoutBinding.descriptorType) == poolSizeMap.end())
{
poolSizeMap[layoutBinding.descriptorType] = 0;
}
poolSizeMap[layoutBinding.descriptorType] += layoutBinding.descriptorCount;
}
// compute descriptor pool size info
for (auto poolSizeIter : poolSizeMap)
{
if (poolSizeIter.second > 0)
{
descriptorPoolSizeInfo.push_back(vk::DescriptorPoolSize()
.setType(poolSizeIter.first)
.setDescriptorCount(poolSizeIter.second));
}
}
return vk::Result::eSuccess;
}
BindingLayout::~BindingLayout()
{
if (descriptorSetLayout)
{
m_Context.device.destroyDescriptorSetLayout(descriptorSetLayout, m_Context.allocationCallbacks);
descriptorSetLayout = vk::DescriptorSetLayout();
}
}
static Texture::TextureSubresourceViewType getTextureViewType(Format bindingFormat, Format textureFormat)
{
Format format = (bindingFormat == Format::UNKNOWN) ? textureFormat : bindingFormat;
const FormatInfo& formatInfo = getFormatInfo(format);
if (formatInfo.hasDepth)
return Texture::TextureSubresourceViewType::DepthOnly;
else if (formatInfo.hasStencil)
return Texture::TextureSubresourceViewType::StencilOnly;
else
return Texture::TextureSubresourceViewType::AllAspects;
}
BindingSetHandle Device::createBindingSet(const BindingSetDesc& desc, IBindingLayout* _layout)
{
BindingLayout* layout = checked_cast<BindingLayout*>(_layout);
BindingSet *ret = new BindingSet(m_Context);
ret->desc = desc;
ret->layout = layout;
const auto& descriptorSetLayout = layout->descriptorSetLayout;
const auto& poolSizes = layout->descriptorPoolSizeInfo;
// create descriptor pool to allocate a descriptor from
auto poolInfo = vk::DescriptorPoolCreateInfo()
.setPoolSizeCount(uint32_t(poolSizes.size()))
.setPPoolSizes(poolSizes.data())
.setMaxSets(1);
vk::Result res = m_Context.device.createDescriptorPool(&poolInfo,
m_Context.allocationCallbacks,
&ret->descriptorPool);
CHECK_VK_FAIL(res)
// create the descriptor set
auto descriptorSetAllocInfo = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(ret->descriptorPool)
.setDescriptorSetCount(1)
.setPSetLayouts(&descriptorSetLayout);
res = m_Context.device.allocateDescriptorSets(&descriptorSetAllocInfo,
&ret->descriptorSet);
CHECK_VK_FAIL(res)
// collect all of the descriptor write data
static_vector<vk::DescriptorImageInfo, c_MaxBindingsPerLayout> descriptorImageInfo;
static_vector<vk::DescriptorBufferInfo, c_MaxBindingsPerLayout> descriptorBufferInfo;
static_vector<vk::WriteDescriptorSet, c_MaxBindingsPerLayout> descriptorWriteInfo;
static_vector<vk::WriteDescriptorSetAccelerationStructureKHR, c_MaxBindingsPerLayout> accelStructWriteInfo;
auto generateWriteDescriptorData =
// generates a vk::WriteDescriptorSet struct in descriptorWriteInfo
[&](uint32_t bindingLocation,
vk::DescriptorType descriptorType,
vk::DescriptorImageInfo *imageInfo,
vk::DescriptorBufferInfo *bufferInfo,
vk::BufferView *bufferView,
const void* pNext = nullptr)
{
descriptorWriteInfo.push_back(
vk::WriteDescriptorSet()
.setDstSet(ret->descriptorSet)
.setDstBinding(bindingLocation)
.setDstArrayElement(0)
.setDescriptorCount(1)
.setDescriptorType(descriptorType)
.setPImageInfo(imageInfo)
.setPBufferInfo(bufferInfo)
.setPTexelBufferView(bufferView)
.setPNext(pNext)
);
};
for (size_t bindingIndex = 0; bindingIndex < desc.bindings.size(); bindingIndex++)
{
const BindingSetItem& binding = desc.bindings[bindingIndex];
const vk::DescriptorSetLayoutBinding& layoutBinding = layout->vulkanLayoutBindings[bindingIndex];
if (binding.resourceHandle == nullptr)
{
continue;
}
ret->resources.push_back(binding.resourceHandle); // keep a strong reference to the resource
switch (binding.type)
{
case ResourceType::Texture_SRV:
{
const auto texture = checked_cast<Texture *>(binding.resourceHandle);
const auto subresource = binding.subresources.resolve(texture->desc, false);
const auto textureViewType = getTextureViewType(binding.format, texture->desc.format);
auto& view = texture->getSubresourceView(subresource, binding.dimension, textureViewType);
auto& imageInfo = descriptorImageInfo.emplace_back();
imageInfo = vk::DescriptorImageInfo()
.setImageView(view.view)
.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
&imageInfo, nullptr, nullptr);
if (!texture->permanentState)
ret->bindingsThatNeedTransitions.push_back(static_cast<uint16_t>(bindingIndex));
else
verifyPermanentResourceState(texture->permanentState,
ResourceStates::ShaderResource,
true, texture->desc.debugName, m_Context.messageCallback);
}
break;
case ResourceType::Texture_UAV:
{
const auto texture = checked_cast<Texture *>(binding.resourceHandle);
const auto subresource = binding.subresources.resolve(texture->desc, true);
const auto textureViewType = getTextureViewType(binding.format, texture->desc.format);
auto& view = texture->getSubresourceView(subresource, binding.dimension, textureViewType);
auto& imageInfo = descriptorImageInfo.emplace_back();
imageInfo = vk::DescriptorImageInfo()
.setImageView(view.view)
.setImageLayout(vk::ImageLayout::eGeneral);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
&imageInfo, nullptr, nullptr);
if (!texture->permanentState)
ret->bindingsThatNeedTransitions.push_back(static_cast<uint16_t>(bindingIndex));
else
verifyPermanentResourceState(texture->permanentState,
ResourceStates::UnorderedAccess,
true, texture->desc.debugName, m_Context.messageCallback);
}
break;
case ResourceType::TypedBuffer_SRV:
case ResourceType::TypedBuffer_UAV:
{
const auto buffer = checked_cast<Buffer *>(binding.resourceHandle);
assert(buffer->desc.canHaveTypedViews);
const bool isUAV = (binding.type == ResourceType::TypedBuffer_UAV);
if (isUAV)
assert(buffer->desc.canHaveUAVs);
Format format = binding.format;
if (format == Format::UNKNOWN)
{
format = buffer->desc.format;
}
auto vkformat = nvrhi::vulkan::convertFormat(format);
const auto& bufferViewFound = buffer->viewCache.find(vkformat);
auto& bufferViewRef = (bufferViewFound != buffer->viewCache.end()) ? bufferViewFound->second : buffer->viewCache[vkformat];
if (bufferViewFound == buffer->viewCache.end())
{
assert(format != Format::UNKNOWN);
const auto range = binding.range.resolve(buffer->desc);
auto bufferViewInfo = vk::BufferViewCreateInfo()
.setBuffer(buffer->buffer)
.setOffset(range.byteOffset)
.setRange(range.byteSize)
.setFormat(vkformat);
res = m_Context.device.createBufferView(&bufferViewInfo, m_Context.allocationCallbacks, &bufferViewRef);
ASSERT_VK_OK(res);
}
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
nullptr, nullptr, &bufferViewRef);
if (!buffer->permanentState)
ret->bindingsThatNeedTransitions.push_back(static_cast<uint16_t>(bindingIndex));
else
verifyPermanentResourceState(buffer->permanentState,
isUAV ? ResourceStates::UnorderedAccess : ResourceStates::ShaderResource,
false, buffer->desc.debugName, m_Context.messageCallback);
}
break;
case ResourceType::StructuredBuffer_SRV:
case ResourceType::StructuredBuffer_UAV:
case ResourceType::RawBuffer_SRV:
case ResourceType::RawBuffer_UAV:
case ResourceType::ConstantBuffer:
case ResourceType::VolatileConstantBuffer:
{
const auto buffer = checked_cast<Buffer *>(binding.resourceHandle);
if (binding.type == ResourceType::StructuredBuffer_UAV || binding.type == ResourceType::RawBuffer_UAV)
assert(buffer->desc.canHaveUAVs);
if (binding.type == ResourceType::StructuredBuffer_UAV || binding.type == ResourceType::StructuredBuffer_SRV)
assert(buffer->desc.structStride != 0);
if (binding.type == ResourceType::RawBuffer_SRV|| binding.type == ResourceType::RawBuffer_UAV)
assert(buffer->desc.canHaveRawViews);
const auto range = binding.range.resolve(buffer->desc);
auto& bufferInfo = descriptorBufferInfo.emplace_back();
bufferInfo = vk::DescriptorBufferInfo()
.setBuffer(buffer->buffer)
.setOffset(range.byteOffset)
.setRange(range.byteSize);
assert(buffer->buffer);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
nullptr, &bufferInfo, nullptr);
if (binding.type == ResourceType::VolatileConstantBuffer)
{
assert(buffer->desc.isVolatile);
ret->volatileConstantBuffers.push_back(buffer);
}
else
{
if (!buffer->permanentState)
ret->bindingsThatNeedTransitions.push_back(static_cast<uint16_t>(bindingIndex));
else
{
ResourceStates requiredState;
if (binding.type == ResourceType::StructuredBuffer_UAV || binding.type == ResourceType::RawBuffer_SRV)
requiredState = ResourceStates::UnorderedAccess;
else if (binding.type == ResourceType::ConstantBuffer)
requiredState = ResourceStates::ConstantBuffer;
else
requiredState = ResourceStates::ShaderResource;
verifyPermanentResourceState(buffer->permanentState, requiredState,
false, buffer->desc.debugName, m_Context.messageCallback);
}
}
}
break;
case ResourceType::Sampler:
{
const auto sampler = checked_cast<Sampler *>(binding.resourceHandle);
auto& imageInfo = descriptorImageInfo.emplace_back();
imageInfo = vk::DescriptorImageInfo()
.setSampler(sampler->sampler);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
&imageInfo, nullptr, nullptr);
}
break;
case ResourceType::RayTracingAccelStruct:
{
const auto as = checked_cast<AccelStruct*>(binding.resourceHandle);
auto& accelStructWrite = accelStructWriteInfo.emplace_back();
accelStructWrite.accelerationStructureCount = 1;
accelStructWrite.pAccelerationStructures = &as->accelStruct;
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
nullptr, nullptr, nullptr, &accelStructWrite);
ret->bindingsThatNeedTransitions.push_back(static_cast<uint16_t>(bindingIndex));
}
break;
case ResourceType::PushConstants:
break;
case ResourceType::None:
case ResourceType::Count:
default:
utils::InvalidEnum();
break;
}
}
m_Context.device.updateDescriptorSets(uint32_t(descriptorWriteInfo.size()), descriptorWriteInfo.data(), 0, nullptr);
return BindingSetHandle::Create(ret);
}
BindingSet::~BindingSet()
{
if (descriptorPool)
{
m_Context.device.destroyDescriptorPool(descriptorPool, m_Context.allocationCallbacks);
descriptorPool = vk::DescriptorPool();
descriptorSet = vk::DescriptorSet();
}
}
Object BindingSet::getNativeObject(ObjectType objectType)
{
switch (objectType)
{
case ObjectTypes::VK_DescriptorPool:
return Object(descriptorPool);
case ObjectTypes::VK_DescriptorSet:
return Object(descriptorSet);
default:
return nullptr;
}
}
DescriptorTableHandle Device::createDescriptorTable(IBindingLayout* _layout)
{
BindingLayout* layout = checked_cast<BindingLayout*>(_layout);
DescriptorTable* ret = new DescriptorTable(m_Context);
ret->layout = layout;
ret->capacity = layout->vulkanLayoutBindings[0].descriptorCount;
const auto& descriptorSetLayout = layout->descriptorSetLayout;
const auto& poolSizes = layout->descriptorPoolSizeInfo;
// create descriptor pool to allocate a descriptor from
auto poolInfo = vk::DescriptorPoolCreateInfo()
.setPoolSizeCount(uint32_t(poolSizes.size()))
.setPPoolSizes(poolSizes.data())
.setMaxSets(1);
vk::Result res = m_Context.device.createDescriptorPool(&poolInfo,
m_Context.allocationCallbacks,
&ret->descriptorPool);
CHECK_VK_FAIL(res)
// create the descriptor set
auto descriptorSetAllocInfo = vk::DescriptorSetAllocateInfo()
.setDescriptorPool(ret->descriptorPool)
.setDescriptorSetCount(1)
.setPSetLayouts(&descriptorSetLayout);
res = m_Context.device.allocateDescriptorSets(&descriptorSetAllocInfo,
&ret->descriptorSet);
CHECK_VK_FAIL(res)
return DescriptorTableHandle::Create(ret);
}
DescriptorTable::~DescriptorTable()
{
if (descriptorPool)
{
m_Context.device.destroyDescriptorPool(descriptorPool, m_Context.allocationCallbacks);
descriptorPool = vk::DescriptorPool();
descriptorSet = vk::DescriptorSet();
}
}
Object DescriptorTable::getNativeObject(ObjectType objectType)
{
switch (objectType)
{
case ObjectTypes::VK_DescriptorPool:
return Object(descriptorPool);
case ObjectTypes::VK_DescriptorSet:
return Object(descriptorSet);
default:
return nullptr;
}
}
void Device::resizeDescriptorTable(IDescriptorTable* _descriptorTable, uint32_t newSize, bool keepContents)
{
assert(newSize <= checked_cast<DescriptorTable*>(_descriptorTable)->layout->getBindlessDesc()->maxCapacity);
(void)_descriptorTable;
(void)newSize;
(void)keepContents;
}
bool Device::writeDescriptorTable(IDescriptorTable* _descriptorTable, const BindingSetItem& binding)
{
DescriptorTable* descriptorTable = checked_cast<DescriptorTable*>(_descriptorTable);
BindingLayout* layout = checked_cast<BindingLayout*>(descriptorTable->layout.Get());
if (binding.slot >= descriptorTable->capacity)
return false;
vk::Result res;
// collect all of the descriptor write data
static_vector<vk::DescriptorImageInfo, c_MaxBindingsPerLayout> descriptorImageInfo;
static_vector<vk::DescriptorBufferInfo, c_MaxBindingsPerLayout> descriptorBufferInfo;
static_vector<vk::WriteDescriptorSet, c_MaxBindingsPerLayout> descriptorWriteInfo;
auto generateWriteDescriptorData =
// generates a vk::WriteDescriptorSet struct in descriptorWriteInfo
[&](uint32_t bindingLocation,
vk::DescriptorType descriptorType,
vk::DescriptorImageInfo* imageInfo,
vk::DescriptorBufferInfo* bufferInfo,
vk::BufferView* bufferView)
{
descriptorWriteInfo.push_back(
vk::WriteDescriptorSet()
.setDstSet(descriptorTable->descriptorSet)
.setDstBinding(bindingLocation)
.setDstArrayElement(binding.slot)
.setDescriptorCount(1)
.setDescriptorType(descriptorType)
.setPImageInfo(imageInfo)
.setPBufferInfo(bufferInfo)
.setPTexelBufferView(bufferView)
);
};
for (uint32_t bindingLocation = 0; bindingLocation < uint32_t(layout->bindlessDesc.registerSpaces.size()); bindingLocation++)
{
if (layout->bindlessDesc.registerSpaces[bindingLocation].type == binding.type)
{
const vk::DescriptorSetLayoutBinding& layoutBinding = layout->vulkanLayoutBindings[bindingLocation];
switch (binding.type)
{
case ResourceType::Texture_SRV:
{
const auto& texture = checked_cast<Texture*>(binding.resourceHandle);
const auto subresource = binding.subresources.resolve(texture->desc, false);
const auto textureViewType = getTextureViewType(binding.format, texture->desc.format);
auto& view = texture->getSubresourceView(subresource, binding.dimension, textureViewType);
auto& imageInfo = descriptorImageInfo.emplace_back();
imageInfo = vk::DescriptorImageInfo()
.setImageView(view.view)
.setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
&imageInfo, nullptr, nullptr);
}
break;
case ResourceType::Texture_UAV:
{
const auto texture = checked_cast<Texture*>(binding.resourceHandle);
const auto subresource = binding.subresources.resolve(texture->desc, true);
const auto textureViewType = getTextureViewType(binding.format, texture->desc.format);
auto& view = texture->getSubresourceView(subresource, binding.dimension, textureViewType);
auto& imageInfo = descriptorImageInfo.emplace_back();
imageInfo = vk::DescriptorImageInfo()
.setImageView(view.view)
.setImageLayout(vk::ImageLayout::eGeneral);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
&imageInfo, nullptr, nullptr);
}
break;
case ResourceType::TypedBuffer_SRV:
case ResourceType::TypedBuffer_UAV:
{
const auto& buffer = checked_cast<Buffer*>(binding.resourceHandle);
auto vkformat = nvrhi::vulkan::convertFormat(binding.format);
const auto& bufferViewFound = buffer->viewCache.find(vkformat);
auto& bufferViewRef = (bufferViewFound != buffer->viewCache.end()) ? bufferViewFound->second : buffer->viewCache[vkformat];
if (bufferViewFound == buffer->viewCache.end())
{
assert(binding.format != Format::UNKNOWN);
const auto range = binding.range.resolve(buffer->desc);
auto bufferViewInfo = vk::BufferViewCreateInfo()
.setBuffer(buffer->buffer)
.setOffset(range.byteOffset)
.setRange(range.byteSize)
.setFormat(vkformat);
res = m_Context.device.createBufferView(&bufferViewInfo, m_Context.allocationCallbacks, &bufferViewRef);
ASSERT_VK_OK(res);
}
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
nullptr, nullptr, &bufferViewRef);
}
break;
case ResourceType::StructuredBuffer_SRV:
case ResourceType::StructuredBuffer_UAV:
case ResourceType::RawBuffer_SRV:
case ResourceType::RawBuffer_UAV:
case ResourceType::ConstantBuffer:
case ResourceType::VolatileConstantBuffer:
{
const auto buffer = checked_cast<Buffer*>(binding.resourceHandle);
const auto range = binding.range.resolve(buffer->desc);
auto& bufferInfo = descriptorBufferInfo.emplace_back();
bufferInfo = vk::DescriptorBufferInfo()
.setBuffer(buffer->buffer)
.setOffset(range.byteOffset)
.setRange(range.byteSize);
assert(buffer->buffer);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
nullptr, &bufferInfo, nullptr);
}
break;
case ResourceType::Sampler:
{
const auto& sampler = checked_cast<Sampler*>(binding.resourceHandle);
auto& imageInfo = descriptorImageInfo.emplace_back();
imageInfo = vk::DescriptorImageInfo()
.setSampler(sampler->sampler);
generateWriteDescriptorData(layoutBinding.binding,
layoutBinding.descriptorType,
&imageInfo, nullptr, nullptr);
}
break;
case ResourceType::RayTracingAccelStruct:
utils::NotImplemented();
break;
case ResourceType::PushConstants:
utils::NotSupported();
break;
case ResourceType::None:
case ResourceType::Count:
default:
utils::InvalidEnum();
}
}
}
m_Context.device.updateDescriptorSets(uint32_t(descriptorWriteInfo.size()), descriptorWriteInfo.data(), 0, nullptr);
return true;
}
void CommandList::bindBindingSets(vk::PipelineBindPoint bindPoint, vk::PipelineLayout pipelineLayout, const BindingSetVector& bindings)
{
BindingVector<vk::DescriptorSet> descriptorSets;
static_vector<uint32_t, c_MaxVolatileConstantBuffers> dynamicOffsets;
for (const auto& bindingSetHandle : bindings)
{
const BindingSetDesc* desc = bindingSetHandle->getDesc();
if (desc)
{
BindingSet* bindingSet = checked_cast<BindingSet*>(bindingSetHandle);
descriptorSets.push_back(bindingSet->descriptorSet);
for (Buffer* constnatBuffer : bindingSet->volatileConstantBuffers)
{
auto found = m_VolatileBufferStates.find(constnatBuffer);
if (found == m_VolatileBufferStates.end())
{
std::stringstream ss;
ss << "Binding volatile constant buffer " << utils::DebugNameToString(constnatBuffer->desc.debugName)
<< " before writing into it is invalid.";
m_Context.error(ss.str());
dynamicOffsets.push_back(0); // use zero offset just to use something
}
else
{
uint32_t version = found->second.latestVersion;
uint64_t offset = version * constnatBuffer->desc.byteSize;
assert(offset < std::numeric_limits<uint32_t>::max());
dynamicOffsets.push_back(uint32_t(offset));
}
}
if (desc->trackLiveness)
m_CurrentCmdBuf->referencedResources.push_back(bindingSetHandle);
}
else
{
DescriptorTable* table = checked_cast<DescriptorTable*>(bindingSetHandle);
descriptorSets.push_back(table->descriptorSet);
}
}
if (!descriptorSets.empty())
{
m_CurrentCmdBuf->cmdBuf.bindDescriptorSets(bindPoint, pipelineLayout,
/* firstSet = */ 0, uint32_t(descriptorSets.size()), descriptorSets.data(),
uint32_t(dynamicOffsets.size()), dynamicOffsets.data());
}
}
} // namespace nvrhi::vulkan
| 40.864238 | 143 | 0.590066 | [
"object",
"vector"
] |
b1201abaa4972fe129a46dea12f67b4fc67c7f55 | 4,800 | cc | C++ | test/1959-redefine-object-instrument/fake_redef_object.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 20 | 2021-06-24T16:38:42.000Z | 2022-01-20T16:15:57.000Z | test/1959-redefine-object-instrument/fake_redef_object.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | null | null | null | test/1959-redefine-object-instrument/fake_redef_object.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 4 | 2021-11-03T06:01:12.000Z | 2022-02-24T02:57:31.000Z | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <limits>
#include <memory>
#include "jni.h"
#include "jvmti.h"
// Test infrastructure
#include "jvmti_helper.h"
#include "test_env.h"
// Slicer's headers have code that triggers these warnings. b/65298177
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wsign-compare"
#pragma clang diagnostic ignored "-Wunused-parameter"
#include "slicer/instrumentation.h"
#include "slicer/reader.h"
#include "slicer/writer.h"
#pragma clang diagnostic pop
namespace art {
namespace Test1959RedefineObjectInstrument {
// Just pull it out of the dex file but don't bother changing anything.
static void JNICALL RedefineObjectHook(jvmtiEnv *jvmti_env,
JNIEnv* env,
jclass class_being_redefined ATTRIBUTE_UNUSED,
jobject loader ATTRIBUTE_UNUSED,
const char* name,
jobject protection_domain ATTRIBUTE_UNUSED,
jint class_data_len,
const unsigned char* class_data,
jint* new_class_data_len,
unsigned char** new_class_data) {
if (strcmp(name, "java/lang/Object") != 0) {
return;
}
dex::Reader reader(class_data, class_data_len);
dex::u4 class_index = reader.FindClassIndex("Ljava/lang/Object;");
if (class_index == dex::kNoIndex) {
env->ThrowNew(env->FindClass("java/lang/RuntimeException"),
"Failed to find object in dex file!");
return;
}
reader.CreateClassIr(class_index);
auto dex_ir = reader.GetIr();
dex::Writer writer(dex_ir);
class JvmtiAllocator : public dex::Writer::Allocator {
public:
explicit JvmtiAllocator(jvmtiEnv* jvmti) : jvmti_(jvmti) {}
void* Allocate(size_t size) override {
unsigned char* res = nullptr;
jvmti_->Allocate(size, &res);
return res;
}
void Free(void* ptr) override {
jvmti_->Deallocate(reinterpret_cast<unsigned char*>(ptr));
}
private:
jvmtiEnv* jvmti_;
};
JvmtiAllocator allocator(jvmti_env);
size_t new_size;
*new_class_data = writer.CreateImage(&allocator, &new_size);
if (new_size > std::numeric_limits<jint>::max()) {
*new_class_data = nullptr;
env->ThrowNew(env->FindClass("java/lang/RuntimeException"),
"transform result is too large!");
return;
}
*new_class_data_len = static_cast<jint>(new_size);
}
extern "C" JNIEXPORT void JNICALL Java_Main_forceRedefine(JNIEnv* env,
jclass klass ATTRIBUTE_UNUSED,
jclass obj_class,
jthread thr) {
if (IsJVM()) {
// RI so don't do anything.
return;
}
jvmtiCapabilities caps {.can_retransform_classes = 1};
if (JvmtiErrorToException(env, jvmti_env, jvmti_env->AddCapabilities(&caps))) {
return;
}
jvmtiEventCallbacks cb {.ClassFileLoadHook = RedefineObjectHook };
if (JvmtiErrorToException(env, jvmti_env, jvmti_env->SetEventCallbacks(&cb, sizeof(cb)))) {
return;
}
if (JvmtiErrorToException(env,
jvmti_env,
jvmti_env->SetEventNotificationMode(JVMTI_ENABLE,
JVMTI_EVENT_CLASS_FILE_LOAD_HOOK,
thr))) {
return;
}
if (JvmtiErrorToException(env,
jvmti_env,
jvmti_env->RetransformClasses(1, &obj_class))) {
return;
}
if (JvmtiErrorToException(env,
jvmti_env,
jvmti_env->SetEventNotificationMode(JVMTI_DISABLE,
JVMTI_EVENT_CLASS_FILE_LOAD_HOOK,
thr))) {
return;
}
}
} // namespace Test1959RedefineObjectInstrument
} // namespace art
| 35.555556 | 97 | 0.583958 | [
"object",
"transform"
] |
b124a834537ec0024578c9eb113b5278a889a13f | 2,540 | cpp | C++ | rootex/core/resource_files/collision_model_resource_file.cpp | ChronicallySerious/Rootex | bf2a0997b6aa5be84dbfc0e7826c31ff693ca0f1 | [
"MIT"
] | 166 | 2019-06-19T19:51:45.000Z | 2022-03-24T13:03:29.000Z | rootex/core/resource_files/collision_model_resource_file.cpp | rahil627/Rootex | 44f827d469bddc7167b34dedf80d7a8b984fdf20 | [
"MIT"
] | 312 | 2019-06-13T19:39:25.000Z | 2022-03-02T18:37:22.000Z | rootex/core/resource_files/collision_model_resource_file.cpp | rahil627/Rootex | 44f827d469bddc7167b34dedf80d7a8b984fdf20 | [
"MIT"
] | 23 | 2019-10-04T11:02:21.000Z | 2021-12-24T16:34:52.000Z | #include "collision_model_resource_file.h"
#include "assimp/Importer.hpp"
#include "assimp/postprocess.h"
#include "assimp/scene.h"
CollisionModelResourceFile::CollisionModelResourceFile(const FilePath& path)
: ResourceFile(Type::CollisionModel, path)
{
reimport();
}
void CollisionModelResourceFile::reimport()
{
ResourceFile::reimport();
Assimp::Importer modelLoader;
const aiScene* scene = modelLoader.ReadFile(
getPath().generic_string(),
aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph | aiProcess_RemoveComponent);
if (!scene)
{
ERR("Collision Model could not be loaded: " + getPath().generic_string());
ERR("Assimp: " + modelLoader.GetErrorString());
return;
}
btTriangleIndexVertexArray meshes;
m_Meshes.clear();
m_Vertices.clear();
m_Indices.clear();
// Stop the arrays from changing memory locations
unsigned int totalVertices = 0;
unsigned int totalIndices = 0;
for (int i = 0; i < scene->mNumMeshes; i++)
{
totalVertices += scene->mMeshes[i]->mNumVertices;
totalIndices += scene->mMeshes[i]->mNumFaces * 3;
}
m_Vertices.reserve(totalVertices);
m_Indices.reserve(totalIndices);
unsigned int indicesSeen = 0;
unsigned int verticesSeen = 0;
for (int i = 0; i < scene->mNumMeshes; i++)
{
const aiMesh* mesh = scene->mMeshes[i];
btIndexedMesh indexedMesh;
{
indexedMesh.m_numTriangles = mesh->mNumFaces;
indexedMesh.m_numVertices = mesh->mNumVertices;
aiFace* face = nullptr;
for (unsigned int f = 0; f < mesh->mNumFaces; f++)
{
face = &mesh->mFaces[f];
//Model already triangulated by aiProcess_Triangulate so no need to check
m_Indices.push_back(face->mIndices[0]);
m_Indices.push_back(face->mIndices[1]);
m_Indices.push_back(face->mIndices[2]);
}
indexedMesh.m_triangleIndexBase = (const unsigned char*)(m_Indices.data() + indicesSeen);
indexedMesh.m_triangleIndexStride = 3 * sizeof(short);
for (unsigned int v = 0; v < mesh->mNumVertices; v++)
{
Vector3 vertex;
vertex.x = mesh->mVertices[v].x;
vertex.y = mesh->mVertices[v].y;
vertex.z = mesh->mVertices[v].z;
m_Vertices.push_back(vertex);
}
indexedMesh.m_vertexBase = (const unsigned char*)(m_Vertices.data() + verticesSeen);
indexedMesh.m_vertexStride = 3 * sizeof(float);
}
indicesSeen += mesh->mNumFaces * 3;
verticesSeen += mesh->mNumVertices;
m_Meshes.push_back(indexedMesh);
meshes.addIndexedMesh(m_Meshes.back(), PHY_SHORT);
}
m_TriangleMesh = meshes;
}
| 29.882353 | 143 | 0.715748 | [
"mesh",
"model"
] |
b12982cd2cf3b54e31a1fddafc3e3df786b65d7d | 2,298 | cpp | C++ | src/ai/src_get/filter_personnes.cpp | guilhermessc/ESS | 02281ff2375c8b3d3e2ef62f755aeb1cae3f75cb | [
"Apache-2.0"
] | null | null | null | src/ai/src_get/filter_personnes.cpp | guilhermessc/ESS | 02281ff2375c8b3d3e2ef62f755aeb1cae3f75cb | [
"Apache-2.0"
] | 3 | 2017-11-19T19:14:23.000Z | 2017-12-11T09:18:38.000Z | src/ai/src_get/filter_personnes.cpp | guilhermessc/ESS | 02281ff2375c8b3d3e2ef62f755aeb1cae3f75cb | [
"Apache-2.0"
] | null | null | null | #include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/objdetect/objdetect.hpp"
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
string path = "/home/cfcv/Desktop/git/Face_Recognition/src_get/personnes/IMG_";
string fn_haar = string("/home/cfcv/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_alt.xml");
int count = 100;
int count_fixed = 0;
int choice;
cv::Mat frame;
cv::namedWindow("Readed", cv::WINDOW_NORMAL);
cv::namedWindow("Cutted", cv::WINDOW_NORMAL);
cv::CascadeClassifier face_cascade;
cv::vector<cv::Rect> faces;
cv::Mat face_area;
face_cascade.load(fn_haar);
while(true){
ostringstream convert;
convert << count;
frame = cv::imread(path+convert.str()+".jpg",CV_LOAD_IMAGE_COLOR);
if(frame.empty()){
break;
}
//cv::cvtColor(frame, gray, CV_BGR2GRAY);
face_cascade.detectMultiScale(frame, faces);
cout << "faces -> " << faces.size() << endl;
if(faces.size() == 1){
cout << faces[0] << endl;
face_area = frame(faces[0]);
ostringstream convert3;
convert3 << count_fixed;
cv::imwrite("/home/cfcv/Desktop/git/Face_Recognition/src_get/personnes/fixed/IMG_"+convert3.str()+".jpg", face_area);
count_fixed++;
}
else if(faces.size() > 1){
cv::Mat aux = frame.clone();
for(int i = 0; i < faces.size(); ++i){
ostringstream convert2;
convert2 << i;
string box_text = convert2.str();
int pos_x = std::max(faces[i].tl().x - 10, 0);
int pos_y = std::max(faces[i].tl().y - 10, 0);
cv::putText(aux, box_text, cv::Point(pos_x, pos_y), cv::FONT_HERSHEY_PLAIN, 1.0, cv::Scalar(0,255,0), 2.0);
cv::rectangle(aux, faces[i], cv::Scalar(0,255,0), 1);
}
cv::imshow("Readed", aux);
cout << "What is yout face?" << endl;
cin >> choice;
face_area = frame(faces[choice]);
cv::imshow("Cutted", face_area);
cv::waitKey(0);
ostringstream convert4;
convert4 << count_fixed;
cv::imwrite("/home/cfcv/Desktop/git/Face_Recognition/src_get/personnes/fixed/IMG_"+convert4.str()+".jpg", face_area);
count_fixed++;
}
//cv::imshow("Cutted", face_area);
//cv::imshow("Readed", frame);
//cv::waitKey(0);
count++;
}
return 0;
} | 30.236842 | 120 | 0.653612 | [
"vector"
] |
b12ebba8ce371b0f77051d443a00fe7a4405de35 | 2,988 | cc | C++ | compiler/emit/enum_literal.cc | perimosocordiae/Icarus | 183098eff886a0503562e5571e7009dd22719367 | [
"Apache-2.0"
] | 10 | 2015-10-28T18:54:41.000Z | 2021-12-29T16:48:31.000Z | compiler/emit/enum_literal.cc | perimosocordiae/Icarus | 183098eff886a0503562e5571e7009dd22719367 | [
"Apache-2.0"
] | 95 | 2020-02-27T22:34:02.000Z | 2022-03-06T19:45:24.000Z | compiler/emit/enum_literal.cc | perimosocordiae/Icarus | 183098eff886a0503562e5571e7009dd22719367 | [
"Apache-2.0"
] | 2 | 2019-02-01T23:16:04.000Z | 2020-02-27T16:06:02.000Z | #include "ast/ast.h"
#include "compiler/compiler.h"
#include "compiler/module.h"
namespace compiler {
void Compiler::EmitToBuffer(ast::EnumLiteral const *node,
ir::PartialResultBuffer &out) {
LOG("EnumLiteral", "Starting enum-literal emission: %p on %s", node,
context().DebugString());
type::Type t;
bool inserted;
switch (node->kind()) {
case ast::EnumLiteral::Kind::Enum: {
std::tie(t, inserted) =
context().EmplaceType<type::Enum>(node, resources().module);
} break;
case ast::EnumLiteral::Kind::Flags: {
std::tie(t, inserted) =
context().EmplaceType<type::Flags>(node, resources().module);
} break;
}
if (inserted) {
// Strictly speaking this conditional is not needed. Enqueuing the same work
// item twice will be deduplicated.
Enqueue({.kind = WorkItem::Kind::CompleteEnum,
.node = node,
.context = &context()},
{WorkItem{.kind = WorkItem::Kind::VerifyEnumBody,
.node = node,
.context = &context()}});
}
out.append(t);
}
bool Compiler::CompleteEnum(ast::EnumLiteral const *node) {
LOG("EnumLiteral", "Completing enum-literal emission: %p", node);
ir::CompiledFn fn(type::Func({}, {}));
type::Type t = context().LoadType(node);
ICARUS_SCOPE(ir::SetCurrent(fn, builder())) {
builder().CurrentBlock() = fn.entry();
std::vector<std::string_view> names(node->enumerators().begin(),
node->enumerators().end());
absl::flat_hash_map<uint64_t, ir::RegOr<type::Enum::underlying_type>>
specified_values;
uint64_t i = 0;
for (uint64_t i = 0; i < names.size(); ++i) {
if (auto iter = node->specified_values().find(names[i]);
iter != node->specified_values().end()) {
specified_values.emplace(i, EmitWithCastTo<type::Enum::underlying_type>(
t, iter->second.get()));
}
}
// TODO: Find a way around these const casts.
switch (node->kind()) {
case ast::EnumLiteral::Kind::Enum: {
current_block()->Append(type::EnumInstruction{
.type = &const_cast<type::Enum &>(t.as<type::Enum>()),
.names_ = std::move(names),
.specified_values_ = std::move(specified_values),
.result = builder().CurrentGroup()->Reserve()});
} break;
case ast::EnumLiteral::Kind::Flags: {
current_block()->Append(type::FlagsInstruction{
.type = &const_cast<type::Flags &>(t.as<type::Flags>()),
.names_ = std::move(names),
.specified_values_ = std::move(specified_values),
.result = builder().CurrentGroup()->Reserve()});
} break;
default: UNREACHABLE();
}
builder().ReturnJump();
}
InterpretAtCompileTime(fn);
return true;
}
} // namespace compiler
| 33.573034 | 80 | 0.568273 | [
"vector"
] |
b13007d9f3be36314650513bd31c56c6cbc630e8 | 1,978 | hpp | C++ | libraries/chain/include/steemit/chain/transaction_object.hpp | btscube/steem | a4e1a071e2915713c475df337d03a50d38bc394c | [
"Unlicense"
] | 38 | 2016-07-11T22:18:51.000Z | 2021-03-13T15:01:13.000Z | libraries/chain/include/steemit/chain/transaction_object.hpp | btscube/steem | a4e1a071e2915713c475df337d03a50d38bc394c | [
"Unlicense"
] | null | null | null | libraries/chain/include/steemit/chain/transaction_object.hpp | btscube/steem | a4e1a071e2915713c475df337d03a50d38bc394c | [
"Unlicense"
] | 8 | 2016-07-15T05:27:38.000Z | 2018-05-21T15:07:07.000Z | #pragma once
#include <fc/io/raw.hpp>
#include <steemit/chain/protocol/transaction.hpp>
#include <graphene/db/index.hpp>
#include <graphene/db/generic_index.hpp>
#include <fc/uint128.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
namespace steemit { namespace chain {
using namespace graphene::db;
using boost::multi_index_container;
using namespace boost::multi_index;
/**
* The purpose of this object is to enable the detection of duplicate transactions. When a transaction is included
* in a block a transaction_object is added. At the end of block processing all transaction_objects that have
* expired can be removed from the index.
*/
class transaction_object : public abstract_object<transaction_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_transaction_object_type;
signed_transaction trx;
transaction_id_type trx_id;
time_point_sec get_expiration()const { return trx.expiration; }
};
struct by_expiration;
struct by_id;
struct by_trx_id;
typedef multi_index_container<
transaction_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
hashed_unique< tag<by_trx_id>, BOOST_MULTI_INDEX_MEMBER(transaction_object, transaction_id_type, trx_id), std::hash<transaction_id_type> >,
ordered_non_unique< tag<by_expiration>, const_mem_fun<transaction_object, time_point_sec, &transaction_object::get_expiration > >
>
> transaction_multi_index_type;
typedef generic_index<transaction_object, transaction_multi_index_type> transaction_index;
} }
FC_REFLECT_DERIVED( steemit::chain::transaction_object, (graphene::db::object), (trx)(trx_id) )
| 38.038462 | 148 | 0.750253 | [
"object"
] |
b13635004a3200aae342b69b8aec7444df91cecd | 4,976 | cpp | C++ | piquassoboost/gaussian/source/tasks_apply_to_C_and_G/insert_transformed_rows.cpp | Budapest-Quantum-Computing-Group/piquassoboost | fd384be8f59cfd20d62654cf86c89f69d3cf8b8c | [
"Apache-2.0"
] | 4 | 2021-11-29T13:28:19.000Z | 2021-12-21T22:57:09.000Z | piquassoboost/gaussian/source/tasks_apply_to_C_and_G/insert_transformed_rows.cpp | Budapest-Quantum-Computing-Group/piquassoboost | fd384be8f59cfd20d62654cf86c89f69d3cf8b8c | [
"Apache-2.0"
] | 11 | 2021-09-24T18:02:26.000Z | 2022-01-27T18:51:47.000Z | piquassoboost/gaussian/source/tasks_apply_to_C_and_G/insert_transformed_rows.cpp | Budapest-Quantum-Computing-Group/piquassoboost | fd384be8f59cfd20d62654cf86c89f69d3cf8b8c | [
"Apache-2.0"
] | 1 | 2021-11-13T10:06:52.000Z | 2021-11-13T10:06:52.000Z | /**
* Copyright 2021 Budapest Quantum Computing Group
*
* 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 <iostream>
#include <tbb/tbb.h>
#include "insert_transformed_rows.h"
#include "matrix.h"
#include <memory.h>
namespace pic {
/**
@brief Constructor of the class.
@param rows_in The matrix containing the transformed rows (T @ mtx(modes,:) )
@param corner_in The matrix containing the transformed elements (T @ mtx(modes,modes) @ T^T)
@param mtx_out The resulting transformed matrix containing all the transformed modes
@param modes_in A vector of row indices that were transformed.
@return Returns with the instance of the class.
*/
Insert_Transformed_Rows::Insert_Transformed_Rows( matrix &rows_in,matrix &corner_in, matrix &mtx_out, std::vector<size_t> &modes_in, bool* cols_logical_in) {
rows = rows_in;
corner = corner_in;
mtx = mtx_out;
modes = modes_in;
cols_logical = cols_logical_in;
}
/**
@brief Operator to insert the transformed rows into the matrix
@param msg A TBB message fireing the node
*/
const tbb::flow::continue_msg &
Insert_Transformed_Rows::operator()(const tbb::flow::continue_msg &msg) {
#ifdef DEBUG
std::cout << "Tasks apply_to_C_and_G: inserting transformed rows and corner elements" << std::endl;
#endif
// raw pointer to the stored data in matrix mtx
Complex16* mtx_data = mtx.get_data();
// raw pointer to the stored data in matrix rows
Complex16* rows_data = rows.get_data();
// raw pointer to the stored data in matrix corner
Complex16* corner_data = corner.get_data();
// A vector of row inices to be extracted
std::vector<size_t> &modes_loc = modes;
// logical indexes of the columns of the matrix mtx. True values stand for columns corresponding to modes, and false otherwise.
bool* cols_logical_loc = cols_logical;
// number of columns
size_t col_num = rows.cols;
// inserting the the transformed rows into the matrix
// parallel for to insert the transformed rows
int N = (int)(modes.size());
tbb::parallel_for(0, N, 1, [rows_data, corner_data, mtx_data, modes_loc, cols_logical_loc, col_num](int i) {
// offset for the i-th row in the matrix rows
int row_offset = i*col_num;
// offset for the modes[i]-th row in the matrix mtx
int mtx_offset = modes_loc[i]*col_num;
// offset for the i-th row in the matrix corner
int corner_offset = i*modes_loc.size();
//std::cout<< i << " " << row_offset << " " << mtx_offset << " " << corner_offset << std::endl;
// raw pointers to the individual rows of the matrices
Complex16* row = rows_data + row_offset;
Complex16* mtx_row = mtx_data + mtx_offset;
Complex16* corner_row = corner_data + corner_offset;
size_t col_idx = 0;
size_t col_range = 1;
size_t corner_row_offset = 0;
// copy the elements from the transformed rows
while (true) {
// condition to exit the loop
if ( col_idx >= col_num ) {
break;
}
//std::cout << col_idx << std::endl;
// find continuous memory slices that can be copied
while (true) {
// condition to exit the loop
if ( cols_logical_loc[col_idx] != cols_logical_loc[col_idx+col_range] ) {
break;
}
else {
if ( col_idx+col_range+1 >= col_num ) {
break;
}
col_range = col_range + 1;
}
}
// determine whether to copy from rows or from corner
if (cols_logical_loc[col_idx] == true) {
// copy from corner
for (size_t idx = 0; idx<col_range; idx++) {
mtx_row[modes_loc[corner_row_offset+idx]] = corner_row[corner_row_offset+idx];
}
corner_row_offset = corner_row_offset + col_range;
//memcpy(mtx_row+col_idx, corner_row, col_range*sizeof(Complex16));
//corner_row = corner_row + col_range;
}
else {
// copy from rows
memcpy(mtx_row+col_idx, row+col_idx, col_range*sizeof(Complex16));
}
col_idx = col_idx + col_range;
col_range = 1;
}
}); // TBB
return msg;
}
} // PIC
| 32.103226 | 157 | 0.625 | [
"vector"
] |
b1368d033215108ac33cacb2d2ba051a517c7999 | 1,982 | cxx | C++ | findMinimumIndex_test.cxx | AnChristos/FindMinimumIndex | 604e39b2d336fc80128a1b6eb9d1bcb77c07ebec | [
"Apache-2.0"
] | null | null | null | findMinimumIndex_test.cxx | AnChristos/FindMinimumIndex | 604e39b2d336fc80128a1b6eb9d1bcb77c07ebec | [
"Apache-2.0"
] | null | null | null | findMinimumIndex_test.cxx | AnChristos/FindMinimumIndex | 604e39b2d336fc80128a1b6eb9d1bcb77c07ebec | [
"Apache-2.0"
] | 2 | 2019-12-15T00:54:32.000Z | 2020-10-01T09:08:13.000Z | #include "findMinimumIndex.h"
#include <iostream>
#include <algorithm>
#include <random>
/*
* Alignment of 64 bytes
*/
constexpr int alignment = 64;
/*
* create global data
* a bit hacky way
*/
constexpr size_t n = 16 << 8;
float* array;
class InitArray
{
public:
InitArray()
{
std::mt19937 gen;
std::uniform_real_distribution<> dis(0.1, 100.0);
// create buffer of right size,properly aligned
size_t const size = n * sizeof(float);
posix_memalign((void**)&array, alignment, size);
for (size_t i = 0; i < n; ++i) {
// Use dis to transform the random unsigned int generated by gen into a
// double. Each call to dis(gen) generates a new random double
array[i] = dis(gen);
}
}
~InitArray() { free(array); }
};
InitArray initArray;
/*
* Scalar code kind of C style
*/
static void
findMinimumIndexC()
{
int32_t minIndex = findMinIndexC(array, n);
std::cout << "C Minimum index : " << minIndex << " with value "
<< array[minIndex] << '\n';
}
static void
findMinimumIndexC2()
{
int32_t minIndex = findMinIndexC2(array, n);
std::cout << "C2 Minimum index : " << minIndex << " with value "
<< array[minIndex] << '\n';
}
/*
* Scalar code using STL
*/
static void
findMinimumIndexSTL()
{
int32_t minIndex = findMinIndexSTL(array, n);
std::cout << "STL Minimum index : " << minIndex << " with value "
<< array[minIndex] << '\n';
}
static void
findMinimumIndexVec()
{
int32_t minIndex = findMinIndexVec(array, n);
std::cout << "Vec Minimum index : " << minIndex << " with value " << array[minIndex]
<< '\n';
}
static void
findMinimumIndexVec16()
{
int32_t minIndex = findMinIndexVec16(array, n);
std::cout << "Vec Minimum index : " << minIndex << " with value " << array[minIndex]
<< '\n';
}
int main()
{
findMinimumIndexC();
findMinimumIndexC2();
findMinimumIndexSTL();
findMinimumIndexVec();
findMinimumIndexVec16();
return 0;
}
| 22.022222 | 86 | 0.627649 | [
"transform"
] |
b137a1de3924a77e3bcc5f2abf88547feb5ca124 | 3,942 | cpp | C++ | src/cfdjs_script.cpp | atomicfinance/cfd-js | 99f3df5308d840814989e616e4d5472ce23249c7 | [
"MIT"
] | 6 | 2019-10-12T11:05:36.000Z | 2021-07-04T07:20:32.000Z | src/cfdjs_script.cpp | atomicfinance/cfd-js | 99f3df5308d840814989e616e4d5472ce23249c7 | [
"MIT"
] | 87 | 2019-10-11T07:10:11.000Z | 2022-03-27T09:10:42.000Z | src/cfdjs_script.cpp | atomicfinance/cfd-js | 99f3df5308d840814989e616e4d5472ce23249c7 | [
"MIT"
] | 3 | 2019-12-26T04:16:20.000Z | 2021-09-21T16:16:48.000Z | // Copyright 2019 CryptoGarage
/**
* @file cfdjs_script.cpp
*
* @brief cfd-apiで利用するScript関連の実装ファイル
*/
#include <string>
#include <vector>
#include "cfd/cfd_transaction_common.h"
#include "cfd/cfdapi_transaction.h"
#include "cfdcore/cfdcore_common.h"
#include "cfdcore/cfdcore_exception.h"
#include "cfdcore/cfdcore_logger.h"
#include "cfdcore/cfdcore_script.h"
#include "cfdjs/cfdjs_api_script.h"
#include "cfdjs_internal.h" // NOLINT
#include "cfdjs_json_transaction.h" // NOLINT
#include "cfdjs_transaction_base.h" // NOLINT
namespace cfd {
namespace js {
namespace api {
using cfd::SignParameter;
using cfd::api::TransactionApi;
using cfd::core::CfdError;
using cfd::core::CfdException;
using cfd::core::Script;
using cfd::core::ScriptBuilder;
using cfd::core::ScriptElement;
using cfd::core::logger::warn;
using cfd::js::api::TransactionStructApiBase;
ParseScriptResponseStruct ScriptStructApi::ParseScript(
const ParseScriptRequestStruct& request) {
auto call_func = [](const ParseScriptRequestStruct& request)
-> ParseScriptResponseStruct {
ParseScriptResponseStruct response;
Script script(request.script);
for (const auto& elem : script.GetElementList()) {
std::string data;
if (elem.IsOpCode()) {
// Convert to OpCode string
data = elem.GetOpCode().ToCodeString();
} else {
data = elem.ToString();
}
response.script_items.push_back(data);
}
return response;
};
ParseScriptResponseStruct result;
result =
ExecuteStructApi<ParseScriptRequestStruct, ParseScriptResponseStruct>(
request, call_func, std::string(__FUNCTION__));
return result;
}
ScriptDataResponseStruct ScriptStructApi::CreateScript(
const CreateScriptRequestStruct& request) {
auto call_func = [](const CreateScriptRequestStruct& request)
-> ScriptDataResponseStruct {
ScriptDataResponseStruct response;
if (request.items.size() == 0) {
warn(CFD_LOG_SOURCE, "empty script items.");
throw CfdException(
CfdError::kCfdIllegalArgumentError,
"Failed to CreateScript. empty script items.");
}
ScriptBuilder sb = ScriptBuilder();
for (const auto& item : request.items) {
sb.AppendString(item);
}
Script script = sb.Build();
response.hex = script.GetHex();
return response;
};
ScriptDataResponseStruct result;
result =
ExecuteStructApi<CreateScriptRequestStruct, ScriptDataResponseStruct>(
request, call_func, std::string(__FUNCTION__));
return result;
}
ScriptDataResponseStruct ScriptStructApi::CreateMultisigScriptSig(
const CreateMultisigScriptSigRequestStruct& request) {
auto call_func = [](const CreateMultisigScriptSigRequestStruct& request)
-> ScriptDataResponseStruct {
ScriptDataResponseStruct response;
if (request.sign_params.size() == 0) {
warn(CFD_LOG_SOURCE, "empty sign params.");
throw CfdException(
CfdError::kCfdIllegalArgumentError,
"Failed to CreateMultisigScriptSig. empty sign params.");
}
Script redeem_script(request.redeem_script);
std::vector<SignParameter> sign_list;
SignParameter sign_data;
for (const auto& stack_req : request.sign_params) {
sign_data =
TransactionStructApiBase::ConvertSignDataStructToSignParameter(
stack_req);
if (!stack_req.related_pubkey.empty()) {
sign_data.SetRelatedPubkey(Pubkey(stack_req.related_pubkey));
}
sign_list.push_back(sign_data);
}
TransactionApi api;
response.hex = api.CreateMultisigScriptSig(sign_list, redeem_script);
return response;
};
ScriptDataResponseStruct result;
result = ExecuteStructApi<
CreateMultisigScriptSigRequestStruct, ScriptDataResponseStruct>(
request, call_func, std::string(__FUNCTION__));
return result;
}
} // namespace api
} // namespace js
} // namespace cfd
| 29.41791 | 76 | 0.71309 | [
"vector"
] |
b139796d0931d33c3443768efbfc68fe524b5782 | 8,687 | cc | C++ | src/node_http.cc | ekg/node | c77964760047f734c58dab49143ff6487f938c6e | [
"MIT"
] | 2 | 2021-06-29T21:07:26.000Z | 2022-01-25T02:50:14.000Z | src/node_http.cc | raycmorgan/node | a0bdcbcead30a42d6d8cd038508c0da8bc08a568 | [
"MIT"
] | null | null | null | src/node_http.cc | raycmorgan/node | a0bdcbcead30a42d6d8cd038508c0da8bc08a568 | [
"MIT"
] | 1 | 2019-12-19T16:28:13.000Z | 2019-12-19T16:28:13.000Z | #include <node_http.h>
#include <assert.h>
#include <stdio.h>
#include <strings.h>
#define METHOD_SYMBOL String::NewSymbol("method")
#define STATUS_CODE_SYMBOL String::NewSymbol("statusCode")
#define HTTP_VERSION_SYMBOL String::NewSymbol("httpVersion")
#define SHOULD_KEEP_ALIVE_SYMBOL String::NewSymbol("should_keep_alive")
using namespace v8;
using namespace node;
Persistent<FunctionTemplate> HTTPConnection::client_constructor_template;
Persistent<FunctionTemplate> HTTPConnection::server_constructor_template;
void
HTTPConnection::Initialize (Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(NewClient);
client_constructor_template = Persistent<FunctionTemplate>::New(t);
client_constructor_template->Inherit(Connection::constructor_template);
client_constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
client_constructor_template->SetClassName(String::NewSymbol("Client"));
target->Set(String::NewSymbol("Client"), client_constructor_template->GetFunction());
t = FunctionTemplate::New(NewServer);
server_constructor_template = Persistent<FunctionTemplate>::New(t);
server_constructor_template->Inherit(Connection::constructor_template);
server_constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
server_constructor_template->SetClassName(String::NewSymbol("ServerSideConnection"));
}
Handle<Value>
HTTPConnection::NewClient (const Arguments& args)
{
HandleScope scope;
HTTPConnection *connection = new HTTPConnection(HTTP_RESPONSE);
connection->Wrap(args.This());
return args.This();
}
Handle<Value>
HTTPConnection::NewServer (const Arguments& args)
{
HandleScope scope;
HTTPConnection *connection = new HTTPConnection(HTTP_REQUEST);
connection->Wrap(args.This());
return args.This();
}
void
HTTPConnection::OnReceive (const void *buf, size_t len)
{
assert(attached_);
http_parser_execute(&parser_, static_cast<const char*>(buf), len);
if (http_parser_has_error(&parser_)) ForceClose();
}
void
HTTPConnection::OnEOF ()
{
HandleScope scope;
assert(attached_);
http_parser_execute(&parser_, NULL, 0);
if (http_parser_has_error(&parser_)) {
ForceClose();
} else {
Emit("eof", 0, NULL);
}
}
int
HTTPConnection::on_message_begin (http_parser *parser)
{
HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
assert(connection->attached_);
connection->Emit("messageBegin", 0, NULL);
return 0;
}
int
HTTPConnection::on_message_complete (http_parser *parser)
{
HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
assert(connection->attached_);
connection->Emit("messageComplete", 0, NULL);
return 0;
}
int
HTTPConnection::on_uri (http_parser *parser, const char *buf, size_t len)
{
HandleScope scope;
HTTPConnection *connection = static_cast<HTTPConnection*>(parser->data);
assert(connection->attached_);
Local<Value> argv[1] = { String::New(buf, len) };
connection->Emit("uri", 1, argv);
return 0;
}
int
HTTPConnection::on_query_string (http_parser *parser, const char *buf, size_t len)
{
HandleScope scope;
HTTPConnection *connection = static_cast<HTTPConnection*>(parser->data);
assert(connection->attached_);
Local<Value> argv[1] = { String::New(buf, len) };
connection->Emit("queryString", 1, argv);
return 0;
}
int
HTTPConnection::on_path (http_parser *parser, const char *buf, size_t len)
{
HandleScope scope;
HTTPConnection *connection = static_cast<HTTPConnection*>(parser->data);
assert(connection->attached_);
Local<Value> argv[1] = { String::New(buf, len) };
connection->Emit("path", 1, argv);
return 0;
}
int
HTTPConnection::on_fragment (http_parser *parser, const char *buf, size_t len)
{
HandleScope scope;
HTTPConnection *connection = static_cast<HTTPConnection*>(parser->data);
assert(connection->attached_);
Local<Value> argv[1] = { String::New(buf, len) };
connection->Emit("fragment", 1, argv);
return 0;
}
const static char normalizer[] =
"\0------------------------------"
"-----------------0123456789-----"
"--abcdefghijklmnopqrstuvwxyz----"
"--abcdefghijklmnopqrstuvwxyz----"
"--------------------------------"
"--------------------------------"
"--------------------------------"
"--------------------------------";
int
HTTPConnection::on_header_field (http_parser *parser, const char *buf, size_t len)
{
HandleScope scope;
HTTPConnection *connection = static_cast<HTTPConnection*>(parser->data);
assert(connection->attached_);
// NORMALIZE
size_t i;
char *nonconstbuf = (char*)buf; // FIXME
for (i = 0; i < len; i++) { nonconstbuf[i] = normalizer[buf[i]]; }
Local<Value> argv[1] = { String::New(buf, len) };
connection->Emit("headerField", 1, argv);
return 0;
}
int
HTTPConnection::on_header_value (http_parser *parser, const char *buf, size_t len)
{
HandleScope scope;
HTTPConnection *connection = static_cast<HTTPConnection*>(parser->data);
assert(connection->attached_);
Local<Value> argv[1] = { String::New(buf, len) };
connection->Emit("headerValue", 1, argv);
return 0;
}
static inline Local<String>
GetMethod (int method)
{
const char *s;
switch (method) {
case HTTP_COPY: s = "COPY"; break;
case HTTP_DELETE: s = "DELETE"; break;
case HTTP_GET: s = "GET"; break;
case HTTP_HEAD: s = "HEAD"; break;
case HTTP_LOCK: s = "LOCK"; break;
case HTTP_MKCOL: s = "MKCOL"; break;
case HTTP_MOVE: s = "MOVE"; break;
case HTTP_OPTIONS: s = "OPTIONS"; break;
case HTTP_POST: s = "POST"; break;
case HTTP_PROPFIND: s = "PROPFIND"; break;
case HTTP_PROPPATCH: s = "PROPPATCH"; break;
case HTTP_PUT: s = "PUT"; break;
case HTTP_TRACE: s = "TRACE"; break;
case HTTP_UNLOCK: s = "UNLOCK"; break;
}
HandleScope scope;
Local<String> method = String::NewSymbol(s);
return scope.Close(method);
}
int
HTTPConnection::on_headers_complete (http_parser *parser)
{
HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
assert(connection->attached_);
HandleScope scope;
Local<Object> message_info = Object::New();
// METHOD
if (connection->parser_.type == HTTP_REQUEST)
message_info->Set(METHOD_SYMBOL, GetMethod(connection->parser_.method));
// STATUS
if (connection->parser_.type == HTTP_RESPONSE)
message_info->Set(STATUS_CODE_SYMBOL,
Integer::New(connection->parser_.status_code));
// VERSION
Local<String> version;
switch (connection->parser_.version) {
case HTTP_VERSION_OTHER:
version = String::NewSymbol("Other");
break;
case HTTP_VERSION_09:
version = String::NewSymbol("0.9");
break;
case HTTP_VERSION_10:
version = String::NewSymbol("1.0");
break;
case HTTP_VERSION_11:
version = String::NewSymbol("1.1");
break;
}
message_info->Set(HTTP_VERSION_SYMBOL, version);
message_info->Set(SHOULD_KEEP_ALIVE_SYMBOL,
http_parser_should_keep_alive(&connection->parser_) ? True() : False());
Local<Value> argv[1] = { message_info };
connection->Emit("headerComplete", 1, argv);
return 0;
}
int
HTTPConnection::on_body (http_parser *parser, const char *buf, size_t len)
{
assert(len != 0);
HTTPConnection *connection = static_cast<HTTPConnection*> (parser->data);
assert(connection->attached_);
HandleScope scope;
// TODO each message should have their encoding.
// don't look at the conneciton for encoding
Local<Value> data = Encode(buf, len, connection->encoding_);
connection->Emit("body", 1, &data);
return 0;
}
Persistent<FunctionTemplate> HTTPServer::constructor_template;
void
HTTPServer::Initialize (Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->Inherit(Server::constructor_template);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("Server"));
target->Set(String::NewSymbol("Server"), constructor_template->GetFunction());
}
Handle<Value>
HTTPServer::New (const Arguments& args)
{
HandleScope scope;
HTTPServer *server = new HTTPServer();
server->Wrap(args.This());
return args.This();
}
Handle<FunctionTemplate>
HTTPServer::GetConnectionTemplate (void)
{
return HTTPConnection::server_constructor_template;
}
Connection*
HTTPServer::UnwrapConnection (Local<Object> connection)
{
HandleScope scope;
return ObjectWrap::Unwrap<HTTPConnection>(connection);
}
| 27.753994 | 87 | 0.701163 | [
"object"
] |
b13a6346a487cb23f3d63b1e50dec15fae26133f | 2,993 | cxx | C++ | Taxi.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | Taxi.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | Taxi.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | // BEGIN CUT HERE
// PROBLEM STATEMENT
// The "taxicab distance" between two points in space is defined to be the distance
that would need to be travelled to get from one to the other using segments
that are parallel to the axes. This is generally longer than the (straight-line)
distance between the two points.
We know the taxicab distance between two points. We want to know the maximum
straight-line distance between them if they lie in the
rectangular region { (x,y) | 0<=x<=maxX, 0<=y<=maxY }.
Create a class Taxi that contains a method maxDis that is given maxX, maxY,
and taxiDis and that returns the largest possible straight-line distance between
the two points. If no two points within the given region have the given taxicab
distance, return -1.0.
DEFINITION
Class:Taxi
Method:maxDis
Parameters:int, int, int
Returns:double
Method signature:double maxDis(int maxX, int maxY, int taxiDis)
NOTES
-A return value with either an absolute or relative error of less than 1.0E-9 is considered correct.
CONSTRAINTS
-maxX and maxY are both between 1 and 1,000,000, inclusive.
-taxiDis is between 0 and 1,000,000, inclusive.
EXAMPLES
0)
10
3
3
Returns: 3.0
The two points could lie in a straight line parallel to one of the axes. Then
the straight-line distance would be the same as the taxicab distance.
1)
10
3
24
Returns: -1.0
No two points with 0<=x<=10, 0<=y<=3, have a taxicab distance between them
that is as big as 24.
2)
7
10
13
Returns: 10.44030650891055
(5,0) and (2,10) are two points in this region whose taxicab distance is |2-5| + |10-0| = 13 and whose straight-line distance is sqrt(3*3 + 10*10) = sqrt(109).
3)
4
4
7
Returns: 5.0
4)
976421
976421
1000000
Returns: 976705.6560100387
// END CUT HERE
#line 92 "Taxi.cxx"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define sz size()
#define PB push_back
#define clr(x) memset(x, 0, sizeof(x))
#define forn(i,n) for(__typeof(n) i = 0; i < (n); i++)
#define ford(i,n) for(int i = (n) - 1; i >= 0; i--)
#define forv(i,v) forn(i, v.sz)
#define For(i, st, en) for(__typeof(en) i = (st); i < (en); i++)
using namespace std;
class Taxi {
public:
double maxDis(int maxX, int maxY, int taxiDis)
{
double ret = -1;
int a = maxX+1, b = maxY;
if(taxiDis <= maxX+maxY)
{
for(int i=0; i<=maxX; i++)
if(taxiDis-i >= 0 && taxiDis-i <= maxY && (long long)i*(taxiDis-i) < (long long)a*b)
{
a = i;
b = taxiDis-i;
}
ret = sqrt(pow(a,2.) + pow(b,2.));
//ret = sqrt(a*a + b*b);
}
return ret;
}
};
| 21.22695 | 163 | 0.648179 | [
"vector"
] |
b13b58fe319bfa49a499a2a70659d11ed586a931 | 34,650 | cpp | C++ | src/lib/pq/port/cipher.cpp | opengauss-mirror/CM | 79664cf29912421163ebca4485fc8e0376a81b95 | [
"MulanPSL-1.0"
] | null | null | null | src/lib/pq/port/cipher.cpp | opengauss-mirror/CM | 79664cf29912421163ebca4485fc8e0376a81b95 | [
"MulanPSL-1.0"
] | null | null | null | src/lib/pq/port/cipher.cpp | opengauss-mirror/CM | 79664cf29912421163ebca4485fc8e0376a81b95 | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) 2021 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* cipher.cpp
*
*
* IDENTIFICATION
* src/lib/pq/port/cipher.cpp
*
* -------------------------------------------------------------------------
*/
#include "cipher.h"
#include "securec.h"
#include "securec_check.h"
#include "utils/syscall_lock.h"
#include "utils/pg_crc_tables.h"
#include "openssl/rand.h"
#include "openssl/evp.h"
#include "openssl/ossl_typ.h"
#include "openssl/x509.h"
#include "openssl/ssl.h"
#include "openssl/asn1.h"
#include "openssl/hmac.h"
#define ENTROPY_F_LEN 128
#define NONCE_F_LEN 128
#ifndef CACHELINE_SIZE
#define CACHELINE_SIZE 32
#endif
#ifndef L1CACHE_SIZE
#define L1CACHE_SIZE (64 * 1024)
#endif
pthread_mutex_t read_cipher_lock;
/* Store entropy message of the seed which used by random function. */
typedef struct {
uint64 data;
uint32 prev_time;
uint32 last_delta;
int32 last_delta2;
uint32 n;
double sum;
} entropy_t;
static bool gen_cipher_file(KeyMode mode, GS_UCHAR* init_rand, GS_UCHAR server_vector[], GS_UCHAR client_vector[],
const char* plain_key, const char* user_name, const char* datadir, const char* preStr);
static bool gen_rand_file(
KeyMode mode, GS_UCHAR* init_rand, const char* user_name, const char* datadir, const char* preStr);
static bool WriteContentToFile(const char* filename, const void* content, size_t csize);
static bool IsSpecialCharacter(char ch);
static bool isModeExists(KeyMode mode);
void ClearCipherKeyFile(CipherkeyFile* cipher_file_content);
void ClearRandKeyFile(RandkeyFile* rand_file_content);
bool init_vector_random(GS_UCHAR* init_vector, size_t vector_len);
GS_UINT32 CRYPT_decrypt(GS_UINT32 ulAlgId, const GS_UCHAR* pucKey, GS_UINT32 ulKeyLen, const GS_UCHAR* pucIV,
GS_UINT32 ulIVLen, GS_UCHAR* pucCipherText, GS_UINT32 ulCLen, GS_UCHAR* pucPlainText, GS_UINT32* pulPLen);
GS_UINT32 CRYPT_encrypt(GS_UINT32 ulAlgId, const GS_UCHAR* pucKey, GS_UINT32 ulKeyLen, const GS_UCHAR* pucIV,
GS_UINT32 ulIVLen, GS_UCHAR* pucPlainText, GS_UINT32 ulPlainLen, GS_UCHAR* pucCipherText, GS_UINT32* pulCLen);
GS_UINT32 CRYPT_hmac(GS_UINT32 ulAlgType, const GS_UCHAR* pucKey, GS_UINT32 upucKeyLen, const GS_UCHAR* pucData,
GS_UINT32 ulDataLen, GS_UCHAR* pucDigest, GS_UINT32* pulDigestLen);
/* for stored cipherfile buffer */
RandkeyFile g_rand_file_content[CIPHER_TYPE_MAX];
CipherkeyFile g_cipher_file_content[CIPHER_TYPE_MAX];
bool init_vector_random(GS_UCHAR* init_vector, size_t vector_len)
{
errno_t errorno = EOK;
int retval = 0;
GS_UCHAR random_vector[RANDOM_LEN] = {0};
retval = RAND_priv_bytes(random_vector, RANDOM_LEN);
if (retval != 1) {
errorno = memset_s(random_vector, RANDOM_LEN, '\0', RANDOM_LEN);
securec_check_c(errorno, "", "");
(void)fprintf(stderr, _("generate random initial vector failed, errcode:%d\n"), retval);
return false;
}
errorno = memcpy_s(init_vector, vector_len, random_vector, RANDOM_LEN);
securec_check_c(errorno, "", "");
errorno = memset_s(random_vector, RANDOM_LEN, '\0', RANDOM_LEN);
securec_check_c(errorno, "", "");
return true;
}
/* check whether the input password(for key derivation) meet the requirements of the length and complexity */
bool check_input_password(const char* password)
{
int key_input_len = 0;
int kinds[PASSWD_KINDS] = {0};
int kinds_num = 0;
const char* ptr = NULL;
int i = 0;
if (password == NULL) {
(void)fprintf(stderr, _("Invalid password,please check it\n"));
return false;
}
key_input_len = strlen(password);
if (key_input_len < MIN_KEY_LEN) {
(void)fprintf(stderr, _("Invalid password,it must contain at least eight characters\n"));
return false;
}
if (key_input_len > MAX_KEY_LEN) {
(void)fprintf(stderr, _("Invalid password,the length exceed %d\n"), MAX_KEY_LEN);
return false;
}
ptr = password;
while (*ptr != '\0') {
if (*ptr >= 'A' && *ptr <= 'Z') {
kinds[0]++;
} else if (*ptr >= 'a' && *ptr <= 'z') {
kinds[1]++;
} else if (*ptr >= '0' && *ptr <= '9') {
kinds[2]++;
} else if (IsSpecialCharacter(*ptr)) {
kinds[3]++;
}
ptr++;
}
for (i = 0; i < PASSWD_KINDS; ++i) {
if (kinds[i] > 0) {
kinds_num++;
}
}
if (kinds_num < PASSWD_KINDS - 1) {
(void)fprintf(stderr, _("Invalid password,it must contain at least three kinds of characters\n"));
return false;
}
return true;
}
/* encrypt the plain text to cipher text */
bool EncryptInputKey(GS_UCHAR* pucPlainText, GS_UCHAR* initrand, GS_UCHAR* keySaltVector, GS_UCHAR* encryptVector,
GS_UCHAR* pucCipherText, GS_UINT32* pulCLen)
{
GS_UCHAR deriver_key[KEDF2_KEY_SIZE] = {0};
GS_UINT32 retval = 0;
GS_UINT32 ulPlainLen = 0;
errno_t rc = EOK;
if (pucPlainText == NULL) {
(void)fprintf(stderr, _("invalid plain text, please check it!\n"));
return false;
}
ulPlainLen = strlen((const char*)pucPlainText);
/* use PKCS5 HMAC sha256 to dump the key for encryption */
retval = PKCS5_PBKDF2_HMAC((const char*)initrand,
RANDOM_LEN,
keySaltVector,
RANDOM_LEN,
ITERATE_TIMES,
EVP_sha256(),
KEDF2_KEY_SIZE,
deriver_key);
if (retval != 1) {
rc = memset_s(deriver_key, KEDF2_KEY_SIZE, 0, KEDF2_KEY_SIZE);
securec_check_c(rc, "\0", "\0");
(void)fprintf(stderr, _("generate the derived key failed, errcode:%u\n"), retval);
return false;
}
retval = CRYPT_encrypt(NID_aes_128_cbc,
deriver_key,
KEDF2_KEY_SIZE,
encryptVector,
RANDOM_LEN,
pucPlainText,
ulPlainLen,
pucCipherText,
pulCLen);
if (retval != 0) {
rc = memset_s(deriver_key, KEDF2_KEY_SIZE, 0, KEDF2_KEY_SIZE);
securec_check_c(rc, "\0", "\0");
(void)fprintf(stderr, _("encrypt plain text to cipher text failed, errcode:%u\n"), retval);
return false;
}
rc = memset_s(deriver_key, KEDF2_KEY_SIZE, 0, KEDF2_KEY_SIZE);
securec_check_c(rc, "\0", "\0");
return true;
}
/* decrypt the cipher text to plain text */
bool DecryptInputKey(GS_UCHAR* pucCipherText, GS_UINT32 ulCLen, GS_UCHAR* initrand, GS_UCHAR* initVector,
GS_UCHAR* decryptVector, GS_UCHAR* pucPlainText, GS_UINT32* pulPLen)
{
GS_UINT32 retval = 0;
GS_UCHAR decrypt_key[RANDOM_LEN] = {0};
errno_t rc = EOK;
if (pucCipherText == NULL) {
(void)fprintf(stderr, _("invalid cipher text, please check it!\n"));
return false;
}
/* get the decrypt key value */
retval = PKCS5_PBKDF2_HMAC((const char*)initrand,
RANDOM_LEN,
initVector,
RANDOM_LEN,
ITERATE_TIMES,
EVP_sha256(),
RANDOM_LEN,
decrypt_key);
if (retval != 1) {
rc = memset_s(decrypt_key, RANDOM_LEN, 0, RANDOM_LEN);
securec_check_c(rc, "\0", "\0");
(void)fprintf(stderr, _("generate the derived key failed, errcode:%u\n"), retval);
return false;
}
/*decrypt the cipher*/
retval = CRYPT_decrypt(NID_aes_128_cbc,
decrypt_key,
RANDOM_LEN,
decryptVector,
RANDOM_LEN,
pucCipherText,
ulCLen,
pucPlainText,
pulPLen);
if (retval != 0) {
rc = memset_s(decrypt_key, RANDOM_LEN, 0, RANDOM_LEN);
securec_check_c(rc, "\0", "\0");
(void)fprintf(stderr, _("decrypt cipher text to plain text failed, errcode:%u\n"), retval);
return false;
}
rc = memset_s(decrypt_key, RANDOM_LEN, 0, RANDOM_LEN);
securec_check_c(rc, "\0", "\0");
return true;
}
/* copy the cipher text to CipherkeyFile */
static void CopyCipher(GS_UCHAR* cipher_str, /* points to cipher string */
GS_UINT32 cipher_len, /* cipher string length */
GS_UCHAR* key_salt, /* salt vector used to derive key */
GS_UCHAR* vector_salt, /* salt vector used to encrypt plaintext */
CipherkeyFile* content) /* file content buffer, be careful caller make sure it's not null */
{
errno_t rc = EOK;
rc = memcpy_s(content->cipherkey, CIPHER_LEN + 1, cipher_str, CIPHER_LEN);
securec_check_c(rc, "\0", "\0");
rc = memcpy_s(content->key_salt, RANDOM_LEN + 1, key_salt, RANDOM_LEN);
securec_check_c(rc, "\0", "\0");
rc = memcpy_s(content->vector_salt, RANDOM_LEN + 1, vector_salt, RANDOM_LEN);
securec_check_c(rc, "\0", "\0");
/* generate the crc value to protect the value in case someone modify it */
INIT_CRC32(content->crc);
COMP_CRC32(content->crc, (char*)content, offsetof(CipherkeyFile, crc));
FIN_CRC32(content->crc);
}
/* copy the cipher text to RandkeyFile */
static void CopyRand(GS_UCHAR* rand_str, RandkeyFile* randfile)
{
errno_t rc = EOK;
/* append rand_key to the front part of cipher text */
rc = memcpy_s(randfile->randkey, RANDOM_LEN + 1, rand_str, RANDOM_LEN);
securec_check_c(rc, "\0", "\0");
/* generate the crc value to protect the value in case someone modify it */
INIT_CRC32(randfile->crc);
COMP_CRC32(randfile->crc, (char*)randfile, offsetof(RandkeyFile, crc));
FIN_CRC32(randfile->crc);
}
/* check the crc of rand file storing the randtext */
bool RandFileIsValid(RandkeyFile* randfile)
{
pg_crc32 rand_crc;
INIT_CRC32(rand_crc);
COMP_CRC32(rand_crc, (char*)randfile, offsetof(RandkeyFile, crc));
FIN_CRC32(rand_crc);
if (!EQ_CRC32(randfile->crc, rand_crc)) {
(void)fprintf(stderr, _("CRC checksum does not match value stored in file, maybe the rand file is corrupt\n"));
return false;
}
return true;
}
/* check the crc of cipher file storing the ciphertext */
bool CipherFileIsValid(CipherkeyFile* cipher)
{
pg_crc32 cipher_crc;
INIT_CRC32(cipher_crc);
COMP_CRC32(cipher_crc, (char*)cipher, offsetof(CipherkeyFile, crc));
FIN_CRC32(cipher_crc);
if (!EQ_CRC32(cipher->crc, cipher_crc)) {
(void)fprintf(
stderr, _("CRC checksum does not match value stored in file, maybe the cipher file is corrupt\n"));
return false;
}
return true;
}
/* Read the contents of the file to buffer */
bool ReadContentFromFile(const char* filename, void* content, size_t csize)
{
FILE* pfRead = NULL;
int cnt = 0;
/*open and read file*/
if ((pfRead = fopen(filename, "rb")) == NULL) {
(void)fprintf(stderr, _("could not open file \"%s\": %s\n"), filename, gs_strerror(errno));
return false;
}
cnt = fread(content, csize, 1, pfRead);
if (cnt < 0) {
fclose(pfRead);
(void)fprintf(stderr, _("could not read file \"%s\": %s\n"), filename, gs_strerror(errno));
return false;
}
if (fclose(pfRead)) {
(void)fprintf(stderr, _("could not close file \"%s\": %s\n"), filename, gs_strerror(errno));
return false;
}
return true;
}
/* write data in buffer to file */
static bool WriteContentToFile(const char* filename, const void* content, size_t csize)
{
FILE* pfWrite = NULL;
int ret = 0;
/*open and write file*/
if ((pfWrite = fopen(filename, "wb")) == NULL) {
(void)fprintf(stderr, _("could not open file \"%s\" for writing: %s\n"), filename, gs_strerror(errno));
return false;
}
if (fwrite(content, csize, 1, pfWrite) != 1) {
fclose(pfWrite);
(void)fprintf(stderr, _("could not write file \"%s\": %s\n"), filename, gs_strerror(errno));
return false;
}
#ifdef WIN32
ret = _chmod(filename, 0400);
#else
ret = fchmod(pfWrite->_fileno, 0400);
#endif
if (fclose(pfWrite)) {
(void)fprintf(stderr, _("could not close file \"%s\": %s\n"), filename, gs_strerror(errno));
return false;
}
if (-1 == ret) {
(void)fprintf(stderr, _("could not set permissions of file \"%s\": %s\n"), filename, gs_strerror(errno));
return false;
}
return true;
}
/* Judge if the KeyMode is legal */
static bool isModeExists(KeyMode mode)
{
if (mode != SERVER_MODE && mode != CLIENT_MODE && mode != HADR_MODE &&
mode != OBS_MODE && mode != SOURCE_MODE && mode != GDS_MODE &&
mode != USER_MAPPING_MODE) {
#ifndef ENABLE_LLT
(void)fprintf(stderr, _("AK/SK encrypt/decrypt encounters invalid key mode.\n"));
return false;
#endif
}
return true;
}
/*
* @Description : reset cipher file content.
* @in cipher_file_context : the file need to be cleared.
* @return : void.
*/
void ClearCipherKeyFile(CipherkeyFile* cipher_file_content)
{
if (cipher_file_content != NULL) {
errno_t rc = EOK;
rc = memset_s((char*)(cipher_file_content->cipherkey), CIPHER_LEN + 1, 0, CIPHER_LEN + 1);
securec_check_c(rc, "", "");
rc = memset_s((char*)(cipher_file_content->key_salt), RANDOM_LEN + 1, 0, RANDOM_LEN + 1);
securec_check_c(rc, "", "");
rc = memset_s((char*)(cipher_file_content->vector_salt), RANDOM_LEN + 1, 0, RANDOM_LEN + 1);
securec_check_c(rc, "", "");
}
return;
}
/*
* @Description : reset rand file content.
* @in rand_file_context : the file need to be cleared.
* @return : void.
*/
void ClearRandKeyFile(RandkeyFile* rand_file_content)
{
if (rand_file_content != NULL) {
errno_t rc = EOK;
rc = memset_s((char*)(rand_file_content->randkey), CIPHER_LEN + 1, 0, CIPHER_LEN + 1);
securec_check_c(rc, "", "");
}
return;
}
/* encrypt the input key,and write the cipher to file */
static bool gen_cipher_file(KeyMode mode, /* SERVER_MODE or CLIENT_MODE or OBS_MODE or SOURCE_MODE */
GS_UCHAR* init_rand, GS_UCHAR server_vector[], GS_UCHAR client_vector[], const char* plain_key,
const char* user_name, const char* datadir, const char* preStr)
{
int ret = 0;
char cipherkeyfile[MAXPGPATH] = {0x00};
GS_UCHAR encrypt_rand[RANDOM_LEN] = {0};
GS_UCHAR ciphertext[CIPHER_LEN + CIPHER_LEN] = {0};
GS_UCHAR* key_salt = NULL;
GS_UINT32 cipherlen = 0;
int retval = 0;
CipherkeyFile cipher_file_content;
/* check whether the key mode is valid */
if (!isModeExists(mode)) {
#ifndef ENABLE_LLT
goto RETURNFALSE;
#endif
}
/* generate init rand key */
retval = RAND_priv_bytes(encrypt_rand, RANDOM_LEN);
if (retval != 1) {
#ifndef ENABLE_LLT
(void)fprintf(stderr, _("generate random key failed,errcode:%d\n"), retval);
goto RETURNFALSE;
#endif
}
if (mode == SERVER_MODE) /* in server_mode,write the file with name like: server% */
{
ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/server%s", datadir, CIPHER_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
key_salt = server_vector;
} else if (mode == OBS_MODE) /* in OBS_mode,write the file with name like: obsserver% */
{
if (NULL == preStr) {
ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/obsserver%s", datadir, CIPHER_KEY_FILE);
} else {
ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", datadir, preStr, CIPHER_KEY_FILE);
}
securec_check_ss_c(ret, "\0", "\0");
key_salt = server_vector;
} else if (mode == SOURCE_MODE) /* in SOURCE_MODE,write the file with name like: datasource% */
{
ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/datasource%s", datadir, CIPHER_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
key_salt = server_vector;
}
/*in client_mode,check with the user name is appointed.if so, write the files naming
with %user_name%,if not,write files naming with client%*/
else if (mode == CLIENT_MODE) {
if (NULL == user_name) {
ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/client%s", datadir, CIPHER_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
} else {
ret = snprintf_s(cipherkeyfile, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", datadir, user_name, CIPHER_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
}
key_salt = client_vector;
} else {
return false;
}
if (!EncryptInputKey((GS_UCHAR*)plain_key, init_rand, key_salt, encrypt_rand, ciphertext, &cipherlen)) {
#ifndef ENABLE_LLT
goto RETURNFALSE;
#endif
}
/*
* Write ciphertext and encrypt rand vector to cipher_file_content
* and generate cipher_file_context's CRC and append to the end of
* cipher_file_context.
*/
CopyCipher(ciphertext, cipherlen, key_salt, encrypt_rand, &cipher_file_content);
if (!WriteContentToFile(cipherkeyfile, (const void*)&cipher_file_content, sizeof(CipherkeyFile))) {
#ifndef ENABLE_LLT
goto RETURNFALSE;
#endif
}
/*
* Change the privileges: include read & write
* Note: it should be checked by OM tool: gs_ec.
*/
if (mode == SOURCE_MODE || mode == CLIENT_MODE || mode == SERVER_MODE || mode == OBS_MODE) {
#ifdef WIN32
ret = _chmod(cipherkeyfile, 0600);
#else
ret = chmod(cipherkeyfile, 0600);
#endif
if (ret != 0) {
#ifndef ENABLE_LLT
(void)fprintf(
stderr, _("could not set permissions of file \"%s\": %s\n"), cipherkeyfile, gs_strerror(errno));
goto RETURNFALSE;
#endif
}
}
/*
* Empty ciphertext and cipher_file_content.
* This is useful. Although ciphertext and cipher_file_content is in stack,
* we should manually clear them.
*/
ret = memset_s(ciphertext, (CIPHER_LEN + CIPHER_LEN), 0, (CIPHER_LEN + CIPHER_LEN));
securec_check_c(ret, "\0", "\0");
ret = memset_s((char*)&cipher_file_content, sizeof(CipherkeyFile), 0, sizeof(CipherkeyFile));
securec_check_c(ret, "\0", "\0");
return true;
#ifndef ENABLE_LLT
RETURNFALSE:
/*
* Empty ciphertext and cipher_file_content.
* This is useful. Although ciphertext and cipher_file_content is in stack,
* we should manually clear them.
*/
ret = memset_s(ciphertext, (CIPHER_LEN + CIPHER_LEN), 0, (CIPHER_LEN + CIPHER_LEN));
securec_check_c(ret, "\0", "\0");
ret = memset_s((void*)&cipher_file_content, sizeof(CipherkeyFile), 0, sizeof(CipherkeyFile));
securec_check_c(ret, "\0", "\0");
return false;
#endif
}
/* write encryption factor to files */
static bool gen_rand_file(
KeyMode mode, GS_UCHAR* init_rand, const char* user_name, const char* datadir, const char* preStr)
{
int ret;
char randfile[MAXPGPATH] = {0x00};
RandkeyFile rand_file_content;
FILE* pfWrite = NULL;
/*check whether the key mode is valid*/
if (!isModeExists(mode)) {
#ifndef ENABLE_LLT
goto RETURNFALSE;
#endif
}
/*in server_mode,write the files naming with server%*/
if (mode == SERVER_MODE) {
ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/server%s", datadir, RAN_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
} else if (mode == OBS_MODE) {
if (preStr == NULL) {
ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/obsserver%s", datadir, RAN_KEY_FILE);
} else {
ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", datadir, preStr, RAN_KEY_FILE);
}
securec_check_ss_c(ret, "\0", "\0");
} else if (mode == SOURCE_MODE) {
ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/datasource%s", datadir, RAN_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
}
/*in client_mode,check with the user name is appointed.if so, write the files naming
with %user_name%,if not,write files naming with client%*/
else if (mode == CLIENT_MODE) {
if (user_name == NULL) {
ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/client%s", datadir, RAN_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
} else {
ret = snprintf_s(randfile, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", datadir, user_name, RAN_KEY_FILE);
securec_check_ss_c(ret, "\0", "\0");
}
}
CopyRand(init_rand, &rand_file_content);
if (!WriteContentToFile(randfile, (const void*)&rand_file_content, sizeof(RandkeyFile))) {
#ifndef ENABLE_LLT
goto RETURNFALSE;
#endif
}
/*
* Change the privileges: include read & write
* Note: it should be checked by OM tool: gs_ec.
*/
if (mode == SOURCE_MODE || mode == CLIENT_MODE || mode == SERVER_MODE || mode == OBS_MODE) {
/*open and write file*/
if ((pfWrite = fopen(randfile, "r")) == NULL) {
(void)fprintf(stderr, _("could not open file \"%s\" for writing: %s\n"), randfile, gs_strerror(errno));
return false;
}
#ifdef WIN32
ret = _chmod(randfile, 0600);
#else
ret = fchmod(pfWrite->_fileno, 0600);
#endif
if (fclose(pfWrite)) {
(void)fprintf(stderr, _("could not close file \"%s\": %s\n"), randfile, gs_strerror(errno));
return false;
}
if (ret != 0) {
(void)fprintf(stderr, _("could not set permissions of file \"%s\": %s\n"), randfile, gs_strerror(errno));
return false;
}
}
/*
* Empty rand_file_content.
* This is useful. Although rand_file_content is in stack,
* we should manually clear it.
*/
ret = memset_s((void*)&rand_file_content, sizeof(RandkeyFile), 0, sizeof(RandkeyFile));
securec_check_c(ret, "\0", "\0");
return true;
#ifndef ENABLE_LLT
RETURNFALSE:
/*
* Empty rand_file_content.
* This is useful. Although rand_file_content is in stack,
* we should manually clear it.
*/
ret = memset_s((void*)&rand_file_content, sizeof(RandkeyFile), 0, sizeof(RandkeyFile));
securec_check_c(ret, "\0", "\0");
return false;
#endif
}
/*
* generate the files of cipher text and encryption factor
* Notice: preStr is only used by OBS
*/
int gen_cipher_rand_files(
KeyMode mode, const char* plain_key, const char* user_name, const char* datadir, const char* preStr)
{
int retval = 0;
GS_UCHAR init_rand[RANDOM_LEN] = {0};
GS_UCHAR server_vector[RANDOM_LEN] = {'\0'};
GS_UCHAR client_vector[RANDOM_LEN] = {'\0'};
retval = RAND_priv_bytes(init_rand, RANDOM_LEN);
if (retval != 1) {
(void)fprintf(stderr, _("generate random key failed,errcode:%d\n"), retval);
return 1;
}
if (mode == SERVER_MODE || mode == SOURCE_MODE || mode == OBS_MODE) {
init_vector_random(server_vector, RANDOM_LEN);
} else if (mode == CLIENT_MODE) {
init_vector_random(client_vector, RANDOM_LEN);
} else {
(void)fprintf(stderr, _("generate cipher file failed, unknown mode:%d.\n"), mode);
return 1;
}
if (!gen_cipher_file(mode, init_rand, server_vector, client_vector, plain_key, user_name, datadir, preStr)) {
#ifndef ENABLE_LLT
(void)fprintf(stderr, _("generate cipher file failed.\n"));
return 1;
#endif
}
if (!gen_rand_file(mode, init_rand, user_name, datadir, preStr)) {
#ifndef ENABLE_LLT
(void)fprintf(stderr, _("generate random parameter file failed.\n"));
return 1;
#endif
}
return 0;
}
/* check whether the character is special characters */
static bool IsSpecialCharacter(char ch)
{
const char* spec_letters = "~!@#$%^&*()-_=+\\|[{}];:,<.>/?";
const char* ptr = spec_letters;
while (*ptr != '\0') {
if (*ptr == ch) {
return true;
}
ptr++;
}
return false;
}
/*
* @Brief : long check_certificate_time()
* @Description : check the time of the certificate.
* @return : return the number of seconds when the certificate expires less than alarm_days.
*/
long check_certificate_time(const SSL_CTX* SSL_context, const int alarm_days)
{
if (SSL_context == NULL) {
return 0;
}
X509* pstCertificate = SSL_CTX_get0_certificate(SSL_context);
if (pstCertificate != NULL) {
int pday = 0;
int psec = 0;
const ASN1_TIME* notafter = NULL;
/* Get the notafter time form this certificate.*/
notafter = X509_get0_notAfter(pstCertificate);
if (notafter == NULL) {
return 0;
}
int retval = ASN1_TIME_diff(&pday, &psec, NULL, notafter);
if (retval == 0) {
return 0;
}
/* Compare localTime with notafter.*/
if (pday < alarm_days && pday >= 0) {
int diff = pday * 24 * 60 * 60 + psec;
return diff;
}
}
return 0;
}
/* get_evp_cipher_by_id: if you need to be use,you can add some types */
const EVP_CIPHER* get_evp_cipher_by_id(GS_UINT32 ulAlgType)
{
const EVP_CIPHER* cipher = NULL;
switch (ulAlgType & 0xFFFF) {
case NID_aes_128_cbc:
cipher = EVP_aes_128_cbc();
break;
case NID_aes_256_cbc:
cipher = EVP_aes_256_cbc();
break;
case NID_undef:
cipher = EVP_enc_null();
break;
default:
break;
}
return cipher;
}
/* get_evp_md_by_id: if you need to be use,you can add some types */
const EVP_MD* get_evp_md_by_id(GS_UINT32 ulAlgType)
{
const EVP_MD* md = NULL;
switch (ulAlgType & 0xFFFF) {
case NID_sha1:
case NID_hmac_sha1:
md = EVP_sha1();
break;
case NID_sha256:
case NID_hmacWithSHA256:
md = EVP_sha256();
break;
case NID_undef:
md = EVP_md_null();
break;
default:
break;
}
return md;
}
/*
* @Brief : GS_UINT32 CRYPT_encrypt()
* @Description : encrypts plain text to cipher text using encryption algorithm.
* It creates symmetric context by creating algorithm object, padding object,
* opmode object.After encryption, symmetric context needs to be freed.
* @return : success: 0, failed: 1.
*
* @Notes : the last block is not full. so here need to padding the last block.(the block size is an algorithm-related
*parameter) 1.here *ISO/IEC 7816-4* padding method is adoptted: the first byte uses "0x80" to padding ,and the others
*uses "0x00". Example(in the following example the block size is 8 bytes): when the last block is not full: The last
*block has 4 bytes, so four bytes need to be filled
* ... | DD DD DD DD DD DD DD DD | DD DD DD DD 80 00 00 00 |
* when the last block is full: here need to add a new block
* ... | DD DD DD DD DD DD DD DD | 80 00 00 00 00 00 00 00 |
* 2.Default padding method of OPENSSL(this method is closed at here): Each byte is filled with the number of
*remaining bytes Example(in the following example the block size is 8 bytes): when the last block is not full: The last
*block has 4 bytes, so four bytes need to be filled
* ... | DD DD DD DD DD DD DD DD | DD DD DD DD 04 04 04 04 |
* when the last block is full: here need to add a new block
* ... | DD DD DD DD DD DD DD DD | 08 08 08 08 08 08 08 08 |
*/
GS_UINT32 CRYPT_encrypt(GS_UINT32 ulAlgId, const GS_UCHAR* pucKey, GS_UINT32 ulKeyLen, const GS_UCHAR* pucIV,
GS_UINT32 ulIVLen, GS_UCHAR* pucPlainText, GS_UINT32 ulPlainLen, GS_UCHAR* pucCipherText, GS_UINT32* pulCLen)
{
EVP_CIPHER_CTX* ctx = NULL;
const EVP_CIPHER* cipher = NULL;
int enc_num = 0;
int blocksize = 0;
int padding_size = 0;
int nInbufferLen = 0;
errno_t rc = EOK;
unsigned char* pchInbuffer = NULL;
if (pucPlainText == NULL) {
(void)fprintf(stderr, ("invalid plain text,please check it!\n"));
return 1;
}
cipher = get_evp_cipher_by_id(ulAlgId);
if (cipher == NULL) {
(void)fprintf(stderr, ("invalid ulAlgType for cipher,please check it!\n"));
return 1;
}
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
(void)fprintf(stderr, ("ERROR in EVP_CIPHER_CTX_new:\n"));
return 1;
}
EVP_CipherInit_ex(ctx, cipher, NULL, pucKey, pucIV, 1);
/* open padding mode */
EVP_CIPHER_CTX_set_padding(ctx, 1);
/* handling the last block */
blocksize = EVP_CIPHER_CTX_block_size(ctx);
if (blocksize == 0) {
(void)fprintf(stderr, ("invalid blocksize, ERROR in EVP_CIPHER_CTX_block_size\n"));
EVP_CIPHER_CTX_free(ctx);
return 1;
}
nInbufferLen = ulPlainLen % blocksize;
padding_size = blocksize - nInbufferLen;
pchInbuffer = (unsigned char*)OPENSSL_malloc(blocksize);
if (pchInbuffer == NULL) {
(void)fprintf(stderr, _("malloc failed\n"));
EVP_CIPHER_CTX_free(ctx);
return 1;
}
/* the first byte uses "0x80" to padding ,and the others uses "0x00" */
rc = memcpy_s(pchInbuffer, blocksize, pucPlainText + (ulPlainLen - nInbufferLen), nInbufferLen);
securec_check_c(rc, "\0", "\0");
rc = memset_s(pchInbuffer + nInbufferLen, padding_size, 0, padding_size);
securec_check_c(rc, "\0", "\0");
pchInbuffer[nInbufferLen] = 0x80;
/* close padding mode, default padding method of OPENSSL is forbidden */
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_EncryptUpdate(ctx, pucCipherText, &enc_num, pucPlainText, ulPlainLen - nInbufferLen)) {
(void)fprintf(stderr, ("ERROR in EVP_EncryptUpdate\n"));
goto err;
}
*pulCLen = enc_num;
if (!EVP_EncryptUpdate(ctx, pucCipherText + enc_num, &enc_num, pchInbuffer, blocksize)) {
(void)fprintf(stderr, ("ERROR in EVP_EncryptUpdate\n"));
goto err;
}
*pulCLen += enc_num;
if (!EVP_EncryptFinal(ctx, pucCipherText + *pulCLen, &enc_num)) {
(void)fprintf(stderr, ("ERROR in EVP_EncryptUpdate\n"));
goto err;
}
*pulCLen += enc_num;
rc = memset_s(pchInbuffer, blocksize, 0, blocksize);
securec_check_c(rc, "\0", "\0");
OPENSSL_free(pchInbuffer);
EVP_CIPHER_CTX_free(ctx);
return 0;
err:
rc = memset_s(pchInbuffer, blocksize, 0, blocksize);
securec_check_c(rc, "\0", "\0");
OPENSSL_free(pchInbuffer);
EVP_CIPHER_CTX_free(ctx);
return 1;
}
/*
* @Brief : GS_UINT32 CRYPT_decrypt()
* @Description : decrypts cipher text to plain text using decryption algorithm.
* It creates symmetric context by creating algorithm object, padding object,
* opmode object. After decryption, symmetric context needs to be freed.
* @return : success: 0, failed: 1.
*
* @Notes : the last block is not full. so here need to padding the last block.(the block size is an
*algorithm-related parameter) 1.here *ISO/IEC 7816-4* padding method is adoptted: the first byte uses "0x80" to padding
*,and the others uses "0x00". Example(in the following example the block size is 8 bytes): when the last block is not
*full: The last block has 4 bits,so padding is required for 4 bytes
* ... | DD DD DD DD DD DD DD DD | DD DD DD DD 80 00 00 00 |
* when the last block is full: here need to add a new block
* ... | DD DD DD DD DD DD DD DD | 80 00 00 00 00 00 00 00 |
*/
GS_UINT32 CRYPT_decrypt(GS_UINT32 ulAlgId, const GS_UCHAR* pucKey, GS_UINT32 ulKeyLen, const GS_UCHAR* pucIV,
GS_UINT32 ulIVLen, GS_UCHAR* pucCipherText, GS_UINT32 ulCLen, GS_UCHAR* pucPlainText, GS_UINT32* pulPLen)
{
EVP_CIPHER_CTX* ctx = NULL;
const EVP_CIPHER* cipher = NULL;
int dec_num = 0;
unsigned int blocksize;
unsigned int oLen;
if (pucCipherText == NULL) {
(void)fprintf(stderr, ("invalid plain text,please check it!\n"));
return 1;
}
cipher = get_evp_cipher_by_id(ulAlgId);
if (cipher == NULL) {
(void)fprintf(stderr, ("invalid ulAlgType for cipher,please check it!\n"));
return 1;
}
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
(void)fprintf(stderr, ("ERROR in EVP_CIPHER_CTX_new:\n"));
return 1;
}
EVP_CipherInit_ex(ctx, cipher, NULL, pucKey, pucIV, 0);
EVP_CIPHER_CTX_set_padding(ctx, 0);
if (!EVP_DecryptUpdate(ctx, pucPlainText, &dec_num, pucCipherText, ulCLen)) {
(void)fprintf(stderr, ("ERROR in EVP_DecryptUpdate\n"));
goto err;
}
*pulPLen = dec_num;
if (!EVP_DecryptFinal(ctx, pucPlainText + dec_num, &dec_num)) {
(void)fprintf(stderr, ("ERROR in EVP_DecryptFinal\n"));
goto err;
}
*pulPLen += dec_num;
/* padding bytes of the last block need to be removed */
blocksize = EVP_CIPHER_CTX_block_size(ctx);
oLen = (*pulPLen) - 1;
while (*(pucPlainText + oLen) == 0) {
oLen--;
}
if (oLen >= ((*pulPLen) - blocksize) && *(pucPlainText + oLen) == 0x80) {
(*pulPLen) = oLen;
} else {
goto err;
}
pucPlainText[oLen] = '\0';
EVP_CIPHER_CTX_free(ctx);
return 0;
err:
EVP_CIPHER_CTX_free(ctx);
return 1;
}
/*
* @Brief : GS_UINT32 CRYPT_hmac()
* @Description : computes hmac of a given data block. Calls init, update, and final.
* This function is used when data is present all at once. There is no need of calling
* Init, Update, Final and MAC can be calculated in one go. Context is not needed here.
* @return : success:1, failed:0.
*/
GS_UINT32 CRYPT_hmac(GS_UINT32 ulAlgType, const GS_UCHAR* pucKey, GS_UINT32 upucKeyLen, const GS_UCHAR* pucData,
GS_UINT32 ulDataLen, GS_UCHAR* pucDigest, GS_UINT32* pulDigestLen)
{
const EVP_MD* evp_md = get_evp_md_by_id(ulAlgType);
if (evp_md == NULL) {
return 1;
}
#ifndef WIN32
if (!HMAC(evp_md, pucKey, (int)upucKeyLen, pucData, ulDataLen, pucDigest, pulDigestLen)) {
return 1;
}
#else
if (!HMAC(evp_md, pucKey, (int)upucKeyLen, pucData, ulDataLen, pucDigest, (unsigned int*)pulDigestLen)) {
return 1;
}
#endif
return 0;
}
| 34.306931 | 120 | 0.631775 | [
"object",
"vector"
] |
b13bf7573e49b618d79bc71c21aac8708b54aa0a | 9,180 | cc | C++ | ash/ambient/model/ambient_backend_model.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/ambient/model/ambient_backend_model.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ash/ambient/model/ambient_backend_model.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/ambient/model/ambient_backend_model.h"
#include <algorithm>
#include <random>
#include <utility>
#include <vector>
#include "ash/ambient/model/ambient_backend_model_observer.h"
#include "ash/ambient/model/ambient_photo_config.h"
#include "ash/public/cpp/ambient/ambient_ui_model.h"
#include "base/check.h"
#include "base/containers/flat_map.h"
#include "base/logging.h"
namespace ash {
namespace {
int TypeToIndex(::ambient::TopicType topic_type) {
int index = static_cast<int>(topic_type);
DCHECK_GE(index, 0);
return index;
}
::ambient::TopicType IndexToType(int index) {
::ambient::TopicType topic_type = static_cast<::ambient::TopicType>(index);
return topic_type;
}
std::vector<AmbientModeTopic> CreatePairedTopics(
const std::vector<AmbientModeTopic>& topics) {
// We pair two topics if:
// 1. They are in the landscape orientation.
// 2. They are in the same category.
// 3. They are not Geo photos.
base::flat_map<int, std::vector<int>> topics_by_type;
std::vector<AmbientModeTopic> paired_topics;
int topic_idx = -1;
for (const auto& topic : topics) {
topic_idx++;
// Do not pair Geo photos, which will be rotate to fill the screen.
// If a photo is portrait, it is from Google Photos and should have a paired
// photo already.
if (topic.topic_type == ::ambient::TopicType::kGeo || topic.is_portrait) {
paired_topics.emplace_back(topic);
continue;
}
int type_index = TypeToIndex(topic.topic_type);
auto it = topics_by_type.find(type_index);
if (it == topics_by_type.end()) {
topics_by_type.insert({type_index, {topic_idx}});
} else {
it->second.emplace_back(topic_idx);
}
}
// We merge two unpaired topics to create a new topic with related images.
for (auto it = topics_by_type.begin(); it < topics_by_type.end(); ++it) {
size_t idx = 0;
while (idx < it->second.size() - 1) {
AmbientModeTopic paired_topic;
const auto& topic_1 = topics[it->second[idx]];
const auto& topic_2 = topics[it->second[idx + 1]];
paired_topic.url = topic_1.url;
paired_topic.related_image_url = topic_2.url;
paired_topic.details = topic_1.details;
paired_topic.related_details = topic_2.details;
paired_topic.topic_type = IndexToType(it->first);
paired_topic.is_portrait = topic_1.is_portrait;
paired_topics.emplace_back(paired_topic);
idx += 2;
}
}
std::shuffle(paired_topics.begin(), paired_topics.end(),
std::default_random_engine());
return paired_topics;
}
std::pair<AmbientModeTopic, AmbientModeTopic> SplitTopic(
const AmbientModeTopic& paired_topic) {
const auto clear_related_fields_from_topic = [](AmbientModeTopic& topic) {
topic.related_image_url.clear();
topic.related_details.clear();
};
AmbientModeTopic topic_with_primary(paired_topic);
clear_related_fields_from_topic(topic_with_primary);
AmbientModeTopic topic_with_related(paired_topic);
topic_with_related.url = std::move(topic_with_related.related_image_url);
topic_with_related.details = std::move(topic_with_related.related_details);
clear_related_fields_from_topic(topic_with_related);
return std::make_pair(topic_with_primary, topic_with_related);
}
} // namespace
// PhotoWithDetails------------------------------------------------------------
PhotoWithDetails::PhotoWithDetails() = default;
PhotoWithDetails::PhotoWithDetails(const PhotoWithDetails&) = default;
PhotoWithDetails& PhotoWithDetails::operator=(const PhotoWithDetails&) =
default;
PhotoWithDetails::PhotoWithDetails(PhotoWithDetails&&) = default;
PhotoWithDetails& PhotoWithDetails::operator=(PhotoWithDetails&&) = default;
PhotoWithDetails::~PhotoWithDetails() = default;
void PhotoWithDetails::Clear() {
photo = gfx::ImageSkia();
details = std::string();
related_photo = gfx::ImageSkia();
related_details = std::string();
is_portrait = false;
}
bool PhotoWithDetails::IsNull() const {
return photo.isNull();
}
// AmbientBackendModel---------------------------------------------------------
AmbientBackendModel::AmbientBackendModel(AmbientPhotoConfig photo_config)
: photo_config_(std::move(photo_config)) {
DCHECK_GT(photo_config_.GetNumDecodedTopicsToBuffer(), 0u);
}
AmbientBackendModel::~AmbientBackendModel() = default;
void AmbientBackendModel::AddObserver(AmbientBackendModelObserver* observer) {
observers_.AddObserver(observer);
}
void AmbientBackendModel::RemoveObserver(
AmbientBackendModelObserver* observer) {
observers_.RemoveObserver(observer);
}
void AmbientBackendModel::AppendTopics(
const std::vector<AmbientModeTopic>& topics_in) {
if (photo_config_.should_split_topics) {
static constexpr int kMaxImagesPerTopic = 2;
topics_.reserve(topics_.size() + kMaxImagesPerTopic * topics_in.size());
for (const AmbientModeTopic& topic : topics_in) {
if (topic.related_image_url.empty()) {
topics_.push_back(topic);
} else {
std::pair<AmbientModeTopic, AmbientModeTopic> split_topic =
SplitTopic(topic);
topics_.push_back(std::move(split_topic.first));
topics_.push_back(std::move(split_topic.second));
}
}
} else {
std::vector<AmbientModeTopic> related_topics =
CreatePairedTopics(topics_in);
topics_.insert(topics_.end(), related_topics.begin(), related_topics.end());
}
NotifyTopicsChanged();
}
bool AmbientBackendModel::ImagesReady() const {
DCHECK_LE(all_decoded_topics_.size(),
photo_config_.GetNumDecodedTopicsToBuffer());
// TODO(esum): Add a timeout (ex: 10 seconds) for the animated screensaver,
// after which we just start the UI anyways if at least 1 topic is buffered
// (duplicating that topic in the animation).
return all_decoded_topics_.size() ==
photo_config_.GetNumDecodedTopicsToBuffer();
}
void AmbientBackendModel::AddNextImage(
const PhotoWithDetails& photo_with_details) {
DCHECK(!photo_with_details.IsNull());
DCHECK(!photo_config_.should_split_topics ||
photo_with_details.related_photo.isNull());
ResetImageFailures();
bool old_images_ready = ImagesReady();
all_decoded_topics_.push_back(photo_with_details);
while (all_decoded_topics_.size() >
photo_config_.GetNumDecodedTopicsToBuffer()) {
DCHECK(!all_decoded_topics_.empty());
all_decoded_topics_.pop_front();
}
NotifyImageAdded();
// Observers expect |OnImagesReady| after |OnImageAdded|.
bool new_images_ready = ImagesReady();
if (!old_images_ready && new_images_ready) {
NotifyImagesReady();
}
}
bool AmbientBackendModel::IsHashDuplicate(const std::string& hash) const {
// Make sure that a photo does not appear twice in a row.
return all_decoded_topics_.empty() ? false
: all_decoded_topics_.back().hash == hash;
}
void AmbientBackendModel::AddImageFailure() {
failures_++;
if (ImageLoadingFailed()) {
DVLOG(3) << "image loading failed";
for (auto& observer : observers_)
observer.OnImagesFailed();
}
}
void AmbientBackendModel::ResetImageFailures() {
failures_ = 0;
}
bool AmbientBackendModel::ImageLoadingFailed() {
return !ImagesReady() && failures_ >= kMaxConsecutiveReadPhotoFailures;
}
base::TimeDelta AmbientBackendModel::GetPhotoRefreshInterval() const {
if (!ImagesReady())
return base::TimeDelta();
return AmbientUiModel::Get()->photo_refresh_interval();
}
void AmbientBackendModel::Clear() {
topics_.clear();
all_decoded_topics_.clear();
}
void AmbientBackendModel::GetCurrentAndNextImages(
PhotoWithDetails* current_image_out,
PhotoWithDetails* next_image_out) const {
auto fill_image_out = [&](size_t idx, PhotoWithDetails* image_out) {
if (!image_out)
return;
image_out->Clear();
if (idx < all_decoded_topics_.size()) {
*image_out = all_decoded_topics_[idx];
}
};
fill_image_out(/*idx=*/0, current_image_out);
fill_image_out(/*idx=*/1, next_image_out);
}
float AmbientBackendModel::GetTemperatureInCelsius() const {
return (temperature_fahrenheit_ - 32) * 5 / 9;
}
void AmbientBackendModel::UpdateWeatherInfo(
const gfx::ImageSkia& weather_condition_icon,
float temperature_fahrenheit,
bool show_celsius) {
weather_condition_icon_ = weather_condition_icon;
temperature_fahrenheit_ = temperature_fahrenheit;
show_celsius_ = show_celsius;
if (!weather_condition_icon.isNull())
NotifyWeatherInfoUpdated();
}
void AmbientBackendModel::NotifyTopicsChanged() {
for (auto& observer : observers_)
observer.OnTopicsChanged();
}
void AmbientBackendModel::NotifyImageAdded() {
for (auto& observer : observers_)
observer.OnImageAdded();
}
void AmbientBackendModel::NotifyImagesReady() {
for (auto& observer : observers_)
observer.OnImagesReady();
}
void AmbientBackendModel::NotifyWeatherInfoUpdated() {
for (auto& observer : observers_)
observer.OnWeatherInfoUpdated();
}
} // namespace ash
| 31.013514 | 80 | 0.719063 | [
"vector",
"model"
] |
b13c23f763841214887f85150c4be508a0d79546 | 15,807 | cc | C++ | modules/planning/math/smoothing_spline/spline_1d_constraint_test.cc | fxbupt/apollo | 65bda57aa2f01b045ecf9cff95d9e6fd80ed091f | [
"Apache-2.0"
] | 1 | 2021-03-08T06:35:35.000Z | 2021-03-08T06:35:35.000Z | modules/planning/math/smoothing_spline/spline_1d_constraint_test.cc | fxbupt/apollo | 65bda57aa2f01b045ecf9cff95d9e6fd80ed091f | [
"Apache-2.0"
] | null | null | null | modules/planning/math/smoothing_spline/spline_1d_constraint_test.cc | fxbupt/apollo | 65bda57aa2f01b045ecf9cff95d9e6fd80ed091f | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2017 The Apollo 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.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/math/smoothing_spline/spline_1d_constraint.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace apollo {
namespace planning {
TEST(Spline1dConstraint, add_boundary) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 6;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0};
std::vector<double> lower_bound = {1.0, 1.0, 1.0};
std::vector<double> upper_bound = {5.0, 5.0, 5.0};
constraint.AddBoundary(x_coord, lower_bound, upper_bound);
const auto mat = constraint.inequality_constraint().constraint_matrix();
const auto boundary =
constraint.inequality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6);
ref_mat <<
1, 0, 0, 0, 0, 0,
1, 0.5, 0.25, 0.125, 0.0625, 0.03125,
1, 1, 1, 1, 1, 1,
-1, -0, -0, -0, -0, -0,
-1, -0.5, -0.25, -0.125, -0.0625, -0.03125,
-1, -1, -1, -1, -1, -1;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1);
ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0;
for (int i = 0; i < ref_boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0));
}
}
TEST(Spline1dConstraint, add_derivative_boundary) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 6;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0};
std::vector<double> lower_bound = {1.0, 1.0, 1.0};
std::vector<double> upper_bound = {5.0, 5.0, 5.0};
constraint.AddDerivativeBoundary(x_coord, lower_bound, upper_bound);
const auto mat = constraint.inequality_constraint().constraint_matrix();
const auto boundary =
constraint.inequality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6);
ref_mat <<
0, 1, 0, 0, 0, 0,
0, 1, 1, 0.75, 0.5, 0.3125,
0, 1, 2, 3, 4, 5,
0, -1, -0, -0, -0, -0,
0, -1, -1, -0.75, -0.5, -0.3125,
0, -1, -2, -3, -4, -5;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1);
ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0;
for (int i = 0; i < ref_boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0));
}
}
TEST(Spline1dConstraint, add_second_derivative_boundary) {
std::vector<double> x_knots = {0.0, 1.0};
int32_t spline_order = 6;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0};
std::vector<double> lower_bound = {1.0, 1.0, 1.0};
std::vector<double> upper_bound = {5.0, 5.0, 5.0};
constraint.AddSecondDerivativeBoundary(x_coord, lower_bound, upper_bound);
const auto mat = constraint.inequality_constraint().constraint_matrix();
const auto boundary =
constraint.inequality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6);
ref_mat <<
0, 0, 2, 0, 0, 0,
0, 0, 2, 3, 3, 2.5,
0, 0, 2, 6, 12, 20,
0, 0, -2, -0, -0, -0,
0, 0, -2, -3, -3, -2.5,
0, 0, -2, -6, -12, -20;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1);
ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0;
for (int i = 0; i < ref_boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0));
}
}
TEST(Spline1dConstraint, add_smooth_constraint_01) {
std::vector<double> x_knots = {0.0, 1.0, 2.0};
int32_t spline_order = 6;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddSmoothConstraint();
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 12);
ref_mat << 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_smooth_constraint_02) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 6;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddSmoothConstraint();
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(2, 18);
// clang-format off
ref_mat <<
1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_derivative_smooth_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddDerivativeSmoothConstraint();
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 12);
ref_mat <<
1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0,
0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0,
0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_second_derivative_smooth_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 4;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddSecondDerivativeSmoothConstraint();
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 12);
ref_mat <<
1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0,
0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0,
0, 0, 2, 6, 0, 0, -2, -0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0,
0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0,
0, 0, 0, 0, 0, 0, 2, 6, 0, 0, -2, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_third_derivative_smooth_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddThirdDerivativeSmoothConstraint();
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(8, 15);
ref_mat <<
1, 1, 1, 1, 1, -1, -0, -0, -0, -0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 0, -1, -0, -0, -0, 0, 0, 0, 0, 0,
0, 0, 2, 6, 12, 0, 0, -2, -0, -0, 0, 0, 0, 0, 0,
0, 0, 0, 6, 24, 0, 0, 0, -6, -0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0,
0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, -1, -0, -0, -0,
0, 0, 0, 0, 0, 0, 0, 2, 6, 12, 0, 0, -2, -0, -0,
0, 0, 0, 0, 0, 0, 0, 0, 6, 24, 0, 0, 0, -6, -0;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_monotone_inequality_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
std::vector<double> x_coord = {0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
constraint.AddMonotoneInequalityConstraint(x_coord);
const auto mat = constraint.inequality_constraint().constraint_matrix();
const auto boundary =
constraint.inequality_constraint().constraint_boundary();
// clang-format off
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 15);
ref_mat <<
0, 0.5, 0.25, 0.125, 0.0625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
-1, -0.5, -0.25, -0.125, -0.0625, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0.5, 0.25, 0.125, 0.0625, 0, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, -1, -0.5, -0.25, -0.125, -0.0625, 1, 0, 0, 0, 0, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.25, 0.125, 0.0625, // NOLINT
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.75, 0.875, 0.9375; // NOLINT
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_monotone_inequality_constraint_at_knots) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddMonotoneInequalityConstraintAtKnots();
const auto mat = constraint.inequality_constraint().constraint_matrix();
const auto boundary =
constraint.inequality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(3, 15);
// clang-format off
ref_mat <<
-1, -0, -0, -0, -0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -1, -0, -0, -0, -0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1;
// clang-format on
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
for (int i = 0; i < boundary.rows(); ++i) {
EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0);
}
}
TEST(Spline1dConstraint, add_point_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointConstraint(2.5, 12.3);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.5, 0.25, 0.125, 0.0625;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 12.3);
}
TEST(Spline1dConstraint, add_point_derivative_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointDerivativeConstraint(2.5, 1.23);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0, 1.0, 0.75, 0.5;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 1.23);
}
TEST(Spline1dConstraint, add_point_second_derivative_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointSecondDerivativeConstraint(2.5, 1.23);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.0, 3.0, 3.0;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 1.23);
}
TEST(Spline1dConstraint, add_point_third_derivative_constraint) {
std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0};
int32_t spline_order = 5;
Spline1dConstraint constraint(x_knots, spline_order);
constraint.AddPointThirdDerivativeConstraint(2.5, 1.23);
const auto mat = constraint.equality_constraint().constraint_matrix();
const auto boundary = constraint.equality_constraint().constraint_boundary();
Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 15);
ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6.0, 12.0;
for (int i = 0; i < mat.rows(); ++i) {
for (int j = 0; j < mat.cols(); ++j) {
EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j));
}
}
EXPECT_EQ(boundary.rows(), 1);
EXPECT_DOUBLE_EQ(boundary(0, 0), 1.23);
}
} // namespace planning
} // namespace apollo
| 35.843537 | 144 | 0.565003 | [
"vector"
] |
b13d3b0e14a9aef07555b6b69b246df19693529c | 2,529 | cpp | C++ | src/Verde/Chunk.cpp | Cannedfood/Verde2D | 3a09e2ecc6b62281e5190183faef55c8f0447d27 | [
"CC0-1.0"
] | null | null | null | src/Verde/Chunk.cpp | Cannedfood/Verde2D | 3a09e2ecc6b62281e5190183faef55c8f0447d27 | [
"CC0-1.0"
] | null | null | null | src/Verde/Chunk.cpp | Cannedfood/Verde2D | 3a09e2ecc6b62281e5190183faef55c8f0447d27 | [
"CC0-1.0"
] | null | null | null | #include "Chunk.hpp"
#include "graphics/Texture.hpp"
#include "Level.hpp"
#include <algorithm>
void Chunk::init(Level* l) {
mLevel = l;
}
std::unique_ptr<Object> Chunk::remove(Object* o) {
std::unique_ptr<Object> result;
for(size_t i = 0; i < mObjects.size(); i++) {
if(mObjects[i].get() == o) {
result = std::move(mObjects[i]);
mObjects.erase(mObjects.begin() + i);
break;
}
}
return result;
}
Object* Chunk::add(std::unique_ptr<Object>&& o, int type) {
mLevel->addObject(o.get(), type);
mObjects.emplace_back(std::move(o));
return mObjects.back().get();
}
Chunk* Chunk::createChunk() {
mChunks.emplace_back(new Chunk);
mChunks.back()->mLevel = mLevel;
mChunks.back()->mParentChunk = this;
return mChunks.back().get();
}
void Chunk::_removeFromParent() {
if(mParentChunk) {
mParentChunk->mChunks.erase(
std::find_if(
mParentChunk->mChunks.begin(),
mParentChunk->mChunks.end(),
[this](auto& a) { return a.get() == this; }
)
);
}
}
void Chunk::removeChunk(Chunk* c) {
assert(c);
assert(c->mParentChunk == this);
c->_removeFromParent();
}
void Chunk::offset(const glm::vec2& p) {
for(auto& c : mChunks)
c->offset(p);
mOffset += p;
}
void Chunk::clear() {
mChunks.clear();
mObjects.clear();
}
void Chunk::clean() {
for(auto& a : mChunks) {
a->clean();
}
for (size_t i = 0; i < mChunks.size(); i++) {
if(mChunks[i]->empty()) {
mChunks.erase(mChunks.begin() + i);
i--;
}
}
}
bool Chunk::empty() {
if(!mObjects.empty()) return false;
for(auto& a : mChunks) {
if(!a->empty())
return false;
}
return true;
}
using namespace YAML;
void Chunk::load(YAML::Node n) {
// TODO: fix loading
glm::vec2 offset_total;
if(Node nn = n["offset"]) {
offset_total.x = nn[0].as<float>();
offset_total.y = nn[1].as<float>();
}
if(Node nn = n["file"]) {
Node loaded = LoadFile(nn.as<std::string>());
}
if(Node nn = n["objects"]) {
mObjects.clear();
for(Node o : nn) {
mObjects.emplace_back(new Object);
mObjects.back()->load(o);
mObjects.back()->mPosition += mOffset;
mLevel->addObject(mObjects.back().get());
}
}
}
void Chunk::save(YAML::Emitter& e) {
glm::vec2 old_offset = mOffset;
offset(-mOffset);
e << BeginMap;
if(mOffset.x != 0 || mOffset.y != 0) {
e << Key << "offset" << BeginSeq;
e << mOffset.x << mOffset.y;
e << EndSeq;
}
if(!mObjects.empty()) {
e << Key << "objects" << BeginSeq;
for(auto& a : mObjects)
a->save(e);
e << EndSeq;
}
e << EndMap;
offset(old_offset);
}
| 18.194245 | 59 | 0.606959 | [
"object"
] |
b13d45e48a2a469fef152b64880045a9c64cfb77 | 72,096 | cpp | C++ | wrappers/matlab/librealsense_mex.cpp | 15901476120/realsense | 90294bca38b4b885d5cf9603a2dda2367b6468d8 | [
"BSD-2-Clause",
"Apache-2.0"
] | 2 | 2020-08-15T18:40:06.000Z | 2021-07-12T04:38:14.000Z | wrappers/matlab/librealsense_mex.cpp | 15901476120/realsense | 90294bca38b4b885d5cf9603a2dda2367b6468d8 | [
"BSD-2-Clause",
"Apache-2.0"
] | 6 | 2018-06-17T19:28:03.000Z | 2021-09-09T14:29:25.000Z | wrappers/matlab/librealsense_mex.cpp | 15901476120/realsense | 90294bca38b4b885d5cf9603a2dda2367b6468d8 | [
"BSD-2-Clause",
"Apache-2.0"
] | 4 | 2020-01-31T14:28:29.000Z | 2022-01-18T05:43:28.000Z | #include "MatlabParamParser.h"
#include "Factory.h"
#include "librealsense2/rs.hpp"
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmex.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "realsense2.lib")
Factory *factory;
void make_factory(){
factory = new Factory();
// rs_frame.hpp
{
ClassFactory stream_profile_factory("rs2::stream_profile");
stream_profile_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::stream_profile());
});
stream_profile_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::stream_profile>(inv[0]);
});
stream_profile_factory.record("stream_index", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.stream_index());
});
stream_profile_factory.record("stream_type", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.stream_type());
});
stream_profile_factory.record("format", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.format());
});
stream_profile_factory.record("fps", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.fps());
});
stream_profile_factory.record("unique_id", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.unique_id());
});
stream_profile_factory.record("clone", 1, 4, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
auto type = MatlabParamParser::parse<rs2_stream>(inv[1]);
auto index = MatlabParamParser::parse<int>(inv[2]);
auto format = MatlabParamParser::parse<rs2_format>(inv[3]);
outv[0] = MatlabParamParser::wrap(thiz.clone(type, index, format));
});
stream_profile_factory.record("operator==", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto rhs = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
auto lhs = MatlabParamParser::parse<rs2::stream_profile>(inv[1]);
MatlabParamParser::wrap(rhs == lhs);
});
stream_profile_factory.record("is", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "stream_profile")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::stream_profile>());
else if (type == "video_stream_profile")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::video_stream_profile>());
else if (type == "motion_stream_profile")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::motion_stream_profile>());
else {
mexWarnMsgTxt("rs2::stream_profile::is: invalid type parameter");
outv[0] = MatlabParamParser::wrap(false);
}
});
stream_profile_factory.record("as", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "stream_profile")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::stream_profile>());
else if (type == "video_stream_profile")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::video_stream_profile>());
else if (type == "motion_stream_profile")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::motion_stream_profile>());
else {
mexWarnMsgTxt("rs2::stream_profile::as: invalid type parameter");
outv[0] = MatlabParamParser::wrap(uint64_t(0));
}
});
stream_profile_factory.record("stream_name", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.stream_name());
});
stream_profile_factory.record("is_default", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.is_default());
});
stream_profile_factory.record("operator bool", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(bool(thiz));
});
stream_profile_factory.record("get_extrinsics_to", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
auto to = MatlabParamParser::parse<rs2::stream_profile>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_extrinsics_to(to));
});
// rs2::stream_profile::register_extrinsics_to [?]
stream_profile_factory.record("is_cloned", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.is_cloned());
});
factory->record(stream_profile_factory);
}
{
ClassFactory video_stream_profile_factory("rs2::video_stream_profile");
// rs2::video_stream_profile::constructor(rs2::stream_profile) [?]
video_stream_profile_factory.record("width", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.width());
});
video_stream_profile_factory.record("height", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.height());
});
video_stream_profile_factory.record("get_intrinsics", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_intrinsics());
});
factory->record(video_stream_profile_factory);
}
{
ClassFactory motion_stream_profile_factory("rs2::motion_stream_profile");
// rs2::motion_stream_profile::constructor(rs2::stream_profile) [?]
motion_stream_profile_factory.record("get_motion_intrinsics", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::motion_stream_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_motion_intrinsics());
});
factory->record(motion_stream_profile_factory);
}
{
ClassFactory frame_factory("rs2::frame");
// rs2::frame::constructor() [?]
frame_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::frame>(inv[0]);
});
// rs2::frame::operator= [?/HOW]
// rs2::frame::copy constructor [?/HOW]
// rs2::frame::swap [?/HOW]
// rs2::frame::keep [TODO/HOW]
frame_factory.record("operator bool", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(bool(thiz));
});
frame_factory.record("get_timestamp", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_timestamp());
});
frame_factory.record("get_frame_timestamp_domain", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_frame_timestamp_domain());
});
frame_factory.record("get_frame_metadata", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
auto frame_metadata = MatlabParamParser::parse<rs2_frame_metadata_value>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_frame_metadata(frame_metadata));
});
frame_factory.record("supports_frame_metadata", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
auto frame_metadata = MatlabParamParser::parse<rs2_frame_metadata_value>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.supports_frame_metadata(frame_metadata));
});
frame_factory.record("get_frame_number", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_frame_number());
});
frame_factory.record("get_data", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
size_t n_bytes = 0;
if (auto vf = thiz.as<rs2::video_frame>()) {
n_bytes = vf.get_height() * vf.get_stride_in_bytes();
} // TODO: support more frame types?
switch (thiz.get_profile().format()) {
case RS2_FORMAT_RAW10:
// TODO: Do the bit hackery ourselves?
mexWarnMsgTxt("Raw10 data provided as unsigned byte array.");
case RS2_FORMAT_RGB8: case RS2_FORMAT_RGBA8:
case RS2_FORMAT_BGR8: case RS2_FORMAT_BGRA8:
case RS2_FORMAT_Y8: case RS2_FORMAT_RAW8:
if (n_bytes == 0) {
n_bytes = 1;
mexWarnMsgTxt("Can't detect frame dims, sending only first pixel");
}
outv[0] = MatlabParamParser::wrap_array(reinterpret_cast<const uint8_t*>(thiz.get_data()), n_bytes);
break;
case RS2_FORMAT_Z16: case RS2_FORMAT_DISPARITY16:
case RS2_FORMAT_Y16: case RS2_FORMAT_RAW16:
if (n_bytes == 0) {
n_bytes = 2;
mexWarnMsgTxt("Can't detect frame dims, sending only first pixel");
}
outv[0] = MatlabParamParser::wrap_array(reinterpret_cast<const uint16_t*>(thiz.get_data()), n_bytes / 2);
break;
case RS2_FORMAT_XYZ32F: case RS2_FORMAT_DISPARITY32:
case RS2_FORMAT_MOTION_XYZ32F:
if (n_bytes == 0) {
n_bytes = 4;
mexWarnMsgTxt("Can't detect frame dims, sending only first pixel");
}
outv[0] = MatlabParamParser::wrap_array(reinterpret_cast<const float*>(thiz.get_data()), n_bytes / 4);
break;
case RS2_FORMAT_UYVY: case RS2_FORMAT_YUYV:
if (n_bytes == 0) {
n_bytes = 4;
mexWarnMsgTxt("Can't detect frame dims, sending only first pixel");
}
outv[0] = MatlabParamParser::wrap_array(reinterpret_cast<const uint32_t*>(thiz.get_data()), n_bytes / 4);
break;
default:
mexWarnMsgTxt("This format isn't supported yet. Sending unsigned byte stream");
if (n_bytes == 0) {
n_bytes = 1;
mexWarnMsgTxt("Can't detect frame dims, sending only first pixel");
}
outv[0] = MatlabParamParser::wrap_array(reinterpret_cast<const uint8_t*>(thiz.get_data()), n_bytes);
}
});
frame_factory.record("get_profile", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_profile());
});
frame_factory.record("is", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "frame")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::frame>());
else if (type == "video_frame")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::video_frame>());
else if (type == "points")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::points>());
else if (type == "depth_frame")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::depth_frame>());
else if (type == "disparity_frame")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::disparity_frame>());
else if (type == "motion_frame")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::motion_frame>());
else if (type == "pose_frame")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::pose_frame>());
else if (type == "frameset")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::frameset>());
else {
mexWarnMsgTxt("rs2::frame::is: invalid type parameter");
outv[0] = MatlabParamParser::wrap(false);
}
});
frame_factory.record("as", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::frame>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "frame")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::frame>());
else if (type == "video_frame")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::video_frame>());
else if (type == "points")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::points>());
else if (type == "depth_frame")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::depth_frame>());
else if (type == "disparity_frame")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::disparity_frame>());
else if (type == "motion_frame")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::motion_frame>());
else if (type == "pose_frame")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::pose_frame>());
else if (type == "frameset")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::frameset>());
else {
mexWarnMsgTxt("rs2::frame::as: invalid type parameter");
outv[0] = MatlabParamParser::wrap(uint64_t(0));
}
});
factory->record(frame_factory);
}
{
ClassFactory video_frame_factory("rs2::video_frame");
// rs2::video_frame::constructor() [?]
video_frame_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::video_frame>(inv[0]);
});
video_frame_factory.record("get_width", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_width());
});
video_frame_factory.record("get_height", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_height());
});
video_frame_factory.record("get_stride_in_bytes", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_stride_in_bytes());
});
video_frame_factory.record("get_bits_per_pixel", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_bits_per_pixel());
});
video_frame_factory.record("get_bytes_per_pixel", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::video_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_bytes_per_pixel());
});
factory->record(video_frame_factory);
}
{
ClassFactory points_factory("rs2::points");
// rs2::points::constructor() [?]
// rs2::points::constrcutor(rs2::frame) [?]
points_factory.record("get_vertices", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::points>(inv[0]);
// TODO: turn into matrix instead of column?
outv[0] = MatlabParamParser::wrap_array(thiz.get_vertices(), thiz.size());
});
points_factory.record("export_to_ply", 0, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::points>(inv[0]);
auto fname = MatlabParamParser::parse<std::string>(inv[1]);
auto texture = MatlabParamParser::parse<rs2::video_frame>(inv[2]);
thiz.export_to_ply(fname, texture);
});
points_factory.record("get_texture_coordinates", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::points>(inv[0]);
// TODO: turn into matrix instead of column?
outv[0] = MatlabParamParser::wrap_array(thiz.get_texture_coordinates(), thiz.size());
});
points_factory.record("size", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::points>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.size());
});
factory->record(points_factory);
}
{
ClassFactory depth_frame_factory("rs2::depth_frame");
// rs2::depth_frame::constructor() [?]
depth_frame_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::depth_frame>(inv[0]);
});
depth_frame_factory.record("get_distance", 1, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::depth_frame>(inv[0]);
auto x = MatlabParamParser::parse<int>(inv[1]);
auto y = MatlabParamParser::parse<int>(inv[2]);
outv[0] = MatlabParamParser::wrap(thiz.get_distance(x, y));
});
factory->record(depth_frame_factory);
}
{
ClassFactory disparity_frame_factory("rs2::disparity_frame");
// rs2::disparity_frame::constructor(rs2::frame) [?]
disparity_frame_factory.record("get_baseline", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::disparity_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_baseline());
});
factory->record(disparity_frame_factory);
}
{
ClassFactory motion_frame_factory("rs2::motion_frame");
// rs2::motion_frame::constructor(rs2::frame) [?]
motion_frame_factory.record("get_motion_data", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::motion_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_motion_data());
});
factory->record(motion_frame_factory);
}
{
ClassFactory pose_frame_factory("rs2::pose_frame");
// rs2::pose_frame::constructor(rs2::frame) [?]
pose_frame_factory.record("get_pose_data", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pose_frame>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_pose_data());
});
factory->record(pose_frame_factory);
}
{
ClassFactory frameset_factory("rs2::frameset");
// rs2::frameset::constructor() [?]
// rs2::frameset::constructor(frame) [?]
frameset_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::frameset>(inv[0]);
});
frameset_factory.record("first_or_default", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frameset>(inv[0]);
auto s = MatlabParamParser::parse<rs2_stream>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.first_or_default(s));
});
frameset_factory.record("first", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frameset>(inv[0]);
auto s = MatlabParamParser::parse<rs2_stream>(inv[1]);
// try/catch moved to outer framework
outv[0] = MatlabParamParser::wrap(thiz.first(s));
});
frameset_factory.record("get_depth_frame", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frameset>(inv[0]);
// try/catch moved to outer framework
outv[0] = MatlabParamParser::wrap(thiz.get_depth_frame());
});
frameset_factory.record("get_color_frame", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frameset>(inv[0]);
// try/catch moved to outer framework
outv[0] = MatlabParamParser::wrap(thiz.get_color_frame());
});
frameset_factory.record("get_infrared_frame", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frameset>(inv[0]);
// try/catch moved to outer framework
outv[0] = MatlabParamParser::wrap(thiz.get_infrared_frame());
});
frameset_factory.record("size", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frameset>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.size());
});
// rs2::frameset::foreach [?/Callbacks]
// rs2::frameset::operator[] [?/HOW]
// rs2::frameset::iterator+begin+end [Pure Matlab?]
factory->record(frameset_factory);
}
// rs_sensor.hpp
// rs2::notification [?]
{
ClassFactory options_factory("rs2::options");
options_factory.record("supports#rs2_option", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.supports(option));
});
options_factory.record("get_option_description", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_option_description(option));
});
options_factory.record("get_option_value_description", 1, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
auto val = MatlabParamParser::parse<float>(inv[2]);
outv[0] = MatlabParamParser::wrap(thiz.get_option_value_description(option, val));
});
options_factory.record("get_option", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_option(option));
});
options_factory.record("get_option_range", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_option_range(option));
});
options_factory.record("set_option", 0, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
auto val = MatlabParamParser::parse<float>(inv[2]);
thiz.set_option(option, val);
});
options_factory.record("is_option_read_only", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::options>(inv[0]);
auto option = MatlabParamParser::parse<rs2_option>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.is_option_read_only(option));
});
// rs2::options::operator= [?/HOW]
options_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::options>(inv[0]);
});
factory->record(options_factory);
}
{
ClassFactory sensor_factory("rs2::sensor");
// rs2::sensor::constructor() [?]
sensor_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::sensor>(inv[0]);
});
sensor_factory.record("open#stream_profile", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto profile = MatlabParamParser::parse<rs2::stream_profile>(inv[1]);
thiz.open(profile);
});
sensor_factory.record("supports#rs2_camera_info", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto info = MatlabParamParser::parse<rs2_camera_info>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.supports(info));
});
sensor_factory.record("get_info", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto info = MatlabParamParser::parse<rs2_camera_info>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_info(info));
});
sensor_factory.record("open#vec_stream_profile", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto profiles = MatlabParamParser::parse<std::vector<rs2::stream_profile>>(inv[1]);
thiz.open(profiles);
});
sensor_factory.record("close", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
thiz.close();
});
// rs2::sensor::start(*) [?/Which/Callbacks]
sensor_factory.record("start#frame_queue", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto queue = MatlabParamParser::parse<rs2::frame_queue>(inv[1]);
thiz.start(queue);
});
sensor_factory.record("stop", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
thiz.stop();
});
sensor_factory.record("get_stream_profiles", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
MatlabParamParser::wrap(thiz.get_stream_profiles());
});
// rs2::sensor::operator= [?]
sensor_factory.record("operator bool", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
outv[0] = MatlabParamParser::wrap(bool(thiz));
});
sensor_factory.record("is", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "sensor")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::sensor>());
else if (type == "roi_sensor")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::roi_sensor>());
else if (type == "depth_sensor")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::depth_sensor>());
else if (type == "depth_stereo_sensor")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::depth_stereo_sensor>());
else {
mexWarnMsgTxt("rs2::sensor::is: invalid type parameter");
outv[0] = MatlabParamParser::wrap(false);
}
});
sensor_factory.record("as", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "sensor")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::sensor>());
else if (type == "roi_sensor")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::roi_sensor>());
else if (type == "depth_sensor")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::depth_sensor>());
else if (type == "depth_stereo_sensor")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::depth_stereo_sensor>());
else {
mexWarnMsgTxt("rs2::sensor::as: invalid type parameter");
outv[0] = MatlabParamParser::wrap(uint64_t(0));
}
});
sensor_factory.record("operator==", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto rhs = MatlabParamParser::parse<rs2::sensor>(inv[0]);
auto lhs = MatlabParamParser::parse<rs2::sensor>(inv[1]);
MatlabParamParser::wrap(rhs == lhs);
});
factory->record(sensor_factory);
}
{
ClassFactory roi_sensor_factory("rs2::roi_sensor");
// rs2::roi_sensor::constructor(rs2::sensor) [?]
roi_sensor_factory.record("set_region_of_interest", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::roi_sensor>(inv[0]);
auto roi = MatlabParamParser::parse<rs2::region_of_interest>(inv[1]);
thiz.set_region_of_interest(roi);
});
roi_sensor_factory.record("get_region_of_interest", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::roi_sensor>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_region_of_interest());
});
// rs2::roi_sensor::operator bool [?]
factory->record(roi_sensor_factory);
}
{
ClassFactory depth_sensor_factory("rs2::depth_sensor");
// rs2::depth_sensor::constructor(rs2::sensor) [?]
depth_sensor_factory.record("get_depth_scale", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::depth_sensor>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_depth_scale());
});
// rs2::depth_sensor::operator bool [?]
factory->record(depth_sensor_factory);
}
{
ClassFactory depth_stereo_sensor_factory("rs2::depth_stereo_sensor");
// rs2::depth_stereo_sensor::constructor(rs2::sensor) [?]
depth_stereo_sensor_factory.record("get_stereo_baseline", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::depth_stereo_sensor>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_stereo_baseline());
});
factory->record(depth_stereo_sensor_factory);
}
// rs_device.hpp
{
ClassFactory device_factory("rs2::device");
// rs2::device::constructor() [?]
// extra helper function for constructing device from device_list
device_factory.record("init", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto list = MatlabParamParser::parse<rs2::device_list>(inv[0]);
auto idx = MatlabParamParser::parse<uint32_t>(inv[1]);
outv[0] = MatlabParamParser::wrap(list[idx]);
MatlabParamParser::destroy<rs2::device_list>(inv[0]);
});
// destructor in case device was never initialized
device_factory.record("delete#uninit", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::device_list>(inv[0]);
});
// destructor in case device was initialized
device_factory.record("delete#init", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::device>(inv[0]);
});
device_factory.record("query_sensors", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.query_sensors());
});
device_factory.record("first", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: better, more maintainable implementation?
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
try {
if (type == "sensor")
outv[0] = MatlabParamParser::wrap(thiz.first<rs2::sensor>());
else if (type == "roi_sensor")
outv[0] = MatlabParamParser::wrap(thiz.first<rs2::roi_sensor>());
else if (type == "depth_sensor")
outv[0] = MatlabParamParser::wrap(thiz.first<rs2::depth_sensor>());
else if (type == "depth_stereo_sensor")
outv[0] = MatlabParamParser::wrap(thiz.first<rs2::depth_stereo_sensor>());
else mexErrMsgTxt("rs2::device::first: Could not find requested sensor type!");
}
catch (rs2::error) {
mexErrMsgTxt("rs2::device::first: Could not find requested sensor type!");
}
});
device_factory.record("supports", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
auto info = MatlabParamParser::parse<rs2_camera_info>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.supports(info));
});
device_factory.record("get_info", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
auto info = MatlabParamParser::parse<rs2_camera_info>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_info(info));
});
device_factory.record("hardware_reset", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
thiz.hardware_reset();
});
// rs2::device::operator= [?]
device_factory.record("operator bool", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
outv[0] = MatlabParamParser::wrap(bool(thiz));
});
device_factory.record("is", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "device")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::device>());
else if (type == "debug_protocol") {
mexWarnMsgTxt("rs2::device::is: Debug Protocol not supported in MATLAB");
outv[0] = MatlabParamParser::wrap(false);
}
else if (type == "advanced_mode") {
mexWarnMsgTxt("rs2::device::is: Advanced Mode not supported in MATLAB");
outv[0] = MatlabParamParser::wrap(false);
}
else if (type == "recorder")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::recorder>());
else if (type == "playback")
outv[0] = MatlabParamParser::wrap(thiz.is<rs2::playback>());
else {
mexWarnMsgTxt("rs2::device::is: invalid type parameter");
outv[0] = MatlabParamParser::wrap(false);
}
});
device_factory.record("as", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: something more maintainable?
auto thiz = MatlabParamParser::parse<rs2::device>(inv[0]);
auto type = MatlabParamParser::parse<std::string>(inv[1]);
if (type == "device")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::device>());
else if (type == "debug_protocol") {
mexErrMsgTxt("rs2::device::as: Debug Protocol not supported in MATLAB");
// outv[0] = MatlabParamParser::wrap(thiz.as<rs2::debug_protocol>());
}
else if (type == "advanced_mode") {
mexErrMsgTxt("rs2::device::as: Advanced Mode not supported in MATLAB");
// outv[0] = MatlabParamParser::wrap(false);
}
else if (type == "recorder")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::recorder>());
else if (type == "playback")
outv[0] = MatlabParamParser::wrap(thiz.as<rs2::playback>());
else {
mexWarnMsgTxt("rs2::device::as: invalid type parameter");
outv[0] = MatlabParamParser::wrap(false);
}
});
factory->record(device_factory);
}
// rs2::debug_protocol [?]
// rs2::device_list [Pure Matlab]
// rs2_record_playback.hpp
{
ClassFactory playback_factory("rs2::playback");
// rs2::playback::constructor(rs2::device) [?]
playback_factory.record("pause", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
thiz.pause();
});
playback_factory.record("resume", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
thiz.resume();
});
playback_factory.record("file_name", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.file_name());
});
playback_factory.record("get_position", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_position());
});
playback_factory.record("get_duration", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_duration());
});
playback_factory.record("seek", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
auto time = MatlabParamParser::parse<std::chrono::nanoseconds>(inv[1]);
thiz.seek(time);
});
playback_factory.record("is_real_time", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.is_real_time());
});
playback_factory.record("set_real_time", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
auto real_time = MatlabParamParser::parse<bool>(inv[1]);
thiz.set_real_time(real_time);
});
playback_factory.record("set_playback_speed", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
auto speed = MatlabParamParser::parse<float>(inv[1]);
thiz.set_playback_speed(speed);
});
// rs2::playback::set_status_changed_callback() [?/Callbacks]
playback_factory.record("current_status", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.current_status());
});
playback_factory.record("stop", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::playback>(inv[0]);
thiz.stop();
});
factory->record(playback_factory);
}
{
ClassFactory recorder_factory("rs2::recorder");
// rs2::recorder::constructor(rs2::device) [?]
recorder_factory.record("new#string_device", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto file = MatlabParamParser::parse<std::string>(inv[0]);
auto device = MatlabParamParser::parse<rs2::device>(inv[1]);
outv[0] = MatlabParamParser::wrap(rs2::recorder(file, device));
});
recorder_factory.record("pause", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::recorder>(inv[0]);
thiz.pause();
});
recorder_factory.record("resume", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::recorder>(inv[0]);
thiz.resume();
});
recorder_factory.record("filename", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::recorder>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.filename());
});
factory->record(recorder_factory);
}
// rs2_processing.hpp
// rs2::processing_block [?]
{
ClassFactory frame_queue_factory("rs2::frame_queue");
frame_queue_factory.record("new", 1, 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
if (inc == 0) {
outv[0] = MatlabParamParser::wrap(rs2::frame_queue());
}
else if (inc == 1) {
auto capacity = MatlabParamParser::parse<unsigned int>(inv[0]);
outv[0] = MatlabParamParser::wrap(rs2::frame_queue(capacity));
}
});
// rs2::frame_queue::enqueue(frame) [?]
frame_queue_factory.record("wait_for_frame", 1, 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame_queue>(inv[0]);
if (inc == 0) {
outv[0] = MatlabParamParser::wrap(thiz.wait_for_frame());
}
else if (inc == 1) {
auto timeout_ms = MatlabParamParser::parse<unsigned int>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.wait_for_frame(timeout_ms));
}
});
// rs2::frame_queue::poll_for_frame(T*) [TODO] [T = {frame, video_frame, points, depth_frame, disparity_frame, motion_frame, pose_frame, frameset}]
frame_queue_factory.record("capacity", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::frame_queue>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.capacity());
});
factory->record(frame_queue_factory);
}
{
ClassFactory pointcloud_factory("rs2::pointcloud");
pointcloud_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::pointcloud());
});
pointcloud_factory.record("calculate", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pointcloud>(inv[0]);
auto depth = MatlabParamParser::parse<rs2::frame>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.calculate(depth));
});
pointcloud_factory.record("map_to", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pointcloud>(inv[0]);
auto mapped = MatlabParamParser::parse<rs2::frame>(inv[1]);
thiz.map_to(mapped);
});
factory->record(pointcloud_factory);
}
{
ClassFactory syncer_factory("rs2::syncer");
syncer_factory.record("new", 1, 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
if (inc == 0) {
outv[0] = MatlabParamParser::wrap(rs2::syncer());
}
else if (inc == 1) {
auto queue_size = MatlabParamParser::parse<int>(inv[0]);
outv[0] = MatlabParamParser::wrap(rs2::syncer(queue_size));
}
});
syncer_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::syncer>(inv[0]);
});
syncer_factory.record("wait_for_frames", 1, 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::syncer>(inv[0]);
if (inc == 0) {
outv[0] = MatlabParamParser::wrap(thiz.wait_for_frames());
}
else if (inc == 1) {
auto timeout_ms = MatlabParamParser::parse<unsigned int>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.wait_for_frames(timeout_ms));
}
});
// rs2::syncer::poll_for_frames(frameset*) [?]
factory->record(syncer_factory);
}
{
ClassFactory align_factory("rs2::align");
align_factory.record("new", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto align_to = MatlabParamParser::parse<rs2_stream>(inv[0]);
outv[0] = MatlabParamParser::wrap(rs2::align(align_to));
});
align_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::align>(inv[0]);
});
align_factory.record("process", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::align>(inv[0]);
auto frame = MatlabParamParser::parse<rs2::frameset>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.process(frame));
});
factory->record(align_factory);
}
{
ClassFactory colorizer_factory("rs2::colorizer");
colorizer_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::colorizer());
});
colorizer_factory.record("colorize", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::colorizer>(inv[0]);
auto depth = MatlabParamParser::parse<rs2::frame>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.colorize(depth));
});
factory->record(colorizer_factory);
}
{
ClassFactory process_interface_factory("rs2::process_interface");
process_interface_factory.record("process", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
// TODO: will this work?
auto *thiz = MatlabParamParser::parse<rs2::process_interface*>(inv[0]);
auto frame = MatlabParamParser::parse<rs2::frame>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz->process(frame));
});
factory->record(process_interface_factory);
}
{
ClassFactory decimation_filter_factory("rs2::decimation_filter");
decimation_filter_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::decimation_filter());
});
factory->record(decimation_filter_factory);
}
{
ClassFactory temporal_filter_factory("rs2::temporal_filter");
temporal_filter_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::temporal_filter());
});
factory->record(temporal_filter_factory);
}
{
ClassFactory spatial_filter_factory("rs2::spatial_filter");
spatial_filter_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::spatial_filter());
});
factory->record(spatial_filter_factory);
}
{
ClassFactory disparity_transform_factory("rs2::disparity_transform");
disparity_transform_factory.record("new", 1, 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
if (inc == 0) {
outv[0] = MatlabParamParser::wrap(rs2::disparity_transform());
}
else if (inc == 1) {
auto transform_to_disparity = MatlabParamParser::parse<bool>(inv[0]);
outv[0] = MatlabParamParser::wrap(rs2::disparity_transform(transform_to_disparity));
}
});
factory->record(disparity_transform_factory);
}
{
ClassFactory hole_filling_filter_factory("rs2::hole_filling_filter");
hole_filling_filter_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::hole_filling_filter());
});
factory->record(hole_filling_filter_factory);
}
// rs_context.hpp
// rs2::event_information [?]
{
ClassFactory context_factory("rs2::context");
// This lambda feels like it should be possible to generate automatically with templates
context_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::context());
});
context_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::context>(inv[0]);
});
context_factory.record("query_devices", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::context>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.query_devices());
});
context_factory.record("query_all_sensors", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::context>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.query_all_sensors());
});
context_factory.record("get_sensor_parent", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::context>(inv[0]);
auto sensor = MatlabParamParser::parse<rs2::sensor>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.get_sensor_parent(sensor));
});
context_factory.record("load_device", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::context>(inv[0]);
auto file = MatlabParamParser::parse<std::string>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.load_device(file));
});
context_factory.record("unload_device", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::context>(inv[0]);
auto file = MatlabParamParser::parse<std::string>(inv[1]);
thiz.unload_device(file);
});
factory->record(context_factory);
}
{
ClassFactory device_hub_factory("rs2::device_hub");
device_hub_factory.record("new", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto ctx = MatlabParamParser::parse<rs2::context>(inv[0]);
outv[0] = MatlabParamParser::wrap(rs2::device_hub(ctx));
});
device_hub_factory.record("delete", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::device_hub>(inv[0]);
});
device_hub_factory.record("wait_for_device", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device_hub>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.wait_for_device());
});
device_hub_factory.record("is_connected", 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::device_hub>(inv[0]);
auto dev = MatlabParamParser::parse<rs2::device>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.is_connected(dev));
});
factory->record(device_hub_factory);
}
// rs_pipeline.hpp
{
ClassFactory pipeline_profile_factory("rs2::pipeline_profile");
// rs2::pipeline_profile::constructor() [?]
pipeline_profile_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::pipeline_profile>(inv[0]);
});
pipeline_profile_factory.record("get_streams", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_streams());
});
pipeline_profile_factory.record("get_stream", 1, 2, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline_profile>(inv[0]);
auto stream_type = MatlabParamParser::parse<rs2_stream>(inv[1]);
if (inc == 2)
outv[0] = MatlabParamParser::wrap(thiz.get_stream(stream_type));
else {
auto stream_index = MatlabParamParser::parse<int>(inv[2]);
outv[0] = MatlabParamParser::wrap(thiz.get_stream(stream_type, stream_index));
}
});
pipeline_profile_factory.record("get_device", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline_profile>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_device());
});
// rs2::pipeline_profile::bool() [?]
factory->record(pipeline_profile_factory);
}
{
ClassFactory config_factory("rs2::config");
config_factory.record("new", 1, 0, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
outv[0] = MatlabParamParser::wrap(rs2::config());
});
config_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::config>(inv[0]);
});
config_factory.record("enable_stream#full", 0, 5, 7, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto stream_type = MatlabParamParser::parse<rs2_stream>(inv[1]);
auto stream_index = MatlabParamParser::parse<int>(inv[2]);
auto width = MatlabParamParser::parse<int>(inv[3]);
auto height = MatlabParamParser::parse<int>(inv[4]);
if (inc == 5) {
thiz.enable_stream(stream_type, stream_index, width, height);
} else if (inc == 6) {
auto format = MatlabParamParser::parse<rs2_format>(inv[5]);
thiz.enable_stream(stream_type, stream_index, width, height, format);
} else if (inc == 7) {
auto format = MatlabParamParser::parse<rs2_format>(inv[5]);
auto framerate = MatlabParamParser::parse<int>(inv[6]);
thiz.enable_stream(stream_type, stream_index, width, height, format, framerate);
}
});
config_factory.record("enable_stream#stream", 0, 2, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto stream_type = MatlabParamParser::parse<rs2_stream>(inv[1]);
if (inc == 2) {
thiz.enable_stream(stream_type);
} else if (inc == 3){
auto stream_index = MatlabParamParser::parse<int>(inv[2]);
thiz.enable_stream(stream_type, stream_index);
}
});
config_factory.record("enable_stream#size", 0, 4, 6, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto stream_type = MatlabParamParser::parse<rs2_stream>(inv[1]);
auto width = MatlabParamParser::parse<int>(inv[2]);
auto height = MatlabParamParser::parse<int>(inv[3]);
if (inc == 4) {
thiz.enable_stream(stream_type, width, height);
} else if (inc == 5) {
auto format = MatlabParamParser::parse<rs2_format>(inv[4]);
thiz.enable_stream(stream_type, width, height, format);
} else if (inc == 6) {
auto format = MatlabParamParser::parse<rs2_format>(inv[4]);
auto framerate = MatlabParamParser::parse<int>(inv[5]);
thiz.enable_stream(stream_type, width, height, format, framerate);
}
});
config_factory.record("enable_stream#format", 0, 3, 4, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto stream_type = MatlabParamParser::parse<rs2_stream>(inv[1]);
auto format = MatlabParamParser::parse<rs2_format>(inv[2]);
if (inc == 3) {
thiz.enable_stream(stream_type, format);
} else if (inc == 4) {
auto framerate = MatlabParamParser::parse<int>(inv[3]);
thiz.enable_stream(stream_type, format, framerate);
}
});
config_factory.record("enable_stream#extended", 0, 4, 5, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto stream_type = MatlabParamParser::parse<rs2_stream>(inv[1]);
auto stream_index = MatlabParamParser::parse<int>(inv[2]);
auto format = MatlabParamParser::parse<rs2_format>(inv[3]);
if (inc == 4) {
thiz.enable_stream(stream_type, stream_index, format);
} else if (inc == 5) {
auto framerate = MatlabParamParser::parse<int>(inv[4]);
thiz.enable_stream(stream_type, stream_index, format, framerate);
}
});
config_factory.record("enable_all_streams", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
thiz.enable_all_streams();
});
config_factory.record("enable_device", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto serial = MatlabParamParser::parse<std::string>(inv[1]);
thiz.enable_device(serial);
});
config_factory.record("enable_device_from_file", 0, 2, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto file_name = MatlabParamParser::parse<std::string>(inv[1]);
if (inc == 2)
thiz.enable_device_from_file(file_name);
else if (inc == 3) {
auto repeat_playback = MatlabParamParser::parse<bool>(inv[2]);
thiz.enable_device_from_file(file_name, repeat_playback);
}
});
config_factory.record("enable_record_to_file", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto file_name = MatlabParamParser::parse<std::string>(inv[1]);
thiz.enable_record_to_file(file_name);
});
config_factory.record("disable_stream", 0, 2, 3, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
auto stream = MatlabParamParser::parse<rs2_stream>(inv[1]);
if (inc == 2)
thiz.disable_stream(stream);
else if (inc == 3) {
auto index = MatlabParamParser::parse<int>(inv[2]);
thiz.disable_stream(stream, index);
}
});
config_factory.record("disable_all_streams", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::config>(inv[0]);
thiz.disable_all_streams();
});
factory->record(config_factory);
}
{
ClassFactory pipeline_factory("rs2::pipeline");
pipeline_factory.record("new", 1, 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
if (inc == 0) {
outv[0] = MatlabParamParser::wrap(rs2::pipeline());
} else if (inc == 1) {
auto ctx = MatlabParamParser::parse<rs2::context>(inv[0]);
outv[0] = MatlabParamParser::wrap(rs2::pipeline(ctx));
}
});
pipeline_factory.record("delete", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
MatlabParamParser::destroy<rs2::pipeline>(inv[0]);
});
pipeline_factory.record("start", 1, 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline>(inv[0]);
if (inc == 1)
outv[0] = MatlabParamParser::wrap(thiz.start());
else if (inc == 2) {
auto config = MatlabParamParser::parse<rs2::config>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.start(config));
}
});
pipeline_factory.record("stop", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline>(inv[0]);
thiz.stop();
});
pipeline_factory.record("wait_for_frames", 1, 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline>(inv[0]);
if (inc == 1) {
outv[0] = MatlabParamParser::wrap(thiz.wait_for_frames());
} else if (inc == 2) {
auto timeout_ms = MatlabParamParser::parse<unsigned int>(inv[1]);
outv[0] = MatlabParamParser::wrap(thiz.wait_for_frames(timeout_ms));
}
});
// rs2::pipeline::poll_for_frames [TODO/HOW] [multi-output?]
pipeline_factory.record("get_active_profile", 1, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[])
{
auto thiz = MatlabParamParser::parse<rs2::pipeline>(inv[0]);
outv[0] = MatlabParamParser::wrap(thiz.get_active_profile());
});
factory->record(pipeline_factory);
}
// rs.hpp
{
ClassFactory free_funcs_factory("rs2");
free_funcs_factory.record("log_to_console", 0, 1, [](int outc, mxArray* outv[], int inc, const mxArray* inv[]) {
auto min_severity = MatlabParamParser::parse<rs2_log_severity>(inv[0]);
rs2::log_to_console(min_severity);
});
free_funcs_factory.record("log_to_file", 0, 1, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[]) {
auto min_severity = MatlabParamParser::parse<rs2_log_severity>(inv[0]);
if (inc == 1)
rs2::log_to_file(min_severity);
else if (inc == 2) {
auto file_path = MatlabParamParser::parse<const char *>(inv[1]);
rs2::log_to_file(min_severity, file_path);
}
});
free_funcs_factory.record("log", 0, 2, [](int outc, mxArray* outv[], int inc, const mxArray* inv[]) {
auto severity = MatlabParamParser::parse<rs2_log_severity>(inv[0]);
auto message = MatlabParamParser::parse<const char *>(inv[1]);
rs2::log(severity, message);
});
}
mexAtExit([]() { delete factory; });
}
void mexFunction(int nOutParams, mxArray *outParams[], int nInParams, const mxArray *inParams[])
{
// does this need to be made threadsafe? also maybe better idea than global object?
if (!factory) make_factory();
if (nInParams < 2) {
mexErrMsgTxt("At least class and command name are needed.");
return;
}
auto cname = MatlabParamParser::parse<std::string>(inParams[0]);
auto fname = MatlabParamParser::parse<std::string>(inParams[1]);
auto f_data = factory->get(cname, fname);
if (!f_data.f) {
mexErrMsgTxt("Unknown Command received.");
return;
}
if (f_data.out != nOutParams) {
std::string errmsg = cname + "::" + fname.substr(0, fname.find("#", 0)) + ": Wrong number of outputs";
mexErrMsgTxt(errmsg.c_str());
}
if (f_data.in_min > nInParams - 2 || f_data.in_max < nInParams - 2) {
std::string errmsg = cname + "::" + fname.substr(0, fname.find("#", 0)) + ": Wrong number of inputs";
mexErrMsgTxt(errmsg.c_str());
}
try {
f_data.f(nOutParams, outParams, nInParams - 2, inParams + 2); // "eat" the two function specifiers
} catch (std::exception &e) {
mexErrMsgTxt(e.what());
} catch (...) {
mexErrMsgTxt("An unknown error occured");
}
} | 51.644699 | 179 | 0.564872 | [
"object",
"vector"
] |
b13e5e08a5be5fce43cf8aaab280ab79f485efce | 41,030 | cpp | C++ | extensions/DRM/dream/Parameter.cpp | mfkiwl/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | 9 | 2020-09-22T17:26:17.000Z | 2022-03-10T17:58:03.000Z | extensions/DRM/dream/Parameter.cpp | hikijun/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | null | null | null | extensions/DRM/dream/Parameter.cpp | hikijun/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | 4 | 2021-02-10T16:13:19.000Z | 2021-09-21T08:04:25.000Z | /******************************************************************************\
* Technische Universitaet Darmstadt, Institut fuer Nachrichtentechnik
* Copyright (c) 2007
*
* Author(s):
* Volker Fischer, Andrew Murphy
*
* Description:
* DRM Parameters
*
******************************************************************************
*
* This program is free software(), you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation(), either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY(), without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program(), if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
\******************************************************************************/
#include "Parameter.h"
#include "DRMReceiver.h"
#include "Version.h"
#include <limits>
#include <sstream>
#include <iomanip>
//#include "util/LogPrint.h"
#ifdef _WIN32
# define PATH_SEPARATOR "\\"
# define PATH_SEPARATORS "/\\"
#else
# define PATH_SEPARATOR "/"
# define PATH_SEPARATORS "/"
#endif
#define DEFAULT_DATA_FILES_DIRECTORY "data" PATH_SEPARATOR
/* Implementation *************************************************************/
CParameter::CParameter():
pDRMRec(nullptr),
eSymbolInterlMode(),
eMSCCodingScheme(),
eSDCCodingScheme(),
iNumAudioService(0),
iNumDataService(0),
iAMSSCarrierMode(0),
sReceiverID(" "),
sSerialNumber(),
sDataFilesDirectory(DEFAULT_DATA_FILES_DIRECTORY),
eTransmitCurrentTime(CT_OFF),
MSCPrLe(),
Stream(MAX_NUM_STREAMS), Service(MAX_NUM_SERVICES),
AudioComponentStatus(MAX_NUM_SERVICES),DataComponentStatus(MAX_NUM_SERVICES),
iNumBitsHierarchFrameTotal(0),
iNumDecodedBitsMSC(0),
iNumSDCBitsPerSFrame(0),
iNumAudioDecoderBits(0),
iNumDataDecoderBits(0),
iYear(0),
iMonth(0),
iDay(0),
iUTCHour(0),
iUTCMin(0),
iFrameIDTransm(0),
iFrameIDReceiv(0),
rFreqOffsetAcqui(0.0),
rFreqOffsetTrack(0.0),
rResampleOffset(0.0),
iTimingOffsTrack(0),
eReceiverMode(RM_NONE),
eAcquiState(AS_NO_SIGNAL),
iNumAudioFrames(0),
vecbiAudioFrameStatus(0),
bMeasurePSD(false), bMeasurePSDAlways(false),
vecrPSD(0),
matcReceivedPilotValues(),
RawSimDa(),
eSimType(ST_NONE),
iDRMChannelNum(0),
iSpecChDoppler(0),
rBitErrRate(0.0),
rSyncTestParam(0.0),
rSINR(0.0),
iNumBitErrors(0),
iChanEstDelay(0),
iNumTaps(0),
iPathDelay(MAX_NUM_TAPS_DRM_CHAN),
rGainCorr(0.0),
iOffUsfExtr(0),
ReceiveStatus(),
FrontEndParameters(),
AltFreqSign(),
rMER(0.0),
rWMERMSC(0.0),
rWMERFAC(0.0),
rSigmaEstimate(0.0),
rMinDelay(0.0),
rMaxDelay(0.0),
bMeasureDelay(),
vecrRdel(0),
vecrRdelThresholds(0),
vecrRdelIntervals(0),
bMeasureDoppler(0),
rRdop(0.0),
bMeasureInterference(false),
rIntFreq(0.0),
rINR(0.0),
rICR(0.0),
rMaxPSDwrtSig(0.0),
rMaxPSDFreq(0.0),
rSigStrengthCorrection(0.0),
CellMappingTable(),
audioencoder(""),audiodecoder(""),
use_gpsd(0), restart_gpsd(false),
gps_host("localhost"), gps_port("2497"),
iAudSampleRate(DEFAULT_SOUNDCRD_SAMPLE_RATE),
iSigSampleRate(DEFAULT_SOUNDCRD_SAMPLE_RATE),
iSigUpscaleRatio(1),
iNewAudSampleRate(0),
iNewSigSampleRate(0),
iNewSigUpscaleRatio(0),
rSysSimSNRdB(0.0),
iFrequency(0),
bValidSignalStrength(false),
rSigStr(0.0),
rIFSigStr(0.0),
iCurSelAudioService(0),
iCurSelDataService(0),
eRobustnessMode(RM_ROBUSTNESS_MODE_B),
eSpectOccup(SO_3),
LastAudioService(),
LastDataService(),
Mutex(), lenient_RSCI(false)
{
GenerateRandomSerialNumber();
CellMappingTable.MakeTable(eRobustnessMode, eSpectOccup, iSigSampleRate);
gps_data.set=0;
gps_data.status=0;
#ifdef HAVE_LIBGPS
gps_data.gps_fd = -1;
#endif
}
CParameter::~CParameter()
{
}
CParameter::CParameter(const CParameter& p):
pDRMRec(p.pDRMRec),
eSymbolInterlMode(p.eSymbolInterlMode),
eMSCCodingScheme(p.eMSCCodingScheme),
eSDCCodingScheme(p.eSDCCodingScheme),
iNumAudioService(p.iNumAudioService),
iNumDataService(p.iNumDataService),
iAMSSCarrierMode(p.iAMSSCarrierMode),
sReceiverID(p.sReceiverID),
sSerialNumber(p.sSerialNumber),
sDataFilesDirectory(p.sDataFilesDirectory),
eTransmitCurrentTime(p.eTransmitCurrentTime),
MSCPrLe(p.MSCPrLe),
Stream(p.Stream), Service(p.Service),
AudioComponentStatus(p.AudioComponentStatus),DataComponentStatus(p.DataComponentStatus),
iNumBitsHierarchFrameTotal(p.iNumBitsHierarchFrameTotal),
iNumDecodedBitsMSC(p.iNumDecodedBitsMSC),
iNumSDCBitsPerSFrame(p.iNumSDCBitsPerSFrame),
iNumAudioDecoderBits(p.iNumAudioDecoderBits),
iNumDataDecoderBits(p.iNumDataDecoderBits),
iYear(p.iYear),
iMonth(p.iMonth),
iDay(p.iDay),
iUTCHour(p.iUTCHour),
iUTCMin(p.iUTCMin),
iUTCOff(p.iUTCOff),
iUTCSense(p.iUTCSense),
bValidUTCOffsetAndSense(p.bValidUTCOffsetAndSense),
iFrameIDTransm(p.iFrameIDTransm),
iFrameIDReceiv(p.iFrameIDReceiv),
rFreqOffsetAcqui(p.rFreqOffsetAcqui),
rFreqOffsetTrack(p.rFreqOffsetTrack),
rResampleOffset(p.rResampleOffset),
iTimingOffsTrack(p.iTimingOffsTrack),
eReceiverMode(p.eReceiverMode),
eAcquiState(p.eAcquiState),
iNumAudioFrames(p.iNumAudioFrames),
vecbiAudioFrameStatus(p.vecbiAudioFrameStatus),
bMeasurePSD(p.bMeasurePSD), bMeasurePSDAlways(p.bMeasurePSDAlways),
vecrPSD(p.vecrPSD),
//matcReceivedPilotValues(p.matcReceivedPilotValues),
matcReceivedPilotValues(), // OPH says copy constructor for CMatrix not safe yet
RawSimDa(p.RawSimDa),
eSimType(p.eSimType),
iDRMChannelNum(p.iDRMChannelNum),
iSpecChDoppler(p.iSpecChDoppler),
rBitErrRate(p.rBitErrRate),
rSyncTestParam (p.rSyncTestParam),
rSINR(p.rSINR),
iNumBitErrors(p.iNumBitErrors),
iChanEstDelay(p.iChanEstDelay),
iNumTaps(p.iNumTaps),
iPathDelay(p.iPathDelay),
rGainCorr(p.rGainCorr),
iOffUsfExtr(p.iOffUsfExtr),
ReceiveStatus(p.ReceiveStatus),
FrontEndParameters(p.FrontEndParameters),
AltFreqSign(p.AltFreqSign),
rMER(p.rMER),
rWMERMSC(p.rWMERMSC),
rWMERFAC(p.rWMERFAC),
rSigmaEstimate(p.rSigmaEstimate),
rMinDelay(p.rMinDelay),
rMaxDelay(p.rMaxDelay),
bMeasureDelay(p.bMeasureDelay),
vecrRdel(p.vecrRdel),
vecrRdelThresholds(p.vecrRdelThresholds),
vecrRdelIntervals(p.vecrRdelIntervals),
bMeasureDoppler(p.bMeasureDoppler),
rRdop(p.rRdop),
bMeasureInterference(p.bMeasureInterference),
rIntFreq(p.rIntFreq),
rINR(p.rINR),
rICR(p.rICR),
rMaxPSDwrtSig(p.rMaxPSDwrtSig),
rMaxPSDFreq(p.rMaxPSDFreq),
rSigStrengthCorrection(p.rSigStrengthCorrection),
CellMappingTable(), // jfbc CCellMappingTable uses a CMatrix :(
audioencoder(p.audioencoder),audiodecoder(p.audiodecoder),
use_gpsd(p.use_gpsd),restart_gpsd(p.restart_gpsd),
gps_host(p.gps_host),gps_port(p.gps_port),
iAudSampleRate(p.iAudSampleRate),
iSigSampleRate(p.iSigSampleRate),
iSigUpscaleRatio(p.iSigUpscaleRatio),
iNewAudSampleRate(p.iNewAudSampleRate),
iNewSigSampleRate(p.iNewSigSampleRate),
iNewSigUpscaleRatio(p.iNewSigUpscaleRatio),
rSysSimSNRdB(p.rSysSimSNRdB),
iFrequency(p.iFrequency),
bValidSignalStrength(p.bValidSignalStrength),
rSigStr(p.rSigStr),
rIFSigStr(p.rIFSigStr),
iCurSelAudioService(p.iCurSelAudioService),
iCurSelDataService(p.iCurSelDataService),
eRobustnessMode(p.eRobustnessMode),
eSpectOccup(p.eSpectOccup),
LastAudioService(p.LastAudioService),
LastDataService(p.LastDataService)
//, Mutex() // jfbc: I don't think this state should be copied
,lenient_RSCI(p.lenient_RSCI)
{
CellMappingTable.MakeTable(eRobustnessMode, eSpectOccup, iSigSampleRate);
matcReceivedPilotValues = p.matcReceivedPilotValues; // TODO
gps_data = p.gps_data;
}
CParameter& CParameter::operator=(const CParameter& p)
{
gps_data = p.gps_data;
pDRMRec = p.pDRMRec;
eSymbolInterlMode = p.eSymbolInterlMode;
eMSCCodingScheme = p.eMSCCodingScheme;
eSDCCodingScheme = p.eSDCCodingScheme;
iNumAudioService = p.iNumAudioService;
iNumDataService = p.iNumDataService;
iAMSSCarrierMode = p.iAMSSCarrierMode;
sReceiverID = p.sReceiverID;
sSerialNumber = p.sSerialNumber;
sDataFilesDirectory = p.sDataFilesDirectory;
eTransmitCurrentTime = p.eTransmitCurrentTime;
MSCPrLe = p.MSCPrLe;
Stream = p.Stream;
Service = p.Service;
AudioComponentStatus = p.AudioComponentStatus;
DataComponentStatus = p.DataComponentStatus;
iNumBitsHierarchFrameTotal = p.iNumBitsHierarchFrameTotal;
iNumDecodedBitsMSC = p.iNumDecodedBitsMSC;
iNumSDCBitsPerSFrame = p.iNumSDCBitsPerSFrame;
iNumAudioDecoderBits = p.iNumAudioDecoderBits;
iNumDataDecoderBits = p.iNumDataDecoderBits;
iYear = p.iYear;
iMonth = p.iMonth;
iDay = p.iDay;
iUTCHour = p.iUTCHour;
iUTCMin = p.iUTCMin;
iFrameIDTransm = p.iFrameIDTransm;
iFrameIDReceiv = p.iFrameIDReceiv;
rFreqOffsetAcqui = p.rFreqOffsetAcqui;
rFreqOffsetTrack = p.rFreqOffsetTrack;
rResampleOffset = p.rResampleOffset;
iTimingOffsTrack = p.iTimingOffsTrack;
eReceiverMode = p.eReceiverMode;
eAcquiState = p.eAcquiState;
iNumAudioFrames = p.iNumAudioFrames;
vecbiAudioFrameStatus = p.vecbiAudioFrameStatus;
bMeasurePSD = p.bMeasurePSD;
bMeasurePSDAlways = p.bMeasurePSDAlways;
vecrPSD = p.vecrPSD;
matcReceivedPilotValues = p.matcReceivedPilotValues;
RawSimDa = p.RawSimDa;
eSimType = p.eSimType;
iDRMChannelNum = p.iDRMChannelNum;
iSpecChDoppler = p.iSpecChDoppler;
rBitErrRate = p.rBitErrRate;
rSyncTestParam = p.rSyncTestParam;
rSINR = p.rSINR;
iNumBitErrors = p.iNumBitErrors;
iChanEstDelay = p.iChanEstDelay;
iNumTaps = p.iNumTaps;
iPathDelay = p.iPathDelay;
rGainCorr = p.rGainCorr;
iOffUsfExtr = p.iOffUsfExtr;
ReceiveStatus = p.ReceiveStatus;
FrontEndParameters = p.FrontEndParameters;
AltFreqSign = p.AltFreqSign;
rMER = p.rMER;
rWMERMSC = p.rWMERMSC;
rWMERFAC = p.rWMERFAC;
rSigmaEstimate = p.rSigmaEstimate;
rMinDelay = p.rMinDelay;
rMaxDelay = p.rMaxDelay;
bMeasureDelay = p.bMeasureDelay;
vecrRdel = p.vecrRdel;
vecrRdelThresholds = p.vecrRdelThresholds;
vecrRdelIntervals = p.vecrRdelIntervals;
bMeasureDoppler = p.bMeasureDoppler;
rRdop = p.rRdop;
bMeasureInterference = p.bMeasureInterference;
rIntFreq = p.rIntFreq;
rINR = p.rINR;
rICR = p.rICR;
rMaxPSDwrtSig = p.rMaxPSDwrtSig;
rMaxPSDFreq = p.rMaxPSDFreq;
rSigStrengthCorrection = p.rSigStrengthCorrection;
CellMappingTable.MakeTable(eRobustnessMode, eSpectOccup, iSigSampleRate); // don't copy CMatrix
audiodecoder = p.audiodecoder;
audioencoder = p.audioencoder;
use_gpsd = p.use_gpsd;
gps_host = p.gps_host;
gps_port = p.gps_port;
restart_gpsd = p.restart_gpsd;
iAudSampleRate = p.iAudSampleRate;
iSigSampleRate = p.iSigSampleRate;
iSigUpscaleRatio = p.iSigUpscaleRatio;
iNewAudSampleRate = p.iNewAudSampleRate;
iNewSigSampleRate = p.iNewSigSampleRate;
iNewSigUpscaleRatio = p.iNewSigUpscaleRatio;
rSysSimSNRdB = p.rSysSimSNRdB;
iFrequency = p.iFrequency;
bValidSignalStrength = p.bValidSignalStrength;
rSigStr = p.rSigStr;
rIFSigStr = p.rIFSigStr;
iCurSelAudioService = p.iCurSelAudioService;
iCurSelDataService = p.iCurSelDataService;
eRobustnessMode = p.eRobustnessMode;
eSpectOccup = p.eSpectOccup;
LastAudioService = p.LastAudioService;
LastDataService = p.LastDataService;
lenient_RSCI = p.lenient_RSCI;
return *this;
}
void CParameter::SetReceiver(CDRMReceiver* pDRMReceiver)
{
pDRMRec = pDRMReceiver;
if (pDRMRec)
eReceiverMode = pDRMRec->GetReceiverMode();
}
void CParameter::ResetServicesStreams()
{
int i;
if (GetReceiverMode() == RM_DRM)
{
/* Store informations about last service selected
* so the current service can be selected automatically after a resync */
if (iCurSelAudioService > 0)
LastAudioService.Save(iCurSelAudioService, Service[iCurSelAudioService].iServiceID);
if (iCurSelDataService > 0)
LastDataService.Save(iCurSelDataService, Service[iCurSelDataService].iServiceID);
/* Reset everything to possible start values */
for (i = 0; i < MAX_NUM_SERVICES; i++)
{
Service[i].AudioParam.strTextMessage = "";
Service[i].AudioParam.iStreamID = STREAM_ID_NOT_USED;
Service[i].AudioParam.eAudioCoding = CAudioParam::AC_NONE;
Service[i].AudioParam.eSBRFlag = CAudioParam::SBR_NOT_USED;
Service[i].AudioParam.eAudioSamplRate = CAudioParam::AS_24KHZ;
Service[i].AudioParam.bTextflag = false;
Service[i].AudioParam.bEnhanceFlag = false;
Service[i].AudioParam.eAudioMode = CAudioParam::AM_MONO;
Service[i].AudioParam.eSurround = CAudioParam::MS_NONE;
Service[i].AudioParam.xHE_AAC_config.clear();
Service[i].DataParam.iStreamID = STREAM_ID_NOT_USED;
Service[i].DataParam.ePacketModInd = CDataParam::PM_PACKET_MODE;
Service[i].DataParam.eDataUnitInd = CDataParam::DU_SINGLE_PACKETS;
Service[i].DataParam.iPacketID = 0;
Service[i].DataParam.iPacketLen = 0;
Service[i].DataParam.eAppDomain = CDataParam::AD_DRM_SPEC_APP;
Service[i].DataParam.iUserAppIdent = 0;
Service[i].iServiceID = SERV_ID_NOT_USED;
Service[i].eCAIndication = CService::CA_NOT_USED;
Service[i].iLanguage = 0;
Service[i].strCountryCode = "";
Service[i].strLanguageCode = "";
Service[i].eAudDataFlag = CService::SF_AUDIO;
Service[i].iServiceDescr = 0;
Service[i].strLabel = "";
AudioComponentStatus[i].SetStatus(NOT_PRESENT);
DataComponentStatus[i].SetStatus(NOT_PRESENT);
}
for (i = 0; i < MAX_NUM_STREAMS; i++)
{
Stream[i].iLenPartA = 0;
Stream[i].iLenPartB = 0;
}
}
else
{
// Set up encoded AM audio parameters
Service[0].AudioParam.strTextMessage = "";
Service[0].AudioParam.iStreamID = 0;
Service[0].AudioParam.eAudioCoding = CAudioParam::AC_AAC;
Service[0].AudioParam.eSBRFlag = CAudioParam::SBR_NOT_USED;
Service[0].AudioParam.eAudioSamplRate = CAudioParam::AS_24KHZ;
Service[0].AudioParam.bTextflag = false;
Service[0].AudioParam.bEnhanceFlag = false;
Service[0].AudioParam.eAudioMode = CAudioParam::AM_MONO; // ? FM could be stereo
Service[0].AudioParam.eSurround = CAudioParam::MS_NONE;
Service[0].AudioParam.xHE_AAC_config.clear();
Service[0].iServiceID = SERV_ID_NOT_USED;
Service[0].eCAIndication = CService::CA_NOT_USED;
Service[0].iLanguage = 0;
Service[0].strCountryCode = "";
Service[0].strLanguageCode = "";
Service[0].eAudDataFlag = CService::SF_AUDIO;
Service[0].iServiceDescr = 0;
Service[0].strLabel = "";
Stream[0].iLenPartA = 0;
Stream[0].iLenPartB = 1044;
}
/* Reset alternative frequencies */
AltFreqSign.Reset();
/* Date, time */
iDay = 0;
iMonth = 0;
iYear = 0;
iUTCHour = 0;
iUTCMin = 0;
iUTCOff = 0;
iUTCSense = 0;
bValidUTCOffsetAndSense = false;
}
void CParameter::GetActiveServices(set<int>& actServ)
{
/* Init return vector */
actServ.clear();
/* Get active services */
for (int i = 0; i < MAX_NUM_SERVICES; i++)
{
if (Service[i].IsActive())
/* A service is active, add ID to set */
actServ.insert(i);
}
}
/* using a set ensures each stream appears only once */
void CParameter::GetActiveStreams(set<int>& actStr)
{
actStr.clear();
/* Determine which streams are active */
for (int i = 0; i < MAX_NUM_SERVICES; i++)
{
if (Service[i].IsActive())
{
/* Audio stream */
if (Service[i].AudioParam.iStreamID != STREAM_ID_NOT_USED)
actStr.insert(Service[i].AudioParam.iStreamID);
/* Data stream */
if (Service[i].DataParam.iStreamID != STREAM_ID_NOT_USED)
actStr.insert(Service[i].DataParam.iStreamID);
}
}
}
_REAL CParameter::GetBitRateKbps(const int iShortID, const bool bAudData) const
{
/* Init lengths to zero in case the stream is not yet assigned */
int iLen = 0;
/* First, check if audio or data service and get lengths */
if (Service[iShortID].eAudDataFlag == CService::SF_AUDIO)
{
/* Check if we want to get the data stream connected to an audio
stream */
if (bAudData)
{
iLen = GetStreamLen( Service[iShortID].DataParam.iStreamID);
}
else
{
iLen = GetStreamLen( Service[iShortID].AudioParam.iStreamID);
}
}
else
{
iLen = GetStreamLen( Service[iShortID].DataParam.iStreamID);
}
/* We have 3 frames with time duration of 1.2 seconds. Bit rate should be
returned in kbps (/ 1000) */
return (_REAL) iLen * SIZEOF__BYTE * 3 / (_REAL) 1.2 / 1000;
}
_REAL CParameter::PartABLenRatio(const int iShortID) const
{
int iLenA = 0;
int iLenB = 0;
/* Get the length of protection part A and B */
if (Service[iShortID].eAudDataFlag == CService::SF_AUDIO)
{
/* Audio service */
if (Service[iShortID].AudioParam.iStreamID != STREAM_ID_NOT_USED)
{
iLenA = Stream[Service[iShortID].AudioParam.iStreamID].iLenPartA;
iLenB = Stream[Service[iShortID].AudioParam.iStreamID].iLenPartB;
}
}
else
{
/* Data service */
if (Service[iShortID].DataParam.iStreamID != STREAM_ID_NOT_USED)
{
iLenA = Stream[Service[iShortID].DataParam.iStreamID].iLenPartA;
iLenB = Stream[Service[iShortID].DataParam.iStreamID].iLenPartB;
}
}
const int iTotLen = iLenA + iLenB;
if (iTotLen != 0)
return (_REAL) iLenA / iTotLen;
else
return (_REAL) 0.0;
}
void CParameter::InitCellMapTable(const ERobMode eNewWaveMode,
const ESpecOcc eNewSpecOcc)
{
/* Set new values and make table */
eRobustnessMode = eNewWaveMode;
eSpectOccup = eNewSpecOcc;
CellMappingTable.MakeTable(eRobustnessMode, eSpectOccup, iSigSampleRate);
}
bool CParameter::SetWaveMode(const ERobMode eNewWaveMode)
{
/* First check if spectrum occupancy and robustness mode pair is defined */
if ((
(eNewWaveMode == RM_ROBUSTNESS_MODE_C) ||
(eNewWaveMode == RM_ROBUSTNESS_MODE_D)
) && !(
(eSpectOccup == SO_3) ||
(eSpectOccup == SO_5)
))
{
/* Set spectrum occupance to a valid parameter */
eSpectOccup = SO_3;
}
/* Apply changes only if new paramter differs from old one */
if (eRobustnessMode != eNewWaveMode)
{
/* Set new value */
eRobustnessMode = eNewWaveMode;
/* This parameter change provokes update of table */
CellMappingTable.MakeTable(eRobustnessMode, eSpectOccup, iSigSampleRate);
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForWaveMode();
/* Signal that parameter has changed */
return true;
}
else
return false;
}
void CParameter::SetSpectrumOccup(ESpecOcc eNewSpecOcc)
{
/* First check if spectrum occupancy and robustness mode pair is defined */
if ((
(eRobustnessMode == RM_ROBUSTNESS_MODE_C) ||
(eRobustnessMode == RM_ROBUSTNESS_MODE_D)
) && !(
(eNewSpecOcc == SO_3) ||
(eNewSpecOcc == SO_5)
))
{
/* Set spectrum occupance to a valid parameter */
eNewSpecOcc = SO_3;
}
/* Apply changes only if new paramter differs from old one */
if (eSpectOccup != eNewSpecOcc)
{
/* Set new value */
eSpectOccup = eNewSpecOcc;
/* This parameter change provokes update of table */
CellMappingTable.MakeTable(eRobustnessMode, eSpectOccup, iSigSampleRate);
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForSpectrumOccup();
}
}
void CParameter::SetStreamLen(const int iStreamID, const int iNewLenPartA,
const int iNewLenPartB)
{
/* Apply changes only if parameters have changed */
if ((Stream[iStreamID].iLenPartA != iNewLenPartA) ||
(Stream[iStreamID].iLenPartB != iNewLenPartB))
{
/* Use new parameters */
Stream[iStreamID].iLenPartA = iNewLenPartA;
Stream[iStreamID].iLenPartB = iNewLenPartB;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSC();
}
}
int CParameter::GetStreamLen(const int iStreamID) const
{
if (iStreamID != STREAM_ID_NOT_USED)
return Stream[iStreamID].iLenPartA + Stream[iStreamID].iLenPartB;
else
return 0;
}
void CParameter::SetNumDecodedBitsMSC(const int iNewNumDecodedBitsMSC)
{
/* Apply changes only if parameters have changed */
if (iNewNumDecodedBitsMSC != iNumDecodedBitsMSC)
{
iNumDecodedBitsMSC = iNewNumDecodedBitsMSC;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSCDemux();
}
}
void CParameter::SetNumDecodedBitsSDC(const int iNewNumDecodedBitsSDC)
{
/* Apply changes only if parameters have changed */
if (iNewNumDecodedBitsSDC != iNumSDCBitsPerSFrame)
{
iNumSDCBitsPerSFrame = iNewNumDecodedBitsSDC;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForNoDecBitsSDC();
}
}
void CParameter::SetNumBitsHieraFrTot(const int iNewNumBitsHieraFrTot)
{
/* Apply changes only if parameters have changed */
if (iNewNumBitsHieraFrTot != iNumBitsHierarchFrameTotal)
{
iNumBitsHierarchFrameTotal = iNewNumBitsHieraFrTot;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSCDemux();
}
}
void CParameter::SetNumAudioDecoderBits(const int iNewNumAudioDecoderBits)
{
/* Apply changes only if parameters have changed */
if (iNewNumAudioDecoderBits != iNumAudioDecoderBits)
{
iNumAudioDecoderBits = iNewNumAudioDecoderBits;
}
}
void CParameter::SetNumDataDecoderBits(const int iNewNumDataDecoderBits)
{
/* Apply changes only if parameters have changed */
if (iNewNumDataDecoderBits != iNumDataDecoderBits)
{
iNumDataDecoderBits = iNewNumDataDecoderBits;
}
}
void CParameter::SetMSCProtLev(const CMSCProtLev NewMSCPrLe,
const bool bWithHierarch)
{
bool bParamersHaveChanged = false;
if ((NewMSCPrLe.iPartA != MSCPrLe.iPartA) ||
(NewMSCPrLe.iPartB != MSCPrLe.iPartB))
{
MSCPrLe.iPartA = NewMSCPrLe.iPartA;
MSCPrLe.iPartB = NewMSCPrLe.iPartB;
bParamersHaveChanged = true;
}
/* Apply changes only if parameters have changed */
if (bWithHierarch)
{
if (NewMSCPrLe.iHierarch != MSCPrLe.iHierarch)
{
MSCPrLe.iHierarch = NewMSCPrLe.iHierarch;
bParamersHaveChanged = true;
}
}
/* In case parameters have changed, set init flags */
if (bParamersHaveChanged)
if (pDRMRec) pDRMRec->InitsForMSC();
}
void CParameter::SetServiceParameters(int iShortID, const CService& newService)
{
Service[iShortID] = newService;
}
void CParameter::SetAudioParam(const int iShortID, const CAudioParam& NewAudParam)
{
/* Apply changes only if parameters have changed */
if (Service[iShortID].AudioParam != NewAudParam)
{
Service[iShortID].AudioParam = NewAudParam;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForAudParam();
}
}
CAudioParam CParameter::GetAudioParam(const int iShortID) const
{
return Service[iShortID].AudioParam;
}
void CParameter::SetDataParam(const int iShortID, const CDataParam& NewDataParam)
{
/* Apply changes only if parameters have changed */
if (Service[iShortID].DataParam != NewDataParam)
{
Service[iShortID].DataParam = NewDataParam;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForDataParam();
}
}
CDataParam CParameter::GetDataParam(const int iShortID) const
{
return Service[iShortID].DataParam;
}
void CParameter::SetInterleaverDepth(const ESymIntMod eNewDepth)
{
if (eSymbolInterlMode != eNewDepth)
{
eSymbolInterlMode = eNewDepth;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForInterlDepth();
}
}
void CParameter::SetMSCCodingScheme(const ECodScheme eNewScheme)
{
if (eMSCCodingScheme != eNewScheme)
{
eMSCCodingScheme = eNewScheme;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSCCodSche();
}
}
void CParameter::SetSDCCodingScheme(const ECodScheme eNewScheme)
{
if (eSDCCodingScheme != eNewScheme)
{
eSDCCodingScheme = eNewScheme;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForSDCCodSche();
}
}
void CParameter::SetCurSelAudioService(const int iNewService)
{
/* Change the current selected audio service ID only if the new ID does
contain an audio service. If not, keep the old ID. In that case it is
possible to select a "data-only" service and still listen to the audio of
the last selected service */
if ((iCurSelAudioService != iNewService) &&
(Service[iNewService].AudioParam.iStreamID != STREAM_ID_NOT_USED))
{
iCurSelAudioService = iNewService;
LastAudioService.Reset();
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForAudParam();
}
}
void CParameter::SetCurSelDataService(const int iNewService)
{
/* Change the current selected data service ID only if the new ID does
contain a data service. If not, keep the old ID. In that case it is
possible to select a "data-only" service and click back to an audio
service to be able to decode data service and listen to audio at the
same time */
if ((iCurSelDataService != iNewService) &&
(Service[iNewService].DataParam.iStreamID != STREAM_ID_NOT_USED))
{
iCurSelDataService = iNewService;
LastDataService.Reset();
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForDataParam();
}
}
void CParameter::SetNumOfServices(const size_t iNNumAuSe, const size_t iNNumDaSe)
{
/* Check whether number of activated services is not greater than the
number of services signalled by the FAC because it can happen that
a false CRC check (it is only a 8 bit CRC) of the FAC block
initializes a wrong service */
set<int> actServ;
GetActiveServices(actServ);
if (actServ.size() > iNNumAuSe + iNNumDaSe)
{
/* Reset services and streams and set flag for init modules */
ResetServicesStreams();
if (pDRMRec) pDRMRec->InitsForMSCDemux();
}
if ((iNumAudioService != iNNumAuSe) || (iNumDataService != iNNumDaSe))
{
iNumAudioService = iNNumAuSe;
iNumDataService = iNNumDaSe;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSCDemux();
}
}
void CParameter::SetAudDataFlag(const int iShortID, const CService::ETyOServ iNewADaFl)
{
if (Service[iShortID].eAudDataFlag != iNewADaFl)
{
Service[iShortID].eAudDataFlag = iNewADaFl;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSC();
}
}
void CParameter::SetServiceID(const int iShortID, const uint32_t iNewServiceID)
{
if (Service[iShortID].iServiceID != iNewServiceID)
{
/* JFBC - what is this for? */
if ((iShortID == 0) && (Service[0].iServiceID > 0))
ResetServicesStreams();
Service[iShortID].iServiceID = iNewServiceID;
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForMSC();
/* If the receiver has lost the sync automatically restore
last current service selected */
if ((iShortID > 0) && (iNewServiceID > 0))
{
if (LastAudioService.iServiceID == iNewServiceID)
{
/* Restore last audio service selected */
iCurSelAudioService = LastAudioService.iService;
LastAudioService.Reset();
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForAudParam();
}
if (LastDataService.iServiceID == iNewServiceID)
{
/* Restore last data service selected */
iCurSelDataService = LastDataService.iService;
LastDataService.Reset();
/* Set init flags */
if (pDRMRec) pDRMRec->InitsForDataParam();
}
}
}
}
/* Append child directory to data files directory,
always terminated by '/' or '\' */
string CParameter::GetDataDirectory(const char* pcChildDirectory) const
{
string sDirectory(sDataFilesDirectory);
size_t p = sDirectory.find_last_of(PATH_SEPARATORS);
if (sDirectory != "" && (p == string::npos || p != (sDirectory.size()-1)))
sDirectory += PATH_SEPARATOR;
if (pcChildDirectory != nullptr)
{
sDirectory += pcChildDirectory;
size_t p = sDirectory.find_last_of(PATH_SEPARATORS);
if (sDirectory != "" && (p == string::npos || p != (sDirectory.size()-1)))
sDirectory += PATH_SEPARATOR;
}
if (sDirectory == "")
sDirectory = DEFAULT_DATA_FILES_DIRECTORY;
return sDirectory;
}
/* Set new data files directory, terminated by '/' or '\' if not */
void CParameter::SetDataDirectory(string sNewDataFilesDirectory)
{
if (sNewDataFilesDirectory == "")
sNewDataFilesDirectory = DEFAULT_DATA_FILES_DIRECTORY;
else
{
size_t p = sNewDataFilesDirectory.find_last_of(PATH_SEPARATORS);
if (p == string::npos || p != (sNewDataFilesDirectory.size()-1))
sNewDataFilesDirectory += PATH_SEPARATOR;
}
sDataFilesDirectory = sNewDataFilesDirectory;
}
/* Implementaions for simulation -------------------------------------------- */
void CRawSimData::Add(uint32_t iNewSRS)
{
/* Attention, function does not take care of overruns, data will be
lost if added to a filled shift register! */
if (iCurWritePos < ciMaxDelBlocks)
veciShRegSt[iCurWritePos++] = iNewSRS;
}
uint32_t CRawSimData::Get()
{
/* We always use the first value of the array for reading and do a
shift of the other data by adding a arbitrary value (0) at the
end of the whole shift register */
uint32_t iRet = veciShRegSt[0];
veciShRegSt.AddEnd(0);
iCurWritePos--;
return iRet;
}
_REAL CParameter::GetSysSNRdBPilPos() const
{
/*
Get system SNR in dB for the pilot positions. Since the average power of
the pilots is higher than the data cells, the SNR is also higher at these
positions compared to the total SNR of the DRM signal.
*/
return (_REAL) 10.0 * log10(pow((_REAL) 10.0, rSysSimSNRdB / 10) /
CellMappingTable.rAvPowPerSymbol *
CellMappingTable.rAvScatPilPow *
(_REAL) CellMappingTable.iNumCarrier);
}
void
CParameter::SetSNR(const _REAL iNewSNR)
{
SNRstat.addSample(iNewSNR);
}
_REAL
CParameter::GetSNR()
{
return SNRstat.getCurrent();
}
_REAL CParameter::GetNominalSNRdB()
{
/* Convert SNR from system bandwidth to nominal bandwidth */
return (_REAL) 10.0 * log10(pow((_REAL) 10.0, rSysSimSNRdB / 10) *
GetSysToNomBWCorrFact());
}
void CParameter::SetNominalSNRdB(const _REAL rSNRdBNominal)
{
/* Convert SNR from nominal bandwidth to system bandwidth */
rSysSimSNRdB = (_REAL) 10.0 * log10(pow((_REAL) 10.0, rSNRdBNominal / 10) /
GetSysToNomBWCorrFact());
}
_REAL CParameter::GetNominalBandwidth()
{
_REAL rNomBW;
/* Nominal bandwidth as defined in the DRM standard */
switch (eSpectOccup)
{
case SO_0:
rNomBW = (_REAL) 4500.0; /* Hz */
break;
case SO_1:
rNomBW = (_REAL) 5000.0; /* Hz */
break;
case SO_2:
rNomBW = (_REAL) 9000.0; /* Hz */
break;
case SO_3:
rNomBW = (_REAL) 10000.0; /* Hz */
break;
case SO_4:
rNomBW = (_REAL) 18000.0; /* Hz */
break;
case SO_5:
rNomBW = (_REAL) 20000.0; /* Hz */
break;
default:
rNomBW = (_REAL) 10000.0; /* Hz */
break;
}
return rNomBW;
}
_REAL CParameter::GetSysToNomBWCorrFact()
{
_REAL rNomBW = GetNominalBandwidth();
/* Calculate system bandwidth (N / T_u) */
const _REAL rSysBW = (_REAL) CellMappingTable.iNumCarrier / CellMappingTable.iFFTSizeN * iSigSampleRate;
return rSysBW / rNomBW;
}
void CParameter::SetIFSignalLevel(_REAL rNewSigStr)
{
rIFSigStr = rNewSigStr;
}
_REAL CParameter::GetIFSignalLevel()
{
return rIFSigStr;
}
void CRxStatus::SetStatus(const ETypeRxStatus OK)
{
status = OK;
iNum++;
if (OK==RX_OK)
iNumOK++;
}
void CParameter::GenerateReceiverID()
{
stringstream ssInfoVer;
ssInfoVer << setw(2) << setfill('0') << setw(2) << setfill('0') << dream_version_major << setw(2) << setfill('0') << dream_version_minor;
sReceiverID = string(dream_manufacturer)+string(dream_implementation)+ssInfoVer.str();
while (sSerialNumber.length() < 6)
sSerialNumber += "_";
if (sSerialNumber.length() > 6)
sSerialNumber.erase(6, sSerialNumber.length()-6);
sReceiverID += sSerialNumber;
}
void CParameter::GenerateRandomSerialNumber()
{
//seed random number generator
srand((unsigned int)time(0));
char randomChars[36];
for (size_t q=0; q < 36; q++)
{
if (q < 26)
randomChars[q] = char(q)+97;
else
randomChars[q] = (char(q)-26)+48;
}
char serialNumTemp[7];
for (size_t i=0; i < 6; i++)
#ifdef _WIN32
serialNumTemp[i] = randomChars[(int) 35.0*rand()/RAND_MAX]; /* integer overflow on linux, RAND_MAX=0x7FFFFFFF */
#else
serialNumTemp[i] = randomChars[35ll * (long long)rand() / RAND_MAX];
#endif
serialNumTemp[6] = '\0';
sSerialNumber = serialNumTemp;
}
CMinMaxMean::CMinMaxMean():rSum(0.0),rCur(0.0),
rMin(numeric_limits<_REAL>::max()),rMax(numeric_limits<_REAL>::min()),iNum(0)
{
}
void
CMinMaxMean::addSample(_REAL r)
{
rCur = r;
rSum += r;
iNum++;
if (r>rMax)
rMax = r;
if (r<rMin)
rMin = r;
}
_REAL
CMinMaxMean::getCurrent()
{
return rCur;
}
_REAL
CMinMaxMean::getMean()
{
_REAL rMean = 0.0;
if (iNum>0)
rMean = rSum / iNum;
rSum = 0.0;
iNum = 0;
return rMean;
}
void
CMinMaxMean::getMinMax(_REAL& rMinOut, _REAL& rMaxOut)
{
if (rMin <= rMax)
{
rMinOut = rMin;
rMaxOut = rMax;
}
else
{
rMinOut = 0.0;
rMaxOut = 0.0;
}
rMin = numeric_limits<_REAL>::max();
rMax = numeric_limits<_REAL>::min();
}
string CServiceDefinition::Frequency(size_t n) const
{
if (n>=veciFrequencies.size())
return ""; // not in the list
stringstream ss;
int iFrequency = veciFrequencies[n];
switch (iSystemID)
{
case 0:
case 1:
case 2:
/* AM or DRM */
ss << iFrequency;
break;
case 3:
case 4:
case 5:
/* 'FM1 frequency' - 87.5 to 107.9 MHz (100 kHz steps) */
ss << 87.5 + 0.1 * float(iFrequency);
break;
case 6:
case 7:
case 8:
/* 'FM2 frequency'- 76.0 to 90.0 MHz (100 kHz steps) */
ss << 76.0 + 0.1 * float(iFrequency);
break;
case 9:
case 10:
case 11:
if (iFrequency<=11) {
int chan = iFrequency / 4;
char subchan = 'A' + iFrequency % 4;
ss << "Band I channel " << (chan+2) << subchan;
} else if (64<= iFrequency && iFrequency <=95) {
int chan = iFrequency / 4;
char subchan = 'A' + iFrequency % 4;
ss << "Band III channel " << (chan-11) << subchan;
} else if (96<= iFrequency && iFrequency <=101) {
int chan = iFrequency / 6;
char subchan = 'A' + iFrequency % 6;
ss << "Band III+ channel " << (chan-3) << subchan;
} else if (128<= iFrequency && iFrequency <=143) {
char chan = iFrequency - 128;
double m = 1452.96+1.712*double(chan);
ss << "European L-Band channel L" << ('A'+chan) << ", " << m << " MHz";
} else if (160<= iFrequency && iFrequency <=182) {
int chan = iFrequency - 159;
double m = 1451.072+1.744*double(chan);
ss << "Canadian L-Band channel " << chan << ", " << m << " MHz";
} else {
ss << "unknown channel " << iFrequency;
}
break;
default:
break;
}
return ss.str();
}
string CServiceDefinition::FrequencyUnits() const
{
switch (iSystemID)
{
case 0:
case 1:
case 2:
return "kHz";
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
return "MHz";
break;
default:
return "";
break;
}
}
string CServiceDefinition::System() const
{
switch (iSystemID)
{
case 0:
return "DRM";
break;
case 1:
case 2:
return "AM";
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
return "FM";
break;
case 9:
case 10:
case 11:
return "DAB";
break;
default:
return "";
break;
}
}
string COtherService::ServiceID() const
{
stringstream ss;
/*
switch (iSystemID)
{
case 0:
case 1:
ss << "ID:" << hex << setw(6) << iServiceID;
break;
case 3:
case 6:
ss << "ECC+PI:" << hex << setw(6) << iServiceID;
break;
case 4:
case 7:
ss << "PI:" << hex << setw(4) << iServiceID;
break;
case 9:
ss << "ECC+aud:" << hex << setw(6) << iServiceID;
break;
case 10:
ss << "AUDIO:" << hex << setw(4) << iServiceID;
break;
case 11:
ss << "DATA:" << hex << setw(8) << iServiceID;
break;
break;
default:
break;
}
*/
return ss.str();
}
/* See ETSI ES 201 980 v2.1.1 Annex O */
bool
CAltFreqSched::IsActive(const time_t ltime)
{
int iScheduleStart;
int iScheduleEnd;
int iWeekDay;
/* Empty schedule is always active */
if (iDuration == 0)
return true;
/* Calculate time in UTC */
struct tm *gmtCur = gmtime(<ime);
/* Check day
tm_wday: day of week (0 - 6; Sunday = 0)
I must normalize so Monday = 0 */
if (gmtCur->tm_wday == 0)
iWeekDay = 6;
else
iWeekDay = gmtCur->tm_wday - 1;
/* iTimeWeek minutes since last Monday 00:00 in UTC */
/* the value is in the range 0 <= iTimeWeek < 60 * 24 * 7) */
const int iTimeWeek =
(iWeekDay * 24 * 60) + (gmtCur->tm_hour * 60) + gmtCur->tm_min;
/* Day Code: this field indicates which days the frequency schedule
* (the following Start Time and Duration) applies to.
* The msb indicates Monday, the lsb Sunday. Between one and seven bits may be set to 1.
*/
for (int i = 0; i < 7; i++)
{
/* Check if day is active */
if ((1 << (6 - i)) & iDayCode)
{
/* Tuesday -> 1 * 24 * 60 = 1440 */
iScheduleStart = (i * 24 * 60) + iStartTime;
iScheduleEnd = iScheduleStart + iDuration;
/* the normal check (are we inside start and end?) */
if ((iTimeWeek >= iScheduleStart) && (iTimeWeek <= iScheduleEnd))
return true;
/* the wrap-around check */
const int iMinutesPerWeek = 7 * 24 * 60;
if (iScheduleEnd > iMinutesPerWeek)
{
/* our duration wraps into next Monday (or even later) */
if (iTimeWeek < (iScheduleEnd - iMinutesPerWeek))
return true;
}
}
}
return false;
}
| 28.996466 | 141 | 0.633634 | [
"vector"
] |
b144b4a0f9584bde41bca66906eda30be637525c | 1,690 | cpp | C++ | dataset/test/1471/9.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/1471/9.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/1471/9.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include <unordered_map>
#include<unordered_set>
using namespace std;
#define _USE_MATH_DEFINES
# define M_PI 3.14159265358979323846 /* pi */
#define ll long long
#define ull unsigned long long
#define ld long double
#define vbe(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define prec(x) << fixed<< setprecision(x)
#define clr(v, d) memset(v, d, sizeof(v))
#define rep(i, v) for(int i=0;i<sz(v);++i)
#define lp(i, n) for(int i=0;i<(int)(n);++i)
#define lpi(i, j, n) for(int i=(j);i<(int)(n);++i)
#define lpd(i, j, n) for(int i=(j);i>=(int)(n);--i)
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define FASTIO ios_base::sync_with_stdio(false); cin.tie(NULL); cin.tie(0);
#define INFLL 1e18
#define INF 1e9
#define MOD 1000000007
#define MOD1 998244353
#define MAXN 200005
ll GCD(ll a, ll b) { return (a) ? GCD(b % a, a) : b; }
ll LCM(ll a, ll b) { return a * b / GCD(a, b); }
ll fastpow(ll b, ll p) {
if (!p) return 1;
ll ret = fastpow(b, p >> 1);
ret *= ret;
if (p & 1) ret *= b;
return ret;
}
void solve(int tst) {
ll n, m;
cin >> n >> m;
vector<ll> k(n), c(m);
lp(i, n) {
cin >> k[i];
k[i]--;
}
lp(i, m)cin >> c[i];
sort(vbe(k));
reverse(vbe(k));
int idx=0;
ll ans=0;
lp(i,n){
if(k[i]>=idx){
ans+=c[idx++];
}else{
ans+=c[k[i]];
}
}
cout<<ans;
}
int main() {
FASTIO;
//freopen("gaser.in", "r", stdin);
int t = 1;
cin >> t;
lp(i, t) {
solve(i + 1);
cout << "\n";
}
} | 23.472222 | 76 | 0.488757 | [
"vector"
] |
b152a7ef3e2c62d4b5257894636d37f70a2979f5 | 2,599 | cpp | C++ | aws-cpp-sdk-kendra/source/model/GroupOrderingIdSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-kendra/source/model/GroupOrderingIdSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-kendra/source/model/GroupOrderingIdSummary.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/kendra/model/GroupOrderingIdSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace kendra
{
namespace Model
{
GroupOrderingIdSummary::GroupOrderingIdSummary() :
m_status(PrincipalMappingStatus::NOT_SET),
m_statusHasBeenSet(false),
m_lastUpdatedAtHasBeenSet(false),
m_receivedAtHasBeenSet(false),
m_orderingId(0),
m_orderingIdHasBeenSet(false),
m_failureReasonHasBeenSet(false)
{
}
GroupOrderingIdSummary::GroupOrderingIdSummary(JsonView jsonValue) :
m_status(PrincipalMappingStatus::NOT_SET),
m_statusHasBeenSet(false),
m_lastUpdatedAtHasBeenSet(false),
m_receivedAtHasBeenSet(false),
m_orderingId(0),
m_orderingIdHasBeenSet(false),
m_failureReasonHasBeenSet(false)
{
*this = jsonValue;
}
GroupOrderingIdSummary& GroupOrderingIdSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Status"))
{
m_status = PrincipalMappingStatusMapper::GetPrincipalMappingStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("LastUpdatedAt"))
{
m_lastUpdatedAt = jsonValue.GetDouble("LastUpdatedAt");
m_lastUpdatedAtHasBeenSet = true;
}
if(jsonValue.ValueExists("ReceivedAt"))
{
m_receivedAt = jsonValue.GetDouble("ReceivedAt");
m_receivedAtHasBeenSet = true;
}
if(jsonValue.ValueExists("OrderingId"))
{
m_orderingId = jsonValue.GetInt64("OrderingId");
m_orderingIdHasBeenSet = true;
}
if(jsonValue.ValueExists("FailureReason"))
{
m_failureReason = jsonValue.GetString("FailureReason");
m_failureReasonHasBeenSet = true;
}
return *this;
}
JsonValue GroupOrderingIdSummary::Jsonize() const
{
JsonValue payload;
if(m_statusHasBeenSet)
{
payload.WithString("Status", PrincipalMappingStatusMapper::GetNameForPrincipalMappingStatus(m_status));
}
if(m_lastUpdatedAtHasBeenSet)
{
payload.WithDouble("LastUpdatedAt", m_lastUpdatedAt.SecondsWithMSPrecision());
}
if(m_receivedAtHasBeenSet)
{
payload.WithDouble("ReceivedAt", m_receivedAt.SecondsWithMSPrecision());
}
if(m_orderingIdHasBeenSet)
{
payload.WithInt64("OrderingId", m_orderingId);
}
if(m_failureReasonHasBeenSet)
{
payload.WithString("FailureReason", m_failureReason);
}
return payload;
}
} // namespace Model
} // namespace kendra
} // namespace Aws
| 21.479339 | 109 | 0.743363 | [
"model"
] |
b1559006799b9f7e8fecb5cdc3e366fcc7de6528 | 9,392 | cpp | C++ | Solver.cpp | darkedge/GT1 | b9b569909c4d505f16400e8b744fba714077c952 | [
"MIT"
] | 1 | 2020-11-08T21:08:04.000Z | 2020-11-08T21:08:04.000Z | Solver.cpp | darkedge/GT1 | b9b569909c4d505f16400e8b744fba714077c952 | [
"MIT"
] | null | null | null | Solver.cpp | darkedge/GT1 | b9b569909c4d505f16400e8b744fba714077c952 | [
"MIT"
] | null | null | null | #include "Solver.h"
#include "RigidBody.h"
#include "Transform.h"
using namespace GT1;
using glm::vec3;
using glm::mat3;
const int Solver::ITERATION_COUNT = 100;
// For the Successive Overrelaxation Method;
// @see http://mathworld.wolfram.com/SuccessiveOverrelaxationMethod.html
const float Solver::RELAXATION = 1.0f;
const float Solver::GRAVITY = 3.0f;
/************************************************************************/
/* Class vecN */
/************************************************************************/
vecN::vecN(int size) {
this->size = size;
cell = new float[size];
LoadZero();
}
vecN::vecN(const vecN& copy) {
this->size = copy.size;
cell = new float[size];
for(int i = 0; i < size; i++)
cell[i] = copy[i];
}
vecN::~vecN() {
delete[] cell;
cell = nullptr;
}
void vecN::LoadZero() {
for(int i = 0; i < size; i++)
cell[i] = 0.0f;
}
// Unchecked
void vecN::InsertVec3(int i, glm::vec3 vec) {
assert(i + 2 < size);
assert(i >= 0);
memcpy(cell + i, &vec[0], sizeof(float) * 3);
}
void vecN::Set(int i, float f) {
assert(i >= 0);
assert(i < size);
cell[i] = f;
}
vec3 vecN::GetVec3(int i) const {
assert(i + 2 < size);
assert(i >= 0);
return vec3(cell[i], cell[i + 1], cell[i + 2]);
}
/************************************************************************/
/* Class matSxN */
/************************************************************************/
matMxN::matMxN(int width, int height) {
this->width = width;
this->height = height;
cell = new float*[height];
for(int i = 0; i < height; i++)
cell[i] = new float[width];
LoadZero();
}
matMxN::matMxN(const matMxN& copy) {
this->width = copy.width;
this->height = copy.height;
cell = new float*[height];
for(int i = 0; i < height; i++)
cell[i] = new float[width];
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
cell[y][x] = copy[y][x];
}
matMxN::~matMxN() {
for(int i = 0; i < height; i++)
delete[] cell[i];
delete[] cell;
}
void matMxN::LoadZero() {
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
cell[y][x] = 0.0f;
}
void matMxN::Set(int x, int y, float val) {
assert(x < width);
assert(x >= 0);
assert(y < height);
assert(y >= 0);
cell[y][x] = val;
}
void matMxN::InsertVec3(int x, int y, vec3 vec) {
assert(x >= 0);
assert(x + 2 < width);
assert(y >= 0);
assert(y < height);
memcpy(cell[y] + x, &vec[0], sizeof(float) * 3);
}
/************************************************************************/
/* Transpose */
/************************************************************************/
matMxN Transpose(const matMxN& mat) {
matMxN result(mat.height, mat.width);
for(int x = 0; x < mat.width; x++)
for(int y = 0; y < mat.height; y++)
result[x][y] = mat[y][x];
return result;
}
/************************************************************************/
/* Class MatCSR */
/************************************************************************/
// Converts a dense matrix to a Compressed Sparse Row matrix.
matCSR::matCSR(const matMxN& mat) {
this->width = mat.width;
this->height = mat.height;
int row = 0;
int k = 0;
row_ptr.reserve(mat.height);
for(int i = 0; i < mat.height; i++) {
int sum = 0;
for(int j = 0; j < mat.width; j++) {
if(mat.cell[i][j] != 0.0f) {
val.push_back(mat.cell[i][j]);
col_ind.push_back(j);
sum++;
}
}
row_ptr.push_back(sum);
}
}
/************************************************************************/
/* Class Constraint */
/************************************************************************/
ContactConstraint::ContactConstraint(glm::vec3 normal, float distance, glm::vec3 r_A, glm::vec3 r_B, RigidBody* a, RigidBody* b) {
this->normal = normal;
this->distance = distance;
this->r_A = r_A;
this->r_B = r_B;
this->rb_A = a;
this->rb_B = b;
this->indexA = Solver::RegisterRigidBody(a);
this->indexB = Solver::RegisterRigidBody(b);
}
void ContactConstraint::FillJacobian(matMxN& mat, int row, vecN& epsilon, vecN& min, vecN& max, float dt) {
mat.InsertVec3(indexA * 6 + 0, row, -normal);
mat.InsertVec3(indexA * 6 + 3, row, -glm::cross(r_A, normal));
mat.InsertVec3(indexB * 6 + 0, row, normal);
mat.InsertVec3(indexB * 6 + 3, row, glm::cross(r_B, normal));
//epsilon->Set(row, distance * 0.00015f / dt);
epsilon[row] = 0.0f;
min[row] = 0.0f;
max[row] = FLT_MAX;
}
FrictionConstraint::FrictionConstraint(glm::vec3 tangent, float mass, glm::vec3 r_A, glm::vec3 r_B, RigidBody* rb_A, RigidBody* rb_B) {
this->tangent = tangent;
this->mass = mass;
this->r_A = r_A;
this->r_B = r_B;
this->rb_A = rb_A;
this->rb_B = rb_B;
this->indexA = Solver::RegisterRigidBody(rb_A);
this->indexB = Solver::RegisterRigidBody(rb_B);
}
void FrictionConstraint::FillJacobian(matMxN& mat, int row, vecN& epsilon, vecN& min, vecN& max, float dt) {
mat.InsertVec3(indexA * 6 + 0, row, -tangent);
mat.InsertVec3(indexA * 6 + 3, row, -glm::cross(r_A, tangent));
mat.InsertVec3(indexB * 6 + 0, row, tangent);
mat.InsertVec3(indexB * 6 + 3, row, glm::cross(r_B, tangent));
epsilon[row] = 0.0f;
min[row] = -0.5f * mass * Solver::GRAVITY;
max[row] = 0.5f * mass * Solver::GRAVITY;
}
/************************************************************************/
/* Class Solver */
/************************************************************************/
std::vector<Constraint*> Solver::constraints;
std::vector<RigidBody*> Solver::rigidBodies;
void Solver::Solve(float dt) {
// Amount of constraints
int s = (int) constraints.size();
if(s == 0) return;
// Number of rigid bodies * 6
int matrixWidth = rigidBodies.size() * 6;
// Velocity vector of all bodies
vecN V(matrixWidth);
// Inverted mass matrix
matMxN M⁻¹(matrixWidth, matrixWidth);
// External vector
vecN Fext(matrixWidth);
// Fill V, M⁻¹ and F
for (int i = 0; i < (int) rigidBodies.size(); i++) {
RigidBody* rb = rigidBodies[i];
// Velocity vector layout
// [Vx Vy Vz ωx ωy ωz [...]]
V.InsertVec3(i * 6, rb->GetVelocity());
V.InsertVec3(i * 6 + 3, rb->GetAngularVelocity());
mat3 I⁻¹ = rb->GetInvertedInertiaTensor();
// Fill matrix like this:
//
// m⁻¹ 0 0 0 0 0 ...
// 0 m⁻¹ 0 0 0 0 ...
// 0 0 m⁻¹ 0 0 0 ...
// 0 0 0 I⁻¹ I⁻¹ I⁻¹ ...
// 0 0 0 I⁻¹ I⁻¹ I⁻¹ ...
// 0 0 0 I⁻¹ I⁻¹ I⁻¹ ...
// ... ... ... ... ... ... [...]
for(int j = 0; j < 3; j++)
M⁻¹.Set(i * 6 + j, i * 6 + j, rb->GetInvertedMass());
for(int y = 0; y < 3; y++)
for(int x = 0; x < 3; x++)
M⁻¹[i * 6 + 3 + y][i * 6 + 3 + x] = I⁻¹[y][x];
// Force vector layout:
// [Fx Fy Fz τx τy τz [...]]
Fext.InsertVec3(i * 6 + 0, rb->NetForce());
Fext.InsertVec3(i * 6 + 3, rb->NetTorque());
}
// Create Jacobian
matMxN J(matrixWidth, s);
// "ϵ is the vector of force offsets
// which allows contact forces to perform work"
vecN epsilon(s);
vecN projMin(s);
vecN projMax(s);
// Let each constraint fill its row
for(int i = 0; i < s; i++)
constraints[i]->FillJacobian(J, i, epsilon, projMin, projMax, dt);
matMxN Jt = Transpose(J);
// From the slides:
// Ax = b where
// A = J * M⁻¹ * Jt
// b = ϵ / Δt - J * V1 - Δt * J * M⁻¹ * Fext
matMxN A = (J * M⁻¹) * Jt;
vecN b = (epsilon / dt) - (J * V) - dt * ((J * M⁻¹) * Fext);
// Solve Ax = b iteratively using PGS
// From this we get a Lagrange multiplier
vecN λ = SolvePGS(A, b, RELAXATION, projMin, projMax, ITERATION_COUNT);
// Multiplying the transposed Jacobian with the Lagrange multiplier
// gives us a change in momentum
vecN P = Jt * λ;
// Apply momentum
for(int i = 0; i < (int) rigidBodies.size(); i++)
rigidBodies[i]->AddMomentum(P.GetVec3(i * 6 + 0), P.GetVec3(i * 6 + 3));
}
// @see: http://stackoverflow.com/questions/11719704/projected-gauss-seidel-for-lcp
// Projected Gauss-Seidel with successive over-relaxation (SOR)
vecN Solver::SolvePGS(matMxN& A, vecN& b, float relaxation, vecN& min, vecN& max, int iterations) {
assert(A.width == b.GetSize());
matCSR csr(A);
int n = b.GetSize();
float delta;
vecN x = b;
while(iterations--) {
int i = 0;
int begin = 0, end = 0;
// for height
for(int it = 0; it < (int) csr.row_ptr.size(); it++, i++) {
// Reset delta
delta = 0.0f;
begin = end;
end += csr.row_ptr[it];
for(int j = begin; j < end; j++) {
if(csr.col_ind[j] != i) {
delta += csr.val[j] * x[csr.col_ind[j]];
}
}
delta = (b[i] - delta) / A[i][i];
// Apply relaxation
x[i] += relaxation * (delta - x[i]);
// Clamping
if(x[i] < min[i])
x[i] = min[i];
else if(x[i] > max[i])
x[i] = max[i];
}
}
return x;
}
// Puts a rigid body into the solver and returns its index
// for future reference. If the body is already listed, then
// that body's index is returned instead.
int Solver::RegisterRigidBody(RigidBody* rb) {
for(int i = 0; i < (int) rigidBodies.size(); i++)
if(rigidBodies[i] == rb) return i;
rigidBodies.push_back(rb);
return (int) (rigidBodies.size() - 1);
}
void Solver::Clear() {
rigidBodies.clear();
for(Constraint* c : constraints)
delete c;
constraints.clear();
} | 25.873278 | 135 | 0.526512 | [
"vector",
"transform"
] |
b15ad3e40870c485dfa79cc91d4c844f8e51a703 | 29,755 | cpp | C++ | impl/src/model.cpp | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null | impl/src/model.cpp | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null | impl/src/model.cpp | mvendra/bolotracker | 2eab0505030b8615de173ce596bb12491a8977f2 | [
"MIT"
] | null | null | null |
#include "model.h"
#include "utils/conversions.h"
#include "exceptions/ex_model_error.h"
#include <vector>
using strvec2 = std::vector<std::vector<std::string>>;
Model::Model():connection{}, db{}{
}
void Model::open_database(){
db.db_path = connection;
db.open_database();
}
void Model::close_database(){
db.close_database();
}
Model::Model(const std::string &conn):connection{conn}, db{connection}{
}
Model::~Model(){
}
//////////////////////
/* WRITE OPERATIONS */
//////////////////////
void Model::add_investor(const std::string& name, const std::string &email,
const std::string& desc, const DateHelper &date_inclusion)
{
std::string name_local {name}; makeStrLower(name_local);
std::string email_local {email}; //makeStrLower(email_local);
std::string desc_local {desc}; //makeStrLower(desc_local);
// prevent duplicates
if (has_investor(name_local)){
EX_THROW(Ex_Model_Error, "Investor named [" + name_local + "] already exists. Unable to add duplicate.");
}
std::string sql {"INSERT INTO investors(name, email, description, date_of_inclusion) VALUES(\""};
sql += name_local + "\", \"" + email_local + "\", \"" + desc_local + "\", \"" + date_inclusion.getDateString() + "\");";
db.exec(sql);
}
void Model::add_subject(const std::string& tag, const std::string &description,
const DateHelper &date_inclusion)
{
std::string tag_local {tag}; makeStrLower(tag_local);
std::string description_local {description}; //makeStrLower(description_local);
if (has_subject(tag_local)){
EX_THROW(Ex_Model_Error, "Subject named [" + tag_local + "] already exists. Unable to add duplicate.");
}
std::string sql {"INSERT INTO subjects(tag, description, date_of_inclusion) VALUES(\""};
sql += tag_local + "\", \"" + description_local + "\", \"" + date_inclusion.getDateString() + "\");";
db.exec(sql);
}
void Model::add_currency(const std::string& label, const std::string &description,
const DateHelper &date_inclusion)
{
std::string label_local {label}; makeStrLower(label_local);
std::string description_local {description}; //makeStrLower(description_local);
if (has_currency(label_local)){
EX_THROW(Ex_Model_Error, "Currency named [" + label_local + "] already exists. Unable to add duplicate.");
}
std::string sql {"INSERT INTO currencies(label, description, date_of_inclusion) VALUES(\""};
sql += label_local + "\", \"" + description_local + "\", \"" + date_inclusion.getDateString() + "\");";
db.exec(sql);
}
void Model::add_invested_time(const std::string &investor_name, const std::string ¤cy_label,
const DateHelper &date, const std::string &description,
const std::string &comment, const unsigned int minutes,
const double price_per_unit)
{
std::string investor_name_local {investor_name}; makeStrLower(investor_name_local);
std::string currency_label_local {currency_label}; makeStrLower(currency_label_local);
unsigned int fk_investor {get_pk_investor(investor_name_local)};
unsigned int fk_currency {get_pk_currency(currency_label_local)};
add_invested_time(fk_investor, fk_currency, date, description, comment, minutes, price_per_unit);
}
void Model::add_invested_time(const unsigned int fk_investor, const unsigned int fk_currency,
const DateHelper &date, const std::string &description,
const std::string &comment, const unsigned int minutes,
const double price_per_unit)
{
std::string description_local {description}; //makeStrLower(description_local);
std::string comment_local {comment}; //makeStrLower(comment_local);
std::string sql {"INSERT INTO invested_time(fk_investor, fk_currency, date, description, comment, minutes, price_per_unit) VALUES("};
sql += uintToStr(fk_investor) + ", " + uintToStr(fk_currency) + ", \"" + date.getDateString() + "\", \"" + description_local + "\", \"";
sql += comment_local + "\", " + uintToStr(minutes) + ", " + doubleToStr(price_per_unit) + ");";
db.exec(sql);
}
void Model::attach_subject_to_invested_time(const unsigned int pk_invested_time, const std::string &subject_tag){
std::string subject_tag_local {subject_tag}; makeStrLower(subject_tag_local);
unsigned int pk_subject {get_pk_subject(subject_tag_local)};
attach_subject_to_invested_time(pk_invested_time, pk_subject);
}
void Model::attach_subject_to_invested_time(const unsigned int pk_invested_time, const unsigned int pk_subject){
std::string sql {"INSERT INTO invested_time_subjects_link(fk_invested_time, fk_subject) VALUES("};
sql += uintToStr(pk_invested_time) + ", " + uintToStr(pk_subject) + ");";
db.exec(sql);
}
void Model::add_invested_asset(const std::string &investor_name, const std::string ¤cy_label,
const DateHelper &date, const std::string &short_name,
const std::string &description, const std::string &comment,
const double price)
{
std::string investor_name_local {investor_name}; makeStrLower(investor_name_local);
std::string currency_label_local {currency_label}; makeStrLower(currency_label_local);
unsigned int fk_investor {get_pk_investor(investor_name_local)};
unsigned int fk_currency {get_pk_currency(currency_label_local)};
add_invested_asset(fk_investor, fk_currency, date, short_name, description, comment, price);
}
void Model::add_invested_asset(const unsigned int fk_investor, const unsigned int fk_currency,
const DateHelper &date, const std::string &short_name,
const std::string &description, const std::string &comment,
const double price)
{
std::string short_name_local {short_name}; //makeStrLower(short_name_local);
std::string description_local {description}; //makeStrLower(description_local);
std::string comment_local {comment}; //makeStrLower(comment_local);
std::string sql {"INSERT INTO invested_assets(fk_investor, fk_currency, date, short_name, description, comment, price) VALUES("};
sql += uintToStr(fk_investor) + ", " + uintToStr(fk_currency) + ", \"" + date.getDateString() + "\", \"" + short_name_local + "\", \"";
sql += description_local + "\", \"" + comment_local + "\", " + doubleToStr(price) + ");";
db.exec(sql);
}
void Model::attach_subject_to_invested_asset(const unsigned int pk_invested_asset, const std::string &subject_tag){
std::string subject_tag_local {subject_tag}; makeStrLower(subject_tag_local);
unsigned int pk_subject {get_pk_subject(subject_tag_local)};
attach_subject_to_invested_asset(pk_invested_asset, pk_subject);
}
void Model::attach_subject_to_invested_asset(const unsigned int pk_invested_asset, const unsigned int pk_subject){
std::string sql {"INSERT INTO invested_assets_subjects_link(fk_invested_asset, fk_subject) VALUES("};
sql += uintToStr(pk_invested_asset) + ", " + uintToStr(pk_subject) + ");";
db.exec(sql);
}
void Model::add_bonus(const std::string &investor_name, const DateHelper &date,
const std::string &short_name, const std::string &description,
const std::string &comment, const std::string &reward)
{
std::string investor_name_local {investor_name}; makeStrLower(investor_name_local);
unsigned int pk_investor {get_pk_investor(investor_name_local)};
add_bonus(pk_investor, date, short_name, description, comment, reward);
}
void Model::add_bonus(const unsigned int fk_investor, const DateHelper &date,
const std::string &short_name, const std::string &description,
const std::string &comment, const std::string &reward)
{
std::string short_name_local {short_name}; //makeStrLower(short_name_local);
std::string description_local {description}; //makeStrLower(description_local);
std::string comment_local {comment}; //makeStrLower(comment_local);
std::string reward_local {reward}; //makeStrLower(reward_local);
std::string sql {"INSERT INTO bonuses(fk_investor, date, short_name, description, comment, reward) VALUES("};
sql += uintToStr(fk_investor) + ", \"" + date.getDateString() + "\", \"" + short_name_local + "\", \"";
sql += description_local + "\", \"" + comment_local + "\", \"" + reward_local + "\");";
db.exec(sql);
}
void Model::attach_subject_to_bonus(const unsigned int pk_bonus, const std::string &subject_tag){
std::string subject_tag_local {subject_tag}; makeStrLower(subject_tag_local);
unsigned int pk_subject {get_pk_subject(subject_tag_local)};
attach_subject_to_bonus(pk_bonus, pk_subject);
}
void Model::attach_subject_to_bonus(const unsigned int pk_bonus, const unsigned int pk_subject){
std::string sql {"INSERT INTO bonuses_subjects_link(fk_bonus, fk_subject) VALUES("};
sql += uintToStr(pk_bonus) + ", " + uintToStr(pk_subject) + ");";
db.exec(sql);
}
void Model::add_invested_money(const std::string &investor_name, const std::string ¤cy_label,
const DateHelper &date, const std::string &short_name,
const std::string &description, const std::string &comment,
const double amount)
{
std::string investor_name_local {investor_name}; makeStrLower(investor_name_local);
std::string currency_label_local {currency_label}; makeStrLower(currency_label_local);
unsigned int pk_investor {get_pk_investor(investor_name_local)};
unsigned int pk_currency {get_pk_currency(currency_label_local)};
add_invested_money(pk_investor, pk_currency, date, short_name, description, comment, amount);
}
void Model::add_invested_money(const unsigned int fk_investor, const unsigned int fk_currency,
const DateHelper &date, const std::string &short_name,
const std::string &description, const std::string &comment,
const double amount)
{
std::string short_name_local {short_name}; //makeStrLower(short_name_local);
std::string description_local {description}; //makeStrLower(description_local);
std::string comment_local {comment}; //makeStrLower(comment_local);
std::string sql {"INSERT INTO invested_money(fk_investor, fk_currency, date, short_name, description, comment, amount) VALUES("};
sql += uintToStr(fk_investor) + ", " + uintToStr(fk_currency) + ", \"" + date.getDateString() + "\", \"" + short_name_local + "\", \"";
sql += description_local + "\", \"" + comment_local + "\", " + doubleToStr(amount) + ");";
db.exec(sql);
}
void Model::attach_subject_to_invested_money(const unsigned int pk_invested_money, const std::string &subject_tag){
std::string subject_tag_local {subject_tag}; makeStrLower(subject_tag_local);
unsigned int pk_subject {get_pk_subject(subject_tag_local)};
attach_subject_to_invested_money(pk_invested_money, pk_subject);
}
void Model::attach_subject_to_invested_money(const unsigned int pk_invested_money, const unsigned int pk_subject){
std::string sql {"INSERT INTO invested_money_subjects_link(fk_invested_money, fk_subject) VALUES("};
sql += uintToStr(pk_invested_money) + ", " + uintToStr(pk_subject) + ");";
db.exec(sql);
}
/////////////////////
/* READ OPERATIONS */
/////////////////////
bool Model::has_investor(const std::string& name){
bool r {has_any_helper("name", name, "pk_investor", "investors")};
return r;
}
bool Model::has_subject(const std::string& tag){
bool r {has_any_helper("tag", tag, "pk_subject", "subjects")};
return r;
}
bool Model::has_currency(const std::string& label){
bool r {has_any_helper("label", label, "pk_currency", "currencies")};
return r;
}
bool Model::get_investor_info(const std::string &name, Investor &inv){
std::string name_local {name}; makeStrLower(name_local);
std::string sql {"SELECT * FROM investors WHERE name = \""};
sql += name_local + "\";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
} else if (res.size() > 1){
EX_THROW(Ex_Model_Error, "While getting investor info for [" + name_local + "], more than one record was returned. This is likely a duplicate.");
}
if (res[0].size() != 5){
EX_THROW(Ex_Model_Error, "While getting investor info for [" + name_local + "], less than 5 columns were returned. This is likely a faulty schema.");
}
inv.pk_investor = strToUint(res[0][0]);
inv.name = name;
inv.email = res[0][2];
inv.description = res[0][3];
inv.date_of_inclusion.setDate(res[0][4]);
return true;
}
bool Model::get_investor_info(const unsigned int pk_investor, Investor &inv){
std::string sql {"SELECT * FROM investors WHERE pk_investor = "};
sql += uintToStr(pk_investor) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
} else if (res.size() > 1){
EX_THROW(Ex_Model_Error, "While getting investor info for [" + uintToStr(pk_investor) + "], more than one record was returned. This is likely a duplicate.");
}
if (res[0].size() != 5){
EX_THROW(Ex_Model_Error, "While getting investor info for [" + uintToStr(pk_investor) + "], more or less than 5 columns were returned. This is likely a faulty schema.");
}
inv.pk_investor = pk_investor;
inv.name = res[0][1];
inv.email = res[0][2];
inv.description = res[0][3];
inv.date_of_inclusion.setDate(res[0][4]);
return true;
}
bool Model::get_subject_info(const std::string &tag, Subject &subj){
std::string tag_local {tag}; makeStrLower(tag_local);
std::string sql {"SELECT * FROM subjects WHERE tag = \""};
sql += tag_local + "\";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
} else if (res.size() > 1){
EX_THROW(Ex_Model_Error, "While getting subject info for [" + tag_local + "], more than one record was returned. This is likely a duplicate.");
}
if (res[0].size() != 4){
EX_THROW(Ex_Model_Error, "While getting subject info for [" + tag_local + "], more or less than 4 columns were returned. This is likely a faulty schema.");
}
subj.pk_subject = strToUint(res[0][0]);
subj.tag = tag;
subj.description = res[0][2];
subj.date_of_inclusion.setDate(res[0][3]);
return true;
}
bool Model::get_subject_info(const unsigned int pk_subject, Subject &subj){
std::string sql {"SELECT * FROM subjects WHERE pk_subject = "};
sql += uintToStr(pk_subject) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
} else if (res.size() > 1){
EX_THROW(Ex_Model_Error, "While getting subject info for [" + uintToStr(pk_subject) + "], more than one record was returned. This is likely a duplicate.");
}
if (res[0].size() != 4){
EX_THROW(Ex_Model_Error, "While getting subject info for [" + uintToStr(pk_subject) + "], more or less than 4 columns were returned. This is likely a faulty schema.");
}
subj.pk_subject = pk_subject;
subj.tag = res[0][1];
subj.description = res[0][2];
subj.date_of_inclusion.setDate(res[0][3]);
return true;
}
bool Model::get_currency_info(const std::string &label, Currency &curr){
std::string label_local {label}; makeStrLower(label_local);
std::string sql {"SELECT * FROM currencies WHERE label = \""};
sql += label_local + "\";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
} else if (res.size() > 1){
EX_THROW(Ex_Model_Error, "While getting currency info for [" + label_local + "], more than one record was returned. This is likely a duplicate.");
}
if (res[0].size() != 4){
EX_THROW(Ex_Model_Error, "While getting currency info for [" + label_local + "], more or less than 4 columns were returned. This is likely a faulty schema.");
}
curr.pk_currency = strToUint(res[0][0]);
curr.label = label;
curr.description = res[0][2];
curr.date_of_inclusion.setDate(res[0][3]);
return true;
}
bool Model::get_currency_info(const unsigned int pk_currency, Currency &curr){
std::string sql {"SELECT * FROM currencies WHERE pk_currency = "};
sql += uintToStr(pk_currency) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
} else if (res.size() > 1){
EX_THROW(Ex_Model_Error, "While getting currency info for [" + uintToStr(pk_currency) + "], more than one record was returned. This is likely a duplicate.");
}
if (res[0].size() != 4){
EX_THROW(Ex_Model_Error, "While getting currency info for [" + uintToStr(pk_currency) + "], more or less than 4 columns were returned. This is likely a faulty schema.");
}
curr.pk_currency = pk_currency;
curr.label = res[0][1];
curr.description = res[0][2];
curr.date_of_inclusion.setDate(res[0][3]);
return true;
}
bool Model::has_any_helper(const std::string &column, const std::string &value, const std::string &pk_name, const std::string &table_name){
std::string column_local {column}; makeStrLower(column_local);
std::string value_local {value}; makeStrLower(value_local);
std::string pk_name_local {pk_name}; makeStrLower(pk_name_local);
std::string table_name_local {table_name}; makeStrLower(table_name_local);
std::string sql {"SELECT "};
sql += pk_name_local + " FROM " + table_name_local + " WHERE ";
sql += column_local + " = \"" + value_local + "\";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
return true;
}
unsigned int Model::get_pk_investor(const std::string &name){
return get_pk_from_unique("investors", "pk_investor", "name", name);
}
unsigned int Model::get_pk_subject(const std::string &tag){
return get_pk_from_unique("subjects", "pk_subject", "tag", tag);
}
unsigned int Model::get_pk_currency(const std::string &label){
return get_pk_from_unique("currencies", "pk_currency", "label", label);
}
unsigned int Model::get_pk_from_unique(const std::string &table, const std::string &pk_handle, const std::string &unique_handle, const std::string &unique_value){
std::string sql {"SELECT "};
sql += pk_handle + " FROM " + table + " WHERE " + unique_handle + " = \"" + unique_value + "\";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
EX_THROW(Ex_Model_Error, "Requested " + table + "." + pk_handle + " for " + unique_handle + "=" + unique_value + " returned nothing.")
}
return strToUint(res[0][0]);
}
void Model::get_all_investors(std::vector<Investor> &invs){
std::string sql {"SELECT * FROM investors;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Investor inv{strToUint(x[0]), x[1], x[2], x[3], x[4]};
invs.push_back(inv);
}
}
void Model::get_all_subjects(std::vector<Subject> &subjs){
std::string sql {"SELECT * FROM subjects;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Subject subj{strToUint(x[0]), x[1], x[2], x[3]};
subjs.push_back(subj);
}
}
void Model::get_all_currencies(std::vector<Currency> &currs){
std::string sql {"SELECT * FROM currencies;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Currency curr{strToUint(x[0]), x[1], x[2], x[3]};
currs.push_back(curr);
}
}
void Model::get_all_invested_time(std::vector<InvestedTime> &vec_inv_time){
std::string sql {"SELECT * FROM invested_time;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Currency curr{0, "", "", DateHelper{}};
if (!get_currency_info(strToUint(x[2]), curr)){
EX_THROW(Ex_Model_Error, "Currency with pk [" + x[2] + "] could not be retrieved")
}
InvestedTime it{strToUint(x[0]), inv, curr, x[3], x[4], x[5], strToUint(x[6]), strToDouble(x[7])};
vec_inv_time.push_back(it);
}
}
void Model::get_all_invested_assets(std::vector<InvestedAsset> &vec_inv_as){
std::string sql {"SELECT * FROM invested_assets;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Currency curr{0, "", "", DateHelper{}};
if (!get_currency_info(strToUint(x[2]), curr)){
EX_THROW(Ex_Model_Error, "Currency with pk [" + x[2] + "] could not be retrieved")
}
InvestedAsset it{strToUint(x[0]), inv, curr, x[3], x[4], x[5], x[6], strToDouble(x[7])};
vec_inv_as.push_back(it);
}
}
void Model::get_all_bonuses(std::vector<Bonus> &vec_bon){
std::string sql {"SELECT * FROM bonuses;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Bonus it{strToUint(x[0]), inv, x[2], x[3], x[4], x[5], x[6]};
vec_bon.push_back(it);
}
}
void Model::get_all_invested_money(std::vector<InvestedMoney> &vec_inv_mon){
std::string sql {"SELECT * FROM invested_money;"};
strvec2 res;
db.exec(sql, res);
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Currency curr{0, "", "", DateHelper{}};
if (!get_currency_info(strToUint(x[2]), curr)){
EX_THROW(Ex_Model_Error, "Currency with pk [" + x[2] + "] could not be retrieved")
}
InvestedMoney it{strToUint(x[0]), inv, curr, x[3], x[4], x[5], x[6], strToDouble(x[7])};
vec_inv_mon.push_back(it);
}
}
bool Model::get_invested_time_by_investor(const std::string &name, std::vector<InvestedTime> &vec_inv_time){
std::string name_local {name}; makeStrLower(name_local);
unsigned int pk_investor {get_pk_investor(name_local)};
return get_invested_time_by_investor(pk_investor, vec_inv_time);
}
bool Model::get_invested_time_by_investor(const unsigned int pk_investor, std::vector<InvestedTime> &vec_inv_time){
std::string sql {"SELECT * FROM invested_time WHERE fk_investor = "};
sql += uintToStr(pk_investor);
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Currency curr{0, "", "", DateHelper{}};
if (!get_currency_info(strToUint(x[2]), curr)){
EX_THROW(Ex_Model_Error, "Currency with pk [" + x[2] + "] could not be retrieved")
}
InvestedTime it{strToUint(x[0]), inv, curr, x[3], x[4], x[5], strToUint(x[6]), strToDouble(x[7])};
vec_inv_time.push_back(it);
}
return true;
}
bool Model::get_invested_time_subjects(const unsigned int pk_invested_time, std::vector<Subject> &subjs){
std::string sql {"SELECT pk_subject, tag, description, date_of_inclusion FROM subjects INNER JOIN invested_time_subjects_link ON subjects.pk_subject = invested_time_subjects_link.fk_subject WHERE invested_time_subjects_link.fk_invested_time = "};
sql += uintToStr(pk_invested_time) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Subject it{strToUint(x[0]), x[1], x[2], DateHelper{x[3]}};
subjs.push_back(it);
}
return true;
}
bool Model::get_invested_assets_by_investor(const std::string &name, std::vector<InvestedAsset> &vec_inv_as){
std::string name_local {name}; makeStrLower(name_local);
unsigned int pk_investor {get_pk_investor(name_local)};
return get_invested_assets_by_investor(pk_investor, vec_inv_as);
}
bool Model::get_invested_assets_by_investor(const unsigned int pk_investor, std::vector<InvestedAsset> &vec_inv_as){
std::string sql {"SELECT * FROM invested_assets WHERE fk_investor = "};
sql += uintToStr(pk_investor);
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Currency curr{0, "", "", DateHelper{}};
if (!get_currency_info(strToUint(x[2]), curr)){
EX_THROW(Ex_Model_Error, "Currency with pk [" + x[2] + "] could not be retrieved")
}
InvestedAsset it{strToUint(x[0]), inv, curr, x[3], x[4], x[5], x[6], strToDouble(x[7])};
vec_inv_as.push_back(it);
}
return true;
}
bool Model::get_invested_asset_subjects(const unsigned int pk_invested_asset, std::vector<Subject> &subjs){
std::string sql {"SELECT pk_subject, tag, description, date_of_inclusion FROM subjects INNER JOIN invested_assets_subjects_link ON subjects.pk_subject = invested_assets_subjects_link.fk_subject WHERE invested_assets_subjects_link.fk_invested_asset = "};
sql += uintToStr(pk_invested_asset) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Subject it{strToUint(x[0]), x[1], x[2], DateHelper{x[3]}};
subjs.push_back(it);
}
return true;
}
bool Model::get_bonuses_by_investor(const std::string &name, std::vector<Bonus> &vec_bon){
std::string name_local {name}; makeStrLower(name_local);
unsigned int pk_investor {get_pk_investor(name_local)};
return get_bonuses_by_investor(pk_investor, vec_bon);
}
bool Model::get_bonuses_by_investor(const unsigned int pk_investor, std::vector<Bonus> &vec_bon){
std::string sql {"SELECT * FROM bonuses WHERE fk_investor = "};
sql += uintToStr(pk_investor);
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Bonus it{strToUint(x[0]), inv, x[2], x[3], x[4], x[5], x[6]};
vec_bon.push_back(it);
}
return true;
}
bool Model::get_bonus_subjects(const unsigned int pk_bonus, std::vector<Subject> &subjs){
std::string sql {"SELECT pk_subject, tag, description, date_of_inclusion FROM subjects INNER JOIN bonuses_subjects_link ON subjects.pk_subject = bonuses_subjects_link.fk_subject WHERE bonuses_subjects_link.fk_bonus = "};
sql += uintToStr(pk_bonus) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Subject it{strToUint(x[0]), x[1], x[2], DateHelper{x[3]}};
subjs.push_back(it);
}
return true;
}
bool Model::get_invested_money_by_investor(const std::string &name, std::vector<InvestedMoney> &vec_mon){
std::string name_local {name}; makeStrLower(name_local);
unsigned int pk_investor {get_pk_investor(name_local)};
return get_invested_money_by_investor(pk_investor, vec_mon);
}
bool Model::get_invested_money_by_investor(const unsigned int pk_investor, std::vector<InvestedMoney> &vec_mon){
std::string sql {"SELECT * FROM invested_money WHERE fk_investor = "};
sql += uintToStr(pk_investor);
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Investor inv{0, "", "", "", DateHelper{}};
if (!get_investor_info(strToUint(x[1]), inv)){
EX_THROW(Ex_Model_Error, "Investor with pk [" + x[1] + "] could not be retrieved")
}
Currency curr{0, "", "", DateHelper{}};
if (!get_currency_info(strToUint(x[2]), curr)){
EX_THROW(Ex_Model_Error, "Currency with pk [" + x[2] + "] could not be retrieved")
}
InvestedMoney it{strToUint(x[0]), inv, curr, x[3], x[4], x[5], x[6], strToDouble(x[7])};
vec_mon.push_back(it);
}
return true;
}
bool Model::get_invested_money_subjects(const unsigned int pk_invested_money, std::vector<Subject> &subjs){
std::string sql {"SELECT pk_subject, tag, description, date_of_inclusion FROM subjects INNER JOIN invested_money_subjects_link ON subjects.pk_subject = invested_money_subjects_link.fk_subject WHERE invested_money_subjects_link.fk_invested_money = "};
sql += uintToStr(pk_invested_money) + ";";
strvec2 res;
db.exec(sql, res);
if (res.size() == 0){
return false;
}
for (auto x: res){
Subject it{strToUint(x[0]), x[1], x[2], DateHelper{x[3]}};
subjs.push_back(it);
}
return true;
}
| 35.677458 | 257 | 0.650983 | [
"vector",
"model"
] |
b15d3178d5d0e9b69e04bfed34cef67ba18657e9 | 6,912 | cc | C++ | third_party/blink/renderer/core/dom/layout_tree_builder.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/dom/layout_tree_builder.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/core/dom/layout_tree_builder.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All
* rights reserved.
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
* (http://www.torchmobile.com/)
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "third_party/blink/renderer/core/dom/layout_tree_builder.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/dom/first_letter_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/v0_insertion_point.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/generated_children.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/core/svg_names.h"
namespace blink {
LayoutTreeBuilderForElement::LayoutTreeBuilderForElement(
Element& element,
Node::AttachContext& context,
const ComputedStyle* style,
LegacyLayout legacy)
: LayoutTreeBuilder(element, context, style), legacy_(legacy) {
DCHECK(element.CanParticipateInFlatTree());
DCHECK(style_);
DCHECK(!style_->IsEnsuredInDisplayNone());
}
LayoutObject* LayoutTreeBuilderForElement::NextLayoutObject() const {
if (node_->IsFirstLetterPseudoElement())
return context_.next_sibling;
if (node_->IsInTopLayer())
return LayoutTreeBuilderTraversal::NextInTopLayer(*node_);
return LayoutTreeBuilder::NextLayoutObject();
}
LayoutObject* LayoutTreeBuilderForElement::ParentLayoutObject() const {
if (node_->IsInTopLayer())
return node_->GetDocument().GetLayoutView();
return context_.parent;
}
DISABLE_CFI_PERF
void LayoutTreeBuilderForElement::CreateLayoutObject() {
LayoutObject* parent_layout_object = ParentLayoutObject();
if (!parent_layout_object)
return;
if (!parent_layout_object->CanHaveChildren())
return;
if (node_->IsPseudoElement() &&
!CanHaveGeneratedChildren(*parent_layout_object))
return;
if (!node_->LayoutObjectIsNeeded(*style_))
return;
LayoutObject* new_layout_object = node_->CreateLayoutObject(*style_, legacy_);
if (!new_layout_object)
return;
if (!parent_layout_object->IsChildAllowed(new_layout_object, *style_)) {
new_layout_object->Destroy();
return;
}
// Make sure the LayoutObject already knows it is going to be added to a
// LayoutFlowThread before we set the style for the first time. Otherwise code
// using IsInsideFlowThread() in the StyleWillChange and StyleDidChange will
// fail.
new_layout_object->SetIsInsideFlowThread(
parent_layout_object->IsInsideFlowThread());
LayoutObject* next_layout_object = NextLayoutObject();
// SetStyle() can depend on LayoutObject() already being set.
node_->SetLayoutObject(new_layout_object);
new_layout_object->SetStyle(style_);
// Note: Adding new_layout_object instead of LayoutObject(). LayoutObject()
// may be a child of new_layout_object.
parent_layout_object->AddChild(new_layout_object, next_layout_object);
}
LayoutObject*
LayoutTreeBuilderForText::CreateInlineWrapperForDisplayContentsIfNeeded() {
// If the parent element is not a display:contents element, the style and the
// parent style will be the same ComputedStyle object. Early out here.
if (style_ == context_.parent->Style())
return nullptr;
scoped_refptr<ComputedStyle> wrapper_style =
ComputedStyle::CreateInheritedDisplayContentsStyleIfNeeded(
*style_, context_.parent->StyleRef());
if (!wrapper_style)
return nullptr;
// Text nodes which are children of display:contents element which modifies
// inherited properties, need to have an anonymous inline wrapper having those
// inherited properties because the layout code expects the LayoutObject
// parent of text nodes to have the same inherited properties.
LayoutObject* inline_wrapper =
LayoutInline::CreateAnonymous(&node_->GetDocument());
inline_wrapper->SetStyle(wrapper_style);
if (!context_.parent->IsChildAllowed(inline_wrapper, *wrapper_style)) {
inline_wrapper->Destroy();
return nullptr;
}
context_.parent->AddChild(inline_wrapper, NextLayoutObject());
return inline_wrapper;
}
void LayoutTreeBuilderForText::CreateLayoutObject() {
const ComputedStyle& style = *style_;
LayoutObject* layout_object_parent = context_.parent;
LayoutObject* next_layout_object = NextLayoutObject();
if (LayoutObject* wrapper = CreateInlineWrapperForDisplayContentsIfNeeded()) {
layout_object_parent = wrapper;
next_layout_object = nullptr;
}
LegacyLayout legacy_layout = layout_object_parent->ForceLegacyLayout()
? LegacyLayout::kForce
: LegacyLayout::kAuto;
LayoutText* new_layout_object =
node_->CreateTextLayoutObject(style, legacy_layout);
if (!layout_object_parent->IsChildAllowed(new_layout_object, style)) {
new_layout_object->Destroy();
return;
}
// Make sure the LayoutObject already knows it is going to be added to a
// LayoutFlowThread before we set the style for the first time. Otherwise code
// using IsInsideFlowThread() in the StyleWillChange and StyleDidChange will
// fail.
new_layout_object->SetIsInsideFlowThread(
context_.parent->IsInsideFlowThread());
node_->SetLayoutObject(new_layout_object);
new_layout_object->SetStyle(&style);
layout_object_parent->AddChild(new_layout_object, next_layout_object);
}
} // namespace blink
| 40.186047 | 80 | 0.758102 | [
"object"
] |
b1602a493d040d3e92ae95df016bda61645ce614 | 14,916 | cpp | C++ | Common.cpp | ghassanpl/reflector | 1b86cb9b9e4bbb7d7ba1f01ce2f441a01409aaf9 | [
"Fair"
] | 5 | 2020-02-19T02:38:13.000Z | 2022-01-24T07:12:44.000Z | Common.cpp | ghassanpl/reflector | 1b86cb9b9e4bbb7d7ba1f01ce2f441a01409aaf9 | [
"Fair"
] | null | null | null | Common.cpp | ghassanpl/reflector | 1b86cb9b9e4bbb7d7ba1f01ce2f441a01409aaf9 | [
"Fair"
] | 2 | 2020-04-16T05:49:58.000Z | 2020-08-02T13:15:53.000Z | /// Copyright 2017-2019 Ghassan.pl
/// Usage of the works is permitted provided that this instrument is retained with
/// the works, so that any entity that uses the works is notified of this instrument.
/// DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
#include "Common.h"
#include "Parse.h"
#include <mutex>
#include <future>
#include <thread>
#include <fstream>
uint64_t ChangeTime = 0;
std::vector<FileMirror> Mirrors;
json Declaration::ToJSON() const
{
json result = json::object();
if (!Attributes.empty())
result["Attributes"] = Attributes;
result["Name"] = Name;
result["DeclarationLine"] = DeclarationLine;
if (Access != AccessMode::Unspecified)
result["Access"] = AMStrings[(int)Access];
if (!Comments.empty())
result["Comments"] = Comments;
return result;
}
Enum const* FindEnum(string_view name)
{
for (auto& mirror : Mirrors)
for (auto& henum : mirror.Enums)
if (henum.Name == name)
return &henum;
return nullptr;
}
void Field::CreateArtificialMethods(FileMirror& mirror, Class& klass)
{
/// Create comments string
auto field_comments = string_ops::join(Comments, string_view{ " " });
if (field_comments.size())
field_comments[0] = (char)string_ops::tolower(field_comments[0]);
else
field_comments = fmt::format("the `{}` field of this object", DisplayName);
/// Getters and Setters
if (!Flags.is_set(Reflector::FieldFlags::NoGetter))
{
klass.AddArtificialMethod(Type + " const &", "Get" + DisplayName, "", "return " + Name + ";", { "Gets " + field_comments }, { Reflector::MethodFlags::Const }, DeclarationLine);
}
if (!Flags.is_set(Reflector::FieldFlags::NoSetter))
{
auto on_change = Attributes.value("OnChange", "");
if (!on_change.empty())
on_change = on_change + "(); ";
klass.AddArtificialMethod("void", "Set" + DisplayName, Type + " const & value", Name + " = value; " + on_change, { "Sets " + field_comments }, {}, DeclarationLine);
}
auto flag_getters = Attributes.value("FlagGetters", "");
auto flag_setters = Attributes.value("Flags", "");
if (!flag_getters.empty() && !flag_setters.empty())
{
ReportError(mirror.SourceFilePath, DeclarationLine, "Only one of `FlagGetters' and `Flags' can be declared");
return;
}
bool do_flags = !flag_getters.empty() || !flag_setters.empty();
bool do_setters = !flag_setters.empty();
auto& enum_name = do_setters ? flag_setters : flag_getters;
if (do_flags)
{
auto henum = FindEnum(string_view{ enum_name });
if (!henum)
{
ReportError(mirror.SourceFilePath, DeclarationLine, "Enum `{}' not reflected", enum_name);
return;
}
for (auto& enumerator : henum->Enumerators)
{
klass.AddArtificialMethod("bool", "Is" + enumerator.Name, "", fmt::format("return ({} & {}{{{}}}) != 0;", Name, Type, 1ULL << enumerator.Value),
{ "Checks whether the `" + enumerator.Name + "` flag is set in " + field_comments }, Reflector::MethodFlags::Const, DeclarationLine);
}
if (do_setters)
{
for (auto& enumerator : henum->Enumerators)
{
klass.AddArtificialMethod("void", "Set" + enumerator.Name, "", fmt::format("{} |= {}{{{}}};", Name, Type, 1ULL << enumerator.Value),
{ "Sets the `" + enumerator.Name + "` flag in " + field_comments }, {}, DeclarationLine);
}
for (auto& enumerator : henum->Enumerators)
{
klass.AddArtificialMethod("void", "Unset" + enumerator.Name, "", fmt::format("{} &= ~{}{{{}}};", Name, Type, 1ULL << enumerator.Value),
{ "Clears the `" + enumerator.Name + "` flag in " + field_comments }, {}, DeclarationLine);
}
for (auto& enumerator : henum->Enumerators)
{
klass.AddArtificialMethod("void", "Toggle" + enumerator.Name, "", fmt::format("{} ^= {}{{{}}};", Name, Type, 1ULL << enumerator.Value),
{ "Toggles the `" + enumerator.Name + "` flag in " + field_comments }, {}, DeclarationLine);
}
}
}
}
json Field::ToJSON() const
{
json result = Declaration::ToJSON();
result["Type"] = Type;
if (!InitializingExpression.empty())
result["InitializingExpression"] = InitializingExpression;
if (DisplayName != Name)
result["DisplayName"] = DisplayName;
#define ADDFLAG(n) if (Flags.is_set(Reflector::FieldFlags::n)) result[#n] = true
ADDFLAG(NoGetter);
ADDFLAG(NoSetter);
ADDFLAG(NoEdit);
#undef ADDFLAG
return result;
}
void Method::Split()
{
auto args = SplitArgs(string_view{ mParameters });
std::vector<std::string> parameters_split;
std::transform(args.begin(), args.end(), std::back_inserter(parameters_split), [](string_view param) { return std::string{ param }; });
ParametersSplit.clear();
for (auto& full_param : parameters_split)
{
auto& param = ParametersSplit.emplace_back();
auto start_of_id = std::find_if(full_param.rbegin(), full_param.rend(), std::not_fn(string_ops::isident)).base();
param.Type = string_ops::trim_whitespace(string_ops::make_sv(full_param.begin(), start_of_id));
param.Name = string_ops::trim_whitespace(make_sv(start_of_id, full_param.end()));
if (param.Type.empty()) /// If we didn't specify a name, type was at the end, not name, so fix that
param.Type = param.Type + ' ' + param.Name;
}
ParametersTypesOnly = string_ops::join(ParametersSplit, string_view{ "," }, [](MethodParameter const& param) { return param.Type; });
ParametersNamesOnly = string_ops::join(ParametersSplit, string_view{ "," }, [](MethodParameter const& param) { return param.Name; });
}
void Method::SetParameters(std::string params)
{
mParameters = std::move(params);
if (mParameters.find('=') != std::string::npos)
{
throw std::exception{ "Default parameters not supported" };
}
Split();
}
std::string Method::GetSignature(Class const& parent_class) const
{
auto base = Flags.is_set(MethodFlags::Static) ?
fmt::format("{} (*)({})", Type, ParametersTypesOnly)
:
fmt::format("{} ({}::*)({})", Type, parent_class.Name, ParametersTypesOnly);
if (Flags.is_set(Reflector::MethodFlags::Const))
base += " const";
if (Flags.is_set(Reflector::MethodFlags::Noexcept))
base += " noexcept";
return base;
}
void Method::CreateArtificialMethods(FileMirror& mirror, Class& klass)
{
if (klass.Flags.is_set(ClassFlags::HasProxy) && Flags.is_set(MethodFlags::Virtual))
{
if (Flags.is_set(MethodFlags::Abstract))
klass.AddArtificialMethod(Type, "_PROXY_"+Name, GetParameters(), fmt::format("throw std::runtime_error{{\"invalid abstract call to function {}::{}\"}};", klass.Name, Name), { "Proxy function for " + Name }, Flags - MethodFlags::Virtual, DeclarationLine);
else
klass.AddArtificialMethod(Type, "_PROXY_" + Name, GetParameters(), "return self_type::" + Name + "(" + ParametersNamesOnly + ");", { "Proxy function for " + Name }, Flags - MethodFlags::Virtual, DeclarationLine);
}
}
json Method::ToJSON() const
{
json result = Declaration::ToJSON();
result["Type"] = Type;
std::transform(ParametersSplit.begin(), ParametersSplit.end(), std::back_inserter(result["Parameters"]), std::function<json(MethodParameter const&)>{ &MethodParameter::ToJSON });
if (!Body.empty())
result["Body"] = Body;
if (SourceFieldDeclarationLine != 0)
result["SourceFieldDeclarationLine"] = SourceFieldDeclarationLine;
#define ADDFLAG(n) if (Flags.is_set(Reflector::MethodFlags::n)) result[#n] = true
ADDFLAG(Inline);
ADDFLAG(Virtual);
ADDFLAG(Static);
ADDFLAG(Const);
ADDFLAG(Noexcept);
ADDFLAG(Final);
ADDFLAG(Explicit);
ADDFLAG(Artificial);
ADDFLAG(HasBody);
ADDFLAG(NoCallable);
#undef ADDFLAG
return result;
}
void Property::CreateArtificialMethods(FileMirror& mirror, Class& klass)
{
}
void Class::AddArtificialMethod(std::string results, std::string name, std::string parameters, std::string body, std::vector<std::string> comments, enum_flags::enum_flags<Reflector::MethodFlags> additional_flags, size_t source_field_declaration_line)
{
Method method;
method.Flags += Reflector::MethodFlags::Artificial;
method.Flags += additional_flags;
method.Type = std::move(results);
method.Name = std::move(name);
method.SetParameters(std::move(parameters));
method.Body = std::move(body);
if (!method.Body.empty())
method.Flags += Reflector::MethodFlags::HasBody;
method.DeclarationLine = 0;
method.Access = AccessMode::Public;
method.Comments = std::move(comments);
method.SourceFieldDeclarationLine = source_field_declaration_line;
mArtificialMethods.push_back(std::move(method));
}
void Class::CreateArtificialMethods(FileMirror& mirror)
{
/// Check if we should build proxy
bool should_build_proxy = false;
for (auto& method : Methods)
{
if (method.Flags.is_set(Reflector::MethodFlags::Virtual) && !method.Flags.is_set(Reflector::MethodFlags::Final))
should_build_proxy = true;
}
should_build_proxy = should_build_proxy && Attributes.value("CreateProxy", true);
Flags.set_to(should_build_proxy, ClassFlags::HasProxy);
/// Create singleton method if singleton
if (Attributes.value("Singleton", false))
AddArtificialMethod("self_type&", "SingletonInstance", "", "static self_type instance; return instance;", { "Returns the single instance of this class" }, Reflector::MethodFlags::Static);
/// Create methods for fields and methods
for (auto& field : Fields)
field.CreateArtificialMethods(mirror, *this);
for (auto& method : Methods)
method.CreateArtificialMethods(mirror, *this);
for (auto& property : Properties)
property.second.CreateArtificialMethods(mirror, *this);
for (auto& am : mArtificialMethods)
Methods.push_back(std::move(am));
mArtificialMethods.clear();
/// First check unique method names
MethodsByName.clear();
for (auto& method : Methods)
{
MethodsByName[method.Name].push_back(&method);
if (!method.UniqueName.empty() && method.Name != method.UniqueName)
MethodsByName[method.UniqueName].push_back(&method);
}
for (auto& method : Methods)
{
if (method.UniqueName.empty())
continue;
if (MethodsByName[method.UniqueName].size() > 1)
{
std::string message;
message += fmt::format("{}({},0): method with unique name not unique", mirror.SourceFilePath.string(), method.DeclarationLine + 1);
for (auto& conflicting_method : MethodsByName[method.UniqueName])
{
if (conflicting_method != &method)
message += fmt::format("\n{}({},0): conflicts with this declaration", mirror.SourceFilePath.string(), conflicting_method->DeclarationLine + 1);
}
throw std::exception{ message.c_str() };
}
}
}
json Class::ToJSON() const
{
auto result = Declaration::ToJSON();
if (!ParentClass.empty())
result["ParentClass"] = ParentClass;
if (Flags.is_set(ClassFlags::Struct))
result["Struct"] = true;
if (Flags.is_set(ClassFlags::NoConstructors))
result["NoConstructors"] = true;
if (!Fields.empty())
{
auto& fields = result["Fields"] = json::object();
for (auto& field : Fields)
{
fields[field.Name] = field.ToJSON();
}
}
if (!Methods.empty())
{
auto& methods = result["Methods"] = json::array();
for (auto& method : Methods)
{
methods.push_back(method.ToJSON());
}
}
result["BodyLine"] = BodyLine;
return result;
}
json Enumerator::ToJSON() const
{
json result = Declaration::ToJSON();
result["Value"] = Value;
return result;
}
json Enum::ToJSON() const
{
json result = Declaration::ToJSON();
auto& enumerators = result["Enumerators"] = json::object();
for (auto& enumerator : Enumerators)
enumerators[enumerator.Name] = enumerator.ToJSON();
return result;
}
json FileMirror::ToJSON() const
{
json result = json::object();
result["SourceFilePath"] = SourceFilePath.string();
auto& classes = result["Classes"] = json::object();
for (auto& klass : Classes)
classes[klass.Name] = klass.ToJSON();
auto& enums = result["Enums"] = json::object();
for (auto& enum_ : Enums)
enums[enum_.Name] = enum_.ToJSON();
return result;
}
void FileMirror::CreateArtificialMethods()
{
for (auto& klass : Classes)
{
klass.CreateArtificialMethods(*this);
}
}
#define OPTION(name, default_value, description) name = OptionsFile.value(#name, default_value); OptionsFile.erase(#name);
Options::Options(path const& options_file_path)
: OptionsFilePath(std::filesystem::canonical(options_file_path))
, OptionsFile(json::parse(std::fstream{ options_file_path }))
{
if (!OptionsFile.is_object())
throw std::exception{ "Options file must contain a JSON object" };
OPTION(Recursive, false, "Recursively search the provided directories for files");
OPTION(Quiet, false, "Don't print out created file names");
OPTION(Force, false, "Ignore timestamps, regenerate all files");
OPTION(Verbose, false, "Print additional information");
OPTION(CreateDatabase, true, "Create a JSON database with reflection data");
OPTION(UseJSON, true, "Output code that uses nlohmann::json to store class attributes");
OPTION(ForwardDeclare, true, "Output forward declarations of reflected classes");
OPTION(CreateArtifacts, true, "Whether to generate artifacts (*.reflect.h files, db, others)");
OPTION(AnnotationPrefix, "R", "The prefix for all annotation macros");
OPTION(MacroPrefix, "REFLECT", "The prefix for all autogenerated macros this tool will generate");
OPTION(ArtifactPath, "", "Path to the directory where the general artifact files will be created");
if (!OptionsFile.contains("Files"))
throw std::exception{ "Options file missing `Files' entry" };
if (OptionsFile["Files"].is_array())
{
for (auto& file : OptionsFile["Files"])
{
if (!file.is_string())
throw std::exception{ "`Files' array must contain only strings" };
PathsToScan.push_back((std::string)file);
}
}
else if (OptionsFile["Files"].is_string())
PathsToScan.push_back((std::string)OptionsFile["Files"]);
else
throw std::exception{ "`Files' entry must be an array of strings or a string" };
OptionsFile.erase("Files");
/// Hidden options :)
OPTION(EnumPrefix, AnnotationPrefix + "Enum", "");
OPTION(EnumeratorPrefix, AnnotationPrefix + "Enumerator", "");
OPTION(ClassPrefix, AnnotationPrefix + "Class", "");
OPTION(FieldPrefix, AnnotationPrefix + "Field", "");
OPTION(MethodPrefix, AnnotationPrefix + "Method", "");
OPTION(BodyPrefix, AnnotationPrefix + "Body", "");
if (OptionsFile.size() > 0 && Verbose)
{
for (auto& opt : OptionsFile.items())
{
PrintLine("Warning: Unrecognized option: {}\n", opt.key());
}
}
}
void PrintSafe(std::ostream& strm, std::string val)
{
static std::mutex print_mutex;
std::unique_lock locl{ print_mutex };
strm << val;
}
std::vector<FileMirror> const& GetMirrors()
{
return Mirrors;
}
void AddMirror(FileMirror mirror)
{
static std::mutex mirror_mutex;
std::unique_lock lock{ mirror_mutex };
Mirrors.push_back(std::move(mirror));
}
void CreateArtificialMethods()
{
/// TODO: Not sure if these are safe to be multithreaded, we ARE adding new methods to the mirrors after all...
std::vector<std::future<void>> futures;
for (auto& mirror : Mirrors)
futures.push_back(std::async([&]() { mirror.CreateArtificialMethods(); }));
for (auto& future : futures)
future.get(); /// to propagate exceptions
}
| 33.594595 | 257 | 0.701394 | [
"object",
"vector",
"transform"
] |
b165aaf9e6c9de18c4e1d137fcd38282b838db62 | 4,460 | hpp | C++ | include/hadoken/thread/latch.hpp | adevress/hadoken | c501c53b14dfd256ae745d417b6417855b77ed05 | [
"BSL-1.0"
] | 5 | 2018-08-11T17:35:30.000Z | 2019-09-06T01:21:17.000Z | include/hadoken/thread/latch.hpp | mrexodia/hadoken | 28cb2c2042aab1d8b086addee8072d2da6c62a25 | [
"BSL-1.0"
] | 5 | 2017-08-29T13:32:12.000Z | 2019-11-04T08:40:23.000Z | include/hadoken/thread/latch.hpp | mrexodia/hadoken | 28cb2c2042aab1d8b086addee8072d2da6c62a25 | [
"BSL-1.0"
] | 10 | 2016-11-16T10:18:18.000Z | 2021-03-30T04:35:59.000Z | /**
* Copyright (c) 2016, Adrien Devresse <adrien.devresse@epfl.ch>
*
* Boost Software License - Version 1.0
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#ifndef _HADOKEN_LATCH_HPP_
#define _HADOKEN_LATCH_HPP_
#include <assert.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <thread>
namespace hadoken {
namespace thread {
///
/// \brief latch class
///
/// latch ( C++17 implementation )
///
/// ( extract from http://en.cppreference.com/w/cpp/experimental/latch )
/// The latch class is a downward counter of type ptrdiff_t which can be used to synchronize threads. The value of the counter
/// is initialized on creation. Threads may block on the latch until the counter is decremented to zero. There is no possibility
/// to increase or reset the counter, which makes the latch a single-use barrier.
///
///
class latch {
public:
///
/// \brief construct a new latch
/// \param value : the initial value of the counter, must be non negative
///
explicit inline latch(std::ptrdiff_t value) : _counter((value != 0) ? (value) : (unlocked)), _cond(), _latch_lock() {
assert(value >= 0);
}
/// default destructor
~latch() = default;
/// count down, without waiting
/// non blocking
///
/// \param n : value to decremement
///
inline void count_down(std::ptrdiff_t n = 1) {
const std::ptrdiff_t previous_val = _counter.fetch_sub(n);
__check_and_notify(previous_val - n);
}
/// count down and wait until the counter is 0
/// \param n : value to decremement
///
inline void count_down_and_wait(std::ptrdiff_t n = 1) {
count_down(n);
wait();
}
///
/// \brief return true if the counter reached 0
///
inline bool is_ready() const { return (_counter.load() <= unlocked); }
///
/// \brief wait untile the counter reach 0
///
inline void wait() {
// lightweight optimistic two phases unlock
// avoid race condition on condition variable/mutex destruction
// if the lifetime of the latch is the same that one of the waiting thread
while (_counter.load() > unlocked) {
if (_counter.load() > 0) {
std::unique_lock<std::mutex> _l(_latch_lock);
_cond.wait_for(_l, std::chrono::milliseconds(1));
} else {
#ifndef HADOKEN_SPIN_NO_YIELD
std::this_thread::yield();
#else
// dummy implementation for platforms without sched_yield() support
std::this_thread::sleep_for(std::chrono::microseconds(1));
#endif
}
}
}
private:
static constexpr std::ptrdiff_t unlocked = -2048;
inline void __check_and_notify(std::ptrdiff_t v) {
if (v <= 0) {
_cond.notify_all();
_counter.store(unlocked);
}
}
latch(const latch&) = delete;
latch& operator=(const latch&) = delete;
std::atomic<std::ptrdiff_t> _counter;
std::condition_variable _cond;
std::mutex _latch_lock;
};
} // namespace thread
} // namespace hadoken
#endif // _HADOKEN_LATCH_HPP_
| 31.631206 | 128 | 0.668161 | [
"object"
] |
b167f63c80f12be8929cb37294ace05a52647fbb | 1,924 | cpp | C++ | contact/ewsfetchcontactdetailjob.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 122 | 2016-03-01T12:53:43.000Z | 2021-11-06T21:14:21.000Z | contact/ewsfetchcontactdetailjob.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 54 | 2016-05-02T10:05:47.000Z | 2022-02-01T18:10:38.000Z | contact/ewsfetchcontactdetailjob.cpp | KrissN/akonadi-ews | 05ce7e24547fbdb559de55dabda86d337716cfba | [
"RSA-MD"
] | 17 | 2016-05-18T21:02:08.000Z | 2022-01-27T20:33:26.000Z | /* This file is part of Akonadi EWS Resource
Copyright (C) 2015-2016 Krzysztof Nowicki <krissn@op.pl>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "ewsfetchcontactdetailjob.h"
#include "ewsitemshape.h"
#include "ewsgetitemrequest.h"
#include "ewsmailbox.h"
#include "ewsclient_debug.h"
using namespace Akonadi;
EwsFetchContactDetailJob::EwsFetchContactDetailJob(EwsClient &client, QObject *parent, const Akonadi::Collection &collection)
: EwsFetchItemDetailJob(client, parent, collection)
{
EwsItemShape shape(EwsShapeIdOnly);
mRequest->setItemShape(shape);
}
EwsFetchContactDetailJob::~EwsFetchContactDetailJob()
{
}
void EwsFetchContactDetailJob::processItems(const QList<EwsGetItemRequest::Response> &responses)
{
Item::List::iterator it = mChangedItems.begin();
Q_FOREACH(const EwsGetItemRequest::Response &resp, responses) {
Item &item = *it;
if (!resp.isSuccess()) {
qCWarningNC(EWSRES_LOG) << QStringLiteral("Failed to fetch item %1").arg(item.remoteId());
continue;
}
//const EwsItem &ewsItem = resp.item();
// TODO: Implement
++it;
}
emitResult();
}
| 31.540984 | 125 | 0.717775 | [
"shape"
] |
b16f32e08aeae714db6b3aef9c57596907b13289 | 6,012 | cc | C++ | mysql-server/router/src/router/src/windows/password_vault.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/router/src/router/src/windows/password_vault.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/router/src/router/src/windows/password_vault.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mysqlrouter/windows/password_vault.h"
#include <windows.h>
#include <Dpapi.h>
#include <Wincrypt.h>
#include <comdef.h>
#include <shlobj.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <strstream>
#include <vector>
#include "mysqlrouter/utils.h"
PasswordVault::PasswordVault() { load_passwords(); }
PasswordVault::~PasswordVault() {
// scrambles all the passwords first
for (auto &it : _passwords) {
// for (std::map<std::string, std::string>::iterator it =
// _passwords.begin(); it != _passwords.end(); ++it) {
std::string &pass = it.second;
password_scrambler(pass);
}
_passwords.clear();
}
std::string PasswordVault::get_vault_path() const {
return "C:\\ProgramData\\MySQL\\MySQL Router\\mysql_router_user_data.dat";
}
void PasswordVault::password_scrambler(std::string &pass) {
for (size_t i = 0; i < pass.length(); ++i) pass.at(i) = '*';
}
void PasswordVault::remove_password(const std::string §ion_name) {
_passwords.erase(section_name);
}
void PasswordVault::update_password(const std::string §ion_name,
const std::string &password) {
_passwords[section_name] = password;
}
bool PasswordVault::get_password(const std::string §ion_name,
std::string &out_password) const {
std::map<std::string, std::string>::const_iterator it =
_passwords.find(section_name);
if (it != _passwords.end()) {
out_password = it->second;
return true;
} else {
return false;
}
}
void PasswordVault::clear_passwords() {
const std::string vault_path = get_vault_path();
std::ofstream f(vault_path, std::ios_base::trunc);
f.flush();
for (auto &it : _passwords) {
std::string &pass = it.second;
password_scrambler(pass);
}
_passwords.clear();
}
void PasswordVault::load_passwords() {
const std::string vault_path = get_vault_path();
std::unique_ptr<std::ifstream> file_vault(
new std::ifstream(vault_path, std::ios_base::binary));
if (!file_vault) {
// creates the file if doesn't exist
std::ofstream file_vault_out(vault_path, std::ios_base::binary);
if (!file_vault_out)
throw std::runtime_error("Cannot open the vault at '" + vault_path + "'");
file_vault_out.close();
file_vault.reset(new std::ifstream(vault_path, std::ios_base::binary));
}
std::streampos begin = file_vault->tellg();
file_vault->seekg(0, std::ios::end);
std::streampos end = file_vault->tellg();
if (end - begin == 0) return;
std::unique_ptr<char, void (*)(char *)> buf(new char[end - begin],
[](char *ptr) { delete[] ptr; });
file_vault->seekg(0, std::ios::beg);
file_vault->read(buf.get(), end - begin);
// decrypt the data
DATA_BLOB buf_encrypted;
DATA_BLOB buf_decrypted;
buf_encrypted.pbData = reinterpret_cast<BYTE *>(buf.get());
buf_encrypted.cbData = end - begin;
if (!CryptUnprotectData(&buf_encrypted, NULL, NULL, NULL, NULL, 0,
&buf_decrypted)) {
DWORD code = GetLastError();
throw std::runtime_error(mysqlrouter::string_format(
"Error when decrypting the vault at '%s' with code '%lu'",
vault_path.c_str(), code));
}
std::strstream ss(reinterpret_cast<char *>(buf_decrypted.pbData),
buf_decrypted.cbData, std::ios_base::in);
std::string line;
std::string section_name;
int i = 0;
while (std::getline(ss, line)) {
if (i % 2 == 0)
section_name = line;
else
_passwords[section_name] = line;
i++;
}
LocalFree(buf_decrypted.pbData);
}
void PasswordVault::store_passwords() {
std::stringstream ss(std::ios_base::out);
for (auto &it : _passwords) {
// for (std::map<std::string, std::string>::iterator it =
// _passwords.begin(); it != _passwords.end(); ++it)
ss << it.first << std::endl;
ss << it.second << std::endl;
}
ss.flush();
// encrypt the data
DATA_BLOB buf_decrypted;
DATA_BLOB buf_encrypted;
std::string data = ss.str();
buf_decrypted.pbData =
reinterpret_cast<BYTE *>(const_cast<char *>(data.c_str()));
buf_decrypted.cbData = ss.str().size();
if (!CryptProtectData(&buf_decrypted, NULL, NULL, NULL, NULL,
CRYPTPROTECT_LOCAL_MACHINE, &buf_encrypted)) {
DWORD code = GetLastError();
throw std::runtime_error(mysqlrouter::string_format(
"Error when encrypting the vault with code '%lu'", code));
}
const std::string vault_path = get_vault_path();
std::ofstream f(vault_path, std::ios_base::trunc | std::ios_base::binary);
if (!f)
throw std::runtime_error("Cannot open the vault at '" + vault_path + "'");
f.write(reinterpret_cast<char *>(buf_encrypted.pbData), buf_encrypted.cbData);
f.flush();
LocalFree(buf_encrypted.pbData);
}
| 33.586592 | 80 | 0.676813 | [
"vector"
] |
b173be3099aa73e971fced53f81d43c24b6eed0d | 1,738 | cpp | C++ | src/integration_tests/geofence_inclusion.cpp | haydockjp/MAVSDK | 9e2805a9a06a6d62f32e1dad918bedff4d472370 | [
"BSD-3-Clause"
] | null | null | null | src/integration_tests/geofence_inclusion.cpp | haydockjp/MAVSDK | 9e2805a9a06a6d62f32e1dad918bedff4d472370 | [
"BSD-3-Clause"
] | null | null | null | src/integration_tests/geofence_inclusion.cpp | haydockjp/MAVSDK | 9e2805a9a06a6d62f32e1dad918bedff4d472370 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <memory>
#include "integration_test_helper.h"
#include "mavsdk.h"
#include "plugins/telemetry/telemetry.h"
#include "plugins/geofence/geofence.h"
using namespace mavsdk;
static Geofence::Point add_point(double latitude_deg, double longitude_deg);
TEST_F(SitlTest, GeofenceInclusion)
{
Mavsdk dl;
ConnectionResult ret = dl.add_udp_connection();
ASSERT_EQ(ret, ConnectionResult::Success);
// Wait for system to connect via heartbeat.
std::this_thread::sleep_for(std::chrono::seconds(2));
System& system = dl.system();
ASSERT_TRUE(system.has_autopilot());
auto telemetry = std::make_shared<Telemetry>(system);
auto geofence = std::make_shared<Geofence>(system);
while (!telemetry->health_all_ok()) {
LogInfo() << "waiting for system to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LogInfo() << "System ready, let's start";
std::vector<Geofence::Point> points;
points.push_back(add_point(47.39929240, 8.54296524));
points.push_back(add_point(47.39696482, 8.54161340));
points.push_back(add_point(47.39626761, 8.54527193));
points.push_back(add_point(47.39980072, 8.54736050));
std::vector<Geofence::Polygon> polygons;
Geofence::Polygon new_polygon{};
new_polygon.fence_type = Geofence::Polygon::FenceType::Inclusion;
new_polygon.points = points;
polygons.push_back(new_polygon);
EXPECT_EQ(Geofence::Result::Success, geofence->upload_geofence(polygons));
}
Geofence::Point add_point(double latitude_deg, double longitude_deg)
{
Geofence::Point new_point;
new_point.latitude_deg = latitude_deg;
new_point.longitude_deg = longitude_deg;
return new_point;
}
| 30.491228 | 78 | 0.722094 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.