text
stringlengths 5
1.04M
|
|---|
#include <FractalPCH.h>
#include <core\managers\PropertiesManager.h>
#include <vector>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <regex>
namespace fractal
{
namespace fcore
{
PropertiesManager::PropertiesManager () :
IManager<PropertiesManager>()
{
// empty
}
PropertiesManager::~PropertiesManager ()
{
// empty
}
bool PropertiesManager::Init ()
{
std::string s = "../resources/engine.INI";
std::ifstream infile;
infile.open (s);
parse (infile);
return true;
}
void PropertiesManager::Update ()
{
// empty
}
bool PropertiesManager::Shutdown ()
{
return true;
}
void PropertiesManager::ReadFile (FString filePath)
{
Section currentSection;
std::list<Section> sections;
using namespace std;
std::string str1, str2;
std::vector<string> vec(10);
std::ifstream infile;
infile.open (filePath);
/*while(infile >> str1)
{
TrimString (str1);
// its a comment - go to next line
if (str1[0] == '#')
continue;
vec.emplace_back (std::move (str1));
}*/
for (std::string line; std::getline (infile, line);)
{
LeftTrim (line);
if (line.empty ())
continue;
// if a comment
if (line[0] == ';' || line[0] == '#')
{
// allow both ; and # comments at the start of a line
continue;
}
// section
if (line[0] == '[')
{
/* A "[section]" line */
size_t end = line.find_first_of (']');
if (end != std::string::npos)
{
// this is a new section so if we have a current section populated, add it to list
if (!currentSection.Name.empty ())
{
sections.push_back (currentSection); // copy
currentSection.Name.clear (); // clear section for re-use
currentSection.KeyValues.clear ();
}
currentSection.Name = line.substr (1, end - 1);
}
continue;
}
if (!line.empty ())
{
/* Not a comment, must be a name[=:]value pair */
size_t end = line.find_first_of ("=");
if (end != std::string::npos)
{
std::string name = line.substr (0, end);
std::string value = line.substr (end + 1);
RightTrim (name);
LeftTrim (value);
currentSection.KeyValues[name] = value;
}
}
}
if (!currentSection.Name.empty ())
{
sections.push_back (currentSection); // copy
currentSection.Name = "";
currentSection.KeyValues.clear ();
}
}
std::string PropertiesManager::GetValue (const std::string& section, const std::string& key) const
{
auto sectionValues = GetSectionValues (section);
if (sectionValues)
{
auto it = sectionValues->find (key);
if (it != sectionValues->end ())
{
return it->second;
}
}
return "";
}
const std::unordered_map<std::string, std::string>* PropertiesManager::GetSectionValues (const std::string& name) const
{
const auto it = m_sections.find (name);
if (it != m_sections.end ())
{
return &it->second;
} else
{
return nullptr;
}
}
void PropertiesManager::LeftTrim (std::string& s)
{
s.erase (s.begin (), std::find_if (s.begin (), s.end (), [](int c)
{
return !std::isspace (c);
}));
}
void PropertiesManager::RightTrim (std::string& s)
{
size_t endpos = s.find_last_not_of (" \t\r\n\v\f");
if (std::string::npos != endpos)
{
s = s.substr (0, endpos + 1);
}
}
void PropertiesManager::parse (std::istream& in)
{
static const std::regex comment_regex{ R"x(\s*[;#])x" };
static const std::regex section_regex{ R"x(\s*\[([^\]]+)\])x" };
static const std::regex value_regex{ R"x(\s*(\S[^ \t=]*)\s*=\s*((\s?\S+)+)\s*$)x" };
std::string current_section;
std::smatch pieces;
for (std::string line; std::getline (in, line);)
{
if (line.empty () || std::regex_match (line, pieces, comment_regex))
{
// skip comment lines and blank lines
}
else if (std::regex_match (line, pieces, section_regex))
{
if (pieces.size () == 2)
{ // exactly one match
current_section = pieces[1].str ();
}
}
else if (std::regex_match (line, pieces, value_regex))
{
if (pieces.size () == 4)
{ // exactly enough matches
m_sections[current_section][pieces[1].str ()] = pieces[2].str ();
}
}
}
}
}
}
|
// Auto generated C++ code started by /home/magnus/gem5-stable_2014_12_14/src/mem/slicc/symbols/StateMachine.py:1157
// Directory: Directory protocol
#include <cassert>
#include "base/misc.hh"
#include "base/trace.hh"
#include "debug/ProtocolTrace.hh"
#include "debug/RubyGenerated.hh"
#include "mem/protocol/Directory_Controller.hh"
#include "mem/protocol/Directory_Event.hh"
#include "mem/protocol/Directory_State.hh"
#include "mem/protocol/Types.hh"
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/system/System.hh"
#define HASH_FUN(state, event) ((int(state)*Directory_Event_NUM)+int(event))
#define GET_TRANSITION_COMMENT() (Directory_transitionComment.str())
#define CLEAR_TRANSITION_COMMENT() (Directory_transitionComment.str(""))
TransitionResult
Directory_Controller::doTransition(Directory_Event event,
Directory_TBE* m_tbe_ptr,
const Address addr)
{
Directory_State state = getState(m_tbe_ptr, addr);
Directory_State next_state = state;
DPRINTF(RubyGenerated, "%s, Time: %lld, state: %s, event: %s, addr: %s\n",
*this, curCycle(), Directory_State_to_string(state),
Directory_Event_to_string(event), addr);
TransitionResult result =
doTransitionWorker(event, state, next_state, m_tbe_ptr, addr);
if (result == TransitionResult_Valid) {
DPRINTF(RubyGenerated, "next_state: %s\n",
Directory_State_to_string(next_state));
countTransition(state, event);
DPRINTFR(ProtocolTrace, "%15d %3s %10s%20s %6s>%-6s %s %s\n",
curTick(), m_version, "Directory",
Directory_Event_to_string(event),
Directory_State_to_string(state),
Directory_State_to_string(next_state),
addr, GET_TRANSITION_COMMENT());
CLEAR_TRANSITION_COMMENT();
setState(m_tbe_ptr, addr, next_state);
setAccessPermission(addr, next_state);
} else if (result == TransitionResult_ResourceStall) {
DPRINTFR(ProtocolTrace, "%15s %3s %10s%20s %6s>%-6s %s %s\n",
curTick(), m_version, "Directory",
Directory_Event_to_string(event),
Directory_State_to_string(state),
Directory_State_to_string(next_state),
addr, "Resource Stall");
} else if (result == TransitionResult_ProtocolStall) {
DPRINTF(RubyGenerated, "stalling\n");
DPRINTFR(ProtocolTrace, "%15s %3s %10s%20s %6s>%-6s %s %s\n",
curTick(), m_version, "Directory",
Directory_Event_to_string(event),
Directory_State_to_string(state),
Directory_State_to_string(next_state),
addr, "Protocol Stall");
}
return result;
}
TransitionResult
Directory_Controller::doTransitionWorker(Directory_Event event,
Directory_State state,
Directory_State& next_state,
Directory_TBE*& m_tbe_ptr,
const Address& addr)
{
switch(HASH_FUN(state, event)) {
case HASH_FUN(Directory_State_M_DRD, Directory_Event_GETX):
case HASH_FUN(Directory_State_M_DWR, Directory_Event_GETX):
case HASH_FUN(Directory_State_M_DWRI, Directory_Event_GETX):
case HASH_FUN(Directory_State_M_DRDI, Directory_Event_GETX):
case HASH_FUN(Directory_State_IM, Directory_Event_GETX):
case HASH_FUN(Directory_State_IM, Directory_Event_GETS):
case HASH_FUN(Directory_State_IM, Directory_Event_PUTX):
case HASH_FUN(Directory_State_IM, Directory_Event_PUTX_NotOwner):
case HASH_FUN(Directory_State_MI, Directory_Event_GETX):
case HASH_FUN(Directory_State_MI, Directory_Event_GETS):
case HASH_FUN(Directory_State_MI, Directory_Event_PUTX):
case HASH_FUN(Directory_State_MI, Directory_Event_PUTX_NotOwner):
case HASH_FUN(Directory_State_ID, Directory_Event_GETX):
case HASH_FUN(Directory_State_ID, Directory_Event_GETS):
case HASH_FUN(Directory_State_ID, Directory_Event_PUTX):
case HASH_FUN(Directory_State_ID, Directory_Event_PUTX_NotOwner):
case HASH_FUN(Directory_State_ID_W, Directory_Event_GETX):
case HASH_FUN(Directory_State_ID_W, Directory_Event_GETS):
case HASH_FUN(Directory_State_ID_W, Directory_Event_PUTX):
case HASH_FUN(Directory_State_ID_W, Directory_Event_PUTX_NotOwner):
z_recycleRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_IM, Directory_Event_DMA_READ):
case HASH_FUN(Directory_State_IM, Directory_Event_DMA_WRITE):
case HASH_FUN(Directory_State_MI, Directory_Event_DMA_READ):
case HASH_FUN(Directory_State_MI, Directory_Event_DMA_WRITE):
case HASH_FUN(Directory_State_ID, Directory_Event_DMA_READ):
case HASH_FUN(Directory_State_ID, Directory_Event_DMA_WRITE):
case HASH_FUN(Directory_State_ID_W, Directory_Event_DMA_READ):
case HASH_FUN(Directory_State_ID_W, Directory_Event_DMA_WRITE):
y_recycleDMARequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_I, Directory_Event_GETX):
next_state = Directory_State_IM;
if (!(*m_memBuffer_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
qf_queueMemoryFetchRequest(m_tbe_ptr, addr);
e_ownerIsRequestor(m_tbe_ptr, addr);
i_popIncomingRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_IM, Directory_Event_Memory_Data):
next_state = Directory_State_M;
if (!(*m_responseFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
d_sendData(m_tbe_ptr, addr);
l_popMemQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_I, Directory_Event_DMA_READ):
next_state = Directory_State_ID;
if (!(*m_memBuffer_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
r_allocateTbeForDmaRead(m_tbe_ptr, addr);
qf_queueMemoryFetchRequestDMA(m_tbe_ptr, addr);
p_popIncomingDMARequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_ID, Directory_Event_Memory_Data):
next_state = Directory_State_I;
if (!(*m_dmaResponseFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
dr_sendDMAData(m_tbe_ptr, addr);
w_deallocateTBE(m_tbe_ptr, addr);
l_popMemQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_I, Directory_Event_DMA_WRITE):
next_state = Directory_State_ID_W;
if (!(*m_memBuffer_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
v_allocateTBE(m_tbe_ptr, addr);
qw_queueMemoryWBRequest_partial(m_tbe_ptr, addr);
p_popIncomingDMARequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_ID_W, Directory_Event_Memory_Ack):
next_state = Directory_State_I;
if (!(*m_dmaResponseFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
dwt_writeDMADataFromTBE(m_tbe_ptr, addr);
da_sendDMAAck(m_tbe_ptr, addr);
w_deallocateTBE(m_tbe_ptr, addr);
l_popMemQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M, Directory_Event_DMA_READ):
next_state = Directory_State_M_DRD;
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
v_allocateTBE(m_tbe_ptr, addr);
inv_sendCacheInvalidate(m_tbe_ptr, addr);
p_popIncomingDMARequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M_DRD, Directory_Event_PUTX):
next_state = Directory_State_M_DRDI;
if (!(*m_dmaResponseFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
if (!(*m_memBuffer_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
l_writeDataToMemory(m_tbe_ptr, addr);
drp_sendDMAData(m_tbe_ptr, addr);
c_clearOwner(m_tbe_ptr, addr);
l_queueMemoryWBRequest(m_tbe_ptr, addr);
i_popIncomingRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M_DRDI, Directory_Event_Memory_Ack):
next_state = Directory_State_I;
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
l_sendWriteBackAck(m_tbe_ptr, addr);
w_deallocateTBE(m_tbe_ptr, addr);
l_popMemQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M, Directory_Event_DMA_WRITE):
next_state = Directory_State_M_DWR;
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
v_allocateTBE(m_tbe_ptr, addr);
inv_sendCacheInvalidate(m_tbe_ptr, addr);
p_popIncomingDMARequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M_DWR, Directory_Event_PUTX):
next_state = Directory_State_M_DWRI;
if (!(*m_memBuffer_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
l_writeDataToMemory(m_tbe_ptr, addr);
qw_queueMemoryWBRequest_partialTBE(m_tbe_ptr, addr);
c_clearOwner(m_tbe_ptr, addr);
i_popIncomingRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M_DWRI, Directory_Event_Memory_Ack):
next_state = Directory_State_I;
if (!(*m_dmaResponseFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
w_writeDataToMemoryFromTBE(m_tbe_ptr, addr);
l_sendWriteBackAck(m_tbe_ptr, addr);
da_sendDMAAck(m_tbe_ptr, addr);
w_deallocateTBE(m_tbe_ptr, addr);
l_popMemQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M, Directory_Event_GETX):
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
f_forwardRequest(m_tbe_ptr, addr);
e_ownerIsRequestor(m_tbe_ptr, addr);
i_popIncomingRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M, Directory_Event_PUTX):
next_state = Directory_State_MI;
if (!(*m_memBuffer_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
c_clearOwner(m_tbe_ptr, addr);
v_allocateTBEFromRequestNet(m_tbe_ptr, addr);
l_queueMemoryWBRequest(m_tbe_ptr, addr);
i_popIncomingRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_MI, Directory_Event_Memory_Ack):
next_state = Directory_State_I;
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
w_writeDataToMemoryFromTBE(m_tbe_ptr, addr);
l_sendWriteBackAck(m_tbe_ptr, addr);
w_deallocateTBE(m_tbe_ptr, addr);
l_popMemQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
case HASH_FUN(Directory_State_M, Directory_Event_PUTX_NotOwner):
case HASH_FUN(Directory_State_I, Directory_Event_PUTX_NotOwner):
if (!(*m_forwardFromDir_ptr).areNSlotsAvailable(1))
return TransitionResult_ResourceStall;
b_sendWriteBackNack(m_tbe_ptr, addr);
i_popIncomingRequestQueue(m_tbe_ptr, addr);
return TransitionResult_Valid;
default:
fatal("Invalid transition\n"
"%s time: %d addr: %s event: %s state: %s\n",
name(), curCycle(), addr, event, state);
}
return TransitionResult_Valid;
}
|
/* C++ implementation of QuickSort */
#include <bits/stdc++.h>
using namespace std;
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
|
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <functional>
#include <list>
#include <string>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/base/thread_annotations.h"
#include "webrtc/call.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/event_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/test/call_test.h"
#include "webrtc/test/direct_transport.h"
#include "webrtc/test/encoder_settings.h"
#include "webrtc/test/fake_decoder.h"
#include "webrtc/test/fake_encoder.h"
#include "webrtc/test/frame_generator_capturer.h"
namespace webrtc {
namespace {
// Note: If you consider to re-use this class, think twice and instead consider
// writing tests that don't depend on the trace system.
class TraceObserver {
public:
TraceObserver() {
Trace::set_level_filter(kTraceTerseInfo);
Trace::CreateTrace();
Trace::SetTraceCallback(&callback_);
// Call webrtc trace to initialize the tracer that would otherwise trigger a
// data-race if left to be initialized by multiple threads (i.e. threads
// spawned by test::DirectTransport members in BitrateEstimatorTest).
WEBRTC_TRACE(kTraceStateInfo,
kTraceUtility,
-1,
"Instantiate without data races.");
}
~TraceObserver() {
Trace::SetTraceCallback(nullptr);
Trace::ReturnTrace();
}
void PushExpectedLogLine(const std::string& expected_log_line) {
callback_.PushExpectedLogLine(expected_log_line);
}
EventTypeWrapper Wait() {
return callback_.Wait();
}
private:
class Callback : public TraceCallback {
public:
Callback() : done_(EventWrapper::Create()) {}
void Print(TraceLevel level, const char* message, int length) override {
rtc::CritScope lock(&crit_sect_);
std::string msg(message);
if (msg.find("BitrateEstimator") != std::string::npos) {
received_log_lines_.push_back(msg);
}
int num_popped = 0;
while (!received_log_lines_.empty() && !expected_log_lines_.empty()) {
std::string a = received_log_lines_.front();
std::string b = expected_log_lines_.front();
received_log_lines_.pop_front();
expected_log_lines_.pop_front();
num_popped++;
EXPECT_TRUE(a.find(b) != std::string::npos);
}
if (expected_log_lines_.size() <= 0) {
if (num_popped > 0) {
done_->Set();
}
return;
}
}
EventTypeWrapper Wait() {
return done_->Wait(test::CallTest::kDefaultTimeoutMs);
}
void PushExpectedLogLine(const std::string& expected_log_line) {
rtc::CritScope lock(&crit_sect_);
expected_log_lines_.push_back(expected_log_line);
}
private:
typedef std::list<std::string> Strings;
rtc::CriticalSection crit_sect_;
Strings received_log_lines_ GUARDED_BY(crit_sect_);
Strings expected_log_lines_ GUARDED_BY(crit_sect_);
rtc::scoped_ptr<EventWrapper> done_;
};
Callback callback_;
};
} // namespace
static const int kTOFExtensionId = 4;
static const int kASTExtensionId = 5;
class BitrateEstimatorTest : public test::CallTest {
public:
BitrateEstimatorTest()
: receiver_trace_(),
send_transport_(),
receive_transport_(),
sender_call_(),
receiver_call_(),
receive_config_(nullptr),
streams_() {
}
virtual ~BitrateEstimatorTest() {
EXPECT_TRUE(streams_.empty());
}
virtual void SetUp() {
receiver_call_.reset(Call::Create(Call::Config()));
sender_call_.reset(Call::Create(Call::Config()));
send_transport_.SetReceiver(receiver_call_->Receiver());
receive_transport_.SetReceiver(sender_call_->Receiver());
send_config_ = VideoSendStream::Config(&send_transport_);
send_config_.rtp.ssrcs.push_back(kSendSsrcs[0]);
// Encoders will be set separately per stream.
send_config_.encoder_settings.encoder = nullptr;
send_config_.encoder_settings.payload_name = "FAKE";
send_config_.encoder_settings.payload_type = kFakeSendPayloadType;
encoder_config_.streams = test::CreateVideoStreams(1);
receive_config_ = VideoReceiveStream::Config(&receive_transport_);
// receive_config_.decoders will be set by every stream separately.
receive_config_.rtp.remote_ssrc = send_config_.rtp.ssrcs[0];
receive_config_.rtp.local_ssrc = kReceiverLocalSsrc;
receive_config_.rtp.remb = true;
receive_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kTOffset, kTOFExtensionId));
receive_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId));
}
virtual void TearDown() {
std::for_each(streams_.begin(), streams_.end(),
std::mem_fun(&Stream::StopSending));
send_transport_.StopSending();
receive_transport_.StopSending();
while (!streams_.empty()) {
delete streams_.back();
streams_.pop_back();
}
receiver_call_.reset();
}
protected:
friend class Stream;
class Stream {
public:
Stream(BitrateEstimatorTest* test, bool receive_audio)
: test_(test),
is_sending_receiving_(false),
send_stream_(nullptr),
audio_receive_stream_(nullptr),
video_receive_stream_(nullptr),
frame_generator_capturer_(),
fake_encoder_(Clock::GetRealTimeClock()),
fake_decoder_() {
test_->send_config_.rtp.ssrcs[0]++;
test_->send_config_.encoder_settings.encoder = &fake_encoder_;
send_stream_ = test_->sender_call_->CreateVideoSendStream(
test_->send_config_, test_->encoder_config_);
RTC_DCHECK_EQ(1u, test_->encoder_config_.streams.size());
frame_generator_capturer_.reset(test::FrameGeneratorCapturer::Create(
send_stream_->Input(),
test_->encoder_config_.streams[0].width,
test_->encoder_config_.streams[0].height,
30,
Clock::GetRealTimeClock()));
send_stream_->Start();
frame_generator_capturer_->Start();
if (receive_audio) {
AudioReceiveStream::Config receive_config;
receive_config.rtp.remote_ssrc = test_->send_config_.rtp.ssrcs[0];
// Bogus non-default id to prevent hitting a RTC_DCHECK when creating
// the AudioReceiveStream. Every receive stream has to correspond to
// an underlying channel id.
receive_config.voe_channel_id = 0;
receive_config.rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId));
receive_config.combined_audio_video_bwe = true;
audio_receive_stream_ = test_->receiver_call_->CreateAudioReceiveStream(
receive_config);
} else {
VideoReceiveStream::Decoder decoder;
decoder.decoder = &fake_decoder_;
decoder.payload_type =
test_->send_config_.encoder_settings.payload_type;
decoder.payload_name =
test_->send_config_.encoder_settings.payload_name;
test_->receive_config_.decoders.push_back(decoder);
test_->receive_config_.rtp.remote_ssrc =
test_->send_config_.rtp.ssrcs[0];
test_->receive_config_.rtp.local_ssrc++;
video_receive_stream_ = test_->receiver_call_->CreateVideoReceiveStream(
test_->receive_config_);
video_receive_stream_->Start();
}
is_sending_receiving_ = true;
}
~Stream() {
EXPECT_FALSE(is_sending_receiving_);
frame_generator_capturer_.reset(nullptr);
test_->sender_call_->DestroyVideoSendStream(send_stream_);
send_stream_ = nullptr;
if (audio_receive_stream_) {
test_->receiver_call_->DestroyAudioReceiveStream(audio_receive_stream_);
audio_receive_stream_ = nullptr;
}
if (video_receive_stream_) {
test_->receiver_call_->DestroyVideoReceiveStream(video_receive_stream_);
video_receive_stream_ = nullptr;
}
}
void StopSending() {
if (is_sending_receiving_) {
frame_generator_capturer_->Stop();
send_stream_->Stop();
if (video_receive_stream_) {
video_receive_stream_->Stop();
}
is_sending_receiving_ = false;
}
}
private:
BitrateEstimatorTest* test_;
bool is_sending_receiving_;
VideoSendStream* send_stream_;
AudioReceiveStream* audio_receive_stream_;
VideoReceiveStream* video_receive_stream_;
rtc::scoped_ptr<test::FrameGeneratorCapturer> frame_generator_capturer_;
test::FakeEncoder fake_encoder_;
test::FakeDecoder fake_decoder_;
};
TraceObserver receiver_trace_;
test::DirectTransport send_transport_;
test::DirectTransport receive_transport_;
rtc::scoped_ptr<Call> sender_call_;
rtc::scoped_ptr<Call> receiver_call_;
VideoReceiveStream::Config receive_config_;
std::vector<Stream*> streams_;
};
static const char* kAbsSendTimeLog =
"RemoteBitrateEstimatorAbsSendTime: Instantiating.";
static const char* kSingleStreamLog =
"RemoteBitrateEstimatorSingleStream: Instantiating.";
TEST_F(BitrateEstimatorTest, InstantiatesTOFPerDefaultForVideo) {
send_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kTOffset, kTOFExtensionId));
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
streams_.push_back(new Stream(this, false));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
}
TEST_F(BitrateEstimatorTest, ImmediatelySwitchToASTForAudio) {
send_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId));
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE.");
receiver_trace_.PushExpectedLogLine(kAbsSendTimeLog);
streams_.push_back(new Stream(this, true));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
}
TEST_F(BitrateEstimatorTest, ImmediatelySwitchToASTForVideo) {
send_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId));
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE.");
receiver_trace_.PushExpectedLogLine(kAbsSendTimeLog);
streams_.push_back(new Stream(this, false));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
}
TEST_F(BitrateEstimatorTest, SwitchesToASTForAudio) {
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
streams_.push_back(new Stream(this, true));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
send_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId));
receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE.");
receiver_trace_.PushExpectedLogLine(kAbsSendTimeLog);
streams_.push_back(new Stream(this, true));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
}
TEST_F(BitrateEstimatorTest, SwitchesToASTForVideo) {
send_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kTOffset, kTOFExtensionId));
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
streams_.push_back(new Stream(this, false));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
send_config_.rtp.extensions[0] =
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId);
receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE.");
receiver_trace_.PushExpectedLogLine(kAbsSendTimeLog);
streams_.push_back(new Stream(this, false));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
}
TEST_F(BitrateEstimatorTest, SwitchesToASTThenBackToTOFForVideo) {
send_config_.rtp.extensions.push_back(
RtpExtension(RtpExtension::kTOffset, kTOFExtensionId));
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
streams_.push_back(new Stream(this, false));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
send_config_.rtp.extensions[0] =
RtpExtension(RtpExtension::kAbsSendTime, kASTExtensionId);
receiver_trace_.PushExpectedLogLine("Switching to absolute send time RBE.");
receiver_trace_.PushExpectedLogLine(kAbsSendTimeLog);
streams_.push_back(new Stream(this, false));
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
send_config_.rtp.extensions[0] =
RtpExtension(RtpExtension::kTOffset, kTOFExtensionId);
receiver_trace_.PushExpectedLogLine(
"WrappingBitrateEstimator: Switching to transmission time offset RBE.");
receiver_trace_.PushExpectedLogLine(kSingleStreamLog);
streams_.push_back(new Stream(this, false));
streams_[0]->StopSending();
streams_[1]->StopSending();
EXPECT_EQ(kEventSignaled, receiver_trace_.Wait());
}
} // namespace webrtc
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, SRI International
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of SRI International nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Sachin Chitta, Dave Coleman, Mike Lautman */
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit_msgs/msg/display_robot_state.hpp>
#include <moveit_msgs/msg/display_trajectory.hpp>
#include <moveit_msgs/msg/attached_collision_object.hpp>
#include <moveit_msgs/msg/collision_object.hpp>
/* #include <moveit_visual_tools/moveit_visual_tools.h> This has not been ported to ros2 yet */
#include <rviz_visual_tools/rviz_visual_tools.hpp>
/* this is a standin for moveit_visual_tools visual_tools.prompt */
#include <moveit/macros/console_colors.h>
void prompt(const std::string& message)
{
printf(MOVEIT_CONSOLE_COLOR_GREEN "\n%s" MOVEIT_CONSOLE_COLOR_RESET, message.c_str());
fflush(stdout);
while (std::cin.get() != '\n' && rclcpp::ok())
;
}
// All source files that use ROS logging should define a file-specific
// static const rclcpp::Logger named LOGGER, located at the top of the file
// and inside the namespace with the narrowest scope (if there is one)
static const rclcpp::Logger LOGGER = rclcpp::get_logger("move_group_demo");
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
rclcpp::NodeOptions node_options;
node_options.automatically_declare_parameters_from_overrides(true);
auto move_group_node = rclcpp::Node::make_shared("move_group_interface_tutorial", node_options);
// We spin up a SingleThreadedExecutor for the current state monitor to get information
// about the robot's state.
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(move_group_node);
std::thread([&executor]() { executor.spin(); }).detach();
// BEGIN_TUTORIAL
//
// Setup
// ^^^^^
//
// MoveIt operates on sets of joints called "planning groups" and stores them in an object called
// the `JointModelGroup`. Throughout MoveIt the terms "planning group" and "joint model group"
// are used interchangably.
static const std::string PLANNING_GROUP = "panda_arm";
// The :planning_interface:`MoveGroupInterface` class can be easily
// setup using just the name of the planning group you would like to control and plan for.
moveit::planning_interface::MoveGroupInterface move_group(move_group_node, PLANNING_GROUP);
// We will use the :planning_interface:`PlanningSceneInterface`
// class to add and remove collision objects in our "virtual world" scene
moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
// Raw pointers are frequently used to refer to the planning group for improved performance.
const moveit::core::JointModelGroup* joint_model_group =
move_group.getCurrentState()->getJointModelGroup(PLANNING_GROUP);
// Visualization
// ^^^^^^^^^^^^^
//
// MoveitVisualTools has not been ported to ROS2 yet so we make use of RvizVisualTools for visualization.
// The package MoveItVisualTools provides many capabilities for visualizing objects, robots,
// and trajectories in RViz as well as debugging tools such as step-by-step introspection of a script.
namespace rvt = rviz_visual_tools;
rviz_visual_tools::RvizVisualTools visual_tools("panda_link0", "move_group_tutorial", move_group_node);
/* moveit_visual_tools::MoveItVisualTools visual_tools("panda_link0"); */
visual_tools.deleteAllMarkers();
/* Remote control is an introspection tool that allows users to step through a high level script */
/* via buttons and keyboard shortcuts in RViz */
/* visual_tools.loadRemoteControl(); */
// RViz provides many types of markers, in this demo we will use text, cylinders, and spheres
Eigen::Isometry3d text_pose = Eigen::Isometry3d::Identity();
text_pose.translation().z() = 1.0;
visual_tools.publishText(text_pose, "MoveGroupInterface Demo", rvt::WHITE, rvt::XLARGE);
// Batch publishing is used to reduce the number of messages being sent to RViz for large visualizations
visual_tools.trigger();
// Getting Basic Information
// ^^^^^^^^^^^^^^^^^^^^^^^^^
//
// We can print the name of the reference frame for this robot.
RCLCPP_INFO(LOGGER, "Planning frame: %s", move_group.getPlanningFrame().c_str());
// We can also print the name of the end-effector link for this group.
RCLCPP_INFO(LOGGER, "End effector link: %s", move_group.getEndEffectorLink().c_str());
// We can get a list of all the groups in the robot:
RCLCPP_INFO(LOGGER, "Available Planning Groups:");
std::copy(move_group.getJointModelGroupNames().begin(), move_group.getJointModelGroupNames().end(),
std::ostream_iterator<std::string>(std::cout, ", "));
// Start the demo
// ^^^^^^^^^^^^^^^^^^^^^^^^^
prompt("Press 'Enter' to start the demo");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to start the demo"); */
// .. _move_group_interface-planning-to-pose-goal:
//
// Planning to a Pose goal
// ^^^^^^^^^^^^^^^^^^^^^^^
// We can plan a motion for this group to a desired pose for the
// end-effector.
geometry_msgs::msg::Pose target_pose1;
target_pose1.orientation.w = 1.0;
target_pose1.position.x = 0.28;
target_pose1.position.y = -0.2;
target_pose1.position.z = 0.5;
move_group.setPoseTarget(target_pose1);
// Now, we call the planner to compute the plan and visualize it.
// Note that we are just planning, not asking move_group
// to actually move the robot.
moveit::planning_interface::MoveGroupInterface::Plan my_plan;
bool success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
RCLCPP_INFO(LOGGER, "Visualizing plan 1 (pose goal) %s", success ? "" : "FAILED");
// Visualizing plans
// ^^^^^^^^^^^^^^^^^
// We can also visualize the plan as a line with markers in RViz.
RCLCPP_INFO(LOGGER, "Visualizing plan 1 as trajectory line");
visual_tools.publishAxisLabeled(target_pose1, "pose1");
visual_tools.publishText(text_pose, "Pose Goal", rvt::WHITE, rvt::XLARGE);
/* visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); */
visual_tools.trigger();
prompt("Press 'Enter' to continue the demo");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo"); */
// Moving to a pose goal
// ^^^^^^^^^^^^^^^^^^^^^
//
// Moving to a pose goal is similar to the step above
// except we now use the move() function. Note that
// the pose goal we had set earlier is still active
// and so the robot will try to move to that goal. We will
// not use that function in this tutorial since it is
// a blocking function and requires a controller to be active
// and report success on execution of a trajectory.
/* Uncomment below line when working with a real robot */
/* move_group.move(); */
// Planning to a joint-space goal
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// Let's set a joint space goal and move towards it. This will replace the
// pose target we set above.
//
// To start, we'll create an pointer that references the current robot's state.
// RobotState is the object that contains all the current position/velocity/acceleration data.
moveit::core::RobotStatePtr current_state = move_group.getCurrentState(10);
//
// Next get the current set of joint values for the group.
std::vector<double> joint_group_positions;
current_state->copyJointGroupPositions(joint_model_group, joint_group_positions);
// Now, let's modify one of the joints, plan to the new joint space goal and visualize the plan.
joint_group_positions[0] = -1.0; // radians
move_group.setJointValueTarget(joint_group_positions);
// We lower the allowed maximum velocity and acceleration to 5% of their maximum.
// The default values are 10% (0.1).
// Set your preferred defaults in the joint_limits.yaml file of your robot's moveit_config
// or set explicit factors in your code if you need your robot to move faster.
move_group.setMaxVelocityScalingFactor(0.05);
move_group.setMaxAccelerationScalingFactor(0.05);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
RCLCPP_INFO(LOGGER, "Visualizing plan 2 (joint space goal) %s", success ? "" : "FAILED");
// Visualize the plan in RViz
visual_tools.deleteAllMarkers();
visual_tools.publishText(text_pose, "Joint Space Goal", rvt::WHITE, rvt::XLARGE);
/* visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); */
visual_tools.trigger();
prompt("Press 'Enter' to continue the demo");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo"); */
// Planning with Path Constraints
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// Path constraints can easily be specified for a link on the robot.
// Let's specify a path constraint and a pose goal for our group.
// First define the path constraint.
moveit_msgs::msg::OrientationConstraint ocm;
ocm.link_name = "panda_link7";
ocm.header.frame_id = "panda_link0";
ocm.orientation.w = 1.0;
ocm.absolute_x_axis_tolerance = 0.1;
ocm.absolute_y_axis_tolerance = 0.1;
ocm.absolute_z_axis_tolerance = 0.1;
ocm.weight = 1.0;
// Now, set it as the path constraint for the group.
moveit_msgs::msg::Constraints test_constraints;
test_constraints.orientation_constraints.push_back(ocm);
move_group.setPathConstraints(test_constraints);
// Enforce Planning in Joint Space
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// Depending on the planning problem MoveIt chooses between
// ``joint space`` and ``cartesian space`` for problem representation.
// Setting the group parameter ``enforce_joint_model_state_space:true`` in
// the ompl_planning.yaml file enforces the use of ``joint space`` for all plans.
//
// By default planning requests with orientation path constraints
// are sampled in ``cartesian space`` so that invoking IK serves as a
// generative sampler.
//
// By enforcing ``joint space`` the planning process will use rejection
// sampling to find valid requests. Please note that this might
// increase planning time considerably.
//
// We will reuse the old goal that we had and plan to it.
// Note that this will only work if the current state already
// satisfies the path constraints. So we need to set the start
// state to a new pose.
moveit::core::RobotState start_state(*move_group.getCurrentState());
geometry_msgs::msg::Pose start_pose2;
start_pose2.orientation.w = 1.0;
start_pose2.position.x = 0.55;
start_pose2.position.y = -0.05;
start_pose2.position.z = 0.8;
start_state.setFromIK(joint_model_group, start_pose2);
move_group.setStartState(start_state);
// Now we will plan to the earlier pose target from the new
// start state that we have just created.
move_group.setPoseTarget(target_pose1);
// Planning with constraints can be slow because every sample must call an inverse kinematics solver.
// Lets increase the planning time from the default 5 seconds to be sure the planner has enough time to succeed.
move_group.setPlanningTime(10.0);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
RCLCPP_INFO(LOGGER, "Visualizing plan 3 (constraints) %s", success ? "" : "FAILED");
// Visualize the plan in RViz
visual_tools.deleteAllMarkers();
visual_tools.publishAxisLabeled(start_pose2, "start");
visual_tools.publishAxisLabeled(target_pose1, "goal");
visual_tools.publishText(text_pose, "Constrained Goal", rvt::WHITE, rvt::XLARGE);
/* visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); */
visual_tools.trigger();
prompt("Press 'Enter' to continue the demo");
/* visual_tools.prompt("next step"); */
// When done with the path constraint be sure to clear it.
move_group.clearPathConstraints();
// Cartesian Paths
// ^^^^^^^^^^^^^^^
// You can plan a Cartesian path directly by specifying a list of waypoints
// for the end-effector to go through. Note that we are starting
// from the new start state above. The initial pose (start state) does not
// need to be added to the waypoint list but adding it can help with visualizations
std::vector<geometry_msgs::msg::Pose> waypoints;
waypoints.push_back(start_pose2);
geometry_msgs::msg::Pose target_pose3 = start_pose2;
target_pose3.position.z -= 0.2;
waypoints.push_back(target_pose3); // down
target_pose3.position.y -= 0.2;
waypoints.push_back(target_pose3); // right
target_pose3.position.z += 0.2;
target_pose3.position.y += 0.2;
target_pose3.position.x -= 0.2;
waypoints.push_back(target_pose3); // up and left
// We want the Cartesian path to be interpolated at a resolution of 1 cm
// which is why we will specify 0.01 as the max step in Cartesian
// translation. We will specify the jump threshold as 0.0, effectively disabling it.
// Warning - disabling the jump threshold while operating real hardware can cause
// large unpredictable motions of redundant joints and could be a safety issue
moveit_msgs::msg::RobotTrajectory trajectory;
const double jump_threshold = 0.0;
const double eef_step = 0.01;
double fraction = move_group.computeCartesianPath(waypoints, eef_step, jump_threshold, trajectory);
RCLCPP_INFO(LOGGER, "Visualizing plan 4 (Cartesian path) (%.2f%% acheived)", fraction * 100.0);
// Visualize the plan in RViz
visual_tools.deleteAllMarkers();
visual_tools.publishText(text_pose, "Cartesian Path", rvt::WHITE, rvt::XLARGE);
visual_tools.publishPath(waypoints, rvt::LIME_GREEN, rvt::SMALL);
for (std::size_t i = 0; i < waypoints.size(); ++i)
visual_tools.publishAxisLabeled(waypoints[i], "pt" + std::to_string(i), rvt::SMALL);
visual_tools.trigger();
prompt("Press 'Enter' to continue the demo");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue the demo"); */
// Cartesian motions should often be slow, e.g. when approaching objects. The speed of cartesian
// plans cannot currently be set through the maxVelocityScalingFactor, but requires you to time
// the trajectory manually, as described `here <https://groups.google.com/forum/#!topic/moveit-users/MOoFxy2exT4>`_.
// Pull requests are welcome.
//
// You can execute a trajectory like this.
/* move_group.execute(trajectory); */
// Adding objects to the environment
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// First let's plan to another simple goal with no objects in the way.
move_group.setStartState(*move_group.getCurrentState());
geometry_msgs::msg::Pose another_pose;
another_pose.orientation.w = 0;
another_pose.orientation.x = -1.0;
another_pose.position.x = 0.7;
another_pose.position.y = 0.0;
another_pose.position.z = 0.59;
move_group.setPoseTarget(another_pose);
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
RCLCPP_INFO(LOGGER, "Visualizing plan 5 (with no obstacles) %s", success ? "" : "FAILED");
visual_tools.deleteAllMarkers();
visual_tools.publishText(text_pose, "Clear Goal", rvt::WHITE, rvt::XLARGE);
visual_tools.publishAxisLabeled(another_pose, "goal");
/* visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); */
visual_tools.trigger();
prompt("Press 'Enter' to continue the demo");
/* visual_tools.prompt("next step"); */
// The result may look like this:
//
// .. image:: ./move_group_interface_tutorial_clear_path.gif
// :alt: animation showing the arm moving relatively straight toward the goal
//
// Now let's define a collision object ROS message for the robot to avoid.
moveit_msgs::msg::CollisionObject collision_object;
collision_object.header.frame_id = move_group.getPlanningFrame();
// The id of the object is used to identify it.
collision_object.id = "box1";
// Define a box to add to the world.
shape_msgs::msg::SolidPrimitive primitive;
primitive.type = primitive.BOX;
primitive.dimensions.resize(3);
primitive.dimensions[primitive.BOX_X] = 0.1;
primitive.dimensions[primitive.BOX_Y] = 1.5;
primitive.dimensions[primitive.BOX_Z] = 0.5;
// Define a pose for the box (specified relative to frame_id)
geometry_msgs::msg::Pose box_pose;
box_pose.orientation.w = 1.0;
box_pose.position.x = 0.48;
box_pose.position.y = 0.0;
box_pose.position.z = 0.25;
collision_object.primitives.push_back(primitive);
collision_object.primitive_poses.push_back(box_pose);
collision_object.operation = collision_object.ADD;
std::vector<moveit_msgs::msg::CollisionObject> collision_objects;
collision_objects.push_back(collision_object);
// Now, let's add the collision object into the world
// (using a vector that could contain additional objects)
RCLCPP_INFO(LOGGER, "Add an object into the world");
planning_scene_interface.addCollisionObjects(collision_objects);
// Show text in RViz of status and wait for MoveGroup to receive and process the collision object message
visual_tools.publishText(text_pose, "Add object", rvt::WHITE, rvt::XLARGE);
visual_tools.trigger();
prompt("Press 'Enter' to continue once the collision object appears in RViz");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object appears in RViz"); */
// Now when we plan a trajectory it will avoid the obstacle
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
RCLCPP_INFO(LOGGER, "Visualizing plan 6 (pose goal move around cuboid) %s", success ? "" : "FAILED");
visual_tools.publishText(text_pose, "Obstacle Goal", rvt::WHITE, rvt::XLARGE);
/* visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); */
visual_tools.trigger();
prompt("Press 'Enter' to continue once the plan is complete");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the plan is complete"); */
// The result may look like this:
//
// .. image:: ./move_group_interface_tutorial_avoid_path.gif
// :alt: animation showing the arm moving avoiding the new obstacle
//
// Attaching objects to the robot
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// You can attach objects to the robot, so that it moves with the robot geometry.
// This simulates picking up the object for the purpose of manipulating it.
// The motion planning should avoid collisions between the two objects as well.
moveit_msgs::msg::CollisionObject object_to_attach;
object_to_attach.id = "cylinder1";
shape_msgs::msg::SolidPrimitive cylinder_primitive;
cylinder_primitive.type = primitive.CYLINDER;
cylinder_primitive.dimensions.resize(2);
cylinder_primitive.dimensions[primitive.CYLINDER_HEIGHT] = 0.20;
cylinder_primitive.dimensions[primitive.CYLINDER_RADIUS] = 0.04;
// We define the frame/pose for this cylinder so that it appears in the gripper
object_to_attach.header.frame_id = move_group.getEndEffectorLink();
geometry_msgs::msg::Pose grab_pose;
grab_pose.orientation.w = 1.0;
grab_pose.position.z = 0.2;
// First, we add the object to the world (without using a vector)
object_to_attach.primitives.push_back(cylinder_primitive);
object_to_attach.primitive_poses.push_back(grab_pose);
object_to_attach.operation = object_to_attach.ADD;
planning_scene_interface.applyCollisionObject(object_to_attach);
// Then, we "attach" the object to the robot. It uses the frame_id to determine which robot link it is attached to
// and we also need to tell MoveIt that the object is allowed to be in collision with the finger links of the gripper.
// You could also use applyAttachedCollisionObject to attach an object to the robot directly.
RCLCPP_INFO(LOGGER, "Attach the object to the robot");
std::vector<std::string> touch_links;
touch_links.push_back("panda_rightfinger");
touch_links.push_back("panda_leftfinger");
move_group.attachObject(object_to_attach.id, "panda_hand", touch_links);
visual_tools.publishText(text_pose, "Object attached to robot", rvt::WHITE, rvt::XLARGE);
visual_tools.trigger();
/* Wait for MoveGroup to receive and process the attached collision object message */
prompt("Press 'Enter' once the collision object attaches to the robot");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the new object is attached to the robot"); */
// Replan, but now with the object in hand.
move_group.setStartStateToCurrentState();
success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
RCLCPP_INFO(LOGGER, "Visualizing plan 7 (move around cuboid with cylinder) %s", success ? "" : "FAILED");
/* visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group); */
visual_tools.trigger();
prompt("Press 'Enter' once the plan is complete");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the plan is complete"); */
// The result may look something like this:
//
// .. image:: ./move_group_interface_tutorial_attached_object.gif
// :alt: animation showing the arm moving differently once the object is attached
//
// Detaching and Removing Objects
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
// Now, let's detach the cylinder from the robot's gripper.
RCLCPP_INFO(LOGGER, "Detach the object from the robot");
move_group.detachObject(object_to_attach.id);
// Show text in RViz of status
visual_tools.deleteAllMarkers();
visual_tools.publishText(text_pose, "Object detached from robot", rvt::WHITE, rvt::XLARGE);
visual_tools.trigger();
/* Wait for MoveGroup to receive and process the attached collision object message */
prompt("Press 'Enter' once the collision object detaches from the robot");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window once the new object is detached from the robot"); */
// Now, let's remove the objects from the world.
RCLCPP_INFO(LOGGER, "Remove the objects from the world");
std::vector<std::string> object_ids;
object_ids.push_back(collision_object.id);
object_ids.push_back(object_to_attach.id);
planning_scene_interface.removeCollisionObjects(object_ids);
// Show text in RViz of status
visual_tools.publishText(text_pose, "Objects removed", rvt::WHITE, rvt::XLARGE);
visual_tools.trigger();
/* Wait for MoveGroup to receive and process the attached collision object message */
prompt("Press 'Enter' once the collision object disappears");
/* visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to once the collision object disapears"); */
// END_TUTORIAL
rclcpp::shutdown();
return 0;
}
|
// Copyright 2016 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 "net/http2/hpack/decoder/hpack_whole_entry_buffer.h"
#include "base/logging.h"
#include "base/trace_event/memory_usage_estimator.h"
namespace net {
HpackWholeEntryBuffer::HpackWholeEntryBuffer(HpackWholeEntryListener* listener,
size_t max_string_size_bytes)
: max_string_size_bytes_(max_string_size_bytes) {
set_listener(listener);
}
HpackWholeEntryBuffer::~HpackWholeEntryBuffer() {}
void HpackWholeEntryBuffer::set_listener(HpackWholeEntryListener* listener) {
CHECK(listener);
listener_ = listener;
}
void HpackWholeEntryBuffer::set_max_string_size_bytes(
size_t max_string_size_bytes) {
max_string_size_bytes_ = max_string_size_bytes;
}
void HpackWholeEntryBuffer::BufferStringsIfUnbuffered() {
name_.BufferStringIfUnbuffered();
value_.BufferStringIfUnbuffered();
}
size_t HpackWholeEntryBuffer::EstimateMemoryUsage() const {
return base::trace_event::EstimateMemoryUsage(name_) +
base::trace_event::EstimateMemoryUsage(value_);
}
void HpackWholeEntryBuffer::OnIndexedHeader(size_t index) {
DVLOG(2) << "HpackWholeEntryBuffer::OnIndexedHeader: index=" << index;
listener_->OnIndexedHeader(index);
}
void HpackWholeEntryBuffer::OnStartLiteralHeader(HpackEntryType entry_type,
size_t maybe_name_index) {
DVLOG(2) << "HpackWholeEntryBuffer::OnStartLiteralHeader: entry_type="
<< entry_type << ", maybe_name_index=" << maybe_name_index;
entry_type_ = entry_type;
maybe_name_index_ = maybe_name_index;
}
void HpackWholeEntryBuffer::OnNameStart(bool huffman_encoded, size_t len) {
DVLOG(2) << "HpackWholeEntryBuffer::OnNameStart: huffman_encoded="
<< (huffman_encoded ? "true" : "false") << ", len=" << len;
DCHECK_EQ(maybe_name_index_, 0u);
if (!error_detected_) {
if (len > max_string_size_bytes_) {
DVLOG(1) << "Name length (" << len << ") is longer than permitted ("
<< max_string_size_bytes_ << ")";
ReportError("HPACK entry name size is too long.");
return;
}
name_.OnStart(huffman_encoded, len);
}
}
void HpackWholeEntryBuffer::OnNameData(const char* data, size_t len) {
DVLOG(2) << "HpackWholeEntryBuffer::OnNameData: len=" << len
<< "\n data: " << Http2StringPiece(data, len);
DCHECK_EQ(maybe_name_index_, 0u);
if (!error_detected_ && !name_.OnData(data, len)) {
ReportError("Error decoding HPACK entry name.");
}
}
void HpackWholeEntryBuffer::OnNameEnd() {
DVLOG(2) << "HpackWholeEntryBuffer::OnNameEnd";
DCHECK_EQ(maybe_name_index_, 0u);
if (!error_detected_ && !name_.OnEnd()) {
ReportError("Error decoding HPACK entry name.");
}
}
void HpackWholeEntryBuffer::OnValueStart(bool huffman_encoded, size_t len) {
DVLOG(2) << "HpackWholeEntryBuffer::OnValueStart: huffman_encoded="
<< (huffman_encoded ? "true" : "false") << ", len=" << len;
if (!error_detected_) {
if (len > max_string_size_bytes_) {
DVLOG(1) << "Value length (" << len << ") is longer than permitted ("
<< max_string_size_bytes_ << ")";
ReportError("HPACK entry value size is too long.");
return;
}
value_.OnStart(huffman_encoded, len);
}
}
void HpackWholeEntryBuffer::OnValueData(const char* data, size_t len) {
DVLOG(2) << "HpackWholeEntryBuffer::OnValueData: len=" << len
<< "\n data: " << Http2StringPiece(data, len);
if (!error_detected_ && !value_.OnData(data, len)) {
ReportError("Error decoding HPACK entry value.");
}
}
void HpackWholeEntryBuffer::OnValueEnd() {
DVLOG(2) << "HpackWholeEntryBuffer::OnValueEnd";
if (error_detected_) {
return;
}
if (!value_.OnEnd()) {
ReportError("Error decoding HPACK entry value.");
return;
}
if (maybe_name_index_ == 0) {
listener_->OnLiteralNameAndValue(entry_type_, &name_, &value_);
name_.Reset();
} else {
listener_->OnNameIndexAndLiteralValue(entry_type_, maybe_name_index_,
&value_);
}
value_.Reset();
}
void HpackWholeEntryBuffer::OnDynamicTableSizeUpdate(size_t size) {
DVLOG(2) << "HpackWholeEntryBuffer::OnDynamicTableSizeUpdate: size=" << size;
listener_->OnDynamicTableSizeUpdate(size);
}
void HpackWholeEntryBuffer::ReportError(Http2StringPiece error_message) {
if (!error_detected_) {
DVLOG(1) << "HpackWholeEntryBuffer::ReportError: " << error_message;
error_detected_ = true;
listener_->OnHpackDecodeError(error_message);
listener_ = HpackWholeEntryNoOpListener::NoOpListener();
}
}
} // namespace net
|
//
// Created by Jakub Gert on 04/05/2021.
//
#include <QtTest/QtTest>
#include "tests/TestSuite.h"
#include "Parser.h"
using namespace gCode;
using namespace machine;
class G18Tests : public TestSuite {
Q_OBJECT
private slots:
void testMissingArgument() {
auto parser = gCode::Parser();
parser.parse("");
auto block = parser.blocks()[0];
auto nextState = MachineState();
auto result = G18(block, nextState);
QCOMPARE(result, false);
QCOMPARE(nextState.error, Error(0, Error::InvalidArgumentsCount));
QCOMPARE(nextState.operation, Operation());
}
void testInvalidCommandChunkType() {
auto parser = gCode::Parser();
parser.parse("X10");
auto block = parser.blocks()[0];
auto nextState = MachineState();
auto result = G18(block, nextState);
QCOMPARE(result, false);
QCOMPARE(nextState.operation, Operation());
QCOMPARE(nextState.error, Error(0, Error::InvalidCommandChunkType));
}
void testInvalidCommandNumber() {
auto parser = gCode::Parser();
parser.parse("G21");
auto block = parser.blocks()[0];
auto nextState = MachineState();
auto result = G18(block, nextState);
QCOMPARE(result, false);
QCOMPARE(nextState.operation, Operation());
QCOMPARE(nextState.error, Error(0, Error::InvalidCommandNumber));
}
void testUnexpectedSubcommand() {
auto parser = gCode::Parser();
parser.parse("G20.1");
auto block = parser.blocks()[0];
auto nextState = MachineState();
auto result = G18(block, nextState);
QCOMPARE(result, false);
QCOMPARE(nextState.operation, Operation());
QCOMPARE(nextState.error, Error(0, Error::InvalidCommandNumber));
}
void testSwitchToYZ() {
auto parser = gCode::Parser();
parser.parse("G18");
MachineState nextState;
nextState.planeSelection = MachineState::PlaneSelection::XY;
auto block = parser.blocks()[0];
auto result = G18(block, nextState);
QCOMPARE(result, true);
QCOMPARE(nextState.error, Error());
QCOMPARE(nextState.operation, Operation());
QCOMPARE(nextState.planeSelection, MachineState::ZX);
QCOMPARE(nextState.lastGCodeCommand, 18);
QCOMPARE(nextState.lastGCodeSubcommand, 0);
}
};
static G18Tests T_G18Tests;
#include "G18.test.moc"
|
#include "CQF_MitkInit.h"
#include "MitkMain/IQF_MitkDataManager.h"
#include "MitkMain/IQF_MitkRenderWindow.h"
#include "iqf_main.h"
//mitk
#include "QmitkRegisterClasses.h"
#include "mitkStandaloneDataStorage.h"
//qt
#include <QSettings>
CQF_MitkInit::CQF_MitkInit(QF::IQF_Main* pMain) :m_pMain(pMain)
{
}
CQF_MitkInit::~CQF_MitkInit()
{
}
void CQF_MitkInit::Init(mitk::DataStorage* dataStorager)
{
vtkObject::GlobalWarningDisplayOff();
QmitkRegisterClasses();
IQF_MitkDataManager* pDataManager = (IQF_MitkDataManager*)m_pMain->GetInterfacePtr(QF_MitkMain_DataManager);
if (pDataManager)
{
if (dataStorager)
{
pDataManager->SetDataStorage(dataStorager);
}
pDataManager->Init();
QSettings set(QString(m_pMain->GetConfigPath()).append("/mitk/config.ini"), QSettings::IniFormat);
set.beginGroup("DataStorage");
foreach(QString str,set.childKeys())
{
if (set.value(str,false).toBool())
{
mitk::DataStorage::Pointer newDataStorage = mitk::StandaloneDataStorage::New();
pDataManager->SetDataStorage(newDataStorage, str.toLocal8Bit().constData());
}
}
set.endGroup();
}
}
void CQF_MitkInit::SetStdMultiWidget(QmitkStdMultiWidget* stdMultiWidget)
{
IQF_MitkRenderWindow* pRenderWindowManager = (IQF_MitkRenderWindow*)m_pMain->GetInterfacePtr(QF_MitkMain_RenderWindow);
if (pRenderWindowManager&&stdMultiWidget)
{
pRenderWindowManager->SetMitkStdMultiWidget(stdMultiWidget);
}
}
|
/*
* Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/HashTable.h>
#include <LibJS/Runtime/WeakMapPrototype.h>
namespace JS {
WeakMapPrototype::WeakMapPrototype(GlobalObject& global_object)
: Object(*global_object.object_prototype())
{
}
void WeakMapPrototype::initialize(GlobalObject& global_object)
{
auto& vm = this->vm();
Object::initialize(global_object);
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(vm.names.delete_, delete_, 1, attr);
define_native_function(vm.names.get, get, 1, attr);
define_native_function(vm.names.has, has, 1, attr);
define_native_function(vm.names.set, set, 2, attr);
// 24.3.3.6 WeakMap.prototype [ @@toStringTag ], https://tc39.es/ecma262/#sec-weakmap.prototype-@@tostringtag
define_property(vm.well_known_symbol_to_string_tag(), js_string(vm.heap(), vm.names.WeakMap.as_string()), Attribute::Configurable);
}
WeakMapPrototype::~WeakMapPrototype()
{
}
WeakMap* WeakMapPrototype::typed_this(VM& vm, GlobalObject& global_object)
{
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return {};
if (!is<WeakMap>(this_object)) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotA, "WeakMap");
return nullptr;
}
return static_cast<WeakMap*>(this_object);
}
// 24.3.3.2 WeakMap.prototype.delete ( key ), https://tc39.es/ecma262/#sec-weakmap.prototype.delete
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::delete_)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object())
return Value(false);
return Value(weak_map->values().remove(&value.as_object()));
}
// 24.3.3.3 WeakMap.prototype.get ( key ), https://tc39.es/ecma262/#sec-weakmap.prototype.get
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::get)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object())
return js_undefined();
auto& values = weak_map->values();
auto result = values.find(&value.as_object());
if (result == values.end())
return js_undefined();
return result->value;
}
// 24.3.3.4 WeakMap.prototype.has ( key ), https://tc39.es/ecma262/#sec-weakmap.prototype.has
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::has)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object())
return Value(false);
auto& values = weak_map->values();
return Value(values.find(&value.as_object()) != values.end());
}
// 24.3.3.5 WeakMap.prototype.set ( key, value ), https://tc39.es/ecma262/#sec-weakmap.prototype.set
JS_DEFINE_NATIVE_FUNCTION(WeakMapPrototype::set)
{
auto* weak_map = typed_this(vm, global_object);
if (!weak_map)
return {};
auto value = vm.argument(0);
if (!value.is_object()) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());
return {};
}
weak_map->values().set(&value.as_object(), vm.argument(1));
return weak_map;
}
}
|
/*
* 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.
*/
/*!
* \file transform.cc
* \brief Dynamic Transform operators.
*/
#include "transform.h"
#include <tvm/relay/attrs/transform.h>
#include <tvm/relay/op.h>
#include <tvm/relay/op_attr_types.h>
#include <tvm/runtime/registry.h>
#include <tvm/tir/data_layout.h>
#include <tvm/topi/broadcast.h>
#include <tvm/topi/elemwise.h>
#include <tvm/topi/transform.h>
#include <string>
#include <utility>
#include <vector>
#include "../../../transforms/infer_layout_utils.h"
namespace tvm {
namespace relay {
namespace dyn {
/* relay.dyn.reshape */
bool ReshapeRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// types: [data, newshape, result]
ICHECK_EQ(types.size(), 3);
const auto* data = types[0].as<TensorTypeNode>();
if (data == nullptr) {
ICHECK(types[0].as<IncompleteTypeNode>())
<< "reshape: expect input type to be TensorType but get " << types[0];
return false;
}
Array<IndexExpr> oshape;
const auto* newshape = types[1].as<TensorTypeNode>();
if (newshape == nullptr) {
ICHECK(types[1].as<IncompleteTypeNode>())
<< "reshape: expect input type to be TensorType but get " << types[1];
return false;
}
const IntImmNode* rank = newshape->shape[0].as<IntImmNode>();
ICHECK(rank != nullptr) << "Dynamic Reshape doesn't support Dynamic Rank";
for (int i = 0; i < rank->value; i++) {
oshape.push_back(Any());
}
reporter->Assign(types[2], TensorType(oshape, data->dtype));
return true;
}
Array<te::Tensor> ReshapeCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
const auto* out_ttype = out_type.as<TensorTypeNode>();
ICHECK(out_ttype != nullptr);
Array<IndexExpr> newshape;
for (auto val : out_ttype->shape) {
if (val->IsInstance<tir::AnyNode>()) {
newshape.push_back(val.as<tir::AnyNode>()->ToVar());
} else {
newshape.push_back(val);
}
}
return {topi::reshape(inputs[0], newshape)};
}
Expr MakeReshape(Expr data, Expr newshape, bool allowzero = false) {
auto attrs = make_object<ReshapeAttrs>();
attrs->allowzero = allowzero;
static const Op& op = Op::Get("dyn.reshape");
return Call(op, {data, newshape}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.reshape").set_body_typed(MakeReshape);
RELAY_REGISTER_OP("dyn.reshape")
.describe(R"code(Reshapes the input array based on the values in the newshape array.
To give user more convenience in without doing manual shape inference,
some dimensions of the shape can take special values from the set {0, -1, -3}.
The significance of each is explained below:
``0`` copy this dimension from the input to the output shape.
.. code-block:: python
data.shape = (2,3,4), newshape = (4,0,2), result.shape = (4,3,2)
data.shape = (2,3,4), newshape = (2,0,0), result.shape = (2,3,4)
``-1`` infers the dimension of the output shape by using the remainder of
the input dimensions keeping the size of the new array same as that of the input array.
At most one dimension of shape can be -1.
.. code-block:: python
data.shape = (2,3,4), newshape = (6,1,-1), result.shape = (6,1,4)
data.shape = (2,3,4), newshape = (3,-1,8), result.shape = (3,1,8)
data.shape = (2,3,4), newshape = (-1,), result.shape = (24,)
``-3`` use the product of two consecutive dimensions of the input shape
as the output dimension.
.. code-block:: python
data.shape = (2,3,4), newshape = (-3,4), result.shape = (6,4)
data.shape = (2,3,4,5), newshape = (-3,-3), result.shape = (6,20)
data.shape = (2,3,4), newshape = (0,-3), result.shape = (2,12)
Special values -2 and -4 from the standard reshape op would introduce dynamic rank
in this op. Thus, they are not permitted.
)code" TVM_ADD_FILELINE)
.set_num_inputs(2)
.set_attrs_type<ReshapeAttrs>()
.add_argument("data", "Tensor", "The input tensor.")
.add_argument("newshape", "Tensor", "The shape of output tensor.")
.set_support_level(3)
.add_type_rel("DynamicReshape", ReshapeRel)
.set_attr<FTVMCompute>("FTVMCompute", ReshapeCompute)
.set_attr<TOpPattern>("TOpPattern", kInjective)
.set_attr<TReshapeOp>("TReshapeOp", true);
// tile operator
// TVM_REGISTER_NODE_TYPE(TileAttrs);
bool TileRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// `types` contains: [data, reps, result]
ICHECK_EQ(types.size(), 3);
const auto* data = types[0].as<TensorTypeNode>();
const auto* reps = types[1].as<TensorTypeNode>();
if (data == nullptr) {
ICHECK(types[0].as<IncompleteTypeNode>())
<< "tile: expect input type to be TensorType but get " << types[0];
return false;
}
if (reps == nullptr) {
ICHECK(types[1].as<IncompleteTypeNode>())
<< "tile: expect input type to be TensorType but get " << types[1];
return false;
}
const IntImmNode* reps_shape = reps->shape[0].as<IntImmNode>();
ICHECK(reps_shape) << "Parameter reps must have static shape";
const size_t ndim = data->shape.size();
const size_t rndim = reps_shape->value;
size_t tndim = (ndim > rndim) ? ndim : rndim;
std::vector<IndexExpr> oshape;
oshape.reserve(tndim);
for (size_t i = 0; i < tndim; ++i) {
oshape.emplace_back(Any());
}
reporter->Assign(types[2], TensorType(oshape, data->dtype));
return true;
}
Array<te::Tensor> TileCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
ICHECK_EQ(inputs.size(), 2);
const auto* out_ttype = out_type.as<TensorTypeNode>();
size_t rndim = inputs[1]->shape[0].as<IntImmNode>()->value;
return {topi::dyn_tile(inputs[0], out_ttype->shape, rndim)};
}
Expr MakeTile(Expr data, Expr reps) {
auto attrs = make_object<TileAttrs>();
static const Op& op = Op::Get("dyn.tile");
return Call(op, {data, reps}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.tile").set_body_typed(MakeTile);
RELAY_REGISTER_OP("dyn.tile")
.describe(R"code(Repeat the whole array multiple times.
- **data**: The input data to the operator.
- **reps**: The number of times to repeat the operator.
)code" TVM_ADD_FILELINE)
.set_num_inputs(2)
.set_attrs_type<TileAttrs>()
.add_argument("data", "Tensor", "The input tensor.")
.add_argument("reps", "Tensor", "The number of times to repeat the input on each axis.")
.set_support_level(3)
.add_type_rel("DynamicTile", TileRel)
.set_attr<FTVMCompute>("FTVMCompute", TileCompute)
.set_attr<TOpPattern>("TOpPattern", kInjective);
// broadcast_to operator
bool BroadCastToRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// types = [data_type, broadcast_shape_type, ret_type]
ICHECK_EQ(types.size(), 3);
const auto* input_type = types[0].as<TensorTypeNode>();
const auto* target_type = types[1].as<TensorTypeNode>();
if (target_type == nullptr) {
return false;
}
if (input_type == nullptr) {
return false;
}
auto out_dtype = input_type->dtype;
// rank must be static
const IntImmNode* rank = target_type->shape[0].as<IntImmNode>();
ICHECK(rank)
<< "Target shape must have static rank"; // rank must be static even in dyn pass
// could add support for dyn rank in futures
std::vector<IndexExpr> oshape;
for (int i = 0; i < rank->value; ++i) {
oshape.push_back(Any());
}
reporter->Assign(types[2], TensorType(oshape, out_dtype));
return true;
}
Expr MakeBroadCastTo(Expr data, Expr shape) {
static const Op& op = Op::Get("dyn.broadcast_to");
auto attrs = make_object<InitOpAttrs>();
return Call(op, {data, shape}, Attrs(attrs), {});
}
Array<te::Tensor> BroadCastToCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
const auto* out_ttype = out_type.as<TensorTypeNode>();
return {topi::broadcast_to(inputs[0], out_ttype->shape)};
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.broadcast_to").set_body_typed(MakeBroadCastTo);
RELAY_REGISTER_OP("dyn.broadcast_to")
.describe(R"code(Broadcast the first input to match the shape argument.
)code" TVM_ADD_FILELINE)
.set_num_inputs(2)
.add_argument("data", "Tensor", "The input tensor.")
.add_argument("shape", "Tensor", "Target shape.")
.set_support_level(4)
.add_type_rel("DynamicBroadCastTo", BroadCastToRel)
.set_attr<FTVMCompute>("FTVMCompute", BroadCastToCompute)
.set_attr<TOpPattern>("TOpPattern", kBroadcast);
// zeros and ones operator
bool InitOpRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// types = [zeros_shape, ret_type]
ICHECK_EQ(types.size(), 2);
const InitOpAttrs* param = attrs.as<InitOpAttrs>();
const auto* fill_shape = types[0].as<TensorTypeNode>();
DataType out_dtype = param->dtype;
const IntImmNode* shape_shape = fill_shape->shape[0].as<IntImmNode>();
ICHECK(shape_shape) << "Parameter shape must have static rank";
std::vector<IndexExpr> oshape;
for (int i = 0; i < shape_shape->value; ++i) {
oshape.push_back(Any());
}
reporter->Assign(types[1], TensorType(oshape, out_dtype));
return true;
}
Expr MakeZeros(Expr shape, DataType dtype) {
auto attrs = make_object<InitOpAttrs>();
attrs->dtype = std::move(dtype);
static const Op& op = Op::Get("dyn.zeros");
return Call(op, {shape}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.zeros").set_body_typed(MakeZeros);
RELAY_REGISTER_OP("dyn.zeros")
.describe(R"code(Fill array with zeros.
)code" TVM_ADD_FILELINE)
.set_attrs_type<InitOpAttrs>()
.set_num_inputs(1)
.add_argument("shape", "Tensor", "Target shape.")
.set_support_level(3)
.add_type_rel("DynamicInitOp", InitOpRel);
Expr MakeOnes(Expr shape, DataType dtype) {
auto attrs = make_object<InitOpAttrs>();
attrs->dtype = std::move(dtype);
static const Op& op = Op::Get("dyn.ones");
return Call(op, {shape}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.ones").set_body_typed(MakeOnes);
RELAY_REGISTER_OP("dyn.ones")
.describe(R"code(Fill array with ones.
)code" TVM_ADD_FILELINE)
.set_attrs_type<InitOpAttrs>()
.set_num_inputs(1)
.add_argument("shape", "Tensor", "Target shape.")
.set_support_level(3)
.add_type_rel("DynamicInitOp", InitOpRel);
bool OneHotRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// `types` contains: [indices, on_value, off_value, result]
ICHECK_EQ(types.size(), 5);
const auto* indices = types[0].as<TensorTypeNode>();
ICHECK(indices);
const auto param = attrs.as<OneHotAttrs>();
Array<IndexExpr> oshape;
int ndim = indices->shape.size() + 1;
int indices_index = 0;
int true_axis = (param->axis == -1) ? indices->shape.size() : param->axis;
for (int i = 0; i < ndim; i++) {
if (i == true_axis) {
oshape.push_back(Any());
} else {
oshape.push_back(indices->shape[indices_index++]);
}
}
reporter->Assign(types[4], TensorType(oshape, param->dtype));
return true;
}
Array<te::Tensor> OneHotCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
const auto* param = attrs.as<OneHotAttrs>();
ICHECK(param != nullptr);
const auto* out_ttype = out_type.as<TensorTypeNode>();
return Array<te::Tensor>{topi::one_hot(inputs[0], inputs[1](), inputs[2](), -1, param->axis,
param->dtype, out_ttype->shape)};
}
Expr MakeOneHot(Expr indices, Expr on_value, Expr off_value, Expr depth, int axis, DataType dtype) {
auto attrs = make_object<OneHotAttrs>();
attrs->axis = axis;
attrs->dtype = dtype;
static const Op& op = Op::Get("dyn.one_hot");
return Call(op, {indices, on_value, off_value, depth}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.one_hot").set_body_typed(MakeOneHot);
RELAY_REGISTER_OP("dyn.one_hot")
.describe(R"code(Returns a one-hot tensor where the locations repsented by indices take value 1,
other locations take value 0. Final dimension is <indices dimensions> x depth.
**indices** Locations to set to 1.
**on_value** Value to fill at indices.
**off_value** Value to fill at all other positions besides indices.
**depth** Depth of the one-hot dimension.
**axis** Axis to fill.
**dtype**)code" TVM_ADD_FILELINE)
.set_attrs_type<OneHotAttrs>()
.set_num_inputs(4)
.add_argument("indices", "Tensor", "Locations to set to on_value.")
.add_argument("on_value", "Expr", "Value to fill at indices.")
.add_argument("off_value", "Expr", "Value to fill at all other positions besides indices.")
.add_argument("depth", "Expr", "Value to fill at all other positions besides indices.")
.set_support_level(10)
.add_type_rel("DynOneHot", OneHotRel)
.set_attr<FTVMCompute>("FTVMCompute", OneHotCompute)
.set_attr<TOpPattern>("TOpPattern", kOutEWiseFusable);
bool FullRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
ICHECK_EQ(types.size(), 3);
const InitOpAttrs* param = attrs.as<InitOpAttrs>();
const auto* fill_value = types[0].as<TensorTypeNode>();
const auto* fill_shape = types[1].as<TensorTypeNode>();
if (fill_value == nullptr) {
return false;
}
if (fill_shape == nullptr) {
return false;
}
DataType out_dtype = param->dtype;
if (out_dtype.bits() == 0) {
out_dtype = fill_value->dtype;
}
ICHECK_EQ(fill_value->shape.size(), 0)
<< "Fill value should be a scalar but has dimension " << fill_value->shape.size() << ".";
const IntImmNode* rank = fill_shape->shape[0].as<IntImmNode>();
ICHECK(rank) << "Parameter shape must have static rank";
std::vector<IndexExpr> oshape;
for (int i = 0; i < rank->value; ++i) {
oshape.push_back(Any());
}
reporter->Assign(types[2], TensorType(oshape, out_dtype));
return true;
}
Expr MakeFull(Expr fill_value, Expr shape, DataType dtype) {
auto attrs = make_object<InitOpAttrs>();
attrs->dtype = std::move(dtype);
static const Op& op = Op::Get("dyn.full");
return Call(op, {fill_value, shape}, Attrs(attrs), {});
}
Array<te::Tensor> FullCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
const auto* out_ttype = out_type.as<TensorTypeNode>();
return {topi::full(out_ttype->shape, out_ttype->dtype, inputs[0]())};
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.full").set_body_typed(MakeFull);
RELAY_REGISTER_OP("dyn.full")
.describe(R"code(Fill array with scalar value.
)code" TVM_ADD_FILELINE)
.set_attrs_type<InitOpAttrs>()
.set_num_inputs(2)
.add_argument("fill_value", "double", "The value to fill.")
.add_argument("shape", "Tensor", "Target shape.")
.set_support_level(3)
.add_type_rel("DynamicFull", FullRel)
.set_attr<FTVMCompute>("FTVMCompute", FullCompute)
.set_attr<TOpPattern>("TOpPattern", kElemWise);
bool StridedSliceRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// [data, begin, end, strides, out]
ICHECK_EQ(types.size(), 5);
const StridedSliceAttrs* param = attrs.as<StridedSliceAttrs>();
if (param == nullptr) {
return false;
}
const auto* data = types[0].as<TensorTypeNode>();
if (data == nullptr) {
return false;
}
auto dshape = data->shape;
int64_t num_axis = dshape.size();
const auto* begin = types[1].as<TensorTypeNode>();
if (begin == nullptr) {
return false;
}
ICHECK(begin);
// calculate output shape
std::vector<IndexExpr> oshape(num_axis);
int64_t num_dynamic_axes = begin->shape[0].as<IntImmNode>()->value;
for (int64_t i = 0; i < num_dynamic_axes; ++i) {
oshape[i] = Any();
}
for (int64_t i = num_dynamic_axes; i < num_axis; ++i) {
oshape[i] = dshape[i];
}
reporter->Assign(types[4], TensorType(oshape, data->dtype));
return true;
}
Array<te::Tensor> StridedSliceCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
te::Tensor data = inputs[0];
te::Tensor begin = inputs[1];
te::Tensor end = inputs[2];
te::Tensor strides = inputs[3];
// Dynamic computation
int64_t data_rank = data->shape.size();
int64_t num_dynamic_axes = begin->shape[0].as<IntImmNode>()->value;
ICHECK(end->shape[0].as<IntImmNode>()->value == num_dynamic_axes &&
strides->shape[0].as<IntImmNode>()->value == num_dynamic_axes)
<< "begin, end, strides should have the same length if they are dynamic variables";
ICHECK(num_dynamic_axes <= data_rank)
<< "the number of dynamic axes to slice should be less than or equal to the data rank";
return Array<te::Tensor>{topi::dynamic_strided_slice(data, begin, end, strides)};
}
Expr MakeStridedSlice(Expr data, Expr begin, Expr end, Expr strides, String slice_mode) {
auto attrs = make_object<StridedSliceAttrs>();
attrs->slice_mode = slice_mode;
static const Op& op = Op::Get("dyn.strided_slice");
return Call(op, {data, begin, end, strides}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.strided_slice").set_body_typed(MakeStridedSlice);
RELAY_REGISTER_OP("dyn.strided_slice")
.describe(R"code(Strided slice of an array.
Examples::
x = [[ 1., 4., 7., 10.],
[ 2., 5., 8., 11.],
[ 3., 6., 9., 12.]]
strided_slice(x, begin=[0, 1], end=[2, 4], stride=[1, 1]) = [[ 4., 7., 10.],
[ 5., 8., 11.]]
x = [[[ 1., 2.],
[ 3., 4.]],
[[ 5., 6.],
[ 7., 8.]]]
strided_slice(x, begin=[0, 0], end=[2, 2]) = [[[ 1., 2.],
[ 3., 4.]],
[[ 5., 6.],
[ 7., 8.]]]
)code" TVM_ADD_FILELINE)
.set_num_inputs(4)
.add_argument("data", "Tensor", "The input tensor.")
.add_argument("begin", "Tensor", "The indices to begin with in the slicing.")
.add_argument("end", "Tensor", "Indices indicating end of the slice.")
.add_argument("strides", "Tensor", "The stride values.")
.add_argument("slice_mode", "Tensor", "The slice mode.")
.set_support_level(4)
.set_attrs_type<StridedSliceAttrs>()
.add_type_rel("DynStridedSlice", StridedSliceRel)
.set_attr<FTVMCompute>("FTVMCompute", StridedSliceCompute)
.set_attr<TOpPattern>("TOpPattern", kInjective)
.set_attr<AnyCodegenStrategy>("AnyCodegenStrategy", kVariableDimensions);
bool SparseToDenseRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
ICHECK_EQ(num_inputs, 4);
auto sparse_indices = types[0].as<TensorTypeNode>();
auto sparse_values = types[1].as<TensorTypeNode>();
auto default_value = types[2].as<TensorTypeNode>();
auto output_shape = types[3].as<TensorTypeNode>();
if (sparse_indices == nullptr || sparse_values == nullptr || default_value == nullptr ||
output_shape == nullptr) {
return false;
}
CHECK(sparse_indices->dtype.is_int()) << "sparse_indices must be tensor of integers";
CHECK_LE(sparse_indices->shape.size(), 3)
<< "sparse_indices must be a tensor of either 0D, 1D or 2D";
CHECK_LE(sparse_values->shape.size(), 2) << "sparse_values must be a tensor of either 0D, 1D";
CHECK_EQ(default_value->shape.size(), 0) << "default_value should be a scalar";
Array<IndexExpr> oshape;
for (int i = 0; i < output_shape->shape[0].as<IntImmNode>()->value; i++) {
oshape.push_back(Any());
}
reporter->Assign(types[4], TensorType(oshape, sparse_values->dtype));
return true;
}
Array<te::Tensor> SparseToDenseCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
ICHECK_EQ(inputs.size(), 4);
const auto* out_ttype = out_type.as<TensorTypeNode>();
ICHECK(out_ttype);
return {topi::sparse_to_dense(inputs[0], out_ttype->shape, inputs[1], inputs[2]())};
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.sparse_to_dense")
.set_body_typed([](Expr indices, Expr output_shape, Expr values, Expr default_value) {
static const Op& op = Op::Get("dyn.sparse_to_dense");
return Call(op, {indices, values, default_value, output_shape});
});
RELAY_REGISTER_OP("dyn.sparse_to_dense")
.describe(R"code(A dense tensor from a sparse representation.
- **sparse_indices**: A 0-D, 1-D, or 2-D tensor of integers containing location of sparse values
- **output_shape**: A list of integers. Shape of the dense output tensor.
- **sparse_values**: A 0-D or 1-D tensor containing the sparse values for the sparse indices.
- **default_value**: A 0-D tensor containing the default value for the remaining locations. Defaults to 0.
Example::
- sparse_to_dense([0, 0], [1, 2]], [3, 4], [1, 2], 0) = [[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]
)code" TVM_ADD_FILELINE)
.set_num_inputs(4)
.set_support_level(3)
.add_argument("sparse_indices", "Tensor", "Contains sparse indices.")
.add_argument("sparse_values", "Tensor", "Contains values for sparse indices.")
.add_argument("default_value", "Tensor", "Value to set for non-sparse indices. Defaults to 0.")
.add_argument("output_shape", "Tensor", "Shape of the dense output tensor")
.add_type_rel("DynSparseToDense", SparseToDenseRel)
.set_attr<TOpIsStateful>("TOpIsStateful", false)
.set_attr<TOpPattern>("TOpPattern", kOpaque)
.set_attr<FInferCorrectLayout>("FInferCorrectLayout", ElemwiseArbitraryLayout)
.set_attr<FTVMCompute>("FTVMCompute", SparseToDenseCompute);
/* relay.dyn.unsqueeze */
TVM_REGISTER_NODE_TYPE(DynExpandDimsAttrs);
bool ExpandDimsRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
ICHECK_EQ(num_inputs, 2);
const auto* data_type = types[0].as<TensorTypeNode>();
if (data_type == nullptr) {
ICHECK(types[0].as<IncompleteTypeNode>())
<< "expand_dims: expect input type to be TensorType but get " << types[0];
return false;
}
const auto* param = attrs.as<DynExpandDimsAttrs>();
// We don't know the output shape until we see the value of the axis input
int ndim = data_type->shape.size();
Array<IndexExpr> oshape(ndim + param->num_newaxis, Any());
const auto* axis_type = types[1].as<TensorTypeNode>();
ICHECK(axis_type->shape.size() == 0) << "Axis should be a scalar got shape " << axis_type->shape;
// Set output shape
reporter->Assign(types[2], TensorType(oshape, data_type->dtype));
return true;
}
Array<te::Tensor> ExpandDimsCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
// inputs = [Input tensor, axis to expand]
ICHECK_EQ(inputs.size(), 2);
const auto* param = attrs.as<DynExpandDimsAttrs>();
Array<IndexExpr> ishape = inputs[0]->shape;
const TensorTypeNode* out_ttype = out_type.as<TensorTypeNode>();
int ndim_out = out_ttype->shape.size();
int ndim_in = ishape.size();
ICHECK_EQ(ndim_in + param->num_newaxis, ndim_out);
Array<IndexExpr> newshape;
for (auto val : out_ttype->shape) {
// These vars will be populated by the VM executor with the results
// of the shape_func for the op.
newshape.push_back(val.as<tir::AnyNode>()->ToVar());
}
return {topi::reshape(inputs[0], newshape)};
}
Expr MakeExpandDims(Expr data, Expr axis_tensor, int num_newaxis) {
auto attrs = make_object<DynExpandDimsAttrs>();
attrs->num_newaxis = num_newaxis;
static const Op& op = Op::Get("dyn.expand_dims");
return Call(op, {data, axis_tensor}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.expand_dims").set_body_typed(MakeExpandDims);
RELAY_REGISTER_OP("dyn.expand_dims")
.describe(R"code(Insert one new axis at the position given by `axis`
- **data**: The input data to the operator.
- **axis**: The axis to insert a new dimension
)code" TVM_ADD_FILELINE)
.set_num_inputs(2)
.add_argument("data", "Tensor", "The input tensor.")
.add_argument("axis", "Tensor", "The axis to insert at a dimension.")
.set_support_level(3)
.add_type_rel("DynamicExpandDims", ExpandDimsRel)
.set_attr<FTVMCompute>("FTVMCompute", ExpandDimsCompute)
.set_attr<TOpPattern>("TOpPattern", kInjective);
bool DynSqueezeRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
// [data, axes, output]
ICHECK_EQ(types.size(), 3);
const auto* data = types[0].as<TensorTypeNode>();
if (data == nullptr) {
return false;
}
const auto* axes = types[1].as<TensorTypeNode>();
if (axes == nullptr) {
return false;
}
ICHECK_EQ(axes->shape.size(), 1) << "Got" << axes->shape.size() << "expected 1";
ICHECK(axes->shape[0].as<IntImmNode>()) << "axes expected to be static rank";
size_t output_rank = data->shape.size() - axes->shape[0].as<IntImmNode>()->value;
std::vector<IndexExpr> result_shape(output_rank, Any());
reporter->Assign(types[2], TensorType(result_shape, data->dtype));
return true;
}
Array<te::Tensor> SqueezeCompute(const Attrs& attrs, const Array<te::Tensor>& inputs,
const Type& out_type) {
const auto* out_ttype = out_type.as<TensorTypeNode>();
ICHECK(out_ttype != nullptr);
Array<IndexExpr> newshape;
for (auto val : out_ttype->shape) {
newshape.push_back(val.as<tir::AnyNode>()->ToVar());
}
return {topi::reshape(inputs[0], newshape)};
}
Expr MakeDynSqueeze(Expr data, Expr axes) {
auto attrs = make_object<SqueezeAttrs>();
static const Op& op = Op::Get("dyn.squeeze");
return Call(op, {data, axes}, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op.dyn._make.squeeze").set_body_typed(MakeDynSqueeze);
RELAY_REGISTER_OP("dyn.squeeze")
.describe(R"code(Remove axes of value 1 in input tensor at the dimensions given by axes
- **data**: The input data to the operator.
- **axes**: The axes to squeeze.
)code" TVM_ADD_FILELINE)
.set_num_inputs(2)
.set_attrs_type<SqueezeAttrs>()
.add_argument("data", "Tensor", "The input tensor.")
.add_argument("axes", "Tensor", "The axes to squeeze.")
.set_support_level(3)
.add_type_rel("DynSqueeze", DynSqueezeRel)
.set_attr<FTVMCompute>("FTVMCompute", SqueezeCompute)
.set_attr<TOpPattern>("TOpPattern", kInjective)
.set_attr<TReshapeOp>("TReshapeOp", true);
} // namespace dyn
} // namespace relay
} // namespace tvm
|
// 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.
#include "olap/tablet_meta_manager.h"
#include <fmt/format.h>
#include <boost/algorithm/string/trim.hpp>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include "common/logging.h"
#include "json2pb/json_to_pb.h"
#include "json2pb/pb_to_json.h"
#include "olap/olap_define.h"
#include "olap/olap_meta.h"
#include "olap/storage_engine.h"
using rocksdb::DB;
using rocksdb::DBOptions;
using rocksdb::ColumnFamilyDescriptor;
using rocksdb::ColumnFamilyHandle;
using rocksdb::ColumnFamilyOptions;
using rocksdb::ReadOptions;
using rocksdb::WriteOptions;
using rocksdb::Slice;
using rocksdb::Iterator;
using rocksdb::Status;
using rocksdb::kDefaultColumnFamilyName;
namespace doris {
// should use tablet->generate_tablet_meta_copy() method to get a copy of current tablet meta
// there are some rowset meta in local meta store and in in-memory tablet meta
// but not in tablet meta in local meta store
Status TabletMetaManager::get_meta(DataDir* store, TTabletId tablet_id, TSchemaHash schema_hash,
TabletMetaSharedPtr tablet_meta) {
OlapMeta* meta = store->get_meta();
std::stringstream key_stream;
key_stream << HEADER_PREFIX << tablet_id << "_" << schema_hash;
std::string key = key_stream.str();
std::string value;
Status s = meta->get(META_COLUMN_FAMILY_INDEX, key, &value);
if (s == Status::OLAPInternalError(OLAP_ERR_META_KEY_NOT_FOUND)) {
LOG(WARNING) << "tablet_id:" << tablet_id << ", schema_hash:" << schema_hash
<< " not found.";
return Status::OLAPInternalError(OLAP_ERR_META_KEY_NOT_FOUND);
} else if (!s.ok()) {
LOG(WARNING) << "load tablet_id:" << tablet_id << ", schema_hash:" << schema_hash
<< " failed.";
return s;
}
return tablet_meta->deserialize(value);
}
Status TabletMetaManager::get_json_meta(DataDir* store, TTabletId tablet_id,
TSchemaHash schema_hash, std::string* json_meta) {
TabletMetaSharedPtr tablet_meta(new TabletMeta());
Status s = get_meta(store, tablet_id, schema_hash, tablet_meta);
if (!s.ok()) {
return s;
}
json2pb::Pb2JsonOptions json_options;
json_options.pretty_json = true;
tablet_meta->to_json(json_meta, json_options);
return Status::OK();
}
// TODO(ygl):
// 1. if term > 0 then save to remote meta store first using term
// 2. save to local meta store
Status TabletMetaManager::save(DataDir* store, TTabletId tablet_id, TSchemaHash schema_hash,
TabletMetaSharedPtr tablet_meta, const string& header_prefix) {
std::string key = fmt::format("{}{}_{}", header_prefix, tablet_id, schema_hash);
std::string value;
tablet_meta->serialize(&value);
OlapMeta* meta = store->get_meta();
VLOG_NOTICE << "save tablet meta"
<< ", key:" << key << ", meta length:" << value.length();
return meta->put(META_COLUMN_FAMILY_INDEX, key, value);
}
Status TabletMetaManager::save(DataDir* store, TTabletId tablet_id, TSchemaHash schema_hash,
const std::string& meta_binary, const string& header_prefix) {
std::string key = fmt::format("{}{}_{}", header_prefix, tablet_id, schema_hash);
OlapMeta* meta = store->get_meta();
VLOG_NOTICE << "save tablet meta "
<< ", key:" << key << " meta_size=" << meta_binary.length();
return meta->put(META_COLUMN_FAMILY_INDEX, key, meta_binary);
}
// TODO(ygl):
// 1. remove load data first
// 2. remove from load meta store using term if term > 0
Status TabletMetaManager::remove(DataDir* store, TTabletId tablet_id, TSchemaHash schema_hash,
const string& header_prefix) {
std::string key = fmt::format("{}{}_{}", header_prefix, tablet_id, schema_hash);
OlapMeta* meta = store->get_meta();
Status res = meta->remove(META_COLUMN_FAMILY_INDEX, key);
VLOG_NOTICE << "remove tablet_meta, key:" << key << ", res:" << res;
return res;
}
Status TabletMetaManager::traverse_headers(
OlapMeta* meta, std::function<bool(long, long, const std::string&)> const& func,
const string& header_prefix) {
auto traverse_header_func = [&func](const std::string& key, const std::string& value) -> bool {
std::vector<std::string> parts;
// old format key format: "hdr_" + tablet_id + "_" + schema_hash 0.11
// new format key format: "tabletmeta_" + tablet_id + "_" + schema_hash 0.10
split_string<char>(key, '_', &parts);
if (parts.size() != 3) {
LOG(WARNING) << "invalid tablet_meta key:" << key << ", split size:" << parts.size();
return true;
}
TTabletId tablet_id = std::stol(parts[1].c_str(), nullptr, 10);
TSchemaHash schema_hash = std::stol(parts[2].c_str(), nullptr, 10);
return func(tablet_id, schema_hash, value);
};
Status status = meta->iterate(META_COLUMN_FAMILY_INDEX, header_prefix, traverse_header_func);
return status;
}
Status TabletMetaManager::load_json_meta(DataDir* store, const std::string& meta_path) {
std::ifstream infile(meta_path);
char buffer[102400];
std::string json_meta;
while (!infile.eof()) {
infile.getline(buffer, 102400);
json_meta = json_meta + buffer;
}
boost::algorithm::trim(json_meta);
TabletMetaPB tablet_meta_pb;
std::string error;
bool ret = json2pb::JsonToProtoMessage(json_meta, &tablet_meta_pb, &error);
if (!ret) {
LOG(ERROR) << "JSON to protobuf message failed: " << error;
return Status::OLAPInternalError(OLAP_ERR_HEADER_LOAD_JSON_HEADER);
}
std::string meta_binary;
tablet_meta_pb.SerializeToString(&meta_binary);
TTabletId tablet_id = tablet_meta_pb.tablet_id();
TSchemaHash schema_hash = tablet_meta_pb.schema_hash();
return save(store, tablet_id, schema_hash, meta_binary);
}
} // namespace doris
|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/common/enums/statement_type.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/common/constants.hpp"
namespace duckdb {
//===--------------------------------------------------------------------===//
// Statement Types
//===--------------------------------------------------------------------===//
enum class StatementType : uint8_t {
INVALID_STATEMENT, // invalid statement type
SELECT_STATEMENT, // select statement type
INSERT_STATEMENT, // insert statement type
UPDATE_STATEMENT, // update statement type
CREATE_STATEMENT, // create statement type
DELETE_STATEMENT, // delete statement type
PREPARE_STATEMENT, // prepare statement type
EXECUTE_STATEMENT, // execute statement type
ALTER_STATEMENT, // alter statement type
TRANSACTION_STATEMENT, // transaction statement type,
COPY_STATEMENT, // copy type
ANALYZE_STATEMENT, // analyze type
VARIABLE_SET_STATEMENT, // variable set statement type
CREATE_FUNC_STATEMENT, // create func statement type
EXPLAIN_STATEMENT, // explain statement type
DROP_STATEMENT, // DROP statement type
EXPORT_STATEMENT, // EXPORT statement type
PRAGMA_STATEMENT, // PRAGMA statement type
SHOW_STATEMENT, // SHOW statement type
VACUUM_STATEMENT, // VACUUM statement type
CALL_STATEMENT, // CALL statement type
SET_STATEMENT, // SET statement type
LOAD_STATEMENT, // LOAD statement type
RELATION_STATEMENT
};
string StatementTypeToString(StatementType type);
} // namespace duckdb
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "behavior_test_plugin_config.hpp"
#include "vpu_test_data.hpp"
INSTANTIATE_TEST_CASE_P(
smoke_BehaviorTest, BehaviorPluginCorrectConfigTest,
ValuesIn(
BehTestParams::concat(
BehTestParams::concat(deviceSpecificConfigurations, deviceAgnosticConfigurations),
withCorrectConfValuesPluginOnly
)
),
getTestCaseName
);
INSTANTIATE_TEST_CASE_P(smoke_BehaviorTest, BehaviorPluginIncorrectConfigTest, ValuesIn(withIncorrectConfValues),
getTestCaseName);
INSTANTIATE_TEST_CASE_P(smoke_BehaviorTest, BehaviorPluginIncorrectConfigTestInferRequestAPI,
ValuesIn(withIncorrectConfKeys),
getTestCaseName);
INSTANTIATE_TEST_CASE_P(smoke_BehaviorTest, BehaviorPluginCorrectConfigTestInferRequestAPI,
ValuesIn(supportedValues),
getTestCaseName);
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cast_certificate/cast_cert_validator.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <utility>
#include "base/memory/singleton.h"
#include "base/stl_util.h"
#include "components/cast_certificate/cast_crl.h"
#include "net/cert/internal/cert_issuer_source_static.h"
#include "net/cert/internal/certificate_policies.h"
#include "net/cert/internal/common_cert_errors.h"
#include "net/cert/internal/extended_key_usage.h"
#include "net/cert/internal/parse_certificate.h"
#include "net/cert/internal/parse_name.h"
#include "net/cert/internal/parsed_certificate.h"
#include "net/cert/internal/path_builder.h"
#include "net/cert/internal/signature_algorithm.h"
#include "net/cert/internal/simple_path_builder_delegate.h"
#include "net/cert/internal/trust_store_in_memory.h"
#include "net/cert/internal/verify_signed_data.h"
#include "net/cert/x509_util.h"
#include "net/der/encode_values.h"
#include "net/der/input.h"
namespace cast_certificate {
namespace {
#define RETURN_STRING_LITERAL(x) \
case x: \
return #x;
// -------------------------------------------------------------------------
// Cast trust anchors.
// -------------------------------------------------------------------------
// There are two trusted roots for Cast certificate chains:
//
// (1) CN=Cast Root CA (kCastRootCaDer)
// (2) CN=Eureka Root CA (kEurekaRootCaDer)
//
// These constants are defined by the files included next:
#include "components/cast_certificate/cast_root_ca_cert_der-inc.h"
#include "components/cast_certificate/eureka_root_ca_der-inc.h"
// Singleton for the Cast trust store.
class CastTrustStore {
public:
static CastTrustStore* GetInstance() {
return base::Singleton<CastTrustStore,
base::LeakySingletonTraits<CastTrustStore>>::get();
}
static net::TrustStore& Get() { return GetInstance()->store_; }
private:
friend struct base::DefaultSingletonTraits<CastTrustStore>;
CastTrustStore() {
AddAnchor(kCastRootCaDer);
AddAnchor(kEurekaRootCaDer);
}
// Adds a trust anchor given a DER-encoded certificate from static
// storage.
template <size_t N>
void AddAnchor(const uint8_t (&data)[N]) {
net::CertErrors errors;
scoped_refptr<net::ParsedCertificate> cert =
net::ParsedCertificate::CreateWithoutCopyingUnsafe(data, N, {},
&errors);
CHECK(cert) << errors.ToDebugString();
// Enforce pathlen constraints and policies defined on the root certificate.
store_.AddTrustAnchorWithConstraints(std::move(cert));
}
net::TrustStoreInMemory store_;
DISALLOW_COPY_AND_ASSIGN(CastTrustStore);
};
// Returns the OID for the Audio-Only Cast policy
// (1.3.6.1.4.1.11129.2.5.2) in DER form.
net::der::Input AudioOnlyPolicyOid() {
static const uint8_t kAudioOnlyPolicy[] = {0x2B, 0x06, 0x01, 0x04, 0x01,
0xD6, 0x79, 0x02, 0x05, 0x02};
return net::der::Input(kAudioOnlyPolicy);
}
// Cast certificates rely on RSASSA-PKCS#1 v1.5 with SHA-1 for signatures.
//
// The following delegate will allow signature algorithms of:
//
// * ECDSA, RSA-SSA, and RSA-PSS
// * Supported EC curves: P-256, P-384, P-521.
// * Hashes: All SHA hashes including SHA-1 (despite being known weak).
//
// It will also require RSA keys have a modulus at least 2048-bits long.
class CastPathBuilderDelegate : public net::SimplePathBuilderDelegate {
public:
CastPathBuilderDelegate() : SimplePathBuilderDelegate(2048) {}
};
class CertVerificationContextImpl : public CertVerificationContext {
public:
// Save a copy of the passed in public key (DER) and common name (text).
CertVerificationContextImpl(const net::der::Input& spki,
const base::StringPiece& common_name)
: spki_(spki.AsString()), common_name_(common_name.as_string()) {}
bool VerifySignatureOverData(
const base::StringPiece& signature,
const base::StringPiece& data,
net::DigestAlgorithm digest_algorithm) const override {
// This code assumes the signature algorithm was RSASSA PKCS#1 v1.5 with
// |digest_algorithm|.
auto signature_algorithm =
net::SignatureAlgorithm::CreateRsaPkcs1(digest_algorithm);
return net::VerifySignedData(
*signature_algorithm, net::der::Input(data),
net::der::BitString(net::der::Input(signature), 0),
net::der::Input(&spki_));
}
std::string GetCommonName() const override { return common_name_; }
private:
std::string spki_;
std::string common_name_;
};
// Helper that extracts the Common Name from a certificate's subject field. On
// success |common_name| contains the text for the attribute (UTF-8, but for
// Cast device certs it should be ASCII).
bool GetCommonNameFromSubject(const net::der::Input& subject_tlv,
std::string* common_name) {
net::RDNSequence rdn_sequence;
if (!net::ParseName(subject_tlv, &rdn_sequence))
return false;
for (const net::RelativeDistinguishedName& rdn : rdn_sequence) {
for (const auto& atv : rdn) {
if (atv.type == net::TypeCommonNameOid()) {
return atv.ValueAsString(common_name);
}
}
}
return false;
}
// Cast device certificates use the policy 1.3.6.1.4.1.11129.2.5.2 to indicate
// it is *restricted* to an audio-only device whereas the absence of a policy
// means it is unrestricted.
//
// This is somewhat different than RFC 5280's notion of policies, so policies
// are checked separately outside of path building.
//
// See the unit-tests VerifyCastDeviceCertTest.Policies* for some
// concrete examples of how this works.
void DetermineDeviceCertificatePolicy(
const net::CertPathBuilderResultPath* result_path,
CastDeviceCertPolicy* policy) {
// Iterate over all the certificates, including the root certificate. If any
// certificate contains the audio-only policy, the whole chain is considered
// constrained to audio-only device certificates.
//
// Policy mappings are not accounted for. The expectation is that top-level
// intermediates issued with audio-only will have no mappings. If subsequent
// certificates in the chain do, it won't matter as the chain is already
// restricted to being audio-only.
bool audio_only = false;
for (const auto& cert : result_path->certs) {
if (cert->has_policy_oids()) {
const std::vector<net::der::Input>& policies = cert->policy_oids();
if (base::ContainsValue(policies, AudioOnlyPolicyOid())) {
audio_only = true;
break;
}
}
}
*policy = audio_only ? CastDeviceCertPolicy::AUDIO_ONLY
: CastDeviceCertPolicy::NONE;
}
// Checks properties on the target certificate.
//
// * The Key Usage must include Digital Signature
WARN_UNUSED_RESULT bool CheckTargetCertificate(
const net::ParsedCertificate* cert,
std::unique_ptr<CertVerificationContext>* context) {
// Get the Key Usage extension.
if (!cert->has_key_usage())
return false;
// Ensure Key Usage contains digitalSignature.
if (!cert->key_usage().AssertsBit(net::KEY_USAGE_BIT_DIGITAL_SIGNATURE))
return false;
// Get the Common Name for the certificate.
std::string common_name;
if (!GetCommonNameFromSubject(cert->tbs().subject_tlv, &common_name))
return false;
context->reset(
new CertVerificationContextImpl(cert->tbs().spki_tlv, common_name));
return true;
}
// Returns the parsing options used for Cast certificates.
net::ParseCertificateOptions GetCertParsingOptions() {
net::ParseCertificateOptions options;
// Some cast intermediate certificates contain serial numbers that are
// 21 octets long, and might also not use valid DER encoding for an
// INTEGER (non-minimal encoding).
//
// Allow these sorts of serial numbers.
//
// TODO(eroman): At some point in the future this workaround will no longer be
// necessary. Should revisit this for removal in 2017 if not earlier.
options.allow_invalid_serial_numbers = true;
return options;
}
// Returns the CastCertError for the failed path building.
// This function must only be called if path building failed.
CastCertError MapToCastError(const net::CertPathBuilder::Result& result) {
DCHECK(!result.HasValidPath());
if (result.paths.empty())
return CastCertError::ERR_CERTS_VERIFY_GENERIC;
const net::CertPathErrors& path_errors =
result.paths.at(result.best_result_index)->errors;
if (path_errors.ContainsError(net::cert_errors::kValidityFailedNotAfter) ||
path_errors.ContainsError(net::cert_errors::kValidityFailedNotBefore)) {
return CastCertError::ERR_CERTS_DATE_INVALID;
}
return CastCertError::ERR_CERTS_VERIFY_GENERIC;
}
} // namespace
CastCertError VerifyDeviceCert(
const std::vector<std::string>& certs,
const base::Time& time,
std::unique_ptr<CertVerificationContext>* context,
CastDeviceCertPolicy* policy,
const CastCRL* crl,
CRLPolicy crl_policy) {
return VerifyDeviceCertUsingCustomTrustStore(
certs, time, context, policy, crl, crl_policy, &CastTrustStore::Get());
}
CastCertError VerifyDeviceCertUsingCustomTrustStore(
const std::vector<std::string>& certs,
const base::Time& time,
std::unique_ptr<CertVerificationContext>* context,
CastDeviceCertPolicy* policy,
const CastCRL* crl,
CRLPolicy crl_policy,
net::TrustStore* trust_store) {
if (!trust_store)
return VerifyDeviceCert(certs, time, context, policy, crl, crl_policy);
if (certs.empty())
return CastCertError::ERR_CERTS_MISSING;
// Fail early if CRL is required but not provided.
if (!crl && crl_policy == CRLPolicy::CRL_REQUIRED)
return CastCertError::ERR_CRL_INVALID;
net::CertErrors errors;
scoped_refptr<net::ParsedCertificate> target_cert;
net::CertIssuerSourceStatic intermediate_cert_issuer_source;
for (size_t i = 0; i < certs.size(); ++i) {
scoped_refptr<net::ParsedCertificate> cert(net::ParsedCertificate::Create(
net::x509_util::CreateCryptoBuffer(certs[i]), GetCertParsingOptions(),
&errors));
if (!cert)
return CastCertError::ERR_CERTS_PARSE;
if (i == 0)
target_cert = std::move(cert);
else
intermediate_cert_issuer_source.AddCert(std::move(cert));
}
CastPathBuilderDelegate path_builder_delegate;
// Do path building and RFC 5280 compatible certificate verification using the
// two Cast trust anchors and Cast signature policy.
net::der::GeneralizedTime verification_time;
if (!net::der::EncodeTimeAsGeneralizedTime(time, &verification_time))
return CastCertError::ERR_UNEXPECTED;
net::CertPathBuilder::Result result;
net::CertPathBuilder path_builder(
target_cert.get(), trust_store, &path_builder_delegate, verification_time,
net::KeyPurpose::CLIENT_AUTH, net::InitialExplicitPolicy::kFalse,
{net::AnyPolicy()}, net::InitialPolicyMappingInhibit::kFalse,
net::InitialAnyPolicyInhibit::kFalse, &result);
path_builder.AddCertIssuerSource(&intermediate_cert_issuer_source);
path_builder.Run();
if (!result.HasValidPath())
return MapToCastError(result);
// Determine whether this device certificate is restricted to audio-only.
DetermineDeviceCertificatePolicy(result.GetBestValidPath(), policy);
// Check properties of the leaf certificate not already verified by path
// building (key usage), and construct a CertVerificationContext that uses
// its public key.
if (!CheckTargetCertificate(target_cert.get(), context))
return CastCertError::ERR_CERTS_RESTRICTIONS;
// Check for revocation.
if (crl && !crl->CheckRevocation(result.GetBestValidPath()->certs, time))
return CastCertError::ERR_CERTS_REVOKED;
return CastCertError::OK;
}
std::unique_ptr<CertVerificationContext> CertVerificationContextImplForTest(
const base::StringPiece& spki) {
// Use a bogus CommonName, since this is just exposed for testing signature
// verification by unittests.
return std::make_unique<CertVerificationContextImpl>(net::der::Input(spki),
"CommonName");
}
std::string CastCertErrorToString(CastCertError error) {
switch (error) {
RETURN_STRING_LITERAL(CastCertError::ERR_CERTS_MISSING);
RETURN_STRING_LITERAL(CastCertError::ERR_CERTS_PARSE);
RETURN_STRING_LITERAL(CastCertError::ERR_CERTS_DATE_INVALID);
RETURN_STRING_LITERAL(CastCertError::ERR_CERTS_VERIFY_GENERIC);
RETURN_STRING_LITERAL(CastCertError::ERR_CERTS_RESTRICTIONS);
RETURN_STRING_LITERAL(CastCertError::ERR_CRL_INVALID);
RETURN_STRING_LITERAL(CastCertError::ERR_CERTS_REVOKED);
RETURN_STRING_LITERAL(CastCertError::ERR_UNEXPECTED);
RETURN_STRING_LITERAL(CastCertError::OK);
}
return "CastCertError::UNKNOWN";
}
} // namespace cast_certificate
|
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/inference/lite/tensor_utils.h"
#include <functional>
#include <map>
#include <memory>
#include "paddle/fluid/framework/convert_utils.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/inference/lite/engine.h"
#include "paddle/fluid/memory/allocation/allocator.h"
namespace paddle {
namespace inference {
namespace lite {
namespace utils {
using paddle::lite_api::DataLayoutType;
using paddle::lite_api::PrecisionType;
using paddle::lite_api::TargetType;
template <typename DstLoD, typename SrcLoD>
void SetLoD(DstLoD* dst, const SrcLoD& src) {
dst->reserve(src.size());
dst->clear();
for (auto&& v : src) {
dst->emplace_back(v);
}
}
template void SetLoD<framework::LoD, paddle::lite::LoD>(
framework::LoD* dst, const paddle::lite::LoD& src);
platform::Place GetNativePlace(const TargetType& type, int id = 0) {
switch (type) {
case TargetType::kHost:
case TargetType::kX86:
case TargetType::kARM:
return platform::CPUPlace();
case TargetType::kCUDA:
return platform::CUDAPlace(id);
case TargetType::kXPU:
LOG(ERROR) << "No corresponding device for XPU yet.";
return platform::Place();
default:
PADDLE_THROW(
platform::errors::Unavailable("Unsupported target type. Now only "
"supports Host, x86, CUDA target."));
return platform::Place();
}
}
TargetType GetLiteTargetType(const platform::Place& place) {
if (platform::is_cpu_place(place)) {
return TargetType::kHost;
}
return TargetType::kCUDA;
}
PrecisionType GetLitePrecisionType(framework::proto::VarType::Type type) {
switch (type) {
case framework::proto::VarType_Type_FP32:
return PrecisionType::kFloat;
case framework::proto::VarType_Type_INT8:
return PrecisionType::kInt8;
case framework::proto::VarType_Type_INT32:
return PrecisionType::kInt32;
case framework::proto::VarType_Type_INT64:
return PrecisionType::kInt64;
default:
PADDLE_THROW(platform::errors::Unimplemented(
"Unsupported precision type. Now only supports FP32, INT8, INT32 and "
"INT64."));
return PrecisionType::kUnk;
}
}
framework::proto::VarType::Type GetNativePrecisionType(
const PrecisionType& type) {
switch (type) {
case PrecisionType::kFloat:
return framework::proto::VarType_Type_FP32;
case PrecisionType::kInt8:
return framework::proto::VarType_Type_INT8;
case PrecisionType::kInt32:
return framework::proto::VarType_Type_INT32;
case PrecisionType::kInt64:
return framework::proto::VarType_Type_INT64;
default:
PADDLE_THROW(platform::errors::Unimplemented(
"Unsupported precision type. Now only supports FP32, INT8, INT32 and "
"INT64."));
return static_cast<framework::proto::VarType::Type>(-1);
}
}
framework::DataLayout GetNativeLayoutType(const DataLayoutType& type) {
switch (type) {
case DataLayoutType::kNCHW:
return framework::DataLayout::kNCHW;
default:
PADDLE_THROW(platform::errors::Unimplemented(
"Unsupported layout type. Now only supports NCHW."));
return static_cast<framework::DataLayout>(-1);
}
}
void MemoryCopyAsync(const platform::Place& dst_place, void* dst_data,
const platform::Place& src_place, const void* src_data,
const size_t size, const platform::DeviceContext& ctx) {
const platform::CPUPlace cpu_place;
if (platform::is_cpu_place(dst_place) && platform::is_cpu_place(src_place)) {
memory::Copy(cpu_place, dst_data, cpu_place, src_data, size);
} else {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
if (platform::is_cpu_place(dst_place) &&
platform::is_gpu_place(src_place)) {
PADDLE_THROW(platform::errors::Unimplemented(
"Lite::MemoryCopy GPU->CPU is not yet implemented."));
} else if (platform::is_gpu_place(dst_place) &&
platform::is_cpu_place(src_place)) {
PADDLE_THROW(platform::errors::Unimplemented(
"Lite::MemoryCopy CPU->GPU is not yet implemented."));
} else if (platform::is_gpu_place(dst_place) &&
platform::is_gpu_place(src_place)) {
auto gpu_place = src_place;
memory::Copy(
gpu_place, dst_data, gpu_place, src_data, size,
static_cast<const platform::CUDADeviceContext&>(ctx).stream());
}
#else
PADDLE_THROW(platform::errors::PreconditionNotMet(
"You must define PADDLE_WITH_CUDA for using CUDAPlace."));
#endif
}
}
void* GetLiteTensorDataPtr(paddle::lite_api::Tensor* src,
PrecisionType precision_type,
TargetType target_type) {
void* res{nullptr};
switch (precision_type) {
case PrecisionType::kFloat:
res = static_cast<void*>(src->mutable_data<float>(target_type));
break;
case PrecisionType::kInt8:
res = static_cast<void*>(src->mutable_data<int8_t>(target_type));
break;
case PrecisionType::kInt32:
res = static_cast<void*>(src->mutable_data<int32_t>(target_type));
break;
case PrecisionType::kInt64:
res = static_cast<void*>(src->mutable_data<int64_t>(target_type));
break;
default:
PADDLE_THROW(platform::errors::Unimplemented(
"Unsupported precision type. Now only supports FP32, INT8, INT32 and "
"INT64."));
break;
}
return res;
}
int64_t GetLiteTensorNumel(const paddle::lite_api::Tensor& tensor) {
auto shape = tensor.shape();
int64_t numel = std::accumulate(shape.begin(), shape.end(), 1,
std::multiplies<int64_t>());
return numel;
}
void InitDstTensor(paddle::lite_api::Tensor* dst,
const framework::LoDTensor& src) {
// Currently, Lite needs to explicitly specify the target type of
// the input tensor.
constexpr int empty_size = 0;
dst->Resize({empty_size});
GetLiteTensorDataPtr(
dst, GetLitePrecisionType(framework::TransToProtoVarType(src.dtype())),
GetLiteTargetType(src.place()));
dst->SetPrecision(
GetLitePrecisionType(framework::TransToProtoVarType(src.dtype())));
paddle::lite::LoD lite_lod;
SetLoD(&lite_lod, src.lod());
dst->SetLoD(lite_lod);
}
void InitDstTensor(framework::LoDTensor* dst,
const paddle::lite_api::Tensor& src) {
dst->mutable_data(
inference::lite::utils::GetNativePlace(src.target()),
framework::TransToPhiDataType(GetNativePrecisionType(src.precision())));
SetLoD(dst->mutable_lod(), src.lod());
}
template <>
void TensorCopyAsync(paddle::lite_api::Tensor* dst,
const framework::LoDTensor& src,
const platform::DeviceContext& ctx) {
InitDstTensor(dst, src);
const platform::Place& src_place = src.place();
const platform::Place& dst_place = GetNativePlace(dst->target());
const size_t bytes =
static_cast<size_t>(src.numel()) * framework::DataTypeSize(src.dtype());
dst->Resize(phi::vectorize(src.dims()));
const void* src_data = src.data();
void* dst_data{nullptr};
dst_data = GetLiteTensorDataPtr(
dst, GetLitePrecisionType(framework::TransToProtoVarType(src.dtype())),
GetLiteTargetType(src.place()));
VLOG(3) << "[CopyAsync fluid -> lite] Bytes = " << bytes << ", src = " << &src
<< ", dst = " << dst
<< ", src_type = " << framework::TransToProtoVarType(src.dtype());
MemoryCopyAsync(dst_place, dst_data, src_place, src_data, bytes, ctx);
VLOG(3) << "[Lite memory size] Bytes = " << bytes;
}
template <>
void TensorCopyAsync(framework::LoDTensor* dst,
const paddle::lite_api::Tensor& src,
const platform::DeviceContext& ctx) {
dst->Resize(phi::make_ddim(src.shape()));
InitDstTensor(dst, src);
const platform::Place& src_place = GetNativePlace(src.target());
const platform::Place& dst_place = dst->place();
int64_t src_numel = GetLiteTensorNumel(src);
const size_t bytes = src_numel * framework::DataTypeSize(dst->dtype());
const void* src_data = src.data<void>();
// When Lite is ready, the source type needs to be modified here.
void* dst_data = dst->mutable_data(dst_place, dst->dtype());
VLOG(3) << "[CopyAsync lite -> fluid] Bytes = " << bytes << ", src = " << &src
<< ", dst = " << dst
<< ", src_type = " << framework::TransToProtoVarType(dst->dtype());
MemoryCopyAsync(dst_place, dst_data, src_place, src_data, bytes, ctx);
VLOG(3) << "[Lite memory size] Bytes = " << bytes;
}
template <>
void TensorDataShare(paddle::lite_api::Tensor* dst, framework::LoDTensor* src) {
dst->Resize(phi::vectorize(src->dims()));
dst->ShareExternalMemory(src->data(), src->memory_size(),
GetLiteTargetType(src->place()));
dst->SetPrecision(
GetLitePrecisionType(framework::TransToProtoVarType(src->dtype())));
paddle::lite::LoD lite_lod;
SetLoD(&lite_lod, src->lod());
dst->SetLoD(lite_lod);
}
template <>
void TensorDataShare(framework::LoDTensor* dst, paddle::lite_api::Tensor* src) {
void* src_raw_data =
GetLiteTensorDataPtr(src, src->precision(), src->target());
size_t memory_size =
GetLiteTensorNumel(*src) *
framework::SizeOfType(GetNativePrecisionType(src->precision()));
std::shared_ptr<phi::Allocation> holder(new phi::Allocation(
src_raw_data, memory_size, GetNativePlace(src->target())));
dst->Resize(phi::make_ddim(src->shape()));
SetLoD(dst->mutable_lod(), src->lod());
dst->ResetHolderWithType(
holder,
framework::TransToPhiDataType(GetNativePrecisionType(src->precision())));
}
} // namespace utils
} // namespace lite
} // namespace inference
} // namespace paddle
|
// Copyright John Maddock 2008.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <pch.hpp>
#ifndef BOOST_MATH_TR1_SOURCE
#define BOOST_MATH_TR1_SOURCE
#endif
#include "c_policy.hpp"
#include <boost/math/special_functions/legendre.hpp>
#include <boost/math/tr1.hpp>
extern "C" double BOOST_MATH_TR1_DECL boost_assoc_legendre
BOOST_PREVENT_MACRO_SUBSTITUTION(unsigned l, unsigned m,
double x) BOOST_MATH_C99_THROW_SPEC
{
return (m & 1 ? -1 : 1) *
c_policies::legendre_p BOOST_PREVENT_MACRO_SUBSTITUTION(l, m, x);
}
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shill/external_task.h"
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <base/bind.h>
#include <base/files/file_path.h>
#include <base/memory/weak_ptr.h>
#include <base/strings/string_util.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "shill/mock_adaptors.h"
#include "shill/mock_control.h"
#include "shill/mock_process_manager.h"
#include "shill/test_event_dispatcher.h"
using testing::_;
using testing::Mock;
using testing::Return;
namespace shill {
class ExternalTaskTest : public testing::Test, public RpcTaskDelegate {
public:
ExternalTaskTest()
: weak_ptr_factory_(this),
death_callback_(base::Bind(&ExternalTaskTest::TaskDiedCallback,
weak_ptr_factory_.GetWeakPtr())),
external_task_(new ExternalTask(&control_,
&process_manager_,
weak_ptr_factory_.GetWeakPtr(),
death_callback_)),
test_rpc_task_destroyed_(false) {}
~ExternalTaskTest() override = default;
void TearDown() override {
if (!external_task_) {
return;
}
if (external_task_->pid_) {
EXPECT_CALL(process_manager_, StopProcess(external_task_->pid_));
}
}
void set_test_rpc_task_destroyed(bool destroyed) {
test_rpc_task_destroyed_ = destroyed;
}
// Defined out-of-line, due to dependency on TestRpcTask.
void FakeUpRunningProcess(unsigned int tag, int pid);
void ExpectStop(unsigned int tag, int pid) {
EXPECT_CALL(process_manager_, StopProcess(pid));
}
void VerifyStop() {
if (external_task_) {
EXPECT_EQ(0, external_task_->pid_);
EXPECT_FALSE(external_task_->rpc_task_);
}
EXPECT_TRUE(test_rpc_task_destroyed_);
// Make sure EXPECTations were met before the fixture's dtor.
Mock::VerifyAndClearExpectations(&process_manager_);
}
protected:
// Implements RpcTaskDelegate interface.
MOCK_METHOD(void, GetLogin, (std::string*, std::string*), (override));
MOCK_METHOD(void,
Notify,
(const std::string&, (const std::map<std::string, std::string>&)),
(override));
MOCK_METHOD(void, TaskDiedCallback, (pid_t, int));
MockControl control_;
EventDispatcherForTest dispatcher_;
MockProcessManager process_manager_;
base::WeakPtrFactory<ExternalTaskTest> weak_ptr_factory_;
base::Callback<void(pid_t, int)> death_callback_;
std::unique_ptr<ExternalTask> external_task_;
bool test_rpc_task_destroyed_;
};
namespace {
class TestRpcTask : public RpcTask {
public:
TestRpcTask(ControlInterface* control, ExternalTaskTest* test);
virtual ~TestRpcTask();
private:
ExternalTaskTest* test_;
};
TestRpcTask::TestRpcTask(ControlInterface* control, ExternalTaskTest* test)
: RpcTask(control, test), test_(test) {
test_->set_test_rpc_task_destroyed(false);
}
TestRpcTask::~TestRpcTask() {
test_->set_test_rpc_task_destroyed(true);
test_ = nullptr;
}
} // namespace
void ExternalTaskTest::FakeUpRunningProcess(unsigned int tag, int pid) {
external_task_->pid_ = pid;
external_task_->rpc_task_.reset(new TestRpcTask(&control_, this));
}
TEST_F(ExternalTaskTest, Destructor) {
const unsigned int kTag = 123;
const int kPID = 123456;
FakeUpRunningProcess(kTag, kPID);
ExpectStop(kTag, kPID);
external_task_.reset();
VerifyStop();
}
TEST_F(ExternalTaskTest, Start) {
const std::string kCommand = "/run/me";
const std::vector<std::string> kCommandOptions{"arg1", "arg2"};
const std::map<std::string, std::string> kCommandEnv{{"env1", "val1"},
{"env2", "val2"}};
std::map<std::string, std::string> expected_env;
expected_env.emplace(kRpcTaskServiceVariable,
RpcTaskMockAdaptor::kRpcConnId.value());
expected_env.emplace(kRpcTaskPathVariable,
RpcTaskMockAdaptor::kRpcId.value());
expected_env.insert(kCommandEnv.begin(), kCommandEnv.end());
const int kPID = 234678;
EXPECT_CALL(process_manager_,
StartProcess(_, base::FilePath(kCommand), kCommandOptions,
expected_env, false, _))
.WillOnce(Return(-1))
.WillOnce(Return(kPID));
Error error;
EXPECT_FALSE(external_task_->Start(base::FilePath(kCommand), kCommandOptions,
kCommandEnv, false, &error));
EXPECT_EQ(Error::kInternalError, error.type());
EXPECT_FALSE(external_task_->rpc_task_);
error.Reset();
EXPECT_TRUE(external_task_->Start(base::FilePath(kCommand), kCommandOptions,
kCommandEnv, false, &error));
EXPECT_TRUE(error.IsSuccess());
EXPECT_EQ(kPID, external_task_->pid_);
EXPECT_NE(nullptr, external_task_->rpc_task_);
}
TEST_F(ExternalTaskTest, Stop) {
const unsigned int kTag = 123;
const int kPID = 123456;
FakeUpRunningProcess(kTag, kPID);
ExpectStop(kTag, kPID);
external_task_->Stop();
ASSERT_NE(nullptr, external_task_);
VerifyStop();
}
TEST_F(ExternalTaskTest, StopNotStarted) {
EXPECT_CALL(process_manager_, StopProcess(_)).Times(0);
external_task_->Stop();
EXPECT_FALSE(test_rpc_task_destroyed_);
}
TEST_F(ExternalTaskTest, GetLogin) {
std::string username;
std::string password;
EXPECT_CALL(*this, GetLogin(&username, &password));
EXPECT_CALL(*this, Notify(_, _)).Times(0);
external_task_->GetLogin(&username, &password);
}
TEST_F(ExternalTaskTest, Notify) {
const std::string kReason("you may already have won!");
const std::map<std::string, std::string>& kArgs{{"arg1", "val1"},
{"arg2", "val2"}};
EXPECT_CALL(*this, GetLogin(_, _)).Times(0);
EXPECT_CALL(*this, Notify(kReason, kArgs));
external_task_->Notify(kReason, kArgs);
}
TEST_F(ExternalTaskTest, OnTaskDied) {
const int kPID = 99999;
const int kExitStatus = 1;
external_task_->pid_ = kPID;
EXPECT_CALL(process_manager_, StopProcess(_)).Times(0);
EXPECT_CALL(*this, TaskDiedCallback(kPID, kExitStatus));
external_task_->OnTaskDied(kExitStatus);
EXPECT_EQ(0, external_task_->pid_);
}
} // namespace shill
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include <locale.h>
#include <string.h>
#include <tchar.h>
#include <fcntl.h>
#include <io.h>
#include <unicode/locid.h>
#endif
#include "ConsoleFeature.h"
#include "ApplicationFeatures/ShellColorsFeature.h"
#include "Basics/ScopeGuard.h"
#include "Basics/StringUtils.h"
#include "Basics/messages.h"
#include "Basics/operating-system.h"
#include "Basics/system-functions.h"
#include "Basics/terminal-utils.h"
#include "FeaturePhases/BasicFeaturePhaseClient.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "Shell/ClientFeature.h"
#if _WIN32
#include "Basics/win-utils.h"
#endif
#ifdef TRI_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <iomanip>
#include <iostream>
using namespace arangodb::basics;
using namespace arangodb::options;
#ifdef _WIN32
static const int FOREGROUND_WHITE = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
static const int BACKGROUND_WHITE = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE;
static const int INTENSITY = FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
#endif
namespace arangodb {
ConsoleFeature::ConsoleFeature(application_features::ApplicationServer& server)
: ApplicationFeature(server, "Console"),
#ifdef _WIN32
_cygwinShell(false),
#endif
_quiet(false),
_colors(true),
_useHistory(true),
_autoComplete(true),
_prettyPrint(true),
_auditFile(),
_pager(false),
_pagerCommand("less -X -R -F -L"),
_prompt("%E@%d> "),
_promptError(false),
_supportsColors(isatty(STDIN_FILENO) != 0),
_toPager(stdout),
_toAuditFile(nullptr),
_lastDuration(0.0),
_startTime(TRI_microtime()) {
setOptional(false);
requiresElevatedPrivileges(false);
startsAfter<application_features::BasicFeaturePhaseClient>();
if (!_supportsColors) {
_colors = false;
}
#if _WIN32
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
_defaultAttribute = info.wAttributes & INTENSITY;
_defaultColor = info.wAttributes & FOREGROUND_WHITE;
_defaultBackground = info.wAttributes & BACKGROUND_WHITE;
_consoleAttribute = _defaultAttribute;
_consoleColor = _defaultColor | _defaultBackground;
#endif
}
void ConsoleFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addOption("--quiet", "silent startup", new BooleanParameter(&_quiet));
options->addSection("console", "Configure the console");
options->addOption("--console.colors", "enable color support",
new BooleanParameter(&_colors),
arangodb::options::makeDefaultFlags(arangodb::options::Flags::Dynamic));
options->addOption("--console.auto-complete", "enable auto completion",
new BooleanParameter(&_autoComplete));
options->addOption("--console.pretty-print", "enable pretty printing",
new BooleanParameter(&_prettyPrint));
options->addOption("--console.audit-file",
"audit log file to save commands and results",
new StringParameter(&_auditFile));
options->addOption("--console.history",
"whether or not to load and persist command-line history",
new BooleanParameter(&_useHistory))
.setIntroducedIn(30405);
options->addOption("--console.pager", "enable paging", new BooleanParameter(&_pager));
options->addOption("--console.pager-command", "pager command",
new StringParameter(&_pagerCommand),
arangodb::options::makeDefaultFlags(arangodb::options::Flags::Hidden));
options->addOption(
"--console.prompt",
"prompt used in REPL. prompt components are: '%t': current time as "
"timestamp, '%p': duration of last command in seconds, '%d': name of "
"current database, '%e': current endpoint, '%E': current endpoint "
"without protocol, '%u': current user",
new StringParameter(&_prompt));
}
void ConsoleFeature::prepare() {
#if _WIN32
if (_is_cyg_tty(STDOUT_FILENO) || getenv("SHELL") != nullptr) {
_cygwinShell = true;
}
#endif
}
void ConsoleFeature::start() { openLog(); }
void ConsoleFeature::unprepare() { closeLog(); }
#ifdef _WIN32
static void _newLine() { fprintf(stdout, "\n"); }
void ConsoleFeature::_print2(std::string const& s) {
size_t sLen = s.size();
if (sLen == 0) {
return;
}
LPWSTR wBuf = new WCHAR[sLen + 1];
int wLen = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)sLen, wBuf,
(int)((sizeof(WCHAR)) * (sLen + 1)));
if (wLen) {
auto handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, _consoleAttribute | _consoleColor);
DWORD n;
WriteConsoleW(handle, wBuf, (DWORD)wLen, &n, NULL);
} else {
fprintf(stdout, "window error: '%d' \r\n", GetLastError());
fprintf(stdout, "%s\r\n", s.c_str());
}
if (wBuf) {
delete[] wBuf;
}
}
void ConsoleFeature::_print(std::string const& s) {
auto pos = s.find_first_of("\x1b");
if (pos == std::string::npos) {
_print2(s);
} else {
std::vector<std::string> lines = StringUtils::split(s, '\x1b');
int i = 0;
for (auto line : lines) {
size_t pos = 0;
if (i++ != 0 && !line.empty()) {
char c = line[0];
if (c == '[') {
int code = 0;
for (++pos; pos < line.size(); ++pos) {
c = line[pos];
if ('0' <= c && c <= '9') {
code = code * 10 + (c - '0');
} else if (c == 'm' || c == ';') {
switch (code) {
case 0:
_consoleAttribute = _defaultAttribute;
_consoleColor = _defaultColor | _defaultBackground;
break;
case 1: // BOLD
case 5: // BLINK
_consoleAttribute = (_defaultAttribute ^ FOREGROUND_INTENSITY) & INTENSITY;
break;
case 30:
_consoleColor = BACKGROUND_WHITE;
break;
case 31:
_consoleColor = FOREGROUND_RED | _defaultBackground;
break;
case 32:
_consoleColor = FOREGROUND_GREEN | _defaultBackground;
break;
case 33:
_consoleColor = FOREGROUND_RED | FOREGROUND_GREEN | _defaultBackground;
break;
case 34:
_consoleColor = FOREGROUND_BLUE | _defaultBackground;
break;
case 35:
_consoleColor = FOREGROUND_BLUE | FOREGROUND_RED | _defaultBackground;
break;
case 36:
_consoleColor = FOREGROUND_BLUE | FOREGROUND_GREEN | _defaultBackground;
break;
case 37:
_consoleColor = FOREGROUND_GREEN | FOREGROUND_RED |
FOREGROUND_BLUE | _defaultBackground;
break;
}
code = 0;
}
if (c == 'm') {
++pos;
break;
}
}
}
}
if (line.size() > pos) {
_print2(line.substr(pos));
}
}
}
auto handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, _consoleAttribute | _consoleColor);
}
#endif
// prints a string to stdout, without a newline
void ConsoleFeature::printContinuous(std::string const& s) {
if (s.empty()) {
return;
}
{
fprintf(stdout, "%s", s.c_str());
fflush(stdout);
}
}
void ConsoleFeature::printLine(std::string const& s) {
{
fprintf(stdout, "%s\n", s.c_str());
fflush(stdout);
}
}
void ConsoleFeature::printErrorLine(std::string const& s) { printLine(s); }
std::string ConsoleFeature::readPassword(std::string const& message) {
printContinuous(message);
std::string password = readPassword();
ConsoleFeature::printLine("");
return password;
}
std::string ConsoleFeature::readPassword() {
TRI_SetStdinVisibility(false);
TRI_DEFER(TRI_SetStdinVisibility(true));
std::string password;
#ifdef _WIN32
std::wstring wpassword;
_setmode(_fileno(stdin), _O_U16TEXT);
std::getline(std::wcin, wpassword);
icu::UnicodeString pw(wpassword.c_str(), static_cast<int32_t>(wpassword.length()));
pw.toUTF8String<std::string>(password);
#else
std::getline(std::cin, password);
#endif
return password;
}
void ConsoleFeature::printWelcomeInfo() {
if (_quiet) {
return;
}
std::ostringstream s;
if (_pager) {
s << "Using pager '" << _pagerCommand << "' for output buffering. ";
}
if (_useHistory) {
s << "Command-line history will be persisted when the shell is exited. You can use `--console.history false` to turn this off";
} else {
s << "Command-line history is enabled for this session only and will *not* be persisted.";
}
printLine(s.str());
}
void ConsoleFeature::printByeBye() {
if (!_quiet) {
printLine(TRI_BYE_MESSAGE);
}
}
static std::string StripBinary(std::string const& value) {
std::string result;
bool inBinary = false;
for (char c : value) {
if (inBinary) {
if (c == 'm') {
inBinary = false;
}
} else {
if (c == '\x1b') {
inBinary = true;
} else {
result.push_back(c);
}
}
}
return result;
}
void ConsoleFeature::print(std::string const& message) {
if (_toPager == stdout) {
printContinuous(message);
} else {
std::string sanitized = StripBinary(message);
fprintf(_toPager, "%s", sanitized.c_str());
}
log(message);
}
void ConsoleFeature::openLog() {
if (!_auditFile.empty()) {
_toAuditFile = TRI_FOPEN(_auditFile.c_str(), "w");
std::ostringstream s;
if (_toAuditFile == nullptr) {
s << "Cannot open file '" << _auditFile << "' for logging.";
printErrorLine(s.str());
} else {
s << "Logging input and output to '" << _auditFile << "'.";
printLine(s.str());
}
}
}
void ConsoleFeature::closeLog() {
if (_toAuditFile != nullptr) {
fclose(_toAuditFile);
_toAuditFile = nullptr;
}
}
void ConsoleFeature::log(std::string const& message) {
if (_toAuditFile != nullptr) {
std::string sanitized = StripBinary(message);
if (!sanitized.empty()) {
// do not print terminal escape sequences into log
fprintf(_toAuditFile, "%s", sanitized.c_str());
}
}
}
void ConsoleFeature::flushLog() {
if (_toAuditFile) {
fflush(_toAuditFile);
}
}
ConsoleFeature::Prompt ConsoleFeature::buildPrompt(ClientFeature* client) {
std::string result;
bool esc = false;
for (char c : _prompt) {
if (c == '\0') {
break;
}
if (esc) {
if (c == '%') {
result.push_back(c);
} else if (c == 't') {
std::ostringstream tmp;
tmp << std::setprecision(6) << std::fixed << TRI_microtime();
result.append(tmp.str());
} else if (c == 'a') {
std::ostringstream tmp;
tmp << std::setprecision(6) << std::fixed << (TRI_microtime() - _startTime);
result.append(tmp.str());
} else if (c == 'p') {
std::ostringstream tmp;
tmp << std::setprecision(6) << std::fixed << _lastDuration;
result.append(tmp.str());
} else if (c == 'd') {
if (client != nullptr) {
result.append(client->databaseName());
} else {
result.append("[database]");
}
} else if (c == 'e' || c == 'E') {
std::string ep;
if (client == nullptr) {
ep = "none";
} else {
ep = client->endpoint();
}
if (c == 'E') {
// replace protocol
if (ep.compare(0, strlen("tcp://"), "tcp://") == 0) {
ep = ep.substr(strlen("tcp://"));
} else if (ep.compare(0, strlen("http+tcp://"), "http+tcp://") == 0) {
ep = ep.substr(strlen("http+tcp://"));
} else if (ep.compare(0, strlen("ssl://"), "ssl://") == 0) {
ep = ep.substr(strlen("ssl://"));
} else if (ep.compare(0, strlen("unix://"), "unix://") == 0) {
ep = ep.substr(strlen("unix://"));
}
}
result.append(ep);
} else if (c == 'u') {
if (client == nullptr) {
result.append("[user]");
} else {
result.append(client->username());
}
}
esc = false;
} else {
if (c == '%') {
esc = true;
} else {
result.push_back(c);
}
}
}
std::string colored;
if (_supportsColors && _colors) {
if (_promptError) {
colored = ShellColorsFeature::SHELL_COLOR_BOLD_RED + result +
ShellColorsFeature::SHELL_COLOR_RESET;
} else {
colored = ShellColorsFeature::SHELL_COLOR_BOLD_GREEN + result +
ShellColorsFeature::SHELL_COLOR_RESET;
}
} else {
colored = result;
}
return {result, colored};
}
void ConsoleFeature::startPager() {
#ifndef _WIN32
if (!_pager || _pagerCommand.empty() || _pagerCommand == "stdout" ||
_pagerCommand == "-") {
_toPager = stdout;
} else {
_toPager = popen(_pagerCommand.c_str(), "w");
if (_toPager == nullptr) {
LOG_TOPIC("25033", ERR, arangodb::Logger::FIXME)
<< "popen() for pager failed! Using stdout instead!";
_toPager = stdout;
_pager = false;
}
}
#endif
}
void ConsoleFeature::stopPager() {
#ifndef _WIN32
if (_toPager != stdout) {
pclose(_toPager);
_toPager = stdout;
}
#endif
}
} // namespace arangodb
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "TurboModule.h"
using namespace facebook;
namespace facebook {
namespace react {
TurboModule::TurboModule(
const std::string &name,
std::shared_ptr<CallInvoker> jsInvoker)
: name_(name), jsInvoker_(jsInvoker) {}
TurboModule::~TurboModule() {}
jsi::Value TurboModule::get(
jsi::Runtime &runtime,
const jsi::PropNameID &propName) {
std::string propNameUtf8 = propName.utf8(runtime);
auto p = methodMap_.find(propNameUtf8);
if (p == methodMap_.end()) {
// Method was not found, let JS decide what to do.
return jsi::Value::undefined();
}
MethodMetadata meta = p->second;
return jsi::Function::createFromHostFunction(
runtime,
propName,
static_cast<unsigned int>(meta.argCount),
[this, meta](
facebook::jsi::Runtime &rt,
const facebook::jsi::Value &thisVal,
const facebook::jsi::Value *args,
size_t count) { return meta.invoker(rt, *this, args, count); });
}
} // namespace react
} // namespace facebook
|
/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 Module
* -------------------------------------------------
*
* Copyright 2019 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.
*
*//*!
* \file
* \brief OpenGL ES 3.1 Test Package that runs on GL4.5 context
*//*--------------------------------------------------------------------*/
#include "tgl45es31TestPackage.hpp"
#include "tes31TestCaseWrapper.hpp"
#include "tes31InfoTests.hpp"
#include "es31fFunctionalTests.hpp"
#include "es31sStressTests.hpp"
#include "gluStateReset.hpp"
#include "gluRenderContext.hpp"
#include "gluContextInfo.hpp"
#include "tcuTestLog.hpp"
#include "tcuCommandLine.hpp"
#include "tcuWaiverUtil.hpp"
#include "glwEnums.hpp"
namespace deqp
{
namespace gles31
{
TestPackageGL45ES31::TestPackageGL45ES31 (tcu::TestContext& testCtx)
: tcu::TestPackage (testCtx, "dEQP-GL45-ES31", "dEQP OpenGL ES 3.1 Tests On GL4.5 Context")
, m_archive (testCtx.getRootArchive(), "gles31/")
, m_context (DE_NULL)
, m_waiverMechanism (new tcu::WaiverUtil)
{
}
TestPackageGL45ES31::~TestPackageGL45ES31 (void)
{
// Destroy children first since destructors may access context.
TestNode::deinit();
delete m_context;
}
void TestPackageGL45ES31::init (void)
{
try
{
// Create context
m_context = new Context(m_testCtx, glu::ApiType::core(4, 5));
// Setup waiver mechanism
if (m_testCtx.getCommandLine().getRunMode() == tcu::RUNMODE_EXECUTE)
{
const glu::ContextInfo& contextInfo = m_context->getContextInfo();
std::string vendor = contextInfo.getString(GL_VENDOR);
std::string renderer = contextInfo.getString(GL_RENDERER);
const tcu::CommandLine& commandLine = m_context->getTestContext().getCommandLine();
tcu::SessionInfo sessionInfo (vendor, renderer, commandLine.getInitialCmdLine());
m_waiverMechanism->setup(commandLine.getWaiverFileName(), m_name, vendor, renderer, sessionInfo);
m_context->getTestContext().getLog().writeSessionInfo(sessionInfo.get());
}
// Add main test groups
addChild(new InfoTests (*m_context));
addChild(new Functional::GL45ES31FunctionalTests (*m_context));
}
catch (...)
{
delete m_context;
m_context = DE_NULL;
throw;
}
}
void TestPackageGL45ES31::deinit (void)
{
TestNode::deinit();
delete m_context;
m_context = DE_NULL;
}
tcu::TestCaseExecutor* TestPackageGL45ES31::createExecutor (void) const
{
return new TestCaseWrapper<TestPackageGL45ES31>(const_cast<TestPackageGL45ES31&>(*this), m_waiverMechanism);
}
} // gles31
} // deqp
|
/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "base/types.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "systemc/core/kernel.hh"
#include "systemc/core/sc_main_fiber.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/messages.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
namespace sc_core
{
namespace
{
sc_stop_mode _stop_mode = SC_STOP_FINISH_DELTA;
} // anonymous namespace
int
sc_argc()
{
return ::sc_gem5::scMainFiber.argc();
}
const char *const *
sc_argv()
{
return ::sc_gem5::scMainFiber.argv();
}
void
sc_start()
{
Tick now = ::sc_gem5::scheduler.getCurTick();
sc_start(sc_time::from_value(MaxTick - now), SC_EXIT_ON_STARVATION);
}
void
sc_pause()
{
if (::sc_gem5::Kernel::status() == SC_RUNNING)
::sc_gem5::scheduler.schedulePause();
}
void
sc_start(const sc_time &time, sc_starvation_policy p)
{
if (time.value() == 0) {
::sc_gem5::scheduler.oneCycle();
} else {
Tick now = ::sc_gem5::scheduler.getCurTick();
if (MaxTick - now < time.value())
SC_REPORT_ERROR(SC_ID_SIMULATION_TIME_OVERFLOW_, "");
::sc_gem5::scheduler.start(now + time.value(), p == SC_RUN_TO_TIME);
}
}
void
sc_set_stop_mode(sc_stop_mode mode)
{
if (sc_is_running()) {
SC_REPORT_ERROR(SC_ID_STOP_MODE_AFTER_START_, "");
return;
}
_stop_mode = mode;
}
sc_stop_mode
sc_get_stop_mode()
{
return _stop_mode;
}
void
sc_stop()
{
static bool stop_called = false;
if (stop_called) {
static bool stop_warned = false;
if (!stop_warned)
SC_REPORT_WARNING(SC_ID_SIMULATION_STOP_CALLED_TWICE_, "");
stop_warned = true;
return;
}
stop_called = true;
if (::sc_gem5::Kernel::status() == SC_STOPPED)
return;
if ((sc_get_status() & SC_RUNNING)) {
bool finish_delta = (_stop_mode == SC_STOP_FINISH_DELTA);
::sc_gem5::scheduler.scheduleStop(finish_delta);
} else {
::sc_gem5::Kernel::stop();
}
}
const sc_time &
sc_time_stamp()
{
static sc_time tstamp(1.0, SC_SEC);
tstamp = sc_time::from_value(::sc_gem5::scheduler.getCurTick());
return tstamp;
}
sc_dt::uint64
sc_delta_count()
{
return sc_gem5::scheduler.numCycles();
}
bool
sc_is_running()
{
return sc_get_status() & (SC_RUNNING | SC_PAUSED);
}
bool
sc_pending_activity_at_current_time()
{
return ::sc_gem5::scheduler.pendingCurr();
}
bool
sc_pending_activity_at_future_time()
{
return ::sc_gem5::scheduler.pendingFuture();
}
bool
sc_pending_activity()
{
return sc_pending_activity_at_current_time() ||
sc_pending_activity_at_future_time();
}
sc_time
sc_time_to_pending_activity()
{
return sc_time::from_value(::sc_gem5::scheduler.timeToPending());
}
sc_status
sc_get_status()
{
return ::sc_gem5::kernel ? ::sc_gem5::kernel->status() : SC_ELABORATION;
}
std::ostream &
operator << (std::ostream &os, sc_status s)
{
switch (s) {
case SC_ELABORATION:
os << "SC_ELABORATION";
break;
case SC_BEFORE_END_OF_ELABORATION:
os << "SC_BEFORE_END_OF_ELABORATION";
break;
case SC_END_OF_ELABORATION:
os << "SC_END_OF_ELABORATION";
break;
case SC_START_OF_SIMULATION:
os << "SC_START_OF_SIMULATION";
break;
case SC_RUNNING:
os << "SC_RUNNING";
break;
case SC_PAUSED:
os << "SC_PAUSED";
break;
case SC_STOPPED:
os << "SC_STOPPED";
break;
case SC_END_OF_SIMULATION:
os << "SC_END_OF_SIMULATION";
break;
// Nonstandard
case SC_END_OF_INITIALIZATION:
os << "SC_END_OF_INITIALIZATION";
break;
case SC_END_OF_UPDATE:
os << "SC_END_OF_UPDATE";
break;
case SC_BEFORE_TIMESTEP:
os << "SC_BEFORE_TIMESTEP";
break;
default:
if (s & SC_STATUS_ANY) {
const char *prefix = "(";
for (sc_status m = (sc_status)0x1;
m < SC_STATUS_ANY; m = (sc_status)(m << 1)) {
if (m & s) {
os << prefix;
prefix = "|";
os << m;
}
}
os << ")";
} else {
ccprintf(os, "%#x", s);
}
}
return os;
}
} // namespace sc_core
|
#include "intrusive.h"
|
//===-- Serialization.cpp - Binary serialization of index data ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Serialization.h"
#include "Headers.h"
#include "RIFF.h"
#include "index/MemIndex.h"
#include "index/SymbolLocation.h"
#include "index/SymbolOrigin.h"
#include "index/dex/Dex.h"
#include "support/Logger.h"
#include "support/Trace.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdint>
#include <vector>
namespace clang {
namespace clangd {
namespace {
// IO PRIMITIVES
// We use little-endian 32 bit ints, sometimes with variable-length encoding.
//
// Variable-length int encoding (varint) uses the bottom 7 bits of each byte
// to encode the number, and the top bit to indicate whether more bytes follow.
// e.g. 9a 2f means [0x1a and keep reading, 0x2f and stop].
// This represents 0x1a | 0x2f<<7 = 6042.
// A 32-bit integer takes 1-5 bytes to encode; small numbers are more compact.
// Reads binary data from a StringRef, and keeps track of position.
class Reader {
const char *Begin, *End;
bool Err = false;
public:
Reader(llvm::StringRef Data) : Begin(Data.begin()), End(Data.end()) {}
// The "error" bit is set by reading past EOF or reading invalid data.
// When in an error state, reads may return zero values: callers should check.
bool err() const { return Err; }
// Did we read all the data, or encounter an error?
bool eof() const { return Begin == End || Err; }
// All the data we didn't read yet.
llvm::StringRef rest() const { return llvm::StringRef(Begin, End - Begin); }
uint8_t consume8() {
if (LLVM_UNLIKELY(Begin == End)) {
Err = true;
return 0;
}
return *Begin++;
}
uint32_t consume32() {
if (LLVM_UNLIKELY(Begin + 4 > End)) {
Err = true;
return 0;
}
auto Ret = llvm::support::endian::read32le(Begin);
Begin += 4;
return Ret;
}
llvm::StringRef consume(int N) {
if (LLVM_UNLIKELY(Begin + N > End)) {
Err = true;
return llvm::StringRef();
}
llvm::StringRef Ret(Begin, N);
Begin += N;
return Ret;
}
uint32_t consumeVar() {
constexpr static uint8_t More = 1 << 7;
// Use a 32 bit unsigned here to prevent promotion to signed int (unless int
// is wider than 32 bits).
uint32_t B = consume8();
if (LLVM_LIKELY(!(B & More)))
return B;
uint32_t Val = B & ~More;
for (int Shift = 7; B & More && Shift < 32; Shift += 7) {
B = consume8();
// 5th byte of a varint can only have lowest 4 bits set.
assert((Shift != 28 || B == (B & 0x0f)) && "Invalid varint encoding");
Val |= (B & ~More) << Shift;
}
return Val;
}
llvm::StringRef consumeString(llvm::ArrayRef<llvm::StringRef> Strings) {
auto StringIndex = consumeVar();
if (LLVM_UNLIKELY(StringIndex >= Strings.size())) {
Err = true;
return llvm::StringRef();
}
return Strings[StringIndex];
}
SymbolID consumeID() {
llvm::StringRef Raw = consume(SymbolID::RawSize); // short if truncated.
return LLVM_UNLIKELY(err()) ? SymbolID() : SymbolID::fromRaw(Raw);
}
// Read a varint (as consumeVar) and resize the container accordingly.
// If the size is invalid, return false and mark an error.
// (The caller should abort in this case).
template <typename T> LLVM_NODISCARD bool consumeSize(T &Container) {
auto Size = consumeVar();
// Conservatively assume each element is at least one byte.
if (Size > (size_t)(End - Begin)) {
Err = true;
return false;
}
Container.resize(Size);
return true;
}
};
void write32(uint32_t I, llvm::raw_ostream &OS) {
char Buf[4];
llvm::support::endian::write32le(Buf, I);
OS.write(Buf, sizeof(Buf));
}
void writeVar(uint32_t I, llvm::raw_ostream &OS) {
constexpr static uint8_t More = 1 << 7;
if (LLVM_LIKELY(I < 1 << 7)) {
OS.write(I);
return;
}
for (;;) {
OS.write(I | More);
I >>= 7;
if (I < 1 << 7) {
OS.write(I);
return;
}
}
}
// STRING TABLE ENCODING
// Index data has many string fields, and many strings are identical.
// We store each string once, and refer to them by index.
//
// The string table's format is:
// - UncompressedSize : uint32 (or 0 for no compression)
// - CompressedData : byte[CompressedSize]
//
// CompressedData is a zlib-compressed byte[UncompressedSize].
// It contains a sequence of null-terminated strings, e.g. "foo\0bar\0".
// These are sorted to improve compression.
// Maps each string to a canonical representation.
// Strings remain owned externally (e.g. by SymbolSlab).
class StringTableOut {
llvm::DenseSet<llvm::StringRef> Unique;
std::vector<llvm::StringRef> Sorted;
// Since strings are interned, look up can be by pointer.
llvm::DenseMap<std::pair<const char *, size_t>, unsigned> Index;
public:
StringTableOut() {
// Ensure there's at least one string in the table.
// Table size zero is reserved to indicate no compression.
Unique.insert("");
}
// Add a string to the table. Overwrites S if an identical string exists.
void intern(llvm::StringRef &S) { S = *Unique.insert(S).first; };
// Finalize the table and write it to OS. No more strings may be added.
void finalize(llvm::raw_ostream &OS) {
Sorted = {Unique.begin(), Unique.end()};
llvm::sort(Sorted);
for (unsigned I = 0; I < Sorted.size(); ++I)
Index.try_emplace({Sorted[I].data(), Sorted[I].size()}, I);
std::string RawTable;
for (llvm::StringRef S : Sorted) {
RawTable.append(std::string(S));
RawTable.push_back(0);
}
if (llvm::zlib::isAvailable()) {
llvm::SmallString<1> Compressed;
llvm::zlib::compress(RawTable, Compressed);
write32(RawTable.size(), OS);
OS << Compressed;
} else {
write32(0, OS); // No compression.
OS << RawTable;
}
}
// Get the ID of an string, which must be interned. Table must be finalized.
unsigned index(llvm::StringRef S) const {
assert(!Sorted.empty() && "table not finalized");
assert(Index.count({S.data(), S.size()}) && "string not interned");
return Index.find({S.data(), S.size()})->second;
}
};
struct StringTableIn {
llvm::BumpPtrAllocator Arena;
std::vector<llvm::StringRef> Strings;
};
llvm::Expected<StringTableIn> readStringTable(llvm::StringRef Data) {
Reader R(Data);
size_t UncompressedSize = R.consume32();
if (R.err())
return error("Truncated string table");
llvm::StringRef Uncompressed;
llvm::SmallString<1> UncompressedStorage;
if (UncompressedSize == 0) // No compression
Uncompressed = R.rest();
else if (llvm::zlib::isAvailable()) {
// Don't allocate a massive buffer if UncompressedSize was corrupted
// This is effective for sharded index, but not big monolithic ones, as
// once compressed size reaches 4MB nothing can be ruled out.
// Theoretical max ratio from https://zlib.net/zlib_tech.html
constexpr int MaxCompressionRatio = 1032;
if (UncompressedSize / MaxCompressionRatio > R.rest().size())
return error("Bad stri table: uncompress {0} -> {1} bytes is implausible",
R.rest().size(), UncompressedSize);
if (llvm::Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage,
UncompressedSize))
return std::move(E);
Uncompressed = UncompressedStorage;
} else
return error("Compressed string table, but zlib is unavailable");
StringTableIn Table;
llvm::StringSaver Saver(Table.Arena);
R = Reader(Uncompressed);
for (Reader R(Uncompressed); !R.eof();) {
auto Len = R.rest().find(0);
if (Len == llvm::StringRef::npos)
return error("Bad string table: not null terminated");
Table.Strings.push_back(Saver.save(R.consume(Len)));
R.consume8();
}
if (R.err())
return error("Truncated string table");
return std::move(Table);
}
// SYMBOL ENCODING
// Each field of clangd::Symbol is encoded in turn (see implementation).
// - StringRef fields encode as varint (index into the string table)
// - enums encode as the underlying type
// - most numbers encode as varint
void writeLocation(const SymbolLocation &Loc, const StringTableOut &Strings,
llvm::raw_ostream &OS) {
writeVar(Strings.index(Loc.FileURI), OS);
for (const auto &Endpoint : {Loc.Start, Loc.End}) {
writeVar(Endpoint.line(), OS);
writeVar(Endpoint.column(), OS);
}
}
SymbolLocation readLocation(Reader &Data,
llvm::ArrayRef<llvm::StringRef> Strings) {
SymbolLocation Loc;
Loc.FileURI = Data.consumeString(Strings).data();
for (auto *Endpoint : {&Loc.Start, &Loc.End}) {
Endpoint->setLine(Data.consumeVar());
Endpoint->setColumn(Data.consumeVar());
}
return Loc;
}
IncludeGraphNode readIncludeGraphNode(Reader &Data,
llvm::ArrayRef<llvm::StringRef> Strings) {
IncludeGraphNode IGN;
IGN.Flags = static_cast<IncludeGraphNode::SourceFlag>(Data.consume8());
IGN.URI = Data.consumeString(Strings);
llvm::StringRef Digest = Data.consume(IGN.Digest.size());
std::copy(Digest.bytes_begin(), Digest.bytes_end(), IGN.Digest.begin());
if (!Data.consumeSize(IGN.DirectIncludes))
return IGN;
for (llvm::StringRef &Include : IGN.DirectIncludes)
Include = Data.consumeString(Strings);
return IGN;
}
void writeIncludeGraphNode(const IncludeGraphNode &IGN,
const StringTableOut &Strings,
llvm::raw_ostream &OS) {
OS.write(static_cast<uint8_t>(IGN.Flags));
writeVar(Strings.index(IGN.URI), OS);
llvm::StringRef Hash(reinterpret_cast<const char *>(IGN.Digest.data()),
IGN.Digest.size());
OS << Hash;
writeVar(IGN.DirectIncludes.size(), OS);
for (llvm::StringRef Include : IGN.DirectIncludes)
writeVar(Strings.index(Include), OS);
}
void writeSymbol(const Symbol &Sym, const StringTableOut &Strings,
llvm::raw_ostream &OS) {
OS << Sym.ID.raw(); // TODO: once we start writing xrefs and posting lists,
// symbol IDs should probably be in a string table.
OS.write(static_cast<uint8_t>(Sym.SymInfo.Kind));
OS.write(static_cast<uint8_t>(Sym.SymInfo.Lang));
writeVar(Strings.index(Sym.Name), OS);
writeVar(Strings.index(Sym.Scope), OS);
writeVar(Strings.index(Sym.TemplateSpecializationArgs), OS);
writeLocation(Sym.Definition, Strings, OS);
writeLocation(Sym.CanonicalDeclaration, Strings, OS);
writeVar(Sym.References, OS);
OS.write(static_cast<uint8_t>(Sym.Flags));
writeVar(Strings.index(Sym.Signature), OS);
writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
writeVar(Strings.index(Sym.Documentation), OS);
writeVar(Strings.index(Sym.ReturnType), OS);
writeVar(Strings.index(Sym.Type), OS);
auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) {
writeVar(Strings.index(Include.IncludeHeader), OS);
writeVar(Include.References, OS);
};
writeVar(Sym.IncludeHeaders.size(), OS);
for (const auto &Include : Sym.IncludeHeaders)
WriteInclude(Include);
}
Symbol readSymbol(Reader &Data, llvm::ArrayRef<llvm::StringRef> Strings,
SymbolOrigin Origin) {
Symbol Sym;
Sym.ID = Data.consumeID();
Sym.SymInfo.Kind = static_cast<index::SymbolKind>(Data.consume8());
Sym.SymInfo.Lang = static_cast<index::SymbolLanguage>(Data.consume8());
Sym.Name = Data.consumeString(Strings);
Sym.Scope = Data.consumeString(Strings);
Sym.TemplateSpecializationArgs = Data.consumeString(Strings);
Sym.Definition = readLocation(Data, Strings);
Sym.CanonicalDeclaration = readLocation(Data, Strings);
Sym.References = Data.consumeVar();
Sym.Flags = static_cast<Symbol::SymbolFlag>(Data.consume8());
Sym.Origin = Origin;
Sym.Signature = Data.consumeString(Strings);
Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
Sym.Documentation = Data.consumeString(Strings);
Sym.ReturnType = Data.consumeString(Strings);
Sym.Type = Data.consumeString(Strings);
if (!Data.consumeSize(Sym.IncludeHeaders))
return Sym;
for (auto &I : Sym.IncludeHeaders) {
I.IncludeHeader = Data.consumeString(Strings);
I.References = Data.consumeVar();
}
return Sym;
}
// REFS ENCODING
// A refs section has data grouped by Symbol. Each symbol has:
// - SymbolID: 8 bytes
// - NumRefs: varint
// - Ref[NumRefs]
// Fields of Ref are encoded in turn, see implementation.
void writeRefs(const SymbolID &ID, llvm::ArrayRef<Ref> Refs,
const StringTableOut &Strings, llvm::raw_ostream &OS) {
OS << ID.raw();
writeVar(Refs.size(), OS);
for (const auto &Ref : Refs) {
OS.write(static_cast<unsigned char>(Ref.Kind));
writeLocation(Ref.Location, Strings, OS);
OS << Ref.Container.raw();
}
}
std::pair<SymbolID, std::vector<Ref>>
readRefs(Reader &Data, llvm::ArrayRef<llvm::StringRef> Strings) {
std::pair<SymbolID, std::vector<Ref>> Result;
Result.first = Data.consumeID();
if (!Data.consumeSize(Result.second))
return Result;
for (auto &Ref : Result.second) {
Ref.Kind = static_cast<RefKind>(Data.consume8());
Ref.Location = readLocation(Data, Strings);
Ref.Container = Data.consumeID();
}
return Result;
}
// RELATIONS ENCODING
// A relations section is a flat list of relations. Each relation has:
// - SymbolID (subject): 8 bytes
// - relation kind (predicate): 1 byte
// - SymbolID (object): 8 bytes
// In the future, we might prefer a packed representation if the need arises.
void writeRelation(const Relation &R, llvm::raw_ostream &OS) {
OS << R.Subject.raw();
OS.write(static_cast<uint8_t>(R.Predicate));
OS << R.Object.raw();
}
Relation readRelation(Reader &Data) {
SymbolID Subject = Data.consumeID();
RelationKind Predicate = static_cast<RelationKind>(Data.consume8());
SymbolID Object = Data.consumeID();
return {Subject, Predicate, Object};
}
struct InternedCompileCommand {
llvm::StringRef Directory;
std::vector<llvm::StringRef> CommandLine;
};
void writeCompileCommand(const InternedCompileCommand &Cmd,
const StringTableOut &Strings,
llvm::raw_ostream &CmdOS) {
writeVar(Strings.index(Cmd.Directory), CmdOS);
writeVar(Cmd.CommandLine.size(), CmdOS);
for (llvm::StringRef C : Cmd.CommandLine)
writeVar(Strings.index(C), CmdOS);
}
InternedCompileCommand
readCompileCommand(Reader CmdReader, llvm::ArrayRef<llvm::StringRef> Strings) {
InternedCompileCommand Cmd;
Cmd.Directory = CmdReader.consumeString(Strings);
if (!CmdReader.consumeSize(Cmd.CommandLine))
return Cmd;
for (llvm::StringRef &C : Cmd.CommandLine)
C = CmdReader.consumeString(Strings);
return Cmd;
}
// FILE ENCODING
// A file is a RIFF chunk with type 'CdIx'.
// It contains the sections:
// - meta: version number
// - srcs: information related to include graph
// - stri: string table
// - symb: symbols
// - refs: references to symbols
// The current versioning scheme is simple - non-current versions are rejected.
// If you make a breaking change, bump this version number to invalidate stored
// data. Later we may want to support some backward compatibility.
constexpr static uint32_t Version = 17;
llvm::Expected<IndexFileIn> readRIFF(llvm::StringRef Data,
SymbolOrigin Origin) {
auto RIFF = riff::readFile(Data);
if (!RIFF)
return RIFF.takeError();
if (RIFF->Type != riff::fourCC("CdIx"))
return error("wrong RIFF filetype: {0}", riff::fourCCStr(RIFF->Type));
llvm::StringMap<llvm::StringRef> Chunks;
for (const auto &Chunk : RIFF->Chunks)
Chunks.try_emplace(llvm::StringRef(Chunk.ID.data(), Chunk.ID.size()),
Chunk.Data);
if (!Chunks.count("meta"))
return error("missing meta chunk");
Reader Meta(Chunks.lookup("meta"));
auto SeenVersion = Meta.consume32();
if (SeenVersion != Version)
return error("wrong version: want {0}, got {1}", Version, SeenVersion);
// meta chunk is checked above, as we prefer the "version mismatch" error.
for (llvm::StringRef RequiredChunk : {"stri"})
if (!Chunks.count(RequiredChunk))
return error("missing required chunk {0}", RequiredChunk);
auto Strings = readStringTable(Chunks.lookup("stri"));
if (!Strings)
return Strings.takeError();
IndexFileIn Result;
if (Chunks.count("srcs")) {
Reader SrcsReader(Chunks.lookup("srcs"));
Result.Sources.emplace();
while (!SrcsReader.eof()) {
auto IGN = readIncludeGraphNode(SrcsReader, Strings->Strings);
auto Entry = Result.Sources->try_emplace(IGN.URI).first;
Entry->getValue() = std::move(IGN);
// We change all the strings inside the structure to point at the keys in
// the map, since it is the only copy of the string that's going to live.
Entry->getValue().URI = Entry->getKey();
for (auto &Include : Entry->getValue().DirectIncludes)
Include = Result.Sources->try_emplace(Include).first->getKey();
}
if (SrcsReader.err())
return error("malformed or truncated include uri");
}
if (Chunks.count("symb")) {
Reader SymbolReader(Chunks.lookup("symb"));
SymbolSlab::Builder Symbols;
while (!SymbolReader.eof())
Symbols.insert(readSymbol(SymbolReader, Strings->Strings, Origin));
if (SymbolReader.err())
return error("malformed or truncated symbol");
Result.Symbols = std::move(Symbols).build();
}
if (Chunks.count("refs")) {
Reader RefsReader(Chunks.lookup("refs"));
RefSlab::Builder Refs;
while (!RefsReader.eof()) {
auto RefsBundle = readRefs(RefsReader, Strings->Strings);
for (const auto &Ref : RefsBundle.second) // FIXME: bulk insert?
Refs.insert(RefsBundle.first, Ref);
}
if (RefsReader.err())
return error("malformed or truncated refs");
Result.Refs = std::move(Refs).build();
}
if (Chunks.count("rela")) {
Reader RelationsReader(Chunks.lookup("rela"));
RelationSlab::Builder Relations;
while (!RelationsReader.eof())
Relations.insert(readRelation(RelationsReader));
if (RelationsReader.err())
return error("malformed or truncated relations");
Result.Relations = std::move(Relations).build();
}
if (Chunks.count("cmdl")) {
Reader CmdReader(Chunks.lookup("cmdl"));
InternedCompileCommand Cmd =
readCompileCommand(CmdReader, Strings->Strings);
if (CmdReader.err())
return error("malformed or truncated commandline section");
Result.Cmd.emplace();
Result.Cmd->Directory = std::string(Cmd.Directory);
Result.Cmd->CommandLine.reserve(Cmd.CommandLine.size());
for (llvm::StringRef C : Cmd.CommandLine)
Result.Cmd->CommandLine.emplace_back(C);
}
return std::move(Result);
}
template <class Callback>
void visitStrings(IncludeGraphNode &IGN, const Callback &CB) {
CB(IGN.URI);
for (llvm::StringRef &Include : IGN.DirectIncludes)
CB(Include);
}
void writeRIFF(const IndexFileOut &Data, llvm::raw_ostream &OS) {
assert(Data.Symbols && "An index file without symbols makes no sense!");
riff::File RIFF;
RIFF.Type = riff::fourCC("CdIx");
llvm::SmallString<4> Meta;
{
llvm::raw_svector_ostream MetaOS(Meta);
write32(Version, MetaOS);
}
RIFF.Chunks.push_back({riff::fourCC("meta"), Meta});
StringTableOut Strings;
std::vector<Symbol> Symbols;
for (const auto &Sym : *Data.Symbols) {
Symbols.emplace_back(Sym);
visitStrings(Symbols.back(),
[&](llvm::StringRef &S) { Strings.intern(S); });
}
std::vector<IncludeGraphNode> Sources;
if (Data.Sources)
for (const auto &Source : *Data.Sources) {
Sources.push_back(Source.getValue());
visitStrings(Sources.back(),
[&](llvm::StringRef &S) { Strings.intern(S); });
}
std::vector<std::pair<SymbolID, std::vector<Ref>>> Refs;
if (Data.Refs) {
for (const auto &Sym : *Data.Refs) {
Refs.emplace_back(Sym);
for (auto &Ref : Refs.back().second) {
llvm::StringRef File = Ref.Location.FileURI;
Strings.intern(File);
Ref.Location.FileURI = File.data();
}
}
}
std::vector<Relation> Relations;
if (Data.Relations) {
for (const auto &Relation : *Data.Relations) {
Relations.emplace_back(Relation);
// No strings to be interned in relations.
}
}
InternedCompileCommand InternedCmd;
if (Data.Cmd) {
InternedCmd.CommandLine.reserve(Data.Cmd->CommandLine.size());
InternedCmd.Directory = Data.Cmd->Directory;
Strings.intern(InternedCmd.Directory);
for (llvm::StringRef C : Data.Cmd->CommandLine) {
InternedCmd.CommandLine.emplace_back(C);
Strings.intern(InternedCmd.CommandLine.back());
}
}
std::string StringSection;
{
llvm::raw_string_ostream StringOS(StringSection);
Strings.finalize(StringOS);
}
RIFF.Chunks.push_back({riff::fourCC("stri"), StringSection});
std::string SymbolSection;
{
llvm::raw_string_ostream SymbolOS(SymbolSection);
for (const auto &Sym : Symbols)
writeSymbol(Sym, Strings, SymbolOS);
}
RIFF.Chunks.push_back({riff::fourCC("symb"), SymbolSection});
std::string RefsSection;
if (Data.Refs) {
{
llvm::raw_string_ostream RefsOS(RefsSection);
for (const auto &Sym : Refs)
writeRefs(Sym.first, Sym.second, Strings, RefsOS);
}
RIFF.Chunks.push_back({riff::fourCC("refs"), RefsSection});
}
std::string RelationSection;
if (Data.Relations) {
{
llvm::raw_string_ostream RelationOS{RelationSection};
for (const auto &Relation : Relations)
writeRelation(Relation, RelationOS);
}
RIFF.Chunks.push_back({riff::fourCC("rela"), RelationSection});
}
std::string SrcsSection;
{
{
llvm::raw_string_ostream SrcsOS(SrcsSection);
for (const auto &SF : Sources)
writeIncludeGraphNode(SF, Strings, SrcsOS);
}
RIFF.Chunks.push_back({riff::fourCC("srcs"), SrcsSection});
}
std::string CmdlSection;
if (Data.Cmd) {
{
llvm::raw_string_ostream CmdOS(CmdlSection);
writeCompileCommand(InternedCmd, Strings, CmdOS);
}
RIFF.Chunks.push_back({riff::fourCC("cmdl"), CmdlSection});
}
OS << RIFF;
}
} // namespace
// Defined in YAMLSerialization.cpp.
void writeYAML(const IndexFileOut &, llvm::raw_ostream &);
llvm::Expected<IndexFileIn> readYAML(llvm::StringRef, SymbolOrigin Origin);
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const IndexFileOut &O) {
switch (O.Format) {
case IndexFileFormat::RIFF:
writeRIFF(O, OS);
break;
case IndexFileFormat::YAML:
writeYAML(O, OS);
break;
}
return OS;
}
llvm::Expected<IndexFileIn> readIndexFile(llvm::StringRef Data,
SymbolOrigin Origin) {
if (Data.startswith("RIFF")) {
return readRIFF(Data, Origin);
}
if (auto YAMLContents = readYAML(Data, Origin)) {
return std::move(*YAMLContents);
} else {
return error("Not a RIFF file and failed to parse as YAML: {0}",
YAMLContents.takeError());
}
}
std::unique_ptr<SymbolIndex> loadIndex(llvm::StringRef SymbolFilename,
SymbolOrigin Origin, bool UseDex) {
trace::Span OverallTracer("LoadIndex");
auto Buffer = llvm::MemoryBuffer::getFile(SymbolFilename);
if (!Buffer) {
elog("Can't open {0}: {1}", SymbolFilename, Buffer.getError().message());
return nullptr;
}
SymbolSlab Symbols;
RefSlab Refs;
RelationSlab Relations;
{
trace::Span Tracer("ParseIndex");
if (auto I = readIndexFile(Buffer->get()->getBuffer(), Origin)) {
if (I->Symbols)
Symbols = std::move(*I->Symbols);
if (I->Refs)
Refs = std::move(*I->Refs);
if (I->Relations)
Relations = std::move(*I->Relations);
} else {
elog("Bad index file: {0}", I.takeError());
return nullptr;
}
}
size_t NumSym = Symbols.size();
size_t NumRefs = Refs.numRefs();
size_t NumRelations = Relations.size();
trace::Span Tracer("BuildIndex");
auto Index = UseDex ? dex::Dex::build(std::move(Symbols), std::move(Refs),
std::move(Relations))
: MemIndex::build(std::move(Symbols), std::move(Refs),
std::move(Relations));
vlog("Loaded {0} from {1} with estimated memory usage {2} bytes\n"
" - number of symbols: {3}\n"
" - number of refs: {4}\n"
" - number of relations: {5}",
UseDex ? "Dex" : "MemIndex", SymbolFilename,
Index->estimateMemoryUsage(), NumSym, NumRefs, NumRelations);
return Index;
}
} // namespace clangd
} // namespace clang
|
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "public/platform/WebTextRun.h"
#include "platform/text/TextRun.h"
namespace blink {
WebTextRun::operator TextRun() const {
return TextRun(text, 0, 0, TextRun::AllowTrailingExpansion,
rtl ? TextDirection::kRtl : TextDirection::kLtr,
directionalOverride);
}
} // namespace blink
|
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------
//! \addtogroup fn_clamp
//! @{
template<typename T1>
arma_warn_unused
inline
typename
enable_if2
<
is_arma_type<T1>::value && is_cx<typename T1::elem_type>::no,
const mtOp<typename T1::elem_type, T1, op_clamp>
>::result
clamp(const T1& X, const typename T1::elem_type min_val, const typename T1::elem_type max_val)
{
arma_extra_debug_sigprint();
arma_debug_check( (min_val > max_val), "clamp(): min_val has to be smaller than max_val" );
return mtOp<typename T1::elem_type, T1, op_clamp>(mtOp_dual_aux_indicator(), X, min_val, max_val);
}
template<typename T1>
arma_warn_unused
inline
const mtOpCube<typename T1::elem_type, T1, op_clamp>
clamp(const BaseCube<typename T1::elem_type,T1>& X, const typename T1::elem_type min_val, const typename T1::elem_type max_val, typename arma_not_cx<typename T1::elem_type>::result* junk = 0)
{
arma_extra_debug_sigprint();
arma_ignore(junk);
arma_debug_check( (min_val > max_val), "clamp(): min_val has to be smaller than max_val" );
return mtOpCube<typename T1::elem_type, T1, op_clamp>(mtOpCube_dual_aux_indicator(), X.get_ref(), min_val, max_val);
}
//! @}
|
////////////////////////////////////////////////////////////////////////////
// Module : game_sv_base_script.cpp
// Created : 28.06.2004
// Modified : 28.06.2004
// Author : Dmitriy Iassenev
// Description : Base server game script export
////////////////////////////////////////////////////////////////////////////
#include "pch_script.h"
#include "game_sv_base.h"
#include "xrMessages.h"
#include "ui/UIInventoryUtilities.h"
#include "xr_time.h"
#include "UI/UIGameTutorial.h"
#include "string_table.h"
#include "object_broker.h"
using namespace luabind;
CUISequencer* g_tutorial = NULL;
CUISequencer* g_tutorial2 = NULL;
void start_tutorial(LPCSTR name)
{
if(g_tutorial){
VERIFY (!g_tutorial2);
g_tutorial2 = g_tutorial;
};
g_tutorial = xr_new<CUISequencer>();
g_tutorial->Start (name);
if(g_tutorial2)
g_tutorial->m_pStoredInputReceiver = g_tutorial2->m_pStoredInputReceiver;
}
LPCSTR translate_string(LPCSTR str)
{
return *CStringTable().translate(str);
}
bool has_active_tutotial()
{
return (g_tutorial!=NULL);
}
#pragma optimize("s",on)
void game_sv_GameState::script_register(lua_State *L)
{
module(L,"game")
[
class_< xrTime >("CTime")
.enum_("date_format")
[
value("DateToDay", int(InventoryUtilities::edpDateToDay)),
value("DateToMonth", int(InventoryUtilities::edpDateToMonth)),
value("DateToYear", int(InventoryUtilities::edpDateToYear))
]
.enum_("time_format")
[
value("TimeToHours", int(InventoryUtilities::etpTimeToHours)),
value("TimeToMinutes", int(InventoryUtilities::etpTimeToMinutes)),
value("TimeToSeconds", int(InventoryUtilities::etpTimeToSeconds)),
value("TimeToMilisecs", int(InventoryUtilities::etpTimeToMilisecs))
]
.def( constructor<>() )
.def( constructor<const xrTime&>())
.def(const_self < xrTime() )
.def(const_self <= xrTime() )
.def(const_self > xrTime() )
.def(const_self >= xrTime() )
.def(const_self == xrTime() )
.def(self + xrTime() )
.def(self - xrTime() )
.def("diffSec" ,&xrTime::diffSec_script)
.def("add" ,&xrTime::add_script)
.def("sub" ,&xrTime::sub_script)
.def("setHMS" ,&xrTime::setHMS)
.def("setHMSms" ,&xrTime::setHMSms)
.def("set" ,&xrTime::set)
.def("get" ,&xrTime::get, out_value(_2) + out_value(_3) + out_value(_4) + out_value(_5) + out_value(_6) + out_value(_7) + out_value(_8))
.def("dateToString" ,&xrTime::dateToString)
.def("timeToString" ,&xrTime::timeToString),
// declarations
def("time", get_time),
def("get_game_time", get_time_struct),
// def("get_surge_time", Game::get_surge_time),
// def("get_object_by_name",Game::get_object_by_name),
class_< game_sv_GameState, game_GameState >("game_sv_GameState")
.def("get_eid", &game_sv_GameState::get_eid)
.def("get_id", &game_sv_GameState::get_id)
//.def("get_it", &game_sv_GameState::get_it)
//.def("get_it_2_id", &game_sv_GameState::get_it_2_id)
//.def("get_name_it", &game_sv_GameState::get_name_it)
.def("get_name_id", &game_sv_GameState::get_name_id)
.def("get_player_name_id", &game_sv_GameState::get_player_name_id)
.def("get_players_count", &game_sv_GameState::get_players_count)
.def("get_id_2_eid", &game_sv_GameState::get_id_2_eid)
.def("get_option_i", &game_sv_GameState::get_option_i)
.def("get_option_s", &game_sv_GameState::get_option_s)
.def("u_EventSend", &game_sv_GameState::u_EventSend)
.def("GenerateGameMessage", &game_sv_GameState::GenerateGameMessage)
.def("getRP", &game_sv_GameState::getRP)
.def("getRPcount", &game_sv_GameState::getRPcount),
def("start_tutorial", &start_tutorial),
def("has_active_tutorial", &has_active_tutotial),
def("translate_string", &translate_string)
];
module(L)
[
class_<enum_exporter<EGamePlayerFlags> >("game_player_flags")
.enum_("flags")
[
value("GAME_PLAYER_FLAG_LOCAL", int(GAME_PLAYER_FLAG_LOCAL)),
value("GAME_PLAYER_FLAG_READY", int(GAME_PLAYER_FLAG_READY)),
value("GAME_PLAYER_FLAG_VERY_VERY_DEAD", int(GAME_PLAYER_FLAG_VERY_VERY_DEAD)),
value("GAME_PLAYER_FLAG_SPECTATOR", int(GAME_PLAYER_FLAG_SPECTATOR)),
value("GAME_PLAYER_FLAG_SCRIPT_BEGINS_FROM", int(GAME_PLAYER_FLAG_SCRIPT_BEGINS_FROM))
],
class_<enum_exporter<EGamePhases> >("game_phases")
.enum_("phases")
[
value("GAME_PHASE_NONE", int(GAME_PHASE_NONE)),
value("GAME_PHASE_INPROGRESS", int(GAME_PHASE_INPROGRESS)),
value("GAME_PHASE_PENDING", int(GAME_PHASE_PENDING)),
value("GAME_PHASE_TEAM1_SCORES", int(GAME_PHASE_TEAM1_SCORES)),
value("GAME_PHASE_TEAM2_SCORES", int(GAME_PHASE_TEAM2_SCORES)),
value("GAME_PHASE_TEAMS_IN_A_DRAW", int(GAME_PHASE_TEAMS_IN_A_DRAW)),
value("GAME_PHASE_SCRIPT_BEGINS_FROM", int(GAME_PHASE_SCRIPT_BEGINS_FROM))
],
class_<enum_exporter<EGameMessages> >("game_messages")
.enum_("messages")
[
value("GAME_EVENT_PLAYER_READY", int(GAME_EVENT_PLAYER_READY)),
value("GAME_EVENT_PLAYER_CHANGE_TEAM", int(GAME_EVENT_PLAYER_GAME_MENU)),
value("GAME_EVENT_PLAYER_KILL", int(GAME_EVENT_PLAYER_KILL)),
value("GAME_EVENT_PLAYER_BUY_FINISHED", int(GAME_EVENT_PLAYER_BUY_FINISHED)),
value("GAME_EVENT_PLAYER_CHANGE_SKIN", int(GAME_EVENT_PLAYER_GAME_MENU)),
value("GAME_EVENT_PLAYER_CONNECTED", int(GAME_EVENT_PLAYER_CONNECTED)),
value("GAME_EVENT_PLAYER_DISCONNECTED", int(GAME_EVENT_PLAYER_DISCONNECTED)),
value("GAME_EVENT_PLAYER_KILLED", int(GAME_EVENT_PLAYER_KILLED)),
value("GAME_EVENT_PLAYER_JOIN_TEAM", int(GAME_EVENT_PLAYER_JOIN_TEAM)),
value("GAME_EVENT_ROUND_STARTED", int(GAME_EVENT_ROUND_STARTED)),
value("GAME_EVENT_ROUND_END", int(GAME_EVENT_ROUND_END)),
value("GAME_EVENT_ARTEFACT_SPAWNED", int(GAME_EVENT_ARTEFACT_SPAWNED)),
value("GAME_EVENT_ARTEFACT_DESTROYED", int(GAME_EVENT_ARTEFACT_DESTROYED)),
value("GAME_EVENT_ARTEFACT_TAKEN", int(GAME_EVENT_ARTEFACT_TAKEN)),
value("GAME_EVENT_ARTEFACT_DROPPED", int(GAME_EVENT_ARTEFACT_DROPPED)),
value("GAME_EVENT_ARTEFACT_ONBASE", int(GAME_EVENT_ARTEFACT_ONBASE)),
value("GAME_EVENT_PLAYER_ENTER_TEAM_BASE", int(GAME_EVENT_PLAYER_ENTER_TEAM_BASE)),
value("GAME_EVENT_PLAYER_LEAVE_TEAM_BASE", int(GAME_EVENT_PLAYER_LEAVE_TEAM_BASE)),
value("GAME_EVENT_BUY_MENU_CLOSED", int(GAME_EVENT_BUY_MENU_CLOSED)),
value("GAME_EVENT_TEAM_MENU_CLOSED", int(GAME_EVENT_TEAM_MENU_CLOSED)),
value("GAME_EVENT_SKIN_MENU_CLOSED", int(GAME_EVENT_SKIN_MENU_CLOSED)),
value("GAME_EVENT_SCRIPT_BEGINS_FROM", int(GAME_EVENT_SCRIPT_BEGINS_FROM))
]
];
}
|
//
// Copyright 2012 Francisco Jerez
//
// 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 <cstring>
#include "api/util.hpp"
#include "core/event.hpp"
#include "core/memory.hpp"
using namespace clover;
namespace {
typedef resource::vector vector_t;
vector_t
vector(const size_t *p) {
return range(p, 3);
}
vector_t
pitch(const vector_t ®ion, vector_t pitch) {
for (auto x : zip(tail(pitch),
map(multiplies(), region, pitch))) {
// The spec defines a value of zero as the natural pitch,
// i.e. the unaligned size of the previous dimension.
if (std::get<0>(x) == 0)
std::get<0>(x) = std::get<1>(x);
}
return pitch;
}
///
/// Size of a region in bytes.
///
size_t
size(const vector_t &pitch, const vector_t ®ion) {
if (any_of(is_zero(), region))
return 0;
else
return dot(pitch, region - vector_t{ 0, 1, 1 });
}
///
/// Common argument checking shared by memory transfer commands.
///
void
validate_common(command_queue &q,
const ref_vector<event> &deps) {
if (any_of([&](const event &ev) {
return ev.context() != q.context();
}, deps))
throw error(CL_INVALID_CONTEXT);
}
///
/// Common error checking for a buffer object argument.
///
void
validate_object(command_queue &q, buffer &mem, const vector_t &origin,
const vector_t &pitch, const vector_t ®ion) {
if (mem.context() != q.context())
throw error(CL_INVALID_CONTEXT);
// The region must fit within the specified pitch,
if (any_of(greater(), map(multiplies(), pitch, region), tail(pitch)))
throw error(CL_INVALID_VALUE);
// ...and within the specified object.
if (dot(pitch, origin) + size(pitch, region) > mem.size())
throw error(CL_INVALID_VALUE);
if (any_of(is_zero(), region))
throw error(CL_INVALID_VALUE);
}
///
/// Common error checking for an image argument.
///
void
validate_object(command_queue &q, image &img,
const vector_t &orig, const vector_t ®ion) {
vector_t size = { img.width(), img.height(), img.depth() };
if (!q.device().image_support())
throw error(CL_INVALID_OPERATION);
if (img.context() != q.context())
throw error(CL_INVALID_CONTEXT);
if (any_of(greater(), orig + region, size))
throw error(CL_INVALID_VALUE);
if (any_of(is_zero(), region))
throw error(CL_INVALID_VALUE);
}
///
/// Common error checking for a host pointer argument.
///
void
validate_object(command_queue &q, const void *ptr, const vector_t &orig,
const vector_t &pitch, const vector_t ®ion) {
if (!ptr)
throw error(CL_INVALID_VALUE);
// The region must fit within the specified pitch.
if (any_of(greater(), map(multiplies(), pitch, region), tail(pitch)))
throw error(CL_INVALID_VALUE);
}
///
/// Common argument checking for a copy between two buffer objects.
///
void
validate_copy(command_queue &q, buffer &dst_mem,
const vector_t &dst_orig, const vector_t &dst_pitch,
buffer &src_mem,
const vector_t &src_orig, const vector_t &src_pitch,
const vector_t ®ion) {
if (dst_mem == src_mem) {
auto dst_offset = dot(dst_pitch, dst_orig);
auto src_offset = dot(src_pitch, src_orig);
if (interval_overlaps()(
dst_offset, dst_offset + size(dst_pitch, region),
src_offset, src_offset + size(src_pitch, region)))
throw error(CL_MEM_COPY_OVERLAP);
}
}
///
/// Common argument checking for a copy between two image objects.
///
void
validate_copy(command_queue &q,
image &dst_img, const vector_t &dst_orig,
image &src_img, const vector_t &src_orig,
const vector_t ®ion) {
if (dst_img.format() != src_img.format())
throw error(CL_IMAGE_FORMAT_MISMATCH);
if (dst_img == src_img) {
if (all_of(interval_overlaps(),
dst_orig, dst_orig + region,
src_orig, src_orig + region))
throw error(CL_MEM_COPY_OVERLAP);
}
}
///
/// Checks that the host access flags of the memory object are
/// within the allowed set \a flags.
///
void
validate_object_access(const memory_obj &mem, const cl_mem_flags flags) {
if (mem.flags() & ~flags &
(CL_MEM_HOST_READ_ONLY | CL_MEM_HOST_WRITE_ONLY |
CL_MEM_HOST_NO_ACCESS))
throw error(CL_INVALID_OPERATION);
}
///
/// Checks that the mapping flags are correct.
///
void
validate_map_flags(const memory_obj &mem, const cl_map_flags flags) {
if ((flags & (CL_MAP_WRITE | CL_MAP_READ)) &&
(flags & CL_MAP_WRITE_INVALIDATE_REGION))
throw error(CL_INVALID_VALUE);
if (flags & CL_MAP_READ)
validate_object_access(mem, CL_MEM_HOST_READ_ONLY);
if (flags & (CL_MAP_WRITE | CL_MAP_WRITE_INVALIDATE_REGION))
validate_object_access(mem, CL_MEM_HOST_WRITE_ONLY);
}
///
/// Class that encapsulates the task of mapping an object of type
/// \a T. The return value of get() should be implicitly
/// convertible to \a void *.
///
template<typename T>
struct _map {
static mapping
get(command_queue &q, T obj, cl_map_flags flags,
size_t offset, size_t size) {
return { q, obj->resource(q), flags, true,
{{ offset }}, {{ size, 1, 1 }} };
}
};
template<>
struct _map<void *> {
static void *
get(command_queue &q, void *obj, cl_map_flags flags,
size_t offset, size_t size) {
return (char *)obj + offset;
}
};
template<>
struct _map<const void *> {
static const void *
get(command_queue &q, const void *obj, cl_map_flags flags,
size_t offset, size_t size) {
return (const char *)obj + offset;
}
};
///
/// Software copy from \a src_obj to \a dst_obj. They can be
/// either pointers or memory objects.
///
template<typename T, typename S>
std::function<void (event &)>
soft_copy_op(command_queue &q,
T dst_obj, const vector_t &dst_orig, const vector_t &dst_pitch,
S src_obj, const vector_t &src_orig, const vector_t &src_pitch,
const vector_t ®ion) {
return [=, &q](event &) {
auto dst = _map<T>::get(q, dst_obj, CL_MAP_WRITE,
dot(dst_pitch, dst_orig),
size(dst_pitch, region));
auto src = _map<S>::get(q, src_obj, CL_MAP_READ,
dot(src_pitch, src_orig),
size(src_pitch, region));
vector_t v = {};
for (v[2] = 0; v[2] < region[2]; ++v[2]) {
for (v[1] = 0; v[1] < region[1]; ++v[1]) {
std::memcpy(
static_cast<char *>(dst) + dot(dst_pitch, v),
static_cast<const char *>(src) + dot(src_pitch, v),
src_pitch[0] * region[0]);
}
}
};
}
///
/// Hardware copy from \a src_obj to \a dst_obj.
///
template<typename T, typename S>
std::function<void (event &)>
hard_copy_op(command_queue &q, T dst_obj, const vector_t &dst_orig,
S src_obj, const vector_t &src_orig, const vector_t ®ion) {
return [=, &q](event &) {
dst_obj->resource(q).copy(q, dst_orig, region,
src_obj->resource(q), src_orig);
};
}
}
CLOVER_API cl_int
clEnqueueReadBuffer(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
size_t offset, size_t size, void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &mem = obj<buffer>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
vector_t region = { size, 1, 1 };
vector_t obj_origin = { offset };
auto obj_pitch = pitch(region, {{ 1 }});
validate_common(q, deps);
validate_object(q, ptr, {}, obj_pitch, region);
validate_object(q, mem, obj_origin, obj_pitch, region);
validate_object_access(mem, CL_MEM_HOST_READ_ONLY);
auto hev = create<hard_event>(
q, CL_COMMAND_READ_BUFFER, deps,
soft_copy_op(q, ptr, {}, obj_pitch,
&mem, obj_origin, obj_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueWriteBuffer(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
size_t offset, size_t size, const void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &mem = obj<buffer>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
vector_t region = { size, 1, 1 };
vector_t obj_origin = { offset };
auto obj_pitch = pitch(region, {{ 1 }});
validate_common(q, deps);
validate_object(q, mem, obj_origin, obj_pitch, region);
validate_object(q, ptr, {}, obj_pitch, region);
validate_object_access(mem, CL_MEM_HOST_WRITE_ONLY);
auto hev = create<hard_event>(
q, CL_COMMAND_WRITE_BUFFER, deps,
soft_copy_op(q, &mem, obj_origin, obj_pitch,
ptr, {}, obj_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueReadBufferRect(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
const size_t *p_obj_origin,
const size_t *p_host_origin,
const size_t *p_region,
size_t obj_row_pitch, size_t obj_slice_pitch,
size_t host_row_pitch, size_t host_slice_pitch,
void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &mem = obj<buffer>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto obj_origin = vector(p_obj_origin);
auto obj_pitch = pitch(region, {{ 1, obj_row_pitch, obj_slice_pitch }});
auto host_origin = vector(p_host_origin);
auto host_pitch = pitch(region, {{ 1, host_row_pitch, host_slice_pitch }});
validate_common(q, deps);
validate_object(q, ptr, host_origin, host_pitch, region);
validate_object(q, mem, obj_origin, obj_pitch, region);
validate_object_access(mem, CL_MEM_HOST_READ_ONLY);
auto hev = create<hard_event>(
q, CL_COMMAND_READ_BUFFER_RECT, deps,
soft_copy_op(q, ptr, host_origin, host_pitch,
&mem, obj_origin, obj_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueWriteBufferRect(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
const size_t *p_obj_origin,
const size_t *p_host_origin,
const size_t *p_region,
size_t obj_row_pitch, size_t obj_slice_pitch,
size_t host_row_pitch, size_t host_slice_pitch,
const void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &mem = obj<buffer>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto obj_origin = vector(p_obj_origin);
auto obj_pitch = pitch(region, {{ 1, obj_row_pitch, obj_slice_pitch }});
auto host_origin = vector(p_host_origin);
auto host_pitch = pitch(region, {{ 1, host_row_pitch, host_slice_pitch }});
validate_common(q, deps);
validate_object(q, mem, obj_origin, obj_pitch, region);
validate_object(q, ptr, host_origin, host_pitch, region);
validate_object_access(mem, CL_MEM_HOST_WRITE_ONLY);
auto hev = create<hard_event>(
q, CL_COMMAND_WRITE_BUFFER_RECT, deps,
soft_copy_op(q, &mem, obj_origin, obj_pitch,
ptr, host_origin, host_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueCopyBuffer(cl_command_queue d_q, cl_mem d_src_mem, cl_mem d_dst_mem,
size_t src_offset, size_t dst_offset, size_t size,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &src_mem = obj<buffer>(d_src_mem);
auto &dst_mem = obj<buffer>(d_dst_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
vector_t region = { size, 1, 1 };
vector_t dst_origin = { dst_offset };
auto dst_pitch = pitch(region, {{ 1 }});
vector_t src_origin = { src_offset };
auto src_pitch = pitch(region, {{ 1 }});
validate_common(q, deps);
validate_object(q, dst_mem, dst_origin, dst_pitch, region);
validate_object(q, src_mem, src_origin, src_pitch, region);
validate_copy(q, dst_mem, dst_origin, dst_pitch,
src_mem, src_origin, src_pitch, region);
auto hev = create<hard_event>(
q, CL_COMMAND_COPY_BUFFER, deps,
hard_copy_op(q, &dst_mem, dst_origin,
&src_mem, src_origin, region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueCopyBufferRect(cl_command_queue d_q, cl_mem d_src_mem,
cl_mem d_dst_mem,
const size_t *p_src_origin, const size_t *p_dst_origin,
const size_t *p_region,
size_t src_row_pitch, size_t src_slice_pitch,
size_t dst_row_pitch, size_t dst_slice_pitch,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &src_mem = obj<buffer>(d_src_mem);
auto &dst_mem = obj<buffer>(d_dst_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto dst_origin = vector(p_dst_origin);
auto dst_pitch = pitch(region, {{ 1, dst_row_pitch, dst_slice_pitch }});
auto src_origin = vector(p_src_origin);
auto src_pitch = pitch(region, {{ 1, src_row_pitch, src_slice_pitch }});
validate_common(q, deps);
validate_object(q, dst_mem, dst_origin, dst_pitch, region);
validate_object(q, src_mem, src_origin, src_pitch, region);
validate_copy(q, dst_mem, dst_origin, dst_pitch,
src_mem, src_origin, src_pitch, region);
auto hev = create<hard_event>(
q, CL_COMMAND_COPY_BUFFER_RECT, deps,
soft_copy_op(q, &dst_mem, dst_origin, dst_pitch,
&src_mem, src_origin, src_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueReadImage(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
const size_t *p_origin, const size_t *p_region,
size_t row_pitch, size_t slice_pitch, void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &img = obj<image>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto dst_pitch = pitch(region, {{ img.pixel_size(),
row_pitch, slice_pitch }});
auto src_origin = vector(p_origin);
auto src_pitch = pitch(region, {{ img.pixel_size(),
img.row_pitch(), img.slice_pitch() }});
validate_common(q, deps);
validate_object(q, ptr, {}, dst_pitch, region);
validate_object(q, img, src_origin, region);
validate_object_access(img, CL_MEM_HOST_READ_ONLY);
auto hev = create<hard_event>(
q, CL_COMMAND_READ_IMAGE, deps,
soft_copy_op(q, ptr, {}, dst_pitch,
&img, src_origin, src_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueWriteImage(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
const size_t *p_origin, const size_t *p_region,
size_t row_pitch, size_t slice_pitch, const void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &img = obj<image>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto dst_origin = vector(p_origin);
auto dst_pitch = pitch(region, {{ img.pixel_size(),
img.row_pitch(), img.slice_pitch() }});
auto src_pitch = pitch(region, {{ img.pixel_size(),
row_pitch, slice_pitch }});
validate_common(q, deps);
validate_object(q, img, dst_origin, region);
validate_object(q, ptr, {}, src_pitch, region);
validate_object_access(img, CL_MEM_HOST_WRITE_ONLY);
auto hev = create<hard_event>(
q, CL_COMMAND_WRITE_IMAGE, deps,
soft_copy_op(q, &img, dst_origin, dst_pitch,
ptr, {}, src_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueCopyImage(cl_command_queue d_q, cl_mem d_src_mem, cl_mem d_dst_mem,
const size_t *p_src_origin, const size_t *p_dst_origin,
const size_t *p_region,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &src_img = obj<image>(d_src_mem);
auto &dst_img = obj<image>(d_dst_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto dst_origin = vector(p_dst_origin);
auto src_origin = vector(p_src_origin);
validate_common(q, deps);
validate_object(q, dst_img, dst_origin, region);
validate_object(q, src_img, src_origin, region);
validate_copy(q, dst_img, dst_origin, src_img, src_origin, region);
auto hev = create<hard_event>(
q, CL_COMMAND_COPY_IMAGE, deps,
hard_copy_op(q, &dst_img, dst_origin,
&src_img, src_origin,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueCopyImageToBuffer(cl_command_queue d_q,
cl_mem d_src_mem, cl_mem d_dst_mem,
const size_t *p_src_origin, const size_t *p_region,
size_t dst_offset,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &src_img = obj<image>(d_src_mem);
auto &dst_mem = obj<buffer>(d_dst_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
vector_t dst_origin = { dst_offset };
auto dst_pitch = pitch(region, {{ src_img.pixel_size() }});
auto src_origin = vector(p_src_origin);
auto src_pitch = pitch(region, {{ src_img.pixel_size(),
src_img.row_pitch(),
src_img.slice_pitch() }});
validate_common(q, deps);
validate_object(q, dst_mem, dst_origin, dst_pitch, region);
validate_object(q, src_img, src_origin, region);
auto hev = create<hard_event>(
q, CL_COMMAND_COPY_IMAGE_TO_BUFFER, deps,
soft_copy_op(q, &dst_mem, dst_origin, dst_pitch,
&src_img, src_origin, src_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueCopyBufferToImage(cl_command_queue d_q,
cl_mem d_src_mem, cl_mem d_dst_mem,
size_t src_offset,
const size_t *p_dst_origin, const size_t *p_region,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &src_mem = obj<buffer>(d_src_mem);
auto &dst_img = obj<image>(d_dst_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto dst_origin = vector(p_dst_origin);
auto dst_pitch = pitch(region, {{ dst_img.pixel_size(),
dst_img.row_pitch(),
dst_img.slice_pitch() }});
vector_t src_origin = { src_offset };
auto src_pitch = pitch(region, {{ dst_img.pixel_size() }});
validate_common(q, deps);
validate_object(q, dst_img, dst_origin, region);
validate_object(q, src_mem, src_origin, src_pitch, region);
auto hev = create<hard_event>(
q, CL_COMMAND_COPY_BUFFER_TO_IMAGE, deps,
soft_copy_op(q, &dst_img, dst_origin, dst_pitch,
&src_mem, src_origin, src_pitch,
region));
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API void *
clEnqueueMapBuffer(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
cl_map_flags flags, size_t offset, size_t size,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev, cl_int *r_errcode) try {
auto &q = obj(d_q);
auto &mem = obj<buffer>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
vector_t region = { size, 1, 1 };
vector_t obj_origin = { offset };
auto obj_pitch = pitch(region, {{ 1 }});
validate_common(q, deps);
validate_object(q, mem, obj_origin, obj_pitch, region);
validate_map_flags(mem, flags);
void *map = mem.resource(q).add_map(q, flags, blocking, obj_origin, region);
ret_object(rd_ev, create<hard_event>(q, CL_COMMAND_MAP_BUFFER, deps));
ret_error(r_errcode, CL_SUCCESS);
return map;
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API void *
clEnqueueMapImage(cl_command_queue d_q, cl_mem d_mem, cl_bool blocking,
cl_map_flags flags,
const size_t *p_origin, const size_t *p_region,
size_t *row_pitch, size_t *slice_pitch,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev, cl_int *r_errcode) try {
auto &q = obj(d_q);
auto &img = obj<image>(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
auto region = vector(p_region);
auto origin = vector(p_origin);
validate_common(q, deps);
validate_object(q, img, origin, region);
validate_map_flags(img, flags);
void *map = img.resource(q).add_map(q, flags, blocking, origin, region);
ret_object(rd_ev, create<hard_event>(q, CL_COMMAND_MAP_IMAGE, deps));
ret_error(r_errcode, CL_SUCCESS);
return map;
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_int
clEnqueueUnmapMemObject(cl_command_queue d_q, cl_mem d_mem, void *ptr,
cl_uint num_deps, const cl_event *d_deps,
cl_event *rd_ev) try {
auto &q = obj(d_q);
auto &mem = obj(d_mem);
auto deps = objs<wait_list_tag>(d_deps, num_deps);
validate_common(q, deps);
auto hev = create<hard_event>(
q, CL_COMMAND_UNMAP_MEM_OBJECT, deps,
[=, &q, &mem](event &) {
mem.resource(q).del_map(ptr);
});
ret_object(rd_ev, hev);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clEnqueueMigrateMemObjects(cl_command_queue command_queue,
cl_uint num_mem_objects,
const cl_mem *mem_objects,
cl_mem_migration_flags flags,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event) {
CLOVER_NOT_SUPPORTED_UNTIL("1.2");
return CL_INVALID_VALUE;
}
|
/*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Rtrsna.cpp,v 1.5 2010/08/07 04:48:33 nakatamaho Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <mblas.h>
#include <mlapack.h>
#define MTRUE 1
#define MFALSE 0
void Rtrsna(const char *job, const char *howmny, LOGICAL * select,
INTEGER n, REAL * t, INTEGER ldt, REAL * vl, INTEGER ldvl, REAL * vr, INTEGER ldvr, REAL * s, REAL * sep,
INTEGER mm, INTEGER * m, REAL * work, INTEGER ldwork, INTEGER * iwork, INTEGER * info)
{
INTEGER i, j, k, n2;
REAL cs;
INTEGER nn, ks;
REAL sn, mu = 0.0, eps, est;
INTEGER kase;
REAL cond;
INTEGER pair;
INTEGER ierr;
REAL dumm = 0.0, prod;
INTEGER ifst;
REAL lnrm;
INTEGER ilst;
REAL rnrm;
REAL prod1, prod2, scale, delta;
INTEGER isave[3];
INTEGER wants;
REAL dummy[1];
REAL bignum;
INTEGER wantbh;
INTEGER somcon;
REAL smlnum;
INTEGER wantsp;
REAL Zero = 0.0, One = 1.0, Two = 2.0;
REAL mtemp1, mtemp2;
//Decode and test the input parameters
wantbh = Mlsame(job, "B");
wants = Mlsame(job, "E") || wantbh;
wantsp = Mlsame(job, "V") || wantbh;
somcon = Mlsame(howmny, "S");
*info = 0;
if (!wants && !wantsp) {
*info = -1;
} else if (!Mlsame(howmny, "A") && !somcon) {
*info = -2;
} else if (n < 0) {
*info = -4;
} else if (ldt < max((INTEGER) 1, n)) {
*info = -6;
} else if (ldvl < 1 || (wants && ldvl < n)) {
*info = -8;
} else if (ldvr < 1 || (wants && ldvr < n)) {
*info = -10;
} else {
//Set M to the number of eigenpairs for which condition numbers
//are required, and test MM.
if (somcon) {
*m = 0;
pair = MFALSE;
for (k = 0; k < n; k++) {
if (pair) {
pair = MFALSE;
} else {
if (k < n) {
if (t[k + 1 + k * ldt] == Zero) {
if (select[k]) {
++(*m);
}
} else {
pair = MTRUE;
if (select[k] || select[k + 1]) {
(*m) = (*m) + 2;
}
}
} else {
if (select[n]) {
++(*m);
}
}
}
}
} else {
(*m) = n;
}
if (mm < (*m)) {
*info = -13;
} else if (ldwork < 1 || (wantsp && ldwork < n)) {
*info = -16;
}
}
if (*info != 0) {
Mxerbla("Rtrsna", -(*info));
return;
}
//Quick return if possible
if (n == 0) {
return;
}
if (n == 1) {
if (somcon) {
if (!select[1]) {
return;
}
}
if (wants) {
s[1] = One;
}
if (wantsp) {
sep[1] = abs(t[ldt + 1]);
}
return;
}
//Get machine constants
eps = Rlamch("P");
smlnum = Rlamch("S") / eps;
bignum = One / smlnum;
//Rlabad(&smlnum, &bignum);
ks = 0;
pair = MFALSE;
for (k = 0; k < n; k++) {
//Determine whether T(k,k) begins a 1-by-1 or 2-by-2 block.
if (pair) {
pair = MFALSE;
goto L60;
} else {
if (k < n) {
pair = t[k + 1 + k * ldt] != Zero;
}
}
//Determine whether condition numbers are required for the k-th
//eigenpair.
if (somcon) {
if (pair) {
if (!select[k] && !select[k + 1]) {
goto L60;
}
} else {
if (!select[k]) {
goto L60;
}
}
}
ks++;
if (wants) {
//Compute the reciprocal condition number of the k-th
//eigenvalue.
if (!pair) {
//Real eigenvalue.
prod = Rdot(n, &vr[ks * ldvr + 1], 1, &vl[ks * ldvl + 1], 1);
rnrm = Rnrm2(n, &vr[ks * ldvr + 1], 1);
lnrm = Rnrm2(n, &vl[ks * ldvl + 1], 1);
s[ks] = abs(prod) / (rnrm * lnrm);
} else {
//Complex eigenvalue.
prod1 = Rdot(n, &vr[ks * ldvr + 1], 1, &vl[ks * ldvl + 1], 1);
prod1 = prod1 + Rdot(n, &vr[(ks + 1) * ldvr + 1], 1, &vl[(ks + 1) * ldvl + 1], 1);
prod2 = Rdot(n, &vl[ks * ldvl + 1], 1, &vr[(ks + 1) * ldvr + 1], 1);
prod2 = prod2 - Rdot(n, &vl[(ks + 1) * ldvl + 1], 1, &vr[ks * ldvr + 1], 1);
mtemp1 = Rnrm2(n, &vr[ks * ldvr + 1], 1);
mtemp2 = Rnrm2(n, &vr[(ks + 1) * ldvr + 1], 1);
rnrm = Rlapy2(mtemp1, mtemp2);
mtemp1 = Rnrm2(n, &vl[ks * ldvl + 1], 1);
mtemp2 = Rnrm2(n, &vl[(ks + 1) * ldvl + 1], 1);
lnrm = Rlapy2(mtemp1, mtemp2);
cond = Rlapy2(prod1, prod2) / (rnrm * lnrm);
s[ks] = cond;
s[ks + 1] = cond;
}
}
if (wantsp) {
//Estimate the reciprocal condition number of the k-th
//eigenvector.
//Copy the matrix T to the array WORK and swap the diagonal
//block beginning at T(k,k) to the (1,1) position.
Rlacpy("Full", n, n, &t[0], ldt, &work[0], ldwork);
ifst = k;
ilst = 1;
Rtrexc("No Q", n, &work[0], ldwork, dummy, 1, &ifst, &ilst, &work[(n + 1) * ldwork + 1], &ierr);
if (ierr == 1 || ierr == 2) {
//Could not swap because blocks not well separated
scale = One;
est = bignum;
} else {
//Reordering successful
if (work[ldwork + 2] == Zero) {
//Form C = T22 - lambda*I in WORK(2:N,2:N).
for (i = 1; i < n; i++) {
work[i + i * ldwork] = work[i + i * ldwork] - work[ldwork + 1];
}
n2 = 1;
nn = n - 1;
} else {
/* Triangularize the 2 by 2 block by unitary */
/* transformation U = [ cs i*ss ] */
/* [ i*ss cs ]. */
/* such that the (1,1) position of WORK is complex */
/* eigenvalue lambda with positive imaginary part. (2,2) */
/* position of WORK is the complex eigenvalue lambda */
/* with negative imaginary part. */
mu = sqrt(abs(work[(ldwork << 1) + 1])) * sqrt(abs(work[ldwork + 2]));
delta = Rlapy2(mu, work[ldwork + 2]);
cs = mu / delta;
sn = -work[ldwork + 2] / delta;
/* Form */
/* C' = WORK(2:N,2:N) + i*[rwork(1) ..... rwork(n-1) ] */
/* [ mu ] */
/* [ .. ] */
/* [ .. ] */
/* [ mu ] */
/* where C' is conjugate transpose of complex matrix C, */
/* and RWORK is stored starting in the N+1-st column of */
/* WORK. */
for (j = 3; j <= n; j++) {
work[j * ldwork + 2] = cs * work[j * ldwork + 2];
work[j + j * ldwork] = work[j + j * ldwork] - work[ldwork + 1];
}
work[(ldwork << 1) + 2] = Zero;
work[(n + 1) * ldwork + 1] = mu * Two;
for (i = 1; i < n - 1; i++) {
work[i + (n + 1) * ldwork] = sn * work[(i + 1) * ldwork + 1];
}
n2 = 2;
nn = (n - 1) * 2;
}
//Estimate norm(inv(C'))
est = Zero;
kase = 0;
L50:
Rlacn2(nn, &work[(n + 2) * ldwork + 1], &work[(n + 4) * ldwork + 1], &iwork[1], &est, &kase, isave);
if (kase != 0) {
if (kase == 1) {
if (n2 == 1) {
//Real eigenvalue: solve C'*x = scale*c.
Rlaqtr(MTRUE, MTRUE, n - 1, &work[(ldwork << 1) + 2], ldwork, dummy, dumm, &scale, &work[(n + 4) * ldwork + 1], &work[(n + 6) * ldwork + 1], &ierr);
} else {
//Complex eigenvalue: solve
//C'*(p+iq) = scale*(c+id) in real arithmetic.
Rlaqtr(MTRUE, MFALSE, n - 1, &work[(ldwork << 1) + 2], ldwork, &work[(n +
1) * ldwork + 1], mu, &scale,
&work[(n + 4) * ldwork + 1], &work[(n + 6) * ldwork + 1], &ierr);
}
} else {
if (n2 == 1) {
//Real eigenvalue: solve C*x = scale*c.
Rlaqtr(MFALSE, MTRUE, n - 1, &work[(ldwork << 1) + 2], ldwork, dummy, dumm, &scale, &work[(n + 4) * ldwork + 1], &work[(n + 6) * ldwork + 1], &ierr);
} else {
//Complex eigenvalue: solve
//C*(p+iq) = scale*(c+id) in real arithmetic.
Rlaqtr(MFALSE, MFALSE, n - 1, &work[(ldwork << 1) + 2], ldwork, &work[(n +
1) * ldwork + 1], mu, &scale,
&work[(n + 4) * ldwork + 1], &work[(n + 6) * ldwork + 1], &ierr);
}
}
goto L50;
}
}
sep[ks] = scale / max(est, smlnum);
if (pair) {
sep[ks + 1] = sep[ks];
}
}
if (pair) {
ks++;
}
L60:
;
}
return;
}
|
//--------------------------------------------------------------------------------------------------
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//--------------------------------------------------------------------------------------------------
#include <boost/optional.hpp>
#include "yb/client/yb_table_name.h"
#include "yb/yql/pggate/pggate.h"
#include "yb/yql/pggate/pggate_flags.h"
#include "yb/yql/pggate/pg_memctx.h"
#include "yb/yql/pggate/pg_ddl.h"
#include "yb/yql/pggate/pg_insert.h"
#include "yb/yql/pggate/pg_update.h"
#include "yb/yql/pggate/pg_delete.h"
#include "yb/yql/pggate/pg_truncate_colocated.h"
#include "yb/yql/pggate/pg_select.h"
#include "yb/yql/pggate/pg_txn_manager.h"
#include "yb/yql/pggate/ybc_pggate.h"
#include "yb/util/flag_tags.h"
#include "yb/client/client_fwd.h"
#include "yb/client/client_utils.h"
#include "yb/rpc/messenger.h"
#include "yb/rpc/secure_stream.h"
#include "yb/server/secure.h"
#include "yb/tserver/tserver_shared_mem.h"
DECLARE_string(rpc_bind_addresses);
DECLARE_bool(use_node_to_node_encryption);
DECLARE_string(certs_dir);
namespace yb {
namespace pggate {
namespace {
CHECKED_STATUS AddColumn(PgCreateTable* pg_stmt, const char *attr_name, int attr_num,
const YBCPgTypeEntity *attr_type, bool is_hash, bool is_range,
bool is_desc, bool is_nulls_first) {
using SortingType = ColumnSchema::SortingType;
SortingType sorting_type = SortingType::kNotSpecified;
if (!is_hash && is_range) {
if (is_desc) {
sorting_type = is_nulls_first ? SortingType::kDescending : SortingType::kDescendingNullsLast;
} else {
sorting_type = is_nulls_first ? SortingType::kAscending : SortingType::kAscendingNullsLast;
}
}
return pg_stmt->AddColumn(attr_name, attr_num, attr_type, is_hash, is_range, sorting_type);
}
Result<PgApiImpl::MessengerHolder> BuildMessenger(
const string& client_name,
int32_t num_reactors,
const scoped_refptr<MetricEntity>& metric_entity,
const std::shared_ptr<MemTracker>& parent_mem_tracker) {
std::unique_ptr<rpc::SecureContext> secure_context;
if (FLAGS_use_node_to_node_encryption) {
secure_context = VERIFY_RESULT(server::CreateSecureContext(FLAGS_certs_dir));
}
auto messenger = VERIFY_RESULT(client::CreateClientMessenger(
client_name, num_reactors, metric_entity, parent_mem_tracker, secure_context.get()));
return PgApiImpl::MessengerHolder{std::move(secure_context), std::move(messenger)};
}
std::unique_ptr<tserver::TServerSharedObject> InitTServerSharedObject() {
// Do not use shared memory in initdb or if explicity set to be ignored.
if (YBCIsInitDbModeEnvVarSet() || FLAGS_TEST_pggate_ignore_tserver_shm ||
FLAGS_pggate_tserver_shm_fd == -1) {
return nullptr;
}
return std::make_unique<tserver::TServerSharedObject>(CHECK_RESULT(
tserver::TServerSharedObject::OpenReadOnly(FLAGS_pggate_tserver_shm_fd)));
}
} // namespace
using std::make_shared;
using client::YBSession;
//--------------------------------------------------------------------------------------------------
PggateOptions::PggateOptions() {
server_type = "tserver";
rpc_opts.default_port = kDefaultPort;
rpc_opts.connection_keepalive_time_ms = FLAGS_pgsql_rpc_keepalive_time_ms;
if (FLAGS_pggate_proxy_bind_address.empty()) {
HostPort host_port;
CHECK_OK(host_port.ParseString(FLAGS_rpc_bind_addresses, 0));
host_port.set_port(PggateOptions::kDefaultPort);
FLAGS_pggate_proxy_bind_address = host_port.ToString();
LOG(INFO) << "Reset YSQL bind address to " << FLAGS_pggate_proxy_bind_address;
}
rpc_opts.rpc_bind_addresses = FLAGS_pggate_proxy_bind_address;
master_addresses_flag = FLAGS_pggate_master_addresses;
server::MasterAddresses master_addresses;
// TODO: we might have to allow setting master_replication_factor similarly to how it is done
// in tserver to support master auto-discovery on Kubernetes.
CHECK_OK(server::DetermineMasterAddresses(
"pggate_master_addresses", master_addresses_flag, /* master_replication_factor */ 0,
&master_addresses, &master_addresses_flag));
SetMasterAddresses(make_shared<server::MasterAddresses>(std::move(master_addresses)));
}
//--------------------------------------------------------------------------------------------------
PgApiImpl::PgApiImpl(const YBCPgTypeEntity *YBCDataTypeArray, int count, YBCPgCallbacks callbacks)
: metric_registry_(new MetricRegistry()),
metric_entity_(METRIC_ENTITY_server.Instantiate(metric_registry_.get(), "yb.pggate")),
mem_tracker_(MemTracker::CreateTracker("PostgreSQL")),
messenger_holder_(CHECK_RESULT(BuildMessenger("pggate_ybclient",
FLAGS_pggate_ybclient_reactor_threads,
metric_entity_,
mem_tracker_))),
async_client_init_(messenger_holder_.messenger.get()->name(),
FLAGS_pggate_ybclient_reactor_threads,
FLAGS_pggate_rpc_timeout_secs,
"" /* tserver_uuid */,
&pggate_options_,
metric_entity_,
mem_tracker_,
messenger_holder_.messenger.get()),
clock_(new server::HybridClock()),
tserver_shared_object_(InitTServerSharedObject()),
pg_txn_manager_(new PgTxnManager(&async_client_init_, clock_, tserver_shared_object_.get())),
pg_callbacks_(callbacks) {
CHECK_OK(clock_->Init());
// Setup type mapping.
for (int idx = 0; idx < count; idx++) {
const YBCPgTypeEntity *type_entity = &YBCDataTypeArray[idx];
type_map_[type_entity->type_oid] = type_entity;
}
async_client_init_.Start();
}
PgApiImpl::~PgApiImpl() {
messenger_holder_.messenger->Shutdown();
async_client_init_.client()->Shutdown();
}
const YBCPgTypeEntity *PgApiImpl::FindTypeEntity(int type_oid) {
const auto iter = type_map_.find(type_oid);
if (iter != type_map_.end()) {
return iter->second;
}
return nullptr;
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::CreateEnv(PgEnv **pg_env) {
*pg_env = pg_env_.get();
return Status::OK();
}
Status PgApiImpl::DestroyEnv(PgEnv *pg_env) {
pg_env_ = nullptr;
return Status::OK();
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::InitSession(const PgEnv *pg_env,
const string& database_name) {
CHECK(!pg_session_);
auto session = make_scoped_refptr<PgSession>(client(),
database_name,
pg_txn_manager_,
clock_,
tserver_shared_object_.get(),
pg_callbacks_);
if (!database_name.empty()) {
RETURN_NOT_OK(session->ConnectDatabase(database_name));
}
pg_session_.swap(session);
return Status::OK();
}
Status PgApiImpl::InvalidateCache() {
pg_session_->InvalidateCache();
return Status::OK();
}
const bool PgApiImpl::GetDisableTransparentCacheRefreshRetry() {
return FLAGS_TEST_ysql_disable_transparent_cache_refresh_retry;
}
//--------------------------------------------------------------------------------------------------
PgMemctx *PgApiImpl::CreateMemctx() {
// Postgres will create YB Memctx when it first use the Memctx to allocate YugaByte object.
return PgMemctx::Create();
}
Status PgApiImpl::DestroyMemctx(PgMemctx *memctx) {
// Postgres will destroy YB Memctx by releasing the pointer.
return PgMemctx::Destroy(memctx);
}
Status PgApiImpl::ResetMemctx(PgMemctx *memctx) {
// Postgres reset YB Memctx when clearing a context content without clearing its nested context.
return PgMemctx::Reset(memctx);
}
// TODO(neil) Use Arena in the future.
// - PgStatement should have been declared as derived class of "MCBase".
// - All objects of PgStatement's derived class should be allocated by YbPgMemctx::Arena.
// - We cannot use Arena yet because quite a large number of YugaByte objects are being referenced
// from other layers. Those added code violated the original design as they assume ScopedPtr
// instead of memory pool is being used. This mess should be cleaned up later.
//
// For now, statements is allocated as ScopedPtr and cached in the memory context. The statements
// would then be destructed when the context is destroyed and all other references are also cleared.
Status PgApiImpl::AddToCurrentPgMemctx(const PgStatement::ScopedRefPtr &stmt,
PgStatement **handle) {
pg_callbacks_.GetCurrentYbMemctx()->Cache(stmt);
*handle = stmt.get();
return Status::OK();
}
// TODO(neil) Most like we don't need table_desc. If we do need it, use Arena here.
// - PgTableDesc should have been declared as derived class of "MCBase".
// - PgTableDesc objects should be allocated by YbPgMemctx::Arena.
//
// For now, table_desc is allocated as ScopedPtr and cached in the memory context. The table_desc
// would then be destructed when the context is destroyed.
Status PgApiImpl::AddToCurrentPgMemctx(size_t table_desc_id,
const PgTableDesc::ScopedRefPtr &table_desc) {
pg_callbacks_.GetCurrentYbMemctx()->Cache(table_desc_id, table_desc);
return Status::OK();
}
Status PgApiImpl::GetTabledescFromCurrentPgMemctx(size_t table_desc_id, PgTableDesc **handle) {
pg_callbacks_.GetCurrentYbMemctx()->GetCache(table_desc_id, handle);
return Status::OK();
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::CreateSequencesDataTable() {
return pg_session_->CreateSequencesDataTable();
}
Status PgApiImpl::InsertSequenceTuple(int64_t db_oid,
int64_t seq_oid,
uint64_t ysql_catalog_version,
int64_t last_val,
bool is_called) {
return pg_session_->InsertSequenceTuple(
db_oid, seq_oid, ysql_catalog_version, last_val, is_called);
}
Status PgApiImpl::UpdateSequenceTupleConditionally(int64_t db_oid,
int64_t seq_oid,
uint64_t ysql_catalog_version,
int64_t last_val,
bool is_called,
int64_t expected_last_val,
bool expected_is_called,
bool *skipped) {
return pg_session_->UpdateSequenceTuple(
db_oid, seq_oid, ysql_catalog_version, last_val, is_called,
expected_last_val, expected_is_called, skipped);
}
Status PgApiImpl::UpdateSequenceTuple(int64_t db_oid,
int64_t seq_oid,
uint64_t ysql_catalog_version,
int64_t last_val,
bool is_called,
bool* skipped) {
return pg_session_->UpdateSequenceTuple(
db_oid, seq_oid, ysql_catalog_version, last_val,
is_called, boost::none, boost::none, skipped);
}
Status PgApiImpl::ReadSequenceTuple(int64_t db_oid,
int64_t seq_oid,
uint64_t ysql_catalog_version,
int64_t *last_val,
bool *is_called) {
return pg_session_->ReadSequenceTuple(db_oid, seq_oid, ysql_catalog_version, last_val, is_called);
}
Status PgApiImpl::DeleteSequenceTuple(int64_t db_oid, int64_t seq_oid) {
return pg_session_->DeleteSequenceTuple(db_oid, seq_oid);
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::ClearBinds(PgStatement *handle) {
return handle->ClearBinds();
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::ConnectDatabase(const char *database_name) {
return pg_session_->ConnectDatabase(database_name);
}
Status PgApiImpl::IsDatabaseColocated(const PgOid database_oid, bool *colocated) {
return pg_session_->IsDatabaseColocated(database_oid, colocated);
}
Status PgApiImpl::NewCreateDatabase(const char *database_name,
const PgOid database_oid,
const PgOid source_database_oid,
const PgOid next_oid,
const bool colocated,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgCreateDatabase>(pg_session_, database_name, database_oid,
source_database_oid, next_oid, colocated);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecCreateDatabase(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_DATABASE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgCreateDatabase*>(handle)->Exec();
}
Status PgApiImpl::NewDropDatabase(const char *database_name,
PgOid database_oid,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgDropDatabase>(pg_session_, database_name, database_oid);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecDropDatabase(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_DATABASE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgDropDatabase*>(handle)->Exec();
}
Status PgApiImpl::NewAlterDatabase(const char *database_name,
PgOid database_oid,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgAlterDatabase>(pg_session_, database_name, database_oid);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::AlterDatabaseRenameDatabase(PgStatement *handle, const char *newname) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_DATABASE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgAlterDatabase*>(handle)->RenameDatabase(newname);
}
Status PgApiImpl::ExecAlterDatabase(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_DATABASE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgAlterDatabase*>(handle)->Exec();
}
Status PgApiImpl::ReserveOids(const PgOid database_oid,
const PgOid next_oid,
const uint32_t count,
PgOid *begin_oid,
PgOid *end_oid) {
return pg_session_->ReserveOids(database_oid, next_oid, count, begin_oid, end_oid);
}
Status PgApiImpl::GetCatalogMasterVersion(uint64_t *version) {
return pg_session_->GetCatalogMasterVersion(version);
}
Result<PgTableDesc::ScopedRefPtr> PgApiImpl::LoadTable(const PgObjectId& table_id) {
return pg_session_->LoadTable(table_id);
}
void PgApiImpl::InvalidateTableCache(const PgObjectId& table_id) {
pg_session_->InvalidateTableCache(table_id);
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::NewCreateTablegroup(const char *database_name,
const PgOid database_oid,
const PgOid tablegroup_oid,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgCreateTablegroup>(pg_session_, database_name,
database_oid, tablegroup_oid);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecCreateTablegroup(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLEGROUP)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgCreateTablegroup*>(handle)->Exec();
}
Status PgApiImpl::NewDropTablegroup(const PgOid database_oid,
const PgOid tablegroup_oid,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgDropTablegroup>(pg_session_, database_oid, tablegroup_oid);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecDropTablegroup(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_TABLEGROUP)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgDropTablegroup*>(handle)->Exec();
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::NewCreateTable(const char *database_name,
const char *schema_name,
const char *table_name,
const PgObjectId& table_id,
bool is_shared_table,
bool if_not_exist,
bool add_primary_key,
const bool colocated,
const PgObjectId& tablegroup_oid,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgCreateTable>(
pg_session_, database_name, schema_name, table_name,
table_id, is_shared_table, if_not_exist, add_primary_key, colocated, tablegroup_oid);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::CreateTableAddColumn(PgStatement *handle, const char *attr_name, int attr_num,
const YBCPgTypeEntity *attr_type,
bool is_hash, bool is_range,
bool is_desc, bool is_nulls_first) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return AddColumn(down_cast<PgCreateTable*>(handle), attr_name, attr_num, attr_type,
is_hash, is_range, is_desc, is_nulls_first);
}
Status PgApiImpl::CreateTableSetNumTablets(PgStatement *handle, int32_t num_tablets) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgCreateTable*>(handle)->SetNumTablets(num_tablets);
}
Status PgApiImpl::CreateTableAddSplitRow(PgStatement *handle, int num_cols,
YBCPgTypeEntity **types, uint64_t *data) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgCreateTable*>(handle)->AddSplitRow(num_cols, types, data);
}
Status PgApiImpl::ExecCreateTable(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgCreateTable*>(handle)->Exec();
}
Status PgApiImpl::NewAlterTable(const PgObjectId& table_id,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgAlterTable>(pg_session_, table_id);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::AlterTableAddColumn(PgStatement *handle, const char *name,
int order, const YBCPgTypeEntity *attr_type,
bool is_not_null) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
return pg_stmt->AddColumn(name, attr_type, order, is_not_null);
}
Status PgApiImpl::AlterTableRenameColumn(PgStatement *handle, const char *oldname,
const char *newname) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
return pg_stmt->RenameColumn(oldname, newname);
}
Status PgApiImpl::AlterTableDropColumn(PgStatement *handle, const char *name) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
return pg_stmt->DropColumn(name);
}
Status PgApiImpl::AlterTableRenameTable(PgStatement *handle, const char *db_name,
const char *newname) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
return pg_stmt->RenameTable(db_name, newname);
}
Status PgApiImpl::ExecAlterTable(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
return pg_stmt->Exec();
}
Status PgApiImpl::NewDropTable(const PgObjectId& table_id,
bool if_exist,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgDropTable>(pg_session_, table_id, if_exist);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecDropTable(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgDropTable*>(handle)->Exec();
}
Status PgApiImpl::NewTruncateTable(const PgObjectId& table_id,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgTruncateTable>(pg_session_, table_id);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecTruncateTable(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_TRUNCATE_TABLE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgTruncateTable*>(handle)->Exec();
}
Status PgApiImpl::GetTableDesc(const PgObjectId& table_id,
PgTableDesc **handle) {
// First read from memory context.
size_t hash_id = hash_value(table_id);
RETURN_NOT_OK(GetTabledescFromCurrentPgMemctx(hash_id, handle));
// Read from environment.
if (*handle == nullptr) {
auto result = pg_session_->LoadTable(table_id);
RETURN_NOT_OK(result);
RETURN_NOT_OK(AddToCurrentPgMemctx(hash_id, *result));
*handle = result->get();
}
return Status::OK();
}
Status PgApiImpl::GetColumnInfo(YBCPgTableDesc table_desc,
int16_t attr_number,
bool *is_primary,
bool *is_hash) {
return table_desc->GetColumnInfo(attr_number, is_primary, is_hash);
}
Status PgApiImpl::DmlModifiesRow(PgStatement *handle, bool *modifies_row) {
if (!handle) {
return STATUS(InvalidArgument, "Invalid statement handle");
}
*modifies_row = false;
switch (handle->stmt_op()) {
case StmtOp::STMT_UPDATE:
case StmtOp::STMT_DELETE:
*modifies_row = true;
break;
default:
break;
}
return Status::OK();
}
Status PgApiImpl::SetIsSysCatalogVersionChange(PgStatement *handle) {
if (!handle) {
return STATUS(InvalidArgument, "Invalid statement handle");
}
switch (handle->stmt_op()) {
case StmtOp::STMT_UPDATE:
case StmtOp::STMT_DELETE:
case StmtOp::STMT_INSERT:
down_cast<PgDmlWrite *>(handle)->SetIsSystemCatalogChange();
return Status::OK();
default:
break;
}
return STATUS(InvalidArgument, "Invalid statement handle");
}
Status PgApiImpl::SetCatalogCacheVersion(PgStatement *handle, uint64_t catalog_cache_version) {
if (!handle) {
return STATUS(InvalidArgument, "Invalid statement handle");
}
switch (handle->stmt_op()) {
case StmtOp::STMT_SELECT:
case StmtOp::STMT_INSERT:
case StmtOp::STMT_UPDATE:
case StmtOp::STMT_DELETE:
down_cast<PgDml *>(handle)->SetCatalogCacheVersion(catalog_cache_version);
return Status::OK();
default:
break;
}
return STATUS(InvalidArgument, "Invalid statement handle");
}
//--------------------------------------------------------------------------------------------------
Status PgApiImpl::NewCreateIndex(const char *database_name,
const char *schema_name,
const char *index_name,
const PgObjectId& index_id,
const PgObjectId& base_table_id,
bool is_shared_index,
bool is_unique_index,
const bool skip_index_backfill,
bool if_not_exist,
const PgObjectId& tablegroup_oid,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgCreateIndex>(
pg_session_, database_name, schema_name, index_name, index_id, base_table_id,
is_shared_index, is_unique_index, skip_index_backfill, if_not_exist, tablegroup_oid);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::CreateIndexAddColumn(PgStatement *handle, const char *attr_name, int attr_num,
const YBCPgTypeEntity *attr_type,
bool is_hash, bool is_range,
bool is_desc, bool is_nulls_first) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_INDEX)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return AddColumn(down_cast<PgCreateIndex*>(handle), attr_name, attr_num, attr_type,
is_hash, is_range, is_desc, is_nulls_first);
}
Status PgApiImpl::CreateIndexSetNumTablets(PgStatement *handle, int32_t num_tablets) {
SCHECK(PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_INDEX),
InvalidArgument,
"Invalid statement handle");
return down_cast<PgCreateIndex*>(handle)->SetNumTablets(num_tablets);
}
Status PgApiImpl::CreateIndexAddSplitRow(PgStatement *handle, int num_cols,
YBCPgTypeEntity **types, uint64_t *data) {
SCHECK(PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_INDEX),
InvalidArgument,
"Invalid statement handle");
return down_cast<PgCreateIndex*>(handle)->AddSplitRow(num_cols, types, data);
}
Status PgApiImpl::ExecCreateIndex(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_INDEX)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgCreateIndex*>(handle)->Exec();
}
Status PgApiImpl::NewDropIndex(const PgObjectId& index_id,
bool if_exist,
PgStatement **handle) {
auto stmt = make_scoped_refptr<PgDropIndex>(pg_session_, index_id, if_exist);
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecDropIndex(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_INDEX)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgDropIndex*>(handle)->Exec();
}
Result<IndexPermissions> PgApiImpl::WaitUntilIndexPermissionsAtLeast(
const PgObjectId& table_id,
const PgObjectId& index_id,
const IndexPermissions& target_index_permissions) {
return pg_session_->WaitUntilIndexPermissionsAtLeast(
table_id,
index_id,
target_index_permissions);
}
Status PgApiImpl::AsyncUpdateIndexPermissions(const PgObjectId& indexed_table_id) {
return pg_session_->AsyncUpdateIndexPermissions(indexed_table_id);
}
//--------------------------------------------------------------------------------------------------
// DML Statment Support.
//--------------------------------------------------------------------------------------------------
// Binding -----------------------------------------------------------------------------------------
Status PgApiImpl::DmlAppendTarget(PgStatement *handle, PgExpr *target) {
return down_cast<PgDml*>(handle)->AppendTarget(target);
}
Status PgApiImpl::DmlBindColumn(PgStatement *handle, int attr_num, PgExpr *attr_value) {
return down_cast<PgDml*>(handle)->BindColumn(attr_num, attr_value);
}
Status PgApiImpl::DmlBindColumnCondEq(PgStatement *handle, int attr_num, PgExpr *attr_value) {
return down_cast<PgDmlRead*>(handle)->BindColumnCondEq(attr_num, attr_value);
}
Status PgApiImpl::DmlBindColumnCondBetween(PgStatement *handle, int attr_num, PgExpr *attr_value,
PgExpr *attr_value_end) {
return down_cast<PgDmlRead*>(handle)->BindColumnCondBetween(attr_num, attr_value, attr_value_end);
}
Status PgApiImpl::DmlBindColumnCondIn(PgStatement *handle, int attr_num, int n_attr_values,
PgExpr **attr_values) {
return down_cast<PgDmlRead*>(handle)->BindColumnCondIn(attr_num, n_attr_values, attr_values);
}
Status PgApiImpl::DmlBindTable(PgStatement *handle) {
return down_cast<PgDml*>(handle)->BindTable();
}
CHECKED_STATUS PgApiImpl::DmlAssignColumn(PgStatement *handle, int attr_num, PgExpr *attr_value) {
return down_cast<PgDml*>(handle)->AssignColumn(attr_num, attr_value);
}
Status PgApiImpl::DmlFetch(PgStatement *handle, int32_t natts, uint64_t *values, bool *isnulls,
PgSysColumns *syscols, bool *has_data) {
return down_cast<PgDml*>(handle)->Fetch(natts, values, isnulls, syscols, has_data);
}
Status PgApiImpl::DmlBuildYBTupleId(PgStatement *handle, const PgAttrValueDescriptor *attrs,
int32_t nattrs, uint64_t *ybctid) {
const string id = VERIFY_RESULT(down_cast<PgDml*>(handle)->BuildYBTupleId(attrs, nattrs));
const YBCPgTypeEntity *type_entity = FindTypeEntity(kPgByteArrayOid);
*ybctid = type_entity->yb_to_datum(id.data(), id.size(), nullptr /* type_attrs */);
return Status::OK();
}
void PgApiImpl::StartOperationsBuffering() {
pg_session_->StartOperationsBuffering();
}
Status PgApiImpl::StopOperationsBuffering() {
return pg_session_->StopOperationsBuffering();
}
Status PgApiImpl::ResetOperationsBuffering() {
return pg_session_->ResetOperationsBuffering();
}
Status PgApiImpl::FlushBufferedOperations() {
return pg_session_->FlushBufferedOperations();
}
void PgApiImpl::DropBufferedOperations() {
pg_session_->DropBufferedOperations();
}
Status PgApiImpl::DmlExecWriteOp(PgStatement *handle, int32_t *rows_affected_count) {
switch (handle->stmt_op()) {
case StmtOp::STMT_INSERT:
case StmtOp::STMT_UPDATE:
case StmtOp::STMT_DELETE:
case StmtOp::STMT_TRUNCATE:
{
auto dml_write = down_cast<PgDmlWrite *>(handle);
RETURN_NOT_OK(dml_write->Exec(rows_affected_count != nullptr /* force_non_bufferable */));
if (rows_affected_count) {
*rows_affected_count = dml_write->GetRowsAffectedCount();
}
return Status::OK();
}
default:
break;
}
return STATUS(InvalidArgument, "Invalid statement handle");
}
// Insert ------------------------------------------------------------------------------------------
Status PgApiImpl::NewInsert(const PgObjectId& table_id,
const bool is_single_row_txn,
PgStatement **handle) {
*handle = nullptr;
auto stmt = make_scoped_refptr<PgInsert>(pg_session_, table_id, is_single_row_txn);
RETURN_NOT_OK(stmt->Prepare());
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecInsert(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_INSERT)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgInsert*>(handle)->Exec();
}
Status PgApiImpl::InsertStmtSetUpsertMode(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_INSERT)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
down_cast<PgInsert*>(handle)->SetUpsertMode();
return Status::OK();
}
Status PgApiImpl::InsertStmtSetWriteTime(PgStatement *handle, const HybridTime write_time) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_INSERT)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
RETURN_NOT_OK(down_cast<PgInsert*>(handle)->SetWriteTime(write_time));
return Status::OK();
}
// Update ------------------------------------------------------------------------------------------
Status PgApiImpl::NewUpdate(const PgObjectId& table_id,
const bool is_single_row_txn,
PgStatement **handle) {
*handle = nullptr;
auto stmt = make_scoped_refptr<PgUpdate>(pg_session_, table_id, is_single_row_txn);
RETURN_NOT_OK(stmt->Prepare());
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecUpdate(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_UPDATE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgUpdate*>(handle)->Exec();
}
// Delete ------------------------------------------------------------------------------------------
Status PgApiImpl::NewDelete(const PgObjectId& table_id,
const bool is_single_row_txn,
PgStatement **handle) {
*handle = nullptr;
auto stmt = make_scoped_refptr<PgDelete>(pg_session_, table_id, is_single_row_txn);
RETURN_NOT_OK(stmt->Prepare());
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecDelete(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DELETE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgDelete*>(handle)->Exec();
}
// Colocated Truncate ------------------------------------------------------------------------------
Status PgApiImpl::NewTruncateColocated(const PgObjectId& table_id,
const bool is_single_row_txn,
PgStatement **handle) {
*handle = nullptr;
auto stmt = make_scoped_refptr<PgTruncateColocated>(pg_session_, table_id, is_single_row_txn);
RETURN_NOT_OK(stmt->Prepare());
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::ExecTruncateColocated(PgStatement *handle) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_TRUNCATE)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgTruncateColocated*>(handle)->Exec();
}
// Select ------------------------------------------------------------------------------------------
Status PgApiImpl::NewSelect(const PgObjectId& table_id,
const PgObjectId& index_id,
const PgPrepareParameters *prepare_params,
PgStatement **handle) {
// Scenarios:
// - Sequential Scan: PgSelect to read from table_id.
// - Primary Scan: PgSelect from table_id. YugaByte does not have separate table for primary key.
// - Index-Only-Scan: PgSelectIndex directly from secondary index_id.
// - IndexScan: Use PgSelectIndex to read from index_id and then PgSelect to read from table_id.
// Note that for SysTable, only one request is send for both table_id and index_id.
*handle = nullptr;
PgDmlRead::ScopedRefPtr stmt;
if (prepare_params && prepare_params->index_only_scan && prepare_params->use_secondary_index) {
if (!index_id.IsValid()) {
return STATUS(InvalidArgument, "Cannot run query with invalid index ID");
}
stmt = make_scoped_refptr<PgSelectIndex>(pg_session_, table_id, index_id, prepare_params);
} else {
// For IndexScan PgSelect processing will create subquery PgSelectIndex.
stmt = make_scoped_refptr<PgSelect>(pg_session_, table_id, index_id, prepare_params);
}
RETURN_NOT_OK(stmt->Prepare());
RETURN_NOT_OK(AddToCurrentPgMemctx(stmt, handle));
return Status::OK();
}
Status PgApiImpl::SetForwardScan(PgStatement *handle, bool is_forward_scan) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_SELECT)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
down_cast<PgDmlRead*>(handle)->SetForwardScan(is_forward_scan);
return Status::OK();
}
Status PgApiImpl::ExecSelect(PgStatement *handle, const PgExecParameters *exec_params) {
if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_SELECT)) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
return down_cast<PgDmlRead*>(handle)->Exec(exec_params);
}
//--------------------------------------------------------------------------------------------------
// Expressions.
//--------------------------------------------------------------------------------------------------
// Column references -------------------------------------------------------------------------------
Status PgApiImpl::NewColumnRef(PgStatement *stmt, int attr_num, const PgTypeEntity *type_entity,
const PgTypeAttrs *type_attrs, PgExpr **expr_handle) {
if (!stmt) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgColumnRef::SharedPtr colref = make_shared<PgColumnRef>(attr_num, type_entity, type_attrs);
stmt->AddExpr(colref);
*expr_handle = colref.get();
return Status::OK();
}
// Constant ----------------------------------------------------------------------------------------
Status PgApiImpl::NewConstant(YBCPgStatement stmt, const YBCPgTypeEntity *type_entity,
uint64_t datum, bool is_null, YBCPgExpr *expr_handle) {
if (!stmt) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgExpr::SharedPtr pg_const = make_shared<PgConstant>(type_entity, datum, is_null);
stmt->AddExpr(pg_const);
*expr_handle = pg_const.get();
return Status::OK();
}
Status PgApiImpl::NewConstantOp(YBCPgStatement stmt, const YBCPgTypeEntity *type_entity,
uint64_t datum, bool is_null, YBCPgExpr *expr_handle, bool is_gt) {
if (!stmt) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
PgExpr::SharedPtr pg_const = make_shared<PgConstant>(type_entity, datum, is_null,
is_gt ? PgExpr::Opcode::PG_EXPR_GT : PgExpr::Opcode::PG_EXPR_LT);
stmt->AddExpr(pg_const);
*expr_handle = pg_const.get();
return Status::OK();
}
// Text constant -----------------------------------------------------------------------------------
Status PgApiImpl::UpdateConstant(PgExpr *expr, const char *value, bool is_null) {
if (expr->opcode() != PgExpr::Opcode::PG_EXPR_CONSTANT) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid expression handle for constant");
}
down_cast<PgConstant*>(expr)->UpdateConstant(value, is_null);
return Status::OK();
}
Status PgApiImpl::UpdateConstant(PgExpr *expr, const void *value, int64_t bytes, bool is_null) {
if (expr->opcode() != PgExpr::Opcode::PG_EXPR_CONSTANT) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid expression handle for constant");
}
down_cast<PgConstant*>(expr)->UpdateConstant(value, bytes, is_null);
return Status::OK();
}
// Text constant -----------------------------------------------------------------------------------
Status PgApiImpl::NewOperator(PgStatement *stmt, const char *opname,
const YBCPgTypeEntity *type_entity,
PgExpr **op_handle) {
if (!stmt) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid statement handle");
}
RETURN_NOT_OK(PgExpr::CheckOperatorName(opname));
// Create operator.
PgExpr::SharedPtr pg_op = make_shared<PgOperator>(opname, type_entity);
stmt->AddExpr(pg_op);
*op_handle = pg_op.get();
return Status::OK();
}
Status PgApiImpl::OperatorAppendArg(PgExpr *op_handle, PgExpr *arg) {
if (!op_handle || !arg) {
// Invalid handle.
return STATUS(InvalidArgument, "Invalid expression handle");
}
down_cast<PgOperator*>(op_handle)->AppendArg(arg);
return Status::OK();
}
Result<bool> PgApiImpl::IsInitDbDone() {
return pg_session_->IsInitDbDone();
}
Result<uint64_t> PgApiImpl::GetSharedCatalogVersion() {
return pg_session_->GetSharedCatalogVersion();
}
// Transaction Control -----------------------------------------------------------------------------
Status PgApiImpl::BeginTransaction() {
pg_session_->InvalidateForeignKeyReferenceCache();
return pg_txn_manager_->BeginTransaction();
}
Status PgApiImpl::RestartTransaction() {
pg_session_->InvalidateForeignKeyReferenceCache();
return pg_txn_manager_->RestartTransaction();
}
Status PgApiImpl::CommitTransaction() {
pg_session_->InvalidateForeignKeyReferenceCache();
return pg_txn_manager_->CommitTransaction();
}
Status PgApiImpl::AbortTransaction() {
pg_session_->InvalidateForeignKeyReferenceCache();
return pg_txn_manager_->AbortTransaction();
}
Status PgApiImpl::SetTransactionIsolationLevel(int isolation) {
return pg_txn_manager_->SetIsolationLevel(isolation);
}
Status PgApiImpl::SetTransactionReadOnly(bool read_only) {
return pg_txn_manager_->SetReadOnly(read_only);
}
Status PgApiImpl::SetTransactionDeferrable(bool deferrable) {
return pg_txn_manager_->SetDeferrable(deferrable);
}
Status PgApiImpl::EnterSeparateDdlTxnMode() {
// Flush all buffered operations as ddl txn use its own transaction session.
RETURN_NOT_OK(pg_session_->FlushBufferedOperations());
return pg_txn_manager_->EnterSeparateDdlTxnMode();
}
Status PgApiImpl::ExitSeparateDdlTxnMode(bool success) {
// Flush all buffered operations as ddl txn use its own transaction session.
if (success) {
RETURN_NOT_OK(pg_session_->FlushBufferedOperations());
} else {
pg_session_->DropBufferedOperations();
}
return pg_txn_manager_->ExitSeparateDdlTxnMode(success);
}
bool PgApiImpl::ForeignKeyReferenceExists(YBCPgOid table_id, std::string&& ybctid) {
return pg_session_->ForeignKeyReferenceExists(table_id, std::move(ybctid));
}
Status PgApiImpl::CacheForeignKeyReference(YBCPgOid table_id, std::string&& ybctid) {
return pg_session_->CacheForeignKeyReference(table_id, std::move(ybctid));
}
Status PgApiImpl::DeleteForeignKeyReference(YBCPgOid table_id, std::string&& ybctid) {
return pg_session_->DeleteForeignKeyReference(table_id, std::move(ybctid));
}
void PgApiImpl::ClearForeignKeyReferenceCache() {
pg_session_->InvalidateForeignKeyReferenceCache();
}
void PgApiImpl::SetTimeout(const int timeout_ms) {
pg_session_->SetTimeout(timeout_ms);
}
} // namespace pggate
} // namespace yb
|
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/oos/model/DeleteSecretParameterResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Oos;
using namespace AlibabaCloud::Oos::Model;
DeleteSecretParameterResult::DeleteSecretParameterResult() :
ServiceResult()
{}
DeleteSecretParameterResult::DeleteSecretParameterResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DeleteSecretParameterResult::~DeleteSecretParameterResult()
{}
void DeleteSecretParameterResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
}
|
// -*- C++ -*-
/**
* @file union_receiver_exec.cpp
* @author Marcel Smit
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
//@@{__RIDL_REGEN_MARKER__} - HEADER_END : union_receiver_impl.cpp[Header]
#include "union_receiver_exec.h"
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl[user_includes]
#include "dds4ccm/tests/common/dds4ccm_test_utils.h"
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl[user_includes]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl[user_global_impl]
// Your declarations here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl[user_global_impl]
namespace Uni_Receiver_Impl
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl[user_namespace_impl]
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl[user_namespace_impl]
/**
* Facet Executor Implementation Class : info_out_data_listener_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_data_listener_exec_i[ctor]
info_out_data_listener_exec_i::info_out_data_listener_exec_i (
IDL::traits< ::Uni::CCM_Receiver_Context>::ref_type context)
: context_ (std::move (context))
{
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_data_listener_exec_i[ctor]
info_out_data_listener_exec_i::~info_out_data_listener_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_data_listener_exec_i[dtor]
if (!this->handled_assignment_a_)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::~info_out_data_listener_exec_i - "
<< "Assignment A was not handled by the receiver." << std::endl;
}
if (!this->handled_assignment_b_)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::~info_out_data_listener_exec_i - "
<< "Assignment B was not handled by the receiver." << std::endl;
}
if (!this->handled_assignment_c_)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::~info_out_data_listener_exec_i - "
<< "Assignment C was not handled by the receiver." << std::endl;
}
if (!this->handled_assignment_d_)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::~info_out_data_listener_exec_i - "
<< "Assignment D was not handled by the receiver." << std::endl;
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_data_listener_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_data_listener_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_data_listener_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_data_listener_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_data_listener_exec_i[user_private_ops]
/** Operations and attributes from info_out_data_listener */
void
info_out_data_listener_exec_i::on_one_data (
const ::Uni::UnionMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_data_listener_exec_i::on_one_data[_datum_info]
X11_UNUSED_ARG(info);
DDS4CCM_TEST_DEBUG << "info_out_data_listener_exec_i::on_one_data - "
<< "New sample " << datum << std::endl;
switch (datum.a ())
{
case Uni::Assignment::A:
this->handle_assignment_a (datum);
break;
case Uni::Assignment::B:
this->handle_assignment_b (datum);
break;
case Uni::Assignment::C:
this->handle_assignment_c (datum);
break;
case Uni::Assignment::D:
this->handle_assignment_d (datum);
break;
default:
case Uni::Assignment::NONE:
break;
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_data_listener_exec_i::on_one_data[_datum_info]
}
void
info_out_data_listener_exec_i::on_many_data (
const ::Uni::UnionMessageSeq& data,
const ::CCM_DDS::ReadInfoSeq& infos)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_data_listener_exec_i::on_many_data[_data_infos]
X11_UNUSED_ARG(data);
X11_UNUSED_ARG(infos);
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::on_many_data - "
<< "unexpected invocation" << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_data_listener_exec_i::on_many_data[_data_infos]
}
/**
* Facet Executor Implementation Class : info_out_status_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_status_exec_i[ctor]
info_out_status_exec_i::info_out_status_exec_i (
IDL::traits< ::Uni::CCM_Receiver_Context>::ref_type context)
: context_ (std::move (context))
{
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_status_exec_i[ctor]
info_out_status_exec_i::~info_out_status_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_status_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_status_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_status_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_status_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_status_exec_i[user_private_ops]
void
info_out_data_listener_exec_i::handle_assignment_a (const Uni::UnionMessage& msg)
{
this->handled_assignment_a_ = true;
// Empty, uninitialized union
try
{
// default
if (msg.b_03 ().b_03_d () != 0)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_aata_listener_exec_i::handle_assignment_a <b_03> - "
<< "unexpected value for the default member detected. Expected <0> - got <"
<< msg.b_03 ().b_03_d () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_a - "
<< "Caught unexpected BAD_PARAM exception whilst examining <b_03>." << std::endl;
}
try
{
if (msg.d ()._d () != Uni::DataType::dtLong)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_a <d> - "
<< "unexpected value for the discriminator detected. Expected <Uni::DataType::dtLong> "
<< "- got <" << msg.d ()._d () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_a - "
<< "Caught unexpected BAD_PARAM exception whilst examining <d>." << std::endl;
}
}
void
info_out_data_listener_exec_i::handle_assignment_b (const Uni::UnionMessage& msg)
{
this->handled_assignment_b_ = true;
// Initialized default
try
{
// default
if (msg.b_03 ().b_03_d () != 5)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_aata_listener_exec_i::handle_assignment_b <b_03> - "
<< "unexpected value for the default member detected. Expected <5> - got <"
<< msg.b_03 ().b_03_d () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_b - "
<< "Caught unexpected BAD_PARAM exception whilst examining the default member of "
<< "<b_03>." << std::endl;
}
try
{
if (msg.d ()._d () != Uni::DataType::dtLong)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_b <d> - "
<< "unexpected value for the discriminator detected. Expected <Uni::DataType::dtLong> "
<< "- got <" << msg.d ()._d () << ">." << std::endl;
}
if (msg.d ().longData () != 5)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_aata_listener_exec_i::handle_assignment_b <d> - "
<< "unexpected value for longData detected. Expected <5> - got <"
<< msg.d ().longData () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_b - "
<< "Caught unexpected BAD_PARAM exception whilst examining <d>." << std::endl;
}
}
void
info_out_data_listener_exec_i::handle_assignment_c (const Uni::UnionMessage& msg)
{
this->handled_assignment_c_ = true;
// first member of b_03
try
{
if (msg.b_03 ()._d () != 0)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_c <b_03> - "
<< "unexpected value for the discriminator detected. Expected <0> - got <"
<< msg.b_03 ()._d () << ">." << std::endl;
}
if (msg.b_03 ().b_03_1 ().b01_1 () != 5)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_c <b_03> - "
<< "unexpected value for the first member detected. Expected <5> - got <"
<< msg.b_03 ().b_03_1 ().b01_1 () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_c - "
<< "Caught unexpected BAD_PARAM exception whilst examining <b_03>." << std::endl;
}
// first member of d
try
{
if (msg.d ()._d () != Uni::DataType::dtLong)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_c <d> - "
<< "unexpected value for the discriminator detected. Expected <Uni::DataType::dtLong> - got <"
<< msg.d ()._d () << ">." << std::endl;
}
if (msg.d ().longData () != 5)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_c <d> - "
<< "unexpected value for the first member detected. Expected <5> - got <"
<< msg.d ().longData () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_c - "
<< "Caught unexpected BAD_PARAM exception whilst examining <d>." << std::endl;
}
}
void
info_out_data_listener_exec_i::handle_assignment_d (const Uni::UnionMessage& msg)
{
this->handled_assignment_d_ = true;
// last member of b_03
try
{
if (msg.b_03 ()._d () != 4)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_d <b_03> - "
<< "unexpected value for the discriminator detected. Expected <4> - got <"
<< msg.b_03 ()._d () << ">." << std::endl;
}
if (msg.b_03 ().b_03_5 () != "XX")
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_d <b_03> - "
<< "unexpected value for the last member detected. Expected <XX> - got <"
<< msg.b_03 ().b_03_5 () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_d - "
<< "Caught unexpected BAD_PARAM exception whilst examining <b_03>." << std::endl;
}
// last member of d
try
{
if (msg.d ()._d () != Uni::DataType::dtGlobal)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_d <d> - "
<< "unexpected value for the discriminator detected. Expected <Uni::DataType::dtGlobal> - got <"
<< msg.d ()._d () << ">." << std::endl;
}
if (msg.d ().globalData ().x () != 4)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_d <d> - "
<< "unexpected value for the last member detected. Expected <4> - got <"
<< msg.d ().globalData ().x () << ">." << std::endl;
}
}
catch (const CORBA::BAD_PARAM&)
{
DDS4CCM_TEST_ERROR << "ERROR: info_out_data_listener_exec_i::handle_assignment_d - "
<< "Caught unexpected BAD_PARAM exception whilst examining <d>." << std::endl;
}
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_status_exec_i[user_private_ops]
/** Operations and attributes from info_out_status */
void
info_out_status_exec_i::on_requested_deadline_missed (
IDL::traits< ::DDS::DataReader>::ref_type the_reader,
const ::DDS::RequestedDeadlineMissedStatus& status)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_status_exec_i::on_requested_deadline_missed[_the_reader_status]
X11_UNUSED_ARG(the_reader);
X11_UNUSED_ARG(status);
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_status_exec_i::on_requested_deadline_missed[_the_reader_status]
}
void
info_out_status_exec_i::on_sample_lost (
IDL::traits< ::DDS::DataReader>::ref_type the_reader,
const ::DDS::SampleLostStatus& status)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::info_out_status_exec_i::on_sample_lost[_the_reader_status]
X11_UNUSED_ARG(the_reader);
X11_UNUSED_ARG(status);
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::info_out_status_exec_i::on_sample_lost[_the_reader_status]
}
/**
* Component Executor Implementation Class : Receiver_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[ctor]
Receiver_exec_i::Receiver_exec_i ()
{
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[ctor]
Receiver_exec_i::~Receiver_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[user_private_ops]
/** Session component operations */
void Receiver_exec_i::configuration_complete ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[configuration_complete]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[configuration_complete]
}
void Receiver_exec_i::ccm_activate ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[ccm_activate]
IDL::traits< ::CCM_DDS::DataListenerControl>::ref_type lc =
this->context_->get_connection_info_out_data_control ();
lc->mode (::CCM_DDS::ListenerMode::ONE_BY_ONE);
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[ccm_activate]
}
void Receiver_exec_i::ccm_passivate ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[ccm_passivate]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[ccm_passivate]
}
void Receiver_exec_i::ccm_remove ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[ccm_remove]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[ccm_remove]
}
IDL::traits< ::Uni::UnionConnector::CCM_Listener>::ref_type
Receiver_exec_i::get_info_out_data_listener ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[get_info_out_data_listener]
if (!this->info_out_data_listener_)
{
this->info_out_data_listener_ = CORBA::make_reference <info_out_data_listener_exec_i> (this->context_);
}
return this->info_out_data_listener_;
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[get_info_out_data_listener]
}
IDL::traits< ::CCM_DDS::CCM_PortStatusListener>::ref_type
Receiver_exec_i::get_info_out_status ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[get_info_out_status]
if (!this->info_out_status_)
{
this->info_out_status_ = CORBA::make_reference <info_out_status_exec_i> (this->context_);
}
return this->info_out_status_;
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[get_info_out_status]
}
/// Operations from Components::SessionComponent
void
Receiver_exec_i::set_session_context (
IDL::traits<Components::SessionContext>::ref_type ctx)
{
// Setting the context of this component.
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl::Receiver_exec_i[set_session_context]
this->context_ = IDL::traits< ::Uni::CCM_Receiver_Context >::narrow (std::move(ctx));
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl::Receiver_exec_i[set_session_context]
}
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl[user_namespace_end_impl]
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl[user_namespace_end_impl]
} // namespace Uni_Receiver_Impl
//@@{__RIDL_REGEN_MARKER__} - BEGIN : Uni_Receiver_Impl[factory]
extern "C" void
create_Uni_Receiver_Impl (
IDL::traits<Components::EnterpriseComponent>::ref_type& component)
{
component = CORBA::make_reference <Uni_Receiver_Impl::Receiver_exec_i> ();
}
//@@{__RIDL_REGEN_MARKER__} - END : Uni_Receiver_Impl[factory]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : union_receiver_impl.cpp[Footer]
// Your footer (code) here
// -*- END -*-
|
/*
* 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.
*/
/*!
* \file src/relay/backend/contrib/libtorch/codegen.cc
* \brief Implementation of libtorch codegen.
*/
#include <ATen/DLConvertor.h>
#include <dlpack/dlpack.h>
#include <torch/csrc/jit/api/compilation_unit.h>
#include <torch/csrc/jit/serialization/import.h>
#include <torch/torch.h>
#include <tvm/relay/attrs/nn.h>
#include <tvm/relay/expr_functor.h>
#include <tvm/relay/op.h>
#include <tvm/relay/transform.h>
#include <tvm/relay/type.h>
#include <tvm/runtime/contrib/libtorch_runtime.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/registry.h>
#include <tvm/tir/op.h>
#include <fstream>
#include <numeric>
#include <sstream>
#include "../../utils.h"
namespace tvm {
namespace relay {
namespace contrib {
using namespace backend;
/*! \brief Attributes of a TorchFunction node */
struct TorchFunctionAttrs : public tvm::AttrsNode<TorchFunctionAttrs> {
std::string serialized_function;
int64_t len;
TVM_DECLARE_ATTRS(TorchFunctionAttrs, "relay.attrs.TorchFunctionAttrs") {
TVM_ATTR_FIELD(serialized_function).set_default("").describe("Function from fn.save(...)");
TVM_ATTR_FIELD(len).set_default(-1).describe("Function from fn.save(...)");
}
};
TVM_REGISTER_NODE_TYPE(TorchFunctionAttrs);
bool TorchOpRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
const TypeReporter& reporter) {
const auto* sfattrs = attrs.as<TorchFunctionAttrs>();
std::stringstream str(sfattrs->serialized_function);
torch::jit::Module mod = torch::jit::load(str);
std::vector<torch::jit::IValue> inputs;
for (int i = 0; i < num_inputs; i++) {
auto* ty = types[i].as<TensorTypeNode>();
ICHECK(ty) << "only accept tensors as inputs";
std::vector<int64_t> shape;
for (const auto& s : ty->shape) {
auto* si = s.as<IntImmNode>();
if (!si) {
return false;
}
shape.push_back(si->value);
}
auto torchScalarType = at::toScalarType(ty->dtype);
inputs.emplace_back(torch::zeros(shape, at::TensorOptions().dtype(torchScalarType)));
}
auto res = mod.forward(inputs);
auto res_t = res.toTensor();
ICHECK((int)types.size() == num_inputs + 1) << "only single output supported";
Array<PrimExpr> res_sizes;
for (int d = 0; d < res_t.dim(); d++) {
res_sizes.push_back(IntImm(DataType::Int(32), res_t.size(d)));
}
reporter->Assign(types[num_inputs], TensorType(res_sizes, DataType(at::getDLDataType(res_t))));
return true;
}
RELAY_REGISTER_OP("torch_op")
.set_support_level(99)
.add_type_rel("TorchOpRel", TorchOpRel)
.set_attrs_type<TorchFunctionAttrs>();
Expr MakeTorchOp(Array<Expr> args, const std::string& serialized_function) {
static const Op& op = Op::Get("torch_op");
auto attrs = make_object<TorchFunctionAttrs>();
attrs->serialized_function = serialized_function;
attrs->len = serialized_function.size();
return Call(op, args, Attrs(attrs), {});
}
TVM_REGISTER_GLOBAL("relay.op._make.torchop").set_body_typed(MakeTorchOp);
/*!
* \brief The external compiler/codegen tool. It takes a Relay expression/module and
* compile it into a runtime module.
*/
runtime::Module TorchCompiler(const ObjectRef& ref) {
ICHECK(ref->IsInstance<FunctionNode>()) << "The input ref is expected to be a Relay function.";
Function func = Downcast<Function>(ref);
std::string func_name = backend::GetExtSymbol(func);
ICHECK(func.defined()) << "Input error: expect a Relay function.";
const auto* call = func->body.as<CallNode>();
ICHECK(call) << "Expected call node\n";
const auto* op_node = call->op.as<OpNode>();
ICHECK(op_node) << "Expect OpNode, but got " << call->op->GetTypeKey();
const auto op_name = GetRef<Op>(op_node)->name;
ICHECK(op_name == "torch_op") << "Unsupported op: " << AsText(call->op, false) << "\n";
const auto* attrs = call->attrs.as<TorchFunctionAttrs>();
return tvm::runtime::contrib::TorchRuntimeCreate(func_name, attrs->serialized_function);
}
TVM_REGISTER_GLOBAL("relay.ext.torch").set_body_typed(TorchCompiler);
} // namespace contrib
} // namespace relay
} // namespace tvm
|
/*
* Copyright 2020 TierIV. 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.
*/
/*
* Copyright 2015-2019 Autoware Foundation. 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 <boost/filesystem.hpp>
#include <ros/ros.h>
#include <map_loader/pointcloud_map_loader_node.h>
namespace fs = boost::filesystem;
int main(int argc, char * argv[])
{
ros::init(argc, argv, "pointcloud_map_loader");
std::vector<std::string> pcd_paths;
for (int i = 1; i < argc; ++i) {
const fs::path arg(argv[i]);
if (!fs::exists(arg)) {
const std::string msg = "invalid path: " + arg.string();
throw std::runtime_error(msg);
}
if (fs::is_regular_file(arg)) {
pcd_paths.push_back(argv[i]);
}
if (fs::is_directory(arg)) {
for (const auto & f : fs::directory_iterator(arg)) {
const auto & p = f.path();
if (!fs::is_regular_file(p)) {
continue;
}
if (p.extension() != ".pcd" && p.extension() != ".PCD") {
continue;
}
pcd_paths.push_back(p.string());
}
}
}
PointCloudMapLoaderNode pointcloud_map_loader_node(pcd_paths);
ros::spin();
return 0;
}
|
// 'AveragePool' implementation in Halide.
#include "common.h"
#include <Halide.h>
using Halide::Expr;
using Halide::Func;
using Halide::Generator;
using Halide::Var;
using Halide::BoundaryConditions::constant_exterior;
using Halide::ConciseCasts::u8_sat;
class AveragePool : public Generator<AveragePool> {
public:
// Unsigned 8-bit input tensor, indexed by depth, x, y, batch.
Input<Buffer<uint8_t>> input_{"input", 4};
// The stride specifies how the input [x, y] are sub-subsampled. For every
// spatial location [x, y] in the output buffer, the input buffer is sampled
// spatially at [x * stride, y * stride]. The caller should ensure that
// [x * stride, y * stride] is a valid spatial location in the input buffer.
// Generally, this means setting the output buffer's [width, height] to be
// the input buffer's [width, height] / stride.
Input<int> stride_{ "stride" };
Input<int> pad_width_{ "pad_width" };
Input<int> pad_height_{ "pad_height" };
Input<int> filter_width_{ "filter_width" };
Input<int> filter_height_{ "filter_height" };
Input<uint8_t> output_min_{ "output_min" };
Input<uint8_t> output_max_{ "output_max" };
Output<Buffer<uint8_t>> output_{"output", 4};
void generate() {
// The algorithm.
// Some free variables, where x and y represent the spatial dimensions.
Var x("x"), y("y"), depth("depth"), batch("batch");
// Add a zero boundary condition to x and y dimensions of the input.
Func input_bounded = constant_exterior(input_, 0,
{ { Expr(), Expr() },
{ 0, input_.dim(1).extent() },
{ 0, input_.dim(2).extent() },
{ Expr(), Expr() } });
// Shift the input spatially in [x, y] by -[pad_width, pad_height].
Func shifted_input_bounded("shifted_input_bounded");
shifted_input_bounded(depth, x, y, batch) =
input_bounded(depth, x - pad_width_, y - pad_height_, batch);
Func sum("sum");
RDom filter_dom(0, filter_width_, 0, filter_height_);
sum(depth, x, y, batch) += (cast<int32_t>(select(
stride_ == 1,
shifted_input_bounded(depth, x + filter_dom.x, y + filter_dom.y, batch),
shifted_input_bounded(depth, x * stride_ + filter_dom.x,
y * stride_ + filter_dom.y, batch))));
Expr in_x_origin = x * stride_ - pad_width_;
Expr x_start = max(0, -in_x_origin);
Expr x_end = min(filter_width_, input_.dim(1).extent() - in_x_origin);
Expr in_y_origin = y * stride_ - pad_height_;
Expr y_start = max(0, -in_y_origin);
Expr y_end = min(filter_height_, input_.dim(2).extent() - in_y_origin);
Expr filter_count = (x_end - x_start) * (y_end - y_start);
Func average("average");
// We add filter_count / 2 before dividing by filter_count to round the
// result.
average(depth, x, y, batch) =
(sum(depth, x, y, batch) + filter_count / 2) / filter_count;
// Saturate and narrow the output.
output_(depth, x, y, batch) =
min(output_max_, max(output_min_, u8_sat(average(depth, x, y, batch))));
bool use_hexagon =
get_target().features_any_of({ Target::HVX_64, Target::HVX_128 });
// Specifying .hexagon() on a Func will generate an RPC to run this stage
// on Hexagon. If Hexagon is the host (that is, the architecture is
// Hexagon), we have to omit the .hexagon() directive as we are already
// running on Hexagon.
if (use_hexagon && get_target().arch != Target::Hexagon) {
output_.hexagon();
}
int vector_size_u8 = get_target().natural_vector_size<uint8_t>();
if (get_target().has_feature(Target::HVX_64)) {
vector_size_u8 = 64;
} else if (get_target().has_feature(Target::HVX_128)) {
vector_size_u8 = 128;
}
shifted_input_bounded.compute_at(output_, batch);
// We only perform vectorization when the depth >= vector size.
Expr can_vectorize_across_depth =
output_.dim(0).extent() >= vector_size_u8;
output_.specialize(can_vectorize_across_depth)
.vectorize(depth, vector_size_u8);
Var yi("yi");
constexpr int kSplitFactor = 4;
output_.split(y, y, yi, kSplitFactor).parallel(y);
struct SpecialCase {
int stride;
int filter_width;
int filter_height;
};
std::vector<SpecialCase> special_cases = { { 1, 4, 4 }, { 2, 7, 7 } };
for (const SpecialCase &special_case : special_cases) {
Expr params_matched = (filter_width_ == special_case.filter_width &&
filter_height_ == special_case.filter_height &&
stride_ == special_case.stride);
sum.update(0).specialize(params_matched).unroll(filter_dom.x);
}
}
};
HALIDE_REGISTER_GENERATOR(AveragePool, AveragePool)
|
/*
* The MIT License
*
* Copyright 2016 annas.
*
* 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.
*/
/*
* File: scoped_ptr.hpp
* Author: annas
*
* Created on 7. Dezember 2016, 23:03
*/
#ifndef SCOPED_PTR_HPP
#define SCOPED_PTR_HPP
#include "algorithm.hpp"
#include "auto_ptr.hpp"
#include "common.hpp"
namespace std {
template <typename T>
class scoped_ptr {
public:
using value_type = T;
using pointer = value_type*;
using const_value_type = const value_type;
using self_type = scoped_ptr<value_type>;
explicit scoped_ptr( pointer pValue = 0 )
: m_pPointer( pValue ) { }
explicit scoped_ptr( const auto_ptr<value_type>& pPtr )
: m_pPointer( pPtr.release() ) { }
~scoped_ptr() { }
void swap(self_type& b) {
std::swap<value_type*>(m_pPointer, b.m_pPointer);
}
void reset( pointer pValue = 0)
{ self_type(pValue).swap(*this); }
pointer get()
{ return m_pPointer; }
const pointer operator -> () {
assert(m_pPointer != 0);
return m_pPointer;
}
const_value_type& operator *() {
assert(m_pPointer != 0);
return *m_pPointer;
}
operator bool() {
return m_pPointer != 0;
}
private:
pointer m_pPointer;
};
template<class T>
inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b) {
a.swap(b);
}
}
#endif /* SCOPED_PTR_HPP */
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/RequestCaller.h"
#include "joynr/IJoynrProvider.h"
namespace joynr
{
RequestCaller::RequestCaller(const std::string& interfaceName,
const types::Version& providerVersion)
: _interfaceName(interfaceName), _providerVersion(providerVersion)
{
}
RequestCaller::RequestCaller(std::string&& interfaceName, types::Version&& providerVersion)
: _interfaceName(std::move(interfaceName)), _providerVersion(std::move(providerVersion))
{
}
const std::string& RequestCaller::getInterfaceName() const
{
return _interfaceName;
}
void RequestCaller::registerAttributeListener(
const std::string& attributeName,
std::shared_ptr<SubscriptionAttributeListener> attributeListener)
{
getProvider()->registerAttributeListener(attributeName, std::move(attributeListener));
}
void RequestCaller::unregisterAttributeListener(
const std::string& attributeName,
std::shared_ptr<SubscriptionAttributeListener> attributeListener)
{
getProvider()->unregisterAttributeListener(attributeName, std::move(attributeListener));
}
void RequestCaller::registerBroadcastListener(
const std::string& broadcastName,
std::shared_ptr<UnicastBroadcastListener> broadcastListener)
{
getProvider()->registerBroadcastListener(broadcastName, std::move(broadcastListener));
}
void RequestCaller::unregisterBroadcastListener(
const std::string& broadcastName,
std::shared_ptr<UnicastBroadcastListener> broadcastListener)
{
getProvider()->unregisterBroadcastListener(broadcastName, std::move(broadcastListener));
}
types::Version RequestCaller::getProviderVersion()
{
return _providerVersion;
}
} // namespace joynr
|
#include <XEUI/UIPanel.hpp>
#include <XEUI/Widget.hpp>
#include <XEUI/UIManager.hpp>
#include <XERenderer/GUI/WLayer.hpp>
#include <XEUI/Desktop.hpp>
//#include <XEUI/widgets/Menu.hpp>
//#include <XEUI/widgets/Navigation.hpp>
//#include <XEUI/OgreConsoleForGorilla.h>
//#include <XEUI/Widgets/Button.hpp>
//#include <XEUI/Widgets/ListBox.hpp>
//#include <XEUI/widgets/ComboBox.hpp>
//#include <XEUI/widgets/Caption.hpp>
#include <XERenderer/GUI/GUIRenderer.hpp>
#include <XEUI/DAL/FB_UI_StateData_generated.h> //need to include ... else link error
namespace XE {
using namespace std;
UIPanel::UIPanel( WLayer& layer, const Ogre::uint16& grp)
: //Widget(nullptr,""), mXEUI(gui),
//, mPosition(position) , mSize(size),
// mMousePointer(NULL), mBackground(NULL)
// m_guiRenderer(guiRenderer)
m_layer(layer)
, m_DebugRectangle(layer, 0, 0, 0, 0)
{
}
UIPanel::~UIPanel()
{
// mXEUI->destroyUIPanel(this);
}
void UIPanel::HandleAlignmentChange(const sf::Vector2f& old_alignment)
{
HandlePositionChange();
}
void UIPanel::HandleAbsolutePositionChange()
{
HandlePositionChange();
}
void UIPanel::setDesktop(std::shared_ptr<Desktop> desktopPtr)
{
m_Desktop = desktopPtr;
}
void UIPanel::HandlePositionChange()
{
//if (m_Desktop)
//{
// //sf::FloatRect parentAllocation(m_Desktop->wi->GetAllocation());
// const sf::Vector2f& alignment = GetAlignment();
// auto newAlloc = GetAllocation(); //copy
// auto requistion = GetRequisition(); //copy
//
// //auto dektopWidth = GetParent().get m_guiRenderer.getLayerRenderer().getActualWidth();
// //auto dektopHeight = m_guiRenderer.getLayerRenderer().getActualHeight();
///* newAlloc.left = std::max(0.0f, std::min(dektopWidth - requistion.x, dektopWidth * alignment.x - newAlloc.width / 2));
// newAlloc.top = std::max(0.0f, std::min(dektopHeight - requistion.y, dektopHeight * alignment.y - newAlloc.height / 2));*/
// newAlloc.left = std::max(0.0f, std::min(m_Desktop->width - requistion.x, m_Desktop->width * alignment.x - newAlloc.width / 2));
// newAlloc.top = std::max(0.0f, std::min(m_Desktop->height - requistion.y, m_Desktop->height * alignment.y - newAlloc.height / 2));
// SetAllocation(newAlloc);
//}
//for (const auto& children : GetChildren())
//{
// children->HandleAbsolutePositionChange();
// children->Invalidate();// HandleAbsolutePositionChange();
// /*requisition.x = std::max(requisition.x, child_position.second.x + child_position.first->GetRequisition().x);
// requisition.y = std::max(requisition.y, child_position.second.y + child_position.first->GetRequisition().y);*/
//}
//Invalidate();
}
UIPanel::Ptr UIPanel::Create( WLayer& layer) {
Ptr panel(new UIPanel( layer));
//label->RequestResize();
// desktop->Add(panel);
return panel;
}
void UIPanel::SetStyle(const char* menuElement, const char* menuStyle)
{
if (menuElement)
{
flatbuffers::GetRoot<XFB_UI::Panel2D>(menuElement);
}
}
void UIPanel::draw() {
//m_DebugRectangle.setBackgroundImage("item_ball_hover.png");
////m_DebugRectangle.setBackground(Ogre::ColourValue::Blue);
//auto& req = GetAllocation();
//m_DebugRectangle.setPosition(sf::Vector2f(req.left, req.top));
//m_DebugRectangle.setSize(sf::Vector2f(req.width, req.height));
////m_Label.SetText(GetText());
////return Context::Get().GetEngine().CreateLabelDrawable( std::dynamic_pointer_cast<const Label>( shared_from_this() ) );
}
void UIPanel::SetLabel(const sf::String& label) {
m_label = label;
//RequestResize();
//Invalidate();
}
void UIPanel::HandleSizeChange()
{
}
void UIPanel::HandleUpdate(float seconds)
{
/*for each (auto& var in GetChildren())
{
var->Update(seconds);
}*/
}
const sf::String& UIPanel::GetLabel() const {
return m_label;
}
const std::string& UIPanel::GetName() const {
static const std::string name("UIPanel");
return name;
}
//sf::Vector2f UIPanel::CalculateRequisition() {
//
// sf::Vector2f requisition(0.f, 0.f);
//
// //// Find size needed to accomodate all widgets without overlapping any other widgets
// //for (const auto& child_position : m_children_position_map) {
// // requisition.x = std::max(requisition.x, child_position.second.x + child_position.first->GetRequisition().x);
// // requisition.y = std::max(requisition.y, child_position.second.y + child_position.first->GetRequisition().y);
// //}
//
// return requisition;
//}
void UIPanel::Put(Widget::Ptr widget, const sf::Vector2f& position) {
m_children_position_map[widget] = position;
Container::Add(widget);
}
void UIPanel::Move(Widget::Ptr widget, const sf::Vector2f& position) {
/*if (m_children_position_map.find(widget) != m_children_position_map.end()) {
m_children_position_map[widget] = position;
widget->SetAllocation(sf::FloatRect(position, widget->GetRequisition()));
RequestResize();
}*/
}
bool UIPanel::HandleAdd(Widget::Ptr child) {
// If there's no position info present for the widget, the user added the widget
// manually, which is not allowed for this class.
if (m_children_position_map.find(child) == m_children_position_map.end()) {
#if defined( SFGUI_DEBUG )
std::cerr << "SFGUI warning: Child must be added via Put() for sfg::Fixed widgets.\n";
#endif
return false;
}
/*Container::HandleAdd(child);
child->SetAllocation(sf::FloatRect(m_children_position_map[child], child->GetRequisition()));
RequestResize();*/
return true;
}
void UIPanel::HandleRemove(Widget::Ptr child) {
m_children_position_map.erase(child);
// RequestResize();
}
void UIPanel::selectOveredItem()
{
//for (WidgetVector::iterator it = mWidgets.begin(); it != mWidgets.end(); ++it)
// if ((*it)->getName() == mCurrentItemName)
// (*it)->selectOveredItem();
}
bool UIPanel::makeNextItemOver()
{
//if (mCurrentItemName.empty())
// if (mWidgets.size() > 0)
// mCurrentItemName = mWidgets[0]->getName(); // set first Element as actual
// else
// return false; //no Elemets
//for (WidgetVector::iterator it = mWidgets.begin(); it != mWidgets.end(); ++it)
//{
// if ((*it)->getName() == mCurrentItemName)
// {
// if ((*it)->makeNextItemOver()) //Current Element(Navigation,Menu ...) Next Item
// return true;
// else
// {
// ++it;
// if (it != mWidgets.end())
// {
// mCurrentItemName = (*it)->getName();
// return (*it)->makeNextItemOver(); // Next Elemt First Item
// }
// else
// return false;
// }
// }
//}
return false;
}
bool UIPanel::makePrevItemOver()
{
//if (mCurrentItemName.empty())
// if (mWidgets.size() > 0)
// mCurrentItemName = mWidgets[0]->getName(); // set first Element as actual
// else
// return false; //no Elemets
//for (WidgetVector::iterator it = mWidgets.end(); it != mWidgets.begin();)
//{
// --it;
// if ((*it)->getName() == mCurrentItemName)
// {
// if ((*it)->makePrevItemOver()) //Current Element(Navigation,Menu ...) Next Item
// return true;
// else
// {
// // --it;
// if (it != mWidgets.begin())
// {
// mCurrentItemName = (*it)->getName();
// return (*it)->makePrevItemOver(); // Next Elemt First Item
// }
// else
// return false;
// }
// }
//}
return false;
}
} // namespace XE
|
#include "TcpServer.h"
//############################ SOCKET PROGRAMMING FUNCTIONS ###############################################//
/*#########################################################################################################*/
// Function to test the server setup by sending a sample data_packet
void tcpipServerSetupTest() {
// encoding
data_packet td;
td.timestamp = 0;
td.transform00 = 0;
td.transform01 = -0.1;
td.transform02 = 0.2;
td.transform03 = 0.3;
td.transform10 = 1;
td.transform11 = -1.1;
td.transform12 = 1.2;
td.transform13 = -1.3;
td.transform20 = -2;
td.transform21 = 2.1;
td.transform22 = 2.2;
td.transform23 = -2.3;
SOCKET ClientSocket = startServerConn(); // start server at default port mentioned in header
sendDataServer(ClientSocket, td); // send data td to the client socket and wait for default delay milliseconds
endServerConn(ClientSocket); // close the server connection
}
// function to create a TCP/IP socket server for the given DEFAULT_PORT
SOCKET startServerConn()
{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo* result = NULL;
struct addrinfo hints;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket creation failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
}
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
}
// No longer need server socket
closesocket(ListenSocket);
return ClientSocket;
}
// shutdown the connection since we're done
void endServerConn(SOCKET ClientSocket)
{
int iResult;
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
printf("Server socket closed.");
}
void sendDataServer(SOCKET ClientSocket, data_packet td)
{
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// serialization
unsigned char* recvbufptr = reinterpret_cast<unsigned char*>(&td); //without unsigned 0.0 and some values like 0.1 or 1.1 will not be casted
if (recvbufptr != nullptr)
{
try {
memcpy(recvbuf, recvbufptr, DEFAULT_BUFLEN);
// reseting the pointer
ZeroMemory(&recvbufptr, sizeof(recvbufptr));
}
catch (std::exception & e)
{
std::cerr << "casting issue at encoding with exception " << e.what() << "\n" << std::endl;
}
}
// Echo the buffer back to the sender
iSendResult = send(ClientSocket, recvbuf, recvbuflen, 0);
if (iSendResult == SOCKET_ERROR)
{
printf("Send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return;
}
//printf("Bytes sent: %d\n", iSendResult);
}
|
#include <nano/crypto_lib/random_pool.hpp>
#include <nano/lib/utility.hpp>
#include <nano/node/lmdb/lmdb_iterator.hpp>
#include <nano/node/node.hpp>
#include <nano/node/wallet.hpp>
#include <nano/node/xorshift.hpp>
#include <boost/filesystem.hpp>
#include <boost/polymorphic_cast.hpp>
#include <future>
#include <argon2.h>
nano::uint256_union nano::wallet_store::check (nano::transaction const & transaction_a)
{
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::check_special));
return value.key;
}
nano::uint256_union nano::wallet_store::salt (nano::transaction const & transaction_a)
{
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::salt_special));
return value.key;
}
void nano::wallet_store::wallet_key (nano::raw_key & prv_a, nano::transaction const & transaction_a)
{
nano::lock_guard<std::recursive_mutex> lock (mutex);
nano::raw_key wallet_l;
wallet_key_mem.value (wallet_l);
nano::raw_key password_l;
password.value (password_l);
prv_a.decrypt (wallet_l.data, password_l, salt (transaction_a).owords[0]);
}
void nano::wallet_store::seed (nano::raw_key & prv_a, nano::transaction const & transaction_a)
{
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::seed_special));
nano::raw_key password_l;
wallet_key (password_l, transaction_a);
prv_a.decrypt (value.key, password_l, salt (transaction_a).owords[seed_iv_index]);
}
void nano::wallet_store::seed_set (nano::transaction const & transaction_a, nano::raw_key const & prv_a)
{
nano::raw_key password_l;
wallet_key (password_l, transaction_a);
nano::uint256_union ciphertext;
ciphertext.encrypt (prv_a, password_l, salt (transaction_a).owords[seed_iv_index]);
entry_put_raw (transaction_a, nano::wallet_store::seed_special, nano::wallet_value (ciphertext, 0));
deterministic_clear (transaction_a);
}
nano::public_key nano::wallet_store::deterministic_insert (nano::transaction const & transaction_a)
{
auto index (deterministic_index_get (transaction_a));
nano::raw_key prv;
deterministic_key (prv, transaction_a, index);
nano::public_key result (nano::pub_key (prv.data));
while (exists (transaction_a, result))
{
++index;
deterministic_key (prv, transaction_a, index);
result = nano::pub_key (prv.data);
}
uint64_t marker (1);
marker <<= 32;
marker |= index;
entry_put_raw (transaction_a, result, nano::wallet_value (nano::uint256_union (marker), 0));
++index;
deterministic_index_set (transaction_a, index);
return result;
}
nano::public_key nano::wallet_store::deterministic_insert (nano::transaction const & transaction_a, uint32_t const index)
{
nano::raw_key prv;
deterministic_key (prv, transaction_a, index);
nano::public_key result (nano::pub_key (prv.data));
uint64_t marker (1);
marker <<= 32;
marker |= index;
entry_put_raw (transaction_a, result, nano::wallet_value (nano::uint256_union (marker), 0));
return result;
}
void nano::wallet_store::deterministic_key (nano::raw_key & prv_a, nano::transaction const & transaction_a, uint32_t index_a)
{
assert (valid_password (transaction_a));
nano::raw_key seed_l;
seed (seed_l, transaction_a);
nano::deterministic_key (seed_l.data, index_a, prv_a.data);
}
uint32_t nano::wallet_store::deterministic_index_get (nano::transaction const & transaction_a)
{
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::deterministic_index_special));
return static_cast<uint32_t> (value.key.number () & static_cast<uint32_t> (-1));
}
void nano::wallet_store::deterministic_index_set (nano::transaction const & transaction_a, uint32_t index_a)
{
nano::uint256_union index_l (index_a);
nano::wallet_value value (index_l, 0);
entry_put_raw (transaction_a, nano::wallet_store::deterministic_index_special, value);
}
void nano::wallet_store::deterministic_clear (nano::transaction const & transaction_a)
{
nano::uint256_union key (0);
for (auto i (begin (transaction_a)), n (end ()); i != n;)
{
switch (key_type (nano::wallet_value (i->second)))
{
case nano::key_type::deterministic:
{
nano::uint256_union const & key (i->first);
erase (transaction_a, key);
i = begin (transaction_a, key);
break;
}
default:
{
++i;
break;
}
}
}
deterministic_index_set (transaction_a, 0);
}
bool nano::wallet_store::valid_password (nano::transaction const & transaction_a)
{
nano::raw_key zero;
zero.data.clear ();
nano::raw_key wallet_key_l;
wallet_key (wallet_key_l, transaction_a);
nano::uint256_union check_l;
check_l.encrypt (zero, wallet_key_l, salt (transaction_a).owords[check_iv_index]);
bool ok = check (transaction_a) == check_l;
return ok;
}
bool nano::wallet_store::attempt_password (nano::transaction const & transaction_a, std::string const & password_a)
{
bool result = false;
{
nano::lock_guard<std::recursive_mutex> lock (mutex);
nano::raw_key password_l;
derive_key (password_l, transaction_a, password_a);
password.value_set (password_l);
result = !valid_password (transaction_a);
}
if (!result)
{
switch (version (transaction_a))
{
case version_1:
upgrade_v1_v2 (transaction_a);
case version_2:
upgrade_v2_v3 (transaction_a);
case version_3:
upgrade_v3_v4 (transaction_a);
case version_4:
break;
default:
assert (false);
}
}
return result;
}
bool nano::wallet_store::rekey (nano::transaction const & transaction_a, std::string const & password_a)
{
nano::lock_guard<std::recursive_mutex> lock (mutex);
bool result (false);
if (valid_password (transaction_a))
{
nano::raw_key password_new;
derive_key (password_new, transaction_a, password_a);
nano::raw_key wallet_key_l;
wallet_key (wallet_key_l, transaction_a);
nano::raw_key password_l;
password.value (password_l);
password.value_set (password_new);
nano::uint256_union encrypted;
encrypted.encrypt (wallet_key_l, password_new, salt (transaction_a).owords[0]);
nano::raw_key wallet_enc;
wallet_enc.data = encrypted;
wallet_key_mem.value_set (wallet_enc);
entry_put_raw (transaction_a, nano::wallet_store::wallet_key_special, nano::wallet_value (encrypted, 0));
}
else
{
result = true;
}
return result;
}
void nano::wallet_store::derive_key (nano::raw_key & prv_a, nano::transaction const & transaction_a, std::string const & password_a)
{
auto salt_l (salt (transaction_a));
kdf.phs (prv_a, password_a, salt_l);
}
nano::fan::fan (nano::uint256_union const & key, size_t count_a)
{
std::unique_ptr<nano::uint256_union> first (new nano::uint256_union (key));
for (auto i (1); i < count_a; ++i)
{
std::unique_ptr<nano::uint256_union> entry (new nano::uint256_union);
nano::random_pool::generate_block (entry->bytes.data (), entry->bytes.size ());
*first ^= *entry;
values.push_back (std::move (entry));
}
values.push_back (std::move (first));
}
void nano::fan::value (nano::raw_key & prv_a)
{
nano::lock_guard<std::mutex> lock (mutex);
value_get (prv_a);
}
void nano::fan::value_get (nano::raw_key & prv_a)
{
assert (!mutex.try_lock ());
prv_a.data.clear ();
for (auto & i : values)
{
prv_a.data ^= *i;
}
}
void nano::fan::value_set (nano::raw_key const & value_a)
{
nano::lock_guard<std::mutex> lock (mutex);
nano::raw_key value_l;
value_get (value_l);
*(values[0]) ^= value_l.data;
*(values[0]) ^= value_a.data;
}
// Wallet version number
nano::uint256_union const nano::wallet_store::version_special (0);
// Random number used to salt private key encryption
nano::uint256_union const nano::wallet_store::salt_special (1);
// Key used to encrypt wallet keys, encrypted itself by the user password
nano::uint256_union const nano::wallet_store::wallet_key_special (2);
// Check value used to see if password is valid
nano::uint256_union const nano::wallet_store::check_special (3);
// Representative account to be used if we open a new account
nano::uint256_union const nano::wallet_store::representative_special (4);
// Wallet seed for deterministic key generation
nano::uint256_union const nano::wallet_store::seed_special (5);
// Current key index for deterministic keys
nano::uint256_union const nano::wallet_store::deterministic_index_special (6);
int const nano::wallet_store::special_count (7);
size_t const nano::wallet_store::check_iv_index (0);
size_t const nano::wallet_store::seed_iv_index (1);
nano::wallet_store::wallet_store (bool & init_a, nano::kdf & kdf_a, nano::transaction & transaction_a, nano::account representative_a, unsigned fanout_a, std::string const & wallet_a, std::string const & json_a) :
password (0, fanout_a),
wallet_key_mem (0, fanout_a),
kdf (kdf_a)
{
init_a = false;
initialize (transaction_a, init_a, wallet_a);
if (!init_a)
{
MDB_val junk;
assert (mdb_get (tx (transaction_a), handle, nano::mdb_val (version_special), &junk) == MDB_NOTFOUND);
boost::property_tree::ptree wallet_l;
std::stringstream istream (json_a);
try
{
boost::property_tree::read_json (istream, wallet_l);
}
catch (...)
{
init_a = true;
}
for (auto i (wallet_l.begin ()), n (wallet_l.end ()); i != n; ++i)
{
nano::uint256_union key;
init_a = key.decode_hex (i->first);
if (!init_a)
{
nano::uint256_union value;
init_a = value.decode_hex (wallet_l.get<std::string> (i->first));
if (!init_a)
{
entry_put_raw (transaction_a, key, nano::wallet_value (value, 0));
}
else
{
init_a = true;
}
}
else
{
init_a = true;
}
}
init_a |= mdb_get (tx (transaction_a), handle, nano::mdb_val (version_special), &junk) != 0;
init_a |= mdb_get (tx (transaction_a), handle, nano::mdb_val (wallet_key_special), &junk) != 0;
init_a |= mdb_get (tx (transaction_a), handle, nano::mdb_val (salt_special), &junk) != 0;
init_a |= mdb_get (tx (transaction_a), handle, nano::mdb_val (check_special), &junk) != 0;
init_a |= mdb_get (tx (transaction_a), handle, nano::mdb_val (representative_special), &junk) != 0;
nano::raw_key key;
key.data.clear ();
password.value_set (key);
key.data = entry_get_raw (transaction_a, nano::wallet_store::wallet_key_special).key;
wallet_key_mem.value_set (key);
}
}
nano::wallet_store::wallet_store (bool & init_a, nano::kdf & kdf_a, nano::transaction & transaction_a, nano::account representative_a, unsigned fanout_a, std::string const & wallet_a) :
password (0, fanout_a),
wallet_key_mem (0, fanout_a),
kdf (kdf_a)
{
init_a = false;
initialize (transaction_a, init_a, wallet_a);
if (!init_a)
{
int version_status;
MDB_val version_value;
version_status = mdb_get (tx (transaction_a), handle, nano::mdb_val (version_special), &version_value);
if (version_status == MDB_NOTFOUND)
{
version_put (transaction_a, version_current);
nano::uint256_union salt_l;
random_pool::generate_block (salt_l.bytes.data (), salt_l.bytes.size ());
entry_put_raw (transaction_a, nano::wallet_store::salt_special, nano::wallet_value (salt_l, 0));
// Wallet key is a fixed random key that encrypts all entries
nano::raw_key wallet_key;
random_pool::generate_block (wallet_key.data.bytes.data (), sizeof (wallet_key.data.bytes));
nano::raw_key password_l;
password_l.data.clear ();
password.value_set (password_l);
nano::raw_key zero;
zero.data.clear ();
// Wallet key is encrypted by the user's password
nano::uint256_union encrypted;
encrypted.encrypt (wallet_key, zero, salt_l.owords[0]);
entry_put_raw (transaction_a, nano::wallet_store::wallet_key_special, nano::wallet_value (encrypted, 0));
nano::raw_key wallet_key_enc;
wallet_key_enc.data = encrypted;
wallet_key_mem.value_set (wallet_key_enc);
nano::uint256_union check;
check.encrypt (zero, wallet_key, salt_l.owords[check_iv_index]);
entry_put_raw (transaction_a, nano::wallet_store::check_special, nano::wallet_value (check, 0));
entry_put_raw (transaction_a, nano::wallet_store::representative_special, nano::wallet_value (representative_a, 0));
nano::raw_key seed;
random_pool::generate_block (seed.data.bytes.data (), seed.data.bytes.size ());
seed_set (transaction_a, seed);
entry_put_raw (transaction_a, nano::wallet_store::deterministic_index_special, nano::wallet_value (nano::uint256_union (0), 0));
}
}
nano::raw_key key;
key.data = entry_get_raw (transaction_a, nano::wallet_store::wallet_key_special).key;
wallet_key_mem.value_set (key);
}
std::vector<nano::account> nano::wallet_store::accounts (nano::transaction const & transaction_a)
{
std::vector<nano::account> result;
for (auto i (begin (transaction_a)), n (end ()); i != n; ++i)
{
nano::account const & account (i->first);
result.push_back (account);
}
return result;
}
void nano::wallet_store::initialize (nano::transaction const & transaction_a, bool & init_a, std::string const & path_a)
{
assert (strlen (path_a.c_str ()) == path_a.size ());
auto error (0);
error |= mdb_dbi_open (tx (transaction_a), path_a.c_str (), MDB_CREATE, &handle);
init_a = error != 0;
}
bool nano::wallet_store::is_representative (nano::transaction const & transaction_a)
{
return exists (transaction_a, representative (transaction_a));
}
void nano::wallet_store::representative_set (nano::transaction const & transaction_a, nano::account const & representative_a)
{
entry_put_raw (transaction_a, nano::wallet_store::representative_special, nano::wallet_value (representative_a, 0));
}
nano::account nano::wallet_store::representative (nano::transaction const & transaction_a)
{
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::representative_special));
return value.key;
}
nano::public_key nano::wallet_store::insert_adhoc (nano::transaction const & transaction_a, nano::raw_key const & prv)
{
assert (valid_password (transaction_a));
nano::public_key pub (nano::pub_key (prv.data));
nano::raw_key password_l;
wallet_key (password_l, transaction_a);
nano::uint256_union ciphertext;
ciphertext.encrypt (prv, password_l, pub.owords[0].number ());
entry_put_raw (transaction_a, pub, nano::wallet_value (ciphertext, 0));
return pub;
}
bool nano::wallet_store::insert_watch (nano::transaction const & transaction_a, nano::public_key const & pub_a)
{
bool error (!valid_public_key (pub_a));
if (!error)
{
entry_put_raw (transaction_a, pub_a, nano::wallet_value (nano::uint256_union (0), 0));
}
return error;
}
void nano::wallet_store::erase (nano::transaction const & transaction_a, nano::public_key const & pub)
{
auto status (mdb_del (tx (transaction_a), handle, nano::mdb_val (pub), nullptr));
(void)status;
assert (status == 0);
}
nano::wallet_value nano::wallet_store::entry_get_raw (nano::transaction const & transaction_a, nano::public_key const & pub_a)
{
nano::wallet_value result;
nano::mdb_val value;
auto status (mdb_get (tx (transaction_a), handle, nano::mdb_val (pub_a), value));
if (status == 0)
{
result = nano::wallet_value (value);
}
else
{
result.key.clear ();
result.work = 0;
}
return result;
}
void nano::wallet_store::entry_put_raw (nano::transaction const & transaction_a, nano::public_key const & pub_a, nano::wallet_value const & entry_a)
{
auto status (mdb_put (tx (transaction_a), handle, nano::mdb_val (pub_a), nano::mdb_val (sizeof (entry_a), const_cast<nano::wallet_value *> (&entry_a)), 0));
(void)status;
assert (status == 0);
}
nano::key_type nano::wallet_store::key_type (nano::wallet_value const & value_a)
{
auto number (value_a.key.number ());
nano::key_type result;
auto text (number.convert_to<std::string> ());
if (number > std::numeric_limits<uint64_t>::max ())
{
result = nano::key_type::adhoc;
}
else
{
if ((number >> 32).convert_to<uint32_t> () == 1)
{
result = nano::key_type::deterministic;
}
else
{
result = nano::key_type::unknown;
}
}
return result;
}
bool nano::wallet_store::fetch (nano::transaction const & transaction_a, nano::public_key const & pub, nano::raw_key & prv)
{
auto result (false);
if (valid_password (transaction_a))
{
nano::wallet_value value (entry_get_raw (transaction_a, pub));
if (!value.key.is_zero ())
{
switch (key_type (value))
{
case nano::key_type::deterministic:
{
nano::raw_key seed_l;
seed (seed_l, transaction_a);
uint32_t index (static_cast<uint32_t> (value.key.number () & static_cast<uint32_t> (-1)));
deterministic_key (prv, transaction_a, index);
break;
}
case nano::key_type::adhoc:
{
// Ad-hoc keys
nano::raw_key password_l;
wallet_key (password_l, transaction_a);
prv.decrypt (value.key, password_l, pub.owords[0].number ());
break;
}
default:
{
result = true;
break;
}
}
}
else
{
result = true;
}
}
else
{
result = true;
}
if (!result)
{
nano::public_key compare (nano::pub_key (prv.data));
if (!(pub == compare))
{
result = true;
}
}
return result;
}
bool nano::wallet_store::valid_public_key (nano::public_key const & pub)
{
return pub.number () >= special_count;
}
bool nano::wallet_store::exists (nano::transaction const & transaction_a, nano::public_key const & pub)
{
return valid_public_key (pub) && find (transaction_a, pub) != end ();
}
void nano::wallet_store::serialize_json (nano::transaction const & transaction_a, std::string & string_a)
{
boost::property_tree::ptree tree;
for (nano::store_iterator<nano::uint256_union, nano::wallet_value> i (std::make_unique<nano::mdb_iterator<nano::uint256_union, nano::wallet_value>> (transaction_a, handle)), n (nullptr); i != n; ++i)
{
tree.put (i->first.to_string (), i->second.key.to_string ());
}
std::stringstream ostream;
boost::property_tree::write_json (ostream, tree);
string_a = ostream.str ();
}
void nano::wallet_store::write_backup (nano::transaction const & transaction_a, boost::filesystem::path const & path_a)
{
std::ofstream backup_file;
backup_file.open (path_a.string ());
if (!backup_file.fail ())
{
// Set permissions to 600
boost::system::error_code ec;
nano::set_secure_perm_file (path_a, ec);
std::string json;
serialize_json (transaction_a, json);
backup_file << json;
}
}
bool nano::wallet_store::move (nano::transaction const & transaction_a, nano::wallet_store & other_a, std::vector<nano::public_key> const & keys)
{
assert (valid_password (transaction_a));
assert (other_a.valid_password (transaction_a));
auto result (false);
for (auto i (keys.begin ()), n (keys.end ()); i != n; ++i)
{
nano::raw_key prv;
auto error (other_a.fetch (transaction_a, *i, prv));
result = result | error;
if (!result)
{
insert_adhoc (transaction_a, prv);
other_a.erase (transaction_a, *i);
}
}
return result;
}
bool nano::wallet_store::import (nano::transaction const & transaction_a, nano::wallet_store & other_a)
{
assert (valid_password (transaction_a));
assert (other_a.valid_password (transaction_a));
auto result (false);
for (auto i (other_a.begin (transaction_a)), n (end ()); i != n; ++i)
{
nano::raw_key prv;
auto error (other_a.fetch (transaction_a, nano::uint256_union (i->first), prv));
result = result | error;
if (!result)
{
if (!prv.data.is_zero ())
{
insert_adhoc (transaction_a, prv);
}
else
{
insert_watch (transaction_a, nano::uint256_union (i->first));
}
other_a.erase (transaction_a, nano::uint256_union (i->first));
}
}
return result;
}
bool nano::wallet_store::work_get (nano::transaction const & transaction_a, nano::public_key const & pub_a, uint64_t & work_a)
{
auto result (false);
auto entry (entry_get_raw (transaction_a, pub_a));
if (!entry.key.is_zero ())
{
work_a = entry.work;
}
else
{
result = true;
}
return result;
}
void nano::wallet_store::work_put (nano::transaction const & transaction_a, nano::public_key const & pub_a, uint64_t work_a)
{
auto entry (entry_get_raw (transaction_a, pub_a));
assert (!entry.key.is_zero ());
entry.work = work_a;
entry_put_raw (transaction_a, pub_a, entry);
}
unsigned nano::wallet_store::version (nano::transaction const & transaction_a)
{
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::version_special));
auto entry (value.key);
auto result (static_cast<unsigned> (entry.bytes[31]));
return result;
}
void nano::wallet_store::version_put (nano::transaction const & transaction_a, unsigned version_a)
{
nano::uint256_union entry (version_a);
entry_put_raw (transaction_a, nano::wallet_store::version_special, nano::wallet_value (entry, 0));
}
void nano::wallet_store::upgrade_v1_v2 (nano::transaction const & transaction_a)
{
assert (version (transaction_a) == 1);
nano::raw_key zero_password;
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::wallet_key_special));
nano::raw_key kdf;
kdf.data.clear ();
zero_password.decrypt (value.key, kdf, salt (transaction_a).owords[0]);
derive_key (kdf, transaction_a, "");
nano::raw_key empty_password;
empty_password.decrypt (value.key, kdf, salt (transaction_a).owords[0]);
for (auto i (begin (transaction_a)), n (end ()); i != n; ++i)
{
nano::public_key const & key (i->first);
nano::raw_key prv;
if (fetch (transaction_a, key, prv))
{
// Key failed to decrypt despite valid password
nano::wallet_value data (entry_get_raw (transaction_a, key));
prv.decrypt (data.key, zero_password, salt (transaction_a).owords[0]);
nano::public_key compare (nano::pub_key (prv.data));
if (compare == key)
{
// If we successfully decrypted it, rewrite the key back with the correct wallet key
insert_adhoc (transaction_a, prv);
}
else
{
// Also try the empty password
nano::wallet_value data (entry_get_raw (transaction_a, key));
prv.decrypt (data.key, empty_password, salt (transaction_a).owords[0]);
nano::public_key compare (nano::pub_key (prv.data));
if (compare == key)
{
// If we successfully decrypted it, rewrite the key back with the correct wallet key
insert_adhoc (transaction_a, prv);
}
}
}
}
version_put (transaction_a, 2);
}
void nano::wallet_store::upgrade_v2_v3 (nano::transaction const & transaction_a)
{
assert (version (transaction_a) == 2);
nano::raw_key seed;
random_pool::generate_block (seed.data.bytes.data (), seed.data.bytes.size ());
seed_set (transaction_a, seed);
entry_put_raw (transaction_a, nano::wallet_store::deterministic_index_special, nano::wallet_value (nano::uint256_union (0), 0));
version_put (transaction_a, 3);
}
void nano::wallet_store::upgrade_v3_v4 (nano::transaction const & transaction_a)
{
assert (version (transaction_a) == 3);
version_put (transaction_a, 4);
assert (valid_password (transaction_a));
nano::raw_key seed;
nano::wallet_value value (entry_get_raw (transaction_a, nano::wallet_store::seed_special));
nano::raw_key password_l;
wallet_key (password_l, transaction_a);
seed.decrypt (value.key, password_l, salt (transaction_a).owords[0]);
nano::uint256_union ciphertext;
ciphertext.encrypt (seed, password_l, salt (transaction_a).owords[seed_iv_index]);
entry_put_raw (transaction_a, nano::wallet_store::seed_special, nano::wallet_value (ciphertext, 0));
for (auto i (begin (transaction_a)), n (end ()); i != n; ++i)
{
nano::wallet_value value (i->second);
if (!value.key.is_zero ())
{
switch (key_type (i->second))
{
case nano::key_type::adhoc:
{
nano::raw_key key;
if (fetch (transaction_a, nano::public_key (i->first), key))
{
// Key failed to decrypt despite valid password
key.decrypt (value.key, password_l, salt (transaction_a).owords[0]);
nano::uint256_union new_key_ciphertext;
new_key_ciphertext.encrypt (key, password_l, (nano::uint256_union (i->first)).owords[0].number ());
nano::wallet_value new_value (new_key_ciphertext, value.work);
erase (transaction_a, nano::public_key (i->first));
entry_put_raw (transaction_a, nano::public_key (i->first), new_value);
}
}
case nano::key_type::deterministic:
break;
default:
assert (false);
}
}
}
}
void nano::kdf::phs (nano::raw_key & result_a, std::string const & password_a, nano::uint256_union const & salt_a)
{
static nano::network_params network_params;
nano::lock_guard<std::mutex> lock (mutex);
auto success (argon2_hash (1, network_params.kdf_work, 1, password_a.data (), password_a.size (), salt_a.bytes.data (), salt_a.bytes.size (), result_a.data.bytes.data (), result_a.data.bytes.size (), NULL, 0, Argon2_d, 0x10));
assert (success == 0);
(void)success;
}
nano::wallet::wallet (bool & init_a, nano::transaction & transaction_a, nano::wallets & wallets_a, std::string const & wallet_a) :
lock_observer ([](bool, bool) {}),
store (init_a, wallets_a.kdf, transaction_a, wallets_a.node.config.random_representative (), wallets_a.node.config.password_fanout, wallet_a),
wallets (wallets_a)
{
}
nano::wallet::wallet (bool & init_a, nano::transaction & transaction_a, nano::wallets & wallets_a, std::string const & wallet_a, std::string const & json) :
lock_observer ([](bool, bool) {}),
store (init_a, wallets_a.kdf, transaction_a, wallets_a.node.config.random_representative (), wallets_a.node.config.password_fanout, wallet_a, json),
wallets (wallets_a)
{
}
void nano::wallet::enter_initial_password ()
{
nano::raw_key password_l;
{
nano::lock_guard<std::recursive_mutex> lock (store.mutex);
store.password.value (password_l);
}
if (password_l.data.is_zero ())
{
auto transaction (wallets.tx_begin_write ());
if (store.valid_password (transaction))
{
// Newly created wallets have a zero key
store.rekey (transaction, "");
}
else
{
enter_password (transaction, "");
}
}
}
bool nano::wallet::enter_password (nano::transaction const & transaction_a, std::string const & password_a)
{
auto result (store.attempt_password (transaction_a, password_a));
if (!result)
{
auto this_l (shared_from_this ());
wallets.node.background ([this_l]() {
this_l->search_pending ();
});
wallets.node.logger.try_log ("Wallet unlocked");
}
else
{
wallets.node.logger.try_log ("Invalid password, wallet locked");
}
lock_observer (result, password_a.empty ());
return result;
}
nano::public_key nano::wallet::deterministic_insert (nano::transaction const & transaction_a, bool generate_work_a)
{
nano::public_key key (0);
if (store.valid_password (transaction_a))
{
key = store.deterministic_insert (transaction_a);
if (generate_work_a)
{
work_ensure (key, key);
}
auto half_principal_weight (wallets.node.minimum_principal_weight () / 2);
if (wallets.check_rep (key, half_principal_weight))
{
nano::lock_guard<std::mutex> lock (representatives_mutex);
representatives.insert (key);
}
}
return key;
}
nano::public_key nano::wallet::deterministic_insert (uint32_t const index, bool generate_work_a)
{
auto transaction (wallets.tx_begin_write ());
nano::public_key key (0);
if (store.valid_password (transaction))
{
key = store.deterministic_insert (transaction, index);
if (generate_work_a)
{
work_ensure (key, key);
}
}
return key;
}
nano::public_key nano::wallet::deterministic_insert (bool generate_work_a)
{
auto transaction (wallets.tx_begin_write ());
auto result (deterministic_insert (transaction, generate_work_a));
return result;
}
nano::public_key nano::wallet::insert_adhoc (nano::transaction const & transaction_a, nano::raw_key const & key_a, bool generate_work_a)
{
nano::public_key key (0);
if (store.valid_password (transaction_a))
{
key = store.insert_adhoc (transaction_a, key_a);
auto block_transaction (wallets.node.store.tx_begin_read ());
if (generate_work_a)
{
work_ensure (key, wallets.node.ledger.latest_root (block_transaction, key));
}
auto half_principal_weight (wallets.node.minimum_principal_weight () / 2);
if (wallets.check_rep (key, half_principal_weight))
{
nano::lock_guard<std::mutex> lock (representatives_mutex);
representatives.insert (key);
}
}
return key;
}
nano::public_key nano::wallet::insert_adhoc (nano::raw_key const & account_a, bool generate_work_a)
{
auto transaction (wallets.tx_begin_write ());
auto result (insert_adhoc (transaction, account_a, generate_work_a));
return result;
}
bool nano::wallet::insert_watch (nano::transaction const & transaction_a, nano::public_key const & pub_a)
{
return store.insert_watch (transaction_a, pub_a);
}
bool nano::wallet::exists (nano::public_key const & account_a)
{
auto transaction (wallets.tx_begin_read ());
return store.exists (transaction, account_a);
}
bool nano::wallet::import (std::string const & json_a, std::string const & password_a)
{
auto error (false);
std::unique_ptr<nano::wallet_store> temp;
{
auto transaction (wallets.tx_begin_write ());
nano::uint256_union id;
random_pool::generate_block (id.bytes.data (), id.bytes.size ());
temp.reset (new nano::wallet_store (error, wallets.node.wallets.kdf, transaction, 0, 1, id.to_string (), json_a));
}
if (!error)
{
auto transaction (wallets.tx_begin_write ());
error = temp->attempt_password (transaction, password_a);
}
auto transaction (wallets.tx_begin_write ());
if (!error)
{
error = store.import (transaction, *temp);
}
temp->destroy (transaction);
return error;
}
void nano::wallet::serialize (std::string & json_a)
{
auto transaction (wallets.tx_begin_read ());
store.serialize_json (transaction, json_a);
}
void nano::wallet_store::destroy (nano::transaction const & transaction_a)
{
auto status (mdb_drop (tx (transaction_a), handle, 1));
(void)status;
assert (status == 0);
handle = 0;
}
std::shared_ptr<nano::block> nano::wallet::receive_action (nano::block const & send_a, nano::account const & representative_a, nano::uint128_union const & amount_a, uint64_t work_a, bool generate_work_a)
{
nano::account account;
auto hash (send_a.hash ());
std::shared_ptr<nano::block> block;
if (wallets.node.config.receive_minimum.number () <= amount_a.number ())
{
auto block_transaction (wallets.node.ledger.store.tx_begin_read ());
auto transaction (wallets.tx_begin_read ());
nano::pending_info pending_info;
if (wallets.node.store.block_exists (block_transaction, hash))
{
account = wallets.node.ledger.block_destination (block_transaction, send_a);
if (!wallets.node.ledger.store.pending_get (block_transaction, nano::pending_key (account, hash), pending_info))
{
nano::raw_key prv;
if (!store.fetch (transaction, account, prv))
{
if (work_a == 0)
{
store.work_get (transaction, account, work_a);
}
nano::account_info info;
auto new_account (wallets.node.ledger.store.account_get (block_transaction, account, info));
if (!new_account)
{
block.reset (new nano::state_block (account, info.head, info.representative, info.balance.number () + pending_info.amount.number (), hash, prv, account, work_a));
}
else
{
block.reset (new nano::state_block (account, 0, representative_a, pending_info.amount, hash, prv, account, work_a));
}
}
else
{
wallets.node.logger.try_log ("Unable to receive, wallet locked");
}
}
else
{
// Ledger doesn't have this marked as available to receive anymore
}
}
else
{
// Ledger doesn't have this block anymore.
}
}
else
{
wallets.node.logger.try_log (boost::str (boost::format ("Not receiving block %1% due to minimum receive threshold") % hash.to_string ()));
// Someone sent us something below the threshold of receiving
}
if (block != nullptr)
{
if (action_complete (block, account, generate_work_a))
{
// Return null block after work generation or ledger process error
block = nullptr;
}
}
return block;
}
std::shared_ptr<nano::block> nano::wallet::change_action (nano::account const & source_a, nano::account const & representative_a, uint64_t work_a, bool generate_work_a)
{
std::shared_ptr<nano::block> block;
{
auto transaction (wallets.tx_begin_read ());
auto block_transaction (wallets.node.store.tx_begin_read ());
if (store.valid_password (transaction))
{
auto existing (store.find (transaction, source_a));
if (existing != store.end () && !wallets.node.ledger.latest (block_transaction, source_a).is_zero ())
{
nano::account_info info;
auto error1 (wallets.node.ledger.store.account_get (block_transaction, source_a, info));
(void)error1;
assert (!error1);
nano::raw_key prv;
auto error2 (store.fetch (transaction, source_a, prv));
(void)error2;
assert (!error2);
if (work_a == 0)
{
store.work_get (transaction, source_a, work_a);
}
block.reset (new nano::state_block (source_a, info.head, representative_a, info.balance, 0, prv, source_a, work_a));
}
}
}
if (block != nullptr)
{
if (action_complete (block, source_a, generate_work_a))
{
// Return null block after work generation or ledger process error
block = nullptr;
}
}
return block;
}
std::shared_ptr<nano::block> nano::wallet::send_action (nano::account const & source_a, nano::account const & account_a, nano::uint128_t const & amount_a, uint64_t work_a, bool generate_work_a, boost::optional<std::string> id_a)
{
boost::optional<nano::mdb_val> id_mdb_val;
if (id_a)
{
id_mdb_val = nano::mdb_val (id_a->size (), const_cast<char *> (id_a->data ()));
}
// clang-format off
auto prepare_send = [&id_mdb_val, &wallets = this->wallets, &store = this->store, &source_a, &amount_a, &work_a, &account_a] (const auto & transaction) {
auto block_transaction (wallets.node.store.tx_begin_read ());
auto error (false);
auto cached_block (false);
std::shared_ptr<nano::block> block;
if (id_mdb_val)
{
nano::mdb_val result;
auto status (mdb_get (wallets.env.tx (transaction), wallets.node.wallets.send_action_ids, *id_mdb_val, result));
if (status == 0)
{
nano::uint256_union hash (result);
block = wallets.node.store.block_get (block_transaction, hash);
if (block != nullptr)
{
cached_block = true;
wallets.node.network.flood_block (block, false);
}
}
else if (status != MDB_NOTFOUND)
{
error = true;
}
}
if (!error && block == nullptr)
{
if (store.valid_password (transaction))
{
auto existing (store.find (transaction, source_a));
if (existing != store.end ())
{
auto balance (wallets.node.ledger.account_balance (block_transaction, source_a));
if (!balance.is_zero () && balance >= amount_a)
{
nano::account_info info;
auto error1 (wallets.node.ledger.store.account_get (block_transaction, source_a, info));
(void)error1;
assert (!error1);
nano::raw_key prv;
auto error2 (store.fetch (transaction, source_a, prv));
(void)error2;
assert (!error2);
if (work_a == 0)
{
store.work_get (transaction, source_a, work_a);
}
block.reset (new nano::state_block (source_a, info.head, info.representative, balance - amount_a, account_a, prv, source_a, work_a));
if (id_mdb_val && block != nullptr)
{
auto status (mdb_put (wallets.env.tx (transaction), wallets.node.wallets.send_action_ids, *id_mdb_val, nano::mdb_val (block->hash ()), 0));
if (status != 0)
{
block = nullptr;
error = true;
}
}
}
}
}
}
return std::make_tuple (block, error, cached_block);
};
// clang-format on
std::tuple<std::shared_ptr<nano::block>, bool, bool> result;
{
if (id_mdb_val)
{
result = prepare_send (wallets.tx_begin_write ());
}
else
{
result = prepare_send (wallets.tx_begin_read ());
}
}
std::shared_ptr<nano::block> block;
bool error;
bool cached_block;
std::tie (block, error, cached_block) = result;
if (!error && block != nullptr && !cached_block)
{
if (action_complete (block, source_a, generate_work_a))
{
// Return null block after work generation or ledger process error
block = nullptr;
}
}
return block;
}
bool nano::wallet::action_complete (std::shared_ptr<nano::block> const & block_a, nano::account const & account_a, bool const generate_work_a)
{
bool error{ false };
if (block_a != nullptr)
{
if (nano::work_validate (*block_a))
{
wallets.node.logger.try_log (boost::str (boost::format ("Cached or provided work for block %1% account %2% is invalid, regenerating") % block_a->hash ().to_string () % account_a.to_account ()));
error = !wallets.node.work_generate_blocking (*block_a, wallets.node.active.limited_active_difficulty ()).is_initialized ();
}
if (!error)
{
wallets.watcher->add (block_a);
error = wallets.node.process_local (block_a).code != nano::process_result::progress;
}
if (!error && generate_work_a)
{
work_ensure (account_a, block_a->hash ());
}
}
return error;
}
bool nano::wallet::change_sync (nano::account const & source_a, nano::account const & representative_a)
{
std::promise<bool> result;
std::future<bool> future = result.get_future ();
// clang-format off
change_async (source_a, representative_a, [&result](std::shared_ptr<nano::block> block_a) {
result.set_value (block_a == nullptr);
},
true);
// clang-format on
return future.get ();
}
void nano::wallet::change_async (nano::account const & source_a, nano::account const & representative_a, std::function<void(std::shared_ptr<nano::block>)> const & action_a, uint64_t work_a, bool generate_work_a)
{
auto this_l (shared_from_this ());
wallets.node.wallets.queue_wallet_action (nano::wallets::high_priority, this_l, [this_l, source_a, representative_a, action_a, work_a, generate_work_a](nano::wallet & wallet_a) {
auto block (wallet_a.change_action (source_a, representative_a, work_a, generate_work_a));
action_a (block);
});
}
bool nano::wallet::receive_sync (std::shared_ptr<nano::block> block_a, nano::account const & representative_a, nano::uint128_t const & amount_a)
{
std::promise<bool> result;
std::future<bool> future = result.get_future ();
// clang-format off
receive_async (block_a, representative_a, amount_a, [&result](std::shared_ptr<nano::block> block_a) {
result.set_value (block_a == nullptr);
},
true);
// clang-format on
return future.get ();
}
void nano::wallet::receive_async (std::shared_ptr<nano::block> block_a, nano::account const & representative_a, nano::uint128_t const & amount_a, std::function<void(std::shared_ptr<nano::block>)> const & action_a, uint64_t work_a, bool generate_work_a)
{
auto this_l (shared_from_this ());
wallets.node.wallets.queue_wallet_action (amount_a, this_l, [this_l, block_a, representative_a, amount_a, action_a, work_a, generate_work_a](nano::wallet & wallet_a) {
auto block (wallet_a.receive_action (*block_a, representative_a, amount_a, work_a, generate_work_a));
action_a (block);
});
}
nano::block_hash nano::wallet::send_sync (nano::account const & source_a, nano::account const & account_a, nano::uint128_t const & amount_a)
{
std::promise<nano::block_hash> result;
std::future<nano::block_hash> future = result.get_future ();
// clang-format off
send_async (source_a, account_a, amount_a, [&result](std::shared_ptr<nano::block> block_a) {
result.set_value (block_a->hash ());
},
true);
// clang-format on
return future.get ();
}
void nano::wallet::send_async (nano::account const & source_a, nano::account const & account_a, nano::uint128_t const & amount_a, std::function<void(std::shared_ptr<nano::block>)> const & action_a, uint64_t work_a, bool generate_work_a, boost::optional<std::string> id_a)
{
auto this_l (shared_from_this ());
wallets.node.wallets.queue_wallet_action (nano::wallets::high_priority, this_l, [this_l, source_a, account_a, amount_a, action_a, work_a, generate_work_a, id_a](nano::wallet & wallet_a) {
auto block (wallet_a.send_action (source_a, account_a, amount_a, work_a, generate_work_a, id_a));
action_a (block);
});
}
// Update work for account if latest root is root_a
void nano::wallet::work_update (nano::transaction const & transaction_a, nano::account const & account_a, nano::block_hash const & root_a, uint64_t work_a)
{
assert (!nano::work_validate (root_a, work_a));
assert (store.exists (transaction_a, account_a));
auto block_transaction (wallets.node.store.tx_begin_read ());
auto latest (wallets.node.ledger.latest_root (block_transaction, account_a));
if (latest == root_a)
{
store.work_put (transaction_a, account_a, work_a);
}
else
{
wallets.node.logger.try_log ("Cached work no longer valid, discarding");
}
}
void nano::wallet::work_ensure (nano::account const & account_a, nano::block_hash const & hash_a)
{
wallets.node.wallets.queue_wallet_action (nano::wallets::generate_priority, shared_from_this (), [account_a, hash_a](nano::wallet & wallet_a) {
wallet_a.work_cache_blocking (account_a, hash_a);
});
}
bool nano::wallet::search_pending ()
{
auto transaction (wallets.tx_begin_read ());
auto result (!store.valid_password (transaction));
if (!result)
{
wallets.node.logger.try_log ("Beginning pending block search");
for (auto i (store.begin (transaction)), n (store.end ()); i != n; ++i)
{
auto block_transaction (wallets.node.store.tx_begin_read ());
nano::account const & account (i->first);
// Don't search pending for watch-only accounts
if (!nano::wallet_value (i->second).key.is_zero ())
{
for (auto j (wallets.node.store.pending_begin (block_transaction, nano::pending_key (account, 0))); nano::pending_key (j->first).account == account; ++j)
{
nano::pending_key key (j->first);
auto hash (key.hash);
nano::pending_info pending (j->second);
auto amount (pending.amount.number ());
if (wallets.node.config.receive_minimum.number () <= amount)
{
wallets.node.logger.try_log (boost::str (boost::format ("Found a pending block %1% for account %2%") % hash.to_string () % pending.source.to_account ()));
auto block (wallets.node.store.block_get (block_transaction, hash));
if (wallets.node.block_confirmed_or_being_confirmed (block_transaction, hash))
{
// Receive confirmed block
auto node_l (wallets.node.shared ());
wallets.node.background ([node_l, block, hash]() {
auto transaction (node_l->store.tx_begin_read ());
node_l->receive_confirmed (transaction, block, hash);
});
}
else
{
// Request confirmation for unconfirmed block
wallets.node.block_confirm (block);
}
}
}
}
}
wallets.node.logger.try_log ("Pending block search phase complete");
}
else
{
wallets.node.logger.try_log ("Stopping search, wallet is locked");
}
return result;
}
void nano::wallet::init_free_accounts (nano::transaction const & transaction_a)
{
free_accounts.clear ();
for (auto i (store.begin (transaction_a)), n (store.end ()); i != n; ++i)
{
free_accounts.insert (nano::uint256_union (i->first));
}
}
uint32_t nano::wallet::deterministic_check (nano::transaction const & transaction_a, uint32_t index)
{
auto block_transaction (wallets.node.store.tx_begin_read ());
for (uint32_t i (index + 1), n (index + 64); i < n; ++i)
{
nano::raw_key prv;
store.deterministic_key (prv, transaction_a, i);
nano::keypair pair (prv.data.to_string ());
// Check if account received at least 1 block
auto latest (wallets.node.ledger.latest (block_transaction, pair.pub));
if (!latest.is_zero ())
{
index = i;
// i + 64 - Check additional 64 accounts
// i/64 - Check additional accounts for large wallets. I.e. 64000/64 = 1000 accounts to check
n = i + 64 + (i / 64);
}
else
{
// Check if there are pending blocks for account
for (auto ii (wallets.node.store.pending_begin (block_transaction, nano::pending_key (pair.pub, 0))); nano::pending_key (ii->first).account == pair.pub; ++ii)
{
index = i;
n = i + 64 + (i / 64);
break;
}
}
}
return index;
}
nano::public_key nano::wallet::change_seed (nano::transaction const & transaction_a, nano::raw_key const & prv_a, uint32_t count)
{
store.seed_set (transaction_a, prv_a);
auto account = deterministic_insert (transaction_a);
if (count == 0)
{
count = deterministic_check (transaction_a, 0);
}
for (uint32_t i (0); i < count; ++i)
{
// Disable work generation to prevent weak CPU nodes stuck
account = deterministic_insert (transaction_a, false);
}
return account;
}
void nano::wallet::deterministic_restore (nano::transaction const & transaction_a)
{
auto index (store.deterministic_index_get (transaction_a));
auto new_index (deterministic_check (transaction_a, index));
for (uint32_t i (index); i <= new_index && index != new_index; ++i)
{
// Disable work generation to prevent weak CPU nodes stuck
deterministic_insert (transaction_a, false);
}
}
bool nano::wallet::live ()
{
return store.handle != 0;
}
void nano::wallet::work_cache_blocking (nano::account const & account_a, nano::block_hash const & root_a)
{
auto opt_work_l (wallets.node.work_generate_blocking (root_a));
if (opt_work_l.is_initialized ())
{
auto transaction_l (wallets.tx_begin_write ());
if (live () && store.exists (transaction_l, account_a))
{
work_update (transaction_l, account_a, root_a, *opt_work_l);
}
}
else
{
wallets.node.logger.try_log (boost::str (boost::format ("Could not precache work for root %1 due to work generation failure") % root_a.to_string ()));
}
}
nano::work_watcher::work_watcher (nano::node & node_a) :
node (node_a),
stopped (false)
{
node.observers.blocks.add ([this](nano::election_status const & status_a, nano::account const & account_a, nano::amount const & amount_a, bool is_state_send_a) {
this->remove (status_a.winner);
});
}
nano::work_watcher::~work_watcher ()
{
stop ();
}
void nano::work_watcher::stop ()
{
nano::unique_lock<std::mutex> lock (mutex);
watched.clear ();
stopped = true;
}
void nano::work_watcher::add (std::shared_ptr<nano::block> block_a)
{
auto block_l (std::dynamic_pointer_cast<nano::state_block> (block_a));
if (!stopped && block_l != nullptr)
{
auto root_l (block_l->qualified_root ());
nano::unique_lock<std::mutex> lock (mutex);
watched[root_l] = block_l;
lock.unlock ();
watching (root_l, block_l);
}
}
void nano::work_watcher::update (nano::qualified_root const & root_a, std::shared_ptr<nano::state_block> block_a)
{
nano::lock_guard<std::mutex> guard (mutex);
watched[root_a] = block_a;
}
void nano::work_watcher::watching (nano::qualified_root const & root_a, std::shared_ptr<nano::state_block> block_a)
{
std::weak_ptr<nano::work_watcher> watcher_w (shared_from_this ());
node.alarm.add (std::chrono::steady_clock::now () + node.config.work_watcher_period, [block_a, root_a, watcher_w]() {
auto watcher_l = watcher_w.lock ();
if (watcher_l && !watcher_l->stopped && block_a != nullptr)
{
nano::unique_lock<std::mutex> lock (watcher_l->mutex);
if (watcher_l->watched.find (root_a) != watcher_l->watched.end ()) // not yet confirmed or cancelled
{
lock.unlock ();
uint64_t difficulty (0);
auto root_l (block_a->root ());
nano::work_validate (root_l, block_a->block_work (), &difficulty);
auto active_difficulty (watcher_l->node.active.limited_active_difficulty ());
if (active_difficulty > difficulty)
{
watcher_l->node.work_generate (
root_l, [watcher_l, block_a, root_a](boost::optional<uint64_t> work_a) {
if (block_a != nullptr && watcher_l != nullptr && !watcher_l->stopped)
{
bool updated_l{ false };
if (work_a.is_initialized ())
{
nano::state_block_builder builder;
std::error_code ec;
std::shared_ptr<nano::state_block> block (builder.from (*block_a).work (*work_a).build (ec));
if (!ec)
{
{
auto hash (block_a->hash ());
nano::lock_guard<std::mutex> active_guard (watcher_l->node.active.mutex);
auto existing (watcher_l->node.active.roots.find (root_a));
if (existing != watcher_l->node.active.roots.end ())
{
auto election (existing->election);
if (election->status.winner->hash () == hash)
{
election->status.winner = block;
}
auto current (election->blocks.find (hash));
assert (current != election->blocks.end ());
current->second = block;
}
}
watcher_l->node.network.flood_block (block, false);
watcher_l->node.active.update_difficulty (*block.get ());
watcher_l->update (root_a, block);
updated_l = true;
watcher_l->watching (root_a, block);
}
}
if (!updated_l)
{
watcher_l->watching (root_a, block_a);
}
}
},
active_difficulty);
}
else
{
watcher_l->watching (root_a, block_a);
}
}
}
});
}
void nano::work_watcher::remove (std::shared_ptr<nano::block> block_a)
{
auto root_l (block_a->qualified_root ());
nano::lock_guard<std::mutex> lock (mutex);
auto existing (watched.find (root_l));
if (existing != watched.end () && existing->second->hash () == block_a->hash ())
{
watched.erase (existing);
node.observers.work_cancel.notify (block_a->root ());
}
}
bool nano::work_watcher::is_watched (nano::qualified_root const & root_a)
{
nano::lock_guard<std::mutex> guard (mutex);
auto exists (watched.find (root_a));
return exists != watched.end ();
}
size_t nano::work_watcher::size ()
{
nano::lock_guard<std::mutex> guard (mutex);
return watched.size ();
}
void nano::wallets::do_wallet_actions ()
{
nano::unique_lock<std::mutex> action_lock (action_mutex);
while (!stopped)
{
if (!actions.empty ())
{
auto first (actions.begin ());
auto wallet (first->second.first);
auto current (std::move (first->second.second));
actions.erase (first);
if (wallet->live ())
{
action_lock.unlock ();
observer (true);
current (*wallet);
observer (false);
action_lock.lock ();
}
}
else
{
condition.wait (action_lock);
}
}
}
nano::wallets::wallets (bool error_a, nano::node & node_a) :
observer ([](bool) {}),
node (node_a),
env (boost::polymorphic_downcast<nano::mdb_wallets_store *> (node_a.wallets_store_impl.get ())->environment),
stopped (false),
watcher (std::make_shared<nano::work_watcher> (node_a)),
thread ([this]() {
nano::thread_role::set (nano::thread_role::name::wallet_actions);
do_wallet_actions ();
})
{
nano::unique_lock<std::mutex> lock (mutex);
if (!error_a)
{
auto transaction (tx_begin_write ());
auto status (mdb_dbi_open (env.tx (transaction), nullptr, MDB_CREATE, &handle));
split_if_needed (transaction, node.store);
status |= mdb_dbi_open (env.tx (transaction), "send_action_ids", MDB_CREATE, &send_action_ids);
assert (status == 0);
std::string beginning (nano::uint256_union (0).to_string ());
std::string end ((nano::uint256_union (nano::uint256_t (0) - nano::uint256_t (1))).to_string ());
nano::store_iterator<std::array<char, 64>, nano::no_value> i (std::make_unique<nano::mdb_iterator<std::array<char, 64>, nano::no_value>> (transaction, handle, nano::mdb_val (beginning.size (), const_cast<char *> (beginning.c_str ()))));
nano::store_iterator<std::array<char, 64>, nano::no_value> n (std::make_unique<nano::mdb_iterator<std::array<char, 64>, nano::no_value>> (transaction, handle, nano::mdb_val (end.size (), const_cast<char *> (end.c_str ()))));
for (; i != n; ++i)
{
nano::uint256_union id;
std::string text (i->first.data (), i->first.size ());
auto error (id.decode_hex (text));
assert (!error);
assert (items.find (id) == items.end ());
auto wallet (std::make_shared<nano::wallet> (error, transaction, *this, text));
if (!error)
{
items[id] = wallet;
}
else
{
// Couldn't open wallet
}
}
}
// Backup before upgrade wallets
bool backup_required (false);
if (node.config.backup_before_upgrade)
{
auto transaction (tx_begin_read ());
for (auto & item : items)
{
if (item.second->store.version (transaction) != nano::wallet_store::version_current)
{
backup_required = true;
break;
}
}
}
if (backup_required)
{
const char * store_path;
mdb_env_get_path (env, &store_path);
const boost::filesystem::path path (store_path);
nano::mdb_store::create_backup_file (env, path, node_a.logger);
}
for (auto & item : items)
{
item.second->enter_initial_password ();
}
if (node_a.config.enable_voting)
{
lock.unlock ();
ongoing_compute_reps ();
}
}
nano::wallets::~wallets ()
{
stop ();
}
std::shared_ptr<nano::wallet> nano::wallets::open (nano::uint256_union const & id_a)
{
nano::lock_guard<std::mutex> lock (mutex);
std::shared_ptr<nano::wallet> result;
auto existing (items.find (id_a));
if (existing != items.end ())
{
result = existing->second;
}
return result;
}
std::shared_ptr<nano::wallet> nano::wallets::create (nano::uint256_union const & id_a)
{
nano::lock_guard<std::mutex> lock (mutex);
assert (items.find (id_a) == items.end ());
std::shared_ptr<nano::wallet> result;
bool error;
{
auto transaction (tx_begin_write ());
result = std::make_shared<nano::wallet> (error, transaction, *this, id_a.to_string ());
}
if (!error)
{
items[id_a] = result;
result->enter_initial_password ();
}
return result;
}
bool nano::wallets::search_pending (nano::uint256_union const & wallet_a)
{
nano::lock_guard<std::mutex> lock (mutex);
auto result (false);
auto existing (items.find (wallet_a));
result = existing == items.end ();
if (!result)
{
auto wallet (existing->second);
result = wallet->search_pending ();
}
return result;
}
void nano::wallets::search_pending_all ()
{
nano::lock_guard<std::mutex> lock (mutex);
for (auto i : items)
{
i.second->search_pending ();
}
}
void nano::wallets::destroy (nano::uint256_union const & id_a)
{
nano::lock_guard<std::mutex> lock (mutex);
auto transaction (tx_begin_write ());
// action_mutex should be after transactions to prevent deadlocks in deterministic_insert () & insert_adhoc ()
nano::lock_guard<std::mutex> action_lock (action_mutex);
auto existing (items.find (id_a));
assert (existing != items.end ());
auto wallet (existing->second);
items.erase (existing);
wallet->store.destroy (transaction);
}
void nano::wallets::reload ()
{
nano::lock_guard<std::mutex> lock (mutex);
auto transaction (tx_begin_write ());
std::unordered_set<nano::uint256_union> stored_items;
std::string beginning (nano::uint256_union (0).to_string ());
std::string end ((nano::uint256_union (nano::uint256_t (0) - nano::uint256_t (1))).to_string ());
nano::store_iterator<std::array<char, 64>, nano::no_value> i (std::make_unique<nano::mdb_iterator<std::array<char, 64>, nano::no_value>> (transaction, handle, nano::mdb_val (beginning.size (), const_cast<char *> (beginning.c_str ()))));
nano::store_iterator<std::array<char, 64>, nano::no_value> n (std::make_unique<nano::mdb_iterator<std::array<char, 64>, nano::no_value>> (transaction, handle, nano::mdb_val (end.size (), const_cast<char *> (end.c_str ()))));
for (; i != n; ++i)
{
nano::uint256_union id;
std::string text (i->first.data (), i->first.size ());
auto error (id.decode_hex (text));
assert (!error);
// New wallet
if (items.find (id) == items.end ())
{
auto wallet (std::make_shared<nano::wallet> (error, transaction, *this, text));
if (!error)
{
items[id] = wallet;
}
}
// List of wallets on disk
stored_items.insert (id);
}
// Delete non existing wallets from memory
std::vector<nano::uint256_union> deleted_items;
for (auto i : items)
{
if (stored_items.find (i.first) == stored_items.end ())
{
deleted_items.push_back (i.first);
}
}
for (auto & i : deleted_items)
{
assert (items.find (i) == items.end ());
items.erase (i);
}
}
void nano::wallets::queue_wallet_action (nano::uint128_t const & amount_a, std::shared_ptr<nano::wallet> wallet_a, std::function<void(nano::wallet &)> const & action_a)
{
{
nano::lock_guard<std::mutex> action_lock (action_mutex);
actions.insert (std::make_pair (amount_a, std::make_pair (wallet_a, std::move (action_a))));
}
condition.notify_all ();
}
void nano::wallets::foreach_representative (std::function<void(nano::public_key const & pub_a, nano::raw_key const & prv_a)> const & action_a)
{
if (node.config.enable_voting)
{
nano::lock_guard<std::mutex> lock (mutex);
auto transaction_l (tx_begin_read ());
for (auto i (items.begin ()), n (items.end ()); i != n; ++i)
{
auto & wallet (*i->second);
nano::lock_guard<std::recursive_mutex> store_lock (wallet.store.mutex);
nano::lock_guard<std::mutex> representatives_lock (wallet.representatives_mutex);
for (auto ii (wallet.representatives.begin ()), nn (wallet.representatives.end ()); ii != nn; ++ii)
{
nano::account account (*ii);
if (wallet.store.exists (transaction_l, account))
{
if (!node.ledger.weight (account).is_zero ())
{
if (wallet.store.valid_password (transaction_l))
{
nano::raw_key prv;
auto error (wallet.store.fetch (transaction_l, account, prv));
(void)error;
assert (!error);
action_a (account, prv);
}
else
{
static auto last_log = std::chrono::steady_clock::time_point ();
if (last_log < std::chrono::steady_clock::now () - std::chrono::seconds (60))
{
last_log = std::chrono::steady_clock::now ();
node.logger.always_log (boost::str (boost::format ("Representative locked inside wallet %1%") % i->first.to_string ()));
}
}
}
}
}
}
}
}
bool nano::wallets::exists (nano::transaction const & transaction_a, nano::public_key const & account_a)
{
nano::lock_guard<std::mutex> lock (mutex);
auto result (false);
for (auto i (items.begin ()), n (items.end ()); !result && i != n; ++i)
{
result = i->second->store.exists (transaction_a, account_a);
}
return result;
}
void nano::wallets::stop ()
{
{
nano::lock_guard<std::mutex> action_lock (action_mutex);
stopped = true;
actions.clear ();
}
condition.notify_all ();
if (thread.joinable ())
{
thread.join ();
}
watcher->stop ();
}
nano::write_transaction nano::wallets::tx_begin_write ()
{
return env.tx_begin_write ();
}
nano::read_transaction nano::wallets::tx_begin_read ()
{
return env.tx_begin_read ();
}
void nano::wallets::clear_send_ids (nano::transaction const & transaction_a)
{
auto status (mdb_drop (env.tx (transaction_a), send_action_ids, 0));
(void)status;
assert (status == 0);
}
bool nano::wallets::check_rep (nano::account const & account_a, nano::uint128_t const & half_principal_weight_a)
{
bool result (false);
auto weight (node.ledger.weight (account_a));
if (weight >= node.config.vote_minimum.number ())
{
result = true;
++reps_count;
if (weight >= half_principal_weight_a)
{
++half_principal_reps_count;
}
}
return result;
}
void nano::wallets::compute_reps ()
{
nano::lock_guard<std::mutex> lock (mutex);
reps_count = 0;
half_principal_reps_count = 0;
auto half_principal_weight (node.minimum_principal_weight () / 2);
auto transaction (tx_begin_read ());
for (auto i (items.begin ()), n (items.end ()); i != n; ++i)
{
auto & wallet (*i->second);
decltype (wallet.representatives) representatives_l;
for (auto ii (wallet.store.begin (transaction)), nn (wallet.store.end ()); ii != nn; ++ii)
{
auto account (ii->first);
if (check_rep (account, half_principal_weight))
{
representatives_l.insert (account);
}
}
nano::lock_guard<std::mutex> representatives_lock (wallet.representatives_mutex);
wallet.representatives.swap (representatives_l);
}
}
void nano::wallets::ongoing_compute_reps ()
{
compute_reps ();
auto & node_l (node);
auto compute_delay (network_params.network.is_test_network () ? std::chrono::milliseconds (10) : std::chrono::milliseconds (15 * 60 * 1000)); // Representation drifts quickly on the test network but very slowly on the live network
node.alarm.add (std::chrono::steady_clock::now () + compute_delay, [&node_l]() {
node_l.wallets.ongoing_compute_reps ();
});
}
void nano::wallets::split_if_needed (nano::transaction & transaction_destination, nano::block_store & store_a)
{
auto store_l (dynamic_cast<nano::mdb_store *> (&store_a));
if (store_l != nullptr)
{
if (items.empty ())
{
std::string beginning (nano::uint256_union (0).to_string ());
std::string end ((nano::uint256_union (nano::uint256_t (0) - nano::uint256_t (1))).to_string ());
// clang-format off
auto get_store_it = [&handle = handle](nano::transaction const & transaction_source, std::string const & hash) {
return nano::store_iterator<std::array<char, 64>, nano::no_value> (std::make_unique<nano::mdb_iterator<std::array<char, 64>, nano::no_value>> (transaction_source, handle, nano::mdb_val (hash.size (), const_cast<char *> (hash.c_str ()))));
};
// clang-format on
// First do a read pass to check if there are any wallets that need extracting (to save holding a write lock and potentially being blocked)
auto wallets_need_splitting (false);
{
auto transaction_source (store_l->tx_begin_read ());
auto i = get_store_it (transaction_source, beginning);
auto n = get_store_it (transaction_source, end);
wallets_need_splitting = (i != n);
}
if (wallets_need_splitting)
{
auto transaction_source (store_l->tx_begin_write ());
auto i = get_store_it (transaction_source, beginning);
auto n = get_store_it (transaction_source, end);
auto tx_source = static_cast<MDB_txn *> (transaction_source.get_handle ());
auto tx_destination = static_cast<MDB_txn *> (transaction_destination.get_handle ());
for (; i != n; ++i)
{
nano::uint256_union id;
std::string text (i->first.data (), i->first.size ());
auto error1 (id.decode_hex (text));
(void)error1;
assert (!error1);
assert (strlen (text.c_str ()) == text.size ());
move_table (text, tx_source, tx_destination);
}
}
}
}
}
void nano::wallets::move_table (std::string const & name_a, MDB_txn * tx_source, MDB_txn * tx_destination)
{
MDB_dbi handle_source;
auto error2 (mdb_dbi_open (tx_source, name_a.c_str (), MDB_CREATE, &handle_source));
(void)error2;
assert (!error2);
MDB_dbi handle_destination;
auto error3 (mdb_dbi_open (tx_destination, name_a.c_str (), MDB_CREATE, &handle_destination));
(void)error3;
assert (!error3);
MDB_cursor * cursor;
auto error4 (mdb_cursor_open (tx_source, handle_source, &cursor));
(void)error4;
assert (!error4);
MDB_val val_key;
MDB_val val_value;
auto cursor_status (mdb_cursor_get (cursor, &val_key, &val_value, MDB_FIRST));
while (cursor_status == MDB_SUCCESS)
{
auto error5 (mdb_put (tx_destination, handle_destination, &val_key, &val_value, 0));
(void)error5;
assert (!error5);
cursor_status = mdb_cursor_get (cursor, &val_key, &val_value, MDB_NEXT);
}
auto error6 (mdb_drop (tx_source, handle_source, 1));
(void)error6;
assert (!error6);
}
nano::uint128_t const nano::wallets::generate_priority = std::numeric_limits<nano::uint128_t>::max ();
nano::uint128_t const nano::wallets::high_priority = std::numeric_limits<nano::uint128_t>::max () - 1;
nano::store_iterator<nano::uint256_union, nano::wallet_value> nano::wallet_store::begin (nano::transaction const & transaction_a)
{
nano::store_iterator<nano::uint256_union, nano::wallet_value> result (std::make_unique<nano::mdb_iterator<nano::uint256_union, nano::wallet_value>> (transaction_a, handle, nano::mdb_val (nano::uint256_union (special_count))));
return result;
}
nano::store_iterator<nano::uint256_union, nano::wallet_value> nano::wallet_store::begin (nano::transaction const & transaction_a, nano::uint256_union const & key)
{
nano::store_iterator<nano::uint256_union, nano::wallet_value> result (std::make_unique<nano::mdb_iterator<nano::uint256_union, nano::wallet_value>> (transaction_a, handle, nano::mdb_val (key)));
return result;
}
nano::store_iterator<nano::uint256_union, nano::wallet_value> nano::wallet_store::find (nano::transaction const & transaction_a, nano::uint256_union const & key)
{
auto result (begin (transaction_a, key));
nano::store_iterator<nano::uint256_union, nano::wallet_value> end (nullptr);
if (result != end)
{
if (nano::uint256_union (result->first) == key)
{
return result;
}
else
{
return end;
}
}
else
{
return end;
}
return result;
}
nano::store_iterator<nano::uint256_union, nano::wallet_value> nano::wallet_store::end ()
{
return nano::store_iterator<nano::uint256_union, nano::wallet_value> (nullptr);
}
nano::mdb_wallets_store::mdb_wallets_store (boost::filesystem::path const & path_a, int lmdb_max_dbs) :
environment (error, path_a, lmdb_max_dbs, false, 1ULL * 1024 * 1024 * 1024)
{
}
bool nano::mdb_wallets_store::init_error () const
{
return error;
}
MDB_txn * nano::wallet_store::tx (nano::transaction const & transaction_a) const
{
return static_cast<MDB_txn *> (transaction_a.get_handle ());
}
namespace nano
{
std::unique_ptr<seq_con_info_component> collect_seq_con_info (wallets & wallets, const std::string & name)
{
size_t items_count = 0;
size_t actions_count = 0;
{
nano::lock_guard<std::mutex> guard (wallets.mutex);
items_count = wallets.items.size ();
actions_count = wallets.actions.size ();
}
auto composite = std::make_unique<seq_con_info_composite> (name);
auto sizeof_item_element = sizeof (decltype (wallets.items)::value_type);
auto sizeof_actions_element = sizeof (decltype (wallets.actions)::value_type);
composite->add_component (std::make_unique<seq_con_info_leaf> (seq_con_info{ "items", items_count, sizeof_item_element }));
composite->add_component (std::make_unique<seq_con_info_leaf> (seq_con_info{ "actions", actions_count, sizeof_actions_element }));
return composite;
}
}
|
// MIT License
//
// Copyright (c) 2020, The Regents of the University of California,
// through Lawrence Berkeley National Laboratory (subject to receipt of any
// required approvals from the U.S. Dept. of Energy). 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.
/**
* \file timemory/settings/types.hpp
* \brief Declare the settings types
*/
#pragma once
#include "timemory/compat/macros.h"
#include "timemory/settings/macros.hpp"
#include <functional>
#include <map>
#include <string>
#include <vector>
namespace tim
{
//
//--------------------------------------------------------------------------------------//
//
// settings
//
//--------------------------------------------------------------------------------------//
//
using setting_callback_t = std::function<void()>;
using setting_callback_map_t = std::map<std::string, setting_callback_t>;
using setting_description_map_t = std::map<std::string, std::string>;
//
//--------------------------------------------------------------------------------------//
//
std::string
get_local_datetime(const char* dt_format);
//
//--------------------------------------------------------------------------------------//
//
struct settings;
//
//--------------------------------------------------------------------------------------//
//
template <typename... T>
inline setting_callback_map_t&
get_parse_callback_map()
{
static setting_callback_map_t _instance;
return _instance;
}
//
//--------------------------------------------------------------------------------------//
//
template <typename... T>
inline setting_description_map_t&
get_descriptions()
{
static setting_description_map_t _instance;
return _instance;
}
//
//--------------------------------------------------------------------------------------//
//
TIMEMORY_SETTINGS_DLL setting_callback_map_t&
get_parse_callbacks() TIMEMORY_VISIBILITY("default");
//
TIMEMORY_SETTINGS_DLL setting_description_map_t&
get_setting_descriptions() TIMEMORY_VISIBILITY("default");
//
//--------------------------------------------------------------------------------------//
//
} // namespace tim
|
/*
* a.cpp
* Copyright (C) 2021 Woshiluo Luo <woshiluo.luo@outlook.com>
*
* 「Two roads diverged in a wood,and I—
* I took the one less traveled by,
* And that has made all the difference.」
*
* Distributed under terms of the GNU AGPLv3+ license.
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
typedef long long ll;
typedef unsigned long long ull;
inline bool isdigit( const char cur ) { return cur >= '0' && cur <= '9'; }/*{{{*/
template <class T>
T Max( T a, T b ) { return a > b? a: b; }
template <class T>
T Min( T a, T b ) { return a < b? a: b; }
template <class T>
void chk_Max( T &a, T b ) { if( b > a ) a = b; }
template <class T>
void chk_Min( T &a, T b ) { if( b < a ) a = b; }
template <typename T>
T read() {
T sum = 0, fl = 1;
char ch = getchar();
for (; isdigit(ch) == 0; ch = getchar())
if (ch == '-') fl = -1;
for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0';
return sum * fl;
}
template <class T>
T pow( T a, int p ) {
T res = 1;
while( p ) {
if( p & 1 )
res = res * a;
a = a * a;
p >>= 1;
}
return res;
}/*}}}*/
const int N = 110;
char a[N], b[N];
bool work() {
int max_len = Max( strlen( a + 1 ), strlen( b + 1 ) );
for( int i = 1; i <= max_len; i ++ ) {
if( a[i] < b[i] )
return true;
if( a[i] > b[i] )
return false;
}
return false;
}
int main() {
scanf( "%s", a + 1 );
scanf( "%s", b + 1 );
printf( "%s\n", work()? "Yes": "No" );
}
|
#include "PhysicsManager.h"
#include "../Physics/Colliders/BoxCollider.h"
physx::PxRigidDynamic* dynamicTest;
physx::PxPhysics* PhysicsManager::gPhysics = nullptr;
physx::PxScene* PhysicsManager::gScene = nullptr;
physx::PxMaterial* PhysicsManager::gMaterial = nullptr;
bool PhysicsManager::preUpdate = true;
bool PhysicsManager::foundationCreated = false;
bool PhysicsManager::physicsCreated = false;
bool PhysicsManager::sceneCreated = false;
PhysicsContactListener PhysicsManager::listener;
Vector3 PhysicsManager::gravity(0, -9.81, 0);
std::vector<physx::PxRigidDynamic*> PhysicsManager::allDynamics;
std::vector<physx::PxRigidStatic*> PhysicsManager::allStatics;
void PhysicsManager::OnStartup()
{
}
void PhysicsManager::OnStart()
{
if (PhysicsManager::sceneCreated == true && gScene != nullptr)
{
gScene->release();
}
if (!PhysicsManager::foundationCreated)
{
gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback);
}
if (!PhysicsManager::physicsCreated)
{
gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, physx::PxTolerancesScale(), true);
}
physx::PxSceneDesc sceneDesc(gPhysics->getTolerancesScale());
sceneDesc.gravity = physx::PxVec3(gravity.x, gravity.y, gravity.z);
gDispatcher = physx::PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = gDispatcher;
sceneDesc.filterShader = PhysicsManager::contactReportFilterShader;
sceneDesc.simulationEventCallback = &PhysicsManager::listener;
gScene = gPhysics->createScene(sceneDesc);
gMaterial = PhysicsManager::gPhysics->createMaterial(0.5f, 0.5f, 0);
PhysicsManager::physicsCreated = true;
PhysicsManager::foundationCreated = true;
PhysicsManager::sceneCreated = true;
PhysicsManager::preUpdate = true;
}
void PhysicsManager::OnUpdate()
{
gScene->simulate(Graphics::DeltaTime());
gScene->fetchResults(true);
if (preUpdate)
{
for (auto i : PhysicsManager::allDynamics)
{
gScene->addActor(*i);
}
for (auto i : PhysicsManager::allStatics)
{
gScene->addActor(*i);
}
std::cout << PhysicsManager::allDynamics.size() << std::endl;
preUpdate = false;
}
}
void PhysicsManager::OnDestroy()
{
PhysicsManager::allDynamics.clear();
std::vector<physx::PxRigidDynamic*>().swap(PhysicsManager::allDynamics);
PhysicsManager::allStatics.clear();
std::vector<physx::PxRigidStatic*>().swap(PhysicsManager::allStatics);
}
void PhysicsManager::SetGravity(Vector3 g)
{
gravity = g;
gScene->setGravity(physx::PxVec3(gravity.x, gravity.y, gravity.z));
}
physx::PxRigidStatic* PhysicsManager::CreateStaticBox(BoxCollider& collider, Vector3 position, Vector3 scale)
{
physx::PxShape* boxShape = PhysicsManager::gPhysics->createShape(physx::PxBoxGeometry(scale.x / 2, scale.y / 2, scale.z / 2), *PhysicsManager::gMaterial);
physx::PxRigidStatic* boxStatic = physx::PxCreateStatic(*PhysicsManager::gPhysics,
physx::PxTransform(physx::PxVec3(position.x, position.y, position.z)),
*boxShape);
PhysicsManager::allStatics.push_back(boxStatic);
int size = PhysicsManager::allStatics.size() - 1;
if (!preUpdate && Application::_engineState == Application::Game)
gScene->addActor(*allStatics[size]);
return boxStatic;
}
physx::PxRigidDynamic* PhysicsManager::CreateDynamicBox(BoxCollider& collider, Vector3 position, Vector3 scale)
{
physx::PxShape* boxShape = PhysicsManager::gPhysics->createShape(physx::PxBoxGeometry(scale.x / 2, scale.y / 2, scale.z / 2), *PhysicsManager::gMaterial);
collider.boxShape = boxShape;
physx::PxRigidDynamic* boxDynamic = physx::PxCreateDynamic(*PhysicsManager::gPhysics,
physx::PxTransform(physx::PxVec3(position.x, position.y, position.z)),
*boxShape, 0);
PhysicsManager::allDynamics.push_back(boxDynamic);
int size = PhysicsManager::allDynamics.size() - 1;
if (!preUpdate && Application::_engineState == Application::Game)
gScene->addActor(*allDynamics[size]);
return boxDynamic;
}
bool PhysicsManager::Raycast(Vector3 origin, Vector3 direction, int maxDistance)
{
physx::PxRaycastBuffer hit;
physx::PxVec3 o(origin.x, origin.y, origin.z), d(direction.x, direction.y, direction.z);
return PhysicsManager::gScene->raycast(o, d, maxDistance, hit);
}
bool PhysicsManager::Raycast(Vector3 origin, Vector3 direction, int maxDistance, RaycastBuffer& buff)
{
const physx::PxU32 bufferSize = 256;
physx::PxRaycastHit hitBuffer[bufferSize];
physx::PxRaycastBuffer hit(hitBuffer, bufferSize);
physx::PxVec3 o(origin.x, origin.y, origin.z), d(direction.x, direction.y, direction.z);
bool ray = PhysicsManager::gScene->raycast(o, d, maxDistance, hit);
if(ray)
{
for (physx::PxU32 i = 0; i < hit.nbTouches; i++)
{
buff.hitScripts.push_back(reinterpret_cast<ScriptBehaviour*>(hit.touches[i].actor->userData));
}
return true;
}
return false;
}
physx::PxFilterFlags PhysicsManager::contactReportFilterShader(physx::PxFilterObjectAttributes attributes0, physx::PxFilterData filterData0,
physx::PxFilterObjectAttributes attributes1, physx::PxFilterData filterData1,
physx::PxPairFlags& pairFlags, const void* constantBlock, physx::PxU32 constantBlockSize)
{
PX_UNUSED(attributes0);
PX_UNUSED(attributes1);
PX_UNUSED(filterData0);
PX_UNUSED(filterData1);
PX_UNUSED(constantBlockSize);
PX_UNUSED(constantBlock);
// all initial and persisting reports for everything, with per-point data
pairFlags = physx::PxPairFlag::eSOLVE_CONTACT | physx::PxPairFlag::eDETECT_DISCRETE_CONTACT
| physx::PxPairFlag::eNOTIFY_TOUCH_FOUND
| physx::PxPairFlag::eNOTIFY_TOUCH_LOST
| physx::PxPairFlag::eNOTIFY_TOUCH_PERSISTS
| physx::PxPairFlag::eNOTIFY_CONTACT_POINTS;
return physx::PxFilterFlag::eDEFAULT;
}
void PhysicsContactListener::onContact(const physx::PxContactPairHeader& pairHeader, const physx::PxContactPair* pairs, physx::PxU32 nbPairs)
{
for (physx::PxU32 i = 0; i < nbPairs; i++)
{
const physx::PxContactPair& cp = pairs[i];
ScriptBehaviour* b1 = reinterpret_cast<ScriptBehaviour*>(pairHeader.actors[0]->userData);
ScriptBehaviour* b2 = reinterpret_cast<ScriptBehaviour*>(pairHeader.actors[1]->userData);
if (cp.events & physx::PxPairFlag::eNOTIFY_TOUCH_FOUND)
{
if (b1 != nullptr)
b1->OnCollisionEnter();
if (b2 != nullptr)
b2->OnCollisionEnter();
}
else if(cp.events & physx::PxPairFlag::eNOTIFY_TOUCH_LOST)
{
if (b1 != nullptr)
b1->OnCollisionExit();
if (b2 != nullptr)
b2->OnCollisionExit();
}
}
}
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2021 Baldur Karlsson
*
* 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.
******************************************************************************/
#define AMD_GPUPERFAPI_SKIP_VULKAN_INCLUDE 1
#include "vk_debug.h"
#include <float.h>
#include "core/settings.h"
#include "data/glsl_shaders.h"
#include "driver/ihv/amd/amd_counters.h"
#include "driver/ihv/amd/official/GPUPerfAPI/Include/gpu_perf_api_vk.h"
#include "driver/shaders/spirv/spirv_compile.h"
#include "maths/camera.h"
#include "maths/formatpacking.h"
#include "maths/matrix.h"
#include "vk_core.h"
#include "vk_replay.h"
#include "vk_shader_cache.h"
#define VULKAN 1
#include "data/glsl/glsl_ubos_cpp.h"
RDOC_CONFIG(bool, Vulkan_HardwareCounters, true,
"Enable support for IHV-specific hardware counters on Vulkan.");
const VkDeviceSize STAGE_BUFFER_BYTE_SIZE = 16 * 1024 * 1024ULL;
static void create(WrappedVulkan *driver, const char *objName, const int line, VkSampler *sampler,
VkFilter samplerFilter)
{
VkSamplerCreateInfo sampInfo = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
sampInfo.minFilter = sampInfo.magFilter = samplerFilter;
sampInfo.mipmapMode = samplerFilter == VK_FILTER_NEAREST ? VK_SAMPLER_MIPMAP_MODE_NEAREST
: VK_SAMPLER_MIPMAP_MODE_LINEAR;
sampInfo.addressModeU = sampInfo.addressModeV = sampInfo.addressModeW =
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampInfo.maxLod = 128.0f;
VkResult vkr = driver->vkCreateSampler(driver->GetDev(), &sampInfo, NULL, sampler);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
}
static void create(WrappedVulkan *driver, const char *objName, const int line,
VkDescriptorSetLayout *descLayout,
std::initializer_list<VkDescriptorSetLayoutBinding> bindings)
{
VkDescriptorSetLayoutCreateInfo descsetLayoutInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
NULL,
0,
(uint32_t)bindings.size(),
bindings.begin(),
};
VkResult vkr =
driver->vkCreateDescriptorSetLayout(driver->GetDev(), &descsetLayoutInfo, NULL, descLayout);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
}
static void create(WrappedVulkan *driver, const char *objName, const int line,
VkPipelineLayout *pipeLayout, VkDescriptorSetLayout setLayout, uint32_t pushBytes)
{
VkPipelineLayoutCreateInfo pipeLayoutInfo = {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
VkPushConstantRange push = {VK_SHADER_STAGE_ALL, 0, pushBytes};
if(pushBytes > 0)
{
pipeLayoutInfo.pPushConstantRanges = &push;
pipeLayoutInfo.pushConstantRangeCount = 1;
}
pipeLayoutInfo.pSetLayouts = &setLayout;
pipeLayoutInfo.setLayoutCount = 1;
VkResult vkr = driver->vkCreatePipelineLayout(driver->GetDev(), &pipeLayoutInfo, NULL, pipeLayout);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
}
// create a single subpass renderpass with a single attachment
static void create(WrappedVulkan *driver, const char *objName, const int line,
VkRenderPass *renderPass, VkFormat attachFormat,
VkSampleCountFlagBits sampleCount = VK_SAMPLE_COUNT_1_BIT,
VkImageLayout layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
{
VkAttachmentDescription attDesc = {0,
attachFormat,
sampleCount,
VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
layout,
layout};
VkAttachmentReference attRef = {0, layout};
VkSubpassDescription sub = {
0, VK_PIPELINE_BIND_POINT_GRAPHICS,
0, NULL, // inputs
1, &attRef, // color
};
if(IsDepthOrStencilFormat(attachFormat))
{
attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
sub.colorAttachmentCount = 0;
sub.pColorAttachments = NULL;
sub.pDepthStencilAttachment = &attRef;
}
VkRenderPassCreateInfo rpinfo = {
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, NULL, 0, 1, &attDesc, 1, &sub,
};
VkResult vkr = driver->vkCreateRenderPass(driver->GetDev(), &rpinfo, NULL, renderPass);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
driver->GetResourceManager()->SetInternalResource(GetResID(*renderPass));
}
// Create a compute pipeline with a shader module
static void create(WrappedVulkan *driver, const char *objName, const int line, VkPipeline *pipe,
VkPipelineLayout pipeLayout, VkShaderModule computeModule)
{
// if the module didn't compile, this pipeline is not be supported. Silently don't create it, code
// later should handle the missing pipeline as indicating lack of support
if(computeModule == VK_NULL_HANDLE)
{
*pipe = VK_NULL_HANDLE;
return;
}
VkComputePipelineCreateInfo compPipeInfo = {
VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
NULL,
0,
{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_COMPUTE_BIT,
computeModule, "main", NULL},
pipeLayout,
VK_NULL_HANDLE,
0,
};
VkResult vkr = driver->vkCreateComputePipelines(
driver->GetDev(), driver->GetShaderCache()->GetPipeCache(), 1, &compPipeInfo, NULL, pipe);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
}
static void create(WrappedVulkan *driver, const char *objName, const int line,
VkDescriptorSet *descSet, VkDescriptorPool pool, VkDescriptorSetLayout setLayout)
{
VkDescriptorSetAllocateInfo descSetAllocInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool, 1, &setLayout,
};
// don't expect this to fail (or if it does then it should be immediately obvious, not transient).
VkResult vkr = driver->vkAllocateDescriptorSets(driver->GetDev(), &descSetAllocInfo, descSet);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
}
// a simpler one-shot descriptor containing anything we might want to vary in a graphics pipeline
struct ConciseGraphicsPipeline
{
// misc
VkRenderPass renderPass;
VkPipelineLayout pipeLayout;
VkShaderModule vertex;
VkShaderModule fragment;
// dynamic state
std::initializer_list<VkDynamicState> dynstates;
// msaa
VkSampleCountFlagBits sampleCount;
bool sampleRateShading;
// depth stencil
bool depthEnable;
bool stencilEnable;
VkStencilOp stencilOp;
// color blend
bool colourOutput;
bool blendEnable;
VkBlendFactor srcBlend;
VkBlendFactor dstBlend;
uint32_t writeMask;
};
static void create(WrappedVulkan *driver, const char *objName, const int line, VkPipeline *pipe,
const ConciseGraphicsPipeline &info)
{
// if the module didn't compile, this pipeline is not be supported. Silently don't create it, code
// later should handle the missing pipeline as indicating lack of support
if(info.vertex == VK_NULL_HANDLE || info.fragment == VK_NULL_HANDLE)
return;
// first configure the structs that contain parameters derived from the info parameter
const VkPipelineShaderStageCreateInfo shaderStages[2] = {
{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_VERTEX_BIT,
info.vertex, "main", NULL},
{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_FRAGMENT_BIT,
info.fragment, "main", NULL},
};
const VkPipelineDynamicStateCreateInfo dynamicState = {
VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
NULL,
0,
(uint32_t)info.dynstates.size(),
info.dynstates.begin(),
};
VkPipelineMultisampleStateCreateInfo msaa = {
VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
};
msaa.rasterizationSamples = info.sampleCount;
if(info.sampleRateShading)
{
msaa.minSampleShading = 1.0f;
msaa.sampleShadingEnable = true;
}
const VkPipelineDepthStencilStateCreateInfo depthStencil = {
VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
NULL,
0,
info.depthEnable,
info.depthEnable,
VK_COMPARE_OP_ALWAYS,
false,
info.stencilEnable,
{info.stencilOp, info.stencilOp, info.stencilOp, VK_COMPARE_OP_ALWAYS, 0xff, 0xff, 0},
{info.stencilOp, info.stencilOp, info.stencilOp, VK_COMPARE_OP_ALWAYS, 0xff, 0xff, 0},
0.0f,
1.0f,
};
const VkPipelineColorBlendAttachmentState colAttach = {
info.blendEnable,
// colour blending
info.srcBlend, info.dstBlend, VK_BLEND_OP_ADD,
// alpha blending
info.srcBlend, info.dstBlend, VK_BLEND_OP_ADD,
// write mask
info.writeMask,
};
const VkPipelineColorBlendStateCreateInfo colorBlend = {
VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
NULL,
0,
false,
VK_LOGIC_OP_NO_OP,
info.colourOutput ? 1U : 0U,
&colAttach,
{1.0f, 1.0f, 1.0f, 1.0f},
};
// below this point, structs are not affected by the info
const VkPipelineVertexInputStateCreateInfo vertexInput = {
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
};
VkPipelineInputAssemblyStateCreateInfo inputAssembly = {
VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
};
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
VkPipelineViewportStateCreateInfo viewScissor = {
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
viewScissor.viewportCount = viewScissor.scissorCount = 1;
// add default scissor, if scissor is dynamic this will be ignored.
VkRect2D scissor = {{0, 0}, {16384, 16384}};
viewScissor.pScissors = &scissor;
// can't really make a sensible one-size-fits-all default viewport like we can with scissors, so
// make it small.
VkViewport viewport = {0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f};
viewScissor.pViewports = &viewport;
VkPipelineRasterizationStateCreateInfo raster = {
VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
};
raster.frontFace = VK_FRONT_FACE_CLOCKWISE;
raster.lineWidth = 1.0f;
const VkGraphicsPipelineCreateInfo graphicsPipeInfo = {
VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
NULL,
0,
2,
shaderStages,
&vertexInput,
&inputAssembly,
NULL, // tess
&viewScissor,
&raster,
&msaa,
&depthStencil,
&colorBlend,
&dynamicState,
info.pipeLayout,
info.renderPass,
0, // sub pass
VK_NULL_HANDLE, // base pipeline handle
-1, // base pipeline index
};
VkResult vkr = driver->vkCreateGraphicsPipelines(
driver->GetDev(), driver->GetShaderCache()->GetPipeCache(), 1, &graphicsPipeInfo, NULL, pipe);
if(vkr != VK_SUCCESS)
RDCERR("Failed creating object %s at line %i, vkr was %s", objName, line, ToStr(vkr).c_str());
}
// utility macro that lets us check for VkResult failures inside the utility helpers while
// preserving context from outside
#define CREATE_OBJECT(obj, ...) create(driver, #obj, __LINE__, &obj, __VA_ARGS__)
VulkanDebugManager::VulkanDebugManager(WrappedVulkan *driver)
{
RenderDoc::Inst().RegisterMemoryRegion(this, sizeof(VulkanDebugManager));
m_pDriver = driver;
m_Device = m_pDriver->GetDev();
VkDevice dev = m_Device;
VulkanResourceManager *rm = driver->GetResourceManager();
VkResult vkr = VK_SUCCESS;
VulkanShaderCache *shaderCache = driver->GetShaderCache();
VkDescriptorPoolSize poolTypes[] = {
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2 * ARRAY_COUNT(m_ArrayMSDescSet)},
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 * ARRAY_COUNT(m_ArrayMSDescSet)},
};
VkDescriptorPoolCreateInfo poolInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
NULL,
0,
ARRAY_COUNT(m_ArrayMSDescSet),
ARRAY_COUNT(poolTypes),
&poolTypes[0],
};
CREATE_OBJECT(m_ArrayMSSampler, VK_FILTER_NEAREST);
rm->SetInternalResource(GetResID(m_ArrayMSSampler));
vkr = m_pDriver->vkCreateDescriptorPool(dev, &poolInfo, NULL, &m_ArrayMSDescriptorPool);
CheckVkResult(vkr);
rm->SetInternalResource(GetResID(m_ArrayMSDescriptorPool));
CREATE_OBJECT(m_ArrayMSDescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{2, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_ALL, NULL},
});
rm->SetInternalResource(GetResID(m_ArrayMSDescSetLayout));
CREATE_OBJECT(m_ArrayMSPipeLayout, m_ArrayMSDescSetLayout, sizeof(Vec4u));
rm->SetInternalResource(GetResID(m_ArrayMSPipeLayout));
//////////////////////////////////////////////////////////////////
// Color MS to Array copy (via compute)
CREATE_OBJECT(m_MS2ArrayPipe, m_ArrayMSPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::MS2ArrayCS));
CREATE_OBJECT(m_Array2MSPipe, m_ArrayMSPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::Array2MSCS));
rm->SetInternalResource(GetResID(m_MS2ArrayPipe));
rm->SetInternalResource(GetResID(m_Array2MSPipe));
//////////////////////////////////////////////////////////////////
// Depth MS to Array copy (via graphics)
// need a dummy UINT texture to fill the binding when we don't have a stencil aspect to copy.
// unfortunately there's no single guaranteed UINT format that can be sampled as MSAA, so we try a
// few since hopefully we'll find one that will work.
VkFormat attemptFormats[] = {VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8_UINT,
VK_FORMAT_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT,
VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT};
for(VkFormat f : attemptFormats)
{
VkImageAspectFlags viewAspectMask =
IsStencilFormat(f) ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_COLOR_BIT;
VkImageAspectFlags barrierAspectMask = viewAspectMask;
if(IsDepthAndStencilFormat(f) && (barrierAspectMask & VK_IMAGE_ASPECT_STENCIL_BIT))
barrierAspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
VkFormatProperties props = {};
driver->vkGetPhysicalDeviceFormatProperties(driver->GetPhysDev(), f, &props);
if(!(props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
continue;
VkImageCreateInfo imInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
NULL,
0,
VK_IMAGE_TYPE_2D,
f,
{1, 1, 1},
1,
1,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_SAMPLED_BIT,
VK_SHARING_MODE_EXCLUSIVE,
0,
NULL,
VK_IMAGE_LAYOUT_UNDEFINED,
};
VkImageFormatProperties imgprops = {};
vkr = driver->vkGetPhysicalDeviceImageFormatProperties(driver->GetPhysDev(), f,
imInfo.imageType, imInfo.tiling,
imInfo.usage, imInfo.flags, &imgprops);
if(vkr == VK_ERROR_FORMAT_NOT_SUPPORTED)
continue;
// if it doesn't support MSAA, bail out
if(imgprops.sampleCounts == VK_SAMPLE_COUNT_1_BIT)
continue;
vkr = driver->vkCreateImage(driver->GetDev(), &imInfo, NULL, &m_DummyStencilImage[0]);
CheckVkResult(vkr);
rm->SetInternalResource(GetResID(m_DummyStencilImage[0]));
imInfo.samples = VK_SAMPLE_COUNT_2_BIT;
// MoltenVK seems to only support 4/8 samples and not 2...
if(imgprops.sampleCounts & VK_SAMPLE_COUNT_2_BIT)
imInfo.samples = VK_SAMPLE_COUNT_2_BIT;
else if(imgprops.sampleCounts & VK_SAMPLE_COUNT_4_BIT)
imInfo.samples = VK_SAMPLE_COUNT_4_BIT;
else if(imgprops.sampleCounts & VK_SAMPLE_COUNT_8_BIT)
imInfo.samples = VK_SAMPLE_COUNT_8_BIT;
else if(imgprops.sampleCounts & VK_SAMPLE_COUNT_16_BIT)
imInfo.samples = VK_SAMPLE_COUNT_16_BIT;
else if(imgprops.sampleCounts & VK_SAMPLE_COUNT_32_BIT)
imInfo.samples = VK_SAMPLE_COUNT_32_BIT;
else
RDCWARN("Can't find supported MSAA sample count");
RDCASSERT(imgprops.sampleCounts & imInfo.samples, imgprops.sampleCounts, imInfo.samples);
vkr = driver->vkCreateImage(driver->GetDev(), &imInfo, NULL, &m_DummyStencilImage[1]);
CheckVkResult(vkr);
rm->SetInternalResource(GetResID(m_DummyStencilImage[1]));
VkMemoryRequirements mrq[2] = {};
driver->vkGetImageMemoryRequirements(driver->GetDev(), m_DummyStencilImage[0], &mrq[0]);
driver->vkGetImageMemoryRequirements(driver->GetDev(), m_DummyStencilImage[1], &mrq[1]);
uint32_t memoryTypeBits = (mrq[0].memoryTypeBits & mrq[1].memoryTypeBits);
// assume we have some memory type available in common
RDCASSERT(memoryTypeBits, mrq[0].memoryTypeBits, mrq[1].memoryTypeBits);
// allocate memory
VkMemoryAllocateInfo allocInfo = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL,
AlignUp(mrq[0].size, mrq[1].alignment) + mrq[1].size,
driver->GetGPULocalMemoryIndex(memoryTypeBits),
};
vkr = driver->vkAllocateMemory(driver->GetDev(), &allocInfo, NULL, &m_DummyStencilMemory);
CheckVkResult(vkr);
if(vkr != VK_SUCCESS)
return;
rm->SetInternalResource(GetResID(m_DummyStencilMemory));
vkr =
driver->vkBindImageMemory(driver->GetDev(), m_DummyStencilImage[0], m_DummyStencilMemory, 0);
CheckVkResult(vkr);
vkr = driver->vkBindImageMemory(driver->GetDev(), m_DummyStencilImage[1], m_DummyStencilMemory,
AlignUp(mrq[0].size, mrq[1].alignment));
CheckVkResult(vkr);
VkImageViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
NULL,
0,
m_DummyStencilImage[0],
VK_IMAGE_VIEW_TYPE_2D_ARRAY,
f,
{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
{
viewAspectMask, 0, 1, 0, 1,
},
};
vkr = driver->vkCreateImageView(driver->GetDev(), &viewInfo, NULL, &m_DummyStencilView[0]);
CheckVkResult(vkr);
rm->SetInternalResource(GetResID(m_DummyStencilView[0]));
viewInfo.image = m_DummyStencilImage[1];
vkr = driver->vkCreateImageView(driver->GetDev(), &viewInfo, NULL, &m_DummyStencilView[1]);
CheckVkResult(vkr);
rm->SetInternalResource(GetResID(m_DummyStencilView[1]));
VkCommandBuffer cmd = driver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
vkr = ObjDisp(cmd)->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
CheckVkResult(vkr);
// need to update image layout into valid state
VkImageMemoryBarrier barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
NULL,
0,
VK_ACCESS_SHADER_READ_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(m_DummyStencilImage[0]),
{barrierAspectMask, 0, 1, 0, 1},
};
DoPipelineBarrier(cmd, 1, &barrier);
barrier.image = Unwrap(m_DummyStencilImage[1]);
DoPipelineBarrier(cmd, 1, &barrier);
ObjDisp(cmd)->EndCommandBuffer(Unwrap(cmd));
break;
}
if(m_DummyStencilImage[0] == VK_NULL_HANDLE)
{
RDCERR("Couldn't find any integer format we could generate a dummy multisampled image with");
}
for(size_t i = 0; i < ARRAY_COUNT(m_ArrayMSDescSet); i++)
{
CREATE_OBJECT(m_ArrayMSDescSet[i], m_ArrayMSDescriptorPool, m_ArrayMSDescSetLayout);
rm->SetInternalResource(GetResID(m_ArrayMSDescSet[i]));
}
VkFormat formats[] = {
VK_FORMAT_D16_UNORM, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_X8_D24_UNORM_PACK32,
VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT,
};
VkSampleCountFlagBits sampleCounts[] = {
VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_8_BIT, VK_SAMPLE_COUNT_16_BIT,
};
RDCCOMPILE_ASSERT(ARRAY_COUNT(m_DepthMS2ArrayPipe) == ARRAY_COUNT(formats),
"Array count mismatch");
RDCCOMPILE_ASSERT(ARRAY_COUNT(m_DepthArray2MSPipe) == ARRAY_COUNT(formats),
"Array count mismatch");
RDCCOMPILE_ASSERT(ARRAY_COUNT(m_DepthArray2MSPipe[0]) == ARRAY_COUNT(sampleCounts),
"Array count mismatch");
// we use VK_IMAGE_LAYOUT_GENERAL here because it matches the expected layout for the
// non-depth copy, which uses a storage image.
VkImageLayout rpLayout = VK_IMAGE_LAYOUT_GENERAL;
for(size_t f = 0; f < ARRAY_COUNT(formats); f++)
{
// if the format isn't supported at all, bail out and don't try to create anything
if(!(m_pDriver->GetFormatProperties(formats[f]).optimalTilingFeatures &
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT))
{
RDCDEBUG("Depth copies MSAA -> Array not supported for format %s", ToStr(formats[f]).c_str());
continue;
}
VkRenderPass depthMS2ArrayRP = VK_NULL_HANDLE;
CREATE_OBJECT(depthMS2ArrayRP, formats[f], VK_SAMPLE_COUNT_1_BIT, rpLayout);
ConciseGraphicsPipeline depthPipeInfo = {
depthMS2ArrayRP,
m_ArrayMSPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::BlitVS),
shaderCache->GetBuiltinModule(BuiltinShader::DepthMS2ArrayFS),
{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_STENCIL_REFERENCE},
VK_SAMPLE_COUNT_1_BIT,
false, // sampleRateShading
true, // depthEnable
true, // stencilEnable
VK_STENCIL_OP_REPLACE,
false, // colourOutput
false, // blendEnable
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
0xf, // writeMask
};
CREATE_OBJECT(m_DepthMS2ArrayPipe[f], depthPipeInfo);
rm->SetInternalResource(GetResID(m_DepthMS2ArrayPipe[f]));
m_pDriver->vkDestroyRenderPass(dev, depthMS2ArrayRP, NULL);
if(!m_pDriver->GetDeviceEnabledFeatures().sampleRateShading)
{
RDCDEBUG("No depth Array -> MSAA copies can be supported without sample rate shading");
continue;
}
for(size_t s = 0; s < ARRAY_COUNT(sampleCounts); s++)
{
// if this sample count isn't supported, don't create it
if(!(m_pDriver->GetDeviceProps().limits.framebufferDepthSampleCounts &
(uint32_t)sampleCounts[s]))
{
RDCDEBUG("Depth copies Array -> MSAA not supported for sample count %u on format %s",
sampleCounts[s], ToStr(formats[f]).c_str());
continue;
}
VkRenderPass depthArray2MSRP;
CREATE_OBJECT(depthArray2MSRP, formats[f], sampleCounts[s], rpLayout);
depthPipeInfo.fragment = shaderCache->GetBuiltinModule(BuiltinShader::DepthArray2MSFS);
depthPipeInfo.renderPass = depthArray2MSRP;
depthPipeInfo.sampleCount = sampleCounts[s];
depthPipeInfo.sampleRateShading = true;
CREATE_OBJECT(m_DepthArray2MSPipe[f][s], depthPipeInfo);
rm->SetInternalResource(GetResID(m_DepthArray2MSPipe[f][s]));
m_pDriver->vkDestroyRenderPass(dev, depthArray2MSRP, NULL);
}
}
if(RenderDoc::Inst().IsReplayApp())
{
VkDescriptorPoolSize descPoolTypes[] = {
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, ARRAY_COUNT(m_DiscardSet)},
};
VkDescriptorPoolCreateInfo descPoolInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
NULL,
0,
ARRAY_COUNT(m_DiscardSet),
ARRAY_COUNT(descPoolTypes),
&descPoolTypes[0],
};
// create descriptor pool
vkr = driver->vkCreateDescriptorPool(driver->GetDev(), &descPoolInfo, NULL, &m_DiscardPool);
CheckVkResult(vkr);
CREATE_OBJECT(m_DiscardSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
});
CREATE_OBJECT(m_DiscardLayout, m_DiscardSetLayout, 4);
ResourceFormat fmt;
fmt.type = ResourceFormatType::Regular;
fmt.compByteWidth = 4;
fmt.compCount = 1;
for(size_t i = 0; i < ARRAY_COUNT(m_DiscardSet); i++)
{
CREATE_OBJECT(m_DiscardSet[i], m_DiscardPool, m_DiscardSetLayout);
fmt.compType = CompType::Float;
bytebuf pattern = GetDiscardPattern(DiscardType(i), fmt);
fmt.compType = CompType::UInt;
pattern.append(GetDiscardPattern(DiscardType(i), fmt));
m_DiscardCB[i].Create(m_pDriver, m_Device, pattern.size(), 1, 0);
memcpy(m_DiscardCB[i].Map(), pattern.data(), pattern.size());
m_DiscardCB[i].Unmap();
VkDescriptorBufferInfo bufInfo = {};
m_DiscardCB[i].FillDescriptor(bufInfo);
VkWriteDescriptorSet writes[] = {
{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(m_DiscardSet[i]), 0, 0, 1,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, NULL, &bufInfo, NULL,
},
};
ObjDisp(dev)->UpdateDescriptorSets(Unwrap(dev), ARRAY_COUNT(writes), writes, 0, NULL);
}
}
// we only need this during replay, so don't create otherwise.
if(RenderDoc::Inst().IsReplayApp())
{
m_ReadbackWindow.Create(driver, dev, STAGE_BUFFER_BYTE_SIZE, 1, GPUBuffer::eGPUBufferReadback);
}
}
VulkanDebugManager::~VulkanDebugManager()
{
VkDevice dev = m_Device;
m_Custom.Destroy(m_pDriver);
m_ReadbackWindow.Destroy();
for(auto it = m_CachedMeshPipelines.begin(); it != m_CachedMeshPipelines.end(); ++it)
for(uint32_t i = 0; i < VKMeshDisplayPipelines::ePipe_Count; i++)
m_pDriver->vkDestroyPipeline(dev, it->second.pipes[i], NULL);
m_pDriver->vkDestroyDescriptorPool(dev, m_ArrayMSDescriptorPool, NULL);
m_pDriver->vkDestroySampler(dev, m_ArrayMSSampler, NULL);
m_pDriver->vkDestroyImageView(dev, m_DummyStencilView[0], NULL);
m_pDriver->vkDestroyImageView(dev, m_DummyStencilView[1], NULL);
m_pDriver->vkDestroyImage(dev, m_DummyStencilImage[0], NULL);
m_pDriver->vkDestroyImage(dev, m_DummyStencilImage[1], NULL);
m_pDriver->vkFreeMemory(dev, m_DummyStencilMemory, NULL);
m_pDriver->vkDestroyDescriptorSetLayout(dev, m_ArrayMSDescSetLayout, NULL);
m_pDriver->vkDestroyPipelineLayout(dev, m_ArrayMSPipeLayout, NULL);
m_pDriver->vkDestroyPipeline(dev, m_Array2MSPipe, NULL);
m_pDriver->vkDestroyPipeline(dev, m_MS2ArrayPipe, NULL);
m_pDriver->vkDestroyDescriptorPool(dev, m_DiscardPool, NULL);
m_pDriver->vkDestroyPipelineLayout(dev, m_DiscardLayout, NULL);
m_pDriver->vkDestroyDescriptorSetLayout(dev, m_DiscardSetLayout, NULL);
for(size_t i = 0; i < ARRAY_COUNT(m_DiscardCB); i++)
m_DiscardCB[i].Destroy();
for(auto it = m_DiscardImages.begin(); it != m_DiscardImages.end(); it++)
{
for(VkImageView view : it->second.views)
m_pDriver->vkDestroyImageView(dev, view, NULL);
for(VkFramebuffer fb : it->second.fbs)
m_pDriver->vkDestroyFramebuffer(dev, fb, NULL);
}
for(auto it = m_DiscardPipes.begin(); it != m_DiscardPipes.end(); it++)
{
m_pDriver->vkDestroyPipeline(dev, it->second.pso, NULL);
m_pDriver->vkDestroyRenderPass(dev, it->second.rp, NULL);
}
for(auto it = m_DiscardPatterns.begin(); it != m_DiscardPatterns.end(); it++)
m_pDriver->vkDestroyBuffer(dev, it->second, NULL);
for(size_t i = 0; i < ARRAY_COUNT(m_DepthMS2ArrayPipe); i++)
m_pDriver->vkDestroyPipeline(dev, m_DepthMS2ArrayPipe[i], NULL);
for(size_t f = 0; f < ARRAY_COUNT(m_DepthArray2MSPipe); f++)
for(size_t s = 0; s < ARRAY_COUNT(m_DepthArray2MSPipe[0]); s++)
m_pDriver->vkDestroyPipeline(dev, m_DepthArray2MSPipe[f][s], NULL);
}
void VulkanDebugManager::CreateCustomShaderTex(uint32_t width, uint32_t height, uint32_t mip)
{
WrappedVulkan *driver = m_pDriver;
VkDevice dev = m_Device;
VkResult vkr = VK_SUCCESS;
if(m_Custom.TexImg != VK_NULL_HANDLE)
{
if(width == m_Custom.TexWidth && height == m_Custom.TexHeight)
{
// recreate framebuffer for this mip
// Create framebuffer rendering just to overlay image, no depth
VkFramebufferCreateInfo fbinfo = {
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
NULL,
0,
m_Custom.TexRP,
1,
&m_Custom.TexImgView[mip],
RDCMAX(1U, width >> mip),
RDCMAX(1U, height >> mip),
1,
};
vkr = m_pDriver->vkCreateFramebuffer(m_Device, &fbinfo, NULL, &m_Custom.TexFB);
CheckVkResult(vkr);
return;
}
m_pDriver->vkDestroyRenderPass(dev, m_Custom.TexRP, NULL);
m_pDriver->vkDestroyFramebuffer(dev, m_Custom.TexFB, NULL);
for(size_t i = 0; i < ARRAY_COUNT(m_Custom.TexImgView); i++)
m_pDriver->vkDestroyImageView(dev, m_Custom.TexImgView[i], NULL);
RDCEraseEl(m_Custom.TexImgView);
m_pDriver->vkDestroyImage(dev, m_Custom.TexImg, NULL);
}
m_Custom.TexWidth = width;
m_Custom.TexHeight = height;
VkImageCreateInfo imInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
NULL,
0,
VK_IMAGE_TYPE_2D,
VK_FORMAT_R16G16B16A16_SFLOAT,
{width, height, 1},
CalcNumMips((int)width, (int)height, 1),
1,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_SHARING_MODE_EXCLUSIVE,
0,
NULL,
VK_IMAGE_LAYOUT_UNDEFINED,
};
vkr = m_pDriver->vkCreateImage(m_Device, &imInfo, NULL, &m_Custom.TexImg);
CheckVkResult(vkr);
VkMemoryRequirements mrq = {0};
m_pDriver->vkGetImageMemoryRequirements(m_Device, m_Custom.TexImg, &mrq);
// if no memory is allocated, or it's not enough,
// then allocate
if(m_Custom.TexMem == VK_NULL_HANDLE || mrq.size > m_Custom.TexMemSize)
{
if(m_Custom.TexMem != VK_NULL_HANDLE)
m_pDriver->vkFreeMemory(m_Device, m_Custom.TexMem, NULL);
VkMemoryAllocateInfo allocInfo = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, mrq.size,
m_pDriver->GetGPULocalMemoryIndex(mrq.memoryTypeBits),
};
vkr = m_pDriver->vkAllocateMemory(m_Device, &allocInfo, NULL, &m_Custom.TexMem);
CheckVkResult(vkr);
if(vkr != VK_SUCCESS)
return;
m_Custom.TexMemSize = mrq.size;
}
vkr = m_pDriver->vkBindImageMemory(m_Device, m_Custom.TexImg, m_Custom.TexMem, 0);
CheckVkResult(vkr);
VkImageViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
NULL,
0,
m_Custom.TexImg,
VK_IMAGE_VIEW_TYPE_2D,
imInfo.format,
{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY},
{
VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1,
},
};
for(uint32_t i = 0; i < imInfo.mipLevels; i++)
{
viewInfo.subresourceRange.baseMipLevel = i;
vkr = m_pDriver->vkCreateImageView(m_Device, &viewInfo, NULL, &m_Custom.TexImgView[i]);
CheckVkResult(vkr);
}
// need to update image layout into valid state
VkCommandBuffer cmd = m_pDriver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
ObjDisp(dev)->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
m_pDriver->FindImageState(GetResID(m_Custom.TexImg))
->InlineTransition(cmd, m_pDriver->m_QueueFamilyIdx, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
m_pDriver->GetImageTransitionInfo());
vkr = ObjDisp(dev)->EndCommandBuffer(Unwrap(cmd));
CheckVkResult(vkr);
#if ENABLED(SINGLE_FLUSH_VALIDATE)
m_pDriver->SubmitCmds();
#endif
CREATE_OBJECT(m_Custom.TexRP, imInfo.format, imInfo.samples);
// Create framebuffer rendering just to overlay image, no depth
VkFramebufferCreateInfo fbinfo = {
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
NULL,
0,
m_Custom.TexRP,
1,
&m_Custom.TexImgView[mip],
RDCMAX(1U, width >> mip),
RDCMAX(1U, height >> mip),
1,
};
vkr = m_pDriver->vkCreateFramebuffer(m_Device, &fbinfo, NULL, &m_Custom.TexFB);
CheckVkResult(vkr);
}
void VulkanDebugManager::CreateCustomShaderPipeline(ResourceId shader, VkPipelineLayout pipeLayout)
{
WrappedVulkan *driver = m_pDriver;
if(shader == ResourceId())
return;
if(m_Custom.TexPipeline != VK_NULL_HANDLE)
{
if(m_Custom.TexShader == shader)
return;
m_pDriver->vkDestroyPipeline(m_Device, m_Custom.TexPipeline, NULL);
}
m_Custom.TexShader = shader;
ConciseGraphicsPipeline customPipe = {
m_Custom.TexRP,
pipeLayout,
m_pDriver->GetShaderCache()->GetBuiltinModule(BuiltinShader::BlitVS),
m_pDriver->GetResourceManager()->GetCurrentHandle<VkShaderModule>(shader),
{VK_DYNAMIC_STATE_VIEWPORT},
VK_SAMPLE_COUNT_1_BIT,
false, // sampleRateShading
false, // depthEnable
false, // stencilEnable
VK_STENCIL_OP_KEEP,
true, // colourOutput
false, // blendEnable
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
0xf, // writeMask
};
CREATE_OBJECT(m_Custom.TexPipeline, customPipe);
}
uint32_t VulkanReplay::PickVertex(uint32_t eventId, int32_t width, int32_t height,
const MeshDisplay &cfg, uint32_t x, uint32_t y)
{
VkDevice dev = m_pDriver->GetDev();
const VkDevDispatchTable *vt = ObjDisp(dev);
VkMarkerRegion::Begin(StringFormat::Fmt("VulkanReplay::PickVertex(%u, %u)", x, y));
Matrix4f projMat = Matrix4f::Perspective(90.0f, 0.1f, 100000.0f, float(width) / float(height));
Matrix4f camMat = cfg.cam ? ((Camera *)cfg.cam)->GetMatrix() : Matrix4f::Identity();
Matrix4f pickMVP = projMat.Mul(camMat);
if(!cfg.position.unproject)
{
pickMVP = pickMVP.Mul(Matrix4f(cfg.axisMapping));
}
bool reverseProjection = false;
Matrix4f guessProj;
Matrix4f guessProjInverse;
if(cfg.position.unproject)
{
// the derivation of the projection matrix might not be right (hell, it could be an
// orthographic projection). But it'll be close enough likely.
if(cfg.position.farPlane != FLT_MAX)
{
guessProj =
Matrix4f::Perspective(cfg.fov, cfg.position.nearPlane, cfg.position.farPlane, cfg.aspect);
}
else
{
reverseProjection = true;
guessProj = Matrix4f::ReversePerspective(cfg.fov, cfg.position.nearPlane, cfg.aspect);
}
if(cfg.ortho)
guessProj = Matrix4f::Orthographic(cfg.position.nearPlane, cfg.position.farPlane);
if(cfg.position.flipY)
guessProj[5] *= -1.0f;
guessProjInverse = guessProj.Inverse();
}
Vec3f rayPos;
Vec3f rayDir;
// convert mouse pos to world space ray
{
float pickX = ((float)x) / ((float)width);
float pickXCanonical = RDCLERP(-1.0f, 1.0f, pickX);
float pickY = ((float)y) / ((float)height);
// flip the Y axis by default for Y-up
float pickYCanonical = RDCLERP(1.0f, -1.0f, pickY);
if(cfg.position.flipY && !cfg.ortho)
pickYCanonical = -pickYCanonical;
// x/y is inside the window. Since we're not using the window projection we need to correct
// for the aspect ratio here.
if(cfg.position.unproject && !cfg.ortho)
pickXCanonical *= (float(width) / float(height)) / cfg.aspect;
// set up the NDC near/far pos
Vec3f nearPosNDC = Vec3f(pickXCanonical, pickYCanonical, 0);
Vec3f farPosNDC = Vec3f(pickXCanonical, pickYCanonical, 1);
if(cfg.position.unproject && cfg.ortho)
{
// orthographic projections we raycast in NDC space
Matrix4f inversePickMVP = pickMVP.Inverse();
// transform from the desired NDC co-ordinates into camera space
Vec3f nearPosCamera = inversePickMVP.Transform(nearPosNDC, 1);
Vec3f farPosCamera = inversePickMVP.Transform(farPosNDC, 1);
Vec3f testDir = (farPosCamera - nearPosCamera);
testDir.Normalise();
Matrix4f pickMVPguessProjInverse = guessProj.Mul(inversePickMVP);
Vec3f nearPosProj = pickMVPguessProjInverse.Transform(nearPosNDC, 1);
Vec3f farPosProj = pickMVPguessProjInverse.Transform(farPosNDC, 1);
rayDir = (farPosProj - nearPosProj);
rayDir.Normalise();
// Calculate the ray direction first in the regular way (above), so we can use the
// the output for testing if the ray we are picking is negative or not. This is similar
// to checking against the forward direction of the camera, but more robust
if(testDir.z < 0)
{
rayDir = -rayDir;
}
rayPos = nearPosProj;
}
else if(cfg.position.unproject)
{
// projected data we pick in world-space to avoid problems with handling unusual transforms
if(reverseProjection)
{
farPosNDC.z = 1e-6f;
nearPosNDC.z = 1e+6f;
}
// invert the guessed projection matrix to get the near/far pos in camera space
Vec3f nearPosCamera = guessProjInverse.Transform(nearPosNDC, 1.0f);
Vec3f farPosCamera = guessProjInverse.Transform(farPosNDC, 1.0f);
// normalise and generate the ray
rayDir = (farPosCamera - nearPosCamera);
rayDir.Normalise();
farPosCamera = nearPosCamera + rayDir;
// invert the camera transform to transform the ray as camera-relative into world space
Matrix4f inverseCamera = camMat.Inverse();
Vec3f nearPosWorld = inverseCamera.Transform(nearPosCamera, 1);
Vec3f farPosWorld = inverseCamera.Transform(farPosCamera, 1);
// again normalise our final ray
rayDir = (farPosWorld - nearPosWorld);
rayDir.Normalise();
rayPos = nearPosWorld;
}
else
{
Matrix4f inversePickMVP = pickMVP.Inverse();
// transform from the desired NDC co-ordinates into model space
Vec3f nearPosCamera = inversePickMVP.Transform(nearPosNDC, 1);
Vec3f farPosCamera = inversePickMVP.Transform(farPosNDC, 1);
rayDir = (farPosCamera - nearPosCamera);
rayDir.Normalise();
rayPos = nearPosCamera;
}
}
const bool fandecode =
(cfg.position.topology == Topology::TriangleFan && cfg.position.allowRestart);
uint32_t numIndices = cfg.position.numIndices;
bytebuf idxs;
uint32_t minIndex = 0;
uint32_t maxIndex = cfg.position.numIndices;
if(cfg.position.indexByteStride && cfg.position.indexResourceId != ResourceId())
GetBufferData(cfg.position.indexResourceId, cfg.position.indexByteOffset, 0, idxs);
uint32_t idxclamp = 0;
if(cfg.position.baseVertex < 0)
idxclamp = uint32_t(-cfg.position.baseVertex);
// We copy into our own buffers to promote to the target type (uint32) that the shader expects.
// Most IBs will be 16-bit indices, most VBs will not be float4. We also apply baseVertex here
if(!idxs.empty())
{
rdcarray<uint32_t> idxtmp;
// if it's a triangle fan that allows restart, we'll have to unpack it.
// Allocate enough space for the list on the GPU, and enough temporary space to upcast into
// first
if(fandecode)
{
idxtmp.resize(numIndices);
numIndices *= 3;
}
// resize up on demand
if(m_VertexPick.IBSize < numIndices * sizeof(uint32_t))
{
if(m_VertexPick.IBSize > 0)
{
m_VertexPick.IB.Destroy();
m_VertexPick.IBUpload.Destroy();
}
m_VertexPick.IBSize = numIndices * sizeof(uint32_t);
m_VertexPick.IB.Create(m_pDriver, dev, m_VertexPick.IBSize, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
m_VertexPick.IBUpload.Create(m_pDriver, dev, m_VertexPick.IBSize, 1, 0);
}
uint32_t *outidxs = (uint32_t *)m_VertexPick.IBUpload.Map();
uint32_t *mappedPtr = outidxs;
memset(outidxs, 0, m_VertexPick.IBSize);
// if we're decoding a fan, we write into our temporary vector first
if(fandecode)
outidxs = idxtmp.data();
uint16_t *idxs16 = (uint16_t *)&idxs[0];
uint32_t *idxs32 = (uint32_t *)&idxs[0];
size_t idxcount = 0;
if(cfg.position.indexByteStride == 2)
{
size_t bufsize = idxs.size() / 2;
for(uint32_t i = 0; i < bufsize && i < cfg.position.numIndices; i++)
{
uint32_t idx = idxs16[i];
if(idx < idxclamp)
idx = 0;
else if(cfg.position.baseVertex < 0)
idx -= idxclamp;
else if(cfg.position.baseVertex > 0)
idx += cfg.position.baseVertex;
if(i == 0)
{
minIndex = maxIndex = idx;
}
else
{
minIndex = RDCMIN(idx, minIndex);
maxIndex = RDCMAX(idx, maxIndex);
}
outidxs[i] = idx;
idxcount++;
}
}
else
{
uint32_t bufsize = uint32_t(idxs.size() / 4);
minIndex = maxIndex = idxs32[0];
for(uint32_t i = 0; i < RDCMIN(bufsize, cfg.position.numIndices); i++)
{
uint32_t idx = idxs32[i];
if(idx < idxclamp)
idx = 0;
else if(cfg.position.baseVertex < 0)
idx -= idxclamp;
else if(cfg.position.baseVertex > 0)
idx += cfg.position.baseVertex;
minIndex = RDCMIN(idx, minIndex);
maxIndex = RDCMAX(idx, maxIndex);
outidxs[i] = idx;
idxcount++;
}
}
// if it's a triangle fan that allows restart, unpack it
if(cfg.position.topology == Topology::TriangleFan && cfg.position.allowRestart)
{
// resize to how many indices were actually read
idxtmp.resize(idxcount);
// patch the index buffer
PatchTriangleFanRestartIndexBufer(idxtmp, cfg.position.restartIndex);
for(uint32_t &idx : idxtmp)
{
if(idx == cfg.position.restartIndex)
idx = 0;
}
numIndices = (uint32_t)idxtmp.size();
// now copy the decoded list to the GPU
memcpy(mappedPtr, idxtmp.data(), idxtmp.size() * sizeof(uint32_t));
}
m_VertexPick.IBUpload.Unmap();
}
// unpack and linearise the data
{
bytebuf oldData;
GetBufferData(cfg.position.vertexResourceId, cfg.position.vertexByteOffset, 0, oldData);
// clamp maxIndex to upper bound in case we got invalid indices or primitive restart indices
maxIndex = RDCMIN(maxIndex, uint32_t(oldData.size() / RDCMAX(1U, cfg.position.vertexByteStride)));
if(m_VertexPick.VBSize < (maxIndex + 1) * sizeof(FloatVector))
{
if(m_VertexPick.VBSize > 0)
{
m_VertexPick.VB.Destroy();
m_VertexPick.VBUpload.Destroy();
}
m_VertexPick.VBSize = (maxIndex + 1) * sizeof(FloatVector);
m_VertexPick.VB.Create(m_pDriver, dev, m_VertexPick.VBSize, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
m_VertexPick.VBUpload.Create(m_pDriver, dev, m_VertexPick.VBSize, 1, 0);
}
byte *data = &oldData[0];
byte *dataEnd = data + oldData.size();
bool valid = true;
FloatVector *vbData = (FloatVector *)m_VertexPick.VBUpload.Map();
// the index buffer may refer to vertices past the start of the vertex buffer, so we can't just
// conver the first N vertices we'll need.
// Instead we grab min and max above, and convert every vertex in that range. This might
// slightly over-estimate but not as bad as 0-max or the whole buffer.
for(uint32_t idx = minIndex; idx <= maxIndex; idx++)
vbData[idx] = HighlightCache::InterpretVertex(data, idx, cfg.position.vertexByteStride,
cfg.position.format, dataEnd, valid);
m_VertexPick.VBUpload.Unmap();
}
MeshPickUBOData *ubo = (MeshPickUBOData *)m_VertexPick.UBO.Map();
ubo->rayPos = rayPos;
ubo->rayDir = rayDir;
ubo->use_indices = cfg.position.indexByteStride ? 1U : 0U;
ubo->numVerts = numIndices;
bool isTriangleMesh = true;
switch(cfg.position.topology)
{
case Topology::TriangleList:
{
ubo->meshMode = MESH_TRIANGLE_LIST;
break;
};
case Topology::TriangleStrip:
{
ubo->meshMode = MESH_TRIANGLE_STRIP;
break;
};
case Topology::TriangleFan:
{
if(fandecode)
ubo->meshMode = MESH_TRIANGLE_LIST;
else
ubo->meshMode = MESH_TRIANGLE_FAN;
break;
};
case Topology::TriangleList_Adj:
{
ubo->meshMode = MESH_TRIANGLE_LIST_ADJ;
break;
};
case Topology::TriangleStrip_Adj:
{
ubo->meshMode = MESH_TRIANGLE_STRIP_ADJ;
break;
};
default: // points, lines, patchlists, unknown
{
ubo->meshMode = MESH_OTHER;
isTriangleMesh = false;
};
}
// line/point data
ubo->unproject = cfg.position.unproject;
ubo->flipY = cfg.position.flipY;
ubo->ortho = cfg.ortho;
ubo->coords = Vec2f((float)x, (float)y);
ubo->viewport = Vec2f((float)width, (float)height);
if(cfg.position.unproject && isTriangleMesh)
{
// projected triangle meshes we transform the vertices into world space, and ray-cast against
// that
//
// NOTE: for ortho, this matrix is not used and we just do the perspective W division on model
// vertices. The ray is cast in NDC
if(cfg.ortho)
ubo->transformMat = Matrix4f::Identity();
else
ubo->transformMat = guessProjInverse;
}
else if(cfg.position.unproject)
{
// projected non-triangles are just point clouds, so we transform the vertices into world space
// then project them back onto the output and compare that against the picking 2D co-ordinates
ubo->transformMat = pickMVP.Mul(guessProjInverse);
}
else
{
// plain meshes of either type, we just transform from model space to the output, and raycast or
// co-ordinate check
ubo->transformMat = pickMVP;
}
m_VertexPick.UBO.Unmap();
VkDescriptorBufferInfo ibInfo = {};
VkDescriptorBufferInfo vbInfo = {};
m_VertexPick.VB.FillDescriptor(vbInfo);
m_VertexPick.IB.FillDescriptor(ibInfo);
VkWriteDescriptorSet writes[] = {
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(m_VertexPick.DescSet), 1, 0, 1,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, NULL, &vbInfo, NULL},
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(m_VertexPick.DescSet), 2, 0, 1,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, NULL, &ibInfo, NULL},
};
if(!idxs.empty())
vt->UpdateDescriptorSets(Unwrap(m_Device), 2, writes, 0, NULL);
else
vt->UpdateDescriptorSets(Unwrap(m_Device), 1, writes, 0, NULL);
VkCommandBuffer cmd = m_pDriver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return ~0U;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
VkBufferCopy bufCopy = {0, 0, 0};
vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
// reset first uint (used as atomic counter) to 0
vt->CmdFillBuffer(Unwrap(cmd), Unwrap(m_VertexPick.Result.buf), 0, sizeof(uint32_t) * 4, 0);
VkBufferMemoryBarrier bufBarrier = {
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
NULL,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(m_VertexPick.Result.buf),
0,
VK_WHOLE_SIZE,
};
// wait for zero to be written to atomic counter before using in shader
DoPipelineBarrier(cmd, 1, &bufBarrier);
// copy uploaded VB and if needed IB
if(!idxs.empty())
{
// wait for writes
bufBarrier.buffer = Unwrap(m_VertexPick.IBUpload.buf);
bufBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
DoPipelineBarrier(cmd, 1, &bufBarrier);
// do copy
bufCopy.size = m_VertexPick.IBSize;
vt->CmdCopyBuffer(Unwrap(cmd), Unwrap(m_VertexPick.IBUpload.buf), Unwrap(m_VertexPick.IB.buf),
1, &bufCopy);
// wait for copy
bufBarrier.buffer = Unwrap(m_VertexPick.IB.buf);
bufBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT;
DoPipelineBarrier(cmd, 1, &bufBarrier);
}
// wait for writes
bufBarrier.buffer = Unwrap(m_VertexPick.VBUpload.buf);
bufBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
DoPipelineBarrier(cmd, 1, &bufBarrier);
// do copy
bufCopy.size = m_VertexPick.VBSize;
vt->CmdCopyBuffer(Unwrap(cmd), Unwrap(m_VertexPick.VBUpload.buf), Unwrap(m_VertexPick.VB.buf), 1,
&bufCopy);
// wait for copy
bufBarrier.buffer = Unwrap(m_VertexPick.VB.buf);
bufBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT;
DoPipelineBarrier(cmd, 1, &bufBarrier);
vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_COMPUTE, Unwrap(m_VertexPick.Pipeline));
vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_COMPUTE, Unwrap(m_VertexPick.Layout),
0, 1, UnwrapPtr(m_VertexPick.DescSet), 0, NULL);
uint32_t workgroupx = uint32_t(cfg.position.numIndices / 128 + 1);
vt->CmdDispatch(Unwrap(cmd), workgroupx, 1, 1);
// wait for shader to finish writing before transferring to readback buffer
bufBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
bufBarrier.buffer = Unwrap(m_VertexPick.Result.buf);
DoPipelineBarrier(cmd, 1, &bufBarrier);
bufCopy.size = m_VertexPick.Result.totalsize;
// copy to readback buffer
vt->CmdCopyBuffer(Unwrap(cmd), Unwrap(m_VertexPick.Result.buf),
Unwrap(m_VertexPick.ResultReadback.buf), 1, &bufCopy);
// wait for transfer to finish before reading on CPU
bufBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
bufBarrier.buffer = Unwrap(m_VertexPick.ResultReadback.buf);
DoPipelineBarrier(cmd, 1, &bufBarrier);
VkResult vkr = vt->EndCommandBuffer(Unwrap(cmd));
CheckVkResult(vkr);
#if ENABLED(SINGLE_FLUSH_VALIDATE)
m_pDriver->SubmitCmds();
#endif
m_pDriver->SubmitCmds();
m_pDriver->FlushQ();
uint32_t *pickResultData = (uint32_t *)m_VertexPick.ResultReadback.Map();
uint32_t numResults = *pickResultData;
uint32_t ret = ~0U;
if(numResults > 0)
{
if(isTriangleMesh)
{
struct PickResult
{
uint32_t vertid;
vec3 intersectionPoint;
};
PickResult *pickResults = (PickResult *)(pickResultData + 4);
PickResult *closest = pickResults;
// distance from raycast hit to nearest worldspace position of the mouse
float closestPickDistance = (closest->intersectionPoint - rayPos).Length();
// min with size of results buffer to protect against overflows
for(uint32_t i = 1; i < RDCMIN((uint32_t)VertexPicking::MaxMeshPicks, numResults); i++)
{
float pickDistance = (pickResults[i].intersectionPoint - rayPos).Length();
if(pickDistance < closestPickDistance)
{
closest = pickResults + i;
}
}
ret = closest->vertid;
}
else
{
struct PickResult
{
uint32_t vertid;
uint32_t idx;
float len;
float depth;
};
PickResult *pickResults = (PickResult *)(pickResultData + 4);
PickResult *closest = pickResults;
// min with size of results buffer to protect against overflows
for(uint32_t i = 1; i < RDCMIN((uint32_t)VertexPicking::MaxMeshPicks, numResults); i++)
{
// We need to keep the picking order consistent in the face
// of random buffer appends, when multiple vertices have the
// identical position (e.g. if UVs or normals are different).
//
// We could do something to try and disambiguate, but it's
// never going to be intuitive, it's just going to flicker
// confusingly.
if(pickResults[i].len < closest->len ||
(pickResults[i].len == closest->len && pickResults[i].depth < closest->depth) ||
(pickResults[i].len == closest->len && pickResults[i].depth == closest->depth &&
pickResults[i].vertid < closest->vertid))
closest = pickResults + i;
}
ret = closest->vertid;
}
}
m_VertexPick.ResultReadback.Unmap();
VkMarkerRegion::Set(StringFormat::Fmt("Result is %u", ret));
VkMarkerRegion::End();
if(fandecode)
{
// undo the triangle list expansion
if(ret > 2)
ret = (ret + 3) / 3 + 1;
}
return ret;
}
const VulkanCreationInfo::Image &VulkanDebugManager::GetImageInfo(ResourceId img) const
{
auto it = m_pDriver->m_CreationInfo.m_Image.find(img);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_Image.end());
return it->second;
}
const VulkanCreationInfo::ImageView &VulkanDebugManager::GetImageViewInfo(ResourceId imgView) const
{
auto it = m_pDriver->m_CreationInfo.m_ImageView.find(imgView);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_ImageView.end());
return it->second;
}
const VulkanCreationInfo::Pipeline &VulkanDebugManager::GetPipelineInfo(ResourceId pipe) const
{
auto it = m_pDriver->m_CreationInfo.m_Pipeline.find(pipe);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_Pipeline.end());
return it->second;
}
const VulkanCreationInfo::ShaderModule &VulkanDebugManager::GetShaderInfo(ResourceId shader) const
{
auto it = m_pDriver->m_CreationInfo.m_ShaderModule.find(shader);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_ShaderModule.end());
return it->second;
}
const VulkanCreationInfo::Framebuffer &VulkanDebugManager::GetFramebufferInfo(ResourceId fb) const
{
auto it = m_pDriver->m_CreationInfo.m_Framebuffer.find(fb);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_Framebuffer.end());
return it->second;
}
const VulkanCreationInfo::RenderPass &VulkanDebugManager::GetRenderPassInfo(ResourceId rp) const
{
auto it = m_pDriver->m_CreationInfo.m_RenderPass.find(rp);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_RenderPass.end());
return it->second;
}
const VulkanCreationInfo::PipelineLayout &VulkanDebugManager::GetPipelineLayoutInfo(ResourceId rp) const
{
auto it = m_pDriver->m_CreationInfo.m_PipelineLayout.find(rp);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_PipelineLayout.end());
return it->second;
}
const DescSetLayout &VulkanDebugManager::GetDescSetLayout(ResourceId dsl) const
{
auto it = m_pDriver->m_CreationInfo.m_DescSetLayout.find(dsl);
RDCASSERT(it != m_pDriver->m_CreationInfo.m_DescSetLayout.end());
return it->second;
}
const WrappedVulkan::DescriptorSetInfo &VulkanDebugManager::GetDescSetInfo(ResourceId ds) const
{
auto it = m_pDriver->m_DescriptorSetState.find(ds);
RDCASSERT(it != m_pDriver->m_DescriptorSetState.end());
return it->second;
}
void VulkanDebugManager::GetBufferData(ResourceId buff, uint64_t offset, uint64_t len, bytebuf &ret)
{
VkDevice dev = m_pDriver->GetDev();
const VkDevDispatchTable *vt = ObjDisp(dev);
WrappedVkRes *res = m_pDriver->GetResourceManager()->GetCurrentResource(buff);
if(res == VK_NULL_HANDLE)
{
RDCERR("Getting buffer data for unknown buffer/memory %s!", ToStr(buff).c_str());
return;
}
VkBuffer srcBuf = VK_NULL_HANDLE;
uint64_t bufsize = 0;
if(WrappedVkDeviceMemory::IsAlloc(res))
{
srcBuf = m_pDriver->m_CreationInfo.m_Memory[buff].wholeMemBuf;
bufsize = m_pDriver->m_CreationInfo.m_Memory[buff].wholeMemBufSize;
if(srcBuf == VK_NULL_HANDLE)
{
RDCLOG(
"Memory doesn't have wholeMemBuf, either non-buffer accessible (non-linear) or dedicated "
"image memory");
return;
}
}
else if(WrappedVkBuffer::IsAlloc(res))
{
srcBuf = m_pDriver->GetResourceManager()->GetCurrentHandle<VkBuffer>(buff);
bufsize = m_pDriver->m_CreationInfo.m_Buffer[buff].size;
}
else
{
RDCERR("Getting buffer data for object that isn't buffer or memory %s!", ToStr(buff).c_str());
return;
}
if(offset >= bufsize)
{
// can't read past the end of the buffer, return empty
return;
}
if(len == 0 || len > bufsize)
{
len = bufsize - offset;
}
if(VkDeviceSize(offset + len) > bufsize)
{
RDCWARN("Attempting to read off the end of the buffer (%llu %llu). Will be clamped (%llu)",
offset, len, bufsize);
len = RDCMIN(len, bufsize - offset);
}
ret.resize((size_t)len);
VkDeviceSize srcoffset = (VkDeviceSize)offset;
size_t dstoffset = 0;
VkDeviceSize sizeRemaining = (VkDeviceSize)len;
VkCommandBuffer cmd = m_pDriver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
VkResult vkr = vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
CheckVkResult(vkr);
VkBufferMemoryBarrier bufBarrier = {
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
NULL,
0,
VK_ACCESS_TRANSFER_READ_BIT,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(srcBuf),
srcoffset,
sizeRemaining,
};
bufBarrier.srcAccessMask = VK_ACCESS_ALL_WRITE_BITS;
// wait for previous writes to happen before we copy to our window buffer
DoPipelineBarrier(cmd, 1, &bufBarrier);
vkr = vt->EndCommandBuffer(Unwrap(cmd));
CheckVkResult(vkr);
#if ENABLED(SINGLE_FLUSH_VALIDATE)
m_pDriver->SubmitCmds();
#endif
while(sizeRemaining > 0)
{
VkDeviceSize chunkSize = RDCMIN(sizeRemaining, STAGE_BUFFER_BYTE_SIZE);
cmd = m_pDriver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return;
vkr = vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
CheckVkResult(vkr);
VkBufferCopy region = {srcoffset, 0, chunkSize};
vt->CmdCopyBuffer(Unwrap(cmd), Unwrap(srcBuf), Unwrap(m_ReadbackWindow.buf), 1, ®ion);
bufBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
bufBarrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
bufBarrier.buffer = Unwrap(m_ReadbackWindow.buf);
bufBarrier.offset = 0;
bufBarrier.size = chunkSize;
// wait for transfer to happen before we read
DoPipelineBarrier(cmd, 1, &bufBarrier);
vkr = vt->EndCommandBuffer(Unwrap(cmd));
CheckVkResult(vkr);
m_pDriver->SubmitCmds();
m_pDriver->FlushQ();
byte *pData = NULL;
vkr = vt->MapMemory(Unwrap(dev), Unwrap(m_ReadbackWindow.mem), 0, VK_WHOLE_SIZE, 0,
(void **)&pData);
CheckVkResult(vkr);
if(vkr != VK_SUCCESS)
return;
VkMappedMemoryRange range = {
VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, NULL, Unwrap(m_ReadbackWindow.mem), 0, VK_WHOLE_SIZE,
};
vkr = vt->InvalidateMappedMemoryRanges(Unwrap(dev), 1, &range);
CheckVkResult(vkr);
RDCASSERT(pData != NULL);
memcpy(&ret[dstoffset], pData, (size_t)chunkSize);
srcoffset += chunkSize;
dstoffset += (size_t)chunkSize;
sizeRemaining -= chunkSize;
vt->UnmapMemory(Unwrap(dev), Unwrap(m_ReadbackWindow.mem));
}
vt->DeviceWaitIdle(Unwrap(dev));
}
void VulkanDebugManager::FillWithDiscardPattern(VkCommandBuffer cmd, DiscardType type,
VkImage image, VkImageLayout curLayout,
VkImageSubresourceRange discardRange,
VkRect2D discardRect)
{
VkDevice dev = m_Device;
const VkDevDispatchTable *vt = ObjDisp(dev);
const VulkanCreationInfo::Image &imInfo = GetImageInfo(GetResID(image));
VkMarkerRegion marker(
cmd, StringFormat::Fmt("FillWithDiscardPattern %s", ToStr(GetResID(image)).c_str()));
if(imInfo.samples > 1)
{
WrappedVulkan *driver = m_pDriver;
bool depth = false;
if(IsDepthOrStencilFormat(imInfo.format))
depth = true;
VkImageAspectFlags imAspects = FormatImageAspects(imInfo.format);
rdcpair<VkFormat, VkSampleCountFlagBits> key = {imInfo.format, imInfo.samples};
DiscardPassData &passdata = m_DiscardPipes[key];
// create and cache a pipeline and RP that writes to this format and sample count
if(passdata.pso == VK_NULL_HANDLE)
{
BuiltinShaderBaseType baseType = BuiltinShaderBaseType::Float;
if(IsSIntFormat(imInfo.format))
baseType = BuiltinShaderBaseType::SInt;
else if(IsUIntFormat(imInfo.format))
baseType = BuiltinShaderBaseType::UInt;
VkAttachmentReference attRef = {
0, depth ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
: VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
};
VkAttachmentDescription attDesc = {
0,
imInfo.format,
imInfo.samples,
VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE,
attRef.layout,
attRef.layout,
};
VkSubpassDescription sub = {
0, VK_PIPELINE_BIND_POINT_GRAPHICS,
};
if(depth)
{
sub.pDepthStencilAttachment = &attRef;
}
else
{
sub.pColorAttachments = &attRef;
sub.colorAttachmentCount = 1;
}
VkRenderPassCreateInfo rpinfo = {
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, NULL, 0, 1, &attDesc, 1, &sub, 0, NULL,
};
VkResult vkr = m_pDriver->vkCreateRenderPass(m_pDriver->GetDev(), &rpinfo, NULL, &passdata.rp);
if(vkr != VK_SUCCESS)
RDCERR("Failed to create shader debug render pass: %s", ToStr(vkr).c_str());
ConciseGraphicsPipeline pipeInfo = {
passdata.rp,
m_DiscardLayout,
m_pDriver->GetShaderCache()->GetBuiltinModule(BuiltinShader::BlitVS),
m_pDriver->GetShaderCache()->GetBuiltinModule(BuiltinShader::DiscardFS, baseType),
{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_REFERENCE},
imInfo.samples,
false, // sampleRateShading
true, // depthEnable
true, // stencilEnable
VK_STENCIL_OP_REPLACE,
true, // colourOutput
false, // blendEnable
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
0xf, // writeMask
};
CREATE_OBJECT(passdata.pso, pipeInfo);
}
if(passdata.pso == VK_NULL_HANDLE)
return;
DiscardImgData &imgdata = m_DiscardImages[GetResID(image)];
// create and cache views and framebuffers for every slice in this image
if(imgdata.fbs.empty())
{
VkImageAspectFlags aspectMask = imAspects;
for(int pass = 0; pass < 3; pass++)
{
// only depth/stencil images need multiple sets of views to mask out one aspect or the other
if(pass > 0)
{
if(imAspects != (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))
break;
if(pass == 1)
aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
else if(pass == 2)
aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
}
for(uint32_t a = 0; a < imInfo.arrayLayers; a++)
{
VkImageViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
NULL,
0,
image,
VK_IMAGE_VIEW_TYPE_2D,
imInfo.format,
{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
{
aspectMask, 0, 1, a, 1,
},
};
VkImageView view;
VkResult vkr = driver->vkCreateImageView(driver->GetDev(), &viewInfo, NULL, &view);
CheckVkResult(vkr);
imgdata.views.push_back(view);
// create framebuffer
VkFramebufferCreateInfo fbinfo = {
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
NULL,
0,
passdata.rp,
1,
&view,
imInfo.extent.width,
imInfo.extent.height,
1,
};
VkFramebuffer fb;
vkr = driver->vkCreateFramebuffer(driver->GetDev(), &fbinfo, NULL, &fb);
CheckVkResult(vkr);
imgdata.fbs.push_back(fb);
}
}
}
if(imgdata.fbs.empty())
return;
ObjDisp(cmd)->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(passdata.pso));
ObjDisp(cmd)->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS,
Unwrap(m_DiscardLayout), 0, 1,
UnwrapPtr(m_DiscardSet[(size_t)type]), 0, NULL);
VkViewport viewport = {0.0f, 0.0f, (float)imInfo.extent.width, (float)imInfo.extent.height, 1.0f};
ObjDisp(cmd)->CmdSetViewport(Unwrap(cmd), 0, 1U, &viewport);
ObjDisp(cmd)->CmdSetScissor(Unwrap(cmd), 0, 1U, &discardRect);
discardRect.extent.width =
RDCMIN(discardRect.extent.width, imInfo.extent.width - discardRect.offset.x);
discardRect.extent.height =
RDCMIN(discardRect.extent.height, imInfo.extent.height - discardRect.offset.y);
discardRange.layerCount =
RDCMIN(discardRange.layerCount, imInfo.arrayLayers - discardRange.baseArrayLayer);
VkRenderPassBeginInfo rpbegin = {
VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
NULL,
Unwrap(passdata.rp),
VK_NULL_HANDLE,
discardRect,
};
uint32_t pass = 0;
VkImageMemoryBarrier dstimBarrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL,
VK_ACCESS_ALL_READ_BITS | VK_ACCESS_ALL_WRITE_BITS, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
curLayout, depth ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
: VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, Unwrap(image), discardRange,
};
DoPipelineBarrier(cmd, 1, &dstimBarrier);
ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(m_DiscardLayout), VK_SHADER_STAGE_ALL, 0, 4,
&pass);
uint32_t offset = 0;
if(imAspects != discardRange.aspectMask)
{
// if we're only discarding one of depth or stencil in a depth/stencil image, pick a
// framebuffer that only targets that aspect.
if(discardRange.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)
offset = imInfo.arrayLayers;
else
offset = imInfo.arrayLayers * 2;
}
for(uint32_t slice = discardRange.baseArrayLayer;
slice < discardRange.baseArrayLayer + discardRange.layerCount; slice++)
{
rpbegin.framebuffer = Unwrap(imgdata.fbs[slice + offset]);
ObjDisp(cmd)->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE);
if(depth && discardRange.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT)
{
pass = 1;
ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(m_DiscardLayout), VK_SHADER_STAGE_ALL, 0,
4, &pass);
ObjDisp(cmd)->CmdSetStencilReference(
Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT | VK_STENCIL_FACE_BACK_BIT, 0x00);
ObjDisp(cmd)->CmdDraw(Unwrap(cmd), 4, 1, 0, 0);
pass = 2;
ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(m_DiscardLayout), VK_SHADER_STAGE_ALL, 0,
4, &pass);
ObjDisp(cmd)->CmdSetStencilReference(
Unwrap(cmd), VK_STENCIL_FACE_FRONT_BIT | VK_STENCIL_FACE_BACK_BIT, 0xff);
ObjDisp(cmd)->CmdDraw(Unwrap(cmd), 4, 1, 0, 0);
}
else
{
ObjDisp(cmd)->CmdDraw(Unwrap(cmd), 4, 1, 0, 0);
}
ObjDisp(cmd)->CmdEndRenderPass(Unwrap(cmd));
}
dstimBarrier.oldLayout = dstimBarrier.newLayout;
dstimBarrier.newLayout = curLayout;
dstimBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dstimBarrier.dstAccessMask = VK_ACCESS_ALL_WRITE_BITS | VK_ACCESS_ALL_READ_BITS;
DoPipelineBarrier(cmd, 1, &dstimBarrier);
/*
for(UINT sub = 0; sub < region->NumSubresources; sub++)
{
UINT subresource = region->FirstSubresource + sub;
if(depth)
{
dsvDesc.Texture2DMSArray.FirstArraySlice = GetSliceForSubresource(res, subresource);
m_pDevice->CreateDepthStencilView(res, &dsvDesc, dsv);
cmd->OMSetRenderTargets(0, NULL, FALSE, &dsv);
}
else
{
rtvDesc.Texture2DMSArray.FirstArraySlice = GetSliceForSubresource(res, subresource);
m_pDevice->CreateRenderTargetView(res, &rtvDesc, rtv);
cmd->OMSetRenderTargets(1, &rtv, FALSE, NULL);
}
UINT mip = GetMipForSubresource(res, subresource);
UINT plane = GetPlaneForSubresource(res, subresource);
for(D3D12_RECT r : rects)
{
r.right = RDCMIN(LONG(RDCMAX(1U, (UINT)desc.Width >> mip)), r.right);
r.bottom = RDCMIN(LONG(RDCMAX(1U, (UINT)desc.Height >> mip)), r.bottom);
cmd->RSSetScissorRects(1, &r);
}
}
*/
m_pDriver->GetCmdRenderState().BindPipeline(m_pDriver, cmd, VulkanRenderState::BindGraphics,
false);
return;
}
rdcpair<VkFormat, DiscardType> key = {imInfo.format, type};
if(key.first == VK_FORMAT_S8_UINT)
key.first = VK_FORMAT_D32_SFLOAT_S8_UINT;
VkBuffer buf = m_DiscardPatterns[key];
VkResult vkr = VK_SUCCESS;
if(buf == VK_NULL_HANDLE)
{
bytebuf pattern = GetDiscardPattern(key.second, MakeResourceFormat(key.first));
VkBufferCreateInfo bufInfo = {
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
NULL,
0,
pattern.size(),
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
};
vkr = m_pDriver->vkCreateBuffer(dev, &bufInfo, NULL, &buf);
CheckVkResult(vkr);
MemoryAllocation alloc = m_pDriver->AllocateMemoryForResource(
buf, MemoryScope::ImmutableReplayDebug, MemoryType::GPULocal);
if(alloc.mem == VK_NULL_HANDLE)
return;
vkr = vt->BindBufferMemory(Unwrap(dev), Unwrap(buf), Unwrap(alloc.mem), alloc.offs);
CheckVkResult(vkr);
vt->CmdUpdateBuffer(Unwrap(cmd), Unwrap(buf), 0, pattern.size(), pattern.data());
m_DiscardPatterns[key] = buf;
VkBufferMemoryBarrier bufBarrier = {
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
NULL,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(buf),
0,
VK_WHOLE_SIZE,
};
DoPipelineBarrier(cmd, 1, &bufBarrier);
}
VkImageAspectFlags aspectFlags = discardRange.aspectMask & FormatImageAspects(imInfo.format);
rdcarray<VkBufferImageCopy> mainCopies, stencilCopies;
VkExtent3D extent;
// copy each slice/mip individually
for(uint32_t a = 0; a < imInfo.arrayLayers; a++)
{
if(a < discardRange.baseArrayLayer || a >= discardRange.baseArrayLayer + discardRange.layerCount)
continue;
extent = imInfo.extent;
extent.width = RDCMIN(extent.width, discardRect.offset.x + discardRect.extent.width);
extent.height = RDCMIN(extent.height, discardRect.offset.y + discardRect.extent.height);
for(uint32_t m = 0; m < imInfo.mipLevels; m++)
{
if(m >= discardRange.baseMipLevel && m < discardRange.baseMipLevel + discardRange.levelCount)
{
for(uint32_t z = 0; z < extent.depth; z++)
{
for(uint32_t y = discardRect.offset.y; y < extent.height; y += DiscardPatternHeight)
{
for(uint32_t x = discardRect.offset.x; x < extent.width; x += DiscardPatternWidth)
{
VkBufferImageCopy region = {
0,
0,
0,
{aspectFlags, m, a, 1},
{
(int)x, (int)y, (int)z,
},
};
region.imageExtent.width = RDCMIN(DiscardPatternWidth, extent.width - x);
region.imageExtent.height = RDCMIN(DiscardPatternHeight, extent.height - y);
region.imageExtent.depth = 1;
region.bufferRowLength = DiscardPatternWidth;
// for depth/stencil copies, write depth first
if(aspectFlags == (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
if(aspectFlags != VK_IMAGE_ASPECT_STENCIL_BIT)
mainCopies.push_back(region);
if(aspectFlags & VK_IMAGE_ASPECT_STENCIL_BIT)
{
uint32_t depthStride = (imInfo.format == VK_FORMAT_D16_UNORM_S8_UINT ? 2 : 4);
// if it's a depth/stencil format, write stencil separately
region.bufferOffset = DiscardPatternWidth * DiscardPatternHeight * depthStride;
region.bufferRowLength = DiscardPatternWidth * depthStride;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
stencilCopies.push_back(region);
}
}
}
}
}
// update the extent for the next mip
extent.width = RDCMAX(extent.width >> 1, 1U);
extent.height = RDCMAX(extent.height >> 1, 1U);
extent.depth = RDCMAX(extent.depth >> 1, 1U);
}
}
VkImageMemoryBarrier dstimBarrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
NULL,
VK_ACCESS_ALL_READ_BITS | VK_ACCESS_ALL_WRITE_BITS,
VK_ACCESS_TRANSFER_WRITE_BIT,
curLayout,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(image),
discardRange,
};
DoPipelineBarrier(cmd, 1, &dstimBarrier);
if(!mainCopies.empty())
ObjDisp(cmd)->CmdCopyBufferToImage(Unwrap(cmd), Unwrap(buf), Unwrap(image),
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
(uint32_t)mainCopies.size(), mainCopies.data());
if(!stencilCopies.empty())
ObjDisp(cmd)->CmdCopyBufferToImage(Unwrap(cmd), Unwrap(buf), Unwrap(image),
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
(uint32_t)stencilCopies.size(), stencilCopies.data());
dstimBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
dstimBarrier.newLayout = curLayout;
dstimBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
dstimBarrier.dstAccessMask = VK_ACCESS_ALL_WRITE_BITS | VK_ACCESS_ALL_READ_BITS;
DoPipelineBarrier(cmd, 1, &dstimBarrier);
}
void VulkanDebugManager::InitReadbackBuffer(VkDeviceSize sz)
{
if(m_ReadbackWindow.buf == VK_NULL_HANDLE || m_ReadbackWindow.sz < sz)
{
if(m_ReadbackWindow.buf != VK_NULL_HANDLE)
{
m_ReadbackWindow.Destroy();
}
VkDevice dev = m_pDriver->GetDev();
m_ReadbackWindow.Create(m_pDriver, dev, AlignUp(sz, (VkDeviceSize)4096), 1,
GPUBuffer::eGPUBufferReadback);
RDCLOG("Allocating readback window of %llu bytes", m_ReadbackWindow.sz);
VkResult vkr = ObjDisp(dev)->MapMemory(Unwrap(dev), Unwrap(m_ReadbackWindow.mem), 0,
VK_WHOLE_SIZE, 0, (void **)&m_ReadbackPtr);
CheckVkResult(vkr);
}
}
void VulkanReplay::PatchReservedDescriptors(const VulkanStatePipeline &pipe,
VkDescriptorPool &descpool,
rdcarray<VkDescriptorSetLayout> &setLayouts,
rdcarray<VkDescriptorSet> &descSets,
VkShaderStageFlagBits patchedBindingStage,
const VkDescriptorSetLayoutBinding *newBindings,
size_t newBindingsCount)
{
VkDevice dev = m_Device;
VulkanCreationInfo &creationInfo = m_pDriver->m_CreationInfo;
const VulkanCreationInfo::Pipeline &pipeInfo = creationInfo.m_Pipeline[pipe.pipeline];
VkResult vkr = VK_SUCCESS;
rdcarray<VkWriteDescriptorSet> descWrites;
struct AllocedWrites
{
~AllocedWrites()
{
for(VkDescriptorImageInfo *a : imgWrites)
delete[] a;
for(VkDescriptorBufferInfo *a : bufWrites)
delete[] a;
for(VkBufferView *a : bufViewWrites)
delete[] a;
for(VkWriteDescriptorSetInlineUniformBlockEXT *a : inlineWrites)
delete a;
}
rdcarray<VkDescriptorImageInfo *> imgWrites;
rdcarray<VkDescriptorBufferInfo *> bufWrites;
rdcarray<VkBufferView *> bufViewWrites;
rdcarray<VkWriteDescriptorSetInlineUniformBlockEXT *> inlineWrites;
} alloced;
rdcarray<VkDescriptorImageInfo *> &allocImgWrites = alloced.imgWrites;
rdcarray<VkDescriptorBufferInfo *> &allocBufWrites = alloced.bufWrites;
rdcarray<VkBufferView *> &allocBufViewWrites = alloced.bufViewWrites;
rdcarray<VkWriteDescriptorSetInlineUniformBlockEXT *> &allocInlineWrites = alloced.inlineWrites;
// one for each descriptor type. 1 of each to start with, we then increment for each descriptor
// we need to allocate
VkDescriptorPoolSize poolSizes[12] = {
{VK_DESCRIPTOR_TYPE_SAMPLER, 1},
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1},
{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1},
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1},
{VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1},
{VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1},
{VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1},
{VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT, 0},
};
VkDescriptorPoolInlineUniformBlockCreateInfoEXT inlineCreateInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_INLINE_UNIFORM_BLOCK_CREATE_INFO_EXT,
};
static const uint32_t InlinePoolIndex = 11;
uint32_t poolSizeCount = InlinePoolIndex;
// count up our own
for(size_t i = 0; i < newBindingsCount; i++)
{
RDCASSERT(newBindings[i].descriptorType < ARRAY_COUNT(poolSizes), newBindings[i].descriptorType);
poolSizes[newBindings[i].descriptorType].descriptorCount += newBindings[i].descriptorCount;
}
const rdcarray<ResourceId> &pipeDescSetLayouts =
creationInfo.m_PipelineLayout[pipeInfo.layout].descSetLayouts;
// need to add our added bindings to the first descriptor set
rdcarray<VkDescriptorSetLayoutBinding> bindings(newBindings, newBindingsCount);
// if there are fewer sets bound than were declared in the pipeline layout, only process the
// bound sets (as otherwise we'd fail to copy from them). Assume the application knew what it
// was doing and the other sets are statically unused.
setLayouts.resize(RDCMIN(pipe.descSets.size(), pipeDescSetLayouts.size()));
size_t boundDescs = setLayouts.size();
// need at least one set, if the shader isn't using any we'll just make our own
if(setLayouts.empty())
setLayouts.resize(1);
// start with the limits as they are, and subtract off them incrementally. When any limit would
// drop below 0, we fail.
uint32_t maxPerStageDescriptorSamplers[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSamplers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSamplers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSamplers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSamplers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSamplers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSamplers,
};
uint32_t maxPerStageDescriptorUniformBuffers[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorUniformBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorUniformBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorUniformBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorUniformBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorUniformBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorUniformBuffers,
};
uint32_t maxPerStageDescriptorStorageBuffers[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageBuffers,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageBuffers,
};
uint32_t maxPerStageDescriptorSampledImages[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSampledImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSampledImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSampledImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSampledImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSampledImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorSampledImages,
};
uint32_t maxPerStageDescriptorStorageImages[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageImages,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorStorageImages,
};
uint32_t maxPerStageDescriptorInputAttachments[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorInputAttachments,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorInputAttachments,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorInputAttachments,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorInputAttachments,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorInputAttachments,
m_pDriver->GetDeviceProps().limits.maxPerStageDescriptorInputAttachments,
};
uint32_t maxPerStageResources[6] = {
m_pDriver->GetDeviceProps().limits.maxPerStageResources,
m_pDriver->GetDeviceProps().limits.maxPerStageResources,
m_pDriver->GetDeviceProps().limits.maxPerStageResources,
m_pDriver->GetDeviceProps().limits.maxPerStageResources,
m_pDriver->GetDeviceProps().limits.maxPerStageResources,
m_pDriver->GetDeviceProps().limits.maxPerStageResources,
};
uint32_t maxDescriptorSetSamplers = m_pDriver->GetDeviceProps().limits.maxDescriptorSetSamplers;
uint32_t maxDescriptorSetUniformBuffers =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetUniformBuffers;
uint32_t maxDescriptorSetUniformBuffersDynamic =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetUniformBuffersDynamic;
uint32_t maxDescriptorSetStorageBuffers =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetStorageBuffers;
uint32_t maxDescriptorSetStorageBuffersDynamic =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetStorageBuffersDynamic;
uint32_t maxDescriptorSetSampledImages =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetSampledImages;
uint32_t maxDescriptorSetStorageImages =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetStorageImages;
uint32_t maxDescriptorSetInputAttachments =
m_pDriver->GetDeviceProps().limits.maxDescriptorSetInputAttachments;
uint32_t maxDescriptorSetInlineUniformBlocks = 0;
uint32_t maxPerStageDescriptorInlineUniformBlocks[6] = {};
if(m_pDriver->GetExtensions(NULL).ext_EXT_inline_uniform_block)
{
VkPhysicalDeviceInlineUniformBlockPropertiesEXT inlineProps = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT,
};
VkPhysicalDeviceProperties2 availBase = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
availBase.pNext = &inlineProps;
m_pDriver->vkGetPhysicalDeviceProperties2(m_pDriver->GetPhysDev(), &availBase);
maxDescriptorSetInlineUniformBlocks = inlineProps.maxDescriptorSetInlineUniformBlocks;
for(size_t i = 0; i < ARRAY_COUNT(maxPerStageDescriptorInlineUniformBlocks); i++)
maxPerStageDescriptorInlineUniformBlocks[i] =
inlineProps.maxPerStageDescriptorInlineUniformBlocks;
}
bool error = false;
#define UPDATE_AND_CHECK_LIMIT(maxLimit) \
if(!error) \
{ \
if(descriptorCount > maxLimit) \
{ \
error = true; \
RDCWARN("Limit %s is exceeded. Cannot patch in required descriptor(s).", #maxLimit); \
} \
else \
{ \
maxLimit -= descriptorCount; \
} \
}
#define UPDATE_AND_CHECK_STAGE_LIMIT(maxLimit) \
if(!error) \
{ \
for(uint32_t sbit = 0; sbit < 6; sbit++) \
{ \
if(newBind.stageFlags & (1U << sbit)) \
{ \
if(descriptorCount > maxLimit[sbit]) \
{ \
error = true; \
RDCWARN("Limit %s is exceeded. Cannot patch in required descriptor(s).", #maxLimit); \
} \
else \
{ \
maxLimit[sbit] -= descriptorCount; \
} \
} \
} \
}
for(size_t i = 0; !error && i < setLayouts.size(); i++)
{
bool hasImmutableSamplers = false;
// except for the first layout we need to start from scratch
if(i > 0)
bindings.clear();
// if the shader had no descriptor sets at all, i will be invalid, so just skip and add a set
// with only our own bindings.
if(i < pipeDescSetLayouts.size() && i < pipe.descSets.size() &&
pipe.descSets[i].pipeLayout != ResourceId())
{
// use the descriptor set layout from when it was bound. If the pipeline layout declared a
// descriptor set layout for this set, but it's statically unused, it may be complete
// garbage and doesn't match what the shader uses. However the pipeline layout at descriptor
// set bind time must have been compatible and valid so we can use it. If this set *is* used
// then the pipeline layout at bind time must be compatible with the pipeline's pipeline
// layout, so we're fine too.
const DescSetLayout &origLayout =
creationInfo.m_DescSetLayout[creationInfo.m_PipelineLayout[pipe.descSets[i].pipeLayout]
.descSetLayouts[i]];
WrappedVulkan::DescriptorSetInfo &setInfo =
m_pDriver->m_DescriptorSetState[pipe.descSets[i].descSet];
for(size_t b = 0; !error && b < origLayout.bindings.size(); b++)
{
const DescSetLayout::Binding &bind = origLayout.bindings[b];
// skip empty bindings
if(bind.descriptorType == VK_DESCRIPTOR_TYPE_MAX_ENUM)
continue;
uint32_t descriptorCount = bind.descriptorCount;
if(bind.variableSize)
descriptorCount = setInfo.data.variableDescriptorCount;
// make room in the pool
if(bind.descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT)
{
poolSizes[InlinePoolIndex].descriptorCount += descriptorCount;
inlineCreateInfo.maxInlineUniformBlockBindings++;
}
else
{
poolSizes[bind.descriptorType].descriptorCount += descriptorCount;
}
VkDescriptorSetLayoutBinding newBind;
// offset the binding. We offset all sets to make it easier for patching - don't need to
// conditionally patch shader bindings depending on which set they're in.
newBind.binding = uint32_t(b + newBindingsCount);
newBind.descriptorCount = descriptorCount;
newBind.descriptorType = bind.descriptorType;
// we only need it available for compute, just make all bindings visible otherwise dynamic
// buffer offsets could be indexed wrongly. Consider the case where we have binding 0 as a
// fragment UBO, and binding 1 as a vertex UBO. Then there are two dynamic offsets, and
// the second is the one we want to use with ours. If we only add the compute visibility
// bit to the second UBO, then suddenly it's the *first* offset that we must provide.
// Instead of trying to remap offsets to match, we simply make every binding compute
// visible so the ordering is still the same. Since compute and graphics are disjoint this
// is safe.
if(patchedBindingStage != 0)
newBind.stageFlags = patchedBindingStage;
else
newBind.stageFlags = bind.stageFlags;
switch(bind.descriptorType)
{
case VK_DESCRIPTOR_TYPE_SAMPLER:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetSamplers);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorSamplers);
break;
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetSampledImages);
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetSamplers);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorSamplers);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorSampledImages);
break;
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetSampledImages);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorSampledImages);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetStorageImages);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorStorageImages);
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetSampledImages);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorSampledImages);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetStorageImages);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorStorageImages);
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetUniformBuffers);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorUniformBuffers);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetStorageBuffers);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorStorageBuffers);
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetUniformBuffersDynamic);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorUniformBuffers);
break;
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetStorageBuffersDynamic);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorStorageBuffers);
break;
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetInputAttachments);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorInputAttachments);
break;
case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT:
descriptorCount = 1;
UPDATE_AND_CHECK_LIMIT(maxDescriptorSetInlineUniformBlocks);
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageDescriptorInlineUniformBlocks);
break;
default: break;
}
UPDATE_AND_CHECK_STAGE_LIMIT(maxPerStageResources);
if(bind.immutableSampler)
{
hasImmutableSamplers = true;
VkSampler *samplers = new VkSampler[bind.descriptorCount];
newBind.pImmutableSamplers = samplers;
for(uint32_t s = 0; s < bind.descriptorCount; s++)
samplers[s] = GetResourceManager()->GetCurrentHandle<VkSampler>(bind.immutableSampler[s]);
}
else
{
newBind.pImmutableSamplers = NULL;
}
bindings.push_back(newBind);
}
}
VkDescriptorSetLayoutCreateInfo descsetLayoutInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
NULL,
0,
(uint32_t)bindings.size(),
bindings.data(),
};
if(!error)
{
// create new offseted descriptor layout
vkr = m_pDriver->vkCreateDescriptorSetLayout(dev, &descsetLayoutInfo, NULL, &setLayouts[i]);
CheckVkResult(vkr);
}
if(hasImmutableSamplers)
{
for(const VkDescriptorSetLayoutBinding &bind : bindings)
delete[] bind.pImmutableSamplers;
}
}
// if we hit an error, we can't create the descriptor set so bail out now
if(error)
return;
VkDescriptorPoolCreateInfo poolCreateInfo = {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
// 1 set for each layout
poolCreateInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
poolCreateInfo.maxSets = (uint32_t)setLayouts.size();
poolCreateInfo.poolSizeCount = poolSizeCount;
poolCreateInfo.pPoolSizes = poolSizes;
if(inlineCreateInfo.maxInlineUniformBlockBindings > 0)
{
poolCreateInfo.poolSizeCount++;
poolCreateInfo.pNext = &inlineCreateInfo;
}
// create descriptor pool with enough space for our descriptors
vkr = m_pDriver->vkCreateDescriptorPool(dev, &poolCreateInfo, NULL, &descpool);
CheckVkResult(vkr);
// allocate all the descriptors
VkDescriptorSetAllocateInfo descSetAllocInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
NULL,
descpool,
(uint32_t)setLayouts.size(),
setLayouts.data(),
};
descSets.resize(setLayouts.size());
m_pDriver->vkAllocateDescriptorSets(dev, &descSetAllocInfo, descSets.data());
// copy the data across from the real descriptors into our adjusted bindings
for(size_t i = 0; i < boundDescs; i++)
{
if(pipe.descSets[i].descSet == ResourceId())
continue;
// as above we use the pipeline layout that was originally used to bind this descriptor set
// and not the pipeline layout from the pipeline, in case the pipeline statically doesn't use
// this set and so its descriptor set layout is garbage (doesn't match the actual bound
// descriptor set)
const DescSetLayout &origLayout =
creationInfo.m_DescSetLayout[creationInfo.m_PipelineLayout[pipe.descSets[i].pipeLayout]
.descSetLayouts[i]];
WrappedVulkan::DescriptorSetInfo &setInfo =
m_pDriver->m_DescriptorSetState[pipe.descSets[i].descSet];
{
// push descriptors don't have a source to copy from, we need to add writes
VkWriteDescriptorSet write = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = descSets[i];
// Only write bindings that actually exist in the current descriptor
// set. If there are bindings that aren't set, assume the app knows
// what it's doing and the remaining bindings are unused.
for(size_t b = 0; b < setInfo.data.binds.size(); b++)
{
const DescSetLayout::Binding &bind = origLayout.bindings[b];
// skip empty bindings
if(bind.descriptorType == VK_DESCRIPTOR_TYPE_MAX_ENUM)
continue;
uint32_t descriptorCount = bind.descriptorCount;
if(bind.variableSize)
descriptorCount = setInfo.data.variableDescriptorCount;
DescriptorSetSlot *slot = setInfo.data.binds[b];
write.dstBinding = uint32_t(b + newBindingsCount);
write.dstArrayElement = 0;
write.descriptorCount = descriptorCount;
write.descriptorType = bind.descriptorType;
switch(write.descriptorType)
{
case VK_DESCRIPTOR_TYPE_SAMPLER:
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
{
VkDescriptorImageInfo *out = new VkDescriptorImageInfo[write.descriptorCount];
for(uint32_t w = 0; w < write.descriptorCount; w++)
{
const DescriptorSetSlotImageInfo &src = slot[w].imageInfo;
out[w].imageLayout = src.imageLayout;
out[w].sampler = GetResourceManager()->GetCurrentHandle<VkSampler>(src.sampler);
out[w].imageView = GetResourceManager()->GetCurrentHandle<VkImageView>(src.imageView);
}
write.pImageInfo = out;
allocImgWrites.push_back(out);
break;
}
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
{
VkBufferView *out = new VkBufferView[write.descriptorCount];
for(uint32_t w = 0; w < write.descriptorCount; w++)
out[w] = GetResourceManager()->GetCurrentHandle<VkBufferView>(slot[w].texelBufferView);
write.pTexelBufferView = out;
allocBufViewWrites.push_back(out);
break;
}
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
{
VkDescriptorBufferInfo *out = new VkDescriptorBufferInfo[write.descriptorCount];
for(uint32_t w = 0; w < write.descriptorCount; w++)
{
const DescriptorSetSlotBufferInfo &src = slot[w].bufferInfo;
out[w].offset = src.offset;
out[w].range = src.range;
out[w].buffer = GetResourceManager()->GetCurrentHandle<VkBuffer>(src.buffer);
}
write.pBufferInfo = out;
allocBufWrites.push_back(out);
break;
}
case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT:
{
allocInlineWrites.push_back(new VkWriteDescriptorSetInlineUniformBlockEXT);
VkWriteDescriptorSetInlineUniformBlockEXT *inlineWrite = allocInlineWrites.back();
inlineWrite->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK_EXT;
inlineWrite->pNext = NULL;
inlineWrite->dataSize = descriptorCount;
inlineWrite->pData = setInfo.data.inlineBytes.data() + slot[0].inlineOffset;
write.pNext = inlineWrite;
break;
}
default: RDCERR("Unexpected descriptor type %d", write.descriptorType);
}
// skip validity check for inline uniform block as the descriptor count means something
// different
if(write.descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT)
{
write.descriptorCount = descriptorCount;
descWrites.push_back(write);
continue;
}
// start with no descriptors
write.descriptorCount = 0;
for(uint32_t w = 0; w < descriptorCount; w++)
{
// if this write is valid, we increment the descriptor count and continue
if(IsValid(m_pDriver->NULLDescriptorsAllowed(), write, w - write.dstArrayElement))
{
write.descriptorCount++;
}
else
{
// if this write isn't valid, then we first check to see if we had any previous
// pending writes in the array we were going to batch together, if so we add them.
if(write.descriptorCount > 0)
descWrites.push_back(write);
// skip past any previous descriptors we just wrote, as well as the current invalid
// one
if(write.pBufferInfo)
write.pBufferInfo += write.descriptorCount + 1;
if(write.pImageInfo)
write.pImageInfo += write.descriptorCount + 1;
if(write.pTexelBufferView)
write.pTexelBufferView += write.descriptorCount + 1;
// now start again from 0 descriptors, at the next array element
write.dstArrayElement += write.descriptorCount + 1;
write.descriptorCount = 0;
}
}
// if there are any left, add them here
if(write.descriptorCount > 0)
descWrites.push_back(write);
// don't leak the arrays and cause double deletes, NULL them after each time
write.pImageInfo = NULL;
write.pBufferInfo = NULL;
write.pTexelBufferView = NULL;
}
}
}
m_pDriver->vkUpdateDescriptorSets(dev, (uint32_t)descWrites.size(), descWrites.data(), 0, NULL);
}
void VulkanDebugManager::CustomShaderRendering::Destroy(WrappedVulkan *driver)
{
driver->vkDestroyRenderPass(driver->GetDev(), TexRP, NULL);
driver->vkDestroyFramebuffer(driver->GetDev(), TexFB, NULL);
driver->vkDestroyImage(driver->GetDev(), TexImg, NULL);
for(size_t i = 0; i < ARRAY_COUNT(TexImgView); i++)
driver->vkDestroyImageView(driver->GetDev(), TexImgView[i], NULL);
driver->vkFreeMemory(driver->GetDev(), TexMem, NULL);
driver->vkDestroyPipeline(driver->GetDev(), TexPipeline, NULL);
}
void VulkanReplay::CreateResources()
{
m_Device = m_pDriver->GetDev();
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.0f);
m_General.Init(m_pDriver, VK_NULL_HANDLE);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.1f);
m_TexRender.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.3f);
m_Overlay.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.4f);
m_MeshRender.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.6f);
m_VertexPick.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.7f);
m_PixelPick.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.75f);
m_PixelHistory.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.8f);
m_Histogram.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 0.9f);
m_ShaderDebugData.Init(m_pDriver, m_General.DescriptorPool);
RenderDoc::Inst().SetProgress(LoadProgress::DebugManagerInit, 1.0f);
GpaVkContextOpenInfo context = {Unwrap(m_pDriver->GetInstance()), Unwrap(m_pDriver->GetPhysDev()),
Unwrap(m_pDriver->GetDev())};
if(!m_pDriver->GetReplay()->IsRemoteProxy() && Vulkan_HardwareCounters())
{
AMDCounters *counters = NULL;
GPUVendor vendor = m_pDriver->GetDriverInfo().Vendor();
if(vendor == GPUVendor::AMD)
{
RDCLOG("AMD GPU detected - trying to initialise AMD counters");
counters = new AMDCounters();
}
else
{
RDCLOG("%s GPU detected - no counters available", ToStr(vendor).c_str());
}
if(counters && counters->Init(AMDCounters::ApiType::Vk, (void *)&context))
{
m_pAMDCounters = counters;
}
else
{
delete counters;
m_pAMDCounters = NULL;
}
}
}
void VulkanReplay::DestroyResources()
{
ClearPostVSCache();
ClearFeedbackCache();
m_General.Destroy(m_pDriver);
m_TexRender.Destroy(m_pDriver);
m_Overlay.Destroy(m_pDriver);
m_VertexPick.Destroy(m_pDriver);
m_PixelPick.Destroy(m_pDriver);
m_PixelHistory.Destroy(m_pDriver);
m_Histogram.Destroy(m_pDriver);
m_PostVS.Destroy(m_pDriver);
SAFE_DELETE(m_pAMDCounters);
}
void VulkanReplay::GeneralMisc::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
VkResult vkr = VK_SUCCESS;
VkDescriptorPoolSize descPoolTypes[] = {
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 320},
{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 128},
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 32},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 128},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 128},
{VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 64},
{VK_DESCRIPTOR_TYPE_SAMPLER, 64},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 32},
};
VkDescriptorPoolCreateInfo descPoolInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
NULL,
0,
32,
ARRAY_COUNT(descPoolTypes),
&descPoolTypes[0],
};
// create descriptor pool
vkr = driver->vkCreateDescriptorPool(driver->GetDev(), &descPoolInfo, NULL, &DescriptorPool);
driver->CheckVkResult(vkr);
CREATE_OBJECT(PointSampler, VK_FILTER_NEAREST);
}
void VulkanReplay::GeneralMisc::Destroy(WrappedVulkan *driver)
{
if(DescriptorPool == VK_NULL_HANDLE)
return;
driver->vkDestroyDescriptorPool(driver->GetDev(), DescriptorPool, NULL);
driver->vkDestroySampler(driver->GetDev(), PointSampler, NULL);
}
void VulkanReplay::TextureRendering::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
VkResult vkr = VK_SUCCESS;
VulkanShaderCache *shaderCache = driver->GetShaderCache();
CREATE_OBJECT(PointSampler, VK_FILTER_NEAREST);
CREATE_OBJECT(LinearSampler, VK_FILTER_LINEAR);
CREATE_OBJECT(DescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, NULL},
{1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, NULL},
{6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{7, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{8, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{9, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{10, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, VK_SHADER_STAGE_ALL, NULL},
{11, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{12, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{13, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{14, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{15, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{16, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{17, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{18, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{19, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{20, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{50, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_ALL, &PointSampler},
{51, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_ALL, &LinearSampler},
});
CREATE_OBJECT(PipeLayout, DescSetLayout, 0);
for(size_t i = 0; i < ARRAY_COUNT(DescSet); i++)
{
CREATE_OBJECT(DescSet[i], descriptorPool, DescSetLayout);
}
UBO.Create(driver, driver->GetDev(), 128, 10, 0);
RDCCOMPILE_ASSERT(sizeof(TexDisplayUBOData) <= 128, "tex display size");
HeatmapUBO.Create(driver, driver->GetDev(), 512, 10, 0);
RDCCOMPILE_ASSERT(sizeof(HeatmapData) <= 512, "tex display size");
{
VkRenderPass SRGBA8RP = VK_NULL_HANDLE;
VkRenderPass RGBA16RP = VK_NULL_HANDLE;
VkRenderPass RGBA32RP = VK_NULL_HANDLE;
CREATE_OBJECT(SRGBA8RP, VK_FORMAT_R8G8B8A8_SRGB);
CREATE_OBJECT(RGBA16RP, VK_FORMAT_R16G16B16A16_SFLOAT);
CREATE_OBJECT(RGBA32RP, VK_FORMAT_R32G32B32A32_SFLOAT);
ConciseGraphicsPipeline texDisplayInfo = {
SRGBA8RP,
PipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::BlitVS),
shaderCache->GetBuiltinModule(BuiltinShader::TexDisplayFS),
{VK_DYNAMIC_STATE_VIEWPORT},
VK_SAMPLE_COUNT_1_BIT,
false, // sampleRateShading
false, // depthEnable
false, // stencilEnable
VK_STENCIL_OP_KEEP,
true, // colourOutput
false, // blendEnable
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ZERO,
0xf, // writeMask
};
ConciseGraphicsPipeline texRemapInfo = texDisplayInfo;
CREATE_OBJECT(Pipeline, texDisplayInfo);
texDisplayInfo.renderPass = RGBA32RP;
CREATE_OBJECT(F32Pipeline, texDisplayInfo);
texDisplayInfo.renderPass = RGBA16RP;
CREATE_OBJECT(F16Pipeline, texDisplayInfo);
texDisplayInfo.renderPass = SRGBA8RP;
texDisplayInfo.blendEnable = true;
texDisplayInfo.srcBlend = VK_BLEND_FACTOR_SRC_ALPHA;
texDisplayInfo.dstBlend = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
CREATE_OBJECT(BlendPipeline, texDisplayInfo);
VkFormat formats[3] = {VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R16G16B16A16_UINT,
VK_FORMAT_R32G32B32A32_UINT};
CompType cast[3] = {CompType::Float, CompType::UInt, CompType::SInt};
for(int f = 0; f < 3; f++)
{
for(int i = 0; i < 3; i++)
{
texRemapInfo.fragment =
shaderCache->GetBuiltinModule(BuiltinShader::TexRemap, BuiltinShaderBaseType(i));
CREATE_OBJECT(texRemapInfo.renderPass, GetViewCastedFormat(formats[f], cast[i]));
CREATE_OBJECT(RemapPipeline[f][i][0], texRemapInfo);
driver->vkDestroyRenderPass(driver->GetDev(), texRemapInfo.renderPass, NULL);
}
}
// make versions that only write to green, for doing two-pass stencil writes
texRemapInfo.writeMask = texDisplayInfo.writeMask = 0x2;
for(int f = 0; f < 3; f++)
{
for(int i = 0; i < 3; i++)
{
texRemapInfo.fragment =
shaderCache->GetBuiltinModule(BuiltinShader::TexRemap, BuiltinShaderBaseType(i));
CREATE_OBJECT(texRemapInfo.renderPass, GetViewCastedFormat(formats[f], cast[i]));
CREATE_OBJECT(RemapPipeline[f][i][1], texRemapInfo);
driver->vkDestroyRenderPass(driver->GetDev(), texRemapInfo.renderPass, NULL);
}
}
texDisplayInfo.renderPass = SRGBA8RP;
CREATE_OBJECT(PipelineGreenOnly, texDisplayInfo);
texDisplayInfo.renderPass = RGBA32RP;
CREATE_OBJECT(F32PipelineGreenOnly, texDisplayInfo);
texDisplayInfo.renderPass = RGBA16RP;
CREATE_OBJECT(F16PipelineGreenOnly, texDisplayInfo);
driver->vkDestroyRenderPass(driver->GetDev(), SRGBA8RP, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), RGBA16RP, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), RGBA32RP, NULL);
}
// create dummy images for filling out the texdisplay descriptors
// in slots that are skipped by dynamic branching (e.g. 3D texture
// when we're displaying a 2D, etc).
{
VkCommandBuffer cmd = driver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
vkr = ObjDisp(cmd)->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
driver->CheckVkResult(vkr);
int index = 0;
// we pick RGBA8 formats to be guaranteed they will be supported
VkFormat formats[] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT};
VkImageType types[] = {VK_IMAGE_TYPE_1D, VK_IMAGE_TYPE_2D, VK_IMAGE_TYPE_3D, VK_IMAGE_TYPE_2D};
VkImageViewType viewtypes[] = {
VK_IMAGE_VIEW_TYPE_1D_ARRAY, VK_IMAGE_VIEW_TYPE_2D_ARRAY, VK_IMAGE_VIEW_TYPE_3D,
VK_IMAGE_VIEW_TYPE_2D_ARRAY,
driver->GetDeviceEnabledFeatures().imageCubeArray ? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY
: VK_IMAGE_VIEW_TYPE_CUBE,
};
VkSampleCountFlagBits sampleCounts[] = {VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT,
VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_4_BIT};
// type max is one higher than the last RESTYPE, and RESTYPES are 1-indexed
RDCCOMPILE_ASSERT(RESTYPE_TEXTYPEMAX - 1 == ARRAY_COUNT(types),
"RESTYPE values don't match formats for dummy images");
RDCCOMPILE_ASSERT(sizeof(DummyImages) == sizeof(DummyImageViews),
"dummy image arrays mismatched sizes");
RDCCOMPILE_ASSERT(ARRAY_COUNT(DummyImages) == ARRAY_COUNT(formats),
"dummy image arrays mismatched sizes");
// types + 1 for cube
RDCCOMPILE_ASSERT(ARRAY_COUNT(DummyImages[0]) == ARRAY_COUNT(types) + 1,
"dummy image arrays mismatched sizes");
RDCCOMPILE_ASSERT(ARRAY_COUNT(DummyImages[0]) == ARRAY_COUNT(viewtypes),
"dummy image arrays mismatched sizes");
RDCCOMPILE_ASSERT(ARRAY_COUNT(DummyWrites) == ARRAY_COUNT(DummyInfos),
"dummy image arrays mismatched sizes");
CREATE_OBJECT(DummySampler, VK_FILTER_NEAREST);
for(size_t fmt = 0; fmt < ARRAY_COUNT(formats); fmt++)
{
for(size_t type = 0; type < ARRAY_COUNT(types); type++)
{
// create 1x1 image of the right size
VkImageCreateInfo imInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
NULL,
0,
types[type],
formats[fmt],
{1, 1, 1},
1,
1,
sampleCounts[type],
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_SAMPLED_BIT,
VK_SHARING_MODE_EXCLUSIVE,
0,
NULL,
VK_IMAGE_LAYOUT_UNDEFINED,
};
// make the 2D image cube-compatible
if(type == 1)
{
imInfo.arrayLayers = 6;
imInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
}
vkr = driver->vkCreateImage(driver->GetDev(), &imInfo, NULL, &DummyImages[fmt][type]);
driver->CheckVkResult(vkr);
MemoryAllocation alloc = driver->AllocateMemoryForResource(
DummyImages[fmt][type], MemoryScope::ImmutableReplayDebug, MemoryType::GPULocal);
if(alloc.mem == VK_NULL_HANDLE)
return;
vkr = driver->vkBindImageMemory(driver->GetDev(), DummyImages[fmt][type], alloc.mem,
alloc.offs);
driver->CheckVkResult(vkr);
// fill out the descriptor set write to the write binding - set will be filled out
// on demand when we're actually using these writes.
DummyWrites[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
DummyWrites[index].pNext = NULL;
DummyWrites[index].dstSet = VK_NULL_HANDLE;
DummyWrites[index].dstBinding =
5 * uint32_t(fmt + 1) + uint32_t(type) + 1; // 5 + RESTYPE_x
DummyWrites[index].dstArrayElement = 0;
DummyWrites[index].descriptorCount = 1;
DummyWrites[index].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
DummyWrites[index].pImageInfo = &DummyInfos[index];
DummyWrites[index].pBufferInfo = NULL;
DummyWrites[index].pTexelBufferView = NULL;
DummyInfos[index].sampler = Unwrap(DummySampler);
DummyInfos[index].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
index++;
}
}
// add the last one for the odd-one-out YUV texture
DummyWrites[index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
DummyWrites[index].pNext = NULL;
DummyWrites[index].dstSet = VK_NULL_HANDLE;
DummyWrites[index].dstBinding = 10; // texYUV
DummyWrites[index].dstArrayElement = 0;
DummyWrites[index].descriptorCount = 1;
DummyWrites[index].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
DummyWrites[index].pImageInfo = &DummyInfos[index];
DummyWrites[index].pBufferInfo = NULL;
DummyWrites[index].pTexelBufferView = NULL;
DummyWrites[index + 1] = DummyWrites[index];
DummyWrites[index + 1].dstArrayElement = 1;
DummyInfos[index].sampler = Unwrap(DummySampler);
DummyInfos[index].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
DummyInfos[index + 1].sampler = Unwrap(DummySampler);
DummyInfos[index + 1].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
// align up for the dummy buffer
{
VkBufferCreateInfo bufInfo = {
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, NULL, 0, 16,
VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
};
vkr = driver->vkCreateBuffer(driver->GetDev(), &bufInfo, NULL, &DummyBuffer);
driver->CheckVkResult(vkr);
MemoryAllocation alloc = driver->AllocateMemoryForResource(
DummyBuffer, MemoryScope::ImmutableReplayDebug, MemoryType::GPULocal);
if(alloc.mem == VK_NULL_HANDLE)
return;
vkr = driver->vkBindBufferMemory(driver->GetDev(), DummyBuffer, alloc.mem, alloc.offs);
driver->CheckVkResult(vkr);
}
// now that the image memory is bound, we can create the image views and fill the descriptor
// set writes.
index = 0;
for(size_t fmt = 0; fmt < ARRAY_COUNT(formats); fmt++)
{
for(size_t type = 0; type < ARRAY_COUNT(viewtypes); type++)
{
size_t imType = type;
// the cubemap view re-uses the 2D image
bool cube = false;
if(viewtypes[type] == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY ||
viewtypes[type] == VK_IMAGE_VIEW_TYPE_CUBE)
{
imType = 1;
cube = true;
}
VkImageViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
NULL,
0,
DummyImages[fmt][imType],
viewtypes[type],
formats[fmt],
{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
{
VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1,
},
};
if(cube)
viewInfo.subresourceRange.layerCount = 6;
vkr = driver->vkCreateImageView(driver->GetDev(), &viewInfo, NULL,
&DummyImageViews[fmt][type]);
driver->CheckVkResult(vkr);
// the cubemap view we don't create an info for it, and the image is already transitioned
if(cube)
continue;
RDCASSERT((size_t)index < ARRAY_COUNT(DummyInfos), index);
DummyInfos[index].imageView = Unwrap(DummyImageViews[fmt][type]);
// need to update image layout into valid state
VkImageMemoryBarrier barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
NULL,
0,
VK_ACCESS_SHADER_READ_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(DummyImages[fmt][imType]),
{VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS},
};
DoPipelineBarrier(cmd, 1, &barrier);
index++;
}
}
// duplicate 2D dummy image into YUV
DummyInfos[index].imageView = DummyInfos[1].imageView;
DummyInfos[index + 1].imageView = DummyInfos[1].imageView;
if(DummyBuffer != VK_NULL_HANDLE)
{
VkFormat bufViewTypes[] = {
VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_SINT,
};
for(size_t i = 0; i < ARRAY_COUNT(bufViewTypes); i++)
{
VkBufferViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO, NULL, 0, DummyBuffer, bufViewTypes[i], 0, 16,
};
vkr = driver->vkCreateBufferView(driver->GetDev(), &viewInfo, NULL, &DummyBufferView[i]);
driver->CheckVkResult(vkr);
}
}
ObjDisp(cmd)->EndCommandBuffer(Unwrap(cmd));
}
}
void VulkanReplay::TextureRendering::Destroy(WrappedVulkan *driver)
{
if(DescSetLayout == VK_NULL_HANDLE)
return;
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), DescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), PipeLayout, NULL);
driver->vkDestroyPipeline(driver->GetDev(), Pipeline, NULL);
driver->vkDestroyPipeline(driver->GetDev(), BlendPipeline, NULL);
driver->vkDestroyPipeline(driver->GetDev(), F16Pipeline, NULL);
driver->vkDestroyPipeline(driver->GetDev(), F32Pipeline, NULL);
for(size_t f = 0; f < 3; f++)
for(size_t i = 0; i < 3; i++)
for(size_t g = 0; g < 2; g++)
driver->vkDestroyPipeline(driver->GetDev(), RemapPipeline[f][i][g], NULL);
driver->vkDestroyPipeline(driver->GetDev(), PipelineGreenOnly, NULL);
driver->vkDestroyPipeline(driver->GetDev(), F16PipelineGreenOnly, NULL);
driver->vkDestroyPipeline(driver->GetDev(), F32PipelineGreenOnly, NULL);
UBO.Destroy();
HeatmapUBO.Destroy();
driver->vkDestroySampler(driver->GetDev(), PointSampler, NULL);
driver->vkDestroySampler(driver->GetDev(), LinearSampler, NULL);
for(size_t fmt = 0; fmt < ARRAY_COUNT(DummyImages); fmt++)
{
for(size_t type = 0; type < ARRAY_COUNT(DummyImages[0]); type++)
{
driver->vkDestroyImageView(driver->GetDev(), DummyImageViews[fmt][type], NULL);
driver->vkDestroyImage(driver->GetDev(), DummyImages[fmt][type], NULL);
}
}
for(size_t fmt = 0; fmt < ARRAY_COUNT(DummyBufferView); fmt++)
driver->vkDestroyBufferView(driver->GetDev(), DummyBufferView[fmt], NULL);
driver->vkDestroyBuffer(driver->GetDev(), DummyBuffer, NULL);
driver->vkDestroySampler(driver->GetDev(), DummySampler, NULL);
}
void VulkanReplay::OverlayRendering::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
VulkanShaderCache *shaderCache = driver->GetShaderCache();
VkRenderPass SRGBA8RP = VK_NULL_HANDLE;
VkRenderPass SRGBA8MSRP = VK_NULL_HANDLE;
CREATE_OBJECT(SRGBA8RP, VK_FORMAT_R8G8B8A8_SRGB);
CREATE_OBJECT(SRGBA8MSRP, VK_FORMAT_R8G8B8A8_SRGB, VULKAN_MESH_VIEW_SAMPLES);
CREATE_OBJECT(m_CheckerDescSetLayout,
{{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, NULL}});
CREATE_OBJECT(m_QuadDescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_ALL, NULL},
});
CREATE_OBJECT(m_TriSizeDescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, NULL},
{2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, NULL},
});
CREATE_OBJECT(m_CheckerPipeLayout, m_CheckerDescSetLayout, 0);
CREATE_OBJECT(m_QuadResolvePipeLayout, m_QuadDescSetLayout, 0);
CREATE_OBJECT(m_TriSizePipeLayout, m_TriSizeDescSetLayout, 0);
CREATE_OBJECT(m_QuadDescSet, descriptorPool, m_QuadDescSetLayout);
CREATE_OBJECT(m_TriSizeDescSet, descriptorPool, m_TriSizeDescSetLayout);
CREATE_OBJECT(m_CheckerDescSet, descriptorPool, m_CheckerDescSetLayout);
m_CheckerUBO.Create(driver, driver->GetDev(), 128, 10, 0);
RDCCOMPILE_ASSERT(sizeof(CheckerboardUBOData) <= 128, "checkerboard UBO size");
m_TriSizeUBO.Create(driver, driver->GetDev(), sizeof(Vec4f), 4096, 0);
ConciseGraphicsPipeline pipeInfo = {
SRGBA8RP,
m_CheckerPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::BlitVS),
shaderCache->GetBuiltinModule(BuiltinShader::CheckerboardFS),
{VK_DYNAMIC_STATE_VIEWPORT},
VK_SAMPLE_COUNT_1_BIT,
false, // sampleRateShading
false, // depthEnable
false, // stencilEnable
VK_STENCIL_OP_KEEP,
true, // colourOutput
false, // blendEnable
VK_BLEND_FACTOR_SRC_ALPHA,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
0xf, // writeMask
};
CREATE_OBJECT(m_CheckerPipeline, pipeInfo);
pipeInfo.renderPass = SRGBA8MSRP;
pipeInfo.sampleCount = VULKAN_MESH_VIEW_SAMPLES;
CREATE_OBJECT(m_CheckerMSAAPipeline, pipeInfo);
uint32_t samplesHandled = 0;
RDCCOMPILE_ASSERT(ARRAY_COUNT(m_CheckerF16Pipeline) == ARRAY_COUNT(m_QuadResolvePipeline),
"Arrays are mismatched in size!");
uint32_t supportedSampleCounts = driver->GetDeviceProps().limits.framebufferColorSampleCounts;
for(size_t i = 0; i < ARRAY_COUNT(m_CheckerF16Pipeline); i++)
{
VkSampleCountFlagBits samples = VkSampleCountFlagBits(1 << i);
if((supportedSampleCounts & (uint32_t)samples) == 0)
continue;
VkRenderPass RGBA16MSRP = VK_NULL_HANDLE;
CREATE_OBJECT(RGBA16MSRP, VK_FORMAT_R16G16B16A16_SFLOAT, samples);
if(RGBA16MSRP != VK_NULL_HANDLE)
samplesHandled |= (uint32_t)samples;
else
continue;
// if we this sample count is supported then create a pipeline
pipeInfo.renderPass = RGBA16MSRP;
pipeInfo.sampleCount = VkSampleCountFlagBits(1 << i);
// set up outline pipeline configuration
pipeInfo.blendEnable = true;
pipeInfo.fragment = shaderCache->GetBuiltinModule(BuiltinShader::CheckerboardFS);
pipeInfo.pipeLayout = m_CheckerPipeLayout;
CREATE_OBJECT(m_CheckerF16Pipeline[i], pipeInfo);
// set up quad resolve pipeline configuration
pipeInfo.blendEnable = false;
pipeInfo.fragment = shaderCache->GetBuiltinModule(BuiltinShader::QuadResolveFS);
pipeInfo.pipeLayout = m_QuadResolvePipeLayout;
if(pipeInfo.fragment != VK_NULL_HANDLE &&
shaderCache->GetBuiltinModule(BuiltinShader::QuadWriteFS) != VK_NULL_HANDLE)
{
CREATE_OBJECT(m_QuadResolvePipeline[i], pipeInfo);
}
driver->vkDestroyRenderPass(driver->GetDev(), RGBA16MSRP, NULL);
}
RDCASSERTEQUAL((uint32_t)driver->GetDeviceProps().limits.framebufferColorSampleCounts,
samplesHandled);
VkDescriptorBufferInfo checkerboard = {};
m_CheckerUBO.FillDescriptor(checkerboard);
VkWriteDescriptorSet writes[] = {
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(m_CheckerDescSet), 0, 0, 1,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, NULL, &checkerboard, NULL},
};
VkDevice dev = driver->GetDev();
ObjDisp(dev)->UpdateDescriptorSets(Unwrap(dev), ARRAY_COUNT(writes), writes, 0, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), SRGBA8RP, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), SRGBA8MSRP, NULL);
}
void VulkanReplay::OverlayRendering::Destroy(WrappedVulkan *driver)
{
if(ImageMem == VK_NULL_HANDLE)
return;
driver->vkFreeMemory(driver->GetDev(), ImageMem, NULL);
driver->vkDestroyImage(driver->GetDev(), Image, NULL);
driver->vkDestroyImageView(driver->GetDev(), ImageView, NULL);
driver->vkDestroyFramebuffer(driver->GetDev(), NoDepthFB, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), NoDepthRP, NULL);
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), m_QuadDescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), m_QuadResolvePipeLayout, NULL);
for(size_t i = 0; i < ARRAY_COUNT(m_QuadResolvePipeline); i++)
driver->vkDestroyPipeline(driver->GetDev(), m_QuadResolvePipeline[i], NULL);
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), m_CheckerDescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), m_CheckerPipeLayout, NULL);
for(size_t i = 0; i < ARRAY_COUNT(m_CheckerF16Pipeline); i++)
driver->vkDestroyPipeline(driver->GetDev(), m_CheckerF16Pipeline[i], NULL);
driver->vkDestroyPipeline(driver->GetDev(), m_CheckerPipeline, NULL);
driver->vkDestroyPipeline(driver->GetDev(), m_CheckerMSAAPipeline, NULL);
m_CheckerUBO.Destroy();
m_TriSizeUBO.Destroy();
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), m_TriSizeDescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), m_TriSizePipeLayout, NULL);
}
void VulkanReplay::MeshRendering::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
CREATE_OBJECT(DescSetLayout,
{{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, NULL}});
CREATE_OBJECT(PipeLayout, DescSetLayout, 0);
CREATE_OBJECT(DescSet, descriptorPool, DescSetLayout);
UBO.Create(driver, driver->GetDev(), sizeof(MeshUBOData), 16, 0);
BBoxVB.Create(driver, driver->GetDev(), sizeof(Vec4f) * 128, 16, GPUBuffer::eGPUBufferVBuffer);
Vec4f TLN = Vec4f(-1.0f, 1.0f, 0.0f, 1.0f); // TopLeftNear, etc...
Vec4f TRN = Vec4f(1.0f, 1.0f, 0.0f, 1.0f);
Vec4f BLN = Vec4f(-1.0f, -1.0f, 0.0f, 1.0f);
Vec4f BRN = Vec4f(1.0f, -1.0f, 0.0f, 1.0f);
Vec4f TLF = Vec4f(-1.0f, 1.0f, 1.0f, 1.0f);
Vec4f TRF = Vec4f(1.0f, 1.0f, 1.0f, 1.0f);
Vec4f BLF = Vec4f(-1.0f, -1.0f, 1.0f, 1.0f);
Vec4f BRF = Vec4f(1.0f, -1.0f, 1.0f, 1.0f);
Vec4f axisFrustum[] = {
// axis marker vertices
Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec4f(1.0f, 0.0f, 0.0f, 1.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f),
Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec4f(0.0f, 0.0f, 0.0f, 1.0f), Vec4f(0.0f, 0.0f, 1.0f, 1.0f),
// frustum vertices
TLN, TRN, TRN, BRN, BRN, BLN, BLN, TLN,
TLN, TLF, TRN, TRF, BLN, BLF, BRN, BRF,
TLF, TRF, TRF, BRF, BRF, BLF, BLF, TLF,
};
// doesn't need to be ring'd as it's immutable
AxisFrustumVB.Create(driver, driver->GetDev(), sizeof(axisFrustum), 1,
GPUBuffer::eGPUBufferVBuffer);
Vec4f *axisData = (Vec4f *)AxisFrustumVB.Map();
memcpy(axisData, axisFrustum, sizeof(axisFrustum));
AxisFrustumVB.Unmap();
VkDescriptorBufferInfo meshrender = {};
UBO.FillDescriptor(meshrender);
VkWriteDescriptorSet writes[] = {
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(DescSet), 0, 0, 1,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, NULL, &meshrender, NULL},
};
VkDevice dev = driver->GetDev();
ObjDisp(dev)->UpdateDescriptorSets(Unwrap(dev), ARRAY_COUNT(writes), writes, 0, NULL);
}
void VulkanReplay::MeshRendering::Destroy(WrappedVulkan *driver)
{
if(DescSetLayout == VK_NULL_HANDLE)
return;
UBO.Destroy();
BBoxVB.Destroy();
AxisFrustumVB.Destroy();
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), DescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), PipeLayout, NULL);
}
void VulkanReplay::VertexPicking::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
VulkanShaderCache *shaderCache = driver->GetShaderCache();
CREATE_OBJECT(DescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
{2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
{3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
});
CREATE_OBJECT(Layout, DescSetLayout, 0);
CREATE_OBJECT(DescSet, descriptorPool, DescSetLayout);
// sizes are always 0 so that these buffers are created on demand
IBSize = 0;
VBSize = 0;
UBO.Create(driver, driver->GetDev(), 128, 1, 0);
RDCCOMPILE_ASSERT(sizeof(MeshPickUBOData) <= 128, "mesh pick UBO size");
const size_t meshPickResultSize = MaxMeshPicks * sizeof(FloatVector) + sizeof(uint32_t);
Result.Create(driver, driver->GetDev(), meshPickResultSize, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
ResultReadback.Create(driver, driver->GetDev(), meshPickResultSize, 1,
GPUBuffer::eGPUBufferReadback);
CREATE_OBJECT(Pipeline, Layout, shaderCache->GetBuiltinModule(BuiltinShader::MeshCS));
VkDescriptorBufferInfo vertexpickUBO = {};
VkDescriptorBufferInfo vertexpickResult = {};
UBO.FillDescriptor(vertexpickUBO);
Result.FillDescriptor(vertexpickResult);
VkWriteDescriptorSet writes[] = {
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(DescSet), 0, 0, 1,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, NULL, &vertexpickUBO, NULL},
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(DescSet), 3, 0, 1,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, NULL, &vertexpickResult, NULL},
};
VkDevice dev = driver->GetDev();
ObjDisp(dev)->UpdateDescriptorSets(Unwrap(dev), ARRAY_COUNT(writes), writes, 0, NULL);
}
void VulkanReplay::VertexPicking::Destroy(WrappedVulkan *driver)
{
if(DescSetLayout == VK_NULL_HANDLE)
return;
UBO.Destroy();
IB.Destroy();
IBUpload.Destroy();
VB.Destroy();
VBUpload.Destroy();
Result.Destroy();
ResultReadback.Destroy();
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), DescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), Layout, NULL);
driver->vkDestroyPipeline(driver->GetDev(), Pipeline, NULL);
}
void VulkanReplay::PixelPicking::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
VkResult vkr = VK_SUCCESS;
VkImageCreateInfo imInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
NULL,
0,
VK_IMAGE_TYPE_2D,
VK_FORMAT_R32G32B32A32_SFLOAT,
{1, 1, 1},
1,
1,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_SHARING_MODE_EXCLUSIVE,
0,
NULL,
VK_IMAGE_LAYOUT_UNDEFINED,
};
vkr = driver->vkCreateImage(driver->GetDev(), &imInfo, NULL, &Image);
driver->CheckVkResult(vkr);
VkMemoryRequirements mrq = {0};
driver->vkGetImageMemoryRequirements(driver->GetDev(), Image, &mrq);
// allocate readback memory
VkMemoryAllocateInfo allocInfo = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, mrq.size,
driver->GetGPULocalMemoryIndex(mrq.memoryTypeBits),
};
vkr = driver->vkAllocateMemory(driver->GetDev(), &allocInfo, NULL, &ImageMem);
driver->CheckVkResult(vkr);
vkr = driver->vkBindImageMemory(driver->GetDev(), Image, ImageMem, 0);
driver->CheckVkResult(vkr);
VkImageViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
NULL,
0,
Image,
VK_IMAGE_VIEW_TYPE_2D,
VK_FORMAT_R32G32B32A32_SFLOAT,
{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY},
{
VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1,
},
};
vkr = driver->vkCreateImageView(driver->GetDev(), &viewInfo, NULL, &ImageView);
driver->CheckVkResult(vkr);
// need to update image layout into valid state
VkCommandBuffer cmd = driver->GetNextCmd();
if(cmd == VK_NULL_HANDLE)
return;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
vkr = ObjDisp(cmd)->BeginCommandBuffer(Unwrap(cmd), &beginInfo);
driver->CheckVkResult(vkr);
VkImageMemoryBarrier barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
NULL,
0,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
Unwrap(Image),
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
};
DoPipelineBarrier(cmd, 1, &barrier);
ObjDisp(cmd)->EndCommandBuffer(Unwrap(cmd));
CREATE_OBJECT(RP, VK_FORMAT_R32G32B32A32_SFLOAT);
// create framebuffer
VkFramebufferCreateInfo fbinfo = {
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, NULL, 0, RP, 1, &ImageView, 1, 1, 1,
};
vkr = driver->vkCreateFramebuffer(driver->GetDev(), &fbinfo, NULL, &FB);
driver->CheckVkResult(vkr);
// since we always sync for readback, doesn't need to be ring'd
ReadbackBuffer.Create(driver, driver->GetDev(), sizeof(float) * 4, 1,
GPUBuffer::eGPUBufferReadback);
}
void VulkanReplay::PixelPicking::Destroy(WrappedVulkan *driver)
{
if(Image == VK_NULL_HANDLE)
return;
driver->vkDestroyImage(driver->GetDev(), Image, NULL);
driver->vkFreeMemory(driver->GetDev(), ImageMem, NULL);
driver->vkDestroyImageView(driver->GetDev(), ImageView, NULL);
ReadbackBuffer.Destroy();
driver->vkDestroyFramebuffer(driver->GetDev(), FB, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), RP, NULL);
}
void VulkanReplay::PixelHistory::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
CREATE_OBJECT(MSCopyDescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
});
VkResult vkr = VK_SUCCESS;
VkDescriptorPoolSize descPoolTypes[] = {
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 64}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 32},
};
VkDescriptorPoolCreateInfo descPoolInfo = {
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
NULL,
0,
32,
ARRAY_COUNT(descPoolTypes),
&descPoolTypes[0],
};
// create descriptor pool
vkr = driver->vkCreateDescriptorPool(driver->GetDev(), &descPoolInfo, NULL, &MSCopyDescPool);
driver->CheckVkResult(vkr);
CREATE_OBJECT(MSCopyPipeLayout, MSCopyDescSetLayout, 32);
CREATE_OBJECT(MSCopyPipe, MSCopyPipeLayout,
driver->GetShaderCache()->GetBuiltinModule(BuiltinShader::PixelHistoryMSCopyCS));
CREATE_OBJECT(MSCopyDepthPipe, MSCopyPipeLayout,
driver->GetShaderCache()->GetBuiltinModule(BuiltinShader::PixelHistoryMSCopyDepthCS));
}
void VulkanReplay::PixelHistory::Destroy(WrappedVulkan *driver)
{
if(MSCopyPipe != VK_NULL_HANDLE)
driver->vkDestroyPipeline(driver->GetDev(), MSCopyPipe, NULL);
if(MSCopyPipeLayout != VK_NULL_HANDLE)
driver->vkDestroyPipelineLayout(driver->GetDev(), MSCopyPipeLayout, NULL);
if(MSCopyDescSetLayout != VK_NULL_HANDLE)
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), MSCopyDescSetLayout, NULL);
if(MSCopyDescPool != VK_NULL_HANDLE)
driver->vkDestroyDescriptorPool(driver->GetDev(), MSCopyDescPool, NULL);
}
void VulkanReplay::HistogramMinMax::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
VulkanShaderCache *shaderCache = driver->GetShaderCache();
shaderCache->SetCaching(true);
rdcstr glsl;
CREATE_OBJECT(m_HistogramDescSetLayout,
{
{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
{2, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL, NULL},
{6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{7, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{8, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{9, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{10, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, VK_SHADER_STAGE_ALL, NULL},
{11, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{12, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{13, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{14, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{16, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{17, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{18, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
{19, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL, NULL},
});
CREATE_OBJECT(m_HistogramPipeLayout, m_HistogramDescSetLayout, 0);
for(size_t i = 0; i < ARRAY_COUNT(m_HistogramDescSet); i++)
CREATE_OBJECT(m_HistogramDescSet[i], descriptorPool, m_HistogramDescSetLayout);
rdcspv::CompilationSettings compileSettings;
compileSettings.lang = rdcspv::InputLanguage::VulkanGLSL;
compileSettings.stage = rdcspv::ShaderStage::Compute;
// type max is one higher than the last RESTYPE, and RESTYPES are 1-indexed
RDCCOMPILE_ASSERT(RESTYPE_TEXTYPEMAX == ARRAY_COUNT(m_MinMaxTilePipe),
"RESTYPE values don't match formats for dummy images");
RDCCOMPILE_ASSERT(ARRAY_COUNT(m_MinMaxTilePipe) == arraydim<BuiltinShaderTextureType>(),
"Array size doesn't match parameter enum");
RDCCOMPILE_ASSERT(ARRAY_COUNT(m_MinMaxTilePipe[0]) == arraydim<BuiltinShaderBaseType>(),
"Array size doesn't match parameter enum");
for(BuiltinShaderTextureType t = BuiltinShaderTextureType::First;
t < BuiltinShaderTextureType::Count; ++t)
{
for(BuiltinShaderBaseType f = BuiltinShaderBaseType::First; f < BuiltinShaderBaseType::Count; ++f)
{
CREATE_OBJECT(m_HistogramPipe[(size_t)t][(size_t)f], m_HistogramPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::HistogramCS, f, t));
CREATE_OBJECT(m_MinMaxTilePipe[(size_t)t][(size_t)f], m_HistogramPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::MinMaxTileCS, f, t));
if(t == BuiltinShaderTextureType::First)
{
CREATE_OBJECT(m_MinMaxResultPipe[(size_t)f], m_HistogramPipeLayout,
shaderCache->GetBuiltinModule(BuiltinShader::MinMaxResultCS, f));
}
}
}
shaderCache->SetCaching(false);
const uint32_t maxTexDim = 16384;
const uint32_t blockPixSize = HGRAM_PIXELS_PER_TILE * HGRAM_TILES_PER_BLOCK;
const uint32_t maxBlocksNeeded = (maxTexDim * maxTexDim) / (blockPixSize * blockPixSize);
const size_t byteSize =
2 * sizeof(Vec4f) * HGRAM_TILES_PER_BLOCK * HGRAM_TILES_PER_BLOCK * maxBlocksNeeded;
m_MinMaxTileResult.Create(driver, driver->GetDev(), byteSize, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
m_MinMaxResult.Create(driver, driver->GetDev(), sizeof(Vec4f) * 2, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
m_MinMaxReadback.Create(driver, driver->GetDev(), sizeof(Vec4f) * 2, 1,
GPUBuffer::eGPUBufferReadback);
m_HistogramBuf.Create(driver, driver->GetDev(), sizeof(uint32_t) * HGRAM_NUM_BUCKETS, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
m_HistogramReadback.Create(driver, driver->GetDev(), sizeof(uint32_t) * HGRAM_NUM_BUCKETS, 1,
GPUBuffer::eGPUBufferReadback);
// don't need to ring this, as we hard-sync for readback anyway
m_HistogramUBO.Create(driver, driver->GetDev(), sizeof(HistogramUBOData), 1, 0);
}
void VulkanReplay::HistogramMinMax::Destroy(WrappedVulkan *driver)
{
if(m_HistogramDescSetLayout == VK_NULL_HANDLE)
return;
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), m_HistogramDescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), m_HistogramPipeLayout, NULL);
for(size_t t = 1; t < ARRAY_COUNT(m_MinMaxTilePipe); t++)
{
for(size_t f = 0; f < ARRAY_COUNT(m_MinMaxTilePipe[0]); f++)
{
driver->vkDestroyPipeline(driver->GetDev(), m_MinMaxTilePipe[t][f], NULL);
driver->vkDestroyPipeline(driver->GetDev(), m_HistogramPipe[t][f], NULL);
if(t == 1)
driver->vkDestroyPipeline(driver->GetDev(), m_MinMaxResultPipe[f], NULL);
}
}
m_MinMaxTileResult.Destroy();
m_MinMaxResult.Destroy();
m_MinMaxReadback.Destroy();
m_HistogramBuf.Destroy();
m_HistogramReadback.Destroy();
m_HistogramUBO.Destroy();
}
void VulkanReplay::PostVS::Destroy(WrappedVulkan *driver)
{
if(XFBQueryPool != VK_NULL_HANDLE)
driver->vkDestroyQueryPool(driver->GetDev(), XFBQueryPool, NULL);
}
void VulkanReplay::Feedback::Destroy(WrappedVulkan *driver)
{
FeedbackBuffer.Destroy();
}
void ShaderDebugData::Init(WrappedVulkan *driver, VkDescriptorPool descriptorPool)
{
// should match the enum ShaderDebugBind
CREATE_OBJECT(
DescSetLayout,
{
// ShaderDebugBind::Tex1D
{1, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::Tex2D
{2, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::Tex3D
{3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::Tex2DMS
{4, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::TexCube
{5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::Buffer
{6, VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::Sampler
{7, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::Constants
{8, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL},
// ShaderDebugBind::MathResult
{9, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1,
VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT, NULL},
});
CREATE_OBJECT(PipeLayout, DescSetLayout, sizeof(Vec4f) * 6 + sizeof(uint32_t));
CREATE_OBJECT(DescSet, descriptorPool, DescSetLayout);
VkResult vkr = VK_SUCCESS;
VkImageCreateInfo imInfo = {
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
NULL,
0,
VK_IMAGE_TYPE_2D,
VK_FORMAT_R32G32B32A32_SFLOAT,
{1, 1, 1},
1,
1,
VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT,
VK_SHARING_MODE_EXCLUSIVE,
0,
NULL,
VK_IMAGE_LAYOUT_UNDEFINED,
};
vkr = driver->vkCreateImage(driver->GetDev(), &imInfo, NULL, &Image);
driver->CheckVkResult(vkr);
VkMemoryRequirements mrq = {0};
driver->vkGetImageMemoryRequirements(driver->GetDev(), Image, &mrq);
// allocate readback memory
VkMemoryAllocateInfo allocInfo = {
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, mrq.size,
driver->GetGPULocalMemoryIndex(mrq.memoryTypeBits),
};
vkr = driver->vkAllocateMemory(driver->GetDev(), &allocInfo, NULL, &ImageMemory);
driver->CheckVkResult(vkr);
vkr = driver->vkBindImageMemory(driver->GetDev(), Image, ImageMemory, 0);
driver->CheckVkResult(vkr);
VkImageViewCreateInfo viewInfo = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
NULL,
0,
Image,
VK_IMAGE_VIEW_TYPE_2D,
VK_FORMAT_R32G32B32A32_SFLOAT,
{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY},
{
VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1,
},
};
vkr = driver->vkCreateImageView(driver->GetDev(), &viewInfo, NULL, &ImageView);
driver->CheckVkResult(vkr);
VkAttachmentDescription attDesc = {
0,
VK_FORMAT_R32G32B32A32_SFLOAT,
VK_SAMPLE_COUNT_1_BIT,
VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL,
};
VkAttachmentReference attRef = {0, VK_IMAGE_LAYOUT_GENERAL};
VkSubpassDescription sub = {
0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, NULL, 1, &attRef,
};
VkSubpassDependency deps[2] = {
{
VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_READ_BIT,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 0,
},
{
0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT, 0,
},
};
VkRenderPassCreateInfo rpinfo = {
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, NULL, 0, 1, &attDesc, 1, &sub, 2, deps,
};
vkr = driver->vkCreateRenderPass(driver->GetDev(), &rpinfo, NULL, &RenderPass);
if(vkr != VK_SUCCESS)
RDCERR("Failed to create shader debug render pass: %s", ToStr(vkr).c_str());
// create framebuffer
VkFramebufferCreateInfo fbinfo = {
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, NULL, 0, RenderPass, 1, &ImageView, 1, 1, 1,
};
vkr = driver->vkCreateFramebuffer(driver->GetDev(), &fbinfo, NULL, &Framebuffer);
driver->CheckVkResult(vkr);
MathResult.Create(driver, driver->GetDev(), sizeof(Vec4f) * 4, 1,
GPUBuffer::eGPUBufferGPULocal | GPUBuffer::eGPUBufferSSBO);
// don't need to ring this, as we hard-sync for readback anyway
ReadbackBuffer.Create(driver, driver->GetDev(), sizeof(Vec4f) * 4, 1,
GPUBuffer::eGPUBufferReadback);
ConstantsBuffer.Create(driver, driver->GetDev(), 1024, 1, 0);
}
void ShaderDebugData::Destroy(WrappedVulkan *driver)
{
ConstantsBuffer.Destroy();
ReadbackBuffer.Destroy();
for(size_t i = 0; i < ARRAY_COUNT(MathPipe); i++)
driver->vkDestroyPipeline(driver->GetDev(), MathPipe[i], NULL);
driver->vkDestroyDescriptorSetLayout(driver->GetDev(), DescSetLayout, NULL);
driver->vkDestroyPipelineLayout(driver->GetDev(), PipeLayout, NULL);
driver->vkDestroyImage(driver->GetDev(), Image, NULL);
driver->vkFreeMemory(driver->GetDev(), ImageMemory, NULL);
driver->vkDestroyImageView(driver->GetDev(), ImageView, NULL);
driver->vkDestroyFramebuffer(driver->GetDev(), Framebuffer, NULL);
driver->vkDestroyRenderPass(driver->GetDev(), RenderPass, NULL);
// one module each for float, uint, sint.
for(size_t i = 0; i < ARRAY_COUNT(Module); i++)
driver->vkDestroyShaderModule(driver->GetDev(), Module[i], NULL);
for(auto it = m_Pipelines.begin(); it != m_Pipelines.end(); it++)
driver->vkDestroyPipeline(driver->GetDev(), it->second, NULL);
}
|
/* Copyright (c) 2012, Achilleas Margaritis, modified by Jin Li
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
#pragma once
//gcc chokes without rule::rule(const rule &),
//msvc complains when rule::rule(const rule &) is defined.
#ifdef _MSC_VER
#pragma warning (disable: 4521)
#endif
#include <vector>
#include <string>
#include <list>
#include <functional>
#include <codecvt>
#include <locale>
namespace parserlib {
///type of the parser's input.
typedef std::basic_string<wchar_t> input;
typedef input::iterator input_it;
typedef std::wstring_convert<std::codecvt_utf8_utf16<input::value_type>> Converter;
class _private;
class _expr;
class _context;
class rule;
struct item_t {
input_it begin;
input_it end;
void* user_data;
};
typedef std::function<bool(const item_t&)> user_handler;
///position into the input.
class pos {
public:
///interator into the input.
input::iterator m_it;
///line.
int m_line;
///column.
int m_col;
///null constructor.
pos():m_line(0),m_col(0) {}
/** constructor from input.
@param i input.
*/
pos(input &i);
};
/** a grammar expression.
*/
class expr {
public:
/** character terminal constructor.
@param c character.
*/
expr(char c);
/** null-terminated string terminal constructor.
@param s null-terminated string.
*/
expr(const char* s);
/** rule reference constructor.
@param r rule.
*/
expr(rule& r);
/** creates a zero-or-more loop out of this expression.
@return a zero-or-more loop expression.
*/
expr operator*() const;
/** creates a one-or-more loop out of this expression.
@return a one-or-more loop expression.
*/
expr operator+() const;
/** creates an optional out of this expression.
@return an optional expression.
*/
expr operator-() const;
/** creates an AND-expression.
@return an AND-expression.
*/
expr operator&() const;
/** creates a NOT-expression.
@return a NOT-expression.
*/
expr operator!() const;
private:
//internal expression
_expr* m_expr;
//internal constructor from internal expression
expr(_expr* e) : m_expr(e) {}
//assignment not allowed
expr& operator=(expr&);
friend class _private;
};
/** type of procedure to invoke when a rule is successfully parsed.
@param b begin position of input.
@param e end position of input.
@param d pointer to user data.
*/
typedef void (*parse_proc)(const pos& b, const pos& e, void* d);
///input range.
class input_range {
public:
virtual ~input_range() {}
///begin position.
pos m_begin;
///end position.
pos m_end;
///empty constructor.
input_range() {}
/** constructor.
@param b begin position.
@param e end position.
*/
input_range(const pos& b, const pos& e);
};
///enum with error types.
enum ERROR_TYPE {
///syntax error
ERROR_SYNTAX_ERROR = 1,
///invalid end of file
ERROR_INVALID_EOF,
///first user error
ERROR_USER = 100
};
///error.
class error : public input_range {
public:
///type
int m_type;
/** constructor.
@param b begin position.
@param e end position.
@param t type.
*/
error(const pos& b, const pos& e, int t);
/** compare on begin position.
@param e the other error to compare this with.
@return true if this comes before the previous error, false otherwise.
*/
bool operator<(const error& e) const;
};
///type of error list.
typedef std::list<error> error_list;
/** represents a rule.
*/
class rule {
public:
/** character terminal constructor.
@param c character.
*/
rule();
rule(char c);
/** null-terminated string terminal constructor.
@param s null-terminated string.
*/
rule(const char* s);
/** constructor from expression.
@param e expression.
*/
rule(const expr& e);
/** constructor from rule.
@param r rule.
*/
rule(rule& r);
/** invalid constructor from rule (required by gcc).
@param r rule.
@exception std::logic_error always thrown.
*/
rule(const rule& r);
/** deletes the internal object that represents the expression.
*/
~rule();
/** creates a zero-or-more loop out of this rule.
@return a zero-or-more loop rule.
*/
expr operator*();
/** creates a one-or-more loop out of this rule.
@return a one-or-more loop rule.
*/
expr operator+();
/** creates an optional out of this rule.
@return an optional rule.
*/
expr operator-();
/** creates an AND-expression out of this rule.
@return an AND-expression out of this rule.
*/
expr operator&();
/** creates a NOT-expression out of this rule.
@return a NOT-expression out of this rule.
*/
expr operator!();
/** sets the parse procedure.
@param p procedure.
*/
void set_parse_proc(parse_proc p);
/** get the this ptr (since operator & is overloaded).
@return pointer to this.
*/
rule* this_ptr() { return this; }
rule& operator=(rule&);
rule& operator=(const expr&);
private:
//mode
enum _MODE {
_PARSE,
_REJECT,
_ACCEPT
};
//state
struct _state {
//position in source code, relative to start
size_t m_pos;
//mode
_MODE m_mode;
//constructor
_state(size_t pos = -1, _MODE mode = _PARSE) :
m_pos(pos), m_mode(mode) {}
};
//internal expression
_expr* m_expr;
//associated parse procedure.
parse_proc m_parse_proc;
//state
_state m_state;
friend class _private;
friend class _context;
};
/** creates a sequence of expressions.
@param left left operand.
@param right right operand.
@return an expression which parses a sequence.
*/
expr operator>>(const expr& left, const expr& right);
/** creates a choice of expressions.
@param left left operand.
@param right right operand.
@return an expression which parses a choice.
*/
expr operator|(const expr& left, const expr& right);
/** converts a parser expression into a terminal.
@param e expression.
@return an expression which parses a terminal.
*/
expr term(const expr& e);
/** creates a set expression from a null-terminated string.
@param s null-terminated string with characters of the set.
@return an expression which parses a single character out of a set.
*/
expr set(const char* s);
/** creates a range expression.
@param min min character.
@param max max character.
@return an expression which parses a single character out of range.
*/
expr range(int min, int max);
/** creates an expression which increments the line counter
and resets the column counter when the given expression
is parsed successfully; used for newline characters.
@param e expression to wrap into a newline parser.
@return an expression that handles newlines.
*/
expr nl(const expr& e);
/** creates an expression which tests for the end of input.
@return an expression that handles the end of input.
*/
expr eof();
/** creates a not expression.
@param e expression.
@return the appropriate expression.
*/
expr not_(const expr& e);
/** creates an and expression.
@param e expression.
@return the appropriate expression.
*/
expr and_(const expr& e);
/** creates an expression that parses any character.
@return the appropriate expression.
*/
expr any();
/** parsing succeeds without consuming any input.
*/
expr true_();
/** parsing fails without consuming any input.
*/
expr false_();
/** parse with target expression and let user handle result.
*/
expr user(const expr& e, const user_handler& handler);
/** parses the given input.
The parse procedures of each rule parsed are executed
before this function returns, if parsing succeeds.
@param i input.
@param g root rule of grammar.
@param el list of errors.
@param d user data, passed to the parse procedures.
@return true on parsing success, false on failure.
*/
bool parse(input& i, rule& g, error_list& el, void* d, void* ud);
/** output the specific input range to the specific stream.
@param stream stream.
@param ir input range.
@return the stream.
*/
template <class T> T& operator<<(T& stream, const input_range& ir) {
for(input::const_iterator it = ir.m_begin.m_it;
it != ir.m_end.m_it;
++it) {
stream << (typename T::char_type)*it;
}
return stream;
}
} //namespace parserlib
|
#include <iostream>
using namespace std;
int main()
{
/*cin.tie(nullptr);
ios_base::sync_with_stdio(false);
double a, b;
cin >> a >> b;
a = powf(a, b);
cout << a << "\n";*/
return 0;
}
// solving in progress
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <pybind11/pybind11.h>
namespace py = pybind11;
void regclass_Parameter(py::module m);
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#include <vector>
#include <zisa/math/symmetric_choices.hpp>
#include <zisa/testing/testing_framework.hpp>
TEST_CASE("Symmetric choices", "[math]") {
std::vector<zisa::int_t> vi{3, 22, 1, 6};
auto choices = zisa::strict_symmetric_choices(vi);
auto it = choices.begin();
auto end_it = choices.end();
auto check = [&end_it, &it](zisa::int_t i, zisa::int_t j) {
auto [k, l] = *it;
REQUIRE(i == k);
REQUIRE(j == l);
REQUIRE(it != end_it);
++it;
};
check(3, 22);
check(3, 1);
check(3, 6);
check(22, 1);
check(22, 6);
check(1, 6);
REQUIRE(it == end_it);
}
TEST_CASE("Symmetric choices; empty", "[math][runme]") {
std::vector<zisa::int_t> vi{};
auto choices = zisa::strict_symmetric_choices(vi);
auto it = choices.begin();
auto end_it = choices.end();
REQUIRE(it == end_it);
}
|
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
//
#include <memory>
#include <vector>
#include <iostream>
#include "catch.hpp"
#include "herald/herald.h"
/**
* Implementation note: BLE Mac should ALWAYS be valid 6 bytes, even if data wrong
*/
TEST_CASE("ble-macaddress-basic", "[ble][macaddress][basic]") {
SECTION("ble-macaddress-basic") {
std::uint8_t data[] {0,1,2,3,4,5}; // mac address data
herald::ble::BLEMacAddress mac(data);
herald::datatype::Data original = (herald::datatype::Data)mac; // explicit conversion operator test
REQUIRE(6 == original.size());
REQUIRE(std::byte(0) == original.at(0));
REQUIRE(std::byte(1) == original.at(1));
REQUIRE(std::byte(2) == original.at(2));
REQUIRE(std::byte(3) == original.at(3));
REQUIRE(std::byte(4) == original.at(4));
REQUIRE(std::byte(5) == original.at(5));
}
}
TEST_CASE("ble-macaddress-ctor-copy", "[ble][macaddress][ctor][copy") {
SECTION("ble-macaddress-ctor-copy") {
std::uint8_t data[] {0,1,2,3,4,5}; // mac address data
herald::ble::BLEMacAddress mac(data);
herald::ble::BLEMacAddress maccopy(mac);
herald::datatype::Data original = (herald::datatype::Data)maccopy; // explicit conversion operator test
REQUIRE(6 == original.size());
REQUIRE(std::byte(0) == original.at(0));
REQUIRE(std::byte(1) == original.at(1));
REQUIRE(std::byte(2) == original.at(2));
REQUIRE(std::byte(3) == original.at(3));
REQUIRE(std::byte(4) == original.at(4));
REQUIRE(std::byte(5) == original.at(5));
REQUIRE(mac == maccopy);
herald::datatype::Data originalOrig = (herald::datatype::Data)mac;
REQUIRE(original == originalOrig);
}
}
TEST_CASE("ble-macaddress-empty", "[ble][macaddress][empty]") {
SECTION("ble-macaddress-empty") {
herald::ble::BLEMacAddress mac;
herald::datatype::Data original = (herald::datatype::Data)mac; // explicit conversion operator test
REQUIRE(6 == original.size());
REQUIRE(std::byte(0) == original.at(0));
REQUIRE(std::byte(0) == original.at(1));
REQUIRE(std::byte(0) == original.at(2));
REQUIRE(std::byte(0) == original.at(3));
REQUIRE(std::byte(0) == original.at(4));
REQUIRE(std::byte(0) == original.at(5));
}
}
TEST_CASE("ble-macaddress-emptydata", "[ble][macaddress][emptydata]") {
SECTION("ble-macaddress-emptydata") {
herald::ble::Data d;
herald::ble::BLEMacAddress mac(d);
herald::datatype::Data original = (herald::datatype::Data)mac; // explicit conversion operator test
REQUIRE(6 == original.size());
REQUIRE(std::byte(0) == original.at(0));
REQUIRE(std::byte(0) == original.at(1));
REQUIRE(std::byte(0) == original.at(2));
REQUIRE(std::byte(0) == original.at(3));
REQUIRE(std::byte(0) == original.at(4));
REQUIRE(std::byte(0) == original.at(5));
}
}
TEST_CASE("ble-macaddress-smalldata", "[ble][macaddress][smalldata]") {
SECTION("ble-macaddress-smalldata") {
std::uint8_t data[] {0,1,2,3}; // mac address data - too small! Use what data we can
herald::ble::Data d(data,4);
herald::ble::BLEMacAddress mac(d);
herald::datatype::Data original = (herald::datatype::Data)mac; // explicit conversion operator test
REQUIRE(6 == original.size());
REQUIRE(std::byte(0) == original.at(0));
REQUIRE(std::byte(1) == original.at(1));
REQUIRE(std::byte(2) == original.at(2));
REQUIRE(std::byte(3) == original.at(3));
REQUIRE(std::byte(0) == original.at(4)); // last two empty
REQUIRE(std::byte(0) == original.at(5)); // last two empty
}
}
TEST_CASE("ble-macaddress-largedata", "[ble][macaddress][largedata]") {
SECTION("ble-macaddress-largedata") {
std::uint8_t data[] {0,1,2,3,4,5,6,7,8,9,10,11}; // mac address data - too large!
herald::ble::Data d(data,12);
herald::ble::BLEMacAddress mac(d);
herald::datatype::Data original = (herald::datatype::Data)mac; // explicit conversion operator test
REQUIRE(6 == original.size());
REQUIRE(std::byte(0) == original.at(0));
REQUIRE(std::byte(1) == original.at(1));
REQUIRE(std::byte(2) == original.at(2));
REQUIRE(std::byte(3) == original.at(3));
REQUIRE(std::byte(4) == original.at(4));
REQUIRE(std::byte(5) == original.at(5));
}
}
TEST_CASE("ble-macaddress-tostring", "[ble][macaddress][tostring]") {
SECTION("ble-macaddress-tostring") {
std::uint8_t data[] {0,1,2,3,4,5}; // mac address data
herald::ble::Data d(data,6);
herald::ble::BLEMacAddress mac(d);
std::string description = (std::string)mac; // conversion operator
INFO("BLEMacAddress: String description: " << description);
REQUIRE(17 == description.size()); // 2 chars per 6 data elements, 5 : char separators
REQUIRE("05:04:03:02:01:00" == description); // little endian conversion
}
}
|
//威佐夫博奕
//wythoff_game.cpp
//A和B两人轮流从两堆物品中取出一些物品
//每次取至少1个物品,多则不限
//每次可以单独从其中一堆物品中取物品,也可以同时从两堆物品中取数量相同的物品
//最后一个将两堆物品取光的人获胜
//1)局势
//当A面临(0, 0)局势时,A已经输了,因为B已经把两堆物品取光,称(0, 0)是最终局势
//当A面临(1, 2)局势时,A也必然输了,A取后B必然能够一次把两堆物品取光
//当A面临(3, 5)局势时,A也必然输了,A取后B虽然存在无法一次就把两堆物品取光的情况
//比如A取后局势变为(3, 4),但B可以在两堆中同时取2个使局势变为(1, 2),A还是输了
//这样必然输的局势称为奇异局势(Cold Position),用(a(k), b(k))表示,k为局势下标非负整数
//最终局势(0, 0)也属于奇异局势
//其中a(k)与b(k)交换位置后仍然是等价的,为了方便设a(k) <= b(k)
//前几个奇异局势是:
//k 0 1 2 3 4 5 6 7 8 9 ...
//a 0 1 3 4 6 8 9 11 12 14 ...
//b 0 2 5 7 10 13 15 18 20 23 ...
//即(a(0), b(0)) = (0, 0),k = 0
//(a(1), b(1)) = (1, 2),k = 1
//(a(2), b(2)) = (3, 5),k = 2
//...
//
//2)局势的性质
//性质1:
//任何自然数都包含于且仅包含于一个奇异局势中
//且a(k) > a(k-1),b(k) > b(k-1),b(k) = a(k) + k
//性质2:
//任意操作都可以将奇异局势改变为非奇异局势(Hot Position)
//性质3:
//通过适当的方法可以将非奇异局势变为奇异局势
//
//3)计算奇异局势序列
//原始的计算方法是初始k = 0时a(0) = 0,b(0) = 0
//以后递归的计算k = 1,k = 2,k = 3...的情况
//对于k = i,a(i)取之前0到i-1中尚未使用的最小自然数作为a(i)的值,而b(i) = a(i) + i
//比如对于:
//k 0 1 2 3 4 5 6 7 8 9
//a 0 1 3 4 6 8 9 11 12 14
//b 0 2 5 7 10 13 15 18 20 23
//当k = 10时,a(10)取从0到9中尚未使用过的最小自然数16,b(10) = 16 + 10 = 26
//
//更快的方式是用黄金分割方法,由威佐夫(Wythoff)提出,该算法也由他的名字命名
//黄金分割Golden Ratio是x^2 = x + 1的正值解,设t为根号5,则黄金分割为(1+t)/2
//从黄金分割有:
//k 0 1 2 3 4 5 6
//k*golden_ratio 0 1.618 3.236 4.854 6.472 8.090 9.708
//a 0 1 3 4 6 8 9
//k*(golden_ratio+1) 0 2.618 5.236 7.854 10.472 13.090 15.708
//b 0 2 5 7 10 13 15
//则可以得到结论,对于i >= 0,a(i)取小于i*golden_ratio的最大整数
//其中i*golden_ratio一定是一个无理数,大于a(i)小于a(i)+1
//
//4)局势变换策略
//从上文可知令对手处于奇异局势(a(k), b(k))即可获胜
//因此获胜关键在于将非奇异局势转化为奇异局势
//非奇异局势(a, b)有5种情况:
//a = b 第1种情况
//a = a(k), b > b(k) 第2种情况
//a = a(k), b < b(k) 第3种情况
//第1种情况:
//将a和b两堆同时取完,令对方面临(0, 0)奇异局势
//第2种情况:
//从b中取b - b(k)数量的物品,使b = b(k),令对方面临(a(k), b(k))奇异局势
//第3种情况:
//i)若b > a,这时必然存在这样一个t = b - a,从a和b中同时取a - a(t)数量的物品
//因为有b(k) = a(k) + k,则有b - (a - a(t)) = b - a + a(t) = b - a + b(t) - t = b(t)
//同时取出a - a(t)物品后使a = a(t),b = b(t),令对方面临(a(t), b(t))奇异局势
//ii)若b < a,则不能b - a,因为本文问题中都是非负整数的计算
//则需求出b在奇异局势数组中的下标k'
//从a中取a - a(k')个物品,使a = a(k'),令对方面临(a(k'), b(k'))奇异局势
//
//网络上流行的中文文档中关于这里的情况划分通常是5种
//但其中第3种情况的讲解非常糟糕,因为网络文档中将局势中a和b的下标k搞混,容易令人误解
//经过总结本文将5种情况进行了筛选,经过测试是正确的
//
//本文引用了“Wythoff’s Game”,作者“Kimberly Hirschfeld-Cotton(Oshkosh, Nebraska)”
#include "general_head.h"
int get_a2k(int a);
int get_b2k(int b);
bool wythoff_game(int a, int b, int& get_a, int& get_b)
{//两堆物品的数量分别为a和b
//判断是否有胜算,若有胜算则返回从a和b中取的物品数量get_a和get_b
//若a = b,直接同时取完令对方面临(0, 0)奇异局势
if(a == b){
get_a = a;
get_b = b;
return(true);
}
//黄金分割1.618
double golden_ratio = (1 + pow((double)5, (double)0.5)) / 2;
//通过a求出其在奇异局势数组中a的对应下标k
int k = get_a2k(a);
//将k带回黄金分割法的公式求出a(k)
//比较k求出的a(k)与a是否相等来验证函数输入的a是否就是奇异函数数组中的a
//若a = a(k)则a就是a(k),否则这个a不是奇异局势数组中的a,而是颠倒顺序的b
//比如在奇异局势数组中:
//k 0 1 2 3 4 5 6 7 8 9
//a 0 1 3 4 6 8 9 11 12 14
//b 0 2 5 7 10 13 15 18 20 23
//若a是一个颠倒的b,比如a = 2时,通过上述计算出的k = 2
//再带回黄金分割法得到的ak = 3与原本的a = 2不相等
//若a = 5,计算出k = 4,带回黄金分割得到ak = 6与原本a = 5不相等
//而若a = 1,计算出k = 1,带回黄金分割得到ak = 1与原本的a = 1相等
int ak = (int)(k * golden_ratio);
if(ak != a)
//若求出的ak与原本的a不相等
//则将两堆物品a和b颠倒顺序,注意取物品的数量get_a和get_b位置也交换
return(wythoff_game(b, a, get_b, get_a));
//若求出的ak = a
//则说明该a就是奇异局势数组中的a,b就是奇异局势数组中的b,而不是颠倒情况
//计算b(k) = a(k) + k
int bk = a + k;
if(b == bk)
//a = a(k),b = b(k),则当前两堆物品已经满足a(k)和b(k)的奇异局势,直接认输
return(false);
else if(b > bk){
//b > b(k),从b中取b - b(k)个物品,使b = b(k)
get_a = 0;
get_b = b - bk;
return(true);
}
else{
//b < b(k)
if(b >= a){
//从a和b中同时取出a - a(t)个物品,使a = a(t),b = b(t)
int t = b - a;
int at = (int)(t * golden_ratio);
get_a = a - at;
get_b = a - at;
}
else{
//b < a
int k2 = get_b2k(b);
int ak2 = k2 * golden_ratio;
get_a = a - ak2;
get_b = 0;
}
return(true);
}
}
int get_a2k(int a)
{//通过a逆向求出k
//黄金分割1.618
double golden_ratio = (1 + pow((double)5, (double)0.5)) / 2;
//物品数量a可能是奇异局势数组中某个a(k),也可能不是
//但此处先假设该a就是奇异局势数组中下标为k处的a(k)
//通过a(k)为小于k*golden_ratio的最大整数来逆向计算a在奇异局势数组中的下标k
double p = a / golden_ratio;
int k = (int)p + 1;
return(k);
}
int get_b2k(int b)
{//通过b逆向求出k
double golden_ratio = (1 + pow((double)5, (double)0.5)) / 2;
//b(k)为小于k*(golden_ratio+1)的最大整数
double p = b / (golden_ratio + 1);
int k = (int)p + 1;
return(k);
}
|
/* $Id: feature_propagate.hpp 632623 2021-06-03 17:38:11Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Colleen Bollin, Igor Filippov
*/
#ifndef _EDIT_FEATURE_PROPAGATE__HPP_
#define _EDIT_FEATURE_PROPAGATE__HPP_
#include <corelib/ncbistd.hpp>
#include <corelib/ncbiobj.hpp>
#include <corelib/ncbi_message.hpp>
#include <objects/seqfeat/Seq_feat.hpp>
#include <objects/seqloc/Seq_loc.hpp>
#include <objects/general/Object_id.hpp>
#include <objects/seqloc/Seq_interval.hpp>
#include <objects/seqalign/Dense_seg.hpp>
#include <objmgr/seq_entry_handle.hpp>
#include <objmgr/bioseq_handle.hpp>
#include <objmgr/bioseq_ci.hpp>
#include <objmgr/scope.hpp>
#include <objmgr/util/sequence.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
BEGIN_SCOPE(edit)
class NCBI_XOBJEDIT_EXPORT CFeaturePropagator
{
public:
NCBI_DEPRECATED CFeaturePropagator(CBioseq_Handle src, CBioseq_Handle target, const CSeq_align& align,
bool stop_at_stop = true, bool cleanup_partials = true, bool merge_abutting = true,
CMessageListener_Basic* pMessageListener = 0,
CObject_id::TId* feat_id = nullptr);
CFeaturePropagator(CBioseq_Handle src, CBioseq_Handle target, const CSeq_align& align,
bool stop_at_stop = true, bool cleanup_partials = true, bool merge_abutting = true, bool expand_over_gaps = true,
CMessageListener_Basic* pMessageListener = 0,
CObject_id::TId* feat_id = nullptr);
~CFeaturePropagator() {}
CRef<CSeq_feat> Propagate(const objects::CSeq_feat& orig_feat);
vector<CRef<CSeq_feat> > PropagateAll();
vector<CRef<CSeq_feat> > PropagateAllReportFailures(
vector<CConstRef<CSeq_feat> >&);
CRef<CSeq_feat> ConstructProteinFeatureForPropagatedCodingRegion(const CSeq_feat& orig_cds, const CSeq_feat& new_cds);
/// Propagates a feature list from the source sequence
/// The propagated protein feature is stored right after the propagated cds
vector<CRef<CSeq_feat>> PropagateFeatureList(const vector<CConstRef<CSeq_feat>>& orig_feats);
typedef enum {
eFeaturePropagationProblem_None = 0,
eFeaturePropagationProblem_FeatureLocation,
eFeaturePropagationProblem_CodeBreakLocation,
eFeaturePropagationProblem_AnticodonLocation
} EGapIntervalType;
private:
// Prohibit copy constructor and assignment operator
CFeaturePropagator(const CFeaturePropagator& value);
CFeaturePropagator& operator=(const CFeaturePropagator& value);
void x_PropagateCds(CSeq_feat& feat, const CSeq_id& targetId, bool origIsPartialStart);
void x_CdsMapCodeBreaks(CSeq_feat& feat, const CSeq_id& targetId);
void x_CdsStopAtStopCodon(CSeq_feat& cds);
void x_CdsCleanupPartials(CSeq_feat& cds, bool origIsPartialStart);
void x_PropagatetRNA(CSeq_feat& feat, const CSeq_id& targetId);
CRef<CSeq_loc> x_MapLocation(const CSeq_loc& sourceLoc, const CSeq_id& targetId);
TSignedSeqPos SeqPosToAlignPos(TSignedSeqPos pos, CDense_seg::TDim row, bool left, bool &partial5, bool &partial3);
TSignedSeqPos AlignPosToSeqPos(TSignedSeqPos pos, CDense_seg::TDim row, bool left, bool &partial5, bool &partial3);
CDense_seg::TDim FindRow(const CSeq_align& align, CBioseq_Handle bsh);
CRef<CSeq_loc> CreateRowSeq_loc(const CSeq_align& align, CDense_seg::TDim row);
bool IsOrdered(const CSeq_loc &loc);
CRef<CSeq_loc> MakeOrdered(const CSeq_loc &loc);
CRef<CSeq_loc> x_TruncateToStopCodon(const CSeq_loc& loc, unsigned int truncLen);
CRef<CSeq_loc> x_ExtendToStopCodon(CSeq_feat& feat);
CBioseq_Handle m_Src;
CBioseq_Handle m_Target;
CConstRef<CSeq_align> m_Alignment;
CScope& m_Scope;
bool m_CdsStopAtStopCodon;
bool m_CdsCleanupPartials;
CMessageListener_Basic* m_MessageListener;
CObject_id::TId* m_MaxFeatId = nullptr;
map<CObject_id::TId, CObject_id::TId> m_FeatIdMap; // map old feat-id to propagated feat-id
bool m_MergeAbutting;
bool m_ExpandOverGaps;
class CSynonymMapper : public ISynonymMapper
{
public:
CSynonymMapper(CFeaturePropagator *e) : m_e(e) {}
virtual ~CSynonymMapper(void) {}
virtual CSeq_id_Handle GetBestSynonym(const CSeq_id& id) {return sequence::GetId(m_e->m_Scope.GetBioseqHandle(id), sequence::eGetId_Best);}
private:
CFeaturePropagator* m_e;
};
CSynonymMapper m_synonym_mapper;
};
END_SCOPE(edit)
END_SCOPE(objects)
END_NCBI_SCOPE
#endif
// _EDIT_FEATURE_PROPAGATE__HPP_
|
//
// BoundaryConditionsData.hpp
// Elasticity
//
// Created by Wim van Rees on 5/4/16.
// Copyright © 2016 Wim van Rees. All rights reserved.
//
#ifndef BoundaryConditionsData_hpp
#define BoundaryConditionsData_hpp
#include "common.hpp"
#include "TopologyData.hpp"
struct BoundaryConditionsData
{
Eigen::MatrixXb vertices_bc;
Eigen::VectorXb edges_bc;
Eigen::MatrixXd clampedEdgeNormals;
std::map<int, int> clampedEdgeNormalsIndices;
void init(const Eigen::MatrixXb & vertices_bc_in, const int nEdges)
{
vertices_bc = vertices_bc_in;
edges_bc.resize(nEdges);
for(int i=0;i<nEdges;++i)
edges_bc(i) = false;
}
void clear()
{
vertices_bc.resize(0,0);
edges_bc.resize(0);
clampedEdgeNormals.resize(0,0);
clampedEdgeNormalsIndices.clear();
}
int clampFixedEdges(const TopologyData & topology, const Eigen::Ref<const Eigen::MatrixXd> & vertices, std::function<Eigen::Vector3d(const Eigen::Vector3d)> midedge_normals)
{
const int nEdges = topology.getNumberOfEdges();
// count number of fixed edges
int cnt=0;
for(int i=0;i<nEdges;++i)
{
const int idx_v0 = topology.edge2vertices(i,0);
const int idx_v1 = topology.edge2vertices(i,1);
const bool fixed_v0 = (vertices_bc(idx_v0,0) and vertices_bc(idx_v0,1) and vertices_bc(idx_v0,2));
const bool fixed_v1 = (vertices_bc(idx_v1,0) and vertices_bc(idx_v1,1) and vertices_bc(idx_v1,2));
if(fixed_v0 and fixed_v1) cnt++;
}
// allocate memory
clampedEdgeNormals.resize(cnt,3);
clampedEdgeNormals.setZero();
// fill arrays
cnt=0;
for(int i=0;i<nEdges;++i)
{
const int idx_v0 = topology.edge2vertices(i,0);
const int idx_v1 = topology.edge2vertices(i,1);
const bool fixed_v0 = (vertices_bc(idx_v0,0) and vertices_bc(idx_v0,1) and vertices_bc(idx_v0,2));
const bool fixed_v1 = (vertices_bc(idx_v1,0) and vertices_bc(idx_v1,1) and vertices_bc(idx_v1,2));
if(fixed_v0 and fixed_v1)
{
clampedEdgeNormalsIndices.insert( std::pair<int,int>(i, cnt));
const Eigen::Vector3d pos_v0 = vertices.row(idx_v0);
const Eigen::Vector3d pos_v1 = vertices.row(idx_v1);
const Eigen::Vector3d pos_edge = 0.5*(pos_v0 + pos_v1);
const Eigen::Vector3d normal = midedge_normals(pos_edge);
clampedEdgeNormals(cnt,0) = normal(0);
clampedEdgeNormals(cnt,1) = normal(1);
clampedEdgeNormals(cnt,2) = normal(2);
edges_bc(i) = true;
cnt++;
}
else
edges_bc(i) = false;
}
return cnt;
}
int clampFixedEdgesDiscrete(const TopologyData & topology, const Eigen::Ref<const Eigen::MatrixXd> & midedge_normals)
{
const int nEdges = topology.getNumberOfEdges();
assert(midedge_normals.rows() == nEdges);
assert(midedge_normals.cols() == 3);
// count number of fixed edges
int cnt=0;
for(int i=0;i<nEdges;++i)
{
const int idx_v0 = topology.edge2vertices(i,0);
const int idx_v1 = topology.edge2vertices(i,1);
const bool fixed_v0 = (vertices_bc(idx_v0,0) and vertices_bc(idx_v0,1) and vertices_bc(idx_v0,2));
const bool fixed_v1 = (vertices_bc(idx_v1,0) and vertices_bc(idx_v1,1) and vertices_bc(idx_v1,2));
if(fixed_v0 and fixed_v1) cnt++;
}
// allocate memory
clampedEdgeNormals.resize(cnt,3);
clampedEdgeNormals.setZero();
// fill arrays
cnt=0;
for(int i=0;i<nEdges;++i)
{
const int idx_v0 = topology.edge2vertices(i,0);
const int idx_v1 = topology.edge2vertices(i,1);
const bool fixed_v0 = (vertices_bc(idx_v0,0) and vertices_bc(idx_v0,1) and vertices_bc(idx_v0,2));
const bool fixed_v1 = (vertices_bc(idx_v1,0) and vertices_bc(idx_v1,1) and vertices_bc(idx_v1,2));
if(fixed_v0 and fixed_v1)
{
clampedEdgeNormalsIndices.insert( std::pair<int,int>(i, cnt));
const Eigen::Vector3d normal = midedge_normals.row(i);
clampedEdgeNormals(cnt,0) = normal(0);
clampedEdgeNormals(cnt,1) = normal(1);
clampedEdgeNormals(cnt,2) = normal(2);
edges_bc(i) = true;
cnt++;
}
else
edges_bc(i) = false;
}
return cnt;
}
Eigen::Ref<Eigen::MatrixXb> getVertexBoundaryConditions()
{
return vertices_bc;
}
const Eigen::Ref<const Eigen::MatrixXb> getVertexBoundaryConditions() const
{
return vertices_bc;
}
const Eigen::Ref<const Eigen::VectorXb> getEdgeBoundaryConditions() const
{
return edges_bc;
}
const Eigen::Ref<const Eigen::MatrixXd> getClampedEdgeNormals() const
{
return clampedEdgeNormals;
}
const std::map<int, int> & getClampedEdgeNormalsIndices() const
{
return clampedEdgeNormalsIndices;
}
};
#endif /* BoundaryConditionsData_hpp */
|
//
// Created by Peter Bone on 15/06/2020.
//
#include <iostream>
#include "InputManager.h"
namespace Engine {
InputManager::InputManager() {
m_listener = nullptr;
m_sdlToInputManagerKeyMappings[SDLK_LEFT] = InputKey::Left;
m_sdlToInputManagerKeyMappings[SDLK_RIGHT] = InputKey::Right;
m_sdlToInputManagerKeyMappings[SDLK_UP] = InputKey::Up;
m_sdlToInputManagerKeyMappings[SDLK_DOWN] = InputKey::Down;
m_sdlToInputManagerKeyMappings[SDLK_SPACE] = InputKey::Space;
m_sdlToInputManagerKeyMappings[SDLK_a] = InputKey::A;
m_sdlToInputManagerKeyMappings[SDLK_s] = InputKey::S;
m_sdlToInputManagerKeyMappings[SDLK_d] = InputKey::D;
m_sdlToInputManagerKeyMappings[SDLK_f] = InputKey::F;
}
InputKey InputManager::MouseButtonFromIndex( int index ){
switch(index){
case 1:
return InputKey::MouseButtonLeft;
case 3:
return InputKey::MouseButtonRight;
default:
return InputKey::UNKNOWN;
}
};
void InputManager::processInput(const SDL_Event &event) {
InputEvent inputEvent{};
// Determine if we pressed or released a key
if( event.type == SDL_KEYDOWN ){
inputEvent.deviceType = InputDeviceType::Keyboard;
inputEvent.state = InputKeyState::Pressed;
} else if( event.type == SDL_KEYUP ){
inputEvent.deviceType = InputDeviceType::Keyboard;
inputEvent.state = InputKeyState::Released;
} else if( event.type == SDL_MOUSEBUTTONDOWN ){
inputEvent.deviceType = InputDeviceType::Mouse;
inputEvent.state = InputKeyState::Pressed;
inputEvent.key = MouseButtonFromIndex(event.button.button);
} else if( event.type == SDL_MOUSEBUTTONUP ){
inputEvent.deviceType = InputDeviceType::Mouse;
inputEvent.state = InputKeyState::Released;
inputEvent.key = MouseButtonFromIndex(event.button.button);
} else if( event.type == SDL_MOUSEMOTION ) {
inputEvent.deviceType = InputDeviceType::Mouse;
inputEvent.state = InputKeyState::Moved;
} else {
// Unsupported type
return;
}
if( inputEvent.deviceType == InputDeviceType::Keyboard ){
// Map the key from SDL to InputManager
if( m_sdlToInputManagerKeyMappings.count(event.key.keysym.sym) ){
inputEvent.key = m_sdlToInputManagerKeyMappings[event.key.keysym.sym];
} else {
// No SDL -> InputManager key mapping defined
return;
}
// Filter key-repeat
if( inputEvent.state == InputKeyState::Pressed && m_pressedKeys.count(inputEvent.key) ){
// Key was already pressed
return;
}
if( inputEvent.state == InputKeyState::Pressed ){
m_pressedKeys.insert(inputEvent.key);
} else {
m_pressedKeys.erase(inputEvent.key);
}
} else if (inputEvent.deviceType == InputDeviceType::Mouse){
inputEvent.position.x = event.motion.x;
inputEvent.position.y = event.motion.y;
m_lastMousePosition = inputEvent;
}
// Send the event to our listener
if( m_listener != nullptr )
{
m_listener->handleInput(inputEvent);
}
}
void InputManager::setListener(IInputListener * const listener)
{
m_listener = listener;
}
InputEvent InputManager::getLastMousePosition()
{
return m_lastMousePosition;
}
}
|
$NetBSD: patch-src_lepton_jpgcoder.cc,v 1.1 2016/08/26 17:20:54 joerg Exp $
--- src/lepton/jpgcoder.cc.orig 2016-08-26 14:02:20.988180370 +0000
+++ src/lepton/jpgcoder.cc
@@ -4615,7 +4615,7 @@ int decode_ac_prg_fs( abitreader* huffr,
// check eobrun
if ( (*eobrun) > 0 ) {
for ( bpos = from; bpos <= to; )
- block[ bpos ] = 0;
+ block[ bpos++ ] = 0;
(*eobrun)--;
return from;
}
|
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <libsocket/inetclientstream.hpp>
using namespace std;
void read_file(string filename, stringstream &buffer){
std::ifstream file(filename.c_str());
if ( file )
{
buffer << file.rdbuf();
file.close();
}
}
int main()
{
try {
libsocket::inet_stream sock("localhost", "9001", LIBSOCKET_IPv4);
sock << "C++ Boost";
} catch (...) {
// standalone usage
}
stringstream text;
read_file("./1.json", text);
boost::property_tree::ptree jobj;
boost::property_tree::read_json(text, jobj);
double x = 0, y = 0, z = 0;
int len = 0;
BOOST_FOREACH(boost::property_tree::ptree::value_type &coord, jobj.get_child("coordinates"))
{
len += 1;
x += coord.second.get<double>("x");
y += coord.second.get<double>("y");
z += coord.second.get<double>("z");
}
printf("%.8f\n", x / len);
printf("%.8f\n", y / len);
printf("%.8f\n", z / len);
return 0;
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoingui.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "modaloverlay.h"
#include "networkstyle.h"
#include "notificator.h"
#include "openuridialog.h"
#include "optionsdialog.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "rpcconsole.h"
#include "utilitydialog.h"
#ifdef ENABLE_WALLET
#include "walletframe.h"
#include "walletmodel.h"
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include "chainparams.h"
#include "init.h"
#include "ui_interface.h"
#include "util.h"
#include "masternode-sync.h"
#include "masternodelist.h"
#include <iostream>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
#include <QListWidget>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressDialog>
#include <QSettings>
#include <QShortcut>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QTimer>
#include <QToolBar>
#include <QVBoxLayout>
#if QT_VERSION < 0x050000
#include <QTextDocument>
#include <QUrl>
#else
#include <QUrlQuery>
#endif
const std::string BitcoinGUI::DEFAULT_UIPLATFORM =
#if defined(Q_OS_MAC)
"macosx"
#elif defined(Q_OS_WIN)
"windows"
#else
"other"
#endif
;
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
QMainWindow(parent),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
labelEncryptionIcon(0),
labelWalletHDStatusIcon(0),
labelConnectionsIcon(0),
labelBlocksIcon(0),
progressBarLabel(0),
progressBar(0),
progressDialog(0),
appMenuBar(0),
overviewAction(0),
historyAction(0),
masternodeAction(0),
quitAction(0),
sendCoinsAction(0),
sendCoinsMenuAction(0),
usedSendingAddressesAction(0),
usedReceivingAddressesAction(0),
signMessageAction(0),
verifyMessageAction(0),
aboutAction(0),
receiveCoinsAction(0),
receiveCoinsMenuAction(0),
optionsAction(0),
toggleHideAction(0),
encryptWalletAction(0),
backupWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
openRPCConsoleAction(0),
openAction(0),
showHelpMessageAction(0),
showPrivateSendHelpAction(0),
trayIcon(0),
trayIconMenu(0),
dockIconMenu(0),
notificator(0),
rpcConsole(0),
helpMessageDialog(0),
modalOverlay(0),
prevBlocks(0),
spinnerFrame(0),
platformStyle(platformStyle)
{
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
QString windowTitle = tr("Addmore Core") + " - ";
#ifdef ENABLE_WALLET
/* if compiled with wallet support, -disablewallet can still disable the wallet */
enableWallet = !GetBoolArg("-disablewallet", false);
#else
enableWallet = false;
#endif // ENABLE_WALLET
if(enableWallet)
{
windowTitle += tr("Wallet");
} else {
windowTitle += tr("Node");
}
QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", ""));
if(!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle;
windowTitle += " " + networkStyle->getTitleAddText();
#ifndef Q_OS_MAC
QApplication::setWindowIcon(networkStyle->getTrayAndWindowIcon());
setWindowIcon(networkStyle->getTrayAndWindowIcon());
#else
MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());
#endif
setWindowTitle(windowTitle);
#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
// This property is not implemented in Qt 5. Setting it has no effect.
// A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
setUnifiedTitleAndToolBarOnMac(true);
#endif
rpcConsole = new RPCConsole(platformStyle, 0);
helpMessageDialog = new HelpMessageDialog(this, HelpMessageDialog::cmdline);
#ifdef ENABLE_WALLET
if(enableWallet)
{
/** Create wallet frame*/
walletFrame = new WalletFrame(platformStyle, this);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
}
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon(networkStyle);
// Create status bar
statusBar();
// Disable size grip because it looks ugly and nobody needs it
statusBar()->setSizeGripEnabled(false);
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,8,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(10);
unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle);
labelEncryptionIcon = new QLabel();
labelWalletHDStatusIcon = new QLabel();
labelConnectionsIcon = new GUIUtil::ClickableLabel();
labelBlocksIcon = new GUIUtil::ClickableLabel();
if(enableWallet)
{
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelWalletHDStatusIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
}
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(true);
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(true);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
// Jump to peers tab by clicking on connections icon
connect(labelConnectionsIcon, SIGNAL(clicked(QPoint)), this, SLOT(showPeers()));
modalOverlay = new ModalOverlay(this->centralWidget());
#ifdef ENABLE_WALLET
if(enableWallet) {
connect(walletFrame, SIGNAL(requestedSyncWarningInfo()), this, SLOT(showModalOverlay()));
connect(labelBlocksIcon, SIGNAL(clicked(QPoint)), this, SLOT(showModalOverlay()));
connect(progressBar, SIGNAL(clicked(QPoint)), this, SLOT(showModalOverlay()));
}
#endif
}
BitcoinGUI::~BitcoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
GUIUtil::saveWindowGeometry("nWindow", this);
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
delete rpcConsole;
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
QString theme = GUIUtil::getThemeName();
overviewAction = new QAction(QIcon(":/icons/" + theme + "/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
#ifdef Q_OS_MAC
overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
#else
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
#endif
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/" + theme + "/send-white"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Addmore address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
#else
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
#endif
tabGroup->addAction(sendCoinsAction);
sendCoinsMenuAction = new QAction(QIcon(":/icons/" + theme + "/send-white"), sendCoinsAction->text(), this);
sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip());
sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip());
receiveCoinsAction = new QAction(QIcon(":/icons/" + theme + "/receive-white"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and addmore: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3));
#else
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
#endif
tabGroup->addAction(receiveCoinsAction);
receiveCoinsMenuAction = new QAction(QIcon(":/icons/" + theme + "/receive-white"), receiveCoinsAction->text(), this);
receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip());
receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip());
historyAction = new QAction(QIcon(":/icons/" + theme + "/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
#ifdef Q_OS_MAC
historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4));
#else
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
#endif
tabGroup->addAction(historyAction);
#ifdef ENABLE_WALLET
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction = new QAction(QIcon(":/icons/" + theme + "/masternode"), tr("&Masternodes"), this);
masternodeAction->setStatusTip(tr("Browse masternodes"));
masternodeAction->setToolTip(masternodeAction->statusTip());
masternodeAction->setCheckable(true);
#ifdef Q_OS_MAC
masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5));
#else
masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
#endif
tabGroup->addAction(masternodeAction);
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage()));
}
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
#endif // ENABLE_WALLET
quitAction = new QAction(QIcon(":/icons/" + theme + "/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/" + theme + "/about"), tr("&About Addmore Core"), this);
aboutAction->setStatusTip(tr("Show information about Addmore Core"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutAction->setEnabled(false);
aboutQtAction = new QAction(QIcon(":/icons/" + theme + "/about-qt"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/" + theme + "/configure"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Addmore Core"));
optionsAction->setMenuRole(QAction::PreferencesRole);
optionsAction->setEnabled(false);
toggleHideAction = new QAction(QIcon(":/icons/" + theme + "/about"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/" + theme + "/lock-closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/" + theme + "/backup"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/" + theme + "/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
unlockWalletAction = new QAction(QIcon(":/icons/" + theme + "/lock-open"), tr("&Unlock Wallet..."), this);
unlockWalletAction->setToolTip(tr("Unlock wallet"));
lockWalletAction = new QAction(QIcon(":/icons/" + theme + "/lock-closed"), tr("&Lock Wallet"), this);
signMessageAction = new QAction(QIcon(":/icons/" + theme + "/signature"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Addmore addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/" + theme + "/tick"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Addmore addresses"));
openInfoAction = new QAction(QIcon(":/icons/" + theme + "/information"), tr("&Information"), this);
openInfoAction->setStatusTip(tr("Show diagnostic information"));
openRPCConsoleAction = new QAction(QIcon(":/icons/" + theme + "/terminal"), tr("&Debug console"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging console"));
openGraphAction = new QAction(QIcon(":/icons/" + theme + "/network"), tr("&Network Monitor"), this);
openGraphAction->setStatusTip(tr("Show network monitor"));
openPeersAction = new QAction(QIcon(":/icons/" + theme + "/peers"), tr("&Peers list"), this);
openPeersAction->setStatusTip(tr("Show peers info"));
openRepairAction = new QAction(QIcon(":/icons/" + theme + "/wrench"), tr("Wallet &Repair"), this);
openRepairAction->setStatusTip(tr("Show wallet repair options"));
openConfEditorAction = new QAction(QIcon(":/icons/" + theme + "/configuration-wallet"), tr("Open Wallet &Configuration File"), this);
openConfEditorAction->setStatusTip(tr("Open configuration file"));
openMNConfEditorAction = new QAction(QIcon(":/icons/" + theme + "/configuration-masternode"), tr("Open &Masternode Configuration File"), this);
openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file"));
showBackupsAction = new QAction(QIcon(":/icons/" + theme + "/browse"), tr("Show Automatic &Backups"), this);
showBackupsAction->setStatusTip(tr("Show automatically created wallet backups"));
// initially disable the debug window menu items
openInfoAction->setEnabled(false);
openRPCConsoleAction->setEnabled(false);
openGraphAction->setEnabled(false);
openPeersAction->setEnabled(false);
openRepairAction->setEnabled(false);
usedSendingAddressesAction = new QAction(QIcon(":/icons/" + theme + "/address-book-send"), tr("&Sending addresses..."), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(QIcon(":/icons/" + theme + "/address-book-receive"), tr("&Receiving addresses..."), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
openAction = new QAction(QIcon(":/icons/" + theme + "/folder"), tr("Open &URI..."), this);
openAction->setStatusTip(tr("Open a addmore: URI or payment request"));
showHelpMessageAction = new QAction(QIcon(":/icons/" + theme + "/information-command-line"), tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the Addmore Core help message to get a list with possible Addmore Core command-line options"));
showPrivateSendHelpAction = new QAction(QIcon(":/icons/" + theme + "/information-privatesend"), tr("&PrivateSend information"), this);
showPrivateSendHelpAction->setMenuRole(QAction::NoRole);
showPrivateSendHelpAction->setStatusTip(tr("Show the PrivateSend basic information"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
connect(showPrivateSendHelpAction, SIGNAL(triggered()), this, SLOT(showPrivateSendHelpClicked()));
// Jump directly to tabs in RPC-console
connect(openInfoAction, SIGNAL(triggered()), this, SLOT(showInfo()));
connect(openRPCConsoleAction, SIGNAL(triggered()), this, SLOT(showConsole()));
connect(openGraphAction, SIGNAL(triggered()), this, SLOT(showGraph()));
connect(openPeersAction, SIGNAL(triggered()), this, SLOT(showPeers()));
connect(openRepairAction, SIGNAL(triggered()), this, SLOT(showRepair()));
// Open configs and backup folder from menu
connect(openConfEditorAction, SIGNAL(triggered()), this, SLOT(showConfEditor()));
connect(openMNConfEditorAction, SIGNAL(triggered()), this, SLOT(showMNConfEditor()));
connect(showBackupsAction, SIGNAL(triggered()), this, SLOT(showBackups()));
// Get restart command-line parameters and handle restart
connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList)));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
#ifdef ENABLE_WALLET
if(walletFrame)
{
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(unlockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(unlockWallet()));
connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
}
#endif // ENABLE_WALLET
new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I), this, SLOT(showInfo()));
new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), this, SLOT(showConsole()));
new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_G), this, SLOT(showGraph()));
new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_P), this, SLOT(showPeers()));
new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_R), this, SLOT(showRepair()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
if(walletFrame)
{
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(usedSendingAddressesAction);
file->addAction(usedReceivingAddressesAction);
file->addSeparator();
}
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
if(walletFrame)
{
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(unlockWalletAction);
settings->addAction(lockWalletAction);
settings->addSeparator();
}
settings->addAction(optionsAction);
if(walletFrame)
{
QMenu *tools = appMenuBar->addMenu(tr("&Tools"));
tools->addAction(openInfoAction);
tools->addAction(openRPCConsoleAction);
tools->addAction(openGraphAction);
tools->addAction(openPeersAction);
tools->addAction(openRepairAction);
tools->addSeparator();
tools->addAction(openConfEditorAction);
tools->addAction(openMNConfEditorAction);
tools->addAction(showBackupsAction);
}
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(showHelpMessageAction);
help->addAction(showPrivateSendHelpAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
#ifdef ENABLE_WALLET
if(walletFrame)
{
QToolBar *toolbar = new QToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool())
{
toolbar->addAction(masternodeAction);
}
toolbar->setMovable(false); // remove unused icon in upper left corner
overviewAction->setChecked(true);
/** Create additional container for toolbar and walletFrame and make it the central widget.
This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too.
*/
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(toolbar);
layout->addWidget(walletFrame);
layout->setSpacing(0);
layout->setContentsMargins(QMargins());
QWidget *containerWidget = new QWidget();
containerWidget->setLayout(layout);
setCentralWidget(containerWidget);
}
#endif // ENABLE_WALLET
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
if (trayIcon) {
// do so only if trayIcon is already set
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
createIconMenu(trayIconMenu);
#ifndef Q_OS_MAC
// Show main window on tray icon click
// Note: ignore this on Mac - this is not the way tray should work there
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is also used to provide menu functionality
// similar to one for tray icon
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
dockIconMenu = dockIconHandler->dockMenu();
createIconMenu(dockIconMenu);
#endif
}
// Keep up to date with client
updateNetworkState();
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(clientModel, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool)));
modalOverlay->setKnownBestHeight(clientModel->getHeaderTipHeight(), QDateTime::fromTime_t(clientModel->getHeaderTipTime()));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getLastBlockDate(), clientModel->getVerificationProgress(NULL), false);
connect(clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool)));
connect(clientModel, SIGNAL(additionalDataSyncProgressChanged(double)), this, SLOT(setAdditionalDataSyncProgress(double)));
// Receive and report messages from client model
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
// Show progress dialog
connect(clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
rpcConsole->setClientModel(clientModel);
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->setClientModel(clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
OptionsModel* optionsModel = clientModel->getOptionsModel();
if(optionsModel)
{
// be aware of the tray icon disable state change reported by the OptionsModel object.
connect(optionsModel,SIGNAL(hideTrayIconChanged(bool)),this,SLOT(setTrayIconVisible(bool)));
// initialize the disable state of the tray icon with the current value in the model.
setTrayIconVisible(optionsModel->getHideTrayIcon());
}
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if(trayIconMenu)
{
// Disable context menu on tray icon
trayIconMenu->clear();
}
// Propagate cleared model to child objects
rpcConsole->setClientModel(nullptr);
#ifdef ENABLE_WALLET
walletFrame->setClientModel(nullptr);
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(nullptr);
#ifdef Q_OS_MAC
if(dockIconMenu)
{
// Disable context menu on dock icon
dockIconMenu->clear();
}
#endif
}
}
#ifdef ENABLE_WALLET
bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
if(!walletFrame)
return false;
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
if(!walletFrame)
return false;
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
if(!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
sendCoinsMenuAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
receiveCoinsMenuAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool() && masternodeAction) {
masternodeAction->setEnabled(enabled);
}
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon(const NetworkStyle *networkStyle)
{
trayIcon = new QSystemTrayIcon(this);
QString toolTip = tr("Addmore Core client") + " " + networkStyle->getTitleAddText();
trayIcon->setToolTip(toolTip);
trayIcon->setIcon(networkStyle->getTrayAndWindowIcon());
trayIcon->hide();
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
}
void BitcoinGUI::createIconMenu(QMenu *pmenu)
{
// Configuration of the tray icon (or dock icon) icon menu
pmenu->addAction(toggleHideAction);
pmenu->addSeparator();
pmenu->addAction(sendCoinsMenuAction);
pmenu->addAction(receiveCoinsMenuAction);
pmenu->addSeparator();
pmenu->addAction(signMessageAction);
pmenu->addAction(verifyMessageAction);
pmenu->addSeparator();
pmenu->addAction(optionsAction);
pmenu->addAction(openInfoAction);
pmenu->addAction(openRPCConsoleAction);
pmenu->addAction(openGraphAction);
pmenu->addAction(openPeersAction);
pmenu->addAction(openRepairAction);
pmenu->addSeparator();
pmenu->addAction(openConfEditorAction);
pmenu->addAction(openMNConfEditorAction);
pmenu->addAction(showBackupsAction);
#ifndef Q_OS_MAC // This is built-in on Mac
pmenu->addSeparator();
pmenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
if(!clientModel)
return;
HelpMessageDialog dlg(this, HelpMessageDialog::about);
dlg.exec();
}
void BitcoinGUI::showDebugWindow()
{
rpcConsole->showNormal();
rpcConsole->show();
rpcConsole->raise();
rpcConsole->activateWindow();
}
void BitcoinGUI::showInfo()
{
rpcConsole->setTabFocus(RPCConsole::TAB_INFO);
showDebugWindow();
}
void BitcoinGUI::showConsole()
{
rpcConsole->setTabFocus(RPCConsole::TAB_CONSOLE);
showDebugWindow();
}
void BitcoinGUI::showGraph()
{
rpcConsole->setTabFocus(RPCConsole::TAB_GRAPH);
showDebugWindow();
}
void BitcoinGUI::showPeers()
{
rpcConsole->setTabFocus(RPCConsole::TAB_PEERS);
showDebugWindow();
}
void BitcoinGUI::showRepair()
{
rpcConsole->setTabFocus(RPCConsole::TAB_REPAIR);
showDebugWindow();
}
void BitcoinGUI::showConfEditor()
{
GUIUtil::openConfigfile();
}
void BitcoinGUI::showMNConfEditor()
{
GUIUtil::openMNConfigfile();
}
void BitcoinGUI::showBackups()
{
GUIUtil::showBackups();
}
void BitcoinGUI::showHelpMessageClicked()
{
helpMessageDialog->show();
}
void BitcoinGUI::showPrivateSendHelpClicked()
{
if(!clientModel)
return;
HelpMessageDialog dlg(this, HelpMessageDialog::pshelp);
dlg.exec();
}
#ifdef ENABLE_WALLET
void BitcoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if(dlg.exec())
{
Q_EMIT receivedURI(dlg.getURI());
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoMasternodePage()
{
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setChecked(true);
if (walletFrame) walletFrame->gotoMasternodePage();
}
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
#endif // ENABLE_WALLET
void BitcoinGUI::updateNetworkState()
{
int count = clientModel->getNumConnections();
QString icon;
QString theme = GUIUtil::getThemeName();
switch(count)
{
case 0: icon = ":/icons/" + theme + "/connect-1"; break;
case 1: case 2: case 3: icon = ":/icons/" + theme + "/connect-2"; break;
case 4: case 5: case 6: icon = ":/icons/" + theme + "/connect-3"; break;
case 7: case 8: case 9: icon = ":/icons/" + theme + "/connect-4"; break;
default: icon = ":/icons/" + theme + "/connect-5"; break;
}
if (clientModel->getNetworkActive()) {
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Addmore network", "", count));
} else {
labelConnectionsIcon->setToolTip(tr("Network activity disabled"));
icon = ":/icons/" + theme + "/network_disabled";
}
labelConnectionsIcon->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
}
void BitcoinGUI::setNumConnections(int count)
{
updateNetworkState();
}
void BitcoinGUI::setNetworkActive(bool networkActive)
{
updateNetworkState();
}
void BitcoinGUI::updateHeadersSyncProgressLabel()
{
int64_t headersTipTime = clientModel->getHeaderTipTime();
int headersTipHeight = clientModel->getHeaderTipHeight();
int estHeadersLeft = (GetTime() - headersTipTime) / Params().GetConsensus().nPowTargetSpacing;
if (estHeadersLeft > HEADER_HEIGHT_DELTA_SYNC)
progressBarLabel->setText(tr("Syncing Headers (%1%)...").arg(QString::number(100.0 / (headersTipHeight+estHeadersLeft)*headersTipHeight, 'f', 1)));
}
void BitcoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header)
{
if (modalOverlay)
{
if (header)
modalOverlay->setKnownBestHeight(count, blockDate);
else
modalOverlay->tipUpdate(count, blockDate, nVerificationProgress);
}
if (!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
if (header) {
updateHeadersSyncProgressLabel();
return;
}
progressBarLabel->setText(tr("Synchronizing with network..."));
updateHeadersSyncProgressLabel();
break;
case BLOCK_SOURCE_DISK:
if (header) {
progressBarLabel->setText(tr("Indexing blocks on disk..."));
} else {
progressBarLabel->setText(tr("Processing blocks on disk..."));
}
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
if (header) {
return;
}
progressBarLabel->setText(tr("Connecting to peers..."));
break;
}
QString tooltip;
QDateTime currentDate = QDateTime::currentDateTime();
qint64 secs = blockDate.secsTo(currentDate);
tooltip = tr("Processed %n block(s) of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
QString theme = GUIUtil::getThemeName();
#ifdef ENABLE_WALLET
if (walletFrame)
{
if(secs < 25*60) // 90*60 in bitcoin
{
modalOverlay->showHide(true, true);
// TODO instead of hiding it forever, we should add meaningful information about MN sync to the overlay
modalOverlay->hideForever();
}
else
{
modalOverlay->showHide();
}
}
#endif // ENABLE_WALLET
if(!masternodeSync.IsBlockchainSynced())
{
QString timeBehindText = GUIUtil::formatNiceTimeOffset(secs);
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(nVerificationProgress * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
if(count != prevBlocks)
{
labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString(
":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->showOutOfSyncWarning(true);
}
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::setAdditionalDataSyncProgress(double nSyncProgress)
{
if(!clientModel)
return;
// No additional data sync should be happening while blockchain is not synced, nothing to update
if(!masternodeSync.IsBlockchainSynced())
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
QString tooltip;
// Set icon state: spinning if catching up, tick otherwise
QString theme = GUIUtil::getThemeName();
QString strSyncStatus;
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
if(masternodeSync.IsSynced()) {
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
labelBlocksIcon->setPixmap(QIcon(":/icons/" + theme + "/tick-white").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
} else {
labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString(
":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
#ifdef ENABLE_WALLET
if(walletFrame)
walletFrame->showOutOfSyncWarning(false);
#endif // ENABLE_WALLET
progressBar->setFormat(tr("Synchronizing additional data: %p%"));
progressBar->setMaximum(1000000000);
progressBar->setValue(nSyncProgress * 1000000000.0 + 0.5);
}
strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str());
progressBarLabel->setText(strSyncStatus);
tooltip = strSyncStatus + QString("<br>") + tooltip;
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("Addmore Core"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
}
else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "Addmore Core - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(clientModel && clientModel->getOptionsModel())
{
if(!clientModel->getOptionsModel()->getMinimizeOnClose())
{
// close rpcConsole in case it was open to make some space for the shutdown window
rpcConsole->close();
QApplication::quit();
}
}
#endif
QMainWindow::closeEvent(event);
}
void BitcoinGUI::showEvent(QShowEvent *event)
{
// enable the debug window when the main window shows up
openInfoAction->setEnabled(true);
openRPCConsoleAction->setEnabled(true);
openGraphAction->setEnabled(true);
openPeersAction->setEnabled(true);
openRepairAction->setEnabled(true);
aboutAction->setEnabled(true);
optionsAction->setEnabled(true);
}
#ifdef ENABLE_WALLET
void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label)
{
// On new transaction, make an info balloon
QString msg = tr("Date: %1\n").arg(date) +
tr("Amount: %1\n").arg(BitcoinUnits::formatWithUnit(unit, amount, true)) +
tr("Type: %1\n").arg(type);
if (!label.isEmpty())
msg += tr("Label: %1\n").arg(label);
else if (!address.isEmpty())
msg += tr("Address: %1\n").arg(address);
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
msg, CClientUIInterface::MSG_INFORMATION);
}
#endif // ENABLE_WALLET
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
Q_FOREACH(const QUrl &uri, event->mimeData()->urls())
{
Q_EMIT receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
#ifdef ENABLE_WALLET
bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient))
{
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void BitcoinGUI::setHDStatus(int hdEnabled)
{
QString theme = GUIUtil::getThemeName();
labelWalletHDStatusIcon->setPixmap(platformStyle->SingleColorIcon(hdEnabled ? ":/icons/" + theme + "/hd-enabled" : ":/icons/" + theme + "/hd-disabled").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelWalletHDStatusIcon->setToolTip(hdEnabled ? tr("HD key generation is <b>enabled</b>") : tr("HD key generation is <b>disabled</b>"));
// eventually disable the QLabel to set its opacity to 50%
labelWalletHDStatusIcon->setEnabled(hdEnabled);
}
void BitcoinGUI::setEncryptionStatus(int status)
{
QString theme = GUIUtil::getThemeName();
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/" + theme + "/lock-open-white").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::UnlockedForMixingOnly:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/" + theme + "/lock-open-white").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for mixing only"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/" + theme + "/lock-closed-white").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
#endif // ENABLE_WALLET
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if(!clientModel)
return;
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested())
{
if(rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void BitcoinGUI::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0)
{
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
}
else if (nProgress == 100)
{
if (progressDialog)
{
progressDialog->close();
progressDialog->deleteLater();
}
}
else if (progressDialog)
progressDialog->setValue(nProgress);
}
void BitcoinGUI::setTrayIconVisible(bool fHideTrayIcon)
{
if (trayIcon)
{
trayIcon->setVisible(!fHideTrayIcon);
}
}
void BitcoinGUI::showModalOverlay()
{
if (modalOverlay && (progressBar->isVisible() || modalOverlay->isLayerVisible()))
modalOverlay->toggleVisibility();
}
static bool ThreadSafeMessageBox(BitcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
void BitcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
uiInterface.ThreadSafeQuestion.connect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));
}
void BitcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
uiInterface.ThreadSafeQuestion.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _3, _4));
}
void BitcoinGUI::toggleNetworkActive()
{
if (clientModel) {
clientModel->setNetworkActive(!clientModel->getNetworkActive());
}
}
/** Get restart command-line parameters and request restart */
void BitcoinGUI::handleRestart(QStringList args)
{
if (!ShutdownRequested())
Q_EMIT requestedRestart(args);
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) :
optionsModel(0),
menu(0)
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
QList<BitcoinUnits::Unit> units = BitcoinUnits::availableUnits();
int max_width = 0;
const QFontMetrics fm(font());
Q_FOREACH (const BitcoinUnits::Unit unit, units)
{
max_width = qMax(max_width, fm.width(BitcoinUnits::name(unit)));
}
setMinimumSize(max_width, 0);
setAlignment(Qt::AlignRight | Qt::AlignVCenter);
setStyleSheet(QString("QLabel { color : #fff; font-weight: bold; }"));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
{
onDisplayUnitsClicked(event->pos());
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu(this);
Q_FOREACH(BitcoinUnits::Unit u, BitcoinUnits::availableUnits())
{
QAction *menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
menu->addAction(menuAction);
}
connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*)));
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *optionsModel)
{
if (optionsModel)
{
this->optionsModel = optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int)));
// initialize the display units label with the current value in the model.
updateDisplayUnit(optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
setText(BitcoinUnits::name(newUnits));
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action)
{
optionsModel->setDisplayUnit(action->data());
}
}
|
/* Copyright (c) 2018-2020, Arm Limited and Contributors
* Copyright (c) 2020, Broadcom Inc.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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 "stats/stats.h"
#include "common/error.h"
#include "core/device.h"
#include "frame_time_stats_provider.h"
#include "hwcpipe_stats_provider.h"
#include "vulkan_stats_provider.h"
namespace vkb
{
Stats::Stats(RenderContext &render_context, size_t buffer_size) :
render_context(render_context),
buffer_size(buffer_size)
{
assert(buffer_size >= 2 && "Buffers size should be greater than 2");
}
Stats::~Stats()
{
if (stop_worker)
{
stop_worker->set_value();
}
if (worker_thread.joinable())
{
worker_thread.join();
}
}
void Stats::request_stats(const std::set<StatIndex> &wanted_stats,
CounterSamplingConfig config)
{
if (providers.size() != 0)
{
throw std::runtime_error("Stats must only be requested once");
}
requested_stats = wanted_stats;
sampling_config = config;
// Copy the requested stats, so they can be changed by the providers below
std::set<StatIndex> stats = requested_stats;
// Initialize our list of providers (in priority order)
// All supported stats will be removed from the given 'stats' set by the provider's constructor
// so subsequent providers only see requests for stats that aren't already supported.
providers.emplace_back(std::make_unique<FrameTimeStatsProvider>(stats));
providers.emplace_back(std::make_unique<HWCPipeStatsProvider>(stats));
providers.emplace_back(std::make_unique<VulkanStatsProvider>(stats, sampling_config, render_context));
// In continuous sampling mode we still need to update the frame times as if we are polling
// Store the frame time provider here so we can easily access it later.
frame_time_provider = providers[0].get();
for (const auto &stat : requested_stats)
{
counters[stat] = std::vector<float>(buffer_size, 0);
}
if (sampling_config.mode == CounterSamplingMode::Continuous)
{
// Start a thread for continuous sample capture
stop_worker = std::make_unique<std::promise<void>>();
worker_thread = std::thread([this] {
continuous_sampling_worker(stop_worker->get_future());
});
// Reduce smoothing for continuous sampling
alpha_smoothing = 0.6f;
}
}
void Stats::resize(const size_t width)
{
// The circular buffer size will be 1/16th of the width of the screen
// which means every sixteen pixels represent one graph value
size_t buffers_size = width >> 4;
for (auto &counter : counters)
{
counter.second.resize(buffers_size);
counter.second.shrink_to_fit();
}
}
bool Stats::is_available(const StatIndex index) const
{
for (const auto &p : providers)
if (p->is_available(index))
return true;
return false;
}
static void add_smoothed_value(std::vector<float> &values, float value, float alpha)
{
assert(values.size() >= 2 && "Buffers size should be greater than 2");
if (values.size() == values.capacity())
{
// Shift values to the left to make space at the end and update counters
std::rotate(values.begin(), values.begin() + 1, values.end());
}
// Use an exponential moving average to smooth values
values.back() = value * alpha + *(values.end() - 2) * (1.0f - alpha);
}
void Stats::update(float delta_time)
{
switch (sampling_config.mode)
{
case CounterSamplingMode::Polling:
{
StatsProvider::Counters sample;
for (auto &p : providers)
{
auto s = p->sample(delta_time);
sample.insert(s.begin(), s.end());
}
push_sample(sample);
break;
}
case CounterSamplingMode::Continuous:
{
// Check that we have no pending samples to be shown
if (pending_samples.size() == 0)
{
std::unique_lock<std::mutex> lock(continuous_sampling_mutex);
if (!should_add_to_continuous_samples)
{
// If we have no pending samples, we let the worker thread
// capture samples for the next frame
should_add_to_continuous_samples = true;
}
else
{
// The worker thread has captured a frame, so we stop it
// and read the samples
should_add_to_continuous_samples = false;
pending_samples = continuous_samples;
continuous_samples.clear();
}
}
if (pending_samples.size() == 0)
return;
// Ensure the number of pending samples is capped at a reasonable value
if (pending_samples.size() > 100)
pending_samples.resize(100);
// Compute the number of samples to show this frame
size_t sample_count = static_cast<size_t>(sampling_config.speed * delta_time) * pending_samples.size();
// Clamp the number of samples
sample_count = std::max<size_t>(1, std::min<size_t>(sample_count, pending_samples.size()));
// Get the frame time stats (not a continuous stat)
StatsProvider::Counters frame_time_sample = frame_time_provider->sample(delta_time);
// Push the samples to circular buffers
std::for_each(pending_samples.end() - sample_count, pending_samples.end(), [this, frame_time_sample](auto &s) {
// Write the correct frame time into the continuous stats
s.insert(frame_time_sample.begin(), frame_time_sample.end());
// Then push the sample to the counters list
this->push_sample(s);
});
pending_samples.erase(pending_samples.end() - sample_count, pending_samples.end());
break;
}
}
}
void Stats::continuous_sampling_worker(std::future<void> should_terminate)
{
worker_timer.tick();
for (auto &p : providers)
p->continuous_sample(0.0f);
while (should_terminate.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
{
auto delta_time = static_cast<float>(worker_timer.tick());
auto interval = std::chrono::duration_cast<std::chrono::duration<float>>(sampling_config.interval).count();
// Ensure we wait for the interval specified in config
if (delta_time < interval)
{
std::this_thread::sleep_for(std::chrono::duration<float>(interval - delta_time));
delta_time += static_cast<float>(worker_timer.tick());
}
// Sample counters
StatsProvider::Counters sample;
for (auto &p : providers)
{
StatsProvider::Counters s = p->continuous_sample(delta_time);
sample.insert(s.begin(), s.end());
}
// Add the new sample to the vector of continuous samples
{
std::unique_lock<std::mutex> lock(continuous_sampling_mutex);
continuous_samples.push_back(sample);
}
}
}
void Stats::push_sample(const StatsProvider::Counters &sample)
{
for (auto &c : counters)
{
StatIndex idx = c.first;
std::vector<float> &values = c.second;
// Find the counter matching this StatIndex in the Sample
const auto &smp = sample.find(idx);
if (smp == sample.end())
continue;
float measurement = static_cast<float>(smp->second.result);
add_smoothed_value(values, measurement, alpha_smoothing);
}
}
void Stats::begin_sampling(CommandBuffer &cb)
{
// Inform the providers
for (auto &p : providers)
p->begin_sampling(cb);
}
void Stats::end_sampling(CommandBuffer &cb)
{
// Inform the providers
for (auto &p : providers)
p->end_sampling(cb);
}
const StatGraphData &Stats::get_graph_data(StatIndex index) const
{
for (auto &p : providers)
{
if (p->is_available(index))
return p->get_graph_data(index);
}
return StatsProvider::default_graph_data(index);
}
StatGraphData::StatGraphData(const std::string &name,
const std::string &graph_label_format,
float scale_factor,
bool has_fixed_max,
float max_value) :
name(name),
format{graph_label_format},
scale_factor{scale_factor},
has_fixed_max{has_fixed_max},
max_value{max_value}
{
}
} // namespace vkb
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <assert.h>
#include <emmintrin.h>
#include <string.h>
#include <algorithm>
#include <random>
#include "fbpcf/mpc_framework/engine/util/util.h"
#include "fbpcf/mpc_framework/engine/tuple_generator/oblivious_transfer/ferret/DummyMultiPointCot.h"
namespace fbpcf::mpc_framework::engine::tuple_generator::oblivious_transfer::
ferret::insecure {
void DummyMultiPointCot::senderInit(
__m128i delta,
int64_t length,
int64_t weight) {
delta_ = delta;
length_ = length;
weight_ = weight;
role_ = util::Role::sender;
}
void DummyMultiPointCot::receiverInit(int64_t length, int64_t weight) {
length_ = length;
weight_ = weight;
role_ = util::Role::receiver;
}
std::vector<__m128i> DummyMultiPointCot::senderExtend(
std::vector<__m128i>&& /*baseCot*/) {
assert(role_ == util::Role::sender);
agent_->sendSingleT<__m128i>(delta_);
std::vector<__m128i> rst(length_);
for (int i = 0; i < length_; i++) {
rst[i] = prg_->getRandomM128i();
util::setLsbTo0(rst[i]);
}
agent_->sendT<__m128i>(rst);
return rst;
}
std::vector<__m128i> DummyMultiPointCot::receiverExtend(
std::vector<__m128i>&& /*baseCot*/) {
assert(role_ == util::Role::receiver);
delta_ = agent_->receiveSingleT<__m128i>();
auto rst = agent_->receiveT<__m128i>(length_);
auto positions = getRandomPositions();
for (int i = 0; i < weight_; i++) {
assert(rst.size() > positions[i]);
rst[positions[i]] = _mm_xor_si128(rst[positions[i]], delta_);
}
return rst;
}
std::vector<int64_t> DummyMultiPointCot::getRandomPositions() {
std::vector<int64_t> rst(length_);
for (int i = 0; i < length_; i++) {
rst[i] = i;
}
std::random_shuffle(rst.begin(), rst.end());
rst.erase(rst.begin() + weight_, rst.end());
return rst;
}
} // namespace
// fbpcf::mpc_framework::engine::tuple_generator::oblivious_transfer::ferret::insecure
|
#include "Pch.h"
#include "PostfxShader.h"
#include "DirectX.h"
#include "Engine.h"
#include "Render.h"
#include "RenderTarget.h"
#include "VertexDeclaration.h"
struct PsGlobals
{
Vec4 skill;
float power;
float time;
};
//=================================================================================================
PostfxShader::PostfxShader() : deviceContext(app::render->GetDeviceContext()), vertexShader(nullptr), pixelShaders(), layout(nullptr), psGlobals(nullptr),
sampler(nullptr), vb(nullptr)
{
}
//=================================================================================================
void PostfxShader::OnInit()
{
Render::ShaderParams params;
params.name = "postfx";
params.decl = VDI_TEX;
params.vertexShader = &vertexShader;
params.pixelShader = &pixelShaders[POSTFX_EMPTY];
params.layout = &layout;
params.vsEntry = "VsEmpty";
params.psEntry = "PsEmpty";
app::render->CreateShader(params);
params.vertexShader = nullptr;
params.pixelShader = &pixelShaders[POSTFX_MONOCHROME];
params.psEntry = "PsMonochrome";
app::render->CreateShader(params);
params.pixelShader = &pixelShaders[POSTFX_DREAM];
params.psEntry = "PsDream";
app::render->CreateShader(params);
params.pixelShader = &pixelShaders[POSTFX_BLUR_X];
params.psEntry = "PsBlurX";
app::render->CreateShader(params);
params.pixelShader = &pixelShaders[POSTFX_BLUR_Y];
params.psEntry = "PsBlurY";
app::render->CreateShader(params);
params.pixelShader = &pixelShaders[POSTFX_MASK];
params.psEntry = "PsMask";
app::render->CreateShader(params);
params.pixelShader = &pixelShaders[POSTFX_VIGNETTE];
params.psEntry = "PsVignette";
app::render->CreateShader(params);
psGlobals = app::render->CreateConstantBuffer(sizeof(PsGlobals), "PostfxPsGlobals");
sampler = app::render->CreateSampler(Render::TEX_ADR_CLAMP);
// create fullscreen vertex buffer
const VTex v[] = {
VTex(-1.f, 1.f, 0.f, 0, 0),
VTex(1.f, 1.f, 0.f, 1, 0),
VTex(1.f, -1.f, 0.f, 1, 1),
VTex(1.f, -1.f, 0.f, 1, 1),
VTex(-1.f, -1.f, 0.f, 0, 1),
VTex(-1.f, 1.f, 0.f, 0, 0)
};
D3D11_BUFFER_DESC desc = {};
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.ByteWidth = sizeof(VTex) * 6;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = v;
V(app::render->GetDevice()->CreateBuffer(&desc, &data, &vb));
}
//=================================================================================================
void PostfxShader::OnRelease()
{
SafeRelease(vertexShader);
SafeRelease(pixelShaders);
SafeRelease(layout);
SafeRelease(psGlobals);
SafeRelease(sampler);
SafeRelease(vb);
}
//=================================================================================================
void PostfxShader::SetTarget()
{
TEX texEmpty[] = { nullptr, nullptr };
deviceContext->PSSetShaderResources(0, 2, texEmpty);
prevTarget = app::render->GetRenderTarget();
activeTarget = GetTarget(true);
ID3D11RenderTargetView* renderTargetView = activeTarget->GetRenderTargetView();
deviceContext->OMSetRenderTargets(1, &renderTargetView, app::render->GetDepthStencilView());
app::render->SetViewport(activeTarget->GetSize());
}
//=================================================================================================
RenderTarget* PostfxShader::GetTarget(bool ms)
{
if(ms && app::render->IsMultisamplingEnabled())
{
if(targetsMS.empty())
return app::render->CreateRenderTarget(Int2::Zero, RenderTarget::F_NO_DEPTH | RenderTarget::F_NO_DRAW);
RenderTarget* target = targetsMS.back();
targetsMS.pop_back();
return target;
}
else
{
if(targets.empty())
return app::render->CreateRenderTarget(Int2::Zero, RenderTarget::F_NO_DEPTH | RenderTarget::F_NO_MS);
RenderTarget* target = targets.back();
targets.pop_back();
return target;
}
}
//=================================================================================================
void PostfxShader::FreeTarget(RenderTarget* target)
{
if(IsSet(target->GetFlags(), RenderTarget::F_NO_DRAW))
targetsMS.push_back(target);
else
targets.push_back(target);
}
//=================================================================================================
RenderTarget* PostfxShader::RequestActiveTarget()
{
assert(activeTarget);
RenderTarget* target = activeTarget;
activeTarget = nullptr;
return target;
}
//=================================================================================================
RenderTarget* PostfxShader::ResolveTarget(RenderTarget* target)
{
if(IsSet(target->GetFlags(), RenderTarget::F_NO_DRAW))
{
RenderTarget* targetNormal = GetTarget(false);
ID3D11Texture2D* texMS, *texNormal;
target->GetRenderTargetView()->GetResource(reinterpret_cast<ID3D11Resource**>(&texMS));
targetNormal->tex->GetResource(reinterpret_cast<ID3D11Resource**>(&texNormal));
deviceContext->ResolveSubresource(texNormal, 0, texMS, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
texMS->Release();
texNormal->Release();
if(activeTarget == target)
activeTarget = targetNormal;
FreeTarget(target);
return targetNormal;
}
else
return target;
}
//=================================================================================================
void PostfxShader::Prepare()
{
app::render->SetBlendState(Render::BLEND_NO);
app::render->SetDepthState(Render::DEPTH_NO);
app::render->SetRasterState(Render::RASTER_NORMAL);
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->PSSetConstantBuffers(0, 1, &psGlobals);
deviceContext->PSSetSamplers(0, 1, &sampler);
uint stride = sizeof(VTex), offset = 0;
deviceContext->IASetInputLayout(layout);
deviceContext->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
}
//=================================================================================================
RenderTarget* PostfxShader::Draw(const vector<PostEffect>& effects, RenderTarget* input, bool finalStage)
{
assert(!effects.empty());
// resolve MS if required
if(!input)
input = activeTarget;
input = ResolveTarget(input);
assert(input);
RenderTarget* currentInput = input;
RenderTarget* tmpTarget = nullptr;
RenderTarget* tmpSource = nullptr;
for(uint i = 0, count = effects.size(); i < count; ++i)
{
const PostEffect& effect = effects[i];
const bool isLast = (i + 1 == count);
// set pixel shader params
{
ResourceLock lock(psGlobals);
PsGlobals& psg = *lock.Get<PsGlobals>();
psg.power = effect.power;
psg.skill = effect.skill;
}
TEX tex[] = { nullptr, nullptr };
deviceContext->PSSetShaderResources(0, 2, tex);
if(isLast && finalStage)
{
if(tmpTarget)
{
FreeTarget(tmpTarget);
tmpTarget = nullptr;
}
app::render->SetRenderTarget(prevTarget);
}
else
{
tmpTarget = GetTarget(false);
ID3D11RenderTargetView* renderTargetView = tmpTarget->GetRenderTargetView();
deviceContext->OMSetRenderTargets(1, &renderTargetView, nullptr);
}
tex[0] = currentInput->tex;
tex[1] = effect.tex;
deviceContext->PSSetShader(pixelShaders[effect.id], nullptr, 0);
deviceContext->PSSetShaderResources(0, 2, tex);
deviceContext->Draw(6, 0);
if(tmpTarget)
{
if(tmpSource)
FreeTarget(tmpSource);
tmpSource = tmpTarget;
tmpTarget = nullptr;
currentInput = tmpSource;
}
}
if(tmpSource && finalStage)
{
FreeTarget(tmpSource);
tmpSource = nullptr;
}
if(activeTarget)
FreeTarget(activeTarget);
return tmpSource;
}
//=================================================================================================
void PostfxShader::Merge(RenderTarget* inputA, RenderTarget* inputB, RenderTarget* output)
{
assert(inputA && inputB);
ID3D11RenderTargetView* renderTargetView;
RenderTarget* tmpTarget = nullptr;
if(!output)
{
if(prevTarget)
{
tmpTarget = GetTarget(false);
renderTargetView = tmpTarget->GetRenderTargetView();
}
else
renderTargetView = app::render->GetRenderTargetView();
}
else
renderTargetView = output->GetRenderTargetView();
deviceContext->VSSetShader(vertexShader, nullptr, 0);
deviceContext->PSSetConstantBuffers(0, 1, &psGlobals);
deviceContext->PSSetSamplers(0, 1, &sampler);
uint stride = sizeof(VTex), offset = 0;
deviceContext->IASetInputLayout(layout);
deviceContext->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
TEX tex[] = { nullptr, nullptr };
deviceContext->PSSetShaderResources(0, 2, tex);
deviceContext->OMSetRenderTargets(1, &renderTargetView, nullptr);
deviceContext->PSSetShader(pixelShaders[POSTFX_EMPTY], nullptr, 0);
tex[0] = inputA->tex;
deviceContext->PSSetShaderResources(0, 2, tex);
deviceContext->Draw(6, 0);
app::render->SetBlendState(Render::BLEND_ADD_ONE2);
tex[0] = inputB->tex;
deviceContext->PSSetShaderResources(0, 2, tex);
deviceContext->Draw(6, 0);
app::render->SetBlendState(Render::BLEND_NO);
if(tmpTarget)
{
renderTargetView = prevTarget->GetRenderTargetView();
deviceContext->OMSetRenderTargets(1, &renderTargetView, prevTarget->GetDepthStencilView());
tex[0] = tmpTarget->tex;
deviceContext->PSSetShaderResources(0, 2, tex);
app::render->SetViewport(prevTarget->GetSize());
deviceContext->Draw(6, 0);
FreeTarget(tmpTarget);
}
else if(output)
activeTarget = output;
else
app::render->SetRenderTarget(nullptr);
}
|
#include "messageManager.h"
void messageManager::sendPrivateMessage(Client* clientFrom, Client* clientToSend, std::string message)
{
SYSTEMTIME time;
GetLocalTime(&time);
std::string mkdir = "mkdir messagesDumper\\" + clientFrom->getNickName();
std::string writeFile = "echo \"" + std::to_string(time.wHour) + ':' + std::to_string(time.wMinute) + " - to:" + clientToSend->getNickName() + " - " + message + "\" >> messagesDumper\\" + clientFrom->getNickName() + '\\' + std::to_string(time.wDay) + '-' + std::to_string(time.wMonth) + '-' + std::to_string(time.wYear);
if (fs::exists("messagesDumper\\" + clientFrom->getNickName()) == false)
std::system(mkdir.c_str());
std::system(writeFile.c_str());
std::vector<std::string> array = { "C_GETMESSAGE", clientFrom->getNickName(), message };
auto toSend = packetBuilder(array);
clientToSend->clientWrite(toSend);
}
void messageManager::sendGlobalMessage(Client* clientFrom, std::string message, std::map<std::string, Client*> clientsToSend)
{
SYSTEMTIME time;
GetLocalTime(&time);
std::string mkdir = "mkdir messagesDumper\\" + clientFrom->getNickName();
std::string writeFile = "echo \"" + std::to_string(time.wHour) + ':' + std::to_string(time.wMinute) + " - " + message + "\" >> messagesDumper\\" + clientFrom->getNickName() + '\\' + std::to_string(time.wDay) + '-' + std::to_string(time.wMonth) + '-' + std::to_string(time.wYear);
if (fs::exists("messagesDumper\\" + clientFrom->getNickName()) == false)
std::system(mkdir.c_str());
std::system(writeFile.c_str());
std::vector<std::string> array = { "C_GETMESSAGE", clientFrom->getNickName(), message };
auto toSend = packetBuilder(array);
for (auto it = clientsToSend.begin(); it != clientsToSend.end(); it++)
{
if (it->first != clientFrom->getNickName())
it->second->clientWrite(toSend);
}
}
|
// Copyright (c) 2017-2019 The QuantisNet Core developers
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sigcache.h"
#include "memusage.h"
#include "pubkey.h"
#include "random.h"
#include "uint256.h"
#include "util.h"
#include "cuckoocache.h"
#include "boost_workaround.hpp"
#include <boost/thread.hpp>
namespace {
/**
* We're hashing a nonce into the entries themselves, so we don't need extra
* blinding in the set hash computation.
*
* This may exhibit platform endian dependent behavior but because these are
* nonced hashes (random) and this state is only ever used locally it is safe.
* All that matters is local consistency.
*/
class SignatureCacheHasher
{
public:
template <uint8_t hash_select>
uint32_t operator()(const uint256& key) const
{
static_assert(hash_select <8, "SignatureCacheHasher only has 8 hashes available.");
uint32_t u;
std::memcpy(&u, key.begin()+4*hash_select, 4);
return u;
}
};
/**
* Valid signature cache, to avoid doing expensive ECDSA signature checking
* twice for every transaction (once when accepted into memory pool, and
* again when accepted into the block chain)
*/
class CSignatureCache
{
private:
//! Entries are SHA256(nonce || signature hash || public key || signature):
uint256 nonce;
typedef CuckooCache::cache<uint256, SignatureCacheHasher> map_type;
map_type setValid;
boost::shared_mutex cs_sigcache;
public:
CSignatureCache()
{
GetRandBytes(nonce.begin(), 32);
}
void
ComputeEntry(uint256& entry, const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubkey)
{
CSHA256().Write(nonce.begin(), 32).Write(hash.begin(), 32).Write(&pubkey[0], pubkey.size()).Write(&vchSig[0], vchSig.size()).Finalize(entry.begin());
}
bool
Get(const uint256& entry, const bool erase)
{
boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
return setValid.contains(entry, erase);
}
void Set(uint256& entry)
{
boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
setValid.insert(entry);
}
uint32_t setup_bytes(size_t n)
{
return setValid.setup_bytes(n);
}
};
/* In previous versions of this code, signatureCache was a local static variable
* in CachingTransactionSignatureChecker::VerifySignature. We initialize
* signatureCache outside of VerifySignature to avoid the atomic operation per
* call overhead associated with local static variables even though
* signatureCache could be made local to VerifySignature.
*/
static CSignatureCache signatureCache;
}
// To be called once in AppInit2/TestingSetup to initialize the signatureCache
void InitSignatureCache()
{
// nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
// setup_bytes creates the minimum possible cache (2 elements).
size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
size_t nElems = signatureCache.setup_bytes(nMaxCacheSize);
LogPrintf("Using %zu MiB out of %zu requested for signature cache, able to store %zu elements\n",
(nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems);
}
bool CachingTransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
{
uint256 entry;
signatureCache.ComputeEntry(entry, sighash, vchSig, pubkey);
if (signatureCache.Get(entry, !store))
return true;
if (!TransactionSignatureChecker::VerifySignature(vchSig, pubkey, sighash))
return false;
if (store)
signatureCache.Set(entry);
return true;
}
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* ArrayVariant.cc (C) 2000-2006 */
/* */
/* Type de base polymorphe pour les tableaux mono-dim (dimension 1). */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/utils/ArcanePrecomp.h"
#include "arcane/utils/Array.h"
#include "arcane/utils/String.h"
#include "arcane/utils/Real2.h"
#include "arcane/utils/Real3.h"
#include "arcane/utils/Real2x2.h"
#include "arcane/utils/Real3x3.h"
#include "arcane/datatype/ArrayVariant.h"
#include "arcane/datatype/BadVariantTypeException.h"
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_BEGIN_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(eType type,Integer asize)
: VariantBase(1, type)
, m_allocated_array(0)
{
switch(type){
case TReal:
{
RealArray* v = new RealUniqueArray(asize);
m_allocated_array = v;
m_real_value = *v;
}
break;
case TInt64:
{
Int64Array* v = new Int64UniqueArray(asize);
m_allocated_array = v;
m_int64_value = *v;
}
break;
case TInt32:
{
Int32Array* v = new Int32UniqueArray(asize);
m_allocated_array = v;
m_int32_value = *v;
}
break;
case TBool:
{
BoolArray* v = new BoolUniqueArray(asize);
m_allocated_array = v;
m_bool_value = *v;
}
break;
case TString:
{
StringArray* v = new StringUniqueArray(asize);
m_allocated_array = v;
m_string_value = *v;
}
break;
case TReal2:
{
Real2Array* v = new Real2UniqueArray(asize);
m_allocated_array = v;
m_real2_value = *v;
}
break;
case TReal3:
{
Real3Array* v = new Real3UniqueArray(asize);
m_allocated_array = v;
m_real3_value = *v;
}
break;
case TReal2x2:
{
Real2x2Array* v = new Real2x2UniqueArray(asize);
m_allocated_array = v;
m_real2x2_value = *v;
}
break;
case TReal3x3:
{
Real3x3Array* v = new Real3x3UniqueArray(asize);
m_allocated_array = v;
m_real3x3_value = *v;
}
break;
default:
throw BadVariantTypeException("ArrayVariant::ArrayVariant(eType,Integer)",type);
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Real> data)
: VariantBase(1,TReal)
, m_real_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Real2> data)
: VariantBase(1,TReal2)
, m_real2_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Real3> data)
: VariantBase(1, TReal3)
, m_real3_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Real2x2> data)
: VariantBase(1,TReal2x2)
, m_real2x2_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Real3x3> data)
: VariantBase(1,TReal3x3)
, m_real3x3_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Int32> data)
: VariantBase(1,TInt32)
, m_int32_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<Int64> data)
: VariantBase(1,TInt64)
, m_int64_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<bool> data)
: VariantBase(1,TBool)
, m_bool_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
ArrayVariant(ArrayView<String> data)
: VariantBase(1,TString)
, m_string_value(data)
, m_allocated_array(0)
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ArrayVariant::
~ArrayVariant()
{
_destroy();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ArrayVariant::
_destroy()
{
if (!m_allocated_array)
return;
switch(m_type){
case TReal: delete reinterpret_cast<RealArray*>(m_allocated_array); break;
case TReal2: delete reinterpret_cast<Real2Array*>(m_allocated_array); break;
case TReal3: delete reinterpret_cast<Real3Array*>(m_allocated_array); break;
case TReal2x2: delete reinterpret_cast<Real2x2Array*>(m_allocated_array); break;
case TReal3x3: delete reinterpret_cast<Real3x3Array*>(m_allocated_array); break;
case TInt64: delete reinterpret_cast<Int64Array*>(m_allocated_array); break;
case TInt32: delete reinterpret_cast<Int32Array*>(m_allocated_array); break;
case TBool: delete reinterpret_cast<BoolArray*>(m_allocated_array); break;
case TString: delete reinterpret_cast<StringArray*>(m_allocated_array); break;
default:
break;
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
Integer ArrayVariant::
size() const
{
switch(m_type){
case TReal:
return m_real_value.size();
case TReal2:
return m_real2_value.size();
case TReal3:
return m_real3_value.size();
case TReal2x2:
return m_real2x2_value.size();
case TReal3x3:
return m_real3x3_value.size();
case TBool:
return m_bool_value.size();
case TString:
return m_string_value.size();
case TInt32:
return m_int32_value.size();
case TInt64:
return m_int64_value.size();
default:
break;
}
return 0;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
extern "C++" ARCANE_DATATYPE_EXPORT std::ostream&
operator<<(std::ostream& s, const ArrayVariant& x)
{
s << "ArrayVariant [t="
<< x.typeName();
s << ", adr=";
Integer size = 0;
switch (x.type())
{
case VariantBase::TReal:
s << x.asReal().data();
s << "], v=[ ";
size = x.asReal().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asReal()[i] << " ";
break;
case VariantBase::TReal2:
s << x.asReal2().data();
s << "], v=[ ";
size = x.asReal2().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asReal2()[i] << " ";
break;
case VariantBase::TReal3:
s << x.asReal3().data();
s << "], v=[ ";
size = x.asReal3().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asReal3()[i] << " ";
break;
case VariantBase::TReal2x2:
s << x.asReal2().data();
s << "], v=[ ";
size = x.asReal2().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asReal2x2()[i] << " ";
break;
case VariantBase::TReal3x3:
s << x.asReal3x3().data();
s << "], v=[ ";
size = x.asReal3x3().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asReal3x3()[i] << " ";
break;
case VariantBase::TInt64:
s << x.asInt64().data();
s << "], v=[ ";
size = x.asInt64().size();
for(Integer i=0 ; i<size ; ++i)
s << x.asInt64()[i] << " ";
break;
case VariantBase::TInt32:
s << x.asInteger().data();
s << "], v=[ ";
size = x.asInteger().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asInteger()[i] << " ";
break;
case VariantBase::TBool:
s << x.asBool().data();
s << "], v=[ ";
size = x.asBool().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asBool()[i] << " ";
break;
case VariantBase::TString:
s << x.asString().data();
s << "], v=[ ";
size = x.asString().size();
for (Integer i=0 ; i<size ; ++i)
s << x.asString()[i] << " ";
break;
default:
break;
}
s << "]";
return s;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
IntegerArrayView ArrayVariant::
asInteger()
{
#ifdef ARCANE_64BIT
return m_int64_value;
#else
return m_int32_value;
#endif
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
IntegerConstArrayView ArrayVariant::
asInteger() const
{
#ifdef ARCANE_64BIT
return m_int64_value;
#else
return m_int32_value;
#endif
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ARCANE_END_NAMESPACE
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
|
/*
problem:
idea:
这道题有个冷却期,卖完不能立即买(卖完的后一条不能买)
这就导致和前面买卖股票的解法不同,寻找局部最小和局部最大的pair
也是参考了别人的解法,有的解法确实不对,就在那儿抄来抄去没什么意思
想了一阵儿才明白到底是什么意思,肯定要用动态规划啦
开辟两个数组,一个叫作 buy[i],另一个是 sell[i]
关键这两个数组代表什么意思,
buy[i]:第i天买股票,从第0天到第i天能赚到的最大收益
sell[i]:第i天卖股票,从第0天到第i天能赚到的最大收益
*/
class Solution {
public:
// solution one
int maxProfit_solu1(vector<int>& prices) {
if(prices.size() < 2)
return 0;
int buy[prices.size()] ={0};
int sell[prices.size()] = {0};
// 这个题思想精妙的一个地方在于,上来第0天就买股票,那我的最大收益就是负的,因为这时候掏了钱,没有收入,很自然的事情
buy[0] = -prices[0];
// buy[1]的取值,意思是第1天买了,能赚取的最大收益;第1天之前是第0天,只能买,不能卖,因为没有股票卖不了东西,所以只能和buy[0]比较取最大值
buy[1] = max(buy[0], -prices[1]);
// 第0天没东西可卖,卖货赚取的最大收益为0
sell[1] = max(0, buy[0] + prices[1]);
for(int i=2; i<prices.size(); i++){
buy[i] = max(buy[i-1], sell[i-2] - prices[i]); // 截止到sell[i-2],收益>=0,第i天要买入,这部分是支出的prices[i],所以要用 “减法”
sell[i] = max(sell[i-1], buy[i-1] + prices[i]); // 第i天要卖出,在原来的基础上,收入prices[i],所以要用 “加法”
// 总之啊,这道题动态规划迭代的时候,思路很清楚,买就要出钱,就要做减法;卖就要往回拿钱,就要做加法
}
return sell[prices.size()-1];
}
// solution two,优化 solution one,将空间复杂度 降到 O(1),很显然 solution one 里头迭代的数组可以用两个变量表示
int maxProfit(vector<int>& prices) {
if(prices.size() < 2)
return 0;
int preBuy = INT_MIN, curBuy = INT_MIN;
int preSell = 0, curSell = 0;
for(int i=0; i<prices.size(); i++){
preBuy = curBuy;
curBuy = max(preBuy, preSell - prices[i]);
preSell = curSell;
curSell = max(preSell, preBuy + prices[i]);
}
return curSell;
}
};
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/usd/usdSkel/bindingAPI.h"
#include "pxr/usd/usd/schemaRegistry.h"
#include "pxr/usd/usd/typed.h"
#include "pxr/usd/usd/tokens.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/assetPath.h"
PXR_NAMESPACE_OPEN_SCOPE
// Register the schema with the TfType system.
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<UsdSkelBindingAPI,
TfType::Bases< UsdAPISchemaBase > >();
}
TF_DEFINE_PRIVATE_TOKENS(
_schemaTokens,
(SkelBindingAPI)
);
/* virtual */
UsdSkelBindingAPI::~UsdSkelBindingAPI()
{
}
/* static */
UsdSkelBindingAPI
UsdSkelBindingAPI::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return UsdSkelBindingAPI();
}
return UsdSkelBindingAPI(stage->GetPrimAtPath(path));
}
/* virtual */
UsdSchemaKind UsdSkelBindingAPI::_GetSchemaKind() const {
return UsdSkelBindingAPI::schemaKind;
}
/* virtual */
UsdSchemaKind UsdSkelBindingAPI::_GetSchemaType() const {
return UsdSkelBindingAPI::schemaType;
}
/* static */
UsdSkelBindingAPI
UsdSkelBindingAPI::Apply(const UsdPrim &prim)
{
if (prim.ApplyAPI<UsdSkelBindingAPI>()) {
return UsdSkelBindingAPI(prim);
}
return UsdSkelBindingAPI();
}
/* static */
const TfType &
UsdSkelBindingAPI::_GetStaticTfType()
{
static TfType tfType = TfType::Find<UsdSkelBindingAPI>();
return tfType;
}
/* static */
bool
UsdSkelBindingAPI::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
UsdSkelBindingAPI::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
UsdSkelBindingAPI::GetGeomBindTransformAttr() const
{
return GetPrim().GetAttribute(UsdSkelTokens->primvarsSkelGeomBindTransform);
}
UsdAttribute
UsdSkelBindingAPI::CreateGeomBindTransformAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(UsdSkelTokens->primvarsSkelGeomBindTransform,
SdfValueTypeNames->Matrix4d,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
UsdSkelBindingAPI::GetJointsAttr() const
{
return GetPrim().GetAttribute(UsdSkelTokens->skelJoints);
}
UsdAttribute
UsdSkelBindingAPI::CreateJointsAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(UsdSkelTokens->skelJoints,
SdfValueTypeNames->TokenArray,
/* custom = */ false,
SdfVariabilityUniform,
defaultValue,
writeSparsely);
}
UsdAttribute
UsdSkelBindingAPI::GetJointIndicesAttr() const
{
return GetPrim().GetAttribute(UsdSkelTokens->primvarsSkelJointIndices);
}
UsdAttribute
UsdSkelBindingAPI::CreateJointIndicesAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(UsdSkelTokens->primvarsSkelJointIndices,
SdfValueTypeNames->IntArray,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
UsdSkelBindingAPI::GetJointWeightsAttr() const
{
return GetPrim().GetAttribute(UsdSkelTokens->primvarsSkelJointWeights);
}
UsdAttribute
UsdSkelBindingAPI::CreateJointWeightsAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(UsdSkelTokens->primvarsSkelJointWeights,
SdfValueTypeNames->FloatArray,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
UsdSkelBindingAPI::GetBlendShapesAttr() const
{
return GetPrim().GetAttribute(UsdSkelTokens->skelBlendShapes);
}
UsdAttribute
UsdSkelBindingAPI::CreateBlendShapesAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(UsdSkelTokens->skelBlendShapes,
SdfValueTypeNames->TokenArray,
/* custom = */ false,
SdfVariabilityUniform,
defaultValue,
writeSparsely);
}
UsdRelationship
UsdSkelBindingAPI::GetAnimationSourceRel() const
{
return GetPrim().GetRelationship(UsdSkelTokens->skelAnimationSource);
}
UsdRelationship
UsdSkelBindingAPI::CreateAnimationSourceRel() const
{
return GetPrim().CreateRelationship(UsdSkelTokens->skelAnimationSource,
/* custom = */ false);
}
UsdRelationship
UsdSkelBindingAPI::GetSkeletonRel() const
{
return GetPrim().GetRelationship(UsdSkelTokens->skelSkeleton);
}
UsdRelationship
UsdSkelBindingAPI::CreateSkeletonRel() const
{
return GetPrim().CreateRelationship(UsdSkelTokens->skelSkeleton,
/* custom = */ false);
}
UsdRelationship
UsdSkelBindingAPI::GetBlendShapeTargetsRel() const
{
return GetPrim().GetRelationship(UsdSkelTokens->skelBlendShapeTargets);
}
UsdRelationship
UsdSkelBindingAPI::CreateBlendShapeTargetsRel() const
{
return GetPrim().CreateRelationship(UsdSkelTokens->skelBlendShapeTargets,
/* custom = */ false);
}
namespace {
static inline TfTokenVector
_ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right)
{
TfTokenVector result;
result.reserve(left.size() + right.size());
result.insert(result.end(), left.begin(), left.end());
result.insert(result.end(), right.begin(), right.end());
return result;
}
}
/*static*/
const TfTokenVector&
UsdSkelBindingAPI::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
UsdSkelTokens->primvarsSkelGeomBindTransform,
UsdSkelTokens->skelJoints,
UsdSkelTokens->primvarsSkelJointIndices,
UsdSkelTokens->primvarsSkelJointWeights,
UsdSkelTokens->skelBlendShapes,
};
static TfTokenVector allNames =
_ConcatenateAttributeNames(
UsdAPISchemaBase::GetSchemaAttributeNames(true),
localNames);
if (includeInherited)
return allNames;
else
return localNames;
}
PXR_NAMESPACE_CLOSE_SCOPE
// ===================================================================== //
// Feel free to add custom code below this line. It will be preserved by
// the code generator.
//
// Just remember to wrap code in the appropriate delimiters:
// 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'.
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
#include "pxr/usd/usdGeom/boundable.h"
#include "pxr/usd/usdGeom/imageable.h"
#include "pxr/usd/usdGeom/tokens.h"
#include "pxr/usd/usdSkel/skeleton.h"
#include "pxr/usd/usdSkel/utils.h"
PXR_NAMESPACE_OPEN_SCOPE
UsdGeomPrimvar
UsdSkelBindingAPI::GetJointIndicesPrimvar() const
{
return UsdGeomPrimvar(GetJointIndicesAttr());
}
UsdGeomPrimvar
UsdSkelBindingAPI::CreateJointIndicesPrimvar(bool constant,
int elementSize) const
{
return UsdGeomImageable(GetPrim()).CreatePrimvar(
UsdSkelTokens->primvarsSkelJointIndices,
SdfValueTypeNames->IntArray,
constant ? UsdGeomTokens->constant : UsdGeomTokens->vertex,
elementSize);
}
UsdGeomPrimvar
UsdSkelBindingAPI::GetJointWeightsPrimvar() const
{
return UsdGeomPrimvar(GetJointWeightsAttr());
}
UsdGeomPrimvar
UsdSkelBindingAPI::CreateJointWeightsPrimvar(bool constant,
int elementSize) const
{
return UsdGeomImageable(GetPrim()).CreatePrimvar(
UsdSkelTokens->primvarsSkelJointWeights,
SdfValueTypeNames->FloatArray,
constant ? UsdGeomTokens->constant : UsdGeomTokens->vertex,
elementSize);
}
bool
UsdSkelBindingAPI::SetRigidJointInfluence(int jointIndex, float weight) const
{
UsdGeomPrimvar jointIndicesPv =
CreateJointIndicesPrimvar(/*constant*/ true, /*elementSize*/ 1);
UsdGeomPrimvar jointWeightsPv =
CreateJointWeightsPrimvar(/*constant*/ true, /*elementSize*/ 1);
if (jointIndex < 0) {
TF_WARN("Invalid jointIndex '%d'", jointIndex);
return false;
}
return jointIndicesPv.Set(VtIntArray(1, jointIndex)) &&
jointWeightsPv.Set(VtFloatArray(1, weight));
}
namespace {
bool
_HasInactiveAncestor(const UsdStagePtr& stage, const SdfPath& path)
{
if (path.IsAbsolutePath() && path.IsPrimPath()) {
for (SdfPath p = path.GetParentPath();
p != SdfPath::AbsoluteRootPath(); p = p.GetParentPath()) {
if (UsdPrim prim = stage->GetPrimAtPath(p)) {
return !prim.IsActive();
}
}
}
return false;
}
/// Return the a resolved prim for a target in \p targets.
UsdPrim
_GetFirstTargetPrimForRel(const UsdRelationship& rel,
const SdfPathVector& targets)
{
if (targets.size() > 0) {
if (targets.size() > 1) {
TF_WARN("%s -- relationship has more than one target. "
"Only the first will be used.",
rel.GetPath().GetText());
}
const SdfPath& target = targets.front();
if (UsdPrim prim = rel.GetStage()->GetPrimAtPath(target))
return prim;
// Should throw a warning about an invalid target.
// However, we may not be able to access the prim because one of its
// ancestors may be inactive. If so, failing to retrieve the prim is
// expected, so we should avoid warning spam.
if (!_HasInactiveAncestor(rel.GetStage(), target)) {
TF_WARN("%s -- Invalid target <%s>.",
rel.GetPath().GetText(), target.GetText());
}
}
return UsdPrim();
}
} // namespace
bool
UsdSkelBindingAPI::GetSkeleton(UsdSkelSkeleton* skel) const
{
if (!skel) {
TF_CODING_ERROR("'skel' pointer is null.");
return false;
}
if (UsdRelationship rel = GetSkeletonRel()) {
SdfPathVector targets;
if (rel.GetForwardedTargets(&targets)) {
if (!targets.empty() || rel.HasAuthoredTargets()) {
UsdPrim prim = _GetFirstTargetPrimForRel(rel, targets);
*skel = UsdSkelSkeleton(prim);
if (prim && !*skel) {
TF_WARN("%s -- target (<%s>) of relationship is not "
"a Skeleton.", rel.GetPath().GetText(),
prim.GetPath().GetText());
}
return true;
}
}
}
*skel = UsdSkelSkeleton();
return false;
}
UsdSkelSkeleton
UsdSkelBindingAPI::GetInheritedSkeleton() const
{
UsdSkelSkeleton skel;
if (UsdPrim p = GetPrim()) {
for( ; !p.IsPseudoRoot(); p = p.GetParent()) {
if (UsdSkelBindingAPI(p).GetSkeleton(&skel)) {
return skel;
}
}
}
return skel;
}
bool
UsdSkelBindingAPI::GetAnimationSource(UsdPrim* prim) const
{
if (!prim) {
TF_CODING_ERROR("'prim' pointer is null.");
return false;
}
if (UsdRelationship rel = GetAnimationSourceRel()) {
SdfPathVector targets;
if (rel.GetForwardedTargets(&targets)) {
if (!targets.empty() || rel.HasAuthoredTargets()) {
*prim = _GetFirstTargetPrimForRel(rel, targets);
if (*prim && !UsdSkelIsSkelAnimationPrim(*prim)) {
TF_WARN("%s -- target (<%s>) of relationship is not a valid "
"skel animation source.",
rel.GetPath().GetText(),
prim->GetPath().GetText());
*prim = UsdPrim();
}
return true;
}
}
}
*prim = UsdPrim();
return false;
}
UsdPrim
UsdSkelBindingAPI::GetInheritedAnimationSource() const
{
UsdPrim animPrim;
if (UsdPrim p = GetPrim()) {
for( ; !p.IsPseudoRoot(); p = p.GetParent()) {
if (UsdSkelBindingAPI(p).GetAnimationSource(&animPrim)) {
return animPrim;
}
}
}
return animPrim;
}
bool
UsdSkelBindingAPI::ValidateJointIndices(TfSpan<const int> indices,
size_t numJoints,
std::string* reason)
{
for (size_t i = 0; i < indices.size(); ++i) {
const int jointIndex = indices[i];
if (jointIndex < 0 || static_cast<size_t>(jointIndex) >= numJoints) {
if (reason) {
*reason = TfStringPrintf(
"Index [%d] at element %td is not in the range [0,%zu)",
jointIndex, i, numJoints);
}
return false;
}
}
return true;
}
PXR_NAMESPACE_CLOSE_SCOPE
|
#include <iostream>
#include <fstream>
#include "variable.h"
#include "struct.h"
#include "internal_functions.h"
#include "program.h"
#include "uniform.h"
class Phong : public GLSL::Shader
{
GLSL::Output<GLSL::Vec4> FragColor;
GLSL::Input<GLSL::Vec3> Normal;
GLSL::Input<GLSL::Vec3> FragPos;
public:
GLSL::Uniform<GLSL::Vec3> lightPos;
GLSL::Uniform<GLSL::Vec3> viewPos;
GLSL::Uniform<GLSL::Vec3> lightColor;
GLSL::Uniform<GLSL::Vec3> objectColor;
Phong()
: GLSL::Shader("300", "es"),
FragColor("FragColor", this),
Normal("Normal", this),
FragPos("FragPos", this),
lightPos("lightPos", this),
viewPos("viewPos", this),
lightColor("lightColor", this),
objectColor("objectColor", this)
{
}
void main() {
using namespace GLSL;
Float ambientStrength = 0.1;
Vec3 ambient = lightColor * ambientStrength;
Vec3 norm = normalize(Normal);
Vec3 lightDir = normalize(lightPos - FragPos);
Float diff = max(dot(norm, lightDir), 0);
Vec3 diffuse = lightColor * diff;
Float specularStrength = 0.5;
Vec3 viewDir = normalize(viewPos - FragPos);
Vec3 reflectDir = reflect(-lightDir, norm);
Float spec = pow(max(dot(viewDir, reflectDir), 0), 32);
Vec3 specular = lightColor * specularStrength * spec;
Vec3 result = (ambient + diffuse + specular) * objectColor;
FragColor = Vec4(result.x, result.y, result.z, 1);
}
};
int main(int argc, char *argv[])
{
Phong shader;
shader.compile();
std::cout << shader.source;
return 0;
}
|
/*
* 4 DIMENSIONAL ARRAY
*/
#include <iostream>
using namespace std;
int main()
{
/*
* FOR 4D ARRAYS IAMGINE A 3D CUBE SOLVED IN TIME TAKEN AS FOURTH DIMENSIONAL
*/
int length; //LENGTH OF THE CUBE
int breadth; //BREADTH OF THE CUBE
int height; //HEIGHT OF THE CUBE
int tym; //HOW MANY CUBE IS ACCESSED
cout << "Enter the time YOU WANT TO access the cube"<<endl;
cin >> tym;
cout << "Enter the length,breadth and height of the cube"<<endl;
cin >> length >> breadth >> height;
int arr[tym][height][length][breadth]; //declared 4d array
cout << "Enter the elements of the 4d array" << endl;
for(int i=0;i<tym;i++) //extra loop for time
{
cout << "VALUE CHANGED " << i <<" time"<< endl; // | E
for(int j=0;j<height;j++) // | N
{ // | T
for(int k=0;k<length;k++) // | E
{ // | R
for(int l=0;l<breadth;l++) // | I
{ // | N
cin >> arr[i][j][k][l]; // | G
} // |
} // | 3 D
} // | ARRAY
}
cout << endl;
cout << "ENTERED 4D ARRAY" << endl;
for(int i=0;i<tym;i++)
{
cout << "ACCESSED " << i << " th time" << endl;
for(int j=0;j<height;j++)
{
for(int k=0;k<length;k++)
{
for(int l=0;l<breadth;l++)
{
if(l==breadth-1)
{
cout << arr[i][j][k][l] << endl;
}
else
{
cout << arr[i][j][k][l] << " ";
}
}
}
cout << "---------" <<endl;
}
cout << "========="<<endl;
}
}
|
// smtc_NavClassScope.cpp
//
#include "smtc_NavClassScope.h"
#ifndef LZZ_ENABLE_INLINE
#include "smtc_NavClassScope.inl"
#endif
// semantic
#include "smtc_ScopeVisitor.h"
#define LZZ_INLINE inline
namespace smtc
{
NavClassScope::NavClassScope (NavClassPtr const & nav_class)
: ClassScope (nav_class)
{}
}
namespace smtc
{
NavClassScope::~ NavClassScope ()
{}
}
namespace smtc
{
void NavClassScope::accept (ScopeVisitor const & visitor) const
{
visitor.visit (* this);
}
}
#undef LZZ_INLINE
|
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#pragma once
#include "thrift/compiler/test/fixtures/basic-annotations/gen-cpp2/MyServicePrioChild.h"
#include <thrift/lib/cpp2/gen/service_tcc.h>
namespace cpp2 {
typedef apache::thrift::ThriftPresult<false> MyServicePrioChild_pang_pargs;
typedef apache::thrift::ThriftPresult<true> MyServicePrioChild_pang_presult;
template <typename ProtocolIn_, typename ProtocolOut_>
void MyServicePrioChildAsyncProcessor::setUpAndProcess_pang(apache::thrift::ResponseChannelRequest::UniquePtr req, apache::thrift::SerializedRequest&& serializedRequest, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
if (!setUpRequestProcessing(req, ctx, eb, tm, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, iface_)) {
return;
}
auto pri = iface_->getRequestPriority(ctx, apache::thrift::concurrency::BEST_EFFORT);
processInThread(std::move(req), std::move(serializedRequest), ctx, eb, tm, pri, apache::thrift::RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE, &MyServicePrioChildAsyncProcessor::process_pang<ProtocolIn_, ProtocolOut_>, this);
}
template <typename ProtocolIn_, typename ProtocolOut_>
void MyServicePrioChildAsyncProcessor::process_pang(apache::thrift::ResponseChannelRequest::UniquePtr req, apache::thrift::SerializedRequest&& serializedRequest, apache::thrift::Cpp2RequestContext* ctx, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
// make sure getConnectionContext is null
// so async calls don't accidentally use it
iface_->setConnectionContext(nullptr);
MyServicePrioChild_pang_pargs args;
std::unique_ptr<apache::thrift::ContextStack> ctxStack(this->getContextStack(this->getServiceName(), "MyServicePrioChild.pang", ctx));
try {
deserializeRequest<ProtocolIn_>(args, ctx->getMethodName(), serializedRequest, ctxStack.get());
}
catch (const std::exception& ex) {
apache::thrift::detail::ap::process_handle_exn_deserialization<ProtocolOut_>(
ex, std::move(req), ctx, eb, "pang");
return;
}
req->setStartedProcessing();
auto callback = std::make_unique<apache::thrift::HandlerCallback<void>>(std::move(req), std::move(ctxStack), return_pang<ProtocolIn_,ProtocolOut_>, throw_wrapped_pang<ProtocolIn_, ProtocolOut_>, ctx->getProtoSeqId(), eb, tm, ctx);
if (!callback->isRequestActive()) {
return;
}
iface_->async_tm_pang(std::move(callback));
}
template <class ProtocolIn_, class ProtocolOut_>
folly::IOBufQueue MyServicePrioChildAsyncProcessor::return_pang(int32_t protoSeqId, apache::thrift::ContextStack* ctx) {
ProtocolOut_ prot;
MyServicePrioChild_pang_presult result;
return serializeResponse("pang", &prot, protoSeqId, ctx, result);
}
template <class ProtocolIn_, class ProtocolOut_>
void MyServicePrioChildAsyncProcessor::throw_wrapped_pang(apache::thrift::ResponseChannelRequest::UniquePtr req,int32_t protoSeqId,apache::thrift::ContextStack* ctx,folly::exception_wrapper ew,apache::thrift::Cpp2RequestContext* reqCtx) {
if (!ew) {
return;
}
{
(void)protoSeqId;
apache::thrift::detail::ap::process_throw_wrapped_handler_error<ProtocolOut_>(
ew, std::move(req), reqCtx, ctx, "pang");
return;
}
}
} // cpp2
|
#include "Operator.h"
using namespace std;
namespace Terse {
int toOperator(const string& t, bool prevWasValue) {
if (t == "!") return Operator::Not;
if (t == "++") return prevWasValue ? Operator::IncrementPostfix : Operator::IncrementPrefix;
if (t == "--") return prevWasValue ? Operator::DecrementPostfix : Operator::DecrementPrefix;
if (t == "+") return Operator::Add;
if (t == "-") return prevWasValue ? Operator::Subtract : Operator::Negate;
if (t == "*") return Operator::Multiply;
if (t == "/") return Operator::Divide;
if (t == "%") return Operator::Remainder;
if (t == "=") return Operator::Equal;
if (t == "!=") return Operator::NotEqual;
if (t == "<") return Operator::Less;
if (t == "<=") return Operator::LessOrEqual;
if (t == ">") return Operator::Greater;
if (t == ">=") return Operator::GreaterOrEqual;
if (t == "|") return Operator::Or;
if (t == "&") return Operator::And;
if (t == ":=") return Operator::Assign;
if (t == "+=") return Operator::AddAssign;
if (t == "-=") return Operator::SubtractAssign;
if (t == "*=") return Operator::MultiplyAssign;
if (t == "/=") return Operator::DivideAssign;
if (t == ".") return prevWasValue ? Operator::MemberAccess : Operator::MemberAccessUnary;
return Operator::None;
}
string toToken(int op) {
switch (op) {
case Operator::IncrementPostfix:
case Operator::IncrementPrefix: return "++";
case Operator::DecrementPostfix:
case Operator::DecrementPrefix: return "--";
case Operator::Negate:
case Operator::Subtract: return "-";
case Operator::Not: return "!";
case Operator::Multiply: return "*";
case Operator::Divide: return "/";
case Operator::Remainder: return "%";
case Operator::Add: return "+";
case Operator::Less: return "<";
case Operator::LessOrEqual: return "<=";
case Operator::Greater: return ">";
case Operator::GreaterOrEqual: return ">=";
case Operator::Equal: return "=";
case Operator::NotEqual: return "!=";
case Operator::And: return "&";
case Operator::Or: return "|";
case Operator::Assign: return ":=";
case Operator::AddAssign: return "+=";
case Operator::SubtractAssign: return "-=";
case Operator::MultiplyAssign: return "*=";
case Operator::DivideAssign: return "/=";
case Operator::MemberAccess:
case Operator::MemberAccessUnary: return ".";
default: return "unknown";
}
}
}
|
/*
* Monster.cpp
*
* Created on: 14.11.2012
* Author: Denis Zagayevskiy
*/
#include "Monster.h"
void Monster::step(double elapsedTime){
if(remainingTime <= 0.0){
remainingTime = drand48()*maxRemainingTime;
newDirectionEvent();
}else{
int iX, iY;
float fCurrentXFloor = floorf(x);
float fCurrentYFloor = floorf(y);
int iCurrentX = (int) fCurrentXFloor;
int iCurrentY = (int) fCurrentYFloor;
switch(state){
case MONSTER_GO_LEFT:
iX = (int) floor(x - radius + speedX*elapsedTime);
iY = iCurrentY;
if(game->getMapAt(iX, iY) != Game::TILE_WALL){
x += speedX*elapsedTime;
}else{
x = fCurrentXFloor + 0.5;
newDirectionEvent();
}
if(lastEvent != EVENT_NONE){
switchDirection(false);
}
break;
case MONSTER_GO_RIGHT:
iX = (int) floor(x + radius + speedX*elapsedTime);
iY = iCurrentY;
if(game->getMapAt(iX, iY) != Game::TILE_WALL){
x += speedX*elapsedTime;
}else{
x = fCurrentXFloor + 0.5;
newDirectionEvent();
}
if(lastEvent != EVENT_NONE){
switchDirection(false);
}
break;
case MONSTER_GO_UP:
iX = iCurrentX;
iY = (int) floor(y - radius + speedY*elapsedTime);
if(game->getMapAt(iX, iY) != Game::TILE_WALL){
y += speedY*elapsedTime;
}else{
y = fCurrentYFloor + 0.5;
newDirectionEvent();
}
if(lastEvent != EVENT_NONE){
switchDirection(true);
}
break;
case MONSTER_GO_DOWN:
iX = iCurrentX;
iY = (int) floor(y + radius + speedY*elapsedTime);
if(game->getMapAt(iX, iY) != Game::TILE_WALL){
y += speedY*elapsedTime;
}else{
y = fCurrentYFloor + 0.5;
newDirectionEvent();
}
if(lastEvent != EVENT_NONE){
switchDirection(true);
}
break;
default: break;
}
remainingTime -= elapsedTime;
totalPathLength += speed*elapsedTime;
totalStepsCount += 1.0;
averageStepLength = totalPathLength / totalStepsCount;
}
}
void Monster::switchDirection(bool verticalDirectionNow){
switch(lastEvent){
case EVENT_MOVE_LEFT:
if(verticalDirectionNow){
if(getYCellCenterDistance() < averageStepLength){
y = floorf(y) + 0.5;
speedX = -speed;
speedY = 0.0;
lastEvent = EVENT_NONE;
state = MONSTER_GO_LEFT;
}
}else{
lastEvent = EVENT_NONE;
speedX = -speed;
state = MONSTER_GO_LEFT;
}
break;
case EVENT_MOVE_RIGHT:
if(verticalDirectionNow){
if(getYCellCenterDistance() < averageStepLength){
y = floorf(y) + 0.5;
speedX = speed;
speedY = 0.0;
lastEvent = EVENT_NONE;
state = MONSTER_GO_RIGHT;
}
}else{
lastEvent = EVENT_NONE;
speedX = speed;
state = MONSTER_GO_RIGHT;
}
break;
case EVENT_MOVE_UP:
if(verticalDirectionNow){
lastEvent = EVENT_NONE;
speedY = -speed;
state = MONSTER_GO_UP;
}else{
if(getXCellCenterDistance() < averageStepLength){
x = floorf(x) + 0.5;
speedX = 0.0f;
speedY = -speed;
lastEvent = EVENT_NONE;
state = MONSTER_GO_UP;
}
}
break;
case EVENT_MOVE_DOWN:
if(verticalDirectionNow){
lastEvent = EVENT_NONE;
speedY = speed;
state = MONSTER_GO_DOWN;
}else{
if(getXCellCenterDistance() < averageStepLength){
x = floorf(x) + 0.5;
speedX = 0.0f;
speedY = speed;
lastEvent = EVENT_NONE;
state = MONSTER_GO_DOWN;
}
}
break;
default: break;
}
}
void Monster::initGraphics(GLuint _shiftProgram){
//animation = new Animation(_shiftProgram, Art::getTexture(Art::TEXTURE_MONSTER_ANIMATION), 2, 2, 2, 500.0, game->getTileSize(), game->getTileSize());
plume = new Plume(game->getTileSize(), Art::getTexture(Art::TEXTURE_WATER), 15.0, 1.0f);
}
void Monster::render(double elapsedTime){
GLfloat tileSize = game->getTileSize();
//animation->render(elapsedTime, (x - radius)*tileSize + game->getShiftX(), (y - radius)*tileSize + game->getShiftY());
plume->pushPoint((x - radius)*tileSize + game->getShiftX(), (y - radius)*tileSize + game->getShiftY());
plume->render(elapsedTime);
}
Monster::~Monster() {
//if(animation){
// delete animation;
//}
if(plume){
delete plume;
}
}
|
#include "CPE.hpp"
bool CPE::IsValidBlock(uint8_t type)
{
for (int i = BlockType::kStartOfBlockTypes; i < BlockType::kEndOfBlockTypes; ++i) {
if (type == i)
return true;
}
return false;
}
void CPE::SendExtInfo(Client* client, std::string appName, short extCount)
{
Packet* packet = new Packet(CPE::PacketType::kExtInfo);
packet->Write(appName);
packet->Write(extCount);
client->QueuePacket(packet);
}
void CPE::SendExtEntry(Client* client, std::string extName, int version)
{
Packet* packet = new Packet(CPE::PacketType::kExtEntry);
packet->Write(extName);
packet->Write(version);
client->QueuePacket(packet);
}
void CPE::SendCustomBlocks(Client* client, uint8_t support)
{
Packet* packet = new Packet(CPE::PacketType::kCustomBlocks);
packet->Write(support);
client->QueuePacket(packet);
}
|
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <atomic>
#define EIGEN_USE_THREADS
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#if GOOGLE_CUDA
#include "third_party/gpus/cudnn/cudnn.h"
#endif // GOOGLE_CUDA
#include "tensorflow/core/kernels/conv_2d.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/util/stream_executor_util.h"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/kernels/fill_functor.h"
#include "tensorflow/core/kernels/fused_batch_norm_op.h"
#include "tensorflow/core/kernels/redux_functor.h"
#include "tensorflow/core/kernels/transpose_functor.h"
#include "tensorflow/core/lib/core/blocking_counter.h"
#include "tensorflow/core/util/env_var.h"
#include "tensorflow/core/util/tensor_format.h"
namespace tensorflow {
using CPUDevice = Eigen::ThreadPoolDevice;
using GPUDevice = Eigen::GpuDevice;
namespace functor {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
using se::DeviceMemory;
using se::ScratchAllocator;
using se::Stream;
using se::port::StatusOr;
#endif
string ToString(FusedBatchNormActivationMode activation_mode) {
switch (activation_mode) {
case FusedBatchNormActivationMode::kIdentity:
return "Identity";
case FusedBatchNormActivationMode::kRelu:
return "Relu";
}
}
Status ParseActivationMode(OpKernelConstruction* context,
FusedBatchNormActivationMode* activation_mode) {
string activation_mode_str;
TF_RETURN_IF_ERROR(context->GetAttr("activation_mode", &activation_mode_str));
if (activation_mode_str == "Identity") {
*activation_mode = FusedBatchNormActivationMode::kIdentity;
return Status::OK();
}
if (activation_mode_str == "Relu") {
*activation_mode = FusedBatchNormActivationMode::kRelu;
return Status::OK();
}
return errors::InvalidArgument("Unsupported activation mode: ",
activation_mode_str);
}
// Functor used by FusedBatchNormOp to do the computations.
template <typename Device, typename T, typename U, bool is_training>
struct FusedBatchNorm;
// Functor used by FusedBatchNormGradOp to do the computations when
// is_training=True.
template <typename Device, typename T, typename U>
struct FusedBatchNormGrad;
template <typename T, typename U>
struct FusedBatchNorm<CPUDevice, T, U, /* is_training= */ true> {
void operator()(OpKernelContext* context, const Tensor& x_input,
const Tensor& scale_input, const Tensor& offset_input,
const Tensor& running_mean_input,
const Tensor& running_variance_input,
const Tensor* side_input, U epsilon, U exponential_avg_factor,
FusedBatchNormActivationMode activation_mode,
Tensor* y_output, Tensor* running_mean_output,
Tensor* running_var_output, Tensor* saved_batch_mean_output,
Tensor* saved_batch_var_output, TensorFormat tensor_format,
bool use_reserved_space) {
OP_REQUIRES(context, side_input == nullptr,
errors::Internal(
"The CPU implementation of FusedBatchNorm does not support "
"side input."));
OP_REQUIRES(context,
activation_mode == FusedBatchNormActivationMode::kIdentity,
errors::Internal("The CPU implementation of FusedBatchNorm "
"does not support activations."));
if (use_reserved_space) {
Tensor* dummy_reserve_space = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(5, {}, &dummy_reserve_space));
// Initialize the memory, to avoid sanitizer alerts.
dummy_reserve_space->flat<U>()(0) = U();
}
Tensor transformed_x;
Tensor transformed_y;
if (tensor_format == FORMAT_NCHW) {
const int64 in_batch = GetTensorDim(x_input, tensor_format, 'N');
const int64 in_rows = GetTensorDim(x_input, tensor_format, 'H');
const int64 in_cols = GetTensorDim(x_input, tensor_format, 'W');
const int64 in_depths = GetTensorDim(x_input, tensor_format, 'C');
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_x));
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_y));
// Perform NCHW to NHWC
std::vector<int32> perm = {0, 2, 3, 1};
OP_REQUIRES_OK(
context, ::tensorflow::DoTranspose(context->eigen_device<CPUDevice>(),
x_input, perm, &transformed_x));
} else {
transformed_x = x_input;
transformed_y = *y_output;
}
typename TTypes<T, 4>::Tensor x(transformed_x.tensor<T, 4>());
typename TTypes<U>::ConstVec scale(scale_input.vec<U>());
typename TTypes<U>::ConstVec offset(offset_input.vec<U>());
typename TTypes<U>::ConstVec old_mean(running_mean_input.vec<U>());
typename TTypes<U>::ConstVec old_variance(running_variance_input.vec<U>());
typename TTypes<T, 4>::Tensor y(transformed_y.tensor<T, 4>());
typename TTypes<U>::Vec new_mean(running_mean_output->vec<U>());
typename TTypes<U>::Vec new_variance(running_var_output->vec<U>());
typename TTypes<U>::Vec saved_batch_mean(saved_batch_mean_output->vec<U>());
typename TTypes<U>::Vec saved_batch_var(saved_batch_var_output->vec<U>());
const CPUDevice& d = context->eigen_device<CPUDevice>();
const int depth = x.dimension(3);
const int size = x.size();
const int rest_size = size / depth;
Eigen::DSizes<Eigen::Index, 2> rest_by_depth(rest_size, depth);
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::DSizes<Eigen::Index, 2> one_by_depth(1, depth);
Eigen::array<int, 1> reduce_dims({0});
Eigen::array<int, 2> bcast_spec({rest_size, 1});
#else
Eigen::IndexList<Eigen::type2index<1>, Eigen::Index> one_by_depth;
one_by_depth.set(1, depth);
Eigen::IndexList<Eigen::type2index<0>> reduce_dims;
Eigen::IndexList<Eigen::Index, Eigen::type2index<1>> bcast_spec;
bcast_spec.set(0, rest_size);
#endif
auto x_rest_by_depth = x.reshape(rest_by_depth).template cast<U>();
const int rest_size_minus_one = (rest_size > 1) ? (rest_size - 1) : 1;
U rest_size_inv = static_cast<U>(1.0f / static_cast<U>(rest_size));
// This adjustment is for Bessel's correction
U rest_size_adjust =
static_cast<U>(rest_size) / static_cast<U>(rest_size_minus_one);
Eigen::Tensor<U, 1, Eigen::RowMajor> batch_mean(depth);
Eigen::Tensor<U, 1, Eigen::RowMajor> batch_variance(depth);
batch_mean.device(d) = (x_rest_by_depth.sum(reduce_dims) * rest_size_inv);
auto x_centered = x_rest_by_depth -
batch_mean.reshape(one_by_depth).broadcast(bcast_spec);
batch_variance.device(d) =
x_centered.square().sum(reduce_dims) * rest_size_inv;
auto scaling_factor = ((batch_variance + epsilon).rsqrt() * scale)
.eval()
.reshape(one_by_depth)
.broadcast(bcast_spec);
auto x_scaled = x_centered * scaling_factor;
auto x_shifted =
(x_scaled + offset.reshape(one_by_depth).broadcast(bcast_spec))
.template cast<T>();
y.reshape(rest_by_depth).device(d) = x_shifted;
if (exponential_avg_factor == U(1.0)) {
saved_batch_var.device(d) = batch_variance;
saved_batch_mean.device(d) = batch_mean;
new_variance.device(d) = batch_variance * rest_size_adjust;
new_mean.device(d) = batch_mean;
} else {
U one_minus_factor = U(1) - exponential_avg_factor;
saved_batch_var.device(d) = batch_variance;
saved_batch_mean.device(d) = batch_mean;
new_variance.device(d) =
one_minus_factor * old_variance +
(exponential_avg_factor * rest_size_adjust) * batch_variance;
new_mean.device(d) =
one_minus_factor * old_mean + exponential_avg_factor * batch_mean;
}
if (tensor_format == FORMAT_NCHW) {
// Perform NHWC to NCHW
const std::vector<int32> perm = {0, 3, 1, 2};
const Status s = ::tensorflow::DoTranspose(
context->eigen_device<CPUDevice>(), transformed_y, perm, y_output);
if (!s.ok()) {
context->SetStatus(errors::InvalidArgument("Transpose failed: ", s));
}
}
}
};
template <typename T, typename U>
struct FusedBatchNorm<CPUDevice, T, U, /* is_training= */ false> {
void operator()(OpKernelContext* context, const Tensor& x_input,
const Tensor& scale_input, const Tensor& offset_input,
const Tensor& estimated_mean_input,
const Tensor& estimated_variance_input,
const Tensor* side_input, U epsilon, U exponential_avg_factor,
FusedBatchNormActivationMode activation_mode,
Tensor* y_output, Tensor* batch_mean_output,
Tensor* batch_var_output, Tensor* saved_mean_output,
Tensor* saved_var_output, TensorFormat tensor_format,
bool use_reserved_space) {
OP_REQUIRES(context, side_input == nullptr,
errors::Internal(
"The CPU implementation of FusedBatchNorm does not support "
"side input."));
OP_REQUIRES(context,
activation_mode == FusedBatchNormActivationMode::kIdentity,
errors::Internal("The CPU implementation of FusedBatchNorm "
"does not support activations."));
if (use_reserved_space) {
Tensor* dummy_reserve_space = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(5, {}, &dummy_reserve_space));
// Initialize the memory, to avoid sanitizer alerts.
dummy_reserve_space->flat<U>()(0) = U();
}
Tensor transformed_x;
Tensor transformed_y;
if (tensor_format == FORMAT_NCHW) {
const int64 in_batch = GetTensorDim(x_input, tensor_format, 'N');
const int64 in_rows = GetTensorDim(x_input, tensor_format, 'H');
const int64 in_cols = GetTensorDim(x_input, tensor_format, 'W');
const int64 in_depths = GetTensorDim(x_input, tensor_format, 'C');
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_x));
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_y));
// Perform NCHW to NHWC
std::vector<int32> perm = {0, 2, 3, 1};
OP_REQUIRES_OK(
context, ::tensorflow::DoTranspose(context->eigen_device<CPUDevice>(),
x_input, perm, &transformed_x));
} else {
transformed_x = x_input;
transformed_y = *y_output;
}
typename TTypes<T, 4>::Tensor x(transformed_x.tensor<T, 4>());
typename TTypes<U>::ConstVec scale(scale_input.vec<U>());
typename TTypes<U>::ConstVec offset(offset_input.vec<U>());
typename TTypes<U>::ConstVec estimated_mean(estimated_mean_input.vec<U>());
typename TTypes<U>::ConstVec estimated_variance(
estimated_variance_input.vec<U>());
typename TTypes<T, 4>::Tensor y(transformed_y.tensor<T, 4>());
typename TTypes<U>::Vec batch_mean(batch_mean_output->vec<U>());
typename TTypes<U>::Vec batch_variance(batch_var_output->vec<U>());
const CPUDevice& d = context->eigen_device<CPUDevice>();
const int depth = x.dimension(3);
OP_REQUIRES(
context, depth != 0,
errors::Internal("The 4th element in the input shape cannot be 0."));
const int size = x.size();
const int rest_size = size / depth;
Eigen::DSizes<Eigen::Index, 2> rest_by_depth(rest_size, depth);
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::DSizes<Eigen::Index, 2> one_by_depth(1, depth);
Eigen::array<int, 1> reduce_dims({0});
Eigen::array<int, 2> bcast_spec({rest_size, 1});
#else
Eigen::IndexList<Eigen::type2index<1>, Eigen::Index> one_by_depth;
one_by_depth.set(1, depth);
Eigen::IndexList<Eigen::Index, Eigen::type2index<1>> bcast_spec;
bcast_spec.set(0, rest_size);
#endif
auto x_rest_by_depth = x.reshape(rest_by_depth).template cast<U>();
auto x_centered =
x_rest_by_depth -
estimated_mean.reshape(one_by_depth).broadcast(bcast_spec);
auto scaling_factor = ((estimated_variance + epsilon).rsqrt() * scale)
.eval()
.reshape(one_by_depth)
.broadcast(bcast_spec);
auto x_scaled = x_centered * scaling_factor;
auto x_shifted =
(x_scaled + offset.reshape(one_by_depth).broadcast(bcast_spec))
.template cast<T>();
y.reshape(rest_by_depth).device(d) = x_shifted;
batch_mean.device(d) = estimated_mean;
batch_variance.device(d) = estimated_variance;
if (tensor_format == FORMAT_NCHW) {
// Perform NHWC to NCHW
const std::vector<int32> perm = {0, 3, 1, 2};
const Status s = ::tensorflow::DoTranspose(
context->eigen_device<CPUDevice>(), transformed_y, perm, y_output);
if (!s.ok()) {
context->SetStatus(errors::InvalidArgument("Transpose failed: ", s));
}
}
}
};
template <typename T, typename U>
struct FusedBatchNormGrad<CPUDevice, T, U> {
void operator()(OpKernelContext* context, const Tensor& y_backprop_input,
const Tensor& x_input, const Tensor& scale_input,
const Tensor* offset_input, const Tensor& mean_input,
const Tensor& variance_input, const Tensor* y_input,
U epsilon, FusedBatchNormActivationMode activation_mode,
Tensor* x_backprop_output, Tensor* scale_backprop_output,
Tensor* offset_backprop_output,
Tensor* side_input_backprop_output, bool use_reserved_space,
TensorFormat tensor_format) {
OP_REQUIRES(context,
y_input == nullptr &&
activation_mode == FusedBatchNormActivationMode::kIdentity,
errors::Internal(
"The CPU implementation of FusedBatchNormGrad does not "
"support activations."));
OP_REQUIRES(context, side_input_backprop_output == nullptr,
errors::Internal("The CPU implementation of FusedBatchNormGrad "
"does not support side input."));
Tensor transformed_y_backprop_input;
Tensor transformed_x_input;
Tensor transformed_x_backprop_output;
if (tensor_format == FORMAT_NCHW) {
const int64 in_batch = GetTensorDim(x_input, tensor_format, 'N');
const int64 in_rows = GetTensorDim(x_input, tensor_format, 'H');
const int64 in_cols = GetTensorDim(x_input, tensor_format, 'W');
const int64 in_depths = GetTensorDim(x_input, tensor_format, 'C');
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_y_backprop_input));
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_x_input));
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NHWC, in_batch,
in_rows, in_cols, in_depths),
&transformed_x_backprop_output));
// Perform NCHW to NHWC
std::vector<int32> perm = {0, 2, 3, 1};
OP_REQUIRES_OK(
context, ::tensorflow::DoTranspose(context->eigen_device<CPUDevice>(),
y_backprop_input, perm,
&transformed_y_backprop_input));
OP_REQUIRES_OK(context, ::tensorflow::DoTranspose(
context->eigen_device<CPUDevice>(), x_input,
perm, &transformed_x_input));
} else {
transformed_y_backprop_input = y_backprop_input;
transformed_x_input = x_input;
transformed_x_backprop_output = *x_backprop_output;
}
typename TTypes<T, 4>::Tensor y_backprop(
transformed_y_backprop_input.tensor<T, 4>());
typename TTypes<T, 4>::Tensor x(transformed_x_input.tensor<T, 4>());
typename TTypes<U>::ConstVec scale(scale_input.vec<U>());
typename TTypes<U>::ConstVec mean(mean_input.vec<U>());
typename TTypes<U>::ConstVec variance(variance_input.vec<U>());
typename TTypes<T, 4>::Tensor x_backprop(
transformed_x_backprop_output.tensor<T, 4>());
typename TTypes<U>::Vec offset_backprop(offset_backprop_output->vec<U>());
// Note: the following formulas are used to compute the gradients for
// back propagation.
// x_backprop = scale * rsqrt(variance + epsilon) *
// [y_backprop - mean(y_backprop) - (x - mean(x)) *
// mean(y_backprop * (x - mean(x))) / (variance + epsilon)]
// scale_backprop = sum(y_backprop *
// (x - mean(x)) * rsqrt(variance + epsilon))
// offset_backprop = sum(y_backprop)
const CPUDevice& d = context->eigen_device<CPUDevice>();
const int depth = x.dimension(3);
const int size = x.size();
const int rest_size = size / depth;
Eigen::DSizes<Eigen::Index, 2> rest_by_depth(rest_size, depth);
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::DSizes<Eigen::Index, 2> one_by_depth(1, depth);
Eigen::array<int, 2> bcast_spec({rest_size, 1});
#else
Eigen::IndexList<Eigen::type2index<1>, Eigen::Index> one_by_depth;
one_by_depth.set(1, depth);
Eigen::IndexList<Eigen::Index, Eigen::type2index<1>> bcast_spec;
bcast_spec.set(0, rest_size);
#endif
auto x_rest_by_depth = x.reshape(rest_by_depth).template cast<U>();
U rest_size_inv = static_cast<U>(1.0f / static_cast<U>(rest_size));
// Eigen is notoriously bad at reducing outer dimension, so we materialize
// all temporary tensors that require reduction, and then use Eigen redux
// functor, that is optimized for this particular task.
//
// All reductions are of this type: [rest_size, depth] -> [depth].
using ScalarSum = Eigen::internal::scalar_sum_op<U>;
const functor::ReduceOuterDimensions<T, U, U, ScalarSum> redux_sum_t;
const functor::ReduceOuterDimensions<U, U, U, ScalarSum> redux_sum_u;
auto scratch_dtype = DataTypeToEnum<U>::value;
// Allocate a temporary workspace of [depth] shape.
Tensor scratch_one_by_depth;
OP_REQUIRES_OK(context, context->allocate_temp(scratch_dtype, {depth},
&scratch_one_by_depth));
// Maybe allocate a temporary workspace of [rest_size, depth] shape.
Tensor scratch_rest_by_depth;
if (std::is_same<T, U>::value) {
OP_REQUIRES(context,
scratch_rest_by_depth.CopyFrom(transformed_x_backprop_output,
{rest_size, depth}),
errors::Internal("Failed to copy a tensor"));
} else {
OP_REQUIRES_OK(context,
context->allocate_temp(scratch_dtype, {rest_size, depth},
&scratch_rest_by_depth));
}
typename TTypes<U, 2>::Tensor scratch_tensor(
scratch_rest_by_depth.tensor<U, 2>());
typename TTypes<U>::Vec scratch_vector(scratch_one_by_depth.vec<U>());
auto x_mean_rest_by_depth =
mean.reshape(one_by_depth).broadcast(bcast_spec);
auto x_centered = (x_rest_by_depth - x_mean_rest_by_depth);
auto coef0_one_by_depth =
(variance.reshape(one_by_depth) + epsilon).rsqrt();
auto coef0_rest_by_depth = coef0_one_by_depth.broadcast(bcast_spec);
auto x_scaled = x_centered * coef0_rest_by_depth;
auto y_backprop_rest_by_depth =
y_backprop.reshape(rest_by_depth).template cast<U>();
// Compute `scale_backprop_output`:
// scale_backprop =
// (y_backprop_rest_by_depth * x_scaled).sum(reduce_dims)
scratch_tensor.device(d) = y_backprop_rest_by_depth * x_scaled;
redux_sum_u(d, rest_by_depth, scratch_rest_by_depth, scale_backprop_output);
// Compute 'offset_backprop_output':
// offset_backprop =
// y_backprop_rest_by_depth.sum(reduce_dims)
redux_sum_t(d, rest_by_depth, transformed_y_backprop_input,
offset_backprop_output);
auto y_backprop_sum = offset_backprop;
auto y_backprop_sum_one_by_depth = y_backprop_sum.reshape(one_by_depth);
auto y_backprop_mean_one_by_depth =
y_backprop_sum_one_by_depth * rest_size_inv;
auto y_backprop_mean_rest_by_depth =
y_backprop_mean_one_by_depth.broadcast(bcast_spec);
auto y_backprop_centered =
y_backprop_rest_by_depth - y_backprop_mean_rest_by_depth;
// Compute expression:
// y_backprop_centered_mean =
// (y_backprop_rest_by_depth * x_centered).mean(reduce_dims)
scratch_tensor.device(d) = y_backprop_rest_by_depth * x_centered;
redux_sum_u(d, rest_by_depth, scratch_rest_by_depth, &scratch_one_by_depth);
auto y_backprop_centered_mean =
scratch_vector.reshape(one_by_depth) / static_cast<U>(rest_size);
auto coef1 = (scale.reshape(one_by_depth) * coef0_one_by_depth)
.broadcast(bcast_spec);
auto coef2 = (coef0_one_by_depth.square() * y_backprop_centered_mean)
.broadcast(bcast_spec);
x_backprop.reshape(rest_by_depth).device(d) =
(coef1 * (y_backprop_centered - x_centered * coef2)).template cast<T>();
if (tensor_format == FORMAT_NCHW) {
// Perform NHWC to NCHW
std::vector<int32> perm = {0, 3, 1, 2};
OP_REQUIRES_OK(
context, ::tensorflow::DoTranspose(context->eigen_device<CPUDevice>(),
transformed_x_backprop_output,
perm, x_backprop_output));
}
}
};
template <typename T, typename U>
struct FusedBatchNormFreezeGrad<CPUDevice, T, U> {
void operator()(OpKernelContext* context, const Tensor& y_backprop_input,
const Tensor& x_input, const Tensor& scale_input,
const Tensor& pop_mean_input,
const Tensor& pop_variance_input, U epsilon,
Tensor* x_backprop_output, Tensor* scale_backprop_output,
Tensor* offset_backprop_output) {
typename TTypes<T, 4>::ConstTensor y_backprop(
y_backprop_input.tensor<T, 4>());
typename TTypes<T, 4>::ConstTensor input(x_input.tensor<T, 4>());
typename TTypes<U>::ConstVec scale(scale_input.vec<U>());
typename TTypes<U>::ConstVec pop_mean(pop_mean_input.vec<U>());
typename TTypes<U>::ConstVec pop_var(pop_variance_input.vec<U>());
typename TTypes<T, 4>::Tensor x_backprop(x_backprop_output->tensor<T, 4>());
typename TTypes<U>::Vec scale_backprop(scale_backprop_output->vec<U>());
const int depth = pop_mean.dimension(0);
const int rest_size = input.size() / depth;
const CPUDevice& d = context->eigen_device<CPUDevice>();
// Allocate two temporary workspaces of [depth] shape.
Tensor scratch1_vec, scratch2_vec;
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<U>::value,
{depth}, &scratch1_vec));
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<U>::value,
{depth}, &scratch2_vec));
// Maybe allocate a temporary workspace of [rest_size, depth] shape.
Tensor scratch3_tensor;
if (std::is_same<T, U>::value) {
OP_REQUIRES(
context,
scratch3_tensor.CopyFrom(*x_backprop_output, {rest_size, depth}),
errors::Internal("Failed to copy a tensor"));
} else {
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<U>::value,
{rest_size, depth},
&scratch3_tensor));
}
typename TTypes<U>::Vec scratch1(scratch1_vec.vec<U>());
typename TTypes<U>::Vec scratch2(scratch2_vec.vec<U>());
typename TTypes<U, 2>::Tensor scratch3(scratch3_tensor.tensor<U, 2>());
Eigen::DSizes<Eigen::Index, 2> rest_by_depth(rest_size, depth);
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::DSizes<Eigen::Index, 2> one_by_depth(1, depth);
Eigen::array<int, 2> rest_by_one({rest_size, 1});
#else
Eigen::IndexList<Eigen::type2index<1>, Eigen::Index> one_by_depth;
one_by_depth.set(1, depth);
Eigen::IndexList<Eigen::Index, Eigen::type2index<1>> rest_by_one;
rest_by_one.set(0, rest_size);
#endif
// Sum reduction along the 0th dimension using custom CPU functor.
using ScalarSum = Eigen::internal::scalar_sum_op<U>;
const functor::ReduceOuterDimensions<T, U, U, ScalarSum> redux_sum_t;
const functor::ReduceOuterDimensions<U, U, U, ScalarSum> redux_sum_u;
// offset_backprop = sum(y_backprop)
// scale_backprop = y_backprop * ((x - pop_mean) * rsqrt(pop_var + epsilon))
// x_backprop = y_backprop * (scale * rsqrt(pop_var + epsilon))
// NOTE: DEFAULT DEVICE comment is added to expression assignments that
// we don't want to be executed in a thread pool.
auto y_backprop_rest_by_depth =
y_backprop.reshape(rest_by_depth).template cast<U>();
auto input_rest_by_depth = input.reshape(rest_by_depth).template cast<U>();
// offset_backprop = sum(y_backprop)
redux_sum_t(d, rest_by_depth, y_backprop_input, offset_backprop_output);
// scratch1 = rsqrt(pop_var + epsilon)
scratch1 = (pop_var + pop_var.constant(epsilon)).rsqrt(); // DEFAULT DEVICE
// scratch2 = sum(y_backprop * (x - mean))
scratch3.device(d) =
y_backprop_rest_by_depth *
(input_rest_by_depth -
pop_mean.reshape(one_by_depth).broadcast(rest_by_one));
redux_sum_u(d, rest_by_depth, scratch3_tensor, &scratch2_vec);
x_backprop.reshape(rest_by_depth).device(d) =
(y_backprop_rest_by_depth *
((scratch1.reshape(one_by_depth) * scale.reshape(one_by_depth))
.broadcast(rest_by_one)))
.template cast<T>();
scale_backprop = scratch2 * scratch1; // DEFAULT DEVICE
}
};
#if !GOOGLE_CUDA
namespace {
// See implementation under GOOGLE_CUDA #ifdef below.
// This is a CUDA specific feature, do not enable it for non-CUDA builds
bool BatchnormSpatialPersistentEnabled() { return false; }
} // namespace
#endif
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
namespace {
se::dnn::ActivationMode AsDnnActivationMode(
const FusedBatchNormActivationMode activation_mode) {
switch (activation_mode) {
case FusedBatchNormActivationMode::kIdentity:
return se::dnn::ActivationMode::kNone;
case FusedBatchNormActivationMode::kRelu:
return se::dnn::ActivationMode::kRelu;
}
}
#if GOOGLE_CUDA
// NOTE(ezhulenev): See `BatchnormSpatialPersistentEnabled` documentation in the
// `cuda_dnn.cc` for details.
bool BatchnormSpatialPersistentEnabled() {
#if CUDNN_VERSION >= 7402
static bool is_enabled = [] {
bool is_enabled = false;
TF_CHECK_OK(tensorflow::ReadBoolFromEnvVar(
"TF_USE_CUDNN_BATCHNORM_SPATIAL_PERSISTENT",
/*default_val=*/false, &is_enabled));
return is_enabled;
}();
return is_enabled;
#else
return false;
#endif
}
#endif
} // namespace
template <typename U, typename T>
DeviceMemory<U> CastDeviceMemory(Tensor* tensor) {
return DeviceMemory<U>::MakeFromByteSize(
tensor->template flat<T>().data(),
tensor->template flat<T>().size() * sizeof(T));
}
// A helper to allocate temporary scratch memory for Cudnn BatchNormEx ops. It
// takes the ownership of the underlying memory. The expectation is that the
// memory should be alive for the span of the Cudnn BatchNormEx itself.
template <typename T>
class CudnnBatchNormAllocatorInTemp : public ScratchAllocator {
public:
~CudnnBatchNormAllocatorInTemp() override = default;
explicit CudnnBatchNormAllocatorInTemp(OpKernelContext* context)
: context_(context) {}
int64 GetMemoryLimitInBytes() override {
return std::numeric_limits<int64>::max();
}
StatusOr<DeviceMemory<uint8>> AllocateBytes(int64 byte_size) override {
Tensor temporary_memory;
const DataType tf_data_type = DataTypeToEnum<T>::v();
int64 allocate_count =
Eigen::divup(byte_size, static_cast<int64>(sizeof(T)));
Status allocation_status(context_->allocate_temp(
tf_data_type, TensorShape({allocate_count}), &temporary_memory));
if (!allocation_status.ok()) {
return allocation_status;
}
// Hold the reference of the allocated tensors until the end of the
// allocator.
allocated_tensors_.push_back(temporary_memory);
total_byte_size_ += byte_size;
return DeviceMemory<uint8>::MakeFromByteSize(
temporary_memory.template flat<T>().data(),
temporary_memory.template flat<T>().size() * sizeof(T));
}
int64 TotalByteSize() const { return total_byte_size_; }
Tensor get_allocated_tensor(int index) const {
return allocated_tensors_[index];
}
private:
int64 total_byte_size_ = 0;
OpKernelContext* context_; // not owned
std::vector<Tensor> allocated_tensors_;
};
// A helper to allocate memory for Cudnn BatchNormEx as a kernel output. It is
// used by forward pass kernel to feed the output to the backward pass.
// The memory is expected to live long enough after the backward pass is
// finished.
template <typename T>
class CudnnBatchNormAllocatorInOutput : public ScratchAllocator {
public:
~CudnnBatchNormAllocatorInOutput() override {
if (!output_allocated) {
Tensor* dummy_reserve_space = nullptr;
OP_REQUIRES_OK(context_, context_->allocate_output(output_index_, {},
&dummy_reserve_space));
}
}
CudnnBatchNormAllocatorInOutput(OpKernelContext* context, int output_index)
: context_(context), output_index_(output_index) {}
int64 GetMemoryLimitInBytes() override {
return std::numeric_limits<int64>::max();
}
StatusOr<DeviceMemory<uint8>> AllocateBytes(int64 byte_size) override {
output_allocated = true;
DCHECK(total_byte_size_ == 0)
<< "Reserve space allocator can only be called once";
int64 allocate_count =
Eigen::divup(byte_size, static_cast<int64>(sizeof(T)));
Tensor* temporary_memory = nullptr;
Status allocation_status(context_->allocate_output(
output_index_, TensorShape({allocate_count}), &temporary_memory));
if (!allocation_status.ok()) {
return allocation_status;
}
total_byte_size_ += byte_size;
auto memory_uint8 = DeviceMemory<uint8>::MakeFromByteSize(
temporary_memory->template flat<T>().data(),
temporary_memory->template flat<T>().size() * sizeof(T));
return StatusOr<DeviceMemory<uint8>>(memory_uint8);
}
int64 TotalByteSize() { return total_byte_size_; }
private:
int64 total_byte_size_ = 0;
OpKernelContext* context_; // not owned
int output_index_;
bool output_allocated = false;
};
template <typename T, typename U, bool is_training>
struct FusedBatchNorm<GPUDevice, T, U, is_training> {
void operator()(OpKernelContext* context, const Tensor& x,
const Tensor& scale, const Tensor& offset,
const Tensor& estimated_mean,
const Tensor& estimated_variance, const Tensor* side_input,
U epsilon, U exponential_avg_factor,
FusedBatchNormActivationMode activation_mode, Tensor* y,
Tensor* batch_mean, Tensor* batch_var, Tensor* saved_mean,
Tensor* saved_inv_var, TensorFormat tensor_format,
bool use_reserved_space) {
auto* stream = context->op_device_context()->stream();
OP_REQUIRES(context, stream, errors::Internal("No GPU stream available"));
const int64 batch_size = GetTensorDim(x, tensor_format, 'N');
const int64 channels = GetTensorDim(x, tensor_format, 'C');
const int64 height = GetTensorDim(x, tensor_format, 'H');
const int64 width = GetTensorDim(x, tensor_format, 'W');
// If use_reserved_space we have reserve_space_3 output (only in
// FusedBatchNormV3 op).
#if GOOGLE_CUDA
// Check if cuDNN batch normalization has a fast NHWC implementation:
// (1) In inference mode it's always fast.
// (2) Tensorflow enabled batchnorm spatial persistence, we are called
// from
// FusedBatchNormV3, i.e. use_reserved_space is true.
const bool fast_nhwc_batch_norm =
!is_training ||
(BatchnormSpatialPersistentEnabled() &&
DataTypeToEnum<T>::value == DT_HALF && use_reserved_space);
#else
// fast NHWC implementation is a CUDA only feature
const bool fast_nhwc_batch_norm = false;
#endif
// If input tensor is in NHWC format, and we have a fast cuDNN
// implementation, there is no need to do data format conversion.
TensorFormat compute_format =
fast_nhwc_batch_norm && tensor_format == FORMAT_NHWC ? FORMAT_NHWC
: FORMAT_NCHW;
VLOG(2) << "FusedBatchNorm:"
<< " batch_size: " << batch_size << " channels: " << channels
<< " height: " << height << " width:" << width
<< " x shape: " << x.shape().DebugString()
<< " scale shape: " << scale.shape().DebugString()
<< " offset shape: " << offset.shape().DebugString()
<< " activation mode: " << ToString(activation_mode)
<< " tensor format: " << ToString(tensor_format)
<< " compute format: " << ToString(compute_format);
auto maybe_make_dummy_output = [context, use_reserved_space]() -> Status {
if (use_reserved_space) {
Tensor* dummy_reserve_space = nullptr;
return context->allocate_output(5, {}, &dummy_reserve_space);
}
return Status::OK();
};
// If input is empty, return NaN mean/variance
if (x.shape().num_elements() == 0) {
OP_REQUIRES_OK(context, maybe_make_dummy_output());
functor::SetNanFunctor<U> f;
f(context->eigen_device<GPUDevice>(), batch_mean->flat<U>());
f(context->eigen_device<GPUDevice>(), batch_var->flat<U>());
return;
}
// In inference mode we use custom CUDA kernel, because cuDNN does not
// support side input and activations for inference.
const bool has_side_input = side_input != nullptr;
const bool has_activation =
activation_mode != FusedBatchNormActivationMode::kIdentity;
if (!is_training && (has_side_input || has_activation)) {
OP_REQUIRES_OK(context, maybe_make_dummy_output());
FusedBatchNormInferenceFunctor<GPUDevice, T, U> inference_functor;
if (has_side_input) {
inference_functor(context, tensor_format, x.tensor<T, 4>(),
scale.vec<U>(), offset.vec<U>(),
estimated_mean.vec<U>(), estimated_variance.vec<U>(),
side_input->tensor<T, 4>(), epsilon, activation_mode,
y->tensor<T, 4>());
} else {
typename TTypes<T, 4>::ConstTensor empty_tensor(nullptr, 0, 0, 0, 0);
inference_functor(context, tensor_format, x.tensor<T, 4>(),
scale.vec<U>(), offset.vec<U>(),
estimated_mean.vec<U>(), estimated_variance.vec<U>(),
empty_tensor, epsilon, activation_mode,
y->tensor<T, 4>());
}
return;
}
Tensor x_maybe_transformed = x;
Tensor x_transformed;
Tensor y_transformed;
se::DeviceMemory<T> y_ptr;
if (tensor_format == compute_format) {
y_ptr = StreamExecutorUtil::AsDeviceMemory<T>(*y);
} else if (tensor_format == FORMAT_NHWC && compute_format == FORMAT_NCHW) {
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(compute_format, batch_size,
height, width, channels),
&x_transformed));
functor::NHWCToNCHW<GPUDevice, T, 4>()(
context->eigen_device<GPUDevice>(),
const_cast<const Tensor&>(x_maybe_transformed).tensor<T, 4>(),
x_transformed.tensor<T, 4>());
x_maybe_transformed = x_transformed;
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(compute_format, batch_size,
height, width, channels),
&y_transformed));
y_ptr = StreamExecutorUtil::AsDeviceMemory<T>(y_transformed);
} else {
context->SetStatus(errors::Internal(
"Unsupported tensor format: ", ToString(tensor_format),
" and compute format: ", ToString(compute_format)));
return;
}
const se::dnn::DataLayout data_layout =
compute_format == FORMAT_NHWC ? se::dnn::DataLayout::kBatchYXDepth
: se::dnn::DataLayout::kBatchDepthYX;
se::dnn::BatchDescriptor x_desc;
x_desc.set_count(batch_size)
.set_feature_map_count(channels)
.set_height(height)
.set_width(width)
.set_layout(data_layout);
se::dnn::BatchDescriptor scale_offset_desc;
scale_offset_desc.set_count(1)
.set_feature_map_count(channels)
.set_height(1)
.set_width(1)
.set_layout(se::dnn::DataLayout::kBatchDepthYX);
auto x_ptr = StreamExecutorUtil::AsDeviceMemory<T>(x_maybe_transformed);
auto scale_ptr = StreamExecutorUtil::AsDeviceMemory<U>(scale);
auto offset_ptr = StreamExecutorUtil::AsDeviceMemory<U>(offset);
auto estimated_mean_ptr =
StreamExecutorUtil::AsDeviceMemory<U>(estimated_mean);
auto estimated_variance_ptr =
StreamExecutorUtil::AsDeviceMemory<U>(estimated_variance);
auto side_input_ptr =
side_input != nullptr
? StreamExecutorUtil::AsDeviceMemory<U>(*side_input)
: se::DeviceMemory<U>();
auto batch_mean_ptr = StreamExecutorUtil::AsDeviceMemory<U>(*batch_mean);
auto batch_var_ptr = StreamExecutorUtil::AsDeviceMemory<U>(*batch_var);
auto saved_mean_ptr = StreamExecutorUtil::AsDeviceMemory<U>(*saved_mean);
auto saved_inv_var_ptr =
StreamExecutorUtil::AsDeviceMemory<U>(*saved_inv_var);
std::unique_ptr<functor::CudnnBatchNormAllocatorInOutput<U>>
reserve_space_allocator;
std::unique_ptr<functor::CudnnBatchNormAllocatorInTemp<uint8>>
workspace_allocator;
if (use_reserved_space) {
reserve_space_allocator.reset(
new functor::CudnnBatchNormAllocatorInOutput<U>(context, 5));
workspace_allocator.reset(
new functor::CudnnBatchNormAllocatorInTemp<uint8>(context));
}
if (!batch_mean->SharesBufferWith(estimated_mean) &&
exponential_avg_factor != 1.0f) {
OP_REQUIRES(
context,
stream
->ThenMemcpyD2D(&batch_mean_ptr, estimated_mean_ptr,
estimated_mean.NumElements() * sizeof(U))
.ok(),
errors::Internal("MatrixTriangularSolveOp: failed to copy rhs "
"from device"));
}
if (!batch_var->SharesBufferWith(estimated_variance) &&
exponential_avg_factor != 1.0f) {
OP_REQUIRES(
context,
stream
->ThenMemcpyD2D(&batch_var_ptr, estimated_variance_ptr,
estimated_variance.NumElements() * sizeof(U))
.ok(),
errors::Internal("MatrixTriangularSolveOp: failed to copy rhs "
"from device"));
}
bool cudnn_launch_status =
stream
->ThenBatchNormalizationForward(
x_ptr, scale_ptr, offset_ptr, estimated_mean_ptr,
estimated_variance_ptr, side_input_ptr, x_desc,
scale_offset_desc, static_cast<double>(epsilon),
static_cast<double>(exponential_avg_factor),
AsDnnActivationMode(activation_mode), &y_ptr, &batch_mean_ptr,
&batch_var_ptr, &saved_mean_ptr, &saved_inv_var_ptr,
is_training, reserve_space_allocator.get(),
workspace_allocator.get())
.ok();
if (!cudnn_launch_status) {
context->SetStatus(
errors::Internal("cuDNN launch failure : input shape (",
x.shape().DebugString(), ")"));
return;
}
if (tensor_format == FORMAT_NHWC && compute_format == FORMAT_NCHW) {
functor::NCHWToNHWC<GPUDevice, T, 4>()(
context->eigen_device<GPUDevice>(),
const_cast<const Tensor&>(y_transformed).tensor<T, 4>(),
y->tensor<T, 4>());
}
}
};
template <typename T, typename U>
struct FusedBatchNormGrad<GPUDevice, T, U> {
void operator()(OpKernelContext* context, const Tensor& y_backprop,
const Tensor& x, const Tensor& scale, const Tensor* offset,
const Tensor& mean, const Tensor& inv_variance,
const Tensor* y, U epsilon,
FusedBatchNormActivationMode activation_mode,
Tensor* x_backprop, Tensor* scale_backprop,
Tensor* offset_backprop, Tensor* side_input_backprop,
bool use_reserved_space, TensorFormat tensor_format) {
auto* stream = context->op_device_context()->stream();
OP_REQUIRES(context, stream, errors::Internal("No GPU stream available"));
const int64 batch_size = GetTensorDim(x, tensor_format, 'N');
const int64 channels = GetTensorDim(x, tensor_format, 'C');
const int64 height = GetTensorDim(x, tensor_format, 'H');
const int64 width = GetTensorDim(x, tensor_format, 'W');
#if GOOGLE_CUDA
// Check if cuDNN batch normalization has a fast NHWC implementation:
// (1) Tensorflow enabled batchnorm spatial persistence, and
// FusedBatchNormGradV3 passed non-null reserve space and allocator.
const bool fast_nhwc_batch_norm = BatchnormSpatialPersistentEnabled() &&
DataTypeToEnum<T>::value == DT_HALF &&
use_reserved_space;
#else
// fast NHWC implementation is a CUDA only feature
const bool fast_nhwc_batch_norm = false;
#endif
// If input tensor is in NHWC format, and we have a fast cuDNN
// implementation, there is no need to do data format conversion.
TensorFormat compute_format =
fast_nhwc_batch_norm && tensor_format == FORMAT_NHWC ? FORMAT_NHWC
: FORMAT_NCHW;
VLOG(2) << "FusedBatchNormGrad:"
<< " batch_size: " << batch_size << " channels: " << channels
<< " height: " << height << " width: " << width
<< " y_backprop shape: " << y_backprop.shape().DebugString()
<< " x shape: " << x.shape().DebugString()
<< " scale shape: " << scale.shape().DebugString()
<< " activation mode: " << ToString(activation_mode)
<< " tensor format: " << ToString(tensor_format)
<< " compute format: " << ToString(compute_format);
// Inputs
Tensor y_backprop_maybe_transformed = y_backprop;
Tensor x_maybe_transformed = x;
Tensor y_backprop_transformed;
Tensor x_transformed;
// Outputs
Tensor x_backprop_transformed;
se::DeviceMemory<T> x_backprop_ptr;
if (tensor_format == compute_format) {
x_backprop_ptr = StreamExecutorUtil::AsDeviceMemory<T>(*x_backprop);
} else if (tensor_format == FORMAT_NHWC && compute_format == FORMAT_NCHW) {
// Transform inputs from 'NHWC' to 'NCHW'
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NCHW, batch_size,
height, width, channels),
&y_backprop_transformed));
functor::NHWCToNCHW<GPUDevice, T, 4>()(
context->eigen_device<GPUDevice>(),
const_cast<const Tensor&>(y_backprop_maybe_transformed)
.tensor<T, 4>(),
y_backprop_transformed.tensor<T, 4>());
y_backprop_maybe_transformed = y_backprop_transformed;
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NCHW, batch_size,
height, width, channels),
&x_transformed));
functor::NHWCToNCHW<GPUDevice, T, 4>()(
context->eigen_device<GPUDevice>(),
const_cast<const Tensor&>(x_maybe_transformed).tensor<T, 4>(),
x_transformed.tensor<T, 4>());
x_maybe_transformed = x_transformed;
// Allocate memory for transformed outputs in 'NCHW'
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NCHW, batch_size,
height, width, channels),
&x_backprop_transformed));
x_backprop_ptr =
StreamExecutorUtil::AsDeviceMemory<T>(x_backprop_transformed);
} else {
context->SetStatus(errors::Internal(
"Unsupported tensor format: ", ToString(tensor_format),
" and compute format: ", ToString(compute_format)));
return;
}
const se::dnn::DataLayout data_layout =
compute_format == FORMAT_NHWC ? se::dnn::DataLayout::kBatchYXDepth
: se::dnn::DataLayout::kBatchDepthYX;
se::dnn::BatchDescriptor x_desc;
x_desc.set_count(batch_size)
.set_feature_map_count(channels)
.set_height(height)
.set_width(width)
.set_layout(data_layout);
se::dnn::BatchDescriptor scale_offset_desc;
scale_offset_desc.set_count(1)
.set_feature_map_count(channels)
.set_height(1)
.set_width(1)
.set_layout(se::dnn::DataLayout::kBatchDepthYX);
auto y_backprop_ptr =
StreamExecutorUtil::AsDeviceMemory<T>(y_backprop_maybe_transformed);
auto x_ptr = StreamExecutorUtil::AsDeviceMemory<T>(x_maybe_transformed);
auto scale_ptr = StreamExecutorUtil::AsDeviceMemory<U>(scale);
auto offset_ptr = offset != nullptr
? StreamExecutorUtil::AsDeviceMemory<U>(*offset)
: se::DeviceMemory<U>();
auto mean_ptr = StreamExecutorUtil::AsDeviceMemory<U>(mean);
auto inv_variance_ptr = StreamExecutorUtil::AsDeviceMemory<U>(inv_variance);
auto y_ptr = y != nullptr ? StreamExecutorUtil::AsDeviceMemory<T>(*y)
: se::DeviceMemory<T>();
auto scale_backprop_ptr =
StreamExecutorUtil::AsDeviceMemory<U>(*scale_backprop);
auto offset_backprop_ptr =
StreamExecutorUtil::AsDeviceMemory<U>(*offset_backprop);
auto side_input_backprop_ptr =
side_input_backprop != nullptr
? StreamExecutorUtil::AsDeviceMemory<T>(*side_input_backprop)
: se::DeviceMemory<T>();
std::unique_ptr<functor::CudnnBatchNormAllocatorInTemp<uint8>>
workspace_allocator;
DeviceMemory<uint8>* reserve_space_data_ptr = nullptr;
DeviceMemory<uint8> reserve_space_data;
#if CUDNN_VERSION >= 7402
if (use_reserved_space) {
const Tensor& reserve_space = context->input(5);
workspace_allocator.reset(
new functor::CudnnBatchNormAllocatorInTemp<uint8>(context));
// the cudnn kernel outputs inverse variance in forward and reuse it in
// backward
if (reserve_space.dims() != 0) {
reserve_space_data = functor::CastDeviceMemory<uint8, U>(
const_cast<Tensor*>(&reserve_space));
reserve_space_data_ptr = &reserve_space_data;
}
}
#endif // CUDNN_VERSION >= 7402
bool cudnn_launch_status =
stream
->ThenBatchNormalizationBackward(
y_backprop_ptr, x_ptr, scale_ptr, offset_ptr, mean_ptr,
inv_variance_ptr, y_ptr, x_desc, scale_offset_desc,
static_cast<double>(epsilon),
AsDnnActivationMode(activation_mode), &x_backprop_ptr,
&scale_backprop_ptr, &offset_backprop_ptr,
&side_input_backprop_ptr, reserve_space_data_ptr,
workspace_allocator.get())
.ok();
if (!cudnn_launch_status) {
context->SetStatus(
errors::Internal("cuDNN launch failure : input shape (",
x.shape().DebugString(), ")"));
}
if (tensor_format == FORMAT_NHWC && compute_format == FORMAT_NCHW) {
functor::NCHWToNHWC<GPUDevice, T, 4>()(
context->eigen_device<GPUDevice>(),
const_cast<const Tensor&>(x_backprop_transformed).tensor<T, 4>(),
x_backprop->tensor<T, 4>());
}
}
};
// Forward declarations of the functor specializations for GPU.
#define DECLARE_GPU_SPEC(T, U) \
template <> \
void FusedBatchNormFreezeGrad<GPUDevice, T, U>::operator()( \
OpKernelContext* context, const Tensor& y_backprop_input, \
const Tensor& x_input, const Tensor& scale_input, \
const Tensor& mean_input, const Tensor& variance_input, U epsilon, \
Tensor* x_backprop_output, Tensor* scale_backprop_output, \
Tensor* offset_backprop_output); \
extern template struct FusedBatchNormFreezeGrad<GPUDevice, T, U>; \
template <> \
void FusedBatchNormInferenceFunctor<GPUDevice, T, U>::operator()( \
OpKernelContext* context, TensorFormat tensor_format, \
typename TTypes<T, 4>::ConstTensor in, \
typename TTypes<U>::ConstVec scale, typename TTypes<U>::ConstVec offset, \
typename TTypes<U>::ConstVec estimated_mean, \
typename TTypes<U>::ConstVec estimated_variance, \
typename TTypes<T, 4>::ConstTensor side_input, U epsilon, \
FusedBatchNormActivationMode activation_mode, \
typename TTypes<T, 4>::Tensor out); \
extern template struct FusedBatchNormInferenceFunctor<GPUDevice, T, U>;
DECLARE_GPU_SPEC(float, float);
DECLARE_GPU_SPEC(Eigen::half, float);
#undef DECLARE_GPU_SPEC
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace functor
template <typename Device, typename T, typename U>
class FusedBatchNormOpBase : public OpKernel {
using FbnActivationMode = functor::FusedBatchNormActivationMode;
protected:
explicit FusedBatchNormOpBase(OpKernelConstruction* context,
bool is_batch_norm_ex = false)
: OpKernel(context) {
float epsilon;
OP_REQUIRES_OK(context, context->GetAttr("epsilon", &epsilon));
epsilon_ = U(epsilon);
float exponential_avg_factor;
OP_REQUIRES_OK(context, context->GetAttr("exponential_avg_factor",
&exponential_avg_factor));
exponential_avg_factor_ = U(exponential_avg_factor);
string tensor_format;
OP_REQUIRES_OK(context, context->GetAttr("data_format", &tensor_format));
OP_REQUIRES(context, FormatFromString(tensor_format, &tensor_format_),
errors::InvalidArgument("Invalid data format"));
OP_REQUIRES_OK(context, context->GetAttr("is_training", &is_training_));
if (!is_batch_norm_ex) {
has_side_input_ = false;
activation_mode_ = FbnActivationMode::kIdentity;
} else {
OP_REQUIRES_OK(context, ParseActivationMode(context, &activation_mode_));
int num_side_inputs;
OP_REQUIRES_OK(context,
context->GetAttr("num_side_inputs", &num_side_inputs));
OP_REQUIRES(context, num_side_inputs >= 0 && num_side_inputs <= 1,
errors::InvalidArgument(
"FusedBatchNorm accepts at most one side input."));
has_side_input_ = (num_side_inputs == 1);
if (has_side_input_ && is_training_) {
OP_REQUIRES(
context, activation_mode_ != FbnActivationMode::kIdentity,
errors::InvalidArgument("Identity activation is not supported with "
"non-empty side input"));
}
}
if (activation_mode_ != FbnActivationMode::kIdentity && is_training_) {
// NOTE(ezhulenev): Following requirements are coming from implementation
// details of cudnnBatchNormalizationForwardTrainingEx used in training
// mode. In inference mode we call custom CUDA kernel that supports all
// data formats and data types.
OP_REQUIRES(context, DataTypeToEnum<T>::value == DT_HALF,
errors::InvalidArgument("FusedBatchNorm with activation "
"supports only DT_HALF data type."));
OP_REQUIRES(context, tensor_format_ == FORMAT_NHWC,
errors::InvalidArgument("FusedBatchNorm with activation "
"supports only NHWC tensor format."));
OP_REQUIRES(context, functor::BatchnormSpatialPersistentEnabled(),
errors::InvalidArgument(
"FusedBatchNorm with activation must run with cuDNN "
"spatial persistence mode enabled."));
}
}
// If use_reserved_space is true, we need to handle the 5th output (a reserved
// space) and a new cudnn batch norm will be called if the version > 7.4.2.
// If use_reserved_space is false, we don't have 5th output.
virtual void ComputeWithReservedSpace(OpKernelContext* context,
bool use_reserved_space) {
Tensor x = context->input(0);
const Tensor& scale = context->input(1);
const Tensor& offset = context->input(2);
const Tensor& estimated_mean = context->input(3);
const Tensor& estimated_variance = context->input(4);
const Tensor* side_input = has_side_input_ ? &context->input(5) : nullptr;
OP_REQUIRES(context, x.dims() == 4 || x.dims() == 5,
errors::InvalidArgument("input must be 4 or 5-dimensional",
x.shape().DebugString()));
OP_REQUIRES(context, scale.dims() == 1,
errors::InvalidArgument("scale must be 1-dimensional",
scale.shape().DebugString()));
OP_REQUIRES(context, offset.dims() == 1,
errors::InvalidArgument("offset must be 1-dimensional",
offset.shape().DebugString()));
OP_REQUIRES(context, estimated_mean.dims() == 1,
errors::InvalidArgument("estimated_mean must be 1-dimensional",
estimated_mean.shape().DebugString()));
OP_REQUIRES(
context, estimated_variance.dims() == 1,
errors::InvalidArgument("estimated_variance must be 1-dimensional",
estimated_variance.shape().DebugString()));
bool use_reshape = (x.dims() == 5);
auto x_shape = x.shape();
TensorShape dest_shape;
if (use_reshape) {
const int64 in_batch = GetTensorDim(x, tensor_format_, 'N');
int64 in_planes = GetTensorDim(x, tensor_format_, '0');
int64 in_rows = GetTensorDim(x, tensor_format_, '1');
int64 in_cols = GetTensorDim(x, tensor_format_, '2');
const int64 in_depth = GetTensorDim(x, tensor_format_, 'C');
dest_shape = ShapeFromFormat(tensor_format_, in_batch,
{{in_planes, in_rows * in_cols}}, in_depth);
OP_REQUIRES(context, x.CopyFrom(x, dest_shape),
errors::InvalidArgument("Error during tensor copy."));
}
if (has_side_input_) {
OP_REQUIRES(context, side_input->shape() == x.shape(),
errors::InvalidArgument(
"side_input shape must be equal to input shape: ",
side_input->shape().DebugString(),
" != ", x.shape().DebugString()));
}
if (activation_mode_ != FbnActivationMode::kIdentity) {
// NOTE(ezhulenev): This requirement is coming from implementation
// details of cudnnBatchNormalizationForwardTrainingEx.
OP_REQUIRES(
context, !is_training_ || x.dim_size(3) % 4 == 0,
errors::InvalidArgument("FusedBatchNorm with activation requires "
"channel dimension to be a multiple of 4."));
}
Tensor* y = nullptr;
auto alloc_shape = use_reshape ? dest_shape : x_shape;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{0}, 0, alloc_shape, &y));
Tensor* batch_mean = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{3}, 1, scale.shape(), &batch_mean));
Tensor* batch_var = nullptr;
OP_REQUIRES_OK(context, context->forward_input_or_allocate_output(
{4}, 2, scale.shape(), &batch_var));
Tensor* saved_mean = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(3, scale.shape(), &saved_mean));
Tensor* saved_maybe_inv_var = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(4, scale.shape(),
&saved_maybe_inv_var));
if (is_training_) {
functor::FusedBatchNorm<Device, T, U, true>()(
context, x, scale, offset, estimated_mean, estimated_variance,
side_input, epsilon_, exponential_avg_factor_, activation_mode_, y,
batch_mean, batch_var, saved_mean, saved_maybe_inv_var,
tensor_format_, use_reserved_space);
} else {
functor::FusedBatchNorm<Device, T, U, false>()(
context, x, scale, offset, estimated_mean, estimated_variance,
side_input, epsilon_, exponential_avg_factor_, activation_mode_, y,
batch_mean, batch_var, saved_mean, saved_maybe_inv_var,
tensor_format_, use_reserved_space);
}
if (use_reshape) {
OP_REQUIRES(context, y->CopyFrom(*y, x_shape),
errors::InvalidArgument("Error during tensor copy."));
}
}
private:
U epsilon_;
U exponential_avg_factor_;
TensorFormat tensor_format_;
bool is_training_;
bool has_side_input_;
FbnActivationMode activation_mode_;
};
template <typename Device, typename T, typename U>
class FusedBatchNormOp : public FusedBatchNormOpBase<Device, T, U> {
public:
explicit FusedBatchNormOp(OpKernelConstruction* context)
: FusedBatchNormOpBase<Device, T, U>(context) {}
void Compute(OpKernelContext* context) override {
FusedBatchNormOpBase<Device, T, U>::ComputeWithReservedSpace(context,
false);
}
};
template <typename Device, typename T, typename U>
class FusedBatchNormOpV3 : public FusedBatchNormOpBase<Device, T, U> {
public:
explicit FusedBatchNormOpV3(OpKernelConstruction* context)
: FusedBatchNormOpBase<Device, T, U>(context) {}
void Compute(OpKernelContext* context) override {
FusedBatchNormOpBase<Device, T, U>::ComputeWithReservedSpace(context, true);
}
};
template <typename Device, typename T, typename U>
class FusedBatchNormOpEx : public FusedBatchNormOpBase<Device, T, U> {
static constexpr bool kWithSideInputAndActivation = true;
public:
explicit FusedBatchNormOpEx(OpKernelConstruction* context)
: FusedBatchNormOpBase<Device, T, U>(context,
kWithSideInputAndActivation) {}
void Compute(OpKernelContext* context) override {
FusedBatchNormOpBase<Device, T, U>::ComputeWithReservedSpace(context, true);
}
};
template <typename Device, typename T, typename U>
class FusedBatchNormGradOpBase : public OpKernel {
using FbnActivationMode = functor::FusedBatchNormActivationMode;
protected:
explicit FusedBatchNormGradOpBase(OpKernelConstruction* context,
bool is_batch_norm_grad_ex = false)
: OpKernel(context) {
float epsilon;
OP_REQUIRES_OK(context, context->GetAttr("epsilon", &epsilon));
epsilon_ = U(epsilon);
string tensor_format;
OP_REQUIRES_OK(context, context->GetAttr("data_format", &tensor_format));
OP_REQUIRES(context, FormatFromString(tensor_format, &tensor_format_),
errors::InvalidArgument("Invalid data format"));
OP_REQUIRES_OK(context, context->GetAttr("is_training", &is_training_));
if (!is_batch_norm_grad_ex) {
has_side_input_ = false;
activation_mode_ = FbnActivationMode::kIdentity;
} else {
OP_REQUIRES_OK(context, ParseActivationMode(context, &activation_mode_));
int num_side_inputs;
OP_REQUIRES_OK(context,
context->GetAttr("num_side_inputs", &num_side_inputs));
OP_REQUIRES(context, num_side_inputs >= 0 && num_side_inputs <= 1,
errors::InvalidArgument(
"FusedBatchNormGrad accepts at most one side input."));
has_side_input_ = (num_side_inputs == 1);
if (has_side_input_ && is_training_) {
OP_REQUIRES(
context, activation_mode_ != FbnActivationMode::kIdentity,
errors::InvalidArgument("Identity activation is not supported with "
"non-empty side input"));
}
}
if (activation_mode_ != FbnActivationMode::kIdentity && is_training_) {
// NOTE(kaixih@nvidia): Following requirements are coming from
// implementation details of cudnnBatchNormalizationBackwardEx used in
// training mode.
OP_REQUIRES(context, DataTypeToEnum<T>::value == DT_HALF,
errors::InvalidArgument("FusedBatchNormGrad with activation "
"supports only DT_HALF data type."));
OP_REQUIRES(context, tensor_format_ == FORMAT_NHWC,
errors::InvalidArgument("FusedBatchNormGrad with activation "
"supports only NHWC tensor format."));
OP_REQUIRES(context, functor::BatchnormSpatialPersistentEnabled(),
errors::InvalidArgument(
"FusedBatchNormGrad with activation must run with cuDNN "
"spatial persistence mode enabled."));
}
}
virtual void ComputeWithReservedSpace(OpKernelContext* context,
bool use_reserved_space) {
Tensor y_backprop = context->input(0);
Tensor x = context->input(1);
const Tensor& scale = context->input(2);
// When is_training=True, batch mean and variance/inverted variance are
// saved in the forward pass to be reused here. When is_training=False,
// population mean and variance need to be forwarded here to compute the
// gradients.
const Tensor& saved_mean_or_pop_mean = context->input(3);
// The Eigen implementation saves variance in the forward pass, while cuDNN
// saves inverted variance.
const Tensor& saved_maybe_inv_var_or_pop_var = context->input(4);
bool use_activation = activation_mode_ != FbnActivationMode::kIdentity;
const Tensor* offset = use_activation ? &context->input(6) : nullptr;
const Tensor* y = use_activation ? &context->input(7) : nullptr;
OP_REQUIRES(context, y_backprop.dims() == 4 || y_backprop.dims() == 5,
errors::InvalidArgument("input must be 4 or 5-dimensional",
y_backprop.shape().DebugString()));
OP_REQUIRES(context, x.dims() == 4 || x.dims() == 5,
errors::InvalidArgument("input must be 4 or 5-dimensional",
x.shape().DebugString()));
OP_REQUIRES(context, scale.dims() == 1,
errors::InvalidArgument("scale must be 1-dimensional",
scale.shape().DebugString()));
OP_REQUIRES(
context, saved_mean_or_pop_mean.dims() == 1,
errors::InvalidArgument("saved mean must be 1-dimensional",
saved_mean_or_pop_mean.shape().DebugString()));
OP_REQUIRES(context, saved_maybe_inv_var_or_pop_var.dims() == 1,
errors::InvalidArgument(
"saved variance must be 1-dimensional",
saved_maybe_inv_var_or_pop_var.shape().DebugString()));
if (use_activation) {
OP_REQUIRES(
context, x.dim_size(3) % 4 == 0,
errors::InvalidArgument("FusedBatchNormGrad with activation requires "
"channel dimension to be a multiple of 4."));
OP_REQUIRES(context, offset->dims() == 1,
errors::InvalidArgument("offset must be 1-dimensional",
offset->shape().DebugString()));
}
bool use_reshape = (x.dims() == 5);
auto x_shape = x.shape();
TensorShape dest_shape;
if (use_reshape) {
const int64 in_batch = GetTensorDim(x, tensor_format_, 'N');
int64 in_planes = GetTensorDim(x, tensor_format_, '0');
int64 in_rows = GetTensorDim(x, tensor_format_, '1');
int64 in_cols = GetTensorDim(x, tensor_format_, '2');
const int64 in_depth = GetTensorDim(x, tensor_format_, 'C');
dest_shape = ShapeFromFormat(tensor_format_, in_batch,
{{in_planes, in_rows * in_cols}}, in_depth);
OP_REQUIRES(context, x.CopyFrom(x, dest_shape),
errors::InvalidArgument("Error during tensor copy."));
OP_REQUIRES(context, y_backprop.CopyFrom(y_backprop, dest_shape),
errors::InvalidArgument("Error during tensor copy."));
}
Tensor* x_backprop = nullptr;
auto alloc_shape = use_reshape ? dest_shape : x_shape;
OP_REQUIRES_OK(context,
context->allocate_output(0, alloc_shape, &x_backprop));
const TensorShape& scale_offset_shape = scale.shape();
Tensor* scale_backprop = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(1, scale_offset_shape,
&scale_backprop));
Tensor* offset_backprop = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(2, scale_offset_shape,
&offset_backprop));
// Two placeholders for estimated_mean and estimated_variance, which are
// used for inference and thus not needed here for gradient computation.
// They are filled with zeros so as to avoid NaN outputs.
Tensor* placeholder_1 = nullptr;
OP_REQUIRES_OK(
context, context->allocate_output(3, TensorShape({0}), &placeholder_1));
Tensor* placeholder_2 = nullptr;
OP_REQUIRES_OK(
context, context->allocate_output(4, TensorShape({0}), &placeholder_2));
Tensor* side_input_backprop = nullptr;
if (has_side_input_) {
OP_REQUIRES_OK(context, context->allocate_output(5, alloc_shape,
&side_input_backprop));
}
// If input is empty, set gradients w.r.t scale/offset to zero.
if (x.shape().num_elements() == 0) {
functor::SetZeroFunctor<Device, U> f;
f(context->eigen_device<Device>(), scale_backprop->flat<U>());
f(context->eigen_device<Device>(), offset_backprop->flat<U>());
return;
}
if (is_training_) {
functor::FusedBatchNormGrad<Device, T, U>()(
context, y_backprop, x, scale, offset, saved_mean_or_pop_mean,
saved_maybe_inv_var_or_pop_var, y, epsilon_, activation_mode_,
x_backprop, scale_backprop, offset_backprop, side_input_backprop,
use_reserved_space, tensor_format_);
} else {
OP_REQUIRES(
context,
activation_mode_ == FbnActivationMode::kIdentity && !has_side_input_,
errors::InvalidArgument(
"FusedBatchNormGrad with activation is only supported "
"when is_training=True."));
// Necessary layout conversion is currently done in python.
OP_REQUIRES(context, tensor_format_ == FORMAT_NHWC,
errors::InvalidArgument(
"The implementation of "
"FusedBatchNormGrad with is_training=False only support "
"NHWC tensor format for now."));
functor::FusedBatchNormFreezeGrad<Device, T, U>()(
context, y_backprop, x, scale, saved_mean_or_pop_mean,
saved_maybe_inv_var_or_pop_var, epsilon_, x_backprop, scale_backprop,
offset_backprop);
}
if (use_reshape) {
OP_REQUIRES(context, x_backprop->CopyFrom(*x_backprop, x_shape),
errors::InvalidArgument("Error during tensor copy."));
}
}
private:
U epsilon_;
TensorFormat tensor_format_;
bool is_training_;
bool has_side_input_;
FbnActivationMode activation_mode_;
};
template <typename Device, typename T, typename U>
class FusedBatchNormGradOp : public FusedBatchNormGradOpBase<Device, T, U> {
public:
explicit FusedBatchNormGradOp(OpKernelConstruction* context)
: FusedBatchNormGradOpBase<Device, T, U>(context) {}
void Compute(OpKernelContext* context) override {
FusedBatchNormGradOpBase<Device, T, U>::ComputeWithReservedSpace(context,
false);
}
};
template <typename Device, typename T, typename U>
class FusedBatchNormGradOpV3 : public FusedBatchNormGradOpBase<Device, T, U> {
public:
explicit FusedBatchNormGradOpV3(OpKernelConstruction* context)
: FusedBatchNormGradOpBase<Device, T, U>(context) {}
void Compute(OpKernelContext* context) override {
FusedBatchNormGradOpBase<Device, T, U>::ComputeWithReservedSpace(context,
true);
}
};
template <typename Device, typename T, typename U>
class FusedBatchNormGradOpEx : public FusedBatchNormGradOpBase<Device, T, U> {
static constexpr bool kWithSideInputAndActivation = true;
public:
explicit FusedBatchNormGradOpEx(OpKernelConstruction* context)
: FusedBatchNormGradOpBase<Device, T, U>(context,
kWithSideInputAndActivation) {}
void Compute(OpKernelContext* context) override {
FusedBatchNormGradOpBase<Device, T, U>::ComputeWithReservedSpace(context,
true);
}
};
REGISTER_KERNEL_BUILDER(
Name("FusedBatchNorm").Device(DEVICE_CPU).TypeConstraint<float>("T"),
FusedBatchNormOp<CPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(
Name("FusedBatchNormGrad").Device(DEVICE_CPU).TypeConstraint<float>("T"),
FusedBatchNormGradOp<CPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV2")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOp<CPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV2")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOp<CPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV2")
.Device(DEVICE_CPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOp<CPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV2")
.Device(DEVICE_CPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOp<CPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV3")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOpV3<CPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV3")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOpV3<CPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV3")
.Device(DEVICE_CPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOpV3<CPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV3")
.Device(DEVICE_CPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOpV3<CPUDevice, Eigen::half, float>);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
REGISTER_KERNEL_BUILDER(
Name("FusedBatchNorm").Device(DEVICE_GPU).TypeConstraint<float>("T"),
FusedBatchNormOp<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(
Name("FusedBatchNormGrad").Device(DEVICE_GPU).TypeConstraint<float>("T"),
FusedBatchNormGradOp<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV2")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOp<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV2")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOp<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV2")
.Device(DEVICE_GPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOp<GPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV2")
.Device(DEVICE_GPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOp<GPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV3")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOpV3<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("_FusedBatchNormEx")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOpEx<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV3")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOpV3<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("_FusedBatchNormGradEx")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOpEx<GPUDevice, float, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormV3")
.Device(DEVICE_GPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOpV3<GPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("_FusedBatchNormEx")
.Device(DEVICE_GPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormOpEx<GPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("FusedBatchNormGradV3")
.Device(DEVICE_GPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOpV3<GPUDevice, Eigen::half, float>);
REGISTER_KERNEL_BUILDER(Name("_FusedBatchNormGradEx")
.Device(DEVICE_GPU)
.TypeConstraint<Eigen::half>("T")
.TypeConstraint<float>("U"),
FusedBatchNormGradOpEx<GPUDevice, Eigen::half, float>);
#endif
} // namespace tensorflow
|
#pragma once
#include "data_types.hpp"
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/bus/match.hpp>
#include <sdbusplus/exception.hpp>
#include <sdbusplus/message.hpp>
#include <string>
struct Loop;
namespace phosphor
{
namespace dbus
{
namespace monitoring
{
using namespace phosphor::logging;
/** @class SDBusPlus
* @brief DBus access delegate implementation for sdbusplus.
*/
class SDBusPlus
{
private:
static auto& getWatches()
{
static std::vector<sdbusplus::bus::match::match> watches;
return watches;
}
public:
static auto& getBus()
{
static auto bus = sdbusplus::bus::new_default();
return bus;
}
/** @brief Invoke a method; ignore reply. */
template <typename... Args>
static void callMethodNoReply(const std::string& busName,
const std::string& path,
const std::string& interface,
const std::string& method, Args&&... args)
{
auto reqMsg = getBus().new_method_call(
busName.c_str(), path.c_str(), interface.c_str(), method.c_str());
reqMsg.append(std::forward<Args>(args)...);
getBus().call_noreply(reqMsg);
// TODO: openbmc/openbmc#1719
// invoke these methods async, with a callback
// handler that checks for errors and logs.
}
/** @brief Invoke a method. */
template <typename... Args>
static auto callMethod(const std::string& busName, const std::string& path,
const std::string& interface,
const std::string& method, Args&&... args)
{
auto reqMsg = getBus().new_method_call(
busName.c_str(), path.c_str(), interface.c_str(), method.c_str());
reqMsg.append(std::forward<Args>(args)...);
return getBus().call(reqMsg);
}
/** @brief Invoke a method and read the response. */
template <typename Ret, typename... Args>
static auto callMethodAndRead(const std::string& busName,
const std::string& path,
const std::string& interface,
const std::string& method, Args&&... args)
{
Ret resp;
sdbusplus::message::message respMsg = callMethod<Args...>(
busName, path, interface, method, std::forward<Args>(args)...);
try
{
respMsg.read(resp);
}
catch (const sdbusplus::exception::exception& e)
{
// Empty responses are expected sometimes, and the calling
// code is set up to handle it.
}
return resp;
}
/** @brief Register a DBus signal callback. */
static auto
addMatch(const std::string& match,
const sdbusplus::bus::match::match::callback_t& callback)
{
getWatches().emplace_back(getBus(), match, callback);
}
/** @brief Look up the bus name for a path and interface */
static auto getBusName(const std::string& path,
const std::string& interface)
{
std::vector<std::string> interfaces{interface};
std::string name;
try
{
auto object = callMethodAndRead<GetObject>(
MAPPER_BUSNAME, MAPPER_PATH, MAPPER_INTERFACE, "GetObject",
path, interfaces);
if (!object.empty())
{
name = object.begin()->first;
}
}
catch (const sdbusplus::exception::exception& e)
{
// Empty responses are expected sometimes, and the calling
// code is set up to handle it.
}
return name;
}
friend Loop;
};
} // namespace monitoring
} // namespace dbus
} // namespace phosphor
|
////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <stdarg.h>
#include <Context.h>
#include <text.h>
#include <test.h>
Context context;
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
UnitTest t (11);
// Ensure environment has no influence.
unsetenv ("TASKDATA");
unsetenv ("TASKRC");
try
{
t.is (format ("pre {1} post", "mid"), "pre mid post", "format 1a");
t.is (format ("pre {1}{1} post", "mid"), "pre midmid post", "format 1b");
t.is (format ("pre {1} post", 0), "pre 0 post", "format 1c");
t.is (format ("pre {1}{1} post", 0), "pre 00 post", "format 1d");
t.is (format ("pre {1}{2} post", "one", "two"), "pre onetwo post", "format 2a");
t.is (format ("pre {2}{1} post", "one", "two"), "pre twoone post", "format 2b");
t.is (format ("pre {1}{2} post", "one", 2), "pre one2 post", "format 2c");
t.is (format ("pre {1}{2} post", 1, "two"), "pre 1two post", "format 2d");
t.is (format ("pre {1}{2} post", 1, 2), "pre 12 post", "format 2e");
t.is (format ("pre {1}{2}{3} post", "one", "two", "three"), "pre onetwothree post", "format 3a");
t.is (format ("pre {3}{1}{2} post", "one", "two", "three"), "pre threeonetwo post", "format 3b");
}
catch (const std::string& error)
{
t.diag (error);
return -1;
}
catch (...)
{
t.diag ("Unknown error.");
return -2;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
|
#ifdef __AVR_ATmega162__
#pragma once
#include "snake.h"
#include "lib/utilities/eeprom.h"
#include <stdlib.h>
#include "../lib/utilities/eeprom.h"
// Code inspired by https://codereview.stackexchange.com/questions/66481/snake-game-in-c
// All functions have been changed, some have been removed and some added
void Snake::run(){
// sets initial conditions
this->initMap();
running = true;
while(running){
//change direction
this->changeDirection();
//update map
this->update();
//Send map to screen
this->printMap();
//wait for length of difficulty
if (difficulty==1)_delay_ms(150);
if (difficulty==2)_delay_ms(100);
if (difficulty==3)_delay_ms(50);
}
// show score for 2 seconds before ending the game
uint8_t best_highscore = eepromRead((uint16_t)EEPROM_SNAKE_ADDR);
if (snakeLength - 3 > best_highscore)
{
best_highscore == snakeLength - 3;
eepromWrite((uint16_t)EEPROM_SNAKE_ADDR, best_highscore);
}
this->printScore(best_highscore);
_delay_ms(2000);
return;
}
void Snake::changeDirection(){
/*
Directions mapped like so:
UP
LEFT + RIGHT
DOWN
1
4 + 2
3
*/
// reads joystick
uint8_t newDir;
newDir = this->getJoystick();
// prevents turning 180 degrees
if(newDir == 1 && this->direction != 3) this->direction = 1;
else if(newDir == 2 && this->direction != 4) this->direction = 2;
else if(newDir == 3 && this->direction != 1) this->direction = 3;
else if(newDir == 4 && this->direction != 2) this->direction = 4;
}
uint8_t Snake::getJoystick(){
// Gets joystick object
Joystick & joystick = Joystick::getInstance();
int8_t x;
int8_t y;
// Returns direction based on input from joystick
Direction dir = joystick.read(&x, &y);
uint8_t threshold = 90;
if (x > threshold) return 2;
if (x < -threshold) return 4;
if (y > threshold) return 1;
if (y < -threshold) return 3;
return 0;
}
void Snake::update(){
// move snake head
switch (this->direction) {
case 0:
break;
case 1: this->move(0, -1);
break;
case 2: this->move(1, 0);
break;
case 3: this->move(0, 1);
break;
case 4: this->move(-1, 0);
break;
}
// Reduce snake values on map by 1
for (uint8_t i = 0; i < s; i++) {
if (map[i] > 0) map[i]--;
}
}
void Snake::move(int8_t dx,int8_t dy){
// determine new head position
uint8_t newx = headxpos + dx;
uint8_t newy = headypos + dy;
// Check if there is food at location
if (map[this->xytomapIndex(newx,newy)] == -1) {
// Increase length of snake
snakeLength++;
// Generate new food on map
this->generateFood();
}
//Game over if snake is outside map
if (newx>mapwidth-1 || newy>mapheight-1 || newx < 0 || newy < 0){
running = false;
return;
}
// Game over if crashing into snake
if (map[this->xytomapIndex(newx,newy)] > 0){
running = false;
return;
}
// Move head to new location
headxpos = newx;
headypos = newy;
map[this->xytomapIndex(headxpos,headypos)] = snakeLength + 1;
}
// Generates new food on map
void Snake::generateFood() {
uint8_t x = 0;
uint8_t y = 0;
do {
// Generate random x and y values within the map
x = rand() % (mapwidth);
y = rand() % (mapheight);
// If location is not free try again
} while (map[this->xytomapIndex(x,y)] != 0);
// Place new food
map[this->xytomapIndex(x,y)] = -1;
}
uint8_t Snake::xytomapIndex(uint8_t x,uint8_t y){
// simple comversion from 2d to 1d
return x + y * mapwidth;
}
void Snake::initMap()
{ // clears map
snakeLength = 3;
for (uint8_t i = 0;i<s;i++){
map[i] = 0;
}
this->printMap();
// Places the initual head location in middle of map
headxpos = mapwidth / 2;
headypos = mapheight / 2;
map[this->xytomapIndex(headxpos,headypos)] = 1;
// Generates first food
this->generateFood();
}
char Snake::getMapValue(int8_t value)
{
// Returns a part of snake body
if (value > 0) return 'o';
// Returns food
if (value == -1) return INDEX_APPLE + ' '; //Apple
// Returns empty space
if (value == 0) return ' ';
}
void Snake::printMap(){
// Screen init
s1.clear();
s1.goToStart();
char pmap[s+1];
// numbers to icons
for (uint8_t i = 0; i < s; i++){
pmap[i] = getMapValue(map[i]);
}
pmap[s] = '\0';
s1.writeString(pmap);
s1.render();
}
void Snake::printScore(uint8_t best_highscore){
// screen init
s1.clear();
s1.goTo(3,32);
// write game over and score
s1.writeString("GAME OVER");
s1.goTo(4,32);
char score[3];
s1.writeString("SCORE: ");
itoa(snakeLength-3, score, 10);
s1.writeString(score);
s1.goTo(5,32);
if (best_highscore < snakeLength - 3)
{
s1.writeString("NEW HIGHSCORE!");
}
else
{
s1.writeString("HIGHSCORE: ");
itoa(best_highscore, score, 10);
s1.writeString(score);
}
// set new highscore
if (snakeLength -3 > highscore) highscore = snakeLength -3;
s1.render();
}
#endif
|
/*
* Copyright Andrey Semashev 2007 - 2015.
* 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)
*/
/*!
* \file threadsafe_queue.cpp
* \author Andrey Semashev
* \date 05.11.2010
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*
* The implementation is based on algorithms published in the "Simple, Fast,
* and Practical Non-Blocking and Blocking Concurrent Queue Algorithms" article
* in PODC96 by Maged M. Michael and Michael L. Scott. Pseudocode is available here:
* http://www.cs.rochester.edu/research/synchronization/pseudocode/queues.html
*
* The lock-free version of the mentioned algorithms contain a race condition and therefore
* were not included here.
*/
#include <boost/log/detail/threadsafe_queue.hpp>
#ifndef BOOST_LOG_NO_THREADS
#include <new>
#include <boost/assert.hpp>
#include <boost/throw_exception.hpp>
#include <boost/align/aligned_alloc.hpp>
#include <boost/type_traits/alignment_of.hpp>
#include <boost/log/detail/adaptive_mutex.hpp>
#include <boost/log/detail/locks.hpp>
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace aux {
//! Generic queue implementation with two locks
class threadsafe_queue_impl_generic :
public threadsafe_queue_impl
{
private:
//! Mutex type to be used
typedef adaptive_mutex mutex_type;
/*!
* A structure that contains a pointer to the node and the associated mutex.
* The alignment below allows to eliminate false sharing, it should not be less than CPU cache line size.
*/
struct BOOST_ALIGNMENT(BOOST_LOG_CPU_CACHE_LINE_SIZE) pointer
{
//! Pointer to the either end of the queue
node_base* node;
//! Lock for access synchronization
mutex_type mutex;
// 128 bytes padding is chosen to mitigate false sharing for NetBurst CPUs, which load two cache lines in one go.
unsigned char padding[128U - (sizeof(node_base*) + sizeof(mutex_type)) % 128U];
};
private:
//! Pointer to the beginning of the queue
pointer m_Head;
//! Pointer to the end of the queue
pointer m_Tail;
public:
explicit threadsafe_queue_impl_generic(node_base* first_node)
{
set_next(first_node, NULL);
m_Head.node = m_Tail.node = first_node;
}
~threadsafe_queue_impl_generic()
{
}
node_base* reset_last_node()
{
BOOST_ASSERT(m_Head.node == m_Tail.node);
node_base* p = m_Head.node;
m_Head.node = m_Tail.node = NULL;
return p;
}
bool unsafe_empty()
{
return m_Head.node == m_Tail.node;
}
void push(node_base* p)
{
set_next(p, NULL);
exclusive_lock_guard< mutex_type > _(m_Tail.mutex);
set_next(m_Tail.node, p);
m_Tail.node = p;
}
bool try_pop(node_base*& node_to_free, node_base*& node_with_value)
{
exclusive_lock_guard< mutex_type > _(m_Head.mutex);
node_base* next = get_next(m_Head.node);
if (next)
{
// We have a node to pop
node_to_free = m_Head.node;
node_with_value = m_Head.node = next;
return true;
}
else
return false;
}
private:
BOOST_FORCEINLINE static void set_next(node_base* p, node_base* next)
{
p->next.data[0] = next;
}
BOOST_FORCEINLINE static node_base* get_next(node_base* p)
{
return static_cast< node_base* >(p->next.data[0]);
}
// Copying and assignment are closed
BOOST_DELETED_FUNCTION(threadsafe_queue_impl_generic(threadsafe_queue_impl_generic const&))
BOOST_DELETED_FUNCTION(threadsafe_queue_impl_generic& operator= (threadsafe_queue_impl_generic const&))
};
BOOST_LOG_API threadsafe_queue_impl* threadsafe_queue_impl::create(node_base* first_node)
{
return new threadsafe_queue_impl_generic(first_node);
}
BOOST_LOG_API void* threadsafe_queue_impl::operator new (std::size_t size)
{
void* p = alignment::aligned_alloc(BOOST_LOG_CPU_CACHE_LINE_SIZE, size);
if (BOOST_UNLIKELY(!p))
BOOST_THROW_EXCEPTION(std::bad_alloc());
return p;
}
BOOST_LOG_API void threadsafe_queue_impl::operator delete (void* p, std::size_t)
{
alignment::aligned_free(p);
}
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_NO_THREADS
|
/**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <gtest/gtest.h>
#include "../EpwFile.hpp"
#include "../../time/Time.hpp"
#include "../../time/Date.hpp"
#include <resources.hxx>
using namespace openstudio;
TEST(Filetypes, EpwFile)
{
try{
// LOCATION,Climate Zone 1,CA,USA,CTZRV2,725945,40.80,-124.20,-8.0,13.0
// DESIGN CONDITIONS,1,Climate Design Data 2009 ASHRAE Handbook,,Heating,12,-0.6,0.6,-4.1,2.7,5.3,-2.2,3.2,3.8,11.1,12.3,9.7,11.3,2,90,Cooling,8,6.5,21.6,15.2,19.9,15.1,18.7,14.6,16.8,19.5,16.1,18.6,15.5,17.6,4.3,320,15.9,11.4,17.5,15.1,10.8,16.8,14.4,10.3,16.2,47.3,19.8,45,18.5,43.3,17.6,1804,Extremes,9,8.2,7.4,20.8,-2.5,28.3,1.7,2.2,-3.7,29.8,-4.6,31.1,-5.6,32.3,-6.8,33.9
// TYPICAL/EXTREME PERIODS,6,Summer - Week Nearest Max Temperature For Period,Extreme,7/ 8,7/14,Summer - Week Nearest Average Temperature For Period,Typical,8/12,8/18,Winter - Week Nearest Min Temperature For Period,Extreme,1/15,1/21,Winter - Week Nearest Average Temperature For Period,Typical,1/22,1/28,Autumn - Week Nearest Average Temperature For Period,Typical,11/26,12/ 2,Spring - Week Nearest Average Temperature For Period,Typical,5/27,6/ 2
// GROUND TEMPERATURES,3,.5,,,,9.66,10.10,10.96,11.78,13.32,14.13,14.35,13.94,12.99,11.81,10.64,9.87,2,,,,10.27,10.38,10.87,11.41,12.60,13.35,13.73,13.65,13.10,12.29,11.37,10.64,4,,,,10.90,10.82,11.04,11.35,12.13,12.72,13.10,13.19,12.95,12.47,11.85,11.28
// HOLIDAYS/DAYLIGHT SAVINGS,No,0,0,0
// COMMENTS 1,California Climate Zone 01 Version 2;
// COMMENTS 2, -- Ground temps produced with a standard soil diffusivity of 2.3225760E-03 {m**2/day}
// DATA PERIODS,1,1,Data,Sunday, 1/ 1,12/31
path p = resourcesPath() / toPath("runmanager/USA_CO_Golden-NREL.724666_TMY3.epw");
EpwFile epwFile(p);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("F188656D", epwFile.checksum());
EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city());
EXPECT_EQ("CO", epwFile.stateProvinceRegion());
EXPECT_EQ("USA", epwFile.country());
EXPECT_EQ("TMY3", epwFile.dataSource());
EXPECT_EQ("724666", epwFile.wmoNumber());
EXPECT_EQ(39.74, epwFile.latitude());
EXPECT_EQ(-105.18, epwFile.longitude());
EXPECT_EQ(-7, epwFile.timeZone());
EXPECT_EQ(1829, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek());
EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate());
}catch(...){
ASSERT_TRUE(false);
}
}
TEST(Filetypes, EpwFile_Data)
{
try{
path p = resourcesPath() / toPath("runmanager/USA_CO_Golden-NREL.724666_TMY3.epw");
EpwFile epwFile(p);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("F188656D", epwFile.checksum());
EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city());
EXPECT_EQ("CO", epwFile.stateProvinceRegion());
EXPECT_EQ("USA", epwFile.country());
EXPECT_EQ("TMY3", epwFile.dataSource());
EXPECT_EQ("724666", epwFile.wmoNumber());
EXPECT_EQ(39.74, epwFile.latitude());
EXPECT_EQ(-105.18, epwFile.longitude());
EXPECT_EQ(-7, epwFile.timeZone());
EXPECT_EQ(1829, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek());
EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate());
// Up to here, everything should be the same as the first test. Now ask for the data
std::vector<EpwDataPoint> data = epwFile.data();
EXPECT_EQ(8760,data.size());
// The last data point should be for the last hour 12/31/1996, with a dry bulb temp of 4C and pressure 81100
openstudio::DateTime dateTime = data[8759].dateTime();
EXPECT_EQ(1, dateTime.date().monthOfYear().value());
EXPECT_EQ(1, dateTime.date().dayOfMonth());
// Stopgap test until things are straightened out with years
EXPECT_EQ(2010, dateTime.date().year());
//EXPECT_EQ(1997, dateTime.date().year());
EXPECT_EQ(0, dateTime.time().hours());
EXPECT_EQ(0, dateTime.time().minutes());
EXPECT_EQ(0, dateTime.time().seconds());
EXPECT_EQ(4.0,data[8759].dryBulbTemperature().get());
EXPECT_EQ(81100,data[8759].atmosphericStationPressure().get());
// Try out the alternate access functions, dew point temperature should be -1C
EXPECT_EQ(-1.0,data[8759].getFieldByName("Dew Point Temperature").get());
EXPECT_EQ(-1.0,data[8759].getField(EpwDataField("Dew Point Temperature")).get());
// The last data point should not have a liquid precipitation depth
EXPECT_FALSE(data[8759].getFieldByName("Liquid Precipitation Depth"));
// Get the data as strings
std::vector<std::string> epwStrings = data[8759].toEpwStrings();
ASSERT_EQ(35, epwStrings.size());
std::vector<std::string> known = { "1996", "12", "31", "24", "0",
"?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9*9*9", "4.0", "-1.0",
"69", "81100", "0", "0", "294", "0.000000", "0", "0", "0", "0", "0",
"0", "130", "6.200000", "9", "9", "48.3", "7500", "9", "999999999",
"60", "0.0310", "0", "88", "0.210", "999", "99" };
for (unsigned i = 0; i < 35; i++) {
EXPECT_EQ(known[i], epwStrings[i]);
}
// Get a time series
boost::optional<openstudio::TimeSeries> series = epwFile.getTimeSeries("Wind Speed");
ASSERT_TRUE(series);
ASSERT_EQ(8760,series->values().size());
DateTimeVector seriesTimes = series->dateTimes();
ASSERT_EQ(8760,seriesTimes.size());
// Check the times in the data and the time series
DateTime current(Date(1,1,1999),Time(0,1)); // Use 1999 to avoid leap years
Time delta(0,1);
for(unsigned i=0;i<8760;i++) {
// This is a lot more complicated that it probably should be to avoid the year being a problem
DateTime datatime = data[i].dateTime();
EXPECT_EQ(datatime.date().monthOfYear(), current.date().monthOfYear());
EXPECT_EQ(datatime.date().dayOfMonth(), current.date().dayOfMonth());
EXPECT_EQ(datatime.time().hours(), current.time().hours());
EXPECT_EQ(datatime.time().minutes(), current.time().minutes());
DateTime seriestime = seriesTimes[i];
EXPECT_EQ(seriestime.date().monthOfYear(), current.date().monthOfYear());
EXPECT_EQ(seriestime.date().dayOfMonth(), current.date().dayOfMonth());
EXPECT_EQ(seriestime.time().hours(), current.time().hours());
EXPECT_EQ(seriestime.time().minutes(), current.time().minutes());
current += delta;
}
// We should redo the original tests because we have reparsed the entire file
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("F188656D", epwFile.checksum());
EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city());
EXPECT_EQ("CO", epwFile.stateProvinceRegion());
EXPECT_EQ("USA", epwFile.country());
EXPECT_EQ("TMY3", epwFile.dataSource());
EXPECT_EQ("724666", epwFile.wmoNumber());
EXPECT_EQ(39.74, epwFile.latitude());
EXPECT_EQ(-105.18, epwFile.longitude());
EXPECT_EQ(-7, epwFile.timeZone());
EXPECT_EQ(1829, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek());
EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate());
}catch(...){
ASSERT_TRUE(false);
}
}
TEST(Filetypes, EpwFile_International_Data)
{
try{
path p = resourcesPath() / toPath("utilities/Filetypes/CHN_Guangdong.Shaoguan.590820_CSWD.epw");
EpwFile epwFile(p,true);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("B68C068B", epwFile.checksum());
EXPECT_EQ("Shaoguan", epwFile.city());
EXPECT_EQ("Guangdong", epwFile.stateProvinceRegion());
EXPECT_EQ("CHN", epwFile.country());
EXPECT_EQ("CSWD", epwFile.dataSource());
EXPECT_EQ("590820", epwFile.wmoNumber());
EXPECT_EQ(24.68, epwFile.latitude());
EXPECT_EQ(113.6, epwFile.longitude());
EXPECT_EQ(8, epwFile.timeZone());
EXPECT_EQ(61, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek());
EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate());
// Up to here, everything should be the same as the first test. Now ask for the data
std::vector<EpwDataPoint> data = epwFile.data();
EXPECT_EQ(8760,data.size());
// The last data point check
EXPECT_EQ(14.7,data[8759].dryBulbTemperature().get());
EXPECT_EQ(101100,data[8759].atmosphericStationPressure().get());
// Try out the alternate access functions, dew point temperature should be -1C
EXPECT_EQ(11.7,data[8759].getFieldByName("Dew Point Temperature").get());
EXPECT_EQ(11.7,data[8759].getField(EpwDataField("Dew Point Temperature")).get());
// The last data point should not have a liquid precipitation depth
EXPECT_FALSE(data[8759].getFieldByName("Liquid Precipitation Depth"));
// Get a time series
boost::optional<openstudio::TimeSeries> series = epwFile.getTimeSeries("Wind Speed");
ASSERT_TRUE(series);
ASSERT_EQ(8760,series->values().size());
DateTimeVector seriesTimes = series->dateTimes();
ASSERT_EQ(8760,seriesTimes.size());
// Check the times in the data and the time series
DateTime current(Date(1,1,1999),Time(0,1)); // Use 1999 to avoid leap years
Time delta(0,1);
for(unsigned i=0;i<8760;i++) {
// This is a lot more complicated that it probably should be to avoid the year being a problem
DateTime datatime = data[i].dateTime();
EXPECT_EQ(datatime.date().monthOfYear(), current.date().monthOfYear());
EXPECT_EQ(datatime.date().dayOfMonth(), current.date().dayOfMonth());
EXPECT_EQ(datatime.time().hours(), current.time().hours());
EXPECT_EQ(datatime.time().minutes(), current.time().minutes());
DateTime seriestime = seriesTimes[i];
EXPECT_EQ(seriestime.date().monthOfYear(), current.date().monthOfYear());
EXPECT_EQ(seriestime.date().dayOfMonth(), current.date().dayOfMonth());
EXPECT_EQ(seriestime.time().hours(), current.time().hours());
EXPECT_EQ(seriestime.time().minutes(), current.time().minutes());
current += delta;
}
// No need to redo the original tests here since the data should have been loaded in the constructor
}catch(...){
ASSERT_TRUE(false);
}
}
TEST(Filetypes, EpwFile_IWEC_Data)
{
try {
path p = resourcesPath() / toPath("utilities/Filetypes/TUN_Tunis.607150_IWEC.epw");
EpwFile epwFile(p, true);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("FEAB878E", epwFile.checksum());
EXPECT_EQ("TUNIS", epwFile.city());
EXPECT_EQ("-", epwFile.stateProvinceRegion());
EXPECT_EQ("TUN", epwFile.country());
EXPECT_EQ("IWEC Data", epwFile.dataSource());
EXPECT_EQ("607150", epwFile.wmoNumber());
EXPECT_EQ(36.83, epwFile.latitude());
EXPECT_EQ(10.23, epwFile.longitude());
EXPECT_EQ(1, epwFile.timeZone());
EXPECT_EQ(4, epwFile.elevation());
EXPECT_EQ(Time(0, 1, 0, 0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek());
EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate());
// Up to here, everything should be the same as the first test. Now ask for the data
std::vector<EpwDataPoint> data = epwFile.data();
EXPECT_EQ(8760, data.size());
// The last data point check
EXPECT_EQ(11.3, data[8759].dryBulbTemperature().get());
EXPECT_EQ(102400, data[8759].atmosphericStationPressure().get());
// Try out the alternate access functions
EXPECT_EQ(9.8, data[8759].getFieldByName("Dew Point Temperature").get());
EXPECT_EQ(9.8, data[8759].getField(EpwDataField("Dew Point Temperature")).get());
// Get a time series
boost::optional<openstudio::TimeSeries> series = epwFile.getTimeSeries("Wind Speed");
ASSERT_TRUE(series);
ASSERT_EQ(8760, series->values().size());
DateTimeVector seriesTimes = series->dateTimes();
ASSERT_EQ(8760, seriesTimes.size());
// Check the times in the data and the time series
DateTime current(Date(1, 1, 1999), Time(0, 1)); // Use 1999 to avoid leap years
Time delta(0, 1);
for (unsigned i = 0; i<8760; i++) {
// This is a lot more complicated that it probably should be to avoid the year being a problem
DateTime datatime = data[i].dateTime();
EXPECT_EQ(datatime.date().monthOfYear(), current.date().monthOfYear());
EXPECT_EQ(datatime.date().dayOfMonth(), current.date().dayOfMonth());
EXPECT_EQ(datatime.time().hours(), current.time().hours());
EXPECT_EQ(datatime.time().minutes(), current.time().minutes());
DateTime seriestime = seriesTimes[i];
EXPECT_EQ(seriestime.date().monthOfYear(), current.date().monthOfYear());
EXPECT_EQ(seriestime.date().dayOfMonth(), current.date().dayOfMonth());
EXPECT_EQ(seriestime.time().hours(), current.time().hours());
EXPECT_EQ(seriestime.time().minutes(), current.time().minutes());
current += delta;
}
// No need to redo the original tests here since the data should have been loaded in the constructor
}
catch (...) {
ASSERT_TRUE(false);
}
}
TEST(Filetypes, EpwFile_TMY)
{
try{
path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.724666_TMY3.epw");
EpwFile epwFile(p);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("BDF687C1", epwFile.checksum());
EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city());
EXPECT_EQ("CO", epwFile.stateProvinceRegion());
EXPECT_EQ("USA", epwFile.country());
EXPECT_EQ("TMY3", epwFile.dataSource());
EXPECT_EQ("724666", epwFile.wmoNumber());
EXPECT_EQ(39.74, epwFile.latitude());
EXPECT_EQ(-105.18, epwFile.longitude());
EXPECT_EQ(-7, epwFile.timeZone());
EXPECT_EQ(1829, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Sunday), epwFile.startDayOfWeek());
EXPECT_FALSE(epwFile.startDateActualYear());
EXPECT_FALSE(epwFile.endDateActualYear());
EXPECT_EQ(Date(MonthOfYear::Jan, 1), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31), epwFile.endDate());
EXPECT_EQ(365, (epwFile.endDate() - epwFile.startDate()).totalDays() + 1);
}catch(...){
ASSERT_TRUE(false);
}
}
TEST(Filetypes, EpwFile_Wrap_TMY)
{
try{
path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.wrap.epw");
EpwFile epwFile(p);
EXPECT_TRUE(false);
}catch(...){
EXPECT_TRUE(true);
}
}
TEST(Filetypes, EpwFile_AMY)
{
try{
path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.amy");
EpwFile epwFile(p);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("521A957C", epwFile.checksum());
EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city());
EXPECT_EQ("CO", epwFile.stateProvinceRegion());
EXPECT_EQ("USA", epwFile.country());
EXPECT_EQ("TMY3", epwFile.dataSource());
EXPECT_EQ("724666", epwFile.wmoNumber());
EXPECT_EQ(39.74, epwFile.latitude());
EXPECT_EQ(-105.18, epwFile.longitude());
EXPECT_EQ(-7, epwFile.timeZone());
EXPECT_EQ(1829, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Friday), epwFile.startDayOfWeek());
ASSERT_TRUE(epwFile.startDateActualYear());
EXPECT_EQ(1999, epwFile.startDateActualYear().get());
ASSERT_TRUE(epwFile.endDateActualYear());
EXPECT_EQ(1999, epwFile.endDateActualYear().get());
EXPECT_EQ(Date(MonthOfYear::Jan, 1, 1999), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Dec, 31, 1999), epwFile.endDate());
EXPECT_EQ(365, (epwFile.endDate() - epwFile.startDate()).totalDays() + 1);
}catch(...){
ASSERT_TRUE(false);
}
}
TEST(Filetypes, EpwFile_Wrap_AMY)
{
try{
path p = resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.wrap.amy");
EpwFile epwFile(p);
EXPECT_EQ(p, epwFile.path());
EXPECT_EQ("8F74A20B", epwFile.checksum());
EXPECT_EQ("Denver Centennial Golden Nr", epwFile.city());
EXPECT_EQ("CO", epwFile.stateProvinceRegion());
EXPECT_EQ("USA", epwFile.country());
EXPECT_EQ("TMY3", epwFile.dataSource());
EXPECT_EQ("724666", epwFile.wmoNumber());
EXPECT_EQ(39.74, epwFile.latitude());
EXPECT_EQ(-105.18, epwFile.longitude());
EXPECT_EQ(-7, epwFile.timeZone());
EXPECT_EQ(1829, epwFile.elevation());
EXPECT_EQ(Time(0,1,0,0), epwFile.timeStep());
EXPECT_EQ(DayOfWeek(DayOfWeek::Saturday), epwFile.startDayOfWeek());
ASSERT_TRUE(epwFile.startDateActualYear());
EXPECT_EQ(1999, epwFile.startDateActualYear().get());
ASSERT_TRUE(epwFile.endDateActualYear());
EXPECT_EQ(2000, epwFile.endDateActualYear().get());
EXPECT_EQ(Date(MonthOfYear::Apr, 10, 1999), epwFile.startDate());
EXPECT_EQ(Date(MonthOfYear::Apr, 8, 2000), epwFile.endDate()); // 2000 is a leap year
EXPECT_EQ(365, (epwFile.endDate() - epwFile.startDate()).totalDays() + 1);
}catch(...){
ASSERT_TRUE(false);
}
}
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/bits.h"
#include "src/base/platform/wrappers.h"
#include "src/codegen/machine-type.h"
#include "src/compiler/backend/instruction-selector-impl.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
namespace v8 {
namespace internal {
namespace compiler {
#define TRACE_UNIMPL() \
PrintF("UNIMPLEMENTED instr_sel: %s at line %d\n", __FUNCTION__, __LINE__)
#define TRACE() PrintF("instr_sel: %s at line %d\n", __FUNCTION__, __LINE__)
// Adds Mips-specific methods for generating InstructionOperands.
class Mips64OperandGenerator final : public OperandGenerator {
public:
explicit Mips64OperandGenerator(InstructionSelector* selector)
: OperandGenerator(selector) {}
InstructionOperand UseOperand(Node* node, InstructionCode opcode) {
if (CanBeImmediate(node, opcode)) {
return UseImmediate(node);
}
return UseRegister(node);
}
// Use the zero register if the node has the immediate value zero, otherwise
// assign a register.
InstructionOperand UseRegisterOrImmediateZero(Node* node) {
if ((IsIntegerConstant(node) && (GetIntegerConstantValue(node) == 0)) ||
(IsFloatConstant(node) &&
(bit_cast<int64_t>(GetFloatConstantValue(node)) == 0))) {
return UseImmediate(node);
}
return UseRegister(node);
}
bool IsIntegerConstant(Node* node) {
return (node->opcode() == IrOpcode::kInt32Constant) ||
(node->opcode() == IrOpcode::kInt64Constant);
}
int64_t GetIntegerConstantValue(Node* node) {
if (node->opcode() == IrOpcode::kInt32Constant) {
return OpParameter<int32_t>(node->op());
}
DCHECK_EQ(IrOpcode::kInt64Constant, node->opcode());
return OpParameter<int64_t>(node->op());
}
bool IsFloatConstant(Node* node) {
return (node->opcode() == IrOpcode::kFloat32Constant) ||
(node->opcode() == IrOpcode::kFloat64Constant);
}
double GetFloatConstantValue(Node* node) {
if (node->opcode() == IrOpcode::kFloat32Constant) {
return OpParameter<float>(node->op());
}
DCHECK_EQ(IrOpcode::kFloat64Constant, node->opcode());
return OpParameter<double>(node->op());
}
bool CanBeImmediate(Node* node, InstructionCode mode) {
return IsIntegerConstant(node) &&
CanBeImmediate(GetIntegerConstantValue(node), mode);
}
bool CanBeImmediate(int64_t value, InstructionCode opcode) {
switch (ArchOpcodeField::decode(opcode)) {
case kMips64Shl:
case kMips64Sar:
case kMips64Shr:
return is_uint5(value);
case kMips64Dshl:
case kMips64Dsar:
case kMips64Dshr:
return is_uint6(value);
case kMips64Add:
case kMips64And32:
case kMips64And:
case kMips64Dadd:
case kMips64Or32:
case kMips64Or:
case kMips64Tst:
case kMips64Xor:
return is_uint16(value);
case kMips64Lb:
case kMips64Lbu:
case kMips64Sb:
case kMips64Lh:
case kMips64Lhu:
case kMips64Sh:
case kMips64Lw:
case kMips64Sw:
case kMips64Ld:
case kMips64Sd:
case kMips64Lwc1:
case kMips64Swc1:
case kMips64Ldc1:
case kMips64Sdc1:
return is_int32(value);
default:
return is_int16(value);
}
}
private:
bool ImmediateFitsAddrMode1Instruction(int32_t imm) const {
TRACE_UNIMPL();
return false;
}
};
static void VisitRR(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
static void VisitRRI(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
int32_t imm = OpParameter<int32_t>(node->op());
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseImmediate(imm));
}
static void VisitSimdShift(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
if (g.IsIntegerConstant(node->InputAt(1))) {
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)),
g.UseImmediate(node->InputAt(1)));
} else {
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(1)));
}
}
static void VisitRRIR(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
int32_t imm = OpParameter<int32_t>(node->op());
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseImmediate(imm),
g.UseRegister(node->InputAt(1)));
}
static void VisitRRR(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(1)));
}
static void VisitUniqueRRR(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseUniqueRegister(node->InputAt(0)),
g.UseUniqueRegister(node->InputAt(1)));
}
void VisitRRRR(InstructionSelector* selector, ArchOpcode opcode, Node* node) {
Mips64OperandGenerator g(selector);
selector->Emit(
opcode, g.DefineSameAsFirst(node), g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(1)), g.UseRegister(node->InputAt(2)));
}
static void VisitRRO(InstructionSelector* selector, ArchOpcode opcode,
Node* node) {
Mips64OperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)),
g.UseOperand(node->InputAt(1), opcode));
}
struct ExtendingLoadMatcher {
ExtendingLoadMatcher(Node* node, InstructionSelector* selector)
: matches_(false), selector_(selector), base_(nullptr), immediate_(0) {
Initialize(node);
}
bool Matches() const { return matches_; }
Node* base() const {
DCHECK(Matches());
return base_;
}
int64_t immediate() const {
DCHECK(Matches());
return immediate_;
}
ArchOpcode opcode() const {
DCHECK(Matches());
return opcode_;
}
private:
bool matches_;
InstructionSelector* selector_;
Node* base_;
int64_t immediate_;
ArchOpcode opcode_;
void Initialize(Node* node) {
Int64BinopMatcher m(node);
// When loading a 64-bit value and shifting by 32, we should
// just load and sign-extend the interesting 4 bytes instead.
// This happens, for example, when we're loading and untagging SMIs.
DCHECK(m.IsWord64Sar());
if (m.left().IsLoad() && m.right().Is(32) &&
selector_->CanCover(m.node(), m.left().node())) {
DCHECK_EQ(selector_->GetEffectLevel(node),
selector_->GetEffectLevel(m.left().node()));
MachineRepresentation rep =
LoadRepresentationOf(m.left().node()->op()).representation();
DCHECK_EQ(3, ElementSizeLog2Of(rep));
if (rep != MachineRepresentation::kTaggedSigned &&
rep != MachineRepresentation::kTaggedPointer &&
rep != MachineRepresentation::kTagged &&
rep != MachineRepresentation::kWord64) {
return;
}
Mips64OperandGenerator g(selector_);
Node* load = m.left().node();
Node* offset = load->InputAt(1);
base_ = load->InputAt(0);
opcode_ = kMips64Lw;
if (g.CanBeImmediate(offset, opcode_)) {
#if defined(V8_TARGET_LITTLE_ENDIAN)
immediate_ = g.GetIntegerConstantValue(offset) + 4;
#elif defined(V8_TARGET_BIG_ENDIAN)
immediate_ = g.GetIntegerConstantValue(offset);
#endif
matches_ = g.CanBeImmediate(immediate_, kMips64Lw);
}
}
}
};
bool TryEmitExtendingLoad(InstructionSelector* selector, Node* node,
Node* output_node) {
ExtendingLoadMatcher m(node, selector);
Mips64OperandGenerator g(selector);
if (m.Matches()) {
InstructionOperand inputs[2];
inputs[0] = g.UseRegister(m.base());
InstructionCode opcode =
m.opcode() | AddressingModeField::encode(kMode_MRI);
DCHECK(is_int32(m.immediate()));
inputs[1] = g.TempImmediate(static_cast<int32_t>(m.immediate()));
InstructionOperand outputs[] = {g.DefineAsRegister(output_node)};
selector->Emit(opcode, arraysize(outputs), outputs, arraysize(inputs),
inputs);
return true;
}
return false;
}
bool TryMatchImmediate(InstructionSelector* selector,
InstructionCode* opcode_return, Node* node,
size_t* input_count_return, InstructionOperand* inputs) {
Mips64OperandGenerator g(selector);
if (g.CanBeImmediate(node, *opcode_return)) {
*opcode_return |= AddressingModeField::encode(kMode_MRI);
inputs[0] = g.UseImmediate(node);
*input_count_return = 1;
return true;
}
return false;
}
static void VisitBinop(InstructionSelector* selector, Node* node,
InstructionCode opcode, bool has_reverse_opcode,
InstructionCode reverse_opcode,
FlagsContinuation* cont) {
Mips64OperandGenerator g(selector);
Int32BinopMatcher m(node);
InstructionOperand inputs[2];
size_t input_count = 0;
InstructionOperand outputs[1];
size_t output_count = 0;
if (TryMatchImmediate(selector, &opcode, m.right().node(), &input_count,
&inputs[1])) {
inputs[0] = g.UseRegister(m.left().node());
input_count++;
} else if (has_reverse_opcode &&
TryMatchImmediate(selector, &reverse_opcode, m.left().node(),
&input_count, &inputs[1])) {
inputs[0] = g.UseRegister(m.right().node());
opcode = reverse_opcode;
input_count++;
} else {
inputs[input_count++] = g.UseRegister(m.left().node());
inputs[input_count++] = g.UseOperand(m.right().node(), opcode);
}
if (cont->IsDeoptimize()) {
// If we can deoptimize as a result of the binop, we need to make sure that
// the deopt inputs are not overwritten by the binop result. One way
// to achieve that is to declare the output register as same-as-first.
outputs[output_count++] = g.DefineSameAsFirst(node);
} else {
outputs[output_count++] = g.DefineAsRegister(node);
}
DCHECK_NE(0u, input_count);
DCHECK_EQ(1u, output_count);
DCHECK_GE(arraysize(inputs), input_count);
DCHECK_GE(arraysize(outputs), output_count);
selector->EmitWithContinuation(opcode, output_count, outputs, input_count,
inputs, cont);
}
static void VisitBinop(InstructionSelector* selector, Node* node,
InstructionCode opcode, bool has_reverse_opcode,
InstructionCode reverse_opcode) {
FlagsContinuation cont;
VisitBinop(selector, node, opcode, has_reverse_opcode, reverse_opcode, &cont);
}
static void VisitBinop(InstructionSelector* selector, Node* node,
InstructionCode opcode, FlagsContinuation* cont) {
VisitBinop(selector, node, opcode, false, kArchNop, cont);
}
static void VisitBinop(InstructionSelector* selector, Node* node,
InstructionCode opcode) {
VisitBinop(selector, node, opcode, false, kArchNop);
}
void InstructionSelector::VisitStackSlot(Node* node) {
StackSlotRepresentation rep = StackSlotRepresentationOf(node->op());
int alignment = rep.alignment();
int slot = frame_->AllocateSpillSlot(rep.size(), alignment);
OperandGenerator g(this);
Emit(kArchStackSlot, g.DefineAsRegister(node),
sequence()->AddImmediate(Constant(slot)),
sequence()->AddImmediate(Constant(alignment)), 0, nullptr);
}
void InstructionSelector::VisitAbortCSAAssert(Node* node) {
Mips64OperandGenerator g(this);
Emit(kArchAbortCSAAssert, g.NoOutput(), g.UseFixed(node->InputAt(0), a0));
}
void EmitLoad(InstructionSelector* selector, Node* node, InstructionCode opcode,
Node* output = nullptr) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
if (g.CanBeImmediate(index, opcode)) {
selector->Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(output == nullptr ? node : output),
g.UseRegister(base), g.UseImmediate(index));
} else {
InstructionOperand addr_reg = g.TempRegister();
selector->Emit(kMips64Dadd | AddressingModeField::encode(kMode_None),
addr_reg, g.UseRegister(base), g.UseRegister(index));
// Emit desired load opcode, using temp addr_reg.
selector->Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(output == nullptr ? node : output),
addr_reg, g.TempImmediate(0));
}
}
namespace {
InstructionOperand EmitAddBeforeS128LoadStore(InstructionSelector* selector,
Node* node,
InstructionCode* opcode) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
InstructionOperand addr_reg = g.TempRegister();
selector->Emit(kMips64Dadd | AddressingModeField::encode(kMode_None),
addr_reg, g.UseRegister(base), g.UseRegister(index));
*opcode |= AddressingModeField::encode(kMode_MRI);
return addr_reg;
}
} // namespace
void InstructionSelector::VisitStoreLane(Node* node) {
StoreLaneParameters params = StoreLaneParametersOf(node->op());
LoadStoreLaneParams f(params.rep, params.laneidx);
InstructionCode opcode = kMips64S128StoreLane;
opcode |= MiscField::encode(f.sz);
Mips64OperandGenerator g(this);
InstructionOperand addr = EmitAddBeforeS128LoadStore(this, node, &opcode);
InstructionOperand inputs[4] = {
g.UseRegister(node->InputAt(2)),
g.UseImmediate(f.laneidx),
addr,
g.TempImmediate(0),
};
Emit(opcode, 0, nullptr, 4, inputs);
}
void InstructionSelector::VisitLoadLane(Node* node) {
LoadLaneParameters params = LoadLaneParametersOf(node->op());
LoadStoreLaneParams f(params.rep.representation(), params.laneidx);
InstructionCode opcode = kMips64S128LoadLane;
opcode |= MiscField::encode(f.sz);
Mips64OperandGenerator g(this);
InstructionOperand addr = EmitAddBeforeS128LoadStore(this, node, &opcode);
Emit(opcode, g.DefineSameAsFirst(node), g.UseRegister(node->InputAt(2)),
g.UseImmediate(f.laneidx), addr, g.TempImmediate(0));
}
void InstructionSelector::VisitLoadTransform(Node* node) {
LoadTransformParameters params = LoadTransformParametersOf(node->op());
InstructionCode opcode = kArchNop;
switch (params.transformation) {
case LoadTransformation::kS128Load8Splat:
opcode = kMips64S128LoadSplat;
opcode |= MiscField::encode(MSASize::MSA_B);
break;
case LoadTransformation::kS128Load16Splat:
opcode = kMips64S128LoadSplat;
opcode |= MiscField::encode(MSASize::MSA_H);
break;
case LoadTransformation::kS128Load32Splat:
opcode = kMips64S128LoadSplat;
opcode |= MiscField::encode(MSASize::MSA_W);
break;
case LoadTransformation::kS128Load64Splat:
opcode = kMips64S128LoadSplat;
opcode |= MiscField::encode(MSASize::MSA_D);
break;
case LoadTransformation::kS128Load8x8S:
opcode = kMips64S128Load8x8S;
break;
case LoadTransformation::kS128Load8x8U:
opcode = kMips64S128Load8x8U;
break;
case LoadTransformation::kS128Load16x4S:
opcode = kMips64S128Load16x4S;
break;
case LoadTransformation::kS128Load16x4U:
opcode = kMips64S128Load16x4U;
break;
case LoadTransformation::kS128Load32x2S:
opcode = kMips64S128Load32x2S;
break;
case LoadTransformation::kS128Load32x2U:
opcode = kMips64S128Load32x2U;
break;
case LoadTransformation::kS128Load32Zero:
opcode = kMips64S128Load32Zero;
break;
case LoadTransformation::kS128Load64Zero:
opcode = kMips64S128Load64Zero;
break;
default:
UNIMPLEMENTED();
}
EmitLoad(this, node, opcode);
}
void InstructionSelector::VisitLoad(Node* node) {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
InstructionCode opcode = kArchNop;
switch (load_rep.representation()) {
case MachineRepresentation::kFloat32:
opcode = kMips64Lwc1;
break;
case MachineRepresentation::kFloat64:
opcode = kMips64Ldc1;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kWord8:
opcode = load_rep.IsUnsigned() ? kMips64Lbu : kMips64Lb;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsUnsigned() ? kMips64Lhu : kMips64Lh;
break;
case MachineRepresentation::kWord32:
opcode = load_rep.IsUnsigned() ? kMips64Lwu : kMips64Lw;
break;
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
case MachineRepresentation::kWord64:
opcode = kMips64Ld;
break;
case MachineRepresentation::kSimd128:
opcode = kMips64MsaLd;
break;
case MachineRepresentation::kCompressedPointer: // Fall through.
case MachineRepresentation::kCompressed: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
}
if (node->opcode() == IrOpcode::kPoisonedLoad) {
CHECK_NE(poisoning_level_, PoisoningMitigationLevel::kDontPoison);
opcode |= AccessModeField::encode(kMemoryAccessPoisoned);
}
EmitLoad(this, node, opcode);
}
void InstructionSelector::VisitPoisonedLoad(Node* node) { VisitLoad(node); }
void InstructionSelector::VisitProtectedLoad(Node* node) {
// TODO(eholk)
UNIMPLEMENTED();
}
void InstructionSelector::VisitStore(Node* node) {
Mips64OperandGenerator g(this);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* value = node->InputAt(2);
StoreRepresentation store_rep = StoreRepresentationOf(node->op());
WriteBarrierKind write_barrier_kind = store_rep.write_barrier_kind();
MachineRepresentation rep = store_rep.representation();
if (FLAG_enable_unconditional_write_barriers && CanBeTaggedPointer(rep)) {
write_barrier_kind = kFullWriteBarrier;
}
// TODO(mips): I guess this could be done in a better way.
if (write_barrier_kind != kNoWriteBarrier && !FLAG_disable_write_barriers) {
DCHECK(CanBeTaggedPointer(rep));
InstructionOperand inputs[3];
size_t input_count = 0;
inputs[input_count++] = g.UseUniqueRegister(base);
inputs[input_count++] = g.UseUniqueRegister(index);
inputs[input_count++] = g.UseUniqueRegister(value);
RecordWriteMode record_write_mode =
WriteBarrierKindToRecordWriteMode(write_barrier_kind);
InstructionOperand temps[] = {g.TempRegister(), g.TempRegister()};
size_t const temp_count = arraysize(temps);
InstructionCode code = kArchStoreWithWriteBarrier;
code |= MiscField::encode(static_cast<int>(record_write_mode));
Emit(code, 0, nullptr, input_count, inputs, temp_count, temps);
} else {
ArchOpcode opcode;
switch (rep) {
case MachineRepresentation::kFloat32:
opcode = kMips64Swc1;
break;
case MachineRepresentation::kFloat64:
opcode = kMips64Sdc1;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kWord8:
opcode = kMips64Sb;
break;
case MachineRepresentation::kWord16:
opcode = kMips64Sh;
break;
case MachineRepresentation::kWord32:
opcode = kMips64Sw;
break;
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
case MachineRepresentation::kWord64:
opcode = kMips64Sd;
break;
case MachineRepresentation::kSimd128:
opcode = kMips64MsaSt;
break;
case MachineRepresentation::kCompressedPointer: // Fall through.
case MachineRepresentation::kCompressed: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
}
if (g.CanBeImmediate(index, opcode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
g.UseRegister(base), g.UseImmediate(index),
g.UseRegisterOrImmediateZero(value));
} else {
InstructionOperand addr_reg = g.TempRegister();
Emit(kMips64Dadd | AddressingModeField::encode(kMode_None), addr_reg,
g.UseRegister(index), g.UseRegister(base));
// Emit desired store opcode, using temp addr_reg.
Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
addr_reg, g.TempImmediate(0), g.UseRegisterOrImmediateZero(value));
}
}
}
void InstructionSelector::VisitProtectedStore(Node* node) {
// TODO(eholk)
UNIMPLEMENTED();
}
void InstructionSelector::VisitWord32And(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
if (m.left().IsWord32Shr() && CanCover(node, m.left().node()) &&
m.right().HasResolvedValue()) {
uint32_t mask = m.right().ResolvedValue();
uint32_t mask_width = base::bits::CountPopulation(mask);
uint32_t mask_msb = base::bits::CountLeadingZeros32(mask);
if ((mask_width != 0) && (mask_msb + mask_width == 32)) {
// The mask must be contiguous, and occupy the least-significant bits.
DCHECK_EQ(0u, base::bits::CountTrailingZeros32(mask));
// Select Ext for And(Shr(x, imm), mask) where the mask is in the least
// significant bits.
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue()) {
// Any shift value can match; int32 shifts use `value % 32`.
uint32_t lsb = mleft.right().ResolvedValue() & 0x1F;
// Ext cannot extract bits past the register size, however since
// shifting the original value would have introduced some zeros we can
// still use Ext with a smaller mask and the remaining bits will be
// zeros.
if (lsb + mask_width > 32) mask_width = 32 - lsb;
Emit(kMips64Ext, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(lsb),
g.TempImmediate(mask_width));
return;
}
// Other cases fall through to the normal And operation.
}
}
if (m.right().HasResolvedValue()) {
uint32_t mask = m.right().ResolvedValue();
uint32_t shift = base::bits::CountPopulation(~mask);
uint32_t msb = base::bits::CountLeadingZeros32(~mask);
if (shift != 0 && shift != 32 && msb + shift == 32) {
// Insert zeros for (x >> K) << K => x & ~(2^K - 1) expression reduction
// and remove constant loading of inverted mask.
Emit(kMips64Ins, g.DefineSameAsFirst(node),
g.UseRegister(m.left().node()), g.TempImmediate(0),
g.TempImmediate(shift));
return;
}
}
VisitBinop(this, node, kMips64And32, true, kMips64And32);
}
void InstructionSelector::VisitWord64And(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
if (m.left().IsWord64Shr() && CanCover(node, m.left().node()) &&
m.right().HasResolvedValue()) {
uint64_t mask = m.right().ResolvedValue();
uint32_t mask_width = base::bits::CountPopulation(mask);
uint32_t mask_msb = base::bits::CountLeadingZeros64(mask);
if ((mask_width != 0) && (mask_msb + mask_width == 64)) {
// The mask must be contiguous, and occupy the least-significant bits.
DCHECK_EQ(0u, base::bits::CountTrailingZeros64(mask));
// Select Dext for And(Shr(x, imm), mask) where the mask is in the least
// significant bits.
Int64BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue()) {
// Any shift value can match; int64 shifts use `value % 64`.
uint32_t lsb =
static_cast<uint32_t>(mleft.right().ResolvedValue() & 0x3F);
// Dext cannot extract bits past the register size, however since
// shifting the original value would have introduced some zeros we can
// still use Dext with a smaller mask and the remaining bits will be
// zeros.
if (lsb + mask_width > 64) mask_width = 64 - lsb;
if (lsb == 0 && mask_width == 64) {
Emit(kArchNop, g.DefineSameAsFirst(node), g.Use(mleft.left().node()));
} else {
Emit(kMips64Dext, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(lsb),
g.TempImmediate(static_cast<int32_t>(mask_width)));
}
return;
}
// Other cases fall through to the normal And operation.
}
}
if (m.right().HasResolvedValue()) {
uint64_t mask = m.right().ResolvedValue();
uint32_t shift = base::bits::CountPopulation(~mask);
uint32_t msb = base::bits::CountLeadingZeros64(~mask);
if (shift != 0 && shift < 32 && msb + shift == 64) {
// Insert zeros for (x >> K) << K => x & ~(2^K - 1) expression reduction
// and remove constant loading of inverted mask. Dins cannot insert bits
// past word size, so shifts smaller than 32 are covered.
Emit(kMips64Dins, g.DefineSameAsFirst(node),
g.UseRegister(m.left().node()), g.TempImmediate(0),
g.TempImmediate(shift));
return;
}
}
VisitBinop(this, node, kMips64And, true, kMips64And);
}
void InstructionSelector::VisitWord32Or(Node* node) {
VisitBinop(this, node, kMips64Or32, true, kMips64Or32);
}
void InstructionSelector::VisitWord64Or(Node* node) {
VisitBinop(this, node, kMips64Or, true, kMips64Or);
}
void InstructionSelector::VisitWord32Xor(Node* node) {
Int32BinopMatcher m(node);
if (m.left().IsWord32Or() && CanCover(node, m.left().node()) &&
m.right().Is(-1)) {
Int32BinopMatcher mleft(m.left().node());
if (!mleft.right().HasResolvedValue()) {
Mips64OperandGenerator g(this);
Emit(kMips64Nor32, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()),
g.UseRegister(mleft.right().node()));
return;
}
}
if (m.right().Is(-1)) {
// Use Nor for bit negation and eliminate constant loading for xori.
Mips64OperandGenerator g(this);
Emit(kMips64Nor32, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.TempImmediate(0));
return;
}
VisitBinop(this, node, kMips64Xor32, true, kMips64Xor32);
}
void InstructionSelector::VisitWord64Xor(Node* node) {
Int64BinopMatcher m(node);
if (m.left().IsWord64Or() && CanCover(node, m.left().node()) &&
m.right().Is(-1)) {
Int64BinopMatcher mleft(m.left().node());
if (!mleft.right().HasResolvedValue()) {
Mips64OperandGenerator g(this);
Emit(kMips64Nor, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()),
g.UseRegister(mleft.right().node()));
return;
}
}
if (m.right().Is(-1)) {
// Use Nor for bit negation and eliminate constant loading for xori.
Mips64OperandGenerator g(this);
Emit(kMips64Nor, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.TempImmediate(0));
return;
}
VisitBinop(this, node, kMips64Xor, true, kMips64Xor);
}
void InstructionSelector::VisitWord32Shl(Node* node) {
Int32BinopMatcher m(node);
if (m.left().IsWord32And() && CanCover(node, m.left().node()) &&
m.right().IsInRange(1, 31)) {
Mips64OperandGenerator g(this);
Int32BinopMatcher mleft(m.left().node());
// Match Word32Shl(Word32And(x, mask), imm) to Shl where the mask is
// contiguous, and the shift immediate non-zero.
if (mleft.right().HasResolvedValue()) {
uint32_t mask = mleft.right().ResolvedValue();
uint32_t mask_width = base::bits::CountPopulation(mask);
uint32_t mask_msb = base::bits::CountLeadingZeros32(mask);
if ((mask_width != 0) && (mask_msb + mask_width == 32)) {
uint32_t shift = m.right().ResolvedValue();
DCHECK_EQ(0u, base::bits::CountTrailingZeros32(mask));
DCHECK_NE(0u, shift);
if ((shift + mask_width) >= 32) {
// If the mask is contiguous and reaches or extends beyond the top
// bit, only the shift is needed.
Emit(kMips64Shl, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()),
g.UseImmediate(m.right().node()));
return;
}
}
}
}
VisitRRO(this, kMips64Shl, node);
}
void InstructionSelector::VisitWord32Shr(Node* node) {
Int32BinopMatcher m(node);
if (m.left().IsWord32And() && m.right().HasResolvedValue()) {
uint32_t lsb = m.right().ResolvedValue() & 0x1F;
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue() &&
mleft.right().ResolvedValue() != 0) {
// Select Ext for Shr(And(x, mask), imm) where the result of the mask is
// shifted into the least-significant bits.
uint32_t mask = (mleft.right().ResolvedValue() >> lsb) << lsb;
unsigned mask_width = base::bits::CountPopulation(mask);
unsigned mask_msb = base::bits::CountLeadingZeros32(mask);
if ((mask_msb + mask_width + lsb) == 32) {
Mips64OperandGenerator g(this);
DCHECK_EQ(lsb, base::bits::CountTrailingZeros32(mask));
Emit(kMips64Ext, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(lsb),
g.TempImmediate(mask_width));
return;
}
}
}
VisitRRO(this, kMips64Shr, node);
}
void InstructionSelector::VisitWord32Sar(Node* node) {
Int32BinopMatcher m(node);
if (m.left().IsWord32Shl() && CanCover(node, m.left().node())) {
Int32BinopMatcher mleft(m.left().node());
if (m.right().HasResolvedValue() && mleft.right().HasResolvedValue()) {
Mips64OperandGenerator g(this);
uint32_t sar = m.right().ResolvedValue();
uint32_t shl = mleft.right().ResolvedValue();
if ((sar == shl) && (sar == 16)) {
Emit(kMips64Seh, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()));
return;
} else if ((sar == shl) && (sar == 24)) {
Emit(kMips64Seb, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()));
return;
} else if ((sar == shl) && (sar == 32)) {
Emit(kMips64Shl, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(0));
return;
}
}
}
VisitRRO(this, kMips64Sar, node);
}
void InstructionSelector::VisitWord64Shl(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
if ((m.left().IsChangeInt32ToInt64() || m.left().IsChangeUint32ToUint64()) &&
m.right().IsInRange(32, 63) && CanCover(node, m.left().node())) {
// There's no need to sign/zero-extend to 64-bit if we shift out the upper
// 32 bits anyway.
Emit(kMips64Dshl, g.DefineSameAsFirst(node),
g.UseRegister(m.left().node()->InputAt(0)),
g.UseImmediate(m.right().node()));
return;
}
if (m.left().IsWord64And() && CanCover(node, m.left().node()) &&
m.right().IsInRange(1, 63)) {
// Match Word64Shl(Word64And(x, mask), imm) to Dshl where the mask is
// contiguous, and the shift immediate non-zero.
Int64BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue()) {
uint64_t mask = mleft.right().ResolvedValue();
uint32_t mask_width = base::bits::CountPopulation(mask);
uint32_t mask_msb = base::bits::CountLeadingZeros64(mask);
if ((mask_width != 0) && (mask_msb + mask_width == 64)) {
uint64_t shift = m.right().ResolvedValue();
DCHECK_EQ(0u, base::bits::CountTrailingZeros64(mask));
DCHECK_NE(0u, shift);
if ((shift + mask_width) >= 64) {
// If the mask is contiguous and reaches or extends beyond the top
// bit, only the shift is needed.
Emit(kMips64Dshl, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()),
g.UseImmediate(m.right().node()));
return;
}
}
}
}
VisitRRO(this, kMips64Dshl, node);
}
void InstructionSelector::VisitWord64Shr(Node* node) {
Int64BinopMatcher m(node);
if (m.left().IsWord64And() && m.right().HasResolvedValue()) {
uint32_t lsb = m.right().ResolvedValue() & 0x3F;
Int64BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue() &&
mleft.right().ResolvedValue() != 0) {
// Select Dext for Shr(And(x, mask), imm) where the result of the mask is
// shifted into the least-significant bits.
uint64_t mask = (mleft.right().ResolvedValue() >> lsb) << lsb;
unsigned mask_width = base::bits::CountPopulation(mask);
unsigned mask_msb = base::bits::CountLeadingZeros64(mask);
if ((mask_msb + mask_width + lsb) == 64) {
Mips64OperandGenerator g(this);
DCHECK_EQ(lsb, base::bits::CountTrailingZeros64(mask));
Emit(kMips64Dext, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(lsb),
g.TempImmediate(mask_width));
return;
}
}
}
VisitRRO(this, kMips64Dshr, node);
}
void InstructionSelector::VisitWord64Sar(Node* node) {
if (TryEmitExtendingLoad(this, node, node)) return;
VisitRRO(this, kMips64Dsar, node);
}
void InstructionSelector::VisitWord32Rol(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitWord64Rol(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitWord32Ror(Node* node) {
VisitRRO(this, kMips64Ror, node);
}
void InstructionSelector::VisitWord32Clz(Node* node) {
VisitRR(this, kMips64Clz, node);
}
void InstructionSelector::VisitWord32ReverseBits(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitWord64ReverseBits(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitWord64ReverseBytes(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64ByteSwap64, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitWord32ReverseBytes(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64ByteSwap32, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitSimd128ReverseBytes(Node* node) {
UNREACHABLE();
}
void InstructionSelector::VisitWord32Ctz(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Ctz, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitWord64Ctz(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Dctz, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitWord32Popcnt(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Popcnt, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitWord64Popcnt(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Dpopcnt, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitWord64Ror(Node* node) {
VisitRRO(this, kMips64Dror, node);
}
void InstructionSelector::VisitWord64Clz(Node* node) {
VisitRR(this, kMips64Dclz, node);
}
void InstructionSelector::VisitInt32Add(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
if (kArchVariant == kMips64r6) {
// Select Lsa for (left + (left_of_right << imm)).
if (m.right().opcode() == IrOpcode::kWord32Shl &&
CanCover(node, m.left().node()) && CanCover(node, m.right().node())) {
Int32BinopMatcher mright(m.right().node());
if (mright.right().HasResolvedValue() && !m.left().HasResolvedValue()) {
int32_t shift_value =
static_cast<int32_t>(mright.right().ResolvedValue());
if (shift_value > 0 && shift_value <= 31) {
Emit(kMips64Lsa, g.DefineAsRegister(node),
g.UseRegister(m.left().node()),
g.UseRegister(mright.left().node()),
g.TempImmediate(shift_value));
return;
}
}
}
// Select Lsa for ((left_of_left << imm) + right).
if (m.left().opcode() == IrOpcode::kWord32Shl &&
CanCover(node, m.right().node()) && CanCover(node, m.left().node())) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue() && !m.right().HasResolvedValue()) {
int32_t shift_value =
static_cast<int32_t>(mleft.right().ResolvedValue());
if (shift_value > 0 && shift_value <= 31) {
Emit(kMips64Lsa, g.DefineAsRegister(node),
g.UseRegister(m.right().node()),
g.UseRegister(mleft.left().node()),
g.TempImmediate(shift_value));
return;
}
}
}
}
VisitBinop(this, node, kMips64Add, true, kMips64Add);
}
void InstructionSelector::VisitInt64Add(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
if (kArchVariant == kMips64r6) {
// Select Dlsa for (left + (left_of_right << imm)).
if (m.right().opcode() == IrOpcode::kWord64Shl &&
CanCover(node, m.left().node()) && CanCover(node, m.right().node())) {
Int64BinopMatcher mright(m.right().node());
if (mright.right().HasResolvedValue() && !m.left().HasResolvedValue()) {
int32_t shift_value =
static_cast<int32_t>(mright.right().ResolvedValue());
if (shift_value > 0 && shift_value <= 31) {
Emit(kMips64Dlsa, g.DefineAsRegister(node),
g.UseRegister(m.left().node()),
g.UseRegister(mright.left().node()),
g.TempImmediate(shift_value));
return;
}
}
}
// Select Dlsa for ((left_of_left << imm) + right).
if (m.left().opcode() == IrOpcode::kWord64Shl &&
CanCover(node, m.right().node()) && CanCover(node, m.left().node())) {
Int64BinopMatcher mleft(m.left().node());
if (mleft.right().HasResolvedValue() && !m.right().HasResolvedValue()) {
int32_t shift_value =
static_cast<int32_t>(mleft.right().ResolvedValue());
if (shift_value > 0 && shift_value <= 31) {
Emit(kMips64Dlsa, g.DefineAsRegister(node),
g.UseRegister(m.right().node()),
g.UseRegister(mleft.left().node()),
g.TempImmediate(shift_value));
return;
}
}
}
}
VisitBinop(this, node, kMips64Dadd, true, kMips64Dadd);
}
void InstructionSelector::VisitInt32Sub(Node* node) {
VisitBinop(this, node, kMips64Sub);
}
void InstructionSelector::VisitInt64Sub(Node* node) {
VisitBinop(this, node, kMips64Dsub);
}
void InstructionSelector::VisitInt32Mul(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
if (m.right().HasResolvedValue() && m.right().ResolvedValue() > 0) {
uint32_t value = static_cast<uint32_t>(m.right().ResolvedValue());
if (base::bits::IsPowerOfTwo(value)) {
Emit(kMips64Shl | AddressingModeField::encode(kMode_None),
g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.TempImmediate(base::bits::WhichPowerOfTwo(value)));
return;
}
if (base::bits::IsPowerOfTwo(value - 1) && kArchVariant == kMips64r6 &&
value - 1 > 0 && value - 1 <= 31) {
Emit(kMips64Lsa, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.UseRegister(m.left().node()),
g.TempImmediate(base::bits::WhichPowerOfTwo(value - 1)));
return;
}
if (base::bits::IsPowerOfTwo(value + 1)) {
InstructionOperand temp = g.TempRegister();
Emit(kMips64Shl | AddressingModeField::encode(kMode_None), temp,
g.UseRegister(m.left().node()),
g.TempImmediate(base::bits::WhichPowerOfTwo(value + 1)));
Emit(kMips64Sub | AddressingModeField::encode(kMode_None),
g.DefineAsRegister(node), temp, g.UseRegister(m.left().node()));
return;
}
}
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
if (CanCover(node, left) && CanCover(node, right)) {
if (left->opcode() == IrOpcode::kWord64Sar &&
right->opcode() == IrOpcode::kWord64Sar) {
Int64BinopMatcher leftInput(left), rightInput(right);
if (leftInput.right().Is(32) && rightInput.right().Is(32)) {
// Combine untagging shifts with Dmul high.
Emit(kMips64DMulHigh, g.DefineSameAsFirst(node),
g.UseRegister(leftInput.left().node()),
g.UseRegister(rightInput.left().node()));
return;
}
}
}
VisitRRR(this, kMips64Mul, node);
}
void InstructionSelector::VisitInt32MulHigh(Node* node) {
VisitRRR(this, kMips64MulHigh, node);
}
void InstructionSelector::VisitUint32MulHigh(Node* node) {
VisitRRR(this, kMips64MulHighU, node);
}
void InstructionSelector::VisitInt64Mul(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
// TODO(dusmil): Add optimization for shifts larger than 32.
if (m.right().HasResolvedValue() && m.right().ResolvedValue() > 0) {
uint32_t value = static_cast<uint32_t>(m.right().ResolvedValue());
if (base::bits::IsPowerOfTwo(value)) {
Emit(kMips64Dshl | AddressingModeField::encode(kMode_None),
g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.TempImmediate(base::bits::WhichPowerOfTwo(value)));
return;
}
if (base::bits::IsPowerOfTwo(value - 1) && kArchVariant == kMips64r6 &&
value - 1 > 0 && value - 1 <= 31) {
// Dlsa macro will handle the shifting value out of bound cases.
Emit(kMips64Dlsa, g.DefineAsRegister(node),
g.UseRegister(m.left().node()), g.UseRegister(m.left().node()),
g.TempImmediate(base::bits::WhichPowerOfTwo(value - 1)));
return;
}
if (base::bits::IsPowerOfTwo(value + 1)) {
InstructionOperand temp = g.TempRegister();
Emit(kMips64Dshl | AddressingModeField::encode(kMode_None), temp,
g.UseRegister(m.left().node()),
g.TempImmediate(base::bits::WhichPowerOfTwo(value + 1)));
Emit(kMips64Dsub | AddressingModeField::encode(kMode_None),
g.DefineAsRegister(node), temp, g.UseRegister(m.left().node()));
return;
}
}
Emit(kMips64Dmul, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitInt32Div(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
if (CanCover(node, left) && CanCover(node, right)) {
if (left->opcode() == IrOpcode::kWord64Sar &&
right->opcode() == IrOpcode::kWord64Sar) {
Int64BinopMatcher rightInput(right), leftInput(left);
if (rightInput.right().Is(32) && leftInput.right().Is(32)) {
// Combine both shifted operands with Ddiv.
Emit(kMips64Ddiv, g.DefineSameAsFirst(node),
g.UseRegister(leftInput.left().node()),
g.UseRegister(rightInput.left().node()));
return;
}
}
}
Emit(kMips64Div, g.DefineSameAsFirst(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitUint32Div(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
Emit(kMips64DivU, g.DefineSameAsFirst(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitInt32Mod(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
if (CanCover(node, left) && CanCover(node, right)) {
if (left->opcode() == IrOpcode::kWord64Sar &&
right->opcode() == IrOpcode::kWord64Sar) {
Int64BinopMatcher rightInput(right), leftInput(left);
if (rightInput.right().Is(32) && leftInput.right().Is(32)) {
// Combine both shifted operands with Dmod.
Emit(kMips64Dmod, g.DefineSameAsFirst(node),
g.UseRegister(leftInput.left().node()),
g.UseRegister(rightInput.left().node()));
return;
}
}
}
Emit(kMips64Mod, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitUint32Mod(Node* node) {
Mips64OperandGenerator g(this);
Int32BinopMatcher m(node);
Emit(kMips64ModU, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitInt64Div(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
Emit(kMips64Ddiv, g.DefineSameAsFirst(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitUint64Div(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
Emit(kMips64DdivU, g.DefineSameAsFirst(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitInt64Mod(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
Emit(kMips64Dmod, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitUint64Mod(Node* node) {
Mips64OperandGenerator g(this);
Int64BinopMatcher m(node);
Emit(kMips64DmodU, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
g.UseRegister(m.right().node()));
}
void InstructionSelector::VisitChangeFloat32ToFloat64(Node* node) {
VisitRR(this, kMips64CvtDS, node);
}
void InstructionSelector::VisitRoundInt32ToFloat32(Node* node) {
VisitRR(this, kMips64CvtSW, node);
}
void InstructionSelector::VisitRoundUint32ToFloat32(Node* node) {
VisitRR(this, kMips64CvtSUw, node);
}
void InstructionSelector::VisitChangeInt32ToFloat64(Node* node) {
VisitRR(this, kMips64CvtDW, node);
}
void InstructionSelector::VisitChangeInt64ToFloat64(Node* node) {
VisitRR(this, kMips64CvtDL, node);
}
void InstructionSelector::VisitChangeUint32ToFloat64(Node* node) {
VisitRR(this, kMips64CvtDUw, node);
}
void InstructionSelector::VisitTruncateFloat32ToInt32(Node* node) {
Mips64OperandGenerator g(this);
InstructionCode opcode = kMips64TruncWS;
TruncateKind kind = OpParameter<TruncateKind>(node->op());
if (kind == TruncateKind::kSetOverflowToMin) {
opcode |= MiscField::encode(true);
}
Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitTruncateFloat32ToUint32(Node* node) {
Mips64OperandGenerator g(this);
InstructionCode opcode = kMips64TruncUwS;
TruncateKind kind = OpParameter<TruncateKind>(node->op());
if (kind == TruncateKind::kSetOverflowToMin) {
opcode |= MiscField::encode(true);
}
Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitChangeFloat64ToInt32(Node* node) {
Mips64OperandGenerator g(this);
Node* value = node->InputAt(0);
// Match ChangeFloat64ToInt32(Float64Round##OP) to corresponding instruction
// which does rounding and conversion to integer format.
if (CanCover(node, value)) {
switch (value->opcode()) {
case IrOpcode::kFloat64RoundDown:
Emit(kMips64FloorWD, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
case IrOpcode::kFloat64RoundUp:
Emit(kMips64CeilWD, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
case IrOpcode::kFloat64RoundTiesEven:
Emit(kMips64RoundWD, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
case IrOpcode::kFloat64RoundTruncate:
Emit(kMips64TruncWD, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
default:
break;
}
if (value->opcode() == IrOpcode::kChangeFloat32ToFloat64) {
Node* next = value->InputAt(0);
if (CanCover(value, next)) {
// Match ChangeFloat64ToInt32(ChangeFloat32ToFloat64(Float64Round##OP))
switch (next->opcode()) {
case IrOpcode::kFloat32RoundDown:
Emit(kMips64FloorWS, g.DefineAsRegister(node),
g.UseRegister(next->InputAt(0)));
return;
case IrOpcode::kFloat32RoundUp:
Emit(kMips64CeilWS, g.DefineAsRegister(node),
g.UseRegister(next->InputAt(0)));
return;
case IrOpcode::kFloat32RoundTiesEven:
Emit(kMips64RoundWS, g.DefineAsRegister(node),
g.UseRegister(next->InputAt(0)));
return;
case IrOpcode::kFloat32RoundTruncate:
Emit(kMips64TruncWS, g.DefineAsRegister(node),
g.UseRegister(next->InputAt(0)));
return;
default:
Emit(kMips64TruncWS, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
}
} else {
// Match float32 -> float64 -> int32 representation change path.
Emit(kMips64TruncWS, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
}
}
}
VisitRR(this, kMips64TruncWD, node);
}
void InstructionSelector::VisitChangeFloat64ToInt64(Node* node) {
VisitRR(this, kMips64TruncLD, node);
}
void InstructionSelector::VisitChangeFloat64ToUint32(Node* node) {
VisitRR(this, kMips64TruncUwD, node);
}
void InstructionSelector::VisitChangeFloat64ToUint64(Node* node) {
VisitRR(this, kMips64TruncUlD, node);
}
void InstructionSelector::VisitTruncateFloat64ToUint32(Node* node) {
VisitRR(this, kMips64TruncUwD, node);
}
void InstructionSelector::VisitTruncateFloat64ToInt64(Node* node) {
Mips64OperandGenerator g(this);
InstructionCode opcode = kMips64TruncLD;
TruncateKind kind = OpParameter<TruncateKind>(node->op());
if (kind == TruncateKind::kSetOverflowToMin) {
opcode |= MiscField::encode(true);
}
Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitTryTruncateFloat32ToInt64(Node* node) {
Mips64OperandGenerator g(this);
InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))};
InstructionOperand outputs[2];
size_t output_count = 0;
outputs[output_count++] = g.DefineAsRegister(node);
Node* success_output = NodeProperties::FindProjection(node, 1);
if (success_output) {
outputs[output_count++] = g.DefineAsRegister(success_output);
}
this->Emit(kMips64TruncLS, output_count, outputs, 1, inputs);
}
void InstructionSelector::VisitTryTruncateFloat64ToInt64(Node* node) {
Mips64OperandGenerator g(this);
InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))};
InstructionOperand outputs[2];
size_t output_count = 0;
outputs[output_count++] = g.DefineAsRegister(node);
Node* success_output = NodeProperties::FindProjection(node, 1);
if (success_output) {
outputs[output_count++] = g.DefineAsRegister(success_output);
}
Emit(kMips64TruncLD, output_count, outputs, 1, inputs);
}
void InstructionSelector::VisitTryTruncateFloat32ToUint64(Node* node) {
Mips64OperandGenerator g(this);
InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))};
InstructionOperand outputs[2];
size_t output_count = 0;
outputs[output_count++] = g.DefineAsRegister(node);
Node* success_output = NodeProperties::FindProjection(node, 1);
if (success_output) {
outputs[output_count++] = g.DefineAsRegister(success_output);
}
Emit(kMips64TruncUlS, output_count, outputs, 1, inputs);
}
void InstructionSelector::VisitTryTruncateFloat64ToUint64(Node* node) {
Mips64OperandGenerator g(this);
InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))};
InstructionOperand outputs[2];
size_t output_count = 0;
outputs[output_count++] = g.DefineAsRegister(node);
Node* success_output = NodeProperties::FindProjection(node, 1);
if (success_output) {
outputs[output_count++] = g.DefineAsRegister(success_output);
}
Emit(kMips64TruncUlD, output_count, outputs, 1, inputs);
}
void InstructionSelector::VisitBitcastWord32ToWord64(Node* node) {
UNIMPLEMENTED();
}
void InstructionSelector::VisitChangeInt32ToInt64(Node* node) {
Node* value = node->InputAt(0);
if (value->opcode() == IrOpcode::kLoad && CanCover(node, value)) {
// Generate sign-extending load.
LoadRepresentation load_rep = LoadRepresentationOf(value->op());
InstructionCode opcode = kArchNop;
switch (load_rep.representation()) {
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kWord8:
opcode = load_rep.IsUnsigned() ? kMips64Lbu : kMips64Lb;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsUnsigned() ? kMips64Lhu : kMips64Lh;
break;
case MachineRepresentation::kWord32:
opcode = kMips64Lw;
break;
default:
UNREACHABLE();
}
EmitLoad(this, value, opcode, node);
} else {
Mips64OperandGenerator g(this);
Emit(kMips64Shl, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)),
g.TempImmediate(0));
}
}
bool InstructionSelector::ZeroExtendsWord32ToWord64NoPhis(Node* node) {
DCHECK_NE(node->opcode(), IrOpcode::kPhi);
switch (node->opcode()) {
// 32-bit operations will write their result in a 64 bit register,
// clearing the top 32 bits of the destination register.
case IrOpcode::kUint32Div:
case IrOpcode::kUint32Mod:
case IrOpcode::kUint32MulHigh:
return true;
case IrOpcode::kLoad: {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
if (load_rep.IsUnsigned()) {
switch (load_rep.representation()) {
case MachineRepresentation::kWord8:
case MachineRepresentation::kWord16:
case MachineRepresentation::kWord32:
return true;
default:
return false;
}
}
return false;
}
default:
return false;
}
}
void InstructionSelector::VisitChangeUint32ToUint64(Node* node) {
Mips64OperandGenerator g(this);
Node* value = node->InputAt(0);
if (ZeroExtendsWord32ToWord64(value)) {
Emit(kArchNop, g.DefineSameAsFirst(node), g.Use(value));
return;
}
Emit(kMips64Dext, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)),
g.TempImmediate(0), g.TempImmediate(32));
}
void InstructionSelector::VisitTruncateInt64ToInt32(Node* node) {
Mips64OperandGenerator g(this);
Node* value = node->InputAt(0);
if (CanCover(node, value)) {
switch (value->opcode()) {
case IrOpcode::kWord64Sar: {
if (CanCoverTransitively(node, value, value->InputAt(0)) &&
TryEmitExtendingLoad(this, value, node)) {
return;
} else {
Int64BinopMatcher m(value);
if (m.right().IsInRange(32, 63)) {
// After smi untagging no need for truncate. Combine sequence.
Emit(kMips64Dsar, g.DefineSameAsFirst(node),
g.UseRegister(m.left().node()),
g.UseImmediate(m.right().node()));
return;
}
}
break;
}
default:
break;
}
}
Emit(kMips64Ext, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)),
g.TempImmediate(0), g.TempImmediate(32));
}
void InstructionSelector::VisitTruncateFloat64ToFloat32(Node* node) {
Mips64OperandGenerator g(this);
Node* value = node->InputAt(0);
// Match TruncateFloat64ToFloat32(ChangeInt32ToFloat64) to corresponding
// instruction.
if (CanCover(node, value) &&
value->opcode() == IrOpcode::kChangeInt32ToFloat64) {
Emit(kMips64CvtSW, g.DefineAsRegister(node),
g.UseRegister(value->InputAt(0)));
return;
}
VisitRR(this, kMips64CvtSD, node);
}
void InstructionSelector::VisitTruncateFloat64ToWord32(Node* node) {
VisitRR(this, kArchTruncateDoubleToI, node);
}
void InstructionSelector::VisitRoundFloat64ToInt32(Node* node) {
VisitRR(this, kMips64TruncWD, node);
}
void InstructionSelector::VisitRoundInt64ToFloat32(Node* node) {
VisitRR(this, kMips64CvtSL, node);
}
void InstructionSelector::VisitRoundInt64ToFloat64(Node* node) {
VisitRR(this, kMips64CvtDL, node);
}
void InstructionSelector::VisitRoundUint64ToFloat32(Node* node) {
VisitRR(this, kMips64CvtSUl, node);
}
void InstructionSelector::VisitRoundUint64ToFloat64(Node* node) {
VisitRR(this, kMips64CvtDUl, node);
}
void InstructionSelector::VisitBitcastFloat32ToInt32(Node* node) {
VisitRR(this, kMips64Float64ExtractLowWord32, node);
}
void InstructionSelector::VisitBitcastFloat64ToInt64(Node* node) {
VisitRR(this, kMips64BitcastDL, node);
}
void InstructionSelector::VisitBitcastInt32ToFloat32(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Float64InsertLowWord32, g.DefineAsRegister(node),
ImmediateOperand(ImmediateOperand::INLINE, 0),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitBitcastInt64ToFloat64(Node* node) {
VisitRR(this, kMips64BitcastLD, node);
}
void InstructionSelector::VisitFloat32Add(Node* node) {
// Optimization with Madd.S(z, x, y) is intentionally removed.
// See explanation for madd_s in assembler-mips64.cc.
VisitRRR(this, kMips64AddS, node);
}
void InstructionSelector::VisitFloat64Add(Node* node) {
// Optimization with Madd.D(z, x, y) is intentionally removed.
// See explanation for madd_d in assembler-mips64.cc.
VisitRRR(this, kMips64AddD, node);
}
void InstructionSelector::VisitFloat32Sub(Node* node) {
// Optimization with Msub.S(z, x, y) is intentionally removed.
// See explanation for madd_s in assembler-mips64.cc.
VisitRRR(this, kMips64SubS, node);
}
void InstructionSelector::VisitFloat64Sub(Node* node) {
// Optimization with Msub.D(z, x, y) is intentionally removed.
// See explanation for madd_d in assembler-mips64.cc.
VisitRRR(this, kMips64SubD, node);
}
void InstructionSelector::VisitFloat32Mul(Node* node) {
VisitRRR(this, kMips64MulS, node);
}
void InstructionSelector::VisitFloat64Mul(Node* node) {
VisitRRR(this, kMips64MulD, node);
}
void InstructionSelector::VisitFloat32Div(Node* node) {
VisitRRR(this, kMips64DivS, node);
}
void InstructionSelector::VisitFloat64Div(Node* node) {
VisitRRR(this, kMips64DivD, node);
}
void InstructionSelector::VisitFloat64Mod(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64ModD, g.DefineAsFixed(node, f0),
g.UseFixed(node->InputAt(0), f12), g.UseFixed(node->InputAt(1), f14))
->MarkAsCall();
}
void InstructionSelector::VisitFloat32Max(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Float32Max, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)));
}
void InstructionSelector::VisitFloat64Max(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Float64Max, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)));
}
void InstructionSelector::VisitFloat32Min(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Float32Min, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)));
}
void InstructionSelector::VisitFloat64Min(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Float64Min, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)));
}
void InstructionSelector::VisitFloat32Abs(Node* node) {
VisitRR(this, kMips64AbsS, node);
}
void InstructionSelector::VisitFloat64Abs(Node* node) {
VisitRR(this, kMips64AbsD, node);
}
void InstructionSelector::VisitFloat32Sqrt(Node* node) {
VisitRR(this, kMips64SqrtS, node);
}
void InstructionSelector::VisitFloat64Sqrt(Node* node) {
VisitRR(this, kMips64SqrtD, node);
}
void InstructionSelector::VisitFloat32RoundDown(Node* node) {
VisitRR(this, kMips64Float32RoundDown, node);
}
void InstructionSelector::VisitFloat64RoundDown(Node* node) {
VisitRR(this, kMips64Float64RoundDown, node);
}
void InstructionSelector::VisitFloat32RoundUp(Node* node) {
VisitRR(this, kMips64Float32RoundUp, node);
}
void InstructionSelector::VisitFloat64RoundUp(Node* node) {
VisitRR(this, kMips64Float64RoundUp, node);
}
void InstructionSelector::VisitFloat32RoundTruncate(Node* node) {
VisitRR(this, kMips64Float32RoundTruncate, node);
}
void InstructionSelector::VisitFloat64RoundTruncate(Node* node) {
VisitRR(this, kMips64Float64RoundTruncate, node);
}
void InstructionSelector::VisitFloat64RoundTiesAway(Node* node) {
UNREACHABLE();
}
void InstructionSelector::VisitFloat32RoundTiesEven(Node* node) {
VisitRR(this, kMips64Float32RoundTiesEven, node);
}
void InstructionSelector::VisitFloat64RoundTiesEven(Node* node) {
VisitRR(this, kMips64Float64RoundTiesEven, node);
}
void InstructionSelector::VisitFloat32Neg(Node* node) {
VisitRR(this, kMips64NegS, node);
}
void InstructionSelector::VisitFloat64Neg(Node* node) {
VisitRR(this, kMips64NegD, node);
}
void InstructionSelector::VisitFloat64Ieee754Binop(Node* node,
InstructionCode opcode) {
Mips64OperandGenerator g(this);
Emit(opcode, g.DefineAsFixed(node, f0), g.UseFixed(node->InputAt(0), f2),
g.UseFixed(node->InputAt(1), f4))
->MarkAsCall();
}
void InstructionSelector::VisitFloat64Ieee754Unop(Node* node,
InstructionCode opcode) {
Mips64OperandGenerator g(this);
Emit(opcode, g.DefineAsFixed(node, f0), g.UseFixed(node->InputAt(0), f12))
->MarkAsCall();
}
void InstructionSelector::EmitPrepareArguments(
ZoneVector<PushParameter>* arguments, const CallDescriptor* call_descriptor,
Node* node) {
Mips64OperandGenerator g(this);
// Prepare for C function call.
if (call_descriptor->IsCFunctionCall()) {
Emit(kArchPrepareCallCFunction | MiscField::encode(static_cast<int>(
call_descriptor->ParameterCount())),
0, nullptr, 0, nullptr);
// Poke any stack arguments.
int slot = kCArgSlotCount;
for (PushParameter input : (*arguments)) {
Emit(kMips64StoreToStackSlot, g.NoOutput(), g.UseRegister(input.node),
g.TempImmediate(slot << kSystemPointerSizeLog2));
++slot;
}
} else {
int push_count = static_cast<int>(call_descriptor->StackParameterCount());
if (push_count > 0) {
// Calculate needed space
int stack_size = 0;
for (PushParameter input : (*arguments)) {
if (input.node) {
stack_size += input.location.GetSizeInPointers();
}
}
Emit(kMips64StackClaim, g.NoOutput(),
g.TempImmediate(stack_size << kSystemPointerSizeLog2));
}
for (size_t n = 0; n < arguments->size(); ++n) {
PushParameter input = (*arguments)[n];
if (input.node) {
Emit(kMips64StoreToStackSlot, g.NoOutput(), g.UseRegister(input.node),
g.TempImmediate(static_cast<int>(n << kSystemPointerSizeLog2)));
}
}
}
}
void InstructionSelector::EmitPrepareResults(
ZoneVector<PushParameter>* results, const CallDescriptor* call_descriptor,
Node* node) {
Mips64OperandGenerator g(this);
for (PushParameter output : *results) {
if (!output.location.IsCallerFrameSlot()) continue;
// Skip any alignment holes in nodes.
if (output.node != nullptr) {
DCHECK(!call_descriptor->IsCFunctionCall());
if (output.location.GetType() == MachineType::Float32()) {
MarkAsFloat32(output.node);
} else if (output.location.GetType() == MachineType::Float64()) {
MarkAsFloat64(output.node);
} else if (output.location.GetType() == MachineType::Simd128()) {
MarkAsSimd128(output.node);
}
int offset = call_descriptor->GetOffsetToReturns();
int reverse_slot = -output.location.GetLocation() - offset;
Emit(kMips64Peek, g.DefineAsRegister(output.node),
g.UseImmediate(reverse_slot));
}
}
}
bool InstructionSelector::IsTailCallAddressImmediate() { return false; }
void InstructionSelector::VisitUnalignedLoad(Node* node) {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
Mips64OperandGenerator g(this);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
ArchOpcode opcode;
switch (load_rep.representation()) {
case MachineRepresentation::kFloat32:
opcode = kMips64Ulwc1;
break;
case MachineRepresentation::kFloat64:
opcode = kMips64Uldc1;
break;
case MachineRepresentation::kWord8:
opcode = load_rep.IsUnsigned() ? kMips64Lbu : kMips64Lb;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsUnsigned() ? kMips64Ulhu : kMips64Ulh;
break;
case MachineRepresentation::kWord32:
opcode = load_rep.IsUnsigned() ? kMips64Ulwu : kMips64Ulw;
break;
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
case MachineRepresentation::kWord64:
opcode = kMips64Uld;
break;
case MachineRepresentation::kSimd128:
opcode = kMips64MsaLd;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kCompressedPointer: // Fall through.
case MachineRepresentation::kCompressed: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
}
if (g.CanBeImmediate(index, opcode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), g.UseRegister(base), g.UseImmediate(index));
} else {
InstructionOperand addr_reg = g.TempRegister();
Emit(kMips64Dadd | AddressingModeField::encode(kMode_None), addr_reg,
g.UseRegister(index), g.UseRegister(base));
// Emit desired load opcode, using temp addr_reg.
Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), addr_reg, g.TempImmediate(0));
}
}
void InstructionSelector::VisitUnalignedStore(Node* node) {
Mips64OperandGenerator g(this);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* value = node->InputAt(2);
UnalignedStoreRepresentation rep = UnalignedStoreRepresentationOf(node->op());
ArchOpcode opcode;
switch (rep) {
case MachineRepresentation::kFloat32:
opcode = kMips64Uswc1;
break;
case MachineRepresentation::kFloat64:
opcode = kMips64Usdc1;
break;
case MachineRepresentation::kWord8:
opcode = kMips64Sb;
break;
case MachineRepresentation::kWord16:
opcode = kMips64Ush;
break;
case MachineRepresentation::kWord32:
opcode = kMips64Usw;
break;
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
case MachineRepresentation::kWord64:
opcode = kMips64Usd;
break;
case MachineRepresentation::kSimd128:
opcode = kMips64MsaSt;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kCompressedPointer: // Fall through.
case MachineRepresentation::kCompressed: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
}
if (g.CanBeImmediate(index, opcode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
g.UseRegister(base), g.UseImmediate(index),
g.UseRegisterOrImmediateZero(value));
} else {
InstructionOperand addr_reg = g.TempRegister();
Emit(kMips64Dadd | AddressingModeField::encode(kMode_None), addr_reg,
g.UseRegister(index), g.UseRegister(base));
// Emit desired store opcode, using temp addr_reg.
Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
addr_reg, g.TempImmediate(0), g.UseRegisterOrImmediateZero(value));
}
}
namespace {
// Shared routine for multiple compare operations.
static void VisitCompare(InstructionSelector* selector, InstructionCode opcode,
InstructionOperand left, InstructionOperand right,
FlagsContinuation* cont) {
selector->EmitWithContinuation(opcode, left, right, cont);
}
// Shared routine for multiple float32 compare operations.
void VisitFloat32Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
Mips64OperandGenerator g(selector);
Float32BinopMatcher m(node);
InstructionOperand lhs, rhs;
lhs = m.left().IsZero() ? g.UseImmediate(m.left().node())
: g.UseRegister(m.left().node());
rhs = m.right().IsZero() ? g.UseImmediate(m.right().node())
: g.UseRegister(m.right().node());
VisitCompare(selector, kMips64CmpS, lhs, rhs, cont);
}
// Shared routine for multiple float64 compare operations.
void VisitFloat64Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
Mips64OperandGenerator g(selector);
Float64BinopMatcher m(node);
InstructionOperand lhs, rhs;
lhs = m.left().IsZero() ? g.UseImmediate(m.left().node())
: g.UseRegister(m.left().node());
rhs = m.right().IsZero() ? g.UseImmediate(m.right().node())
: g.UseRegister(m.right().node());
VisitCompare(selector, kMips64CmpD, lhs, rhs, cont);
}
// Shared routine for multiple word compare operations.
void VisitWordCompare(InstructionSelector* selector, Node* node,
InstructionCode opcode, FlagsContinuation* cont,
bool commutative) {
Mips64OperandGenerator g(selector);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
// Match immediates on left or right side of comparison.
if (g.CanBeImmediate(right, opcode)) {
if (opcode == kMips64Tst) {
VisitCompare(selector, opcode, g.UseRegister(left), g.UseImmediate(right),
cont);
} else {
switch (cont->condition()) {
case kEqual:
case kNotEqual:
if (cont->IsSet()) {
VisitCompare(selector, opcode, g.UseRegister(left),
g.UseImmediate(right), cont);
} else {
VisitCompare(selector, opcode, g.UseRegister(left),
g.UseRegister(right), cont);
}
break;
case kSignedLessThan:
case kSignedGreaterThanOrEqual:
case kUnsignedLessThan:
case kUnsignedGreaterThanOrEqual:
VisitCompare(selector, opcode, g.UseRegister(left),
g.UseImmediate(right), cont);
break;
default:
VisitCompare(selector, opcode, g.UseRegister(left),
g.UseRegister(right), cont);
}
}
} else if (g.CanBeImmediate(left, opcode)) {
if (!commutative) cont->Commute();
if (opcode == kMips64Tst) {
VisitCompare(selector, opcode, g.UseRegister(right), g.UseImmediate(left),
cont);
} else {
switch (cont->condition()) {
case kEqual:
case kNotEqual:
if (cont->IsSet()) {
VisitCompare(selector, opcode, g.UseRegister(right),
g.UseImmediate(left), cont);
} else {
VisitCompare(selector, opcode, g.UseRegister(right),
g.UseRegister(left), cont);
}
break;
case kSignedLessThan:
case kSignedGreaterThanOrEqual:
case kUnsignedLessThan:
case kUnsignedGreaterThanOrEqual:
VisitCompare(selector, opcode, g.UseRegister(right),
g.UseImmediate(left), cont);
break;
default:
VisitCompare(selector, opcode, g.UseRegister(right),
g.UseRegister(left), cont);
}
}
} else {
VisitCompare(selector, opcode, g.UseRegister(left), g.UseRegister(right),
cont);
}
}
bool IsNodeUnsigned(Node* n) {
NodeMatcher m(n);
if (m.IsLoad() || m.IsUnalignedLoad() || m.IsPoisonedLoad() ||
m.IsProtectedLoad() || m.IsWord32AtomicLoad() || m.IsWord64AtomicLoad()) {
LoadRepresentation load_rep = LoadRepresentationOf(n->op());
return load_rep.IsUnsigned();
} else {
return m.IsUint32Div() || m.IsUint32LessThan() ||
m.IsUint32LessThanOrEqual() || m.IsUint32Mod() ||
m.IsUint32MulHigh() || m.IsChangeFloat64ToUint32() ||
m.IsTruncateFloat64ToUint32() || m.IsTruncateFloat32ToUint32();
}
}
// Shared routine for multiple word compare operations.
void VisitFullWord32Compare(InstructionSelector* selector, Node* node,
InstructionCode opcode, FlagsContinuation* cont) {
Mips64OperandGenerator g(selector);
InstructionOperand leftOp = g.TempRegister();
InstructionOperand rightOp = g.TempRegister();
selector->Emit(kMips64Dshl, leftOp, g.UseRegister(node->InputAt(0)),
g.TempImmediate(32));
selector->Emit(kMips64Dshl, rightOp, g.UseRegister(node->InputAt(1)),
g.TempImmediate(32));
VisitCompare(selector, opcode, leftOp, rightOp, cont);
}
void VisitOptimizedWord32Compare(InstructionSelector* selector, Node* node,
InstructionCode opcode,
FlagsContinuation* cont) {
if (FLAG_debug_code) {
Mips64OperandGenerator g(selector);
InstructionOperand leftOp = g.TempRegister();
InstructionOperand rightOp = g.TempRegister();
InstructionOperand optimizedResult = g.TempRegister();
InstructionOperand fullResult = g.TempRegister();
FlagsCondition condition = cont->condition();
InstructionCode testOpcode = opcode |
FlagsConditionField::encode(condition) |
FlagsModeField::encode(kFlags_set);
selector->Emit(testOpcode, optimizedResult, g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(1)));
selector->Emit(kMips64Dshl, leftOp, g.UseRegister(node->InputAt(0)),
g.TempImmediate(32));
selector->Emit(kMips64Dshl, rightOp, g.UseRegister(node->InputAt(1)),
g.TempImmediate(32));
selector->Emit(testOpcode, fullResult, leftOp, rightOp);
selector->Emit(
kMips64AssertEqual, g.NoOutput(), optimizedResult, fullResult,
g.TempImmediate(
static_cast<int>(AbortReason::kUnsupportedNonPrimitiveCompare)));
}
VisitWordCompare(selector, node, opcode, cont, false);
}
void VisitWord32Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
// MIPS64 doesn't support Word32 compare instructions. Instead it relies
// that the values in registers are correctly sign-extended and uses
// Word64 comparison instead. This behavior is correct in most cases,
// but doesn't work when comparing signed with unsigned operands.
// We could simulate full Word32 compare in all cases but this would
// create an unnecessary overhead since unsigned integers are rarely
// used in JavaScript.
// The solution proposed here tries to match a comparison of signed
// with unsigned operand, and perform full Word32Compare only
// in those cases. Unfortunately, the solution is not complete because
// it might skip cases where Word32 full compare is needed, so
// basically it is a hack.
// When call to a host function in simulator, if the function return a
// int32 value, the simulator do not sign-extended to int64 because in
// simulator we do not know the function whether return a int32 or int64.
// so we need do a full word32 compare in this case.
#ifndef USE_SIMULATOR
if (IsNodeUnsigned(node->InputAt(0)) != IsNodeUnsigned(node->InputAt(1))) {
#else
if (IsNodeUnsigned(node->InputAt(0)) != IsNodeUnsigned(node->InputAt(1)) ||
node->InputAt(0)->opcode() == IrOpcode::kCall ||
node->InputAt(1)->opcode() == IrOpcode::kCall ) {
#endif
VisitFullWord32Compare(selector, node, kMips64Cmp, cont);
} else {
VisitOptimizedWord32Compare(selector, node, kMips64Cmp, cont);
}
}
void VisitWord64Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
VisitWordCompare(selector, node, kMips64Cmp, cont, false);
}
void EmitWordCompareZero(InstructionSelector* selector, Node* value,
FlagsContinuation* cont) {
Mips64OperandGenerator g(selector);
selector->EmitWithContinuation(kMips64Cmp, g.UseRegister(value),
g.TempImmediate(0), cont);
}
void VisitAtomicLoad(InstructionSelector* selector, Node* node,
ArchOpcode opcode) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
if (g.CanBeImmediate(index, opcode)) {
selector->Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), g.UseRegister(base),
g.UseImmediate(index));
} else {
InstructionOperand addr_reg = g.TempRegister();
selector->Emit(kMips64Dadd | AddressingModeField::encode(kMode_None),
addr_reg, g.UseRegister(index), g.UseRegister(base));
// Emit desired load opcode, using temp addr_reg.
selector->Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), addr_reg, g.TempImmediate(0));
}
}
void VisitAtomicStore(InstructionSelector* selector, Node* node,
ArchOpcode opcode) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* value = node->InputAt(2);
if (g.CanBeImmediate(index, opcode)) {
selector->Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.NoOutput(), g.UseRegister(base), g.UseImmediate(index),
g.UseRegisterOrImmediateZero(value));
} else {
InstructionOperand addr_reg = g.TempRegister();
selector->Emit(kMips64Dadd | AddressingModeField::encode(kMode_None),
addr_reg, g.UseRegister(index), g.UseRegister(base));
// Emit desired store opcode, using temp addr_reg.
selector->Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.NoOutput(), addr_reg, g.TempImmediate(0),
g.UseRegisterOrImmediateZero(value));
}
}
void VisitAtomicExchange(InstructionSelector* selector, Node* node,
ArchOpcode opcode) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* value = node->InputAt(2);
AddressingMode addressing_mode = kMode_MRI;
InstructionOperand inputs[3];
size_t input_count = 0;
inputs[input_count++] = g.UseUniqueRegister(base);
inputs[input_count++] = g.UseUniqueRegister(index);
inputs[input_count++] = g.UseUniqueRegister(value);
InstructionOperand outputs[1];
outputs[0] = g.UseUniqueRegister(node);
InstructionOperand temp[3];
temp[0] = g.TempRegister();
temp[1] = g.TempRegister();
temp[2] = g.TempRegister();
InstructionCode code = opcode | AddressingModeField::encode(addressing_mode);
selector->Emit(code, 1, outputs, input_count, inputs, 3, temp);
}
void VisitAtomicCompareExchange(InstructionSelector* selector, Node* node,
ArchOpcode opcode) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* old_value = node->InputAt(2);
Node* new_value = node->InputAt(3);
AddressingMode addressing_mode = kMode_MRI;
InstructionOperand inputs[4];
size_t input_count = 0;
inputs[input_count++] = g.UseUniqueRegister(base);
inputs[input_count++] = g.UseUniqueRegister(index);
inputs[input_count++] = g.UseUniqueRegister(old_value);
inputs[input_count++] = g.UseUniqueRegister(new_value);
InstructionOperand outputs[1];
outputs[0] = g.UseUniqueRegister(node);
InstructionOperand temp[3];
temp[0] = g.TempRegister();
temp[1] = g.TempRegister();
temp[2] = g.TempRegister();
InstructionCode code = opcode | AddressingModeField::encode(addressing_mode);
selector->Emit(code, 1, outputs, input_count, inputs, 3, temp);
}
void VisitAtomicBinop(InstructionSelector* selector, Node* node,
ArchOpcode opcode) {
Mips64OperandGenerator g(selector);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* value = node->InputAt(2);
AddressingMode addressing_mode = kMode_MRI;
InstructionOperand inputs[3];
size_t input_count = 0;
inputs[input_count++] = g.UseUniqueRegister(base);
inputs[input_count++] = g.UseUniqueRegister(index);
inputs[input_count++] = g.UseUniqueRegister(value);
InstructionOperand outputs[1];
outputs[0] = g.UseUniqueRegister(node);
InstructionOperand temps[4];
temps[0] = g.TempRegister();
temps[1] = g.TempRegister();
temps[2] = g.TempRegister();
temps[3] = g.TempRegister();
InstructionCode code = opcode | AddressingModeField::encode(addressing_mode);
selector->Emit(code, 1, outputs, input_count, inputs, 4, temps);
}
} // namespace
void InstructionSelector::VisitStackPointerGreaterThan(
Node* node, FlagsContinuation* cont) {
StackCheckKind kind = StackCheckKindOf(node->op());
InstructionCode opcode =
kArchStackPointerGreaterThan | MiscField::encode(static_cast<int>(kind));
Mips64OperandGenerator g(this);
// No outputs.
InstructionOperand* const outputs = nullptr;
const int output_count = 0;
// Applying an offset to this stack check requires a temp register. Offsets
// are only applied to the first stack check. If applying an offset, we must
// ensure the input and temp registers do not alias, thus kUniqueRegister.
InstructionOperand temps[] = {g.TempRegister()};
const int temp_count = (kind == StackCheckKind::kJSFunctionEntry ? 1 : 0);
const auto register_mode = (kind == StackCheckKind::kJSFunctionEntry)
? OperandGenerator::kUniqueRegister
: OperandGenerator::kRegister;
Node* const value = node->InputAt(0);
InstructionOperand inputs[] = {g.UseRegisterWithMode(value, register_mode)};
static constexpr int input_count = arraysize(inputs);
EmitWithContinuation(opcode, output_count, outputs, input_count, inputs,
temp_count, temps, cont);
}
// Shared routine for word comparisons against zero.
void InstructionSelector::VisitWordCompareZero(Node* user, Node* value,
FlagsContinuation* cont) {
// Try to combine with comparisons against 0 by simply inverting the branch.
while (CanCover(user, value)) {
if (value->opcode() == IrOpcode::kWord32Equal) {
Int32BinopMatcher m(value);
if (!m.right().Is(0)) break;
user = value;
value = m.left().node();
} else if (value->opcode() == IrOpcode::kWord64Equal) {
Int64BinopMatcher m(value);
if (!m.right().Is(0)) break;
user = value;
value = m.left().node();
} else {
break;
}
cont->Negate();
}
if (CanCover(user, value)) {
switch (value->opcode()) {
case IrOpcode::kWord32Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitWord32Compare(this, value, cont);
case IrOpcode::kInt32LessThan:
cont->OverwriteAndNegateIfEqual(kSignedLessThan);
return VisitWord32Compare(this, value, cont);
case IrOpcode::kInt32LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual);
return VisitWord32Compare(this, value, cont);
case IrOpcode::kUint32LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitWord32Compare(this, value, cont);
case IrOpcode::kUint32LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitWord32Compare(this, value, cont);
case IrOpcode::kWord64Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitWord64Compare(this, value, cont);
case IrOpcode::kInt64LessThan:
cont->OverwriteAndNegateIfEqual(kSignedLessThan);
return VisitWord64Compare(this, value, cont);
case IrOpcode::kInt64LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual);
return VisitWord64Compare(this, value, cont);
case IrOpcode::kUint64LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitWord64Compare(this, value, cont);
case IrOpcode::kUint64LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitWord64Compare(this, value, cont);
case IrOpcode::kFloat32Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitFloat32Compare(this, value, cont);
case IrOpcode::kFloat32LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitFloat32Compare(this, value, cont);
case IrOpcode::kFloat32LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitFloat32Compare(this, value, cont);
case IrOpcode::kFloat64Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitFloat64Compare(this, value, cont);
case IrOpcode::kFloat64LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitFloat64Compare(this, value, cont);
case IrOpcode::kFloat64LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitFloat64Compare(this, value, cont);
case IrOpcode::kProjection:
// Check if this is the overflow output projection of an
// <Operation>WithOverflow node.
if (ProjectionIndexOf(value->op()) == 1u) {
// We cannot combine the <Operation>WithOverflow with this branch
// unless the 0th projection (the use of the actual value of the
// <Operation> is either nullptr, which means there's no use of the
// actual value, or was already defined, which means it is scheduled
// *AFTER* this branch).
Node* const node = value->InputAt(0);
Node* const result = NodeProperties::FindProjection(node, 0);
if (result == nullptr || IsDefined(result)) {
switch (node->opcode()) {
case IrOpcode::kInt32AddWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop(this, node, kMips64Dadd, cont);
case IrOpcode::kInt32SubWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop(this, node, kMips64Dsub, cont);
case IrOpcode::kInt32MulWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop(this, node, kMips64MulOvf, cont);
case IrOpcode::kInt64AddWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop(this, node, kMips64DaddOvf, cont);
case IrOpcode::kInt64SubWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop(this, node, kMips64DsubOvf, cont);
default:
break;
}
}
}
break;
case IrOpcode::kWord32And:
case IrOpcode::kWord64And:
return VisitWordCompare(this, value, kMips64Tst, cont, true);
case IrOpcode::kStackPointerGreaterThan:
cont->OverwriteAndNegateIfEqual(kStackPointerGreaterThanCondition);
return VisitStackPointerGreaterThan(value, cont);
default:
break;
}
}
// Continuation could not be combined with a compare, emit compare against 0.
EmitWordCompareZero(this, value, cont);
}
void InstructionSelector::VisitSwitch(Node* node, const SwitchInfo& sw) {
Mips64OperandGenerator g(this);
InstructionOperand value_operand = g.UseRegister(node->InputAt(0));
// Emit either ArchTableSwitch or ArchBinarySearchSwitch.
if (enable_switch_jump_table_ == kEnableSwitchJumpTable) {
static const size_t kMaxTableSwitchValueRange = 2 << 16;
size_t table_space_cost = 10 + 2 * sw.value_range();
size_t table_time_cost = 3;
size_t lookup_space_cost = 2 + 2 * sw.case_count();
size_t lookup_time_cost = sw.case_count();
if (sw.case_count() > 0 &&
table_space_cost + 3 * table_time_cost <=
lookup_space_cost + 3 * lookup_time_cost &&
sw.min_value() > std::numeric_limits<int32_t>::min() &&
sw.value_range() <= kMaxTableSwitchValueRange) {
InstructionOperand index_operand = value_operand;
if (sw.min_value()) {
index_operand = g.TempRegister();
Emit(kMips64Sub, index_operand, value_operand,
g.TempImmediate(sw.min_value()));
}
// Generate a table lookup.
return EmitTableSwitch(sw, index_operand);
}
}
// Generate a tree of conditional jumps.
return EmitBinarySearchSwitch(sw, value_operand);
}
void InstructionSelector::VisitWord32Equal(Node* const node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
Int32BinopMatcher m(node);
if (m.right().Is(0)) {
return VisitWordCompareZero(m.node(), m.left().node(), &cont);
}
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitInt32LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitInt32LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kSignedLessThanOrEqual, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitUint32LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitUint32LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitInt32AddWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop(this, node, kMips64Dadd, &cont);
}
FlagsContinuation cont;
VisitBinop(this, node, kMips64Dadd, &cont);
}
void InstructionSelector::VisitInt32SubWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop(this, node, kMips64Dsub, &cont);
}
FlagsContinuation cont;
VisitBinop(this, node, kMips64Dsub, &cont);
}
void InstructionSelector::VisitInt32MulWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop(this, node, kMips64MulOvf, &cont);
}
FlagsContinuation cont;
VisitBinop(this, node, kMips64MulOvf, &cont);
}
void InstructionSelector::VisitInt64AddWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop(this, node, kMips64DaddOvf, &cont);
}
FlagsContinuation cont;
VisitBinop(this, node, kMips64DaddOvf, &cont);
}
void InstructionSelector::VisitInt64SubWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop(this, node, kMips64DsubOvf, &cont);
}
FlagsContinuation cont;
VisitBinop(this, node, kMips64DsubOvf, &cont);
}
void InstructionSelector::VisitWord64Equal(Node* const node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
Int64BinopMatcher m(node);
if (m.right().Is(0)) {
return VisitWordCompareZero(m.node(), m.left().node(), &cont);
}
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitInt64LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitInt64LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kSignedLessThanOrEqual, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitUint64LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitUint64LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat32Equal(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
VisitFloat32Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat32LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitFloat32Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat32LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitFloat32Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64Equal(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
VisitFloat64Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitFloat64Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitFloat64Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64ExtractLowWord32(Node* node) {
VisitRR(this, kMips64Float64ExtractLowWord32, node);
}
void InstructionSelector::VisitFloat64ExtractHighWord32(Node* node) {
VisitRR(this, kMips64Float64ExtractHighWord32, node);
}
void InstructionSelector::VisitFloat64SilenceNaN(Node* node) {
VisitRR(this, kMips64Float64SilenceNaN, node);
}
void InstructionSelector::VisitFloat64InsertLowWord32(Node* node) {
Mips64OperandGenerator g(this);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
Emit(kMips64Float64InsertLowWord32, g.DefineSameAsFirst(node),
g.UseRegister(left), g.UseRegister(right));
}
void InstructionSelector::VisitFloat64InsertHighWord32(Node* node) {
Mips64OperandGenerator g(this);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
Emit(kMips64Float64InsertHighWord32, g.DefineSameAsFirst(node),
g.UseRegister(left), g.UseRegister(right));
}
void InstructionSelector::VisitMemoryBarrier(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Sync, g.NoOutput());
}
void InstructionSelector::VisitWord32AtomicLoad(Node* node) {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
ArchOpcode opcode;
switch (load_rep.representation()) {
case MachineRepresentation::kWord8:
opcode =
load_rep.IsSigned() ? kWord32AtomicLoadInt8 : kWord32AtomicLoadUint8;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsSigned() ? kWord32AtomicLoadInt16
: kWord32AtomicLoadUint16;
break;
case MachineRepresentation::kWord32:
opcode = kWord32AtomicLoadWord32;
break;
default:
UNREACHABLE();
}
VisitAtomicLoad(this, node, opcode);
}
void InstructionSelector::VisitWord32AtomicStore(Node* node) {
MachineRepresentation rep = AtomicStoreRepresentationOf(node->op());
ArchOpcode opcode;
switch (rep) {
case MachineRepresentation::kWord8:
opcode = kWord32AtomicStoreWord8;
break;
case MachineRepresentation::kWord16:
opcode = kWord32AtomicStoreWord16;
break;
case MachineRepresentation::kWord32:
opcode = kWord32AtomicStoreWord32;
break;
default:
UNREACHABLE();
}
VisitAtomicStore(this, node, opcode);
}
void InstructionSelector::VisitWord64AtomicLoad(Node* node) {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
ArchOpcode opcode;
switch (load_rep.representation()) {
case MachineRepresentation::kWord8:
opcode = kMips64Word64AtomicLoadUint8;
break;
case MachineRepresentation::kWord16:
opcode = kMips64Word64AtomicLoadUint16;
break;
case MachineRepresentation::kWord32:
opcode = kMips64Word64AtomicLoadUint32;
break;
case MachineRepresentation::kWord64:
opcode = kMips64Word64AtomicLoadUint64;
break;
default:
UNREACHABLE();
}
VisitAtomicLoad(this, node, opcode);
}
void InstructionSelector::VisitWord64AtomicStore(Node* node) {
MachineRepresentation rep = AtomicStoreRepresentationOf(node->op());
ArchOpcode opcode;
switch (rep) {
case MachineRepresentation::kWord8:
opcode = kMips64Word64AtomicStoreWord8;
break;
case MachineRepresentation::kWord16:
opcode = kMips64Word64AtomicStoreWord16;
break;
case MachineRepresentation::kWord32:
opcode = kMips64Word64AtomicStoreWord32;
break;
case MachineRepresentation::kWord64:
opcode = kMips64Word64AtomicStoreWord64;
break;
default:
UNREACHABLE();
}
VisitAtomicStore(this, node, opcode);
}
void InstructionSelector::VisitWord32AtomicExchange(Node* node) {
ArchOpcode opcode;
MachineType type = AtomicOpType(node->op());
if (type == MachineType::Int8()) {
opcode = kWord32AtomicExchangeInt8;
} else if (type == MachineType::Uint8()) {
opcode = kWord32AtomicExchangeUint8;
} else if (type == MachineType::Int16()) {
opcode = kWord32AtomicExchangeInt16;
} else if (type == MachineType::Uint16()) {
opcode = kWord32AtomicExchangeUint16;
} else if (type == MachineType::Int32() || type == MachineType::Uint32()) {
opcode = kWord32AtomicExchangeWord32;
} else {
UNREACHABLE();
}
VisitAtomicExchange(this, node, opcode);
}
void InstructionSelector::VisitWord64AtomicExchange(Node* node) {
ArchOpcode opcode;
MachineType type = AtomicOpType(node->op());
if (type == MachineType::Uint8()) {
opcode = kMips64Word64AtomicExchangeUint8;
} else if (type == MachineType::Uint16()) {
opcode = kMips64Word64AtomicExchangeUint16;
} else if (type == MachineType::Uint32()) {
opcode = kMips64Word64AtomicExchangeUint32;
} else if (type == MachineType::Uint64()) {
opcode = kMips64Word64AtomicExchangeUint64;
} else {
UNREACHABLE();
}
VisitAtomicExchange(this, node, opcode);
}
void InstructionSelector::VisitWord32AtomicCompareExchange(Node* node) {
ArchOpcode opcode;
MachineType type = AtomicOpType(node->op());
if (type == MachineType::Int8()) {
opcode = kWord32AtomicCompareExchangeInt8;
} else if (type == MachineType::Uint8()) {
opcode = kWord32AtomicCompareExchangeUint8;
} else if (type == MachineType::Int16()) {
opcode = kWord32AtomicCompareExchangeInt16;
} else if (type == MachineType::Uint16()) {
opcode = kWord32AtomicCompareExchangeUint16;
} else if (type == MachineType::Int32() || type == MachineType::Uint32()) {
opcode = kWord32AtomicCompareExchangeWord32;
} else {
UNREACHABLE();
}
VisitAtomicCompareExchange(this, node, opcode);
}
void InstructionSelector::VisitWord64AtomicCompareExchange(Node* node) {
ArchOpcode opcode;
MachineType type = AtomicOpType(node->op());
if (type == MachineType::Uint8()) {
opcode = kMips64Word64AtomicCompareExchangeUint8;
} else if (type == MachineType::Uint16()) {
opcode = kMips64Word64AtomicCompareExchangeUint16;
} else if (type == MachineType::Uint32()) {
opcode = kMips64Word64AtomicCompareExchangeUint32;
} else if (type == MachineType::Uint64()) {
opcode = kMips64Word64AtomicCompareExchangeUint64;
} else {
UNREACHABLE();
}
VisitAtomicCompareExchange(this, node, opcode);
}
void InstructionSelector::VisitWord32AtomicBinaryOperation(
Node* node, ArchOpcode int8_op, ArchOpcode uint8_op, ArchOpcode int16_op,
ArchOpcode uint16_op, ArchOpcode word32_op) {
ArchOpcode opcode;
MachineType type = AtomicOpType(node->op());
if (type == MachineType::Int8()) {
opcode = int8_op;
} else if (type == MachineType::Uint8()) {
opcode = uint8_op;
} else if (type == MachineType::Int16()) {
opcode = int16_op;
} else if (type == MachineType::Uint16()) {
opcode = uint16_op;
} else if (type == MachineType::Int32() || type == MachineType::Uint32()) {
opcode = word32_op;
} else {
UNREACHABLE();
}
VisitAtomicBinop(this, node, opcode);
}
#define VISIT_ATOMIC_BINOP(op) \
void InstructionSelector::VisitWord32Atomic##op(Node* node) { \
VisitWord32AtomicBinaryOperation( \
node, kWord32Atomic##op##Int8, kWord32Atomic##op##Uint8, \
kWord32Atomic##op##Int16, kWord32Atomic##op##Uint16, \
kWord32Atomic##op##Word32); \
}
VISIT_ATOMIC_BINOP(Add)
VISIT_ATOMIC_BINOP(Sub)
VISIT_ATOMIC_BINOP(And)
VISIT_ATOMIC_BINOP(Or)
VISIT_ATOMIC_BINOP(Xor)
#undef VISIT_ATOMIC_BINOP
void InstructionSelector::VisitWord64AtomicBinaryOperation(
Node* node, ArchOpcode uint8_op, ArchOpcode uint16_op, ArchOpcode uint32_op,
ArchOpcode uint64_op) {
ArchOpcode opcode;
MachineType type = AtomicOpType(node->op());
if (type == MachineType::Uint8()) {
opcode = uint8_op;
} else if (type == MachineType::Uint16()) {
opcode = uint16_op;
} else if (type == MachineType::Uint32()) {
opcode = uint32_op;
} else if (type == MachineType::Uint64()) {
opcode = uint64_op;
} else {
UNREACHABLE();
}
VisitAtomicBinop(this, node, opcode);
}
#define VISIT_ATOMIC_BINOP(op) \
void InstructionSelector::VisitWord64Atomic##op(Node* node) { \
VisitWord64AtomicBinaryOperation( \
node, kMips64Word64Atomic##op##Uint8, kMips64Word64Atomic##op##Uint16, \
kMips64Word64Atomic##op##Uint32, kMips64Word64Atomic##op##Uint64); \
}
VISIT_ATOMIC_BINOP(Add)
VISIT_ATOMIC_BINOP(Sub)
VISIT_ATOMIC_BINOP(And)
VISIT_ATOMIC_BINOP(Or)
VISIT_ATOMIC_BINOP(Xor)
#undef VISIT_ATOMIC_BINOP
void InstructionSelector::VisitInt32AbsWithOverflow(Node* node) {
UNREACHABLE();
}
void InstructionSelector::VisitInt64AbsWithOverflow(Node* node) {
UNREACHABLE();
}
#define SIMD_TYPE_LIST(V) \
V(F64x2) \
V(F32x4) \
V(I64x2) \
V(I32x4) \
V(I16x8) \
V(I8x16)
#define SIMD_UNOP_LIST(V) \
V(F64x2Abs, kMips64F64x2Abs) \
V(F64x2Neg, kMips64F64x2Neg) \
V(F64x2Sqrt, kMips64F64x2Sqrt) \
V(F64x2Ceil, kMips64F64x2Ceil) \
V(F64x2Floor, kMips64F64x2Floor) \
V(F64x2Trunc, kMips64F64x2Trunc) \
V(F64x2NearestInt, kMips64F64x2NearestInt) \
V(I64x2Neg, kMips64I64x2Neg) \
V(I64x2BitMask, kMips64I64x2BitMask) \
V(F64x2ConvertLowI32x4S, kMips64F64x2ConvertLowI32x4S) \
V(F64x2ConvertLowI32x4U, kMips64F64x2ConvertLowI32x4U) \
V(F64x2PromoteLowF32x4, kMips64F64x2PromoteLowF32x4) \
V(F32x4SConvertI32x4, kMips64F32x4SConvertI32x4) \
V(F32x4UConvertI32x4, kMips64F32x4UConvertI32x4) \
V(F32x4Abs, kMips64F32x4Abs) \
V(F32x4Neg, kMips64F32x4Neg) \
V(F32x4Sqrt, kMips64F32x4Sqrt) \
V(F32x4RecipApprox, kMips64F32x4RecipApprox) \
V(F32x4RecipSqrtApprox, kMips64F32x4RecipSqrtApprox) \
V(F32x4Ceil, kMips64F32x4Ceil) \
V(F32x4Floor, kMips64F32x4Floor) \
V(F32x4Trunc, kMips64F32x4Trunc) \
V(F32x4NearestInt, kMips64F32x4NearestInt) \
V(F32x4DemoteF64x2Zero, kMips64F32x4DemoteF64x2Zero) \
V(I64x2Abs, kMips64I64x2Abs) \
V(I64x2SConvertI32x4Low, kMips64I64x2SConvertI32x4Low) \
V(I64x2SConvertI32x4High, kMips64I64x2SConvertI32x4High) \
V(I64x2UConvertI32x4Low, kMips64I64x2UConvertI32x4Low) \
V(I64x2UConvertI32x4High, kMips64I64x2UConvertI32x4High) \
V(I32x4SConvertF32x4, kMips64I32x4SConvertF32x4) \
V(I32x4UConvertF32x4, kMips64I32x4UConvertF32x4) \
V(I32x4Neg, kMips64I32x4Neg) \
V(I32x4SConvertI16x8Low, kMips64I32x4SConvertI16x8Low) \
V(I32x4SConvertI16x8High, kMips64I32x4SConvertI16x8High) \
V(I32x4UConvertI16x8Low, kMips64I32x4UConvertI16x8Low) \
V(I32x4UConvertI16x8High, kMips64I32x4UConvertI16x8High) \
V(I32x4Abs, kMips64I32x4Abs) \
V(I32x4BitMask, kMips64I32x4BitMask) \
V(I32x4TruncSatF64x2SZero, kMips64I32x4TruncSatF64x2SZero) \
V(I32x4TruncSatF64x2UZero, kMips64I32x4TruncSatF64x2UZero) \
V(I16x8Neg, kMips64I16x8Neg) \
V(I16x8SConvertI8x16Low, kMips64I16x8SConvertI8x16Low) \
V(I16x8SConvertI8x16High, kMips64I16x8SConvertI8x16High) \
V(I16x8UConvertI8x16Low, kMips64I16x8UConvertI8x16Low) \
V(I16x8UConvertI8x16High, kMips64I16x8UConvertI8x16High) \
V(I16x8Abs, kMips64I16x8Abs) \
V(I16x8BitMask, kMips64I16x8BitMask) \
V(I8x16Neg, kMips64I8x16Neg) \
V(I8x16Abs, kMips64I8x16Abs) \
V(I8x16Popcnt, kMips64I8x16Popcnt) \
V(I8x16BitMask, kMips64I8x16BitMask) \
V(S128Not, kMips64S128Not) \
V(V64x2AllTrue, kMips64V64x2AllTrue) \
V(V32x4AllTrue, kMips64V32x4AllTrue) \
V(V16x8AllTrue, kMips64V16x8AllTrue) \
V(V8x16AllTrue, kMips64V8x16AllTrue) \
V(V128AnyTrue, kMips64V128AnyTrue)
#define SIMD_SHIFT_OP_LIST(V) \
V(I64x2Shl) \
V(I64x2ShrS) \
V(I64x2ShrU) \
V(I32x4Shl) \
V(I32x4ShrS) \
V(I32x4ShrU) \
V(I16x8Shl) \
V(I16x8ShrS) \
V(I16x8ShrU) \
V(I8x16Shl) \
V(I8x16ShrS) \
V(I8x16ShrU)
#define SIMD_BINOP_LIST(V) \
V(F64x2Add, kMips64F64x2Add) \
V(F64x2Sub, kMips64F64x2Sub) \
V(F64x2Mul, kMips64F64x2Mul) \
V(F64x2Div, kMips64F64x2Div) \
V(F64x2Min, kMips64F64x2Min) \
V(F64x2Max, kMips64F64x2Max) \
V(F64x2Eq, kMips64F64x2Eq) \
V(F64x2Ne, kMips64F64x2Ne) \
V(F64x2Lt, kMips64F64x2Lt) \
V(F64x2Le, kMips64F64x2Le) \
V(I64x2Eq, kMips64I64x2Eq) \
V(I64x2Ne, kMips64I64x2Ne) \
V(I64x2Add, kMips64I64x2Add) \
V(I64x2Sub, kMips64I64x2Sub) \
V(I64x2Mul, kMips64I64x2Mul) \
V(I64x2GtS, kMips64I64x2GtS) \
V(I64x2GeS, kMips64I64x2GeS) \
V(F32x4Add, kMips64F32x4Add) \
V(F32x4AddHoriz, kMips64F32x4AddHoriz) \
V(F32x4Sub, kMips64F32x4Sub) \
V(F32x4Mul, kMips64F32x4Mul) \
V(F32x4Div, kMips64F32x4Div) \
V(F32x4Max, kMips64F32x4Max) \
V(F32x4Min, kMips64F32x4Min) \
V(F32x4Eq, kMips64F32x4Eq) \
V(F32x4Ne, kMips64F32x4Ne) \
V(F32x4Lt, kMips64F32x4Lt) \
V(F32x4Le, kMips64F32x4Le) \
V(I32x4Add, kMips64I32x4Add) \
V(I32x4AddHoriz, kMips64I32x4AddHoriz) \
V(I32x4Sub, kMips64I32x4Sub) \
V(I32x4Mul, kMips64I32x4Mul) \
V(I32x4MaxS, kMips64I32x4MaxS) \
V(I32x4MinS, kMips64I32x4MinS) \
V(I32x4MaxU, kMips64I32x4MaxU) \
V(I32x4MinU, kMips64I32x4MinU) \
V(I32x4Eq, kMips64I32x4Eq) \
V(I32x4Ne, kMips64I32x4Ne) \
V(I32x4GtS, kMips64I32x4GtS) \
V(I32x4GeS, kMips64I32x4GeS) \
V(I32x4GtU, kMips64I32x4GtU) \
V(I32x4GeU, kMips64I32x4GeU) \
V(I32x4DotI16x8S, kMips64I32x4DotI16x8S) \
V(I16x8Add, kMips64I16x8Add) \
V(I16x8AddSatS, kMips64I16x8AddSatS) \
V(I16x8AddSatU, kMips64I16x8AddSatU) \
V(I16x8AddHoriz, kMips64I16x8AddHoriz) \
V(I16x8Sub, kMips64I16x8Sub) \
V(I16x8SubSatS, kMips64I16x8SubSatS) \
V(I16x8SubSatU, kMips64I16x8SubSatU) \
V(I16x8Mul, kMips64I16x8Mul) \
V(I16x8MaxS, kMips64I16x8MaxS) \
V(I16x8MinS, kMips64I16x8MinS) \
V(I16x8MaxU, kMips64I16x8MaxU) \
V(I16x8MinU, kMips64I16x8MinU) \
V(I16x8Eq, kMips64I16x8Eq) \
V(I16x8Ne, kMips64I16x8Ne) \
V(I16x8GtS, kMips64I16x8GtS) \
V(I16x8GeS, kMips64I16x8GeS) \
V(I16x8GtU, kMips64I16x8GtU) \
V(I16x8GeU, kMips64I16x8GeU) \
V(I16x8RoundingAverageU, kMips64I16x8RoundingAverageU) \
V(I16x8SConvertI32x4, kMips64I16x8SConvertI32x4) \
V(I16x8UConvertI32x4, kMips64I16x8UConvertI32x4) \
V(I16x8Q15MulRSatS, kMips64I16x8Q15MulRSatS) \
V(I8x16Add, kMips64I8x16Add) \
V(I8x16AddSatS, kMips64I8x16AddSatS) \
V(I8x16AddSatU, kMips64I8x16AddSatU) \
V(I8x16Sub, kMips64I8x16Sub) \
V(I8x16SubSatS, kMips64I8x16SubSatS) \
V(I8x16SubSatU, kMips64I8x16SubSatU) \
V(I8x16Mul, kMips64I8x16Mul) \
V(I8x16MaxS, kMips64I8x16MaxS) \
V(I8x16MinS, kMips64I8x16MinS) \
V(I8x16MaxU, kMips64I8x16MaxU) \
V(I8x16MinU, kMips64I8x16MinU) \
V(I8x16Eq, kMips64I8x16Eq) \
V(I8x16Ne, kMips64I8x16Ne) \
V(I8x16GtS, kMips64I8x16GtS) \
V(I8x16GeS, kMips64I8x16GeS) \
V(I8x16GtU, kMips64I8x16GtU) \
V(I8x16GeU, kMips64I8x16GeU) \
V(I8x16RoundingAverageU, kMips64I8x16RoundingAverageU) \
V(I8x16SConvertI16x8, kMips64I8x16SConvertI16x8) \
V(I8x16UConvertI16x8, kMips64I8x16UConvertI16x8) \
V(S128And, kMips64S128And) \
V(S128Or, kMips64S128Or) \
V(S128Xor, kMips64S128Xor) \
V(S128AndNot, kMips64S128AndNot)
void InstructionSelector::VisitS128Const(Node* node) {
Mips64OperandGenerator g(this);
static const int kUint32Immediates = kSimd128Size / sizeof(uint32_t);
uint32_t val[kUint32Immediates];
base::Memcpy(val, S128ImmediateParameterOf(node->op()).data(), kSimd128Size);
// If all bytes are zeros or ones, avoid emitting code for generic constants
bool all_zeros = !(val[0] || val[1] || val[2] || val[3]);
bool all_ones = val[0] == UINT32_MAX && val[1] == UINT32_MAX &&
val[2] == UINT32_MAX && val[3] == UINT32_MAX;
InstructionOperand dst = g.DefineAsRegister(node);
if (all_zeros) {
Emit(kMips64S128Zero, dst);
} else if (all_ones) {
Emit(kMips64S128AllOnes, dst);
} else {
Emit(kMips64S128Const, dst, g.UseImmediate(val[0]), g.UseImmediate(val[1]),
g.UseImmediate(val[2]), g.UseImmediate(val[3]));
}
}
void InstructionSelector::VisitS128Zero(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64S128Zero, g.DefineAsRegister(node));
}
#define SIMD_VISIT_SPLAT(Type) \
void InstructionSelector::Visit##Type##Splat(Node* node) { \
VisitRR(this, kMips64##Type##Splat, node); \
}
SIMD_TYPE_LIST(SIMD_VISIT_SPLAT)
#undef SIMD_VISIT_SPLAT
#define SIMD_VISIT_EXTRACT_LANE(Type, Sign) \
void InstructionSelector::Visit##Type##ExtractLane##Sign(Node* node) { \
VisitRRI(this, kMips64##Type##ExtractLane##Sign, node); \
}
SIMD_VISIT_EXTRACT_LANE(F64x2, )
SIMD_VISIT_EXTRACT_LANE(F32x4, )
SIMD_VISIT_EXTRACT_LANE(I64x2, )
SIMD_VISIT_EXTRACT_LANE(I32x4, )
SIMD_VISIT_EXTRACT_LANE(I16x8, U)
SIMD_VISIT_EXTRACT_LANE(I16x8, S)
SIMD_VISIT_EXTRACT_LANE(I8x16, U)
SIMD_VISIT_EXTRACT_LANE(I8x16, S)
#undef SIMD_VISIT_EXTRACT_LANE
#define SIMD_VISIT_REPLACE_LANE(Type) \
void InstructionSelector::Visit##Type##ReplaceLane(Node* node) { \
VisitRRIR(this, kMips64##Type##ReplaceLane, node); \
}
SIMD_TYPE_LIST(SIMD_VISIT_REPLACE_LANE)
#undef SIMD_VISIT_REPLACE_LANE
#define SIMD_VISIT_UNOP(Name, instruction) \
void InstructionSelector::Visit##Name(Node* node) { \
VisitRR(this, instruction, node); \
}
SIMD_UNOP_LIST(SIMD_VISIT_UNOP)
#undef SIMD_VISIT_UNOP
#define SIMD_VISIT_SHIFT_OP(Name) \
void InstructionSelector::Visit##Name(Node* node) { \
VisitSimdShift(this, kMips64##Name, node); \
}
SIMD_SHIFT_OP_LIST(SIMD_VISIT_SHIFT_OP)
#undef SIMD_VISIT_SHIFT_OP
#define SIMD_VISIT_BINOP(Name, instruction) \
void InstructionSelector::Visit##Name(Node* node) { \
VisitRRR(this, instruction, node); \
}
SIMD_BINOP_LIST(SIMD_VISIT_BINOP)
#undef SIMD_VISIT_BINOP
void InstructionSelector::VisitS128Select(Node* node) {
VisitRRRR(this, kMips64S128Select, node);
}
namespace {
struct ShuffleEntry {
uint8_t shuffle[kSimd128Size];
ArchOpcode opcode;
};
static const ShuffleEntry arch_shuffles[] = {
{{0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23},
kMips64S32x4InterleaveRight},
{{8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31},
kMips64S32x4InterleaveLeft},
{{0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27},
kMips64S32x4PackEven},
{{4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31},
kMips64S32x4PackOdd},
{{0, 1, 2, 3, 16, 17, 18, 19, 8, 9, 10, 11, 24, 25, 26, 27},
kMips64S32x4InterleaveEven},
{{4, 5, 6, 7, 20, 21, 22, 23, 12, 13, 14, 15, 28, 29, 30, 31},
kMips64S32x4InterleaveOdd},
{{0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23},
kMips64S16x8InterleaveRight},
{{8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31},
kMips64S16x8InterleaveLeft},
{{0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29},
kMips64S16x8PackEven},
{{2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31},
kMips64S16x8PackOdd},
{{0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29},
kMips64S16x8InterleaveEven},
{{2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31},
kMips64S16x8InterleaveOdd},
{{6, 7, 4, 5, 2, 3, 0, 1, 14, 15, 12, 13, 10, 11, 8, 9},
kMips64S16x4Reverse},
{{2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13},
kMips64S16x2Reverse},
{{0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23},
kMips64S8x16InterleaveRight},
{{8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31},
kMips64S8x16InterleaveLeft},
{{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30},
kMips64S8x16PackEven},
{{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31},
kMips64S8x16PackOdd},
{{0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30},
kMips64S8x16InterleaveEven},
{{1, 17, 3, 19, 5, 21, 7, 23, 9, 25, 11, 27, 13, 29, 15, 31},
kMips64S8x16InterleaveOdd},
{{7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8},
kMips64S8x8Reverse},
{{3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12},
kMips64S8x4Reverse},
{{1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14},
kMips64S8x2Reverse}};
bool TryMatchArchShuffle(const uint8_t* shuffle, const ShuffleEntry* table,
size_t num_entries, bool is_swizzle,
ArchOpcode* opcode) {
uint8_t mask = is_swizzle ? kSimd128Size - 1 : 2 * kSimd128Size - 1;
for (size_t i = 0; i < num_entries; ++i) {
const ShuffleEntry& entry = table[i];
int j = 0;
for (; j < kSimd128Size; ++j) {
if ((entry.shuffle[j] & mask) != (shuffle[j] & mask)) {
break;
}
}
if (j == kSimd128Size) {
*opcode = entry.opcode;
return true;
}
}
return false;
}
} // namespace
void InstructionSelector::VisitI8x16Shuffle(Node* node) {
uint8_t shuffle[kSimd128Size];
bool is_swizzle;
CanonicalizeShuffle(node, shuffle, &is_swizzle);
uint8_t shuffle32x4[4];
ArchOpcode opcode;
if (TryMatchArchShuffle(shuffle, arch_shuffles, arraysize(arch_shuffles),
is_swizzle, &opcode)) {
VisitRRR(this, opcode, node);
return;
}
Node* input0 = node->InputAt(0);
Node* input1 = node->InputAt(1);
uint8_t offset;
Mips64OperandGenerator g(this);
if (wasm::SimdShuffle::TryMatchConcat(shuffle, &offset)) {
Emit(kMips64S8x16Concat, g.DefineSameAsFirst(node), g.UseRegister(input1),
g.UseRegister(input0), g.UseImmediate(offset));
return;
}
if (wasm::SimdShuffle::TryMatch32x4Shuffle(shuffle, shuffle32x4)) {
Emit(kMips64S32x4Shuffle, g.DefineAsRegister(node), g.UseRegister(input0),
g.UseRegister(input1),
g.UseImmediate(wasm::SimdShuffle::Pack4Lanes(shuffle32x4)));
return;
}
Emit(kMips64I8x16Shuffle, g.DefineAsRegister(node), g.UseRegister(input0),
g.UseRegister(input1),
g.UseImmediate(wasm::SimdShuffle::Pack4Lanes(shuffle)),
g.UseImmediate(wasm::SimdShuffle::Pack4Lanes(shuffle + 4)),
g.UseImmediate(wasm::SimdShuffle::Pack4Lanes(shuffle + 8)),
g.UseImmediate(wasm::SimdShuffle::Pack4Lanes(shuffle + 12)));
}
void InstructionSelector::VisitI8x16Swizzle(Node* node) {
Mips64OperandGenerator g(this);
InstructionOperand temps[] = {g.TempSimd128Register()};
// We don't want input 0 or input 1 to be the same as output, since we will
// modify output before do the calculation.
Emit(kMips64I8x16Swizzle, g.DefineAsRegister(node),
g.UseUniqueRegister(node->InputAt(0)),
g.UseUniqueRegister(node->InputAt(1)), arraysize(temps), temps);
}
void InstructionSelector::VisitSignExtendWord8ToInt32(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Seb, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitSignExtendWord16ToInt32(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Seh, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitSignExtendWord8ToInt64(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Seb, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitSignExtendWord16ToInt64(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Seh, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitSignExtendWord32ToInt64(Node* node) {
Mips64OperandGenerator g(this);
Emit(kMips64Shl, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)),
g.TempImmediate(0));
}
void InstructionSelector::VisitF32x4Pmin(Node* node) {
VisitUniqueRRR(this, kMips64F32x4Pmin, node);
}
void InstructionSelector::VisitF32x4Pmax(Node* node) {
VisitUniqueRRR(this, kMips64F32x4Pmax, node);
}
void InstructionSelector::VisitF64x2Pmin(Node* node) {
VisitUniqueRRR(this, kMips64F64x2Pmin, node);
}
void InstructionSelector::VisitF64x2Pmax(Node* node) {
VisitUniqueRRR(this, kMips64F64x2Pmax, node);
}
#define VISIT_EXT_MUL(OPCODE1, OPCODE2, TYPE) \
void InstructionSelector::Visit##OPCODE1##ExtMulLow##OPCODE2(Node* node) { \
Mips64OperandGenerator g(this); \
Emit(kMips64ExtMulLow | MiscField::encode(TYPE), g.DefineAsRegister(node), \
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1))); \
} \
void InstructionSelector::Visit##OPCODE1##ExtMulHigh##OPCODE2(Node* node) { \
Mips64OperandGenerator g(this); \
Emit(kMips64ExtMulHigh | MiscField::encode(TYPE), \
g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), \
g.UseRegister(node->InputAt(1))); \
}
VISIT_EXT_MUL(I64x2, I32x4S, MSAS32)
VISIT_EXT_MUL(I64x2, I32x4U, MSAU32)
VISIT_EXT_MUL(I32x4, I16x8S, MSAS16)
VISIT_EXT_MUL(I32x4, I16x8U, MSAU16)
VISIT_EXT_MUL(I16x8, I8x16S, MSAS8)
VISIT_EXT_MUL(I16x8, I8x16U, MSAU8)
#undef VISIT_EXT_MUL
#define VISIT_EXTADD_PAIRWISE(OPCODE, TYPE) \
void InstructionSelector::Visit##OPCODE(Node* node) { \
Mips64OperandGenerator g(this); \
Emit(kMips64ExtAddPairwise | MiscField::encode(TYPE), \
g.DefineAsRegister(node), g.UseRegister(node->InputAt(0))); \
}
VISIT_EXTADD_PAIRWISE(I16x8ExtAddPairwiseI8x16S, MSAS8)
VISIT_EXTADD_PAIRWISE(I16x8ExtAddPairwiseI8x16U, MSAU8)
VISIT_EXTADD_PAIRWISE(I32x4ExtAddPairwiseI16x8S, MSAS16)
VISIT_EXTADD_PAIRWISE(I32x4ExtAddPairwiseI16x8U, MSAU16)
#undef VISIT_EXTADD_PAIRWISE
// static
MachineOperatorBuilder::Flags
InstructionSelector::SupportedMachineOperatorFlags() {
MachineOperatorBuilder::Flags flags = MachineOperatorBuilder::kNoFlags;
return flags | MachineOperatorBuilder::kWord32Ctz |
MachineOperatorBuilder::kWord64Ctz |
MachineOperatorBuilder::kWord32Popcnt |
MachineOperatorBuilder::kWord64Popcnt |
MachineOperatorBuilder::kWord32ShiftIsSafe |
MachineOperatorBuilder::kInt32DivIsSafe |
MachineOperatorBuilder::kUint32DivIsSafe |
MachineOperatorBuilder::kFloat64RoundDown |
MachineOperatorBuilder::kFloat32RoundDown |
MachineOperatorBuilder::kFloat64RoundUp |
MachineOperatorBuilder::kFloat32RoundUp |
MachineOperatorBuilder::kFloat64RoundTruncate |
MachineOperatorBuilder::kFloat32RoundTruncate |
MachineOperatorBuilder::kFloat64RoundTiesEven |
MachineOperatorBuilder::kFloat32RoundTiesEven;
}
// static
MachineOperatorBuilder::AlignmentRequirements
InstructionSelector::AlignmentRequirements() {
if (kArchVariant == kMips64r6) {
return MachineOperatorBuilder::AlignmentRequirements::
FullUnalignedAccessSupport();
} else {
DCHECK_EQ(kMips64r2, kArchVariant);
return MachineOperatorBuilder::AlignmentRequirements::
NoUnalignedAccessSupport();
}
}
#undef SIMD_BINOP_LIST
#undef SIMD_SHIFT_OP_LIST
#undef SIMD_UNOP_LIST
#undef SIMD_TYPE_LIST
#undef TRACE_UNIMPL
#undef TRACE
} // namespace compiler
} // namespace internal
} // namespace v8
|
#include <MTScheduler.h>
#include "Profiler.h"
#if defined(MT_INSTRUMENTED_BUILD) && defined(MT_ENABLE_BROFILER_SUPPORT)
#pragma comment( lib, "BrofilerCore.lib" )
#pragma comment( lib, "Advapi32.lib" )
const uint32 MAX_INSTRUMENTED_WORKERS = 8;
const char *g_WorkerNames[MAX_INSTRUMENTED_WORKERS] = {"worker0","worker1","worker2","worker3","worker4","worker5","worker6","worker7"};
class ProfilerEventListener : public MT::IProfilerEventListener
{
Brofiler::EventStorage* fiberEventStorages[MT::MT_MAX_STANDART_FIBERS_COUNT + MT::MT_MAX_EXTENDED_FIBERS_COUNT];
uint32 totalFibersCount;
static mt_thread_local Brofiler::EventStorage* originalThreadStorage;
static mt_thread_local Brofiler::EventStorage* activeThreadStorage;
public:
ProfilerEventListener()
: totalFibersCount(0)
{
}
virtual void OnFibersCreated(uint32 fibersCount) override
{
totalFibersCount = fibersCount;
MT_ASSERT(fibersCount <= MT_ARRAY_SIZE(fiberEventStorages), "Too many fibers!");
for(uint32 fiberIndex = 0; fiberIndex < fibersCount; fiberIndex++)
{
Brofiler::RegisterFiber(fiberIndex, &fiberEventStorages[fiberIndex]);
}
}
virtual void OnThreadsCreated(uint32 threadsCount) override
{
MT_UNUSED(threadsCount);
}
virtual void OnTemporaryWorkerThreadLeave() override
{
Brofiler::EventStorage** currentThreadStorageSlot = Brofiler::GetEventStorageSlotForCurrentThread();
MT_ASSERT(currentThreadStorageSlot, "Sanity check failed");
Brofiler::EventStorage* storage = *currentThreadStorageSlot;
// if profile session is not active
if (storage == nullptr)
{
return;
}
MT_ASSERT(IsFiberStorage(storage) == false, "Sanity check failed");
}
virtual void OnTemporaryWorkerThreadJoin() override
{
Brofiler::EventStorage** currentThreadStorageSlot = Brofiler::GetEventStorageSlotForCurrentThread();
MT_ASSERT(currentThreadStorageSlot, "Sanity check failed");
Brofiler::EventStorage* storage = *currentThreadStorageSlot;
// if profile session is not active
if (storage == nullptr)
{
return;
}
MT_ASSERT(IsFiberStorage(storage) == false, "Sanity check failed");
}
virtual void OnThreadCreated(uint32 workerIndex) override
{
BROFILER_START_THREAD("Scheduler(Worker)");
MT_UNUSED(workerIndex);
}
virtual void OnThreadStarted(uint32 workerIndex) override
{
MT_UNUSED(workerIndex);
}
virtual void OnThreadStoped(uint32 workerIndex) override
{
MT_UNUSED(workerIndex);
BROFILER_STOP_THREAD();
}
virtual void OnThreadIdleStarted(uint32 workerIndex) override
{
MT_UNUSED(workerIndex);
}
virtual void OnThreadIdleFinished(uint32 workerIndex) override
{
MT_UNUSED(workerIndex);
}
virtual void OnThreadWaitStarted() override
{
}
virtual void OnThreadWaitFinished() override
{
}
virtual void OnTaskExecuteStateChanged(MT::Color::Type debugColor, const mt_char* debugID, MT::TaskExecuteState::Type type, int32 fiberIndex) override
{
MT_UNUSED(debugColor);
MT_UNUSED(debugID);
//MT_UNUSED(type);
MT_ASSERT(fiberIndex < (int32)totalFibersCount, "Sanity check failed");
Brofiler::EventStorage** currentThreadStorageSlot = Brofiler::GetEventStorageSlotForCurrentThread();
MT_ASSERT(currentThreadStorageSlot, "Sanity check failed");
// if profile session is not active
if (*currentThreadStorageSlot == nullptr)
{
return;
}
// if actual fiber is scheduler internal fiber (don't have event storage for internal scheduler fibers)
if (fiberIndex < 0)
{
return;
}
switch(type)
{
case MT::TaskExecuteState::START:
case MT::TaskExecuteState::RESUME:
{
MT_ASSERT(originalThreadStorage == nullptr, "Sanity check failed");
originalThreadStorage = *currentThreadStorageSlot;
MT_ASSERT(IsFiberStorage(originalThreadStorage) == false, "Sanity check failed");
Brofiler::EventStorage* currentFiberStorage = nullptr;
if (fiberIndex >= (int32)0)
{
currentFiberStorage = fiberEventStorages[fiberIndex];
}
*currentThreadStorageSlot = currentFiberStorage;
activeThreadStorage = currentFiberStorage;
Brofiler::FiberSyncData::AttachToThread(currentFiberStorage, MT::ThreadId::Self().AsUInt64());
}
break;
case MT::TaskExecuteState::STOP:
case MT::TaskExecuteState::SUSPEND:
{
Brofiler::EventStorage* currentFiberStorage = *currentThreadStorageSlot;
//////////////////////////////////////////////////////////////////////////
Brofiler::EventStorage* checkFiberStorage = nullptr;
if (fiberIndex >= (int32)0)
{
checkFiberStorage = fiberEventStorages[fiberIndex];
}
MT_ASSERT(checkFiberStorage == currentFiberStorage, "Sanity check failed");
MT_ASSERT(activeThreadStorage == currentFiberStorage, "Sanity check failed");
//////////////////////////////////////////////////////////////////////////
MT_ASSERT(IsFiberStorage(currentFiberStorage) == true, "Sanity check failed");
Brofiler::FiberSyncData::DetachFromThread(currentFiberStorage);
*currentThreadStorageSlot = originalThreadStorage;
originalThreadStorage = nullptr;
}
break;
}
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
mt_thread_local Brofiler::EventStorage* ProfilerEventListener::originalThreadStorage = nullptr;
mt_thread_local Brofiler::EventStorage* ProfilerEventListener::activeThreadStorage = 0;
#endif
MT::IProfilerEventListener* GetProfiler()
{
#if defined(MT_INSTRUMENTED_BUILD) && defined(MT_ENABLE_BROFILER_SUPPORT)
static ProfilerEventListener profilerListener;
return &profilerListener;
#else
return nullptr;
#endif
}
|
//
// Created by DefTruth on 2021/7/7.
//
#include "lite/lite.h"
static void test_default()
{
std::string onnx_path = "../../../hub/onnx/cv/focal-arcface-bh-ir50-asia.onnx";
std::string test_img_path0 = "../../../examples/lite/resources/test_lite_focal_asia_arcface_0.png";
std::string test_img_path1 = "../../../examples/lite/resources/test_lite_focal_asia_arcface_1.png";
lite::cv::faceid::FocalAsiaArcFace *focal_asia_arcface = new lite::cv::faceid::FocalAsiaArcFace(onnx_path);
lite::cv::types::FaceContent face_content0, face_content1;
cv::Mat img_bgr0 = cv::imread(test_img_path0);
cv::Mat img_bgr1 = cv::imread(test_img_path1);
focal_asia_arcface->detect(img_bgr0, face_content0);
focal_asia_arcface->detect(img_bgr1, face_content1);
if (face_content0.flag && face_content1.flag)
{
float sim = lite::cv::utils::math::cosine_similarity<float>(
face_content0.embedding, face_content1.embedding);
std::cout << "Default Version Detected Sim: " << sim << std::endl;
}
delete focal_asia_arcface;
}
static void test_onnxruntime()
{
std::string onnx_path = "../../../hub/onnx/cv/focal-arcface-bh-ir50-asia.onnx";
std::string test_img_path0 = "../../../examples/lite/resources/test_lite_focal_asia_arcface_0.png";
std::string test_img_path1 = "../../../examples/lite/resources/test_lite_focal_asia_arcface_2.png";
lite::onnxruntime::cv::faceid::FocalAsiaArcFace *focal_asia_arcface =
new lite::onnxruntime::cv::faceid::FocalAsiaArcFace(onnx_path);
lite::onnxruntime::cv::types::FaceContent face_content0, face_content1;
cv::Mat img_bgr0 = cv::imread(test_img_path0);
cv::Mat img_bgr1 = cv::imread(test_img_path1);
focal_asia_arcface->detect(img_bgr0, face_content0);
focal_asia_arcface->detect(img_bgr1, face_content1);
if (face_content0.flag && face_content1.flag)
{
float sim = lite::onnxruntime::cv::utils::math::cosine_similarity<float>(
face_content0.embedding, face_content1.embedding);
std::cout << "ONNXRuntime Version Detected Sim: " << sim << std::endl;
}
delete focal_asia_arcface;
}
static void test_mnn()
{
}
static void test_ncnn()
{
}
static void test_tnn()
{
}
static void test_lite()
{
test_default();
test_onnxruntime();
test_mnn();
test_ncnn();
test_tnn();
}
int main(__unused int argc, __unused char *argv[])
{
test_lite();
return 0;
}
|
#include "global.h"
#include "ScreenClearBookkeepingData.h"
#include "ScreenManager.h"
#include "ThemeManager.h"
#include "Bookkeeper.h"
#define NEXT_SCREEN THEME->GetMetric(m_sName,"NextScreen")
ScreenClearBookkeepingData::ScreenClearBookkeepingData( const CString &sName ): Screen( sName )
{
BOOKKEEPER->ClearAll();
BOOKKEEPER->WriteToDisk();
SCREENMAN->SystemMessage( "Bookkeeping data cleared." );
SCREENMAN->SetNewScreen( NEXT_SCREEN );
}
/*
* (c) 2004 Chris Danford
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
|
// System::Windows::Forms::DataGridTableStyle::LinkColor;
// System::Windows::Forms::DataGridTableStyle::HeaderFont;
// System::Windows::Forms::DataGridTableStyle::LinkColorChanged;
// System::Windows::Forms::DataGridTableStyle::HeaderFontChanged;
/* The following example demonstrates the properties 'LinkColor', 'HeaderFont'
and Events 'LinkColorChanged', 'HeaderFontChanged' of DataGridTableStyle.
The following program creates a Windows form, a DataSet containing two DataTable objects,
and a DataRelation that relates the two tables. A button on the form changes the appearance
of the grid by setting the linkcolor and headerfont.
*/
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.Data.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
namespace SampleDataGridTableStyle
{
public ref class DataGridTableStyle_Sample: public System::Windows::Forms::Form
{
private:
System::Windows::Forms::DataGrid^ myDataGrid;
System::Windows::Forms::DataGridTableStyle^ myDataGridTableStyle1;
System::Windows::Forms::DataGridTableStyle^ myDataGridTableStyle2;
DataSet^ myDataSet;
System::Windows::Forms::Button^ btnApplyStyles;
System::ComponentModel::Container^ components;
public:
DataGridTableStyle_Sample()
{
components = nullptr;
InitializeComponent();
// Call SetUp to bind the controls.
SetUp();
}
public:
~DataGridTableStyle_Sample()
{
if ( components != nullptr )
{
delete components;
}
}
private:
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this->btnApplyStyles = gcnew System::Windows::Forms::Button;
this->myDataGrid = gcnew System::Windows::Forms::DataGrid;
(dynamic_cast<System::ComponentModel::ISupportInitialize^>(this->myDataGrid))->BeginInit();
this->SuspendLayout();
//
// btnApplyStyles
//
this->btnApplyStyles->Font = gcnew System::Drawing::Font( "Arial",8.25F,System::Drawing::FontStyle::Bold,System::Drawing::GraphicsUnit::Point,((System::Byte)(0)) );
this->btnApplyStyles->Location = System::Drawing::Point( 88, 208 );
this->btnApplyStyles->Name = "btnApplyStyles";
this->btnApplyStyles->Size = System::Drawing::Size( 144, 40 );
this->btnApplyStyles->TabIndex = 1;
this->btnApplyStyles->Text = "Apply Custom Styles";
this->btnApplyStyles->Click += gcnew System::EventHandler( this, &DataGridTableStyle_Sample::btnApplyStyles_Click );
//
// myDataGrid
//
this->myDataGrid->BackColor = System::Drawing::SystemColors::Info;
this->myDataGrid->CaptionText = "Microsoft DataGrid Control";
this->myDataGrid->DataMember = "";
this->myDataGrid->LinkColor = System::Drawing::Color::Gray;
this->myDataGrid->Location = System::Drawing::Point( 48, 32 );
this->myDataGrid->Name = "myDataGrid";
this->myDataGrid->Size = System::Drawing::Size( 312, 128 );
this->myDataGrid->TabIndex = 0;
//
// DataGridTableStyle_Sample
//
this->ClientSize = System::Drawing::Size( 440, 273 );
array<System::Windows::Forms::Control^>^formControls = {this->btnApplyStyles,this->myDataGrid};
this->Controls->AddRange( formControls );
this->Name = "DataGridTableStyle_Sample";
this->Text = "DataGridTableStyle_Sample";
this->Load += gcnew System::EventHandler( this, &DataGridTableStyle_Sample::DataGridTableStyle_Sample_Load );
(dynamic_cast<System::ComponentModel::ISupportInitialize^>(this->myDataGrid))->EndInit();
this->ResumeLayout( false );
}
void DataGridTableStyle_Sample_Load( Object^ /*sender*/, EventArgs^ /*e*/ ){}
void SetUp()
{
// Create a DataSet with two tables and one relation.
MakeDataSet();
// Bind the DataGrid to the DataSet.
myDataGrid->SetDataBinding( myDataSet, "Customers" );
}
// <Snippet1>
// <Snippet2>
// <Snippet3>
// <Snippet4>
private:
void AddCustomDataTableStyle()
{
myDataGridTableStyle1 = gcnew DataGridTableStyle;
myDataGridTableStyle2 = gcnew DataGridTableStyle;
MessageBox::Show( String::Concat( "LinkColor Before : ", myDataGridTableStyle1->LinkColor ) );
MessageBox::Show( String::Concat( "HeaderFont Before : ", myDataGridTableStyle1->HeaderFont ) );
myDataGridTableStyle1->LinkColorChanged += gcnew System::EventHandler( this, &DataGridTableStyle_Sample::LinkColorChanged_Handler );
myDataGridTableStyle1->HeaderFontChanged += gcnew System::EventHandler( this, &DataGridTableStyle_Sample::HeaderFontChanged_Handler );
myDataGridTableStyle1->MappingName = "Customers";
// Set other properties.
myDataGridTableStyle1->AlternatingBackColor = Color::LightGray;
myDataGridTableStyle1->LinkColor = Color::Red;
myDataGridTableStyle1->HeaderFont = gcnew System::Drawing::Font( "Verdana",8.25F,System::Drawing::FontStyle::Bold,System::Drawing::GraphicsUnit::Point,((System::Byte)(0)) );
// Add a GridColumnStyle and set its MappingName.
DataGridColumnStyle^ myBoolCol = gcnew DataGridBoolColumn;
myBoolCol->MappingName = "Current";
myBoolCol->HeaderText = "IsCurrent Customer";
myBoolCol->Width = 150;
myDataGridTableStyle1->GridColumnStyles->Add( myBoolCol );
// Add a second column style.
DataGridColumnStyle^ myTextCol = gcnew DataGridTextBoxColumn;
myTextCol->MappingName = "custName";
myTextCol->HeaderText = "Customer Name";
myTextCol->Width = 250;
myDataGridTableStyle1->GridColumnStyles->Add( myTextCol );
// Create new ColumnStyle objects
DataGridColumnStyle^ cOrderDate = gcnew DataGridTextBoxColumn;
cOrderDate->MappingName = "OrderDate";
cOrderDate->HeaderText = "Order Date";
cOrderDate->Width = 100;
// PropertyDescriptor to create a formatted column.
PropertyDescriptorCollection^ myPropertyDescriptorCollection = this->BindingContext[myDataSet, "Customers.custToOrders"]->GetItemProperties();
DataGridColumnStyle^ csOrderAmount = gcnew DataGridTextBoxColumn( myPropertyDescriptorCollection[ "OrderAmount" ],"c",true );
csOrderAmount->MappingName = "OrderAmount";
csOrderAmount->HeaderText = "Total";
csOrderAmount->Width = 100;
// Add the DataGridTableStyle instances to GridTableStylesCollection.
myDataGrid->TableStyles->Add( myDataGridTableStyle1 );
}
void LinkColorChanged_Handler( Object^ /*sender*/, EventArgs^ /*e*/ )
{
MessageBox::Show( "LinkColor changed to 'RED'", "DataGridTableStyle" );
}
void HeaderFontChanged_Handler( Object^ /*sender*/, EventArgs^ /*e*/ )
{
MessageBox::Show( "HeaderFont changed to 'VERDANA'", "DataGridTableStyle" );
}
// </Snippet4>
// </Snippet3>
// </Snippet2>
// </Snippet1>
// Create a DataSet with two tables and populate it.
void MakeDataSet()
{
// Create a DataSet.
myDataSet = gcnew DataSet( "myDataSet" );
// Create Customer DataTables.
DataTable^ tCust = gcnew DataTable( "Customers" );
// Create two columns, and add them to the first table.
DataColumn^ cCustID = gcnew DataColumn( "CustID",int::typeid );
DataColumn^ cCustName = gcnew DataColumn( "CustName" );
DataColumn^ cCurrent = gcnew DataColumn( "Current",bool::typeid );
tCust->Columns->Add( cCustID );
tCust->Columns->Add( cCustName );
tCust->Columns->Add( cCurrent );
// Create Customer order table.
DataTable^ tOrders = gcnew DataTable( "Orders" );
// Create three columns, and add them to the second table.
DataColumn^ cID = gcnew DataColumn( "CustID",int::typeid );
DataColumn^ cOrderDate = gcnew DataColumn( "orderDate",DateTime::typeid );
DataColumn^ cOrderAmount = gcnew DataColumn( "OrderAmount",Decimal::typeid );
tOrders->Columns->Add( cOrderAmount );
tOrders->Columns->Add( cID );
tOrders->Columns->Add( cOrderDate );
// Add the tables to the DataSet.
myDataSet->Tables->Add( tCust );
myDataSet->Tables->Add( tOrders );
// Create a DataRelation, and add it to the DataSet.
DataRelation^ dr = gcnew DataRelation( "custToOrders",cCustID,cID );
myDataSet->Relations->Add( dr );
// Populate the tables.
DataRow^ newRow1;
DataRow^ newRow2;
// Create three customers in the Customers Table.
for ( int i = 1; i < 4; i++ )
{
newRow1 = tCust->NewRow();
newRow1[ "custID" ] = i;
// Add the row to the Customers table.
tCust->Rows->Add( newRow1 );
}
tCust->Rows[ 0 ][ "custName" ] = "Alpha";
tCust->Rows[ 1 ][ "custName" ] = "Beta";
tCust->Rows[ 2 ][ "custName" ] = "Gamma";
// Give the Current column a value.
tCust->Rows[ 0 ][ "Current" ] = true.ToString();
tCust->Rows[ 1 ][ "Current" ] = true.ToString();
tCust->Rows[ 2 ][ "Current" ] = false.ToString();
// For each customer, create five rows in the Orders table.
for ( int i = 1; i < 4; i++ )
{
for ( int j = 1; j < 6; j++ )
{
newRow2 = tOrders->NewRow();
newRow2[ "CustID" ] = i;
newRow2[ "orderDate" ] = DateTime(2001,i,j * 2);
newRow2[ "OrderAmount" ] = i * 10 + j * .1;
// Add the row to the Orders table.
tOrders->Rows->Add( newRow2 );
}
}
}
void btnApplyStyles_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
AddCustomDataTableStyle();
btnApplyStyles->Enabled = false;
}
};
}
[STAThread]
int main()
{
Application::Run( gcnew SampleDataGridTableStyle::DataGridTableStyle_Sample );
}
|
/*
*
* Copyright 2015 gRPC 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 <grpc/support/port_platform.h>
#include <limits.h>
#include <memory.h>
#include <grpc/fork.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channelz_registry.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/fork.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/resource_quota.h"
#include "src/core/lib/iomgr/timer_manager.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/init.h"
#include "src/core/lib/surface/lame_client.h"
#include "src/core/lib/surface/server.h"
#include "src/core/lib/transport/bdp_estimator.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/transport_impl.h"
/* (generated) built in registry of plugins */
extern void grpc_register_built_in_plugins(void);
#define MAX_PLUGINS 128
static gpr_once g_basic_init = GPR_ONCE_INIT;
static gpr_mu g_init_mu;
static int g_initializations;
static void do_basic_init(void) {
gpr_log_verbosity_init();
gpr_mu_init(&g_init_mu);
grpc_register_built_in_plugins();
grpc_cq_global_init();
g_initializations = 0;
}
static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_append_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static bool prepend_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_prepend_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static void register_builtin_channel_init() {
grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
append_filter, (void*)&grpc_lame_filter);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter,
(void*)&grpc_server_top_filter);
}
typedef struct grpc_plugin {
void (*init)();
void (*destroy)();
} grpc_plugin;
static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
static int g_number_of_plugins = 0;
void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2,
((void*)(intptr_t)init, (void*)(intptr_t)destroy));
GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
g_all_of_the_plugins[g_number_of_plugins].init = init;
g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
g_number_of_plugins++;
}
void grpc_init(void) {
int i;
gpr_once_init(&g_basic_init, do_basic_init);
gpr_mu_lock(&g_init_mu);
if (++g_initializations == 1) {
grpc_core::Fork::GlobalInit();
grpc_fork_handlers_auto_register();
gpr_time_init();
gpr_arena_init();
grpc_stats_init();
grpc_slice_intern_init();
grpc_mdctx_global_init();
grpc_channel_init_init();
grpc_core::channelz::ChannelzRegistry::Init();
grpc_security_pre_init();
grpc_core::ApplicationCallbackExecCtx::GlobalInit();
grpc_core::ExecCtx::GlobalInit();
grpc_iomgr_init();
gpr_timers_global_init();
grpc_handshaker_factory_registry_init();
grpc_security_init();
for (i = 0; i < g_number_of_plugins; i++) {
if (g_all_of_the_plugins[i].init != nullptr) {
g_all_of_the_plugins[i].init();
}
}
/* register channel finalization AFTER all plugins, to ensure that it's run
* at the appropriate time */
grpc_register_security_filters();
register_builtin_channel_init();
grpc_tracer_init("GRPC_TRACE");
/* no more changes to channel init pipelines */
grpc_channel_init_finalize();
grpc_iomgr_start();
}
gpr_mu_unlock(&g_init_mu);
GRPC_API_TRACE("grpc_init(void)", 0, ());
}
void grpc_shutdown(void) {
int i;
GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
gpr_mu_lock(&g_init_mu);
if (--g_initializations == 0) {
{
grpc_core::ExecCtx exec_ctx(0);
grpc_iomgr_shutdown_background_closure();
{
grpc_timer_manager_set_threading(
false); // shutdown timer_manager thread
grpc_core::Executor::ShutdownAll();
for (i = g_number_of_plugins; i >= 0; i--) {
if (g_all_of_the_plugins[i].destroy != nullptr) {
g_all_of_the_plugins[i].destroy();
}
}
}
grpc_iomgr_shutdown();
gpr_timers_global_destroy();
grpc_tracer_shutdown();
grpc_mdctx_global_shutdown();
grpc_handshaker_factory_registry_shutdown();
grpc_slice_intern_shutdown();
grpc_core::channelz::ChannelzRegistry::Shutdown();
grpc_stats_shutdown();
grpc_core::Fork::GlobalShutdown();
}
grpc_core::ExecCtx::GlobalShutdown();
grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
}
gpr_mu_unlock(&g_init_mu);
}
int grpc_is_initialized(void) {
int r;
gpr_once_init(&g_basic_init, do_basic_init);
gpr_mu_lock(&g_init_mu);
r = g_initializations > 0;
gpr_mu_unlock(&g_init_mu);
return r;
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:d5fcdcf0b2213d806211cc9fc2b547b0b80e2cb0a5eed3da63ad4a384cf5b3a3
size 3750
|
// Copyright © 2022 Brad Howes. All rights reserved.
#include <iostream>
#include "SF2Lib/Entity/Bag.hpp"
using namespace SF2::Entity;
void
Bag::dump(const std::string& indent, size_t index) const noexcept
{
std::cout << indent << '[' << index << "] genIndex: " << firstGeneratorIndex() << " count: " << generatorCount()
<< " modIndex: " << firstModulatorIndex() << " count: " << modulatorCount() << std::endl;
}
|
/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/sksl/ir/SkSLConstructorScalarCast.h"
namespace SkSL {
static std::unique_ptr<Expression> cast_scalar_literal(const Type& constructorType,
const Expression& expr) {
if (expr.is<IntLiteral>()) {
SKSL_INT value = expr.as<IntLiteral>().value();
if (constructorType.isFloat()) {
// promote float(1) to 1.0
return FloatLiteral::Make(expr.fOffset, (SKSL_FLOAT)value, &constructorType);
} else if (constructorType.isInteger()) {
// promote uint(1) to 1u
return IntLiteral::Make(expr.fOffset, value, &constructorType);
} else if (constructorType.isBoolean()) {
// promote bool(1) to true/false
return BoolLiteral::Make(expr.fOffset, value != 0, &constructorType);
}
} else if (expr.is<FloatLiteral>()) {
float value = expr.as<FloatLiteral>().value();
if (constructorType.isFloat()) {
// promote float(1.23) to 1.23
return FloatLiteral::Make(expr.fOffset, value, &constructorType);
} else if (constructorType.isInteger()) {
// promote uint(1.23) to 1u
return IntLiteral::Make(expr.fOffset, (SKSL_INT)value, &constructorType);
} else if (constructorType.isBoolean()) {
// promote bool(1.23) to true/false
return BoolLiteral::Make(expr.fOffset, value != 0.0f, &constructorType);
}
} else if (expr.is<BoolLiteral>()) {
bool value = expr.as<BoolLiteral>().value();
if (constructorType.isFloat()) {
// promote float(true) to 1.0
return FloatLiteral::Make(expr.fOffset, value ? 1.0f : 0.0f, &constructorType);
} else if (constructorType.isInteger()) {
// promote uint(true) to 1u
return IntLiteral::Make(expr.fOffset, value ? 1 : 0, &constructorType);
} else if (constructorType.isBoolean()) {
// promote bool(true) to true/false
return BoolLiteral::Make(expr.fOffset, value, &constructorType);
}
}
return nullptr;
}
std::unique_ptr<Expression> ConstructorScalarCast::Convert(const Context& context,
int offset,
const Type& rawType,
ExpressionArray args) {
// As you might expect, scalar-cast constructors should only be created with scalar types.
const Type& type = rawType.scalarTypeForLiteral();
SkASSERT(type.isScalar());
if (args.size() != 1) {
context.fErrors.error(offset, "invalid arguments to '" + type.displayName() +
"' constructor, (expected exactly 1 argument, but found " +
to_string((uint64_t)args.size()) + ")");
return nullptr;
}
const Type& argType = args[0]->type();
if (!argType.isScalar()) {
context.fErrors.error(offset, "invalid argument to '" + type.displayName() +
"' constructor (expected a number or bool, but found '" +
argType.displayName() + "')");
return nullptr;
}
return ConstructorScalarCast::Make(context, offset, type, std::move(args[0]));
}
std::unique_ptr<Expression> ConstructorScalarCast::Make(const Context& context,
int offset,
const Type& type,
std::unique_ptr<Expression> arg) {
SkASSERT(type.isScalar());
SkASSERT(arg->type().isScalar());
// No cast required when the types match.
if (arg->type() == type) {
return arg;
}
// We can cast scalar literals at compile-time.
if (std::unique_ptr<Expression> converted = cast_scalar_literal(type, *arg)) {
return converted;
}
return std::make_unique<ConstructorScalarCast>(offset, type, std::move(arg));
}
} // namespace SkSL
|
#pragma once
#include "../serializationnode.hpp"
#include "xmlserializationdocument.hpp"
#include <tinyxml2/tinyxml2.hpp>
namespace wgt
{
class XMLSerializationNode : public SerializationNode
{
typedef std::unique_ptr<SerializationNode> NodePtr;
friend NodePtr XMLSerializationDocument::findNode(const char*);
friend NodePtr XMLSerializationDocument::getRootNode();
friend bool operator==(XMLSerializationNode& lhs, XMLSerializationNode& rhs);
public:
XMLSerializationNode() = delete;
~XMLSerializationNode() override;
NodePtr getChildNode(const char* childName, size_t nameSize) override;
NodePtr getChildNode(const SStringRef& childName) override;
std::vector<NodePtr> getAllChildren(const char* childName = "", size_t nameSize = size_t(0)) override;
std::vector<NodePtr> getAllChildren(const SStringRef& childName) override;
bool isNull() const override;
std::string getName() const override;
std::string getType() const override;
std::string getHandlerName() const override;
// Primitive type getValues
std::string getValueString() const override;
std::wstring getValueWString() const override;
double getValueDouble() const override;
intmax_t getValueInt() const override;
uintmax_t getValueUint() const override;
char getValueChar() const override;
wchar_t getValueWChar() const override;
bool getValueBool() const override;
// Primitive type setValues
void setValueString(const char* value, size_t valueSize, bool setType = true) override;
void setValueString(const SStringRef& value, bool setType = true) override;
void setValueWString(const wchar_t* value, size_t valueSize, bool setType = true) override;
void setValueWString(const WSStringRef& value, bool setType = true) override;
void setValueDouble(double value, bool setType = true) override;
void setValueInt(intmax_t value, bool setType = true) override;
void setValueUint(uintmax_t value, bool setType = true) override;
void setValueChar(char value, bool setType = true) override;
void setValueWChar(wchar_t value, bool setType = true) override;
void setValueBool(bool value, bool setType = true) override;
void setValueRawData(const char* value, size_t valueSize, const char* typeName, size_t typeNameSize) override;
void setValueRawData(const char* value, size_t valueSize, const SStringRef& typeName) override;
void setHandlerName(const char* handlerName, size_t handlerNameSize) override;
void setHandlerName(const SStringRef& value) override;
void setType(const char* typeName, size_t typeNameSize) override;
void setType(const SStringRef& typeName) override;
void deleteChild(const char* childName, size_t nameSize) override;
void deleteChild(const SStringRef& childName) override;
void deleteChild(NodePtr& childNode) override;
void deleteChildren() override;
protected:
XMLSerializationNode(XMLSerializationDocument* document, tinyxml2::XMLElement* node)
: SerializationNode(document), xmlNode_(node)
{
}
NodePtr createEmptyChildInternal(const char* childName, size_t nameSize) override;
NodePtr createEmptyChildInternal(const SStringRef& childName) override;
void setNameInternal(const char* name, size_t nameSize) override;
void setNameInternal(const SStringRef& name) override;
tinyxml2::XMLElement* getInternalNode();
private:
NodePtr createNodeInternal(tinyxml2::XMLElement* node);
XMLSerializationDocument* getDocumentInternal() const;
std::string makeCharSizeString(const char* charData) const;
/**TinyXML2 only accepts null-terminated char* (can't specify a size). Currently worked around by creating an
std::string, but can be optimized if performance is an issue.*/
tinyxml2::XMLElement* xmlNode_;
};
}
|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// Scenario4.xaml.cpp
// Implementation of the Scenario4 class
//
#include "pch.h"
#include "Scenario4.xaml.h"
using namespace SDKTemplate;
using namespace concurrency;
using namespace Platform;
using namespace Windows::Storage;
using namespace Windows::Storage::FileProperties;
using namespace Windows::Storage::Pickers;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Scenario4::Scenario4()
{
InitializeComponent();
rootPage = MainPage::Current;
}
void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
{
rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
}
void Scenario4::GetThumbnailButton_Click(Object^ sender, RoutedEventArgs^ e)
{
rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
// Pick a folder
FolderPicker^ folderPicker = ref new FolderPicker();
Array<String^>^ extensions = FileExtensions::Image;
for (unsigned int i = 0; i < extensions->Length; i++)
{
folderPicker->FileTypeFilter->Append(extensions[i]);
}
create_task(folderPicker->PickSingleFolderAsync()).then([this](StorageFolder^ folder)
{
if (folder != nullptr)
{
const ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
const size_t size = 200;
create_task(folder->GetThumbnailAsync(thumbnailMode, size)).then([this, folder, size](StorageItemThumbnail^ thumbnail)
{
if (thumbnail != nullptr)
{
MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "PicturesView", size, folder, thumbnail, false);
}
else
{
rootPage->NotifyUser(Errors::NoImages, NotifyType::StatusMessage);
}
});
}
else
{
rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
}
});
}
|
#include "PipelineObjPropDockWidget.h"
PipelineObjPropDockWidget::PipelineObjPropDockWidget(QWidget *parent) :
QDockWidget(parent)
{
this->setWindowTitle(tr("Pipeline properties"));
propWidget = new PipelineObjPropWidget;
setWidget(propWidget);
wid = 200;
hei = 400;
}
PipelineObjPropDockWidget::~PipelineObjPropDockWidget()
{
//delete ui;
}
void PipelineObjPropDockWidget::reTranslate()
{
this->setWindowTitle(tr("Pipeline properties"));
propWidget->reTranslate();
}
|
#include <bits/stdc++.h>
using namespace std;
void fl() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
// freopen("ot.txt", "w", stdout);
#else
// freopen("jumping.in", "r", stdin); // HERE
#endif
}
#define forr(i,j, n) for(int i = j;i < n;i++)
#define F first
#define S second
#define mem(a,b) memset(a,b,sizeof(a))
////////////////////////////////////////////////////////////////////////////////////////////////
// snippet :: dinp , dhelp , dvec , lli , dfor , dcons , dbit
int n, m, l = 1, r, a, f;
int main() { // dfil
fl(); //TODO
cin >> n >> m;
r = INT_MAX;
for (int i = 0; i < m; ++i) {
cin >> a >> f;
l = max(l, 1 + (a - 1) / f);
if (f > 1)
r = min(r, (a - 1) / (f - 1));
}
l = 1 + (n - 1) / l;
r = 1 + (n - 1) / r;
cout << (l == r ? l : -1);
return 0;
}
|
// Generated from /POI/java/org/apache/poi/ss/formula/ParseNode.java
#include <org/apache/poi/ss/formula/ParseNode.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/IllegalArgumentException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <org/apache/poi/ss/formula/ParseNode_TokenCollector.hpp>
#include <org/apache/poi/ss/formula/function/FunctionMetadataRegistry.hpp>
#include <org/apache/poi/ss/formula/ptg/ArrayPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/AttrPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/FuncVarPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemAreaPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemFuncPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/Ptg.hpp>
#include <ObjectArray.hpp>
#include <SubArray.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace ss
{
namespace formula
{
typedef ::SubArray< ::poi::ss::formula::ParseNode, ::java::lang::ObjectArray > ParseNodeArray;
namespace ptg
{
typedef ::SubArray< ::poi::ss::formula::ptg::Ptg, ::java::lang::ObjectArray > PtgArray;
} // ptg
} // formula
} // ss
} // poi
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::ss::formula::ParseNode::ParseNode(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::formula::ParseNode::ParseNode(::poi::ss::formula::ptg::Ptg* token, ParseNodeArray* children)
: ParseNode(*static_cast< ::default_init_tag* >(0))
{
ctor(token,children);
}
poi::ss::formula::ParseNode::ParseNode(::poi::ss::formula::ptg::Ptg* token)
: ParseNode(*static_cast< ::default_init_tag* >(0))
{
ctor(token);
}
poi::ss::formula::ParseNode::ParseNode(::poi::ss::formula::ptg::Ptg* token, ParseNode* child0)
: ParseNode(*static_cast< ::default_init_tag* >(0))
{
ctor(token,child0);
}
poi::ss::formula::ParseNode::ParseNode(::poi::ss::formula::ptg::Ptg* token, ParseNode* child0, ParseNode* child1)
: ParseNode(*static_cast< ::default_init_tag* >(0))
{
ctor(token,child0,child1);
}
poi::ss::formula::ParseNodeArray*& poi::ss::formula::ParseNode::EMPTY_ARRAY()
{
clinit();
return EMPTY_ARRAY_;
}
poi::ss::formula::ParseNodeArray* poi::ss::formula::ParseNode::EMPTY_ARRAY_;
void poi::ss::formula::ParseNode::ctor(::poi::ss::formula::ptg::Ptg* token, ParseNodeArray* children)
{
super::ctor();
if(token == nullptr) {
throw new ::java::lang::IllegalArgumentException(u"token must not be null"_j);
}
_token = token;
_children = npc(children)->clone();
_isIf = isIf(token);
auto tokenCount = int32_t(1);
for (auto i = int32_t(0); i < npc(children)->length; i++) {
tokenCount += npc((*children)[i])->getTokenCount();
}
if(_isIf) {
tokenCount += npc(children)->length;
}
_tokenCount = tokenCount;
}
void poi::ss::formula::ParseNode::ctor(::poi::ss::formula::ptg::Ptg* token)
{
ctor(token, EMPTY_ARRAY_);
}
void poi::ss::formula::ParseNode::ctor(::poi::ss::formula::ptg::Ptg* token, ParseNode* child0)
{
ctor(token, new ParseNodeArray({child0}));
}
void poi::ss::formula::ParseNode::ctor(::poi::ss::formula::ptg::Ptg* token, ParseNode* child0, ParseNode* child1)
{
ctor(token, new ParseNodeArray({
child0
, child1
}));
}
int32_t poi::ss::formula::ParseNode::getTokenCount()
{
return _tokenCount;
}
int32_t poi::ss::formula::ParseNode::getEncodedSize()
{
auto result = dynamic_cast< ::poi::ss::formula::ptg::ArrayPtg* >(_token) != nullptr ? ::poi::ss::formula::ptg::ArrayPtg::PLAIN_TOKEN_SIZE : npc(_token)->getSize();
for (auto i = int32_t(0); i < npc(_children)->length; i++) {
result += npc((*_children)[i])->getEncodedSize();
}
return result;
}
poi::ss::formula::ptg::PtgArray* poi::ss::formula::ParseNode::toTokenArray_(ParseNode* rootNode)
{
clinit();
auto temp = new ParseNode_TokenCollector(npc(rootNode)->getTokenCount());
npc(rootNode)->collectPtgs(temp);
return npc(temp)->getResult();
}
void poi::ss::formula::ParseNode::collectPtgs(ParseNode_TokenCollector* temp)
{
if(isIf(_token)) {
collectIfPtgs(temp);
return;
}
auto isPreFixOperator = dynamic_cast< ::poi::ss::formula::ptg::MemFuncPtg* >(_token) != nullptr || dynamic_cast< ::poi::ss::formula::ptg::MemAreaPtg* >(_token) != nullptr;
if(isPreFixOperator) {
npc(temp)->add(_token);
}
for (auto i = int32_t(0); i < npc(getChildren())->length; i++) {
npc((*getChildren())[i])->collectPtgs(temp);
}
if(!isPreFixOperator) {
npc(temp)->add(_token);
}
}
void poi::ss::formula::ParseNode::collectIfPtgs(ParseNode_TokenCollector* temp)
{
npc((*getChildren())[int32_t(0)])->collectPtgs(temp);
auto ifAttrIndex = npc(temp)->createPlaceholder();
npc((*getChildren())[int32_t(1)])->collectPtgs(temp);
auto skipAfterTrueParamIndex = npc(temp)->createPlaceholder();
auto trueParamSize = npc(temp)->sumTokenSizes(ifAttrIndex + int32_t(1), skipAfterTrueParamIndex);
auto attrIf = ::poi::ss::formula::ptg::AttrPtg::createIf(trueParamSize + int32_t(4));
if(npc(getChildren())->length > 2) {
npc((*getChildren())[int32_t(2)])->collectPtgs(temp);
auto skipAfterFalseParamIndex = npc(temp)->createPlaceholder();
auto falseParamSize = npc(temp)->sumTokenSizes(skipAfterTrueParamIndex + int32_t(1), skipAfterFalseParamIndex);
auto attrSkipAfterTrue = ::poi::ss::formula::ptg::AttrPtg::createSkip(falseParamSize + int32_t(4) + int32_t(4) - int32_t(1));
auto attrSkipAfterFalse = ::poi::ss::formula::ptg::AttrPtg::createSkip(int32_t(4) - int32_t(1));
npc(temp)->setPlaceholder(ifAttrIndex, attrIf);
npc(temp)->setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue);
npc(temp)->setPlaceholder(skipAfterFalseParamIndex, attrSkipAfterFalse);
} else {
auto attrSkipAfterTrue = ::poi::ss::formula::ptg::AttrPtg::createSkip(int32_t(4) - int32_t(1));
npc(temp)->setPlaceholder(ifAttrIndex, attrIf);
npc(temp)->setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue);
}
npc(temp)->add(_token);
}
bool poi::ss::formula::ParseNode::isIf(::poi::ss::formula::ptg::Ptg* token)
{
clinit();
if(dynamic_cast< ::poi::ss::formula::ptg::FuncVarPtg* >(token) != nullptr) {
auto func = java_cast< ::poi::ss::formula::ptg::FuncVarPtg* >(token);
if(npc(::poi::ss::formula::function::FunctionMetadataRegistry::FUNCTION_NAME_IF())->equals(static_cast< ::java::lang::Object* >(npc(func)->getName()))) {
return true;
}
}
return false;
}
poi::ss::formula::ptg::Ptg* poi::ss::formula::ParseNode::getToken()
{
return _token;
}
poi::ss::formula::ParseNodeArray* poi::ss::formula::ParseNode::getChildren()
{
return _children;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::formula::ParseNode::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.ParseNode", 35);
return c;
}
void poi::ss::formula::ParseNode::clinit()
{
super::clinit();
static bool in_cl_init = false;
struct clinit_ {
clinit_() {
in_cl_init = true;
EMPTY_ARRAY_ = (new ::poi::ss::formula::ParseNodeArray({}));
}
};
if(!in_cl_init) {
static clinit_ clinit_instance;
}
}
java::lang::Class* poi::ss::formula::ParseNode::getClass0()
{
return class_();
}
|
/*
* Copyright (c) 2019 SK Telecom Co., Ltd. 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.
*/
#ifndef __NUGU_DIRECTIVE_SEQUENCER_INTERFACE_H__
#define __NUGU_DIRECTIVE_SEQUENCER_INTERFACE_H__
#include <base/nugu_directive.h>
namespace NuguClientKit {
/**
* @file directive_sequencer_interface.hh
* @defgroup DirectiveSequencerInterface DirectiveSequencerInterface
* @ingroup SDKNuguClientKit
* @brief Directive Sequencer Interface
*
* DirectiveSequencer delivers the directives received from the network to
* the CapabilityAgent according to the dialog-id and blocking policy.
*
* @{
*/
/**
* @brief BlockingMedium
*/
enum class BlockingMedium {
AUDIO = 0, /**< Audio related medium */
VISUAL = 1, /**< Visual related medium */
NONE = 2 /**< None medium */
};
/**
* @brief BlockingPolicy
*/
typedef struct {
BlockingMedium medium; /**< BlockingMedium */
bool isBlocking; /**< true: Blocking, false: Non-blocking */
} BlockingPolicy;
/**
* @brief IDirectiveSequencerListener
* @see IDirectiveSequencer
*/
class IDirectiveSequencerListener {
public:
virtual ~IDirectiveSequencerListener() = default;
/**
* @brief Notify the directive to handle in advance
* @param[in] ndir NuguDirective object
* @return Stop propagation or not.
* @retval true The directive is handled. Stop propagating to other listeners.
* @retval false The directive is not handled.
*/
virtual bool onPreHandleDirective(NuguDirective* ndir) = 0;
/**
* @brief Notify the directive to handle
* @param[in] ndir NuguDirective object
* @return Directive processing result
* @retval true The directives were handled normally.
* @retval false There was a problem with the directive processing.
*/
virtual bool onHandleDirective(NuguDirective* ndir) = 0;
/**
* @brief Notify the directive to cancel
* @param[in] ndir NuguDirective object
*/
virtual void onCancelDirective(NuguDirective* ndir) = 0;
};
/**
* @brief IDirectiveSequencer
* @see IDirectiveSequencerListener
*/
class IDirectiveSequencer {
public:
virtual ~IDirectiveSequencer() = default;
/**
* @brief Add the Listener object
* @param[in] name_space directive namespace
* @param[in] listener listener object
*/
virtual void addListener(const std::string& name_space, IDirectiveSequencerListener* listener) = 0;
/**
* @brief Remove the Listener object
* @param[in] name_space directive namespace
* @param[in] listener listener object
*/
virtual void removeListener(const std::string& name_space, IDirectiveSequencerListener* listener) = 0;
/**
* @brief Add the BlockingPolicy
* @param[in] name_space directive namespace
* @param[in] name directive name
* @param[in] policy BlockingPolicy
* @return Result of adding policy
* @retval true success
* @retval false failure
*/
virtual bool addPolicy(const std::string& name_space, const std::string& name, BlockingPolicy policy) = 0;
/**
* @brief Get the BlockingPolicy for namespace.name
* @param[in] name_space directive namespace
* @param[in] name directive name
* @return BlockingPolicy
*/
virtual BlockingPolicy getPolicy(const std::string& name_space, const std::string& name) = 0;
/**
* @brief Cancel all pending directives related to the dialog_id.
* The canceled directives are freed.
* @param[in] dialog_id dialog-request-id
* @return result
* @retval true success
* @retval false failure
*/
virtual bool cancel(const std::string& dialog_id) = 0;
/**
* @brief Complete the blocking directive. The NuguDirective object will be destroyed.
* If there are pending directives, those directives will be processed at the next idle time.
* @param[in] ndir NuguDirective object
* @return result
* @retval true success
* @retval false failure
*/
virtual bool complete(NuguDirective* ndir) = 0;
/**
* @brief Add new directive to sequencer
* @param[in] ndir NuguDirective object
* @return result
* @retval true success
* @retval false failure
*/
virtual bool add(NuguDirective* ndir) = 0;
};
/**
* @}
*/
} // NuguClientKit
#endif /* __NUGU_DIRECTIVE_SEQUENCER_INTERFACE_H__ */
|
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Erewhon Shared" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <Shared/BaseApplication.hpp>
#include <iostream>
namespace ewn
{
BaseApplication::~BaseApplication() = default;
bool BaseApplication::Run()
{
for (const auto& reactorPtr : m_reactors)
{
reactorPtr->Poll([&](bool outgoing, std::size_t clientId, Nz::UInt32 data) { HandlePeerConnection(outgoing, clientId, data); },
[&](std::size_t clientId, Nz::UInt32 data) { HandlePeerDisconnection(clientId, data); },
[&](std::size_t clientId, Nz::NetPacket&& packet) { HandlePeerPacket(clientId, std::move(packet)); });
}
return Application::Run();
}
void BaseApplication::SetupNetwork(std::size_t peerPerReactor, const Nz::IpAddress& ipAddress)
{
m_peerPerReactor = peerPerReactor;
m_reactors.emplace_back(std::make_unique<NetworkReactor>(0, ipAddress, peerPerReactor));
}
void BaseApplication::OnConfigLoaded(const ConfigFile& /*config*/)
{
}
Nz::Clock BaseApplication::s_appClock;
}
|
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "AddressChecksum.h"
#include "../Hash.h"
#include "../HexCoding.h"
#include <cctype>
using namespace TW;
using namespace TW::Ethereum;
std::string Ethereum::checksumed(const Address& address, enum ChecksumType type) {
const auto addressString = hex(address.bytes);
const auto hash = hex(Hash::keccak256(addressString));
std::string string = "0x";
for (auto i = 0; i < std::min(addressString.size(), hash.size()); i += 1) {
const auto a = addressString[i];
const auto h = hash[i];
if (a >= '0' && a <= '9') {
string.push_back(a);
} else if ((h >= '8' && h <= '9') || (h >= 'a' && h <= 'f')) {
switch (type) {
case eip55:
string.push_back(static_cast<char>(toupper(a)));
break;
case wanchain:
string.push_back(static_cast<char>(tolower(a)));
break;
}
} else {
switch (type) {
case eip55:
string.push_back(static_cast<char>(tolower(a)));
break;
case wanchain:
string.push_back(static_cast<char>(toupper(a)));
break;
}
}
}
return string;
}
|
#pragma once
#include "search/model.hpp"
#include "search/pre_ranking_info.hpp"
#include "search/ranking_utils.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <ostream>
#include <string>
#include <utility>
class FeatureType;
namespace search
{
struct RankingInfo
{
static double const kMaxDistMeters;
static void PrintCSVHeader(std::ostream & os);
void ToCSV(std::ostream & os) const;
// Returns rank calculated by a linear model. Large values
// correspond to important features.
double GetLinearModelRank() const;
double GetErrorsMadePerToken() const;
// Distance from the feature to the pivot point.
double m_distanceToPivot = kMaxDistMeters;
// Rank of the feature.
uint8_t m_rank = 0;
// Popularity rank of the feature.
uint8_t m_popularity = 0;
// Confidence and UGC rating.
std::pair<uint8_t, float> m_rating = {0, 0.0f};
// Score for the feature's name.
NameScore m_nameScore = NAME_SCORE_ZERO;
// Number of misprints.
ErrorsMade m_errorsMade;
// Query tokens number.
size_t m_numTokens = 0;
// Matched parts of the query.
// todo(@m) Using TokenType instead of ModelType here would
// allow to distinguish postcodes too.
std::array<TokenRange, Model::TYPE_COUNT> m_tokenRanges;
// Fraction of characters from original query matched to feature.
double m_matchedFraction = 0.0;
// True iff all tokens that are not stop-words
// were used when retrieving the feature.
bool m_allTokensUsed = true;
// True iff all tokens retrieved from search index were matched without misprints.
bool m_exactMatch = true;
// True iff feature has country or capital type and matches request: full match with all tokens
// used and without misprints.
bool m_exactCountryOrCapital = true;
// Search type for the feature.
Model::Type m_type = Model::TYPE_COUNT;
// True if all of the tokens that the feature was matched by
// correspond to this feature's categories.
bool m_pureCats = false;
// True if none of the tokens that the feature was matched by
// corresponds to this feature's categories although all of the
// tokens are categorial ones.
bool m_falseCats = false;
// True iff the request is categorial.
bool m_categorialRequest = false;
// True iff the feature has a name.
bool m_hasName = false;
};
std::string DebugPrint(RankingInfo const & info);
} // namespace search
|
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/instant/instant_loader.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/history/history_tab_helper.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/safe_browsing/safe_browsing_tab_observer.h"
#include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
#include "chrome/browser/ui/constrained_window_tab_helper.h"
#include "chrome/browser/ui/constrained_window_tab_helper_delegate.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents_delegate.h"
#include "ipc/ipc_message.h"
namespace {
int kUserDataKey;
class InstantLoaderUserData : public base::SupportsUserData::Data {
public:
explicit InstantLoaderUserData(InstantLoader* loader) : loader_(loader) {}
InstantLoader* loader() const { return loader_; }
private:
~InstantLoaderUserData() {}
InstantLoader* const loader_;
DISALLOW_COPY_AND_ASSIGN(InstantLoaderUserData);
};
}
// WebContentsDelegateImpl -----------------------------------------------------
class InstantLoader::WebContentsDelegateImpl
: public ConstrainedWindowTabHelperDelegate,
public CoreTabHelperDelegate,
public content::WebContentsDelegate {
public:
explicit WebContentsDelegateImpl(InstantLoader* loader);
private:
// Overridden from ConstrainedWindowTabHelperDelegate:
virtual bool ShouldFocusConstrainedWindow() OVERRIDE;
// Overridden from CoreTabHelperDelegate:
virtual void SwapTabContents(content::WebContents* old_contents,
content::WebContents* new_contents) OVERRIDE;
// Overridden from content::WebContentsDelegate:
virtual bool ShouldSuppressDialogs() OVERRIDE;
virtual bool ShouldFocusPageAfterCrash() OVERRIDE;
virtual void LostCapture() OVERRIDE;
virtual void WebContentsFocused(content::WebContents* contents) OVERRIDE;
virtual bool CanDownload(content::RenderViewHost* render_view_host,
int request_id,
const std::string& request_method) OVERRIDE;
virtual void HandleMouseDown() OVERRIDE;
virtual void HandleMouseUp() OVERRIDE;
virtual void HandlePointerActivate() OVERRIDE;
virtual void HandleGestureEnd() OVERRIDE;
virtual void DragEnded() OVERRIDE;
virtual bool OnGoToEntryOffset(int offset) OVERRIDE;
virtual content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) OVERRIDE;
void MaybeCommitFromPointerRelease();
InstantLoader* const loader_;
DISALLOW_COPY_AND_ASSIGN(WebContentsDelegateImpl);
};
InstantLoader::WebContentsDelegateImpl::WebContentsDelegateImpl(
InstantLoader* loader)
: loader_(loader) {
}
bool InstantLoader::WebContentsDelegateImpl::ShouldFocusConstrainedWindow() {
// Return false so that constrained windows are not initially focused. If we
// did otherwise the preview would prematurely get committed when focus goes
// to the constrained window.
return false;
}
void InstantLoader::WebContentsDelegateImpl::SwapTabContents(
content::WebContents* old_contents,
content::WebContents* new_contents) {
// If this is being called, something is swapping in to loader's |contents_|
// before we've added it to the tab strip.
loader_->ReplacePreviewContents(old_contents, new_contents);
}
bool InstantLoader::WebContentsDelegateImpl::ShouldSuppressDialogs() {
// Any message shown during Instant cancels Instant, so we suppress them.
return true;
}
bool InstantLoader::WebContentsDelegateImpl::ShouldFocusPageAfterCrash() {
return false;
}
void InstantLoader::WebContentsDelegateImpl::LostCapture() {
MaybeCommitFromPointerRelease();
}
void InstantLoader::WebContentsDelegateImpl::WebContentsFocused(
content::WebContents* /* contents */) {
// The preview is getting focus. Equivalent to it being clicked.
bool tmp = loader_->is_pointer_down_from_activate_;
loader_->is_pointer_down_from_activate_ = true;
loader_->controller_->InstantLoaderContentsFocused();
loader_->is_pointer_down_from_activate_ = tmp;
}
bool InstantLoader::WebContentsDelegateImpl::CanDownload(
content::RenderViewHost* /* render_view_host */,
int /* request_id */,
const std::string& /* request_method */) {
// Downloads are disabled.
return false;
}
void InstantLoader::WebContentsDelegateImpl::HandleMouseDown() {
loader_->is_pointer_down_from_activate_ = true;
}
void InstantLoader::WebContentsDelegateImpl::HandleMouseUp() {
MaybeCommitFromPointerRelease();
}
void InstantLoader::WebContentsDelegateImpl::HandlePointerActivate() {
loader_->is_pointer_down_from_activate_ = true;
}
void InstantLoader::WebContentsDelegateImpl::HandleGestureEnd() {
MaybeCommitFromPointerRelease();
}
void InstantLoader::WebContentsDelegateImpl::DragEnded() {
// If the user drags, we won't get a mouse up (at least on Linux). Commit the
// Instant result when the drag ends, so that during the drag the page won't
// move around.
MaybeCommitFromPointerRelease();
}
bool InstantLoader::WebContentsDelegateImpl::OnGoToEntryOffset(int offset) {
return false;
}
content::WebContents* InstantLoader::WebContentsDelegateImpl::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
content::WebContents* preview = loader_->contents_.get();
if (loader_->controller_->CommitIfPossible(INSTANT_COMMIT_NAVIGATED))
return preview->GetDelegate()->OpenURLFromTab(source, params);
return NULL;
}
void InstantLoader::WebContentsDelegateImpl::MaybeCommitFromPointerRelease() {
if (loader_->is_pointer_down_from_activate_) {
loader_->is_pointer_down_from_activate_ = false;
loader_->controller_->CommitIfPossible(INSTANT_COMMIT_FOCUS_LOST);
}
}
// InstantLoader ---------------------------------------------------------------
// static
InstantLoader* InstantLoader::FromWebContents(
const content::WebContents* web_contents) {
InstantLoaderUserData* data = static_cast<InstantLoaderUserData*>(
web_contents->GetUserData(&kUserDataKey));
return data ? data->loader() : NULL;
}
InstantLoader::InstantLoader(InstantController* controller,
const std::string& instant_url)
: client_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
controller_(controller),
delegate_(new WebContentsDelegateImpl(
ALLOW_THIS_IN_INITIALIZER_LIST(this))),
instant_url_(instant_url),
supports_instant_(false),
is_pointer_down_from_activate_(false) {
}
InstantLoader::~InstantLoader() {
}
void InstantLoader::InitContents(const content::WebContents* active_tab) {
content::WebContents::CreateParams create_params(
active_tab->GetBrowserContext());
create_params.base_web_contents = active_tab;
contents_.reset(content::WebContents::CreateWithSessionStorage(
create_params,
active_tab->GetController().GetSessionStorageNamespaceMap()));
SetupPreviewContents();
// This HTTP header and value are set on loads that originate from Instant.
const char kInstantHeader[] = "X-Purpose: Instant";
DVLOG(1) << "LoadURL: " << instant_url_;
contents_->GetController().LoadURL(GURL(instant_url_), content::Referrer(),
content::PAGE_TRANSITION_GENERATED, kInstantHeader);
contents_->WasHidden();
}
content::WebContents* InstantLoader::ReleaseContents() {
CleanupPreviewContents();
return contents_.release();
}
void InstantLoader::DidNavigate(
const history::HistoryAddPageArgs& add_page_args) {
last_navigation_ = add_page_args;
}
bool InstantLoader::IsUsingLocalPreview() const {
return instant_url_ == InstantController::kLocalOmniboxPopupURL;
}
void InstantLoader::Update(const string16& text,
size_t selection_start,
size_t selection_end,
bool verbatim) {
last_navigation_ = history::HistoryAddPageArgs();
client_.Update(text, selection_start, selection_end, verbatim);
}
void InstantLoader::Submit(const string16& text) {
client_.Submit(text);
}
void InstantLoader::Cancel(const string16& text) {
client_.Cancel(text);
}
void InstantLoader::SetPopupBounds(const gfx::Rect& bounds) {
client_.SetPopupBounds(bounds);
}
void InstantLoader::SetMarginSize(int start, int end) {
client_.SetMarginSize(start, end);
}
void InstantLoader::SendAutocompleteResults(
const std::vector<InstantAutocompleteResult>& results) {
client_.SendAutocompleteResults(results);
}
void InstantLoader::UpOrDownKeyPressed(int count) {
client_.UpOrDownKeyPressed(count);
}
void InstantLoader::SearchModeChanged(const chrome::search::Mode& mode) {
client_.SearchModeChanged(mode);
}
void InstantLoader::SendThemeBackgroundInfo(
const ThemeBackgroundInfo& theme_info) {
client_.SendThemeBackgroundInfo(theme_info);
}
void InstantLoader::SendThemeAreaHeight(int height) {
client_.SendThemeAreaHeight(height);
}
void InstantLoader::SetDisplayInstantResults(bool display_instant_results) {
client_.SetDisplayInstantResults(display_instant_results);
}
void InstantLoader::KeyCaptureChanged(bool is_key_capture_enabled) {
client_.KeyCaptureChanged(is_key_capture_enabled);
}
void InstantLoader::SetSuggestions(
const std::vector<InstantSuggestion>& suggestions) {
InstantSupportDetermined(true);
controller_->SetSuggestions(contents(), suggestions);
}
void InstantLoader::InstantSupportDetermined(bool supports_instant) {
// If we had already determined that the page supports Instant, nothing to do.
if (supports_instant_)
return;
supports_instant_ = supports_instant;
controller_->InstantSupportDetermined(contents(), supports_instant);
}
void InstantLoader::ShowInstantPreview(InstantShownReason reason,
int height,
InstantSizeUnits units) {
InstantSupportDetermined(true);
controller_->ShowInstantPreview(reason, height, units);
}
void InstantLoader::StartCapturingKeyStrokes() {
InstantSupportDetermined(true);
controller_->StartCapturingKeyStrokes();
}
void InstantLoader::StopCapturingKeyStrokes() {
InstantSupportDetermined(true);
controller_->StopCapturingKeyStrokes();
}
void InstantLoader::RenderViewGone() {
controller_->InstantLoaderRenderViewGone();
}
void InstantLoader::AboutToNavigateMainFrame(const GURL& url) {
controller_->InstantLoaderAboutToNavigateMainFrame(url);
}
void InstantLoader::NavigateToURL(const GURL& url,
content::PageTransition transition) {
InstantSupportDetermined(true);
controller_->NavigateToURL(url, transition);
}
void InstantLoader::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
#if defined(OS_MACOSX)
if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) {
if (content::RenderWidgetHostView* rwhv =
contents_->GetRenderWidgetHostView())
rwhv->SetTakesFocusOnlyOnMouseDown(true);
return;
}
NOTREACHED();
#endif
}
void InstantLoader::SetupPreviewContents() {
client_.SetContents(contents());
contents_->SetUserData(&kUserDataKey, new InstantLoaderUserData(this));
contents_->SetDelegate(delegate_.get());
// Set up various tab helpers. The rest will get attached when (if) the
// contents is added to the tab strip.
// Tab helpers to control popups.
BlockedContentTabHelper::CreateForWebContents(contents());
BlockedContentTabHelper::FromWebContents(contents())->
SetAllContentsBlocked(true);
TabSpecificContentSettings::CreateForWebContents(contents());
TabSpecificContentSettings::FromWebContents(contents())->
SetPopupsBlocked(true);
// A tab helper to control constrained windows.
ConstrainedWindowTabHelper::CreateForWebContents(contents());
ConstrainedWindowTabHelper::FromWebContents(contents())->
set_delegate(delegate_.get());
// A tab helper to catch prerender content swapping shenanigans.
CoreTabHelper::CreateForWebContents(contents());
CoreTabHelper::FromWebContents(contents())->set_delegate(delegate_.get());
// Tab helpers used when committing a preview.
chrome::search::SearchTabHelper::CreateForWebContents(contents());
HistoryTabHelper::CreateForWebContents(contents());
// Observers.
extensions::WebNavigationTabObserver::CreateForWebContents(contents());
// Favicons, required by the Task Manager.
FaviconTabHelper::CreateForWebContents(contents());
// And some flat-out paranoia.
safe_browsing::SafeBrowsingTabObserver::CreateForWebContents(contents());
#if defined(OS_MACOSX)
// If |contents_| doesn't yet have a RWHV, SetTakesFocusOnlyOnMouseDown() will
// be called later, when NOTIFICATION_RENDER_VIEW_HOST_CHANGED is received.
if (content::RenderWidgetHostView* rwhv =
contents_->GetRenderWidgetHostView())
rwhv->SetTakesFocusOnlyOnMouseDown(true);
registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
content::Source<content::NavigationController>(
&contents_->GetController()));
#endif
}
void InstantLoader::CleanupPreviewContents() {
client_.SetContents(NULL);
contents_->RemoveUserData(&kUserDataKey);
contents_->SetDelegate(NULL);
// Undo tab helper work done in SetupPreviewContents().
BlockedContentTabHelper::FromWebContents(contents())->
SetAllContentsBlocked(false);
TabSpecificContentSettings::FromWebContents(contents())->
SetPopupsBlocked(false);
ConstrainedWindowTabHelper::FromWebContents(contents())->
set_delegate(NULL);
CoreTabHelper::FromWebContents(contents())->set_delegate(NULL);
#if defined(OS_MACOSX)
if (content::RenderWidgetHostView* rwhv =
contents_->GetRenderWidgetHostView())
rwhv->SetTakesFocusOnlyOnMouseDown(false);
registrar_.Remove(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
content::Source<content::NavigationController>(
&contents_->GetController()));
#endif
}
void InstantLoader::ReplacePreviewContents(content::WebContents* old_contents,
content::WebContents* new_contents) {
DCHECK_EQ(old_contents, contents());
CleanupPreviewContents();
// We release here without deleting so that the caller still has the
// responsibility for deleting the WebContents.
ignore_result(contents_.release());
contents_.reset(new_contents);
SetupPreviewContents();
controller_->SwappedWebContents();
}
|
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <config.h>
#include <libgearman/common.h>
gearman_unique_t gearman_unique_make(const char *arg, size_t arg_size)
{
gearman_unique_t local= { arg, arg_size };
return local;
}
size_t gearman_unique_size(gearman_unique_t *self)
{
if (not self)
return 0;
return self->size;
}
|
// MultiSpec
//
// Copyright 1988-2020 Purdue Research Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at: https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
//
// MultiSpec is curated by the Laboratory for Applications of Remote Sensing at
// Purdue University in West Lafayette, IN and licensed by Larry Biehl.
//
// File: SStrings.cpp
//
// Authors: Larry L. Biehl
//
// Revision date: 08/30/2020
//
// Language: C
//
// System: Linux, Macintosh, and Windows Operating Systems
//
// Brief description: The purpose of the routines in this file is to
// provide utility type functions in MultiSpec that are
// shared in the Mac and Windows versions.
//
//------------------------------------------------------------------------------------
#include "SMultiSpec.h"
#include <ctype.h>
#if defined multispec_wx
#include "SMultiSpec.h"
#include "wx/string.h"
#include "wx/textfile.h"
#include "xGraphDoc.h"
#include "xGraphFrame.h"
#include "xGraphView.h"
#include "xImageView.h"
#include "xImageFrame.h"
#include "xImageDoc.h"
#include "xTextView.h"
#include "wx/stdpaths.h"
#endif // defined multispec_wx
#if defined multispec_mac || defined multispec_mac_swift
#include "MGraphView.h"
#define IDS_Processor20 20
#define IDS_Processor21 21
#define IDS_Processor22 22
#define IDS_Processor23 23
#define IDS_Processor24 24
#define IDS_Processor25 25
#define IDS_Processor26 26
#endif // defined multispec_mac || defined multispec_mac_swift
#if defined multispec_win
#include "SDisplay_class.h"
#include "SImageWindow_class.h"
#include "WGraphView.h"
#include "WImageView.h"
#include "WImageDoc.h"
#include "WStatisticsView.h"
#include "WTextDoc.h"
#include "WTextView.h"
Boolean MGetString (
TBYTE* outTextPtr,
UInt16 stringListID,
UInt16 stringID,
UInt16 maxStringLength=255);
#endif // defined multispec_win
extern void ListString (
const char* textBuffer);
extern Boolean ListString (
char* textBuffer,
unsigned int textLength=0);
// Prototypes for routines in this file that are only called by
// other routines in this file.
void ConcatPStringsUnicode (
FileStringPtr ioFirstStr,
const UCharPtr inSecondStr,
SInt16 inDestSize);
Boolean LoadSpecifiedStringNumberLong (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
SInt32 lValue1,
SInt32 lValue2);
Boolean LoadSpecifiedStringNumberString (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
char* inputStringPtr);
Boolean LoadSpecifiedStringNumberString (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
FileStringPtr inputStringPtr);
#if defined multispec_wx
void MSetWindowTitle (
wxDocument* documentCPtr,
UCharPtr titleStringPtr);
#endif
#if defined multispec_mac
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CheckStringLength
//
// Software purpose: The purpose of this routine is to check the length
// of the input string relative to the width to be
// drawn in. If the string is too long, then remove
// characters from the end until the string does fit
// and add the ellipses "".
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By: DrawClassPrompt
// DrawFieldPrompt
//
// Coded By: Larry L. Biehl Date: 02/07/1989
// Revised By: Larry L. Biehl Date: 03/15/2017
void CheckStringLength (
SInt16 maxWidth,
Str255* inputString,
Str255* outputString)
{
// Declare local variables and structures
SInt16 inputStringWidth,
newCharLength,
space = 2;
// Get the width of the input string.
inputStringWidth = StringWidth (*inputString);
// Adjust maximum width to allow for some space at the beginning and
// end of the string.
maxWidth -= space + space;
// Copy input string to the output string.
if (inputStringWidth > 0)
CopyPToP ((UCharPtr)outputString, (UCharPtr)inputString);
else // inputStringWidth <= 0
(*outputString)[0] = 0;
// If input string width is greater than the maximum width allowed,
// then remove character from the end until it fits.
if (inputStringWidth > maxWidth)
{
newCharLength = (*outputString)[0];
//maxWidth -= CharWidth ('\p…');
//maxWidth -= CharWidth ('…');
maxWidth -= CharWidth (0xC9);
do
{
inputStringWidth -= CharWidth ((*outputString)[newCharLength]);
newCharLength--;
} while (inputStringWidth > maxWidth && newCharLength >= 0);
// Add the ellipses character.
newCharLength++;
(*outputString)[newCharLength] = 0xC9; // ellipsis character (...)
(*outputString)[0] = newCharLength;
} // end "if (inputStringWidth > maxWidth)"
} // end "CheckStringLength"
#endif // defined multispec_mac
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean CheckTextWindowSpaceNeeded
//
// Software purpose: The purpose of this routine is to check if there is
// enough memory to list the input number of characters
// in the text window. This has been set up for the Macintosh
// OS. I have not determined an equivalent for Windows. For now
// I will just use the same. The TextBlock structure under
// Windows is really just filler.
//
// For wxWidgets interface (Linux & MacOS), just return true.
//
// Parameters in: Estimated number of characters to go into the text output
// window.
//
// Parameters out: None
//
// Value Returned:
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/03/1993
// Revised By: Larry L. Biehl Date: 03/22/2019
Boolean CheckTextWindowSpaceNeeded (
UInt32 numberBytesNeeded)
{
#ifndef multispec_wx
double floatTextSizeNeeded;
SInt64 contiguousMemory;
UInt32 textSizeNeeded;
SInt16 returnCode;
// Check amount of contiguous memory available. We will use
// contiguous memory here to be on the safe side; the memory does
// not have to be contiguous.
MGetFreeMemory (&contiguousMemory);
textSizeNeeded = numberBytesNeeded;
// Take into account Word Solution overhead for text buffers.
// one text buffer for around every 700 characters. The maximum
// buffer size is 1536.
numberBytesNeeded = textSizeNeeded/700 + 1;
//textSizeNeeded += numberBytesNeeded * sizeof (TextBlock);
// For now use the following for WASTE until I know more.
floatTextSizeNeeded = textSizeNeeded;
floatTextSizeNeeded += (double)numberBytesNeeded * 720;
if (floatTextSizeNeeded > contiguousMemory - gTextMemoryMinimum)
{
// Display an alert to indicated that there is not enough space
// available for the classification output in the text window.
returnCode = DisplayAlert (kErrorAlert2ID,
kStopAlert,
kAlertStrID,
IDS_Alert57,
0,
NULL);
return (FALSE);
} // end "if (floatTextSizeNeeded > contiguousMemory)"
return (TRUE);
#else // if it is wxwidgets interface
return true;
#endif
} // end "CheckTextWindowSpaceNeeded"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 CompareStringsNoCase
//
// Software purpose: The purpose of this routine is to compare strings str1 and str2
// ignoring the case of the characters in the string.
//
// Parameters in:
//
// Parameters out: None
//
// Value Returned: 0: the strings are the same.
// not 0: the strings are not the same.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: ??/??/????
// Revised By: Larry L. Biehl Date: 10/19/2017
SInt16 CompareStringsNoCase (
const UCharPtr str1,
const UCharPtr str2)
{
UCharPtr p1 = str1;
UCharPtr p2 = str2;
UInt32 c1,
c2;
c1 = toupper (*p1);
c2 = toupper (*p2);
while (c1 == c2)
{
if (c1 == 0)
return (0);
p1++;
p2++;
c1 = toupper (*p1);
c2 = toupper (*p2);
} // end "while (c1 == c2)"
return ((SInt16)(c1-c2));
} // end "CompareStringsNoCase"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 CompareStringsNoCase
//
// Software purpose: The purpose of this routine is to compare the first
// numberCharacters in strings str1 and str2
// ignoring the case of the characters in the string.
//
// Parameters in:
//
// Parameters out: None
//
// Value Returned: 0: the strings are the same.
// not 0: the strings are not the same.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: ??/??/????
// Revised By: Larry L. Biehl Date: 10/19/2017
SInt16 CompareStringsNoCase (
const UCharPtr str1,
const UCharPtr str2,
UInt32 numberCharacters)
{
const unsigned char* p1 = (unsigned char*)str1;
const unsigned char* p2 = (unsigned char*)str2;
UInt32 c1,
c2,
index;
if (str1 == NULL || str2 == NULL)
return (0);
index = 0;
do
{
if (index >= numberCharacters)
return (0);
c1 = toupper (*p1);
c2 = toupper (*p2);
p1++;
p2++;
index++;
} while (c1 == c2);
return ((SInt16)(c1-c2));
} // end "CompareStringsNoCase"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean CompareSuffixNoCase
//
// Software purpose: This routine compares the input suffix of length n
// with the last n characters of the input string.
// TRUE is returned if they compare and FALSE otherwise.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/04/1988
// Revised By: Larry L. Biehl Date: 04/10/2020
Boolean CompareSuffixNoCase (
const CharPtr suffixStringPtr,
FileStringPtr stringPtr,
UInt16* numSuffixCharsPtr)
{
StringPtr tempPtr;
SInt32 diff,
index;
UInt32 lengthSuffixString;
UInt16 stringLength;
Boolean returnFlag;
returnFlag = FALSE;
lengthSuffixString = (UInt32)suffixStringPtr[0];
if (lengthSuffixString == 0)
{
// This must be a C string. Get the length.
lengthSuffixString = (UInt32)strlen ((char*)&suffixStringPtr[1]);
lengthSuffixString = MIN (lengthSuffixString, 255);
} // end "if (lengthSuffixString == 0)"
if (numSuffixCharsPtr != NULL)
*numSuffixCharsPtr = (UInt16)lengthSuffixString;
//index = (SInt32)*stringPtr - lengthSuffixString + 1;
stringLength = GetFileStringLength (stringPtr);
index = (SInt32)stringLength - lengthSuffixString + 2;
if (index > 2)
{
stringPtr = &stringPtr[index];
tempPtr = (StringPtr)&suffixStringPtr[1];
if (tempPtr == stringPtr)
return (TRUE);
while (lengthSuffixString > 0)
{
if (*tempPtr != '?')
{
diff = toupper (*tempPtr) - toupper (*stringPtr);
if (diff != 0)
return (FALSE);
} // end "if (*tempPtr != '?')"
tempPtr++;
stringPtr++;
lengthSuffixString--;
} // end "while (lengthSuffixString > 0)"
return (TRUE);
} // end "if (index > 2)"
return (returnFlag);
} // end "CompareSuffixNoCase"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean CompareSuffixNoCase
//
// Software purpose: This routine compares the input suffix of length n
// with the last n characters of the input string.
// TRUE is returned if they compare and FALSE otherwise.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/04/1988
// Revised By: Larry L. Biehl Date: 04/10/2020
Boolean CompareSuffixNoCase (
const CharPtr suffixStringPtr,
WideFileStringPtr stringPtr,
UInt16* numSuffixCharsPtr)
{
char* tempPtr;
UInt16* stringLengthPtr;
SInt32 diff,
index;
UInt32 lengthSuffixString;
Boolean returnFlag;
returnFlag = FALSE;
lengthSuffixString = (UInt32)*suffixStringPtr;
if (lengthSuffixString == 0)
{
// This must be a C string. Get the length.
lengthSuffixString = (UInt32)strlen ((char*)&suffixStringPtr[1]);
lengthSuffixString = MIN (lengthSuffixString, 255);
} // end "if (lengthSuffixString == 0)"
if (numSuffixCharsPtr != NULL)
*numSuffixCharsPtr = (UInt16)lengthSuffixString;
//index = (SInt32)stringPtr[0] - lengthSuffixString + 1;
stringLengthPtr = (UInt16*)stringPtr;
index = (SInt32)stringLengthPtr[0] - lengthSuffixString + 2;
if (index > 1)
{
stringPtr = &stringPtr[index];
tempPtr = &suffixStringPtr[1];
if ((wchar_t*)tempPtr == stringPtr)
return (TRUE);
while (lengthSuffixString > 0)
{
if (*tempPtr != L'?')
{
wchar_t wideTempChar;
mbstowcs (&wideTempChar, (const char*)tempPtr, 1);
diff = towupper (wideTempChar) - towupper (*stringPtr);
if (diff != 0)
return (FALSE);
} // end "if (*tempPtr != '?')"
tempPtr++;
stringPtr++;
lengthSuffixString--;
} // end "while (lengthSuffixString > 0)"
return (TRUE);
} // end "if (index > 1)"
return (returnFlag);
} // end "CompareSuffixNoCase"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConcatFilenameSuffix
//
// Software purpose: The purpose of this routine is to append the input suffix to
// the input file name. First the length of the file name will
// be shorten if needed to allow the suffix.
//
// Parameters in: Address of input file name
// Address of input suffix to be added
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 06/21/2001
// Revised By: Larry L. Biehl Date: 03/13/2017
void ConcatFilenameSuffix (
wchar_t* fileNamePtr,
const StringPtr suffixPtr,
SInt16 charFormatCode)
{
// Limit combined string to inDestSize chars
UInt16 charsToCopy = suffixPtr[0];
// If length of the second string is 0, then assume that
// it is a C string and get the length.
if (charsToCopy == 0)
charsToCopy = (UInt16)strlen ((CharPtr)&suffixPtr[1]);
if (gFileNameLengthLimit > charsToCopy)
{
// Make sure that the name with the suffix fits within the max file
// name length.
if (charFormatCode == kAsciiFormatCode)
{
UCharPtr charFileNamePtr = (UCharPtr)fileNamePtr;
charFileNamePtr[0] = MIN (charFileNamePtr[0], gFileNameLengthLimit-charsToCopy);
ConcatPStrings (charFileNamePtr, suffixPtr, 255);
} // end "if (charFormatCode == kAsciiFormatCode)"
else // charFormatCode != kAsciiFormatCode
{
fileNamePtr[0] = MIN (fileNamePtr[0], gFileNameLengthLimit-charsToCopy);
// Convert char suffix to unicode suffix
TBYTE wideSuffix[16];
mbstowcs (&wideSuffix[1], (const char*)&suffixPtr[1], charsToCopy);
wideSuffix[0] = charsToCopy;
//ConcatPStrings (fileNamePtr, wideSuffix, 255);
} // end "else charFormatCode != kAsciiFormatCode"
} // end "if (gFileNameLengthLimit > charsToCopy)"
// Force a c terminator as the last character of the input string.
fileNamePtr[255] = 0;
} // end "ConcatFilenameSuffix"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConcatFilenameSuffix
//
// Software purpose: The purpose of this routine is to append the input suffix to
// the input file name. First the length of the file name will
// be shorten if needed to allow the suffix.
//
// Parameters in: Address of input file name
// Address of input suffix to be added
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/10/2017
// Revised By: Larry L. Biehl Date: 04/15/2020
void ConcatFilenameSuffix (
FileStringPtr fileNamePtr,
UInt8* charSuffixPtr)
{
UInt16 fileNameLength;
// Limit combined string to inDestSize chars
UInt16 charsToCopy = charSuffixPtr[0];
// If length of the second string is 0, then assume that
// it is a C string and get the length.
if (charsToCopy == 0)
charsToCopy = (UInt16)strlen ((CharPtr)&charSuffixPtr[1]);
fileNameLength = GetFileStringLength (fileNamePtr);
if (gFilePathNameLengthLimit > charsToCopy)
{
fileNameLength = MIN (fileNameLength, gFilePathNameLengthLimit-charsToCopy);
memcpy (&fileNamePtr[fileNameLength+2], &charSuffixPtr[1], charsToCopy);
SetFileStringLength (fileNamePtr, fileNameLength+charsToCopy);
} // end "if (gFilePathNameLengthLimit > charsToCopy)"
else // gFilePathNameLengthLimit <= charsToCopy
// Cannot add the suffix to the input string.
// Force a c terminator as the last character of the input string.
fileNamePtr[fileNameLength+2] = 0;
} // end "ConcatFilenameSuffix"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConcatPStrings
//
// Software purpose: The purpose of this routine is to append a pascal
// string to the end of another pascal string.
//
// Parameters in: Address of base string
// Address of string to be copied to end of the base string.
// Maximum number of characters allowed for the appended string.
// This does not include the pascal character count.
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/19/1995
// Revised By: Larry L. Biehl Date: 12/02/2011
void ConcatPStrings (
UCharPtr ioFirstStr,
const UCharPtr inSecondStr,
SInt16 inDestSize)
{
if (ioFirstStr != NULL && inSecondStr != NULL)
{
// Limit combined string to inDestSize chars
SInt16 charsToCopy = (SInt16)inSecondStr[0];
// If length of the second string is 0, then assume that
// it is a C string and get the length.
if (charsToCopy == 0)
charsToCopy = (SInt16)strlen ((CharPtr)&inSecondStr[1]);
if ((SInt16)*ioFirstStr + charsToCopy > inDestSize)
charsToCopy = inDestSize - *ioFirstStr;
if (charsToCopy < 0)
charsToCopy = 0;
// Copy second to end of first string
memcpy (ioFirstStr + *ioFirstStr + 1,
inSecondStr + 1,
charsToCopy);
// Set length of combined string
ioFirstStr[0] += (UInt8)charsToCopy;
// Also make the string a C string if there is enough space.
if (ioFirstStr[0]+1 <= inDestSize)
ioFirstStr[ioFirstStr[0]+1] = 0;
} // end "if (ioFirstStr != NULL && inSecondStr != NULL)"
} // end "ConcatPStrings"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConvertMultibyteStringToUnicodeString
//
// Software purpose: The purpose of this routine is to convert the input multibyte
// string to a unicode string. This will use the global gWideTextString
// as the location for the output string. Note that the output string
// cannot be larger than 254 characters plus pascal character count and
// c terminator.
//
// Parameters in: Address of input multibyte string set up as pascal string.
//
// Parameters out: None
//
// Value Returned: Address of output unicode string
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/21/2017
// Revised By: Larry L. Biehl Date: 06/19/2017
wchar_t* ConvertMultibyteStringToUnicodeString (
UCharPtr inputMultibyteStringPtr)
{
#if defined multispec_wx
wxWCharBuffer unicodeString;
size_t numberUnicodeChars;
unicodeString = wxConvUTF8.cMB2WC ((char*)inputMultibyteStringPtr,
wxNO_LEN,
&numberUnicodeChars);
wcsncpy (&gWideTextString[1], unicodeString, numberUnicodeChars);
gWideTextString[0] = numberUnicodeChars;
#endif // end "multispec_wx"
#if defined multispec_win
if (inputMultibyteStringPtr != NULL)
{
int sizeNeeded = MultiByteToWideChar (
CP_UTF8, 0, (LPCSTR)inputMultibyteStringPtr, -1, NULL, 0);
sizeNeeded = MIN (sizeNeeded, 254);
MultiByteToWideChar (CP_UTF8,
0,
(LPCSTR)inputMultibyteStringPtr,
-1,
(LPWSTR)&gWideTextString[1],
sizeNeeded);
gWideTextString[0] = (wchar_t)wcslen (&gWideTextString[1]);
} // end "if (inputMultibyteStringPtr != NULL)"
else // inputMultibyteStringPtr == NULL
{
gWideTextString[0] = 0;
gWideTextString[1] = 0;
} // else inputMultibyteStringPtr == NULL
return (gWideTextString);
#endif
return (NULL);
} // end "ConvertMultibyteStringToUnicodeString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConvertUnicodeStringToMultibyteString
//
// Software purpose: The purpose of this routine is to convert the input unicode
// string to a UTF8 string.
//
// Parameters in: Address of input unicode string set up as pascal string.
// Address of output utf8 formatted string set up as a C string.
//
// Parameters out: Number of characters in the output string
//
// Value Returned: Address of output unicode string
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/22/2017
// Revised By: Larry L. Biehl Date: 07/27/2018
void ConvertUnicodeStringToMultibyteString (
wchar_t* inputUnicodeStringPtr,
UCharPtr outputUTF8StringPtr,
UInt16 numberCharactersToCopy,
SInt16* outputStringLengthPtr)
{
#if defined multispec_mac
UniChar* uniCharInputStringPtr;
CFStringRef cfStringRef;
UInt16 numberChars;
outputUTF8StringPtr[0] = 0;
outputUTF8StringPtr[1] = 0;
if (numberCharactersToCopy == 0)
numberChars = inputUnicodeStringPtr[0];
else
numberChars = MIN (inputUnicodeStringPtr[0], numberCharactersToCopy);
uniCharInputStringPtr = (UniChar*)inputUnicodeStringPtr;
cfStringRef = CFStringCreateWithCharacters (
kCFAllocatorDefault,
(UniChar*)&uniCharInputStringPtr[1],
numberChars);
if (cfStringRef != NULL)
{
CFStringGetCString (cfStringRef,
(char*)outputUTF8StringPtr,
(CFIndex)255,
kCFStringEncodingUTF8);
*outputStringLengthPtr = strlen ((char*)outputUTF8StringPtr);
} // end "if (cfStringRef != NULL)"
#endif
#if defined multispec_wx
wxCharBuffer multiByteString;
UInt16 numberChars;
size_t numberMultiByteChars;
outputUTF8StringPtr[0] = 0;
outputUTF8StringPtr[1] = 0;
outputUTF8StringPtr[2] = 0;
if (numberCharactersToCopy == 0)
numberChars = inputUnicodeStringPtr[0];
else
numberChars = MIN (inputUnicodeStringPtr[0], numberCharactersToCopy);
multiByteString = wxConvUTF8.cWC2MB (&inputUnicodeStringPtr[1],
numberChars,
&numberMultiByteChars);
strncpy ((char*)outputUTF8StringPtr, multiByteString, numberMultiByteChars);
*outputStringLengthPtr = numberMultiByteChars;
#endif // end "multispec_wx"
#if defined multispec_win
UInt16 numberChars;
outputUTF8StringPtr[0] = 0;
outputUTF8StringPtr[1] = 0;
if (numberCharactersToCopy == 0)
numberChars = inputUnicodeStringPtr[0];
else
numberChars = MIN (inputUnicodeStringPtr[0], numberCharactersToCopy);
//int size = wcslen (titleBufferPtr);
int sizeNeeded = WideCharToMultiByte (
CP_UTF8, 0, &inputUnicodeStringPtr[1], numberChars, NULL, 0, NULL, NULL);
WideCharToMultiByte (CP_UTF8,
0,
&inputUnicodeStringPtr[1],
numberChars,
(LPSTR)outputUTF8StringPtr,
sizeNeeded,
NULL,
NULL);
*outputStringLengthPtr = sizeNeeded;
#endif // end "multispec_win"
// Make sure this can also be treated as a c string.
if (*outputStringLengthPtr < 256)
outputUTF8StringPtr[*outputStringLengthPtr] = 0;
} // end "ConvertUnicodeStringToMultibyteString"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConcatPStrings
//
// Software purpose: The purpose of this routine is to append a pascal
// string to the end of another pascal string.
//
// Parameters in: Address of base string
// Address of string to be copied to end of the base string.
// Maximum number of characters allowed for the appended string.
// This does not include the pascal character count.
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/23/2017
// Revised By: Larry L. Biehl Date: 03/14/2017
void ConcatPStrings (
wchar_t* ioFirstStr,
const wchar_t* inSecondStr,
SInt16 inDestSize)
{
if (ioFirstStr != NULL && inSecondStr != NULL)
{
// Limit combined string to inDestSize chars
SInt16 charsToCopy = (SInt16)inSecondStr[0];
// If length of the second string is 0, then assume that it is a C
// string and get the length.
if (charsToCopy == 0)
charsToCopy = wcslen (&inSecondStr[1]);
if ((SInt16)*ioFirstStr + charsToCopy > inDestSize)
charsToCopy = inDestSize - *ioFirstStr;
if (charsToCopy < 0)
charsToCopy = 0;
// Copy second to end of first string
wmemcpy (&ioFirstStr[*ioFirstStr+1],
&inSecondStr[1],
charsToCopy);
// Set length of combined string
ioFirstStr[0] += (UInt8)charsToCopy;
// Also make the string a C string if there is enough space.
if (ioFirstStr[0]+1 <= inDestSize)
ioFirstStr[ioFirstStr[0]+1] = 0;
} // end "if (ioFirstStr != NULL && inSecondStr != NULL)"
} // end "ConcatPStrings"
*/
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ConcatPStringsUnicode
//
// Software purpose: The purpose of this routine is to append a pascal
// string to the end of another pascal string.
//
// Parameters in: Address of base string
// Address of string to be copied to end of the base string.
// Maximum number of characters allowed for the appended string.
// This does not include the pascal character count.
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/22/2017
// Revised By: Larry L. Biehl Date: 02/22/2017
void ConcatPStringsUnicode (
UCharPtr ioFirstStr,
const UCharPtr inSecondStr,
SInt16 inDestSize)
{
if (ioFirstStr != NULL && inSecondStr != NULL)
{
// Limit combined string to inDestSize chars
SInt16 charsToCopy = (SInt16)inSecondStr[0];
// If length of the second string is 0, then assume that
// it is a C string and get the length.
if (charsToCopy == 0)
charsToCopy = strlen ((CharPtr)&inSecondStr[1]);
if ((SInt16)*ioFirstStr + charsToCopy > inDestSize)
charsToCopy = inDestSize - *ioFirstStr;
if (charsToCopy < 0)
charsToCopy = 0;
// Copy second to end of first string
memcpy (ioFirstStr + *ioFirstStr + 1,
inSecondStr + 1,
charsToCopy);
// Set length of combined string
ioFirstStr[0] += (UInt8)charsToCopy;
// Also make the string a C string if there is enough space.
if (ioFirstStr[0]+1 <= inDestSize)
ioFirstStr[ioFirstStr[0]+1] = 0;
} // end "if (ioFirstStr != NULL && inSecondStr != NULL)"
} // end "ConcatPStringsUnicode"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CopyFileStringToFileString
//
// Software purpose: The purpose of this routine is to copy a file string in which
// first 2-bytes included the string length to another file string.
// Allowance is made for a maximum string length that will be copied.
// The output string will be set to null string if the input length
// is 0.
//
// Parameters in: Address of from file string
// Address of to file string
// Maximum number of characters to copy
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/11/2020
// Revised By: Larry L. Biehl Date: 04/11/2020
void CopyFileStringToFileString (
FileStringPtr fromFileStringPtr,
FileStringPtr toFileStringPtr,
UInt16 maxLength)
{
UInt16 fileStringLength;
if (fromFileStringPtr != NULL && toFileStringPtr != NULL)
{
fileStringLength = GetFileStringLength (fromFileStringPtr);
fileStringLength = MIN (fileStringLength+3, maxLength);
memcpy (toFileStringPtr,
fromFileStringPtr,
fileStringLength+3);
} // end "if (fromFileStringPtr != NULL && toFileStringPtr != NULL)"
} // end "CopyFileStringToFileString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CopyFileStringToString
//
// Software purpose: The purpose of this routine is to copy a file string in which
// first 2-bytes included the string length to a string which
// contains just 1 byte at the beginning for the length of the string.
// The output string length is limited to 254 characters to allow
// for one byte for the count and one byte for the termination
// character at the end.
//
// Parameters in: Address of from file string
// Address of to file string
// Maximum number of characters to copy
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/16/2020
// Revised By: Larry L. Biehl Date: 04/16/2020
void CopyFileStringToString (
FileStringPtr fromFileStringPtr,
char* toFileStringPtr)
{
UInt16 fileStringLength;
if (fromFileStringPtr != NULL && toFileStringPtr != NULL)
{
fileStringLength = GetFileStringLength (fromFileStringPtr);
fileStringLength = MIN (fileStringLength, 254);
memcpy (&toFileStringPtr[1],
&fromFileStringPtr[2],
fileStringLength);
toFileStringPtr[0] = (char)fileStringLength;
toFileStringPtr[fileStringLength+1] = 0;
} // end "if (fromFileStringPtr != NULL && toFileStringPtr != NULL)"
} // end "CopyFileStringToString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CopyPToP
//
// Software purpose: The purpose of this routine is to copy a pascal
// string from one address to another address.
//
// Parameters in: Address of base string (p1)
// Address of string to copy to p1 (p2)
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: ?/ ?/????
// Revised By: Larry L. Biehl Date: 03/15/2017
void CopyPToP (
UCharPtr p1,
UCharPtr p2)
{
// Force the output string to be empty
if (p1 != NULL)
p1[0] = 0;
ConcatPStrings ((StringPtr)p1, (StringPtr)p2, 255);
} // end "CopyPToP"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CopyPToP
//
// Software purpose: The purpose of this routine is to copy a pascal
// wide string from one address to another address.
// Note that after going to UTF8 strings, this routine is not
// needed any more.
//
// Parameters in: Address of base string (p1)
// Address of string to copy to p1 (p2)
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/23/2017
// Revised By: Larry L. Biehl Date: 02/23/2017
void CopyPToP (
wchar_t* p1,
wchar_t* p2)
{
// Force the output string to be empty
if (p1 != NULL)
p1[0] = 0;
ConcatPStrings ((wchar_t*)p1, (wchar_t*)p2, 255);
} // end "CopyPToP"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CopyStringToFileString
//
// Software purpose: The purpose of this routine is to copy a string in which
// first byte includes the string length to another file string in
// which the first 2-bytes includes the string length.
// Allowance is made for a maximum string length that will be copied.
// The output string will be set to null string if the input length
// is 0.
//
// Parameters in: Address of from file string
// Address of to file string
// Maximum number of characters to copy
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/12/2020
// Revised By: Larry L. Biehl Date: 04/12/2020
void CopyStringToFileString (
UCharPtr fromStringPtr,
FileStringPtr toFileStringPtr,
UInt16 maxLength)
{
UInt16 stringLength;
if (fromStringPtr != NULL && toFileStringPtr != NULL)
{
stringLength = fromStringPtr[0];
stringLength = MIN (stringLength, maxLength-3);
memcpy (&toFileStringPtr[2],
&fromStringPtr[1],
stringLength);
SetFileStringLength (toFileStringPtr, stringLength);
} // end "if (fromFileStringPtr != NULL && toFileStringPtr != NULL)"
else if (fromStringPtr == NULL && toFileStringPtr != NULL)
{
SetFileStringLength (toFileStringPtr, 0);
} // end "else if (fromStringPtr == NULL && toFileStringPtr != NULL)"
} // end "CopyStringToFileString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 CreateNumberWithCommasInString
//
// Software purpose: This routine converts a decimal value to a string with commas.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 05/01/2003
// Revised By: Larry L. Biehl Date: 05/01/2003
SInt16 CreateNumberWithCommasInString (
char* inputStringPtr,
SInt32 dataValue)
{
SInt16 numberChars;
numberChars = sprintf (inputStringPtr, "%d", (int)dataValue);
numberChars = InsertCommasInNumberString (inputStringPtr,
numberChars,
-1,
numberChars);
return (numberChars);
} // end "CreateNumberWithCommasInString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 CreateNumberWithCommasInString
//
// Software purpose: This routine converts a decimal value to a string with commas.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/23/2010
// Revised By: Larry L. Biehl Date: 08/26/2010
SInt16 CreateNumberWithCommasInString (
char* inputStringPtr,
SInt64 dataValue)
{
SInt16 numberChars;
numberChars = sprintf (inputStringPtr, "%lld", dataValue);
numberChars = InsertCommasInNumberString (inputStringPtr,
numberChars,
-1,
numberChars);
return (numberChars);
} // end "CreateNumberWithCommasInString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CharPtr CtoPstring
//
// Software purpose: This routine copies the input C string to an output
// pascal string. The input and output string pointers
// can represent the same string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/24/1995
// Revised By: Larry L. Biehl Date: 04/09/2020
UCharPtr CtoPstring (
UCharPtr inCStringPtr,
UCharPtr outPStringPtr,
int maxStringLength)
{
if (inCStringPtr != NULL && outPStringPtr != NULL)
{
size_t bytesToMove = strlen ((CharPtr)inCStringPtr);
bytesToMove = MIN (bytesToMove, maxStringLength);
if (bytesToMove > 0)
memmove (&outPStringPtr[1], inCStringPtr, bytesToMove);
outPStringPtr[0] = 255;
if (bytesToMove < 255)
outPStringPtr[0] = (UInt8)bytesToMove;
// Also make it a c string.
outPStringPtr[bytesToMove+1] = 0;
} // end "if (inCStringPtr != NULL && ...)"
return outPStringPtr;
} // end "CtoPstring"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: FileStringPtr CtoPstring
//
// Software purpose: This routine copies the input C string to an output
// pascal string. The input and output string pointers
// can represent the same string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/23/2017
// Revised By: Larry L. Biehl Date: 04/09/2020
wchar_t* CtoPstring (
wchar_t* inCStringPtr,
wchar_t* outPStringPtr,
int maxStringLength)
{
if (inCStringPtr != NULL && outPStringPtr != NULL)
{
size_t bytesToMove = wcslen (inCStringPtr);
bytesToMove = MIN (bytesToMove, maxStringLength);
if (bytesToMove > 0)
wmemmove (&outPStringPtr[1], inCStringPtr, bytesToMove);
outPStringPtr[0] = (wchar_t)bytesToMove;
// Also make it a c string.
outPStringPtr[bytesToMove+1] = 0;
} // end "if (inCStringPtr != NULL && ...)
return outPStringPtr;
} // end "CtoPstring"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ForceTextToEnd
//
// Software purpose: The purpose of this routine is to force the text
// selection location to be at the end of the current
// text in the output text window.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By: ClassifyControl in SClassify.cpp
//
// Coded By: Larry L. Biehl Date: 12/14/1990
// Revised By: Larry L. Biehl Date: 03/27/2017
void ForceTextToEnd (void)
{
#if defined multispec_mac
GrafPtr savedPort;
if (gOutputWindow != NULL)
{
// Save the current port.
GetPort (&savedPort);
SetPortWindowPort (gOutputWindow);
// Force text selection to start from end of present text
#if use_mlte_for_text_window
TXNSetSelection (gOutputTextH, kTXNEndOffset, kTXNEndOffset);
#endif // !use_mlte_for_text_window
#if !use_mlte_for_text_window
WESetSelection (LONG_MAX, LONG_MAX, gOutputTextH);
#endif // !use_mlte_for_text_window
SetPort (savedPort);
} // end "if (gOutputWindow != NULL)"
#endif // defined multispec_mac
#if defined multispec_win
if (gOutputViewCPtr != NULL)
gOutputViewCPtr->GetEditCtrl().SetSel (2147483646, 2147483646, TRUE);
#endif // defined multispec_win
#if defined multispec_wx
wxStyledTextCtrl* textCtrl;
if (gOutputViewCPtr != NULL)
{
textCtrl = gOutputViewCPtr->m_textsw;
textCtrl->ShowPosition (textCtrl->GetLastPosition ());
} // end "if (gOutputViewCPtr != NULL)"
#endif
} // end "ForceTextToEnd"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void GetActiveImageWindowTitle
//
// Software purpose: The purpose of this routine is to get the
// title for the active image window.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/29/1995
// Revised By: Larry L. Biehl Date: 03/20/2018
void GetActiveImageWindowTitle (
UCharPtr titleStringPtr)
{
titleStringPtr[0] = 0;
#if defined multispec_mac
if (gActiveImageWindow != NULL)
{
GetWTitle (gActiveImageWindow, titleStringPtr);
titleStringPtr[titleStringPtr[0]+1] = 0;
} // end "if (gActiveImageWindow != NULL)"
#endif // defined multispec_mac
#if defined multispec_win
if (gActiveImageViewCPtr != NULL)
{
CMImageDoc* documentCPtr = gActiveImageViewCPtr->GetDocument ();
CString titleString = documentCPtr->GetTitle ();
UInt16 titleLength = titleString.GetLength ();
LPTSTR titleBufferPtr = titleString.GetBuffer (titleLength);
int size = (int)wcslen (titleBufferPtr);
int sizeNeeded = WideCharToMultiByte (
CP_UTF8, 0, titleBufferPtr, size, NULL, 0, NULL, NULL);
WideCharToMultiByte (CP_UTF8,
0,
titleBufferPtr,
size,
(LPSTR)&titleStringPtr[1],
sizeNeeded,
NULL,
NULL);
//memcpy (&titleStringPtr[1],
// titleBufferPtr,
// titleLength);
titleString.ReleaseBuffer ();
//titleStringPtr[0] = (UInt8)strlen ((char*)&titleStringPtr[1]);
titleStringPtr[0] = (UInt8)sizeNeeded;
titleStringPtr[sizeNeeded+1] = 0;
} // end "if (gActiveImageViewCPtr != NULL)"
#endif // defined multispec_win
#if defined multispec_wx
wxString titleString = (gActiveImageViewCPtr->m_frame)->GetTitle ();
UInt16 titleLength = MIN ((UInt16)titleString.Length (), 254);
strncpy ((char*)&titleStringPtr[1],
(const char*)titleString.mb_str (wxConvUTF8),
254);
titleStringPtr[0] = (UInt8)titleLength;
titleStringPtr[titleLength+1] = 0;
#endif
} // end "GetActiveImageWindowTitle"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: int GetFileStringLength
//
// Software purpose: The purpose of this routine is to return the length of the
// input file string.
//
// Parameters in: Wide file string.
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/10/2020
// Revised By: Larry L. Biehl Date: 04/10/2020
int GetFileStringLength (
FileStringPtr fileStringPtr)
{
UInt16* fileStringLengthPtr;
fileStringLengthPtr = (UInt16*)fileStringPtr;
return (fileStringLengthPtr[0]);
} // end "GetFileStringLength"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void GetImageWindowName
//
// Software purpose: The purpose of this routine is to get the text for a window
// name or a tiff file name.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By: SetImageWTitle in SDisplayMultispectral.cpp
// FileSpecificationDialogOK in SOpenFileDialog.cpp
// SaveImageWindowAs in SSaveWrite.cpp
// CreateImageWindow in SImageWindow_class.cpp
//
// Coded By: Larry L. Biehl Date: 10/23/2000
// Revised By: Larry L. Biehl Date: 04/12/2020
void GetImageWindowName (
DisplaySpecsPtr displaySpecsPtr,
FileInfoPtr fileInfoPtr,
UCharPtr namePtr,
Boolean removeSuffixFlag)
{
unsigned char windowNameString[512];
int numChars;
SInt16 length,
savedLength,
totalLength;
if (namePtr == NULL)
return;
if (fileInfoPtr == NULL)
{
namePtr[1] = 0;
return;
}
// Initialize local variables.
totalLength = 1;
// First check if this window represents several file layers.
if (gImageWindowInfoPtr != NULL && gImageWindowInfoPtr->numberImageFiles > 1)
{
//sprintf ((char*)&namePtr[0], "L%hd-", gImageWindowInfoPtr->numberImageFiles);
//CtoPstring (namePtr, namePtr);
//totalLength += namePtr[0];
numChars = sprintf ((char*)&windowNameString[2],
"L%hd-",
gImageWindowInfoPtr->numberImageFiles);
totalLength += numChars;
} // end "if (gImageWindowInfoPtr != NULL && gImageWindowInfoPtr->..."
length = 0;
if (fileInfoPtr->hdfHandle != NULL)
{
CreateFullDataSetIdentifierName (fileInfoPtr,
fileInfoPtr->hdfDataSetSelection,
(StringPtr)gTextString2,
60);
length = gTextString2[0];
//sprintf ((char*)&namePtr[totalLength],
// "%s",
// &gTextString2[1]);
sprintf ((char*)&windowNameString[totalLength+1],
"%s",
&gTextString2[1]);
} // end "if (fileInfoPtr->format == kHDF4Type || ..."
if (length == 0)
{
char* fileNamePtr = (char*)GetFileNameCPointerFromFileInfo (fileInfoPtr);
length = (SInt16)strlen (fileNamePtr);
//sprintf ((char*)&namePtr[totalLength],
// "%s",
// fileNamePtr);
sprintf ((char*)&windowNameString[totalLength+1],
"%s",
fileNamePtr);
} // end "if (length == 0)"
totalLength += length;
if (removeSuffixFlag)
{
//namePtr[0] = totalLength - 1;
//RemoveSuffix ((FileStringPtr)namePtr);
//totalLength = namePtr[0] + 1;
SetFileStringLength ((FileStringPtr)windowNameString, totalLength-1);
RemoveSuffix ((FileStringPtr)windowNameString);
totalLength = GetFileStringLength (windowNameString) + 1;
savedLength = totalLength - 1;
} // end "if (removeSuffixFlag)"
else // !removeSuffixFlag
{
//sprintf ((char*)&namePtr[totalLength], " ");
sprintf ((char*)&windowNameString[totalLength+1], " ");
totalLength++;
} // end "else !removeSuffixFlag"
if (displaySpecsPtr != NULL && !fileInfoPtr->thematicType)
{
if (displaySpecsPtr->displayType == k1_ChannelThematicDisplayType ||
displaySpecsPtr->displayType == k1_ChannelGrayLevelDisplayType)
{
#undef MONTH_DAY_DESCRIPTION
#ifdef MONTH_DAY_DESCRIPTION
Str15 monthString[12] = {
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec" };
SInt16 day,
leapYearOffset = 1,
monthIndex;
// For GDD image sequence create string for date (month-day)
if (displaySpecsPtr->channelNumber <= 31)
{
monthIndex = 0;
day = displaySpecsPtr->channelNumber;
}
else if (displaySpecsPtr->channelNumber <= 59+leapYearOffset)
{
monthIndex = 1;
day = displaySpecsPtr->channelNumber - 31;
}
else if (displaySpecsPtr->channelNumber <= 90+leapYearOffset)
{
monthIndex = 2;
day = displaySpecsPtr->channelNumber - (59+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 120+leapYearOffset)
{
monthIndex = 3;
day = displaySpecsPtr->channelNumber - (90+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 151+leapYearOffset)
{
monthIndex = 4;
day = displaySpecsPtr->channelNumber - (120+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 181+leapYearOffset)
{
monthIndex = 5;
day = displaySpecsPtr->channelNumber - (151+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 212+leapYearOffset)
{
monthIndex = 6;
day = displaySpecsPtr->channelNumber - (181+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 243+leapYearOffset)
{
monthIndex = 7;
day = displaySpecsPtr->channelNumber - (212+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 273+leapYearOffset)
{
monthIndex = 8;
day = displaySpecsPtr->channelNumber - (243+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 304+leapYearOffset)
{
monthIndex = 9;
day = displaySpecsPtr->channelNumber - (273+leapYearOffset);
}
else if (displaySpecsPtr->channelNumber <= 334+leapYearOffset)
{
monthIndex = 10;
day = displaySpecsPtr->channelNumber - (304+leapYearOffset);
}
else // displaySpecsPtr->channelNumber <= 365)
{
monthIndex = 11;
day = displaySpecsPtr->channelNumber - (334+leapYearOffset);
}
//sprintf (&namePtr[totalLength],
sprintf ((char*)&windowNameString[totalLength+1],
"(%s %hd)",
monthString[monthIndex],
day);
#endif // MONTH_DAY_DESCRIPTION
#ifndef MONTH_DAY_DESCRIPTION
if (displaySpecsPtr->displayType == k1_ChannelThematicDisplayType)
//sprintf ((char*)&namePtr[totalLength],
sprintf ((char*)&windowNameString[totalLength+1],
"(ch_%hdT)",
//"(day %hd)",
displaySpecsPtr->channelNumber);
else
//sprintf ((char*)&namePtr[totalLength],
sprintf ((char*)&windowNameString[totalLength+1],
"(ch_%hd)",
//"(day %hd)",
displaySpecsPtr->channelNumber);
#endif // !MONTH_DAY_DESCRIPTION
} // end "if (displaySpecsPtr->displayType == ..."
else if (displaySpecsPtr->displayType == k3_ChannelDisplayType ||
displaySpecsPtr->displayType == k3_2_ChannelDisplayType)
{
//sprintf ((char*)&namePtr[totalLength],
sprintf ((char*)&windowNameString[totalLength+1],
"(chs_%hd,%hd,%hd)",
displaySpecsPtr->redChannelNumber,
displaySpecsPtr->greenChannelNumber,
displaySpecsPtr->blueChannelNumber);
} // end "else if (displaySpecsPtr->displayType == k3_ChannelDisplayType ..."
/*
else if (displaySpecsPtr->displayType == k2_ChannelDisplayType)
{
// This feature was removed in 11/2019
SInt16 channel1 = 1,
channel2 = 1;
if (displaySpecsPtr->rgbColors == kRGColor)
{
channel1 = displaySpecsPtr->redChannelNumber;
channel2 = displaySpecsPtr->greenChannelNumber;
} // end "if (sDisplaySpecsPtr->rgbColors == kRGColor)"
else if (displaySpecsPtr->rgbColors == kRBColor)
{
channel1 = displaySpecsPtr->redChannelNumber;
channel2 = displaySpecsPtr->blueChannelNumber;
} // end "if (displaySpecsPtr->rgbColors == kRBColor)"
else if (displaySpecsPtr->rgbColors == kGBColor)
{
channel1 = displaySpecsPtr->greenChannelNumber;
channel2 = displaySpecsPtr->blueChannelNumber;
} // end "if (displaySpecsPtr->rgbColors == kGBColor)"
sprintf ((char*)&namePtr[totalLength],
"(chs_%hd,%hd)",
channel1,
channel2);
} // end "else if (displaySpecsPtr->displayType == k2_ChannelDisplayType)"
*/
else if (displaySpecsPtr->displayType == kSideSideChannelDisplayType)
{
//sprintf ((char*)&namePtr[totalLength],
sprintf ((char*)&windowNameString[totalLength+1],
"(multichannels)");
} // end "else if (displaySpecsPtr->displayType == ..."
} // end "if (displaySpecsPtr != NULL)"
// If the name is going to be the default for a tiff image file, then
// verify that the name will not be two long. If so remove the "(...)"
// info.
//totalLength = (SInt16)strlen ((char*)&namePtr[1]);
totalLength = (SInt16)strlen ((char*)&windowNameString[2]);
totalLength = MIN (totalLength, gFileNameLengthLimit);
// Copy string to output
if (removeSuffixFlag)
{
// The output string needs to be a File String with first 2 characters
// reserved for the name length
if (totalLength > gFileNameLengthLimit-4)
totalLength = savedLength;
memcpy (&namePtr[2],
(char*)&windowNameString[2],
totalLength);
SetFileStringLength ((FileStringPtr)namePtr, totalLength);
} // end "if (removeSuffixFlag)"
else // !removeSuffixFlag
{
memcpy (&namePtr[1],
(char*)&windowNameString[2],
totalLength);
// Include the character count
namePtr[0] = (char)totalLength;
namePtr[totalLength+1] = 0;
} // end "else // !removeSuffixFlag"
} // end "GetImageWindowName"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void GetImageWindowTitle
//
// Software purpose: The purpose of this routine is to get the
// title for the input image window.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/15/2013
// Revised By: Larry L. Biehl Date: 08/13/2013
void GetImageWindowTitle (
Handle windowInfoHandle,
UCharPtr titleStringPtr)
{
WindowPtr windowPtr;
titleStringPtr[0] = 0;
windowPtr = GetWindowPtr (windowInfoHandle);
GetWindowTitle (windowPtr, titleStringPtr);
} // end "GetImageWindowTitle"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: UInt16 GetNumberLeadingDecimalZeros
//
// Software purpose: The purpose of this routine is to get the number of decimal
// digits such that the user can see unique values when printed.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 12/16/2005
// Revised By: Larry L. Biehl Date: 12/30/2005
UInt16 GetNumberLeadingDecimalZeros (
double dataValue)
{
UInt16 numberDigitsAfter;
numberDigitsAfter = 0;
dataValue = fabs (dataValue);
if (dataValue > 0)
{
while (dataValue < 1)
{
numberDigitsAfter++;
dataValue *= 10;
} // end "while (dataValue < 1)"
} // end "if (dataValue > 0)"
return (numberDigitsAfter);
} // end "GetNumberLeadingDecimalZeros"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: UInt16 GetNumberWholeDigits
//
// Software purpose: The purpose of this routine is to get the number of decimal
// digits such that the user can see unique values when printed.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/09/2006
// Revised By: Larry L. Biehl Date: 09/26/2017
UInt16 GetNumberWholeDigits (
double dataValue)
{
SInt16 exponent;
UInt16 numberWholeDigits;
numberWholeDigits = 1;
if (dataValue != 0)
{
exponent = (SInt16)log10 (fabs (dataValue));
numberWholeDigits = MAX (0, exponent) + 1;
} // end "if (dataValue != 0)"
return (numberWholeDigits);
} // end "GetNumberWholeDigits"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void GetOutputWindowTitle
//
// Software purpose: The purpose of this routine is to get the title for the
// output window.
// This routine is currently not being used.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/29/1995
// Revised By: Larry L. Biehl Date: 05/19/1997
void GetOutputWindowTitle (
UCharPtr titleStringPtr)
{
#if defined multispec_mac
if (gOutputWindow != NULL)
GetWTitle (gOutputWindow, titleStringPtr);
#endif // defined multispec_mac
#if defined multispec_win
if (gOutputViewCPtr != NULL)
{
CMTextDoc* documentCPtr = gOutputViewCPtr->GetDocument ();
CString titleString = documentCPtr->GetTitle ();
UInt16 titleLength = titleString.GetLength ();
LPTSTR titleBufferPtr = titleString.GetBuffer (titleLength);
// Move the window title making sure that there are no
// spaces in the name.
UInt16 inIndex,
outIndex = 1;
for (inIndex=0; inIndex<titleLength; inIndex++)
{
if (titleBufferPtr[inIndex] != ' ')
{
titleStringPtr[outIndex] = (char)titleBufferPtr[inIndex];
outIndex++;
} // end "if (titleBufferPtr[inIndex] != ' ')"
} // end "for (inIndex=0; inIndex<titleLength; inIndex++)"
titleString.ReleaseBuffer ();
// Make the string a pascal string and terminate it with as
// if it were a c string.
titleStringPtr[0] = (UInt8)(outIndex - 1);
titleStringPtr[outIndex] = 0;
} // end "if (gOutputViewCPtr != NULL)"
#endif // defined multispec_win
#if defined multispec_wx
// Implement if needed.
#endif
} // end "GetOutputWindowTitle"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt32 GetSpecifiedString
//
// Software purpose: The purpose of this routine is to get a handle, pointer
// and length of the specified string from the Resource file.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/17/1993
// Revised By: Larry L. Biehl Date: 12/12/2011
SInt32 GetSpecifiedString (
SInt16 stringID,
StringHandle* stringHandlePtr,
char** stringPtrPtr)
{
SInt32 stringLength;
stringLength = 0;
*stringPtrPtr = NULL;
#if defined multispec_mac
*stringHandlePtr = GetString (stringID);
if (*stringHandlePtr)
{
HLock ((Handle)*stringHandlePtr);
*stringPtrPtr = (char*)**stringHandlePtr;
stringLength = GetHandleSize ((Handle)*stringHandlePtr);
} // end "if (*stringHandlePtr)"
#endif // defined multispec_mac
#if defined multispec_win || defined multispec_wx
unsigned char* stringPtr = NULL;
unsigned char string128[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x3e, 0x3c, 0x28, 0x3a, 0x5e,
0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x5c,
0x3d, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x5f, 0x2c, 0x25, 0x5f, 0x3e, 0x3f,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3a, 0x23, 0x40, 0x25, 0x3d, 0x22,
0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
0x71, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x5b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x5d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
0x51, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x5c, 0x00, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x5e, 0x00, 0x00, 0x00, 0x00, 0x00};
/*
unsigned char string129[70] = {
0x22, 0x00, 0x38, 0x00, 0x40, 0x00, 0x48, 0x00,
0x52, 0x00, 0x59, 0x00, 0x61, 0x00, 0x70, 0x00,
0x89, 0x00, 0x91, 0x00, 0x97, 0x00, 0x9C, 0x00,
0xA5, 0x00, 0xB1, 0x00, 0xB8, 0x00, 0xBC, 0x00,
0xC1, 0x00, 0xC6, 0x00, 0xCA, 0x00, 0xCE, 0x00,
0xD2, 0x00, 0xD6, 0x00, 0xE4, 0x00, 0xEB, 0x00,
0xF4, 0x00, 0xF9, 0x00, 0x01, 0x01, 0x09, 0x01,
0x38, 0x00, 0x18, 0x01, 0x1F, 0x01, 0x25, 0x01,
0x2E, 0x01, 0x32, 0x01, 0x37, 0x01};
unsigned char string132[65] = {
0x07, 0x00, 0x10, 0x00, 0x18, 0x00, 0x1C, 0x00,
0x20, 0x00, 0x24, 0x00, 0x2B, 0x00, 0x39, 0x00,
'U', 'n', 'k', 'n', 'o', 'w', 'n', 0x00,
'B', 'I', 'L', 0x00, 'B', 'S', 'Q', 0x00,
'B', 'I', 'S', 0x00, 'B', 'N', 'o', 'n',
'S', 'Q', 0x00, 'B', 'N', 'o', 'n', 'S',
'Q', 'B', 'l', 'o', 'c', 'k', 'e', 'd',
0x00, 'B', 'I', 'B', 'l', 'o', 'c', 'k',
0x00 };
unsigned char string133[320] = {
0x22, 0x00, 0x38, 0x00, 0x40, 0x00, 0x48, 0x00,
0x52, 0x00, 0x59, 0x00, 0x61, 0x00, 0x70, 0x00,
0x89, 0x00, 0x91, 0x00, 0x97, 0x00, 0x9C, 0x00,
0xA5, 0x00, 0xB1, 0x00, 0xB8, 0x00, 0xBC, 0x00,
0xC1, 0x00, 0xC6, 0x00, 0xCA, 0x00, 0xCE, 0x00,
0xD2, 0x00, 0xD6, 0x00, 0xE4, 0x00, 0xEB, 0x00,
0xF4, 0x00, 0xF9, 0x00, 0x01, 0x01, 0x09, 0x01,
'U', 'n', 'k', 'n', 'o', 'w', 'n', 0x00, // 64
'E', 'r', 'd', 'a', 's', '7', '3', 0x00,
'M', 'u', 'l', 't', 'i', 'S', 'p', 'e',
'c', 0x00, 'A', 'V', 'I', 'R', 'I', 'S',
0x00, 'U', 'n', 'k', 'n', 'o', 'w', 'n',
0x00, 'S', 'u', 'n', ' ', 'S', 'c', 'r',
'e', 'e', 'n', 'D', 'u', 'm', 'p', 0x00,
'M', 'u', 'l', 't', 'i', 'S', 'p', 'e',
'c', ' ', 'C', 'l', 'a', 's', 's', 'i', // 128
'f', 'i', 'c', 'a', 't', 'i', 'o', 'n',
0x00, 'E', 'r', 'd', 'a', 's', '7', '4',
0x00, 'V', 'I', 'C', 'A', 'R', 0x00, 'G',
'A', 'I', 'A', 0x00, 'M', 'a', 'c', 'S',
'A', 'D', 'I', 'E' , 0x00, 'L', 'A', 'R',
'S', 'Y', 'S', ' ', 'M', 'I', 'S', 'T',
0x00, 'M', 'A', 'T', 'L', 'A', 'B', 0x00,
'T', 'G', 'A', 0x00, 'G', 'A', 'I', 'A', // 192
0x00, 'T', 'I', 'F', 'F', 0x00, 'L', 'A',
'S', 0x00, 'L', 'A', 'S', 0x00, 'H', 'D',
'F', 0x00, 'P', 'D', 'S', 0x00, 'E', 'R',
'D', 'A', 'S', ' ', 'I', 'm', 'a', 'g',
'i', 'n', 'e', 0x00, 'L', 'G', 'S', 'O',
'W', 'G', 0x00, 'F', 'A', 'S', 'T', '-',
'L', '7', 'A', 0x00, 'E', 'N', 'V', 'I',
0x00, 'A', 'r', 'c', 'V', 'i', 'e', 'w', // 256
0x00, 'G', 'e', 'o', 'T', 'I', 'F', 'F', // 264
0x00, 'W', 'i', 'n', 'd', 'o', 'w', 's', // 272
' ', 'B', 'i', 't', 'M', 'a', 'p', 0x00, // 280
'n', 'e', 't', 'C', 'D', 'F', 0x00, 'N', // 288
'L', 'A', 'P', 'S', 0x00, 'J', 'P', 'E', // 296
'G', '2', '0', '0', '0', 0x00, 'P', 'N', // 304
'G', 0x00, 'J', 'P', 'E', 'G', 0x00, 'H', // 312
'D', 'F', '5', 0x00, 0x00, 0x00, 0x00, 0x00 }; // 320
*/
unsigned char string137[1063] = {
' ', 'G', 'R', 'O', 'U', 'P', ' ', 'D',
'E', 'S', 'C', 'R', 'I', 'P', 'T', 'I',
'O', 'N', 'S', ' ', '1', ' ', '1', ' ',
'9', ' ', 'G', 'r', 'o', 'u', 'p', 'i',
'n', 'g', '1', ' ', ' ', ' ', '1', '6',
' ', '1', ' ', ' ', ' ', ' ', '1', ' ',
' ', ' ', ' ', '2', ' ', ' ', ' ', ' ',
'2', ' ', ' ', ' ', ' ', '2', ' ', ' ',
' ', ' ', '2', ' ', ' ', ' ', ' ', '2',
' ', ' ', ' ', ' ', '2', ' ', ' ', ' ',
' ', '2', ' ', ' ', ' ', ' ', '2', ' ',
' ', ' ', ' ', '2', ' ', ' ', ' ', ' ',
'2', ' ', ' ', ' ', ' ', '2', ' ', ' ',
' ', ' ', '2', ' ', ' ', ' ', ' ', '2',
' ', ' ', ' ', ' ', '2', ' ', ' ', ' ',
' ', '2', ' ', ' ', ' ', ' ', '2', ' ',
' ', ' ', ' ', '2', ' ', ' ', ' ', ' ',
'2', ' ', ' ', ' ', ' ', '2', ' ', ' ',
' ', ' ', '2', ' ', ' ', ' ', ' ', '2',
' ', ' ', ' ', ' ', '2', ' ', ' ', ' ',
' ', '3', ' ', ' ', ' ', ' ', '4', ' ',
' ', ' ', ' ', '5', ' ', ' ', ' ', ' ',
'6', ' ', ' ', ' ', ' ', '7', ' ', ' ',
' ', ' ', '7', ' ', ' ', ' ', ' ', '7',
' ', ' ', ' ', ' ', '7', ' ', ' ', ' ',
' ', '7', ' ', ' ', ' ', ' ', '8', ' ',
' ', ' ', ' ', '8', ' ', ' ', ' ', ' ',
'8', ' ', ' ', ' ', ' ', '8', ' ', ' ',
' ', ' ', '8', ' ', ' ', ' ', ' ', '8',
' ', ' ', ' ', ' ', '8', ' ', ' ', ' ',
' ', '8', ' ', ' ', ' ', ' ', '8', ' ',
' ', ' ', ' ', '8', ' ', ' ', ' ', ' ',
'9', ' ', ' ', ' ', ' ', '9', ' ', ' ',
' ', ' ', '9', ' ', ' ', ' ', ' ', '9',
' ', ' ', ' ', ' ', '9', ' ', ' ', ' ',
' ', '9', ' ', ' ', ' ', ' ', '9', ' ',
' ', ' ', ' ', '9', ' ', ' ', ' ', ' ',
'9', ' ', ' ', ' ', ' ', '9', ' ', ' ',
' ', '1', '0', ' ', ' ', ' ', '1', '0',
' ', ' ', ' ', '1', '0', ' ', ' ', ' ',
'1', '0', ' ', ' ', ' ', '1', '0', ' ',
' ', ' ', '1', '0', ' ', ' ', ' ', '1',
'0', ' ', ' ', ' ', '1', '0', ' ', ' ',
' ', '1', '0', ' ', ' ', ' ', '1', '0',
' ', ' ', ' ', '1', '1', ' ', ' ', ' ',
'1', '1', ' ', ' ', ' ', '1', '1', ' ',
' ', ' ', '1', '1', ' ', ' ', ' ', '1',
'1', ' ', ' ', ' ', '1', '1', ' ', ' ',
' ', '1', '1', ' ', ' ', ' ', '1', '1',
' ', ' ', ' ', '1', '1', ' ', ' ', ' ',
'1', '1', ' ', ' ', ' ', '1', '2', ' ',
' ', ' ', '1', '2', ' ', ' ', ' ', '1',
'2', ' ', ' ', ' ', '1', '2', ' ', ' ',
' ', '1', '2', ' ', ' ', ' ', '1', '2',
' ', ' ', ' ', '1', '2', ' ', ' ', ' ',
'1', '2', ' ', ' ', ' ', '1', '2', ' ',
' ', ' ', '1', '2', ' ', ' ', ' ', '1',
'3', ' ', ' ', ' ', '1', '3', ' ', ' ',
' ', '1', '3', ' ', ' ', ' ', '1', '3',
' ', ' ', ' ', '1', '3', ' ', ' ', ' ',
'1', '3', ' ', ' ', ' ', '1', '3', ' ',
' ', ' ', '1', '3', ' ', ' ', ' ', '1',
'3', ' ', ' ', ' ', '1', '3', ' ', ' ',
' ', '1', '4', ' ', ' ', ' ', '1', '4',
' ', ' ', ' ', '1', '4', ' ', ' ', ' ',
'1', '4', ' ', ' ', ' ', '1', '4', ' ',
' ', ' ', '1', '4', ' ', ' ', ' ', '1',
'4', ' ', ' ', ' ', '1', '4', ' ', ' ',
' ', '1', '4', ' ', ' ', ' ', '1', '4',
' ', ' ', ' ', '1', '5', ' ', ' ', ' ',
'1', '5', ' ', ' ', ' ', '1', '5', ' ',
' ', ' ', '1', '5', ' ', ' ', ' ', '1',
'5', ' ', ' ', ' ', '1', '5', ' ', ' ',
' ', '1', '5', ' ', ' ', ' ', '1', '5',
' ', ' ', ' ', '1', '5', ' ', ' ', ' ',
'1', '5', ' ', ' ', ' ', '1', '6', ' ',
' ', ' ', '1', '6', ' ', ' ', ' ', '1',
'6', ' ', ' ', ' ', '1', '6', ' ', ' ',
' ', '1', '6', ' ', ' ', ' ', '1', '6',
' ', ' ', ' ', '1', '6', ' ', ' ', ' ',
'1', '6', ' ', ' ', ' ', '1', '6', ' ',
' ', ' ', '1', '6', ' ', ' ', ' ', '1',
'0', ' ', 'b', 'a', 'c', 'k', 'g', 'r',
'o', 'u', 'n', 'd', ' ', 'f', 'f', '0',
'0', ' ', 'f', 'f', '0', '0', ' ', 'f',
'f', '0', '0', ' ', ' ', ' ', ' ', '3',
' ', '0', '-', '1', ' ', ' ', ' ', ' ',
'0', ' ', ' ', ' ', ' ', '0', ' ', 'f',
'e', '0', '0', ' ', ' ', ' ', ' ', '3',
' ', '1', '-', '2', ' ', ' ', ' ', ' ',
'0', ' ', 'f', 'a', 'e', '0', ' ', 'a',
'1', '4', '7', ' ', ' ', ' ', ' ', '3',
' ', '2', '-', '3', ' ', ' ', ' ', ' ',
'0', ' ', 'f', 'a', 'e', '0', ' ', '8',
'f', '5', 'b', ' ', ' ', ' ', ' ', '3',
' ', '3', '-', '4', ' ', ' ', ' ', ' ',
'0', ' ', 'f', 'a', 'e', '0', ' ', '7',
'f', 'f', 'f', ' ', ' ', ' ', ' ', '3',
' ', '4', '-', '5', ' ', ' ', ' ', ' ',
'0', ' ', 'f', 'a', 'e', '0', ' ', '7',
'0', 'a', '3', ' ', ' ', ' ', ' ', '4',
' ', '5', '-', '1', '0', ' ', ' ', ' ',
' ', '0', ' ', 'f', 'a', 'e', '0', ' ',
'4', 'f', '5', 'b', ' ', ' ', ' ', ' ',
'5', ' ', '1', '0', '-', '2', '0', ' ',
' ', ' ', ' ', '0', ' ', 'f', 'a', 'e',
'0', ' ', ' ', 'f', '5', 'c', ' ', ' ',
' ', ' ', '5', ' ', '2', '0', '-', '3',
'0', ' ', '3', 'f', 'f', 'f', ' ', 'f',
'a', 'e', '0', ' ', ' ', ' ', ' ', '0',
' ', ' ', ' ', ' ', '5', ' ', '3', '0',
'-', '4', '0', ' ', '8', 'f', '5', 'b',
' ', 'f', 'a', 'e', '0', ' ', ' ', ' ',
' ', '0', ' ', ' ', ' ', ' ', '5', ' ',
'4', '0', '-', '5', '0', ' ', 'e', '1',
'4', '6', ' ', 'e', 'a', 'e', '0', ' ',
' ', ' ', ' ', '0', ' ', ' ', ' ', ' ',
'5', ' ', '5', '0', '-', '6', '0', ' ',
'f', 'd', '6', 'f', ' ', 'c', '5', '1',
'd', ' ', ' ', ' ', ' ', '0', ' ', ' ',
' ', ' ', '5', ' ', '6', '0', '-', '7',
'0', ' ', 'f', 'd', '6', 'f', ' ', '8',
'c', 'c', 'c', ' ', ' ', ' ', ' ', '0',
' ', ' ', ' ', ' ', '5', ' ', '7', '0',
'-', '8', '0', ' ', 'f', 'd', '6', 'f',
' ', '6', '3', 'd', '6', ' ', ' ', ' ',
' ', '0', ' ', ' ', ' ', ' ', '5', ' ',
'8', '0', '-', '9', '0', ' ', 'f', 'e',
'6', 'f', ' ', '3', 'd', '7', '0', ' ',
' ', ' ', ' ', '0', ' ', ' ', ' ', ' ',
'6', ' ', '9', '0', '-', '1', '0', '0',
' ', 'f', 'd', '6', 'f', ' ', ' ', '5',
'1', 'e', ' ', ' ', ' ', ' ', '0', };
stringLength = 256;
/*
if (stringID == 129)
{
stringLength = sizeof (string129);
stringPtr = &string129[0];
} // end "if (stringID == 129)"
if (stringID == 132)
{
stringLength = sizeof (string132);
stringPtr = &string132[0];
} // end "if (stringID == 132)"
else if (stringID == 133)
{
stringLength = sizeof (string133);
stringPtr = &string133[0];
} // end "else if (stringID == 133)"
*/
if (stringID == 128)
{
stringLength = sizeof (string128);
stringPtr = &string128[0];
} // end "else if (stringID == 128)"
else if (stringID == 137)
{
stringLength = sizeof (string137);
stringPtr = &string137[0];
} // end "else if (stringID == 137)"
*stringHandlePtr = (StringHandle)MNewHandle (stringLength);
*stringPtrPtr = (char*)GetHandlePointer ((Handle)*stringHandlePtr, kLock);
if (*stringPtrPtr != NULL)
{
if (stringPtr != NULL)
{
BlockMoveData (stringPtr, *stringPtrPtr, stringLength);
} // end "if (stringID == 137)"
else // stringPtr == NULL
{
MGetString ((UCharPtr)*stringPtrPtr, NULL, stringID);
stringLength = (*stringPtrPtr)[0];
} // end "else stringPtr == NULL"
} // end "if (*stringPtrPtr != NULL)"
#endif // defined multispec_win || defined multispec_wx
return (stringLength);
} // end "GetSpecifiedString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean GetSpecifiedStringNumber
//
// Software purpose: This routine get the specified string number. A
// NULL character is added to the end of the string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string obtained successfully.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/26/1994
// Revised By: Larry L. Biehl Date: 02/27/2017
Boolean GetSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
UCharPtr textStringPtr,
Boolean continueFlag)
{
if (continueFlag)
{
MGetString ((UCharPtr)textStringPtr, strListID, index);
continueFlag = (textStringPtr[0] != 0);
} // end "if (continueFlag)"
return (continueFlag);
} // end "GetSpecifiedStringNumber"
#if defined multispec_win
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean GetSpecifiedStringNumber
//
// Software purpose: This routine get the specified string number. A
// NULL character is added to the end of the string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string obtained successfully.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/26/2016
// Revised By: Larry L. Biehl Date: 08/28/2017
Boolean GetSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
TBYTE* textStringPtr,
Boolean continueFlag,
UInt16 maxStringLength)
{
if (continueFlag)
{
MGetString (textStringPtr, strListID, index, maxStringLength);
continueFlag = (textStringPtr[0] != 0);
} // end "if (continueFlag)"
return (continueFlag);
} // end "GetSpecifiedStringNumber"
#endif // defined multispec_win
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 GetStringToComma
//
// Software purpose: This routine copies the characters from the input string to the
// output string until a comma is found.
//
// Parameters in:
//
// Parameters out: None
//
// Value Returned:
//
// Called By: ReadENVIHeaderMapInfo in SOpenImage.cpp
//
// Coded By: Larry L. Biehl Date: 07/14/2006
// Revised By: Larry L. Biehl Date: 08/25/2006
char* GetStringToComma (
char* inputStringPtr,
char* inputStringEndPtr,
char* stringPtr,
SInt16 maxStringLength)
{
char* outputStringPtr;
SInt16 numberCharacters;
numberCharacters = 0;
if (inputStringPtr != NULL && inputStringEndPtr > inputStringPtr)
{
// Skip any leading blanks.
while (*inputStringPtr == ' ')
inputStringPtr++;
// Now find the ',' if requested. For this option one will want to read
// all characters to the ','
outputStringPtr = (char*)strstr (inputStringPtr, ",");
if (outputStringPtr == NULL || outputStringPtr > inputStringEndPtr)
outputStringPtr = inputStringEndPtr;
if (outputStringPtr != NULL)
numberCharacters = (SInt16)(outputStringPtr - inputStringPtr);
if (numberCharacters >= 0)
{
// Set string limit to allow for pascal and c string identifiers.
numberCharacters = MIN (numberCharacters, maxStringLength-2);
// Get the string that follows the identifer that is numberCharacters
// long.
BlockMoveData (inputStringPtr, &stringPtr[1], numberCharacters);
// Skip the comma
outputStringPtr++;
} // end "if (numberCharacters >= 0"
} // end "if (inputStringPtr != NULL && ..."
else // inputStringPtr == NULL || ...
outputStringPtr = NULL;
if (maxStringLength >= 2)
{
// Make pascal and c string.
stringPtr[0] = (char)numberCharacters;
stringPtr[numberCharacters+1] = 0;
} // end "if (maxStringLength >= 2)"
return (outputStringPtr);
} // end "GetStringToComma"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: int GetWideFileStringLength
//
// Software purpose: The purpose of this routine is to return the length of the
// input wide file string.
//
// Parameters in: Wide file string.
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/10/2020
// Revised By: Larry L. Biehl Date: 04/10/2020
int GetWideFileStringLength (
WideFileStringPtr wideFileStringPtr)
{
UInt16* wideFileStringLengthPtr;
wideFileStringLengthPtr = (UInt16*)wideFileStringPtr;
return (wideFileStringLengthPtr[0]);
} // end "GetWideFileStringLength"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void GetWindowTitle
//
// Software purpose: The purpose of this routine is to get the title for the input
// window.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/13/2013
// Revised By: Larry L. Biehl Date: 06/11/2015
void GetWindowTitle (
WindowPtr windowPtr,
UCharPtr titleStringPtr)
{
titleStringPtr[0] = 0;
titleStringPtr[1] = 0;
if (windowPtr != NULL)
{
#if defined multispec_mac
GetWTitle (windowPtr, titleStringPtr);
titleStringPtr[titleStringPtr[0]+1] = 0;
#endif // defined multispec_mac
#if defined multispec_win
CMImageDoc* documentCPtr = windowPtr->GetDocument ();
CString titleString = documentCPtr->GetTitle ();
UInt16 titleLength = titleString.GetLength ();
LPTSTR titleBufferPtr = titleString.GetBuffer (titleLength);
memcpy (&titleStringPtr[1],
titleBufferPtr,
titleLength);
titleString.ReleaseBuffer ();
titleStringPtr[0] = (UInt8)titleLength;
titleStringPtr[titleLength+1] = 0;
#endif // defined multispec_win
#if defined multispec_wx
wxString titleString;
titleString = windowPtr->m_frame->GetTitle ();
UInt16 titleLength = MIN ((UInt16)titleString.Length (), 254);
strncpy ((char*)&titleStringPtr[1], (const char*)titleString.mb_str (wxConvUTF8), 254);
titleStringPtr[0] = (UInt8)titleLength;
titleStringPtr[titleLength+1] = 0;
#endif // defined multispec_wx
} // end "if (windowPtr != NULL)"
} // end "GetWindowTitle"
#if defined multispec_wx
void GetGraphWindowTitle (
WindowPtr windowPtr,
UCharPtr titleStringPtr)
{
titleStringPtr[0] = 0;
titleStringPtr[1] = 0;
if (windowPtr != NULL)
{
wxString titleString = ((CMGraphView*)windowPtr)->m_frame->GetTitle ();
UInt16 titleLength = MIN ((UInt16)titleString.Length (), 254);
strncpy ((char*)&titleStringPtr[1],
(const char*)titleString.mb_str (wxConvUTF8),
254);
titleStringPtr[0] = (UInt8)titleLength;
titleStringPtr[titleLength+1] = 0;
}
} // end "GetGraphWindowTitle"
#endif // defined multispec_wx
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void InitializeDateVersionStrings
//
// Software purpose: The purpose of this routine is to initialize the global date
// version string and the application identifier string. It is
// called once just after MultiSpec is started.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/09/2007
// Revised By: Larry L. Biehl Date: 08/30/2020
void InitializeDateVersionStrings ()
{
// Date version string
sprintf (gDateVersionString, "2020.08.30");
// Application identifier string
#if defined multispec_mac
#ifndef __XCODE__
#ifdef TARGET_CPU_PPC
sprintf (
gApplicationIdentifierString, "MultiSpecPPC_%s", gDateVersionString);
#endif // TARGET_CPU_PPC
sprintf (
gApplicationIdentifierString, "MultiSpecCarb_%s", gDateVersionString);
#endif // !__XCODE__
#ifdef __XCODE__
if (gSystemArchitectureCode == kIntel)
sprintf (
gApplicationIdentifierString, "MultiSpecIntel_%s", gDateVersionString);
if (gSystemArchitectureCode == kPPC)
sprintf (gApplicationIdentifierString,
"MultiSpecUniversalPPC_%s",
gDateVersionString);
#endif // __XCODE__
#endif // defined multispec_mac
#if defined multispec_win
#if defined _WIN64
sprintf (
gApplicationIdentifierString, "MultiSpecWin64_%s", gDateVersionString);
#else
sprintf (
gApplicationIdentifierString, "MultiSpecWin32_%s", gDateVersionString);
#endif
#endif // defined multispec_win
#if defined multispec_wx
#ifdef NetBeansProject
sprintf ((char*)gApplicationIdentifierString,
"MultiSpecLinux_%s",
gDateVersionString);
#else
#if defined multispec_wxmac
sprintf ((char*)gApplicationIdentifierString,
"MultiSpec64_%s",
gDateVersionString);
#else
sprintf ((char*)gApplicationIdentifierString,
"MultiSpec_on_MyGeohub_%s",
gDateVersionString);
#endif
#endif
#endif
} // end "InitializeDateVersionStrings"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 InsertCommasInNumberString
//
// Software purpose: The purpose of this routine is to insert commas into the input
// number string. The insertion is done within the input string
// so make sure that the input string is long enough.
//
// Parameters in: decimalPlaces: if <0, then integer value is assumed.
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/09/2000
// Revised By: Larry L. Biehl Date: 07/02/2002
SInt16 InsertCommasInNumberString (
char* inputStringPtr,
UInt32 numberInputCharacters,
SInt16 decimalPlaces,
SInt16 numberOutputCharacters)
{
SInt32 decimalLocation,
firstBlankIndex,
index,
newIndex;
UInt32 numberBlanks,
numberCommas,
numberPlaces,
numberWholeValueDigits;
SInt16 justificationCode;
// Initialize local variables.
justificationCode = 1;
if (numberOutputCharacters < 0)
justificationCode = -1;
numberOutputCharacters = abs (numberOutputCharacters);
// Get the number of digits less any decimal places and the period.
if (decimalPlaces < 0)
{
decimalPlaces = 0;
decimalLocation = numberInputCharacters;
} // end "if (decimalPlaces < 0)"
else // decimalPlaces >= 0
{
decimalPlaces++;
decimalLocation = numberInputCharacters - decimalPlaces;
decimalLocation = MAX (0, decimalLocation);
} // end "else decimalPlaces >= 0"
numberWholeValueDigits = decimalLocation;
// Do not include a blank as a whole number digit
index = 0;
while (inputStringPtr[index] == ' ' && index < (SInt32)numberWholeValueDigits)
{
numberWholeValueDigits--;
index++;
} // end "while (inputStringPtr[index] == ' ')"
numberBlanks = index;
// Do not include a leading '-' as a whole number digit
if (inputStringPtr[index] == '-')
numberWholeValueDigits--;
if (numberWholeValueDigits > 0)
numberCommas = (numberWholeValueDigits - 1)/3;
else // numberWholeValueDigits == 0
numberCommas = 0;
if (numberCommas > 0 || numberInputCharacters < (UInt32)numberOutputCharacters)
{
// Make sure that the number of output characters will handle
// the number of commas being added.
numberOutputCharacters = (SInt16)MAX ((UInt32)numberOutputCharacters,
numberInputCharacters + numberCommas);
// Limit the number of output characters to 60 to be on the
// safe side.
numberOutputCharacters = MIN (numberOutputCharacters, 60);
index = numberInputCharacters - 1;
newIndex = numberOutputCharacters - 1;
if (justificationCode < 0)
{
// Left justify the number.
// Add spaces to the end of the number if needed.
firstBlankIndex = numberInputCharacters + numberCommas;
while (newIndex >= firstBlankIndex)
{
inputStringPtr[newIndex] = ' ';
newIndex--;
} // end "while (while (newIndex >= firstBlankIndex)"
} // end "if (justificationCode < 0)"
// Make sure that the decimal separator is the correct character.
if (decimalPlaces > 0)
inputStringPtr[decimalLocation] = gDecimalSeparator;
// Move decimal digits.
while (index >= decimalLocation)
{
inputStringPtr[newIndex] = inputStringPtr[index];
index--;
newIndex--;
} // end "while (index >= decimalLocation)"
numberPlaces = 0;
while (newIndex >= 0)
{
if (numberPlaces == 3 && index >= 0 &&
inputStringPtr[index] != ' ' && inputStringPtr[index] != '-')
{
inputStringPtr[newIndex] = gThousandsSeparator;
newIndex--;
numberPlaces = 0;
} // end "if (numberPlaces == 3 && ..."
if (index == newIndex)
break;
if (index >= 0)
{
inputStringPtr[newIndex] = inputStringPtr[index];
index--;
if (index < decimalLocation)
numberPlaces++;
if (index == 0 && inputStringPtr[index] == '-')
numberPlaces = 0;
} // end "if (index >= 0)"
else // index < 0
inputStringPtr[newIndex] = ' ';
newIndex--;
} // end "while (newIndex >= 0)"
inputStringPtr[numberOutputCharacters] = 0;
} // end "if (numberCommas > 0)"
return (numberOutputCharacters);
} // end "InsertCommasInNumberString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListChannelsUsed
//
// Software purpose: The purpose of this routine is to list the channels
// used for the processor. The output will be listed
// in the output text window and/or the outputdisk file
// as specified.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 10/04/1989
// Revised By: Larry L. Biehl Date: 08/25/2020
Boolean ListChannelsUsed (
FileInfoPtr fileInfoPtr,
SInt16* featuresPtr,
SInt16* channelsPtr,
SInt16 numberChannels,
CMFileStream* outputFilePtr,
SInt16* outputCodePtr,
Boolean useTransformFlag)
{
// Declare local variables and structures
ChannelDescriptionPtr channelDescriptionPtr;
FileInfoPtr localFileInfoPtr;
LayerInfoPtr localImageLayerInfoPtr;
SInt16* lChannelsPtr;
SInt32 stringLength;
UInt32 channelNum,
index,
layerChanIndex,
nextChannelNum,
nextIndex;
SInt16 channelNumberLength,
fileChanNum,
fileInfoIndex;
Boolean continueFlag,
shortListFlag;
// Check input variables.
if (fileInfoPtr == NULL && gImageLayerInfoPtr != NULL)
return (FALSE);
if (fileInfoPtr != NULL && gImageLayerInfoPtr == NULL)
return (FALSE);
// Initialize local variables.
channelDescriptionPtr = NULL;
localFileInfoPtr = NULL;
continueFlag = TRUE;
gTextString2[24] = 0;
shortListFlag = TRUE;
lChannelsPtr = channelsPtr;
if (useTransformFlag)
lChannelsPtr = featuresPtr;
// List the channels or features used.
if (useTransformFlag)
{
if (gProcessorCode == kRefChangeFileFormatProcessor)
stringLength = sprintf ((char*)gTextString,
" Features created: %s",
gEndOfLine);
else // gProcessorCode != kRefChangeFileFormatProcessor
stringLength = sprintf ((char*)gTextString,
" Features used: %s",
gEndOfLine);
} // end "if (useTransformFlag)"
else // !useTransformFlag
stringLength = sprintf ((char*)gTextString,
" Channels used: %s",
gEndOfLine);
// If all channels are to be used and there are no channel
// descriptions then just list the channels.
// For now we will only do this check for those cases where there is
// only one disk file for the image "file" being used.
if (fileInfoPtr && !useTransformFlag && fileInfoPtr->channelDescriptionH)
shortListFlag = FALSE;
if (gImageWindowInfoPtr &&
gImageWindowInfoPtr->numberImageFiles > 1 &&
gProcessorCode != kRefChangeFileFormatProcessor)
shortListFlag = FALSE;
if (fileInfoPtr != gImageFileInfoPtr &&
gImageWindowInfoPtr->numberImageFiles > 1 &&
gProcessorCode != kListDescriptionProcessor)
// This indicates that the gImageLayerInfoPtr does not go with
// fileInfoPtr. This is from a new image being created by a reformat
// processor. More work needs to be done to be able to determine
// what the channel descriptions are if any when linked files are
// involved.
shortListFlag = TRUE;
// If a short list is to be used, verify that the list is
// continuous.
if (shortListFlag)
{
Boolean dashFlag = FALSE;
Boolean listFlag = FALSE;
UInt32 startChannel;
startChannel = 0;
if (lChannelsPtr != NULL)
startChannel = lChannelsPtr[0];
stringLength -= gNumberOfEndOfLineCharacters;
channelNum = startChannel;
for (index=0; index<(UInt16)numberChannels; index++)
{
channelNum++;
nextIndex = MIN (index + 1, (UInt32)(numberChannels - 1));
nextChannelNum = index + 1;
if (lChannelsPtr != NULL)
nextChannelNum = lChannelsPtr[nextIndex];
if ((index == (UInt16)(numberChannels - 1)) ||
channelNum != (UInt16)nextChannelNum)
{
listFlag = TRUE;
} // end "if (index == (UInt16)(numberChannels - 1) || ..."
else // channelNum == nextChannel && ...
{
if (!dashFlag)
{
startChannel = channelNum - 1;
dashFlag = TRUE;
} // end "if (!dashFlag && ...)"
} // end "else lChannelsPtr[index] == channelNum && ..."
if (listFlag)
{
if (dashFlag)
{
// List the continuous channel list first.
channelNum = nextChannelNum;
if (lChannelsPtr != NULL)
channelNum = lChannelsPtr[index] + 1;
stringLength += sprintf ((char*)&gTextString[stringLength],
"%u-%u,",
(unsigned int)(startChannel+1),
(unsigned int)channelNum);
dashFlag = FALSE;
} // end "if (dashFlag)"
else // !dashFlag
{
// List channel number separated by comma
stringLength += sprintf ((char*)&gTextString[stringLength],
"%u,",
startChannel+1);
} // end "else !dashFlag"
listFlag = FALSE;
if (index < (UInt16)(numberChannels - 1))
{
startChannel = (UInt16)nextChannelNum;
channelNum = startChannel;
} // end "if ((index < (UInt16)numberChannels - 1))"
if (stringLength >= 256-23)
break;
} // end "if (listFlag)"
} // end "for (index=0; index<numberChannels; index++)"
// Remove last comma and add 2 returns.
sprintf ((char*)&gTextString[stringLength-1],
"%s",
gEndOfLine);
stringLength += gNumberOfEndOfLineCharacters - 1;
} // end "if (shortListFlag)"
continueFlag = OutputString (outputFilePtr,
(char*)gTextString,
stringLength,
*outputCodePtr,
continueFlag);
if (!shortListFlag)
{
fileInfoIndex = -1;
layerChanIndex = 1;
localFileInfoPtr = fileInfoPtr;
// If this is a call from the List Description Information processor,
// this routine will be called once for each linked file. Therefore,
// we need to find the actual channels to be processed for this
// call. That will be when the input fileInfoPtr is equal to that
// for the respective fileInfoIndex.
localImageLayerInfoPtr = gImageLayerInfoPtr;
if (gProcessorCode == kListDescriptionProcessor &&
gImageWindowInfoPtr->numberImageFiles > 1)
{
localImageLayerInfoPtr = NULL;
// Find the index into gImageLayerInfoPtr for the correct set
// of channels.
for (index=0; index<gImageWindowInfoPtr->totalNumberChannels; index++)
{
if (localImageLayerInfoPtr != NULL && fileInfoIndex !=
(SInt16)localImageLayerInfoPtr[layerChanIndex].fileInfoIndex)
{
fileInfoIndex = localImageLayerInfoPtr[layerChanIndex].fileInfoIndex;
localFileInfoPtr = &gImageFileInfoPtr[fileInfoIndex];
if (localFileInfoPtr == fileInfoPtr)
break;
} // end "if (gImageLayerInfoPtr != NULL && ..."
layerChanIndex++;
} // end "for (index=0; index<gImageWindowInfoPtr->..."
} // end "if (gProcessorCode == kListDescriptionProcessor && ..."
stringLength = 9 + gNumberOfEndOfLineCharacters;
channelNum = 0;
channelNumberLength = 4;
if (lChannelsPtr != NULL && lChannelsPtr[numberChannels-1] >= 10000)
channelNumberLength = 5;
else if (numberChannels >= 10000)
channelNumberLength = 5;
for (index=0; index<(UInt16)numberChannels; index++)
{
if (lChannelsPtr != NULL)
channelNum = lChannelsPtr[index];
channelNum++;
if (gProcessorCode != kListDescriptionProcessor)
layerChanIndex = channelNum;
if (localImageLayerInfoPtr != NULL && fileInfoIndex !=
(SInt16)localImageLayerInfoPtr[layerChanIndex].fileInfoIndex)
{
if (fileInfoIndex != -1)
CheckAndUnlockHandle (localFileInfoPtr->channelDescriptionH);
fileInfoIndex = localImageLayerInfoPtr[layerChanIndex].fileInfoIndex;
localFileInfoPtr = &fileInfoPtr[fileInfoIndex];
} // end "if (localImageLayerInfoPtr && fileInfoIndex != ..."
if (localFileInfoPtr && !useTransformFlag)
{
channelDescriptionPtr = NULL;
stringLength = 5 + channelNumberLength + gNumberOfEndOfLineCharacters;
if (localFileInfoPtr->channelDescriptionH)
{
channelDescriptionPtr = (ChannelDescriptionPtr)GetHandlePointer (
localFileInfoPtr->channelDescriptionH,
kLock);
stringLength = 31 + channelNumberLength + gNumberOfEndOfLineCharacters;
} // end "if (localFileInfoPtr->channelDescriptionH)"
} // end "if (localFileInfoPtr && !useTransformFlag)"
if (channelDescriptionPtr == NULL)
sprintf ((char*)gTextString,
" %*u%s",
channelNumberLength,
(unsigned int)channelNum,
gEndOfLine);
else // channelDescriptionPtr != NULL
{
fileChanNum = (SInt16)(index + 1);
if (localImageLayerInfoPtr != NULL)
fileChanNum = localImageLayerInfoPtr[layerChanIndex].fileChannelNumber;
BlockMoveData (&channelDescriptionPtr[fileChanNum-1], gTextString2, 24);
sprintf ((char*)gTextString,
" %*u: %s%s",
channelNumberLength,
(unsigned int)channelNum,
gTextString2,
gEndOfLine);
} // end "else channelDescriptionPtr"
continueFlag = OutputString (outputFilePtr,
(char*)gTextString,
stringLength,
*outputCodePtr,
continueFlag);
if (!continueFlag)
break;
layerChanIndex++;
} // end "for (channel=0;..."
} // end "if (!shortListFlag)"
// Insert a blank line after the table.
continueFlag = OutputString (outputFilePtr,
gEndOfLine,
gNumberOfEndOfLineCharacters,
*outputCodePtr,
continueFlag);
if (localFileInfoPtr != NULL)
CheckAndUnlockHandle (localFileInfoPtr->channelDescriptionH);
return (continueFlag);
} // end "ListChannelsUsed"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListCountValue
//
// Software purpose: The purpose of this routine is to list the area value within
// the specific classification summary line.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By: ListClassificationSummary in SListResults.cpp
//
// Coded By: Larry L. Biehl Date: 03/26/2004
// Revised By: Larry L. Biehl Date: 08/14/2010
SInt16 ListCountValue (
char* stringPtr,
SInt64 count,
SInt16 countNumberWidth,
SInt16 strLength,
SInt16 countWidthWithCommas,
Boolean includeTabFlag)
{
SInt16 numberChars;
if (includeTabFlag)
{
numberChars = sprintf (&stringPtr[strLength],
"\t");
strLength += numberChars;
} // end "if (includeTabFlag)"
if (countNumberWidth > 0)
numberChars = sprintf (&stringPtr[strLength],
"%*lld",
countNumberWidth,
count);
else // countNumberWidth <= 0
numberChars = sprintf (&stringPtr[strLength],
"%lld",
count);
if (countWidthWithCommas <= 0)
countWidthWithCommas = numberChars;
numberChars = InsertCommasInNumberString (&stringPtr[strLength],
numberChars,
-1,
countWidthWithCommas);
strLength += numberChars;
return (strLength);
} // end "ListCountValue"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ListCPUTimeInformation
//
// Software purpose: The purpose of this routine is to list the cpu time
// that the operation took and whether the operation
// was cancelled.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if listing to output was accomplished with no problems
// FALSE if not
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/30/1993
// Revised By: Larry L. Biehl Date: 05/31/2020
Boolean ListCPUTimeInformation (
CMFileStream* resultsFileStreamPtr,
Boolean continueFlag,
time_t startTime)
{
UInt32 hours,
minutes,
totalTime;
Boolean localContinueFlag;
if (gOutputForce1Code == 0)
return (continueFlag);
localContinueFlag = continueFlag;
if (gOperationCanceledFlag)
localContinueFlag = TRUE;
// List the CPU time taken for the processor.
totalTime = GetTotalTime (startTime);
switch (gProcessorCode)
{
case kOpenImageFileProcessor:
sprintf ((char*)gTextString2, "opening image");
break;
case kDisplayProcessor:
sprintf ((char*)gTextString2, "displaying image");
break;
case kHistogramProcessor:
case kHistogramInDisplayProcessor:
sprintf ((char*)gTextString2, "histograming image");
break;
case kRefChangeHeaderProcessor:
case kRefChangeFileFormatProcessor:
case kRefMosaicImagesProcessor:
case kRefFieldsToThematicFileProcessor:
case kRectifyImageProcessor:
case kRefModifyChanDescriptionsProcessor:
case kMultispecToThematicProcessor:
case kENVIROIToThematic:
case kRecodeThematicImageProcessor:
sprintf ((char*)gTextString2, "reformatting");
break;
case kListDataProcessor:
sprintf ((char*)gTextString2, "listing data");
break;
case kClusterProcessor:
sprintf ((char*)gTextString2, "clustering");
break;
case kComputeStatsProcessor:
sprintf ((char*)gTextString2, "statistics computation");
break;
case kListStatsProcessor:
sprintf ((char*)gTextString2, "listing statistics");
break;
case kHistogramStatsProcessor:
sprintf ((char*)gTextString2, "histograming statistics");
break;
case kStatEnhanceProcessor:
sprintf ((char*)gTextString2, "enhance statistics");
break;
case kFeatureExtractionProcessor:
sprintf ((char*)gTextString2, "feature extraction");
break;
case kSeparabilityProcessor:
sprintf ((char*)gTextString2, "feature selection");
break;
case kClassifyProcessor:
sprintf ((char*)gTextString2, "classification");
break;
case kListResultsProcessor:
sprintf ((char*)gTextString2, "results listing");
break;
case kPrincipalComponentsProcessor:
sprintf ((char*)gTextString2, "principal component analysis");
break;
case kStatisticsImageProcessor:
sprintf ((char*)gTextString2, "creating statistics images");
break;
case kBiPlotDataProcessor:
sprintf ((char*)gTextString2, "creating biplot of data");
break;
case kCovarianceCheckProcessor:
sprintf ((char*)gTextString2, "checking covariance statistics");
break;
case kTransformCheckProcessor:
sprintf ((char*)gTextString2, "checking transformation matrix");
break;
default:
sprintf ((char*)gTextString2, "operation");
break;
} // end "switch (gProcessorCode)"
if (gOperationCanceledFlag)
{
if (gAlertReturnCode == 1)
// Operation was stopped and results to that point were listed.
sprintf ((char*)gTextString,
"%s %s was stopped. Results at that point were listed.",
gEndOfLine,
gTextString2);
else // gAlertReturnCode != 1
sprintf ((char*)gTextString,
"%s %s was cancelled.",
gEndOfLine,
gTextString2);
localContinueFlag = OutputString (
resultsFileStreamPtr,
(char*)gTextString,
0,
gOutputForce1Code,
localContinueFlag);
} // end "if (gOperationCanceledFlag)"
// Add the date and time to the line.
time_t currentTime = time (NULL);
struct tm *currentDate = localtime (¤tTime);
strftime ((char*)gTextString3, 254, " %m-%d-%Y %X", currentDate);
if (totalTime < 60)
sprintf ((char*)gTextString,
"%s %u CPU seconds for %s.%s%s",
gEndOfLine,
(unsigned int)totalTime,
gTextString2,
gTextString3,
gEndOfLine);
else // totalTime >= 60)
{
// Get number of minutes and seconds
minutes = totalTime/60;
totalTime -= minutes*60;
if (minutes < 60)
{
sprintf ((char*)gTextString,
"%s %u minutes and %u seconds CPU time for %s.%s%s",
gEndOfLine,
(unsigned int)minutes,
(unsigned int)totalTime,
gTextString2,
gTextString3,
gEndOfLine);
} // end "if (minutes < 60)"
else // minutes >= 60
{
// Get number of hours and minutes
hours = minutes/60;
minutes -= hours*60;
sprintf ((char*)gTextString,
"%s %u hours, %u minutes and %u seconds CPU time for %s.%s%s",
gEndOfLine,
(unsigned int)hours,
(unsigned int)minutes,
(unsigned int)totalTime,
gTextString2,
gTextString3,
gEndOfLine);
} // end "else startTime >= 3600"
} // end "else startTime >= 60)"
continueFlag = OutputString (
resultsFileStreamPtr,
(char*)gTextString,
0,
gOutputForce1Code,
localContinueFlag);
/*
// Add a carriage return.
continueFlag = OutputString (resultsFileStreamPtr,
&gEndOfLine[0],
gNumberOfEndOfLineCharacters,
gOutputCode,
continueFlag);
*/
// List the dashed line separator string to indicate end of processor
// output.
if (gProcessorCode != kHistogramInDisplayProcessor)
continueFlag = ListSpecifiedStringNumber (kSharedStrID,
IDS_Shared6,
(unsigned char*)gTextString,
resultsFileStreamPtr,
gOutputForce1Code,
continueFlag);
return (continueFlag);
} // end "ListCPUTimeInformation"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListHeaderInfo
//
// Software purpose: The purpose of this routine is to list the requested
// information for the header in the output window.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By: ListDataControl in SListData.cpp
// PrincipalComponentControl in SPrincipalComponents.cpp
// ListClassificationHeaderInfo in SProjectUtilities.cpp
// SeparabilityControl in SFeatureSelection.cpp
//
// Coded By: Larry L. Biehl Date: 01/03/1994
// Revised By: Larry L. Biehl Date: 08/02/2013
Boolean ListHeaderInfo (
CMFileStream* resultsFileStreamPtr,
SInt16 listCode,
SInt16* outputCodePtr,
SInt16 covarianceStatsToUse,
Boolean continueFlag)
{
if (continueFlag && *outputCodePtr > 0)
{
// List the dashed line separator string to indicate start of processor
// output.
ListSpecifiedStringNumber (kSharedStrID,
IDS_Shared5,
(unsigned char*)gTextString,
NULL,
*outputCodePtr,
continueFlag);
// List the processor name, date and time.
if (continueFlag)
continueFlag = ListProcessorTitleLine (
resultsFileStreamPtr, outputCodePtr, continueFlag);
// List " Input Parameters:".
if (continueFlag && listCode != 0)
continueFlag = ListSpecifiedStringNumber (kSharedStrID,
IDS_Shared7,
(unsigned char*)gTextString,
resultsFileStreamPtr,
*outputCodePtr,
continueFlag);
// List image file name and statistics information.
if (continueFlag && listCode != 0 && listCode != kLInputParametersLineOnly)
continueFlag = ListProjectAndImageName (resultsFileStreamPtr,
outputCodePtr,
listCode,
covarianceStatsToUse,
continueFlag);
} // end "if (continueFlag && *outputCodePtr > 0)"
return (continueFlag);
} // end "ListHeaderInfo"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListLineColumnIntervalString
//
// Software purpose: The purpose of this routine is to list the input line-
// column-interval values.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 09/03/1997
// Revised By: Larry L. Biehl Date: 09/03/1997
Boolean ListLineColumnIntervalString (
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
UInt32 lineStart,
UInt32 lineEnd,
UInt32 lineInterval,
UInt32 columnStart,
UInt32 columnEnd,
UInt32 columnInterval,
Boolean continueFlag)
{
// " Lines %ld to %ld by %ld. Columns %ld to %ld by %ld.%s"
if (continueFlag)
continueFlag = MGetString (gTextString2, kSharedStrID, IDS_Shared3);
if (continueFlag)
sprintf ((char*)gTextString,
(char*)&gTextString2[1],
lineStart,
lineEnd,
lineInterval,
columnStart,
columnEnd,
columnInterval);
continueFlag = OutputString (
resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
continueFlag);
return (continueFlag);
} // end "ListLineColumnIntervalString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListMapProjectionString
//
// Software purpose: The purpose of this routine is to list the name of the map
// projection to the output text window.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/03/2007
// Revised By: Larry L. Biehl Date: 03/15/2012
Boolean ListMapProjectionString (
Handle mapProjectionHandle,
char* spaceStringPtr,
Boolean continueFlag)
{
SInt16 projectionCode;
if (mapProjectionHandle != NULL)
{
projectionCode = GetProjectionCode (mapProjectionHandle);
// Allow for MultiSpec Geographic code which is -1;
/*
if (projectionCode > 0)
projectionCode++;
else if (projectionCode < 0)
projectionCode = 1;
if (projectionCode <= 0)
{
sprintf ((char*)gTextString,
"%sNone specified%s",
spaceStringPtr,
gEndOfLine);
if (continueFlag)
continueFlag = ListString (
(char*)gTextString, strlen ((char*)gTextString), gOutputTextH);
} // end "if (projectionCode <= 0)"
*/
if (projectionCode > 0)
{
#if defined multispec_mac
GetMenuItemText (gPopUpProjectionMenu,
projectionCode+1,
gTextString2);
gTextString2[gTextString2[0]+1] = 0;
#endif // defined multispec_mac
#if defined multispec_win || defined multispec_wx
MGetString (gTextString2,
0,
IDS_ProjectionType01+projectionCode);
#endif // defined multispec_win
sprintf ((char*)gTextString,
"%sProjection: %s%s",
spaceStringPtr,
&gTextString2[1],
gEndOfLine);
if (continueFlag)
continueFlag = ListString (
(char*)gTextString, (UInt32)strlen ((char*)gTextString), gOutputTextH);
} // end "if (projectionCode > 0)"
} // end "if (mapProjectionHandle != NULL)"
return (continueFlag);
} // end "ListMapProjectionString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListMapReferenceSystemString
//
// Software purpose: The purpose of this routine is to list the name of the map
// reference system to the output text window.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/14/2012
// Revised By: Larry L. Biehl Date: 03/14/2012
Boolean ListMapReferenceSystemString (
Handle mapProjectionHandle,
char* spaceStringPtr,
Boolean continueFlag)
{
SInt16 referenceSystemCode;
if (mapProjectionHandle != NULL)
{
referenceSystemCode = GetReferenceSystemCode (mapProjectionHandle);
if (referenceSystemCode <= 0)
{
sprintf ((char*)gTextString,
"%sNone specified%s",
spaceStringPtr,
gEndOfLine);
if (continueFlag)
continueFlag = ListString (
(char*)gTextString, (UInt32)strlen ((char*)gTextString), gOutputTextH);
} // end "if (projectionCode <= 0)"
else // referenceSystemCode > 0
{
#if defined multispec_mac
GetMenuItemText (gPopUpReferenceSystemMenu,
referenceSystemCode+1,
gTextString2);
gTextString2[gTextString2[0]+1] = 0;
#endif // defined multispec_mac
#if defined multispec_win | defined multispec_wx
MGetString (gTextString2,
0,
IDS_ReferenceSystem01+referenceSystemCode);
#endif // defined multispec_win
sprintf ((char*)gTextString,
"%sReference System: %s%s",
spaceStringPtr,
&gTextString2[1],
gEndOfLine);
if (continueFlag)
continueFlag = ListString (
(char*)gTextString, (UInt32)strlen ((char*)gTextString), gOutputTextH);
} // end "else projectionCode > 0"
} // end "if (mapProjectionHandle != NULL)"
return (continueFlag);
} // end "ListMapReferenceSystemString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ListMemoryMessage
//
// Software purpose: The purpose of this routine is to list a message in the text
// output window indicating that memory was not available to
// complete the process.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 07/10/2009
// Revised By: Larry L. Biehl Date: 07/10/2009
Boolean ListMemoryMessage (
CMFileStream* resultsFileStreamPtr)
{
Boolean continueFlag = TRUE;
if (gMemoryError != 0)
{
continueFlag = ListSpecifiedStringNumber (kAlertStrID,
IDS_Alert136,
gTextString,
resultsFileStreamPtr,
gOutputForce1Code,
continueFlag);
if (gProcessorCode == kClusterProcessor)
continueFlag = ListSpecifiedStringNumber (kClusterStrID,
IDS_Cluster50,
gTextString,
resultsFileStreamPtr,
gOutputForce1Code,
continueFlag);
else if (gProcessorCode == kClassifyProcessor)
continueFlag = ListSpecifiedStringNumber (kClassifyStrID,
IDS_Classify66,
gTextString,
resultsFileStreamPtr,
gOutputForce1Code,
continueFlag);
#if defined multispec_win | defined multispec_wx
gMemoryError = 0;
#endif // defined multispec_win
} // end "if (gMemoryError != 0)"
return (continueFlag);
} // end "ListMemoryMessage"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListProcessorTitleLine
//
// Software purpose: The purpose of this routine is to list the title
// line for the processor being run.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By: ListHeaderInfo in SStrings.cpp
//
// Coded By: Larry L. Biehl Date: 04/09/1991
// Revised By: Larry L. Biehl Date: 09/01/2017
Boolean ListProcessorTitleLine (
CMFileStream* resultsFileStreamPtr,
SInt16* outputCodePtr,
Boolean continueFlag)
{
char textString[512];
SInt16 indexStart,
stringIndex;
Boolean listClassificationIdentifierFlag;
// Initialize local variables.
indexStart = 0;
listClassificationIdentifierFlag = FALSE;
stringIndex = IDS_ProcessorDisplay;
switch (gProcessorCode)
{
case kDisplayProcessor:
stringIndex = IDS_ProcessorDisplay;
break;
case kDisplayOverlayProcessor:
stringIndex = IDS_Processor19;
break;
case kHistogramProcessor:
stringIndex = IDS_ProcessorHistogram;
break;
case kReformatProcessor:
case kRefChangeHeaderProcessor:
case kRefModifyChanDescriptionsProcessor:
case kMultispecToThematicProcessor:
stringIndex = IDS_ProcessorReformat;
break;
case kRefChangeFileFormatProcessor:
stringIndex = IDS_Processor20;
break;
case kRectifyImageProcessor:
stringIndex = IDS_Processor21;
break;
case kRefShapeToThematicFileProcessor:
stringIndex = IDS_Processor22;
break;
case kRecodeThematicImageProcessor:
stringIndex = IDS_Processor23;
break;
case kRefFieldsToThematicFileProcessor:
stringIndex = IDS_Processor24;
break;
case kENVIROIToThematic:
stringIndex = IDS_Processor25;
break;
case kRefMosaicImagesProcessor:
stringIndex = IDS_Processor26;
break;
case kListDataProcessor:
stringIndex = IDS_ProcessorListData;
break;
case kClusterProcessor:
stringIndex = IDS_ProcessorCluster;
listClassificationIdentifierFlag = TRUE;
break;
case kComputeStatsProcessor:
stringIndex = IDS_Processor18;
break;
case kListStatsProcessor:
stringIndex = IDS_ProcessorListStats;
break;
case kHistogramStatsProcessor:
stringIndex = IDS_ProcessorHistStats;
break;
case kStatEnhanceProcessor:
stringIndex = IDS_ProcessorEnhance;
break;
case kFeatureExtractionProcessor:
stringIndex = IDS_ProcessorExtract;
break;
case kSeparabilityProcessor:
stringIndex = IDS_ProcessorFeature;
break;
case kClassifyProcessor:
stringIndex = IDS_ProcessorClassify;
listClassificationIdentifierFlag = TRUE;
break;
case kListResultsProcessor:
stringIndex = IDS_ProcessorResults;
break;
case kPrincipalComponentsProcessor:
stringIndex = IDS_ProcessorPrinc;
break;
case kStatisticsImageProcessor:
stringIndex = IDS_ProcessorCreateStat;
break;
case kBiPlotDataProcessor:
stringIndex = IDS_ProcessorBiPlot;
break;
case kCovarianceCheckProcessor:
stringIndex = IDS_ProcessorCheckCov;
break;
case kTransformCheckProcessor:
stringIndex = IDS_ProcessorCheckTran;
break;
} // end "switch (gProcessorCode)"
// List the MultiSpec classification header identifier line.
if (listClassificationIdentifierFlag)
{
MGetString (gTextString2, kFileIOStrID, IDS_MultiSpecType); // 42
sprintf ((char*)gTextString, "%s%s", &gTextString2[1], gEndOfLine);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
*outputCodePtr,
TRUE);
} // end "if (listClassificationIdentifierFlag)"
MGetString ((UCharPtr)gTextString2, kProcessorStrID, stringIndex);
if (gProcessorCode == kDisplayProcessor)
{
// Include the image file name
char* fileNamePtr = (char*)GetFileNameCPointerFromFileInfo (gImageFileInfoPtr);
sprintf ((char*)&gTextString2[gTextString2[0]+1],
(char*)" '%s'",
fileNamePtr);
} // end "if (gProcessorCode == kDisplayProcessor)"
// Add the date and time to the line.
time_t currentTime = time (NULL);
struct tm *currentDate = localtime (¤tTime);
strftime ((char*)gTextString3, 254, " %m-%d-%Y %X", currentDate);
sprintf (&textString[0],
"%s%s (%s)%s",
&gTextString2[1],
gTextString3,
gApplicationIdentifierString,
gEndOfLine);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)&textString[indexStart],
0,
*outputCodePtr,
continueFlag,
kUTF8CharString);
if (gProcessorCode == kDisplayProcessor)
{
// Include the hdf data set name if needed.
if (gImageFileInfoPtr->hdfHandle != NULL)
{
Str255 hdfDataSetName;
UInt16 numChars;
GetHdfDataSetName (gImageFileInfoPtr,
gImageFileInfoPtr->hdfDataSetSelection,
(StringPtr)&hdfDataSetName,
NULL);
numChars = hdfDataSetName[0];
if (numChars > 0)
{
numChars = sprintf ((char*)gTextString,
" %s",
"(hdf set: ");
numChars = sprintf ((char*)&gTextString[numChars],
"%s)%s",
&hdfDataSetName[1],
gEndOfLine);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
*outputCodePtr,
continueFlag);
} // end "if (numChars > 0)"
} // end "if (gImageFileInfoPtr == kHDF4Type || ..."
} // end "if (gProcessorCode == kDisplayProcessor)"
return (continueFlag);
} // end "ListProcessorTitleLine"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListProjectAndImageName
//
// Software purpose: The purpose of this routine is to list the project
// name and the base image file name.
//
// Parameters in: The dialog pointer.
// The dialog item number.
// Address to the draw routine.
//
// Parameters out: Rectangle for the input item number.
//
// Value Returned: None.
//
// Called By: ListHeaderInfo in SStrings.cpp
//
// Coded By: Larry L. Biehl Date: 05/20/1992
// Revised By: Larry L. Biehl Date: 11/25/2019
Boolean ListProjectAndImageName (
CMFileStream* resultsFileStreamPtr,
SInt16* outputCodePtr,
SInt16 listCode,
SInt16 covarianceStatsToUse,
Boolean continueFlag)
{
SInt16 strLength;
if (continueFlag)
{
if ((listCode & kLProjectName) && gProjectInfoPtr != NULL)
{
// List the project name.
char* projectFileNamePtr =
(char*)GetFileNameCPointerFromProjectInfo (gProjectInfoPtr);
if (strlen (projectFileNamePtr) == 0)
sprintf ((char*)gTextString2,
(char*)"Untitled Project");
else // projectFileNamePtr[0] != 0
sprintf ((char*)gTextString2, "%s", projectFileNamePtr);
sprintf ((char*)gTextString,
(char*)" Project = '%s'%s",
gTextString2,
gEndOfLine);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
*outputCodePtr,
continueFlag,
kUTF8CharString);
} // end "if ((listCode & kProjectName) && gProjectInfoPtr)"
if ((listCode & kLStatType) && gProjectInfoPtr != NULL)
{
SInt16 stringCode = 0;
if (covarianceStatsToUse == kOriginalStats)
stringCode = IDS_Project46;
else if (covarianceStatsToUse == kLeaveOneOutStats)
{
if (gProjectInfoPtr->mixingParameterCode == kComputedOptimum)
stringCode = IDS_Project47;
else if (gProjectInfoPtr->mixingParameterCode == kUserSet)
stringCode = IDS_Project73;
else if (gProjectInfoPtr->mixingParameterCode == kIdentityMatrix)
stringCode = IDS_Project74;
} // end "else if (covarianceStatsToUse == kLeaveOneOutStats)"
else if (covarianceStatsToUse == kEnhancedStats)
{
if (gProjectInfoPtr->enhancedStatsOrigin == kOriginalStats)
stringCode = IDS_Project48;
else if (gProjectInfoPtr->enhancedStatsOrigin == kLeaveOneOutStats)
stringCode = IDS_Project75;
else // ...->enhancedStatsOrigin == kMixedStats
stringCode = IDS_Project76;
} // end "else if (covarianceStatsToUse == kEnhancedStats)"
else if (covarianceStatsToUse == kMixedStats)
stringCode = IDS_Project49;
if (stringCode != 0)
continueFlag = ListSpecifiedStringNumber (
kProjectStrID,
stringCode,
(unsigned char*)gTextString,
NULL,
*outputCodePtr,
continueFlag);
if (covarianceStatsToUse == kLeaveOneOutStats &&
!gProjectInfoPtr->useCommonCovarianceInLOOCFlag)
continueFlag = ListSpecifiedStringNumber (
kProjectStrID,
IDS_Project58,
(unsigned char*)gTextString,
NULL,
*outputCodePtr,
continueFlag);
} // end "if ((listCode & kLStatType) && gProjectInfoPtr != NULL)"
if ((listCode & kLProjectImageName) && gProjectInfoPtr)
{
// List the project image file name.
pstr ((char*)gTextString2,
(char*)gProjectInfoPtr->imageFileName,
&strLength);
sprintf ((char*)gTextString,
(char*)" Base image file = '%s'%s",
gTextString2,
gEndOfLine);
} // end "if ((listCode & kLProjectImageName) && ..."
else // !(listCode & kLProjectImageName) || !gProjectInfoPtr
{
// List just the image file name.
char* fileNamePtr =
(char*)GetFileNameCPointerFromFileInfo (gImageFileInfoPtr);
sprintf ((char*)gTextString,
(char*)" Image file = '%s'%s",
fileNamePtr,
gEndOfLine);
} // end "else !(listCode & kProjectName) || !gProjectInfoPtr"
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
*outputCodePtr,
continueFlag,
kUTF8CharString);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListProjectAndImageName"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 10/28/1993
// Revised By: Larry L. Biehl Date: 08/24/2020
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
UCharPtr stringPtr,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
Boolean continueFlag)
{
//Str255* str255Ptr;
if (continueFlag)
{
//str255Ptr = (Str255*)stringPtr;
continueFlag = MGetString (stringPtr, strListID, index);
if (continueFlag)
continueFlag = OutputString (resultsFileStreamPtr,
(char*)&stringPtr[1],
(SInt32)stringPtr[0],
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input double value. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/26/1994
// Revised By: Larry L. Biehl Date: 01/26/1994
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
double dValue,
Boolean continueFlag)
{
char* stringPtr2;
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
dValue);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input long value. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/26/1994
// Revised By: Larry L. Biehl Date: 01/26/1994
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
SInt32 lValue,
Boolean continueFlag)
{
char* stringPtr2;
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
lValue);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with two input long values. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 10/21/1994
// Revised By: Larry L. Biehl Date: 10/21/1994
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
SInt32 lValue,
SInt32 lValue2,
Boolean continueFlag)
{
CharPtr stringPtr2;
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
lValue,
lValue2);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with three input long values. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/01/1996
// Revised By: Larry L. Biehl Date: 08/01/1996
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
SInt32 lValue,
SInt32 lValue2,
SInt32 lValue3,
Boolean continueFlag)
{
CharPtr stringPtr2;
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
lValue,
lValue2,
lValue3);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input long value. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/20/2010
// Revised By: Larry L. Biehl Date: 08/20/2010
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
SInt64 lValue,
Boolean continueFlag)
{
char* stringPtr2;
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
lValue);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with two input long values. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/23/2010
// Revised By: Larry L. Biehl Date: 08/23/2010
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
SInt64 llValue,
SInt32 lValue2,
Boolean continueFlag)
{
CharPtr stringPtr2;
UInt32 numChars;
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
numChars = sprintf ((char*)gTextString,
&stringPtr2[1],
llValue,
lValue2);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
numChars,
outputCode,
TRUE);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input Pascal string. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to
// the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 06/24/1994
// Revised By: Larry L. Biehl Date: 06/26/1995
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
UCharPtr inputStringPtr,
Boolean continueFlag)
{
SInt16 strLength;
// Make certain the pascal string has a null at the end so that it
// can be treated as a C string.
pstr ((char*)gTextString3, (char*)inputStringPtr, &strLength);
continueFlag = ListSpecifiedStringNumber (
strListID,
index,
resultsFileStreamPtr,
outputCode,
(CharPtr)gTextString3,
continueFlag);
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input C string. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
// This is an overload function
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to
// the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 09/05/2017
// Revised By: Larry L. Biehl Date: 04/17/2020
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
CharPtr inputStringPtr,
Boolean continueFlag)
{
char tempString[_MAX_PATH];
CharPtr stringPtr2;
int tempStringLength;
// Get the base string from the resource fork.
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)gTextString2;
tempStringLength = sprintf (tempString,
&stringPtr2[1],
inputStringPtr);
continueFlag = OutputString (resultsFileStreamPtr,
tempString,
tempStringLength,
outputCode,
TRUE,
kASCIICharString);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input C string. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to
// the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 06/26/1995
// Revised By: Larry L. Biehl Date: 04/11/2020
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
CharPtr inputStringPtr,
Boolean continueFlag,
SInt16 charFormatCode)
{
char textString[1280];
CharPtr stringPtr2;
UInt32 numChars;
// Get the base string from the resource fork.
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
numChars = sprintf (textString,
&stringPtr2[1],
inputStringPtr);
continueFlag = OutputString (resultsFileStreamPtr,
textString,
numChars,
outputCode,
TRUE,
charFormatCode);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input C string. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
// This is an overload function
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to
// the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 09/05/1999
// Revised By: Larry L. Biehl Date: 09/05/2017
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
CharPtr inputStringPtr,
CharPtr inputString2Ptr,
Boolean continueFlag)
{
CharPtr stringPtr2;
// Get the base string from the resource fork.
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
inputStringPtr,
inputString2Ptr);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE,
kASCIICharString);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListSpecifiedStringNumber
//
// Software purpose: This routine lists the specified string number in the
// resource file to the output text window and/or
// disk file with the input C string. Note that
// gTextString and gTextString2 are used for temporary
// storage. Make certain that they are not being used
// for other items.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to
// the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/16/1999
// Revised By: Larry L. Biehl Date: 03/16/2017
Boolean ListSpecifiedStringNumber (
SInt16 strListID,
SInt16 index,
CMFileStream* resultsFileStreamPtr,
SInt16 outputCode,
CharPtr inputStringPtr,
CharPtr inputString2Ptr,
Boolean continueFlag,
SInt16 charFormatCode)
{
CharPtr stringPtr2;
// Get the base string from the resource fork.
continueFlag = GetSpecifiedStringNumber (
strListID, index, gTextString2, continueFlag);
if (continueFlag)
{
stringPtr2 = (char*)&gTextString2;
sprintf ((char*)gTextString,
&stringPtr2[1],
inputStringPtr,
inputString2Ptr);
continueFlag = OutputString (resultsFileStreamPtr,
(char*)gTextString,
0,
outputCode,
TRUE,
charFormatCode);
} // end "if (continueFlag)"
return (continueFlag);
} // end "ListSpecifiedStringNumber"
void ListString (
const char* textBuffer)
{
unsigned int textLength;
textLength = (unsigned int)strlen (textBuffer);
ListString ((HPtr)textBuffer,
(UInt32)textLength,
gOutputTextH,
kASCIICharString);
} // end "ListString"
Boolean ListString (
char* textBuffer,
unsigned int textLength)
{
return (ListString ((HPtr)textBuffer,
(UInt32)textLength,
gOutputTextH,
kASCIICharString));
} // end "ListString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ListString
//
// Software purpose: The purpose of this routine is to call the OS specific
// routine to list the string in the output test window.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 09/05/1988
// Revised By: Larry L. Biehl Date: 09/05/2017
Boolean ListString (
HPtr stringPtr,
UInt32 stringLength,
#if use_mlte_for_text_window
TXNObject textH)
#endif
#if !use_mlte_for_text_window
WEReference textH)
#endif
{
return (ListString ((HPtr)stringPtr,
(UInt32)stringLength,
textH,
kASCIICharString));
} // end "ListString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void ListString
//
// Software purpose: The purpose of this routine is to call the OS specific
// routine to list the string in the output test window.
//
// Only verify available memory if the request is for more than
// 10 MB; will assume 10 MB is relatively easily available. This
// is to save on calls to determine available memory.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/30/1988
// Revised By: Larry L. Biehl Date: 03/22/2019
Boolean ListString (
HPtr stringPtr,
UInt32 stringLength,
#if use_mlte_for_text_window
TXNObject textH,
#endif
#if !use_mlte_for_text_window
WEReference textH,
#endif
SInt16 charFormatCode)
{
SInt64 lContBlock;
Boolean memoryOKFlag = TRUE,
returnFlag = FALSE;
if (2*stringLength > 10000000)
{
MGetFreeMemory (&lContBlock);
if (lContBlock < 2*stringLength)
memoryOKFlag = FALSE;
} // end "if (2*stringLength > 10000000)"
// Continue if memory ok.
if (memoryOKFlag)
{
#if defined multispec_mac
// Local Declarations
SInt16 savedMemoryError;
if (gOutputWindow == NULL)
return (returnFlag);
// Save the memory error. We want to be sure to catch the any memory error caused by
// listing the message. The message may already be about a memory allocation error.
savedMemoryError = gMemoryError;
gMemoryError = noErr;
// Add input string to text buffer.
// Also -
// Update maximum string length if needed. This assumes that the
// string has a carriage return at the end. Even if wrong this
// shouldn't cause too much problem.
#if !use_mlte_for_text_window
if (stringLength <= gMaxCharsAllowedInLine)
{
#endif // !use_mlte_for_text_window
#if use_mlte_for_text_window
UniChar tempBuffer[512];
char* txnSetDataStringPtr;
CFStringRef cfStringRef = NULL;
OSStatus returnCode;
txnSetDataStringPtr = stringPtr;
TXNDataType stringDataType = kTXNTextData;
if (charFormatCode == kUnicodeCharString || charFormatCode == kUTF8CharString)
{
CFIndex usedBufferLength = 0;
stringDataType = kTXNUnicodeTextData;
if (charFormatCode == kUTF8CharString)
{
CFIndex numerCharacters = 0;
// Now get the UTF8 formatted file name.
cfStringRef = CFStringCreateWithBytes (
kCFAllocatorDefault,
(UInt8*)stringPtr,
stringLength,
kCFStringEncodingUTF8,
false);
if (cfStringRef != NULL)
{
CFStringGetBytes (cfStringRef,
CFRangeMake (0, stringLength),
kCFStringEncodingUnicode,
'?',
false,
(UInt8*)tempBuffer,
512,
&usedBufferLength);
// Get the number of characters in the unicode string.
numerCharacters = CFStringGetLength (cfStringRef);
/*
CFStringGetCString (cfStringRef,
(char*)&fileStreamPtr->fileName[1],
(CFIndex)255,
kCFStringEncodingUTF8);
fileStreamPtr->fileName[0] = strlen ((char*)&fileStreamPtr->fileName[1]);
*/
} // end "if (cfStringRef != NULL)"
txnSetDataStringPtr = (char*)tempBuffer;
stringLength = 2 * numerCharacters;
} // end "if (charFormatCode == kUTF8CharString)"
/*
else // charFormatCode == kUnicodeCharString
{
// Need to convert wchar_t (4 bytes) to unicode char (2 bytes). For now
// will just leave out bytes 3 & 4 of all of the input wchar_t characters
// to see how it works.
char* tempCharPtr = (char*)stringPtr;
UInt32 characterCount;
UInt32 fromIndex = 4;
UInt32 toIndex = 2;
for (characterCount = 1; characterCount<stringLength; characterCount++)
{
tempCharPtr[toIndex] = tempCharPtr[fromIndex];
toIndex++;
fromIndex++;
tempCharPtr[toIndex] = tempCharPtr[fromIndex];
toIndex++;
fromIndex += 3;
} // end "for (characterCount = 1; characterCount<stringLength; characterCount++)"
stringLength *= 2;
} // end "else charFormatCode == kUnicodeCharString"
*/
} // end "if (charFormatCode == kUnicodeCharString || ...; else"
returnCode = TXNSetData (textH,
stringDataType,
txnSetDataStringPtr,
stringLength,
kTXNEndOffset,
kTXNEndOffset);
if (cfStringRef != NULL)
//CFAllocatorDeallocate (kCFAllocatorDefault, (void*)cfStringRef);
CFRelease (cfStringRef);
#endif // use_mlte_for_text_window
#if !use_mlte_for_text_window
WEInsert (stringPtr, stringLength, NULL, NULL, textH);
#endif // !use_mlte_for_text_window
gMaxCharsInLine = MAX (gMaxCharsInLine, stringLength);
#if !use_mlte_for_text_window
} // end "if (stringLength <= gMaxCharsAllowedInLine)"
else // stringLength > gMaxCharsAllowedInLine
{
SInt32 lTextLength;
lTextLength = gMaxCharsAllowedInLine;
while (stringLength > 0)
{
//redisplayFlag = WSInsert (textH, stringPtr, lTextLength);
WEInsert (stringPtr, lTextLength, NULL, NULL, textH);
/*
WEPut (0,
0,
stringPtr,
lTextLength,
kTextEncodingMacRoman,
0,
0,
NULL,
NULL,
textH);
*/
stringPtr += lTextLength;
stringLength -= lTextLength;
lTextLength = MIN (lTextLength, stringLength);
if (lTextLength > 0)
{
// Add a carriage return in the text since the length
// of the line exceeds the maximum length allowed for a
// line of text. This assumes that there are no other
// carriage returns within this line of text which is
// the case for any long text strings in MultiSpec.
//redisplayFlag = WSInsert (textH, gEndOfLine, 1);
WEInsert (gEndOfLine, 1, NULL, NULL, textH);
} // end "if (lTextLength > 0)"
} // end "while (stringLength > 0)"
gMaxCharsInLine = gMaxCharsAllowedInLine;
} // end "else stringLength > gMaxCharsAllowedInLine"
#endif // !use_mlte_for_text_window
returnFlag = (gMemoryError == noErr);
gMemoryError = savedMemoryError;
// Indicate that the window has changed.
SetOutputWindowChangedFlag (TRUE);
#endif // defined multispec_mac
#if defined multispec_win || defined multispec_wx
if (gOutputViewCPtr == NULL)
return (returnFlag);
returnFlag = gOutputViewCPtr->ListString (
stringPtr, stringLength, charFormatCode);
#endif // defined multispec_win
} // end "if (memoryOKFlag)"
else // !memoryOKFlag
{
DisplayAlert (kTextWindowLowMemoryAlertID,
kCautionAlert,
kAlertStrID,
IDS_Alert58,
0,
NULL);
returnFlag = FALSE;
} // end "else !memoryOKFlag"
return (returnFlag);
} // end "ListString"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean ListZoneMapProjectionString
//
// Software purpose: The purpose of this routine is to list the name of the map
// projection being used for the UTM or State Plane map projection
// system to the output text window.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/01/2007
// Revised By: Larry L. Biehl Date: 03/14/2012
Boolean ListZoneMapProjectionString (
SInt16 projectionCode,
char* spaceStringPtr,
Boolean continueFlag)
{
if (projectionCode >= -1)
{
// Allow for MultiSpec Geographic code which is -1;
if (projectionCode > 0)
projectionCode++;
else if (projectionCode < 0)
projectionCode = 1;
if (projectionCode <= 0)
{
sprintf ((char*)gTextString,
"%sNone specified%s",
spaceStringPtr,
gEndOfLine);
if (continueFlag)
continueFlag = ListString (
(char*)gTextString, strlen ((char*)gTextString), gOutputTextH);
} // end "if (projectionCode <= 0)"
else // projectionCode > 0
{
#if defined multispec_mac
GetMenuItemText (gPopUpProjectionMenu,
projectionCode+1,
gTextString2);
gTextString2[gTextString2[0]+1] = 0;
#endif // defined multispec_mac
#if defined multispec_win
MGetString (gTextString2,
0,
IDS_ProjectionType01+projectionCode);
#endif // defined multispec_win
sprintf ((char*)gTextString,
"%sZone Projection: %s%s",
spaceStringPtr,
&gTextString2[1],
gEndOfLine);
if (continueFlag)
continueFlag = ListString (
(char*)gTextString, strlen ((char*)gTextString), gOutputTextH);
} // end "else projectionCode > 0"
} // end "if (projectionCode >= -1)"
return (continueFlag);
} // end "ListZoneMapProjectionString"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 LoadRealValueString
//
// Software purpose: This routine loads the input string with the real value with the
// specified field size and decimals in either f or E format
// depending on the input data value.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: Length of the string
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/09/2006
// Revised By: Larry L. Biehl Date: 03/12/2012
SInt16 LoadRealValueString (
char* stringPtr,
double dataValue,
SInt16 dataValueFieldSize,
SInt16 numberFDecimalDigits,
SInt16 numberEDecimalDigits,
char* startStringPtr,
char* endStringPtr)
{
double absValue;
SInt16 numberChars;
absValue = fabs (dataValue);
if (absValue == 0. ||
(absValue >= (double)kMinValueToListWith_f &&
absValue <= (double)kMaxValueToListWith_f))
{
if (numberFDecimalDigits >= 0)
numberChars = sprintf (stringPtr,
"%s%*.*f%s",
startStringPtr,
dataValueFieldSize,
numberFDecimalDigits,
dataValue,
endStringPtr);
else
numberChars = sprintf (stringPtr,
"%s%g%s",
startStringPtr,
dataValue,
endStringPtr);
} // end "if (absValue == 0. || ..."
else // absValue != 0 && (absValue < kMinValueToListWith_f || ...
numberChars = sprintf (stringPtr,
"%s%*.*E%s",
startStringPtr,
dataValueFieldSize,
numberEDecimalDigits,
dataValue,
endStringPtr);
return (numberChars);
} // end "LoadRealValueString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberDouble
//
// Software purpose: This routine loads the specified string number in the
// resource file to the input string with the input double values.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/25/2007
// Revised By: Larry L. Biehl Date: 04/25/2007
Boolean LoadSpecifiedStringNumberDouble (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
double doubleValue1,
double doubleValue2,
double doubleValue3,
double doubleValue4,
double doubleValue5)
{
continueFlag = GetSpecifiedStringNumber (
strListID, index, (UCharPtr)stringPtr2, continueFlag);
if (continueFlag)
{
sprintf ((char*)stringPtr1,
&stringPtr2[1],
doubleValue1,
doubleValue2,
doubleValue3,
doubleValue4,
doubleValue5);
} // end "if (continueFlag)"
return (continueFlag);
} // end "LoadSpecifiedStringNumberDouble"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberLong
//
// Software purpose: This routine loads the specified string number in the
// resource file to the input string the input long value.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/10/1995
// Revised By: Larry L. Biehl Date: 02/10/1995
Boolean LoadSpecifiedStringNumberLong (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
SInt32 lValue1,
SInt32 lValue2)
{
continueFlag = GetSpecifiedStringNumber (
strListID, index, (UCharPtr)stringPtr2, continueFlag);
if (continueFlag)
{
sprintf ((char*)stringPtr1,
&stringPtr2[1],
lValue1,
lValue2);
} // end "if (continueFlag)"
return (continueFlag);
} // end "LoadSpecifiedStringNumberLong"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberLongP
//
// Software purpose: This routine loads the specified string number in the
// resource file to the specified output pascal string
// with the input long value.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/10/1995
// Revised By: Larry L. Biehl Date: 02/10/1995
Boolean LoadSpecifiedStringNumberLongP (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
SInt32 lValue1,
SInt32 lValue2)
{
UInt16 stringLength;
continueFlag = LoadSpecifiedStringNumberLong (
strListID,
index,
&stringPtr1[1],
stringPtr2,
continueFlag,
lValue1,
lValue2);
if (continueFlag)
{
stringLength = (UInt16)strlen (&stringPtr1[1]);
stringPtr1[0] = (UInt8)stringLength;
} // end "if (continueFlag)"
return (continueFlag);
} // end "LoadSpecifiedStringNumberLongP"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberString
//
// Software purpose: This routine loads the specified string number in the
// resource file to the output string with the input string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was loaded.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 12/12/1995
// Revised By: Larry L. Biehl Date: 07/20/1999
Boolean LoadSpecifiedStringNumberString (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
char* inputStringPtr)
{
continueFlag = GetSpecifiedStringNumber (
strListID, index, (UCharPtr)stringPtr2, continueFlag);
if (continueFlag)
{
sprintf ((char*)stringPtr1,
&stringPtr2[1],
inputStringPtr);
} // end "if (continueFlag)"
else // !continueFlag
stringPtr2[1] = 0;
return (continueFlag);
} // end "LoadSpecifiedStringNumberString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberString
//
// Software purpose: This routine loads the specified string number in the
// resource file to the output string with the input string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was loaded.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/23/2017
// Revised By: Larry L. Biehl Date: 02/23/2017
Boolean LoadSpecifiedStringNumberString (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
FileStringPtr inputStringPtr)
{
continueFlag = GetSpecifiedStringNumber (
strListID, index, (UCharPtr)stringPtr2, continueFlag);
if (continueFlag)
{
sprintf ((char*)stringPtr1,
&stringPtr2[1],
inputStringPtr);
} // end "if (continueFlag)"
else // !continueFlag
stringPtr2[1] = 0;
return (continueFlag);
} // end "LoadSpecifiedStringNumberString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberStringP
//
// Software purpose: This routine loads the specified string number in the
// resource file to the specified output pascal string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/10/1995
// Revised By: Larry L. Biehl Date: 07/20/1999
Boolean LoadSpecifiedStringNumberStringP (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
char* inputStringPtr)
{
UInt16 stringLength;
continueFlag = LoadSpecifiedStringNumberString (
strListID,
index,
&stringPtr1[1],
stringPtr2,
continueFlag,
inputStringPtr);
if (continueFlag)
{
stringLength = (UInt16)strlen (&stringPtr1[1]);
stringPtr1[0] = (UInt8)stringLength;
} // end "if (continueFlag)"
else // !continueFlag
stringPtr1[0] = 0;
return (continueFlag);
} // end "LoadSpecifiedStringNumberStringP"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean LoadSpecifiedStringNumberStringP
//
// Software purpose: This routine loads the specified string number in the
// resource file to the specified output pascal string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was listed and/or written to the output file.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/23/2017
// Revised By: Larry L. Biehl Date: 02/23/2017
Boolean LoadSpecifiedStringNumberStringP (
SInt16 strListID,
SInt16 index,
char* stringPtr1,
char* stringPtr2,
Boolean continueFlag,
FileStringPtr inputStringPtr)
{
UInt16 stringLength;
continueFlag = LoadSpecifiedStringNumberString (
strListID,
index,
&stringPtr1[1],
stringPtr2,
continueFlag,
inputStringPtr);
if (continueFlag)
{
stringLength = (UInt16)strlen (&stringPtr1[1]);
stringPtr1[0] = (UInt8)stringLength;
} // end "if (continueFlag)"
else // !continueFlag
stringPtr1[0] = 0;
return (continueFlag);
} // end "LoadSpecifiedStringNumberStringP"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void* MemoryCopy
//
// Software purpose: This routine is a helper function to handle the conversion of
// code from character base to unicode base. The routine will use
// memcpy when character string is being used and wmemcpy when
// unicode strings are being used.
//
// Not used now.
//
// Parameters in: Pointer to title string.
//
// Parameters out: None.
//
// Value Returned: None.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/03/2017
// Revised By: Larry L. Biehl Date: 03/08/2017
void* MemoryCopy (
void* str1,
void* str2,
int numberCharacters,
Boolean wideCharacterStringFlag)
{
if (wideCharacterStringFlag)
return (void*)wmemcpy ((wchar_t*)str1, (wchar_t*)str2, numberCharacters);
else // !wideCharacterStringFlag
return (void*)memcpy ((char*)str1, (char*)str2, numberCharacters);
} // end "MemoryCopy"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void MGetString
//
// Software purpose: The purpose of this routine is to obtain the requested
// string from the resource file.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/14/1995
// Revised By: Larry L. Biehl Date: 12/12/2019
//
// For wxWidgets interface: The String Table must be defined in xStringTable.def
// The format for string table is given in xStringTable.def
Boolean MGetString (
UCharPtr outTextPtr,
UInt16 stringListID,
UInt16 stringID,
UInt16 maxStringLength)
{
outTextPtr[0] = 0;
outTextPtr[1] = 0;
#if defined multispec_mac
UCharPtr tempStringPtr;
tempStringPtr = outTextPtr;
::GetIndString (tempStringPtr, (SInt16)stringListID, (SInt16)stringID);
// Force a c-string terminator. Do not allow strings over 254
// characters in length.
SInt16 stringLength = tempStringPtr[0];
stringLength = MIN (stringLength, 254);
outTextPtr[stringLength+1] = kNullTerminator;
return (stringLength != 0);
#endif // defined multispec_mac
#if defined multispec_mac_swift
return (FALSE);
#endif // || defined multispec_mac_swift
#if defined multispec_win
USES_CONVERSION;
TBYTE string[512];
SInt16 numberCharacters;
numberCharacters = ::LoadString (AfxGetInstanceHandle (),
stringID,
(LPWSTR)string,
510);
strcpy ((char*)&outTextPtr[1], T2A(string));
// Note that the incorrect count of characters could cause a problem. The
// only current case with the number of characters are more than 255 is
// one of the filter strings used for GetFile and PutFile. In that case
// the number of characters is not used ... only the c terminator.
outTextPtr[0] = (Byte)MIN (numberCharacters, 255);
return (numberCharacters > 0);
#endif // defined multispec_win
#if defined multispec_wx
#ifdef NetBeansProject
wxTextFile file (wxT("xStringTable.def"));
#else
// First get the path to this executable file
wxStandardPaths std = wxStandardPaths::Get ();
wxString exePath = std.GetExecutablePath ();
#ifdef multispec_wxmac
wxString exeDir = exePath.BeforeLast (wxUniChar('M'));
exeDir = exeDir.BeforeLast (wxUniChar ('M'));
exeDir.Append ("Resources/xStringTable.def");
#else
// This will be for MultiSpec on mygeohub
//wxString exeDir = exePath.BeforeLast ('/');
//exeDir.Append ("xStringTable.def");
#endif
//wxTextFile file (exeDir);
wxTextFile file (wxT("xStringTable.def"));
#endif
if (!file.Exists ())
return false;
if (!file.Open ())
return false;
bool found = false;
wxString str, strout, strend;
wxString index (wxT("#"));
index << stringID; // Append string id
for (str = file.GetFirstLine (); !file.Eof (); str = file.GetNextLine ())
{
if (str.Contains (index))
{
// Now extract string
if (str.Contains (wxT("\"")))
{
// Verify that this is the last character in the string. If
// not, then the '"' is part of the string not the designator
// for the end of the string. Will need to go to the next line
// to get the end.
str = str.AfterFirst ('"');
strend = str.AfterLast ('"');
if (str.Contains (wxT("\"")) && strend.IsEmpty ())
{
strout = str.BeforeLast ('"');
strncpy ((char*)&outTextPtr[1],
(const char*)strout.mb_str (wxConvUTF8),
maxStringLength);
outTextPtr[0] = (unsigned char) strout.Len ();
found = true;
} // end "if (str.Contains (wxT("\"")))"
else // read next line for search of second"
{
strout = str;
while (!file.Eof () && !found)
{
strout << '\n';
str = file.GetNextLine ();
//str = str.Trim (false);
if (str.Contains (wxT("\"")))
{
found = true;
strout << str.BeforeLast ('"');
strncpy ((char*)&outTextPtr[1],
(const char*) strout.mb_str (wxConvUTF8),
maxStringLength);
outTextPtr[0] = (unsigned char)strout.Len ();
} // end "if (str.Contains (wxT("\"")))"
else
strout << str;
} // end "while (!file.Eof () && !found)"
} // end "else read next line for search of second"
} // end "if (str.Contains (wxT("\"")))"
} // end "if (str.Contains (index))"
if (found)
break;
} // end "for (str = file.GetFirstLine ();..."
file.Close ();
if (!found)
{
char tempString[256];
int numberChars = sprintf (tempString,
" *String number %d was not found.%s",
stringID,
gEndOfLine);
ListString (tempString, numberChars, gOutputTextH);
} // end "if (!found)"
return (outTextPtr[1] != 0 && found);
#endif // defined multispec_wx
} // end "MGetString"
#if defined multispec_win
#if defined _UNICODE
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void MGetString
//
// Software purpose: The purpose of this routine is to obtain the requested
// string from the resource file.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/14/1995
// Revised By: Larry L. Biehl Date: 08/28/2017
Boolean MGetString (
TBYTE* outTextPtr,
UInt16 stringListID,
UInt16 stringID,
UInt16 maxStringLength)
{
SInt16 numberCharacters;
numberCharacters = ::LoadString (AfxGetInstanceHandle (),
stringID,
&outTextPtr[1],
maxStringLength);
outTextPtr[0] = (Byte)numberCharacters;
return (numberCharacters > 0);
} // end "MGetString"
#endif // defined _UNICODE
#endif // defined multispec_win
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void MSetWindowTitle
//
// Software purpose: The purpose of this routine is to set the specified
// window title.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 05/10/1995
// Revised By: Larry L. Biehl Date: 06/19/2017
void MSetWindowTitle (
WindowPtr windowPtr,
UCharPtr titleStringPtr)
{
if (windowPtr != NULL)
{
if (titleStringPtr[0] == 0)
titleStringPtr[0] = (UInt8)strlen ((char*)&titleStringPtr[1]);
#if defined multispec_mac
CFStringRef cfStringRef;
cfStringRef = CFStringCreateWithBytes (kCFAllocatorDefault,
(UInt8*)&titleStringPtr[1],
titleStringPtr[0],
kCFStringEncodingUTF8,
false);
if (cfStringRef != NULL)
{
SetWindowTitleWithCFString (windowPtr, cfStringRef);
// Using CFallocatorDeallocate causes system to crash later.
// Not sure when one should use it and not use it.
//CFAllocatorDeallocate (kCFAllocatorDefault, (void*)cfStringRef);
CFRelease (cfStringRef);
} // end "if (cfStringRef != NULL)"
#endif // defined multispec_mac
#if defined multispec_win
CDocument* documentCPtr = windowPtr->GetDocument ();
MSetWindowTitle (documentCPtr, titleStringPtr);
#endif // defined multispec_win
#if defined multispec_wx
wxDocument* documentCPtr = windowPtr->GetDocument ();
documentCPtr->SetTitle (titleStringPtr);
#endif // defined multispec_wx
} // end "if (windowPtr != NULL)"
} // end "MSetWindowTitle"
#if defined multispec_win
void MSetWindowTitle (
StatisticsWindowPtr windowPtr,
UCharPtr titleStringPtr)
{
if (titleStringPtr[0] == 0)
titleStringPtr[0] = (UInt8)strlen ((char*)&titleStringPtr[1]);
if (windowPtr != NULL)
{
CDocument* documentCPtr = windowPtr->GetDocument ();
MSetWindowTitle (documentCPtr, titleStringPtr);
} // end "if (windowPtr != NULL)"
} // end "MSetWindowTitle"
#endif // defined multispec_win
#if defined multispec_win
void MSetWindowTitle (
CDocument* documentCPtr,
UCharPtr titleStringPtr)
{
//TBYTE tempWideCharacterString[1000];
TBYTE* tempUnicodeCharacterStringPtr;
if (documentCPtr != NULL)
{
// Make sure there is a C string terminator at the end.
titleStringPtr[titleStringPtr[0]+1] = 0;
// Convert from UTF8 string to wide character string
tempUnicodeCharacterStringPtr =
ConvertMultibyteStringToUnicodeString (&titleStringPtr[1]);
documentCPtr->SetTitle (&tempUnicodeCharacterStringPtr[1]);
} // end "if (documentCPtr != NULL)"
} // end "MSetWindowTitle"
#endif // defined multispec_win
#if defined multispec_wx
void MSetWindowTitle (
wxDocument* documentCPtr,
UCharPtr titleStringPtr)
{
if (documentCPtr != NULL)
{
// Make sure there is a C string terminator at the end.
titleStringPtr[titleStringPtr[0]+1] = 0;
wxString ntitle = wxString::FromUTF8 ((char*)&titleStringPtr[1]);
documentCPtr->SetTitle (ntitle);
} // end "if (documentCPtr != NULL)"
} // end "MSetWindowTitle"
#endif
//-----------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void NumToString
//
// Software purpose: This routine converts the input 32-bit unsigned integer
// to a string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/26/2010
// Revised By: Larry L. Biehl Date: 08/27/2010
void NumToString (
UInt32 numberValue,
UCharPtr stringPtr)
{
sprintf ((CharPtr)&stringPtr[1],
"%u",
(unsigned int)numberValue);
stringPtr[0] = (UInt8)strlen ((CharPtr)&stringPtr[1]);
} // end "NumToString"
//-----------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void NumToString
//
// Software purpose: This routine converts the input 64-bit signed integer
// to a string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 08/26/2010
// Revised By: Larry L. Biehl Date: 08/26/2010
void NumToString (
SInt64 numberValue,
UCharPtr stringPtr)
{
sprintf ((CharPtr)&stringPtr[1],
"%lld",
numberValue);
stringPtr[0] = (UInt8)strlen ((CharPtr)&stringPtr[1]);
} // end "NumToString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean OutputString
//
// Software purpose: The purpose of this routine is to put the
// input string into the output window and/or the
// results disk file as requested.
// This is an overload routine for OutputString
//
// Parameters in:
//
// Parameters out:
//
// Value Returned:
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 09/05/2017
// Revised By: Larry L. Biehl Date: 09/05/2017
Boolean OutputString (
CMFileStream* resultsFileStreamPtr,
HPtr stringPtr,
UInt32 stringLength,
SInt16 outputCode,
Boolean continueFlag)
{
if (continueFlag)
return (OutputString2 (resultsFileStreamPtr,
stringPtr,
stringLength,
outputCode,
continueFlag,
-1,
kASCIICharString));
return (FALSE);
} // end "OutputString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean OutputString
//
// Software purpose: The purpose of this routine is to put the
// input string into the output window and/or the
// results disk file as requested.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned:
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/01/1989
// Revised By: Larry L. Biehl Date: 03/13/2012
Boolean OutputString (
CMFileStream* resultsFileStreamPtr,
HPtr stringPtr,
UInt32 stringLength,
SInt16 outputCode,
Boolean continueFlag,
SInt16 charFormatCode)
{
if (continueFlag)
return (OutputString2 (resultsFileStreamPtr,
stringPtr,
stringLength,
outputCode,
continueFlag,
-1,
charFormatCode));
return (FALSE);
} // end "OutputString"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean OutputString2
//
// Software purpose: The purpose of this routine is to put the input string into the
// output window (up to the requested limit) and/or the results disk
// file as requested.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned:
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 02/23/2012
// Revised By: Larry L. Biehl Date: 03/13/2012
Boolean OutputString2 (
CMFileStream* resultsFileStreamPtr,
HPtr stringPtr,
UInt32 stringLength,
SInt16 outputCode,
Boolean continueFlag,
SInt32 stringLimit,
SInt16 charFormatCode)
{
SInt16 errCode;
if (!continueFlag)
return (FALSE);
// Get the string length if needed.
if (stringLength == 0)
stringLength = StringLength ((void*)stringPtr, (charFormatCode!=kUnicodeCharString));
if (stringLength > 0)
{
// Put string into results disk file if requested.
if ((outputCode & kAsciiFormatCode) && resultsFileStreamPtr != NULL)
{
errCode = MWriteData (resultsFileStreamPtr,
&stringLength,
stringPtr,
kErrorMessages);
if (errCode != noErr)
{
gOutputCode = (gOutputCode & 0xfffd);
gOutputForce1Code = (gOutputForce1Code & 0xfffd);
} // end "if (errCode != noErr)"
} // end "if ((outputCode & kAsciiFormatCode) && ..."
// Put string in output text window if requested but only put
// in the requested limit.
if (outputCode & kOutputWindowFormatCode)
{
if (stringLimit > 0 && stringLength > (UInt32)stringLimit)
{
sprintf (&stringPtr[stringLimit], "%s", gEndOfLine);
stringLength = stringLimit + gNumberOfEndOfLineCharacters;
} /// end "if (stringLimit > 0 && stringLength > stringLimit)"
if (!ListString (stringPtr, stringLength, gOutputTextH, charFormatCode))
{
gOutputCode = (gOutputCode & 0xfffe);
gOutputForce1Code = gOutputCode;
gOutputTextOKFlag = FALSE;
} // end "if (!continueFlag)"
} // end "if (!ListString (..."
} // end "if (stringLength > 0)"
return (gOutputForce1Code & 0x0003);
} // end "OutputString2"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: pstr
//
// Software purpose: This routine moves a pascal string to the
// specified memory location and returns the number
// of characters that were moved. A termination
// character is added at the end to make it a 'C'
// string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Ravi Budruk Date: ?/??/????
// Revised By: Larry L. Biehl Date: 06/19/2001
void pstr (
char* sPtr,
char* tPtr,
SInt16* lenPtr)
{
SInt16 i;
*lenPtr = (SInt16)((UInt8)(*tPtr));
for (i=1; i<=*lenPtr; i++)
{
*sPtr = *(++tPtr);
sPtr++;
}
*sPtr = 0;
} // end "pstr"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: CharPtr PtoCstring
//
// Software purpose: This routine copies the input pascal string to an output
// C string. The input and output string pointers
// can represent the same string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/08/1997
// Revised By: Larry L. Biehl Date: 01/08/1997
CharPtr PtoCstring (
CharPtr inPStringPtr,
CharPtr outCStringPtr)
{
if (inPStringPtr != NULL && outCStringPtr != NULL)
{
size_t bytesToMove = inPStringPtr[0];
bytesToMove = MIN (bytesToMove, 254);
if (bytesToMove > 0)
memmove (outCStringPtr, &inPStringPtr[1], bytesToMove);
outCStringPtr[bytesToMove] = 0;
} // end "if (inCStringPtr != NULL && ...)"
return outCStringPtr;
} // end "CtoPstring"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void RemoveCharsAddVersion
//
// Software purpose: This routine checks if the characters in the 'removeString'
// plus number characters are at the end of 'string'. The
// 'removeString' and 'numbers' are removed if they exist.
// If number characters are at the end then '_' and the
// first character in 'remove string' are added plus the number
// characters. This allows for the number characters or version
// to stay with the input string.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/10/1992
// Revised By: Larry L. Biehl Date: 04/14/2020
void RemoveCharsAddVersion (
UCharPtr removeStringPtr,
FileStringPtr stringPtr)
{
UInt8 tempString[2];
FileStringPtr tempPtr,
temp2Ptr;
SInt16 index,
lengthString,
numberCharacters;
UInt16 lengthRemoveString;
//char asciiCharacter;
#if defined multispec_win
USES_CONVERSION;
#endif
lengthRemoveString = *removeStringPtr;
if (lengthRemoveString == 0)
{
// This must be a C string. Get the length.
lengthRemoveString = (UInt16)strlen ((char*)&removeStringPtr[1]);
lengthRemoveString = MIN (lengthRemoveString, 255);
} // end "if (lengthRemoveString == 0)"
//lengthString = *stringPtr;
lengthString = GetFileStringLength (stringPtr);
// Get number of numbers at the end of the input string.
// Note that need to allow for 2-bytes being used for the string length
// at the beginning of the string.
numberCharacters = 0;
tempString[1] = 0;
for (index=lengthString+1; index>0; index--)
{
if (stringPtr[index] < 0x30 || stringPtr[index] > 0x39)
break;
numberCharacters++;
} // end "for (index=lengthString; index>0; index--)"
// Now make stringPtr a pascal string without the version information.
//*stringPtr -= (UInt8)numberCharacters;
lengthString -= numberCharacters;
SetFileStringLength (stringPtr, lengthString);
// Now determine if input suffix characters can be removed.
if (CompareSuffixNoCase ((char*)removeStringPtr, stringPtr, &lengthRemoveString))
{
//index = lengthString - lengthRemoveString - numberCharacters + 1;
index = lengthString - lengthRemoveString + 2;
tempPtr = &stringPtr[index];
//*stringPtr -= (UInt8)lengthRemoveString;
lengthString -= lengthRemoveString;
SetFileStringLength (stringPtr, lengthString);
if (numberCharacters > 0)
{
// Replace the '.' with an underscore.
*tempPtr = '_';
// Keep the First character after the period.
tempPtr += 2;
temp2Ptr = &tempPtr[lengthRemoveString-2];
BlockMoveData (removeStringPtr, tempPtr, numberCharacters);
//*stringPtr += (UInt8)(2 + numberCharacters);
lengthString += (2 + numberCharacters);
SetFileStringLength (stringPtr, lengthString);
} // end "if (numberCharacters > 0)"
} // end "if (CompareSuffixNoCase (..."
else // !CompareSuffixNoCase (...
//*stringPtr += (UInt8)numberCharacters;
SetFileStringLength (stringPtr, lengthString+numberCharacters);
} // end "RemoveCharsAddVersion"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: RemoveCharsNoCase
//
// Software purpose: This routine removes the characters in
// "removeString" from the end of "string" if they exist.
// This routine was developed specifically to remove
// .lan (ERDAS convention) from the end of filenames to
// be ready to add .sta for image statistics file names
//
// This routine is not currently needed.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/04/1988
// Revised By: Larry L. Biehl Date: 03/14/2017
void RemoveCharsNoCase (
const CharPtr removeStringPtr,
wchar_t* stringPtr)
{
UInt16 numChars;
#if defined multispec_win
if (CompareSuffixNoCase (removeStringPtr, stringPtr, &numChars))
//wchar_t wideStringPtr[256];
//numChars = mbstowcs (wideStringPtr, &removeStringPtr[1], 255);
//int stringLength = wcslen (wideStringPtr);
//if (_wcsicmp (wideStringPtr, &stringPtr[stringLength-numChars]) == 0)
{
*stringPtr -= numChars;
// Also make sure this is a valid c-string
stringPtr[stringPtr[0]+1] = 0;
} // end "if (CompareSuffixNoCase (removeStringPtr, ..."
#else
if (CompareSuffixNoCase (removeStringPtr, stringPtr, &numChars))
{
*stringPtr -= (UInt8)numChars;
// Also make sure this is a valid c-string
stringPtr[stringPtr[0]+1] = 0;
} // end "if (CompareSuffixNoCase (removeStringPtr, ..."
#endif
} // end "RemoveCharsNoCase"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: RemoveCharsNoCase
//
// Software purpose: This routine removes the characters in
// "removeString" from the end of "string" if they exist.
// This routine was developed specifically to remove
// .lan (ERDAS convention) from the end of filenames to
// be ready to add .sta for image statistics file names.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/13/2017
// Revised By: Larry L. Biehl Date: 04/10/2020
void RemoveCharsNoCase (
const CharPtr removeStringPtr,
UCharPtr stringPtr)
{
UInt16 removeStringLength,
stringLength;
if (CompareSuffixNoCase (removeStringPtr,
stringPtr,
&removeStringLength))
{
stringLength = GetFileStringLength (stringPtr);
//*stringPtr -= (UInt8)removeStringLength;
stringLength -= (UInt8)removeStringLength;
// Set the new file string length
//stringPtr[stringPtr[0]+1] = 0;
SetFileStringLength (stringPtr, stringLength);
} // end "if (CompareSuffixNoCase (removeStringPtr, ..."
} // end "RemoveCharsNoCase"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void SetActiveImageWindowTitle
//
// Software purpose: The purpose of this routine is to set the specified
// title to the active image window.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 11/29/1995
// Revised By: Larry L. Biehl Date: 03/13/2017
void SetActiveImageWindowTitle (
UCharPtr titleStringPtr)
{
#if defined multispec_mac
if (gActiveImageWindow != NULL)
MSetWindowTitle (gActiveImageWindow, titleStringPtr);
#endif // defined multispec_mac
#if defined multispec_win
if (gActiveImageViewCPtr != NULL)
{
titleStringPtr[titleStringPtr[0]+1] = 0;
CMImageDoc* documentCPtr = gActiveImageViewCPtr->GetDocument ();
documentCPtr->SetTitle ((LPCTSTR)&titleStringPtr[1]);
} // end " if (gActiveImageViewCPtr != NULL)"
#endif // defined multispec_win
#if defined multispec_wx
if (gActiveImageViewCPtr != NULL)
{
titleStringPtr[titleStringPtr[0] + 1] = 0;
CMImageFrame* frameCPtr = (CMImageFrame *)(gActiveImageViewCPtr->GetFrame ());
wxString frametitle (& titleStringPtr[1], wxConvUTF8);
frameCPtr->SetTitle (frametitle);
CMImageDoc* documentCPtr = (CMImageDoc *)(gActiveImageViewCPtr->GetDocument ());
documentCPtr->SetTitle (frametitle);
} // end " if (gActiveImageViewCPtr != NULL)"
#endif
} // end "SetActiveImageWindowTitle"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void SetFileStringLength
//
// Software purpose: The purpose of this routine is to set the input length of the
// of the input file string in the first 2 bytes of the input
// file string.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/10/2020
// Revised By: Larry L. Biehl Date: 04/10/2020
void SetFileStringLength (
FileStringPtr fileStringPtr,
int fileStringLength)
{
UInt16* fileStringLengthPtr;
fileStringLengthPtr = (UInt16*)fileStringPtr;
fileStringLengthPtr[0] = fileStringLength;
fileStringPtr[fileStringLength+2] = 0;
} // end "SetFileStringLength"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void SetImageWindowTitle
//
// Software purpose: The purpose of this routine is to set the specified
// title to the specified image window.
//
// Parameters in:
//
// Parameters out: None.
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 01/15/2013
// Revised By: Larry L. Biehl Date: 04/27/2017
void SetImageWindowTitle (
Handle windowInfoHandle,
UCharPtr titleStringPtr)
{
WindowPtr windowPtr;
windowPtr = GetWindowPtr (windowInfoHandle);
if (windowPtr != NULL)
{
#if defined multispec_mac
MSetWindowTitle (windowPtr, titleStringPtr);
#endif // defined multispec_mac
#if defined multispec_win
//if (windowPtr != NULL)
//{
titleStringPtr[titleStringPtr[0]+1] = 0;
CMImageDoc* documentCPtr = gActiveImageViewCPtr->GetDocument ();
MSetWindowTitle (documentCPtr, titleStringPtr);
//} // end " if (windowPtr != NULL)"
#endif // defined multispec_win
#if defined multispec_wx
titleStringPtr[titleStringPtr[0]+1] = 0;
wxString ntitle = wxString::FromUTF8 ((char*)&titleStringPtr[1]);
(windowPtr->m_frame)->SetTitle (ntitle);
#endif
} // end "if (windowPtr != NULL)"
} // end "SetImageWindowTitle"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void SetOutputWTitle
//
// Software purpose: This routine set the title for the output text window.
//
// Parameters in: Pointer to title string.
//
// Parameters out: None.
//
// Value Returned: None.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 12/13/1995
// Revised By: Larry L. Biehl Date: 12/13/1995
void SetOutputWTitle (
UCharPtr titleStringPtr)
{
#if defined multispec_mac
SetWTitle (gOutputWindow, titleStringPtr);
#endif // defined multispec_mac
#if defined multispec_win
if (gOutputViewCPtr != NULL)
MSetWindowTitle ((CDocument*)gOutputViewCPtr->GetDocument (),
(UCharPtr)gTextString);
#endif // defined multispec_win
} // end "SetOutputWTitle"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void SetPascalStringLengthCharacter
//
// Software purpose: This routine is a helper function to handle the conversion of
// code from character base to unicode base. The routine will use
// strlen when character string is being used and wcrlen when
// unicode strings are being used.
//
// Parameters in: Pointer to title string.
//
// Parameters out: None.
//
// Value Returned: None.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/03/2017
// Revised By: Larry L. Biehl Date: 03/09/2017
void SetPascalStringLengthCharacter (
void* stringPtr,
int length,
SInt16 charWidthCode)
{
if (charWidthCode == kReturnASCII)
{
UCharPtr charStringPtr = (UCharPtr)stringPtr;
charStringPtr[0] = length;
} // end "if (charWidthCode == kReturnASCII)"
else // charWidthCode != ReturnASCII
{
// Do according to the use_wide_character directive
wchar_t* wideStringPtr = (wchar_t*)stringPtr;
wideStringPtr[0] = length;
} // end "else !wideCharStringFlag"
} // end "StringLength"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: SInt16 StringCompare
//
// Software purpose: This routine is a helper function to handle the conversion of
// code from character base to unicode base. The routine will use
// strcmp when character string is being used and wcrcmp when
// unicode strings are being used.
//
// Parameters in: Pointer to title string.
//
// Parameters out: None.
//
// Value Returned: None.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/03/2017
// Revised By: Larry L. Biehl Date: 03/03/2017
SInt16 StringCompare (
UInt8* str1,
UInt8* str2)
{
return strcmp ((char*)str1, (char*)str2);
} // end "StringCompare"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void* StringCopy
//
// Software purpose: This routine is a helper function to handle the conversion of
// code from character base to wide character base. The routine will use
// strcpy when character string is being used and wcrcpy when
// wide character strings are being used.
// The string starting at location str2 is copy to the location
// given by str1.
//
// Parameters in: Pointers string 1 and string 2
// Code indicating whether single character copy should be forced.
//
// Parameters out: None.
//
// Value Returned: Memory location for the for the new c terminator at the end
// of str1.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/03/2017
// Revised By: Larry L. Biehl Date: 03/20/2017
void* StringCopy (
void* str1,
void* str2,
UInt16 startInputStringIndex,
UInt16 charWidthCode)
{
char* charString1Ptr;
wchar_t* wideCharString1Ptr;
if (charWidthCode == kASCIICharString)
{
charString1Ptr = (char*)str1;
return (void*)strcpy ((char*)&charString1Ptr[startInputStringIndex],
(char*)str2);
} // end "if (charWidthCode == kASCIICharString)"
else // charWidthCode == kUnicodeCharString
{
wideCharString1Ptr = (wchar_t*)str1;
return (void*)wcscpy ((wchar_t*)&wideCharString1Ptr[startInputStringIndex],
(wchar_t*)str2);
} // end "else charWidthCode == kUnicodeCharString"
} // end "StringCopy"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: int StringLength
//
// Software purpose: This routine is a helper function to handle the conversion of
// code from character base to unicode base. The routine will use
// strlen when character string is being used and wcrlen when
// unicode strings are being used.
//
// Parameters in: Pointer to title string.
//
// Parameters out: None.
//
// Value Returned: None.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/03/2017
// Revised By: Larry L. Biehl Date: 03/10/2017
int StringLength (
void* stringPtr,
Boolean asciiCharStringFlag)
{
if (asciiCharStringFlag)
return ((int)strlen ((char*)stringPtr));
else // !asciiCharStringFlag
{
// Do according to the use_wide_character directive
return ((int)wcslen ((wchar_t*)stringPtr));
} // end "else !asciiCharStringFlag"
} // end "StringLength"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void StringToNumber
//
// Software purpose: The purpose of this routine is to convert the input string
// to a number. This will be using CFStringGetIntValue for Mac OS X.
//
// Parameters in:
//
// Parameters out: None
//
// Value Returned:
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 03/24/2012
// Revised By: Larry L. Biehl Date: 09/11/2017
void StringToNumber (
char* stringPtr,
SInt32* theNumPtr)
{
#if defined multispec_mac
CFStringRef cfStringPtr;
cfStringPtr = CFStringCreateWithCString (kCFAllocatorDefault,
stringPtr,
kCFStringEncodingMacRoman);
*theNumPtr = CFStringGetIntValue (cfStringPtr);
CFRelease (cfStringPtr);
#endif // defined multispec_mac
#if defined multispec_mac_swift
// To be done
#endif // defined multispec_mac_swift
#if defined multispec_win | defined multispec_wx
*theNumPtr = atol (stringPtr);
#endif // defined multispec_win
} // end "StringToNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: char* StrStrNoCase
//
// Software purpose: The purpose of this routine is to find string 2 within string 1
// ignoring the case of the characters in the string.
//
// Parameters in:
//
// Parameters out: None
//
// Value Returned: NULL: string 2 was not found within string 1
// Address: location within string 1 where string 2 starts
//
// Called By:
//
// Coded By: Larry L. Biehl Date: ??/??/????
// Revised By: Larry L. Biehl Date: 10/19/2017
char* StrStrNoCase (
const char* str1,
const char* str2)
{
const unsigned char* p1 = (unsigned char*)str1;
const unsigned char* p2 = (unsigned char*)str2;
char* stringStartPtr;
UInt32 c1,
c2;
c1 = toupper (*p1);
c2 = toupper (*p2);
while (c1 != 0)
{
if (c1 == c2)
{
stringStartPtr = (char*)p1;
while (c1 == c2)
{
p1++;
p2++;
c1 = toupper (*p1);
c2 = toupper (*p2);
if (c2 == 0)
return (stringStartPtr);
} // end "while (c1 == c2)"
// Substring not found. Check again.
p1 = (unsigned char*)stringStartPtr;
p2 = (unsigned char*)str2;
c2 = toupper (*p2);
} // end "if (c1 == c2)"
p1++;
c1 = toupper (*p1);
} // end "while (c1 != 0)"
return (NULL);
} // end "StrStrNoCase"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: char* StrStrNoCase
//
// Software purpose: The purpose of this routine is to find the first 'numberCharacters
// of string 2 within string 1 ignoring the case of the characters
// in the string.
//
// Parameters in:
//
// Parameters out: None
//
// Value Returned: NULL: first n characters of string 2 was not found within
// string 1
// Address: location within string 1 where string 2 starts
//
// Called By:
//
// Coded By: Larry L. Biehl Date: ??/??/????
// Revised By: Larry L. Biehl Date: 10/19/2017
char* StrStrNoCase (
const char* str1,
const char* str2,
UInt32 numberCharacters)
{
const unsigned char* p1 = (unsigned char*)str1;
const unsigned char* p2 = (unsigned char*)str2;
char* stringStartPtr;
UInt32 c1,
c2,
index;
c1 = toupper (*p1);
c2 = toupper (*p2);
while (c1 != 0)
{
if (c1 == c2)
{
index = 1;
stringStartPtr = (char*)p1;
do
{
if (index >= numberCharacters)
return (stringStartPtr);
p1++;
p2++;
c1 = toupper (*p1);
c2 = toupper (*p2);
index++;
} while (c1 == c2);
// Substring not found. Check again.
p1 = (unsigned char*)stringStartPtr;
p2 = (unsigned char*)str2;
c2 = toupper (*p2);
} // end "if (c1 == c2)"
p1++;
c1 = toupper (*p1);
} // end "while (c1 != 0)"
return (NULL);
} // end "StrStrNoCase"
/*
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: void VerifyDOSFileName
//
// Software purpose: The purpose of this routine for the Windows version of
// MultiSpec is to verify that the input file name does
// not break the 8 plus 3 character limits for DOS. If
// it does, the first part of the name is truncated to 8
// charaters and the extension is removed so that the file
// name is ready for a new extension to be added.
//
// Parameters in: None
//
// Parameters out: None
//
// Value Returned: None
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 10/05/1995
// Revised By: Larry L. Biehl Date: 02/23/2017
void VerifyDOSFileName (
FileStringPtr filePathPtr)
{
#if defined multispec_win
#if !defined _WIN32
UCharPtr inFileNamePtr,
outFileNamePtr;
UInt16 directoryLength,
nameLength,
pathLength;
// Find the start of the file name. I.E after the directory
// info.
pathLength = filePathPtr[0];
inFileNamePtr = (UCharPtr)&filePathPtr[pathLength];
nameLength = 0;
while ((nameLength < pathLength) && (*inFileNamePtr != '\\'))
{
inFileNamePtr--;
nameLength++;
} // end "while ((nameLength < pathLength) && ..."
if (nameLength > 0)
{
directoryLength = pathLength - nameLength;
inFileNamePtr++;
// The start of the file name has been found. Now find the
// '.' if it exists. If it does, then strip the '.' and the
// extension off. Also truncate the name to 8 charaters.
// Also make sure that the name does not have a blank character.
nameLength = 0;
outFileNamePtr = inFileNamePtr;
while ((nameLength < 8) &&
(*inFileNamePtr != '.') &&
(*inFileNamePtr != 0))
{
if (*inFileNamePtr != ' ')
{
if (outFileNamePtr != inFileNamePtr)
*outFileNamePtr = *inFileNamePtr;
outFileNamePtr++;
nameLength++;
} // end "if (*inFileNamePtr != ' ')"
inFileNamePtr++;
} // end "while ((nameLength < 8) && ..."
pathLength = MIN (directoryLength+nameLength, pathLength);
pathLength = MIN (gFileNameLengthLimit-2, pathLength);
filePathPtr[0] = (UInt8)pathLength;
filePathPtr[pathLength+1] = 0;
} // end "if (nameLength > 0)"
#endif // !defined _WIN32
#endif // defined multispec_win
} // end "VerifyDOSFileName"
*/
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean WriteSpecifiedStringNumber
//
// Software purpose: This routine loads the specified string number in the
// resource file and writes it out to the specifie file.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was loaded.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/13/2007
// Revised By: Larry L. Biehl Date: 04/13/2007
Boolean WriteSpecifiedStringNumber (
CMFileStream* resultsFileStreamPtr,
SInt16 strListID,
SInt16 index,
char* resourceStringPtr,
Boolean continueFlag)
{
UInt32 stringLength;
SInt16 errCode;
continueFlag = GetSpecifiedStringNumber (
strListID, index, (UCharPtr)resourceStringPtr, continueFlag);
if (continueFlag)
{
stringLength = resourceStringPtr[0];
errCode = MWriteData (resultsFileStreamPtr,
&stringLength,
&resourceStringPtr[1],
kErrorMessages);
if (errCode != noErr)
continueFlag = FALSE;
} // end "if (continueFlag)"
return (continueFlag);
} // end "WriteSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean WriteSpecifiedStringNumber
//
// Software purpose: This routine loads the specified string number in the
// resource file and writes it out to the specifie file.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was written to file okay.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/13/2007
// Revised By: Larry L. Biehl Date: 04/13/2007
Boolean WriteSpecifiedStringNumber (
CMFileStream* resultsFileStreamPtr,
SInt16 strListID,
SInt16 index,
char* finalStringPtr,
char* resourceStringPtr,
char* inputStringPtr,
Boolean continueFlag)
{
UInt32 stringLength;
SInt16 errCode;
continueFlag = LoadSpecifiedStringNumberStringP (
strListID,
index,
finalStringPtr,
resourceStringPtr,
continueFlag,
inputStringPtr);
if (continueFlag)
{
stringLength = finalStringPtr[0];
errCode = MWriteData (resultsFileStreamPtr,
&stringLength,
&finalStringPtr[1],
kErrorMessages);
if (errCode != noErr)
continueFlag = FALSE;
} // end "if (continueFlag)"
return (continueFlag);
} // end "WriteSpecifiedStringNumber"
//------------------------------------------------------------------------------------
// Copyright 1988-2020 Purdue Research Foundation
//
// Function name: Boolean WriteSpecifiedStringNumber
//
// Software purpose: This routine loads the specified string number in the
// resource file and writes it out to the specifie file.
//
// Parameters in:
//
// Parameters out:
//
// Value Returned: TRUE if string was written to file okay.
// FALSE if not.
//
// Called By:
//
// Coded By: Larry L. Biehl Date: 04/25/2007
// Revised By: Larry L. Biehl Date: 04/25/2007
Boolean WriteSpecifiedStringNumber (
CMFileStream* resultsFileStreamPtr,
SInt16 strListID,
SInt16 index,
char* finalStringPtr,
char* resourceStringPtr,
double inputDoubleValue1,
double inputDoubleValue2,
double inputDoubleValue3,
double inputDoubleValue4,
double inputDoubleValue5,
Boolean continueFlag)
{
UInt32 stringLength;
SInt16 errCode;
continueFlag = LoadSpecifiedStringNumberDouble (
strListID,
index,
finalStringPtr,
resourceStringPtr,
continueFlag,
inputDoubleValue1,
inputDoubleValue2,
inputDoubleValue3,
inputDoubleValue4,
inputDoubleValue5);
if (continueFlag)
{
stringLength = (UInt32)strlen (finalStringPtr);
errCode = MWriteData (resultsFileStreamPtr,
&stringLength,
finalStringPtr,
kErrorMessages);
if (errCode != noErr)
continueFlag = FALSE;
} // end "if (continueFlag)"
return (continueFlag);
} // end "WriteSpecifiedStringNumber"
|
#pragma once
#include "Core/Events/Event.hpp"
#include <sstream>
namespace Maxy
{
class MouseMovedEvent : public Event
{
public:
MouseMovedEvent(float x, float y)
: m_MouseX(x), m_MouseY(y) { }
inline float GetX() const { return m_MouseX; }
inline float GetY() const { return m_MouseY; }
std::string ToString() const override
{
std::stringstream ss;
ss << "Mouse moved: [" << m_MouseX << ", " << m_MouseY << "]";
return ss.str();
}
EVENT_CLASS_TYPE(EventType::MouseMoved)
EVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput)
private:
float m_MouseX, m_MouseY;
};
class MouseScrolledEvent : public Event
{
public:
MouseScrolledEvent(float offsetX, float offsetY)
: m_OffsetX(offsetX), m_OffsetY(offsetY) { }
inline float GetXOffset() const { return m_OffsetX; }
inline float GetYOffset() const { return m_OffsetY; }
std::string ToString() const override
{
std::stringstream ss;
ss << "Mouse scrolled: [" << m_OffsetX << ", " << m_OffsetY << "]";
return ss.str();
}
EVENT_CLASS_TYPE(EventType::MouseScrolled)
EVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput)
private:
float m_OffsetX, m_OffsetY;
};
class MouseButonEvent : public Event
{
public:
inline int GetMouseButton() const { return m_Button; }
EVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput)
protected:
MouseButonEvent(int button)
: m_Button(button) { }
int m_Button;
};
class MouseButtonPressedEvent : public MouseButonEvent
{
public:
MouseButtonPressedEvent(int button)
: MouseButonEvent(button) { }
std::string ToString() const override
{
std::stringstream ss;
ss << "Mouse button pressed: [" << m_Button << "]";
return ss.str();
}
EVENT_CLASS_TYPE(EventType::MouseButtonPressed)
};
class MouseButtonReleasedEvent : public MouseButonEvent
{
public:
MouseButtonReleasedEvent(int button)
: MouseButonEvent(button) { }
std::string ToString() const override
{
std::stringstream ss;
ss << "Mouse button released: [" << m_Button << "]";
return ss.str();
}
EVENT_CLASS_TYPE(EventType::MouseButtonReleased)
};
}
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
#include "iconpreviewarea.h"
#include "iconsizespinbox.h"
#include "imagedelegate.h"
#include "mainwindow.h"
//! [40]
enum { OtherSize = QStyle::PM_CustomBase };
//! [40]
//! [0]
MainWindow::MainWindow()
{
QWidget *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
createActions();
QGridLayout *mainLayout = new QGridLayout(centralWidget);
QGroupBox *previewGroupBox = new QGroupBox(tr("Preview"));
previewArea = new IconPreviewArea(previewGroupBox);
QVBoxLayout *previewLayout = new QVBoxLayout(previewGroupBox);
previewLayout->addWidget(previewArea);
mainLayout->addWidget(previewGroupBox, 0, 0, 1, 2);
mainLayout->addWidget(createImagesGroupBox(), 1, 0);
QVBoxLayout *vBox = new QVBoxLayout;
vBox->addWidget(createIconSizeGroupBox());
vBox->addWidget(createHighDpiIconSizeGroupBox());
vBox->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
mainLayout->addLayout(vBox, 1, 1);
createContextMenu();
setWindowTitle(tr("Icons"));
checkCurrentStyle();
sizeButtonGroup->button(OtherSize)->click();
}
//! [0]
//! [44]
void MainWindow::show()
{
QMainWindow::show();
connect(windowHandle(), &QWindow::screenChanged, this, &MainWindow::screenChanged);
screenChanged();
}
//! [44]
//! [1]
void MainWindow::about()
{
QMessageBox::about(this, tr("About Icons"),
tr("The <b>Icons</b> example illustrates how Qt renders an icon in "
"different modes (active, normal, disabled, and selected) and "
"states (on and off) based on a set of images."));
}
//! [1]
//! [2]
void MainWindow::changeStyle(bool checked)
{
if (!checked)
return;
const QAction *action = qobject_cast<QAction *>(sender());
//! [2] //! [3]
QStyle *style = QStyleFactory::create(action->data().toString());
//! [3] //! [4]
Q_ASSERT(style);
QApplication::setStyle(style);
foreach (QAbstractButton *button, sizeButtonGroup->buttons()) {
const QStyle::PixelMetric metric = static_cast<QStyle::PixelMetric>(sizeButtonGroup->id(button));
const int value = style->pixelMetric(metric);
switch (metric) {
case QStyle::PM_SmallIconSize:
button->setText(tr("Small (%1 x %1)").arg(value));
break;
case QStyle::PM_LargeIconSize:
button->setText(tr("Large (%1 x %1)").arg(value));
break;
case QStyle::PM_ToolBarIconSize:
button->setText(tr("Toolbars (%1 x %1)").arg(value));
break;
case QStyle::PM_ListViewIconSize:
button->setText(tr("List views (%1 x %1)").arg(value));
break;
case QStyle::PM_IconViewIconSize:
button->setText(tr("Icon views (%1 x %1)").arg(value));
break;
case QStyle::PM_TabBarIconSize:
button->setText(tr("Tab bars (%1 x %1)").arg(value));
break;
default:
break;
}
}
triggerChangeSize();
}
//! [4]
//! [5]
void MainWindow::changeSize(int id, bool checked)
{
if (!checked)
return;
const bool other = id == int(OtherSize);
const int extent = other
? otherSpinBox->value()
: QApplication::style()->pixelMetric(static_cast<QStyle::PixelMetric>(id));
previewArea->setSize(QSize(extent, extent));
otherSpinBox->setEnabled(other);
}
void MainWindow::triggerChangeSize()
{
changeSize(sizeButtonGroup->checkedId(), true);
}
//! [5]
//! [6]
void MainWindow::changeIcon()
{
QIcon icon;
for (int row = 0; row < imagesTable->rowCount(); ++row) {
const QTableWidgetItem *fileItem = imagesTable->item(row, 0);
const QTableWidgetItem *modeItem = imagesTable->item(row, 1);
const QTableWidgetItem *stateItem = imagesTable->item(row, 2);
if (fileItem->checkState() == Qt::Checked) {
const int modeIndex = IconPreviewArea::iconModeNames().indexOf(modeItem->text());
Q_ASSERT(modeIndex >= 0);
const int stateIndex = IconPreviewArea::iconStateNames().indexOf(stateItem->text());
Q_ASSERT(stateIndex >= 0);
const QIcon::Mode mode = IconPreviewArea::iconModes().at(modeIndex);
const QIcon::State state = IconPreviewArea::iconStates().at(stateIndex);
//! [6]
//! [8]
const QString fileName = fileItem->data(Qt::UserRole).toString();
QImage image(fileName);
if (!image.isNull())
icon.addPixmap(QPixmap::fromImage(image), mode, state);
//! [8] //! [9]
}
//! [9] //! [10]
}
//! [10]
//! [11]
previewArea->setIcon(icon);
}
//! [11]
void MainWindow::addSampleImages()
{
addImages(QLatin1String(SRCDIR) + QLatin1String("/images"));
}
void MainWindow::addOtherImages()
{
static bool firstInvocation = true;
QString directory;
if (firstInvocation) {
firstInvocation = false;
directory = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).value(0, QString());
}
addImages(directory);
}
//! [12]
void MainWindow::addImages(const QString &directory)
{
QFileDialog fileDialog(this, tr("Open Images"), directory);
QStringList mimeTypeFilters;
foreach (const QByteArray &mimeTypeName, QImageReader::supportedMimeTypes())
mimeTypeFilters.append(mimeTypeName);
mimeTypeFilters.sort();
fileDialog.setMimeTypeFilters(mimeTypeFilters);
fileDialog.selectMimeTypeFilter(QLatin1String("image/png"));
fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
fileDialog.setFileMode(QFileDialog::ExistingFiles);
if (!nativeFileDialogAct->isChecked())
fileDialog.setOption(QFileDialog::DontUseNativeDialog);
if (fileDialog.exec() == QDialog::Accepted)
loadImages(fileDialog.selectedFiles());
//! [12]
}
void MainWindow::loadImages(const QStringList &fileNames)
{
foreach (const QString &fileName, fileNames) {
const int row = imagesTable->rowCount();
imagesTable->setRowCount(row + 1);
//! [13]
const QFileInfo fileInfo(fileName);
const QString imageName = fileInfo.baseName();
const QString fileName2x = fileInfo.absolutePath()
+ QLatin1Char('/') + imageName + QLatin1String("@2x.") + fileInfo.suffix();
const QFileInfo fileInfo2x(fileName2x);
const QImage image(fileName);
const QString toolTip =
tr("Directory: %1\nFile: %2\nFile@2x: %3\nSize: %4x%5")
.arg(QDir::toNativeSeparators(fileInfo.absolutePath()), fileInfo.fileName())
.arg(fileInfo2x.exists() ? fileInfo2x.fileName() : tr("<None>"))
.arg(image.width()).arg(image.height());
//! [13] //! [14]
QTableWidgetItem *fileItem = new QTableWidgetItem(imageName);
fileItem->setData(Qt::UserRole, fileName);
fileItem->setIcon(QPixmap::fromImage(image));
fileItem->setFlags((fileItem->flags() | Qt::ItemIsUserCheckable) & ~Qt::ItemIsEditable);
fileItem->setToolTip(toolTip);
//! [14]
//! [15]
QIcon::Mode mode = QIcon::Normal;
//! [15] //! [16]
QIcon::State state = QIcon::Off;
if (guessModeStateAct->isChecked()) {
if (imageName.contains(QLatin1String("_act"), Qt::CaseInsensitive))
mode = QIcon::Active;
else if (imageName.contains(QLatin1String("_dis"), Qt::CaseInsensitive))
mode = QIcon::Disabled;
else if (imageName.contains(QLatin1String("_sel"), Qt::CaseInsensitive))
mode = QIcon::Selected;
if (imageName.contains(QLatin1String("_on"), Qt::CaseInsensitive))
state = QIcon::On;
//! [16] //! [17]
}
//! [17]
//! [18]
imagesTable->setItem(row, 0, fileItem);
//! [18] //! [19]
QTableWidgetItem *modeItem =
new QTableWidgetItem(IconPreviewArea::iconModeNames().at(IconPreviewArea::iconModes().indexOf(mode)));
modeItem->setToolTip(toolTip);
imagesTable->setItem(row, 1, modeItem);
QTableWidgetItem *stateItem =
new QTableWidgetItem(IconPreviewArea::iconStateNames().at(IconPreviewArea::iconStates().indexOf(state)));
stateItem->setToolTip(toolTip);
imagesTable->setItem(row, 2, stateItem);
imagesTable->openPersistentEditor(modeItem);
imagesTable->openPersistentEditor(stateItem);
fileItem->setCheckState(Qt::Checked);
}
}
//! [19]
void MainWindow::useHighDpiPixmapsChanged(int checkState)
{
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps, checkState == Qt::Checked);
changeIcon();
}
//! [20]
void MainWindow::removeAllImages()
{
imagesTable->setRowCount(0);
changeIcon();
}
//! [20]
//! [21]
QWidget *MainWindow::createImagesGroupBox()
{
QGroupBox *imagesGroupBox = new QGroupBox(tr("Images"));
imagesTable = new QTableWidget;
imagesTable->setSelectionMode(QAbstractItemView::NoSelection);
imagesTable->setItemDelegate(new ImageDelegate(this));
//! [21]
//! [22]
QStringList labels;
//! [22] //! [23]
labels << tr("Image") << tr("Mode") << tr("State");
imagesTable->horizontalHeader()->setDefaultSectionSize(90);
imagesTable->setColumnCount(3);
imagesTable->setHorizontalHeaderLabels(labels);
imagesTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
imagesTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
imagesTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
imagesTable->verticalHeader()->hide();
//! [23]
//! [24]
connect(imagesTable, &QTableWidget::itemChanged,
//! [24] //! [25]
this, &MainWindow::changeIcon);
QVBoxLayout *layout = new QVBoxLayout(imagesGroupBox);
layout->addWidget(imagesTable);
return imagesGroupBox;
}
//! [25]
//! [26]
QWidget *MainWindow::createIconSizeGroupBox()
{
QGroupBox *iconSizeGroupBox = new QGroupBox(tr("Icon Size"));
sizeButtonGroup = new QButtonGroup(this);
sizeButtonGroup->setExclusive(true);
connect(sizeButtonGroup, QOverload<int, bool>::of(&QButtonGroup::buttonToggled),
this, &MainWindow::changeSize);
QRadioButton *smallRadioButton = new QRadioButton;
sizeButtonGroup->addButton(smallRadioButton, QStyle::PM_SmallIconSize);
QRadioButton *largeRadioButton = new QRadioButton;
sizeButtonGroup->addButton(largeRadioButton, QStyle::PM_LargeIconSize);
QRadioButton *toolBarRadioButton = new QRadioButton;
sizeButtonGroup->addButton(toolBarRadioButton, QStyle::PM_ToolBarIconSize);
QRadioButton *listViewRadioButton = new QRadioButton;
sizeButtonGroup->addButton(listViewRadioButton, QStyle::PM_ListViewIconSize);
QRadioButton *iconViewRadioButton = new QRadioButton;
sizeButtonGroup->addButton(iconViewRadioButton, QStyle::PM_IconViewIconSize);
QRadioButton *tabBarRadioButton = new QRadioButton;
sizeButtonGroup->addButton(tabBarRadioButton, QStyle::PM_TabBarIconSize);
QRadioButton *otherRadioButton = new QRadioButton(tr("Other:"));
sizeButtonGroup->addButton(otherRadioButton, OtherSize);
otherSpinBox = new IconSizeSpinBox;
otherSpinBox->setRange(8, 256);
const QString spinBoxToolTip =
tr("Enter a custom size within %1..%2")
.arg(otherSpinBox->minimum()).arg(otherSpinBox->maximum());
otherSpinBox->setValue(64);
otherSpinBox->setToolTip(spinBoxToolTip);
otherRadioButton->setToolTip(spinBoxToolTip);
//! [26]
//! [27]
connect(otherSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
this, &MainWindow::triggerChangeSize);
QHBoxLayout *otherSizeLayout = new QHBoxLayout;
otherSizeLayout->addWidget(otherRadioButton);
otherSizeLayout->addWidget(otherSpinBox);
otherSizeLayout->addStretch();
QGridLayout *layout = new QGridLayout(iconSizeGroupBox);
layout->addWidget(smallRadioButton, 0, 0);
layout->addWidget(largeRadioButton, 1, 0);
layout->addWidget(toolBarRadioButton, 2, 0);
layout->addWidget(listViewRadioButton, 0, 1);
layout->addWidget(iconViewRadioButton, 1, 1);
layout->addWidget(tabBarRadioButton, 2, 1);
layout->addLayout(otherSizeLayout, 3, 0, 1, 2);
layout->setRowStretch(4, 1);
return iconSizeGroupBox;
}
//! [27]
void MainWindow::screenChanged()
{
devicePixelRatioLabel->setText(QString::number(devicePixelRatioF()));
if (const QWindow *window = windowHandle()) {
const QScreen *screen = window->screen();
const QString screenDescription =
tr("\"%1\" (%2x%3)").arg(screen->name())
.arg(screen->geometry().width()).arg(screen->geometry().height());
screenNameLabel->setText(screenDescription);
}
changeIcon();
}
QWidget *MainWindow::createHighDpiIconSizeGroupBox()
{
QGroupBox *highDpiGroupBox = new QGroupBox(tr("High DPI Scaling"));
QFormLayout *layout = new QFormLayout(highDpiGroupBox);
devicePixelRatioLabel = new QLabel(highDpiGroupBox);
screenNameLabel = new QLabel(highDpiGroupBox);
layout->addRow(tr("Screen:"), screenNameLabel);
layout->addRow(tr("Device pixel ratio:"), devicePixelRatioLabel);
QCheckBox *highDpiPixmapsCheckBox = new QCheckBox(QLatin1String("Qt::AA_UseHighDpiPixmaps"));
highDpiPixmapsCheckBox->setChecked(QCoreApplication::testAttribute(Qt::AA_UseHighDpiPixmaps));
connect(highDpiPixmapsCheckBox, &QCheckBox::stateChanged, this, &MainWindow::useHighDpiPixmapsChanged);
layout->addRow(highDpiPixmapsCheckBox);
return highDpiGroupBox;
}
//! [28]
void MainWindow::createActions()
{
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
addSampleImagesAct = new QAction(tr("Add &Sample Images..."), this);
addSampleImagesAct->setShortcut(tr("Ctrl+A"));
connect(addSampleImagesAct, &QAction::triggered, this, &MainWindow::addSampleImages);
fileMenu->addAction(addSampleImagesAct);
addOtherImagesAct = new QAction(tr("&Add Images..."), this);
addOtherImagesAct->setShortcut(QKeySequence::Open);
connect(addOtherImagesAct, &QAction::triggered, this, &MainWindow::addOtherImages);
fileMenu->addAction(addOtherImagesAct);
removeAllImagesAct = new QAction(tr("&Remove All Images"), this);
removeAllImagesAct->setShortcut(tr("Ctrl+R"));
connect(removeAllImagesAct, &QAction::triggered,
this, &MainWindow::removeAllImages);
fileMenu->addAction(removeAllImagesAct);
fileMenu->addSeparator();
QAction *exitAct = fileMenu->addAction(tr("&Quit"), this, &QWidget::close);
exitAct->setShortcuts(QKeySequence::Quit);
QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
styleActionGroup = new QActionGroup(this);
foreach (const QString &styleName, QStyleFactory::keys()) {
QAction *action = new QAction(tr("%1 Style").arg(styleName), styleActionGroup);
action->setData(styleName);
action->setCheckable(true);
connect(action, &QAction::triggered, this, &MainWindow::changeStyle);
viewMenu->addAction(action);
}
QMenu *settingsMenu = menuBar()->addMenu(tr("&Settings"));
guessModeStateAct = new QAction(tr("&Guess Image Mode/State"), this);
guessModeStateAct->setCheckable(true);
guessModeStateAct->setChecked(true);
settingsMenu->addAction(guessModeStateAct);
nativeFileDialogAct = new QAction(tr("&Use Native File Dialog"), this);
nativeFileDialogAct->setCheckable(true);
nativeFileDialogAct->setChecked(true);
settingsMenu->addAction(nativeFileDialogAct);
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(tr("&About"), this, &MainWindow::about);
helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
}
//! [28]
//! [30]
void MainWindow::createContextMenu()
{
imagesTable->setContextMenuPolicy(Qt::ActionsContextMenu);
imagesTable->addAction(addSampleImagesAct);
imagesTable->addAction(addOtherImagesAct);
imagesTable->addAction(removeAllImagesAct);
}
//! [30]
//! [31]
void MainWindow::checkCurrentStyle()
{
foreach (QAction *action, styleActionGroup->actions()) {
QString styleName = action->data().toString();
QScopedPointer<QStyle> candidate(QStyleFactory::create(styleName));
Q_ASSERT(!candidate.isNull());
if (candidate->metaObject()->className()
== QApplication::style()->metaObject()->className()) {
action->trigger();
return;
}
}
}
//! [31]
|
#include "stdhdr.h"
#include "otwdrive.h"
#include "simdrive.h"
#include "mfd.h"
#include "rwr.h"
#include "hud.h"
#include "Graphics/Include/render2d.h"
#include "Graphics/Include/renderow.h"
#include "cpmanager.h"
#include "aircrft.h"
#include "lantirn.h"
extern RECT VirtualMFD[OTWDriverClass::NumPopups + 1];
ViewportBounds hudViewportBounds;
// sfr: WTF is this???
void OTWDriverClass::DoPopUps(void)
{
int i;
for (i = 0; i < NumPopups; i++)
{
/*
if (popupHas[i] == 2)
{
// Draw RWR Here
}
else
*/
if (popupHas[i] >= 0)
{
// OTWImage->Compose (MfdDisplay[popupHas[i]]->image, &(VirtualMFD[NumPopups]), &(VirtualMFD[i]));
}
}
}
void OTWDriverClass::Draw2DHud(void)
{
int oldFont;
BOOL DoHud;
// COBRA - RED - Add the Vibration Offset, reverting the monitor Scaling...
Tpoint PitTurbulence = SimDriver.GetPlayerAircraft()->GetTurbulence();
// A copy of the ViewPort to use and then Add Vibration Offsets
DoHud = pCockpitManager->GetViewportBounds(&hudViewportBounds, BOUNDS_HUD);
pCockpitManager->AddTurbulenceVp(&hudViewportBounds);
if (theLantirn and theLantirn->IsFLIR())
{
#if DO_HIRESCOCK_HACK
if ( not gDoCockpitHack and (mOTWDisplayMode == ModeHud or mOTWDisplayMode == ModePadlockEFOV or
mOTWDisplayMode == Mode2DCockpit and pCockpitManager))
{
#else
if (mOTWDisplayMode == ModeHud or mOTWDisplayMode == ModePadlockEFOV or
mOTWDisplayMode == Mode2DCockpit and pCockpitManager)
{
#endif
if (DoHud)
{
theLantirn->DisplayInit(renderer->GetImageBuffer());
renderer->EndDraw();
theLantirn->GetDisplay()->SetViewport(hudViewportBounds.left,
hudViewportBounds.top,
hudViewportBounds.right,
hudViewportBounds.bottom);
float temppitch = theLantirn->GetDPitch();
theLantirn->SetDPitch(temppitch + (((60.0f * DTR) - renderer->GetFOV()) / 8.0f)); //Wombat778 10-18-2003 added to compensate for changed FOV
theLantirn->SetFOV(renderer->GetFOV() * (hudViewportBounds.right - hudViewportBounds.left) / 2.0f); //Wombat778 10-18-2003 changed 60.0f * DTR to getfov()
theLantirn->Display(theLantirn->GetDisplay());
renderer->StartDraw(); //Wombat778 10-18-2003 set pitch back to the original.
theLantirn->SetDPitch(temppitch);
}
}
}
renderer->SetColor(TheHud->GetHudColor());
#if DO_HIRESCOCK_HACK
if (
not gDoCockpitHack and (mOTWDisplayMode == ModeHud or mOTWDisplayMode == ModePadlockEFOV or
mOTWDisplayMode == Mode2DCockpit and pCockpitManager)
#else
if (
mOTWDisplayMode == ModeHud or mOTWDisplayMode == ModePadlockEFOV or
mOTWDisplayMode == Mode2DCockpit and pCockpitManager
#endif
)
{
if (DoHud)
{
oldFont = VirtualDisplay::CurFont();
ShiAssert(otwPlatform); // If we don't have this we could pass NULL for TheHud target...
if (TheHud->Ownship())
TheHud->SetTarget(TheHud->Ownship()->targetPtr);
else
TheHud->SetTarget(NULL);
if (
(mOTWDisplayMode == ModeHud) and
((((float)DisplayOptions.DispWidth)) == 1.25F * DisplayOptions.DispHeight)
)
{
//Check for hud mode and 1.25 ratio
//Wombat778 11-25-2003 Shift the viewport down by 1/16 (1/32 was not enough)
renderer->SetViewport(hudViewportBounds.left,
hudViewportBounds.top + ((hudViewportBounds.bottom - hudViewportBounds.top) * 0.0625F),
hudViewportBounds.right,
hudViewportBounds.bottom + ((hudViewportBounds.bottom - hudViewportBounds.top) * 0.0625F));
}
else
{
renderer->SetViewport(hudViewportBounds.left,
hudViewportBounds.top,
hudViewportBounds.right,
hudViewportBounds.bottom);
}
// Should probably assert that hudViewportBounds.left = -hudViewportBounds.right
// since we're assuming the HUD is horizontally centered in the display when it is active in 2D...
// RV - RED - With new scaling pit code, the Hud Half Angle must be updated by 2D pit scaling values
TheHud->SetHalfAngle((float)atan(
hudViewportBounds.right * tan(renderer->GetFOV() / 2.0f)) * RTD ,
1.0f, pCockpitManager->mHScale / pCockpitManager->mVScale
);
VirtualDisplay::SetFont(pCockpitManager->HudFont());
if (TheHud->Ownship())
{
TheHud->Display(renderer, true); // COBRA - RED - Translucent Hud
}
VirtualDisplay::SetFont(oldFont);
}
}
else
{
ShiAssert(otwPlatform); // If we don't have this we could pass NULL for TheHud target...
TheHud->SetTarget(TheHud->Ownship()->targetPtr);
renderer->SetViewport(-0.4675F, 0.25F, 0.47F, -1.0F);
hudViewportBounds.left = -0.4675F;
hudViewportBounds.top = 0.25F;
hudViewportBounds.right = 0.47F;
hudViewportBounds.bottom = -1.0F;
TheHud->SetHalfAngle(15.1434F);
TheHud->Display(renderer, true); // COBRA - RED - Translucent Hud
}
renderer->SetColor(0xff00ff00);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.